Daily bump.
[official-gcc.git] / gcc / fold-const.cc
blob1fd957288d4aa4084cfcb0f6a12401e9f3f9c428
1 /* Fold a constant sub-tree into a single node for C-compiler
2 Copyright (C) 1987-2024 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 /*@@ This file should be rewritten to use an arbitrary precision
21 @@ representation for "struct tree_int_cst" and "struct tree_real_cst".
22 @@ Perhaps the routines could also be used for bc/dc, and made a lib.
23 @@ The routines that translate from the ap rep should
24 @@ warn if precision et. al. is lost.
25 @@ This would also make life easier when this technology is used
26 @@ for cross-compilers. */
28 /* The entry points in this file are fold, size_int_wide and size_binop.
30 fold takes a tree as argument and returns a simplified tree.
32 size_binop takes a tree code for an arithmetic operation
33 and two operands that are trees, and produces a tree for the
34 result, assuming the type comes from `sizetype'.
36 size_int takes an integer value, and creates a tree constant
37 with type from `sizetype'.
39 Note: Since the folders get called on non-gimple code as well as
40 gimple code, we need to handle GIMPLE tuples as well as their
41 corresponding tree equivalents. */
43 #define INCLUDE_ALGORITHM
44 #include "config.h"
45 #include "system.h"
46 #include "coretypes.h"
47 #include "backend.h"
48 #include "target.h"
49 #include "rtl.h"
50 #include "tree.h"
51 #include "gimple.h"
52 #include "predict.h"
53 #include "memmodel.h"
54 #include "tm_p.h"
55 #include "tree-ssa-operands.h"
56 #include "optabs-query.h"
57 #include "cgraph.h"
58 #include "diagnostic-core.h"
59 #include "flags.h"
60 #include "alias.h"
61 #include "fold-const.h"
62 #include "fold-const-call.h"
63 #include "stor-layout.h"
64 #include "calls.h"
65 #include "tree-iterator.h"
66 #include "expr.h"
67 #include "intl.h"
68 #include "langhooks.h"
69 #include "tree-eh.h"
70 #include "gimplify.h"
71 #include "tree-dfa.h"
72 #include "builtins.h"
73 #include "generic-match.h"
74 #include "gimple-iterator.h"
75 #include "gimple-fold.h"
76 #include "tree-into-ssa.h"
77 #include "md5.h"
78 #include "case-cfn-macros.h"
79 #include "stringpool.h"
80 #include "tree-vrp.h"
81 #include "tree-ssanames.h"
82 #include "selftest.h"
83 #include "stringpool.h"
84 #include "attribs.h"
85 #include "tree-vector-builder.h"
86 #include "vec-perm-indices.h"
87 #include "asan.h"
88 #include "gimple-range.h"
90 /* Nonzero if we are folding constants inside an initializer or a C++
91 manifestly-constant-evaluated context; zero otherwise.
92 Should be used when folding in initializer enables additional
93 optimizations. */
94 int folding_initializer = 0;
96 /* Nonzero if we are folding C++ manifestly-constant-evaluated context; zero
97 otherwise.
98 Should be used when certain constructs shouldn't be optimized
99 during folding in that context. */
100 bool folding_cxx_constexpr = false;
102 /* The following constants represent a bit based encoding of GCC's
103 comparison operators. This encoding simplifies transformations
104 on relational comparison operators, such as AND and OR. */
105 enum comparison_code {
106 COMPCODE_FALSE = 0,
107 COMPCODE_LT = 1,
108 COMPCODE_EQ = 2,
109 COMPCODE_LE = 3,
110 COMPCODE_GT = 4,
111 COMPCODE_LTGT = 5,
112 COMPCODE_GE = 6,
113 COMPCODE_ORD = 7,
114 COMPCODE_UNORD = 8,
115 COMPCODE_UNLT = 9,
116 COMPCODE_UNEQ = 10,
117 COMPCODE_UNLE = 11,
118 COMPCODE_UNGT = 12,
119 COMPCODE_NE = 13,
120 COMPCODE_UNGE = 14,
121 COMPCODE_TRUE = 15
124 static bool negate_expr_p (tree);
125 static tree negate_expr (tree);
126 static tree associate_trees (location_t, tree, tree, enum tree_code, tree);
127 static enum comparison_code comparison_to_compcode (enum tree_code);
128 static enum tree_code compcode_to_comparison (enum comparison_code);
129 static bool twoval_comparison_p (tree, tree *, tree *);
130 static tree eval_subst (location_t, tree, tree, tree, tree, tree);
131 static tree optimize_bit_field_compare (location_t, enum tree_code,
132 tree, tree, tree);
133 static bool simple_operand_p (const_tree);
134 static tree range_binop (enum tree_code, tree, tree, int, tree, int);
135 static tree range_predecessor (tree);
136 static tree range_successor (tree);
137 static tree fold_range_test (location_t, enum tree_code, tree, tree, tree);
138 static tree fold_cond_expr_with_comparison (location_t, tree, enum tree_code,
139 tree, tree, tree, tree);
140 static tree unextend (tree, int, int, tree);
141 static tree extract_muldiv (tree, tree, enum tree_code, tree, bool *);
142 static tree extract_muldiv_1 (tree, tree, enum tree_code, tree, bool *);
143 static tree fold_binary_op_with_conditional_arg (location_t,
144 enum tree_code, tree,
145 tree, tree,
146 tree, tree, int);
147 static tree fold_negate_const (tree, tree);
148 static tree fold_not_const (const_tree, tree);
149 static tree fold_relational_const (enum tree_code, tree, tree, tree);
150 static tree fold_convert_const (enum tree_code, tree, tree);
151 static tree fold_view_convert_expr (tree, tree);
152 static tree fold_negate_expr (location_t, tree);
154 /* This is a helper function to detect min/max for some operands of COND_EXPR.
155 The form is "(EXP0 CMP EXP1) ? EXP2 : EXP3". */
156 tree_code
157 minmax_from_comparison (tree_code cmp, tree exp0, tree exp1, tree exp2, tree exp3)
159 enum tree_code code = ERROR_MARK;
161 if (HONOR_NANS (exp0) || HONOR_SIGNED_ZEROS (exp0))
162 return ERROR_MARK;
164 if (!operand_equal_p (exp0, exp2))
165 return ERROR_MARK;
167 if (TREE_CODE (exp3) == INTEGER_CST && TREE_CODE (exp1) == INTEGER_CST)
169 if (wi::to_widest (exp1) == (wi::to_widest (exp3) - 1))
171 /* X <= Y - 1 equals to X < Y. */
172 if (cmp == LE_EXPR)
173 code = LT_EXPR;
174 /* X > Y - 1 equals to X >= Y. */
175 if (cmp == GT_EXPR)
176 code = GE_EXPR;
177 /* a != MIN_RANGE<a> ? a : MIN_RANGE<a>+1 -> MAX_EXPR<MIN_RANGE<a>+1, a> */
178 if (cmp == NE_EXPR && TREE_CODE (exp0) == SSA_NAME)
180 value_range r;
181 get_range_query (cfun)->range_of_expr (r, exp0);
182 if (r.undefined_p ())
183 r.set_varying (TREE_TYPE (exp0));
185 widest_int min = widest_int::from (r.lower_bound (),
186 TYPE_SIGN (TREE_TYPE (exp0)));
187 if (min == wi::to_widest (exp1))
188 code = MAX_EXPR;
191 if (wi::to_widest (exp1) == (wi::to_widest (exp3) + 1))
193 /* X < Y + 1 equals to X <= Y. */
194 if (cmp == LT_EXPR)
195 code = LE_EXPR;
196 /* X >= Y + 1 equals to X > Y. */
197 if (cmp == GE_EXPR)
198 code = GT_EXPR;
199 /* a != MAX_RANGE<a> ? a : MAX_RANGE<a>-1 -> MIN_EXPR<MIN_RANGE<a>-1, a> */
200 if (cmp == NE_EXPR && TREE_CODE (exp0) == SSA_NAME)
202 value_range r;
203 get_range_query (cfun)->range_of_expr (r, exp0);
204 if (r.undefined_p ())
205 r.set_varying (TREE_TYPE (exp0));
207 widest_int max = widest_int::from (r.upper_bound (),
208 TYPE_SIGN (TREE_TYPE (exp0)));
209 if (max == wi::to_widest (exp1))
210 code = MIN_EXPR;
214 if (code != ERROR_MARK
215 || operand_equal_p (exp1, exp3))
217 if (cmp == LT_EXPR || cmp == LE_EXPR)
218 code = MIN_EXPR;
219 if (cmp == GT_EXPR || cmp == GE_EXPR)
220 code = MAX_EXPR;
222 return code;
225 /* Return EXPR_LOCATION of T if it is not UNKNOWN_LOCATION.
226 Otherwise, return LOC. */
228 static location_t
229 expr_location_or (tree t, location_t loc)
231 location_t tloc = EXPR_LOCATION (t);
232 return tloc == UNKNOWN_LOCATION ? loc : tloc;
235 /* Similar to protected_set_expr_location, but never modify x in place,
236 if location can and needs to be set, unshare it. */
238 tree
239 protected_set_expr_location_unshare (tree x, location_t loc)
241 if (CAN_HAVE_LOCATION_P (x)
242 && EXPR_LOCATION (x) != loc
243 && !(TREE_CODE (x) == SAVE_EXPR
244 || TREE_CODE (x) == TARGET_EXPR
245 || TREE_CODE (x) == BIND_EXPR))
247 x = copy_node (x);
248 SET_EXPR_LOCATION (x, loc);
250 return x;
253 /* If ARG2 divides ARG1 with zero remainder, carries out the exact
254 division and returns the quotient. Otherwise returns
255 NULL_TREE. */
257 tree
258 div_if_zero_remainder (const_tree arg1, const_tree arg2)
260 widest_int quo;
262 if (wi::multiple_of_p (wi::to_widest (arg1), wi::to_widest (arg2),
263 SIGNED, &quo))
264 return wide_int_to_tree (TREE_TYPE (arg1), quo);
266 return NULL_TREE;
269 /* This is nonzero if we should defer warnings about undefined
270 overflow. This facility exists because these warnings are a
271 special case. The code to estimate loop iterations does not want
272 to issue any warnings, since it works with expressions which do not
273 occur in user code. Various bits of cleanup code call fold(), but
274 only use the result if it has certain characteristics (e.g., is a
275 constant); that code only wants to issue a warning if the result is
276 used. */
278 static int fold_deferring_overflow_warnings;
280 /* If a warning about undefined overflow is deferred, this is the
281 warning. Note that this may cause us to turn two warnings into
282 one, but that is fine since it is sufficient to only give one
283 warning per expression. */
285 static const char* fold_deferred_overflow_warning;
287 /* If a warning about undefined overflow is deferred, this is the
288 level at which the warning should be emitted. */
290 static enum warn_strict_overflow_code fold_deferred_overflow_code;
292 /* Start deferring overflow warnings. We could use a stack here to
293 permit nested calls, but at present it is not necessary. */
295 void
296 fold_defer_overflow_warnings (void)
298 ++fold_deferring_overflow_warnings;
301 /* Stop deferring overflow warnings. If there is a pending warning,
302 and ISSUE is true, then issue the warning if appropriate. STMT is
303 the statement with which the warning should be associated (used for
304 location information); STMT may be NULL. CODE is the level of the
305 warning--a warn_strict_overflow_code value. This function will use
306 the smaller of CODE and the deferred code when deciding whether to
307 issue the warning. CODE may be zero to mean to always use the
308 deferred code. */
310 void
311 fold_undefer_overflow_warnings (bool issue, const gimple *stmt, int code)
313 const char *warnmsg;
314 location_t locus;
316 gcc_assert (fold_deferring_overflow_warnings > 0);
317 --fold_deferring_overflow_warnings;
318 if (fold_deferring_overflow_warnings > 0)
320 if (fold_deferred_overflow_warning != NULL
321 && code != 0
322 && code < (int) fold_deferred_overflow_code)
323 fold_deferred_overflow_code = (enum warn_strict_overflow_code) code;
324 return;
327 warnmsg = fold_deferred_overflow_warning;
328 fold_deferred_overflow_warning = NULL;
330 if (!issue || warnmsg == NULL)
331 return;
333 if (warning_suppressed_p (stmt, OPT_Wstrict_overflow))
334 return;
336 /* Use the smallest code level when deciding to issue the
337 warning. */
338 if (code == 0 || code > (int) fold_deferred_overflow_code)
339 code = fold_deferred_overflow_code;
341 if (!issue_strict_overflow_warning (code))
342 return;
344 if (stmt == NULL)
345 locus = input_location;
346 else
347 locus = gimple_location (stmt);
348 warning_at (locus, OPT_Wstrict_overflow, "%s", warnmsg);
351 /* Stop deferring overflow warnings, ignoring any deferred
352 warnings. */
354 void
355 fold_undefer_and_ignore_overflow_warnings (void)
357 fold_undefer_overflow_warnings (false, NULL, 0);
360 /* Whether we are deferring overflow warnings. */
362 bool
363 fold_deferring_overflow_warnings_p (void)
365 return fold_deferring_overflow_warnings > 0;
368 /* This is called when we fold something based on the fact that signed
369 overflow is undefined. */
371 void
372 fold_overflow_warning (const char* gmsgid, enum warn_strict_overflow_code wc)
374 if (fold_deferring_overflow_warnings > 0)
376 if (fold_deferred_overflow_warning == NULL
377 || wc < fold_deferred_overflow_code)
379 fold_deferred_overflow_warning = gmsgid;
380 fold_deferred_overflow_code = wc;
383 else if (issue_strict_overflow_warning (wc))
384 warning (OPT_Wstrict_overflow, gmsgid);
387 /* Return true if the built-in mathematical function specified by CODE
388 is odd, i.e. -f(x) == f(-x). */
390 bool
391 negate_mathfn_p (combined_fn fn)
393 switch (fn)
395 CASE_CFN_ASIN:
396 CASE_CFN_ASIN_FN:
397 CASE_CFN_ASINH:
398 CASE_CFN_ASINH_FN:
399 CASE_CFN_ATAN:
400 CASE_CFN_ATAN_FN:
401 CASE_CFN_ATANH:
402 CASE_CFN_ATANH_FN:
403 CASE_CFN_CASIN:
404 CASE_CFN_CASIN_FN:
405 CASE_CFN_CASINH:
406 CASE_CFN_CASINH_FN:
407 CASE_CFN_CATAN:
408 CASE_CFN_CATAN_FN:
409 CASE_CFN_CATANH:
410 CASE_CFN_CATANH_FN:
411 CASE_CFN_CBRT:
412 CASE_CFN_CBRT_FN:
413 CASE_CFN_CPROJ:
414 CASE_CFN_CPROJ_FN:
415 CASE_CFN_CSIN:
416 CASE_CFN_CSIN_FN:
417 CASE_CFN_CSINH:
418 CASE_CFN_CSINH_FN:
419 CASE_CFN_CTAN:
420 CASE_CFN_CTAN_FN:
421 CASE_CFN_CTANH:
422 CASE_CFN_CTANH_FN:
423 CASE_CFN_ERF:
424 CASE_CFN_ERF_FN:
425 CASE_CFN_LLROUND:
426 CASE_CFN_LLROUND_FN:
427 CASE_CFN_LROUND:
428 CASE_CFN_LROUND_FN:
429 CASE_CFN_ROUND:
430 CASE_CFN_ROUNDEVEN:
431 CASE_CFN_ROUNDEVEN_FN:
432 CASE_CFN_SIN:
433 CASE_CFN_SIN_FN:
434 CASE_CFN_SINH:
435 CASE_CFN_SINH_FN:
436 CASE_CFN_TAN:
437 CASE_CFN_TAN_FN:
438 CASE_CFN_TANH:
439 CASE_CFN_TANH_FN:
440 CASE_CFN_TRUNC:
441 CASE_CFN_TRUNC_FN:
442 return true;
444 CASE_CFN_LLRINT:
445 CASE_CFN_LLRINT_FN:
446 CASE_CFN_LRINT:
447 CASE_CFN_LRINT_FN:
448 CASE_CFN_NEARBYINT:
449 CASE_CFN_NEARBYINT_FN:
450 CASE_CFN_RINT:
451 CASE_CFN_RINT_FN:
452 return !flag_rounding_math;
454 default:
455 break;
457 return false;
460 /* Check whether we may negate an integer constant T without causing
461 overflow. */
463 bool
464 may_negate_without_overflow_p (const_tree t)
466 tree type;
468 gcc_assert (TREE_CODE (t) == INTEGER_CST);
470 type = TREE_TYPE (t);
471 if (TYPE_UNSIGNED (type))
472 return false;
474 return !wi::only_sign_bit_p (wi::to_wide (t));
477 /* Determine whether an expression T can be cheaply negated using
478 the function negate_expr without introducing undefined overflow. */
480 static bool
481 negate_expr_p (tree t)
483 tree type;
485 if (t == 0)
486 return false;
488 type = TREE_TYPE (t);
490 STRIP_SIGN_NOPS (t);
491 switch (TREE_CODE (t))
493 case INTEGER_CST:
494 if (INTEGRAL_TYPE_P (type) && TYPE_UNSIGNED (type))
495 return true;
497 /* Check that -CST will not overflow type. */
498 return may_negate_without_overflow_p (t);
499 case BIT_NOT_EXPR:
500 return (INTEGRAL_TYPE_P (type)
501 && TYPE_OVERFLOW_WRAPS (type));
503 case FIXED_CST:
504 return true;
506 case NEGATE_EXPR:
507 return !TYPE_OVERFLOW_SANITIZED (type);
509 case REAL_CST:
510 /* We want to canonicalize to positive real constants. Pretend
511 that only negative ones can be easily negated. */
512 return REAL_VALUE_NEGATIVE (TREE_REAL_CST (t));
514 case COMPLEX_CST:
515 return negate_expr_p (TREE_REALPART (t))
516 && negate_expr_p (TREE_IMAGPART (t));
518 case VECTOR_CST:
520 if (FLOAT_TYPE_P (TREE_TYPE (type)) || TYPE_OVERFLOW_WRAPS (type))
521 return true;
523 /* Steps don't prevent negation. */
524 unsigned int count = vector_cst_encoded_nelts (t);
525 for (unsigned int i = 0; i < count; ++i)
526 if (!negate_expr_p (VECTOR_CST_ENCODED_ELT (t, i)))
527 return false;
529 return true;
532 case COMPLEX_EXPR:
533 return negate_expr_p (TREE_OPERAND (t, 0))
534 && negate_expr_p (TREE_OPERAND (t, 1));
536 case CONJ_EXPR:
537 return negate_expr_p (TREE_OPERAND (t, 0));
539 case PLUS_EXPR:
540 if (HONOR_SIGN_DEPENDENT_ROUNDING (type)
541 || HONOR_SIGNED_ZEROS (type)
542 || (ANY_INTEGRAL_TYPE_P (type)
543 && ! TYPE_OVERFLOW_WRAPS (type)))
544 return false;
545 /* -(A + B) -> (-B) - A. */
546 if (negate_expr_p (TREE_OPERAND (t, 1)))
547 return true;
548 /* -(A + B) -> (-A) - B. */
549 return negate_expr_p (TREE_OPERAND (t, 0));
551 case MINUS_EXPR:
552 /* We can't turn -(A-B) into B-A when we honor signed zeros. */
553 return !HONOR_SIGN_DEPENDENT_ROUNDING (type)
554 && !HONOR_SIGNED_ZEROS (type)
555 && (! ANY_INTEGRAL_TYPE_P (type)
556 || TYPE_OVERFLOW_WRAPS (type));
558 case MULT_EXPR:
559 if (TYPE_UNSIGNED (type))
560 break;
561 /* INT_MIN/n * n doesn't overflow while negating one operand it does
562 if n is a (negative) power of two. */
563 if (INTEGRAL_TYPE_P (TREE_TYPE (t))
564 && ! TYPE_OVERFLOW_WRAPS (TREE_TYPE (t))
565 && ! ((TREE_CODE (TREE_OPERAND (t, 0)) == INTEGER_CST
566 && (wi::popcount
567 (wi::abs (wi::to_wide (TREE_OPERAND (t, 0))))) != 1)
568 || (TREE_CODE (TREE_OPERAND (t, 1)) == INTEGER_CST
569 && (wi::popcount
570 (wi::abs (wi::to_wide (TREE_OPERAND (t, 1))))) != 1)))
571 break;
573 /* Fall through. */
575 case RDIV_EXPR:
576 if (! HONOR_SIGN_DEPENDENT_ROUNDING (t))
577 return negate_expr_p (TREE_OPERAND (t, 1))
578 || negate_expr_p (TREE_OPERAND (t, 0));
579 break;
581 case TRUNC_DIV_EXPR:
582 case ROUND_DIV_EXPR:
583 case EXACT_DIV_EXPR:
584 if (TYPE_UNSIGNED (type))
585 break;
586 /* In general we can't negate A in A / B, because if A is INT_MIN and
587 B is not 1 we change the sign of the result. */
588 if (TREE_CODE (TREE_OPERAND (t, 0)) == INTEGER_CST
589 && negate_expr_p (TREE_OPERAND (t, 0)))
590 return true;
591 /* In general we can't negate B in A / B, because if A is INT_MIN and
592 B is 1, we may turn this into INT_MIN / -1 which is undefined
593 and actually traps on some architectures. */
594 if (! ANY_INTEGRAL_TYPE_P (TREE_TYPE (t))
595 || TYPE_OVERFLOW_WRAPS (TREE_TYPE (t))
596 || (TREE_CODE (TREE_OPERAND (t, 1)) == INTEGER_CST
597 && ! integer_onep (TREE_OPERAND (t, 1))))
598 return negate_expr_p (TREE_OPERAND (t, 1));
599 break;
601 case NOP_EXPR:
602 /* Negate -((double)float) as (double)(-float). */
603 if (SCALAR_FLOAT_TYPE_P (type))
605 tree tem = strip_float_extensions (t);
606 if (tem != t)
607 return negate_expr_p (tem);
609 break;
611 case CALL_EXPR:
612 /* Negate -f(x) as f(-x). */
613 if (negate_mathfn_p (get_call_combined_fn (t)))
614 return negate_expr_p (CALL_EXPR_ARG (t, 0));
615 break;
617 case RSHIFT_EXPR:
618 /* Optimize -((int)x >> 31) into (unsigned)x >> 31 for int. */
619 if (TREE_CODE (TREE_OPERAND (t, 1)) == INTEGER_CST)
621 tree op1 = TREE_OPERAND (t, 1);
622 if (wi::to_wide (op1) == element_precision (type) - 1)
623 return true;
625 break;
627 default:
628 break;
630 return false;
633 /* Given T, an expression, return a folded tree for -T or NULL_TREE, if no
634 simplification is possible.
635 If negate_expr_p would return true for T, NULL_TREE will never be
636 returned. */
638 static tree
639 fold_negate_expr_1 (location_t loc, tree t)
641 tree type = TREE_TYPE (t);
642 tree tem;
644 switch (TREE_CODE (t))
646 /* Convert - (~A) to A + 1. */
647 case BIT_NOT_EXPR:
648 if (INTEGRAL_TYPE_P (type))
649 return fold_build2_loc (loc, PLUS_EXPR, type, TREE_OPERAND (t, 0),
650 build_one_cst (type));
651 break;
653 case INTEGER_CST:
654 tem = fold_negate_const (t, type);
655 if (TREE_OVERFLOW (tem) == TREE_OVERFLOW (t)
656 || (ANY_INTEGRAL_TYPE_P (type)
657 && !TYPE_OVERFLOW_TRAPS (type)
658 && TYPE_OVERFLOW_WRAPS (type))
659 || (flag_sanitize & SANITIZE_SI_OVERFLOW) == 0)
660 return tem;
661 break;
663 case POLY_INT_CST:
664 case REAL_CST:
665 case FIXED_CST:
666 tem = fold_negate_const (t, type);
667 return tem;
669 case COMPLEX_CST:
671 tree rpart = fold_negate_expr (loc, TREE_REALPART (t));
672 tree ipart = fold_negate_expr (loc, TREE_IMAGPART (t));
673 if (rpart && ipart)
674 return build_complex (type, rpart, ipart);
676 break;
678 case VECTOR_CST:
680 tree_vector_builder elts;
681 elts.new_unary_operation (type, t, true);
682 unsigned int count = elts.encoded_nelts ();
683 for (unsigned int i = 0; i < count; ++i)
685 tree elt = fold_negate_expr (loc, VECTOR_CST_ELT (t, i));
686 if (elt == NULL_TREE)
687 return NULL_TREE;
688 elts.quick_push (elt);
691 return elts.build ();
694 case COMPLEX_EXPR:
695 if (negate_expr_p (t))
696 return fold_build2_loc (loc, COMPLEX_EXPR, type,
697 fold_negate_expr (loc, TREE_OPERAND (t, 0)),
698 fold_negate_expr (loc, TREE_OPERAND (t, 1)));
699 break;
701 case CONJ_EXPR:
702 if (negate_expr_p (t))
703 return fold_build1_loc (loc, CONJ_EXPR, type,
704 fold_negate_expr (loc, TREE_OPERAND (t, 0)));
705 break;
707 case NEGATE_EXPR:
708 if (!TYPE_OVERFLOW_SANITIZED (type))
709 return TREE_OPERAND (t, 0);
710 break;
712 case PLUS_EXPR:
713 if (!HONOR_SIGN_DEPENDENT_ROUNDING (type)
714 && !HONOR_SIGNED_ZEROS (type))
716 /* -(A + B) -> (-B) - A. */
717 if (negate_expr_p (TREE_OPERAND (t, 1)))
719 tem = negate_expr (TREE_OPERAND (t, 1));
720 return fold_build2_loc (loc, MINUS_EXPR, type,
721 tem, TREE_OPERAND (t, 0));
724 /* -(A + B) -> (-A) - B. */
725 if (negate_expr_p (TREE_OPERAND (t, 0)))
727 tem = negate_expr (TREE_OPERAND (t, 0));
728 return fold_build2_loc (loc, MINUS_EXPR, type,
729 tem, TREE_OPERAND (t, 1));
732 break;
734 case MINUS_EXPR:
735 /* - (A - B) -> B - A */
736 if (!HONOR_SIGN_DEPENDENT_ROUNDING (type)
737 && !HONOR_SIGNED_ZEROS (type))
738 return fold_build2_loc (loc, MINUS_EXPR, type,
739 TREE_OPERAND (t, 1), TREE_OPERAND (t, 0));
740 break;
742 case MULT_EXPR:
743 if (TYPE_UNSIGNED (type))
744 break;
746 /* Fall through. */
748 case RDIV_EXPR:
749 if (! HONOR_SIGN_DEPENDENT_ROUNDING (type))
751 tem = TREE_OPERAND (t, 1);
752 if (negate_expr_p (tem))
753 return fold_build2_loc (loc, TREE_CODE (t), type,
754 TREE_OPERAND (t, 0), negate_expr (tem));
755 tem = TREE_OPERAND (t, 0);
756 if (negate_expr_p (tem))
757 return fold_build2_loc (loc, TREE_CODE (t), type,
758 negate_expr (tem), TREE_OPERAND (t, 1));
760 break;
762 case TRUNC_DIV_EXPR:
763 case ROUND_DIV_EXPR:
764 case EXACT_DIV_EXPR:
765 if (TYPE_UNSIGNED (type))
766 break;
767 /* In general we can't negate A in A / B, because if A is INT_MIN and
768 B is not 1 we change the sign of the result. */
769 if (TREE_CODE (TREE_OPERAND (t, 0)) == INTEGER_CST
770 && negate_expr_p (TREE_OPERAND (t, 0)))
771 return fold_build2_loc (loc, TREE_CODE (t), type,
772 negate_expr (TREE_OPERAND (t, 0)),
773 TREE_OPERAND (t, 1));
774 /* In general we can't negate B in A / B, because if A is INT_MIN and
775 B is 1, we may turn this into INT_MIN / -1 which is undefined
776 and actually traps on some architectures. */
777 if ((! ANY_INTEGRAL_TYPE_P (TREE_TYPE (t))
778 || TYPE_OVERFLOW_WRAPS (TREE_TYPE (t))
779 || (TREE_CODE (TREE_OPERAND (t, 1)) == INTEGER_CST
780 && ! integer_onep (TREE_OPERAND (t, 1))))
781 && negate_expr_p (TREE_OPERAND (t, 1)))
782 return fold_build2_loc (loc, TREE_CODE (t), type,
783 TREE_OPERAND (t, 0),
784 negate_expr (TREE_OPERAND (t, 1)));
785 break;
787 case NOP_EXPR:
788 /* Convert -((double)float) into (double)(-float). */
789 if (SCALAR_FLOAT_TYPE_P (type))
791 tem = strip_float_extensions (t);
792 if (tem != t && negate_expr_p (tem))
793 return fold_convert_loc (loc, type, negate_expr (tem));
795 break;
797 case CALL_EXPR:
798 /* Negate -f(x) as f(-x). */
799 if (negate_mathfn_p (get_call_combined_fn (t))
800 && negate_expr_p (CALL_EXPR_ARG (t, 0)))
802 tree fndecl, arg;
804 fndecl = get_callee_fndecl (t);
805 arg = negate_expr (CALL_EXPR_ARG (t, 0));
806 return build_call_expr_loc (loc, fndecl, 1, arg);
808 break;
810 case RSHIFT_EXPR:
811 /* Optimize -((int)x >> 31) into (unsigned)x >> 31 for int. */
812 if (TREE_CODE (TREE_OPERAND (t, 1)) == INTEGER_CST)
814 tree op1 = TREE_OPERAND (t, 1);
815 if (wi::to_wide (op1) == element_precision (type) - 1)
817 tree ntype = TYPE_UNSIGNED (type)
818 ? signed_type_for (type)
819 : unsigned_type_for (type);
820 tree temp = fold_convert_loc (loc, ntype, TREE_OPERAND (t, 0));
821 temp = fold_build2_loc (loc, RSHIFT_EXPR, ntype, temp, op1);
822 return fold_convert_loc (loc, type, temp);
825 break;
827 default:
828 break;
831 return NULL_TREE;
834 /* A wrapper for fold_negate_expr_1. */
836 static tree
837 fold_negate_expr (location_t loc, tree t)
839 tree type = TREE_TYPE (t);
840 STRIP_SIGN_NOPS (t);
841 tree tem = fold_negate_expr_1 (loc, t);
842 if (tem == NULL_TREE)
843 return NULL_TREE;
844 return fold_convert_loc (loc, type, tem);
847 /* Like fold_negate_expr, but return a NEGATE_EXPR tree, if T cannot be
848 negated in a simpler way. Also allow for T to be NULL_TREE, in which case
849 return NULL_TREE. */
851 static tree
852 negate_expr (tree t)
854 tree type, tem;
855 location_t loc;
857 if (t == NULL_TREE)
858 return NULL_TREE;
860 loc = EXPR_LOCATION (t);
861 type = TREE_TYPE (t);
862 STRIP_SIGN_NOPS (t);
864 tem = fold_negate_expr (loc, t);
865 if (!tem)
866 tem = build1_loc (loc, NEGATE_EXPR, TREE_TYPE (t), t);
867 return fold_convert_loc (loc, type, tem);
870 /* Split a tree IN into a constant, literal and variable parts that could be
871 combined with CODE to make IN. "constant" means an expression with
872 TREE_CONSTANT but that isn't an actual constant. CODE must be a
873 commutative arithmetic operation. Store the constant part into *CONP,
874 the literal in *LITP and return the variable part. If a part isn't
875 present, set it to null. If the tree does not decompose in this way,
876 return the entire tree as the variable part and the other parts as null.
878 If CODE is PLUS_EXPR we also split trees that use MINUS_EXPR. In that
879 case, we negate an operand that was subtracted. Except if it is a
880 literal for which we use *MINUS_LITP instead.
882 If NEGATE_P is true, we are negating all of IN, again except a literal
883 for which we use *MINUS_LITP instead. If a variable part is of pointer
884 type, it is negated after converting to TYPE. This prevents us from
885 generating illegal MINUS pointer expression. LOC is the location of
886 the converted variable part.
888 If IN is itself a literal or constant, return it as appropriate.
890 Note that we do not guarantee that any of the three values will be the
891 same type as IN, but they will have the same signedness and mode. */
893 static tree
894 split_tree (tree in, tree type, enum tree_code code,
895 tree *minus_varp, tree *conp, tree *minus_conp,
896 tree *litp, tree *minus_litp, int negate_p)
898 tree var = 0;
899 *minus_varp = 0;
900 *conp = 0;
901 *minus_conp = 0;
902 *litp = 0;
903 *minus_litp = 0;
905 /* Strip any conversions that don't change the machine mode or signedness. */
906 STRIP_SIGN_NOPS (in);
908 if (TREE_CODE (in) == INTEGER_CST || TREE_CODE (in) == REAL_CST
909 || TREE_CODE (in) == FIXED_CST)
910 *litp = in;
911 else if (TREE_CODE (in) == code
912 || ((! FLOAT_TYPE_P (TREE_TYPE (in)) || flag_associative_math)
913 && ! SAT_FIXED_POINT_TYPE_P (TREE_TYPE (in))
914 /* We can associate addition and subtraction together (even
915 though the C standard doesn't say so) for integers because
916 the value is not affected. For reals, the value might be
917 affected, so we can't. */
918 && ((code == PLUS_EXPR && TREE_CODE (in) == POINTER_PLUS_EXPR)
919 || (code == PLUS_EXPR && TREE_CODE (in) == MINUS_EXPR)
920 || (code == MINUS_EXPR
921 && (TREE_CODE (in) == PLUS_EXPR
922 || TREE_CODE (in) == POINTER_PLUS_EXPR)))))
924 tree op0 = TREE_OPERAND (in, 0);
925 tree op1 = TREE_OPERAND (in, 1);
926 bool neg1_p = TREE_CODE (in) == MINUS_EXPR;
927 bool neg_litp_p = false, neg_conp_p = false, neg_var_p = false;
929 /* First see if either of the operands is a literal, then a constant. */
930 if (TREE_CODE (op0) == INTEGER_CST || TREE_CODE (op0) == REAL_CST
931 || TREE_CODE (op0) == FIXED_CST)
932 *litp = op0, op0 = 0;
933 else if (TREE_CODE (op1) == INTEGER_CST || TREE_CODE (op1) == REAL_CST
934 || TREE_CODE (op1) == FIXED_CST)
935 *litp = op1, neg_litp_p = neg1_p, op1 = 0;
937 if (op0 != 0 && TREE_CONSTANT (op0))
938 *conp = op0, op0 = 0;
939 else if (op1 != 0 && TREE_CONSTANT (op1))
940 *conp = op1, neg_conp_p = neg1_p, op1 = 0;
942 /* If we haven't dealt with either operand, this is not a case we can
943 decompose. Otherwise, VAR is either of the ones remaining, if any. */
944 if (op0 != 0 && op1 != 0)
945 var = in;
946 else if (op0 != 0)
947 var = op0;
948 else
949 var = op1, neg_var_p = neg1_p;
951 /* Now do any needed negations. */
952 if (neg_litp_p)
953 *minus_litp = *litp, *litp = 0;
954 if (neg_conp_p && *conp)
955 *minus_conp = *conp, *conp = 0;
956 if (neg_var_p && var)
957 *minus_varp = var, var = 0;
959 else if (TREE_CONSTANT (in))
960 *conp = in;
961 else if (TREE_CODE (in) == BIT_NOT_EXPR
962 && code == PLUS_EXPR)
964 /* -1 - X is folded to ~X, undo that here. Do _not_ do this
965 when IN is constant. */
966 *litp = build_minus_one_cst (type);
967 *minus_varp = TREE_OPERAND (in, 0);
969 else
970 var = in;
972 if (negate_p)
974 if (*litp)
975 *minus_litp = *litp, *litp = 0;
976 else if (*minus_litp)
977 *litp = *minus_litp, *minus_litp = 0;
978 if (*conp)
979 *minus_conp = *conp, *conp = 0;
980 else if (*minus_conp)
981 *conp = *minus_conp, *minus_conp = 0;
982 if (var)
983 *minus_varp = var, var = 0;
984 else if (*minus_varp)
985 var = *minus_varp, *minus_varp = 0;
988 if (*litp
989 && TREE_OVERFLOW_P (*litp))
990 *litp = drop_tree_overflow (*litp);
991 if (*minus_litp
992 && TREE_OVERFLOW_P (*minus_litp))
993 *minus_litp = drop_tree_overflow (*minus_litp);
995 return var;
998 /* Re-associate trees split by the above function. T1 and T2 are
999 either expressions to associate or null. Return the new
1000 expression, if any. LOC is the location of the new expression. If
1001 we build an operation, do it in TYPE and with CODE. */
1003 static tree
1004 associate_trees (location_t loc, tree t1, tree t2, enum tree_code code, tree type)
1006 if (t1 == 0)
1008 gcc_assert (t2 == 0 || code != MINUS_EXPR);
1009 return t2;
1011 else if (t2 == 0)
1012 return t1;
1014 /* If either input is CODE, a PLUS_EXPR, or a MINUS_EXPR, don't
1015 try to fold this since we will have infinite recursion. But do
1016 deal with any NEGATE_EXPRs. */
1017 if (TREE_CODE (t1) == code || TREE_CODE (t2) == code
1018 || TREE_CODE (t1) == PLUS_EXPR || TREE_CODE (t2) == PLUS_EXPR
1019 || TREE_CODE (t1) == MINUS_EXPR || TREE_CODE (t2) == MINUS_EXPR)
1021 if (code == PLUS_EXPR)
1023 if (TREE_CODE (t1) == NEGATE_EXPR)
1024 return build2_loc (loc, MINUS_EXPR, type,
1025 fold_convert_loc (loc, type, t2),
1026 fold_convert_loc (loc, type,
1027 TREE_OPERAND (t1, 0)));
1028 else if (TREE_CODE (t2) == NEGATE_EXPR)
1029 return build2_loc (loc, MINUS_EXPR, type,
1030 fold_convert_loc (loc, type, t1),
1031 fold_convert_loc (loc, type,
1032 TREE_OPERAND (t2, 0)));
1033 else if (integer_zerop (t2))
1034 return fold_convert_loc (loc, type, t1);
1036 else if (code == MINUS_EXPR)
1038 if (integer_zerop (t2))
1039 return fold_convert_loc (loc, type, t1);
1042 return build2_loc (loc, code, type, fold_convert_loc (loc, type, t1),
1043 fold_convert_loc (loc, type, t2));
1046 return fold_build2_loc (loc, code, type, fold_convert_loc (loc, type, t1),
1047 fold_convert_loc (loc, type, t2));
1050 /* Check whether TYPE1 and TYPE2 are equivalent integer types, suitable
1051 for use in int_const_binop, size_binop and size_diffop. */
1053 static bool
1054 int_binop_types_match_p (enum tree_code code, const_tree type1, const_tree type2)
1056 if (!INTEGRAL_TYPE_P (type1) && !POINTER_TYPE_P (type1))
1057 return false;
1058 if (!INTEGRAL_TYPE_P (type2) && !POINTER_TYPE_P (type2))
1059 return false;
1061 switch (code)
1063 case LSHIFT_EXPR:
1064 case RSHIFT_EXPR:
1065 case LROTATE_EXPR:
1066 case RROTATE_EXPR:
1067 return true;
1069 default:
1070 break;
1073 return TYPE_UNSIGNED (type1) == TYPE_UNSIGNED (type2)
1074 && TYPE_PRECISION (type1) == TYPE_PRECISION (type2)
1075 && TYPE_MODE (type1) == TYPE_MODE (type2);
1078 /* Combine two wide ints ARG1 and ARG2 under operation CODE to produce
1079 a new constant in RES. Return FALSE if we don't know how to
1080 evaluate CODE at compile-time. */
1082 bool
1083 wide_int_binop (wide_int &res,
1084 enum tree_code code, const wide_int &arg1, const wide_int &arg2,
1085 signop sign, wi::overflow_type *overflow)
1087 wide_int tmp;
1088 *overflow = wi::OVF_NONE;
1089 switch (code)
1091 case BIT_IOR_EXPR:
1092 res = wi::bit_or (arg1, arg2);
1093 break;
1095 case BIT_XOR_EXPR:
1096 res = wi::bit_xor (arg1, arg2);
1097 break;
1099 case BIT_AND_EXPR:
1100 res = wi::bit_and (arg1, arg2);
1101 break;
1103 case LSHIFT_EXPR:
1104 if (wi::neg_p (arg2))
1105 return false;
1106 res = wi::lshift (arg1, arg2);
1107 break;
1109 case RSHIFT_EXPR:
1110 if (wi::neg_p (arg2))
1111 return false;
1112 /* It's unclear from the C standard whether shifts can overflow.
1113 The following code ignores overflow; perhaps a C standard
1114 interpretation ruling is needed. */
1115 res = wi::rshift (arg1, arg2, sign);
1116 break;
1118 case RROTATE_EXPR:
1119 case LROTATE_EXPR:
1120 if (wi::neg_p (arg2))
1122 tmp = -arg2;
1123 if (code == RROTATE_EXPR)
1124 code = LROTATE_EXPR;
1125 else
1126 code = RROTATE_EXPR;
1128 else
1129 tmp = arg2;
1131 if (code == RROTATE_EXPR)
1132 res = wi::rrotate (arg1, tmp);
1133 else
1134 res = wi::lrotate (arg1, tmp);
1135 break;
1137 case PLUS_EXPR:
1138 res = wi::add (arg1, arg2, sign, overflow);
1139 break;
1141 case MINUS_EXPR:
1142 res = wi::sub (arg1, arg2, sign, overflow);
1143 break;
1145 case MULT_EXPR:
1146 res = wi::mul (arg1, arg2, sign, overflow);
1147 break;
1149 case MULT_HIGHPART_EXPR:
1150 res = wi::mul_high (arg1, arg2, sign);
1151 break;
1153 case TRUNC_DIV_EXPR:
1154 case EXACT_DIV_EXPR:
1155 if (arg2 == 0)
1156 return false;
1157 res = wi::div_trunc (arg1, arg2, sign, overflow);
1158 break;
1160 case FLOOR_DIV_EXPR:
1161 if (arg2 == 0)
1162 return false;
1163 res = wi::div_floor (arg1, arg2, sign, overflow);
1164 break;
1166 case CEIL_DIV_EXPR:
1167 if (arg2 == 0)
1168 return false;
1169 res = wi::div_ceil (arg1, arg2, sign, overflow);
1170 break;
1172 case ROUND_DIV_EXPR:
1173 if (arg2 == 0)
1174 return false;
1175 res = wi::div_round (arg1, arg2, sign, overflow);
1176 break;
1178 case TRUNC_MOD_EXPR:
1179 if (arg2 == 0)
1180 return false;
1181 res = wi::mod_trunc (arg1, arg2, sign, overflow);
1182 break;
1184 case FLOOR_MOD_EXPR:
1185 if (arg2 == 0)
1186 return false;
1187 res = wi::mod_floor (arg1, arg2, sign, overflow);
1188 break;
1190 case CEIL_MOD_EXPR:
1191 if (arg2 == 0)
1192 return false;
1193 res = wi::mod_ceil (arg1, arg2, sign, overflow);
1194 break;
1196 case ROUND_MOD_EXPR:
1197 if (arg2 == 0)
1198 return false;
1199 res = wi::mod_round (arg1, arg2, sign, overflow);
1200 break;
1202 case MIN_EXPR:
1203 res = wi::min (arg1, arg2, sign);
1204 break;
1206 case MAX_EXPR:
1207 res = wi::max (arg1, arg2, sign);
1208 break;
1210 default:
1211 return false;
1213 return true;
1216 /* Returns true if we know who is smaller or equal, ARG1 or ARG2, and set the
1217 min value to RES. */
1218 bool
1219 can_min_p (const_tree arg1, const_tree arg2, poly_wide_int &res)
1221 if (known_le (wi::to_poly_widest (arg1), wi::to_poly_widest (arg2)))
1223 res = wi::to_poly_wide (arg1);
1224 return true;
1226 else if (known_le (wi::to_poly_widest (arg2), wi::to_poly_widest (arg1)))
1228 res = wi::to_poly_wide (arg2);
1229 return true;
1232 return false;
1235 /* Combine two poly int's ARG1 and ARG2 under operation CODE to
1236 produce a new constant in RES. Return FALSE if we don't know how
1237 to evaluate CODE at compile-time. */
1239 static bool
1240 poly_int_binop (poly_wide_int &res, enum tree_code code,
1241 const_tree arg1, const_tree arg2,
1242 signop sign, wi::overflow_type *overflow)
1244 gcc_assert (NUM_POLY_INT_COEFFS != 1);
1245 gcc_assert (poly_int_tree_p (arg1) && poly_int_tree_p (arg2));
1246 switch (code)
1248 case PLUS_EXPR:
1249 res = wi::add (wi::to_poly_wide (arg1),
1250 wi::to_poly_wide (arg2), sign, overflow);
1251 break;
1253 case MINUS_EXPR:
1254 res = wi::sub (wi::to_poly_wide (arg1),
1255 wi::to_poly_wide (arg2), sign, overflow);
1256 break;
1258 case MULT_EXPR:
1259 if (TREE_CODE (arg2) == INTEGER_CST)
1260 res = wi::mul (wi::to_poly_wide (arg1),
1261 wi::to_wide (arg2), sign, overflow);
1262 else if (TREE_CODE (arg1) == INTEGER_CST)
1263 res = wi::mul (wi::to_poly_wide (arg2),
1264 wi::to_wide (arg1), sign, overflow);
1265 else
1266 return NULL_TREE;
1267 break;
1269 case LSHIFT_EXPR:
1270 if (TREE_CODE (arg2) == INTEGER_CST)
1271 res = wi::to_poly_wide (arg1) << wi::to_wide (arg2);
1272 else
1273 return false;
1274 break;
1276 case BIT_IOR_EXPR:
1277 if (TREE_CODE (arg2) != INTEGER_CST
1278 || !can_ior_p (wi::to_poly_wide (arg1), wi::to_wide (arg2),
1279 &res))
1280 return false;
1281 break;
1283 case MIN_EXPR:
1284 if (!can_min_p (arg1, arg2, res))
1285 return false;
1286 break;
1288 default:
1289 return false;
1291 return true;
1294 /* Combine two integer constants ARG1 and ARG2 under operation CODE to
1295 produce a new constant. Return NULL_TREE if we don't know how to
1296 evaluate CODE at compile-time. */
1298 tree
1299 int_const_binop (enum tree_code code, const_tree arg1, const_tree arg2,
1300 int overflowable)
1302 poly_wide_int poly_res;
1303 tree type = TREE_TYPE (arg1);
1304 signop sign = TYPE_SIGN (type);
1305 wi::overflow_type overflow = wi::OVF_NONE;
1307 if (TREE_CODE (arg1) == INTEGER_CST && TREE_CODE (arg2) == INTEGER_CST)
1309 wide_int warg1 = wi::to_wide (arg1), res;
1310 wide_int warg2 = wi::to_wide (arg2, TYPE_PRECISION (type));
1311 if (!wide_int_binop (res, code, warg1, warg2, sign, &overflow))
1312 return NULL_TREE;
1313 poly_res = res;
1315 else if (!poly_int_tree_p (arg1)
1316 || !poly_int_tree_p (arg2)
1317 || !poly_int_binop (poly_res, code, arg1, arg2, sign, &overflow))
1318 return NULL_TREE;
1319 return force_fit_type (type, poly_res, overflowable,
1320 (((sign == SIGNED || overflowable == -1)
1321 && overflow)
1322 | TREE_OVERFLOW (arg1) | TREE_OVERFLOW (arg2)));
1325 /* Return true if binary operation OP distributes over addition in operand
1326 OPNO, with the other operand being held constant. OPNO counts from 1. */
1328 static bool
1329 distributes_over_addition_p (tree_code op, int opno)
1331 switch (op)
1333 case PLUS_EXPR:
1334 case MINUS_EXPR:
1335 case MULT_EXPR:
1336 return true;
1338 case LSHIFT_EXPR:
1339 return opno == 1;
1341 default:
1342 return false;
1346 /* Combine two constants ARG1 and ARG2 under operation CODE to produce a new
1347 constant. We assume ARG1 and ARG2 have the same data type, or at least
1348 are the same kind of constant and the same machine mode. Return zero if
1349 combining the constants is not allowed in the current operating mode. */
1351 static tree
1352 const_binop (enum tree_code code, tree arg1, tree arg2)
1354 /* Sanity check for the recursive cases. */
1355 if (!arg1 || !arg2)
1356 return NULL_TREE;
1358 STRIP_NOPS (arg1);
1359 STRIP_NOPS (arg2);
1361 if (poly_int_tree_p (arg1) && poly_int_tree_p (arg2))
1363 if (code == POINTER_PLUS_EXPR)
1364 return int_const_binop (PLUS_EXPR,
1365 arg1, fold_convert (TREE_TYPE (arg1), arg2));
1367 return int_const_binop (code, arg1, arg2);
1370 if (TREE_CODE (arg1) == REAL_CST && TREE_CODE (arg2) == REAL_CST)
1372 machine_mode mode;
1373 REAL_VALUE_TYPE d1;
1374 REAL_VALUE_TYPE d2;
1375 REAL_VALUE_TYPE value;
1376 REAL_VALUE_TYPE result;
1377 bool inexact;
1378 tree t, type;
1380 /* The following codes are handled by real_arithmetic. */
1381 switch (code)
1383 case PLUS_EXPR:
1384 case MINUS_EXPR:
1385 case MULT_EXPR:
1386 case RDIV_EXPR:
1387 case MIN_EXPR:
1388 case MAX_EXPR:
1389 break;
1391 default:
1392 return NULL_TREE;
1395 d1 = TREE_REAL_CST (arg1);
1396 d2 = TREE_REAL_CST (arg2);
1398 type = TREE_TYPE (arg1);
1399 mode = TYPE_MODE (type);
1401 /* Don't perform operation if we honor signaling NaNs and
1402 either operand is a signaling NaN. */
1403 if (HONOR_SNANS (mode)
1404 && (REAL_VALUE_ISSIGNALING_NAN (d1)
1405 || REAL_VALUE_ISSIGNALING_NAN (d2)))
1406 return NULL_TREE;
1408 /* Don't perform operation if it would raise a division
1409 by zero exception. */
1410 if (code == RDIV_EXPR
1411 && real_equal (&d2, &dconst0)
1412 && (flag_trapping_math || ! MODE_HAS_INFINITIES (mode)))
1413 return NULL_TREE;
1415 /* If either operand is a NaN, just return it. Otherwise, set up
1416 for floating-point trap; we return an overflow. */
1417 if (REAL_VALUE_ISNAN (d1))
1419 /* Make resulting NaN value to be qNaN when flag_signaling_nans
1420 is off. */
1421 d1.signalling = 0;
1422 t = build_real (type, d1);
1423 return t;
1425 else if (REAL_VALUE_ISNAN (d2))
1427 /* Make resulting NaN value to be qNaN when flag_signaling_nans
1428 is off. */
1429 d2.signalling = 0;
1430 t = build_real (type, d2);
1431 return t;
1434 inexact = real_arithmetic (&value, code, &d1, &d2);
1435 real_convert (&result, mode, &value);
1437 /* Don't constant fold this floating point operation if
1438 both operands are not NaN but the result is NaN, and
1439 flag_trapping_math. Such operations should raise an
1440 invalid operation exception. */
1441 if (flag_trapping_math
1442 && MODE_HAS_NANS (mode)
1443 && REAL_VALUE_ISNAN (result)
1444 && !REAL_VALUE_ISNAN (d1)
1445 && !REAL_VALUE_ISNAN (d2))
1446 return NULL_TREE;
1448 /* Don't constant fold this floating point operation if
1449 the result has overflowed and flag_trapping_math. */
1450 if (flag_trapping_math
1451 && MODE_HAS_INFINITIES (mode)
1452 && REAL_VALUE_ISINF (result)
1453 && !REAL_VALUE_ISINF (d1)
1454 && !REAL_VALUE_ISINF (d2))
1455 return NULL_TREE;
1457 /* Don't constant fold this floating point operation if the
1458 result may dependent upon the run-time rounding mode and
1459 flag_rounding_math is set, or if GCC's software emulation
1460 is unable to accurately represent the result. */
1461 if ((flag_rounding_math
1462 || (MODE_COMPOSITE_P (mode) && !flag_unsafe_math_optimizations))
1463 && (inexact || !real_identical (&result, &value)))
1464 return NULL_TREE;
1466 t = build_real (type, result);
1468 TREE_OVERFLOW (t) = TREE_OVERFLOW (arg1) | TREE_OVERFLOW (arg2);
1469 return t;
1472 if (TREE_CODE (arg1) == FIXED_CST)
1474 FIXED_VALUE_TYPE f1;
1475 FIXED_VALUE_TYPE f2;
1476 FIXED_VALUE_TYPE result;
1477 tree t, type;
1478 bool sat_p;
1479 bool overflow_p;
1481 /* The following codes are handled by fixed_arithmetic. */
1482 switch (code)
1484 case PLUS_EXPR:
1485 case MINUS_EXPR:
1486 case MULT_EXPR:
1487 case TRUNC_DIV_EXPR:
1488 if (TREE_CODE (arg2) != FIXED_CST)
1489 return NULL_TREE;
1490 f2 = TREE_FIXED_CST (arg2);
1491 break;
1493 case LSHIFT_EXPR:
1494 case RSHIFT_EXPR:
1496 if (TREE_CODE (arg2) != INTEGER_CST)
1497 return NULL_TREE;
1498 wi::tree_to_wide_ref w2 = wi::to_wide (arg2);
1499 f2.data.high = w2.elt (1);
1500 f2.data.low = w2.ulow ();
1501 f2.mode = SImode;
1503 break;
1505 default:
1506 return NULL_TREE;
1509 f1 = TREE_FIXED_CST (arg1);
1510 type = TREE_TYPE (arg1);
1511 sat_p = TYPE_SATURATING (type);
1512 overflow_p = fixed_arithmetic (&result, code, &f1, &f2, sat_p);
1513 t = build_fixed (type, result);
1514 /* Propagate overflow flags. */
1515 if (overflow_p | TREE_OVERFLOW (arg1) | TREE_OVERFLOW (arg2))
1516 TREE_OVERFLOW (t) = 1;
1517 return t;
1520 if (TREE_CODE (arg1) == COMPLEX_CST && TREE_CODE (arg2) == COMPLEX_CST)
1522 tree type = TREE_TYPE (arg1);
1523 tree r1 = TREE_REALPART (arg1);
1524 tree i1 = TREE_IMAGPART (arg1);
1525 tree r2 = TREE_REALPART (arg2);
1526 tree i2 = TREE_IMAGPART (arg2);
1527 tree real, imag;
1529 switch (code)
1531 case PLUS_EXPR:
1532 case MINUS_EXPR:
1533 real = const_binop (code, r1, r2);
1534 imag = const_binop (code, i1, i2);
1535 break;
1537 case MULT_EXPR:
1538 if (COMPLEX_FLOAT_TYPE_P (type))
1539 return do_mpc_arg2 (arg1, arg2, type,
1540 /* do_nonfinite= */ folding_initializer,
1541 mpc_mul);
1543 real = const_binop (MINUS_EXPR,
1544 const_binop (MULT_EXPR, r1, r2),
1545 const_binop (MULT_EXPR, i1, i2));
1546 imag = const_binop (PLUS_EXPR,
1547 const_binop (MULT_EXPR, r1, i2),
1548 const_binop (MULT_EXPR, i1, r2));
1549 break;
1551 case RDIV_EXPR:
1552 if (COMPLEX_FLOAT_TYPE_P (type))
1553 return do_mpc_arg2 (arg1, arg2, type,
1554 /* do_nonfinite= */ folding_initializer,
1555 mpc_div);
1556 /* Fallthru. */
1557 case TRUNC_DIV_EXPR:
1558 case CEIL_DIV_EXPR:
1559 case FLOOR_DIV_EXPR:
1560 case ROUND_DIV_EXPR:
1561 if (flag_complex_method == 0)
1563 /* Keep this algorithm in sync with
1564 tree-complex.cc:expand_complex_div_straight().
1566 Expand complex division to scalars, straightforward algorithm.
1567 a / b = ((ar*br + ai*bi)/t) + i((ai*br - ar*bi)/t)
1568 t = br*br + bi*bi
1570 tree magsquared
1571 = const_binop (PLUS_EXPR,
1572 const_binop (MULT_EXPR, r2, r2),
1573 const_binop (MULT_EXPR, i2, i2));
1574 tree t1
1575 = const_binop (PLUS_EXPR,
1576 const_binop (MULT_EXPR, r1, r2),
1577 const_binop (MULT_EXPR, i1, i2));
1578 tree t2
1579 = const_binop (MINUS_EXPR,
1580 const_binop (MULT_EXPR, i1, r2),
1581 const_binop (MULT_EXPR, r1, i2));
1583 real = const_binop (code, t1, magsquared);
1584 imag = const_binop (code, t2, magsquared);
1586 else
1588 /* Keep this algorithm in sync with
1589 tree-complex.cc:expand_complex_div_wide().
1591 Expand complex division to scalars, modified algorithm to minimize
1592 overflow with wide input ranges. */
1593 tree compare = fold_build2 (LT_EXPR, boolean_type_node,
1594 fold_abs_const (r2, TREE_TYPE (type)),
1595 fold_abs_const (i2, TREE_TYPE (type)));
1597 if (integer_nonzerop (compare))
1599 /* In the TRUE branch, we compute
1600 ratio = br/bi;
1601 div = (br * ratio) + bi;
1602 tr = (ar * ratio) + ai;
1603 ti = (ai * ratio) - ar;
1604 tr = tr / div;
1605 ti = ti / div; */
1606 tree ratio = const_binop (code, r2, i2);
1607 tree div = const_binop (PLUS_EXPR, i2,
1608 const_binop (MULT_EXPR, r2, ratio));
1609 real = const_binop (MULT_EXPR, r1, ratio);
1610 real = const_binop (PLUS_EXPR, real, i1);
1611 real = const_binop (code, real, div);
1613 imag = const_binop (MULT_EXPR, i1, ratio);
1614 imag = const_binop (MINUS_EXPR, imag, r1);
1615 imag = const_binop (code, imag, div);
1617 else
1619 /* In the FALSE branch, we compute
1620 ratio = d/c;
1621 divisor = (d * ratio) + c;
1622 tr = (b * ratio) + a;
1623 ti = b - (a * ratio);
1624 tr = tr / div;
1625 ti = ti / div; */
1626 tree ratio = const_binop (code, i2, r2);
1627 tree div = const_binop (PLUS_EXPR, r2,
1628 const_binop (MULT_EXPR, i2, ratio));
1630 real = const_binop (MULT_EXPR, i1, ratio);
1631 real = const_binop (PLUS_EXPR, real, r1);
1632 real = const_binop (code, real, div);
1634 imag = const_binop (MULT_EXPR, r1, ratio);
1635 imag = const_binop (MINUS_EXPR, i1, imag);
1636 imag = const_binop (code, imag, div);
1639 break;
1641 default:
1642 return NULL_TREE;
1645 if (real && imag)
1646 return build_complex (type, real, imag);
1649 if (TREE_CODE (arg1) == VECTOR_CST
1650 && TREE_CODE (arg2) == VECTOR_CST
1651 && known_eq (TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg1)),
1652 TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg2))))
1654 tree type = TREE_TYPE (arg1);
1655 bool step_ok_p;
1656 if (VECTOR_CST_STEPPED_P (arg1)
1657 && VECTOR_CST_STEPPED_P (arg2))
1658 /* We can operate directly on the encoding if:
1660 a3 - a2 == a2 - a1 && b3 - b2 == b2 - b1
1661 implies
1662 (a3 op b3) - (a2 op b2) == (a2 op b2) - (a1 op b1)
1664 Addition and subtraction are the supported operators
1665 for which this is true. */
1666 step_ok_p = (code == PLUS_EXPR || code == MINUS_EXPR);
1667 else if (VECTOR_CST_STEPPED_P (arg1))
1668 /* We can operate directly on stepped encodings if:
1670 a3 - a2 == a2 - a1
1671 implies:
1672 (a3 op c) - (a2 op c) == (a2 op c) - (a1 op c)
1674 which is true if (x -> x op c) distributes over addition. */
1675 step_ok_p = distributes_over_addition_p (code, 1);
1676 else
1677 /* Similarly in reverse. */
1678 step_ok_p = distributes_over_addition_p (code, 2);
1679 tree_vector_builder elts;
1680 if (!elts.new_binary_operation (type, arg1, arg2, step_ok_p))
1681 return NULL_TREE;
1682 unsigned int count = elts.encoded_nelts ();
1683 for (unsigned int i = 0; i < count; ++i)
1685 tree elem1 = VECTOR_CST_ELT (arg1, i);
1686 tree elem2 = VECTOR_CST_ELT (arg2, i);
1688 tree elt = const_binop (code, elem1, elem2);
1690 /* It is possible that const_binop cannot handle the given
1691 code and return NULL_TREE */
1692 if (elt == NULL_TREE)
1693 return NULL_TREE;
1694 elts.quick_push (elt);
1697 return elts.build ();
1700 /* Shifts allow a scalar offset for a vector. */
1701 if (TREE_CODE (arg1) == VECTOR_CST
1702 && TREE_CODE (arg2) == INTEGER_CST)
1704 tree type = TREE_TYPE (arg1);
1705 bool step_ok_p = distributes_over_addition_p (code, 1);
1706 tree_vector_builder elts;
1707 if (!elts.new_unary_operation (type, arg1, step_ok_p))
1708 return NULL_TREE;
1709 unsigned int count = elts.encoded_nelts ();
1710 for (unsigned int i = 0; i < count; ++i)
1712 tree elem1 = VECTOR_CST_ELT (arg1, i);
1714 tree elt = const_binop (code, elem1, arg2);
1716 /* It is possible that const_binop cannot handle the given
1717 code and return NULL_TREE. */
1718 if (elt == NULL_TREE)
1719 return NULL_TREE;
1720 elts.quick_push (elt);
1723 return elts.build ();
1725 return NULL_TREE;
1728 /* Overload that adds a TYPE parameter to be able to dispatch
1729 to fold_relational_const. */
1731 tree
1732 const_binop (enum tree_code code, tree type, tree arg1, tree arg2)
1734 if (TREE_CODE_CLASS (code) == tcc_comparison)
1735 return fold_relational_const (code, type, arg1, arg2);
1737 /* ??? Until we make the const_binop worker take the type of the
1738 result as argument put those cases that need it here. */
1739 switch (code)
1741 case VEC_SERIES_EXPR:
1742 if (CONSTANT_CLASS_P (arg1)
1743 && CONSTANT_CLASS_P (arg2))
1744 return build_vec_series (type, arg1, arg2);
1745 return NULL_TREE;
1747 case COMPLEX_EXPR:
1748 if ((TREE_CODE (arg1) == REAL_CST
1749 && TREE_CODE (arg2) == REAL_CST)
1750 || (TREE_CODE (arg1) == INTEGER_CST
1751 && TREE_CODE (arg2) == INTEGER_CST))
1752 return build_complex (type, arg1, arg2);
1753 return NULL_TREE;
1755 case POINTER_DIFF_EXPR:
1756 if (poly_int_tree_p (arg1) && poly_int_tree_p (arg2))
1758 poly_offset_int res = (wi::to_poly_offset (arg1)
1759 - wi::to_poly_offset (arg2));
1760 return force_fit_type (type, res, 1,
1761 TREE_OVERFLOW (arg1) | TREE_OVERFLOW (arg2));
1763 return NULL_TREE;
1765 case VEC_PACK_TRUNC_EXPR:
1766 case VEC_PACK_FIX_TRUNC_EXPR:
1767 case VEC_PACK_FLOAT_EXPR:
1769 unsigned int HOST_WIDE_INT out_nelts, in_nelts, i;
1771 if (TREE_CODE (arg1) != VECTOR_CST
1772 || TREE_CODE (arg2) != VECTOR_CST)
1773 return NULL_TREE;
1775 if (!VECTOR_CST_NELTS (arg1).is_constant (&in_nelts))
1776 return NULL_TREE;
1778 out_nelts = in_nelts * 2;
1779 gcc_assert (known_eq (in_nelts, VECTOR_CST_NELTS (arg2))
1780 && known_eq (out_nelts, TYPE_VECTOR_SUBPARTS (type)));
1782 tree_vector_builder elts (type, out_nelts, 1);
1783 for (i = 0; i < out_nelts; i++)
1785 tree elt = (i < in_nelts
1786 ? VECTOR_CST_ELT (arg1, i)
1787 : VECTOR_CST_ELT (arg2, i - in_nelts));
1788 elt = fold_convert_const (code == VEC_PACK_TRUNC_EXPR
1789 ? NOP_EXPR
1790 : code == VEC_PACK_FLOAT_EXPR
1791 ? FLOAT_EXPR : FIX_TRUNC_EXPR,
1792 TREE_TYPE (type), elt);
1793 if (elt == NULL_TREE || !CONSTANT_CLASS_P (elt))
1794 return NULL_TREE;
1795 elts.quick_push (elt);
1798 return elts.build ();
1801 case VEC_WIDEN_MULT_LO_EXPR:
1802 case VEC_WIDEN_MULT_HI_EXPR:
1803 case VEC_WIDEN_MULT_EVEN_EXPR:
1804 case VEC_WIDEN_MULT_ODD_EXPR:
1806 unsigned HOST_WIDE_INT out_nelts, in_nelts, out, ofs, scale;
1808 if (TREE_CODE (arg1) != VECTOR_CST || TREE_CODE (arg2) != VECTOR_CST)
1809 return NULL_TREE;
1811 if (!VECTOR_CST_NELTS (arg1).is_constant (&in_nelts))
1812 return NULL_TREE;
1813 out_nelts = in_nelts / 2;
1814 gcc_assert (known_eq (in_nelts, VECTOR_CST_NELTS (arg2))
1815 && known_eq (out_nelts, TYPE_VECTOR_SUBPARTS (type)));
1817 if (code == VEC_WIDEN_MULT_LO_EXPR)
1818 scale = 0, ofs = BYTES_BIG_ENDIAN ? out_nelts : 0;
1819 else if (code == VEC_WIDEN_MULT_HI_EXPR)
1820 scale = 0, ofs = BYTES_BIG_ENDIAN ? 0 : out_nelts;
1821 else if (code == VEC_WIDEN_MULT_EVEN_EXPR)
1822 scale = 1, ofs = 0;
1823 else /* if (code == VEC_WIDEN_MULT_ODD_EXPR) */
1824 scale = 1, ofs = 1;
1826 tree_vector_builder elts (type, out_nelts, 1);
1827 for (out = 0; out < out_nelts; out++)
1829 unsigned int in = (out << scale) + ofs;
1830 tree t1 = fold_convert_const (NOP_EXPR, TREE_TYPE (type),
1831 VECTOR_CST_ELT (arg1, in));
1832 tree t2 = fold_convert_const (NOP_EXPR, TREE_TYPE (type),
1833 VECTOR_CST_ELT (arg2, in));
1835 if (t1 == NULL_TREE || t2 == NULL_TREE)
1836 return NULL_TREE;
1837 tree elt = const_binop (MULT_EXPR, t1, t2);
1838 if (elt == NULL_TREE || !CONSTANT_CLASS_P (elt))
1839 return NULL_TREE;
1840 elts.quick_push (elt);
1843 return elts.build ();
1846 default:;
1849 if (TREE_CODE_CLASS (code) != tcc_binary)
1850 return NULL_TREE;
1852 /* Make sure type and arg0 have the same saturating flag. */
1853 gcc_checking_assert (TYPE_SATURATING (type)
1854 == TYPE_SATURATING (TREE_TYPE (arg1)));
1856 return const_binop (code, arg1, arg2);
1859 /* Compute CODE ARG1 with resulting type TYPE with ARG1 being constant.
1860 Return zero if computing the constants is not possible. */
1862 tree
1863 const_unop (enum tree_code code, tree type, tree arg0)
1865 /* Don't perform the operation, other than NEGATE and ABS, if
1866 flag_signaling_nans is on and the operand is a signaling NaN. */
1867 if (TREE_CODE (arg0) == REAL_CST
1868 && HONOR_SNANS (arg0)
1869 && REAL_VALUE_ISSIGNALING_NAN (TREE_REAL_CST (arg0))
1870 && code != NEGATE_EXPR
1871 && code != ABS_EXPR
1872 && code != ABSU_EXPR)
1873 return NULL_TREE;
1875 switch (code)
1877 CASE_CONVERT:
1878 case FLOAT_EXPR:
1879 case FIX_TRUNC_EXPR:
1880 case FIXED_CONVERT_EXPR:
1881 return fold_convert_const (code, type, arg0);
1883 case ADDR_SPACE_CONVERT_EXPR:
1884 /* If the source address is 0, and the source address space
1885 cannot have a valid object at 0, fold to dest type null. */
1886 if (integer_zerop (arg0)
1887 && !(targetm.addr_space.zero_address_valid
1888 (TYPE_ADDR_SPACE (TREE_TYPE (TREE_TYPE (arg0))))))
1889 return fold_convert_const (code, type, arg0);
1890 break;
1892 case VIEW_CONVERT_EXPR:
1893 return fold_view_convert_expr (type, arg0);
1895 case NEGATE_EXPR:
1897 /* Can't call fold_negate_const directly here as that doesn't
1898 handle all cases and we might not be able to negate some
1899 constants. */
1900 tree tem = fold_negate_expr (UNKNOWN_LOCATION, arg0);
1901 if (tem && CONSTANT_CLASS_P (tem))
1902 return tem;
1903 break;
1906 case ABS_EXPR:
1907 case ABSU_EXPR:
1908 if (TREE_CODE (arg0) == INTEGER_CST || TREE_CODE (arg0) == REAL_CST)
1909 return fold_abs_const (arg0, type);
1910 break;
1912 case CONJ_EXPR:
1913 if (TREE_CODE (arg0) == COMPLEX_CST)
1915 tree ipart = fold_negate_const (TREE_IMAGPART (arg0),
1916 TREE_TYPE (type));
1917 return build_complex (type, TREE_REALPART (arg0), ipart);
1919 break;
1921 case BIT_NOT_EXPR:
1922 if (TREE_CODE (arg0) == INTEGER_CST)
1923 return fold_not_const (arg0, type);
1924 else if (POLY_INT_CST_P (arg0))
1925 return wide_int_to_tree (type, -poly_int_cst_value (arg0));
1926 /* Perform BIT_NOT_EXPR on each element individually. */
1927 else if (TREE_CODE (arg0) == VECTOR_CST)
1929 tree elem;
1931 /* This can cope with stepped encodings because ~x == -1 - x. */
1932 tree_vector_builder elements;
1933 elements.new_unary_operation (type, arg0, true);
1934 unsigned int i, count = elements.encoded_nelts ();
1935 for (i = 0; i < count; ++i)
1937 elem = VECTOR_CST_ELT (arg0, i);
1938 elem = const_unop (BIT_NOT_EXPR, TREE_TYPE (type), elem);
1939 if (elem == NULL_TREE)
1940 break;
1941 elements.quick_push (elem);
1943 if (i == count)
1944 return elements.build ();
1946 break;
1948 case TRUTH_NOT_EXPR:
1949 if (TREE_CODE (arg0) == INTEGER_CST)
1950 return constant_boolean_node (integer_zerop (arg0), type);
1951 break;
1953 case REALPART_EXPR:
1954 if (TREE_CODE (arg0) == COMPLEX_CST)
1955 return fold_convert (type, TREE_REALPART (arg0));
1956 break;
1958 case IMAGPART_EXPR:
1959 if (TREE_CODE (arg0) == COMPLEX_CST)
1960 return fold_convert (type, TREE_IMAGPART (arg0));
1961 break;
1963 case VEC_UNPACK_LO_EXPR:
1964 case VEC_UNPACK_HI_EXPR:
1965 case VEC_UNPACK_FLOAT_LO_EXPR:
1966 case VEC_UNPACK_FLOAT_HI_EXPR:
1967 case VEC_UNPACK_FIX_TRUNC_LO_EXPR:
1968 case VEC_UNPACK_FIX_TRUNC_HI_EXPR:
1970 unsigned HOST_WIDE_INT out_nelts, in_nelts, i;
1971 enum tree_code subcode;
1973 if (TREE_CODE (arg0) != VECTOR_CST)
1974 return NULL_TREE;
1976 if (!VECTOR_CST_NELTS (arg0).is_constant (&in_nelts))
1977 return NULL_TREE;
1978 out_nelts = in_nelts / 2;
1979 gcc_assert (known_eq (out_nelts, TYPE_VECTOR_SUBPARTS (type)));
1981 unsigned int offset = 0;
1982 if ((!BYTES_BIG_ENDIAN) ^ (code == VEC_UNPACK_LO_EXPR
1983 || code == VEC_UNPACK_FLOAT_LO_EXPR
1984 || code == VEC_UNPACK_FIX_TRUNC_LO_EXPR))
1985 offset = out_nelts;
1987 if (code == VEC_UNPACK_LO_EXPR || code == VEC_UNPACK_HI_EXPR)
1988 subcode = NOP_EXPR;
1989 else if (code == VEC_UNPACK_FLOAT_LO_EXPR
1990 || code == VEC_UNPACK_FLOAT_HI_EXPR)
1991 subcode = FLOAT_EXPR;
1992 else
1993 subcode = FIX_TRUNC_EXPR;
1995 tree_vector_builder elts (type, out_nelts, 1);
1996 for (i = 0; i < out_nelts; i++)
1998 tree elt = fold_convert_const (subcode, TREE_TYPE (type),
1999 VECTOR_CST_ELT (arg0, i + offset));
2000 if (elt == NULL_TREE || !CONSTANT_CLASS_P (elt))
2001 return NULL_TREE;
2002 elts.quick_push (elt);
2005 return elts.build ();
2008 case VEC_DUPLICATE_EXPR:
2009 if (CONSTANT_CLASS_P (arg0))
2010 return build_vector_from_val (type, arg0);
2011 return NULL_TREE;
2013 default:
2014 break;
2017 return NULL_TREE;
2020 /* Create a sizetype INT_CST node with NUMBER sign extended. KIND
2021 indicates which particular sizetype to create. */
2023 tree
2024 size_int_kind (poly_int64 number, enum size_type_kind kind)
2026 return build_int_cst (sizetype_tab[(int) kind], number);
2029 /* Combine operands OP1 and OP2 with arithmetic operation CODE. CODE
2030 is a tree code. The type of the result is taken from the operands.
2031 Both must be equivalent integer types, ala int_binop_types_match_p.
2032 If the operands are constant, so is the result. */
2034 tree
2035 size_binop_loc (location_t loc, enum tree_code code, tree arg0, tree arg1)
2037 tree type = TREE_TYPE (arg0);
2039 if (arg0 == error_mark_node || arg1 == error_mark_node)
2040 return error_mark_node;
2042 gcc_assert (int_binop_types_match_p (code, TREE_TYPE (arg0),
2043 TREE_TYPE (arg1)));
2045 /* Handle the special case of two poly_int constants faster. */
2046 if (poly_int_tree_p (arg0) && poly_int_tree_p (arg1))
2048 /* And some specific cases even faster than that. */
2049 if (code == PLUS_EXPR)
2051 if (integer_zerop (arg0)
2052 && !TREE_OVERFLOW (tree_strip_any_location_wrapper (arg0)))
2053 return arg1;
2054 if (integer_zerop (arg1)
2055 && !TREE_OVERFLOW (tree_strip_any_location_wrapper (arg1)))
2056 return arg0;
2058 else if (code == MINUS_EXPR)
2060 if (integer_zerop (arg1)
2061 && !TREE_OVERFLOW (tree_strip_any_location_wrapper (arg1)))
2062 return arg0;
2064 else if (code == MULT_EXPR)
2066 if (integer_onep (arg0)
2067 && !TREE_OVERFLOW (tree_strip_any_location_wrapper (arg0)))
2068 return arg1;
2071 /* Handle general case of two integer constants. For sizetype
2072 constant calculations we always want to know about overflow,
2073 even in the unsigned case. */
2074 tree res = int_const_binop (code, arg0, arg1, -1);
2075 if (res != NULL_TREE)
2076 return res;
2079 return fold_build2_loc (loc, code, type, arg0, arg1);
2082 /* Given two values, either both of sizetype or both of bitsizetype,
2083 compute the difference between the two values. Return the value
2084 in signed type corresponding to the type of the operands. */
2086 tree
2087 size_diffop_loc (location_t loc, tree arg0, tree arg1)
2089 tree type = TREE_TYPE (arg0);
2090 tree ctype;
2092 gcc_assert (int_binop_types_match_p (MINUS_EXPR, TREE_TYPE (arg0),
2093 TREE_TYPE (arg1)));
2095 /* If the type is already signed, just do the simple thing. */
2096 if (!TYPE_UNSIGNED (type))
2097 return size_binop_loc (loc, MINUS_EXPR, arg0, arg1);
2099 if (type == sizetype)
2100 ctype = ssizetype;
2101 else if (type == bitsizetype)
2102 ctype = sbitsizetype;
2103 else
2104 ctype = signed_type_for (type);
2106 /* If either operand is not a constant, do the conversions to the signed
2107 type and subtract. The hardware will do the right thing with any
2108 overflow in the subtraction. */
2109 if (TREE_CODE (arg0) != INTEGER_CST || TREE_CODE (arg1) != INTEGER_CST)
2110 return size_binop_loc (loc, MINUS_EXPR,
2111 fold_convert_loc (loc, ctype, arg0),
2112 fold_convert_loc (loc, ctype, arg1));
2114 /* If ARG0 is larger than ARG1, subtract and return the result in CTYPE.
2115 Otherwise, subtract the other way, convert to CTYPE (we know that can't
2116 overflow) and negate (which can't either). Special-case a result
2117 of zero while we're here. */
2118 if (tree_int_cst_equal (arg0, arg1))
2119 return build_int_cst (ctype, 0);
2120 else if (tree_int_cst_lt (arg1, arg0))
2121 return fold_convert_loc (loc, ctype,
2122 size_binop_loc (loc, MINUS_EXPR, arg0, arg1));
2123 else
2124 return size_binop_loc (loc, MINUS_EXPR, build_int_cst (ctype, 0),
2125 fold_convert_loc (loc, ctype,
2126 size_binop_loc (loc,
2127 MINUS_EXPR,
2128 arg1, arg0)));
2131 /* A subroutine of fold_convert_const handling conversions of an
2132 INTEGER_CST to another integer type. */
2134 static tree
2135 fold_convert_const_int_from_int (tree type, const_tree arg1)
2137 /* Given an integer constant, make new constant with new type,
2138 appropriately sign-extended or truncated. Use widest_int
2139 so that any extension is done according ARG1's type. */
2140 tree arg1_type = TREE_TYPE (arg1);
2141 unsigned prec = MAX (TYPE_PRECISION (arg1_type), TYPE_PRECISION (type));
2142 return force_fit_type (type, wide_int::from (wi::to_wide (arg1), prec,
2143 TYPE_SIGN (arg1_type)),
2144 !POINTER_TYPE_P (TREE_TYPE (arg1)),
2145 TREE_OVERFLOW (arg1));
2148 /* A subroutine of fold_convert_const handling conversions a REAL_CST
2149 to an integer type. */
2151 static tree
2152 fold_convert_const_int_from_real (enum tree_code code, tree type, const_tree arg1)
2154 bool overflow = false;
2155 tree t;
2157 /* The following code implements the floating point to integer
2158 conversion rules required by the Java Language Specification,
2159 that IEEE NaNs are mapped to zero and values that overflow
2160 the target precision saturate, i.e. values greater than
2161 INT_MAX are mapped to INT_MAX, and values less than INT_MIN
2162 are mapped to INT_MIN. These semantics are allowed by the
2163 C and C++ standards that simply state that the behavior of
2164 FP-to-integer conversion is unspecified upon overflow. */
2166 wide_int val;
2167 REAL_VALUE_TYPE r;
2168 REAL_VALUE_TYPE x = TREE_REAL_CST (arg1);
2170 switch (code)
2172 case FIX_TRUNC_EXPR:
2173 real_trunc (&r, VOIDmode, &x);
2174 break;
2176 default:
2177 gcc_unreachable ();
2180 /* If R is NaN, return zero and show we have an overflow. */
2181 if (REAL_VALUE_ISNAN (r))
2183 overflow = true;
2184 val = wi::zero (TYPE_PRECISION (type));
2187 /* See if R is less than the lower bound or greater than the
2188 upper bound. */
2190 if (! overflow)
2192 tree lt = TYPE_MIN_VALUE (type);
2193 REAL_VALUE_TYPE l = real_value_from_int_cst (NULL_TREE, lt);
2194 if (real_less (&r, &l))
2196 overflow = true;
2197 val = wi::to_wide (lt);
2201 if (! overflow)
2203 tree ut = TYPE_MAX_VALUE (type);
2204 if (ut)
2206 REAL_VALUE_TYPE u = real_value_from_int_cst (NULL_TREE, ut);
2207 if (real_less (&u, &r))
2209 overflow = true;
2210 val = wi::to_wide (ut);
2215 if (! overflow)
2216 val = real_to_integer (&r, &overflow, TYPE_PRECISION (type));
2218 t = force_fit_type (type, val, -1, overflow | TREE_OVERFLOW (arg1));
2219 return t;
2222 /* A subroutine of fold_convert_const handling conversions of a
2223 FIXED_CST to an integer type. */
2225 static tree
2226 fold_convert_const_int_from_fixed (tree type, const_tree arg1)
2228 tree t;
2229 double_int temp, temp_trunc;
2230 scalar_mode mode;
2232 /* Right shift FIXED_CST to temp by fbit. */
2233 temp = TREE_FIXED_CST (arg1).data;
2234 mode = TREE_FIXED_CST (arg1).mode;
2235 if (GET_MODE_FBIT (mode) < HOST_BITS_PER_DOUBLE_INT)
2237 temp = temp.rshift (GET_MODE_FBIT (mode),
2238 HOST_BITS_PER_DOUBLE_INT,
2239 SIGNED_FIXED_POINT_MODE_P (mode));
2241 /* Left shift temp to temp_trunc by fbit. */
2242 temp_trunc = temp.lshift (GET_MODE_FBIT (mode),
2243 HOST_BITS_PER_DOUBLE_INT,
2244 SIGNED_FIXED_POINT_MODE_P (mode));
2246 else
2248 temp = double_int_zero;
2249 temp_trunc = double_int_zero;
2252 /* If FIXED_CST is negative, we need to round the value toward 0.
2253 By checking if the fractional bits are not zero to add 1 to temp. */
2254 if (SIGNED_FIXED_POINT_MODE_P (mode)
2255 && temp_trunc.is_negative ()
2256 && TREE_FIXED_CST (arg1).data != temp_trunc)
2257 temp += double_int_one;
2259 /* Given a fixed-point constant, make new constant with new type,
2260 appropriately sign-extended or truncated. */
2261 t = force_fit_type (type, temp, -1,
2262 (temp.is_negative ()
2263 && (TYPE_UNSIGNED (type)
2264 < TYPE_UNSIGNED (TREE_TYPE (arg1))))
2265 | TREE_OVERFLOW (arg1));
2267 return t;
2270 /* A subroutine of fold_convert_const handling conversions a REAL_CST
2271 to another floating point type. */
2273 static tree
2274 fold_convert_const_real_from_real (tree type, const_tree arg1)
2276 REAL_VALUE_TYPE value;
2277 tree t;
2279 /* If the underlying modes are the same, simply treat it as
2280 copy and rebuild with TREE_REAL_CST information and the
2281 given type. */
2282 if (TYPE_MODE (type) == TYPE_MODE (TREE_TYPE (arg1)))
2284 t = build_real (type, TREE_REAL_CST (arg1));
2285 return t;
2288 /* Don't perform the operation if flag_signaling_nans is on
2289 and the operand is a signaling NaN. */
2290 if (HONOR_SNANS (arg1)
2291 && REAL_VALUE_ISSIGNALING_NAN (TREE_REAL_CST (arg1)))
2292 return NULL_TREE;
2294 /* With flag_rounding_math we should respect the current rounding mode
2295 unless the conversion is exact. */
2296 if (HONOR_SIGN_DEPENDENT_ROUNDING (arg1)
2297 && !exact_real_truncate (TYPE_MODE (type), &TREE_REAL_CST (arg1)))
2298 return NULL_TREE;
2300 real_convert (&value, TYPE_MODE (type), &TREE_REAL_CST (arg1));
2301 t = build_real (type, value);
2303 /* If converting an infinity or NAN to a representation that doesn't
2304 have one, set the overflow bit so that we can produce some kind of
2305 error message at the appropriate point if necessary. It's not the
2306 most user-friendly message, but it's better than nothing. */
2307 if (REAL_VALUE_ISINF (TREE_REAL_CST (arg1))
2308 && !MODE_HAS_INFINITIES (TYPE_MODE (type)))
2309 TREE_OVERFLOW (t) = 1;
2310 else if (REAL_VALUE_ISNAN (TREE_REAL_CST (arg1))
2311 && !MODE_HAS_NANS (TYPE_MODE (type)))
2312 TREE_OVERFLOW (t) = 1;
2313 /* Regular overflow, conversion produced an infinity in a mode that
2314 can't represent them. */
2315 else if (!MODE_HAS_INFINITIES (TYPE_MODE (type))
2316 && REAL_VALUE_ISINF (value)
2317 && !REAL_VALUE_ISINF (TREE_REAL_CST (arg1)))
2318 TREE_OVERFLOW (t) = 1;
2319 else
2320 TREE_OVERFLOW (t) = TREE_OVERFLOW (arg1);
2321 return t;
2324 /* A subroutine of fold_convert_const handling conversions a FIXED_CST
2325 to a floating point type. */
2327 static tree
2328 fold_convert_const_real_from_fixed (tree type, const_tree arg1)
2330 REAL_VALUE_TYPE value;
2331 tree t;
2333 real_convert_from_fixed (&value, SCALAR_FLOAT_TYPE_MODE (type),
2334 &TREE_FIXED_CST (arg1));
2335 t = build_real (type, value);
2337 TREE_OVERFLOW (t) = TREE_OVERFLOW (arg1);
2338 return t;
2341 /* A subroutine of fold_convert_const handling conversions a FIXED_CST
2342 to another fixed-point type. */
2344 static tree
2345 fold_convert_const_fixed_from_fixed (tree type, const_tree arg1)
2347 FIXED_VALUE_TYPE value;
2348 tree t;
2349 bool overflow_p;
2351 overflow_p = fixed_convert (&value, SCALAR_TYPE_MODE (type),
2352 &TREE_FIXED_CST (arg1), TYPE_SATURATING (type));
2353 t = build_fixed (type, value);
2355 /* Propagate overflow flags. */
2356 if (overflow_p | TREE_OVERFLOW (arg1))
2357 TREE_OVERFLOW (t) = 1;
2358 return t;
2361 /* A subroutine of fold_convert_const handling conversions an INTEGER_CST
2362 to a fixed-point type. */
2364 static tree
2365 fold_convert_const_fixed_from_int (tree type, const_tree arg1)
2367 FIXED_VALUE_TYPE value;
2368 tree t;
2369 bool overflow_p;
2370 double_int di;
2372 gcc_assert (TREE_INT_CST_NUNITS (arg1) <= 2);
2374 di.low = TREE_INT_CST_ELT (arg1, 0);
2375 if (TREE_INT_CST_NUNITS (arg1) == 1)
2376 di.high = (HOST_WIDE_INT) di.low < 0 ? HOST_WIDE_INT_M1 : 0;
2377 else
2378 di.high = TREE_INT_CST_ELT (arg1, 1);
2380 overflow_p = fixed_convert_from_int (&value, SCALAR_TYPE_MODE (type), di,
2381 TYPE_UNSIGNED (TREE_TYPE (arg1)),
2382 TYPE_SATURATING (type));
2383 t = build_fixed (type, value);
2385 /* Propagate overflow flags. */
2386 if (overflow_p | TREE_OVERFLOW (arg1))
2387 TREE_OVERFLOW (t) = 1;
2388 return t;
2391 /* A subroutine of fold_convert_const handling conversions a REAL_CST
2392 to a fixed-point type. */
2394 static tree
2395 fold_convert_const_fixed_from_real (tree type, const_tree arg1)
2397 FIXED_VALUE_TYPE value;
2398 tree t;
2399 bool overflow_p;
2401 overflow_p = fixed_convert_from_real (&value, SCALAR_TYPE_MODE (type),
2402 &TREE_REAL_CST (arg1),
2403 TYPE_SATURATING (type));
2404 t = build_fixed (type, value);
2406 /* Propagate overflow flags. */
2407 if (overflow_p | TREE_OVERFLOW (arg1))
2408 TREE_OVERFLOW (t) = 1;
2409 return t;
2412 /* Attempt to fold type conversion operation CODE of expression ARG1 to
2413 type TYPE. If no simplification can be done return NULL_TREE. */
2415 static tree
2416 fold_convert_const (enum tree_code code, tree type, tree arg1)
2418 tree arg_type = TREE_TYPE (arg1);
2419 if (arg_type == type)
2420 return arg1;
2422 /* We can't widen types, since the runtime value could overflow the
2423 original type before being extended to the new type. */
2424 if (POLY_INT_CST_P (arg1)
2425 && (POINTER_TYPE_P (type) || INTEGRAL_TYPE_P (type))
2426 && TYPE_PRECISION (type) <= TYPE_PRECISION (arg_type))
2427 return build_poly_int_cst (type,
2428 poly_wide_int::from (poly_int_cst_value (arg1),
2429 TYPE_PRECISION (type),
2430 TYPE_SIGN (arg_type)));
2432 if (POINTER_TYPE_P (type) || INTEGRAL_TYPE_P (type)
2433 || TREE_CODE (type) == OFFSET_TYPE)
2435 if (TREE_CODE (arg1) == INTEGER_CST)
2436 return fold_convert_const_int_from_int (type, arg1);
2437 else if (TREE_CODE (arg1) == REAL_CST)
2438 return fold_convert_const_int_from_real (code, type, arg1);
2439 else if (TREE_CODE (arg1) == FIXED_CST)
2440 return fold_convert_const_int_from_fixed (type, arg1);
2442 else if (SCALAR_FLOAT_TYPE_P (type))
2444 if (TREE_CODE (arg1) == INTEGER_CST)
2446 tree res = build_real_from_int_cst (type, arg1);
2447 /* Avoid the folding if flag_rounding_math is on and the
2448 conversion is not exact. */
2449 if (HONOR_SIGN_DEPENDENT_ROUNDING (type))
2451 bool fail = false;
2452 wide_int w = real_to_integer (&TREE_REAL_CST (res), &fail,
2453 TYPE_PRECISION (TREE_TYPE (arg1)));
2454 if (fail || wi::ne_p (w, wi::to_wide (arg1)))
2455 return NULL_TREE;
2457 return res;
2459 else if (TREE_CODE (arg1) == REAL_CST)
2460 return fold_convert_const_real_from_real (type, arg1);
2461 else if (TREE_CODE (arg1) == FIXED_CST)
2462 return fold_convert_const_real_from_fixed (type, arg1);
2464 else if (FIXED_POINT_TYPE_P (type))
2466 if (TREE_CODE (arg1) == FIXED_CST)
2467 return fold_convert_const_fixed_from_fixed (type, arg1);
2468 else if (TREE_CODE (arg1) == INTEGER_CST)
2469 return fold_convert_const_fixed_from_int (type, arg1);
2470 else if (TREE_CODE (arg1) == REAL_CST)
2471 return fold_convert_const_fixed_from_real (type, arg1);
2473 else if (VECTOR_TYPE_P (type))
2475 if (TREE_CODE (arg1) == VECTOR_CST
2476 && known_eq (TYPE_VECTOR_SUBPARTS (type), VECTOR_CST_NELTS (arg1)))
2478 tree elttype = TREE_TYPE (type);
2479 tree arg1_elttype = TREE_TYPE (TREE_TYPE (arg1));
2480 /* We can't handle steps directly when extending, since the
2481 values need to wrap at the original precision first. */
2482 bool step_ok_p
2483 = (INTEGRAL_TYPE_P (elttype)
2484 && INTEGRAL_TYPE_P (arg1_elttype)
2485 && TYPE_PRECISION (elttype) <= TYPE_PRECISION (arg1_elttype));
2486 tree_vector_builder v;
2487 if (!v.new_unary_operation (type, arg1, step_ok_p))
2488 return NULL_TREE;
2489 unsigned int len = v.encoded_nelts ();
2490 for (unsigned int i = 0; i < len; ++i)
2492 tree elt = VECTOR_CST_ELT (arg1, i);
2493 tree cvt = fold_convert_const (code, elttype, elt);
2494 if (cvt == NULL_TREE)
2495 return NULL_TREE;
2496 v.quick_push (cvt);
2498 return v.build ();
2501 return NULL_TREE;
2504 /* Construct a vector of zero elements of vector type TYPE. */
2506 static tree
2507 build_zero_vector (tree type)
2509 tree t;
2511 t = fold_convert_const (NOP_EXPR, TREE_TYPE (type), integer_zero_node);
2512 return build_vector_from_val (type, t);
2515 /* Returns true, if ARG is convertible to TYPE using a NOP_EXPR. */
2517 bool
2518 fold_convertible_p (const_tree type, const_tree arg)
2520 const_tree orig = TREE_TYPE (arg);
2522 if (type == orig)
2523 return true;
2525 if (TREE_CODE (arg) == ERROR_MARK
2526 || TREE_CODE (type) == ERROR_MARK
2527 || TREE_CODE (orig) == ERROR_MARK)
2528 return false;
2530 if (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (orig))
2531 return true;
2533 switch (TREE_CODE (type))
2535 case INTEGER_TYPE: case ENUMERAL_TYPE: case BOOLEAN_TYPE:
2536 case POINTER_TYPE: case REFERENCE_TYPE:
2537 case OFFSET_TYPE:
2538 return (INTEGRAL_TYPE_P (orig)
2539 || (POINTER_TYPE_P (orig)
2540 && TYPE_PRECISION (type) <= TYPE_PRECISION (orig))
2541 || TREE_CODE (orig) == OFFSET_TYPE);
2543 case REAL_TYPE:
2544 case FIXED_POINT_TYPE:
2545 case VOID_TYPE:
2546 return TREE_CODE (type) == TREE_CODE (orig);
2548 case VECTOR_TYPE:
2549 return (VECTOR_TYPE_P (orig)
2550 && known_eq (TYPE_VECTOR_SUBPARTS (type),
2551 TYPE_VECTOR_SUBPARTS (orig))
2552 && tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (orig)));
2554 default:
2555 return false;
2559 /* Convert expression ARG to type TYPE. Used by the middle-end for
2560 simple conversions in preference to calling the front-end's convert. */
2562 tree
2563 fold_convert_loc (location_t loc, tree type, tree arg)
2565 tree orig = TREE_TYPE (arg);
2566 tree tem;
2568 if (type == orig)
2569 return arg;
2571 if (TREE_CODE (arg) == ERROR_MARK
2572 || TREE_CODE (type) == ERROR_MARK
2573 || TREE_CODE (orig) == ERROR_MARK)
2574 return error_mark_node;
2576 switch (TREE_CODE (type))
2578 case POINTER_TYPE:
2579 case REFERENCE_TYPE:
2580 /* Handle conversions between pointers to different address spaces. */
2581 if (POINTER_TYPE_P (orig)
2582 && (TYPE_ADDR_SPACE (TREE_TYPE (type))
2583 != TYPE_ADDR_SPACE (TREE_TYPE (orig))))
2584 return fold_build1_loc (loc, ADDR_SPACE_CONVERT_EXPR, type, arg);
2585 /* fall through */
2587 case INTEGER_TYPE: case ENUMERAL_TYPE: case BOOLEAN_TYPE:
2588 case OFFSET_TYPE: case BITINT_TYPE:
2589 if (TREE_CODE (arg) == INTEGER_CST)
2591 tem = fold_convert_const (NOP_EXPR, type, arg);
2592 if (tem != NULL_TREE)
2593 return tem;
2595 if (INTEGRAL_TYPE_P (orig) || POINTER_TYPE_P (orig)
2596 || TREE_CODE (orig) == OFFSET_TYPE)
2597 return fold_build1_loc (loc, NOP_EXPR, type, arg);
2598 if (TREE_CODE (orig) == COMPLEX_TYPE)
2599 return fold_convert_loc (loc, type,
2600 fold_build1_loc (loc, REALPART_EXPR,
2601 TREE_TYPE (orig), arg));
2602 gcc_assert (VECTOR_TYPE_P (orig)
2603 && tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (orig)));
2604 return fold_build1_loc (loc, VIEW_CONVERT_EXPR, type, arg);
2606 case REAL_TYPE:
2607 if (TREE_CODE (arg) == INTEGER_CST)
2609 tem = fold_convert_const (FLOAT_EXPR, type, arg);
2610 if (tem != NULL_TREE)
2611 return tem;
2613 else if (TREE_CODE (arg) == REAL_CST)
2615 tem = fold_convert_const (NOP_EXPR, type, arg);
2616 if (tem != NULL_TREE)
2617 return tem;
2619 else if (TREE_CODE (arg) == FIXED_CST)
2621 tem = fold_convert_const (FIXED_CONVERT_EXPR, type, arg);
2622 if (tem != NULL_TREE)
2623 return tem;
2626 switch (TREE_CODE (orig))
2628 case INTEGER_TYPE: case BITINT_TYPE:
2629 case BOOLEAN_TYPE: case ENUMERAL_TYPE:
2630 case POINTER_TYPE: case REFERENCE_TYPE:
2631 return fold_build1_loc (loc, FLOAT_EXPR, type, arg);
2633 case REAL_TYPE:
2634 return fold_build1_loc (loc, NOP_EXPR, type, arg);
2636 case FIXED_POINT_TYPE:
2637 return fold_build1_loc (loc, FIXED_CONVERT_EXPR, type, arg);
2639 case COMPLEX_TYPE:
2640 tem = fold_build1_loc (loc, REALPART_EXPR, TREE_TYPE (orig), arg);
2641 return fold_convert_loc (loc, type, tem);
2643 default:
2644 gcc_unreachable ();
2647 case FIXED_POINT_TYPE:
2648 if (TREE_CODE (arg) == FIXED_CST || TREE_CODE (arg) == INTEGER_CST
2649 || TREE_CODE (arg) == REAL_CST)
2651 tem = fold_convert_const (FIXED_CONVERT_EXPR, type, arg);
2652 if (tem != NULL_TREE)
2653 goto fold_convert_exit;
2656 switch (TREE_CODE (orig))
2658 case FIXED_POINT_TYPE:
2659 case INTEGER_TYPE:
2660 case ENUMERAL_TYPE:
2661 case BOOLEAN_TYPE:
2662 case REAL_TYPE:
2663 case BITINT_TYPE:
2664 return fold_build1_loc (loc, FIXED_CONVERT_EXPR, type, arg);
2666 case COMPLEX_TYPE:
2667 tem = fold_build1_loc (loc, REALPART_EXPR, TREE_TYPE (orig), arg);
2668 return fold_convert_loc (loc, type, tem);
2670 default:
2671 gcc_unreachable ();
2674 case COMPLEX_TYPE:
2675 switch (TREE_CODE (orig))
2677 case INTEGER_TYPE: case BITINT_TYPE:
2678 case BOOLEAN_TYPE: case ENUMERAL_TYPE:
2679 case POINTER_TYPE: case REFERENCE_TYPE:
2680 case REAL_TYPE:
2681 case FIXED_POINT_TYPE:
2682 return fold_build2_loc (loc, COMPLEX_EXPR, type,
2683 fold_convert_loc (loc, TREE_TYPE (type), arg),
2684 fold_convert_loc (loc, TREE_TYPE (type),
2685 integer_zero_node));
2686 case COMPLEX_TYPE:
2688 tree rpart, ipart;
2690 if (TREE_CODE (arg) == COMPLEX_EXPR)
2692 rpart = fold_convert_loc (loc, TREE_TYPE (type),
2693 TREE_OPERAND (arg, 0));
2694 ipart = fold_convert_loc (loc, TREE_TYPE (type),
2695 TREE_OPERAND (arg, 1));
2696 return fold_build2_loc (loc, COMPLEX_EXPR, type, rpart, ipart);
2699 arg = save_expr (arg);
2700 rpart = fold_build1_loc (loc, REALPART_EXPR, TREE_TYPE (orig), arg);
2701 ipart = fold_build1_loc (loc, IMAGPART_EXPR, TREE_TYPE (orig), arg);
2702 rpart = fold_convert_loc (loc, TREE_TYPE (type), rpart);
2703 ipart = fold_convert_loc (loc, TREE_TYPE (type), ipart);
2704 return fold_build2_loc (loc, COMPLEX_EXPR, type, rpart, ipart);
2707 default:
2708 gcc_unreachable ();
2711 case VECTOR_TYPE:
2712 if (integer_zerop (arg))
2713 return build_zero_vector (type);
2714 gcc_assert (tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (orig)));
2715 gcc_assert (INTEGRAL_TYPE_P (orig) || POINTER_TYPE_P (orig)
2716 || VECTOR_TYPE_P (orig));
2717 return fold_build1_loc (loc, VIEW_CONVERT_EXPR, type, arg);
2719 case VOID_TYPE:
2720 tem = fold_ignored_result (arg);
2721 return fold_build1_loc (loc, NOP_EXPR, type, tem);
2723 default:
2724 if (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (orig))
2725 return fold_build1_loc (loc, NOP_EXPR, type, arg);
2726 gcc_unreachable ();
2728 fold_convert_exit:
2729 tem = protected_set_expr_location_unshare (tem, loc);
2730 return tem;
2733 /* Return false if expr can be assumed not to be an lvalue, true
2734 otherwise. */
2736 static bool
2737 maybe_lvalue_p (const_tree x)
2739 /* We only need to wrap lvalue tree codes. */
2740 switch (TREE_CODE (x))
2742 case VAR_DECL:
2743 case PARM_DECL:
2744 case RESULT_DECL:
2745 case LABEL_DECL:
2746 case FUNCTION_DECL:
2747 case SSA_NAME:
2748 case COMPOUND_LITERAL_EXPR:
2750 case COMPONENT_REF:
2751 case MEM_REF:
2752 case INDIRECT_REF:
2753 case ARRAY_REF:
2754 case ARRAY_RANGE_REF:
2755 case BIT_FIELD_REF:
2756 case OBJ_TYPE_REF:
2758 case REALPART_EXPR:
2759 case IMAGPART_EXPR:
2760 case PREINCREMENT_EXPR:
2761 case PREDECREMENT_EXPR:
2762 case SAVE_EXPR:
2763 case TRY_CATCH_EXPR:
2764 case WITH_CLEANUP_EXPR:
2765 case COMPOUND_EXPR:
2766 case MODIFY_EXPR:
2767 case TARGET_EXPR:
2768 case COND_EXPR:
2769 case BIND_EXPR:
2770 case VIEW_CONVERT_EXPR:
2771 break;
2773 default:
2774 /* Assume the worst for front-end tree codes. */
2775 if ((int)TREE_CODE (x) >= NUM_TREE_CODES)
2776 break;
2777 return false;
2780 return true;
2783 /* Return an expr equal to X but certainly not valid as an lvalue. */
2785 tree
2786 non_lvalue_loc (location_t loc, tree x)
2788 /* While we are in GIMPLE, NON_LVALUE_EXPR doesn't mean anything to
2789 us. */
2790 if (in_gimple_form)
2791 return x;
2793 if (! maybe_lvalue_p (x))
2794 return x;
2795 return build1_loc (loc, NON_LVALUE_EXPR, TREE_TYPE (x), x);
2798 /* Given a tree comparison code, return the code that is the logical inverse.
2799 It is generally not safe to do this for floating-point comparisons, except
2800 for EQ_EXPR, NE_EXPR, ORDERED_EXPR and UNORDERED_EXPR, so we return
2801 ERROR_MARK in this case. */
2803 enum tree_code
2804 invert_tree_comparison (enum tree_code code, bool honor_nans)
2806 if (honor_nans && flag_trapping_math && code != EQ_EXPR && code != NE_EXPR
2807 && code != ORDERED_EXPR && code != UNORDERED_EXPR)
2808 return ERROR_MARK;
2810 switch (code)
2812 case EQ_EXPR:
2813 return NE_EXPR;
2814 case NE_EXPR:
2815 return EQ_EXPR;
2816 case GT_EXPR:
2817 return honor_nans ? UNLE_EXPR : LE_EXPR;
2818 case GE_EXPR:
2819 return honor_nans ? UNLT_EXPR : LT_EXPR;
2820 case LT_EXPR:
2821 return honor_nans ? UNGE_EXPR : GE_EXPR;
2822 case LE_EXPR:
2823 return honor_nans ? UNGT_EXPR : GT_EXPR;
2824 case LTGT_EXPR:
2825 return UNEQ_EXPR;
2826 case UNEQ_EXPR:
2827 return LTGT_EXPR;
2828 case UNGT_EXPR:
2829 return LE_EXPR;
2830 case UNGE_EXPR:
2831 return LT_EXPR;
2832 case UNLT_EXPR:
2833 return GE_EXPR;
2834 case UNLE_EXPR:
2835 return GT_EXPR;
2836 case ORDERED_EXPR:
2837 return UNORDERED_EXPR;
2838 case UNORDERED_EXPR:
2839 return ORDERED_EXPR;
2840 default:
2841 gcc_unreachable ();
2845 /* Similar, but return the comparison that results if the operands are
2846 swapped. This is safe for floating-point. */
2848 enum tree_code
2849 swap_tree_comparison (enum tree_code code)
2851 switch (code)
2853 case EQ_EXPR:
2854 case NE_EXPR:
2855 case ORDERED_EXPR:
2856 case UNORDERED_EXPR:
2857 case LTGT_EXPR:
2858 case UNEQ_EXPR:
2859 return code;
2860 case GT_EXPR:
2861 return LT_EXPR;
2862 case GE_EXPR:
2863 return LE_EXPR;
2864 case LT_EXPR:
2865 return GT_EXPR;
2866 case LE_EXPR:
2867 return GE_EXPR;
2868 case UNGT_EXPR:
2869 return UNLT_EXPR;
2870 case UNGE_EXPR:
2871 return UNLE_EXPR;
2872 case UNLT_EXPR:
2873 return UNGT_EXPR;
2874 case UNLE_EXPR:
2875 return UNGE_EXPR;
2876 default:
2877 gcc_unreachable ();
2882 /* Convert a comparison tree code from an enum tree_code representation
2883 into a compcode bit-based encoding. This function is the inverse of
2884 compcode_to_comparison. */
2886 static enum comparison_code
2887 comparison_to_compcode (enum tree_code code)
2889 switch (code)
2891 case LT_EXPR:
2892 return COMPCODE_LT;
2893 case EQ_EXPR:
2894 return COMPCODE_EQ;
2895 case LE_EXPR:
2896 return COMPCODE_LE;
2897 case GT_EXPR:
2898 return COMPCODE_GT;
2899 case NE_EXPR:
2900 return COMPCODE_NE;
2901 case GE_EXPR:
2902 return COMPCODE_GE;
2903 case ORDERED_EXPR:
2904 return COMPCODE_ORD;
2905 case UNORDERED_EXPR:
2906 return COMPCODE_UNORD;
2907 case UNLT_EXPR:
2908 return COMPCODE_UNLT;
2909 case UNEQ_EXPR:
2910 return COMPCODE_UNEQ;
2911 case UNLE_EXPR:
2912 return COMPCODE_UNLE;
2913 case UNGT_EXPR:
2914 return COMPCODE_UNGT;
2915 case LTGT_EXPR:
2916 return COMPCODE_LTGT;
2917 case UNGE_EXPR:
2918 return COMPCODE_UNGE;
2919 default:
2920 gcc_unreachable ();
2924 /* Convert a compcode bit-based encoding of a comparison operator back
2925 to GCC's enum tree_code representation. This function is the
2926 inverse of comparison_to_compcode. */
2928 static enum tree_code
2929 compcode_to_comparison (enum comparison_code code)
2931 switch (code)
2933 case COMPCODE_LT:
2934 return LT_EXPR;
2935 case COMPCODE_EQ:
2936 return EQ_EXPR;
2937 case COMPCODE_LE:
2938 return LE_EXPR;
2939 case COMPCODE_GT:
2940 return GT_EXPR;
2941 case COMPCODE_NE:
2942 return NE_EXPR;
2943 case COMPCODE_GE:
2944 return GE_EXPR;
2945 case COMPCODE_ORD:
2946 return ORDERED_EXPR;
2947 case COMPCODE_UNORD:
2948 return UNORDERED_EXPR;
2949 case COMPCODE_UNLT:
2950 return UNLT_EXPR;
2951 case COMPCODE_UNEQ:
2952 return UNEQ_EXPR;
2953 case COMPCODE_UNLE:
2954 return UNLE_EXPR;
2955 case COMPCODE_UNGT:
2956 return UNGT_EXPR;
2957 case COMPCODE_LTGT:
2958 return LTGT_EXPR;
2959 case COMPCODE_UNGE:
2960 return UNGE_EXPR;
2961 default:
2962 gcc_unreachable ();
2966 /* Return true if COND1 tests the opposite condition of COND2. */
2968 bool
2969 inverse_conditions_p (const_tree cond1, const_tree cond2)
2971 return (COMPARISON_CLASS_P (cond1)
2972 && COMPARISON_CLASS_P (cond2)
2973 && (invert_tree_comparison
2974 (TREE_CODE (cond1),
2975 HONOR_NANS (TREE_OPERAND (cond1, 0))) == TREE_CODE (cond2))
2976 && operand_equal_p (TREE_OPERAND (cond1, 0),
2977 TREE_OPERAND (cond2, 0), 0)
2978 && operand_equal_p (TREE_OPERAND (cond1, 1),
2979 TREE_OPERAND (cond2, 1), 0));
2982 /* Return a tree for the comparison which is the combination of
2983 doing the AND or OR (depending on CODE) of the two operations LCODE
2984 and RCODE on the identical operands LL_ARG and LR_ARG. Take into account
2985 the possibility of trapping if the mode has NaNs, and return NULL_TREE
2986 if this makes the transformation invalid. */
2988 tree
2989 combine_comparisons (location_t loc,
2990 enum tree_code code, enum tree_code lcode,
2991 enum tree_code rcode, tree truth_type,
2992 tree ll_arg, tree lr_arg)
2994 bool honor_nans = HONOR_NANS (ll_arg);
2995 enum comparison_code lcompcode = comparison_to_compcode (lcode);
2996 enum comparison_code rcompcode = comparison_to_compcode (rcode);
2997 int compcode;
2999 switch (code)
3001 case TRUTH_AND_EXPR: case TRUTH_ANDIF_EXPR:
3002 compcode = lcompcode & rcompcode;
3003 break;
3005 case TRUTH_OR_EXPR: case TRUTH_ORIF_EXPR:
3006 compcode = lcompcode | rcompcode;
3007 break;
3009 default:
3010 return NULL_TREE;
3013 if (!honor_nans)
3015 /* Eliminate unordered comparisons, as well as LTGT and ORD
3016 which are not used unless the mode has NaNs. */
3017 compcode &= ~COMPCODE_UNORD;
3018 if (compcode == COMPCODE_LTGT)
3019 compcode = COMPCODE_NE;
3020 else if (compcode == COMPCODE_ORD)
3021 compcode = COMPCODE_TRUE;
3023 else if (flag_trapping_math)
3025 /* Check that the original operation and the optimized ones will trap
3026 under the same condition. */
3027 bool ltrap = (lcompcode & COMPCODE_UNORD) == 0
3028 && (lcompcode != COMPCODE_EQ)
3029 && (lcompcode != COMPCODE_ORD);
3030 bool rtrap = (rcompcode & COMPCODE_UNORD) == 0
3031 && (rcompcode != COMPCODE_EQ)
3032 && (rcompcode != COMPCODE_ORD);
3033 bool trap = (compcode & COMPCODE_UNORD) == 0
3034 && (compcode != COMPCODE_EQ)
3035 && (compcode != COMPCODE_ORD);
3037 /* In a short-circuited boolean expression the LHS might be
3038 such that the RHS, if evaluated, will never trap. For
3039 example, in ORD (x, y) && (x < y), we evaluate the RHS only
3040 if neither x nor y is NaN. (This is a mixed blessing: for
3041 example, the expression above will never trap, hence
3042 optimizing it to x < y would be invalid). */
3043 if ((code == TRUTH_ORIF_EXPR && (lcompcode & COMPCODE_UNORD))
3044 || (code == TRUTH_ANDIF_EXPR && !(lcompcode & COMPCODE_UNORD)))
3045 rtrap = false;
3047 /* If the comparison was short-circuited, and only the RHS
3048 trapped, we may now generate a spurious trap. */
3049 if (rtrap && !ltrap
3050 && (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR))
3051 return NULL_TREE;
3053 /* If we changed the conditions that cause a trap, we lose. */
3054 if ((ltrap || rtrap) != trap)
3055 return NULL_TREE;
3058 if (compcode == COMPCODE_TRUE)
3059 return constant_boolean_node (true, truth_type);
3060 else if (compcode == COMPCODE_FALSE)
3061 return constant_boolean_node (false, truth_type);
3062 else
3064 enum tree_code tcode;
3066 tcode = compcode_to_comparison ((enum comparison_code) compcode);
3067 return fold_build2_loc (loc, tcode, truth_type, ll_arg, lr_arg);
3071 /* Return nonzero if two operands (typically of the same tree node)
3072 are necessarily equal. FLAGS modifies behavior as follows:
3074 If OEP_ONLY_CONST is set, only return nonzero for constants.
3075 This function tests whether the operands are indistinguishable;
3076 it does not test whether they are equal using C's == operation.
3077 The distinction is important for IEEE floating point, because
3078 (1) -0.0 and 0.0 are distinguishable, but -0.0==0.0, and
3079 (2) two NaNs may be indistinguishable, but NaN!=NaN.
3081 If OEP_ONLY_CONST is unset, a VAR_DECL is considered equal to itself
3082 even though it may hold multiple values during a function.
3083 This is because a GCC tree node guarantees that nothing else is
3084 executed between the evaluation of its "operands" (which may often
3085 be evaluated in arbitrary order). Hence if the operands themselves
3086 don't side-effect, the VAR_DECLs, PARM_DECLs etc... must hold the
3087 same value in each operand/subexpression. Hence leaving OEP_ONLY_CONST
3088 unset means assuming isochronic (or instantaneous) tree equivalence.
3089 Unless comparing arbitrary expression trees, such as from different
3090 statements, this flag can usually be left unset.
3092 If OEP_PURE_SAME is set, then pure functions with identical arguments
3093 are considered the same. It is used when the caller has other ways
3094 to ensure that global memory is unchanged in between.
3096 If OEP_ADDRESS_OF is set, we are actually comparing addresses of objects,
3097 not values of expressions.
3099 If OEP_LEXICOGRAPHIC is set, then also handle expressions with side-effects
3100 such as MODIFY_EXPR, RETURN_EXPR, as well as STATEMENT_LISTs.
3102 If OEP_BITWISE is set, then require the values to be bitwise identical
3103 rather than simply numerically equal. Do not take advantage of things
3104 like math-related flags or undefined behavior; only return true for
3105 values that are provably bitwise identical in all circumstances.
3107 Unless OEP_MATCH_SIDE_EFFECTS is set, the function returns false on
3108 any operand with side effect. This is unnecesarily conservative in the
3109 case we know that arg0 and arg1 are in disjoint code paths (such as in
3110 ?: operator). In addition OEP_MATCH_SIDE_EFFECTS is used when comparing
3111 addresses with TREE_CONSTANT flag set so we know that &var == &var
3112 even if var is volatile. */
3114 bool
3115 operand_compare::operand_equal_p (const_tree arg0, const_tree arg1,
3116 unsigned int flags)
3118 bool r;
3119 if (verify_hash_value (arg0, arg1, flags, &r))
3120 return r;
3122 STRIP_ANY_LOCATION_WRAPPER (arg0);
3123 STRIP_ANY_LOCATION_WRAPPER (arg1);
3125 /* If either is ERROR_MARK, they aren't equal. */
3126 if (TREE_CODE (arg0) == ERROR_MARK || TREE_CODE (arg1) == ERROR_MARK
3127 || TREE_TYPE (arg0) == error_mark_node
3128 || TREE_TYPE (arg1) == error_mark_node)
3129 return false;
3131 /* Similar, if either does not have a type (like a template id),
3132 they aren't equal. */
3133 if (!TREE_TYPE (arg0) || !TREE_TYPE (arg1))
3134 return false;
3136 /* Bitwise identity makes no sense if the values have different layouts. */
3137 if ((flags & OEP_BITWISE)
3138 && !tree_nop_conversion_p (TREE_TYPE (arg0), TREE_TYPE (arg1)))
3139 return false;
3141 /* We cannot consider pointers to different address space equal. */
3142 if (POINTER_TYPE_P (TREE_TYPE (arg0))
3143 && POINTER_TYPE_P (TREE_TYPE (arg1))
3144 && (TYPE_ADDR_SPACE (TREE_TYPE (TREE_TYPE (arg0)))
3145 != TYPE_ADDR_SPACE (TREE_TYPE (TREE_TYPE (arg1)))))
3146 return false;
3148 /* Check equality of integer constants before bailing out due to
3149 precision differences. */
3150 if (TREE_CODE (arg0) == INTEGER_CST && TREE_CODE (arg1) == INTEGER_CST)
3152 /* Address of INTEGER_CST is not defined; check that we did not forget
3153 to drop the OEP_ADDRESS_OF flags. */
3154 gcc_checking_assert (!(flags & OEP_ADDRESS_OF));
3155 return tree_int_cst_equal (arg0, arg1);
3158 if (!(flags & OEP_ADDRESS_OF))
3160 /* If both types don't have the same signedness, then we can't consider
3161 them equal. We must check this before the STRIP_NOPS calls
3162 because they may change the signedness of the arguments. As pointers
3163 strictly don't have a signedness, require either two pointers or
3164 two non-pointers as well. */
3165 if (TYPE_UNSIGNED (TREE_TYPE (arg0)) != TYPE_UNSIGNED (TREE_TYPE (arg1))
3166 || POINTER_TYPE_P (TREE_TYPE (arg0))
3167 != POINTER_TYPE_P (TREE_TYPE (arg1)))
3168 return false;
3170 /* If both types don't have the same precision, then it is not safe
3171 to strip NOPs. */
3172 if (element_precision (TREE_TYPE (arg0))
3173 != element_precision (TREE_TYPE (arg1)))
3174 return false;
3176 STRIP_NOPS (arg0);
3177 STRIP_NOPS (arg1);
3179 #if 0
3180 /* FIXME: Fortran FE currently produce ADDR_EXPR of NOP_EXPR. Enable the
3181 sanity check once the issue is solved. */
3182 else
3183 /* Addresses of conversions and SSA_NAMEs (and many other things)
3184 are not defined. Check that we did not forget to drop the
3185 OEP_ADDRESS_OF/OEP_CONSTANT_ADDRESS_OF flags. */
3186 gcc_checking_assert (!CONVERT_EXPR_P (arg0) && !CONVERT_EXPR_P (arg1)
3187 && TREE_CODE (arg0) != SSA_NAME);
3188 #endif
3190 /* In case both args are comparisons but with different comparison
3191 code, try to swap the comparison operands of one arg to produce
3192 a match and compare that variant. */
3193 if (TREE_CODE (arg0) != TREE_CODE (arg1)
3194 && COMPARISON_CLASS_P (arg0)
3195 && COMPARISON_CLASS_P (arg1))
3197 enum tree_code swap_code = swap_tree_comparison (TREE_CODE (arg1));
3199 if (TREE_CODE (arg0) == swap_code)
3200 return operand_equal_p (TREE_OPERAND (arg0, 0),
3201 TREE_OPERAND (arg1, 1), flags)
3202 && operand_equal_p (TREE_OPERAND (arg0, 1),
3203 TREE_OPERAND (arg1, 0), flags);
3206 if (TREE_CODE (arg0) != TREE_CODE (arg1))
3208 /* NOP_EXPR and CONVERT_EXPR are considered equal. */
3209 if (CONVERT_EXPR_P (arg0) && CONVERT_EXPR_P (arg1))
3211 else if (flags & OEP_ADDRESS_OF)
3213 /* If we are interested in comparing addresses ignore
3214 MEM_REF wrappings of the base that can appear just for
3215 TBAA reasons. */
3216 if (TREE_CODE (arg0) == MEM_REF
3217 && DECL_P (arg1)
3218 && TREE_CODE (TREE_OPERAND (arg0, 0)) == ADDR_EXPR
3219 && TREE_OPERAND (TREE_OPERAND (arg0, 0), 0) == arg1
3220 && integer_zerop (TREE_OPERAND (arg0, 1)))
3221 return true;
3222 else if (TREE_CODE (arg1) == MEM_REF
3223 && DECL_P (arg0)
3224 && TREE_CODE (TREE_OPERAND (arg1, 0)) == ADDR_EXPR
3225 && TREE_OPERAND (TREE_OPERAND (arg1, 0), 0) == arg0
3226 && integer_zerop (TREE_OPERAND (arg1, 1)))
3227 return true;
3228 return false;
3230 else
3231 return false;
3234 /* When not checking adddresses, this is needed for conversions and for
3235 COMPONENT_REF. Might as well play it safe and always test this. */
3236 if (TREE_CODE (TREE_TYPE (arg0)) == ERROR_MARK
3237 || TREE_CODE (TREE_TYPE (arg1)) == ERROR_MARK
3238 || (TYPE_MODE (TREE_TYPE (arg0)) != TYPE_MODE (TREE_TYPE (arg1))
3239 && !(flags & OEP_ADDRESS_OF)))
3240 return false;
3242 /* If ARG0 and ARG1 are the same SAVE_EXPR, they are necessarily equal.
3243 We don't care about side effects in that case because the SAVE_EXPR
3244 takes care of that for us. In all other cases, two expressions are
3245 equal if they have no side effects. If we have two identical
3246 expressions with side effects that should be treated the same due
3247 to the only side effects being identical SAVE_EXPR's, that will
3248 be detected in the recursive calls below.
3249 If we are taking an invariant address of two identical objects
3250 they are necessarily equal as well. */
3251 if (arg0 == arg1 && ! (flags & OEP_ONLY_CONST)
3252 && (TREE_CODE (arg0) == SAVE_EXPR
3253 || (flags & OEP_MATCH_SIDE_EFFECTS)
3254 || (! TREE_SIDE_EFFECTS (arg0) && ! TREE_SIDE_EFFECTS (arg1))))
3255 return true;
3257 /* Next handle constant cases, those for which we can return 1 even
3258 if ONLY_CONST is set. */
3259 if (TREE_CONSTANT (arg0) && TREE_CONSTANT (arg1))
3260 switch (TREE_CODE (arg0))
3262 case INTEGER_CST:
3263 return tree_int_cst_equal (arg0, arg1);
3265 case FIXED_CST:
3266 return FIXED_VALUES_IDENTICAL (TREE_FIXED_CST (arg0),
3267 TREE_FIXED_CST (arg1));
3269 case REAL_CST:
3270 if (real_identical (&TREE_REAL_CST (arg0), &TREE_REAL_CST (arg1)))
3271 return true;
3273 if (!(flags & OEP_BITWISE) && !HONOR_SIGNED_ZEROS (arg0))
3275 /* If we do not distinguish between signed and unsigned zero,
3276 consider them equal. */
3277 if (real_zerop (arg0) && real_zerop (arg1))
3278 return true;
3280 return false;
3282 case VECTOR_CST:
3284 if (VECTOR_CST_LOG2_NPATTERNS (arg0)
3285 != VECTOR_CST_LOG2_NPATTERNS (arg1))
3286 return false;
3288 if (VECTOR_CST_NELTS_PER_PATTERN (arg0)
3289 != VECTOR_CST_NELTS_PER_PATTERN (arg1))
3290 return false;
3292 unsigned int count = vector_cst_encoded_nelts (arg0);
3293 for (unsigned int i = 0; i < count; ++i)
3294 if (!operand_equal_p (VECTOR_CST_ENCODED_ELT (arg0, i),
3295 VECTOR_CST_ENCODED_ELT (arg1, i), flags))
3296 return false;
3297 return true;
3300 case COMPLEX_CST:
3301 return (operand_equal_p (TREE_REALPART (arg0), TREE_REALPART (arg1),
3302 flags)
3303 && operand_equal_p (TREE_IMAGPART (arg0), TREE_IMAGPART (arg1),
3304 flags));
3306 case STRING_CST:
3307 return (TREE_STRING_LENGTH (arg0) == TREE_STRING_LENGTH (arg1)
3308 && ! memcmp (TREE_STRING_POINTER (arg0),
3309 TREE_STRING_POINTER (arg1),
3310 TREE_STRING_LENGTH (arg0)));
3312 case ADDR_EXPR:
3313 gcc_checking_assert (!(flags & OEP_ADDRESS_OF));
3314 return operand_equal_p (TREE_OPERAND (arg0, 0), TREE_OPERAND (arg1, 0),
3315 flags | OEP_ADDRESS_OF
3316 | OEP_MATCH_SIDE_EFFECTS);
3317 case CONSTRUCTOR:
3319 /* In GIMPLE empty constructors are allowed in initializers of
3320 aggregates. */
3321 if (!CONSTRUCTOR_NELTS (arg0) && !CONSTRUCTOR_NELTS (arg1))
3322 return true;
3324 /* See sem_variable::equals in ipa-icf for a similar approach. */
3325 tree typ0 = TREE_TYPE (arg0);
3326 tree typ1 = TREE_TYPE (arg1);
3328 if (TREE_CODE (typ0) != TREE_CODE (typ1))
3329 return false;
3330 else if (TREE_CODE (typ0) == ARRAY_TYPE)
3332 /* For arrays, check that the sizes all match. */
3333 const HOST_WIDE_INT siz0 = int_size_in_bytes (typ0);
3334 if (TYPE_MODE (typ0) != TYPE_MODE (typ1)
3335 || siz0 < 0
3336 || siz0 != int_size_in_bytes (typ1))
3337 return false;
3339 else if (!types_compatible_p (typ0, typ1))
3340 return false;
3342 vec<constructor_elt, va_gc> *v0 = CONSTRUCTOR_ELTS (arg0);
3343 vec<constructor_elt, va_gc> *v1 = CONSTRUCTOR_ELTS (arg1);
3344 if (vec_safe_length (v0) != vec_safe_length (v1))
3345 return false;
3347 /* Address of CONSTRUCTOR is defined in GENERIC to mean the value
3348 of the CONSTRUCTOR referenced indirectly. */
3349 flags &= ~OEP_ADDRESS_OF;
3351 for (unsigned idx = 0; idx < vec_safe_length (v0); ++idx)
3353 constructor_elt *c0 = &(*v0)[idx];
3354 constructor_elt *c1 = &(*v1)[idx];
3356 /* Check that the values are the same... */
3357 if (c0->value != c1->value
3358 && !operand_equal_p (c0->value, c1->value, flags))
3359 return false;
3361 /* ... and that they apply to the same field! */
3362 if (c0->index != c1->index
3363 && (TREE_CODE (typ0) == ARRAY_TYPE
3364 ? !operand_equal_p (c0->index, c1->index, flags)
3365 : !operand_equal_p (DECL_FIELD_OFFSET (c0->index),
3366 DECL_FIELD_OFFSET (c1->index),
3367 flags)
3368 || !operand_equal_p (DECL_FIELD_BIT_OFFSET (c0->index),
3369 DECL_FIELD_BIT_OFFSET (c1->index),
3370 flags)))
3371 return false;
3374 return true;
3377 default:
3378 break;
3381 /* Don't handle more cases for OEP_BITWISE, since we can't guarantee that
3382 two instances of undefined behavior will give identical results. */
3383 if (flags & (OEP_ONLY_CONST | OEP_BITWISE))
3384 return false;
3386 /* Define macros to test an operand from arg0 and arg1 for equality and a
3387 variant that allows null and views null as being different from any
3388 non-null value. In the latter case, if either is null, the both
3389 must be; otherwise, do the normal comparison. */
3390 #define OP_SAME(N) operand_equal_p (TREE_OPERAND (arg0, N), \
3391 TREE_OPERAND (arg1, N), flags)
3393 #define OP_SAME_WITH_NULL(N) \
3394 ((!TREE_OPERAND (arg0, N) || !TREE_OPERAND (arg1, N)) \
3395 ? TREE_OPERAND (arg0, N) == TREE_OPERAND (arg1, N) : OP_SAME (N))
3397 switch (TREE_CODE_CLASS (TREE_CODE (arg0)))
3399 case tcc_unary:
3400 /* Two conversions are equal only if signedness and modes match. */
3401 switch (TREE_CODE (arg0))
3403 CASE_CONVERT:
3404 case FIX_TRUNC_EXPR:
3405 if (TYPE_UNSIGNED (TREE_TYPE (arg0))
3406 != TYPE_UNSIGNED (TREE_TYPE (arg1)))
3407 return false;
3408 break;
3409 default:
3410 break;
3413 return OP_SAME (0);
3416 case tcc_comparison:
3417 case tcc_binary:
3418 if (OP_SAME (0) && OP_SAME (1))
3419 return true;
3421 /* For commutative ops, allow the other order. */
3422 return (commutative_tree_code (TREE_CODE (arg0))
3423 && operand_equal_p (TREE_OPERAND (arg0, 0),
3424 TREE_OPERAND (arg1, 1), flags)
3425 && operand_equal_p (TREE_OPERAND (arg0, 1),
3426 TREE_OPERAND (arg1, 0), flags));
3428 case tcc_reference:
3429 /* If either of the pointer (or reference) expressions we are
3430 dereferencing contain a side effect, these cannot be equal,
3431 but their addresses can be. */
3432 if ((flags & OEP_MATCH_SIDE_EFFECTS) == 0
3433 && (TREE_SIDE_EFFECTS (arg0)
3434 || TREE_SIDE_EFFECTS (arg1)))
3435 return false;
3437 switch (TREE_CODE (arg0))
3439 case INDIRECT_REF:
3440 if (!(flags & OEP_ADDRESS_OF))
3442 if (TYPE_ALIGN (TREE_TYPE (arg0))
3443 != TYPE_ALIGN (TREE_TYPE (arg1)))
3444 return false;
3445 /* Verify that the access types are compatible. */
3446 if (TYPE_MAIN_VARIANT (TREE_TYPE (arg0))
3447 != TYPE_MAIN_VARIANT (TREE_TYPE (arg1)))
3448 return false;
3450 flags &= ~OEP_ADDRESS_OF;
3451 return OP_SAME (0);
3453 case IMAGPART_EXPR:
3454 /* Require the same offset. */
3455 if (!operand_equal_p (TYPE_SIZE (TREE_TYPE (arg0)),
3456 TYPE_SIZE (TREE_TYPE (arg1)),
3457 flags & ~OEP_ADDRESS_OF))
3458 return false;
3460 /* Fallthru. */
3461 case REALPART_EXPR:
3462 case VIEW_CONVERT_EXPR:
3463 return OP_SAME (0);
3465 case TARGET_MEM_REF:
3466 case MEM_REF:
3467 if (!(flags & OEP_ADDRESS_OF))
3469 /* Require equal access sizes */
3470 if (TYPE_SIZE (TREE_TYPE (arg0)) != TYPE_SIZE (TREE_TYPE (arg1))
3471 && (!TYPE_SIZE (TREE_TYPE (arg0))
3472 || !TYPE_SIZE (TREE_TYPE (arg1))
3473 || !operand_equal_p (TYPE_SIZE (TREE_TYPE (arg0)),
3474 TYPE_SIZE (TREE_TYPE (arg1)),
3475 flags)))
3476 return false;
3477 /* Verify that access happens in similar types. */
3478 if (!types_compatible_p (TREE_TYPE (arg0), TREE_TYPE (arg1)))
3479 return false;
3480 /* Verify that accesses are TBAA compatible. */
3481 if (!alias_ptr_types_compatible_p
3482 (TREE_TYPE (TREE_OPERAND (arg0, 1)),
3483 TREE_TYPE (TREE_OPERAND (arg1, 1)))
3484 || (MR_DEPENDENCE_CLIQUE (arg0)
3485 != MR_DEPENDENCE_CLIQUE (arg1))
3486 || (MR_DEPENDENCE_BASE (arg0)
3487 != MR_DEPENDENCE_BASE (arg1)))
3488 return false;
3489 /* Verify that alignment is compatible. */
3490 if (TYPE_ALIGN (TREE_TYPE (arg0))
3491 != TYPE_ALIGN (TREE_TYPE (arg1)))
3492 return false;
3494 flags &= ~OEP_ADDRESS_OF;
3495 return (OP_SAME (0) && OP_SAME (1)
3496 /* TARGET_MEM_REF require equal extra operands. */
3497 && (TREE_CODE (arg0) != TARGET_MEM_REF
3498 || (OP_SAME_WITH_NULL (2)
3499 && OP_SAME_WITH_NULL (3)
3500 && OP_SAME_WITH_NULL (4))));
3502 case ARRAY_REF:
3503 case ARRAY_RANGE_REF:
3504 if (!OP_SAME (0))
3505 return false;
3506 flags &= ~OEP_ADDRESS_OF;
3507 /* Compare the array index by value if it is constant first as we
3508 may have different types but same value here. */
3509 return ((tree_int_cst_equal (TREE_OPERAND (arg0, 1),
3510 TREE_OPERAND (arg1, 1))
3511 || OP_SAME (1))
3512 && OP_SAME_WITH_NULL (2)
3513 && OP_SAME_WITH_NULL (3)
3514 /* Compare low bound and element size as with OEP_ADDRESS_OF
3515 we have to account for the offset of the ref. */
3516 && (TREE_TYPE (TREE_OPERAND (arg0, 0))
3517 == TREE_TYPE (TREE_OPERAND (arg1, 0))
3518 || (operand_equal_p (array_ref_low_bound
3519 (CONST_CAST_TREE (arg0)),
3520 array_ref_low_bound
3521 (CONST_CAST_TREE (arg1)), flags)
3522 && operand_equal_p (array_ref_element_size
3523 (CONST_CAST_TREE (arg0)),
3524 array_ref_element_size
3525 (CONST_CAST_TREE (arg1)),
3526 flags))));
3528 case COMPONENT_REF:
3529 /* Handle operand 2 the same as for ARRAY_REF. Operand 0
3530 may be NULL when we're called to compare MEM_EXPRs. */
3531 if (!OP_SAME_WITH_NULL (0))
3532 return false;
3534 bool compare_address = flags & OEP_ADDRESS_OF;
3536 /* Most of time we only need to compare FIELD_DECLs for equality.
3537 However when determining address look into actual offsets.
3538 These may match for unions and unshared record types. */
3539 flags &= ~OEP_ADDRESS_OF;
3540 if (!OP_SAME (1))
3542 if (compare_address
3543 && (flags & OEP_ADDRESS_OF_SAME_FIELD) == 0)
3545 tree field0 = TREE_OPERAND (arg0, 1);
3546 tree field1 = TREE_OPERAND (arg1, 1);
3548 /* Non-FIELD_DECL operands can appear in C++ templates. */
3549 if (TREE_CODE (field0) != FIELD_DECL
3550 || TREE_CODE (field1) != FIELD_DECL
3551 || !operand_equal_p (DECL_FIELD_OFFSET (field0),
3552 DECL_FIELD_OFFSET (field1), flags)
3553 || !operand_equal_p (DECL_FIELD_BIT_OFFSET (field0),
3554 DECL_FIELD_BIT_OFFSET (field1),
3555 flags))
3556 return false;
3558 else
3559 return false;
3562 return OP_SAME_WITH_NULL (2);
3564 case BIT_FIELD_REF:
3565 if (!OP_SAME (0))
3566 return false;
3567 flags &= ~OEP_ADDRESS_OF;
3568 return OP_SAME (1) && OP_SAME (2);
3570 default:
3571 return false;
3574 case tcc_expression:
3575 switch (TREE_CODE (arg0))
3577 case ADDR_EXPR:
3578 /* Be sure we pass right ADDRESS_OF flag. */
3579 gcc_checking_assert (!(flags & OEP_ADDRESS_OF));
3580 return operand_equal_p (TREE_OPERAND (arg0, 0),
3581 TREE_OPERAND (arg1, 0),
3582 flags | OEP_ADDRESS_OF);
3584 case TRUTH_NOT_EXPR:
3585 return OP_SAME (0);
3587 case TRUTH_ANDIF_EXPR:
3588 case TRUTH_ORIF_EXPR:
3589 return OP_SAME (0) && OP_SAME (1);
3591 case WIDEN_MULT_PLUS_EXPR:
3592 case WIDEN_MULT_MINUS_EXPR:
3593 if (!OP_SAME (2))
3594 return false;
3595 /* The multiplcation operands are commutative. */
3596 /* FALLTHRU */
3598 case TRUTH_AND_EXPR:
3599 case TRUTH_OR_EXPR:
3600 case TRUTH_XOR_EXPR:
3601 if (OP_SAME (0) && OP_SAME (1))
3602 return true;
3604 /* Otherwise take into account this is a commutative operation. */
3605 return (operand_equal_p (TREE_OPERAND (arg0, 0),
3606 TREE_OPERAND (arg1, 1), flags)
3607 && operand_equal_p (TREE_OPERAND (arg0, 1),
3608 TREE_OPERAND (arg1, 0), flags));
3610 case COND_EXPR:
3611 if (! OP_SAME (1) || ! OP_SAME_WITH_NULL (2))
3612 return false;
3613 flags &= ~OEP_ADDRESS_OF;
3614 return OP_SAME (0);
3616 case BIT_INSERT_EXPR:
3617 /* BIT_INSERT_EXPR has an implict operand as the type precision
3618 of op1. Need to check to make sure they are the same. */
3619 if (TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
3620 && TREE_CODE (TREE_OPERAND (arg1, 1)) == INTEGER_CST
3621 && TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (arg0, 1)))
3622 != TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (arg1, 1))))
3623 return false;
3624 /* FALLTHRU */
3626 case VEC_COND_EXPR:
3627 case DOT_PROD_EXPR:
3628 return OP_SAME (0) && OP_SAME (1) && OP_SAME (2);
3630 case MODIFY_EXPR:
3631 case INIT_EXPR:
3632 case COMPOUND_EXPR:
3633 case PREDECREMENT_EXPR:
3634 case PREINCREMENT_EXPR:
3635 case POSTDECREMENT_EXPR:
3636 case POSTINCREMENT_EXPR:
3637 if (flags & OEP_LEXICOGRAPHIC)
3638 return OP_SAME (0) && OP_SAME (1);
3639 return false;
3641 case CLEANUP_POINT_EXPR:
3642 case EXPR_STMT:
3643 case SAVE_EXPR:
3644 if (flags & OEP_LEXICOGRAPHIC)
3645 return OP_SAME (0);
3646 return false;
3648 case OBJ_TYPE_REF:
3649 /* Virtual table reference. */
3650 if (!operand_equal_p (OBJ_TYPE_REF_EXPR (arg0),
3651 OBJ_TYPE_REF_EXPR (arg1), flags))
3652 return false;
3653 flags &= ~OEP_ADDRESS_OF;
3654 if (tree_to_uhwi (OBJ_TYPE_REF_TOKEN (arg0))
3655 != tree_to_uhwi (OBJ_TYPE_REF_TOKEN (arg1)))
3656 return false;
3657 if (!operand_equal_p (OBJ_TYPE_REF_OBJECT (arg0),
3658 OBJ_TYPE_REF_OBJECT (arg1), flags))
3659 return false;
3660 if (virtual_method_call_p (arg0))
3662 if (!virtual_method_call_p (arg1))
3663 return false;
3664 return types_same_for_odr (obj_type_ref_class (arg0),
3665 obj_type_ref_class (arg1));
3667 return false;
3669 default:
3670 return false;
3673 case tcc_vl_exp:
3674 switch (TREE_CODE (arg0))
3676 case CALL_EXPR:
3677 if ((CALL_EXPR_FN (arg0) == NULL_TREE)
3678 != (CALL_EXPR_FN (arg1) == NULL_TREE))
3679 /* If not both CALL_EXPRs are either internal or normal function
3680 functions, then they are not equal. */
3681 return false;
3682 else if (CALL_EXPR_FN (arg0) == NULL_TREE)
3684 /* If the CALL_EXPRs call different internal functions, then they
3685 are not equal. */
3686 if (CALL_EXPR_IFN (arg0) != CALL_EXPR_IFN (arg1))
3687 return false;
3689 else
3691 /* If the CALL_EXPRs call different functions, then they are not
3692 equal. */
3693 if (! operand_equal_p (CALL_EXPR_FN (arg0), CALL_EXPR_FN (arg1),
3694 flags))
3695 return false;
3698 /* FIXME: We could skip this test for OEP_MATCH_SIDE_EFFECTS. */
3700 unsigned int cef = call_expr_flags (arg0);
3701 if (flags & OEP_PURE_SAME)
3702 cef &= ECF_CONST | ECF_PURE;
3703 else
3704 cef &= ECF_CONST;
3705 if (!cef && !(flags & OEP_LEXICOGRAPHIC))
3706 return false;
3709 /* Now see if all the arguments are the same. */
3711 const_call_expr_arg_iterator iter0, iter1;
3712 const_tree a0, a1;
3713 for (a0 = first_const_call_expr_arg (arg0, &iter0),
3714 a1 = first_const_call_expr_arg (arg1, &iter1);
3715 a0 && a1;
3716 a0 = next_const_call_expr_arg (&iter0),
3717 a1 = next_const_call_expr_arg (&iter1))
3718 if (! operand_equal_p (a0, a1, flags))
3719 return false;
3721 /* If we get here and both argument lists are exhausted
3722 then the CALL_EXPRs are equal. */
3723 return ! (a0 || a1);
3725 default:
3726 return false;
3729 case tcc_declaration:
3730 /* Consider __builtin_sqrt equal to sqrt. */
3731 if (TREE_CODE (arg0) == FUNCTION_DECL)
3732 return (fndecl_built_in_p (arg0) && fndecl_built_in_p (arg1)
3733 && DECL_BUILT_IN_CLASS (arg0) == DECL_BUILT_IN_CLASS (arg1)
3734 && (DECL_UNCHECKED_FUNCTION_CODE (arg0)
3735 == DECL_UNCHECKED_FUNCTION_CODE (arg1)));
3737 if (DECL_P (arg0)
3738 && (flags & OEP_DECL_NAME)
3739 && (flags & OEP_LEXICOGRAPHIC))
3741 /* Consider decls with the same name equal. The caller needs
3742 to make sure they refer to the same entity (such as a function
3743 formal parameter). */
3744 tree a0name = DECL_NAME (arg0);
3745 tree a1name = DECL_NAME (arg1);
3746 const char *a0ns = a0name ? IDENTIFIER_POINTER (a0name) : NULL;
3747 const char *a1ns = a1name ? IDENTIFIER_POINTER (a1name) : NULL;
3748 return a0ns && a1ns && strcmp (a0ns, a1ns) == 0;
3750 return false;
3752 case tcc_exceptional:
3753 if (TREE_CODE (arg0) == CONSTRUCTOR)
3755 if (CONSTRUCTOR_NO_CLEARING (arg0) != CONSTRUCTOR_NO_CLEARING (arg1))
3756 return false;
3758 /* In GIMPLE constructors are used only to build vectors from
3759 elements. Individual elements in the constructor must be
3760 indexed in increasing order and form an initial sequence.
3762 We make no effort to compare nonconstant ones in GENERIC. */
3763 if (!VECTOR_TYPE_P (TREE_TYPE (arg0))
3764 || !VECTOR_TYPE_P (TREE_TYPE (arg1)))
3765 return false;
3767 /* Be sure that vectors constructed have the same representation.
3768 We only tested element precision and modes to match.
3769 Vectors may be BLKmode and thus also check that the number of
3770 parts match. */
3771 if (maybe_ne (TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0)),
3772 TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg1))))
3773 return false;
3775 vec<constructor_elt, va_gc> *v0 = CONSTRUCTOR_ELTS (arg0);
3776 vec<constructor_elt, va_gc> *v1 = CONSTRUCTOR_ELTS (arg1);
3777 unsigned int len = vec_safe_length (v0);
3779 if (len != vec_safe_length (v1))
3780 return false;
3782 for (unsigned int i = 0; i < len; i++)
3784 constructor_elt *c0 = &(*v0)[i];
3785 constructor_elt *c1 = &(*v1)[i];
3787 if (!operand_equal_p (c0->value, c1->value, flags)
3788 /* In GIMPLE the indexes can be either NULL or matching i.
3789 Double check this so we won't get false
3790 positives for GENERIC. */
3791 || (c0->index
3792 && (TREE_CODE (c0->index) != INTEGER_CST
3793 || compare_tree_int (c0->index, i)))
3794 || (c1->index
3795 && (TREE_CODE (c1->index) != INTEGER_CST
3796 || compare_tree_int (c1->index, i))))
3797 return false;
3799 return true;
3801 else if (TREE_CODE (arg0) == STATEMENT_LIST
3802 && (flags & OEP_LEXICOGRAPHIC))
3804 /* Compare the STATEMENT_LISTs. */
3805 tree_stmt_iterator tsi1, tsi2;
3806 tree body1 = CONST_CAST_TREE (arg0);
3807 tree body2 = CONST_CAST_TREE (arg1);
3808 for (tsi1 = tsi_start (body1), tsi2 = tsi_start (body2); ;
3809 tsi_next (&tsi1), tsi_next (&tsi2))
3811 /* The lists don't have the same number of statements. */
3812 if (tsi_end_p (tsi1) ^ tsi_end_p (tsi2))
3813 return false;
3814 if (tsi_end_p (tsi1) && tsi_end_p (tsi2))
3815 return true;
3816 if (!operand_equal_p (tsi_stmt (tsi1), tsi_stmt (tsi2),
3817 flags & (OEP_LEXICOGRAPHIC
3818 | OEP_NO_HASH_CHECK)))
3819 return false;
3822 return false;
3824 case tcc_statement:
3825 switch (TREE_CODE (arg0))
3827 case RETURN_EXPR:
3828 if (flags & OEP_LEXICOGRAPHIC)
3829 return OP_SAME_WITH_NULL (0);
3830 return false;
3831 case DEBUG_BEGIN_STMT:
3832 if (flags & OEP_LEXICOGRAPHIC)
3833 return true;
3834 return false;
3835 default:
3836 return false;
3839 default:
3840 return false;
3843 #undef OP_SAME
3844 #undef OP_SAME_WITH_NULL
3847 /* Generate a hash value for an expression. This can be used iteratively
3848 by passing a previous result as the HSTATE argument. */
3850 void
3851 operand_compare::hash_operand (const_tree t, inchash::hash &hstate,
3852 unsigned int flags)
3854 int i;
3855 enum tree_code code;
3856 enum tree_code_class tclass;
3858 if (t == NULL_TREE || t == error_mark_node)
3860 hstate.merge_hash (0);
3861 return;
3864 STRIP_ANY_LOCATION_WRAPPER (t);
3866 if (!(flags & OEP_ADDRESS_OF))
3867 STRIP_NOPS (t);
3869 code = TREE_CODE (t);
3871 switch (code)
3873 /* Alas, constants aren't shared, so we can't rely on pointer
3874 identity. */
3875 case VOID_CST:
3876 hstate.merge_hash (0);
3877 return;
3878 case INTEGER_CST:
3879 gcc_checking_assert (!(flags & OEP_ADDRESS_OF));
3880 for (i = 0; i < TREE_INT_CST_EXT_NUNITS (t); i++)
3881 hstate.add_hwi (TREE_INT_CST_ELT (t, i));
3882 return;
3883 case REAL_CST:
3885 unsigned int val2;
3886 if (!HONOR_SIGNED_ZEROS (t) && real_zerop (t))
3887 val2 = rvc_zero;
3888 else
3889 val2 = real_hash (TREE_REAL_CST_PTR (t));
3890 hstate.merge_hash (val2);
3891 return;
3893 case FIXED_CST:
3895 unsigned int val2 = fixed_hash (TREE_FIXED_CST_PTR (t));
3896 hstate.merge_hash (val2);
3897 return;
3899 case STRING_CST:
3900 hstate.add ((const void *) TREE_STRING_POINTER (t),
3901 TREE_STRING_LENGTH (t));
3902 return;
3903 case COMPLEX_CST:
3904 hash_operand (TREE_REALPART (t), hstate, flags);
3905 hash_operand (TREE_IMAGPART (t), hstate, flags);
3906 return;
3907 case VECTOR_CST:
3909 hstate.add_int (VECTOR_CST_NPATTERNS (t));
3910 hstate.add_int (VECTOR_CST_NELTS_PER_PATTERN (t));
3911 unsigned int count = vector_cst_encoded_nelts (t);
3912 for (unsigned int i = 0; i < count; ++i)
3913 hash_operand (VECTOR_CST_ENCODED_ELT (t, i), hstate, flags);
3914 return;
3916 case SSA_NAME:
3917 /* We can just compare by pointer. */
3918 hstate.add_hwi (SSA_NAME_VERSION (t));
3919 return;
3920 case PLACEHOLDER_EXPR:
3921 /* The node itself doesn't matter. */
3922 return;
3923 case BLOCK:
3924 case OMP_CLAUSE:
3925 /* Ignore. */
3926 return;
3927 case TREE_LIST:
3928 /* A list of expressions, for a CALL_EXPR or as the elements of a
3929 VECTOR_CST. */
3930 for (; t; t = TREE_CHAIN (t))
3931 hash_operand (TREE_VALUE (t), hstate, flags);
3932 return;
3933 case CONSTRUCTOR:
3935 unsigned HOST_WIDE_INT idx;
3936 tree field, value;
3937 flags &= ~OEP_ADDRESS_OF;
3938 hstate.add_int (CONSTRUCTOR_NO_CLEARING (t));
3939 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (t), idx, field, value)
3941 /* In GIMPLE the indexes can be either NULL or matching i. */
3942 if (field == NULL_TREE)
3943 field = bitsize_int (idx);
3944 if (TREE_CODE (field) == FIELD_DECL)
3946 hash_operand (DECL_FIELD_OFFSET (field), hstate, flags);
3947 hash_operand (DECL_FIELD_BIT_OFFSET (field), hstate, flags);
3949 else
3950 hash_operand (field, hstate, flags);
3951 hash_operand (value, hstate, flags);
3953 return;
3955 case STATEMENT_LIST:
3957 tree_stmt_iterator i;
3958 for (i = tsi_start (CONST_CAST_TREE (t));
3959 !tsi_end_p (i); tsi_next (&i))
3960 hash_operand (tsi_stmt (i), hstate, flags);
3961 return;
3963 case TREE_VEC:
3964 for (i = 0; i < TREE_VEC_LENGTH (t); ++i)
3965 hash_operand (TREE_VEC_ELT (t, i), hstate, flags);
3966 return;
3967 case IDENTIFIER_NODE:
3968 hstate.add_object (IDENTIFIER_HASH_VALUE (t));
3969 return;
3970 case FUNCTION_DECL:
3971 /* When referring to a built-in FUNCTION_DECL, use the __builtin__ form.
3972 Otherwise nodes that compare equal according to operand_equal_p might
3973 get different hash codes. However, don't do this for machine specific
3974 or front end builtins, since the function code is overloaded in those
3975 cases. */
3976 if (DECL_BUILT_IN_CLASS (t) == BUILT_IN_NORMAL
3977 && builtin_decl_explicit_p (DECL_FUNCTION_CODE (t)))
3979 t = builtin_decl_explicit (DECL_FUNCTION_CODE (t));
3980 code = TREE_CODE (t);
3982 /* FALL THROUGH */
3983 default:
3984 if (POLY_INT_CST_P (t))
3986 for (unsigned int i = 0; i < NUM_POLY_INT_COEFFS; ++i)
3987 hstate.add_wide_int (wi::to_wide (POLY_INT_CST_COEFF (t, i)));
3988 return;
3990 tclass = TREE_CODE_CLASS (code);
3992 if (tclass == tcc_declaration)
3994 /* DECL's have a unique ID */
3995 hstate.add_hwi (DECL_UID (t));
3997 else if (tclass == tcc_comparison && !commutative_tree_code (code))
3999 /* For comparisons that can be swapped, use the lower
4000 tree code. */
4001 enum tree_code ccode = swap_tree_comparison (code);
4002 if (code < ccode)
4003 ccode = code;
4004 hstate.add_object (ccode);
4005 hash_operand (TREE_OPERAND (t, ccode != code), hstate, flags);
4006 hash_operand (TREE_OPERAND (t, ccode == code), hstate, flags);
4008 else if (CONVERT_EXPR_CODE_P (code))
4010 /* NOP_EXPR and CONVERT_EXPR are considered equal by
4011 operand_equal_p. */
4012 enum tree_code ccode = NOP_EXPR;
4013 hstate.add_object (ccode);
4015 /* Don't hash the type, that can lead to having nodes which
4016 compare equal according to operand_equal_p, but which
4017 have different hash codes. Make sure to include signedness
4018 in the hash computation. */
4019 hstate.add_int (TYPE_UNSIGNED (TREE_TYPE (t)));
4020 hash_operand (TREE_OPERAND (t, 0), hstate, flags);
4022 /* For OEP_ADDRESS_OF, hash MEM_EXPR[&decl, 0] the same as decl. */
4023 else if (code == MEM_REF
4024 && (flags & OEP_ADDRESS_OF) != 0
4025 && TREE_CODE (TREE_OPERAND (t, 0)) == ADDR_EXPR
4026 && DECL_P (TREE_OPERAND (TREE_OPERAND (t, 0), 0))
4027 && integer_zerop (TREE_OPERAND (t, 1)))
4028 hash_operand (TREE_OPERAND (TREE_OPERAND (t, 0), 0),
4029 hstate, flags);
4030 /* Don't ICE on FE specific trees, or their arguments etc.
4031 during operand_equal_p hash verification. */
4032 else if (!IS_EXPR_CODE_CLASS (tclass))
4033 gcc_assert (flags & OEP_HASH_CHECK);
4034 else
4036 unsigned int sflags = flags;
4038 hstate.add_object (code);
4040 switch (code)
4042 case ADDR_EXPR:
4043 gcc_checking_assert (!(flags & OEP_ADDRESS_OF));
4044 flags |= OEP_ADDRESS_OF;
4045 sflags = flags;
4046 break;
4048 case INDIRECT_REF:
4049 case MEM_REF:
4050 case TARGET_MEM_REF:
4051 flags &= ~OEP_ADDRESS_OF;
4052 sflags = flags;
4053 break;
4055 case COMPONENT_REF:
4056 if (sflags & OEP_ADDRESS_OF)
4058 hash_operand (TREE_OPERAND (t, 0), hstate, flags);
4059 hash_operand (DECL_FIELD_OFFSET (TREE_OPERAND (t, 1)),
4060 hstate, flags & ~OEP_ADDRESS_OF);
4061 hash_operand (DECL_FIELD_BIT_OFFSET (TREE_OPERAND (t, 1)),
4062 hstate, flags & ~OEP_ADDRESS_OF);
4063 return;
4065 break;
4066 case ARRAY_REF:
4067 case ARRAY_RANGE_REF:
4068 case BIT_FIELD_REF:
4069 sflags &= ~OEP_ADDRESS_OF;
4070 break;
4072 case COND_EXPR:
4073 flags &= ~OEP_ADDRESS_OF;
4074 break;
4076 case WIDEN_MULT_PLUS_EXPR:
4077 case WIDEN_MULT_MINUS_EXPR:
4079 /* The multiplication operands are commutative. */
4080 inchash::hash one, two;
4081 hash_operand (TREE_OPERAND (t, 0), one, flags);
4082 hash_operand (TREE_OPERAND (t, 1), two, flags);
4083 hstate.add_commutative (one, two);
4084 hash_operand (TREE_OPERAND (t, 2), two, flags);
4085 return;
4088 case CALL_EXPR:
4089 if (CALL_EXPR_FN (t) == NULL_TREE)
4090 hstate.add_int (CALL_EXPR_IFN (t));
4091 break;
4093 case TARGET_EXPR:
4094 /* For TARGET_EXPR, just hash on the TARGET_EXPR_SLOT.
4095 Usually different TARGET_EXPRs just should use
4096 different temporaries in their slots. */
4097 hash_operand (TARGET_EXPR_SLOT (t), hstate, flags);
4098 return;
4100 case OBJ_TYPE_REF:
4101 /* Virtual table reference. */
4102 inchash::add_expr (OBJ_TYPE_REF_EXPR (t), hstate, flags);
4103 flags &= ~OEP_ADDRESS_OF;
4104 inchash::add_expr (OBJ_TYPE_REF_TOKEN (t), hstate, flags);
4105 inchash::add_expr (OBJ_TYPE_REF_OBJECT (t), hstate, flags);
4106 if (!virtual_method_call_p (t))
4107 return;
4108 if (tree c = obj_type_ref_class (t))
4110 c = TYPE_NAME (TYPE_MAIN_VARIANT (c));
4111 /* We compute mangled names only when free_lang_data is run.
4112 In that case we can hash precisely. */
4113 if (TREE_CODE (c) == TYPE_DECL
4114 && DECL_ASSEMBLER_NAME_SET_P (c))
4115 hstate.add_object
4116 (IDENTIFIER_HASH_VALUE
4117 (DECL_ASSEMBLER_NAME (c)));
4119 return;
4120 default:
4121 break;
4124 /* Don't hash the type, that can lead to having nodes which
4125 compare equal according to operand_equal_p, but which
4126 have different hash codes. */
4127 if (code == NON_LVALUE_EXPR)
4129 /* Make sure to include signness in the hash computation. */
4130 hstate.add_int (TYPE_UNSIGNED (TREE_TYPE (t)));
4131 hash_operand (TREE_OPERAND (t, 0), hstate, flags);
4134 else if (commutative_tree_code (code))
4136 /* It's a commutative expression. We want to hash it the same
4137 however it appears. We do this by first hashing both operands
4138 and then rehashing based on the order of their independent
4139 hashes. */
4140 inchash::hash one, two;
4141 hash_operand (TREE_OPERAND (t, 0), one, flags);
4142 hash_operand (TREE_OPERAND (t, 1), two, flags);
4143 hstate.add_commutative (one, two);
4145 else
4146 for (i = TREE_OPERAND_LENGTH (t) - 1; i >= 0; --i)
4147 hash_operand (TREE_OPERAND (t, i), hstate,
4148 i == 0 ? flags : sflags);
4150 return;
4154 bool
4155 operand_compare::verify_hash_value (const_tree arg0, const_tree arg1,
4156 unsigned int flags, bool *ret)
4158 /* When checking and unless comparing DECL names, verify that if
4159 the outermost operand_equal_p call returns non-zero then ARG0
4160 and ARG1 have the same hash value. */
4161 if (flag_checking && !(flags & OEP_NO_HASH_CHECK))
4163 if (operand_equal_p (arg0, arg1, flags | OEP_NO_HASH_CHECK))
4165 if (arg0 != arg1 && !(flags & OEP_DECL_NAME))
4167 inchash::hash hstate0 (0), hstate1 (0);
4168 hash_operand (arg0, hstate0, flags | OEP_HASH_CHECK);
4169 hash_operand (arg1, hstate1, flags | OEP_HASH_CHECK);
4170 hashval_t h0 = hstate0.end ();
4171 hashval_t h1 = hstate1.end ();
4172 gcc_assert (h0 == h1);
4174 *ret = true;
4176 else
4177 *ret = false;
4179 return true;
4182 return false;
4186 static operand_compare default_compare_instance;
4188 /* Conveinece wrapper around operand_compare class because usually we do
4189 not need to play with the valueizer. */
4191 bool
4192 operand_equal_p (const_tree arg0, const_tree arg1, unsigned int flags)
4194 return default_compare_instance.operand_equal_p (arg0, arg1, flags);
4197 namespace inchash
4200 /* Generate a hash value for an expression. This can be used iteratively
4201 by passing a previous result as the HSTATE argument.
4203 This function is intended to produce the same hash for expressions which
4204 would compare equal using operand_equal_p. */
4205 void
4206 add_expr (const_tree t, inchash::hash &hstate, unsigned int flags)
4208 default_compare_instance.hash_operand (t, hstate, flags);
4213 /* Similar to operand_equal_p, but see if ARG0 might be a variant of ARG1
4214 with a different signedness or a narrower precision. */
4216 static bool
4217 operand_equal_for_comparison_p (tree arg0, tree arg1)
4219 if (operand_equal_p (arg0, arg1, 0))
4220 return true;
4222 if (! INTEGRAL_TYPE_P (TREE_TYPE (arg0))
4223 || ! INTEGRAL_TYPE_P (TREE_TYPE (arg1)))
4224 return false;
4226 /* Discard any conversions that don't change the modes of ARG0 and ARG1
4227 and see if the inner values are the same. This removes any
4228 signedness comparison, which doesn't matter here. */
4229 tree op0 = arg0;
4230 tree op1 = arg1;
4231 STRIP_NOPS (op0);
4232 STRIP_NOPS (op1);
4233 if (operand_equal_p (op0, op1, 0))
4234 return true;
4236 /* Discard a single widening conversion from ARG1 and see if the inner
4237 value is the same as ARG0. */
4238 if (CONVERT_EXPR_P (arg1)
4239 && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (arg1, 0)))
4240 && TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (arg1, 0)))
4241 < TYPE_PRECISION (TREE_TYPE (arg1))
4242 && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
4243 return true;
4245 return false;
4248 /* See if ARG is an expression that is either a comparison or is performing
4249 arithmetic on comparisons. The comparisons must only be comparing
4250 two different values, which will be stored in *CVAL1 and *CVAL2; if
4251 they are nonzero it means that some operands have already been found.
4252 No variables may be used anywhere else in the expression except in the
4253 comparisons.
4255 If this is true, return 1. Otherwise, return zero. */
4257 static bool
4258 twoval_comparison_p (tree arg, tree *cval1, tree *cval2)
4260 enum tree_code code = TREE_CODE (arg);
4261 enum tree_code_class tclass = TREE_CODE_CLASS (code);
4263 /* We can handle some of the tcc_expression cases here. */
4264 if (tclass == tcc_expression && code == TRUTH_NOT_EXPR)
4265 tclass = tcc_unary;
4266 else if (tclass == tcc_expression
4267 && (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR
4268 || code == COMPOUND_EXPR))
4269 tclass = tcc_binary;
4271 switch (tclass)
4273 case tcc_unary:
4274 return twoval_comparison_p (TREE_OPERAND (arg, 0), cval1, cval2);
4276 case tcc_binary:
4277 return (twoval_comparison_p (TREE_OPERAND (arg, 0), cval1, cval2)
4278 && twoval_comparison_p (TREE_OPERAND (arg, 1), cval1, cval2));
4280 case tcc_constant:
4281 return true;
4283 case tcc_expression:
4284 if (code == COND_EXPR)
4285 return (twoval_comparison_p (TREE_OPERAND (arg, 0), cval1, cval2)
4286 && twoval_comparison_p (TREE_OPERAND (arg, 1), cval1, cval2)
4287 && twoval_comparison_p (TREE_OPERAND (arg, 2), cval1, cval2));
4288 return false;
4290 case tcc_comparison:
4291 /* First see if we can handle the first operand, then the second. For
4292 the second operand, we know *CVAL1 can't be zero. It must be that
4293 one side of the comparison is each of the values; test for the
4294 case where this isn't true by failing if the two operands
4295 are the same. */
4297 if (operand_equal_p (TREE_OPERAND (arg, 0),
4298 TREE_OPERAND (arg, 1), 0))
4299 return false;
4301 if (*cval1 == 0)
4302 *cval1 = TREE_OPERAND (arg, 0);
4303 else if (operand_equal_p (*cval1, TREE_OPERAND (arg, 0), 0))
4305 else if (*cval2 == 0)
4306 *cval2 = TREE_OPERAND (arg, 0);
4307 else if (operand_equal_p (*cval2, TREE_OPERAND (arg, 0), 0))
4309 else
4310 return false;
4312 if (operand_equal_p (*cval1, TREE_OPERAND (arg, 1), 0))
4314 else if (*cval2 == 0)
4315 *cval2 = TREE_OPERAND (arg, 1);
4316 else if (operand_equal_p (*cval2, TREE_OPERAND (arg, 1), 0))
4318 else
4319 return false;
4321 return true;
4323 default:
4324 return false;
4328 /* ARG is a tree that is known to contain just arithmetic operations and
4329 comparisons. Evaluate the operations in the tree substituting NEW0 for
4330 any occurrence of OLD0 as an operand of a comparison and likewise for
4331 NEW1 and OLD1. */
4333 static tree
4334 eval_subst (location_t loc, tree arg, tree old0, tree new0,
4335 tree old1, tree new1)
4337 tree type = TREE_TYPE (arg);
4338 enum tree_code code = TREE_CODE (arg);
4339 enum tree_code_class tclass = TREE_CODE_CLASS (code);
4341 /* We can handle some of the tcc_expression cases here. */
4342 if (tclass == tcc_expression && code == TRUTH_NOT_EXPR)
4343 tclass = tcc_unary;
4344 else if (tclass == tcc_expression
4345 && (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR))
4346 tclass = tcc_binary;
4348 switch (tclass)
4350 case tcc_unary:
4351 return fold_build1_loc (loc, code, type,
4352 eval_subst (loc, TREE_OPERAND (arg, 0),
4353 old0, new0, old1, new1));
4355 case tcc_binary:
4356 return fold_build2_loc (loc, code, type,
4357 eval_subst (loc, TREE_OPERAND (arg, 0),
4358 old0, new0, old1, new1),
4359 eval_subst (loc, TREE_OPERAND (arg, 1),
4360 old0, new0, old1, new1));
4362 case tcc_expression:
4363 switch (code)
4365 case SAVE_EXPR:
4366 return eval_subst (loc, TREE_OPERAND (arg, 0), old0, new0,
4367 old1, new1);
4369 case COMPOUND_EXPR:
4370 return eval_subst (loc, TREE_OPERAND (arg, 1), old0, new0,
4371 old1, new1);
4373 case COND_EXPR:
4374 return fold_build3_loc (loc, code, type,
4375 eval_subst (loc, TREE_OPERAND (arg, 0),
4376 old0, new0, old1, new1),
4377 eval_subst (loc, TREE_OPERAND (arg, 1),
4378 old0, new0, old1, new1),
4379 eval_subst (loc, TREE_OPERAND (arg, 2),
4380 old0, new0, old1, new1));
4381 default:
4382 break;
4384 /* Fall through - ??? */
4386 case tcc_comparison:
4388 tree arg0 = TREE_OPERAND (arg, 0);
4389 tree arg1 = TREE_OPERAND (arg, 1);
4391 /* We need to check both for exact equality and tree equality. The
4392 former will be true if the operand has a side-effect. In that
4393 case, we know the operand occurred exactly once. */
4395 if (arg0 == old0 || operand_equal_p (arg0, old0, 0))
4396 arg0 = new0;
4397 else if (arg0 == old1 || operand_equal_p (arg0, old1, 0))
4398 arg0 = new1;
4400 if (arg1 == old0 || operand_equal_p (arg1, old0, 0))
4401 arg1 = new0;
4402 else if (arg1 == old1 || operand_equal_p (arg1, old1, 0))
4403 arg1 = new1;
4405 return fold_build2_loc (loc, code, type, arg0, arg1);
4408 default:
4409 return arg;
4413 /* Return a tree for the case when the result of an expression is RESULT
4414 converted to TYPE and OMITTED was previously an operand of the expression
4415 but is now not needed (e.g., we folded OMITTED * 0).
4417 If OMITTED has side effects, we must evaluate it. Otherwise, just do
4418 the conversion of RESULT to TYPE. */
4420 tree
4421 omit_one_operand_loc (location_t loc, tree type, tree result, tree omitted)
4423 tree t = fold_convert_loc (loc, type, result);
4425 /* If the resulting operand is an empty statement, just return the omitted
4426 statement casted to void. */
4427 if (IS_EMPTY_STMT (t) && TREE_SIDE_EFFECTS (omitted))
4428 return build1_loc (loc, NOP_EXPR, void_type_node,
4429 fold_ignored_result (omitted));
4431 if (TREE_SIDE_EFFECTS (omitted))
4432 return build2_loc (loc, COMPOUND_EXPR, type,
4433 fold_ignored_result (omitted), t);
4435 return non_lvalue_loc (loc, t);
4438 /* Return a tree for the case when the result of an expression is RESULT
4439 converted to TYPE and OMITTED1 and OMITTED2 were previously operands
4440 of the expression but are now not needed.
4442 If OMITTED1 or OMITTED2 has side effects, they must be evaluated.
4443 If both OMITTED1 and OMITTED2 have side effects, OMITTED1 is
4444 evaluated before OMITTED2. Otherwise, if neither has side effects,
4445 just do the conversion of RESULT to TYPE. */
4447 tree
4448 omit_two_operands_loc (location_t loc, tree type, tree result,
4449 tree omitted1, tree omitted2)
4451 tree t = fold_convert_loc (loc, type, result);
4453 if (TREE_SIDE_EFFECTS (omitted2))
4454 t = build2_loc (loc, COMPOUND_EXPR, type, omitted2, t);
4455 if (TREE_SIDE_EFFECTS (omitted1))
4456 t = build2_loc (loc, COMPOUND_EXPR, type, omitted1, t);
4458 return TREE_CODE (t) != COMPOUND_EXPR ? non_lvalue_loc (loc, t) : t;
4462 /* Return a simplified tree node for the truth-negation of ARG. This
4463 never alters ARG itself. We assume that ARG is an operation that
4464 returns a truth value (0 or 1).
4466 FIXME: one would think we would fold the result, but it causes
4467 problems with the dominator optimizer. */
4469 static tree
4470 fold_truth_not_expr (location_t loc, tree arg)
4472 tree type = TREE_TYPE (arg);
4473 enum tree_code code = TREE_CODE (arg);
4474 location_t loc1, loc2;
4476 /* If this is a comparison, we can simply invert it, except for
4477 floating-point non-equality comparisons, in which case we just
4478 enclose a TRUTH_NOT_EXPR around what we have. */
4480 if (TREE_CODE_CLASS (code) == tcc_comparison)
4482 tree op_type = TREE_TYPE (TREE_OPERAND (arg, 0));
4483 if (FLOAT_TYPE_P (op_type)
4484 && flag_trapping_math
4485 && code != ORDERED_EXPR && code != UNORDERED_EXPR
4486 && code != NE_EXPR && code != EQ_EXPR)
4487 return NULL_TREE;
4489 code = invert_tree_comparison (code, HONOR_NANS (op_type));
4490 if (code == ERROR_MARK)
4491 return NULL_TREE;
4493 tree ret = build2_loc (loc, code, type, TREE_OPERAND (arg, 0),
4494 TREE_OPERAND (arg, 1));
4495 copy_warning (ret, arg);
4496 return ret;
4499 switch (code)
4501 case INTEGER_CST:
4502 return constant_boolean_node (integer_zerop (arg), type);
4504 case TRUTH_AND_EXPR:
4505 loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
4506 loc2 = expr_location_or (TREE_OPERAND (arg, 1), loc);
4507 return build2_loc (loc, TRUTH_OR_EXPR, type,
4508 invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)),
4509 invert_truthvalue_loc (loc2, TREE_OPERAND (arg, 1)));
4511 case TRUTH_OR_EXPR:
4512 loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
4513 loc2 = expr_location_or (TREE_OPERAND (arg, 1), loc);
4514 return build2_loc (loc, TRUTH_AND_EXPR, type,
4515 invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)),
4516 invert_truthvalue_loc (loc2, TREE_OPERAND (arg, 1)));
4518 case TRUTH_XOR_EXPR:
4519 /* Here we can invert either operand. We invert the first operand
4520 unless the second operand is a TRUTH_NOT_EXPR in which case our
4521 result is the XOR of the first operand with the inside of the
4522 negation of the second operand. */
4524 if (TREE_CODE (TREE_OPERAND (arg, 1)) == TRUTH_NOT_EXPR)
4525 return build2_loc (loc, TRUTH_XOR_EXPR, type, TREE_OPERAND (arg, 0),
4526 TREE_OPERAND (TREE_OPERAND (arg, 1), 0));
4527 else
4528 return build2_loc (loc, TRUTH_XOR_EXPR, type,
4529 invert_truthvalue_loc (loc, TREE_OPERAND (arg, 0)),
4530 TREE_OPERAND (arg, 1));
4532 case TRUTH_ANDIF_EXPR:
4533 loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
4534 loc2 = expr_location_or (TREE_OPERAND (arg, 1), loc);
4535 return build2_loc (loc, TRUTH_ORIF_EXPR, type,
4536 invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)),
4537 invert_truthvalue_loc (loc2, TREE_OPERAND (arg, 1)));
4539 case TRUTH_ORIF_EXPR:
4540 loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
4541 loc2 = expr_location_or (TREE_OPERAND (arg, 1), loc);
4542 return build2_loc (loc, TRUTH_ANDIF_EXPR, type,
4543 invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)),
4544 invert_truthvalue_loc (loc2, TREE_OPERAND (arg, 1)));
4546 case TRUTH_NOT_EXPR:
4547 return TREE_OPERAND (arg, 0);
4549 case COND_EXPR:
4551 tree arg1 = TREE_OPERAND (arg, 1);
4552 tree arg2 = TREE_OPERAND (arg, 2);
4554 loc1 = expr_location_or (TREE_OPERAND (arg, 1), loc);
4555 loc2 = expr_location_or (TREE_OPERAND (arg, 2), loc);
4557 /* A COND_EXPR may have a throw as one operand, which
4558 then has void type. Just leave void operands
4559 as they are. */
4560 return build3_loc (loc, COND_EXPR, type, TREE_OPERAND (arg, 0),
4561 VOID_TYPE_P (TREE_TYPE (arg1))
4562 ? arg1 : invert_truthvalue_loc (loc1, arg1),
4563 VOID_TYPE_P (TREE_TYPE (arg2))
4564 ? arg2 : invert_truthvalue_loc (loc2, arg2));
4567 case COMPOUND_EXPR:
4568 loc1 = expr_location_or (TREE_OPERAND (arg, 1), loc);
4569 return build2_loc (loc, COMPOUND_EXPR, type,
4570 TREE_OPERAND (arg, 0),
4571 invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 1)));
4573 case NON_LVALUE_EXPR:
4574 loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
4575 return invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0));
4577 CASE_CONVERT:
4578 if (TREE_CODE (TREE_TYPE (arg)) == BOOLEAN_TYPE)
4579 return build1_loc (loc, TRUTH_NOT_EXPR, type, arg);
4581 /* fall through */
4583 case FLOAT_EXPR:
4584 loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
4585 return build1_loc (loc, TREE_CODE (arg), type,
4586 invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)));
4588 case BIT_AND_EXPR:
4589 if (!integer_onep (TREE_OPERAND (arg, 1)))
4590 return NULL_TREE;
4591 return build2_loc (loc, EQ_EXPR, type, arg, build_int_cst (type, 0));
4593 case SAVE_EXPR:
4594 return build1_loc (loc, TRUTH_NOT_EXPR, type, arg);
4596 case CLEANUP_POINT_EXPR:
4597 loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
4598 return build1_loc (loc, CLEANUP_POINT_EXPR, type,
4599 invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)));
4601 default:
4602 return NULL_TREE;
4606 /* Fold the truth-negation of ARG. This never alters ARG itself. We
4607 assume that ARG is an operation that returns a truth value (0 or 1
4608 for scalars, 0 or -1 for vectors). Return the folded expression if
4609 folding is successful. Otherwise, return NULL_TREE. */
4611 static tree
4612 fold_invert_truthvalue (location_t loc, tree arg)
4614 tree type = TREE_TYPE (arg);
4615 return fold_unary_loc (loc, VECTOR_TYPE_P (type)
4616 ? BIT_NOT_EXPR
4617 : TRUTH_NOT_EXPR,
4618 type, arg);
4621 /* Return a simplified tree node for the truth-negation of ARG. This
4622 never alters ARG itself. We assume that ARG is an operation that
4623 returns a truth value (0 or 1 for scalars, 0 or -1 for vectors). */
4625 tree
4626 invert_truthvalue_loc (location_t loc, tree arg)
4628 if (TREE_CODE (arg) == ERROR_MARK)
4629 return arg;
4631 tree type = TREE_TYPE (arg);
4632 return fold_build1_loc (loc, VECTOR_TYPE_P (type)
4633 ? BIT_NOT_EXPR
4634 : TRUTH_NOT_EXPR,
4635 type, arg);
4638 /* Return a BIT_FIELD_REF of type TYPE to refer to BITSIZE bits of INNER
4639 starting at BITPOS. The field is unsigned if UNSIGNEDP is nonzero
4640 and uses reverse storage order if REVERSEP is nonzero. ORIG_INNER
4641 is the original memory reference used to preserve the alias set of
4642 the access. */
4644 static tree
4645 make_bit_field_ref (location_t loc, tree inner, tree orig_inner, tree type,
4646 HOST_WIDE_INT bitsize, poly_int64 bitpos,
4647 int unsignedp, int reversep)
4649 tree result, bftype;
4651 /* Attempt not to lose the access path if possible. */
4652 if (TREE_CODE (orig_inner) == COMPONENT_REF)
4654 tree ninner = TREE_OPERAND (orig_inner, 0);
4655 machine_mode nmode;
4656 poly_int64 nbitsize, nbitpos;
4657 tree noffset;
4658 int nunsignedp, nreversep, nvolatilep = 0;
4659 tree base = get_inner_reference (ninner, &nbitsize, &nbitpos,
4660 &noffset, &nmode, &nunsignedp,
4661 &nreversep, &nvolatilep);
4662 if (base == inner
4663 && noffset == NULL_TREE
4664 && known_subrange_p (bitpos, bitsize, nbitpos, nbitsize)
4665 && !reversep
4666 && !nreversep
4667 && !nvolatilep)
4669 inner = ninner;
4670 bitpos -= nbitpos;
4674 alias_set_type iset = get_alias_set (orig_inner);
4675 if (iset == 0 && get_alias_set (inner) != iset)
4676 inner = fold_build2 (MEM_REF, TREE_TYPE (inner),
4677 build_fold_addr_expr (inner),
4678 build_int_cst (ptr_type_node, 0));
4680 if (known_eq (bitpos, 0) && !reversep)
4682 tree size = TYPE_SIZE (TREE_TYPE (inner));
4683 if ((INTEGRAL_TYPE_P (TREE_TYPE (inner))
4684 || POINTER_TYPE_P (TREE_TYPE (inner)))
4685 && tree_fits_shwi_p (size)
4686 && tree_to_shwi (size) == bitsize)
4687 return fold_convert_loc (loc, type, inner);
4690 bftype = type;
4691 if (TYPE_PRECISION (bftype) != bitsize
4692 || TYPE_UNSIGNED (bftype) == !unsignedp)
4693 bftype = build_nonstandard_integer_type (bitsize, 0);
4695 result = build3_loc (loc, BIT_FIELD_REF, bftype, inner,
4696 bitsize_int (bitsize), bitsize_int (bitpos));
4697 REF_REVERSE_STORAGE_ORDER (result) = reversep;
4699 if (bftype != type)
4700 result = fold_convert_loc (loc, type, result);
4702 return result;
4705 /* Optimize a bit-field compare.
4707 There are two cases: First is a compare against a constant and the
4708 second is a comparison of two items where the fields are at the same
4709 bit position relative to the start of a chunk (byte, halfword, word)
4710 large enough to contain it. In these cases we can avoid the shift
4711 implicit in bitfield extractions.
4713 For constants, we emit a compare of the shifted constant with the
4714 BIT_AND_EXPR of a mask and a byte, halfword, or word of the operand being
4715 compared. For two fields at the same position, we do the ANDs with the
4716 similar mask and compare the result of the ANDs.
4718 CODE is the comparison code, known to be either NE_EXPR or EQ_EXPR.
4719 COMPARE_TYPE is the type of the comparison, and LHS and RHS
4720 are the left and right operands of the comparison, respectively.
4722 If the optimization described above can be done, we return the resulting
4723 tree. Otherwise we return zero. */
4725 static tree
4726 optimize_bit_field_compare (location_t loc, enum tree_code code,
4727 tree compare_type, tree lhs, tree rhs)
4729 poly_int64 plbitpos, plbitsize, rbitpos, rbitsize;
4730 HOST_WIDE_INT lbitpos, lbitsize, nbitpos, nbitsize;
4731 tree type = TREE_TYPE (lhs);
4732 tree unsigned_type;
4733 int const_p = TREE_CODE (rhs) == INTEGER_CST;
4734 machine_mode lmode, rmode;
4735 scalar_int_mode nmode;
4736 int lunsignedp, runsignedp;
4737 int lreversep, rreversep;
4738 int lvolatilep = 0, rvolatilep = 0;
4739 tree linner, rinner = NULL_TREE;
4740 tree mask;
4741 tree offset;
4743 /* Get all the information about the extractions being done. If the bit size
4744 is the same as the size of the underlying object, we aren't doing an
4745 extraction at all and so can do nothing. We also don't want to
4746 do anything if the inner expression is a PLACEHOLDER_EXPR since we
4747 then will no longer be able to replace it. */
4748 linner = get_inner_reference (lhs, &plbitsize, &plbitpos, &offset, &lmode,
4749 &lunsignedp, &lreversep, &lvolatilep);
4750 if (linner == lhs
4751 || !known_size_p (plbitsize)
4752 || !plbitsize.is_constant (&lbitsize)
4753 || !plbitpos.is_constant (&lbitpos)
4754 || known_eq (lbitsize, GET_MODE_BITSIZE (lmode))
4755 || offset != 0
4756 || TREE_CODE (linner) == PLACEHOLDER_EXPR
4757 || lvolatilep)
4758 return 0;
4760 if (const_p)
4761 rreversep = lreversep;
4762 else
4764 /* If this is not a constant, we can only do something if bit positions,
4765 sizes, signedness and storage order are the same. */
4766 rinner
4767 = get_inner_reference (rhs, &rbitsize, &rbitpos, &offset, &rmode,
4768 &runsignedp, &rreversep, &rvolatilep);
4770 if (rinner == rhs
4771 || maybe_ne (lbitpos, rbitpos)
4772 || maybe_ne (lbitsize, rbitsize)
4773 || lunsignedp != runsignedp
4774 || lreversep != rreversep
4775 || offset != 0
4776 || TREE_CODE (rinner) == PLACEHOLDER_EXPR
4777 || rvolatilep)
4778 return 0;
4781 /* Honor the C++ memory model and mimic what RTL expansion does. */
4782 poly_uint64 bitstart = 0;
4783 poly_uint64 bitend = 0;
4784 if (TREE_CODE (lhs) == COMPONENT_REF)
4786 get_bit_range (&bitstart, &bitend, lhs, &plbitpos, &offset);
4787 if (!plbitpos.is_constant (&lbitpos) || offset != NULL_TREE)
4788 return 0;
4791 /* See if we can find a mode to refer to this field. We should be able to,
4792 but fail if we can't. */
4793 if (!get_best_mode (lbitsize, lbitpos, bitstart, bitend,
4794 const_p ? TYPE_ALIGN (TREE_TYPE (linner))
4795 : MIN (TYPE_ALIGN (TREE_TYPE (linner)),
4796 TYPE_ALIGN (TREE_TYPE (rinner))),
4797 BITS_PER_WORD, false, &nmode))
4798 return 0;
4800 /* Set signed and unsigned types of the precision of this mode for the
4801 shifts below. */
4802 unsigned_type = lang_hooks.types.type_for_mode (nmode, 1);
4804 /* Compute the bit position and size for the new reference and our offset
4805 within it. If the new reference is the same size as the original, we
4806 won't optimize anything, so return zero. */
4807 nbitsize = GET_MODE_BITSIZE (nmode);
4808 nbitpos = lbitpos & ~ (nbitsize - 1);
4809 lbitpos -= nbitpos;
4810 if (nbitsize == lbitsize)
4811 return 0;
4813 if (lreversep ? !BYTES_BIG_ENDIAN : BYTES_BIG_ENDIAN)
4814 lbitpos = nbitsize - lbitsize - lbitpos;
4816 /* Make the mask to be used against the extracted field. */
4817 mask = build_int_cst_type (unsigned_type, -1);
4818 mask = const_binop (LSHIFT_EXPR, mask, size_int (nbitsize - lbitsize));
4819 mask = const_binop (RSHIFT_EXPR, mask,
4820 size_int (nbitsize - lbitsize - lbitpos));
4822 if (! const_p)
4824 if (nbitpos < 0)
4825 return 0;
4827 /* If not comparing with constant, just rework the comparison
4828 and return. */
4829 tree t1 = make_bit_field_ref (loc, linner, lhs, unsigned_type,
4830 nbitsize, nbitpos, 1, lreversep);
4831 t1 = fold_build2_loc (loc, BIT_AND_EXPR, unsigned_type, t1, mask);
4832 tree t2 = make_bit_field_ref (loc, rinner, rhs, unsigned_type,
4833 nbitsize, nbitpos, 1, rreversep);
4834 t2 = fold_build2_loc (loc, BIT_AND_EXPR, unsigned_type, t2, mask);
4835 return fold_build2_loc (loc, code, compare_type, t1, t2);
4838 /* Otherwise, we are handling the constant case. See if the constant is too
4839 big for the field. Warn and return a tree for 0 (false) if so. We do
4840 this not only for its own sake, but to avoid having to test for this
4841 error case below. If we didn't, we might generate wrong code.
4843 For unsigned fields, the constant shifted right by the field length should
4844 be all zero. For signed fields, the high-order bits should agree with
4845 the sign bit. */
4847 if (lunsignedp)
4849 if (wi::lrshift (wi::to_wide (rhs), lbitsize) != 0)
4851 warning (0, "comparison is always %d due to width of bit-field",
4852 code == NE_EXPR);
4853 return constant_boolean_node (code == NE_EXPR, compare_type);
4856 else
4858 wide_int tem = wi::arshift (wi::to_wide (rhs), lbitsize - 1);
4859 if (tem != 0 && tem != -1)
4861 warning (0, "comparison is always %d due to width of bit-field",
4862 code == NE_EXPR);
4863 return constant_boolean_node (code == NE_EXPR, compare_type);
4867 if (nbitpos < 0)
4868 return 0;
4870 /* Single-bit compares should always be against zero. */
4871 if (lbitsize == 1 && ! integer_zerop (rhs))
4873 code = code == EQ_EXPR ? NE_EXPR : EQ_EXPR;
4874 rhs = build_int_cst (type, 0);
4877 /* Make a new bitfield reference, shift the constant over the
4878 appropriate number of bits and mask it with the computed mask
4879 (in case this was a signed field). If we changed it, make a new one. */
4880 lhs = make_bit_field_ref (loc, linner, lhs, unsigned_type,
4881 nbitsize, nbitpos, 1, lreversep);
4883 rhs = const_binop (BIT_AND_EXPR,
4884 const_binop (LSHIFT_EXPR,
4885 fold_convert_loc (loc, unsigned_type, rhs),
4886 size_int (lbitpos)),
4887 mask);
4889 lhs = build2_loc (loc, code, compare_type,
4890 build2 (BIT_AND_EXPR, unsigned_type, lhs, mask), rhs);
4891 return lhs;
4894 /* Subroutine for fold_truth_andor_1: decode a field reference.
4896 If EXP is a comparison reference, we return the innermost reference.
4898 *PBITSIZE is set to the number of bits in the reference, *PBITPOS is
4899 set to the starting bit number.
4901 If the innermost field can be completely contained in a mode-sized
4902 unit, *PMODE is set to that mode. Otherwise, it is set to VOIDmode.
4904 *PVOLATILEP is set to 1 if the any expression encountered is volatile;
4905 otherwise it is not changed.
4907 *PUNSIGNEDP is set to the signedness of the field.
4909 *PREVERSEP is set to the storage order of the field.
4911 *PMASK is set to the mask used. This is either contained in a
4912 BIT_AND_EXPR or derived from the width of the field.
4914 *PAND_MASK is set to the mask found in a BIT_AND_EXPR, if any.
4916 Return 0 if this is not a component reference or is one that we can't
4917 do anything with. */
4919 static tree
4920 decode_field_reference (location_t loc, tree *exp_, HOST_WIDE_INT *pbitsize,
4921 HOST_WIDE_INT *pbitpos, machine_mode *pmode,
4922 int *punsignedp, int *preversep, int *pvolatilep,
4923 tree *pmask, tree *pand_mask)
4925 tree exp = *exp_;
4926 tree outer_type = 0;
4927 tree and_mask = 0;
4928 tree mask, inner, offset;
4929 tree unsigned_type;
4930 unsigned int precision;
4932 /* All the optimizations using this function assume integer fields.
4933 There are problems with FP fields since the type_for_size call
4934 below can fail for, e.g., XFmode. */
4935 if (! INTEGRAL_TYPE_P (TREE_TYPE (exp)))
4936 return NULL_TREE;
4938 /* We are interested in the bare arrangement of bits, so strip everything
4939 that doesn't affect the machine mode. However, record the type of the
4940 outermost expression if it may matter below. */
4941 if (CONVERT_EXPR_P (exp)
4942 || TREE_CODE (exp) == NON_LVALUE_EXPR)
4943 outer_type = TREE_TYPE (exp);
4944 STRIP_NOPS (exp);
4946 if (TREE_CODE (exp) == BIT_AND_EXPR)
4948 and_mask = TREE_OPERAND (exp, 1);
4949 exp = TREE_OPERAND (exp, 0);
4950 STRIP_NOPS (exp); STRIP_NOPS (and_mask);
4951 if (TREE_CODE (and_mask) != INTEGER_CST)
4952 return NULL_TREE;
4955 poly_int64 poly_bitsize, poly_bitpos;
4956 inner = get_inner_reference (exp, &poly_bitsize, &poly_bitpos, &offset,
4957 pmode, punsignedp, preversep, pvolatilep);
4958 if ((inner == exp && and_mask == 0)
4959 || !poly_bitsize.is_constant (pbitsize)
4960 || !poly_bitpos.is_constant (pbitpos)
4961 || *pbitsize < 0
4962 || offset != 0
4963 || TREE_CODE (inner) == PLACEHOLDER_EXPR
4964 /* Reject out-of-bound accesses (PR79731). */
4965 || (! AGGREGATE_TYPE_P (TREE_TYPE (inner))
4966 && compare_tree_int (TYPE_SIZE (TREE_TYPE (inner)),
4967 *pbitpos + *pbitsize) < 0))
4968 return NULL_TREE;
4970 unsigned_type = lang_hooks.types.type_for_size (*pbitsize, 1);
4971 if (unsigned_type == NULL_TREE)
4972 return NULL_TREE;
4974 *exp_ = exp;
4976 /* If the number of bits in the reference is the same as the bitsize of
4977 the outer type, then the outer type gives the signedness. Otherwise
4978 (in case of a small bitfield) the signedness is unchanged. */
4979 if (outer_type && *pbitsize == TYPE_PRECISION (outer_type))
4980 *punsignedp = TYPE_UNSIGNED (outer_type);
4982 /* Compute the mask to access the bitfield. */
4983 precision = TYPE_PRECISION (unsigned_type);
4985 mask = build_int_cst_type (unsigned_type, -1);
4987 mask = const_binop (LSHIFT_EXPR, mask, size_int (precision - *pbitsize));
4988 mask = const_binop (RSHIFT_EXPR, mask, size_int (precision - *pbitsize));
4990 /* Merge it with the mask we found in the BIT_AND_EXPR, if any. */
4991 if (and_mask != 0)
4992 mask = fold_build2_loc (loc, BIT_AND_EXPR, unsigned_type,
4993 fold_convert_loc (loc, unsigned_type, and_mask), mask);
4995 *pmask = mask;
4996 *pand_mask = and_mask;
4997 return inner;
5000 /* Return nonzero if MASK represents a mask of SIZE ones in the low-order
5001 bit positions and MASK is SIGNED. */
5003 static bool
5004 all_ones_mask_p (const_tree mask, unsigned int size)
5006 tree type = TREE_TYPE (mask);
5007 unsigned int precision = TYPE_PRECISION (type);
5009 /* If this function returns true when the type of the mask is
5010 UNSIGNED, then there will be errors. In particular see
5011 gcc.c-torture/execute/990326-1.c. There does not appear to be
5012 any documentation paper trail as to why this is so. But the pre
5013 wide-int worked with that restriction and it has been preserved
5014 here. */
5015 if (size > precision || TYPE_SIGN (type) == UNSIGNED)
5016 return false;
5018 return wi::mask (size, false, precision) == wi::to_wide (mask);
5021 /* Subroutine for fold: determine if VAL is the INTEGER_CONST that
5022 represents the sign bit of EXP's type. If EXP represents a sign
5023 or zero extension, also test VAL against the unextended type.
5024 The return value is the (sub)expression whose sign bit is VAL,
5025 or NULL_TREE otherwise. */
5027 tree
5028 sign_bit_p (tree exp, const_tree val)
5030 int width;
5031 tree t;
5033 /* Tree EXP must have an integral type. */
5034 t = TREE_TYPE (exp);
5035 if (! INTEGRAL_TYPE_P (t))
5036 return NULL_TREE;
5038 /* Tree VAL must be an integer constant. */
5039 if (TREE_CODE (val) != INTEGER_CST
5040 || TREE_OVERFLOW (val))
5041 return NULL_TREE;
5043 width = TYPE_PRECISION (t);
5044 if (wi::only_sign_bit_p (wi::to_wide (val), width))
5045 return exp;
5047 /* Handle extension from a narrower type. */
5048 if (TREE_CODE (exp) == NOP_EXPR
5049 && TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (exp, 0))) < width)
5050 return sign_bit_p (TREE_OPERAND (exp, 0), val);
5052 return NULL_TREE;
5055 /* Subroutine for fold_truth_andor_1 and simple_condition_p: determine if an
5056 operand is simple enough to be evaluated unconditionally. */
5058 static bool
5059 simple_operand_p (const_tree exp)
5061 /* Strip any conversions that don't change the machine mode. */
5062 STRIP_NOPS (exp);
5064 return (CONSTANT_CLASS_P (exp)
5065 || TREE_CODE (exp) == SSA_NAME
5066 || (DECL_P (exp)
5067 && ! TREE_ADDRESSABLE (exp)
5068 && ! TREE_THIS_VOLATILE (exp)
5069 && ! DECL_NONLOCAL (exp)
5070 /* Don't regard global variables as simple. They may be
5071 allocated in ways unknown to the compiler (shared memory,
5072 #pragma weak, etc). */
5073 && ! TREE_PUBLIC (exp)
5074 && ! DECL_EXTERNAL (exp)
5075 /* Weakrefs are not safe to be read, since they can be NULL.
5076 They are !TREE_PUBLIC && !DECL_EXTERNAL but still
5077 have DECL_WEAK flag set. */
5078 && (! VAR_OR_FUNCTION_DECL_P (exp) || ! DECL_WEAK (exp))
5079 /* Loading a static variable is unduly expensive, but global
5080 registers aren't expensive. */
5081 && (! TREE_STATIC (exp) || DECL_REGISTER (exp))));
5084 /* Determine if an operand is simple enough to be evaluated unconditionally.
5085 In addition to simple_operand_p, we assume that comparisons, conversions,
5086 and logic-not operations are simple, if their operands are simple, too. */
5088 bool
5089 simple_condition_p (tree exp)
5091 enum tree_code code;
5093 if (TREE_SIDE_EFFECTS (exp) || generic_expr_could_trap_p (exp))
5094 return false;
5096 while (CONVERT_EXPR_P (exp))
5097 exp = TREE_OPERAND (exp, 0);
5099 code = TREE_CODE (exp);
5101 if (TREE_CODE_CLASS (code) == tcc_comparison)
5102 return (simple_operand_p (TREE_OPERAND (exp, 0))
5103 && simple_operand_p (TREE_OPERAND (exp, 1)));
5105 if (code == TRUTH_NOT_EXPR)
5106 return simple_condition_p (TREE_OPERAND (exp, 0));
5108 return simple_operand_p (exp);
5112 /* The following functions are subroutines to fold_range_test and allow it to
5113 try to change a logical combination of comparisons into a range test.
5115 For example, both
5116 X == 2 || X == 3 || X == 4 || X == 5
5118 X >= 2 && X <= 5
5119 are converted to
5120 (unsigned) (X - 2) <= 3
5122 We describe each set of comparisons as being either inside or outside
5123 a range, using a variable named like IN_P, and then describe the
5124 range with a lower and upper bound. If one of the bounds is omitted,
5125 it represents either the highest or lowest value of the type.
5127 In the comments below, we represent a range by two numbers in brackets
5128 preceded by a "+" to designate being inside that range, or a "-" to
5129 designate being outside that range, so the condition can be inverted by
5130 flipping the prefix. An omitted bound is represented by a "-". For
5131 example, "- [-, 10]" means being outside the range starting at the lowest
5132 possible value and ending at 10, in other words, being greater than 10.
5133 The range "+ [-, -]" is always true and hence the range "- [-, -]" is
5134 always false.
5136 We set up things so that the missing bounds are handled in a consistent
5137 manner so neither a missing bound nor "true" and "false" need to be
5138 handled using a special case. */
5140 /* Return the result of applying CODE to ARG0 and ARG1, but handle the case
5141 of ARG0 and/or ARG1 being omitted, meaning an unlimited range. UPPER0_P
5142 and UPPER1_P are nonzero if the respective argument is an upper bound
5143 and zero for a lower. TYPE, if nonzero, is the type of the result; it
5144 must be specified for a comparison. ARG1 will be converted to ARG0's
5145 type if both are specified. */
5147 static tree
5148 range_binop (enum tree_code code, tree type, tree arg0, int upper0_p,
5149 tree arg1, int upper1_p)
5151 tree tem;
5152 int result;
5153 int sgn0, sgn1;
5155 /* If neither arg represents infinity, do the normal operation.
5156 Else, if not a comparison, return infinity. Else handle the special
5157 comparison rules. Note that most of the cases below won't occur, but
5158 are handled for consistency. */
5160 if (arg0 != 0 && arg1 != 0)
5162 tem = fold_build2 (code, type != 0 ? type : TREE_TYPE (arg0),
5163 arg0, fold_convert (TREE_TYPE (arg0), arg1));
5164 STRIP_NOPS (tem);
5165 return TREE_CODE (tem) == INTEGER_CST ? tem : 0;
5168 if (TREE_CODE_CLASS (code) != tcc_comparison)
5169 return 0;
5171 /* Set SGN[01] to -1 if ARG[01] is a lower bound, 1 for upper, and 0
5172 for neither. In real maths, we cannot assume open ended ranges are
5173 the same. But, this is computer arithmetic, where numbers are finite.
5174 We can therefore make the transformation of any unbounded range with
5175 the value Z, Z being greater than any representable number. This permits
5176 us to treat unbounded ranges as equal. */
5177 sgn0 = arg0 != 0 ? 0 : (upper0_p ? 1 : -1);
5178 sgn1 = arg1 != 0 ? 0 : (upper1_p ? 1 : -1);
5179 switch (code)
5181 case EQ_EXPR:
5182 result = sgn0 == sgn1;
5183 break;
5184 case NE_EXPR:
5185 result = sgn0 != sgn1;
5186 break;
5187 case LT_EXPR:
5188 result = sgn0 < sgn1;
5189 break;
5190 case LE_EXPR:
5191 result = sgn0 <= sgn1;
5192 break;
5193 case GT_EXPR:
5194 result = sgn0 > sgn1;
5195 break;
5196 case GE_EXPR:
5197 result = sgn0 >= sgn1;
5198 break;
5199 default:
5200 gcc_unreachable ();
5203 return constant_boolean_node (result, type);
5206 /* Helper routine for make_range. Perform one step for it, return
5207 new expression if the loop should continue or NULL_TREE if it should
5208 stop. */
5210 tree
5211 make_range_step (location_t loc, enum tree_code code, tree arg0, tree arg1,
5212 tree exp_type, tree *p_low, tree *p_high, int *p_in_p,
5213 bool *strict_overflow_p)
5215 tree arg0_type = TREE_TYPE (arg0);
5216 tree n_low, n_high, low = *p_low, high = *p_high;
5217 int in_p = *p_in_p, n_in_p;
5219 switch (code)
5221 case TRUTH_NOT_EXPR:
5222 /* We can only do something if the range is testing for zero. */
5223 if (low == NULL_TREE || high == NULL_TREE
5224 || ! integer_zerop (low) || ! integer_zerop (high))
5225 return NULL_TREE;
5226 *p_in_p = ! in_p;
5227 return arg0;
5229 case EQ_EXPR: case NE_EXPR:
5230 case LT_EXPR: case LE_EXPR: case GE_EXPR: case GT_EXPR:
5231 /* We can only do something if the range is testing for zero
5232 and if the second operand is an integer constant. Note that
5233 saying something is "in" the range we make is done by
5234 complementing IN_P since it will set in the initial case of
5235 being not equal to zero; "out" is leaving it alone. */
5236 if (low == NULL_TREE || high == NULL_TREE
5237 || ! integer_zerop (low) || ! integer_zerop (high)
5238 || TREE_CODE (arg1) != INTEGER_CST)
5239 return NULL_TREE;
5241 switch (code)
5243 case NE_EXPR: /* - [c, c] */
5244 low = high = arg1;
5245 break;
5246 case EQ_EXPR: /* + [c, c] */
5247 in_p = ! in_p, low = high = arg1;
5248 break;
5249 case GT_EXPR: /* - [-, c] */
5250 low = 0, high = arg1;
5251 break;
5252 case GE_EXPR: /* + [c, -] */
5253 in_p = ! in_p, low = arg1, high = 0;
5254 break;
5255 case LT_EXPR: /* - [c, -] */
5256 low = arg1, high = 0;
5257 break;
5258 case LE_EXPR: /* + [-, c] */
5259 in_p = ! in_p, low = 0, high = arg1;
5260 break;
5261 default:
5262 gcc_unreachable ();
5265 /* If this is an unsigned comparison, we also know that EXP is
5266 greater than or equal to zero. We base the range tests we make
5267 on that fact, so we record it here so we can parse existing
5268 range tests. We test arg0_type since often the return type
5269 of, e.g. EQ_EXPR, is boolean. */
5270 if (TYPE_UNSIGNED (arg0_type) && (low == 0 || high == 0))
5272 if (! merge_ranges (&n_in_p, &n_low, &n_high,
5273 in_p, low, high, 1,
5274 build_int_cst (arg0_type, 0),
5275 NULL_TREE))
5276 return NULL_TREE;
5278 in_p = n_in_p, low = n_low, high = n_high;
5280 /* If the high bound is missing, but we have a nonzero low
5281 bound, reverse the range so it goes from zero to the low bound
5282 minus 1. */
5283 if (high == 0 && low && ! integer_zerop (low))
5285 in_p = ! in_p;
5286 high = range_binop (MINUS_EXPR, NULL_TREE, low, 0,
5287 build_int_cst (TREE_TYPE (low), 1), 0);
5288 low = build_int_cst (arg0_type, 0);
5292 *p_low = low;
5293 *p_high = high;
5294 *p_in_p = in_p;
5295 return arg0;
5297 case NEGATE_EXPR:
5298 /* If flag_wrapv and ARG0_TYPE is signed, make sure
5299 low and high are non-NULL, then normalize will DTRT. */
5300 if (!TYPE_UNSIGNED (arg0_type)
5301 && !TYPE_OVERFLOW_UNDEFINED (arg0_type))
5303 if (low == NULL_TREE)
5304 low = TYPE_MIN_VALUE (arg0_type);
5305 if (high == NULL_TREE)
5306 high = TYPE_MAX_VALUE (arg0_type);
5309 /* (-x) IN [a,b] -> x in [-b, -a] */
5310 n_low = range_binop (MINUS_EXPR, exp_type,
5311 build_int_cst (exp_type, 0),
5312 0, high, 1);
5313 n_high = range_binop (MINUS_EXPR, exp_type,
5314 build_int_cst (exp_type, 0),
5315 0, low, 0);
5316 if (n_high != 0 && TREE_OVERFLOW (n_high))
5317 return NULL_TREE;
5318 goto normalize;
5320 case BIT_NOT_EXPR:
5321 /* ~ X -> -X - 1 */
5322 return build2_loc (loc, MINUS_EXPR, exp_type, negate_expr (arg0),
5323 build_int_cst (exp_type, 1));
5325 case PLUS_EXPR:
5326 case MINUS_EXPR:
5327 if (TREE_CODE (arg1) != INTEGER_CST)
5328 return NULL_TREE;
5330 /* If flag_wrapv and ARG0_TYPE is signed, then we cannot
5331 move a constant to the other side. */
5332 if (!TYPE_UNSIGNED (arg0_type)
5333 && !TYPE_OVERFLOW_UNDEFINED (arg0_type))
5334 return NULL_TREE;
5336 /* If EXP is signed, any overflow in the computation is undefined,
5337 so we don't worry about it so long as our computations on
5338 the bounds don't overflow. For unsigned, overflow is defined
5339 and this is exactly the right thing. */
5340 n_low = range_binop (code == MINUS_EXPR ? PLUS_EXPR : MINUS_EXPR,
5341 arg0_type, low, 0, arg1, 0);
5342 n_high = range_binop (code == MINUS_EXPR ? PLUS_EXPR : MINUS_EXPR,
5343 arg0_type, high, 1, arg1, 0);
5344 if ((n_low != 0 && TREE_OVERFLOW (n_low))
5345 || (n_high != 0 && TREE_OVERFLOW (n_high)))
5346 return NULL_TREE;
5348 if (TYPE_OVERFLOW_UNDEFINED (arg0_type))
5349 *strict_overflow_p = true;
5351 normalize:
5352 /* Check for an unsigned range which has wrapped around the maximum
5353 value thus making n_high < n_low, and normalize it. */
5354 if (n_low && n_high && tree_int_cst_lt (n_high, n_low))
5356 low = range_binop (PLUS_EXPR, arg0_type, n_high, 0,
5357 build_int_cst (TREE_TYPE (n_high), 1), 0);
5358 high = range_binop (MINUS_EXPR, arg0_type, n_low, 0,
5359 build_int_cst (TREE_TYPE (n_low), 1), 0);
5361 /* If the range is of the form +/- [ x+1, x ], we won't
5362 be able to normalize it. But then, it represents the
5363 whole range or the empty set, so make it
5364 +/- [ -, - ]. */
5365 if (tree_int_cst_equal (n_low, low)
5366 && tree_int_cst_equal (n_high, high))
5367 low = high = 0;
5368 else
5369 in_p = ! in_p;
5371 else
5372 low = n_low, high = n_high;
5374 *p_low = low;
5375 *p_high = high;
5376 *p_in_p = in_p;
5377 return arg0;
5379 CASE_CONVERT:
5380 case NON_LVALUE_EXPR:
5381 if (TYPE_PRECISION (arg0_type) > TYPE_PRECISION (exp_type))
5382 return NULL_TREE;
5384 if (! INTEGRAL_TYPE_P (arg0_type)
5385 || (low != 0 && ! int_fits_type_p (low, arg0_type))
5386 || (high != 0 && ! int_fits_type_p (high, arg0_type)))
5387 return NULL_TREE;
5389 n_low = low, n_high = high;
5391 if (n_low != 0)
5392 n_low = fold_convert_loc (loc, arg0_type, n_low);
5394 if (n_high != 0)
5395 n_high = fold_convert_loc (loc, arg0_type, n_high);
5397 /* If we're converting arg0 from an unsigned type, to exp,
5398 a signed type, we will be doing the comparison as unsigned.
5399 The tests above have already verified that LOW and HIGH
5400 are both positive.
5402 So we have to ensure that we will handle large unsigned
5403 values the same way that the current signed bounds treat
5404 negative values. */
5406 if (!TYPE_UNSIGNED (exp_type) && TYPE_UNSIGNED (arg0_type))
5408 tree high_positive;
5409 tree equiv_type;
5410 /* For fixed-point modes, we need to pass the saturating flag
5411 as the 2nd parameter. */
5412 if (ALL_FIXED_POINT_MODE_P (TYPE_MODE (arg0_type)))
5413 equiv_type
5414 = lang_hooks.types.type_for_mode (TYPE_MODE (arg0_type),
5415 TYPE_SATURATING (arg0_type));
5416 else if (TREE_CODE (arg0_type) == BITINT_TYPE)
5417 equiv_type = arg0_type;
5418 else
5419 equiv_type
5420 = lang_hooks.types.type_for_mode (TYPE_MODE (arg0_type), 1);
5422 /* A range without an upper bound is, naturally, unbounded.
5423 Since convert would have cropped a very large value, use
5424 the max value for the destination type. */
5425 high_positive
5426 = TYPE_MAX_VALUE (equiv_type) ? TYPE_MAX_VALUE (equiv_type)
5427 : TYPE_MAX_VALUE (arg0_type);
5429 if (TYPE_PRECISION (exp_type) == TYPE_PRECISION (arg0_type))
5430 high_positive = fold_build2_loc (loc, RSHIFT_EXPR, arg0_type,
5431 fold_convert_loc (loc, arg0_type,
5432 high_positive),
5433 build_int_cst (arg0_type, 1));
5435 /* If the low bound is specified, "and" the range with the
5436 range for which the original unsigned value will be
5437 positive. */
5438 if (low != 0)
5440 if (! merge_ranges (&n_in_p, &n_low, &n_high, 1, n_low, n_high,
5441 1, fold_convert_loc (loc, arg0_type,
5442 integer_zero_node),
5443 high_positive))
5444 return NULL_TREE;
5446 in_p = (n_in_p == in_p);
5448 else
5450 /* Otherwise, "or" the range with the range of the input
5451 that will be interpreted as negative. */
5452 if (! merge_ranges (&n_in_p, &n_low, &n_high, 0, n_low, n_high,
5453 1, fold_convert_loc (loc, arg0_type,
5454 integer_zero_node),
5455 high_positive))
5456 return NULL_TREE;
5458 in_p = (in_p != n_in_p);
5462 /* Otherwise, if we are converting arg0 from signed type, to exp,
5463 an unsigned type, we will do the comparison as signed. If
5464 high is non-NULL, we punt above if it doesn't fit in the signed
5465 type, so if we get through here, +[-, high] or +[low, high] are
5466 equivalent to +[-, n_high] or +[n_low, n_high]. Similarly,
5467 +[-, -] or -[-, -] are equivalent too. But if low is specified and
5468 high is not, the +[low, -] range is equivalent to union of
5469 +[n_low, -] and +[-, -1] ranges, so +[low, -] is equivalent to
5470 -[0, n_low-1] and similarly -[low, -] to +[0, n_low-1], except for
5471 low being 0, which should be treated as [-, -]. */
5472 else if (TYPE_UNSIGNED (exp_type)
5473 && !TYPE_UNSIGNED (arg0_type)
5474 && low
5475 && !high)
5477 if (integer_zerop (low))
5478 n_low = NULL_TREE;
5479 else
5481 n_high = fold_build2_loc (loc, PLUS_EXPR, arg0_type,
5482 n_low, build_int_cst (arg0_type, -1));
5483 n_low = build_zero_cst (arg0_type);
5484 in_p = !in_p;
5488 *p_low = n_low;
5489 *p_high = n_high;
5490 *p_in_p = in_p;
5491 return arg0;
5493 default:
5494 return NULL_TREE;
5498 /* Given EXP, a logical expression, set the range it is testing into
5499 variables denoted by PIN_P, PLOW, and PHIGH. Return the expression
5500 actually being tested. *PLOW and *PHIGH will be made of the same
5501 type as the returned expression. If EXP is not a comparison, we
5502 will most likely not be returning a useful value and range. Set
5503 *STRICT_OVERFLOW_P to true if the return value is only valid
5504 because signed overflow is undefined; otherwise, do not change
5505 *STRICT_OVERFLOW_P. */
5507 tree
5508 make_range (tree exp, int *pin_p, tree *plow, tree *phigh,
5509 bool *strict_overflow_p)
5511 enum tree_code code;
5512 tree arg0, arg1 = NULL_TREE;
5513 tree exp_type, nexp;
5514 int in_p;
5515 tree low, high;
5516 location_t loc = EXPR_LOCATION (exp);
5518 /* Start with simply saying "EXP != 0" and then look at the code of EXP
5519 and see if we can refine the range. Some of the cases below may not
5520 happen, but it doesn't seem worth worrying about this. We "continue"
5521 the outer loop when we've changed something; otherwise we "break"
5522 the switch, which will "break" the while. */
5524 in_p = 0;
5525 low = high = build_int_cst (TREE_TYPE (exp), 0);
5527 while (1)
5529 code = TREE_CODE (exp);
5530 exp_type = TREE_TYPE (exp);
5531 arg0 = NULL_TREE;
5533 if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (code)))
5535 if (TREE_OPERAND_LENGTH (exp) > 0)
5536 arg0 = TREE_OPERAND (exp, 0);
5537 if (TREE_CODE_CLASS (code) == tcc_binary
5538 || TREE_CODE_CLASS (code) == tcc_comparison
5539 || (TREE_CODE_CLASS (code) == tcc_expression
5540 && TREE_OPERAND_LENGTH (exp) > 1))
5541 arg1 = TREE_OPERAND (exp, 1);
5543 if (arg0 == NULL_TREE)
5544 break;
5546 nexp = make_range_step (loc, code, arg0, arg1, exp_type, &low,
5547 &high, &in_p, strict_overflow_p);
5548 if (nexp == NULL_TREE)
5549 break;
5550 exp = nexp;
5553 /* If EXP is a constant, we can evaluate whether this is true or false. */
5554 if (TREE_CODE (exp) == INTEGER_CST)
5556 in_p = in_p == (integer_onep (range_binop (GE_EXPR, integer_type_node,
5557 exp, 0, low, 0))
5558 && integer_onep (range_binop (LE_EXPR, integer_type_node,
5559 exp, 1, high, 1)));
5560 low = high = 0;
5561 exp = 0;
5564 *pin_p = in_p, *plow = low, *phigh = high;
5565 return exp;
5568 /* Returns TRUE if [LOW, HIGH] range check can be optimized to
5569 a bitwise check i.e. when
5570 LOW == 0xXX...X00...0
5571 HIGH == 0xXX...X11...1
5572 Return corresponding mask in MASK and stem in VALUE. */
5574 static bool
5575 maskable_range_p (const_tree low, const_tree high, tree type, tree *mask,
5576 tree *value)
5578 if (TREE_CODE (low) != INTEGER_CST
5579 || TREE_CODE (high) != INTEGER_CST)
5580 return false;
5582 unsigned prec = TYPE_PRECISION (type);
5583 wide_int lo = wi::to_wide (low, prec);
5584 wide_int hi = wi::to_wide (high, prec);
5586 wide_int end_mask = lo ^ hi;
5587 if ((end_mask & (end_mask + 1)) != 0
5588 || (lo & end_mask) != 0)
5589 return false;
5591 wide_int stem_mask = ~end_mask;
5592 wide_int stem = lo & stem_mask;
5593 if (stem != (hi & stem_mask))
5594 return false;
5596 *mask = wide_int_to_tree (type, stem_mask);
5597 *value = wide_int_to_tree (type, stem);
5599 return true;
5602 /* Helper routine for build_range_check and match.pd. Return the type to
5603 perform the check or NULL if it shouldn't be optimized. */
5605 tree
5606 range_check_type (tree etype)
5608 /* First make sure that arithmetics in this type is valid, then make sure
5609 that it wraps around. */
5610 if (TREE_CODE (etype) == ENUMERAL_TYPE || TREE_CODE (etype) == BOOLEAN_TYPE)
5611 etype = lang_hooks.types.type_for_size (TYPE_PRECISION (etype), 1);
5613 if (TREE_CODE (etype) == INTEGER_TYPE && !TYPE_UNSIGNED (etype))
5615 tree utype, minv, maxv;
5617 /* Check if (unsigned) INT_MAX + 1 == (unsigned) INT_MIN
5618 for the type in question, as we rely on this here. */
5619 utype = unsigned_type_for (etype);
5620 maxv = fold_convert (utype, TYPE_MAX_VALUE (etype));
5621 maxv = range_binop (PLUS_EXPR, NULL_TREE, maxv, 1,
5622 build_int_cst (TREE_TYPE (maxv), 1), 1);
5623 minv = fold_convert (utype, TYPE_MIN_VALUE (etype));
5625 if (integer_zerop (range_binop (NE_EXPR, integer_type_node,
5626 minv, 1, maxv, 1)))
5627 etype = utype;
5628 else
5629 return NULL_TREE;
5631 else if (POINTER_TYPE_P (etype)
5632 || TREE_CODE (etype) == OFFSET_TYPE
5633 /* Right now all BITINT_TYPEs satisfy
5634 (unsigned) max + 1 == (unsigned) min, so no need to verify
5635 that like for INTEGER_TYPEs. */
5636 || TREE_CODE (etype) == BITINT_TYPE)
5637 etype = unsigned_type_for (etype);
5638 return etype;
5641 /* Given a range, LOW, HIGH, and IN_P, an expression, EXP, and a result
5642 type, TYPE, return an expression to test if EXP is in (or out of, depending
5643 on IN_P) the range. Return 0 if the test couldn't be created. */
5645 tree
5646 build_range_check (location_t loc, tree type, tree exp, int in_p,
5647 tree low, tree high)
5649 tree etype = TREE_TYPE (exp), mask, value;
5651 /* Disable this optimization for function pointer expressions
5652 on targets that require function pointer canonicalization. */
5653 if (targetm.have_canonicalize_funcptr_for_compare ()
5654 && POINTER_TYPE_P (etype)
5655 && FUNC_OR_METHOD_TYPE_P (TREE_TYPE (etype)))
5656 return NULL_TREE;
5658 if (! in_p)
5660 value = build_range_check (loc, type, exp, 1, low, high);
5661 if (value != 0)
5662 return invert_truthvalue_loc (loc, value);
5664 return 0;
5667 if (low == 0 && high == 0)
5668 return omit_one_operand_loc (loc, type, build_int_cst (type, 1), exp);
5670 if (low == 0)
5671 return fold_build2_loc (loc, LE_EXPR, type, exp,
5672 fold_convert_loc (loc, etype, high));
5674 if (high == 0)
5675 return fold_build2_loc (loc, GE_EXPR, type, exp,
5676 fold_convert_loc (loc, etype, low));
5678 if (operand_equal_p (low, high, 0))
5679 return fold_build2_loc (loc, EQ_EXPR, type, exp,
5680 fold_convert_loc (loc, etype, low));
5682 if (TREE_CODE (exp) == BIT_AND_EXPR
5683 && maskable_range_p (low, high, etype, &mask, &value))
5684 return fold_build2_loc (loc, EQ_EXPR, type,
5685 fold_build2_loc (loc, BIT_AND_EXPR, etype,
5686 exp, mask),
5687 value);
5689 if (integer_zerop (low))
5691 if (! TYPE_UNSIGNED (etype))
5693 etype = unsigned_type_for (etype);
5694 high = fold_convert_loc (loc, etype, high);
5695 exp = fold_convert_loc (loc, etype, exp);
5697 return build_range_check (loc, type, exp, 1, 0, high);
5700 /* Optimize (c>=1) && (c<=127) into (signed char)c > 0. */
5701 if (integer_onep (low) && TREE_CODE (high) == INTEGER_CST)
5703 int prec = TYPE_PRECISION (etype);
5705 if (wi::mask <widest_int> (prec - 1, false) == wi::to_widest (high))
5707 if (TYPE_UNSIGNED (etype))
5709 tree signed_etype = signed_type_for (etype);
5710 if (TYPE_PRECISION (signed_etype) != TYPE_PRECISION (etype))
5711 etype
5712 = build_nonstandard_integer_type (TYPE_PRECISION (etype), 0);
5713 else
5714 etype = signed_etype;
5715 exp = fold_convert_loc (loc, etype, exp);
5717 return fold_build2_loc (loc, GT_EXPR, type, exp,
5718 build_int_cst (etype, 0));
5722 /* Optimize (c>=low) && (c<=high) into (c-low>=0) && (c-low<=high-low).
5723 This requires wrap-around arithmetics for the type of the expression. */
5724 etype = range_check_type (etype);
5725 if (etype == NULL_TREE)
5726 return NULL_TREE;
5728 high = fold_convert_loc (loc, etype, high);
5729 low = fold_convert_loc (loc, etype, low);
5730 exp = fold_convert_loc (loc, etype, exp);
5732 value = const_binop (MINUS_EXPR, high, low);
5734 if (value != 0 && !TREE_OVERFLOW (value))
5735 return build_range_check (loc, type,
5736 fold_build2_loc (loc, MINUS_EXPR, etype, exp, low),
5737 1, build_int_cst (etype, 0), value);
5739 return 0;
5742 /* Return the predecessor of VAL in its type, handling the infinite case. */
5744 static tree
5745 range_predecessor (tree val)
5747 tree type = TREE_TYPE (val);
5749 if (INTEGRAL_TYPE_P (type)
5750 && operand_equal_p (val, TYPE_MIN_VALUE (type), 0))
5751 return 0;
5752 else
5753 return range_binop (MINUS_EXPR, NULL_TREE, val, 0,
5754 build_int_cst (TREE_TYPE (val), 1), 0);
5757 /* Return the successor of VAL in its type, handling the infinite case. */
5759 static tree
5760 range_successor (tree val)
5762 tree type = TREE_TYPE (val);
5764 if (INTEGRAL_TYPE_P (type)
5765 && operand_equal_p (val, TYPE_MAX_VALUE (type), 0))
5766 return 0;
5767 else
5768 return range_binop (PLUS_EXPR, NULL_TREE, val, 0,
5769 build_int_cst (TREE_TYPE (val), 1), 0);
5772 /* Given two ranges, see if we can merge them into one. Return 1 if we
5773 can, 0 if we can't. Set the output range into the specified parameters. */
5775 bool
5776 merge_ranges (int *pin_p, tree *plow, tree *phigh, int in0_p, tree low0,
5777 tree high0, int in1_p, tree low1, tree high1)
5779 bool no_overlap;
5780 int subset;
5781 int temp;
5782 tree tem;
5783 int in_p;
5784 tree low, high;
5785 int lowequal = ((low0 == 0 && low1 == 0)
5786 || integer_onep (range_binop (EQ_EXPR, integer_type_node,
5787 low0, 0, low1, 0)));
5788 int highequal = ((high0 == 0 && high1 == 0)
5789 || integer_onep (range_binop (EQ_EXPR, integer_type_node,
5790 high0, 1, high1, 1)));
5792 /* Make range 0 be the range that starts first, or ends last if they
5793 start at the same value. Swap them if it isn't. */
5794 if (integer_onep (range_binop (GT_EXPR, integer_type_node,
5795 low0, 0, low1, 0))
5796 || (lowequal
5797 && integer_onep (range_binop (GT_EXPR, integer_type_node,
5798 high1, 1, high0, 1))))
5800 temp = in0_p, in0_p = in1_p, in1_p = temp;
5801 tem = low0, low0 = low1, low1 = tem;
5802 tem = high0, high0 = high1, high1 = tem;
5805 /* If the second range is != high1 where high1 is the type maximum of
5806 the type, try first merging with < high1 range. */
5807 if (low1
5808 && high1
5809 && TREE_CODE (low1) == INTEGER_CST
5810 && (TREE_CODE (TREE_TYPE (low1)) == INTEGER_TYPE
5811 || (TREE_CODE (TREE_TYPE (low1)) == ENUMERAL_TYPE
5812 && known_eq (TYPE_PRECISION (TREE_TYPE (low1)),
5813 GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE (low1))))))
5814 && operand_equal_p (low1, high1, 0))
5816 if (tree_int_cst_equal (low1, TYPE_MAX_VALUE (TREE_TYPE (low1)))
5817 && merge_ranges (pin_p, plow, phigh, in0_p, low0, high0,
5818 !in1_p, NULL_TREE, range_predecessor (low1)))
5819 return true;
5820 /* Similarly for the second range != low1 where low1 is the type minimum
5821 of the type, try first merging with > low1 range. */
5822 if (tree_int_cst_equal (low1, TYPE_MIN_VALUE (TREE_TYPE (low1)))
5823 && merge_ranges (pin_p, plow, phigh, in0_p, low0, high0,
5824 !in1_p, range_successor (low1), NULL_TREE))
5825 return true;
5828 /* Now flag two cases, whether the ranges are disjoint or whether the
5829 second range is totally subsumed in the first. Note that the tests
5830 below are simplified by the ones above. */
5831 no_overlap = integer_onep (range_binop (LT_EXPR, integer_type_node,
5832 high0, 1, low1, 0));
5833 subset = integer_onep (range_binop (LE_EXPR, integer_type_node,
5834 high1, 1, high0, 1));
5836 /* We now have four cases, depending on whether we are including or
5837 excluding the two ranges. */
5838 if (in0_p && in1_p)
5840 /* If they don't overlap, the result is false. If the second range
5841 is a subset it is the result. Otherwise, the range is from the start
5842 of the second to the end of the first. */
5843 if (no_overlap)
5844 in_p = 0, low = high = 0;
5845 else if (subset)
5846 in_p = 1, low = low1, high = high1;
5847 else
5848 in_p = 1, low = low1, high = high0;
5851 else if (in0_p && ! in1_p)
5853 /* If they don't overlap, the result is the first range. If they are
5854 equal, the result is false. If the second range is a subset of the
5855 first, and the ranges begin at the same place, we go from just after
5856 the end of the second range to the end of the first. If the second
5857 range is not a subset of the first, or if it is a subset and both
5858 ranges end at the same place, the range starts at the start of the
5859 first range and ends just before the second range.
5860 Otherwise, we can't describe this as a single range. */
5861 if (no_overlap)
5862 in_p = 1, low = low0, high = high0;
5863 else if (lowequal && highequal)
5864 in_p = 0, low = high = 0;
5865 else if (subset && lowequal)
5867 low = range_successor (high1);
5868 high = high0;
5869 in_p = 1;
5870 if (low == 0)
5872 /* We are in the weird situation where high0 > high1 but
5873 high1 has no successor. Punt. */
5874 return 0;
5877 else if (! subset || highequal)
5879 low = low0;
5880 high = range_predecessor (low1);
5881 in_p = 1;
5882 if (high == 0)
5884 /* low0 < low1 but low1 has no predecessor. Punt. */
5885 return 0;
5888 else
5889 return 0;
5892 else if (! in0_p && in1_p)
5894 /* If they don't overlap, the result is the second range. If the second
5895 is a subset of the first, the result is false. Otherwise,
5896 the range starts just after the first range and ends at the
5897 end of the second. */
5898 if (no_overlap)
5899 in_p = 1, low = low1, high = high1;
5900 else if (subset || highequal)
5901 in_p = 0, low = high = 0;
5902 else
5904 low = range_successor (high0);
5905 high = high1;
5906 in_p = 1;
5907 if (low == 0)
5909 /* high1 > high0 but high0 has no successor. Punt. */
5910 return 0;
5915 else
5917 /* The case where we are excluding both ranges. Here the complex case
5918 is if they don't overlap. In that case, the only time we have a
5919 range is if they are adjacent. If the second is a subset of the
5920 first, the result is the first. Otherwise, the range to exclude
5921 starts at the beginning of the first range and ends at the end of the
5922 second. */
5923 if (no_overlap)
5925 if (integer_onep (range_binop (EQ_EXPR, integer_type_node,
5926 range_successor (high0),
5927 1, low1, 0)))
5928 in_p = 0, low = low0, high = high1;
5929 else
5931 /* Canonicalize - [min, x] into - [-, x]. */
5932 if (low0 && TREE_CODE (low0) == INTEGER_CST)
5933 switch (TREE_CODE (TREE_TYPE (low0)))
5935 case ENUMERAL_TYPE:
5936 if (maybe_ne (TYPE_PRECISION (TREE_TYPE (low0)),
5937 GET_MODE_BITSIZE
5938 (TYPE_MODE (TREE_TYPE (low0)))))
5939 break;
5940 /* FALLTHROUGH */
5941 case INTEGER_TYPE:
5942 if (tree_int_cst_equal (low0,
5943 TYPE_MIN_VALUE (TREE_TYPE (low0))))
5944 low0 = 0;
5945 break;
5946 case POINTER_TYPE:
5947 if (TYPE_UNSIGNED (TREE_TYPE (low0))
5948 && integer_zerop (low0))
5949 low0 = 0;
5950 break;
5951 default:
5952 break;
5955 /* Canonicalize - [x, max] into - [x, -]. */
5956 if (high1 && TREE_CODE (high1) == INTEGER_CST)
5957 switch (TREE_CODE (TREE_TYPE (high1)))
5959 case ENUMERAL_TYPE:
5960 if (maybe_ne (TYPE_PRECISION (TREE_TYPE (high1)),
5961 GET_MODE_BITSIZE
5962 (TYPE_MODE (TREE_TYPE (high1)))))
5963 break;
5964 /* FALLTHROUGH */
5965 case INTEGER_TYPE:
5966 if (tree_int_cst_equal (high1,
5967 TYPE_MAX_VALUE (TREE_TYPE (high1))))
5968 high1 = 0;
5969 break;
5970 case POINTER_TYPE:
5971 if (TYPE_UNSIGNED (TREE_TYPE (high1))
5972 && integer_zerop (range_binop (PLUS_EXPR, NULL_TREE,
5973 high1, 1,
5974 build_int_cst (TREE_TYPE (high1), 1),
5975 1)))
5976 high1 = 0;
5977 break;
5978 default:
5979 break;
5982 /* The ranges might be also adjacent between the maximum and
5983 minimum values of the given type. For
5984 - [{min,-}, x] and - [y, {max,-}] ranges where x + 1 < y
5985 return + [x + 1, y - 1]. */
5986 if (low0 == 0 && high1 == 0)
5988 low = range_successor (high0);
5989 high = range_predecessor (low1);
5990 if (low == 0 || high == 0)
5991 return 0;
5993 in_p = 1;
5995 else
5996 return 0;
5999 else if (subset)
6000 in_p = 0, low = low0, high = high0;
6001 else
6002 in_p = 0, low = low0, high = high1;
6005 *pin_p = in_p, *plow = low, *phigh = high;
6006 return 1;
6010 /* Subroutine of fold, looking inside expressions of the form
6011 A op B ? A : C, where (ARG00, COMP_CODE, ARG01), ARG1 and ARG2
6012 are the three operands of the COND_EXPR. This function is
6013 being used also to optimize A op B ? C : A, by reversing the
6014 comparison first.
6016 Return a folded expression whose code is not a COND_EXPR
6017 anymore, or NULL_TREE if no folding opportunity is found. */
6019 static tree
6020 fold_cond_expr_with_comparison (location_t loc, tree type,
6021 enum tree_code comp_code,
6022 tree arg00, tree arg01, tree arg1, tree arg2)
6024 tree arg1_type = TREE_TYPE (arg1);
6025 tree tem;
6027 STRIP_NOPS (arg1);
6028 STRIP_NOPS (arg2);
6030 /* If we have A op 0 ? A : -A, consider applying the following
6031 transformations:
6033 A == 0? A : -A same as -A
6034 A != 0? A : -A same as A
6035 A >= 0? A : -A same as abs (A)
6036 A > 0? A : -A same as abs (A)
6037 A <= 0? A : -A same as -abs (A)
6038 A < 0? A : -A same as -abs (A)
6040 None of these transformations work for modes with signed
6041 zeros. If A is +/-0, the first two transformations will
6042 change the sign of the result (from +0 to -0, or vice
6043 versa). The last four will fix the sign of the result,
6044 even though the original expressions could be positive or
6045 negative, depending on the sign of A.
6047 Note that all these transformations are correct if A is
6048 NaN, since the two alternatives (A and -A) are also NaNs. */
6049 if (!HONOR_SIGNED_ZEROS (type)
6050 && (FLOAT_TYPE_P (TREE_TYPE (arg01))
6051 ? real_zerop (arg01)
6052 : integer_zerop (arg01))
6053 && ((TREE_CODE (arg2) == NEGATE_EXPR
6054 && operand_equal_p (TREE_OPERAND (arg2, 0), arg1, 0))
6055 /* In the case that A is of the form X-Y, '-A' (arg2) may
6056 have already been folded to Y-X, check for that. */
6057 || (TREE_CODE (arg1) == MINUS_EXPR
6058 && TREE_CODE (arg2) == MINUS_EXPR
6059 && operand_equal_p (TREE_OPERAND (arg1, 0),
6060 TREE_OPERAND (arg2, 1), 0)
6061 && operand_equal_p (TREE_OPERAND (arg1, 1),
6062 TREE_OPERAND (arg2, 0), 0))))
6063 switch (comp_code)
6065 case EQ_EXPR:
6066 case UNEQ_EXPR:
6067 tem = fold_convert_loc (loc, arg1_type, arg1);
6068 return fold_convert_loc (loc, type, negate_expr (tem));
6069 case NE_EXPR:
6070 case LTGT_EXPR:
6071 return fold_convert_loc (loc, type, arg1);
6072 case UNGE_EXPR:
6073 case UNGT_EXPR:
6074 if (flag_trapping_math)
6075 break;
6076 /* Fall through. */
6077 case GE_EXPR:
6078 case GT_EXPR:
6079 if (TYPE_UNSIGNED (TREE_TYPE (arg1)))
6080 break;
6081 tem = fold_build1_loc (loc, ABS_EXPR, TREE_TYPE (arg1), arg1);
6082 return fold_convert_loc (loc, type, tem);
6083 case UNLE_EXPR:
6084 case UNLT_EXPR:
6085 if (flag_trapping_math)
6086 break;
6087 /* FALLTHRU */
6088 case LE_EXPR:
6089 case LT_EXPR:
6090 if (TYPE_UNSIGNED (TREE_TYPE (arg1)))
6091 break;
6092 if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (arg1))
6093 && !TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg1)))
6095 /* A <= 0 ? A : -A for A INT_MIN is valid, but -abs(INT_MIN)
6096 is not, invokes UB both in abs and in the negation of it.
6097 So, use ABSU_EXPR instead. */
6098 tree utype = unsigned_type_for (TREE_TYPE (arg1));
6099 tem = fold_build1_loc (loc, ABSU_EXPR, utype, arg1);
6100 tem = negate_expr (tem);
6101 return fold_convert_loc (loc, type, tem);
6103 else
6105 tem = fold_build1_loc (loc, ABS_EXPR, TREE_TYPE (arg1), arg1);
6106 return negate_expr (fold_convert_loc (loc, type, tem));
6108 default:
6109 gcc_assert (TREE_CODE_CLASS (comp_code) == tcc_comparison);
6110 break;
6113 /* A != 0 ? A : 0 is simply A, unless A is -0. Likewise
6114 A == 0 ? A : 0 is always 0 unless A is -0. Note that
6115 both transformations are correct when A is NaN: A != 0
6116 is then true, and A == 0 is false. */
6118 if (!HONOR_SIGNED_ZEROS (type)
6119 && integer_zerop (arg01) && integer_zerop (arg2))
6121 if (comp_code == NE_EXPR)
6122 return fold_convert_loc (loc, type, arg1);
6123 else if (comp_code == EQ_EXPR)
6124 return build_zero_cst (type);
6127 /* Try some transformations of A op B ? A : B.
6129 A == B? A : B same as B
6130 A != B? A : B same as A
6131 A >= B? A : B same as max (A, B)
6132 A > B? A : B same as max (B, A)
6133 A <= B? A : B same as min (A, B)
6134 A < B? A : B same as min (B, A)
6136 As above, these transformations don't work in the presence
6137 of signed zeros. For example, if A and B are zeros of
6138 opposite sign, the first two transformations will change
6139 the sign of the result. In the last four, the original
6140 expressions give different results for (A=+0, B=-0) and
6141 (A=-0, B=+0), but the transformed expressions do not.
6143 The first two transformations are correct if either A or B
6144 is a NaN. In the first transformation, the condition will
6145 be false, and B will indeed be chosen. In the case of the
6146 second transformation, the condition A != B will be true,
6147 and A will be chosen.
6149 The conversions to max() and min() are not correct if B is
6150 a number and A is not. The conditions in the original
6151 expressions will be false, so all four give B. The min()
6152 and max() versions would give a NaN instead. */
6153 if (!HONOR_SIGNED_ZEROS (type)
6154 && operand_equal_for_comparison_p (arg01, arg2)
6155 /* Avoid these transformations if the COND_EXPR may be used
6156 as an lvalue in the C++ front-end. PR c++/19199. */
6157 && (in_gimple_form
6158 || VECTOR_TYPE_P (type)
6159 || (! lang_GNU_CXX ()
6160 && strcmp (lang_hooks.name, "GNU Objective-C++") != 0)
6161 || ! maybe_lvalue_p (arg1)
6162 || ! maybe_lvalue_p (arg2)))
6164 tree comp_op0 = arg00;
6165 tree comp_op1 = arg01;
6166 tree comp_type = TREE_TYPE (comp_op0);
6168 switch (comp_code)
6170 case EQ_EXPR:
6171 return fold_convert_loc (loc, type, arg2);
6172 case NE_EXPR:
6173 return fold_convert_loc (loc, type, arg1);
6174 case LE_EXPR:
6175 case LT_EXPR:
6176 case UNLE_EXPR:
6177 case UNLT_EXPR:
6178 /* In C++ a ?: expression can be an lvalue, so put the
6179 operand which will be used if they are equal first
6180 so that we can convert this back to the
6181 corresponding COND_EXPR. */
6182 if (!HONOR_NANS (arg1))
6184 comp_op0 = fold_convert_loc (loc, comp_type, comp_op0);
6185 comp_op1 = fold_convert_loc (loc, comp_type, comp_op1);
6186 tem = (comp_code == LE_EXPR || comp_code == UNLE_EXPR)
6187 ? fold_build2_loc (loc, MIN_EXPR, comp_type, comp_op0, comp_op1)
6188 : fold_build2_loc (loc, MIN_EXPR, comp_type,
6189 comp_op1, comp_op0);
6190 return fold_convert_loc (loc, type, tem);
6192 break;
6193 case GE_EXPR:
6194 case GT_EXPR:
6195 case UNGE_EXPR:
6196 case UNGT_EXPR:
6197 if (!HONOR_NANS (arg1))
6199 comp_op0 = fold_convert_loc (loc, comp_type, comp_op0);
6200 comp_op1 = fold_convert_loc (loc, comp_type, comp_op1);
6201 tem = (comp_code == GE_EXPR || comp_code == UNGE_EXPR)
6202 ? fold_build2_loc (loc, MAX_EXPR, comp_type, comp_op0, comp_op1)
6203 : fold_build2_loc (loc, MAX_EXPR, comp_type,
6204 comp_op1, comp_op0);
6205 return fold_convert_loc (loc, type, tem);
6207 break;
6208 case UNEQ_EXPR:
6209 if (!HONOR_NANS (arg1))
6210 return fold_convert_loc (loc, type, arg2);
6211 break;
6212 case LTGT_EXPR:
6213 if (!HONOR_NANS (arg1))
6214 return fold_convert_loc (loc, type, arg1);
6215 break;
6216 default:
6217 gcc_assert (TREE_CODE_CLASS (comp_code) == tcc_comparison);
6218 break;
6222 return NULL_TREE;
6227 #ifndef LOGICAL_OP_NON_SHORT_CIRCUIT
6228 #define LOGICAL_OP_NON_SHORT_CIRCUIT \
6229 (BRANCH_COST (optimize_function_for_speed_p (cfun), \
6230 false) >= 2)
6231 #endif
6233 /* EXP is some logical combination of boolean tests. See if we can
6234 merge it into some range test. Return the new tree if so. */
6236 static tree
6237 fold_range_test (location_t loc, enum tree_code code, tree type,
6238 tree op0, tree op1)
6240 int or_op = (code == TRUTH_ORIF_EXPR
6241 || code == TRUTH_OR_EXPR);
6242 int in0_p, in1_p, in_p;
6243 tree low0, low1, low, high0, high1, high;
6244 bool strict_overflow_p = false;
6245 tree tem, lhs, rhs;
6246 const char * const warnmsg = G_("assuming signed overflow does not occur "
6247 "when simplifying range test");
6249 if (!INTEGRAL_TYPE_P (type))
6250 return 0;
6252 lhs = make_range (op0, &in0_p, &low0, &high0, &strict_overflow_p);
6253 /* If op0 is known true or false and this is a short-circuiting
6254 operation we must not merge with op1 since that makes side-effects
6255 unconditional. So special-case this. */
6256 if (!lhs
6257 && ((code == TRUTH_ORIF_EXPR && in0_p)
6258 || (code == TRUTH_ANDIF_EXPR && !in0_p)))
6259 return op0;
6260 rhs = make_range (op1, &in1_p, &low1, &high1, &strict_overflow_p);
6262 /* If this is an OR operation, invert both sides; we will invert
6263 again at the end. */
6264 if (or_op)
6265 in0_p = ! in0_p, in1_p = ! in1_p;
6267 /* If both expressions are the same, if we can merge the ranges, and we
6268 can build the range test, return it or it inverted. If one of the
6269 ranges is always true or always false, consider it to be the same
6270 expression as the other. */
6271 if ((lhs == 0 || rhs == 0 || operand_equal_p (lhs, rhs, 0))
6272 && merge_ranges (&in_p, &low, &high, in0_p, low0, high0,
6273 in1_p, low1, high1)
6274 && (tem = (build_range_check (loc, type,
6275 lhs != 0 ? lhs
6276 : rhs != 0 ? rhs : integer_zero_node,
6277 in_p, low, high))) != 0)
6279 if (strict_overflow_p)
6280 fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_COMPARISON);
6281 return or_op ? invert_truthvalue_loc (loc, tem) : tem;
6284 /* On machines where the branch cost is expensive, if this is a
6285 short-circuited branch and the underlying object on both sides
6286 is the same, make a non-short-circuit operation. */
6287 bool logical_op_non_short_circuit = LOGICAL_OP_NON_SHORT_CIRCUIT;
6288 if (param_logical_op_non_short_circuit != -1)
6289 logical_op_non_short_circuit
6290 = param_logical_op_non_short_circuit;
6291 if (logical_op_non_short_circuit
6292 && !sanitize_coverage_p ()
6293 && lhs != 0 && rhs != 0
6294 && (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR)
6295 && operand_equal_p (lhs, rhs, 0))
6297 /* If simple enough, just rewrite. Otherwise, make a SAVE_EXPR
6298 unless we are at top level or LHS contains a PLACEHOLDER_EXPR, in
6299 which cases we can't do this. */
6300 if (simple_operand_p (lhs))
6301 return build2_loc (loc, code == TRUTH_ANDIF_EXPR
6302 ? TRUTH_AND_EXPR : TRUTH_OR_EXPR,
6303 type, op0, op1);
6305 else if (!lang_hooks.decls.global_bindings_p ()
6306 && !CONTAINS_PLACEHOLDER_P (lhs))
6308 tree common = save_expr (lhs);
6310 if ((lhs = build_range_check (loc, type, common,
6311 or_op ? ! in0_p : in0_p,
6312 low0, high0)) != 0
6313 && (rhs = build_range_check (loc, type, common,
6314 or_op ? ! in1_p : in1_p,
6315 low1, high1)) != 0)
6317 if (strict_overflow_p)
6318 fold_overflow_warning (warnmsg,
6319 WARN_STRICT_OVERFLOW_COMPARISON);
6320 return build2_loc (loc, code == TRUTH_ANDIF_EXPR
6321 ? TRUTH_AND_EXPR : TRUTH_OR_EXPR,
6322 type, lhs, rhs);
6327 return 0;
6330 /* Subroutine for fold_truth_andor_1: C is an INTEGER_CST interpreted as a P
6331 bit value. Arrange things so the extra bits will be set to zero if and
6332 only if C is signed-extended to its full width. If MASK is nonzero,
6333 it is an INTEGER_CST that should be AND'ed with the extra bits. */
6335 static tree
6336 unextend (tree c, int p, int unsignedp, tree mask)
6338 tree type = TREE_TYPE (c);
6339 int modesize = GET_MODE_BITSIZE (SCALAR_INT_TYPE_MODE (type));
6340 tree temp;
6342 if (p == modesize || unsignedp)
6343 return c;
6345 /* We work by getting just the sign bit into the low-order bit, then
6346 into the high-order bit, then sign-extend. We then XOR that value
6347 with C. */
6348 temp = build_int_cst (TREE_TYPE (c),
6349 wi::extract_uhwi (wi::to_wide (c), p - 1, 1));
6351 /* We must use a signed type in order to get an arithmetic right shift.
6352 However, we must also avoid introducing accidental overflows, so that
6353 a subsequent call to integer_zerop will work. Hence we must
6354 do the type conversion here. At this point, the constant is either
6355 zero or one, and the conversion to a signed type can never overflow.
6356 We could get an overflow if this conversion is done anywhere else. */
6357 if (TYPE_UNSIGNED (type))
6358 temp = fold_convert (signed_type_for (type), temp);
6360 temp = const_binop (LSHIFT_EXPR, temp, size_int (modesize - 1));
6361 temp = const_binop (RSHIFT_EXPR, temp, size_int (modesize - p - 1));
6362 if (mask != 0)
6363 temp = const_binop (BIT_AND_EXPR, temp,
6364 fold_convert (TREE_TYPE (c), mask));
6365 /* If necessary, convert the type back to match the type of C. */
6366 if (TYPE_UNSIGNED (type))
6367 temp = fold_convert (type, temp);
6369 return fold_convert (type, const_binop (BIT_XOR_EXPR, c, temp));
6372 /* For an expression that has the form
6373 (A && B) || ~B
6375 (A || B) && ~B,
6376 we can drop one of the inner expressions and simplify to
6377 A || ~B
6379 A && ~B
6380 LOC is the location of the resulting expression. OP is the inner
6381 logical operation; the left-hand side in the examples above, while CMPOP
6382 is the right-hand side. RHS_ONLY is used to prevent us from accidentally
6383 removing a condition that guards another, as in
6384 (A != NULL && A->...) || A == NULL
6385 which we must not transform. If RHS_ONLY is true, only eliminate the
6386 right-most operand of the inner logical operation. */
6388 static tree
6389 merge_truthop_with_opposite_arm (location_t loc, tree op, tree cmpop,
6390 bool rhs_only)
6392 tree type = TREE_TYPE (cmpop);
6393 enum tree_code code = TREE_CODE (cmpop);
6394 enum tree_code truthop_code = TREE_CODE (op);
6395 tree lhs = TREE_OPERAND (op, 0);
6396 tree rhs = TREE_OPERAND (op, 1);
6397 tree orig_lhs = lhs, orig_rhs = rhs;
6398 enum tree_code rhs_code = TREE_CODE (rhs);
6399 enum tree_code lhs_code = TREE_CODE (lhs);
6400 enum tree_code inv_code;
6402 if (TREE_SIDE_EFFECTS (op) || TREE_SIDE_EFFECTS (cmpop))
6403 return NULL_TREE;
6405 if (TREE_CODE_CLASS (code) != tcc_comparison)
6406 return NULL_TREE;
6408 if (rhs_code == truthop_code)
6410 tree newrhs = merge_truthop_with_opposite_arm (loc, rhs, cmpop, rhs_only);
6411 if (newrhs != NULL_TREE)
6413 rhs = newrhs;
6414 rhs_code = TREE_CODE (rhs);
6417 if (lhs_code == truthop_code && !rhs_only)
6419 tree newlhs = merge_truthop_with_opposite_arm (loc, lhs, cmpop, false);
6420 if (newlhs != NULL_TREE)
6422 lhs = newlhs;
6423 lhs_code = TREE_CODE (lhs);
6427 inv_code = invert_tree_comparison (code, HONOR_NANS (type));
6428 if (inv_code == rhs_code
6429 && operand_equal_p (TREE_OPERAND (rhs, 0), TREE_OPERAND (cmpop, 0), 0)
6430 && operand_equal_p (TREE_OPERAND (rhs, 1), TREE_OPERAND (cmpop, 1), 0))
6431 return lhs;
6432 if (!rhs_only && inv_code == lhs_code
6433 && operand_equal_p (TREE_OPERAND (lhs, 0), TREE_OPERAND (cmpop, 0), 0)
6434 && operand_equal_p (TREE_OPERAND (lhs, 1), TREE_OPERAND (cmpop, 1), 0))
6435 return rhs;
6436 if (rhs != orig_rhs || lhs != orig_lhs)
6437 return fold_build2_loc (loc, truthop_code, TREE_TYPE (cmpop),
6438 lhs, rhs);
6439 return NULL_TREE;
6442 /* Find ways of folding logical expressions of LHS and RHS:
6443 Try to merge two comparisons to the same innermost item.
6444 Look for range tests like "ch >= '0' && ch <= '9'".
6445 Look for combinations of simple terms on machines with expensive branches
6446 and evaluate the RHS unconditionally.
6448 For example, if we have p->a == 2 && p->b == 4 and we can make an
6449 object large enough to span both A and B, we can do this with a comparison
6450 against the object ANDed with the a mask.
6452 If we have p->a == q->a && p->b == q->b, we may be able to use bit masking
6453 operations to do this with one comparison.
6455 We check for both normal comparisons and the BIT_AND_EXPRs made this by
6456 function and the one above.
6458 CODE is the logical operation being done. It can be TRUTH_ANDIF_EXPR,
6459 TRUTH_AND_EXPR, TRUTH_ORIF_EXPR, or TRUTH_OR_EXPR.
6461 TRUTH_TYPE is the type of the logical operand and LHS and RHS are its
6462 two operands.
6464 We return the simplified tree or 0 if no optimization is possible. */
6466 static tree
6467 fold_truth_andor_1 (location_t loc, enum tree_code code, tree truth_type,
6468 tree lhs, tree rhs)
6470 /* If this is the "or" of two comparisons, we can do something if
6471 the comparisons are NE_EXPR. If this is the "and", we can do something
6472 if the comparisons are EQ_EXPR. I.e.,
6473 (a->b == 2 && a->c == 4) can become (a->new == NEW).
6475 WANTED_CODE is this operation code. For single bit fields, we can
6476 convert EQ_EXPR to NE_EXPR so we need not reject the "wrong"
6477 comparison for one-bit fields. */
6479 enum tree_code wanted_code;
6480 enum tree_code lcode, rcode;
6481 tree ll_arg, lr_arg, rl_arg, rr_arg;
6482 tree ll_inner, lr_inner, rl_inner, rr_inner;
6483 HOST_WIDE_INT ll_bitsize, ll_bitpos, lr_bitsize, lr_bitpos;
6484 HOST_WIDE_INT rl_bitsize, rl_bitpos, rr_bitsize, rr_bitpos;
6485 HOST_WIDE_INT xll_bitpos, xlr_bitpos, xrl_bitpos, xrr_bitpos;
6486 HOST_WIDE_INT lnbitsize, lnbitpos, rnbitsize, rnbitpos;
6487 int ll_unsignedp, lr_unsignedp, rl_unsignedp, rr_unsignedp;
6488 int ll_reversep, lr_reversep, rl_reversep, rr_reversep;
6489 machine_mode ll_mode, lr_mode, rl_mode, rr_mode;
6490 scalar_int_mode lnmode, rnmode;
6491 tree ll_mask, lr_mask, rl_mask, rr_mask;
6492 tree ll_and_mask, lr_and_mask, rl_and_mask, rr_and_mask;
6493 tree l_const, r_const;
6494 tree lntype, rntype, result;
6495 HOST_WIDE_INT first_bit, end_bit;
6496 int volatilep;
6498 /* Start by getting the comparison codes. Fail if anything is volatile.
6499 If one operand is a BIT_AND_EXPR with the constant one, treat it as if
6500 it were surrounded with a NE_EXPR. */
6502 if (TREE_SIDE_EFFECTS (lhs) || TREE_SIDE_EFFECTS (rhs))
6503 return 0;
6505 lcode = TREE_CODE (lhs);
6506 rcode = TREE_CODE (rhs);
6508 if (lcode == BIT_AND_EXPR && integer_onep (TREE_OPERAND (lhs, 1)))
6510 lhs = build2 (NE_EXPR, truth_type, lhs,
6511 build_int_cst (TREE_TYPE (lhs), 0));
6512 lcode = NE_EXPR;
6515 if (rcode == BIT_AND_EXPR && integer_onep (TREE_OPERAND (rhs, 1)))
6517 rhs = build2 (NE_EXPR, truth_type, rhs,
6518 build_int_cst (TREE_TYPE (rhs), 0));
6519 rcode = NE_EXPR;
6522 if (TREE_CODE_CLASS (lcode) != tcc_comparison
6523 || TREE_CODE_CLASS (rcode) != tcc_comparison)
6524 return 0;
6526 ll_arg = TREE_OPERAND (lhs, 0);
6527 lr_arg = TREE_OPERAND (lhs, 1);
6528 rl_arg = TREE_OPERAND (rhs, 0);
6529 rr_arg = TREE_OPERAND (rhs, 1);
6531 /* Simplify (x<y) && (x==y) into (x<=y) and related optimizations. */
6532 if (simple_operand_p (ll_arg)
6533 && simple_operand_p (lr_arg))
6535 if (operand_equal_p (ll_arg, rl_arg, 0)
6536 && operand_equal_p (lr_arg, rr_arg, 0))
6538 result = combine_comparisons (loc, code, lcode, rcode,
6539 truth_type, ll_arg, lr_arg);
6540 if (result)
6541 return result;
6543 else if (operand_equal_p (ll_arg, rr_arg, 0)
6544 && operand_equal_p (lr_arg, rl_arg, 0))
6546 result = combine_comparisons (loc, code, lcode,
6547 swap_tree_comparison (rcode),
6548 truth_type, ll_arg, lr_arg);
6549 if (result)
6550 return result;
6554 code = ((code == TRUTH_AND_EXPR || code == TRUTH_ANDIF_EXPR)
6555 ? TRUTH_AND_EXPR : TRUTH_OR_EXPR);
6557 /* If the RHS can be evaluated unconditionally and its operands are
6558 simple, it wins to evaluate the RHS unconditionally on machines
6559 with expensive branches. In this case, this isn't a comparison
6560 that can be merged. */
6562 if (BRANCH_COST (optimize_function_for_speed_p (cfun),
6563 false) >= 2
6564 && ! FLOAT_TYPE_P (TREE_TYPE (rl_arg))
6565 && simple_operand_p (rl_arg)
6566 && simple_operand_p (rr_arg))
6568 /* Convert (a != 0) || (b != 0) into (a | b) != 0. */
6569 if (code == TRUTH_OR_EXPR
6570 && lcode == NE_EXPR && integer_zerop (lr_arg)
6571 && rcode == NE_EXPR && integer_zerop (rr_arg)
6572 && TREE_TYPE (ll_arg) == TREE_TYPE (rl_arg)
6573 && INTEGRAL_TYPE_P (TREE_TYPE (ll_arg)))
6574 return build2_loc (loc, NE_EXPR, truth_type,
6575 build2 (BIT_IOR_EXPR, TREE_TYPE (ll_arg),
6576 ll_arg, rl_arg),
6577 build_int_cst (TREE_TYPE (ll_arg), 0));
6579 /* Convert (a == 0) && (b == 0) into (a | b) == 0. */
6580 if (code == TRUTH_AND_EXPR
6581 && lcode == EQ_EXPR && integer_zerop (lr_arg)
6582 && rcode == EQ_EXPR && integer_zerop (rr_arg)
6583 && TREE_TYPE (ll_arg) == TREE_TYPE (rl_arg)
6584 && INTEGRAL_TYPE_P (TREE_TYPE (ll_arg)))
6585 return build2_loc (loc, EQ_EXPR, truth_type,
6586 build2 (BIT_IOR_EXPR, TREE_TYPE (ll_arg),
6587 ll_arg, rl_arg),
6588 build_int_cst (TREE_TYPE (ll_arg), 0));
6591 /* See if the comparisons can be merged. Then get all the parameters for
6592 each side. */
6594 if ((lcode != EQ_EXPR && lcode != NE_EXPR)
6595 || (rcode != EQ_EXPR && rcode != NE_EXPR))
6596 return 0;
6598 ll_reversep = lr_reversep = rl_reversep = rr_reversep = 0;
6599 volatilep = 0;
6600 ll_inner = decode_field_reference (loc, &ll_arg,
6601 &ll_bitsize, &ll_bitpos, &ll_mode,
6602 &ll_unsignedp, &ll_reversep, &volatilep,
6603 &ll_mask, &ll_and_mask);
6604 lr_inner = decode_field_reference (loc, &lr_arg,
6605 &lr_bitsize, &lr_bitpos, &lr_mode,
6606 &lr_unsignedp, &lr_reversep, &volatilep,
6607 &lr_mask, &lr_and_mask);
6608 rl_inner = decode_field_reference (loc, &rl_arg,
6609 &rl_bitsize, &rl_bitpos, &rl_mode,
6610 &rl_unsignedp, &rl_reversep, &volatilep,
6611 &rl_mask, &rl_and_mask);
6612 rr_inner = decode_field_reference (loc, &rr_arg,
6613 &rr_bitsize, &rr_bitpos, &rr_mode,
6614 &rr_unsignedp, &rr_reversep, &volatilep,
6615 &rr_mask, &rr_and_mask);
6617 /* It must be true that the inner operation on the lhs of each
6618 comparison must be the same if we are to be able to do anything.
6619 Then see if we have constants. If not, the same must be true for
6620 the rhs's. */
6621 if (volatilep
6622 || ll_reversep != rl_reversep
6623 || ll_inner == 0 || rl_inner == 0
6624 || ! operand_equal_p (ll_inner, rl_inner, 0))
6625 return 0;
6627 if (TREE_CODE (lr_arg) == INTEGER_CST
6628 && TREE_CODE (rr_arg) == INTEGER_CST)
6630 l_const = lr_arg, r_const = rr_arg;
6631 lr_reversep = ll_reversep;
6633 else if (lr_reversep != rr_reversep
6634 || lr_inner == 0 || rr_inner == 0
6635 || ! operand_equal_p (lr_inner, rr_inner, 0))
6636 return 0;
6637 else
6638 l_const = r_const = 0;
6640 /* If either comparison code is not correct for our logical operation,
6641 fail. However, we can convert a one-bit comparison against zero into
6642 the opposite comparison against that bit being set in the field. */
6644 wanted_code = (code == TRUTH_AND_EXPR ? EQ_EXPR : NE_EXPR);
6645 if (lcode != wanted_code)
6647 if (l_const && integer_zerop (l_const) && integer_pow2p (ll_mask))
6649 /* Make the left operand unsigned, since we are only interested
6650 in the value of one bit. Otherwise we are doing the wrong
6651 thing below. */
6652 ll_unsignedp = 1;
6653 l_const = ll_mask;
6655 else
6656 return 0;
6659 /* This is analogous to the code for l_const above. */
6660 if (rcode != wanted_code)
6662 if (r_const && integer_zerop (r_const) && integer_pow2p (rl_mask))
6664 rl_unsignedp = 1;
6665 r_const = rl_mask;
6667 else
6668 return 0;
6671 /* See if we can find a mode that contains both fields being compared on
6672 the left. If we can't, fail. Otherwise, update all constants and masks
6673 to be relative to a field of that size. */
6674 first_bit = MIN (ll_bitpos, rl_bitpos);
6675 end_bit = MAX (ll_bitpos + ll_bitsize, rl_bitpos + rl_bitsize);
6676 if (!get_best_mode (end_bit - first_bit, first_bit, 0, 0,
6677 TYPE_ALIGN (TREE_TYPE (ll_inner)), BITS_PER_WORD,
6678 volatilep, &lnmode))
6679 return 0;
6681 lnbitsize = GET_MODE_BITSIZE (lnmode);
6682 lnbitpos = first_bit & ~ (lnbitsize - 1);
6683 lntype = lang_hooks.types.type_for_size (lnbitsize, 1);
6684 xll_bitpos = ll_bitpos - lnbitpos, xrl_bitpos = rl_bitpos - lnbitpos;
6686 if (ll_reversep ? !BYTES_BIG_ENDIAN : BYTES_BIG_ENDIAN)
6688 xll_bitpos = lnbitsize - xll_bitpos - ll_bitsize;
6689 xrl_bitpos = lnbitsize - xrl_bitpos - rl_bitsize;
6692 ll_mask = const_binop (LSHIFT_EXPR, fold_convert_loc (loc, lntype, ll_mask),
6693 size_int (xll_bitpos));
6694 rl_mask = const_binop (LSHIFT_EXPR, fold_convert_loc (loc, lntype, rl_mask),
6695 size_int (xrl_bitpos));
6696 if (ll_mask == NULL_TREE || rl_mask == NULL_TREE)
6697 return 0;
6699 if (l_const)
6701 l_const = fold_convert_loc (loc, lntype, l_const);
6702 l_const = unextend (l_const, ll_bitsize, ll_unsignedp, ll_and_mask);
6703 l_const = const_binop (LSHIFT_EXPR, l_const, size_int (xll_bitpos));
6704 if (l_const == NULL_TREE)
6705 return 0;
6706 if (! integer_zerop (const_binop (BIT_AND_EXPR, l_const,
6707 fold_build1_loc (loc, BIT_NOT_EXPR,
6708 lntype, ll_mask))))
6710 warning (0, "comparison is always %d", wanted_code == NE_EXPR);
6712 return constant_boolean_node (wanted_code == NE_EXPR, truth_type);
6715 if (r_const)
6717 r_const = fold_convert_loc (loc, lntype, r_const);
6718 r_const = unextend (r_const, rl_bitsize, rl_unsignedp, rl_and_mask);
6719 r_const = const_binop (LSHIFT_EXPR, r_const, size_int (xrl_bitpos));
6720 if (r_const == NULL_TREE)
6721 return 0;
6722 if (! integer_zerop (const_binop (BIT_AND_EXPR, r_const,
6723 fold_build1_loc (loc, BIT_NOT_EXPR,
6724 lntype, rl_mask))))
6726 warning (0, "comparison is always %d", wanted_code == NE_EXPR);
6728 return constant_boolean_node (wanted_code == NE_EXPR, truth_type);
6732 /* If the right sides are not constant, do the same for it. Also,
6733 disallow this optimization if a size, signedness or storage order
6734 mismatch occurs between the left and right sides. */
6735 if (l_const == 0)
6737 if (ll_bitsize != lr_bitsize || rl_bitsize != rr_bitsize
6738 || ll_unsignedp != lr_unsignedp || rl_unsignedp != rr_unsignedp
6739 || ll_reversep != lr_reversep
6740 /* Make sure the two fields on the right
6741 correspond to the left without being swapped. */
6742 || ll_bitpos - rl_bitpos != lr_bitpos - rr_bitpos)
6743 return 0;
6745 first_bit = MIN (lr_bitpos, rr_bitpos);
6746 end_bit = MAX (lr_bitpos + lr_bitsize, rr_bitpos + rr_bitsize);
6747 if (!get_best_mode (end_bit - first_bit, first_bit, 0, 0,
6748 TYPE_ALIGN (TREE_TYPE (lr_inner)), BITS_PER_WORD,
6749 volatilep, &rnmode))
6750 return 0;
6752 rnbitsize = GET_MODE_BITSIZE (rnmode);
6753 rnbitpos = first_bit & ~ (rnbitsize - 1);
6754 rntype = lang_hooks.types.type_for_size (rnbitsize, 1);
6755 xlr_bitpos = lr_bitpos - rnbitpos, xrr_bitpos = rr_bitpos - rnbitpos;
6757 if (lr_reversep ? !BYTES_BIG_ENDIAN : BYTES_BIG_ENDIAN)
6759 xlr_bitpos = rnbitsize - xlr_bitpos - lr_bitsize;
6760 xrr_bitpos = rnbitsize - xrr_bitpos - rr_bitsize;
6763 lr_mask = const_binop (LSHIFT_EXPR, fold_convert_loc (loc,
6764 rntype, lr_mask),
6765 size_int (xlr_bitpos));
6766 rr_mask = const_binop (LSHIFT_EXPR, fold_convert_loc (loc,
6767 rntype, rr_mask),
6768 size_int (xrr_bitpos));
6769 if (lr_mask == NULL_TREE || rr_mask == NULL_TREE)
6770 return 0;
6772 /* Make a mask that corresponds to both fields being compared.
6773 Do this for both items being compared. If the operands are the
6774 same size and the bits being compared are in the same position
6775 then we can do this by masking both and comparing the masked
6776 results. */
6777 ll_mask = const_binop (BIT_IOR_EXPR, ll_mask, rl_mask);
6778 lr_mask = const_binop (BIT_IOR_EXPR, lr_mask, rr_mask);
6779 if (lnbitsize == rnbitsize
6780 && xll_bitpos == xlr_bitpos
6781 && lnbitpos >= 0
6782 && rnbitpos >= 0)
6784 lhs = make_bit_field_ref (loc, ll_inner, ll_arg,
6785 lntype, lnbitsize, lnbitpos,
6786 ll_unsignedp || rl_unsignedp, ll_reversep);
6787 if (! all_ones_mask_p (ll_mask, lnbitsize))
6788 lhs = build2 (BIT_AND_EXPR, lntype, lhs, ll_mask);
6790 rhs = make_bit_field_ref (loc, lr_inner, lr_arg,
6791 rntype, rnbitsize, rnbitpos,
6792 lr_unsignedp || rr_unsignedp, lr_reversep);
6793 if (! all_ones_mask_p (lr_mask, rnbitsize))
6794 rhs = build2 (BIT_AND_EXPR, rntype, rhs, lr_mask);
6796 return build2_loc (loc, wanted_code, truth_type, lhs, rhs);
6799 /* There is still another way we can do something: If both pairs of
6800 fields being compared are adjacent, we may be able to make a wider
6801 field containing them both.
6803 Note that we still must mask the lhs/rhs expressions. Furthermore,
6804 the mask must be shifted to account for the shift done by
6805 make_bit_field_ref. */
6806 if (((ll_bitsize + ll_bitpos == rl_bitpos
6807 && lr_bitsize + lr_bitpos == rr_bitpos)
6808 || (ll_bitpos == rl_bitpos + rl_bitsize
6809 && lr_bitpos == rr_bitpos + rr_bitsize))
6810 && ll_bitpos >= 0
6811 && rl_bitpos >= 0
6812 && lr_bitpos >= 0
6813 && rr_bitpos >= 0)
6815 tree type;
6817 lhs = make_bit_field_ref (loc, ll_inner, ll_arg, lntype,
6818 ll_bitsize + rl_bitsize,
6819 MIN (ll_bitpos, rl_bitpos),
6820 ll_unsignedp, ll_reversep);
6821 rhs = make_bit_field_ref (loc, lr_inner, lr_arg, rntype,
6822 lr_bitsize + rr_bitsize,
6823 MIN (lr_bitpos, rr_bitpos),
6824 lr_unsignedp, lr_reversep);
6826 ll_mask = const_binop (RSHIFT_EXPR, ll_mask,
6827 size_int (MIN (xll_bitpos, xrl_bitpos)));
6828 lr_mask = const_binop (RSHIFT_EXPR, lr_mask,
6829 size_int (MIN (xlr_bitpos, xrr_bitpos)));
6830 if (ll_mask == NULL_TREE || lr_mask == NULL_TREE)
6831 return 0;
6833 /* Convert to the smaller type before masking out unwanted bits. */
6834 type = lntype;
6835 if (lntype != rntype)
6837 if (lnbitsize > rnbitsize)
6839 lhs = fold_convert_loc (loc, rntype, lhs);
6840 ll_mask = fold_convert_loc (loc, rntype, ll_mask);
6841 type = rntype;
6843 else if (lnbitsize < rnbitsize)
6845 rhs = fold_convert_loc (loc, lntype, rhs);
6846 lr_mask = fold_convert_loc (loc, lntype, lr_mask);
6847 type = lntype;
6851 if (! all_ones_mask_p (ll_mask, ll_bitsize + rl_bitsize))
6852 lhs = build2 (BIT_AND_EXPR, type, lhs, ll_mask);
6854 if (! all_ones_mask_p (lr_mask, lr_bitsize + rr_bitsize))
6855 rhs = build2 (BIT_AND_EXPR, type, rhs, lr_mask);
6857 return build2_loc (loc, wanted_code, truth_type, lhs, rhs);
6860 return 0;
6863 /* Handle the case of comparisons with constants. If there is something in
6864 common between the masks, those bits of the constants must be the same.
6865 If not, the condition is always false. Test for this to avoid generating
6866 incorrect code below. */
6867 result = const_binop (BIT_AND_EXPR, ll_mask, rl_mask);
6868 if (! integer_zerop (result)
6869 && simple_cst_equal (const_binop (BIT_AND_EXPR, result, l_const),
6870 const_binop (BIT_AND_EXPR, result, r_const)) != 1)
6872 if (wanted_code == NE_EXPR)
6874 warning (0, "%<or%> of unmatched not-equal tests is always 1");
6875 return constant_boolean_node (true, truth_type);
6877 else
6879 warning (0, "%<and%> of mutually exclusive equal-tests is always 0");
6880 return constant_boolean_node (false, truth_type);
6884 if (lnbitpos < 0)
6885 return 0;
6887 /* Construct the expression we will return. First get the component
6888 reference we will make. Unless the mask is all ones the width of
6889 that field, perform the mask operation. Then compare with the
6890 merged constant. */
6891 result = make_bit_field_ref (loc, ll_inner, ll_arg,
6892 lntype, lnbitsize, lnbitpos,
6893 ll_unsignedp || rl_unsignedp, ll_reversep);
6895 ll_mask = const_binop (BIT_IOR_EXPR, ll_mask, rl_mask);
6896 if (! all_ones_mask_p (ll_mask, lnbitsize))
6897 result = build2_loc (loc, BIT_AND_EXPR, lntype, result, ll_mask);
6899 return build2_loc (loc, wanted_code, truth_type, result,
6900 const_binop (BIT_IOR_EXPR, l_const, r_const));
6903 /* T is an integer expression that is being multiplied, divided, or taken a
6904 modulus (CODE says which and what kind of divide or modulus) by a
6905 constant C. See if we can eliminate that operation by folding it with
6906 other operations already in T. WIDE_TYPE, if non-null, is a type that
6907 should be used for the computation if wider than our type.
6909 For example, if we are dividing (X * 8) + (Y * 16) by 4, we can return
6910 (X * 2) + (Y * 4). We must, however, be assured that either the original
6911 expression would not overflow or that overflow is undefined for the type
6912 in the language in question.
6914 If we return a non-null expression, it is an equivalent form of the
6915 original computation, but need not be in the original type.
6917 We set *STRICT_OVERFLOW_P to true if the return values depends on
6918 signed overflow being undefined. Otherwise we do not change
6919 *STRICT_OVERFLOW_P. */
6921 static tree
6922 extract_muldiv (tree t, tree c, enum tree_code code, tree wide_type,
6923 bool *strict_overflow_p)
6925 /* To avoid exponential search depth, refuse to allow recursion past
6926 three levels. Beyond that (1) it's highly unlikely that we'll find
6927 something interesting and (2) we've probably processed it before
6928 when we built the inner expression. */
6930 static int depth;
6931 tree ret;
6933 if (depth > 3)
6934 return NULL;
6936 depth++;
6937 ret = extract_muldiv_1 (t, c, code, wide_type, strict_overflow_p);
6938 depth--;
6940 return ret;
6943 static tree
6944 extract_muldiv_1 (tree t, tree c, enum tree_code code, tree wide_type,
6945 bool *strict_overflow_p)
6947 tree type = TREE_TYPE (t);
6948 enum tree_code tcode = TREE_CODE (t);
6949 tree ctype = type;
6950 if (wide_type)
6952 if (TREE_CODE (type) == BITINT_TYPE
6953 || TREE_CODE (wide_type) == BITINT_TYPE)
6955 if (TYPE_PRECISION (wide_type) > TYPE_PRECISION (type))
6956 ctype = wide_type;
6958 else if (GET_MODE_SIZE (SCALAR_INT_TYPE_MODE (wide_type))
6959 > GET_MODE_SIZE (SCALAR_INT_TYPE_MODE (type)))
6960 ctype = wide_type;
6962 tree t1, t2;
6963 bool same_p = tcode == code;
6964 tree op0 = NULL_TREE, op1 = NULL_TREE;
6965 bool sub_strict_overflow_p;
6967 /* Don't deal with constants of zero here; they confuse the code below. */
6968 if (integer_zerop (c))
6969 return NULL_TREE;
6971 if (TREE_CODE_CLASS (tcode) == tcc_unary)
6972 op0 = TREE_OPERAND (t, 0);
6974 if (TREE_CODE_CLASS (tcode) == tcc_binary)
6975 op0 = TREE_OPERAND (t, 0), op1 = TREE_OPERAND (t, 1);
6977 /* Note that we need not handle conditional operations here since fold
6978 already handles those cases. So just do arithmetic here. */
6979 switch (tcode)
6981 case INTEGER_CST:
6982 /* For a constant, we can always simplify if we are a multiply
6983 or (for divide and modulus) if it is a multiple of our constant. */
6984 if (code == MULT_EXPR
6985 || wi::multiple_of_p (wi::to_wide (t), wi::to_wide (c),
6986 TYPE_SIGN (type)))
6988 tree tem = const_binop (code, fold_convert (ctype, t),
6989 fold_convert (ctype, c));
6990 /* If the multiplication overflowed, we lost information on it.
6991 See PR68142 and PR69845. */
6992 if (TREE_OVERFLOW (tem))
6993 return NULL_TREE;
6994 return tem;
6996 break;
6998 CASE_CONVERT: case NON_LVALUE_EXPR:
6999 if (!INTEGRAL_TYPE_P (TREE_TYPE (op0)))
7000 break;
7001 /* If op0 is an expression ... */
7002 if ((COMPARISON_CLASS_P (op0)
7003 || UNARY_CLASS_P (op0)
7004 || BINARY_CLASS_P (op0)
7005 || VL_EXP_CLASS_P (op0)
7006 || EXPRESSION_CLASS_P (op0))
7007 /* ... and has wrapping overflow, and its type is smaller
7008 than ctype, then we cannot pass through as widening. */
7009 && ((TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0))
7010 && (TYPE_PRECISION (ctype)
7011 > TYPE_PRECISION (TREE_TYPE (op0))))
7012 /* ... or this is a truncation (t is narrower than op0),
7013 then we cannot pass through this narrowing. */
7014 || (TYPE_PRECISION (type)
7015 < TYPE_PRECISION (TREE_TYPE (op0)))
7016 /* ... or signedness changes for division or modulus,
7017 then we cannot pass through this conversion. */
7018 || (code != MULT_EXPR
7019 && (TYPE_UNSIGNED (ctype)
7020 != TYPE_UNSIGNED (TREE_TYPE (op0))))
7021 /* ... or has undefined overflow while the converted to
7022 type has not, we cannot do the operation in the inner type
7023 as that would introduce undefined overflow. */
7024 || (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (op0))
7025 && !TYPE_OVERFLOW_UNDEFINED (type))))
7026 break;
7028 /* Pass the constant down and see if we can make a simplification. If
7029 we can, replace this expression with the inner simplification for
7030 possible later conversion to our or some other type. */
7031 if ((t2 = fold_convert (TREE_TYPE (op0), c)) != 0
7032 && TREE_CODE (t2) == INTEGER_CST
7033 && !TREE_OVERFLOW (t2)
7034 && (t1 = extract_muldiv (op0, t2, code,
7035 code == MULT_EXPR ? ctype : NULL_TREE,
7036 strict_overflow_p)) != 0)
7037 return t1;
7038 break;
7040 case ABS_EXPR:
7041 /* If widening the type changes it from signed to unsigned, then we
7042 must avoid building ABS_EXPR itself as unsigned. */
7043 if (TYPE_UNSIGNED (ctype) && !TYPE_UNSIGNED (type))
7045 tree cstype = (*signed_type_for) (ctype);
7046 if ((t1 = extract_muldiv (op0, c, code, cstype, strict_overflow_p))
7047 != 0)
7049 t1 = fold_build1 (tcode, cstype, fold_convert (cstype, t1));
7050 return fold_convert (ctype, t1);
7052 break;
7054 /* If the constant is negative, we cannot simplify this. */
7055 if (tree_int_cst_sgn (c) == -1)
7056 break;
7057 /* FALLTHROUGH */
7058 case NEGATE_EXPR:
7059 /* For division and modulus, type can't be unsigned, as e.g.
7060 (-(x / 2U)) / 2U isn't equal to -((x / 2U) / 2U) for x >= 2.
7061 For signed types, even with wrapping overflow, this is fine. */
7062 if (code != MULT_EXPR && TYPE_UNSIGNED (type))
7063 break;
7064 if ((t1 = extract_muldiv (op0, c, code, wide_type, strict_overflow_p))
7065 != 0)
7066 return fold_build1 (tcode, ctype, fold_convert (ctype, t1));
7067 break;
7069 case MIN_EXPR: case MAX_EXPR:
7070 /* If widening the type changes the signedness, then we can't perform
7071 this optimization as that changes the result. */
7072 if (TYPE_UNSIGNED (ctype) != TYPE_UNSIGNED (type))
7073 break;
7075 /* MIN (a, b) / 5 -> MIN (a / 5, b / 5) */
7076 sub_strict_overflow_p = false;
7077 if ((t1 = extract_muldiv (op0, c, code, wide_type,
7078 &sub_strict_overflow_p)) != 0
7079 && (t2 = extract_muldiv (op1, c, code, wide_type,
7080 &sub_strict_overflow_p)) != 0)
7082 if (tree_int_cst_sgn (c) < 0)
7083 tcode = (tcode == MIN_EXPR ? MAX_EXPR : MIN_EXPR);
7084 if (sub_strict_overflow_p)
7085 *strict_overflow_p = true;
7086 return fold_build2 (tcode, ctype, fold_convert (ctype, t1),
7087 fold_convert (ctype, t2));
7089 break;
7091 case LSHIFT_EXPR: case RSHIFT_EXPR:
7092 /* If the second operand is constant, this is a multiplication
7093 or floor division, by a power of two, so we can treat it that
7094 way unless the multiplier or divisor overflows. Signed
7095 left-shift overflow is implementation-defined rather than
7096 undefined in C90, so do not convert signed left shift into
7097 multiplication. */
7098 if (TREE_CODE (op1) == INTEGER_CST
7099 && (tcode == RSHIFT_EXPR || TYPE_UNSIGNED (TREE_TYPE (op0)))
7100 /* const_binop may not detect overflow correctly,
7101 so check for it explicitly here. */
7102 && wi::gtu_p (TYPE_PRECISION (TREE_TYPE (size_one_node)),
7103 wi::to_wide (op1))
7104 && (t1 = fold_convert (ctype,
7105 const_binop (LSHIFT_EXPR, size_one_node,
7106 op1))) != 0
7107 && !TREE_OVERFLOW (t1))
7108 return extract_muldiv (build2 (tcode == LSHIFT_EXPR
7109 ? MULT_EXPR : FLOOR_DIV_EXPR,
7110 ctype,
7111 fold_convert (ctype, op0),
7112 t1),
7113 c, code, wide_type, strict_overflow_p);
7114 break;
7116 case PLUS_EXPR: case MINUS_EXPR:
7117 /* See if we can eliminate the operation on both sides. If we can, we
7118 can return a new PLUS or MINUS. If we can't, the only remaining
7119 cases where we can do anything are if the second operand is a
7120 constant. */
7121 sub_strict_overflow_p = false;
7122 t1 = extract_muldiv (op0, c, code, wide_type, &sub_strict_overflow_p);
7123 t2 = extract_muldiv (op1, c, code, wide_type, &sub_strict_overflow_p);
7124 if (t1 != 0 && t2 != 0
7125 && TYPE_OVERFLOW_WRAPS (ctype)
7126 && (code == MULT_EXPR
7127 /* If not multiplication, we can only do this if both operands
7128 are divisible by c. */
7129 || (multiple_of_p (ctype, op0, c)
7130 && multiple_of_p (ctype, op1, c))))
7132 if (sub_strict_overflow_p)
7133 *strict_overflow_p = true;
7134 return fold_build2 (tcode, ctype, fold_convert (ctype, t1),
7135 fold_convert (ctype, t2));
7138 /* If this was a subtraction, negate OP1 and set it to be an addition.
7139 This simplifies the logic below. */
7140 if (tcode == MINUS_EXPR)
7142 tcode = PLUS_EXPR, op1 = negate_expr (op1);
7143 /* If OP1 was not easily negatable, the constant may be OP0. */
7144 if (TREE_CODE (op0) == INTEGER_CST)
7146 std::swap (op0, op1);
7147 std::swap (t1, t2);
7151 if (TREE_CODE (op1) != INTEGER_CST)
7152 break;
7154 /* If either OP1 or C are negative, this optimization is not safe for
7155 some of the division and remainder types while for others we need
7156 to change the code. */
7157 if (tree_int_cst_sgn (op1) < 0 || tree_int_cst_sgn (c) < 0)
7159 if (code == CEIL_DIV_EXPR)
7160 code = FLOOR_DIV_EXPR;
7161 else if (code == FLOOR_DIV_EXPR)
7162 code = CEIL_DIV_EXPR;
7163 else if (code != MULT_EXPR
7164 && code != CEIL_MOD_EXPR && code != FLOOR_MOD_EXPR)
7165 break;
7168 /* If it's a multiply or a division/modulus operation of a multiple
7169 of our constant, do the operation and verify it doesn't overflow. */
7170 if (code == MULT_EXPR
7171 || wi::multiple_of_p (wi::to_wide (op1), wi::to_wide (c),
7172 TYPE_SIGN (type)))
7174 op1 = const_binop (code, fold_convert (ctype, op1),
7175 fold_convert (ctype, c));
7176 /* We allow the constant to overflow with wrapping semantics. */
7177 if (op1 == 0
7178 || (TREE_OVERFLOW (op1) && !TYPE_OVERFLOW_WRAPS (ctype)))
7179 break;
7181 else
7182 break;
7184 /* If we have an unsigned type, we cannot widen the operation since it
7185 will change the result if the original computation overflowed. */
7186 if (TYPE_UNSIGNED (ctype) && ctype != type)
7187 break;
7189 /* The last case is if we are a multiply. In that case, we can
7190 apply the distributive law to commute the multiply and addition
7191 if the multiplication of the constants doesn't overflow
7192 and overflow is defined. With undefined overflow
7193 op0 * c might overflow, while (op0 + orig_op1) * c doesn't.
7194 But fold_plusminus_mult_expr would factor back any power-of-two
7195 value so do not distribute in the first place in this case. */
7196 if (code == MULT_EXPR
7197 && TYPE_OVERFLOW_WRAPS (ctype)
7198 && !(tree_fits_shwi_p (c) && pow2p_hwi (absu_hwi (tree_to_shwi (c)))))
7199 return fold_build2 (tcode, ctype,
7200 fold_build2 (code, ctype,
7201 fold_convert (ctype, op0),
7202 fold_convert (ctype, c)),
7203 op1);
7205 break;
7207 case MULT_EXPR:
7208 /* We have a special case here if we are doing something like
7209 (C * 8) % 4 since we know that's zero. */
7210 if ((code == TRUNC_MOD_EXPR || code == CEIL_MOD_EXPR
7211 || code == FLOOR_MOD_EXPR || code == ROUND_MOD_EXPR)
7212 /* If the multiplication can overflow we cannot optimize this. */
7213 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (t))
7214 && TREE_CODE (TREE_OPERAND (t, 1)) == INTEGER_CST
7215 && wi::multiple_of_p (wi::to_wide (op1), wi::to_wide (c),
7216 TYPE_SIGN (type)))
7218 *strict_overflow_p = true;
7219 return omit_one_operand (type, integer_zero_node, op0);
7222 /* ... fall through ... */
7224 case TRUNC_DIV_EXPR: case CEIL_DIV_EXPR: case FLOOR_DIV_EXPR:
7225 case ROUND_DIV_EXPR: case EXACT_DIV_EXPR:
7226 /* If we can extract our operation from the LHS, do so and return a
7227 new operation. Likewise for the RHS from a MULT_EXPR. Otherwise,
7228 do something only if the second operand is a constant. */
7229 if (same_p
7230 && TYPE_OVERFLOW_WRAPS (ctype)
7231 && (t1 = extract_muldiv (op0, c, code, wide_type,
7232 strict_overflow_p)) != 0)
7233 return fold_build2 (tcode, ctype, fold_convert (ctype, t1),
7234 fold_convert (ctype, op1));
7235 else if (tcode == MULT_EXPR && code == MULT_EXPR
7236 && TYPE_OVERFLOW_WRAPS (ctype)
7237 && (t1 = extract_muldiv (op1, c, code, wide_type,
7238 strict_overflow_p)) != 0)
7239 return fold_build2 (tcode, ctype, fold_convert (ctype, op0),
7240 fold_convert (ctype, t1));
7241 else if (TREE_CODE (op1) != INTEGER_CST)
7242 return 0;
7244 /* If these are the same operation types, we can associate them
7245 assuming no overflow. */
7246 if (tcode == code)
7248 bool overflow_p = false;
7249 wi::overflow_type overflow_mul;
7250 signop sign = TYPE_SIGN (ctype);
7251 unsigned prec = TYPE_PRECISION (ctype);
7252 wide_int mul = wi::mul (wi::to_wide (op1, prec),
7253 wi::to_wide (c, prec),
7254 sign, &overflow_mul);
7255 overflow_p = TREE_OVERFLOW (c) | TREE_OVERFLOW (op1);
7256 if (overflow_mul
7257 && ((sign == UNSIGNED && tcode != MULT_EXPR) || sign == SIGNED))
7258 overflow_p = true;
7259 if (!overflow_p)
7260 return fold_build2 (tcode, ctype, fold_convert (ctype, op0),
7261 wide_int_to_tree (ctype, mul));
7264 /* If these operations "cancel" each other, we have the main
7265 optimizations of this pass, which occur when either constant is a
7266 multiple of the other, in which case we replace this with either an
7267 operation or CODE or TCODE.
7269 If we have an unsigned type, we cannot do this since it will change
7270 the result if the original computation overflowed. */
7271 if (TYPE_OVERFLOW_UNDEFINED (ctype)
7272 && !TYPE_OVERFLOW_SANITIZED (ctype)
7273 && ((code == MULT_EXPR && tcode == EXACT_DIV_EXPR)
7274 || (tcode == MULT_EXPR
7275 && code != TRUNC_MOD_EXPR && code != CEIL_MOD_EXPR
7276 && code != FLOOR_MOD_EXPR && code != ROUND_MOD_EXPR
7277 && code != MULT_EXPR)))
7279 if (wi::multiple_of_p (wi::to_wide (op1), wi::to_wide (c),
7280 TYPE_SIGN (type)))
7282 *strict_overflow_p = true;
7283 return fold_build2 (tcode, ctype, fold_convert (ctype, op0),
7284 fold_convert (ctype,
7285 const_binop (TRUNC_DIV_EXPR,
7286 op1, c)));
7288 else if (wi::multiple_of_p (wi::to_wide (c), wi::to_wide (op1),
7289 TYPE_SIGN (type)))
7291 *strict_overflow_p = true;
7292 return fold_build2 (code, ctype, fold_convert (ctype, op0),
7293 fold_convert (ctype,
7294 const_binop (TRUNC_DIV_EXPR,
7295 c, op1)));
7298 break;
7300 default:
7301 break;
7304 return 0;
7307 /* Return a node which has the indicated constant VALUE (either 0 or
7308 1 for scalars or {-1,-1,..} or {0,0,...} for vectors),
7309 and is of the indicated TYPE. */
7311 tree
7312 constant_boolean_node (bool value, tree type)
7314 if (type == integer_type_node)
7315 return value ? integer_one_node : integer_zero_node;
7316 else if (type == boolean_type_node)
7317 return value ? boolean_true_node : boolean_false_node;
7318 else if (VECTOR_TYPE_P (type))
7319 return build_vector_from_val (type,
7320 build_int_cst (TREE_TYPE (type),
7321 value ? -1 : 0));
7322 else
7323 return fold_convert (type, value ? integer_one_node : integer_zero_node);
7327 /* Transform `a + (b ? x : y)' into `b ? (a + x) : (a + y)'.
7328 Transform, `a + (x < y)' into `(x < y) ? (a + 1) : (a + 0)'. Here
7329 CODE corresponds to the `+', COND to the `(b ? x : y)' or `(x < y)'
7330 expression, and ARG to `a'. If COND_FIRST_P is nonzero, then the
7331 COND is the first argument to CODE; otherwise (as in the example
7332 given here), it is the second argument. TYPE is the type of the
7333 original expression. Return NULL_TREE if no simplification is
7334 possible. */
7336 static tree
7337 fold_binary_op_with_conditional_arg (location_t loc,
7338 enum tree_code code,
7339 tree type, tree op0, tree op1,
7340 tree cond, tree arg, int cond_first_p)
7342 tree cond_type = cond_first_p ? TREE_TYPE (op0) : TREE_TYPE (op1);
7343 tree arg_type = cond_first_p ? TREE_TYPE (op1) : TREE_TYPE (op0);
7344 tree test, true_value, false_value;
7345 tree lhs = NULL_TREE;
7346 tree rhs = NULL_TREE;
7347 enum tree_code cond_code = COND_EXPR;
7349 /* Do not move possibly trapping operations into the conditional as this
7350 pessimizes code and causes gimplification issues when applied late. */
7351 if (operation_could_trap_p (code, FLOAT_TYPE_P (type),
7352 ANY_INTEGRAL_TYPE_P (type)
7353 && TYPE_OVERFLOW_TRAPS (type), op1))
7354 return NULL_TREE;
7356 if (TREE_CODE (cond) == COND_EXPR
7357 || TREE_CODE (cond) == VEC_COND_EXPR)
7359 test = TREE_OPERAND (cond, 0);
7360 true_value = TREE_OPERAND (cond, 1);
7361 false_value = TREE_OPERAND (cond, 2);
7362 /* If this operand throws an expression, then it does not make
7363 sense to try to perform a logical or arithmetic operation
7364 involving it. */
7365 if (VOID_TYPE_P (TREE_TYPE (true_value)))
7366 lhs = true_value;
7367 if (VOID_TYPE_P (TREE_TYPE (false_value)))
7368 rhs = false_value;
7370 else if (!(TREE_CODE (type) != VECTOR_TYPE
7371 && VECTOR_TYPE_P (TREE_TYPE (cond))))
7373 tree testtype = TREE_TYPE (cond);
7374 test = cond;
7375 true_value = constant_boolean_node (true, testtype);
7376 false_value = constant_boolean_node (false, testtype);
7378 else
7379 /* Detect the case of mixing vector and scalar types - bail out. */
7380 return NULL_TREE;
7382 if (VECTOR_TYPE_P (TREE_TYPE (test)))
7383 cond_code = VEC_COND_EXPR;
7385 /* This transformation is only worthwhile if we don't have to wrap ARG
7386 in a SAVE_EXPR and the operation can be simplified without recursing
7387 on at least one of the branches once its pushed inside the COND_EXPR. */
7388 if (!TREE_CONSTANT (arg)
7389 && (TREE_SIDE_EFFECTS (arg)
7390 || TREE_CODE (arg) == COND_EXPR || TREE_CODE (arg) == VEC_COND_EXPR
7391 || TREE_CONSTANT (true_value) || TREE_CONSTANT (false_value)))
7392 return NULL_TREE;
7394 arg = fold_convert_loc (loc, arg_type, arg);
7395 if (lhs == 0)
7397 true_value = fold_convert_loc (loc, cond_type, true_value);
7398 if (cond_first_p)
7399 lhs = fold_build2_loc (loc, code, type, true_value, arg);
7400 else
7401 lhs = fold_build2_loc (loc, code, type, arg, true_value);
7403 if (rhs == 0)
7405 false_value = fold_convert_loc (loc, cond_type, false_value);
7406 if (cond_first_p)
7407 rhs = fold_build2_loc (loc, code, type, false_value, arg);
7408 else
7409 rhs = fold_build2_loc (loc, code, type, arg, false_value);
7412 /* Check that we have simplified at least one of the branches. */
7413 if (!TREE_CONSTANT (arg) && !TREE_CONSTANT (lhs) && !TREE_CONSTANT (rhs))
7414 return NULL_TREE;
7416 return fold_build3_loc (loc, cond_code, type, test, lhs, rhs);
7420 /* Subroutine of fold() that checks for the addition of ARG +/- 0.0.
7422 If !NEGATE, return true if ZERO_ARG is +/-0.0 and, for all ARG of
7423 type TYPE, ARG + ZERO_ARG is the same as ARG. If NEGATE, return true
7424 if ARG - ZERO_ARG is the same as X.
7426 If ARG is NULL, check for any value of type TYPE.
7428 X + 0 and X - 0 both give X when X is NaN, infinite, or nonzero
7429 and finite. The problematic cases are when X is zero, and its mode
7430 has signed zeros. In the case of rounding towards -infinity,
7431 X - 0 is not the same as X because 0 - 0 is -0. In other rounding
7432 modes, X + 0 is not the same as X because -0 + 0 is 0. */
7434 bool
7435 fold_real_zero_addition_p (const_tree type, const_tree arg,
7436 const_tree zero_arg, int negate)
7438 if (!real_zerop (zero_arg))
7439 return false;
7441 /* Don't allow the fold with -fsignaling-nans. */
7442 if (arg ? tree_expr_maybe_signaling_nan_p (arg) : HONOR_SNANS (type))
7443 return false;
7445 /* Allow the fold if zeros aren't signed, or their sign isn't important. */
7446 if (!HONOR_SIGNED_ZEROS (type))
7447 return true;
7449 /* There is no case that is safe for all rounding modes. */
7450 if (HONOR_SIGN_DEPENDENT_ROUNDING (type))
7451 return false;
7453 /* In a vector or complex, we would need to check the sign of all zeros. */
7454 if (TREE_CODE (zero_arg) == VECTOR_CST)
7455 zero_arg = uniform_vector_p (zero_arg);
7456 if (!zero_arg || TREE_CODE (zero_arg) != REAL_CST)
7457 return false;
7459 /* Treat x + -0 as x - 0 and x - -0 as x + 0. */
7460 if (REAL_VALUE_MINUS_ZERO (TREE_REAL_CST (zero_arg)))
7461 negate = !negate;
7463 /* The mode has signed zeros, and we have to honor their sign.
7464 In this situation, there are only two cases we can return true for.
7465 (i) X - 0 is the same as X with default rounding.
7466 (ii) X + 0 is X when X can't possibly be -0.0. */
7467 return negate || (arg && !tree_expr_maybe_real_minus_zero_p (arg));
7470 /* Subroutine of match.pd that optimizes comparisons of a division by
7471 a nonzero integer constant against an integer constant, i.e.
7472 X/C1 op C2.
7474 CODE is the comparison operator: EQ_EXPR, NE_EXPR, GT_EXPR, LT_EXPR,
7475 GE_EXPR or LE_EXPR. ARG01 and ARG1 must be a INTEGER_CST. */
7477 enum tree_code
7478 fold_div_compare (enum tree_code code, tree c1, tree c2, tree *lo,
7479 tree *hi, bool *neg_overflow)
7481 tree prod, tmp, type = TREE_TYPE (c1);
7482 signop sign = TYPE_SIGN (type);
7483 wi::overflow_type overflow;
7485 /* We have to do this the hard way to detect unsigned overflow.
7486 prod = int_const_binop (MULT_EXPR, c1, c2); */
7487 wide_int val = wi::mul (wi::to_wide (c1), wi::to_wide (c2), sign, &overflow);
7488 prod = force_fit_type (type, val, -1, overflow);
7489 *neg_overflow = false;
7491 if (sign == UNSIGNED)
7493 tmp = int_const_binop (MINUS_EXPR, c1, build_int_cst (type, 1));
7494 *lo = prod;
7496 /* Likewise *hi = int_const_binop (PLUS_EXPR, prod, tmp). */
7497 val = wi::add (wi::to_wide (prod), wi::to_wide (tmp), sign, &overflow);
7498 *hi = force_fit_type (type, val, -1, overflow | TREE_OVERFLOW (prod));
7500 else if (tree_int_cst_sgn (c1) >= 0)
7502 tmp = int_const_binop (MINUS_EXPR, c1, build_int_cst (type, 1));
7503 switch (tree_int_cst_sgn (c2))
7505 case -1:
7506 *neg_overflow = true;
7507 *lo = int_const_binop (MINUS_EXPR, prod, tmp);
7508 *hi = prod;
7509 break;
7511 case 0:
7512 *lo = fold_negate_const (tmp, type);
7513 *hi = tmp;
7514 break;
7516 case 1:
7517 *hi = int_const_binop (PLUS_EXPR, prod, tmp);
7518 *lo = prod;
7519 break;
7521 default:
7522 gcc_unreachable ();
7525 else
7527 /* A negative divisor reverses the relational operators. */
7528 code = swap_tree_comparison (code);
7530 tmp = int_const_binop (PLUS_EXPR, c1, build_int_cst (type, 1));
7531 switch (tree_int_cst_sgn (c2))
7533 case -1:
7534 *hi = int_const_binop (MINUS_EXPR, prod, tmp);
7535 *lo = prod;
7536 break;
7538 case 0:
7539 *hi = fold_negate_const (tmp, type);
7540 *lo = tmp;
7541 break;
7543 case 1:
7544 *neg_overflow = true;
7545 *lo = int_const_binop (PLUS_EXPR, prod, tmp);
7546 *hi = prod;
7547 break;
7549 default:
7550 gcc_unreachable ();
7554 if (code != EQ_EXPR && code != NE_EXPR)
7555 return code;
7557 if (TREE_OVERFLOW (*lo)
7558 || operand_equal_p (*lo, TYPE_MIN_VALUE (type), 0))
7559 *lo = NULL_TREE;
7560 if (TREE_OVERFLOW (*hi)
7561 || operand_equal_p (*hi, TYPE_MAX_VALUE (type), 0))
7562 *hi = NULL_TREE;
7564 return code;
7567 /* Test whether it is preferable to swap two operands, ARG0 and
7568 ARG1, for example because ARG0 is an integer constant and ARG1
7569 isn't. */
7571 bool
7572 tree_swap_operands_p (const_tree arg0, const_tree arg1)
7574 if (CONSTANT_CLASS_P (arg1))
7575 return false;
7576 if (CONSTANT_CLASS_P (arg0))
7577 return true;
7579 STRIP_NOPS (arg0);
7580 STRIP_NOPS (arg1);
7582 if (TREE_CONSTANT (arg1))
7583 return false;
7584 if (TREE_CONSTANT (arg0))
7585 return true;
7587 /* It is preferable to swap two SSA_NAME to ensure a canonical form
7588 for commutative and comparison operators. Ensuring a canonical
7589 form allows the optimizers to find additional redundancies without
7590 having to explicitly check for both orderings. */
7591 if (TREE_CODE (arg0) == SSA_NAME
7592 && TREE_CODE (arg1) == SSA_NAME
7593 && SSA_NAME_VERSION (arg0) > SSA_NAME_VERSION (arg1))
7594 return true;
7596 /* Put SSA_NAMEs last. */
7597 if (TREE_CODE (arg1) == SSA_NAME)
7598 return false;
7599 if (TREE_CODE (arg0) == SSA_NAME)
7600 return true;
7602 /* Put variables last. */
7603 if (DECL_P (arg1))
7604 return false;
7605 if (DECL_P (arg0))
7606 return true;
7608 return false;
7612 /* Fold A < X && A + 1 > Y to A < X && A >= Y. Normally A + 1 > Y
7613 means A >= Y && A != MAX, but in this case we know that
7614 A < X <= MAX. INEQ is A + 1 > Y, BOUND is A < X. */
7616 static tree
7617 fold_to_nonsharp_ineq_using_bound (location_t loc, tree ineq, tree bound)
7619 tree a, typea, type = TREE_TYPE (bound), a1, diff, y;
7621 if (TREE_CODE (bound) == LT_EXPR)
7622 a = TREE_OPERAND (bound, 0);
7623 else if (TREE_CODE (bound) == GT_EXPR)
7624 a = TREE_OPERAND (bound, 1);
7625 else
7626 return NULL_TREE;
7628 typea = TREE_TYPE (a);
7629 if (!INTEGRAL_TYPE_P (typea)
7630 && !POINTER_TYPE_P (typea))
7631 return NULL_TREE;
7633 if (TREE_CODE (ineq) == LT_EXPR)
7635 a1 = TREE_OPERAND (ineq, 1);
7636 y = TREE_OPERAND (ineq, 0);
7638 else if (TREE_CODE (ineq) == GT_EXPR)
7640 a1 = TREE_OPERAND (ineq, 0);
7641 y = TREE_OPERAND (ineq, 1);
7643 else
7644 return NULL_TREE;
7646 if (TREE_TYPE (a1) != typea)
7647 return NULL_TREE;
7649 if (POINTER_TYPE_P (typea))
7651 /* Convert the pointer types into integer before taking the difference. */
7652 tree ta = fold_convert_loc (loc, ssizetype, a);
7653 tree ta1 = fold_convert_loc (loc, ssizetype, a1);
7654 diff = fold_binary_loc (loc, MINUS_EXPR, ssizetype, ta1, ta);
7656 else
7657 diff = fold_binary_loc (loc, MINUS_EXPR, typea, a1, a);
7659 if (!diff || !integer_onep (diff))
7660 return NULL_TREE;
7662 return fold_build2_loc (loc, GE_EXPR, type, a, y);
7665 /* Fold a sum or difference of at least one multiplication.
7666 Returns the folded tree or NULL if no simplification could be made. */
7668 static tree
7669 fold_plusminus_mult_expr (location_t loc, enum tree_code code, tree type,
7670 tree arg0, tree arg1)
7672 tree arg00, arg01, arg10, arg11;
7673 tree alt0 = NULL_TREE, alt1 = NULL_TREE, same;
7675 /* (A * C) +- (B * C) -> (A+-B) * C.
7676 (A * C) +- A -> A * (C+-1).
7677 We are most concerned about the case where C is a constant,
7678 but other combinations show up during loop reduction. Since
7679 it is not difficult, try all four possibilities. */
7681 if (TREE_CODE (arg0) == MULT_EXPR)
7683 arg00 = TREE_OPERAND (arg0, 0);
7684 arg01 = TREE_OPERAND (arg0, 1);
7686 else if (TREE_CODE (arg0) == INTEGER_CST)
7688 arg00 = build_one_cst (type);
7689 arg01 = arg0;
7691 else
7693 /* We cannot generate constant 1 for fract. */
7694 if (ALL_FRACT_MODE_P (TYPE_MODE (type)))
7695 return NULL_TREE;
7696 arg00 = arg0;
7697 arg01 = build_one_cst (type);
7699 if (TREE_CODE (arg1) == MULT_EXPR)
7701 arg10 = TREE_OPERAND (arg1, 0);
7702 arg11 = TREE_OPERAND (arg1, 1);
7704 else if (TREE_CODE (arg1) == INTEGER_CST)
7706 arg10 = build_one_cst (type);
7707 /* As we canonicalize A - 2 to A + -2 get rid of that sign for
7708 the purpose of this canonicalization. */
7709 if (wi::neg_p (wi::to_wide (arg1), TYPE_SIGN (TREE_TYPE (arg1)))
7710 && negate_expr_p (arg1)
7711 && code == PLUS_EXPR)
7713 arg11 = negate_expr (arg1);
7714 code = MINUS_EXPR;
7716 else
7717 arg11 = arg1;
7719 else
7721 /* We cannot generate constant 1 for fract. */
7722 if (ALL_FRACT_MODE_P (TYPE_MODE (type)))
7723 return NULL_TREE;
7724 arg10 = arg1;
7725 arg11 = build_one_cst (type);
7727 same = NULL_TREE;
7729 /* Prefer factoring a common non-constant. */
7730 if (operand_equal_p (arg00, arg10, 0))
7731 same = arg00, alt0 = arg01, alt1 = arg11;
7732 else if (operand_equal_p (arg01, arg11, 0))
7733 same = arg01, alt0 = arg00, alt1 = arg10;
7734 else if (operand_equal_p (arg00, arg11, 0))
7735 same = arg00, alt0 = arg01, alt1 = arg10;
7736 else if (operand_equal_p (arg01, arg10, 0))
7737 same = arg01, alt0 = arg00, alt1 = arg11;
7739 /* No identical multiplicands; see if we can find a common
7740 power-of-two factor in non-power-of-two multiplies. This
7741 can help in multi-dimensional array access. */
7742 else if (tree_fits_shwi_p (arg01) && tree_fits_shwi_p (arg11))
7744 HOST_WIDE_INT int01 = tree_to_shwi (arg01);
7745 HOST_WIDE_INT int11 = tree_to_shwi (arg11);
7746 HOST_WIDE_INT tmp;
7747 bool swap = false;
7748 tree maybe_same;
7750 /* Move min of absolute values to int11. */
7751 if (absu_hwi (int01) < absu_hwi (int11))
7753 tmp = int01, int01 = int11, int11 = tmp;
7754 alt0 = arg00, arg00 = arg10, arg10 = alt0;
7755 maybe_same = arg01;
7756 swap = true;
7758 else
7759 maybe_same = arg11;
7761 const unsigned HOST_WIDE_INT factor = absu_hwi (int11);
7762 if (factor > 1
7763 && pow2p_hwi (factor)
7764 && (int01 & (factor - 1)) == 0
7765 /* The remainder should not be a constant, otherwise we
7766 end up folding i * 4 + 2 to (i * 2 + 1) * 2 which has
7767 increased the number of multiplications necessary. */
7768 && TREE_CODE (arg10) != INTEGER_CST)
7770 alt0 = fold_build2_loc (loc, MULT_EXPR, TREE_TYPE (arg00), arg00,
7771 build_int_cst (TREE_TYPE (arg00),
7772 int01 / int11));
7773 alt1 = arg10;
7774 same = maybe_same;
7775 if (swap)
7776 maybe_same = alt0, alt0 = alt1, alt1 = maybe_same;
7780 if (!same)
7781 return NULL_TREE;
7783 if (! ANY_INTEGRAL_TYPE_P (type)
7784 || TYPE_OVERFLOW_WRAPS (type)
7785 /* We are neither factoring zero nor minus one. */
7786 || TREE_CODE (same) == INTEGER_CST)
7787 return fold_build2_loc (loc, MULT_EXPR, type,
7788 fold_build2_loc (loc, code, type,
7789 fold_convert_loc (loc, type, alt0),
7790 fold_convert_loc (loc, type, alt1)),
7791 fold_convert_loc (loc, type, same));
7793 /* Same may be zero and thus the operation 'code' may overflow. Likewise
7794 same may be minus one and thus the multiplication may overflow. Perform
7795 the sum operation in an unsigned type. */
7796 tree utype = unsigned_type_for (type);
7797 tree tem = fold_build2_loc (loc, code, utype,
7798 fold_convert_loc (loc, utype, alt0),
7799 fold_convert_loc (loc, utype, alt1));
7800 /* If the sum evaluated to a constant that is not -INF the multiplication
7801 cannot overflow. */
7802 if (TREE_CODE (tem) == INTEGER_CST
7803 && (wi::to_wide (tem)
7804 != wi::min_value (TYPE_PRECISION (utype), SIGNED)))
7805 return fold_build2_loc (loc, MULT_EXPR, type,
7806 fold_convert (type, tem), same);
7808 /* Do not resort to unsigned multiplication because
7809 we lose the no-overflow property of the expression. */
7810 return NULL_TREE;
7813 /* Subroutine of native_encode_expr. Encode the INTEGER_CST
7814 specified by EXPR into the buffer PTR of length LEN bytes.
7815 Return the number of bytes placed in the buffer, or zero
7816 upon failure. */
7818 static int
7819 native_encode_int (const_tree expr, unsigned char *ptr, int len, int off)
7821 tree type = TREE_TYPE (expr);
7822 int total_bytes;
7823 if (TREE_CODE (type) == BITINT_TYPE)
7825 struct bitint_info info;
7826 bool ok = targetm.c.bitint_type_info (TYPE_PRECISION (type), &info);
7827 gcc_assert (ok);
7828 scalar_int_mode limb_mode = as_a <scalar_int_mode> (info.limb_mode);
7829 if (TYPE_PRECISION (type) > GET_MODE_PRECISION (limb_mode))
7831 total_bytes = tree_to_uhwi (TYPE_SIZE_UNIT (type));
7832 /* More work is needed when adding _BitInt support to PDP endian
7833 if limb is smaller than word, or if _BitInt limb ordering doesn't
7834 match target endianity here. */
7835 gcc_checking_assert (info.big_endian == WORDS_BIG_ENDIAN
7836 && (BYTES_BIG_ENDIAN == WORDS_BIG_ENDIAN
7837 || (GET_MODE_SIZE (limb_mode)
7838 >= UNITS_PER_WORD)));
7840 else
7841 total_bytes = GET_MODE_SIZE (SCALAR_INT_TYPE_MODE (type));
7843 else
7844 total_bytes = GET_MODE_SIZE (SCALAR_INT_TYPE_MODE (type));
7845 int byte, offset, word, words;
7846 unsigned char value;
7848 if ((off == -1 && total_bytes > len) || off >= total_bytes)
7849 return 0;
7850 if (off == -1)
7851 off = 0;
7853 if (ptr == NULL)
7854 /* Dry run. */
7855 return MIN (len, total_bytes - off);
7857 words = total_bytes / UNITS_PER_WORD;
7859 for (byte = 0; byte < total_bytes; byte++)
7861 int bitpos = byte * BITS_PER_UNIT;
7862 /* Extend EXPR according to TYPE_SIGN if the precision isn't a whole
7863 number of bytes. */
7864 value = wi::extract_uhwi (wi::to_widest (expr), bitpos, BITS_PER_UNIT);
7866 if (total_bytes > UNITS_PER_WORD)
7868 word = byte / UNITS_PER_WORD;
7869 if (WORDS_BIG_ENDIAN)
7870 word = (words - 1) - word;
7871 offset = word * UNITS_PER_WORD;
7872 if (BYTES_BIG_ENDIAN)
7873 offset += (UNITS_PER_WORD - 1) - (byte % UNITS_PER_WORD);
7874 else
7875 offset += byte % UNITS_PER_WORD;
7877 else
7878 offset = BYTES_BIG_ENDIAN ? (total_bytes - 1) - byte : byte;
7879 if (offset >= off && offset - off < len)
7880 ptr[offset - off] = value;
7882 return MIN (len, total_bytes - off);
7886 /* Subroutine of native_encode_expr. Encode the FIXED_CST
7887 specified by EXPR into the buffer PTR of length LEN bytes.
7888 Return the number of bytes placed in the buffer, or zero
7889 upon failure. */
7891 static int
7892 native_encode_fixed (const_tree expr, unsigned char *ptr, int len, int off)
7894 tree type = TREE_TYPE (expr);
7895 scalar_mode mode = SCALAR_TYPE_MODE (type);
7896 int total_bytes = GET_MODE_SIZE (mode);
7897 FIXED_VALUE_TYPE value;
7898 tree i_value, i_type;
7900 if (total_bytes * BITS_PER_UNIT > HOST_BITS_PER_DOUBLE_INT)
7901 return 0;
7903 i_type = lang_hooks.types.type_for_size (GET_MODE_BITSIZE (mode), 1);
7905 if (NULL_TREE == i_type || TYPE_PRECISION (i_type) != total_bytes)
7906 return 0;
7908 value = TREE_FIXED_CST (expr);
7909 i_value = double_int_to_tree (i_type, value.data);
7911 return native_encode_int (i_value, ptr, len, off);
7915 /* Subroutine of native_encode_expr. Encode the REAL_CST
7916 specified by EXPR into the buffer PTR of length LEN bytes.
7917 Return the number of bytes placed in the buffer, or zero
7918 upon failure. */
7920 static int
7921 native_encode_real (const_tree expr, unsigned char *ptr, int len, int off)
7923 tree type = TREE_TYPE (expr);
7924 int total_bytes = GET_MODE_SIZE (SCALAR_FLOAT_TYPE_MODE (type));
7925 int byte, offset, word, words, bitpos;
7926 unsigned char value;
7928 /* There are always 32 bits in each long, no matter the size of
7929 the hosts long. We handle floating point representations with
7930 up to 192 bits. */
7931 long tmp[6];
7933 if ((off == -1 && total_bytes > len) || off >= total_bytes)
7934 return 0;
7935 if (off == -1)
7936 off = 0;
7938 if (ptr == NULL)
7939 /* Dry run. */
7940 return MIN (len, total_bytes - off);
7942 words = (32 / BITS_PER_UNIT) / UNITS_PER_WORD;
7944 real_to_target (tmp, TREE_REAL_CST_PTR (expr), TYPE_MODE (type));
7946 for (bitpos = 0; bitpos < total_bytes * BITS_PER_UNIT;
7947 bitpos += BITS_PER_UNIT)
7949 byte = (bitpos / BITS_PER_UNIT) & 3;
7950 value = (unsigned char) (tmp[bitpos / 32] >> (bitpos & 31));
7952 if (UNITS_PER_WORD < 4)
7954 word = byte / UNITS_PER_WORD;
7955 if (WORDS_BIG_ENDIAN)
7956 word = (words - 1) - word;
7957 offset = word * UNITS_PER_WORD;
7958 if (BYTES_BIG_ENDIAN)
7959 offset += (UNITS_PER_WORD - 1) - (byte % UNITS_PER_WORD);
7960 else
7961 offset += byte % UNITS_PER_WORD;
7963 else
7965 offset = byte;
7966 if (BYTES_BIG_ENDIAN)
7968 /* Reverse bytes within each long, or within the entire float
7969 if it's smaller than a long (for HFmode). */
7970 offset = MIN (3, total_bytes - 1) - offset;
7971 gcc_assert (offset >= 0);
7974 offset = offset + ((bitpos / BITS_PER_UNIT) & ~3);
7975 if (offset >= off
7976 && offset - off < len)
7977 ptr[offset - off] = value;
7979 return MIN (len, total_bytes - off);
7982 /* Subroutine of native_encode_expr. Encode the COMPLEX_CST
7983 specified by EXPR into the buffer PTR of length LEN bytes.
7984 Return the number of bytes placed in the buffer, or zero
7985 upon failure. */
7987 static int
7988 native_encode_complex (const_tree expr, unsigned char *ptr, int len, int off)
7990 int rsize, isize;
7991 tree part;
7993 part = TREE_REALPART (expr);
7994 rsize = native_encode_expr (part, ptr, len, off);
7995 if (off == -1 && rsize == 0)
7996 return 0;
7997 part = TREE_IMAGPART (expr);
7998 if (off != -1)
7999 off = MAX (0, off - GET_MODE_SIZE (SCALAR_TYPE_MODE (TREE_TYPE (part))));
8000 isize = native_encode_expr (part, ptr ? ptr + rsize : NULL,
8001 len - rsize, off);
8002 if (off == -1 && isize != rsize)
8003 return 0;
8004 return rsize + isize;
8007 /* Like native_encode_vector, but only encode the first COUNT elements.
8008 The other arguments are as for native_encode_vector. */
8010 static int
8011 native_encode_vector_part (const_tree expr, unsigned char *ptr, int len,
8012 int off, unsigned HOST_WIDE_INT count)
8014 tree itype = TREE_TYPE (TREE_TYPE (expr));
8015 if (VECTOR_BOOLEAN_TYPE_P (TREE_TYPE (expr))
8016 && TYPE_PRECISION (itype) <= BITS_PER_UNIT)
8018 /* This is the only case in which elements can be smaller than a byte.
8019 Element 0 is always in the lsb of the containing byte. */
8020 unsigned int elt_bits = TYPE_PRECISION (itype);
8021 int total_bytes = CEIL (elt_bits * count, BITS_PER_UNIT);
8022 if ((off == -1 && total_bytes > len) || off >= total_bytes)
8023 return 0;
8025 if (off == -1)
8026 off = 0;
8028 /* Zero the buffer and then set bits later where necessary. */
8029 int extract_bytes = MIN (len, total_bytes - off);
8030 if (ptr)
8031 memset (ptr, 0, extract_bytes);
8033 unsigned int elts_per_byte = BITS_PER_UNIT / elt_bits;
8034 unsigned int first_elt = off * elts_per_byte;
8035 unsigned int extract_elts = extract_bytes * elts_per_byte;
8036 for (unsigned int i = 0; i < extract_elts; ++i)
8038 tree elt = VECTOR_CST_ELT (expr, first_elt + i);
8039 if (TREE_CODE (elt) != INTEGER_CST)
8040 return 0;
8042 if (ptr && wi::extract_uhwi (wi::to_wide (elt), 0, 1))
8044 unsigned int bit = i * elt_bits;
8045 ptr[bit / BITS_PER_UNIT] |= 1 << (bit % BITS_PER_UNIT);
8048 return extract_bytes;
8051 int offset = 0;
8052 int size = GET_MODE_SIZE (SCALAR_TYPE_MODE (itype));
8053 for (unsigned HOST_WIDE_INT i = 0; i < count; i++)
8055 if (off >= size)
8057 off -= size;
8058 continue;
8060 tree elem = VECTOR_CST_ELT (expr, i);
8061 int res = native_encode_expr (elem, ptr ? ptr + offset : NULL,
8062 len - offset, off);
8063 if ((off == -1 && res != size) || res == 0)
8064 return 0;
8065 offset += res;
8066 if (offset >= len)
8067 return (off == -1 && i < count - 1) ? 0 : offset;
8068 if (off != -1)
8069 off = 0;
8071 return offset;
8074 /* Subroutine of native_encode_expr. Encode the VECTOR_CST
8075 specified by EXPR into the buffer PTR of length LEN bytes.
8076 Return the number of bytes placed in the buffer, or zero
8077 upon failure. */
8079 static int
8080 native_encode_vector (const_tree expr, unsigned char *ptr, int len, int off)
8082 unsigned HOST_WIDE_INT count;
8083 if (!VECTOR_CST_NELTS (expr).is_constant (&count))
8084 return 0;
8085 return native_encode_vector_part (expr, ptr, len, off, count);
8089 /* Subroutine of native_encode_expr. Encode the STRING_CST
8090 specified by EXPR into the buffer PTR of length LEN bytes.
8091 Return the number of bytes placed in the buffer, or zero
8092 upon failure. */
8094 static int
8095 native_encode_string (const_tree expr, unsigned char *ptr, int len, int off)
8097 tree type = TREE_TYPE (expr);
8099 /* Wide-char strings are encoded in target byte-order so native
8100 encoding them is trivial. */
8101 if (BITS_PER_UNIT != CHAR_BIT
8102 || TREE_CODE (type) != ARRAY_TYPE
8103 || TREE_CODE (TREE_TYPE (type)) != INTEGER_TYPE
8104 || !tree_fits_shwi_p (TYPE_SIZE_UNIT (type)))
8105 return 0;
8107 HOST_WIDE_INT total_bytes = tree_to_shwi (TYPE_SIZE_UNIT (TREE_TYPE (expr)));
8108 if ((off == -1 && total_bytes > len) || off >= total_bytes)
8109 return 0;
8110 if (off == -1)
8111 off = 0;
8112 len = MIN (total_bytes - off, len);
8113 if (ptr == NULL)
8114 /* Dry run. */;
8115 else
8117 int written = 0;
8118 if (off < TREE_STRING_LENGTH (expr))
8120 written = MIN (len, TREE_STRING_LENGTH (expr) - off);
8121 memcpy (ptr, TREE_STRING_POINTER (expr) + off, written);
8123 memset (ptr + written, 0, len - written);
8125 return len;
8129 /* Subroutine of fold_view_convert_expr. Encode the INTEGER_CST, REAL_CST,
8130 FIXED_CST, COMPLEX_CST, STRING_CST, or VECTOR_CST specified by EXPR into
8131 the buffer PTR of size LEN bytes. If PTR is NULL, don't actually store
8132 anything, just do a dry run. Fail either if OFF is -1 and LEN isn't
8133 sufficient to encode the entire EXPR, or if OFF is out of bounds.
8134 Otherwise, start at byte offset OFF and encode at most LEN bytes.
8135 Return the number of bytes placed in the buffer, or zero upon failure. */
8138 native_encode_expr (const_tree expr, unsigned char *ptr, int len, int off)
8140 /* We don't support starting at negative offset and -1 is special. */
8141 if (off < -1)
8142 return 0;
8144 switch (TREE_CODE (expr))
8146 case INTEGER_CST:
8147 return native_encode_int (expr, ptr, len, off);
8149 case REAL_CST:
8150 return native_encode_real (expr, ptr, len, off);
8152 case FIXED_CST:
8153 return native_encode_fixed (expr, ptr, len, off);
8155 case COMPLEX_CST:
8156 return native_encode_complex (expr, ptr, len, off);
8158 case VECTOR_CST:
8159 return native_encode_vector (expr, ptr, len, off);
8161 case STRING_CST:
8162 return native_encode_string (expr, ptr, len, off);
8164 default:
8165 return 0;
8169 /* Try to find a type whose byte size is smaller or equal to LEN bytes larger
8170 or equal to FIELDSIZE bytes, with underlying mode precision/size multiple
8171 of BITS_PER_UNIT. As native_{interpret,encode}_int works in term of
8172 machine modes, we can't just use build_nonstandard_integer_type. */
8174 tree
8175 find_bitfield_repr_type (int fieldsize, int len)
8177 machine_mode mode;
8178 for (int pass = 0; pass < 2; pass++)
8180 enum mode_class mclass = pass ? MODE_PARTIAL_INT : MODE_INT;
8181 FOR_EACH_MODE_IN_CLASS (mode, mclass)
8182 if (known_ge (GET_MODE_SIZE (mode), fieldsize)
8183 && known_eq (GET_MODE_PRECISION (mode),
8184 GET_MODE_BITSIZE (mode))
8185 && known_le (GET_MODE_SIZE (mode), len))
8187 tree ret = lang_hooks.types.type_for_mode (mode, 1);
8188 if (ret && TYPE_MODE (ret) == mode)
8189 return ret;
8193 for (int i = 0; i < NUM_INT_N_ENTS; i ++)
8194 if (int_n_enabled_p[i]
8195 && int_n_data[i].bitsize >= (unsigned) (BITS_PER_UNIT * fieldsize)
8196 && int_n_trees[i].unsigned_type)
8198 tree ret = int_n_trees[i].unsigned_type;
8199 mode = TYPE_MODE (ret);
8200 if (known_ge (GET_MODE_SIZE (mode), fieldsize)
8201 && known_eq (GET_MODE_PRECISION (mode),
8202 GET_MODE_BITSIZE (mode))
8203 && known_le (GET_MODE_SIZE (mode), len))
8204 return ret;
8207 return NULL_TREE;
8210 /* Similar to native_encode_expr, but also handle CONSTRUCTORs, VCEs,
8211 NON_LVALUE_EXPRs and nops. If MASK is non-NULL (then PTR has
8212 to be non-NULL and OFF zero), then in addition to filling the
8213 bytes pointed by PTR with the value also clear any bits pointed
8214 by MASK that are known to be initialized, keep them as is for
8215 e.g. uninitialized padding bits or uninitialized fields. */
8218 native_encode_initializer (tree init, unsigned char *ptr, int len,
8219 int off, unsigned char *mask)
8221 int r;
8223 /* We don't support starting at negative offset and -1 is special. */
8224 if (off < -1 || init == NULL_TREE)
8225 return 0;
8227 gcc_assert (mask == NULL || (off == 0 && ptr));
8229 STRIP_NOPS (init);
8230 switch (TREE_CODE (init))
8232 case VIEW_CONVERT_EXPR:
8233 case NON_LVALUE_EXPR:
8234 return native_encode_initializer (TREE_OPERAND (init, 0), ptr, len, off,
8235 mask);
8236 default:
8237 r = native_encode_expr (init, ptr, len, off);
8238 if (mask)
8239 memset (mask, 0, r);
8240 return r;
8241 case CONSTRUCTOR:
8242 tree type = TREE_TYPE (init);
8243 HOST_WIDE_INT total_bytes = int_size_in_bytes (type);
8244 if (total_bytes < 0)
8245 return 0;
8246 if ((off == -1 && total_bytes > len) || off >= total_bytes)
8247 return 0;
8248 int o = off == -1 ? 0 : off;
8249 if (TREE_CODE (type) == ARRAY_TYPE)
8251 tree min_index;
8252 unsigned HOST_WIDE_INT cnt;
8253 HOST_WIDE_INT curpos = 0, fieldsize, valueinit = -1;
8254 constructor_elt *ce;
8256 if (!TYPE_DOMAIN (type)
8257 || TREE_CODE (TYPE_MIN_VALUE (TYPE_DOMAIN (type))) != INTEGER_CST)
8258 return 0;
8260 fieldsize = int_size_in_bytes (TREE_TYPE (type));
8261 if (fieldsize <= 0)
8262 return 0;
8264 min_index = TYPE_MIN_VALUE (TYPE_DOMAIN (type));
8265 if (ptr)
8266 memset (ptr, '\0', MIN (total_bytes - off, len));
8268 for (cnt = 0; ; cnt++)
8270 tree val = NULL_TREE, index = NULL_TREE;
8271 HOST_WIDE_INT pos = curpos, count = 0;
8272 bool full = false;
8273 if (vec_safe_iterate (CONSTRUCTOR_ELTS (init), cnt, &ce))
8275 val = ce->value;
8276 index = ce->index;
8278 else if (mask == NULL
8279 || CONSTRUCTOR_NO_CLEARING (init)
8280 || curpos >= total_bytes)
8281 break;
8282 else
8283 pos = total_bytes;
8285 if (index && TREE_CODE (index) == RANGE_EXPR)
8287 if (TREE_CODE (TREE_OPERAND (index, 0)) != INTEGER_CST
8288 || TREE_CODE (TREE_OPERAND (index, 1)) != INTEGER_CST)
8289 return 0;
8290 offset_int wpos
8291 = wi::sext (wi::to_offset (TREE_OPERAND (index, 0))
8292 - wi::to_offset (min_index),
8293 TYPE_PRECISION (sizetype));
8294 wpos *= fieldsize;
8295 if (!wi::fits_shwi_p (pos))
8296 return 0;
8297 pos = wpos.to_shwi ();
8298 offset_int wcount
8299 = wi::sext (wi::to_offset (TREE_OPERAND (index, 1))
8300 - wi::to_offset (TREE_OPERAND (index, 0)),
8301 TYPE_PRECISION (sizetype));
8302 if (!wi::fits_shwi_p (wcount))
8303 return 0;
8304 count = wcount.to_shwi ();
8306 else if (index)
8308 if (TREE_CODE (index) != INTEGER_CST)
8309 return 0;
8310 offset_int wpos
8311 = wi::sext (wi::to_offset (index)
8312 - wi::to_offset (min_index),
8313 TYPE_PRECISION (sizetype));
8314 wpos *= fieldsize;
8315 if (!wi::fits_shwi_p (wpos))
8316 return 0;
8317 pos = wpos.to_shwi ();
8320 if (mask && !CONSTRUCTOR_NO_CLEARING (init) && curpos != pos)
8322 if (valueinit == -1)
8324 tree zero = build_zero_cst (TREE_TYPE (type));
8325 r = native_encode_initializer (zero, ptr + curpos,
8326 fieldsize, 0,
8327 mask + curpos);
8328 if (TREE_CODE (zero) == CONSTRUCTOR)
8329 ggc_free (zero);
8330 if (!r)
8331 return 0;
8332 valueinit = curpos;
8333 curpos += fieldsize;
8335 while (curpos != pos)
8337 memcpy (ptr + curpos, ptr + valueinit, fieldsize);
8338 memcpy (mask + curpos, mask + valueinit, fieldsize);
8339 curpos += fieldsize;
8343 curpos = pos;
8344 if (val)
8347 if (off == -1
8348 || (curpos >= off
8349 && (curpos + fieldsize
8350 <= (HOST_WIDE_INT) off + len)))
8352 if (full)
8354 if (ptr)
8355 memcpy (ptr + (curpos - o), ptr + (pos - o),
8356 fieldsize);
8357 if (mask)
8358 memcpy (mask + curpos, mask + pos, fieldsize);
8360 else if (!native_encode_initializer (val,
8362 ? ptr + curpos - o
8363 : NULL,
8364 fieldsize,
8365 off == -1 ? -1
8366 : 0,
8367 mask
8368 ? mask + curpos
8369 : NULL))
8370 return 0;
8371 else
8373 full = true;
8374 pos = curpos;
8377 else if (curpos + fieldsize > off
8378 && curpos < (HOST_WIDE_INT) off + len)
8380 /* Partial overlap. */
8381 unsigned char *p = NULL;
8382 int no = 0;
8383 int l;
8384 gcc_assert (mask == NULL);
8385 if (curpos >= off)
8387 if (ptr)
8388 p = ptr + curpos - off;
8389 l = MIN ((HOST_WIDE_INT) off + len - curpos,
8390 fieldsize);
8392 else
8394 p = ptr;
8395 no = off - curpos;
8396 l = len;
8398 if (!native_encode_initializer (val, p, l, no, NULL))
8399 return 0;
8401 curpos += fieldsize;
8403 while (count-- != 0);
8405 return MIN (total_bytes - off, len);
8407 else if (TREE_CODE (type) == RECORD_TYPE
8408 || TREE_CODE (type) == UNION_TYPE)
8410 unsigned HOST_WIDE_INT cnt;
8411 constructor_elt *ce;
8412 tree fld_base = TYPE_FIELDS (type);
8413 tree to_free = NULL_TREE;
8415 gcc_assert (TREE_CODE (type) == RECORD_TYPE || mask == NULL);
8416 if (ptr != NULL)
8417 memset (ptr, '\0', MIN (total_bytes - o, len));
8418 for (cnt = 0; ; cnt++)
8420 tree val = NULL_TREE, field = NULL_TREE;
8421 HOST_WIDE_INT pos = 0, fieldsize;
8422 unsigned HOST_WIDE_INT bpos = 0, epos = 0;
8424 if (to_free)
8426 ggc_free (to_free);
8427 to_free = NULL_TREE;
8430 if (vec_safe_iterate (CONSTRUCTOR_ELTS (init), cnt, &ce))
8432 val = ce->value;
8433 field = ce->index;
8434 if (field == NULL_TREE)
8435 return 0;
8437 pos = int_byte_position (field);
8438 if (off != -1 && (HOST_WIDE_INT) off + len <= pos)
8439 continue;
8441 else if (mask == NULL
8442 || CONSTRUCTOR_NO_CLEARING (init))
8443 break;
8444 else
8445 pos = total_bytes;
8447 if (mask && !CONSTRUCTOR_NO_CLEARING (init))
8449 tree fld;
8450 for (fld = fld_base; fld; fld = DECL_CHAIN (fld))
8452 if (TREE_CODE (fld) != FIELD_DECL)
8453 continue;
8454 if (fld == field)
8455 break;
8456 if (DECL_PADDING_P (fld))
8457 continue;
8458 if (DECL_SIZE_UNIT (fld) == NULL_TREE
8459 || !tree_fits_shwi_p (DECL_SIZE_UNIT (fld)))
8460 return 0;
8461 if (integer_zerop (DECL_SIZE_UNIT (fld)))
8462 continue;
8463 break;
8465 if (fld == NULL_TREE)
8467 if (ce == NULL)
8468 break;
8469 return 0;
8471 fld_base = DECL_CHAIN (fld);
8472 if (fld != field)
8474 cnt--;
8475 field = fld;
8476 pos = int_byte_position (field);
8477 val = build_zero_cst (TREE_TYPE (fld));
8478 if (TREE_CODE (val) == CONSTRUCTOR)
8479 to_free = val;
8483 if (TREE_CODE (TREE_TYPE (field)) == ARRAY_TYPE
8484 && TYPE_DOMAIN (TREE_TYPE (field))
8485 && ! TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (field))))
8487 if (mask || off != -1)
8488 return 0;
8489 if (val == NULL_TREE)
8490 continue;
8491 if (TREE_CODE (TREE_TYPE (val)) != ARRAY_TYPE)
8492 return 0;
8493 fieldsize = int_size_in_bytes (TREE_TYPE (val));
8494 if (fieldsize < 0
8495 || (int) fieldsize != fieldsize
8496 || (pos + fieldsize) > INT_MAX)
8497 return 0;
8498 if (pos + fieldsize > total_bytes)
8500 if (ptr != NULL && total_bytes < len)
8501 memset (ptr + total_bytes, '\0',
8502 MIN (pos + fieldsize, len) - total_bytes);
8503 total_bytes = pos + fieldsize;
8506 else
8508 if (DECL_SIZE_UNIT (field) == NULL_TREE
8509 || !tree_fits_shwi_p (DECL_SIZE_UNIT (field)))
8510 return 0;
8511 fieldsize = tree_to_shwi (DECL_SIZE_UNIT (field));
8513 if (fieldsize == 0)
8514 continue;
8516 /* Prepare to deal with integral bit-fields and filter out other
8517 bit-fields that do not start and end on a byte boundary. */
8518 if (DECL_BIT_FIELD (field))
8520 if (!tree_fits_uhwi_p (DECL_FIELD_BIT_OFFSET (field)))
8521 return 0;
8522 bpos = tree_to_uhwi (DECL_FIELD_BIT_OFFSET (field));
8523 if (INTEGRAL_TYPE_P (TREE_TYPE (field)))
8525 bpos %= BITS_PER_UNIT;
8526 fieldsize = TYPE_PRECISION (TREE_TYPE (field)) + bpos;
8527 epos = fieldsize % BITS_PER_UNIT;
8528 fieldsize += BITS_PER_UNIT - 1;
8529 fieldsize /= BITS_PER_UNIT;
8531 else if (bpos % BITS_PER_UNIT
8532 || DECL_SIZE (field) == NULL_TREE
8533 || !tree_fits_shwi_p (DECL_SIZE (field))
8534 || tree_to_shwi (DECL_SIZE (field)) % BITS_PER_UNIT)
8535 return 0;
8538 if (off != -1 && pos + fieldsize <= off)
8539 continue;
8541 if (val == NULL_TREE)
8542 continue;
8544 if (DECL_BIT_FIELD (field)
8545 && INTEGRAL_TYPE_P (TREE_TYPE (field)))
8547 /* FIXME: Handle PDP endian. */
8548 if (BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN)
8549 return 0;
8551 if (TREE_CODE (val) != INTEGER_CST)
8552 return 0;
8554 tree repr = DECL_BIT_FIELD_REPRESENTATIVE (field);
8555 tree repr_type = NULL_TREE;
8556 HOST_WIDE_INT rpos = 0;
8557 if (repr && INTEGRAL_TYPE_P (TREE_TYPE (repr)))
8559 rpos = int_byte_position (repr);
8560 repr_type = TREE_TYPE (repr);
8562 else
8564 repr_type = find_bitfield_repr_type (fieldsize, len);
8565 if (repr_type == NULL_TREE)
8566 return 0;
8567 HOST_WIDE_INT repr_size = int_size_in_bytes (repr_type);
8568 gcc_assert (repr_size > 0 && repr_size <= len);
8569 if (pos + repr_size <= o + len)
8570 rpos = pos;
8571 else
8573 rpos = o + len - repr_size;
8574 gcc_assert (rpos <= pos);
8578 if (rpos > pos)
8579 return 0;
8580 wide_int w = wi::to_wide (val, TYPE_PRECISION (repr_type));
8581 int diff = (TYPE_PRECISION (repr_type)
8582 - TYPE_PRECISION (TREE_TYPE (field)));
8583 HOST_WIDE_INT bitoff = (pos - rpos) * BITS_PER_UNIT + bpos;
8584 if (!BYTES_BIG_ENDIAN)
8585 w = wi::lshift (w, bitoff);
8586 else
8587 w = wi::lshift (w, diff - bitoff);
8588 val = wide_int_to_tree (repr_type, w);
8590 unsigned char buf[MAX_BITSIZE_MODE_ANY_INT
8591 / BITS_PER_UNIT + 1];
8592 int l = native_encode_int (val, buf, sizeof buf, 0);
8593 if (l * BITS_PER_UNIT != TYPE_PRECISION (repr_type))
8594 return 0;
8596 if (ptr == NULL)
8597 continue;
8599 /* If the bitfield does not start at byte boundary, handle
8600 the partial byte at the start. */
8601 if (bpos
8602 && (off == -1 || (pos >= off && len >= 1)))
8604 if (!BYTES_BIG_ENDIAN)
8606 int msk = (1 << bpos) - 1;
8607 buf[pos - rpos] &= ~msk;
8608 buf[pos - rpos] |= ptr[pos - o] & msk;
8609 if (mask)
8611 if (fieldsize > 1 || epos == 0)
8612 mask[pos] &= msk;
8613 else
8614 mask[pos] &= (msk | ~((1 << epos) - 1));
8617 else
8619 int msk = (1 << (BITS_PER_UNIT - bpos)) - 1;
8620 buf[pos - rpos] &= msk;
8621 buf[pos - rpos] |= ptr[pos - o] & ~msk;
8622 if (mask)
8624 if (fieldsize > 1 || epos == 0)
8625 mask[pos] &= ~msk;
8626 else
8627 mask[pos] &= (~msk
8628 | ((1 << (BITS_PER_UNIT - epos))
8629 - 1));
8633 /* If the bitfield does not end at byte boundary, handle
8634 the partial byte at the end. */
8635 if (epos
8636 && (off == -1
8637 || pos + fieldsize <= (HOST_WIDE_INT) off + len))
8639 if (!BYTES_BIG_ENDIAN)
8641 int msk = (1 << epos) - 1;
8642 buf[pos - rpos + fieldsize - 1] &= msk;
8643 buf[pos - rpos + fieldsize - 1]
8644 |= ptr[pos + fieldsize - 1 - o] & ~msk;
8645 if (mask && (fieldsize > 1 || bpos == 0))
8646 mask[pos + fieldsize - 1] &= ~msk;
8648 else
8650 int msk = (1 << (BITS_PER_UNIT - epos)) - 1;
8651 buf[pos - rpos + fieldsize - 1] &= ~msk;
8652 buf[pos - rpos + fieldsize - 1]
8653 |= ptr[pos + fieldsize - 1 - o] & msk;
8654 if (mask && (fieldsize > 1 || bpos == 0))
8655 mask[pos + fieldsize - 1] &= msk;
8658 if (off == -1
8659 || (pos >= off
8660 && (pos + fieldsize <= (HOST_WIDE_INT) off + len)))
8662 memcpy (ptr + pos - o, buf + (pos - rpos), fieldsize);
8663 if (mask && (fieldsize > (bpos != 0) + (epos != 0)))
8664 memset (mask + pos + (bpos != 0), 0,
8665 fieldsize - (bpos != 0) - (epos != 0));
8667 else
8669 /* Partial overlap. */
8670 HOST_WIDE_INT fsz = fieldsize;
8671 gcc_assert (mask == NULL);
8672 if (pos < off)
8674 fsz -= (off - pos);
8675 pos = off;
8677 if (pos + fsz > (HOST_WIDE_INT) off + len)
8678 fsz = (HOST_WIDE_INT) off + len - pos;
8679 memcpy (ptr + pos - off, buf + (pos - rpos), fsz);
8681 continue;
8684 if (off == -1
8685 || (pos >= off
8686 && (pos + fieldsize <= (HOST_WIDE_INT) off + len)))
8688 int fldsize = fieldsize;
8689 if (off == -1)
8691 tree fld = DECL_CHAIN (field);
8692 while (fld)
8694 if (TREE_CODE (fld) == FIELD_DECL)
8695 break;
8696 fld = DECL_CHAIN (fld);
8698 if (fld == NULL_TREE)
8699 fldsize = len - pos;
8701 r = native_encode_initializer (val, ptr ? ptr + pos - o
8702 : NULL,
8703 fldsize,
8704 off == -1 ? -1 : 0,
8705 mask ? mask + pos : NULL);
8706 if (!r)
8707 return 0;
8708 if (off == -1
8709 && fldsize != fieldsize
8710 && r > fieldsize
8711 && pos + r > total_bytes)
8712 total_bytes = pos + r;
8714 else
8716 /* Partial overlap. */
8717 unsigned char *p = NULL;
8718 int no = 0;
8719 int l;
8720 gcc_assert (mask == NULL);
8721 if (pos >= off)
8723 if (ptr)
8724 p = ptr + pos - off;
8725 l = MIN ((HOST_WIDE_INT) off + len - pos,
8726 fieldsize);
8728 else
8730 p = ptr;
8731 no = off - pos;
8732 l = len;
8734 if (!native_encode_initializer (val, p, l, no, NULL))
8735 return 0;
8738 return MIN (total_bytes - off, len);
8740 return 0;
8745 /* Subroutine of native_interpret_expr. Interpret the contents of
8746 the buffer PTR of length LEN as an INTEGER_CST of type TYPE.
8747 If the buffer cannot be interpreted, return NULL_TREE. */
8749 static tree
8750 native_interpret_int (tree type, const unsigned char *ptr, int len)
8752 int total_bytes;
8753 if (TREE_CODE (type) == BITINT_TYPE)
8755 struct bitint_info info;
8756 bool ok = targetm.c.bitint_type_info (TYPE_PRECISION (type), &info);
8757 gcc_assert (ok);
8758 scalar_int_mode limb_mode = as_a <scalar_int_mode> (info.limb_mode);
8759 if (TYPE_PRECISION (type) > GET_MODE_PRECISION (limb_mode))
8761 total_bytes = tree_to_uhwi (TYPE_SIZE_UNIT (type));
8762 /* More work is needed when adding _BitInt support to PDP endian
8763 if limb is smaller than word, or if _BitInt limb ordering doesn't
8764 match target endianity here. */
8765 gcc_checking_assert (info.big_endian == WORDS_BIG_ENDIAN
8766 && (BYTES_BIG_ENDIAN == WORDS_BIG_ENDIAN
8767 || (GET_MODE_SIZE (limb_mode)
8768 >= UNITS_PER_WORD)));
8770 else
8771 total_bytes = GET_MODE_SIZE (SCALAR_INT_TYPE_MODE (type));
8773 else
8774 total_bytes = GET_MODE_SIZE (SCALAR_INT_TYPE_MODE (type));
8776 if (total_bytes > len)
8777 return NULL_TREE;
8779 wide_int result = wi::from_buffer (ptr, total_bytes);
8781 return wide_int_to_tree (type, result);
8785 /* Subroutine of native_interpret_expr. Interpret the contents of
8786 the buffer PTR of length LEN as a FIXED_CST of type TYPE.
8787 If the buffer cannot be interpreted, return NULL_TREE. */
8789 static tree
8790 native_interpret_fixed (tree type, const unsigned char *ptr, int len)
8792 scalar_mode mode = SCALAR_TYPE_MODE (type);
8793 int total_bytes = GET_MODE_SIZE (mode);
8794 double_int result;
8795 FIXED_VALUE_TYPE fixed_value;
8797 if (total_bytes > len
8798 || total_bytes * BITS_PER_UNIT > HOST_BITS_PER_DOUBLE_INT)
8799 return NULL_TREE;
8801 result = double_int::from_buffer (ptr, total_bytes);
8802 fixed_value = fixed_from_double_int (result, mode);
8804 return build_fixed (type, fixed_value);
8808 /* Subroutine of native_interpret_expr. Interpret the contents of
8809 the buffer PTR of length LEN as a REAL_CST of type TYPE.
8810 If the buffer cannot be interpreted, return NULL_TREE. */
8812 tree
8813 native_interpret_real (tree type, const unsigned char *ptr, int len)
8815 scalar_float_mode mode = SCALAR_FLOAT_TYPE_MODE (type);
8816 int total_bytes = GET_MODE_SIZE (mode);
8817 unsigned char value;
8818 /* There are always 32 bits in each long, no matter the size of
8819 the hosts long. We handle floating point representations with
8820 up to 192 bits. */
8821 REAL_VALUE_TYPE r;
8822 long tmp[6];
8824 if (total_bytes > len || total_bytes > 24)
8825 return NULL_TREE;
8826 int words = (32 / BITS_PER_UNIT) / UNITS_PER_WORD;
8828 memset (tmp, 0, sizeof (tmp));
8829 for (int bitpos = 0; bitpos < total_bytes * BITS_PER_UNIT;
8830 bitpos += BITS_PER_UNIT)
8832 /* Both OFFSET and BYTE index within a long;
8833 bitpos indexes the whole float. */
8834 int offset, byte = (bitpos / BITS_PER_UNIT) & 3;
8835 if (UNITS_PER_WORD < 4)
8837 int word = byte / UNITS_PER_WORD;
8838 if (WORDS_BIG_ENDIAN)
8839 word = (words - 1) - word;
8840 offset = word * UNITS_PER_WORD;
8841 if (BYTES_BIG_ENDIAN)
8842 offset += (UNITS_PER_WORD - 1) - (byte % UNITS_PER_WORD);
8843 else
8844 offset += byte % UNITS_PER_WORD;
8846 else
8848 offset = byte;
8849 if (BYTES_BIG_ENDIAN)
8851 /* Reverse bytes within each long, or within the entire float
8852 if it's smaller than a long (for HFmode). */
8853 offset = MIN (3, total_bytes - 1) - offset;
8854 gcc_assert (offset >= 0);
8857 value = ptr[offset + ((bitpos / BITS_PER_UNIT) & ~3)];
8859 tmp[bitpos / 32] |= (unsigned long)value << (bitpos & 31);
8862 real_from_target (&r, tmp, mode);
8863 return build_real (type, r);
8867 /* Subroutine of native_interpret_expr. Interpret the contents of
8868 the buffer PTR of length LEN as a COMPLEX_CST of type TYPE.
8869 If the buffer cannot be interpreted, return NULL_TREE. */
8871 static tree
8872 native_interpret_complex (tree type, const unsigned char *ptr, int len)
8874 tree etype, rpart, ipart;
8875 int size;
8877 etype = TREE_TYPE (type);
8878 size = GET_MODE_SIZE (SCALAR_TYPE_MODE (etype));
8879 if (size * 2 > len)
8880 return NULL_TREE;
8881 rpart = native_interpret_expr (etype, ptr, size);
8882 if (!rpart)
8883 return NULL_TREE;
8884 ipart = native_interpret_expr (etype, ptr+size, size);
8885 if (!ipart)
8886 return NULL_TREE;
8887 return build_complex (type, rpart, ipart);
8890 /* Read a vector of type TYPE from the target memory image given by BYTES,
8891 which contains LEN bytes. The vector is known to be encodable using
8892 NPATTERNS interleaved patterns with NELTS_PER_PATTERN elements each.
8894 Return the vector on success, otherwise return null. */
8896 static tree
8897 native_interpret_vector_part (tree type, const unsigned char *bytes,
8898 unsigned int len, unsigned int npatterns,
8899 unsigned int nelts_per_pattern)
8901 tree elt_type = TREE_TYPE (type);
8902 if (VECTOR_BOOLEAN_TYPE_P (type)
8903 && TYPE_PRECISION (elt_type) <= BITS_PER_UNIT)
8905 /* This is the only case in which elements can be smaller than a byte.
8906 Element 0 is always in the lsb of the containing byte. */
8907 unsigned int elt_bits = TYPE_PRECISION (elt_type);
8908 if (elt_bits * npatterns * nelts_per_pattern > len * BITS_PER_UNIT)
8909 return NULL_TREE;
8911 tree_vector_builder builder (type, npatterns, nelts_per_pattern);
8912 for (unsigned int i = 0; i < builder.encoded_nelts (); ++i)
8914 unsigned int bit_index = i * elt_bits;
8915 unsigned int byte_index = bit_index / BITS_PER_UNIT;
8916 unsigned int lsb = bit_index % BITS_PER_UNIT;
8917 builder.quick_push (bytes[byte_index] & (1 << lsb)
8918 ? build_all_ones_cst (elt_type)
8919 : build_zero_cst (elt_type));
8921 return builder.build ();
8924 unsigned int elt_bytes = tree_to_uhwi (TYPE_SIZE_UNIT (elt_type));
8925 if (elt_bytes * npatterns * nelts_per_pattern > len)
8926 return NULL_TREE;
8928 tree_vector_builder builder (type, npatterns, nelts_per_pattern);
8929 for (unsigned int i = 0; i < builder.encoded_nelts (); ++i)
8931 tree elt = native_interpret_expr (elt_type, bytes, elt_bytes);
8932 if (!elt)
8933 return NULL_TREE;
8934 builder.quick_push (elt);
8935 bytes += elt_bytes;
8937 return builder.build ();
8940 /* Subroutine of native_interpret_expr. Interpret the contents of
8941 the buffer PTR of length LEN as a VECTOR_CST of type TYPE.
8942 If the buffer cannot be interpreted, return NULL_TREE. */
8944 static tree
8945 native_interpret_vector (tree type, const unsigned char *ptr, unsigned int len)
8947 unsigned HOST_WIDE_INT size;
8949 if (!tree_to_poly_uint64 (TYPE_SIZE_UNIT (type)).is_constant (&size)
8950 || size > len)
8951 return NULL_TREE;
8953 unsigned HOST_WIDE_INT count = TYPE_VECTOR_SUBPARTS (type).to_constant ();
8954 return native_interpret_vector_part (type, ptr, len, count, 1);
8958 /* Subroutine of fold_view_convert_expr. Interpret the contents of
8959 the buffer PTR of length LEN as a constant of type TYPE. For
8960 INTEGRAL_TYPE_P we return an INTEGER_CST, for SCALAR_FLOAT_TYPE_P
8961 we return a REAL_CST, etc... If the buffer cannot be interpreted,
8962 return NULL_TREE. */
8964 tree
8965 native_interpret_expr (tree type, const unsigned char *ptr, int len)
8967 switch (TREE_CODE (type))
8969 case INTEGER_TYPE:
8970 case ENUMERAL_TYPE:
8971 case BOOLEAN_TYPE:
8972 case POINTER_TYPE:
8973 case REFERENCE_TYPE:
8974 case OFFSET_TYPE:
8975 case BITINT_TYPE:
8976 return native_interpret_int (type, ptr, len);
8978 case REAL_TYPE:
8979 if (tree ret = native_interpret_real (type, ptr, len))
8981 /* For floating point values in composite modes, punt if this
8982 folding doesn't preserve bit representation. As the mode doesn't
8983 have fixed precision while GCC pretends it does, there could be
8984 valid values that GCC can't really represent accurately.
8985 See PR95450. Even for other modes, e.g. x86 XFmode can have some
8986 bit combinationations which GCC doesn't preserve. */
8987 unsigned char buf[24 * 2];
8988 scalar_float_mode mode = SCALAR_FLOAT_TYPE_MODE (type);
8989 int total_bytes = GET_MODE_SIZE (mode);
8990 memcpy (buf + 24, ptr, total_bytes);
8991 clear_type_padding_in_mask (type, buf + 24);
8992 if (native_encode_expr (ret, buf, total_bytes, 0) != total_bytes
8993 || memcmp (buf + 24, buf, total_bytes) != 0)
8994 return NULL_TREE;
8995 return ret;
8997 return NULL_TREE;
8999 case FIXED_POINT_TYPE:
9000 return native_interpret_fixed (type, ptr, len);
9002 case COMPLEX_TYPE:
9003 return native_interpret_complex (type, ptr, len);
9005 case VECTOR_TYPE:
9006 return native_interpret_vector (type, ptr, len);
9008 default:
9009 return NULL_TREE;
9013 /* Returns true if we can interpret the contents of a native encoding
9014 as TYPE. */
9016 bool
9017 can_native_interpret_type_p (tree type)
9019 switch (TREE_CODE (type))
9021 case INTEGER_TYPE:
9022 case ENUMERAL_TYPE:
9023 case BOOLEAN_TYPE:
9024 case POINTER_TYPE:
9025 case REFERENCE_TYPE:
9026 case FIXED_POINT_TYPE:
9027 case REAL_TYPE:
9028 case COMPLEX_TYPE:
9029 case VECTOR_TYPE:
9030 case OFFSET_TYPE:
9031 return true;
9032 default:
9033 return false;
9037 /* Attempt to interpret aggregate of TYPE from bytes encoded in target
9038 byte order at PTR + OFF with LEN bytes. Does not handle unions. */
9040 tree
9041 native_interpret_aggregate (tree type, const unsigned char *ptr, int off,
9042 int len)
9044 vec<constructor_elt, va_gc> *elts = NULL;
9045 if (TREE_CODE (type) == ARRAY_TYPE)
9047 HOST_WIDE_INT eltsz = int_size_in_bytes (TREE_TYPE (type));
9048 if (eltsz < 0 || eltsz > len || TYPE_DOMAIN (type) == NULL_TREE)
9049 return NULL_TREE;
9051 HOST_WIDE_INT cnt = 0;
9052 if (TYPE_MAX_VALUE (TYPE_DOMAIN (type)))
9054 if (!tree_fits_shwi_p (TYPE_MAX_VALUE (TYPE_DOMAIN (type))))
9055 return NULL_TREE;
9056 cnt = tree_to_shwi (TYPE_MAX_VALUE (TYPE_DOMAIN (type))) + 1;
9058 if (eltsz == 0)
9059 cnt = 0;
9060 HOST_WIDE_INT pos = 0;
9061 for (HOST_WIDE_INT i = 0; i < cnt; i++, pos += eltsz)
9063 tree v = NULL_TREE;
9064 if (pos >= len || pos + eltsz > len)
9065 return NULL_TREE;
9066 if (can_native_interpret_type_p (TREE_TYPE (type)))
9068 v = native_interpret_expr (TREE_TYPE (type),
9069 ptr + off + pos, eltsz);
9070 if (v == NULL_TREE)
9071 return NULL_TREE;
9073 else if (TREE_CODE (TREE_TYPE (type)) == RECORD_TYPE
9074 || TREE_CODE (TREE_TYPE (type)) == ARRAY_TYPE)
9075 v = native_interpret_aggregate (TREE_TYPE (type), ptr, off + pos,
9076 eltsz);
9077 if (v == NULL_TREE)
9078 return NULL_TREE;
9079 CONSTRUCTOR_APPEND_ELT (elts, size_int (i), v);
9081 return build_constructor (type, elts);
9083 if (TREE_CODE (type) != RECORD_TYPE)
9084 return NULL_TREE;
9085 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
9087 if (TREE_CODE (field) != FIELD_DECL || DECL_PADDING_P (field)
9088 || is_empty_type (TREE_TYPE (field)))
9089 continue;
9090 tree fld = field;
9091 HOST_WIDE_INT bitoff = 0, pos = 0, sz = 0;
9092 int diff = 0;
9093 tree v = NULL_TREE;
9094 if (DECL_BIT_FIELD (field))
9096 fld = DECL_BIT_FIELD_REPRESENTATIVE (field);
9097 if (fld && INTEGRAL_TYPE_P (TREE_TYPE (fld)))
9099 poly_int64 bitoffset;
9100 poly_uint64 field_offset, fld_offset;
9101 if (poly_int_tree_p (DECL_FIELD_OFFSET (field), &field_offset)
9102 && poly_int_tree_p (DECL_FIELD_OFFSET (fld), &fld_offset))
9103 bitoffset = (field_offset - fld_offset) * BITS_PER_UNIT;
9104 else
9105 bitoffset = 0;
9106 bitoffset += (tree_to_uhwi (DECL_FIELD_BIT_OFFSET (field))
9107 - tree_to_uhwi (DECL_FIELD_BIT_OFFSET (fld)));
9108 diff = (TYPE_PRECISION (TREE_TYPE (fld))
9109 - TYPE_PRECISION (TREE_TYPE (field)));
9110 if (!bitoffset.is_constant (&bitoff)
9111 || bitoff < 0
9112 || bitoff > diff)
9113 return NULL_TREE;
9115 else
9117 if (!tree_fits_uhwi_p (DECL_FIELD_BIT_OFFSET (field)))
9118 return NULL_TREE;
9119 int fieldsize = TYPE_PRECISION (TREE_TYPE (field));
9120 int bpos = tree_to_uhwi (DECL_FIELD_BIT_OFFSET (field));
9121 bpos %= BITS_PER_UNIT;
9122 fieldsize += bpos;
9123 fieldsize += BITS_PER_UNIT - 1;
9124 fieldsize /= BITS_PER_UNIT;
9125 tree repr_type = find_bitfield_repr_type (fieldsize, len);
9126 if (repr_type == NULL_TREE)
9127 return NULL_TREE;
9128 sz = int_size_in_bytes (repr_type);
9129 if (sz < 0 || sz > len)
9130 return NULL_TREE;
9131 pos = int_byte_position (field);
9132 if (pos < 0 || pos > len || pos + fieldsize > len)
9133 return NULL_TREE;
9134 HOST_WIDE_INT rpos;
9135 if (pos + sz <= len)
9136 rpos = pos;
9137 else
9139 rpos = len - sz;
9140 gcc_assert (rpos <= pos);
9142 bitoff = (HOST_WIDE_INT) (pos - rpos) * BITS_PER_UNIT + bpos;
9143 pos = rpos;
9144 diff = (TYPE_PRECISION (repr_type)
9145 - TYPE_PRECISION (TREE_TYPE (field)));
9146 v = native_interpret_expr (repr_type, ptr + off + pos, sz);
9147 if (v == NULL_TREE)
9148 return NULL_TREE;
9149 fld = NULL_TREE;
9153 if (fld)
9155 sz = int_size_in_bytes (TREE_TYPE (fld));
9156 if (sz < 0 || sz > len)
9157 return NULL_TREE;
9158 tree byte_pos = byte_position (fld);
9159 if (!tree_fits_shwi_p (byte_pos))
9160 return NULL_TREE;
9161 pos = tree_to_shwi (byte_pos);
9162 if (pos < 0 || pos > len || pos + sz > len)
9163 return NULL_TREE;
9165 if (fld == NULL_TREE)
9166 /* Already handled above. */;
9167 else if (can_native_interpret_type_p (TREE_TYPE (fld)))
9169 v = native_interpret_expr (TREE_TYPE (fld),
9170 ptr + off + pos, sz);
9171 if (v == NULL_TREE)
9172 return NULL_TREE;
9174 else if (TREE_CODE (TREE_TYPE (fld)) == RECORD_TYPE
9175 || TREE_CODE (TREE_TYPE (fld)) == ARRAY_TYPE)
9176 v = native_interpret_aggregate (TREE_TYPE (fld), ptr, off + pos, sz);
9177 if (v == NULL_TREE)
9178 return NULL_TREE;
9179 if (fld != field)
9181 if (TREE_CODE (v) != INTEGER_CST)
9182 return NULL_TREE;
9184 /* FIXME: Figure out how to handle PDP endian bitfields. */
9185 if (BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN)
9186 return NULL_TREE;
9187 if (!BYTES_BIG_ENDIAN)
9188 v = wide_int_to_tree (TREE_TYPE (field),
9189 wi::lrshift (wi::to_wide (v), bitoff));
9190 else
9191 v = wide_int_to_tree (TREE_TYPE (field),
9192 wi::lrshift (wi::to_wide (v),
9193 diff - bitoff));
9195 CONSTRUCTOR_APPEND_ELT (elts, field, v);
9197 return build_constructor (type, elts);
9200 /* Routines for manipulation of native_encode_expr encoded data if the encoded
9201 or extracted constant positions and/or sizes aren't byte aligned. */
9203 /* Shift left the bytes in PTR of SZ elements by AMNT bits, carrying over the
9204 bits between adjacent elements. AMNT should be within
9205 [0, BITS_PER_UNIT).
9206 Example, AMNT = 2:
9207 00011111|11100000 << 2 = 01111111|10000000
9208 PTR[1] | PTR[0] PTR[1] | PTR[0]. */
9210 void
9211 shift_bytes_in_array_left (unsigned char *ptr, unsigned int sz,
9212 unsigned int amnt)
9214 if (amnt == 0)
9215 return;
9217 unsigned char carry_over = 0U;
9218 unsigned char carry_mask = (~0U) << (unsigned char) (BITS_PER_UNIT - amnt);
9219 unsigned char clear_mask = (~0U) << amnt;
9221 for (unsigned int i = 0; i < sz; i++)
9223 unsigned prev_carry_over = carry_over;
9224 carry_over = (ptr[i] & carry_mask) >> (BITS_PER_UNIT - amnt);
9226 ptr[i] <<= amnt;
9227 if (i != 0)
9229 ptr[i] &= clear_mask;
9230 ptr[i] |= prev_carry_over;
9235 /* Like shift_bytes_in_array_left but for big-endian.
9236 Shift right the bytes in PTR of SZ elements by AMNT bits, carrying over the
9237 bits between adjacent elements. AMNT should be within
9238 [0, BITS_PER_UNIT).
9239 Example, AMNT = 2:
9240 00011111|11100000 >> 2 = 00000111|11111000
9241 PTR[0] | PTR[1] PTR[0] | PTR[1]. */
9243 void
9244 shift_bytes_in_array_right (unsigned char *ptr, unsigned int sz,
9245 unsigned int amnt)
9247 if (amnt == 0)
9248 return;
9250 unsigned char carry_over = 0U;
9251 unsigned char carry_mask = ~(~0U << amnt);
9253 for (unsigned int i = 0; i < sz; i++)
9255 unsigned prev_carry_over = carry_over;
9256 carry_over = ptr[i] & carry_mask;
9258 carry_over <<= (unsigned char) BITS_PER_UNIT - amnt;
9259 ptr[i] >>= amnt;
9260 ptr[i] |= prev_carry_over;
9264 /* Try to view-convert VECTOR_CST EXPR to VECTOR_TYPE TYPE by operating
9265 directly on the VECTOR_CST encoding, in a way that works for variable-
9266 length vectors. Return the resulting VECTOR_CST on success or null
9267 on failure. */
9269 static tree
9270 fold_view_convert_vector_encoding (tree type, tree expr)
9272 tree expr_type = TREE_TYPE (expr);
9273 poly_uint64 type_bits, expr_bits;
9274 if (!poly_int_tree_p (TYPE_SIZE (type), &type_bits)
9275 || !poly_int_tree_p (TYPE_SIZE (expr_type), &expr_bits))
9276 return NULL_TREE;
9278 poly_uint64 type_units = TYPE_VECTOR_SUBPARTS (type);
9279 poly_uint64 expr_units = TYPE_VECTOR_SUBPARTS (expr_type);
9280 unsigned int type_elt_bits = vector_element_size (type_bits, type_units);
9281 unsigned int expr_elt_bits = vector_element_size (expr_bits, expr_units);
9283 /* We can only preserve the semantics of a stepped pattern if the new
9284 vector element is an integer of the same size. */
9285 if (VECTOR_CST_STEPPED_P (expr)
9286 && (!INTEGRAL_TYPE_P (type) || type_elt_bits != expr_elt_bits))
9287 return NULL_TREE;
9289 /* The number of bits needed to encode one element from every pattern
9290 of the original vector. */
9291 unsigned int expr_sequence_bits
9292 = VECTOR_CST_NPATTERNS (expr) * expr_elt_bits;
9294 /* The number of bits needed to encode one element from every pattern
9295 of the result. */
9296 unsigned int type_sequence_bits
9297 = least_common_multiple (expr_sequence_bits, type_elt_bits);
9299 /* Don't try to read more bytes than are available, which can happen
9300 for constant-sized vectors if TYPE has larger elements than EXPR_TYPE.
9301 The general VIEW_CONVERT handling can cope with that case, so there's
9302 no point complicating things here. */
9303 unsigned int nelts_per_pattern = VECTOR_CST_NELTS_PER_PATTERN (expr);
9304 unsigned int buffer_bytes = CEIL (nelts_per_pattern * type_sequence_bits,
9305 BITS_PER_UNIT);
9306 unsigned int buffer_bits = buffer_bytes * BITS_PER_UNIT;
9307 if (known_gt (buffer_bits, expr_bits))
9308 return NULL_TREE;
9310 /* Get enough bytes of EXPR to form the new encoding. */
9311 auto_vec<unsigned char, 128> buffer (buffer_bytes);
9312 buffer.quick_grow (buffer_bytes);
9313 if (native_encode_vector_part (expr, buffer.address (), buffer_bytes, 0,
9314 buffer_bits / expr_elt_bits)
9315 != (int) buffer_bytes)
9316 return NULL_TREE;
9318 /* Reencode the bytes as TYPE. */
9319 unsigned int type_npatterns = type_sequence_bits / type_elt_bits;
9320 return native_interpret_vector_part (type, &buffer[0], buffer.length (),
9321 type_npatterns, nelts_per_pattern);
9324 /* Fold a VIEW_CONVERT_EXPR of a constant expression EXPR to type
9325 TYPE at compile-time. If we're unable to perform the conversion
9326 return NULL_TREE. */
9328 static tree
9329 fold_view_convert_expr (tree type, tree expr)
9331 unsigned char buffer[128];
9332 unsigned char *buf;
9333 int len;
9334 HOST_WIDE_INT l;
9336 /* Check that the host and target are sane. */
9337 if (CHAR_BIT != 8 || BITS_PER_UNIT != 8)
9338 return NULL_TREE;
9340 if (VECTOR_TYPE_P (type) && TREE_CODE (expr) == VECTOR_CST)
9341 if (tree res = fold_view_convert_vector_encoding (type, expr))
9342 return res;
9344 l = int_size_in_bytes (type);
9345 if (l > (int) sizeof (buffer)
9346 && l <= WIDE_INT_MAX_PRECISION / BITS_PER_UNIT)
9348 buf = XALLOCAVEC (unsigned char, l);
9349 len = l;
9351 else
9353 buf = buffer;
9354 len = sizeof (buffer);
9356 len = native_encode_expr (expr, buf, len);
9357 if (len == 0)
9358 return NULL_TREE;
9360 return native_interpret_expr (type, buf, len);
9363 /* Build an expression for the address of T. Folds away INDIRECT_REF
9364 to avoid confusing the gimplify process. */
9366 tree
9367 build_fold_addr_expr_with_type_loc (location_t loc, tree t, tree ptrtype)
9369 /* The size of the object is not relevant when talking about its address. */
9370 if (TREE_CODE (t) == WITH_SIZE_EXPR)
9371 t = TREE_OPERAND (t, 0);
9373 if (INDIRECT_REF_P (t))
9375 t = TREE_OPERAND (t, 0);
9377 if (TREE_TYPE (t) != ptrtype)
9378 t = build1_loc (loc, NOP_EXPR, ptrtype, t);
9380 else if (TREE_CODE (t) == MEM_REF
9381 && integer_zerop (TREE_OPERAND (t, 1)))
9383 t = TREE_OPERAND (t, 0);
9385 if (TREE_TYPE (t) != ptrtype)
9386 t = fold_convert_loc (loc, ptrtype, t);
9388 else if (TREE_CODE (t) == MEM_REF
9389 && TREE_CODE (TREE_OPERAND (t, 0)) == INTEGER_CST)
9390 return fold_binary (POINTER_PLUS_EXPR, ptrtype,
9391 TREE_OPERAND (t, 0),
9392 convert_to_ptrofftype (TREE_OPERAND (t, 1)));
9393 else if (TREE_CODE (t) == VIEW_CONVERT_EXPR)
9395 t = build_fold_addr_expr_loc (loc, TREE_OPERAND (t, 0));
9397 if (TREE_TYPE (t) != ptrtype)
9398 t = fold_convert_loc (loc, ptrtype, t);
9400 else
9401 t = build1_loc (loc, ADDR_EXPR, ptrtype, t);
9403 return t;
9406 /* Build an expression for the address of T. */
9408 tree
9409 build_fold_addr_expr_loc (location_t loc, tree t)
9411 tree ptrtype = build_pointer_type (TREE_TYPE (t));
9413 return build_fold_addr_expr_with_type_loc (loc, t, ptrtype);
9416 /* Fold a unary expression of code CODE and type TYPE with operand
9417 OP0. Return the folded expression if folding is successful.
9418 Otherwise, return NULL_TREE. */
9420 tree
9421 fold_unary_loc (location_t loc, enum tree_code code, tree type, tree op0)
9423 tree tem;
9424 tree arg0;
9425 enum tree_code_class kind = TREE_CODE_CLASS (code);
9427 gcc_assert (IS_EXPR_CODE_CLASS (kind)
9428 && TREE_CODE_LENGTH (code) == 1);
9430 arg0 = op0;
9431 if (arg0)
9433 if (CONVERT_EXPR_CODE_P (code)
9434 || code == FLOAT_EXPR || code == ABS_EXPR || code == NEGATE_EXPR)
9436 /* Don't use STRIP_NOPS, because signedness of argument type
9437 matters. */
9438 STRIP_SIGN_NOPS (arg0);
9440 else
9442 /* Strip any conversions that don't change the mode. This
9443 is safe for every expression, except for a comparison
9444 expression because its signedness is derived from its
9445 operands.
9447 Note that this is done as an internal manipulation within
9448 the constant folder, in order to find the simplest
9449 representation of the arguments so that their form can be
9450 studied. In any cases, the appropriate type conversions
9451 should be put back in the tree that will get out of the
9452 constant folder. */
9453 STRIP_NOPS (arg0);
9456 if (CONSTANT_CLASS_P (arg0))
9458 tree tem = const_unop (code, type, arg0);
9459 if (tem)
9461 if (TREE_TYPE (tem) != type)
9462 tem = fold_convert_loc (loc, type, tem);
9463 return tem;
9468 tem = generic_simplify (loc, code, type, op0);
9469 if (tem)
9470 return tem;
9472 if (TREE_CODE_CLASS (code) == tcc_unary)
9474 if (TREE_CODE (arg0) == COMPOUND_EXPR)
9475 return build2 (COMPOUND_EXPR, type, TREE_OPERAND (arg0, 0),
9476 fold_build1_loc (loc, code, type,
9477 fold_convert_loc (loc, TREE_TYPE (op0),
9478 TREE_OPERAND (arg0, 1))));
9479 else if (TREE_CODE (arg0) == COND_EXPR)
9481 tree arg01 = TREE_OPERAND (arg0, 1);
9482 tree arg02 = TREE_OPERAND (arg0, 2);
9483 if (! VOID_TYPE_P (TREE_TYPE (arg01)))
9484 arg01 = fold_build1_loc (loc, code, type,
9485 fold_convert_loc (loc,
9486 TREE_TYPE (op0), arg01));
9487 if (! VOID_TYPE_P (TREE_TYPE (arg02)))
9488 arg02 = fold_build1_loc (loc, code, type,
9489 fold_convert_loc (loc,
9490 TREE_TYPE (op0), arg02));
9491 tem = fold_build3_loc (loc, COND_EXPR, type, TREE_OPERAND (arg0, 0),
9492 arg01, arg02);
9494 /* If this was a conversion, and all we did was to move into
9495 inside the COND_EXPR, bring it back out. But leave it if
9496 it is a conversion from integer to integer and the
9497 result precision is no wider than a word since such a
9498 conversion is cheap and may be optimized away by combine,
9499 while it couldn't if it were outside the COND_EXPR. Then return
9500 so we don't get into an infinite recursion loop taking the
9501 conversion out and then back in. */
9503 if ((CONVERT_EXPR_CODE_P (code)
9504 || code == NON_LVALUE_EXPR)
9505 && TREE_CODE (tem) == COND_EXPR
9506 && TREE_CODE (TREE_OPERAND (tem, 1)) == code
9507 && TREE_CODE (TREE_OPERAND (tem, 2)) == code
9508 && ! VOID_TYPE_P (TREE_TYPE (TREE_OPERAND (tem, 1)))
9509 && ! VOID_TYPE_P (TREE_TYPE (TREE_OPERAND (tem, 2)))
9510 && (TREE_TYPE (TREE_OPERAND (TREE_OPERAND (tem, 1), 0))
9511 == TREE_TYPE (TREE_OPERAND (TREE_OPERAND (tem, 2), 0)))
9512 && (! (INTEGRAL_TYPE_P (TREE_TYPE (tem))
9513 && (INTEGRAL_TYPE_P
9514 (TREE_TYPE (TREE_OPERAND (TREE_OPERAND (tem, 1), 0))))
9515 && TYPE_PRECISION (TREE_TYPE (tem)) <= BITS_PER_WORD)
9516 || flag_syntax_only))
9517 tem = build1_loc (loc, code, type,
9518 build3 (COND_EXPR,
9519 TREE_TYPE (TREE_OPERAND
9520 (TREE_OPERAND (tem, 1), 0)),
9521 TREE_OPERAND (tem, 0),
9522 TREE_OPERAND (TREE_OPERAND (tem, 1), 0),
9523 TREE_OPERAND (TREE_OPERAND (tem, 2),
9524 0)));
9525 return tem;
9529 switch (code)
9531 case NON_LVALUE_EXPR:
9532 if (!maybe_lvalue_p (op0))
9533 return fold_convert_loc (loc, type, op0);
9534 return NULL_TREE;
9536 CASE_CONVERT:
9537 case FLOAT_EXPR:
9538 case FIX_TRUNC_EXPR:
9539 if (COMPARISON_CLASS_P (op0))
9541 /* If we have (type) (a CMP b) and type is an integral type, return
9542 new expression involving the new type. Canonicalize
9543 (type) (a CMP b) to (a CMP b) ? (type) true : (type) false for
9544 non-integral type.
9545 Do not fold the result as that would not simplify further, also
9546 folding again results in recursions. */
9547 if (TREE_CODE (type) == BOOLEAN_TYPE)
9548 return build2_loc (loc, TREE_CODE (op0), type,
9549 TREE_OPERAND (op0, 0),
9550 TREE_OPERAND (op0, 1));
9551 else if (!INTEGRAL_TYPE_P (type) && !VOID_TYPE_P (type)
9552 && TREE_CODE (type) != VECTOR_TYPE)
9553 return build3_loc (loc, COND_EXPR, type, op0,
9554 constant_boolean_node (true, type),
9555 constant_boolean_node (false, type));
9558 /* Handle (T *)&A.B.C for A being of type T and B and C
9559 living at offset zero. This occurs frequently in
9560 C++ upcasting and then accessing the base. */
9561 if (TREE_CODE (op0) == ADDR_EXPR
9562 && POINTER_TYPE_P (type)
9563 && handled_component_p (TREE_OPERAND (op0, 0)))
9565 poly_int64 bitsize, bitpos;
9566 tree offset;
9567 machine_mode mode;
9568 int unsignedp, reversep, volatilep;
9569 tree base
9570 = get_inner_reference (TREE_OPERAND (op0, 0), &bitsize, &bitpos,
9571 &offset, &mode, &unsignedp, &reversep,
9572 &volatilep);
9573 /* If the reference was to a (constant) zero offset, we can use
9574 the address of the base if it has the same base type
9575 as the result type and the pointer type is unqualified. */
9576 if (!offset
9577 && known_eq (bitpos, 0)
9578 && (TYPE_MAIN_VARIANT (TREE_TYPE (type))
9579 == TYPE_MAIN_VARIANT (TREE_TYPE (base)))
9580 && TYPE_QUALS (type) == TYPE_UNQUALIFIED)
9581 return fold_convert_loc (loc, type,
9582 build_fold_addr_expr_loc (loc, base));
9585 if (TREE_CODE (op0) == MODIFY_EXPR
9586 && TREE_CONSTANT (TREE_OPERAND (op0, 1))
9587 /* Detect assigning a bitfield. */
9588 && !(TREE_CODE (TREE_OPERAND (op0, 0)) == COMPONENT_REF
9589 && DECL_BIT_FIELD
9590 (TREE_OPERAND (TREE_OPERAND (op0, 0), 1))))
9592 /* Don't leave an assignment inside a conversion
9593 unless assigning a bitfield. */
9594 tem = fold_build1_loc (loc, code, type, TREE_OPERAND (op0, 1));
9595 /* First do the assignment, then return converted constant. */
9596 tem = build2_loc (loc, COMPOUND_EXPR, TREE_TYPE (tem), op0, tem);
9597 suppress_warning (tem /* What warning? */);
9598 TREE_USED (tem) = 1;
9599 return tem;
9602 /* Convert (T)(x & c) into (T)x & (T)c, if c is an integer
9603 constants (if x has signed type, the sign bit cannot be set
9604 in c). This folds extension into the BIT_AND_EXPR.
9605 ??? We don't do it for BOOLEAN_TYPE or ENUMERAL_TYPE because they
9606 very likely don't have maximal range for their precision and this
9607 transformation effectively doesn't preserve non-maximal ranges. */
9608 if (TREE_CODE (type) == INTEGER_TYPE
9609 && TREE_CODE (op0) == BIT_AND_EXPR
9610 && TREE_CODE (TREE_OPERAND (op0, 1)) == INTEGER_CST)
9612 tree and_expr = op0;
9613 tree and0 = TREE_OPERAND (and_expr, 0);
9614 tree and1 = TREE_OPERAND (and_expr, 1);
9615 int change = 0;
9617 if (TYPE_UNSIGNED (TREE_TYPE (and_expr))
9618 || (TYPE_PRECISION (type)
9619 <= TYPE_PRECISION (TREE_TYPE (and_expr))))
9620 change = 1;
9621 else if (TYPE_PRECISION (TREE_TYPE (and1))
9622 <= HOST_BITS_PER_WIDE_INT
9623 && tree_fits_uhwi_p (and1))
9625 unsigned HOST_WIDE_INT cst;
9627 cst = tree_to_uhwi (and1);
9628 cst &= HOST_WIDE_INT_M1U
9629 << (TYPE_PRECISION (TREE_TYPE (and1)) - 1);
9630 change = (cst == 0);
9631 if (change
9632 && !flag_syntax_only
9633 && (load_extend_op (TYPE_MODE (TREE_TYPE (and0)))
9634 == ZERO_EXTEND))
9636 tree uns = unsigned_type_for (TREE_TYPE (and0));
9637 and0 = fold_convert_loc (loc, uns, and0);
9638 and1 = fold_convert_loc (loc, uns, and1);
9641 if (change)
9643 tree and1_type = TREE_TYPE (and1);
9644 unsigned prec = MAX (TYPE_PRECISION (and1_type),
9645 TYPE_PRECISION (type));
9646 tem = force_fit_type (type,
9647 wide_int::from (wi::to_wide (and1), prec,
9648 TYPE_SIGN (and1_type)),
9649 0, TREE_OVERFLOW (and1));
9650 return fold_build2_loc (loc, BIT_AND_EXPR, type,
9651 fold_convert_loc (loc, type, and0), tem);
9655 /* Convert (T1)(X p+ Y) into ((T1)X p+ Y), for pointer type, when the new
9656 cast (T1)X will fold away. We assume that this happens when X itself
9657 is a cast. */
9658 if (POINTER_TYPE_P (type)
9659 && TREE_CODE (arg0) == POINTER_PLUS_EXPR
9660 && CONVERT_EXPR_P (TREE_OPERAND (arg0, 0)))
9662 tree arg00 = TREE_OPERAND (arg0, 0);
9663 tree arg01 = TREE_OPERAND (arg0, 1);
9665 /* If -fsanitize=alignment, avoid this optimization in GENERIC
9666 when the pointed type needs higher alignment than
9667 the p+ first operand's pointed type. */
9668 if (!in_gimple_form
9669 && sanitize_flags_p (SANITIZE_ALIGNMENT)
9670 && (min_align_of_type (TREE_TYPE (type))
9671 > min_align_of_type (TREE_TYPE (TREE_TYPE (arg00)))))
9672 return NULL_TREE;
9674 /* Similarly, avoid this optimization in GENERIC for -fsanitize=null
9675 when type is a reference type and arg00's type is not,
9676 because arg00 could be validly nullptr and if arg01 doesn't return,
9677 we don't want false positive binding of reference to nullptr. */
9678 if (TREE_CODE (type) == REFERENCE_TYPE
9679 && !in_gimple_form
9680 && sanitize_flags_p (SANITIZE_NULL)
9681 && TREE_CODE (TREE_TYPE (arg00)) != REFERENCE_TYPE)
9682 return NULL_TREE;
9684 arg00 = fold_convert_loc (loc, type, arg00);
9685 return fold_build_pointer_plus_loc (loc, arg00, arg01);
9688 /* Convert (T1)(~(T2)X) into ~(T1)X if T1 and T2 are integral types
9689 of the same precision, and X is an integer type not narrower than
9690 types T1 or T2, i.e. the cast (T2)X isn't an extension. */
9691 if (INTEGRAL_TYPE_P (type)
9692 && TREE_CODE (op0) == BIT_NOT_EXPR
9693 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
9694 && CONVERT_EXPR_P (TREE_OPERAND (op0, 0))
9695 && TYPE_PRECISION (type) == TYPE_PRECISION (TREE_TYPE (op0)))
9697 tem = TREE_OPERAND (TREE_OPERAND (op0, 0), 0);
9698 if (INTEGRAL_TYPE_P (TREE_TYPE (tem))
9699 && TYPE_PRECISION (type) <= TYPE_PRECISION (TREE_TYPE (tem)))
9700 return fold_build1_loc (loc, BIT_NOT_EXPR, type,
9701 fold_convert_loc (loc, type, tem));
9704 /* Convert (T1)(X * Y) into (T1)X * (T1)Y if T1 is narrower than the
9705 type of X and Y (integer types only). */
9706 if (INTEGRAL_TYPE_P (type)
9707 && TREE_CODE (op0) == MULT_EXPR
9708 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
9709 && TYPE_PRECISION (type) < TYPE_PRECISION (TREE_TYPE (op0))
9710 && (TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0))
9711 || !sanitize_flags_p (SANITIZE_SI_OVERFLOW)))
9713 /* Be careful not to introduce new overflows. */
9714 tree mult_type;
9715 if (TYPE_OVERFLOW_WRAPS (type))
9716 mult_type = type;
9717 else
9718 mult_type = unsigned_type_for (type);
9720 if (TYPE_PRECISION (mult_type) < TYPE_PRECISION (TREE_TYPE (op0)))
9722 tem = fold_build2_loc (loc, MULT_EXPR, mult_type,
9723 fold_convert_loc (loc, mult_type,
9724 TREE_OPERAND (op0, 0)),
9725 fold_convert_loc (loc, mult_type,
9726 TREE_OPERAND (op0, 1)));
9727 return fold_convert_loc (loc, type, tem);
9731 return NULL_TREE;
9733 case VIEW_CONVERT_EXPR:
9734 if (TREE_CODE (op0) == MEM_REF)
9736 if (TYPE_ALIGN (TREE_TYPE (op0)) != TYPE_ALIGN (type))
9737 type = build_aligned_type (type, TYPE_ALIGN (TREE_TYPE (op0)));
9738 tem = fold_build2_loc (loc, MEM_REF, type,
9739 TREE_OPERAND (op0, 0), TREE_OPERAND (op0, 1));
9740 REF_REVERSE_STORAGE_ORDER (tem) = REF_REVERSE_STORAGE_ORDER (op0);
9741 return tem;
9744 return NULL_TREE;
9746 case NEGATE_EXPR:
9747 tem = fold_negate_expr (loc, arg0);
9748 if (tem)
9749 return fold_convert_loc (loc, type, tem);
9750 return NULL_TREE;
9752 case ABS_EXPR:
9753 /* Convert fabs((double)float) into (double)fabsf(float). */
9754 if (TREE_CODE (arg0) == NOP_EXPR
9755 && TREE_CODE (type) == REAL_TYPE)
9757 tree targ0 = strip_float_extensions (arg0);
9758 if (targ0 != arg0)
9759 return fold_convert_loc (loc, type,
9760 fold_build1_loc (loc, ABS_EXPR,
9761 TREE_TYPE (targ0),
9762 targ0));
9764 return NULL_TREE;
9766 case BIT_NOT_EXPR:
9767 /* Convert ~(X ^ Y) to ~X ^ Y or X ^ ~Y if ~X or ~Y simplify. */
9768 if (TREE_CODE (arg0) == BIT_XOR_EXPR
9769 && (tem = fold_unary_loc (loc, BIT_NOT_EXPR, type,
9770 fold_convert_loc (loc, type,
9771 TREE_OPERAND (arg0, 0)))))
9772 return fold_build2_loc (loc, BIT_XOR_EXPR, type, tem,
9773 fold_convert_loc (loc, type,
9774 TREE_OPERAND (arg0, 1)));
9775 else if (TREE_CODE (arg0) == BIT_XOR_EXPR
9776 && (tem = fold_unary_loc (loc, BIT_NOT_EXPR, type,
9777 fold_convert_loc (loc, type,
9778 TREE_OPERAND (arg0, 1)))))
9779 return fold_build2_loc (loc, BIT_XOR_EXPR, type,
9780 fold_convert_loc (loc, type,
9781 TREE_OPERAND (arg0, 0)), tem);
9783 return NULL_TREE;
9785 case TRUTH_NOT_EXPR:
9786 /* Note that the operand of this must be an int
9787 and its values must be 0 or 1.
9788 ("true" is a fixed value perhaps depending on the language,
9789 but we don't handle values other than 1 correctly yet.) */
9790 tem = fold_truth_not_expr (loc, arg0);
9791 if (!tem)
9792 return NULL_TREE;
9793 return fold_convert_loc (loc, type, tem);
9795 case INDIRECT_REF:
9796 /* Fold *&X to X if X is an lvalue. */
9797 if (TREE_CODE (op0) == ADDR_EXPR)
9799 tree op00 = TREE_OPERAND (op0, 0);
9800 if ((VAR_P (op00)
9801 || TREE_CODE (op00) == PARM_DECL
9802 || TREE_CODE (op00) == RESULT_DECL)
9803 && !TREE_READONLY (op00))
9804 return op00;
9806 return NULL_TREE;
9808 default:
9809 return NULL_TREE;
9810 } /* switch (code) */
9814 /* If the operation was a conversion do _not_ mark a resulting constant
9815 with TREE_OVERFLOW if the original constant was not. These conversions
9816 have implementation defined behavior and retaining the TREE_OVERFLOW
9817 flag here would confuse later passes such as VRP. */
9818 tree
9819 fold_unary_ignore_overflow_loc (location_t loc, enum tree_code code,
9820 tree type, tree op0)
9822 tree res = fold_unary_loc (loc, code, type, op0);
9823 if (res
9824 && TREE_CODE (res) == INTEGER_CST
9825 && TREE_CODE (op0) == INTEGER_CST
9826 && CONVERT_EXPR_CODE_P (code))
9827 TREE_OVERFLOW (res) = TREE_OVERFLOW (op0);
9829 return res;
9832 /* Fold a binary bitwise/truth expression of code CODE and type TYPE with
9833 operands OP0 and OP1. LOC is the location of the resulting expression.
9834 ARG0 and ARG1 are the NOP_STRIPed results of OP0 and OP1.
9835 Return the folded expression if folding is successful. Otherwise,
9836 return NULL_TREE. */
9837 static tree
9838 fold_truth_andor (location_t loc, enum tree_code code, tree type,
9839 tree arg0, tree arg1, tree op0, tree op1)
9841 tree tem;
9843 /* We only do these simplifications if we are optimizing. */
9844 if (!optimize)
9845 return NULL_TREE;
9847 /* Check for things like (A || B) && (A || C). We can convert this
9848 to A || (B && C). Note that either operator can be any of the four
9849 truth and/or operations and the transformation will still be
9850 valid. Also note that we only care about order for the
9851 ANDIF and ORIF operators. If B contains side effects, this
9852 might change the truth-value of A. */
9853 if (TREE_CODE (arg0) == TREE_CODE (arg1)
9854 && (TREE_CODE (arg0) == TRUTH_ANDIF_EXPR
9855 || TREE_CODE (arg0) == TRUTH_ORIF_EXPR
9856 || TREE_CODE (arg0) == TRUTH_AND_EXPR
9857 || TREE_CODE (arg0) == TRUTH_OR_EXPR)
9858 && ! TREE_SIDE_EFFECTS (TREE_OPERAND (arg0, 1)))
9860 tree a00 = TREE_OPERAND (arg0, 0);
9861 tree a01 = TREE_OPERAND (arg0, 1);
9862 tree a10 = TREE_OPERAND (arg1, 0);
9863 tree a11 = TREE_OPERAND (arg1, 1);
9864 bool commutative = ((TREE_CODE (arg0) == TRUTH_OR_EXPR
9865 || TREE_CODE (arg0) == TRUTH_AND_EXPR)
9866 && (code == TRUTH_AND_EXPR
9867 || code == TRUTH_OR_EXPR));
9869 if (operand_equal_p (a00, a10, 0))
9870 return fold_build2_loc (loc, TREE_CODE (arg0), type, a00,
9871 fold_build2_loc (loc, code, type, a01, a11));
9872 else if (commutative && operand_equal_p (a00, a11, 0))
9873 return fold_build2_loc (loc, TREE_CODE (arg0), type, a00,
9874 fold_build2_loc (loc, code, type, a01, a10));
9875 else if (commutative && operand_equal_p (a01, a10, 0))
9876 return fold_build2_loc (loc, TREE_CODE (arg0), type, a01,
9877 fold_build2_loc (loc, code, type, a00, a11));
9879 /* This case if tricky because we must either have commutative
9880 operators or else A10 must not have side-effects. */
9882 else if ((commutative || ! TREE_SIDE_EFFECTS (a10))
9883 && operand_equal_p (a01, a11, 0))
9884 return fold_build2_loc (loc, TREE_CODE (arg0), type,
9885 fold_build2_loc (loc, code, type, a00, a10),
9886 a01);
9889 /* See if we can build a range comparison. */
9890 if ((tem = fold_range_test (loc, code, type, op0, op1)) != 0)
9891 return tem;
9893 if ((code == TRUTH_ANDIF_EXPR && TREE_CODE (arg0) == TRUTH_ORIF_EXPR)
9894 || (code == TRUTH_ORIF_EXPR && TREE_CODE (arg0) == TRUTH_ANDIF_EXPR))
9896 tem = merge_truthop_with_opposite_arm (loc, arg0, arg1, true);
9897 if (tem)
9898 return fold_build2_loc (loc, code, type, tem, arg1);
9901 if ((code == TRUTH_ANDIF_EXPR && TREE_CODE (arg1) == TRUTH_ORIF_EXPR)
9902 || (code == TRUTH_ORIF_EXPR && TREE_CODE (arg1) == TRUTH_ANDIF_EXPR))
9904 tem = merge_truthop_with_opposite_arm (loc, arg1, arg0, false);
9905 if (tem)
9906 return fold_build2_loc (loc, code, type, arg0, tem);
9909 /* Check for the possibility of merging component references. If our
9910 lhs is another similar operation, try to merge its rhs with our
9911 rhs. Then try to merge our lhs and rhs. */
9912 if (TREE_CODE (arg0) == code
9913 && (tem = fold_truth_andor_1 (loc, code, type,
9914 TREE_OPERAND (arg0, 1), arg1)) != 0)
9915 return fold_build2_loc (loc, code, type, TREE_OPERAND (arg0, 0), tem);
9917 if ((tem = fold_truth_andor_1 (loc, code, type, arg0, arg1)) != 0)
9918 return tem;
9920 bool logical_op_non_short_circuit = LOGICAL_OP_NON_SHORT_CIRCUIT;
9921 if (param_logical_op_non_short_circuit != -1)
9922 logical_op_non_short_circuit
9923 = param_logical_op_non_short_circuit;
9924 if (logical_op_non_short_circuit
9925 && !sanitize_coverage_p ()
9926 && (code == TRUTH_AND_EXPR
9927 || code == TRUTH_ANDIF_EXPR
9928 || code == TRUTH_OR_EXPR
9929 || code == TRUTH_ORIF_EXPR))
9931 enum tree_code ncode, icode;
9933 ncode = (code == TRUTH_ANDIF_EXPR || code == TRUTH_AND_EXPR)
9934 ? TRUTH_AND_EXPR : TRUTH_OR_EXPR;
9935 icode = ncode == TRUTH_AND_EXPR ? TRUTH_ANDIF_EXPR : TRUTH_ORIF_EXPR;
9937 /* Transform ((A AND-IF B) AND[-IF] C) into (A AND-IF (B AND C)),
9938 or ((A OR-IF B) OR[-IF] C) into (A OR-IF (B OR C))
9939 We don't want to pack more than two leafs to a non-IF AND/OR
9940 expression.
9941 If tree-code of left-hand operand isn't an AND/OR-IF code and not
9942 equal to IF-CODE, then we don't want to add right-hand operand.
9943 If the inner right-hand side of left-hand operand has
9944 side-effects, or isn't simple, then we can't add to it,
9945 as otherwise we might destroy if-sequence. */
9946 if (TREE_CODE (arg0) == icode
9947 && simple_condition_p (arg1)
9948 /* Needed for sequence points to handle trappings, and
9949 side-effects. */
9950 && simple_condition_p (TREE_OPERAND (arg0, 1)))
9952 tem = fold_build2_loc (loc, ncode, type, TREE_OPERAND (arg0, 1),
9953 arg1);
9954 return fold_build2_loc (loc, icode, type, TREE_OPERAND (arg0, 0),
9955 tem);
9957 /* Same as above but for (A AND[-IF] (B AND-IF C)) -> ((A AND B) AND-IF C),
9958 or (A OR[-IF] (B OR-IF C) -> ((A OR B) OR-IF C). */
9959 else if (TREE_CODE (arg1) == icode
9960 && simple_condition_p (arg0)
9961 /* Needed for sequence points to handle trappings, and
9962 side-effects. */
9963 && simple_condition_p (TREE_OPERAND (arg1, 0)))
9965 tem = fold_build2_loc (loc, ncode, type,
9966 arg0, TREE_OPERAND (arg1, 0));
9967 return fold_build2_loc (loc, icode, type, tem,
9968 TREE_OPERAND (arg1, 1));
9970 /* Transform (A AND-IF B) into (A AND B), or (A OR-IF B)
9971 into (A OR B).
9972 For sequence point consistancy, we need to check for trapping,
9973 and side-effects. */
9974 else if (code == icode && simple_condition_p (arg0)
9975 && simple_condition_p (arg1))
9976 return fold_build2_loc (loc, ncode, type, arg0, arg1);
9979 return NULL_TREE;
9982 /* Helper that tries to canonicalize the comparison ARG0 CODE ARG1
9983 by changing CODE to reduce the magnitude of constants involved in
9984 ARG0 of the comparison.
9985 Returns a canonicalized comparison tree if a simplification was
9986 possible, otherwise returns NULL_TREE.
9987 Set *STRICT_OVERFLOW_P to true if the canonicalization is only
9988 valid if signed overflow is undefined. */
9990 static tree
9991 maybe_canonicalize_comparison_1 (location_t loc, enum tree_code code, tree type,
9992 tree arg0, tree arg1,
9993 bool *strict_overflow_p)
9995 enum tree_code code0 = TREE_CODE (arg0);
9996 tree t, cst0 = NULL_TREE;
9997 int sgn0;
9999 /* Match A +- CST code arg1. We can change this only if overflow
10000 is undefined. */
10001 if (!((ANY_INTEGRAL_TYPE_P (TREE_TYPE (arg0))
10002 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg0)))
10003 /* In principle pointers also have undefined overflow behavior,
10004 but that causes problems elsewhere. */
10005 && !POINTER_TYPE_P (TREE_TYPE (arg0))
10006 && (code0 == MINUS_EXPR
10007 || code0 == PLUS_EXPR)
10008 && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST))
10009 return NULL_TREE;
10011 /* Identify the constant in arg0 and its sign. */
10012 cst0 = TREE_OPERAND (arg0, 1);
10013 sgn0 = tree_int_cst_sgn (cst0);
10015 /* Overflowed constants and zero will cause problems. */
10016 if (integer_zerop (cst0)
10017 || TREE_OVERFLOW (cst0))
10018 return NULL_TREE;
10020 /* See if we can reduce the magnitude of the constant in
10021 arg0 by changing the comparison code. */
10022 /* A - CST < arg1 -> A - CST-1 <= arg1. */
10023 if (code == LT_EXPR
10024 && code0 == ((sgn0 == -1) ? PLUS_EXPR : MINUS_EXPR))
10025 code = LE_EXPR;
10026 /* A + CST > arg1 -> A + CST-1 >= arg1. */
10027 else if (code == GT_EXPR
10028 && code0 == ((sgn0 == -1) ? MINUS_EXPR : PLUS_EXPR))
10029 code = GE_EXPR;
10030 /* A + CST <= arg1 -> A + CST-1 < arg1. */
10031 else if (code == LE_EXPR
10032 && code0 == ((sgn0 == -1) ? MINUS_EXPR : PLUS_EXPR))
10033 code = LT_EXPR;
10034 /* A - CST >= arg1 -> A - CST-1 > arg1. */
10035 else if (code == GE_EXPR
10036 && code0 == ((sgn0 == -1) ? PLUS_EXPR : MINUS_EXPR))
10037 code = GT_EXPR;
10038 else
10039 return NULL_TREE;
10040 *strict_overflow_p = true;
10042 /* Now build the constant reduced in magnitude. But not if that
10043 would produce one outside of its types range. */
10044 if (INTEGRAL_TYPE_P (TREE_TYPE (cst0))
10045 && ((sgn0 == 1
10046 && TYPE_MIN_VALUE (TREE_TYPE (cst0))
10047 && tree_int_cst_equal (cst0, TYPE_MIN_VALUE (TREE_TYPE (cst0))))
10048 || (sgn0 == -1
10049 && TYPE_MAX_VALUE (TREE_TYPE (cst0))
10050 && tree_int_cst_equal (cst0, TYPE_MAX_VALUE (TREE_TYPE (cst0))))))
10051 return NULL_TREE;
10053 t = int_const_binop (sgn0 == -1 ? PLUS_EXPR : MINUS_EXPR,
10054 cst0, build_int_cst (TREE_TYPE (cst0), 1));
10055 t = fold_build2_loc (loc, code0, TREE_TYPE (arg0), TREE_OPERAND (arg0, 0), t);
10056 t = fold_convert (TREE_TYPE (arg1), t);
10058 return fold_build2_loc (loc, code, type, t, arg1);
10061 /* Canonicalize the comparison ARG0 CODE ARG1 with type TYPE with undefined
10062 overflow further. Try to decrease the magnitude of constants involved
10063 by changing LE_EXPR and GE_EXPR to LT_EXPR and GT_EXPR or vice versa
10064 and put sole constants at the second argument position.
10065 Returns the canonicalized tree if changed, otherwise NULL_TREE. */
10067 static tree
10068 maybe_canonicalize_comparison (location_t loc, enum tree_code code, tree type,
10069 tree arg0, tree arg1)
10071 tree t;
10072 bool strict_overflow_p;
10073 const char * const warnmsg = G_("assuming signed overflow does not occur "
10074 "when reducing constant in comparison");
10076 /* Try canonicalization by simplifying arg0. */
10077 strict_overflow_p = false;
10078 t = maybe_canonicalize_comparison_1 (loc, code, type, arg0, arg1,
10079 &strict_overflow_p);
10080 if (t)
10082 if (strict_overflow_p)
10083 fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_MAGNITUDE);
10084 return t;
10087 /* Try canonicalization by simplifying arg1 using the swapped
10088 comparison. */
10089 code = swap_tree_comparison (code);
10090 strict_overflow_p = false;
10091 t = maybe_canonicalize_comparison_1 (loc, code, type, arg1, arg0,
10092 &strict_overflow_p);
10093 if (t && strict_overflow_p)
10094 fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_MAGNITUDE);
10095 return t;
10098 /* Return whether BASE + OFFSET + BITPOS may wrap around the address
10099 space. This is used to avoid issuing overflow warnings for
10100 expressions like &p->x which cannot wrap. */
10102 static bool
10103 pointer_may_wrap_p (tree base, tree offset, poly_int64 bitpos)
10105 if (!POINTER_TYPE_P (TREE_TYPE (base)))
10106 return true;
10108 if (maybe_lt (bitpos, 0))
10109 return true;
10111 poly_wide_int wi_offset;
10112 int precision = TYPE_PRECISION (TREE_TYPE (base));
10113 if (offset == NULL_TREE)
10114 wi_offset = wi::zero (precision);
10115 else if (!poly_int_tree_p (offset) || TREE_OVERFLOW (offset))
10116 return true;
10117 else
10118 wi_offset = wi::to_poly_wide (offset);
10120 wi::overflow_type overflow;
10121 poly_wide_int units = wi::shwi (bits_to_bytes_round_down (bitpos),
10122 precision);
10123 poly_wide_int total = wi::add (wi_offset, units, UNSIGNED, &overflow);
10124 if (overflow)
10125 return true;
10127 poly_uint64 total_hwi, size;
10128 if (!total.to_uhwi (&total_hwi)
10129 || !poly_int_tree_p (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (base))),
10130 &size)
10131 || known_eq (size, 0U))
10132 return true;
10134 if (known_le (total_hwi, size))
10135 return false;
10137 /* We can do slightly better for SIZE if we have an ADDR_EXPR of an
10138 array. */
10139 if (TREE_CODE (base) == ADDR_EXPR
10140 && poly_int_tree_p (TYPE_SIZE_UNIT (TREE_TYPE (TREE_OPERAND (base, 0))),
10141 &size)
10142 && maybe_ne (size, 0U)
10143 && known_le (total_hwi, size))
10144 return false;
10146 return true;
10149 /* Return a positive integer when the symbol DECL is known to have
10150 a nonzero address, zero when it's known not to (e.g., it's a weak
10151 symbol), and a negative integer when the symbol is not yet in the
10152 symbol table and so whether or not its address is zero is unknown.
10153 For function local objects always return positive integer. */
10154 static int
10155 maybe_nonzero_address (tree decl)
10157 /* Normally, don't do anything for variables and functions before symtab is
10158 built; it is quite possible that DECL will be declared weak later.
10159 But if folding_initializer, we need a constant answer now, so create
10160 the symtab entry and prevent later weak declaration. */
10161 if (DECL_P (decl) && decl_in_symtab_p (decl))
10162 if (struct symtab_node *symbol
10163 = (folding_initializer
10164 ? symtab_node::get_create (decl)
10165 : symtab_node::get (decl)))
10166 return symbol->nonzero_address ();
10168 /* Function local objects are never NULL. */
10169 if (DECL_P (decl)
10170 && (DECL_CONTEXT (decl)
10171 && TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL
10172 && auto_var_in_fn_p (decl, DECL_CONTEXT (decl))))
10173 return 1;
10175 return -1;
10178 /* Subroutine of fold_binary. This routine performs all of the
10179 transformations that are common to the equality/inequality
10180 operators (EQ_EXPR and NE_EXPR) and the ordering operators
10181 (LT_EXPR, LE_EXPR, GE_EXPR and GT_EXPR). Callers other than
10182 fold_binary should call fold_binary. Fold a comparison with
10183 tree code CODE and type TYPE with operands OP0 and OP1. Return
10184 the folded comparison or NULL_TREE. */
10186 static tree
10187 fold_comparison (location_t loc, enum tree_code code, tree type,
10188 tree op0, tree op1)
10190 const bool equality_code = (code == EQ_EXPR || code == NE_EXPR);
10191 tree arg0, arg1, tem;
10193 arg0 = op0;
10194 arg1 = op1;
10196 STRIP_SIGN_NOPS (arg0);
10197 STRIP_SIGN_NOPS (arg1);
10199 /* For comparisons of pointers we can decompose it to a compile time
10200 comparison of the base objects and the offsets into the object.
10201 This requires at least one operand being an ADDR_EXPR or a
10202 POINTER_PLUS_EXPR to do more than the operand_equal_p test below. */
10203 if (POINTER_TYPE_P (TREE_TYPE (arg0))
10204 && (TREE_CODE (arg0) == ADDR_EXPR
10205 || TREE_CODE (arg1) == ADDR_EXPR
10206 || TREE_CODE (arg0) == POINTER_PLUS_EXPR
10207 || TREE_CODE (arg1) == POINTER_PLUS_EXPR))
10209 tree base0, base1, offset0 = NULL_TREE, offset1 = NULL_TREE;
10210 poly_int64 bitsize, bitpos0 = 0, bitpos1 = 0;
10211 machine_mode mode;
10212 int volatilep, reversep, unsignedp;
10213 bool indirect_base0 = false, indirect_base1 = false;
10215 /* Get base and offset for the access. Strip ADDR_EXPR for
10216 get_inner_reference, but put it back by stripping INDIRECT_REF
10217 off the base object if possible. indirect_baseN will be true
10218 if baseN is not an address but refers to the object itself. */
10219 base0 = arg0;
10220 if (TREE_CODE (arg0) == ADDR_EXPR)
10222 base0
10223 = get_inner_reference (TREE_OPERAND (arg0, 0),
10224 &bitsize, &bitpos0, &offset0, &mode,
10225 &unsignedp, &reversep, &volatilep);
10226 if (INDIRECT_REF_P (base0))
10227 base0 = TREE_OPERAND (base0, 0);
10228 else
10229 indirect_base0 = true;
10231 else if (TREE_CODE (arg0) == POINTER_PLUS_EXPR)
10233 base0 = TREE_OPERAND (arg0, 0);
10234 STRIP_SIGN_NOPS (base0);
10235 if (TREE_CODE (base0) == ADDR_EXPR)
10237 base0
10238 = get_inner_reference (TREE_OPERAND (base0, 0),
10239 &bitsize, &bitpos0, &offset0, &mode,
10240 &unsignedp, &reversep, &volatilep);
10241 if (INDIRECT_REF_P (base0))
10242 base0 = TREE_OPERAND (base0, 0);
10243 else
10244 indirect_base0 = true;
10246 if (offset0 == NULL_TREE || integer_zerop (offset0))
10247 offset0 = TREE_OPERAND (arg0, 1);
10248 else
10249 offset0 = size_binop (PLUS_EXPR, offset0,
10250 TREE_OPERAND (arg0, 1));
10251 if (poly_int_tree_p (offset0))
10253 poly_offset_int tem = wi::sext (wi::to_poly_offset (offset0),
10254 TYPE_PRECISION (sizetype));
10255 tem <<= LOG2_BITS_PER_UNIT;
10256 tem += bitpos0;
10257 if (tem.to_shwi (&bitpos0))
10258 offset0 = NULL_TREE;
10262 base1 = arg1;
10263 if (TREE_CODE (arg1) == ADDR_EXPR)
10265 base1
10266 = get_inner_reference (TREE_OPERAND (arg1, 0),
10267 &bitsize, &bitpos1, &offset1, &mode,
10268 &unsignedp, &reversep, &volatilep);
10269 if (INDIRECT_REF_P (base1))
10270 base1 = TREE_OPERAND (base1, 0);
10271 else
10272 indirect_base1 = true;
10274 else if (TREE_CODE (arg1) == POINTER_PLUS_EXPR)
10276 base1 = TREE_OPERAND (arg1, 0);
10277 STRIP_SIGN_NOPS (base1);
10278 if (TREE_CODE (base1) == ADDR_EXPR)
10280 base1
10281 = get_inner_reference (TREE_OPERAND (base1, 0),
10282 &bitsize, &bitpos1, &offset1, &mode,
10283 &unsignedp, &reversep, &volatilep);
10284 if (INDIRECT_REF_P (base1))
10285 base1 = TREE_OPERAND (base1, 0);
10286 else
10287 indirect_base1 = true;
10289 if (offset1 == NULL_TREE || integer_zerop (offset1))
10290 offset1 = TREE_OPERAND (arg1, 1);
10291 else
10292 offset1 = size_binop (PLUS_EXPR, offset1,
10293 TREE_OPERAND (arg1, 1));
10294 if (poly_int_tree_p (offset1))
10296 poly_offset_int tem = wi::sext (wi::to_poly_offset (offset1),
10297 TYPE_PRECISION (sizetype));
10298 tem <<= LOG2_BITS_PER_UNIT;
10299 tem += bitpos1;
10300 if (tem.to_shwi (&bitpos1))
10301 offset1 = NULL_TREE;
10305 /* If we have equivalent bases we might be able to simplify. */
10306 if (indirect_base0 == indirect_base1
10307 && operand_equal_p (base0, base1,
10308 indirect_base0 ? OEP_ADDRESS_OF : 0))
10310 /* We can fold this expression to a constant if the non-constant
10311 offset parts are equal. */
10312 if ((offset0 == offset1
10313 || (offset0 && offset1
10314 && operand_equal_p (offset0, offset1, 0)))
10315 && (equality_code
10316 || (indirect_base0
10317 && (DECL_P (base0) || CONSTANT_CLASS_P (base0)))
10318 || TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg0))))
10320 if (!equality_code
10321 && maybe_ne (bitpos0, bitpos1)
10322 && (pointer_may_wrap_p (base0, offset0, bitpos0)
10323 || pointer_may_wrap_p (base1, offset1, bitpos1)))
10324 fold_overflow_warning (("assuming pointer wraparound does not "
10325 "occur when comparing P +- C1 with "
10326 "P +- C2"),
10327 WARN_STRICT_OVERFLOW_CONDITIONAL);
10329 switch (code)
10331 case EQ_EXPR:
10332 if (known_eq (bitpos0, bitpos1))
10333 return constant_boolean_node (true, type);
10334 if (known_ne (bitpos0, bitpos1))
10335 return constant_boolean_node (false, type);
10336 break;
10337 case NE_EXPR:
10338 if (known_ne (bitpos0, bitpos1))
10339 return constant_boolean_node (true, type);
10340 if (known_eq (bitpos0, bitpos1))
10341 return constant_boolean_node (false, type);
10342 break;
10343 case LT_EXPR:
10344 if (known_lt (bitpos0, bitpos1))
10345 return constant_boolean_node (true, type);
10346 if (known_ge (bitpos0, bitpos1))
10347 return constant_boolean_node (false, type);
10348 break;
10349 case LE_EXPR:
10350 if (known_le (bitpos0, bitpos1))
10351 return constant_boolean_node (true, type);
10352 if (known_gt (bitpos0, bitpos1))
10353 return constant_boolean_node (false, type);
10354 break;
10355 case GE_EXPR:
10356 if (known_ge (bitpos0, bitpos1))
10357 return constant_boolean_node (true, type);
10358 if (known_lt (bitpos0, bitpos1))
10359 return constant_boolean_node (false, type);
10360 break;
10361 case GT_EXPR:
10362 if (known_gt (bitpos0, bitpos1))
10363 return constant_boolean_node (true, type);
10364 if (known_le (bitpos0, bitpos1))
10365 return constant_boolean_node (false, type);
10366 break;
10367 default:;
10370 /* We can simplify the comparison to a comparison of the variable
10371 offset parts if the constant offset parts are equal.
10372 Be careful to use signed sizetype here because otherwise we
10373 mess with array offsets in the wrong way. This is possible
10374 because pointer arithmetic is restricted to retain within an
10375 object and overflow on pointer differences is undefined as of
10376 6.5.6/8 and /9 with respect to the signed ptrdiff_t. */
10377 else if (known_eq (bitpos0, bitpos1)
10378 && (equality_code
10379 || (indirect_base0
10380 && (DECL_P (base0) || CONSTANT_CLASS_P (base0)))
10381 || TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg0))))
10383 /* By converting to signed sizetype we cover middle-end pointer
10384 arithmetic which operates on unsigned pointer types of size
10385 type size and ARRAY_REF offsets which are properly sign or
10386 zero extended from their type in case it is narrower than
10387 sizetype. */
10388 if (offset0 == NULL_TREE)
10389 offset0 = build_int_cst (ssizetype, 0);
10390 else
10391 offset0 = fold_convert_loc (loc, ssizetype, offset0);
10392 if (offset1 == NULL_TREE)
10393 offset1 = build_int_cst (ssizetype, 0);
10394 else
10395 offset1 = fold_convert_loc (loc, ssizetype, offset1);
10397 if (!equality_code
10398 && (pointer_may_wrap_p (base0, offset0, bitpos0)
10399 || pointer_may_wrap_p (base1, offset1, bitpos1)))
10400 fold_overflow_warning (("assuming pointer wraparound does not "
10401 "occur when comparing P +- C1 with "
10402 "P +- C2"),
10403 WARN_STRICT_OVERFLOW_COMPARISON);
10405 return fold_build2_loc (loc, code, type, offset0, offset1);
10408 /* For equal offsets we can simplify to a comparison of the
10409 base addresses. */
10410 else if (known_eq (bitpos0, bitpos1)
10411 && (indirect_base0
10412 ? base0 != TREE_OPERAND (arg0, 0) : base0 != arg0)
10413 && (indirect_base1
10414 ? base1 != TREE_OPERAND (arg1, 0) : base1 != arg1)
10415 && ((offset0 == offset1)
10416 || (offset0 && offset1
10417 && operand_equal_p (offset0, offset1, 0))))
10419 if (indirect_base0)
10420 base0 = build_fold_addr_expr_loc (loc, base0);
10421 if (indirect_base1)
10422 base1 = build_fold_addr_expr_loc (loc, base1);
10423 return fold_build2_loc (loc, code, type, base0, base1);
10425 /* Comparison between an ordinary (non-weak) symbol and a null
10426 pointer can be eliminated since such symbols must have a non
10427 null address. In C, relational expressions between pointers
10428 to objects and null pointers are undefined. The results
10429 below follow the C++ rules with the additional property that
10430 every object pointer compares greater than a null pointer.
10432 else if (((DECL_P (base0)
10433 && maybe_nonzero_address (base0) > 0
10434 /* Avoid folding references to struct members at offset 0 to
10435 prevent tests like '&ptr->firstmember == 0' from getting
10436 eliminated. When ptr is null, although the -> expression
10437 is strictly speaking invalid, GCC retains it as a matter
10438 of QoI. See PR c/44555. */
10439 && (offset0 == NULL_TREE && known_ne (bitpos0, 0)))
10440 || CONSTANT_CLASS_P (base0))
10441 && indirect_base0
10442 /* The caller guarantees that when one of the arguments is
10443 constant (i.e., null in this case) it is second. */
10444 && integer_zerop (arg1))
10446 switch (code)
10448 case EQ_EXPR:
10449 case LE_EXPR:
10450 case LT_EXPR:
10451 return constant_boolean_node (false, type);
10452 case GE_EXPR:
10453 case GT_EXPR:
10454 case NE_EXPR:
10455 return constant_boolean_node (true, type);
10456 default:
10457 gcc_unreachable ();
10462 /* Transform comparisons of the form X +- C1 CMP Y +- C2 to
10463 X CMP Y +- C2 +- C1 for signed X, Y. This is valid if
10464 the resulting offset is smaller in absolute value than the
10465 original one and has the same sign. */
10466 if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (arg0))
10467 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg0))
10468 && (TREE_CODE (arg0) == PLUS_EXPR || TREE_CODE (arg0) == MINUS_EXPR)
10469 && (TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
10470 && !TREE_OVERFLOW (TREE_OPERAND (arg0, 1)))
10471 && (TREE_CODE (arg1) == PLUS_EXPR || TREE_CODE (arg1) == MINUS_EXPR)
10472 && (TREE_CODE (TREE_OPERAND (arg1, 1)) == INTEGER_CST
10473 && !TREE_OVERFLOW (TREE_OPERAND (arg1, 1))))
10475 tree const1 = TREE_OPERAND (arg0, 1);
10476 tree const2 = TREE_OPERAND (arg1, 1);
10477 tree variable1 = TREE_OPERAND (arg0, 0);
10478 tree variable2 = TREE_OPERAND (arg1, 0);
10479 tree cst;
10480 const char * const warnmsg = G_("assuming signed overflow does not "
10481 "occur when combining constants around "
10482 "a comparison");
10484 /* Put the constant on the side where it doesn't overflow and is
10485 of lower absolute value and of same sign than before. */
10486 cst = int_const_binop (TREE_CODE (arg0) == TREE_CODE (arg1)
10487 ? MINUS_EXPR : PLUS_EXPR,
10488 const2, const1);
10489 if (!TREE_OVERFLOW (cst)
10490 && tree_int_cst_compare (const2, cst) == tree_int_cst_sgn (const2)
10491 && tree_int_cst_sgn (cst) == tree_int_cst_sgn (const2))
10493 fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_COMPARISON);
10494 return fold_build2_loc (loc, code, type,
10495 variable1,
10496 fold_build2_loc (loc, TREE_CODE (arg1),
10497 TREE_TYPE (arg1),
10498 variable2, cst));
10501 cst = int_const_binop (TREE_CODE (arg0) == TREE_CODE (arg1)
10502 ? MINUS_EXPR : PLUS_EXPR,
10503 const1, const2);
10504 if (!TREE_OVERFLOW (cst)
10505 && tree_int_cst_compare (const1, cst) == tree_int_cst_sgn (const1)
10506 && tree_int_cst_sgn (cst) == tree_int_cst_sgn (const1))
10508 fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_COMPARISON);
10509 return fold_build2_loc (loc, code, type,
10510 fold_build2_loc (loc, TREE_CODE (arg0),
10511 TREE_TYPE (arg0),
10512 variable1, cst),
10513 variable2);
10517 tem = maybe_canonicalize_comparison (loc, code, type, arg0, arg1);
10518 if (tem)
10519 return tem;
10521 /* If we are comparing an expression that just has comparisons
10522 of two integer values, arithmetic expressions of those comparisons,
10523 and constants, we can simplify it. There are only three cases
10524 to check: the two values can either be equal, the first can be
10525 greater, or the second can be greater. Fold the expression for
10526 those three values. Since each value must be 0 or 1, we have
10527 eight possibilities, each of which corresponds to the constant 0
10528 or 1 or one of the six possible comparisons.
10530 This handles common cases like (a > b) == 0 but also handles
10531 expressions like ((x > y) - (y > x)) > 0, which supposedly
10532 occur in macroized code. */
10534 if (TREE_CODE (arg1) == INTEGER_CST && TREE_CODE (arg0) != INTEGER_CST)
10536 tree cval1 = 0, cval2 = 0;
10538 if (twoval_comparison_p (arg0, &cval1, &cval2)
10539 /* Don't handle degenerate cases here; they should already
10540 have been handled anyway. */
10541 && cval1 != 0 && cval2 != 0
10542 && ! (TREE_CONSTANT (cval1) && TREE_CONSTANT (cval2))
10543 && TREE_TYPE (cval1) == TREE_TYPE (cval2)
10544 && INTEGRAL_TYPE_P (TREE_TYPE (cval1))
10545 && TYPE_MAX_VALUE (TREE_TYPE (cval1))
10546 && TYPE_MAX_VALUE (TREE_TYPE (cval2))
10547 && ! operand_equal_p (TYPE_MIN_VALUE (TREE_TYPE (cval1)),
10548 TYPE_MAX_VALUE (TREE_TYPE (cval2)), 0))
10550 tree maxval = TYPE_MAX_VALUE (TREE_TYPE (cval1));
10551 tree minval = TYPE_MIN_VALUE (TREE_TYPE (cval1));
10553 /* We can't just pass T to eval_subst in case cval1 or cval2
10554 was the same as ARG1. */
10556 tree high_result
10557 = fold_build2_loc (loc, code, type,
10558 eval_subst (loc, arg0, cval1, maxval,
10559 cval2, minval),
10560 arg1);
10561 tree equal_result
10562 = fold_build2_loc (loc, code, type,
10563 eval_subst (loc, arg0, cval1, maxval,
10564 cval2, maxval),
10565 arg1);
10566 tree low_result
10567 = fold_build2_loc (loc, code, type,
10568 eval_subst (loc, arg0, cval1, minval,
10569 cval2, maxval),
10570 arg1);
10572 /* All three of these results should be 0 or 1. Confirm they are.
10573 Then use those values to select the proper code to use. */
10575 if (TREE_CODE (high_result) == INTEGER_CST
10576 && TREE_CODE (equal_result) == INTEGER_CST
10577 && TREE_CODE (low_result) == INTEGER_CST)
10579 /* Make a 3-bit mask with the high-order bit being the
10580 value for `>', the next for '=', and the low for '<'. */
10581 switch ((integer_onep (high_result) * 4)
10582 + (integer_onep (equal_result) * 2)
10583 + integer_onep (low_result))
10585 case 0:
10586 /* Always false. */
10587 return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
10588 case 1:
10589 code = LT_EXPR;
10590 break;
10591 case 2:
10592 code = EQ_EXPR;
10593 break;
10594 case 3:
10595 code = LE_EXPR;
10596 break;
10597 case 4:
10598 code = GT_EXPR;
10599 break;
10600 case 5:
10601 code = NE_EXPR;
10602 break;
10603 case 6:
10604 code = GE_EXPR;
10605 break;
10606 case 7:
10607 /* Always true. */
10608 return omit_one_operand_loc (loc, type, integer_one_node, arg0);
10611 return fold_build2_loc (loc, code, type, cval1, cval2);
10616 return NULL_TREE;
10620 /* Subroutine of fold_binary. Optimize complex multiplications of the
10621 form z * conj(z), as pow(realpart(z),2) + pow(imagpart(z),2). The
10622 argument EXPR represents the expression "z" of type TYPE. */
10624 static tree
10625 fold_mult_zconjz (location_t loc, tree type, tree expr)
10627 tree itype = TREE_TYPE (type);
10628 tree rpart, ipart, tem;
10630 if (TREE_CODE (expr) == COMPLEX_EXPR)
10632 rpart = TREE_OPERAND (expr, 0);
10633 ipart = TREE_OPERAND (expr, 1);
10635 else if (TREE_CODE (expr) == COMPLEX_CST)
10637 rpart = TREE_REALPART (expr);
10638 ipart = TREE_IMAGPART (expr);
10640 else
10642 expr = save_expr (expr);
10643 rpart = fold_build1_loc (loc, REALPART_EXPR, itype, expr);
10644 ipart = fold_build1_loc (loc, IMAGPART_EXPR, itype, expr);
10647 rpart = save_expr (rpart);
10648 ipart = save_expr (ipart);
10649 tem = fold_build2_loc (loc, PLUS_EXPR, itype,
10650 fold_build2_loc (loc, MULT_EXPR, itype, rpart, rpart),
10651 fold_build2_loc (loc, MULT_EXPR, itype, ipart, ipart));
10652 return fold_build2_loc (loc, COMPLEX_EXPR, type, tem,
10653 build_zero_cst (itype));
10657 /* Helper function for fold_vec_perm. Store elements of VECTOR_CST or
10658 CONSTRUCTOR ARG into array ELTS, which has NELTS elements, and return
10659 true if successful. */
10661 static bool
10662 vec_cst_ctor_to_array (tree arg, unsigned int nelts, tree *elts)
10664 unsigned HOST_WIDE_INT i, nunits;
10666 if (TREE_CODE (arg) == VECTOR_CST
10667 && VECTOR_CST_NELTS (arg).is_constant (&nunits))
10669 for (i = 0; i < nunits; ++i)
10670 elts[i] = VECTOR_CST_ELT (arg, i);
10672 else if (TREE_CODE (arg) == CONSTRUCTOR)
10674 constructor_elt *elt;
10676 FOR_EACH_VEC_SAFE_ELT (CONSTRUCTOR_ELTS (arg), i, elt)
10677 if (i >= nelts || TREE_CODE (TREE_TYPE (elt->value)) == VECTOR_TYPE)
10678 return false;
10679 else
10680 elts[i] = elt->value;
10682 else
10683 return false;
10684 for (; i < nelts; i++)
10685 elts[i]
10686 = fold_convert (TREE_TYPE (TREE_TYPE (arg)), integer_zero_node);
10687 return true;
10690 /* Helper routine for fold_vec_perm_cst to check if SEL is a suitable
10691 mask for VLA vec_perm folding.
10692 REASON if specified, will contain the reason why SEL is not suitable.
10693 Used only for debugging and unit-testing. */
10695 static bool
10696 valid_mask_for_fold_vec_perm_cst_p (tree arg0, tree arg1,
10697 const vec_perm_indices &sel,
10698 const char **reason = NULL)
10700 unsigned sel_npatterns = sel.encoding ().npatterns ();
10701 unsigned sel_nelts_per_pattern = sel.encoding ().nelts_per_pattern ();
10703 if (!(pow2p_hwi (sel_npatterns)
10704 && pow2p_hwi (VECTOR_CST_NPATTERNS (arg0))
10705 && pow2p_hwi (VECTOR_CST_NPATTERNS (arg1))))
10707 if (reason)
10708 *reason = "npatterns is not power of 2";
10709 return false;
10712 /* We want to avoid cases where sel.length is not a multiple of npatterns.
10713 For eg: sel.length = 2 + 2x, and sel npatterns = 4. */
10714 poly_uint64 esel;
10715 if (!multiple_p (sel.length (), sel_npatterns, &esel))
10717 if (reason)
10718 *reason = "sel.length is not multiple of sel_npatterns";
10719 return false;
10722 if (sel_nelts_per_pattern < 3)
10723 return true;
10725 for (unsigned pattern = 0; pattern < sel_npatterns; pattern++)
10727 poly_uint64 a1 = sel[pattern + sel_npatterns];
10728 poly_uint64 a2 = sel[pattern + 2 * sel_npatterns];
10729 HOST_WIDE_INT step;
10730 if (!poly_int64 (a2 - a1).is_constant (&step))
10732 if (reason)
10733 *reason = "step is not constant";
10734 return false;
10736 // FIXME: Punt on step < 0 for now, revisit later.
10737 if (step < 0)
10738 return false;
10739 if (step == 0)
10740 continue;
10742 if (!pow2p_hwi (step))
10744 if (reason)
10745 *reason = "step is not power of 2";
10746 return false;
10749 /* Ensure that stepped sequence of the pattern selects elements
10750 only from the same input vector. */
10751 uint64_t q1, qe;
10752 poly_uint64 r1, re;
10753 poly_uint64 ae = a1 + (esel - 2) * step;
10754 poly_uint64 arg_len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
10756 if (!(can_div_trunc_p (a1, arg_len, &q1, &r1)
10757 && can_div_trunc_p (ae, arg_len, &qe, &re)
10758 && q1 == qe))
10760 if (reason)
10761 *reason = "crossed input vectors";
10762 return false;
10765 /* Ensure that the stepped sequence always selects from the same
10766 input pattern. */
10767 tree arg = ((q1 & 1) == 0) ? arg0 : arg1;
10768 unsigned arg_npatterns = VECTOR_CST_NPATTERNS (arg);
10770 if (!multiple_p (step, arg_npatterns))
10772 if (reason)
10773 *reason = "step is not multiple of npatterns";
10774 return false;
10777 /* If a1 chooses base element from arg, ensure that it's a natural
10778 stepped sequence, ie, (arg[2] - arg[1]) == (arg[1] - arg[0])
10779 to preserve arg's encoding. */
10781 if (maybe_lt (r1, arg_npatterns))
10783 unsigned HOST_WIDE_INT index;
10784 if (!r1.is_constant (&index))
10785 return false;
10787 tree arg_elem0 = vector_cst_elt (arg, index);
10788 tree arg_elem1 = vector_cst_elt (arg, index + arg_npatterns);
10789 tree arg_elem2 = vector_cst_elt (arg, index + arg_npatterns * 2);
10791 tree step1, step2;
10792 if (!(step1 = const_binop (MINUS_EXPR, arg_elem1, arg_elem0))
10793 || !(step2 = const_binop (MINUS_EXPR, arg_elem2, arg_elem1))
10794 || !operand_equal_p (step1, step2, 0))
10796 if (reason)
10797 *reason = "not a natural stepped sequence";
10798 return false;
10803 return true;
10806 /* Try to fold permutation of ARG0 and ARG1 with SEL selector when
10807 the input vectors are VECTOR_CST. Return NULL_TREE otherwise.
10808 REASON has same purpose as described in
10809 valid_mask_for_fold_vec_perm_cst_p. */
10811 static tree
10812 fold_vec_perm_cst (tree type, tree arg0, tree arg1, const vec_perm_indices &sel,
10813 const char **reason = NULL)
10815 unsigned res_npatterns, res_nelts_per_pattern;
10816 unsigned HOST_WIDE_INT res_nelts;
10818 /* First try to implement the fold in a VLA-friendly way.
10820 (1) If the selector is simply a duplication of N elements, the
10821 result is likewise a duplication of N elements.
10823 (2) If the selector is N elements followed by a duplication
10824 of N elements, the result is too.
10826 (3) If the selector is N elements followed by an interleaving
10827 of N linear series, the situation is more complex.
10829 valid_mask_for_fold_vec_perm_cst_p detects whether we
10830 can handle this case. If we can, then each of the N linear
10831 series either (a) selects the same element each time or
10832 (b) selects a linear series from one of the input patterns.
10834 If (b) holds for one of the linear series, the result
10835 will contain a linear series, and so the result will have
10836 the same shape as the selector. If (a) holds for all of
10837 the linear series, the result will be the same as (2) above.
10839 (b) can only hold if one of the input patterns has a
10840 stepped encoding. */
10842 if (valid_mask_for_fold_vec_perm_cst_p (arg0, arg1, sel, reason))
10844 res_npatterns = sel.encoding ().npatterns ();
10845 res_nelts_per_pattern = sel.encoding ().nelts_per_pattern ();
10846 if (res_nelts_per_pattern == 3
10847 && VECTOR_CST_NELTS_PER_PATTERN (arg0) < 3
10848 && VECTOR_CST_NELTS_PER_PATTERN (arg1) < 3)
10849 res_nelts_per_pattern = 2;
10850 res_nelts = res_npatterns * res_nelts_per_pattern;
10852 else if (TYPE_VECTOR_SUBPARTS (type).is_constant (&res_nelts))
10854 res_npatterns = res_nelts;
10855 res_nelts_per_pattern = 1;
10857 else
10858 return NULL_TREE;
10860 tree_vector_builder out_elts (type, res_npatterns, res_nelts_per_pattern);
10861 for (unsigned i = 0; i < res_nelts; i++)
10863 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
10864 uint64_t q;
10865 poly_uint64 r;
10866 unsigned HOST_WIDE_INT index;
10868 /* Punt if sel[i] /trunc_div len cannot be determined,
10869 because the input vector to be chosen will depend on
10870 runtime vector length.
10871 For example if len == 4 + 4x, and sel[i] == 4,
10872 If len at runtime equals 4, we choose arg1[0].
10873 For any other value of len > 4 at runtime, we choose arg0[4].
10874 which makes the element choice dependent on runtime vector length. */
10875 if (!can_div_trunc_p (sel[i], len, &q, &r))
10877 if (reason)
10878 *reason = "cannot divide selector element by arg len";
10879 return NULL_TREE;
10882 /* sel[i] % len will give the index of element in the chosen input
10883 vector. For example if sel[i] == 5 + 4x and len == 4 + 4x,
10884 we will choose arg1[1] since (5 + 4x) % (4 + 4x) == 1. */
10885 if (!r.is_constant (&index))
10887 if (reason)
10888 *reason = "remainder is not constant";
10889 return NULL_TREE;
10892 tree arg = ((q & 1) == 0) ? arg0 : arg1;
10893 tree elem = vector_cst_elt (arg, index);
10894 out_elts.quick_push (elem);
10897 return out_elts.build ();
10900 /* Attempt to fold vector permutation of ARG0 and ARG1 vectors using SEL
10901 selector. Return the folded VECTOR_CST or CONSTRUCTOR if successful,
10902 NULL_TREE otherwise. */
10904 tree
10905 fold_vec_perm (tree type, tree arg0, tree arg1, const vec_perm_indices &sel)
10907 unsigned int i;
10908 unsigned HOST_WIDE_INT nelts;
10910 gcc_assert (known_eq (TYPE_VECTOR_SUBPARTS (type), sel.length ())
10911 && known_eq (TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0)),
10912 TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg1))));
10914 if (TREE_TYPE (TREE_TYPE (arg0)) != TREE_TYPE (type)
10915 || TREE_TYPE (TREE_TYPE (arg1)) != TREE_TYPE (type))
10916 return NULL_TREE;
10918 if (TREE_CODE (arg0) == VECTOR_CST
10919 && TREE_CODE (arg1) == VECTOR_CST)
10920 return fold_vec_perm_cst (type, arg0, arg1, sel);
10922 /* For fall back case, we want to ensure we have VLS vectors
10923 with equal length. */
10924 if (!sel.length ().is_constant (&nelts))
10925 return NULL_TREE;
10927 gcc_assert (known_eq (sel.length (),
10928 TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0))));
10929 tree *in_elts = XALLOCAVEC (tree, nelts * 2);
10930 if (!vec_cst_ctor_to_array (arg0, nelts, in_elts)
10931 || !vec_cst_ctor_to_array (arg1, nelts, in_elts + nelts))
10932 return NULL_TREE;
10934 vec<constructor_elt, va_gc> *v;
10935 vec_alloc (v, nelts);
10936 for (i = 0; i < nelts; i++)
10938 HOST_WIDE_INT index;
10939 if (!sel[i].is_constant (&index))
10940 return NULL_TREE;
10941 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, in_elts[index]);
10943 return build_constructor (type, v);
10946 /* Try to fold a pointer difference of type TYPE two address expressions of
10947 array references AREF0 and AREF1 using location LOC. Return a
10948 simplified expression for the difference or NULL_TREE. */
10950 static tree
10951 fold_addr_of_array_ref_difference (location_t loc, tree type,
10952 tree aref0, tree aref1,
10953 bool use_pointer_diff)
10955 tree base0 = TREE_OPERAND (aref0, 0);
10956 tree base1 = TREE_OPERAND (aref1, 0);
10957 tree base_offset = build_int_cst (type, 0);
10959 /* If the bases are array references as well, recurse. If the bases
10960 are pointer indirections compute the difference of the pointers.
10961 If the bases are equal, we are set. */
10962 if ((TREE_CODE (base0) == ARRAY_REF
10963 && TREE_CODE (base1) == ARRAY_REF
10964 && (base_offset
10965 = fold_addr_of_array_ref_difference (loc, type, base0, base1,
10966 use_pointer_diff)))
10967 || (INDIRECT_REF_P (base0)
10968 && INDIRECT_REF_P (base1)
10969 && (base_offset
10970 = use_pointer_diff
10971 ? fold_binary_loc (loc, POINTER_DIFF_EXPR, type,
10972 TREE_OPERAND (base0, 0),
10973 TREE_OPERAND (base1, 0))
10974 : fold_binary_loc (loc, MINUS_EXPR, type,
10975 fold_convert (type,
10976 TREE_OPERAND (base0, 0)),
10977 fold_convert (type,
10978 TREE_OPERAND (base1, 0)))))
10979 || operand_equal_p (base0, base1, OEP_ADDRESS_OF))
10981 tree op0 = fold_convert_loc (loc, type, TREE_OPERAND (aref0, 1));
10982 tree op1 = fold_convert_loc (loc, type, TREE_OPERAND (aref1, 1));
10983 tree esz = fold_convert_loc (loc, type, array_ref_element_size (aref0));
10984 tree diff = fold_build2_loc (loc, MINUS_EXPR, type, op0, op1);
10985 return fold_build2_loc (loc, PLUS_EXPR, type,
10986 base_offset,
10987 fold_build2_loc (loc, MULT_EXPR, type,
10988 diff, esz));
10990 return NULL_TREE;
10993 /* If the real or vector real constant CST of type TYPE has an exact
10994 inverse, return it, else return NULL. */
10996 tree
10997 exact_inverse (tree type, tree cst)
10999 REAL_VALUE_TYPE r;
11000 tree unit_type;
11001 machine_mode mode;
11003 switch (TREE_CODE (cst))
11005 case REAL_CST:
11006 r = TREE_REAL_CST (cst);
11008 if (exact_real_inverse (TYPE_MODE (type), &r))
11009 return build_real (type, r);
11011 return NULL_TREE;
11013 case VECTOR_CST:
11015 unit_type = TREE_TYPE (type);
11016 mode = TYPE_MODE (unit_type);
11018 tree_vector_builder elts;
11019 if (!elts.new_unary_operation (type, cst, false))
11020 return NULL_TREE;
11021 unsigned int count = elts.encoded_nelts ();
11022 for (unsigned int i = 0; i < count; ++i)
11024 r = TREE_REAL_CST (VECTOR_CST_ELT (cst, i));
11025 if (!exact_real_inverse (mode, &r))
11026 return NULL_TREE;
11027 elts.quick_push (build_real (unit_type, r));
11030 return elts.build ();
11033 default:
11034 return NULL_TREE;
11038 /* Mask out the tz least significant bits of X of type TYPE where
11039 tz is the number of trailing zeroes in Y. */
11040 static wide_int
11041 mask_with_tz (tree type, const wide_int &x, const wide_int &y)
11043 int tz = wi::ctz (y);
11044 if (tz > 0)
11045 return wi::mask (tz, true, TYPE_PRECISION (type)) & x;
11046 return x;
11049 /* Return true when T is an address and is known to be nonzero.
11050 For floating point we further ensure that T is not denormal.
11051 Similar logic is present in nonzero_address in rtlanal.h.
11053 If the return value is based on the assumption that signed overflow
11054 is undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't
11055 change *STRICT_OVERFLOW_P. */
11057 static bool
11058 tree_expr_nonzero_warnv_p (tree t, bool *strict_overflow_p)
11060 tree type = TREE_TYPE (t);
11061 enum tree_code code;
11063 /* Doing something useful for floating point would need more work. */
11064 if (!INTEGRAL_TYPE_P (type) && !POINTER_TYPE_P (type))
11065 return false;
11067 code = TREE_CODE (t);
11068 switch (TREE_CODE_CLASS (code))
11070 case tcc_unary:
11071 return tree_unary_nonzero_warnv_p (code, type, TREE_OPERAND (t, 0),
11072 strict_overflow_p);
11073 case tcc_binary:
11074 case tcc_comparison:
11075 return tree_binary_nonzero_warnv_p (code, type,
11076 TREE_OPERAND (t, 0),
11077 TREE_OPERAND (t, 1),
11078 strict_overflow_p);
11079 case tcc_constant:
11080 case tcc_declaration:
11081 case tcc_reference:
11082 return tree_single_nonzero_warnv_p (t, strict_overflow_p);
11084 default:
11085 break;
11088 switch (code)
11090 case TRUTH_NOT_EXPR:
11091 return tree_unary_nonzero_warnv_p (code, type, TREE_OPERAND (t, 0),
11092 strict_overflow_p);
11094 case TRUTH_AND_EXPR:
11095 case TRUTH_OR_EXPR:
11096 case TRUTH_XOR_EXPR:
11097 return tree_binary_nonzero_warnv_p (code, type,
11098 TREE_OPERAND (t, 0),
11099 TREE_OPERAND (t, 1),
11100 strict_overflow_p);
11102 case COND_EXPR:
11103 case CONSTRUCTOR:
11104 case OBJ_TYPE_REF:
11105 case ADDR_EXPR:
11106 case WITH_SIZE_EXPR:
11107 case SSA_NAME:
11108 return tree_single_nonzero_warnv_p (t, strict_overflow_p);
11110 case COMPOUND_EXPR:
11111 case MODIFY_EXPR:
11112 case BIND_EXPR:
11113 return tree_expr_nonzero_warnv_p (TREE_OPERAND (t, 1),
11114 strict_overflow_p);
11116 case SAVE_EXPR:
11117 return tree_expr_nonzero_warnv_p (TREE_OPERAND (t, 0),
11118 strict_overflow_p);
11120 case CALL_EXPR:
11122 tree fndecl = get_callee_fndecl (t);
11123 if (!fndecl) return false;
11124 if (flag_delete_null_pointer_checks && !flag_check_new
11125 && DECL_IS_OPERATOR_NEW_P (fndecl)
11126 && !TREE_NOTHROW (fndecl))
11127 return true;
11128 if (flag_delete_null_pointer_checks
11129 && lookup_attribute ("returns_nonnull",
11130 TYPE_ATTRIBUTES (TREE_TYPE (fndecl))))
11131 return true;
11132 return alloca_call_p (t);
11135 default:
11136 break;
11138 return false;
11141 /* Return true when T is an address and is known to be nonzero.
11142 Handle warnings about undefined signed overflow. */
11144 bool
11145 tree_expr_nonzero_p (tree t)
11147 bool ret, strict_overflow_p;
11149 strict_overflow_p = false;
11150 ret = tree_expr_nonzero_warnv_p (t, &strict_overflow_p);
11151 if (strict_overflow_p)
11152 fold_overflow_warning (("assuming signed overflow does not occur when "
11153 "determining that expression is always "
11154 "non-zero"),
11155 WARN_STRICT_OVERFLOW_MISC);
11156 return ret;
11159 /* Return true if T is known not to be equal to an integer W. */
11161 bool
11162 expr_not_equal_to (tree t, const wide_int &w)
11164 int_range_max vr;
11165 switch (TREE_CODE (t))
11167 case INTEGER_CST:
11168 return wi::to_wide (t) != w;
11170 case SSA_NAME:
11171 if (!INTEGRAL_TYPE_P (TREE_TYPE (t)))
11172 return false;
11174 get_range_query (cfun)->range_of_expr (vr, t);
11175 if (!vr.undefined_p () && !vr.contains_p (w))
11176 return true;
11177 /* If T has some known zero bits and W has any of those bits set,
11178 then T is known not to be equal to W. */
11179 if (wi::ne_p (wi::zext (wi::bit_and_not (w, get_nonzero_bits (t)),
11180 TYPE_PRECISION (TREE_TYPE (t))), 0))
11181 return true;
11182 return false;
11184 default:
11185 return false;
11189 /* Fold a binary expression of code CODE and type TYPE with operands
11190 OP0 and OP1. LOC is the location of the resulting expression.
11191 Return the folded expression if folding is successful. Otherwise,
11192 return NULL_TREE. */
11194 tree
11195 fold_binary_loc (location_t loc, enum tree_code code, tree type,
11196 tree op0, tree op1)
11198 enum tree_code_class kind = TREE_CODE_CLASS (code);
11199 tree arg0, arg1, tem;
11200 tree t1 = NULL_TREE;
11201 bool strict_overflow_p;
11202 unsigned int prec;
11204 gcc_assert (IS_EXPR_CODE_CLASS (kind)
11205 && TREE_CODE_LENGTH (code) == 2
11206 && op0 != NULL_TREE
11207 && op1 != NULL_TREE);
11209 arg0 = op0;
11210 arg1 = op1;
11212 /* Strip any conversions that don't change the mode. This is
11213 safe for every expression, except for a comparison expression
11214 because its signedness is derived from its operands. So, in
11215 the latter case, only strip conversions that don't change the
11216 signedness. MIN_EXPR/MAX_EXPR also need signedness of arguments
11217 preserved.
11219 Note that this is done as an internal manipulation within the
11220 constant folder, in order to find the simplest representation
11221 of the arguments so that their form can be studied. In any
11222 cases, the appropriate type conversions should be put back in
11223 the tree that will get out of the constant folder. */
11225 if (kind == tcc_comparison || code == MIN_EXPR || code == MAX_EXPR)
11227 STRIP_SIGN_NOPS (arg0);
11228 STRIP_SIGN_NOPS (arg1);
11230 else
11232 STRIP_NOPS (arg0);
11233 STRIP_NOPS (arg1);
11236 /* Note that TREE_CONSTANT isn't enough: static var addresses are
11237 constant but we can't do arithmetic on them. */
11238 if (CONSTANT_CLASS_P (arg0) && CONSTANT_CLASS_P (arg1))
11240 tem = const_binop (code, type, arg0, arg1);
11241 if (tem != NULL_TREE)
11243 if (TREE_TYPE (tem) != type)
11244 tem = fold_convert_loc (loc, type, tem);
11245 return tem;
11249 /* If this is a commutative operation, and ARG0 is a constant, move it
11250 to ARG1 to reduce the number of tests below. */
11251 if (commutative_tree_code (code)
11252 && tree_swap_operands_p (arg0, arg1))
11253 return fold_build2_loc (loc, code, type, op1, op0);
11255 /* Likewise if this is a comparison, and ARG0 is a constant, move it
11256 to ARG1 to reduce the number of tests below. */
11257 if (kind == tcc_comparison
11258 && tree_swap_operands_p (arg0, arg1))
11259 return fold_build2_loc (loc, swap_tree_comparison (code), type, op1, op0);
11261 tem = generic_simplify (loc, code, type, op0, op1);
11262 if (tem)
11263 return tem;
11265 /* ARG0 is the first operand of EXPR, and ARG1 is the second operand.
11267 First check for cases where an arithmetic operation is applied to a
11268 compound, conditional, or comparison operation. Push the arithmetic
11269 operation inside the compound or conditional to see if any folding
11270 can then be done. Convert comparison to conditional for this purpose.
11271 The also optimizes non-constant cases that used to be done in
11272 expand_expr.
11274 Before we do that, see if this is a BIT_AND_EXPR or a BIT_IOR_EXPR,
11275 one of the operands is a comparison and the other is a comparison, a
11276 BIT_AND_EXPR with the constant 1, or a truth value. In that case, the
11277 code below would make the expression more complex. Change it to a
11278 TRUTH_{AND,OR}_EXPR. Likewise, convert a similar NE_EXPR to
11279 TRUTH_XOR_EXPR and an EQ_EXPR to the inversion of a TRUTH_XOR_EXPR. */
11281 if ((code == BIT_AND_EXPR || code == BIT_IOR_EXPR
11282 || code == EQ_EXPR || code == NE_EXPR)
11283 && !VECTOR_TYPE_P (TREE_TYPE (arg0))
11284 && ((truth_value_p (TREE_CODE (arg0))
11285 && (truth_value_p (TREE_CODE (arg1))
11286 || (TREE_CODE (arg1) == BIT_AND_EXPR
11287 && integer_onep (TREE_OPERAND (arg1, 1)))))
11288 || (truth_value_p (TREE_CODE (arg1))
11289 && (truth_value_p (TREE_CODE (arg0))
11290 || (TREE_CODE (arg0) == BIT_AND_EXPR
11291 && integer_onep (TREE_OPERAND (arg0, 1)))))))
11293 tem = fold_build2_loc (loc, code == BIT_AND_EXPR ? TRUTH_AND_EXPR
11294 : code == BIT_IOR_EXPR ? TRUTH_OR_EXPR
11295 : TRUTH_XOR_EXPR,
11296 boolean_type_node,
11297 fold_convert_loc (loc, boolean_type_node, arg0),
11298 fold_convert_loc (loc, boolean_type_node, arg1));
11300 if (code == EQ_EXPR)
11301 tem = invert_truthvalue_loc (loc, tem);
11303 return fold_convert_loc (loc, type, tem);
11306 if (TREE_CODE_CLASS (code) == tcc_binary
11307 || TREE_CODE_CLASS (code) == tcc_comparison)
11309 if (TREE_CODE (arg0) == COMPOUND_EXPR)
11311 tem = fold_build2_loc (loc, code, type,
11312 fold_convert_loc (loc, TREE_TYPE (op0),
11313 TREE_OPERAND (arg0, 1)), op1);
11314 return build2_loc (loc, COMPOUND_EXPR, type, TREE_OPERAND (arg0, 0),
11315 tem);
11317 if (TREE_CODE (arg1) == COMPOUND_EXPR)
11319 tem = fold_build2_loc (loc, code, type, op0,
11320 fold_convert_loc (loc, TREE_TYPE (op1),
11321 TREE_OPERAND (arg1, 1)));
11322 return build2_loc (loc, COMPOUND_EXPR, type, TREE_OPERAND (arg1, 0),
11323 tem);
11326 if (TREE_CODE (arg0) == COND_EXPR
11327 || TREE_CODE (arg0) == VEC_COND_EXPR
11328 || COMPARISON_CLASS_P (arg0))
11330 tem = fold_binary_op_with_conditional_arg (loc, code, type, op0, op1,
11331 arg0, arg1,
11332 /*cond_first_p=*/1);
11333 if (tem != NULL_TREE)
11334 return tem;
11337 if (TREE_CODE (arg1) == COND_EXPR
11338 || TREE_CODE (arg1) == VEC_COND_EXPR
11339 || COMPARISON_CLASS_P (arg1))
11341 tem = fold_binary_op_with_conditional_arg (loc, code, type, op0, op1,
11342 arg1, arg0,
11343 /*cond_first_p=*/0);
11344 if (tem != NULL_TREE)
11345 return tem;
11349 switch (code)
11351 case MEM_REF:
11352 /* MEM[&MEM[p, CST1], CST2] -> MEM[p, CST1 + CST2]. */
11353 if (TREE_CODE (arg0) == ADDR_EXPR
11354 && TREE_CODE (TREE_OPERAND (arg0, 0)) == MEM_REF)
11356 tree iref = TREE_OPERAND (arg0, 0);
11357 return fold_build2 (MEM_REF, type,
11358 TREE_OPERAND (iref, 0),
11359 int_const_binop (PLUS_EXPR, arg1,
11360 TREE_OPERAND (iref, 1)));
11363 /* MEM[&a.b, CST2] -> MEM[&a, offsetof (a, b) + CST2]. */
11364 if (TREE_CODE (arg0) == ADDR_EXPR
11365 && handled_component_p (TREE_OPERAND (arg0, 0)))
11367 tree base;
11368 poly_int64 coffset;
11369 base = get_addr_base_and_unit_offset (TREE_OPERAND (arg0, 0),
11370 &coffset);
11371 if (!base)
11372 return NULL_TREE;
11373 return fold_build2 (MEM_REF, type,
11374 build1 (ADDR_EXPR, TREE_TYPE (arg0), base),
11375 int_const_binop (PLUS_EXPR, arg1,
11376 size_int (coffset)));
11379 return NULL_TREE;
11381 case POINTER_PLUS_EXPR:
11382 /* INT +p INT -> (PTR)(INT + INT). Stripping types allows for this. */
11383 if (INTEGRAL_TYPE_P (TREE_TYPE (arg1))
11384 && INTEGRAL_TYPE_P (TREE_TYPE (arg0)))
11385 return fold_convert_loc (loc, type,
11386 fold_build2_loc (loc, PLUS_EXPR, sizetype,
11387 fold_convert_loc (loc, sizetype,
11388 arg1),
11389 fold_convert_loc (loc, sizetype,
11390 arg0)));
11392 return NULL_TREE;
11394 case PLUS_EXPR:
11395 if (INTEGRAL_TYPE_P (type) || VECTOR_INTEGER_TYPE_P (type))
11397 /* X + (X / CST) * -CST is X % CST. */
11398 if (TREE_CODE (arg1) == MULT_EXPR
11399 && TREE_CODE (TREE_OPERAND (arg1, 0)) == TRUNC_DIV_EXPR
11400 && operand_equal_p (arg0,
11401 TREE_OPERAND (TREE_OPERAND (arg1, 0), 0), 0))
11403 tree cst0 = TREE_OPERAND (TREE_OPERAND (arg1, 0), 1);
11404 tree cst1 = TREE_OPERAND (arg1, 1);
11405 tree sum = fold_binary_loc (loc, PLUS_EXPR, TREE_TYPE (cst1),
11406 cst1, cst0);
11407 if (sum && integer_zerop (sum))
11408 return fold_convert_loc (loc, type,
11409 fold_build2_loc (loc, TRUNC_MOD_EXPR,
11410 TREE_TYPE (arg0), arg0,
11411 cst0));
11415 /* Handle (A1 * C1) + (A2 * C2) with A1, A2 or C1, C2 being the same or
11416 one. Make sure the type is not saturating and has the signedness of
11417 the stripped operands, as fold_plusminus_mult_expr will re-associate.
11418 ??? The latter condition should use TYPE_OVERFLOW_* flags instead. */
11419 if ((TREE_CODE (arg0) == MULT_EXPR
11420 || TREE_CODE (arg1) == MULT_EXPR)
11421 && !TYPE_SATURATING (type)
11422 && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (TREE_TYPE (arg0))
11423 && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (TREE_TYPE (arg1))
11424 && (!FLOAT_TYPE_P (type) || flag_associative_math))
11426 tree tem = fold_plusminus_mult_expr (loc, code, type, arg0, arg1);
11427 if (tem)
11428 return tem;
11431 if (! FLOAT_TYPE_P (type))
11433 /* Reassociate (plus (plus (mult) (foo)) (mult)) as
11434 (plus (plus (mult) (mult)) (foo)) so that we can
11435 take advantage of the factoring cases below. */
11436 if (ANY_INTEGRAL_TYPE_P (type)
11437 && TYPE_OVERFLOW_WRAPS (type)
11438 && (((TREE_CODE (arg0) == PLUS_EXPR
11439 || TREE_CODE (arg0) == MINUS_EXPR)
11440 && TREE_CODE (arg1) == MULT_EXPR)
11441 || ((TREE_CODE (arg1) == PLUS_EXPR
11442 || TREE_CODE (arg1) == MINUS_EXPR)
11443 && TREE_CODE (arg0) == MULT_EXPR)))
11445 tree parg0, parg1, parg, marg;
11446 enum tree_code pcode;
11448 if (TREE_CODE (arg1) == MULT_EXPR)
11449 parg = arg0, marg = arg1;
11450 else
11451 parg = arg1, marg = arg0;
11452 pcode = TREE_CODE (parg);
11453 parg0 = TREE_OPERAND (parg, 0);
11454 parg1 = TREE_OPERAND (parg, 1);
11455 STRIP_NOPS (parg0);
11456 STRIP_NOPS (parg1);
11458 if (TREE_CODE (parg0) == MULT_EXPR
11459 && TREE_CODE (parg1) != MULT_EXPR)
11460 return fold_build2_loc (loc, pcode, type,
11461 fold_build2_loc (loc, PLUS_EXPR, type,
11462 fold_convert_loc (loc, type,
11463 parg0),
11464 fold_convert_loc (loc, type,
11465 marg)),
11466 fold_convert_loc (loc, type, parg1));
11467 if (TREE_CODE (parg0) != MULT_EXPR
11468 && TREE_CODE (parg1) == MULT_EXPR)
11469 return
11470 fold_build2_loc (loc, PLUS_EXPR, type,
11471 fold_convert_loc (loc, type, parg0),
11472 fold_build2_loc (loc, pcode, type,
11473 fold_convert_loc (loc, type, marg),
11474 fold_convert_loc (loc, type,
11475 parg1)));
11478 else
11480 /* Fold __complex__ ( x, 0 ) + __complex__ ( 0, y )
11481 to __complex__ ( x, y ). This is not the same for SNaNs or
11482 if signed zeros are involved. */
11483 if (!HONOR_SNANS (arg0)
11484 && !HONOR_SIGNED_ZEROS (arg0)
11485 && COMPLEX_FLOAT_TYPE_P (TREE_TYPE (arg0)))
11487 tree rtype = TREE_TYPE (TREE_TYPE (arg0));
11488 tree arg0r = fold_unary_loc (loc, REALPART_EXPR, rtype, arg0);
11489 tree arg0i = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg0);
11490 bool arg0rz = false, arg0iz = false;
11491 if ((arg0r && (arg0rz = real_zerop (arg0r)))
11492 || (arg0i && (arg0iz = real_zerop (arg0i))))
11494 tree arg1r = fold_unary_loc (loc, REALPART_EXPR, rtype, arg1);
11495 tree arg1i = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg1);
11496 if (arg0rz && arg1i && real_zerop (arg1i))
11498 tree rp = arg1r ? arg1r
11499 : build1 (REALPART_EXPR, rtype, arg1);
11500 tree ip = arg0i ? arg0i
11501 : build1 (IMAGPART_EXPR, rtype, arg0);
11502 return fold_build2_loc (loc, COMPLEX_EXPR, type, rp, ip);
11504 else if (arg0iz && arg1r && real_zerop (arg1r))
11506 tree rp = arg0r ? arg0r
11507 : build1 (REALPART_EXPR, rtype, arg0);
11508 tree ip = arg1i ? arg1i
11509 : build1 (IMAGPART_EXPR, rtype, arg1);
11510 return fold_build2_loc (loc, COMPLEX_EXPR, type, rp, ip);
11515 /* Convert a + (b*c + d*e) into (a + b*c) + d*e.
11516 We associate floats only if the user has specified
11517 -fassociative-math. */
11518 if (flag_associative_math
11519 && TREE_CODE (arg1) == PLUS_EXPR
11520 && TREE_CODE (arg0) != MULT_EXPR)
11522 tree tree10 = TREE_OPERAND (arg1, 0);
11523 tree tree11 = TREE_OPERAND (arg1, 1);
11524 if (TREE_CODE (tree11) == MULT_EXPR
11525 && TREE_CODE (tree10) == MULT_EXPR)
11527 tree tree0;
11528 tree0 = fold_build2_loc (loc, PLUS_EXPR, type, arg0, tree10);
11529 return fold_build2_loc (loc, PLUS_EXPR, type, tree0, tree11);
11532 /* Convert (b*c + d*e) + a into b*c + (d*e +a).
11533 We associate floats only if the user has specified
11534 -fassociative-math. */
11535 if (flag_associative_math
11536 && TREE_CODE (arg0) == PLUS_EXPR
11537 && TREE_CODE (arg1) != MULT_EXPR)
11539 tree tree00 = TREE_OPERAND (arg0, 0);
11540 tree tree01 = TREE_OPERAND (arg0, 1);
11541 if (TREE_CODE (tree01) == MULT_EXPR
11542 && TREE_CODE (tree00) == MULT_EXPR)
11544 tree tree0;
11545 tree0 = fold_build2_loc (loc, PLUS_EXPR, type, tree01, arg1);
11546 return fold_build2_loc (loc, PLUS_EXPR, type, tree00, tree0);
11551 bit_rotate:
11552 /* (A << C1) + (A >> C2) if A is unsigned and C1+C2 is the size of A
11553 is a rotate of A by C1 bits. */
11554 /* (A << B) + (A >> (Z - B)) if A is unsigned and Z is the size of A
11555 is a rotate of A by B bits.
11556 Similarly for (A << B) | (A >> (-B & C3)) where C3 is Z-1,
11557 though in this case CODE must be | and not + or ^, otherwise
11558 it doesn't return A when B is 0. */
11560 enum tree_code code0, code1;
11561 tree rtype;
11562 code0 = TREE_CODE (arg0);
11563 code1 = TREE_CODE (arg1);
11564 if (((code0 == RSHIFT_EXPR && code1 == LSHIFT_EXPR)
11565 || (code1 == RSHIFT_EXPR && code0 == LSHIFT_EXPR))
11566 && operand_equal_p (TREE_OPERAND (arg0, 0),
11567 TREE_OPERAND (arg1, 0), 0)
11568 && (rtype = TREE_TYPE (TREE_OPERAND (arg0, 0)),
11569 TYPE_UNSIGNED (rtype))
11570 /* Only create rotates in complete modes. Other cases are not
11571 expanded properly. */
11572 && (element_precision (rtype)
11573 == GET_MODE_UNIT_PRECISION (TYPE_MODE (rtype))))
11575 tree tree01, tree11;
11576 tree orig_tree01, orig_tree11;
11577 enum tree_code code01, code11;
11579 tree01 = orig_tree01 = TREE_OPERAND (arg0, 1);
11580 tree11 = orig_tree11 = TREE_OPERAND (arg1, 1);
11581 STRIP_NOPS (tree01);
11582 STRIP_NOPS (tree11);
11583 code01 = TREE_CODE (tree01);
11584 code11 = TREE_CODE (tree11);
11585 if (code11 != MINUS_EXPR
11586 && (code01 == MINUS_EXPR || code01 == BIT_AND_EXPR))
11588 std::swap (code0, code1);
11589 std::swap (code01, code11);
11590 std::swap (tree01, tree11);
11591 std::swap (orig_tree01, orig_tree11);
11593 if (code01 == INTEGER_CST
11594 && code11 == INTEGER_CST
11595 && (wi::to_widest (tree01) + wi::to_widest (tree11)
11596 == element_precision (rtype)))
11598 tem = build2_loc (loc, LROTATE_EXPR,
11599 rtype, TREE_OPERAND (arg0, 0),
11600 code0 == LSHIFT_EXPR
11601 ? orig_tree01 : orig_tree11);
11602 return fold_convert_loc (loc, type, tem);
11604 else if (code11 == MINUS_EXPR)
11606 tree tree110, tree111;
11607 tree110 = TREE_OPERAND (tree11, 0);
11608 tree111 = TREE_OPERAND (tree11, 1);
11609 STRIP_NOPS (tree110);
11610 STRIP_NOPS (tree111);
11611 if (TREE_CODE (tree110) == INTEGER_CST
11612 && compare_tree_int (tree110,
11613 element_precision (rtype)) == 0
11614 && operand_equal_p (tree01, tree111, 0))
11616 tem = build2_loc (loc, (code0 == LSHIFT_EXPR
11617 ? LROTATE_EXPR : RROTATE_EXPR),
11618 rtype, TREE_OPERAND (arg0, 0),
11619 orig_tree01);
11620 return fold_convert_loc (loc, type, tem);
11623 else if (code == BIT_IOR_EXPR
11624 && code11 == BIT_AND_EXPR
11625 && pow2p_hwi (element_precision (rtype)))
11627 tree tree110, tree111;
11628 tree110 = TREE_OPERAND (tree11, 0);
11629 tree111 = TREE_OPERAND (tree11, 1);
11630 STRIP_NOPS (tree110);
11631 STRIP_NOPS (tree111);
11632 if (TREE_CODE (tree110) == NEGATE_EXPR
11633 && TREE_CODE (tree111) == INTEGER_CST
11634 && compare_tree_int (tree111,
11635 element_precision (rtype) - 1) == 0
11636 && operand_equal_p (tree01, TREE_OPERAND (tree110, 0), 0))
11638 tem = build2_loc (loc, (code0 == LSHIFT_EXPR
11639 ? LROTATE_EXPR : RROTATE_EXPR),
11640 rtype, TREE_OPERAND (arg0, 0),
11641 orig_tree01);
11642 return fold_convert_loc (loc, type, tem);
11648 associate:
11649 /* In most languages, can't associate operations on floats through
11650 parentheses. Rather than remember where the parentheses were, we
11651 don't associate floats at all, unless the user has specified
11652 -fassociative-math.
11653 And, we need to make sure type is not saturating. */
11655 if ((! FLOAT_TYPE_P (type) || flag_associative_math)
11656 && !TYPE_SATURATING (type)
11657 && !TYPE_OVERFLOW_SANITIZED (type))
11659 tree var0, minus_var0, con0, minus_con0, lit0, minus_lit0;
11660 tree var1, minus_var1, con1, minus_con1, lit1, minus_lit1;
11661 tree atype = type;
11662 bool ok = true;
11664 /* Split both trees into variables, constants, and literals. Then
11665 associate each group together, the constants with literals,
11666 then the result with variables. This increases the chances of
11667 literals being recombined later and of generating relocatable
11668 expressions for the sum of a constant and literal. */
11669 var0 = split_tree (arg0, type, code,
11670 &minus_var0, &con0, &minus_con0,
11671 &lit0, &minus_lit0, 0);
11672 var1 = split_tree (arg1, type, code,
11673 &minus_var1, &con1, &minus_con1,
11674 &lit1, &minus_lit1, code == MINUS_EXPR);
11676 /* Recombine MINUS_EXPR operands by using PLUS_EXPR. */
11677 if (code == MINUS_EXPR)
11678 code = PLUS_EXPR;
11680 /* With undefined overflow prefer doing association in a type
11681 which wraps on overflow, if that is one of the operand types. */
11682 if ((POINTER_TYPE_P (type) || INTEGRAL_TYPE_P (type))
11683 && !TYPE_OVERFLOW_WRAPS (type))
11685 if (INTEGRAL_TYPE_P (TREE_TYPE (arg0))
11686 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg0)))
11687 atype = TREE_TYPE (arg0);
11688 else if (INTEGRAL_TYPE_P (TREE_TYPE (arg1))
11689 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg1)))
11690 atype = TREE_TYPE (arg1);
11691 gcc_assert (TYPE_PRECISION (atype) == TYPE_PRECISION (type));
11694 /* With undefined overflow we can only associate constants with one
11695 variable, and constants whose association doesn't overflow. */
11696 if ((POINTER_TYPE_P (atype) || INTEGRAL_TYPE_P (atype))
11697 && !TYPE_OVERFLOW_WRAPS (atype))
11699 if ((var0 && var1) || (minus_var0 && minus_var1))
11701 /* ??? If split_tree would handle NEGATE_EXPR we could
11702 simply reject these cases and the allowed cases would
11703 be the var0/minus_var1 ones. */
11704 tree tmp0 = var0 ? var0 : minus_var0;
11705 tree tmp1 = var1 ? var1 : minus_var1;
11706 bool one_neg = false;
11708 if (TREE_CODE (tmp0) == NEGATE_EXPR)
11710 tmp0 = TREE_OPERAND (tmp0, 0);
11711 one_neg = !one_neg;
11713 if (CONVERT_EXPR_P (tmp0)
11714 && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (tmp0, 0)))
11715 && (TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (tmp0, 0)))
11716 <= TYPE_PRECISION (atype)))
11717 tmp0 = TREE_OPERAND (tmp0, 0);
11718 if (TREE_CODE (tmp1) == NEGATE_EXPR)
11720 tmp1 = TREE_OPERAND (tmp1, 0);
11721 one_neg = !one_neg;
11723 if (CONVERT_EXPR_P (tmp1)
11724 && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (tmp1, 0)))
11725 && (TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (tmp1, 0)))
11726 <= TYPE_PRECISION (atype)))
11727 tmp1 = TREE_OPERAND (tmp1, 0);
11728 /* The only case we can still associate with two variables
11729 is if they cancel out. */
11730 if (!one_neg
11731 || !operand_equal_p (tmp0, tmp1, 0))
11732 ok = false;
11734 else if ((var0 && minus_var1
11735 && ! operand_equal_p (var0, minus_var1, 0))
11736 || (minus_var0 && var1
11737 && ! operand_equal_p (minus_var0, var1, 0)))
11738 ok = false;
11741 /* Only do something if we found more than two objects. Otherwise,
11742 nothing has changed and we risk infinite recursion. */
11743 if (ok
11744 && ((var0 != 0) + (var1 != 0)
11745 + (minus_var0 != 0) + (minus_var1 != 0)
11746 + (con0 != 0) + (con1 != 0)
11747 + (minus_con0 != 0) + (minus_con1 != 0)
11748 + (lit0 != 0) + (lit1 != 0)
11749 + (minus_lit0 != 0) + (minus_lit1 != 0)) > 2)
11751 var0 = associate_trees (loc, var0, var1, code, atype);
11752 minus_var0 = associate_trees (loc, minus_var0, minus_var1,
11753 code, atype);
11754 con0 = associate_trees (loc, con0, con1, code, atype);
11755 minus_con0 = associate_trees (loc, minus_con0, minus_con1,
11756 code, atype);
11757 lit0 = associate_trees (loc, lit0, lit1, code, atype);
11758 minus_lit0 = associate_trees (loc, minus_lit0, minus_lit1,
11759 code, atype);
11761 if (minus_var0 && var0)
11763 var0 = associate_trees (loc, var0, minus_var0,
11764 MINUS_EXPR, atype);
11765 minus_var0 = 0;
11767 if (minus_con0 && con0)
11769 con0 = associate_trees (loc, con0, minus_con0,
11770 MINUS_EXPR, atype);
11771 minus_con0 = 0;
11774 /* Preserve the MINUS_EXPR if the negative part of the literal is
11775 greater than the positive part. Otherwise, the multiplicative
11776 folding code (i.e extract_muldiv) may be fooled in case
11777 unsigned constants are subtracted, like in the following
11778 example: ((X*2 + 4) - 8U)/2. */
11779 if (minus_lit0 && lit0)
11781 if (TREE_CODE (lit0) == INTEGER_CST
11782 && TREE_CODE (minus_lit0) == INTEGER_CST
11783 && tree_int_cst_lt (lit0, minus_lit0)
11784 /* But avoid ending up with only negated parts. */
11785 && (var0 || con0))
11787 minus_lit0 = associate_trees (loc, minus_lit0, lit0,
11788 MINUS_EXPR, atype);
11789 lit0 = 0;
11791 else
11793 lit0 = associate_trees (loc, lit0, minus_lit0,
11794 MINUS_EXPR, atype);
11795 minus_lit0 = 0;
11799 /* Don't introduce overflows through reassociation. */
11800 if ((lit0 && TREE_OVERFLOW_P (lit0))
11801 || (minus_lit0 && TREE_OVERFLOW_P (minus_lit0)))
11802 return NULL_TREE;
11804 /* Eliminate lit0 and minus_lit0 to con0 and minus_con0. */
11805 con0 = associate_trees (loc, con0, lit0, code, atype);
11806 lit0 = 0;
11807 minus_con0 = associate_trees (loc, minus_con0, minus_lit0,
11808 code, atype);
11809 minus_lit0 = 0;
11811 /* Eliminate minus_con0. */
11812 if (minus_con0)
11814 if (con0)
11815 con0 = associate_trees (loc, con0, minus_con0,
11816 MINUS_EXPR, atype);
11817 else if (var0)
11818 var0 = associate_trees (loc, var0, minus_con0,
11819 MINUS_EXPR, atype);
11820 else
11821 gcc_unreachable ();
11822 minus_con0 = 0;
11825 /* Eliminate minus_var0. */
11826 if (minus_var0)
11828 if (con0)
11829 con0 = associate_trees (loc, con0, minus_var0,
11830 MINUS_EXPR, atype);
11831 else
11832 gcc_unreachable ();
11833 minus_var0 = 0;
11836 return
11837 fold_convert_loc (loc, type, associate_trees (loc, var0, con0,
11838 code, atype));
11842 return NULL_TREE;
11844 case POINTER_DIFF_EXPR:
11845 case MINUS_EXPR:
11846 /* Fold &a[i] - &a[j] to i-j. */
11847 if (TREE_CODE (arg0) == ADDR_EXPR
11848 && TREE_CODE (TREE_OPERAND (arg0, 0)) == ARRAY_REF
11849 && TREE_CODE (arg1) == ADDR_EXPR
11850 && TREE_CODE (TREE_OPERAND (arg1, 0)) == ARRAY_REF)
11852 tree tem = fold_addr_of_array_ref_difference (loc, type,
11853 TREE_OPERAND (arg0, 0),
11854 TREE_OPERAND (arg1, 0),
11855 code
11856 == POINTER_DIFF_EXPR);
11857 if (tem)
11858 return tem;
11861 /* Further transformations are not for pointers. */
11862 if (code == POINTER_DIFF_EXPR)
11863 return NULL_TREE;
11865 /* (-A) - B -> (-B) - A where B is easily negated and we can swap. */
11866 if (TREE_CODE (arg0) == NEGATE_EXPR
11867 && negate_expr_p (op1)
11868 /* If arg0 is e.g. unsigned int and type is int, then this could
11869 introduce UB, because if A is INT_MIN at runtime, the original
11870 expression can be well defined while the latter is not.
11871 See PR83269. */
11872 && !(ANY_INTEGRAL_TYPE_P (type)
11873 && TYPE_OVERFLOW_UNDEFINED (type)
11874 && ANY_INTEGRAL_TYPE_P (TREE_TYPE (arg0))
11875 && !TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg0))))
11876 return fold_build2_loc (loc, MINUS_EXPR, type, negate_expr (op1),
11877 fold_convert_loc (loc, type,
11878 TREE_OPERAND (arg0, 0)));
11880 /* Fold __complex__ ( x, 0 ) - __complex__ ( 0, y ) to
11881 __complex__ ( x, -y ). This is not the same for SNaNs or if
11882 signed zeros are involved. */
11883 if (!HONOR_SNANS (arg0)
11884 && !HONOR_SIGNED_ZEROS (arg0)
11885 && COMPLEX_FLOAT_TYPE_P (TREE_TYPE (arg0)))
11887 tree rtype = TREE_TYPE (TREE_TYPE (arg0));
11888 tree arg0r = fold_unary_loc (loc, REALPART_EXPR, rtype, arg0);
11889 tree arg0i = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg0);
11890 bool arg0rz = false, arg0iz = false;
11891 if ((arg0r && (arg0rz = real_zerop (arg0r)))
11892 || (arg0i && (arg0iz = real_zerop (arg0i))))
11894 tree arg1r = fold_unary_loc (loc, REALPART_EXPR, rtype, arg1);
11895 tree arg1i = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg1);
11896 if (arg0rz && arg1i && real_zerop (arg1i))
11898 tree rp = fold_build1_loc (loc, NEGATE_EXPR, rtype,
11899 arg1r ? arg1r
11900 : build1 (REALPART_EXPR, rtype, arg1));
11901 tree ip = arg0i ? arg0i
11902 : build1 (IMAGPART_EXPR, rtype, arg0);
11903 return fold_build2_loc (loc, COMPLEX_EXPR, type, rp, ip);
11905 else if (arg0iz && arg1r && real_zerop (arg1r))
11907 tree rp = arg0r ? arg0r
11908 : build1 (REALPART_EXPR, rtype, arg0);
11909 tree ip = fold_build1_loc (loc, NEGATE_EXPR, rtype,
11910 arg1i ? arg1i
11911 : build1 (IMAGPART_EXPR, rtype, arg1));
11912 return fold_build2_loc (loc, COMPLEX_EXPR, type, rp, ip);
11917 /* A - B -> A + (-B) if B is easily negatable. */
11918 if (negate_expr_p (op1)
11919 && ! TYPE_OVERFLOW_SANITIZED (type)
11920 && ((FLOAT_TYPE_P (type)
11921 /* Avoid this transformation if B is a positive REAL_CST. */
11922 && (TREE_CODE (op1) != REAL_CST
11923 || REAL_VALUE_NEGATIVE (TREE_REAL_CST (op1))))
11924 || INTEGRAL_TYPE_P (type)))
11925 return fold_build2_loc (loc, PLUS_EXPR, type,
11926 fold_convert_loc (loc, type, arg0),
11927 negate_expr (op1));
11929 /* Handle (A1 * C1) - (A2 * C2) with A1, A2 or C1, C2 being the same or
11930 one. Make sure the type is not saturating and has the signedness of
11931 the stripped operands, as fold_plusminus_mult_expr will re-associate.
11932 ??? The latter condition should use TYPE_OVERFLOW_* flags instead. */
11933 if ((TREE_CODE (arg0) == MULT_EXPR
11934 || TREE_CODE (arg1) == MULT_EXPR)
11935 && !TYPE_SATURATING (type)
11936 && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (TREE_TYPE (arg0))
11937 && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (TREE_TYPE (arg1))
11938 && (!FLOAT_TYPE_P (type) || flag_associative_math))
11940 tree tem = fold_plusminus_mult_expr (loc, code, type, arg0, arg1);
11941 if (tem)
11942 return tem;
11945 goto associate;
11947 case MULT_EXPR:
11948 if (! FLOAT_TYPE_P (type))
11950 /* Transform x * -C into -x * C if x is easily negatable. */
11951 if (TREE_CODE (op1) == INTEGER_CST
11952 && tree_int_cst_sgn (op1) == -1
11953 && negate_expr_p (op0)
11954 && negate_expr_p (op1)
11955 && (tem = negate_expr (op1)) != op1
11956 && ! TREE_OVERFLOW (tem))
11957 return fold_build2_loc (loc, MULT_EXPR, type,
11958 fold_convert_loc (loc, type,
11959 negate_expr (op0)), tem);
11961 strict_overflow_p = false;
11962 if (TREE_CODE (arg1) == INTEGER_CST
11963 && (tem = extract_muldiv (op0, arg1, code, NULL_TREE,
11964 &strict_overflow_p)) != 0)
11966 if (strict_overflow_p)
11967 fold_overflow_warning (("assuming signed overflow does not "
11968 "occur when simplifying "
11969 "multiplication"),
11970 WARN_STRICT_OVERFLOW_MISC);
11971 return fold_convert_loc (loc, type, tem);
11974 /* Optimize z * conj(z) for integer complex numbers. */
11975 if (TREE_CODE (arg0) == CONJ_EXPR
11976 && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
11977 return fold_mult_zconjz (loc, type, arg1);
11978 if (TREE_CODE (arg1) == CONJ_EXPR
11979 && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
11980 return fold_mult_zconjz (loc, type, arg0);
11982 else
11984 /* Fold z * +-I to __complex__ (-+__imag z, +-__real z).
11985 This is not the same for NaNs or if signed zeros are
11986 involved. */
11987 if (!HONOR_NANS (arg0)
11988 && !HONOR_SIGNED_ZEROS (arg0)
11989 && COMPLEX_FLOAT_TYPE_P (TREE_TYPE (arg0))
11990 && TREE_CODE (arg1) == COMPLEX_CST
11991 && real_zerop (TREE_REALPART (arg1)))
11993 tree rtype = TREE_TYPE (TREE_TYPE (arg0));
11994 if (real_onep (TREE_IMAGPART (arg1)))
11995 return
11996 fold_build2_loc (loc, COMPLEX_EXPR, type,
11997 negate_expr (fold_build1_loc (loc, IMAGPART_EXPR,
11998 rtype, arg0)),
11999 fold_build1_loc (loc, REALPART_EXPR, rtype, arg0));
12000 else if (real_minus_onep (TREE_IMAGPART (arg1)))
12001 return
12002 fold_build2_loc (loc, COMPLEX_EXPR, type,
12003 fold_build1_loc (loc, IMAGPART_EXPR, rtype, arg0),
12004 negate_expr (fold_build1_loc (loc, REALPART_EXPR,
12005 rtype, arg0)));
12008 /* Optimize z * conj(z) for floating point complex numbers.
12009 Guarded by flag_unsafe_math_optimizations as non-finite
12010 imaginary components don't produce scalar results. */
12011 if (flag_unsafe_math_optimizations
12012 && TREE_CODE (arg0) == CONJ_EXPR
12013 && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
12014 return fold_mult_zconjz (loc, type, arg1);
12015 if (flag_unsafe_math_optimizations
12016 && TREE_CODE (arg1) == CONJ_EXPR
12017 && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
12018 return fold_mult_zconjz (loc, type, arg0);
12020 goto associate;
12022 case BIT_IOR_EXPR:
12023 /* Canonicalize (X & C1) | C2. */
12024 if (TREE_CODE (arg0) == BIT_AND_EXPR
12025 && TREE_CODE (arg1) == INTEGER_CST
12026 && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
12028 int width = TYPE_PRECISION (type), w;
12029 wide_int c1 = wi::to_wide (TREE_OPERAND (arg0, 1));
12030 wide_int c2 = wi::to_wide (arg1);
12032 /* If (C1&C2) == C1, then (X&C1)|C2 becomes (X,C2). */
12033 if ((c1 & c2) == c1)
12034 return omit_one_operand_loc (loc, type, arg1,
12035 TREE_OPERAND (arg0, 0));
12037 wide_int msk = wi::mask (width, false,
12038 TYPE_PRECISION (TREE_TYPE (arg1)));
12040 /* If (C1|C2) == ~0 then (X&C1)|C2 becomes X|C2. */
12041 if (wi::bit_and_not (msk, c1 | c2) == 0)
12043 tem = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
12044 return fold_build2_loc (loc, BIT_IOR_EXPR, type, tem, arg1);
12047 /* Minimize the number of bits set in C1, i.e. C1 := C1 & ~C2,
12048 unless (C1 & ~C2) | (C2 & C3) for some C3 is a mask of some
12049 mode which allows further optimizations. */
12050 c1 &= msk;
12051 c2 &= msk;
12052 wide_int c3 = wi::bit_and_not (c1, c2);
12053 for (w = BITS_PER_UNIT; w <= width; w <<= 1)
12055 wide_int mask = wi::mask (w, false,
12056 TYPE_PRECISION (type));
12057 if (((c1 | c2) & mask) == mask
12058 && wi::bit_and_not (c1, mask) == 0)
12060 c3 = mask;
12061 break;
12065 if (c3 != c1)
12067 tem = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
12068 tem = fold_build2_loc (loc, BIT_AND_EXPR, type, tem,
12069 wide_int_to_tree (type, c3));
12070 return fold_build2_loc (loc, BIT_IOR_EXPR, type, tem, arg1);
12074 /* See if this can be simplified into a rotate first. If that
12075 is unsuccessful continue in the association code. */
12076 goto bit_rotate;
12078 case BIT_XOR_EXPR:
12079 /* Fold (X & 1) ^ 1 as (X & 1) == 0. */
12080 if (TREE_CODE (arg0) == BIT_AND_EXPR
12081 && INTEGRAL_TYPE_P (type)
12082 && integer_onep (TREE_OPERAND (arg0, 1))
12083 && integer_onep (arg1))
12084 return fold_build2_loc (loc, EQ_EXPR, type, arg0,
12085 build_zero_cst (TREE_TYPE (arg0)));
12087 /* See if this can be simplified into a rotate first. If that
12088 is unsuccessful continue in the association code. */
12089 goto bit_rotate;
12091 case BIT_AND_EXPR:
12092 /* Fold !X & 1 as X == 0. */
12093 if (TREE_CODE (arg0) == TRUTH_NOT_EXPR
12094 && integer_onep (arg1))
12096 tem = TREE_OPERAND (arg0, 0);
12097 return fold_build2_loc (loc, EQ_EXPR, type, tem,
12098 build_zero_cst (TREE_TYPE (tem)));
12101 /* Fold (X * Y) & -(1 << CST) to X * Y if Y is a constant
12102 multiple of 1 << CST. */
12103 if (TREE_CODE (arg1) == INTEGER_CST)
12105 wi::tree_to_wide_ref cst1 = wi::to_wide (arg1);
12106 wide_int ncst1 = -cst1;
12107 if ((cst1 & ncst1) == ncst1
12108 && multiple_of_p (type, arg0,
12109 wide_int_to_tree (TREE_TYPE (arg1), ncst1)))
12110 return fold_convert_loc (loc, type, arg0);
12113 /* Fold (X * CST1) & CST2 to zero if we can, or drop known zero
12114 bits from CST2. */
12115 if (TREE_CODE (arg1) == INTEGER_CST
12116 && TREE_CODE (arg0) == MULT_EXPR
12117 && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
12119 wi::tree_to_wide_ref warg1 = wi::to_wide (arg1);
12120 wide_int masked
12121 = mask_with_tz (type, warg1, wi::to_wide (TREE_OPERAND (arg0, 1)));
12123 if (masked == 0)
12124 return omit_two_operands_loc (loc, type, build_zero_cst (type),
12125 arg0, arg1);
12126 else if (masked != warg1)
12128 /* Avoid the transform if arg1 is a mask of some
12129 mode which allows further optimizations. */
12130 int pop = wi::popcount (warg1);
12131 if (!(pop >= BITS_PER_UNIT
12132 && pow2p_hwi (pop)
12133 && wi::mask (pop, false, warg1.get_precision ()) == warg1))
12134 return fold_build2_loc (loc, code, type, op0,
12135 wide_int_to_tree (type, masked));
12139 /* Simplify ((int)c & 0377) into (int)c, if c is unsigned char. */
12140 if (TREE_CODE (arg1) == INTEGER_CST && TREE_CODE (arg0) == NOP_EXPR
12141 && TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (arg0, 0))))
12143 prec = element_precision (TREE_TYPE (TREE_OPERAND (arg0, 0)));
12145 wide_int mask = wide_int::from (wi::to_wide (arg1), prec, UNSIGNED);
12146 if (mask == -1)
12147 return
12148 fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
12151 goto associate;
12153 case RDIV_EXPR:
12154 /* Don't touch a floating-point divide by zero unless the mode
12155 of the constant can represent infinity. */
12156 if (TREE_CODE (arg1) == REAL_CST
12157 && !MODE_HAS_INFINITIES (TYPE_MODE (TREE_TYPE (arg1)))
12158 && real_zerop (arg1))
12159 return NULL_TREE;
12161 /* (-A) / (-B) -> A / B */
12162 if (TREE_CODE (arg0) == NEGATE_EXPR && negate_expr_p (arg1))
12163 return fold_build2_loc (loc, RDIV_EXPR, type,
12164 TREE_OPERAND (arg0, 0),
12165 negate_expr (arg1));
12166 if (TREE_CODE (arg1) == NEGATE_EXPR && negate_expr_p (arg0))
12167 return fold_build2_loc (loc, RDIV_EXPR, type,
12168 negate_expr (arg0),
12169 TREE_OPERAND (arg1, 0));
12170 return NULL_TREE;
12172 case TRUNC_DIV_EXPR:
12173 /* Fall through */
12175 case FLOOR_DIV_EXPR:
12176 /* Simplify A / (B << N) where A and B are positive and B is
12177 a power of 2, to A >> (N + log2(B)). */
12178 strict_overflow_p = false;
12179 if (TREE_CODE (arg1) == LSHIFT_EXPR
12180 && (TYPE_UNSIGNED (type)
12181 || tree_expr_nonnegative_warnv_p (op0, &strict_overflow_p)))
12183 tree sval = TREE_OPERAND (arg1, 0);
12184 if (integer_pow2p (sval) && tree_int_cst_sgn (sval) > 0)
12186 tree sh_cnt = TREE_OPERAND (arg1, 1);
12187 tree pow2 = build_int_cst (TREE_TYPE (sh_cnt),
12188 wi::exact_log2 (wi::to_wide (sval)));
12190 if (strict_overflow_p)
12191 fold_overflow_warning (("assuming signed overflow does not "
12192 "occur when simplifying A / (B << N)"),
12193 WARN_STRICT_OVERFLOW_MISC);
12195 sh_cnt = fold_build2_loc (loc, PLUS_EXPR, TREE_TYPE (sh_cnt),
12196 sh_cnt, pow2);
12197 return fold_build2_loc (loc, RSHIFT_EXPR, type,
12198 fold_convert_loc (loc, type, arg0), sh_cnt);
12202 /* Fall through */
12204 case ROUND_DIV_EXPR:
12205 case CEIL_DIV_EXPR:
12206 case EXACT_DIV_EXPR:
12207 if (integer_zerop (arg1))
12208 return NULL_TREE;
12210 /* Convert -A / -B to A / B when the type is signed and overflow is
12211 undefined. */
12212 if ((!ANY_INTEGRAL_TYPE_P (type) || TYPE_OVERFLOW_UNDEFINED (type))
12213 && TREE_CODE (op0) == NEGATE_EXPR
12214 && negate_expr_p (op1))
12216 if (ANY_INTEGRAL_TYPE_P (type))
12217 fold_overflow_warning (("assuming signed overflow does not occur "
12218 "when distributing negation across "
12219 "division"),
12220 WARN_STRICT_OVERFLOW_MISC);
12221 return fold_build2_loc (loc, code, type,
12222 fold_convert_loc (loc, type,
12223 TREE_OPERAND (arg0, 0)),
12224 negate_expr (op1));
12226 if ((!ANY_INTEGRAL_TYPE_P (type) || TYPE_OVERFLOW_UNDEFINED (type))
12227 && TREE_CODE (arg1) == NEGATE_EXPR
12228 && negate_expr_p (op0))
12230 if (ANY_INTEGRAL_TYPE_P (type))
12231 fold_overflow_warning (("assuming signed overflow does not occur "
12232 "when distributing negation across "
12233 "division"),
12234 WARN_STRICT_OVERFLOW_MISC);
12235 return fold_build2_loc (loc, code, type,
12236 negate_expr (op0),
12237 fold_convert_loc (loc, type,
12238 TREE_OPERAND (arg1, 0)));
12241 /* If arg0 is a multiple of arg1, then rewrite to the fastest div
12242 operation, EXACT_DIV_EXPR.
12244 Note that only CEIL_DIV_EXPR and FLOOR_DIV_EXPR are rewritten now.
12245 At one time others generated faster code, it's not clear if they do
12246 after the last round to changes to the DIV code in expmed.cc. */
12247 if ((code == CEIL_DIV_EXPR || code == FLOOR_DIV_EXPR)
12248 && multiple_of_p (type, arg0, arg1))
12249 return fold_build2_loc (loc, EXACT_DIV_EXPR, type,
12250 fold_convert (type, arg0),
12251 fold_convert (type, arg1));
12253 strict_overflow_p = false;
12254 if (TREE_CODE (arg1) == INTEGER_CST
12255 && (tem = extract_muldiv (op0, arg1, code, NULL_TREE,
12256 &strict_overflow_p)) != 0)
12258 if (strict_overflow_p)
12259 fold_overflow_warning (("assuming signed overflow does not occur "
12260 "when simplifying division"),
12261 WARN_STRICT_OVERFLOW_MISC);
12262 return fold_convert_loc (loc, type, tem);
12265 return NULL_TREE;
12267 case CEIL_MOD_EXPR:
12268 case FLOOR_MOD_EXPR:
12269 case ROUND_MOD_EXPR:
12270 case TRUNC_MOD_EXPR:
12271 strict_overflow_p = false;
12272 if (TREE_CODE (arg1) == INTEGER_CST
12273 && (tem = extract_muldiv (op0, arg1, code, NULL_TREE,
12274 &strict_overflow_p)) != 0)
12276 if (strict_overflow_p)
12277 fold_overflow_warning (("assuming signed overflow does not occur "
12278 "when simplifying modulus"),
12279 WARN_STRICT_OVERFLOW_MISC);
12280 return fold_convert_loc (loc, type, tem);
12283 return NULL_TREE;
12285 case LROTATE_EXPR:
12286 case RROTATE_EXPR:
12287 case RSHIFT_EXPR:
12288 case LSHIFT_EXPR:
12289 /* Since negative shift count is not well-defined,
12290 don't try to compute it in the compiler. */
12291 if (TREE_CODE (arg1) == INTEGER_CST && tree_int_cst_sgn (arg1) < 0)
12292 return NULL_TREE;
12294 prec = element_precision (type);
12296 /* If we have a rotate of a bit operation with the rotate count and
12297 the second operand of the bit operation both constant,
12298 permute the two operations. */
12299 if (code == RROTATE_EXPR && TREE_CODE (arg1) == INTEGER_CST
12300 && (TREE_CODE (arg0) == BIT_AND_EXPR
12301 || TREE_CODE (arg0) == BIT_IOR_EXPR
12302 || TREE_CODE (arg0) == BIT_XOR_EXPR)
12303 && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
12305 tree arg00 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
12306 tree arg01 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 1));
12307 return fold_build2_loc (loc, TREE_CODE (arg0), type,
12308 fold_build2_loc (loc, code, type,
12309 arg00, arg1),
12310 fold_build2_loc (loc, code, type,
12311 arg01, arg1));
12314 /* Two consecutive rotates adding up to the some integer
12315 multiple of the precision of the type can be ignored. */
12316 if (code == RROTATE_EXPR && TREE_CODE (arg1) == INTEGER_CST
12317 && TREE_CODE (arg0) == RROTATE_EXPR
12318 && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
12319 && wi::umod_trunc (wi::to_wide (arg1)
12320 + wi::to_wide (TREE_OPERAND (arg0, 1)),
12321 prec) == 0)
12322 return fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
12324 return NULL_TREE;
12326 case MIN_EXPR:
12327 case MAX_EXPR:
12328 goto associate;
12330 case TRUTH_ANDIF_EXPR:
12331 /* Note that the operands of this must be ints
12332 and their values must be 0 or 1.
12333 ("true" is a fixed value perhaps depending on the language.) */
12334 /* If first arg is constant zero, return it. */
12335 if (integer_zerop (arg0))
12336 return fold_convert_loc (loc, type, arg0);
12337 /* FALLTHRU */
12338 case TRUTH_AND_EXPR:
12339 /* If either arg is constant true, drop it. */
12340 if (TREE_CODE (arg0) == INTEGER_CST && ! integer_zerop (arg0))
12341 return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg1));
12342 if (TREE_CODE (arg1) == INTEGER_CST && ! integer_zerop (arg1)
12343 /* Preserve sequence points. */
12344 && (code != TRUTH_ANDIF_EXPR || ! TREE_SIDE_EFFECTS (arg0)))
12345 return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
12346 /* If second arg is constant zero, result is zero, but first arg
12347 must be evaluated. */
12348 if (integer_zerop (arg1))
12349 return omit_one_operand_loc (loc, type, arg1, arg0);
12350 /* Likewise for first arg, but note that only the TRUTH_AND_EXPR
12351 case will be handled here. */
12352 if (integer_zerop (arg0))
12353 return omit_one_operand_loc (loc, type, arg0, arg1);
12355 /* !X && X is always false. */
12356 if (TREE_CODE (arg0) == TRUTH_NOT_EXPR
12357 && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
12358 return omit_one_operand_loc (loc, type, integer_zero_node, arg1);
12359 /* X && !X is always false. */
12360 if (TREE_CODE (arg1) == TRUTH_NOT_EXPR
12361 && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
12362 return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
12364 /* A < X && A + 1 > Y ==> A < X && A >= Y. Normally A + 1 > Y
12365 means A >= Y && A != MAX, but in this case we know that
12366 A < X <= MAX. */
12368 if (!TREE_SIDE_EFFECTS (arg0)
12369 && !TREE_SIDE_EFFECTS (arg1))
12371 tem = fold_to_nonsharp_ineq_using_bound (loc, arg0, arg1);
12372 if (tem && !operand_equal_p (tem, arg0, 0))
12373 return fold_convert (type,
12374 fold_build2_loc (loc, code, TREE_TYPE (arg1),
12375 tem, arg1));
12377 tem = fold_to_nonsharp_ineq_using_bound (loc, arg1, arg0);
12378 if (tem && !operand_equal_p (tem, arg1, 0))
12379 return fold_convert (type,
12380 fold_build2_loc (loc, code, TREE_TYPE (arg0),
12381 arg0, tem));
12384 if ((tem = fold_truth_andor (loc, code, type, arg0, arg1, op0, op1))
12385 != NULL_TREE)
12386 return tem;
12388 return NULL_TREE;
12390 case TRUTH_ORIF_EXPR:
12391 /* Note that the operands of this must be ints
12392 and their values must be 0 or true.
12393 ("true" is a fixed value perhaps depending on the language.) */
12394 /* If first arg is constant true, return it. */
12395 if (TREE_CODE (arg0) == INTEGER_CST && ! integer_zerop (arg0))
12396 return fold_convert_loc (loc, type, arg0);
12397 /* FALLTHRU */
12398 case TRUTH_OR_EXPR:
12399 /* If either arg is constant zero, drop it. */
12400 if (TREE_CODE (arg0) == INTEGER_CST && integer_zerop (arg0))
12401 return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg1));
12402 if (TREE_CODE (arg1) == INTEGER_CST && integer_zerop (arg1)
12403 /* Preserve sequence points. */
12404 && (code != TRUTH_ORIF_EXPR || ! TREE_SIDE_EFFECTS (arg0)))
12405 return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
12406 /* If second arg is constant true, result is true, but we must
12407 evaluate first arg. */
12408 if (TREE_CODE (arg1) == INTEGER_CST && ! integer_zerop (arg1))
12409 return omit_one_operand_loc (loc, type, arg1, arg0);
12410 /* Likewise for first arg, but note this only occurs here for
12411 TRUTH_OR_EXPR. */
12412 if (TREE_CODE (arg0) == INTEGER_CST && ! integer_zerop (arg0))
12413 return omit_one_operand_loc (loc, type, arg0, arg1);
12415 /* !X || X is always true. */
12416 if (TREE_CODE (arg0) == TRUTH_NOT_EXPR
12417 && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
12418 return omit_one_operand_loc (loc, type, integer_one_node, arg1);
12419 /* X || !X is always true. */
12420 if (TREE_CODE (arg1) == TRUTH_NOT_EXPR
12421 && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
12422 return omit_one_operand_loc (loc, type, integer_one_node, arg0);
12424 /* (X && !Y) || (!X && Y) is X ^ Y */
12425 if (TREE_CODE (arg0) == TRUTH_AND_EXPR
12426 && TREE_CODE (arg1) == TRUTH_AND_EXPR)
12428 tree a0, a1, l0, l1, n0, n1;
12430 a0 = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 0));
12431 a1 = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 1));
12433 l0 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
12434 l1 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 1));
12436 n0 = fold_build1_loc (loc, TRUTH_NOT_EXPR, type, l0);
12437 n1 = fold_build1_loc (loc, TRUTH_NOT_EXPR, type, l1);
12439 if ((operand_equal_p (n0, a0, 0)
12440 && operand_equal_p (n1, a1, 0))
12441 || (operand_equal_p (n0, a1, 0)
12442 && operand_equal_p (n1, a0, 0)))
12443 return fold_build2_loc (loc, TRUTH_XOR_EXPR, type, l0, n1);
12446 if ((tem = fold_truth_andor (loc, code, type, arg0, arg1, op0, op1))
12447 != NULL_TREE)
12448 return tem;
12450 return NULL_TREE;
12452 case TRUTH_XOR_EXPR:
12453 /* If the second arg is constant zero, drop it. */
12454 if (integer_zerop (arg1))
12455 return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
12456 /* If the second arg is constant true, this is a logical inversion. */
12457 if (integer_onep (arg1))
12459 tem = invert_truthvalue_loc (loc, arg0);
12460 return non_lvalue_loc (loc, fold_convert_loc (loc, type, tem));
12462 /* Identical arguments cancel to zero. */
12463 if (operand_equal_p (arg0, arg1, 0))
12464 return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
12466 /* !X ^ X is always true. */
12467 if (TREE_CODE (arg0) == TRUTH_NOT_EXPR
12468 && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
12469 return omit_one_operand_loc (loc, type, integer_one_node, arg1);
12471 /* X ^ !X is always true. */
12472 if (TREE_CODE (arg1) == TRUTH_NOT_EXPR
12473 && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
12474 return omit_one_operand_loc (loc, type, integer_one_node, arg0);
12476 return NULL_TREE;
12478 case EQ_EXPR:
12479 case NE_EXPR:
12480 STRIP_NOPS (arg0);
12481 STRIP_NOPS (arg1);
12483 tem = fold_comparison (loc, code, type, op0, op1);
12484 if (tem != NULL_TREE)
12485 return tem;
12487 /* bool_var != 1 becomes !bool_var. */
12488 if (TREE_CODE (TREE_TYPE (arg0)) == BOOLEAN_TYPE && integer_onep (arg1)
12489 && code == NE_EXPR)
12490 return fold_convert_loc (loc, type,
12491 fold_build1_loc (loc, TRUTH_NOT_EXPR,
12492 TREE_TYPE (arg0), arg0));
12494 /* bool_var == 0 becomes !bool_var. */
12495 if (TREE_CODE (TREE_TYPE (arg0)) == BOOLEAN_TYPE && integer_zerop (arg1)
12496 && code == EQ_EXPR)
12497 return fold_convert_loc (loc, type,
12498 fold_build1_loc (loc, TRUTH_NOT_EXPR,
12499 TREE_TYPE (arg0), arg0));
12501 /* !exp != 0 becomes !exp */
12502 if (TREE_CODE (arg0) == TRUTH_NOT_EXPR && integer_zerop (arg1)
12503 && code == NE_EXPR)
12504 return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
12506 /* If this is an EQ or NE comparison with zero and ARG0 is
12507 (1 << foo) & bar, convert it to (bar >> foo) & 1. Both require
12508 two operations, but the latter can be done in one less insn
12509 on machines that have only two-operand insns or on which a
12510 constant cannot be the first operand. */
12511 if (TREE_CODE (arg0) == BIT_AND_EXPR
12512 && integer_zerop (arg1))
12514 tree arg00 = TREE_OPERAND (arg0, 0);
12515 tree arg01 = TREE_OPERAND (arg0, 1);
12516 if (TREE_CODE (arg00) == LSHIFT_EXPR
12517 && integer_onep (TREE_OPERAND (arg00, 0)))
12519 tree tem = fold_build2_loc (loc, RSHIFT_EXPR, TREE_TYPE (arg00),
12520 arg01, TREE_OPERAND (arg00, 1));
12521 tem = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg0), tem,
12522 build_one_cst (TREE_TYPE (arg0)));
12523 return fold_build2_loc (loc, code, type,
12524 fold_convert_loc (loc, TREE_TYPE (arg1),
12525 tem), arg1);
12527 else if (TREE_CODE (arg01) == LSHIFT_EXPR
12528 && integer_onep (TREE_OPERAND (arg01, 0)))
12530 tree tem = fold_build2_loc (loc, RSHIFT_EXPR, TREE_TYPE (arg01),
12531 arg00, TREE_OPERAND (arg01, 1));
12532 tem = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg0), tem,
12533 build_one_cst (TREE_TYPE (arg0)));
12534 return fold_build2_loc (loc, code, type,
12535 fold_convert_loc (loc, TREE_TYPE (arg1),
12536 tem), arg1);
12540 /* If this is a comparison of a field, we may be able to simplify it. */
12541 if ((TREE_CODE (arg0) == COMPONENT_REF
12542 || TREE_CODE (arg0) == BIT_FIELD_REF)
12543 /* Handle the constant case even without -O
12544 to make sure the warnings are given. */
12545 && (optimize || TREE_CODE (arg1) == INTEGER_CST))
12547 t1 = optimize_bit_field_compare (loc, code, type, arg0, arg1);
12548 if (t1)
12549 return t1;
12552 /* Optimize comparisons of strlen vs zero to a compare of the
12553 first character of the string vs zero. To wit,
12554 strlen(ptr) == 0 => *ptr == 0
12555 strlen(ptr) != 0 => *ptr != 0
12556 Other cases should reduce to one of these two (or a constant)
12557 due to the return value of strlen being unsigned. */
12558 if (TREE_CODE (arg0) == CALL_EXPR && integer_zerop (arg1))
12560 tree fndecl = get_callee_fndecl (arg0);
12562 if (fndecl
12563 && fndecl_built_in_p (fndecl, BUILT_IN_STRLEN)
12564 && call_expr_nargs (arg0) == 1
12565 && (TREE_CODE (TREE_TYPE (CALL_EXPR_ARG (arg0, 0)))
12566 == POINTER_TYPE))
12568 tree ptrtype
12569 = build_pointer_type (build_qualified_type (char_type_node,
12570 TYPE_QUAL_CONST));
12571 tree ptr = fold_convert_loc (loc, ptrtype,
12572 CALL_EXPR_ARG (arg0, 0));
12573 tree iref = build_fold_indirect_ref_loc (loc, ptr);
12574 return fold_build2_loc (loc, code, type, iref,
12575 build_int_cst (TREE_TYPE (iref), 0));
12579 /* Fold (X >> C) != 0 into X < 0 if C is one less than the width
12580 of X. Similarly fold (X >> C) == 0 into X >= 0. */
12581 if (TREE_CODE (arg0) == RSHIFT_EXPR
12582 && integer_zerop (arg1)
12583 && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
12585 tree arg00 = TREE_OPERAND (arg0, 0);
12586 tree arg01 = TREE_OPERAND (arg0, 1);
12587 tree itype = TREE_TYPE (arg00);
12588 if (wi::to_wide (arg01) == element_precision (itype) - 1)
12590 if (TYPE_UNSIGNED (itype))
12592 itype = signed_type_for (itype);
12593 arg00 = fold_convert_loc (loc, itype, arg00);
12595 return fold_build2_loc (loc, code == EQ_EXPR ? GE_EXPR : LT_EXPR,
12596 type, arg00, build_zero_cst (itype));
12600 /* Fold (~X & C) == 0 into (X & C) != 0 and (~X & C) != 0 into
12601 (X & C) == 0 when C is a single bit. */
12602 if (TREE_CODE (arg0) == BIT_AND_EXPR
12603 && TREE_CODE (TREE_OPERAND (arg0, 0)) == BIT_NOT_EXPR
12604 && integer_zerop (arg1)
12605 && integer_pow2p (TREE_OPERAND (arg0, 1)))
12607 tem = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg0),
12608 TREE_OPERAND (TREE_OPERAND (arg0, 0), 0),
12609 TREE_OPERAND (arg0, 1));
12610 return fold_build2_loc (loc, code == EQ_EXPR ? NE_EXPR : EQ_EXPR,
12611 type, tem,
12612 fold_convert_loc (loc, TREE_TYPE (arg0),
12613 arg1));
12616 /* Fold ((X & C) ^ C) eq/ne 0 into (X & C) ne/eq 0, when the
12617 constant C is a power of two, i.e. a single bit. */
12618 if (TREE_CODE (arg0) == BIT_XOR_EXPR
12619 && TREE_CODE (TREE_OPERAND (arg0, 0)) == BIT_AND_EXPR
12620 && integer_zerop (arg1)
12621 && integer_pow2p (TREE_OPERAND (arg0, 1))
12622 && operand_equal_p (TREE_OPERAND (TREE_OPERAND (arg0, 0), 1),
12623 TREE_OPERAND (arg0, 1), OEP_ONLY_CONST))
12625 tree arg00 = TREE_OPERAND (arg0, 0);
12626 return fold_build2_loc (loc, code == EQ_EXPR ? NE_EXPR : EQ_EXPR, type,
12627 arg00, build_int_cst (TREE_TYPE (arg00), 0));
12630 /* Likewise, fold ((X ^ C) & C) eq/ne 0 into (X & C) ne/eq 0,
12631 when is C is a power of two, i.e. a single bit. */
12632 if (TREE_CODE (arg0) == BIT_AND_EXPR
12633 && TREE_CODE (TREE_OPERAND (arg0, 0)) == BIT_XOR_EXPR
12634 && integer_zerop (arg1)
12635 && integer_pow2p (TREE_OPERAND (arg0, 1))
12636 && operand_equal_p (TREE_OPERAND (TREE_OPERAND (arg0, 0), 1),
12637 TREE_OPERAND (arg0, 1), OEP_ONLY_CONST))
12639 tree arg000 = TREE_OPERAND (TREE_OPERAND (arg0, 0), 0);
12640 tem = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg000),
12641 arg000, TREE_OPERAND (arg0, 1));
12642 return fold_build2_loc (loc, code == EQ_EXPR ? NE_EXPR : EQ_EXPR, type,
12643 tem, build_int_cst (TREE_TYPE (tem), 0));
12646 if (TREE_CODE (arg0) == BIT_XOR_EXPR
12647 && TREE_CODE (arg1) == BIT_XOR_EXPR)
12649 tree arg00 = TREE_OPERAND (arg0, 0);
12650 tree arg01 = TREE_OPERAND (arg0, 1);
12651 tree arg10 = TREE_OPERAND (arg1, 0);
12652 tree arg11 = TREE_OPERAND (arg1, 1);
12653 tree itype = TREE_TYPE (arg0);
12655 /* Optimize (X ^ Z) op (Y ^ Z) as X op Y, and symmetries.
12656 operand_equal_p guarantees no side-effects so we don't need
12657 to use omit_one_operand on Z. */
12658 if (operand_equal_p (arg01, arg11, 0))
12659 return fold_build2_loc (loc, code, type, arg00,
12660 fold_convert_loc (loc, TREE_TYPE (arg00),
12661 arg10));
12662 if (operand_equal_p (arg01, arg10, 0))
12663 return fold_build2_loc (loc, code, type, arg00,
12664 fold_convert_loc (loc, TREE_TYPE (arg00),
12665 arg11));
12666 if (operand_equal_p (arg00, arg11, 0))
12667 return fold_build2_loc (loc, code, type, arg01,
12668 fold_convert_loc (loc, TREE_TYPE (arg01),
12669 arg10));
12670 if (operand_equal_p (arg00, arg10, 0))
12671 return fold_build2_loc (loc, code, type, arg01,
12672 fold_convert_loc (loc, TREE_TYPE (arg01),
12673 arg11));
12675 /* Optimize (X ^ C1) op (Y ^ C2) as (X ^ (C1 ^ C2)) op Y. */
12676 if (TREE_CODE (arg01) == INTEGER_CST
12677 && TREE_CODE (arg11) == INTEGER_CST)
12679 tem = fold_build2_loc (loc, BIT_XOR_EXPR, itype, arg01,
12680 fold_convert_loc (loc, itype, arg11));
12681 tem = fold_build2_loc (loc, BIT_XOR_EXPR, itype, arg00, tem);
12682 return fold_build2_loc (loc, code, type, tem,
12683 fold_convert_loc (loc, itype, arg10));
12687 /* Attempt to simplify equality/inequality comparisons of complex
12688 values. Only lower the comparison if the result is known or
12689 can be simplified to a single scalar comparison. */
12690 if ((TREE_CODE (arg0) == COMPLEX_EXPR
12691 || TREE_CODE (arg0) == COMPLEX_CST)
12692 && (TREE_CODE (arg1) == COMPLEX_EXPR
12693 || TREE_CODE (arg1) == COMPLEX_CST))
12695 tree real0, imag0, real1, imag1;
12696 tree rcond, icond;
12698 if (TREE_CODE (arg0) == COMPLEX_EXPR)
12700 real0 = TREE_OPERAND (arg0, 0);
12701 imag0 = TREE_OPERAND (arg0, 1);
12703 else
12705 real0 = TREE_REALPART (arg0);
12706 imag0 = TREE_IMAGPART (arg0);
12709 if (TREE_CODE (arg1) == COMPLEX_EXPR)
12711 real1 = TREE_OPERAND (arg1, 0);
12712 imag1 = TREE_OPERAND (arg1, 1);
12714 else
12716 real1 = TREE_REALPART (arg1);
12717 imag1 = TREE_IMAGPART (arg1);
12720 rcond = fold_binary_loc (loc, code, type, real0, real1);
12721 if (rcond && TREE_CODE (rcond) == INTEGER_CST)
12723 if (integer_zerop (rcond))
12725 if (code == EQ_EXPR)
12726 return omit_two_operands_loc (loc, type, boolean_false_node,
12727 imag0, imag1);
12728 return fold_build2_loc (loc, NE_EXPR, type, imag0, imag1);
12730 else
12732 if (code == NE_EXPR)
12733 return omit_two_operands_loc (loc, type, boolean_true_node,
12734 imag0, imag1);
12735 return fold_build2_loc (loc, EQ_EXPR, type, imag0, imag1);
12739 icond = fold_binary_loc (loc, code, type, imag0, imag1);
12740 if (icond && TREE_CODE (icond) == INTEGER_CST)
12742 if (integer_zerop (icond))
12744 if (code == EQ_EXPR)
12745 return omit_two_operands_loc (loc, type, boolean_false_node,
12746 real0, real1);
12747 return fold_build2_loc (loc, NE_EXPR, type, real0, real1);
12749 else
12751 if (code == NE_EXPR)
12752 return omit_two_operands_loc (loc, type, boolean_true_node,
12753 real0, real1);
12754 return fold_build2_loc (loc, EQ_EXPR, type, real0, real1);
12759 return NULL_TREE;
12761 case LT_EXPR:
12762 case GT_EXPR:
12763 case LE_EXPR:
12764 case GE_EXPR:
12765 tem = fold_comparison (loc, code, type, op0, op1);
12766 if (tem != NULL_TREE)
12767 return tem;
12769 /* Transform comparisons of the form X +- C CMP X. */
12770 if ((TREE_CODE (arg0) == PLUS_EXPR || TREE_CODE (arg0) == MINUS_EXPR)
12771 && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0)
12772 && TREE_CODE (TREE_OPERAND (arg0, 1)) == REAL_CST
12773 && !HONOR_SNANS (arg0))
12775 tree arg01 = TREE_OPERAND (arg0, 1);
12776 enum tree_code code0 = TREE_CODE (arg0);
12777 int is_positive = REAL_VALUE_NEGATIVE (TREE_REAL_CST (arg01)) ? -1 : 1;
12779 /* (X - c) > X becomes false. */
12780 if (code == GT_EXPR
12781 && ((code0 == MINUS_EXPR && is_positive >= 0)
12782 || (code0 == PLUS_EXPR && is_positive <= 0)))
12783 return constant_boolean_node (0, type);
12785 /* Likewise (X + c) < X becomes false. */
12786 if (code == LT_EXPR
12787 && ((code0 == PLUS_EXPR && is_positive >= 0)
12788 || (code0 == MINUS_EXPR && is_positive <= 0)))
12789 return constant_boolean_node (0, type);
12791 /* Convert (X - c) <= X to true. */
12792 if (!HONOR_NANS (arg1)
12793 && code == LE_EXPR
12794 && ((code0 == MINUS_EXPR && is_positive >= 0)
12795 || (code0 == PLUS_EXPR && is_positive <= 0)))
12796 return constant_boolean_node (1, type);
12798 /* Convert (X + c) >= X to true. */
12799 if (!HONOR_NANS (arg1)
12800 && code == GE_EXPR
12801 && ((code0 == PLUS_EXPR && is_positive >= 0)
12802 || (code0 == MINUS_EXPR && is_positive <= 0)))
12803 return constant_boolean_node (1, type);
12806 /* If we are comparing an ABS_EXPR with a constant, we can
12807 convert all the cases into explicit comparisons, but they may
12808 well not be faster than doing the ABS and one comparison.
12809 But ABS (X) <= C is a range comparison, which becomes a subtraction
12810 and a comparison, and is probably faster. */
12811 if (code == LE_EXPR
12812 && TREE_CODE (arg1) == INTEGER_CST
12813 && TREE_CODE (arg0) == ABS_EXPR
12814 && ! TREE_SIDE_EFFECTS (arg0)
12815 && (tem = negate_expr (arg1)) != 0
12816 && TREE_CODE (tem) == INTEGER_CST
12817 && !TREE_OVERFLOW (tem))
12818 return fold_build2_loc (loc, TRUTH_ANDIF_EXPR, type,
12819 build2 (GE_EXPR, type,
12820 TREE_OPERAND (arg0, 0), tem),
12821 build2 (LE_EXPR, type,
12822 TREE_OPERAND (arg0, 0), arg1));
12824 /* Convert ABS_EXPR<x> >= 0 to true. */
12825 strict_overflow_p = false;
12826 if (code == GE_EXPR
12827 && (integer_zerop (arg1)
12828 || (! HONOR_NANS (arg0)
12829 && real_zerop (arg1)))
12830 && tree_expr_nonnegative_warnv_p (arg0, &strict_overflow_p))
12832 if (strict_overflow_p)
12833 fold_overflow_warning (("assuming signed overflow does not occur "
12834 "when simplifying comparison of "
12835 "absolute value and zero"),
12836 WARN_STRICT_OVERFLOW_CONDITIONAL);
12837 return omit_one_operand_loc (loc, type,
12838 constant_boolean_node (true, type),
12839 arg0);
12842 /* Convert ABS_EXPR<x> < 0 to false. */
12843 strict_overflow_p = false;
12844 if (code == LT_EXPR
12845 && (integer_zerop (arg1) || real_zerop (arg1))
12846 && tree_expr_nonnegative_warnv_p (arg0, &strict_overflow_p))
12848 if (strict_overflow_p)
12849 fold_overflow_warning (("assuming signed overflow does not occur "
12850 "when simplifying comparison of "
12851 "absolute value and zero"),
12852 WARN_STRICT_OVERFLOW_CONDITIONAL);
12853 return omit_one_operand_loc (loc, type,
12854 constant_boolean_node (false, type),
12855 arg0);
12858 /* If X is unsigned, convert X < (1 << Y) into X >> Y == 0
12859 and similarly for >= into !=. */
12860 if ((code == LT_EXPR || code == GE_EXPR)
12861 && TYPE_UNSIGNED (TREE_TYPE (arg0))
12862 && TREE_CODE (arg1) == LSHIFT_EXPR
12863 && integer_onep (TREE_OPERAND (arg1, 0)))
12864 return build2_loc (loc, code == LT_EXPR ? EQ_EXPR : NE_EXPR, type,
12865 build2 (RSHIFT_EXPR, TREE_TYPE (arg0), arg0,
12866 TREE_OPERAND (arg1, 1)),
12867 build_zero_cst (TREE_TYPE (arg0)));
12869 /* Similarly for X < (cast) (1 << Y). But cast can't be narrowing,
12870 otherwise Y might be >= # of bits in X's type and thus e.g.
12871 (unsigned char) (1 << Y) for Y 15 might be 0.
12872 If the cast is widening, then 1 << Y should have unsigned type,
12873 otherwise if Y is number of bits in the signed shift type minus 1,
12874 we can't optimize this. E.g. (unsigned long long) (1 << Y) for Y
12875 31 might be 0xffffffff80000000. */
12876 if ((code == LT_EXPR || code == GE_EXPR)
12877 && (INTEGRAL_TYPE_P (TREE_TYPE (arg0))
12878 || VECTOR_INTEGER_TYPE_P (TREE_TYPE (arg0)))
12879 && TYPE_UNSIGNED (TREE_TYPE (arg0))
12880 && CONVERT_EXPR_P (arg1)
12881 && TREE_CODE (TREE_OPERAND (arg1, 0)) == LSHIFT_EXPR
12882 && (element_precision (TREE_TYPE (arg1))
12883 >= element_precision (TREE_TYPE (TREE_OPERAND (arg1, 0))))
12884 && (TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (arg1, 0)))
12885 || (element_precision (TREE_TYPE (arg1))
12886 == element_precision (TREE_TYPE (TREE_OPERAND (arg1, 0)))))
12887 && integer_onep (TREE_OPERAND (TREE_OPERAND (arg1, 0), 0)))
12889 tem = build2 (RSHIFT_EXPR, TREE_TYPE (arg0), arg0,
12890 TREE_OPERAND (TREE_OPERAND (arg1, 0), 1));
12891 return build2_loc (loc, code == LT_EXPR ? EQ_EXPR : NE_EXPR, type,
12892 fold_convert_loc (loc, TREE_TYPE (arg0), tem),
12893 build_zero_cst (TREE_TYPE (arg0)));
12896 return NULL_TREE;
12898 case UNORDERED_EXPR:
12899 case ORDERED_EXPR:
12900 case UNLT_EXPR:
12901 case UNLE_EXPR:
12902 case UNGT_EXPR:
12903 case UNGE_EXPR:
12904 case UNEQ_EXPR:
12905 case LTGT_EXPR:
12906 /* Fold (double)float1 CMP (double)float2 into float1 CMP float2. */
12908 tree targ0 = strip_float_extensions (arg0);
12909 tree targ1 = strip_float_extensions (arg1);
12910 tree newtype = TREE_TYPE (targ0);
12912 if (element_precision (TREE_TYPE (targ1)) > element_precision (newtype))
12913 newtype = TREE_TYPE (targ1);
12915 if (element_precision (newtype) < element_precision (TREE_TYPE (arg0))
12916 && (!VECTOR_TYPE_P (type) || is_truth_type_for (newtype, type)))
12917 return fold_build2_loc (loc, code, type,
12918 fold_convert_loc (loc, newtype, targ0),
12919 fold_convert_loc (loc, newtype, targ1));
12922 return NULL_TREE;
12924 case COMPOUND_EXPR:
12925 /* When pedantic, a compound expression can be neither an lvalue
12926 nor an integer constant expression. */
12927 if (TREE_SIDE_EFFECTS (arg0) || TREE_CONSTANT (arg1))
12928 return NULL_TREE;
12929 /* Don't let (0, 0) be null pointer constant. */
12930 tem = integer_zerop (arg1) ? build1_loc (loc, NOP_EXPR, type, arg1)
12931 : fold_convert_loc (loc, type, arg1);
12932 return tem;
12934 default:
12935 return NULL_TREE;
12936 } /* switch (code) */
12939 /* For constants M and N, if M == (1LL << cst) - 1 && (N & M) == M,
12940 ((A & N) + B) & M -> (A + B) & M
12941 Similarly if (N & M) == 0,
12942 ((A | N) + B) & M -> (A + B) & M
12943 and for - instead of + (or unary - instead of +)
12944 and/or ^ instead of |.
12945 If B is constant and (B & M) == 0, fold into A & M.
12947 This function is a helper for match.pd patterns. Return non-NULL
12948 type in which the simplified operation should be performed only
12949 if any optimization is possible.
12951 ARG1 is M above, ARG00 is left operand of +/-, if CODE00 is BIT_*_EXPR,
12952 then ARG00{0,1} are operands of that bitop, otherwise CODE00 is ERROR_MARK.
12953 Similarly for ARG01, CODE01 and ARG01{0,1}, just for the right operand of
12954 +/-. */
12955 tree
12956 fold_bit_and_mask (tree type, tree arg1, enum tree_code code,
12957 tree arg00, enum tree_code code00, tree arg000, tree arg001,
12958 tree arg01, enum tree_code code01, tree arg010, tree arg011,
12959 tree *pmop)
12961 gcc_assert (TREE_CODE (arg1) == INTEGER_CST);
12962 gcc_assert (code == PLUS_EXPR || code == MINUS_EXPR || code == NEGATE_EXPR);
12963 wi::tree_to_wide_ref cst1 = wi::to_wide (arg1);
12964 if (~cst1 == 0
12965 || (cst1 & (cst1 + 1)) != 0
12966 || !INTEGRAL_TYPE_P (type)
12967 || (!TYPE_OVERFLOW_WRAPS (type)
12968 && TREE_CODE (type) != INTEGER_TYPE)
12969 || (wi::max_value (type) & cst1) != cst1)
12970 return NULL_TREE;
12972 enum tree_code codes[2] = { code00, code01 };
12973 tree arg0xx[4] = { arg000, arg001, arg010, arg011 };
12974 int which = 0;
12975 wide_int cst0;
12977 /* Now we know that arg0 is (C + D) or (C - D) or -C and
12978 arg1 (M) is == (1LL << cst) - 1.
12979 Store C into PMOP[0] and D into PMOP[1]. */
12980 pmop[0] = arg00;
12981 pmop[1] = arg01;
12982 which = code != NEGATE_EXPR;
12984 for (; which >= 0; which--)
12985 switch (codes[which])
12987 case BIT_AND_EXPR:
12988 case BIT_IOR_EXPR:
12989 case BIT_XOR_EXPR:
12990 gcc_assert (TREE_CODE (arg0xx[2 * which + 1]) == INTEGER_CST);
12991 cst0 = wi::to_wide (arg0xx[2 * which + 1]) & cst1;
12992 if (codes[which] == BIT_AND_EXPR)
12994 if (cst0 != cst1)
12995 break;
12997 else if (cst0 != 0)
12998 break;
12999 /* If C or D is of the form (A & N) where
13000 (N & M) == M, or of the form (A | N) or
13001 (A ^ N) where (N & M) == 0, replace it with A. */
13002 pmop[which] = arg0xx[2 * which];
13003 break;
13004 case ERROR_MARK:
13005 if (TREE_CODE (pmop[which]) != INTEGER_CST)
13006 break;
13007 /* If C or D is a N where (N & M) == 0, it can be
13008 omitted (replaced with 0). */
13009 if ((code == PLUS_EXPR
13010 || (code == MINUS_EXPR && which == 0))
13011 && (cst1 & wi::to_wide (pmop[which])) == 0)
13012 pmop[which] = build_int_cst (type, 0);
13013 /* Similarly, with C - N where (-N & M) == 0. */
13014 if (code == MINUS_EXPR
13015 && which == 1
13016 && (cst1 & -wi::to_wide (pmop[which])) == 0)
13017 pmop[which] = build_int_cst (type, 0);
13018 break;
13019 default:
13020 gcc_unreachable ();
13023 /* Only build anything new if we optimized one or both arguments above. */
13024 if (pmop[0] == arg00 && pmop[1] == arg01)
13025 return NULL_TREE;
13027 if (TYPE_OVERFLOW_WRAPS (type))
13028 return type;
13029 else
13030 return unsigned_type_for (type);
13033 /* Used by contains_label_[p1]. */
13035 struct contains_label_data
13037 hash_set<tree> *pset;
13038 bool inside_switch_p;
13041 /* Callback for walk_tree, looking for LABEL_EXPR. Return *TP if it is
13042 a LABEL_EXPR or CASE_LABEL_EXPR not inside of another SWITCH_EXPR; otherwise
13043 return NULL_TREE. Do not check the subtrees of GOTO_EXPR. */
13045 static tree
13046 contains_label_1 (tree *tp, int *walk_subtrees, void *data)
13048 contains_label_data *d = (contains_label_data *) data;
13049 switch (TREE_CODE (*tp))
13051 case LABEL_EXPR:
13052 return *tp;
13054 case CASE_LABEL_EXPR:
13055 if (!d->inside_switch_p)
13056 return *tp;
13057 return NULL_TREE;
13059 case SWITCH_EXPR:
13060 if (!d->inside_switch_p)
13062 if (walk_tree (&SWITCH_COND (*tp), contains_label_1, data, d->pset))
13063 return *tp;
13064 d->inside_switch_p = true;
13065 if (walk_tree (&SWITCH_BODY (*tp), contains_label_1, data, d->pset))
13066 return *tp;
13067 d->inside_switch_p = false;
13068 *walk_subtrees = 0;
13070 return NULL_TREE;
13072 case GOTO_EXPR:
13073 *walk_subtrees = 0;
13074 return NULL_TREE;
13076 default:
13077 return NULL_TREE;
13081 /* Return whether the sub-tree ST contains a label which is accessible from
13082 outside the sub-tree. */
13084 static bool
13085 contains_label_p (tree st)
13087 hash_set<tree> pset;
13088 contains_label_data data = { &pset, false };
13089 return walk_tree (&st, contains_label_1, &data, &pset) != NULL_TREE;
13092 /* Fold a ternary expression of code CODE and type TYPE with operands
13093 OP0, OP1, and OP2. Return the folded expression if folding is
13094 successful. Otherwise, return NULL_TREE. */
13096 tree
13097 fold_ternary_loc (location_t loc, enum tree_code code, tree type,
13098 tree op0, tree op1, tree op2)
13100 tree tem;
13101 tree arg0 = NULL_TREE, arg1 = NULL_TREE, arg2 = NULL_TREE;
13102 enum tree_code_class kind = TREE_CODE_CLASS (code);
13104 gcc_assert (IS_EXPR_CODE_CLASS (kind)
13105 && TREE_CODE_LENGTH (code) == 3);
13107 /* If this is a commutative operation, and OP0 is a constant, move it
13108 to OP1 to reduce the number of tests below. */
13109 if (commutative_ternary_tree_code (code)
13110 && tree_swap_operands_p (op0, op1))
13111 return fold_build3_loc (loc, code, type, op1, op0, op2);
13113 tem = generic_simplify (loc, code, type, op0, op1, op2);
13114 if (tem)
13115 return tem;
13117 /* Strip any conversions that don't change the mode. This is safe
13118 for every expression, except for a comparison expression because
13119 its signedness is derived from its operands. So, in the latter
13120 case, only strip conversions that don't change the signedness.
13122 Note that this is done as an internal manipulation within the
13123 constant folder, in order to find the simplest representation of
13124 the arguments so that their form can be studied. In any cases,
13125 the appropriate type conversions should be put back in the tree
13126 that will get out of the constant folder. */
13127 if (op0)
13129 arg0 = op0;
13130 STRIP_NOPS (arg0);
13133 if (op1)
13135 arg1 = op1;
13136 STRIP_NOPS (arg1);
13139 if (op2)
13141 arg2 = op2;
13142 STRIP_NOPS (arg2);
13145 switch (code)
13147 case COMPONENT_REF:
13148 if (TREE_CODE (arg0) == CONSTRUCTOR
13149 && ! type_contains_placeholder_p (TREE_TYPE (arg0)))
13151 unsigned HOST_WIDE_INT idx;
13152 tree field, value;
13153 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg0), idx, field, value)
13154 if (field == arg1)
13155 return value;
13157 return NULL_TREE;
13159 case COND_EXPR:
13160 case VEC_COND_EXPR:
13161 /* Pedantic ANSI C says that a conditional expression is never an lvalue,
13162 so all simple results must be passed through pedantic_non_lvalue. */
13163 if (TREE_CODE (arg0) == INTEGER_CST)
13165 tree unused_op = integer_zerop (arg0) ? op1 : op2;
13166 tem = integer_zerop (arg0) ? op2 : op1;
13167 /* Only optimize constant conditions when the selected branch
13168 has the same type as the COND_EXPR. This avoids optimizing
13169 away "c ? x : throw", where the throw has a void type.
13170 Avoid throwing away that operand which contains label. */
13171 if ((!TREE_SIDE_EFFECTS (unused_op)
13172 || !contains_label_p (unused_op))
13173 && (! VOID_TYPE_P (TREE_TYPE (tem))
13174 || VOID_TYPE_P (type)))
13175 return protected_set_expr_location_unshare (tem, loc);
13176 return NULL_TREE;
13178 else if (TREE_CODE (arg0) == VECTOR_CST)
13180 unsigned HOST_WIDE_INT nelts;
13181 if ((TREE_CODE (arg1) == VECTOR_CST
13182 || TREE_CODE (arg1) == CONSTRUCTOR)
13183 && (TREE_CODE (arg2) == VECTOR_CST
13184 || TREE_CODE (arg2) == CONSTRUCTOR)
13185 && TYPE_VECTOR_SUBPARTS (type).is_constant (&nelts))
13187 vec_perm_builder sel (nelts, nelts, 1);
13188 for (unsigned int i = 0; i < nelts; i++)
13190 tree val = VECTOR_CST_ELT (arg0, i);
13191 if (integer_all_onesp (val))
13192 sel.quick_push (i);
13193 else if (integer_zerop (val))
13194 sel.quick_push (nelts + i);
13195 else /* Currently unreachable. */
13196 return NULL_TREE;
13198 vec_perm_indices indices (sel, 2, nelts);
13199 tree t = fold_vec_perm (type, arg1, arg2, indices);
13200 if (t != NULL_TREE)
13201 return t;
13205 /* If we have A op B ? A : C, we may be able to convert this to a
13206 simpler expression, depending on the operation and the values
13207 of B and C. Signed zeros prevent all of these transformations,
13208 for reasons given above each one.
13210 Also try swapping the arguments and inverting the conditional. */
13211 if (COMPARISON_CLASS_P (arg0)
13212 && operand_equal_for_comparison_p (TREE_OPERAND (arg0, 0), op1)
13213 && !HONOR_SIGNED_ZEROS (op1))
13215 tem = fold_cond_expr_with_comparison (loc, type, TREE_CODE (arg0),
13216 TREE_OPERAND (arg0, 0),
13217 TREE_OPERAND (arg0, 1),
13218 op1, op2);
13219 if (tem)
13220 return tem;
13223 if (COMPARISON_CLASS_P (arg0)
13224 && operand_equal_for_comparison_p (TREE_OPERAND (arg0, 0), op2)
13225 && !HONOR_SIGNED_ZEROS (op2))
13227 enum tree_code comp_code = TREE_CODE (arg0);
13228 tree arg00 = TREE_OPERAND (arg0, 0);
13229 tree arg01 = TREE_OPERAND (arg0, 1);
13230 comp_code = invert_tree_comparison (comp_code, HONOR_NANS (arg00));
13231 if (comp_code != ERROR_MARK)
13232 tem = fold_cond_expr_with_comparison (loc, type, comp_code,
13233 arg00,
13234 arg01,
13235 op2, op1);
13236 if (tem)
13237 return tem;
13240 /* If the second operand is simpler than the third, swap them
13241 since that produces better jump optimization results. */
13242 if (truth_value_p (TREE_CODE (arg0))
13243 && tree_swap_operands_p (op1, op2))
13245 location_t loc0 = expr_location_or (arg0, loc);
13246 /* See if this can be inverted. If it can't, possibly because
13247 it was a floating-point inequality comparison, don't do
13248 anything. */
13249 tem = fold_invert_truthvalue (loc0, arg0);
13250 if (tem)
13251 return fold_build3_loc (loc, code, type, tem, op2, op1);
13254 /* Convert A ? 1 : 0 to simply A. */
13255 if ((code == VEC_COND_EXPR ? integer_all_onesp (op1)
13256 : (integer_onep (op1)
13257 && !VECTOR_TYPE_P (type)))
13258 && integer_zerop (op2)
13259 /* If we try to convert OP0 to our type, the
13260 call to fold will try to move the conversion inside
13261 a COND, which will recurse. In that case, the COND_EXPR
13262 is probably the best choice, so leave it alone. */
13263 && type == TREE_TYPE (arg0))
13264 return protected_set_expr_location_unshare (arg0, loc);
13266 /* Convert A ? 0 : 1 to !A. This prefers the use of NOT_EXPR
13267 over COND_EXPR in cases such as floating point comparisons. */
13268 if (integer_zerop (op1)
13269 && code == COND_EXPR
13270 && integer_onep (op2)
13271 && !VECTOR_TYPE_P (type)
13272 && truth_value_p (TREE_CODE (arg0)))
13273 return fold_convert_loc (loc, type,
13274 invert_truthvalue_loc (loc, arg0));
13276 /* A < 0 ? <sign bit of A> : 0 is simply (A & <sign bit of A>). */
13277 if (TREE_CODE (arg0) == LT_EXPR
13278 && integer_zerop (TREE_OPERAND (arg0, 1))
13279 && integer_zerop (op2)
13280 && (tem = sign_bit_p (TREE_OPERAND (arg0, 0), arg1)))
13282 /* sign_bit_p looks through both zero and sign extensions,
13283 but for this optimization only sign extensions are
13284 usable. */
13285 tree tem2 = TREE_OPERAND (arg0, 0);
13286 while (tem != tem2)
13288 if (TREE_CODE (tem2) != NOP_EXPR
13289 || TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (tem2, 0))))
13291 tem = NULL_TREE;
13292 break;
13294 tem2 = TREE_OPERAND (tem2, 0);
13296 /* sign_bit_p only checks ARG1 bits within A's precision.
13297 If <sign bit of A> has wider type than A, bits outside
13298 of A's precision in <sign bit of A> need to be checked.
13299 If they are all 0, this optimization needs to be done
13300 in unsigned A's type, if they are all 1 in signed A's type,
13301 otherwise this can't be done. */
13302 if (tem
13303 && TYPE_PRECISION (TREE_TYPE (tem))
13304 < TYPE_PRECISION (TREE_TYPE (arg1))
13305 && TYPE_PRECISION (TREE_TYPE (tem))
13306 < TYPE_PRECISION (type))
13308 int inner_width, outer_width;
13309 tree tem_type;
13311 inner_width = TYPE_PRECISION (TREE_TYPE (tem));
13312 outer_width = TYPE_PRECISION (TREE_TYPE (arg1));
13313 if (outer_width > TYPE_PRECISION (type))
13314 outer_width = TYPE_PRECISION (type);
13316 wide_int mask = wi::shifted_mask
13317 (inner_width, outer_width - inner_width, false,
13318 TYPE_PRECISION (TREE_TYPE (arg1)));
13320 wide_int common = mask & wi::to_wide (arg1);
13321 if (common == mask)
13323 tem_type = signed_type_for (TREE_TYPE (tem));
13324 tem = fold_convert_loc (loc, tem_type, tem);
13326 else if (common == 0)
13328 tem_type = unsigned_type_for (TREE_TYPE (tem));
13329 tem = fold_convert_loc (loc, tem_type, tem);
13331 else
13332 tem = NULL;
13335 if (tem)
13336 return
13337 fold_convert_loc (loc, type,
13338 fold_build2_loc (loc, BIT_AND_EXPR,
13339 TREE_TYPE (tem), tem,
13340 fold_convert_loc (loc,
13341 TREE_TYPE (tem),
13342 arg1)));
13345 /* (A >> N) & 1 ? (1 << N) : 0 is simply A & (1 << N). A & 1 was
13346 already handled above. */
13347 if (TREE_CODE (arg0) == BIT_AND_EXPR
13348 && integer_onep (TREE_OPERAND (arg0, 1))
13349 && integer_zerop (op2)
13350 && integer_pow2p (arg1))
13352 tree tem = TREE_OPERAND (arg0, 0);
13353 STRIP_NOPS (tem);
13354 if (TREE_CODE (tem) == RSHIFT_EXPR
13355 && tree_fits_uhwi_p (TREE_OPERAND (tem, 1))
13356 && (unsigned HOST_WIDE_INT) tree_log2 (arg1)
13357 == tree_to_uhwi (TREE_OPERAND (tem, 1)))
13358 return fold_build2_loc (loc, BIT_AND_EXPR, type,
13359 fold_convert_loc (loc, type,
13360 TREE_OPERAND (tem, 0)),
13361 op1);
13364 /* A & N ? N : 0 is simply A & N if N is a power of two. This
13365 is probably obsolete because the first operand should be a
13366 truth value (that's why we have the two cases above), but let's
13367 leave it in until we can confirm this for all front-ends. */
13368 if (integer_zerop (op2)
13369 && TREE_CODE (arg0) == NE_EXPR
13370 && integer_zerop (TREE_OPERAND (arg0, 1))
13371 && integer_pow2p (arg1)
13372 && TREE_CODE (TREE_OPERAND (arg0, 0)) == BIT_AND_EXPR
13373 && operand_equal_p (TREE_OPERAND (TREE_OPERAND (arg0, 0), 1),
13374 arg1, OEP_ONLY_CONST)
13375 /* operand_equal_p compares just value, not precision, so e.g.
13376 arg1 could be 8-bit -128 and be power of two, but BIT_AND_EXPR
13377 second operand 32-bit -128, which is not a power of two (or vice
13378 versa. */
13379 && integer_pow2p (TREE_OPERAND (TREE_OPERAND (arg0, 0), 1)))
13380 return fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
13382 /* Disable the transformations below for vectors, since
13383 fold_binary_op_with_conditional_arg may undo them immediately,
13384 yielding an infinite loop. */
13385 if (code == VEC_COND_EXPR)
13386 return NULL_TREE;
13388 /* Convert A ? B : 0 into A && B if A and B are truth values. */
13389 if (integer_zerop (op2)
13390 && truth_value_p (TREE_CODE (arg0))
13391 && truth_value_p (TREE_CODE (arg1))
13392 && (code == VEC_COND_EXPR || !VECTOR_TYPE_P (type)))
13393 return fold_build2_loc (loc, code == VEC_COND_EXPR ? BIT_AND_EXPR
13394 : TRUTH_ANDIF_EXPR,
13395 type, fold_convert_loc (loc, type, arg0), op1);
13397 /* Convert A ? B : 1 into !A || B if A and B are truth values. */
13398 if (code == VEC_COND_EXPR ? integer_all_onesp (op2) : integer_onep (op2)
13399 && truth_value_p (TREE_CODE (arg0))
13400 && truth_value_p (TREE_CODE (arg1))
13401 && (code == VEC_COND_EXPR || !VECTOR_TYPE_P (type)))
13403 location_t loc0 = expr_location_or (arg0, loc);
13404 /* Only perform transformation if ARG0 is easily inverted. */
13405 tem = fold_invert_truthvalue (loc0, arg0);
13406 if (tem)
13407 return fold_build2_loc (loc, code == VEC_COND_EXPR
13408 ? BIT_IOR_EXPR
13409 : TRUTH_ORIF_EXPR,
13410 type, fold_convert_loc (loc, type, tem),
13411 op1);
13414 /* Convert A ? 0 : B into !A && B if A and B are truth values. */
13415 if (integer_zerop (arg1)
13416 && truth_value_p (TREE_CODE (arg0))
13417 && truth_value_p (TREE_CODE (op2))
13418 && (code == VEC_COND_EXPR || !VECTOR_TYPE_P (type)))
13420 location_t loc0 = expr_location_or (arg0, loc);
13421 /* Only perform transformation if ARG0 is easily inverted. */
13422 tem = fold_invert_truthvalue (loc0, arg0);
13423 if (tem)
13424 return fold_build2_loc (loc, code == VEC_COND_EXPR
13425 ? BIT_AND_EXPR : TRUTH_ANDIF_EXPR,
13426 type, fold_convert_loc (loc, type, tem),
13427 op2);
13430 /* Convert A ? 1 : B into A || B if A and B are truth values. */
13431 if (code == VEC_COND_EXPR ? integer_all_onesp (arg1) : integer_onep (arg1)
13432 && truth_value_p (TREE_CODE (arg0))
13433 && truth_value_p (TREE_CODE (op2))
13434 && (code == VEC_COND_EXPR || !VECTOR_TYPE_P (type)))
13435 return fold_build2_loc (loc, code == VEC_COND_EXPR
13436 ? BIT_IOR_EXPR : TRUTH_ORIF_EXPR,
13437 type, fold_convert_loc (loc, type, arg0), op2);
13439 return NULL_TREE;
13441 case CALL_EXPR:
13442 /* CALL_EXPRs used to be ternary exprs. Catch any mistaken uses
13443 of fold_ternary on them. */
13444 gcc_unreachable ();
13446 case BIT_FIELD_REF:
13447 if (TREE_CODE (arg0) == VECTOR_CST
13448 && (type == TREE_TYPE (TREE_TYPE (arg0))
13449 || (VECTOR_TYPE_P (type)
13450 && TREE_TYPE (type) == TREE_TYPE (TREE_TYPE (arg0))))
13451 && tree_fits_uhwi_p (op1)
13452 && tree_fits_uhwi_p (op2))
13454 tree eltype = TREE_TYPE (TREE_TYPE (arg0));
13455 unsigned HOST_WIDE_INT width
13456 = (TREE_CODE (eltype) == BOOLEAN_TYPE
13457 ? TYPE_PRECISION (eltype) : tree_to_uhwi (TYPE_SIZE (eltype)));
13458 unsigned HOST_WIDE_INT n = tree_to_uhwi (arg1);
13459 unsigned HOST_WIDE_INT idx = tree_to_uhwi (op2);
13461 if (n != 0
13462 && (idx % width) == 0
13463 && (n % width) == 0
13464 && known_le ((idx + n) / width,
13465 TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0))))
13467 idx = idx / width;
13468 n = n / width;
13470 if (TREE_CODE (arg0) == VECTOR_CST)
13472 if (n == 1)
13474 tem = VECTOR_CST_ELT (arg0, idx);
13475 if (VECTOR_TYPE_P (type))
13476 tem = fold_build1 (VIEW_CONVERT_EXPR, type, tem);
13477 return tem;
13480 tree_vector_builder vals (type, n, 1);
13481 for (unsigned i = 0; i < n; ++i)
13482 vals.quick_push (VECTOR_CST_ELT (arg0, idx + i));
13483 return vals.build ();
13488 /* On constants we can use native encode/interpret to constant
13489 fold (nearly) all BIT_FIELD_REFs. */
13490 if (CONSTANT_CLASS_P (arg0)
13491 && can_native_interpret_type_p (type)
13492 && BITS_PER_UNIT == 8
13493 && tree_fits_uhwi_p (op1)
13494 && tree_fits_uhwi_p (op2))
13496 unsigned HOST_WIDE_INT bitpos = tree_to_uhwi (op2);
13497 unsigned HOST_WIDE_INT bitsize = tree_to_uhwi (op1);
13498 /* Limit us to a reasonable amount of work. To relax the
13499 other limitations we need bit-shifting of the buffer
13500 and rounding up the size. */
13501 if (bitpos % BITS_PER_UNIT == 0
13502 && bitsize % BITS_PER_UNIT == 0
13503 && bitsize <= MAX_BITSIZE_MODE_ANY_MODE)
13505 unsigned char b[MAX_BITSIZE_MODE_ANY_MODE / BITS_PER_UNIT];
13506 unsigned HOST_WIDE_INT len
13507 = native_encode_expr (arg0, b, bitsize / BITS_PER_UNIT,
13508 bitpos / BITS_PER_UNIT);
13509 if (len > 0
13510 && len * BITS_PER_UNIT >= bitsize)
13512 tree v = native_interpret_expr (type, b,
13513 bitsize / BITS_PER_UNIT);
13514 if (v)
13515 return v;
13520 return NULL_TREE;
13522 case VEC_PERM_EXPR:
13523 /* Perform constant folding of BIT_INSERT_EXPR. */
13524 if (TREE_CODE (arg2) == VECTOR_CST
13525 && TREE_CODE (op0) == VECTOR_CST
13526 && TREE_CODE (op1) == VECTOR_CST)
13528 /* Build a vector of integers from the tree mask. */
13529 vec_perm_builder builder;
13530 if (!tree_to_vec_perm_builder (&builder, arg2))
13531 return NULL_TREE;
13533 /* Create a vec_perm_indices for the integer vector. */
13534 poly_uint64 nelts = TYPE_VECTOR_SUBPARTS (type);
13535 bool single_arg = (op0 == op1);
13536 vec_perm_indices sel (builder, single_arg ? 1 : 2, nelts);
13537 return fold_vec_perm (type, op0, op1, sel);
13539 return NULL_TREE;
13541 case BIT_INSERT_EXPR:
13542 /* Perform (partial) constant folding of BIT_INSERT_EXPR. */
13543 if (TREE_CODE (arg0) == INTEGER_CST
13544 && TREE_CODE (arg1) == INTEGER_CST)
13546 unsigned HOST_WIDE_INT bitpos = tree_to_uhwi (op2);
13547 unsigned bitsize = TYPE_PRECISION (TREE_TYPE (arg1));
13548 wide_int tem = (wi::to_wide (arg0)
13549 & wi::shifted_mask (bitpos, bitsize, true,
13550 TYPE_PRECISION (type)));
13551 wide_int tem2
13552 = wi::lshift (wi::zext (wi::to_wide (arg1, TYPE_PRECISION (type)),
13553 bitsize), bitpos);
13554 return wide_int_to_tree (type, wi::bit_or (tem, tem2));
13556 else if (TREE_CODE (arg0) == VECTOR_CST
13557 && CONSTANT_CLASS_P (arg1)
13558 && types_compatible_p (TREE_TYPE (TREE_TYPE (arg0)),
13559 TREE_TYPE (arg1)))
13561 unsigned HOST_WIDE_INT bitpos = tree_to_uhwi (op2);
13562 unsigned HOST_WIDE_INT elsize
13563 = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (arg1)));
13564 if (bitpos % elsize == 0)
13566 unsigned k = bitpos / elsize;
13567 unsigned HOST_WIDE_INT nelts;
13568 if (operand_equal_p (VECTOR_CST_ELT (arg0, k), arg1, 0))
13569 return arg0;
13570 else if (VECTOR_CST_NELTS (arg0).is_constant (&nelts))
13572 tree_vector_builder elts (type, nelts, 1);
13573 elts.quick_grow (nelts);
13574 for (unsigned HOST_WIDE_INT i = 0; i < nelts; ++i)
13575 elts[i] = (i == k ? arg1 : VECTOR_CST_ELT (arg0, i));
13576 return elts.build ();
13580 return NULL_TREE;
13582 default:
13583 return NULL_TREE;
13584 } /* switch (code) */
13587 /* Gets the element ACCESS_INDEX from CTOR, which must be a CONSTRUCTOR
13588 of an array (or vector). *CTOR_IDX if non-NULL is updated with the
13589 constructor element index of the value returned. If the element is
13590 not found NULL_TREE is returned and *CTOR_IDX is updated to
13591 the index of the element after the ACCESS_INDEX position (which
13592 may be outside of the CTOR array). */
13594 tree
13595 get_array_ctor_element_at_index (tree ctor, offset_int access_index,
13596 unsigned *ctor_idx)
13598 tree index_type = NULL_TREE;
13599 signop index_sgn = UNSIGNED;
13600 offset_int low_bound = 0;
13602 if (TREE_CODE (TREE_TYPE (ctor)) == ARRAY_TYPE)
13604 tree domain_type = TYPE_DOMAIN (TREE_TYPE (ctor));
13605 if (domain_type && TYPE_MIN_VALUE (domain_type))
13607 /* Static constructors for variably sized objects makes no sense. */
13608 gcc_assert (TREE_CODE (TYPE_MIN_VALUE (domain_type)) == INTEGER_CST);
13609 index_type = TREE_TYPE (TYPE_MIN_VALUE (domain_type));
13610 /* ??? When it is obvious that the range is signed, treat it so. */
13611 if (TYPE_UNSIGNED (index_type)
13612 && TYPE_MAX_VALUE (domain_type)
13613 && tree_int_cst_lt (TYPE_MAX_VALUE (domain_type),
13614 TYPE_MIN_VALUE (domain_type)))
13616 index_sgn = SIGNED;
13617 low_bound
13618 = offset_int::from (wi::to_wide (TYPE_MIN_VALUE (domain_type)),
13619 SIGNED);
13621 else
13623 index_sgn = TYPE_SIGN (index_type);
13624 low_bound = wi::to_offset (TYPE_MIN_VALUE (domain_type));
13629 if (index_type)
13630 access_index = wi::ext (access_index, TYPE_PRECISION (index_type),
13631 index_sgn);
13633 offset_int index = low_bound;
13634 if (index_type)
13635 index = wi::ext (index, TYPE_PRECISION (index_type), index_sgn);
13637 offset_int max_index = index;
13638 unsigned cnt;
13639 tree cfield, cval;
13640 bool first_p = true;
13642 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), cnt, cfield, cval)
13644 /* Array constructor might explicitly set index, or specify a range,
13645 or leave index NULL meaning that it is next index after previous
13646 one. */
13647 if (cfield)
13649 if (TREE_CODE (cfield) == INTEGER_CST)
13650 max_index = index
13651 = offset_int::from (wi::to_wide (cfield), index_sgn);
13652 else
13654 gcc_assert (TREE_CODE (cfield) == RANGE_EXPR);
13655 index = offset_int::from (wi::to_wide (TREE_OPERAND (cfield, 0)),
13656 index_sgn);
13657 max_index
13658 = offset_int::from (wi::to_wide (TREE_OPERAND (cfield, 1)),
13659 index_sgn);
13660 gcc_checking_assert (wi::le_p (index, max_index, index_sgn));
13663 else if (!first_p)
13665 index = max_index + 1;
13666 if (index_type)
13667 index = wi::ext (index, TYPE_PRECISION (index_type), index_sgn);
13668 gcc_checking_assert (wi::gt_p (index, max_index, index_sgn));
13669 max_index = index;
13671 else
13672 first_p = false;
13674 /* Do we have match? */
13675 if (wi::cmp (access_index, index, index_sgn) >= 0)
13677 if (wi::cmp (access_index, max_index, index_sgn) <= 0)
13679 if (ctor_idx)
13680 *ctor_idx = cnt;
13681 return cval;
13684 else if (in_gimple_form)
13685 /* We're past the element we search for. Note during parsing
13686 the elements might not be sorted.
13687 ??? We should use a binary search and a flag on the
13688 CONSTRUCTOR as to whether elements are sorted in declaration
13689 order. */
13690 break;
13692 if (ctor_idx)
13693 *ctor_idx = cnt;
13694 return NULL_TREE;
13697 /* Perform constant folding and related simplification of EXPR.
13698 The related simplifications include x*1 => x, x*0 => 0, etc.,
13699 and application of the associative law.
13700 NOP_EXPR conversions may be removed freely (as long as we
13701 are careful not to change the type of the overall expression).
13702 We cannot simplify through a CONVERT_EXPR, FIX_EXPR or FLOAT_EXPR,
13703 but we can constant-fold them if they have constant operands. */
13705 #ifdef ENABLE_FOLD_CHECKING
13706 # define fold(x) fold_1 (x)
13707 static tree fold_1 (tree);
13708 static
13709 #endif
13710 tree
13711 fold (tree expr)
13713 const tree t = expr;
13714 enum tree_code code = TREE_CODE (t);
13715 enum tree_code_class kind = TREE_CODE_CLASS (code);
13716 tree tem;
13717 location_t loc = EXPR_LOCATION (expr);
13719 /* Return right away if a constant. */
13720 if (kind == tcc_constant)
13721 return t;
13723 /* CALL_EXPR-like objects with variable numbers of operands are
13724 treated specially. */
13725 if (kind == tcc_vl_exp)
13727 if (code == CALL_EXPR)
13729 tem = fold_call_expr (loc, expr, false);
13730 return tem ? tem : expr;
13732 return expr;
13735 if (IS_EXPR_CODE_CLASS (kind))
13737 tree type = TREE_TYPE (t);
13738 tree op0, op1, op2;
13740 switch (TREE_CODE_LENGTH (code))
13742 case 1:
13743 op0 = TREE_OPERAND (t, 0);
13744 tem = fold_unary_loc (loc, code, type, op0);
13745 return tem ? tem : expr;
13746 case 2:
13747 op0 = TREE_OPERAND (t, 0);
13748 op1 = TREE_OPERAND (t, 1);
13749 tem = fold_binary_loc (loc, code, type, op0, op1);
13750 return tem ? tem : expr;
13751 case 3:
13752 op0 = TREE_OPERAND (t, 0);
13753 op1 = TREE_OPERAND (t, 1);
13754 op2 = TREE_OPERAND (t, 2);
13755 tem = fold_ternary_loc (loc, code, type, op0, op1, op2);
13756 return tem ? tem : expr;
13757 default:
13758 break;
13762 switch (code)
13764 case ARRAY_REF:
13766 tree op0 = TREE_OPERAND (t, 0);
13767 tree op1 = TREE_OPERAND (t, 1);
13769 if (TREE_CODE (op1) == INTEGER_CST
13770 && TREE_CODE (op0) == CONSTRUCTOR
13771 && ! type_contains_placeholder_p (TREE_TYPE (op0)))
13773 tree val = get_array_ctor_element_at_index (op0,
13774 wi::to_offset (op1));
13775 if (val)
13776 return val;
13779 return t;
13782 /* Return a VECTOR_CST if possible. */
13783 case CONSTRUCTOR:
13785 tree type = TREE_TYPE (t);
13786 if (TREE_CODE (type) != VECTOR_TYPE)
13787 return t;
13789 unsigned i;
13790 tree val;
13791 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (t), i, val)
13792 if (! CONSTANT_CLASS_P (val))
13793 return t;
13795 return build_vector_from_ctor (type, CONSTRUCTOR_ELTS (t));
13798 case CONST_DECL:
13799 return fold (DECL_INITIAL (t));
13801 default:
13802 return t;
13803 } /* switch (code) */
13806 #ifdef ENABLE_FOLD_CHECKING
13807 #undef fold
13809 static void fold_checksum_tree (const_tree, struct md5_ctx *,
13810 hash_table<nofree_ptr_hash<const tree_node> > *);
13811 static void fold_check_failed (const_tree, const_tree);
13812 void print_fold_checksum (const_tree);
13814 /* When --enable-checking=fold, compute a digest of expr before
13815 and after actual fold call to see if fold did not accidentally
13816 change original expr. */
13818 tree
13819 fold (tree expr)
13821 tree ret;
13822 struct md5_ctx ctx;
13823 unsigned char checksum_before[16], checksum_after[16];
13824 hash_table<nofree_ptr_hash<const tree_node> > ht (32);
13826 md5_init_ctx (&ctx);
13827 fold_checksum_tree (expr, &ctx, &ht);
13828 md5_finish_ctx (&ctx, checksum_before);
13829 ht.empty ();
13831 ret = fold_1 (expr);
13833 md5_init_ctx (&ctx);
13834 fold_checksum_tree (expr, &ctx, &ht);
13835 md5_finish_ctx (&ctx, checksum_after);
13837 if (memcmp (checksum_before, checksum_after, 16))
13838 fold_check_failed (expr, ret);
13840 return ret;
13843 void
13844 print_fold_checksum (const_tree expr)
13846 struct md5_ctx ctx;
13847 unsigned char checksum[16], cnt;
13848 hash_table<nofree_ptr_hash<const tree_node> > ht (32);
13850 md5_init_ctx (&ctx);
13851 fold_checksum_tree (expr, &ctx, &ht);
13852 md5_finish_ctx (&ctx, checksum);
13853 for (cnt = 0; cnt < 16; ++cnt)
13854 fprintf (stderr, "%02x", checksum[cnt]);
13855 putc ('\n', stderr);
13858 static void
13859 fold_check_failed (const_tree expr ATTRIBUTE_UNUSED, const_tree ret ATTRIBUTE_UNUSED)
13861 internal_error ("fold check: original tree changed by fold");
13864 static void
13865 fold_checksum_tree (const_tree expr, struct md5_ctx *ctx,
13866 hash_table<nofree_ptr_hash <const tree_node> > *ht)
13868 const tree_node **slot;
13869 enum tree_code code;
13870 union tree_node *buf;
13871 int i, len;
13873 recursive_label:
13874 if (expr == NULL)
13875 return;
13876 slot = ht->find_slot (expr, INSERT);
13877 if (*slot != NULL)
13878 return;
13879 *slot = expr;
13880 code = TREE_CODE (expr);
13881 if (TREE_CODE_CLASS (code) == tcc_declaration
13882 && HAS_DECL_ASSEMBLER_NAME_P (expr))
13884 /* Allow DECL_ASSEMBLER_NAME and symtab_node to be modified. */
13885 size_t sz = tree_size (expr);
13886 buf = XALLOCAVAR (union tree_node, sz);
13887 memcpy ((char *) buf, expr, sz);
13888 SET_DECL_ASSEMBLER_NAME ((tree) buf, NULL);
13889 buf->decl_with_vis.symtab_node = NULL;
13890 buf->base.nowarning_flag = 0;
13891 expr = (tree) buf;
13893 else if (TREE_CODE_CLASS (code) == tcc_type
13894 && (TYPE_POINTER_TO (expr)
13895 || TYPE_REFERENCE_TO (expr)
13896 || TYPE_CACHED_VALUES_P (expr)
13897 || TYPE_CONTAINS_PLACEHOLDER_INTERNAL (expr)
13898 || TYPE_NEXT_VARIANT (expr)
13899 || TYPE_ALIAS_SET_KNOWN_P (expr)))
13901 /* Allow these fields to be modified. */
13902 tree tmp;
13903 size_t sz = tree_size (expr);
13904 buf = XALLOCAVAR (union tree_node, sz);
13905 memcpy ((char *) buf, expr, sz);
13906 expr = tmp = (tree) buf;
13907 TYPE_CONTAINS_PLACEHOLDER_INTERNAL (tmp) = 0;
13908 TYPE_POINTER_TO (tmp) = NULL;
13909 TYPE_REFERENCE_TO (tmp) = NULL;
13910 TYPE_NEXT_VARIANT (tmp) = NULL;
13911 TYPE_ALIAS_SET (tmp) = -1;
13912 if (TYPE_CACHED_VALUES_P (tmp))
13914 TYPE_CACHED_VALUES_P (tmp) = 0;
13915 TYPE_CACHED_VALUES (tmp) = NULL;
13918 else if (warning_suppressed_p (expr) && (DECL_P (expr) || EXPR_P (expr)))
13920 /* Allow the no-warning bit to be set. Perhaps we shouldn't allow
13921 that and change builtins.cc etc. instead - see PR89543. */
13922 size_t sz = tree_size (expr);
13923 buf = XALLOCAVAR (union tree_node, sz);
13924 memcpy ((char *) buf, expr, sz);
13925 buf->base.nowarning_flag = 0;
13926 expr = (tree) buf;
13928 md5_process_bytes (expr, tree_size (expr), ctx);
13929 if (CODE_CONTAINS_STRUCT (code, TS_TYPED))
13930 fold_checksum_tree (TREE_TYPE (expr), ctx, ht);
13931 if (TREE_CODE_CLASS (code) != tcc_type
13932 && TREE_CODE_CLASS (code) != tcc_declaration
13933 && code != TREE_LIST
13934 && code != SSA_NAME
13935 && CODE_CONTAINS_STRUCT (code, TS_COMMON))
13936 fold_checksum_tree (TREE_CHAIN (expr), ctx, ht);
13937 switch (TREE_CODE_CLASS (code))
13939 case tcc_constant:
13940 switch (code)
13942 case STRING_CST:
13943 md5_process_bytes (TREE_STRING_POINTER (expr),
13944 TREE_STRING_LENGTH (expr), ctx);
13945 break;
13946 case COMPLEX_CST:
13947 fold_checksum_tree (TREE_REALPART (expr), ctx, ht);
13948 fold_checksum_tree (TREE_IMAGPART (expr), ctx, ht);
13949 break;
13950 case VECTOR_CST:
13951 len = vector_cst_encoded_nelts (expr);
13952 for (i = 0; i < len; ++i)
13953 fold_checksum_tree (VECTOR_CST_ENCODED_ELT (expr, i), ctx, ht);
13954 break;
13955 default:
13956 break;
13958 break;
13959 case tcc_exceptional:
13960 switch (code)
13962 case TREE_LIST:
13963 fold_checksum_tree (TREE_PURPOSE (expr), ctx, ht);
13964 fold_checksum_tree (TREE_VALUE (expr), ctx, ht);
13965 expr = TREE_CHAIN (expr);
13966 goto recursive_label;
13967 break;
13968 case TREE_VEC:
13969 for (i = 0; i < TREE_VEC_LENGTH (expr); ++i)
13970 fold_checksum_tree (TREE_VEC_ELT (expr, i), ctx, ht);
13971 break;
13972 default:
13973 break;
13975 break;
13976 case tcc_expression:
13977 case tcc_reference:
13978 case tcc_comparison:
13979 case tcc_unary:
13980 case tcc_binary:
13981 case tcc_statement:
13982 case tcc_vl_exp:
13983 len = TREE_OPERAND_LENGTH (expr);
13984 for (i = 0; i < len; ++i)
13985 fold_checksum_tree (TREE_OPERAND (expr, i), ctx, ht);
13986 break;
13987 case tcc_declaration:
13988 fold_checksum_tree (DECL_NAME (expr), ctx, ht);
13989 fold_checksum_tree (DECL_CONTEXT (expr), ctx, ht);
13990 if (CODE_CONTAINS_STRUCT (TREE_CODE (expr), TS_DECL_COMMON))
13992 fold_checksum_tree (DECL_SIZE (expr), ctx, ht);
13993 fold_checksum_tree (DECL_SIZE_UNIT (expr), ctx, ht);
13994 fold_checksum_tree (DECL_INITIAL (expr), ctx, ht);
13995 fold_checksum_tree (DECL_ABSTRACT_ORIGIN (expr), ctx, ht);
13996 fold_checksum_tree (DECL_ATTRIBUTES (expr), ctx, ht);
13999 if (CODE_CONTAINS_STRUCT (TREE_CODE (expr), TS_DECL_NON_COMMON))
14001 if (TREE_CODE (expr) == FUNCTION_DECL)
14003 fold_checksum_tree (DECL_VINDEX (expr), ctx, ht);
14004 fold_checksum_tree (DECL_ARGUMENTS (expr), ctx, ht);
14006 fold_checksum_tree (DECL_RESULT_FLD (expr), ctx, ht);
14008 break;
14009 case tcc_type:
14010 if (TREE_CODE (expr) == ENUMERAL_TYPE)
14011 fold_checksum_tree (TYPE_VALUES (expr), ctx, ht);
14012 fold_checksum_tree (TYPE_SIZE (expr), ctx, ht);
14013 fold_checksum_tree (TYPE_SIZE_UNIT (expr), ctx, ht);
14014 fold_checksum_tree (TYPE_ATTRIBUTES (expr), ctx, ht);
14015 fold_checksum_tree (TYPE_NAME (expr), ctx, ht);
14016 if (INTEGRAL_TYPE_P (expr)
14017 || SCALAR_FLOAT_TYPE_P (expr))
14019 fold_checksum_tree (TYPE_MIN_VALUE (expr), ctx, ht);
14020 fold_checksum_tree (TYPE_MAX_VALUE (expr), ctx, ht);
14022 fold_checksum_tree (TYPE_MAIN_VARIANT (expr), ctx, ht);
14023 if (RECORD_OR_UNION_TYPE_P (expr))
14024 fold_checksum_tree (TYPE_BINFO (expr), ctx, ht);
14025 fold_checksum_tree (TYPE_CONTEXT (expr), ctx, ht);
14026 break;
14027 default:
14028 break;
14032 /* Helper function for outputting the checksum of a tree T. When
14033 debugging with gdb, you can "define mynext" to be "next" followed
14034 by "call debug_fold_checksum (op0)", then just trace down till the
14035 outputs differ. */
14037 DEBUG_FUNCTION void
14038 debug_fold_checksum (const_tree t)
14040 int i;
14041 unsigned char checksum[16];
14042 struct md5_ctx ctx;
14043 hash_table<nofree_ptr_hash<const tree_node> > ht (32);
14045 md5_init_ctx (&ctx);
14046 fold_checksum_tree (t, &ctx, &ht);
14047 md5_finish_ctx (&ctx, checksum);
14048 ht.empty ();
14050 for (i = 0; i < 16; i++)
14051 fprintf (stderr, "%d ", checksum[i]);
14053 fprintf (stderr, "\n");
14056 #endif
14058 /* Fold a unary tree expression with code CODE of type TYPE with an
14059 operand OP0. LOC is the location of the resulting expression.
14060 Return a folded expression if successful. Otherwise, return a tree
14061 expression with code CODE of type TYPE with an operand OP0. */
14063 tree
14064 fold_build1_loc (location_t loc,
14065 enum tree_code code, tree type, tree op0 MEM_STAT_DECL)
14067 tree tem;
14068 #ifdef ENABLE_FOLD_CHECKING
14069 unsigned char checksum_before[16], checksum_after[16];
14070 struct md5_ctx ctx;
14071 hash_table<nofree_ptr_hash<const tree_node> > ht (32);
14073 md5_init_ctx (&ctx);
14074 fold_checksum_tree (op0, &ctx, &ht);
14075 md5_finish_ctx (&ctx, checksum_before);
14076 ht.empty ();
14077 #endif
14079 tem = fold_unary_loc (loc, code, type, op0);
14080 if (!tem)
14081 tem = build1_loc (loc, code, type, op0 PASS_MEM_STAT);
14083 #ifdef ENABLE_FOLD_CHECKING
14084 md5_init_ctx (&ctx);
14085 fold_checksum_tree (op0, &ctx, &ht);
14086 md5_finish_ctx (&ctx, checksum_after);
14088 if (memcmp (checksum_before, checksum_after, 16))
14089 fold_check_failed (op0, tem);
14090 #endif
14091 return tem;
14094 /* Fold a binary tree expression with code CODE of type TYPE with
14095 operands OP0 and OP1. LOC is the location of the resulting
14096 expression. Return a folded expression if successful. Otherwise,
14097 return a tree expression with code CODE of type TYPE with operands
14098 OP0 and OP1. */
14100 tree
14101 fold_build2_loc (location_t loc,
14102 enum tree_code code, tree type, tree op0, tree op1
14103 MEM_STAT_DECL)
14105 tree tem;
14106 #ifdef ENABLE_FOLD_CHECKING
14107 unsigned char checksum_before_op0[16],
14108 checksum_before_op1[16],
14109 checksum_after_op0[16],
14110 checksum_after_op1[16];
14111 struct md5_ctx ctx;
14112 hash_table<nofree_ptr_hash<const tree_node> > ht (32);
14114 md5_init_ctx (&ctx);
14115 fold_checksum_tree (op0, &ctx, &ht);
14116 md5_finish_ctx (&ctx, checksum_before_op0);
14117 ht.empty ();
14119 md5_init_ctx (&ctx);
14120 fold_checksum_tree (op1, &ctx, &ht);
14121 md5_finish_ctx (&ctx, checksum_before_op1);
14122 ht.empty ();
14123 #endif
14125 tem = fold_binary_loc (loc, code, type, op0, op1);
14126 if (!tem)
14127 tem = build2_loc (loc, code, type, op0, op1 PASS_MEM_STAT);
14129 #ifdef ENABLE_FOLD_CHECKING
14130 md5_init_ctx (&ctx);
14131 fold_checksum_tree (op0, &ctx, &ht);
14132 md5_finish_ctx (&ctx, checksum_after_op0);
14133 ht.empty ();
14135 if (memcmp (checksum_before_op0, checksum_after_op0, 16))
14136 fold_check_failed (op0, tem);
14138 md5_init_ctx (&ctx);
14139 fold_checksum_tree (op1, &ctx, &ht);
14140 md5_finish_ctx (&ctx, checksum_after_op1);
14142 if (memcmp (checksum_before_op1, checksum_after_op1, 16))
14143 fold_check_failed (op1, tem);
14144 #endif
14145 return tem;
14148 /* Fold a ternary tree expression with code CODE of type TYPE with
14149 operands OP0, OP1, and OP2. Return a folded expression if
14150 successful. Otherwise, return a tree expression with code CODE of
14151 type TYPE with operands OP0, OP1, and OP2. */
14153 tree
14154 fold_build3_loc (location_t loc, enum tree_code code, tree type,
14155 tree op0, tree op1, tree op2 MEM_STAT_DECL)
14157 tree tem;
14158 #ifdef ENABLE_FOLD_CHECKING
14159 unsigned char checksum_before_op0[16],
14160 checksum_before_op1[16],
14161 checksum_before_op2[16],
14162 checksum_after_op0[16],
14163 checksum_after_op1[16],
14164 checksum_after_op2[16];
14165 struct md5_ctx ctx;
14166 hash_table<nofree_ptr_hash<const tree_node> > ht (32);
14168 md5_init_ctx (&ctx);
14169 fold_checksum_tree (op0, &ctx, &ht);
14170 md5_finish_ctx (&ctx, checksum_before_op0);
14171 ht.empty ();
14173 md5_init_ctx (&ctx);
14174 fold_checksum_tree (op1, &ctx, &ht);
14175 md5_finish_ctx (&ctx, checksum_before_op1);
14176 ht.empty ();
14178 md5_init_ctx (&ctx);
14179 fold_checksum_tree (op2, &ctx, &ht);
14180 md5_finish_ctx (&ctx, checksum_before_op2);
14181 ht.empty ();
14182 #endif
14184 gcc_assert (TREE_CODE_CLASS (code) != tcc_vl_exp);
14185 tem = fold_ternary_loc (loc, code, type, op0, op1, op2);
14186 if (!tem)
14187 tem = build3_loc (loc, code, type, op0, op1, op2 PASS_MEM_STAT);
14189 #ifdef ENABLE_FOLD_CHECKING
14190 md5_init_ctx (&ctx);
14191 fold_checksum_tree (op0, &ctx, &ht);
14192 md5_finish_ctx (&ctx, checksum_after_op0);
14193 ht.empty ();
14195 if (memcmp (checksum_before_op0, checksum_after_op0, 16))
14196 fold_check_failed (op0, tem);
14198 md5_init_ctx (&ctx);
14199 fold_checksum_tree (op1, &ctx, &ht);
14200 md5_finish_ctx (&ctx, checksum_after_op1);
14201 ht.empty ();
14203 if (memcmp (checksum_before_op1, checksum_after_op1, 16))
14204 fold_check_failed (op1, tem);
14206 md5_init_ctx (&ctx);
14207 fold_checksum_tree (op2, &ctx, &ht);
14208 md5_finish_ctx (&ctx, checksum_after_op2);
14210 if (memcmp (checksum_before_op2, checksum_after_op2, 16))
14211 fold_check_failed (op2, tem);
14212 #endif
14213 return tem;
14216 /* Fold a CALL_EXPR expression of type TYPE with operands FN and NARGS
14217 arguments in ARGARRAY, and a null static chain.
14218 Return a folded expression if successful. Otherwise, return a CALL_EXPR
14219 of type TYPE from the given operands as constructed by build_call_array. */
14221 tree
14222 fold_build_call_array_loc (location_t loc, tree type, tree fn,
14223 int nargs, tree *argarray)
14225 tree tem;
14226 #ifdef ENABLE_FOLD_CHECKING
14227 unsigned char checksum_before_fn[16],
14228 checksum_before_arglist[16],
14229 checksum_after_fn[16],
14230 checksum_after_arglist[16];
14231 struct md5_ctx ctx;
14232 hash_table<nofree_ptr_hash<const tree_node> > ht (32);
14233 int i;
14235 md5_init_ctx (&ctx);
14236 fold_checksum_tree (fn, &ctx, &ht);
14237 md5_finish_ctx (&ctx, checksum_before_fn);
14238 ht.empty ();
14240 md5_init_ctx (&ctx);
14241 for (i = 0; i < nargs; i++)
14242 fold_checksum_tree (argarray[i], &ctx, &ht);
14243 md5_finish_ctx (&ctx, checksum_before_arglist);
14244 ht.empty ();
14245 #endif
14247 tem = fold_builtin_call_array (loc, type, fn, nargs, argarray);
14248 if (!tem)
14249 tem = build_call_array_loc (loc, type, fn, nargs, argarray);
14251 #ifdef ENABLE_FOLD_CHECKING
14252 md5_init_ctx (&ctx);
14253 fold_checksum_tree (fn, &ctx, &ht);
14254 md5_finish_ctx (&ctx, checksum_after_fn);
14255 ht.empty ();
14257 if (memcmp (checksum_before_fn, checksum_after_fn, 16))
14258 fold_check_failed (fn, tem);
14260 md5_init_ctx (&ctx);
14261 for (i = 0; i < nargs; i++)
14262 fold_checksum_tree (argarray[i], &ctx, &ht);
14263 md5_finish_ctx (&ctx, checksum_after_arglist);
14265 if (memcmp (checksum_before_arglist, checksum_after_arglist, 16))
14266 fold_check_failed (NULL_TREE, tem);
14267 #endif
14268 return tem;
14271 /* Perform constant folding and related simplification of initializer
14272 expression EXPR. These behave identically to "fold_buildN" but ignore
14273 potential run-time traps and exceptions that fold must preserve. */
14275 #define START_FOLD_INIT \
14276 int saved_signaling_nans = flag_signaling_nans;\
14277 int saved_trapping_math = flag_trapping_math;\
14278 int saved_rounding_math = flag_rounding_math;\
14279 int saved_trapv = flag_trapv;\
14280 int saved_folding_initializer = folding_initializer;\
14281 flag_signaling_nans = 0;\
14282 flag_trapping_math = 0;\
14283 flag_rounding_math = 0;\
14284 flag_trapv = 0;\
14285 folding_initializer = 1;
14287 #define END_FOLD_INIT \
14288 flag_signaling_nans = saved_signaling_nans;\
14289 flag_trapping_math = saved_trapping_math;\
14290 flag_rounding_math = saved_rounding_math;\
14291 flag_trapv = saved_trapv;\
14292 folding_initializer = saved_folding_initializer;
14294 tree
14295 fold_init (tree expr)
14297 tree result;
14298 START_FOLD_INIT;
14300 result = fold (expr);
14302 END_FOLD_INIT;
14303 return result;
14306 tree
14307 fold_build1_initializer_loc (location_t loc, enum tree_code code,
14308 tree type, tree op)
14310 tree result;
14311 START_FOLD_INIT;
14313 result = fold_build1_loc (loc, code, type, op);
14315 END_FOLD_INIT;
14316 return result;
14319 tree
14320 fold_build2_initializer_loc (location_t loc, enum tree_code code,
14321 tree type, tree op0, tree op1)
14323 tree result;
14324 START_FOLD_INIT;
14326 result = fold_build2_loc (loc, code, type, op0, op1);
14328 END_FOLD_INIT;
14329 return result;
14332 tree
14333 fold_build_call_array_initializer_loc (location_t loc, tree type, tree fn,
14334 int nargs, tree *argarray)
14336 tree result;
14337 START_FOLD_INIT;
14339 result = fold_build_call_array_loc (loc, type, fn, nargs, argarray);
14341 END_FOLD_INIT;
14342 return result;
14345 tree
14346 fold_binary_initializer_loc (location_t loc, tree_code code, tree type,
14347 tree lhs, tree rhs)
14349 tree result;
14350 START_FOLD_INIT;
14352 result = fold_binary_loc (loc, code, type, lhs, rhs);
14354 END_FOLD_INIT;
14355 return result;
14358 #undef START_FOLD_INIT
14359 #undef END_FOLD_INIT
14361 /* Determine if first argument is a multiple of second argument. Return
14362 false if it is not, or we cannot easily determined it to be.
14364 An example of the sort of thing we care about (at this point; this routine
14365 could surely be made more general, and expanded to do what the *_DIV_EXPR's
14366 fold cases do now) is discovering that
14368 SAVE_EXPR (I) * SAVE_EXPR (J * 8)
14370 is a multiple of
14372 SAVE_EXPR (J * 8)
14374 when we know that the two SAVE_EXPR (J * 8) nodes are the same node.
14376 This code also handles discovering that
14378 SAVE_EXPR (I) * SAVE_EXPR (J * 8)
14380 is a multiple of 8 so we don't have to worry about dealing with a
14381 possible remainder.
14383 Note that we *look* inside a SAVE_EXPR only to determine how it was
14384 calculated; it is not safe for fold to do much of anything else with the
14385 internals of a SAVE_EXPR, since it cannot know when it will be evaluated
14386 at run time. For example, the latter example above *cannot* be implemented
14387 as SAVE_EXPR (I) * J or any variant thereof, since the value of J at
14388 evaluation time of the original SAVE_EXPR is not necessarily the same at
14389 the time the new expression is evaluated. The only optimization of this
14390 sort that would be valid is changing
14392 SAVE_EXPR (I) * SAVE_EXPR (SAVE_EXPR (J) * 8)
14394 divided by 8 to
14396 SAVE_EXPR (I) * SAVE_EXPR (J)
14398 (where the same SAVE_EXPR (J) is used in the original and the
14399 transformed version).
14401 NOWRAP specifies whether all outer operations in TYPE should
14402 be considered not wrapping. Any type conversion within TOP acts
14403 as a barrier and we will fall back to NOWRAP being false.
14404 NOWRAP is mostly used to treat expressions in TYPE_SIZE and friends
14405 as not wrapping even though they are generally using unsigned arithmetic. */
14407 bool
14408 multiple_of_p (tree type, const_tree top, const_tree bottom, bool nowrap)
14410 gimple *stmt;
14411 tree op1, op2;
14413 if (operand_equal_p (top, bottom, 0))
14414 return true;
14416 if (TREE_CODE (type) != INTEGER_TYPE)
14417 return false;
14419 switch (TREE_CODE (top))
14421 case BIT_AND_EXPR:
14422 /* Bitwise and provides a power of two multiple. If the mask is
14423 a multiple of BOTTOM then TOP is a multiple of BOTTOM. */
14424 if (!integer_pow2p (bottom))
14425 return false;
14426 return (multiple_of_p (type, TREE_OPERAND (top, 1), bottom, nowrap)
14427 || multiple_of_p (type, TREE_OPERAND (top, 0), bottom, nowrap));
14429 case MULT_EXPR:
14430 /* If the multiplication can wrap we cannot recurse further unless
14431 the bottom is a power of two which is where wrapping does not
14432 matter. */
14433 if (!nowrap
14434 && !TYPE_OVERFLOW_UNDEFINED (type)
14435 && !integer_pow2p (bottom))
14436 return false;
14437 if (TREE_CODE (bottom) == INTEGER_CST)
14439 op1 = TREE_OPERAND (top, 0);
14440 op2 = TREE_OPERAND (top, 1);
14441 if (TREE_CODE (op1) == INTEGER_CST)
14442 std::swap (op1, op2);
14443 if (TREE_CODE (op2) == INTEGER_CST)
14445 if (multiple_of_p (type, op2, bottom, nowrap))
14446 return true;
14447 /* Handle multiple_of_p ((x * 2 + 2) * 4, 8). */
14448 if (multiple_of_p (type, bottom, op2, nowrap))
14450 widest_int w = wi::sdiv_trunc (wi::to_widest (bottom),
14451 wi::to_widest (op2));
14452 if (wi::fits_to_tree_p (w, TREE_TYPE (bottom)))
14454 op2 = wide_int_to_tree (TREE_TYPE (bottom), w);
14455 return multiple_of_p (type, op1, op2, nowrap);
14458 return multiple_of_p (type, op1, bottom, nowrap);
14461 return (multiple_of_p (type, TREE_OPERAND (top, 1), bottom, nowrap)
14462 || multiple_of_p (type, TREE_OPERAND (top, 0), bottom, nowrap));
14464 case LSHIFT_EXPR:
14465 /* Handle X << CST as X * (1 << CST) and only process the constant. */
14466 if (TREE_CODE (TREE_OPERAND (top, 1)) == INTEGER_CST)
14468 op1 = TREE_OPERAND (top, 1);
14469 if (wi::to_widest (op1) < TYPE_PRECISION (type))
14471 wide_int mul_op
14472 = wi::one (TYPE_PRECISION (type)) << wi::to_wide (op1);
14473 return multiple_of_p (type,
14474 wide_int_to_tree (type, mul_op), bottom,
14475 nowrap);
14478 return false;
14480 case MINUS_EXPR:
14481 case PLUS_EXPR:
14482 /* If the addition or subtraction can wrap we cannot recurse further
14483 unless bottom is a power of two which is where wrapping does not
14484 matter. */
14485 if (!nowrap
14486 && !TYPE_OVERFLOW_UNDEFINED (type)
14487 && !integer_pow2p (bottom))
14488 return false;
14490 /* Handle cases like op0 + 0xfffffffd as op0 - 3 if the expression has
14491 unsigned type. For example, (X / 3) + 0xfffffffd is multiple of 3,
14492 but 0xfffffffd is not. */
14493 op1 = TREE_OPERAND (top, 1);
14494 if (TREE_CODE (top) == PLUS_EXPR
14495 && nowrap
14496 && TYPE_UNSIGNED (type)
14497 && TREE_CODE (op1) == INTEGER_CST && tree_int_cst_sign_bit (op1))
14498 op1 = fold_build1 (NEGATE_EXPR, type, op1);
14500 /* It is impossible to prove if op0 +- op1 is multiple of bottom
14501 precisely, so be conservative here checking if both op0 and op1
14502 are multiple of bottom. Note we check the second operand first
14503 since it's usually simpler. */
14504 return (multiple_of_p (type, op1, bottom, nowrap)
14505 && multiple_of_p (type, TREE_OPERAND (top, 0), bottom, nowrap));
14507 CASE_CONVERT:
14508 /* Can't handle conversions from non-integral or wider integral type. */
14509 if ((TREE_CODE (TREE_TYPE (TREE_OPERAND (top, 0))) != INTEGER_TYPE)
14510 || (TYPE_PRECISION (type)
14511 < TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (top, 0)))))
14512 return false;
14513 /* NOWRAP only extends to operations in the outermost type so
14514 make sure to strip it off here. */
14515 return multiple_of_p (TREE_TYPE (TREE_OPERAND (top, 0)),
14516 TREE_OPERAND (top, 0), bottom, false);
14518 case SAVE_EXPR:
14519 return multiple_of_p (type, TREE_OPERAND (top, 0), bottom, nowrap);
14521 case COND_EXPR:
14522 return (multiple_of_p (type, TREE_OPERAND (top, 1), bottom, nowrap)
14523 && multiple_of_p (type, TREE_OPERAND (top, 2), bottom, nowrap));
14525 case INTEGER_CST:
14526 if (TREE_CODE (bottom) != INTEGER_CST || integer_zerop (bottom))
14527 return false;
14528 return wi::multiple_of_p (wi::to_widest (top), wi::to_widest (bottom),
14529 SIGNED);
14531 case SSA_NAME:
14532 if (TREE_CODE (bottom) == INTEGER_CST
14533 && (stmt = SSA_NAME_DEF_STMT (top)) != NULL
14534 && gimple_code (stmt) == GIMPLE_ASSIGN)
14536 enum tree_code code = gimple_assign_rhs_code (stmt);
14538 /* Check for special cases to see if top is defined as multiple
14539 of bottom:
14541 top = (X & ~(bottom - 1) ; bottom is power of 2
14545 Y = X % bottom
14546 top = X - Y. */
14547 if (code == BIT_AND_EXPR
14548 && (op2 = gimple_assign_rhs2 (stmt)) != NULL_TREE
14549 && TREE_CODE (op2) == INTEGER_CST
14550 && integer_pow2p (bottom)
14551 && wi::multiple_of_p (wi::to_widest (op2),
14552 wi::to_widest (bottom), SIGNED))
14553 return true;
14555 op1 = gimple_assign_rhs1 (stmt);
14556 if (code == MINUS_EXPR
14557 && (op2 = gimple_assign_rhs2 (stmt)) != NULL_TREE
14558 && TREE_CODE (op2) == SSA_NAME
14559 && (stmt = SSA_NAME_DEF_STMT (op2)) != NULL
14560 && gimple_code (stmt) == GIMPLE_ASSIGN
14561 && (code = gimple_assign_rhs_code (stmt)) == TRUNC_MOD_EXPR
14562 && operand_equal_p (op1, gimple_assign_rhs1 (stmt), 0)
14563 && operand_equal_p (bottom, gimple_assign_rhs2 (stmt), 0))
14564 return true;
14567 /* fall through */
14569 default:
14570 if (POLY_INT_CST_P (top) && poly_int_tree_p (bottom))
14571 return multiple_p (wi::to_poly_widest (top),
14572 wi::to_poly_widest (bottom));
14574 return false;
14578 /* Return true if expression X cannot be (or contain) a NaN or infinity.
14579 This function returns true for integer expressions, and returns
14580 false if uncertain. */
14582 bool
14583 tree_expr_finite_p (const_tree x)
14585 machine_mode mode = element_mode (x);
14586 if (!HONOR_NANS (mode) && !HONOR_INFINITIES (mode))
14587 return true;
14588 switch (TREE_CODE (x))
14590 case REAL_CST:
14591 return real_isfinite (TREE_REAL_CST_PTR (x));
14592 case COMPLEX_CST:
14593 return tree_expr_finite_p (TREE_REALPART (x))
14594 && tree_expr_finite_p (TREE_IMAGPART (x));
14595 case FLOAT_EXPR:
14596 return true;
14597 case ABS_EXPR:
14598 case CONVERT_EXPR:
14599 case NON_LVALUE_EXPR:
14600 case NEGATE_EXPR:
14601 case SAVE_EXPR:
14602 return tree_expr_finite_p (TREE_OPERAND (x, 0));
14603 case MIN_EXPR:
14604 case MAX_EXPR:
14605 return tree_expr_finite_p (TREE_OPERAND (x, 0))
14606 && tree_expr_finite_p (TREE_OPERAND (x, 1));
14607 case COND_EXPR:
14608 return tree_expr_finite_p (TREE_OPERAND (x, 1))
14609 && tree_expr_finite_p (TREE_OPERAND (x, 2));
14610 case CALL_EXPR:
14611 switch (get_call_combined_fn (x))
14613 CASE_CFN_FABS:
14614 CASE_CFN_FABS_FN:
14615 return tree_expr_finite_p (CALL_EXPR_ARG (x, 0));
14616 CASE_CFN_FMAX:
14617 CASE_CFN_FMAX_FN:
14618 CASE_CFN_FMIN:
14619 CASE_CFN_FMIN_FN:
14620 return tree_expr_finite_p (CALL_EXPR_ARG (x, 0))
14621 && tree_expr_finite_p (CALL_EXPR_ARG (x, 1));
14622 default:
14623 return false;
14626 default:
14627 return false;
14631 /* Return true if expression X evaluates to an infinity.
14632 This function returns false for integer expressions. */
14634 bool
14635 tree_expr_infinite_p (const_tree x)
14637 if (!HONOR_INFINITIES (x))
14638 return false;
14639 switch (TREE_CODE (x))
14641 case REAL_CST:
14642 return real_isinf (TREE_REAL_CST_PTR (x));
14643 case ABS_EXPR:
14644 case NEGATE_EXPR:
14645 case NON_LVALUE_EXPR:
14646 case SAVE_EXPR:
14647 return tree_expr_infinite_p (TREE_OPERAND (x, 0));
14648 case COND_EXPR:
14649 return tree_expr_infinite_p (TREE_OPERAND (x, 1))
14650 && tree_expr_infinite_p (TREE_OPERAND (x, 2));
14651 default:
14652 return false;
14656 /* Return true if expression X could evaluate to an infinity.
14657 This function returns false for integer expressions, and returns
14658 true if uncertain. */
14660 bool
14661 tree_expr_maybe_infinite_p (const_tree x)
14663 if (!HONOR_INFINITIES (x))
14664 return false;
14665 switch (TREE_CODE (x))
14667 case REAL_CST:
14668 return real_isinf (TREE_REAL_CST_PTR (x));
14669 case FLOAT_EXPR:
14670 return false;
14671 case ABS_EXPR:
14672 case NEGATE_EXPR:
14673 return tree_expr_maybe_infinite_p (TREE_OPERAND (x, 0));
14674 case COND_EXPR:
14675 return tree_expr_maybe_infinite_p (TREE_OPERAND (x, 1))
14676 || tree_expr_maybe_infinite_p (TREE_OPERAND (x, 2));
14677 default:
14678 return true;
14682 /* Return true if expression X evaluates to a signaling NaN.
14683 This function returns false for integer expressions. */
14685 bool
14686 tree_expr_signaling_nan_p (const_tree x)
14688 if (!HONOR_SNANS (x))
14689 return false;
14690 switch (TREE_CODE (x))
14692 case REAL_CST:
14693 return real_issignaling_nan (TREE_REAL_CST_PTR (x));
14694 case NON_LVALUE_EXPR:
14695 case SAVE_EXPR:
14696 return tree_expr_signaling_nan_p (TREE_OPERAND (x, 0));
14697 case COND_EXPR:
14698 return tree_expr_signaling_nan_p (TREE_OPERAND (x, 1))
14699 && tree_expr_signaling_nan_p (TREE_OPERAND (x, 2));
14700 default:
14701 return false;
14705 /* Return true if expression X could evaluate to a signaling NaN.
14706 This function returns false for integer expressions, and returns
14707 true if uncertain. */
14709 bool
14710 tree_expr_maybe_signaling_nan_p (const_tree x)
14712 if (!HONOR_SNANS (x))
14713 return false;
14714 switch (TREE_CODE (x))
14716 case REAL_CST:
14717 return real_issignaling_nan (TREE_REAL_CST_PTR (x));
14718 case FLOAT_EXPR:
14719 return false;
14720 case ABS_EXPR:
14721 case CONVERT_EXPR:
14722 case NEGATE_EXPR:
14723 case NON_LVALUE_EXPR:
14724 case SAVE_EXPR:
14725 return tree_expr_maybe_signaling_nan_p (TREE_OPERAND (x, 0));
14726 case MIN_EXPR:
14727 case MAX_EXPR:
14728 return tree_expr_maybe_signaling_nan_p (TREE_OPERAND (x, 0))
14729 || tree_expr_maybe_signaling_nan_p (TREE_OPERAND (x, 1));
14730 case COND_EXPR:
14731 return tree_expr_maybe_signaling_nan_p (TREE_OPERAND (x, 1))
14732 || tree_expr_maybe_signaling_nan_p (TREE_OPERAND (x, 2));
14733 case CALL_EXPR:
14734 switch (get_call_combined_fn (x))
14736 CASE_CFN_FABS:
14737 CASE_CFN_FABS_FN:
14738 return tree_expr_maybe_signaling_nan_p (CALL_EXPR_ARG (x, 0));
14739 CASE_CFN_FMAX:
14740 CASE_CFN_FMAX_FN:
14741 CASE_CFN_FMIN:
14742 CASE_CFN_FMIN_FN:
14743 return tree_expr_maybe_signaling_nan_p (CALL_EXPR_ARG (x, 0))
14744 || tree_expr_maybe_signaling_nan_p (CALL_EXPR_ARG (x, 1));
14745 default:
14746 return true;
14748 default:
14749 return true;
14753 /* Return true if expression X evaluates to a NaN.
14754 This function returns false for integer expressions. */
14756 bool
14757 tree_expr_nan_p (const_tree x)
14759 if (!HONOR_NANS (x))
14760 return false;
14761 switch (TREE_CODE (x))
14763 case REAL_CST:
14764 return real_isnan (TREE_REAL_CST_PTR (x));
14765 case NON_LVALUE_EXPR:
14766 case SAVE_EXPR:
14767 return tree_expr_nan_p (TREE_OPERAND (x, 0));
14768 case COND_EXPR:
14769 return tree_expr_nan_p (TREE_OPERAND (x, 1))
14770 && tree_expr_nan_p (TREE_OPERAND (x, 2));
14771 default:
14772 return false;
14776 /* Return true if expression X could evaluate to a NaN.
14777 This function returns false for integer expressions, and returns
14778 true if uncertain. */
14780 bool
14781 tree_expr_maybe_nan_p (const_tree x)
14783 if (!HONOR_NANS (x))
14784 return false;
14785 switch (TREE_CODE (x))
14787 case REAL_CST:
14788 return real_isnan (TREE_REAL_CST_PTR (x));
14789 case FLOAT_EXPR:
14790 return false;
14791 case PLUS_EXPR:
14792 case MINUS_EXPR:
14793 case MULT_EXPR:
14794 return !tree_expr_finite_p (TREE_OPERAND (x, 0))
14795 || !tree_expr_finite_p (TREE_OPERAND (x, 1));
14796 case ABS_EXPR:
14797 case CONVERT_EXPR:
14798 case NEGATE_EXPR:
14799 case NON_LVALUE_EXPR:
14800 case SAVE_EXPR:
14801 return tree_expr_maybe_nan_p (TREE_OPERAND (x, 0));
14802 case MIN_EXPR:
14803 case MAX_EXPR:
14804 return tree_expr_maybe_nan_p (TREE_OPERAND (x, 0))
14805 || tree_expr_maybe_nan_p (TREE_OPERAND (x, 1));
14806 case COND_EXPR:
14807 return tree_expr_maybe_nan_p (TREE_OPERAND (x, 1))
14808 || tree_expr_maybe_nan_p (TREE_OPERAND (x, 2));
14809 case CALL_EXPR:
14810 switch (get_call_combined_fn (x))
14812 CASE_CFN_FABS:
14813 CASE_CFN_FABS_FN:
14814 return tree_expr_maybe_nan_p (CALL_EXPR_ARG (x, 0));
14815 CASE_CFN_FMAX:
14816 CASE_CFN_FMAX_FN:
14817 CASE_CFN_FMIN:
14818 CASE_CFN_FMIN_FN:
14819 return tree_expr_maybe_nan_p (CALL_EXPR_ARG (x, 0))
14820 || tree_expr_maybe_nan_p (CALL_EXPR_ARG (x, 1));
14821 default:
14822 return true;
14824 default:
14825 return true;
14829 /* Return true if expression X could evaluate to -0.0.
14830 This function returns true if uncertain. */
14832 bool
14833 tree_expr_maybe_real_minus_zero_p (const_tree x)
14835 if (!HONOR_SIGNED_ZEROS (x))
14836 return false;
14837 switch (TREE_CODE (x))
14839 case REAL_CST:
14840 return REAL_VALUE_MINUS_ZERO (TREE_REAL_CST (x));
14841 case INTEGER_CST:
14842 case FLOAT_EXPR:
14843 case ABS_EXPR:
14844 return false;
14845 case NON_LVALUE_EXPR:
14846 case SAVE_EXPR:
14847 return tree_expr_maybe_real_minus_zero_p (TREE_OPERAND (x, 0));
14848 case COND_EXPR:
14849 return tree_expr_maybe_real_minus_zero_p (TREE_OPERAND (x, 1))
14850 || tree_expr_maybe_real_minus_zero_p (TREE_OPERAND (x, 2));
14851 case CALL_EXPR:
14852 switch (get_call_combined_fn (x))
14854 CASE_CFN_FABS:
14855 CASE_CFN_FABS_FN:
14856 return false;
14857 default:
14858 break;
14860 default:
14861 break;
14863 /* Ideally !(tree_expr_nonzero_p (X) || tree_expr_nonnegative_p (X))
14864 * but currently those predicates require tree and not const_tree. */
14865 return true;
14868 #define tree_expr_nonnegative_warnv_p(X, Y) \
14869 _Pragma ("GCC error \"Use RECURSE for recursive calls\"") 0
14871 #define RECURSE(X) \
14872 ((tree_expr_nonnegative_warnv_p) (X, strict_overflow_p, depth + 1))
14874 /* Return true if CODE or TYPE is known to be non-negative. */
14876 static bool
14877 tree_simple_nonnegative_warnv_p (enum tree_code code, tree type)
14879 if (!VECTOR_TYPE_P (type)
14880 && (TYPE_PRECISION (type) != 1 || TYPE_UNSIGNED (type))
14881 && truth_value_p (code))
14882 /* Truth values evaluate to 0 or 1, which is nonnegative unless we
14883 have a signed:1 type (where the value is -1 and 0). */
14884 return true;
14885 return false;
14888 /* Return true if (CODE OP0) is known to be non-negative. If the return
14889 value is based on the assumption that signed overflow is undefined,
14890 set *STRICT_OVERFLOW_P to true; otherwise, don't change
14891 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
14893 bool
14894 tree_unary_nonnegative_warnv_p (enum tree_code code, tree type, tree op0,
14895 bool *strict_overflow_p, int depth)
14897 if (TYPE_UNSIGNED (type))
14898 return true;
14900 switch (code)
14902 case ABS_EXPR:
14903 /* We can't return 1 if flag_wrapv is set because
14904 ABS_EXPR<INT_MIN> = INT_MIN. */
14905 if (!ANY_INTEGRAL_TYPE_P (type))
14906 return true;
14907 if (TYPE_OVERFLOW_UNDEFINED (type))
14909 *strict_overflow_p = true;
14910 return true;
14912 break;
14914 case NON_LVALUE_EXPR:
14915 case FLOAT_EXPR:
14916 case FIX_TRUNC_EXPR:
14917 return RECURSE (op0);
14919 CASE_CONVERT:
14921 tree inner_type = TREE_TYPE (op0);
14922 tree outer_type = type;
14924 if (SCALAR_FLOAT_TYPE_P (outer_type))
14926 if (SCALAR_FLOAT_TYPE_P (inner_type))
14927 return RECURSE (op0);
14928 if (INTEGRAL_TYPE_P (inner_type))
14930 if (TYPE_UNSIGNED (inner_type))
14931 return true;
14932 return RECURSE (op0);
14935 else if (INTEGRAL_TYPE_P (outer_type))
14937 if (SCALAR_FLOAT_TYPE_P (inner_type))
14938 return RECURSE (op0);
14939 if (INTEGRAL_TYPE_P (inner_type))
14940 return TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type)
14941 && TYPE_UNSIGNED (inner_type);
14944 break;
14946 default:
14947 return tree_simple_nonnegative_warnv_p (code, type);
14950 /* We don't know sign of `t', so be conservative and return false. */
14951 return false;
14954 /* Return true if (CODE OP0 OP1) is known to be non-negative. If the return
14955 value is based on the assumption that signed overflow is undefined,
14956 set *STRICT_OVERFLOW_P to true; otherwise, don't change
14957 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
14959 bool
14960 tree_binary_nonnegative_warnv_p (enum tree_code code, tree type, tree op0,
14961 tree op1, bool *strict_overflow_p,
14962 int depth)
14964 if (TYPE_UNSIGNED (type))
14965 return true;
14967 switch (code)
14969 case POINTER_PLUS_EXPR:
14970 case PLUS_EXPR:
14971 if (FLOAT_TYPE_P (type))
14972 return RECURSE (op0) && RECURSE (op1);
14974 /* zero_extend(x) + zero_extend(y) is non-negative if x and y are
14975 both unsigned and at least 2 bits shorter than the result. */
14976 if (TREE_CODE (type) == INTEGER_TYPE
14977 && TREE_CODE (op0) == NOP_EXPR
14978 && TREE_CODE (op1) == NOP_EXPR)
14980 tree inner1 = TREE_TYPE (TREE_OPERAND (op0, 0));
14981 tree inner2 = TREE_TYPE (TREE_OPERAND (op1, 0));
14982 if (TREE_CODE (inner1) == INTEGER_TYPE && TYPE_UNSIGNED (inner1)
14983 && TREE_CODE (inner2) == INTEGER_TYPE && TYPE_UNSIGNED (inner2))
14985 unsigned int prec = MAX (TYPE_PRECISION (inner1),
14986 TYPE_PRECISION (inner2)) + 1;
14987 return prec < TYPE_PRECISION (type);
14990 break;
14992 case MULT_EXPR:
14993 if (FLOAT_TYPE_P (type) || TYPE_OVERFLOW_UNDEFINED (type))
14995 /* x * x is always non-negative for floating point x
14996 or without overflow. */
14997 if (operand_equal_p (op0, op1, 0)
14998 || (RECURSE (op0) && RECURSE (op1)))
15000 if (ANY_INTEGRAL_TYPE_P (type)
15001 && TYPE_OVERFLOW_UNDEFINED (type))
15002 *strict_overflow_p = true;
15003 return true;
15007 /* zero_extend(x) * zero_extend(y) is non-negative if x and y are
15008 both unsigned and their total bits is shorter than the result. */
15009 if (TREE_CODE (type) == INTEGER_TYPE
15010 && (TREE_CODE (op0) == NOP_EXPR || TREE_CODE (op0) == INTEGER_CST)
15011 && (TREE_CODE (op1) == NOP_EXPR || TREE_CODE (op1) == INTEGER_CST))
15013 tree inner0 = (TREE_CODE (op0) == NOP_EXPR)
15014 ? TREE_TYPE (TREE_OPERAND (op0, 0))
15015 : TREE_TYPE (op0);
15016 tree inner1 = (TREE_CODE (op1) == NOP_EXPR)
15017 ? TREE_TYPE (TREE_OPERAND (op1, 0))
15018 : TREE_TYPE (op1);
15020 bool unsigned0 = TYPE_UNSIGNED (inner0);
15021 bool unsigned1 = TYPE_UNSIGNED (inner1);
15023 if (TREE_CODE (op0) == INTEGER_CST)
15024 unsigned0 = unsigned0 || tree_int_cst_sgn (op0) >= 0;
15026 if (TREE_CODE (op1) == INTEGER_CST)
15027 unsigned1 = unsigned1 || tree_int_cst_sgn (op1) >= 0;
15029 if (TREE_CODE (inner0) == INTEGER_TYPE && unsigned0
15030 && TREE_CODE (inner1) == INTEGER_TYPE && unsigned1)
15032 unsigned int precision0 = (TREE_CODE (op0) == INTEGER_CST)
15033 ? tree_int_cst_min_precision (op0, UNSIGNED)
15034 : TYPE_PRECISION (inner0);
15036 unsigned int precision1 = (TREE_CODE (op1) == INTEGER_CST)
15037 ? tree_int_cst_min_precision (op1, UNSIGNED)
15038 : TYPE_PRECISION (inner1);
15040 return precision0 + precision1 < TYPE_PRECISION (type);
15043 return false;
15045 case BIT_AND_EXPR:
15046 return RECURSE (op0) || RECURSE (op1);
15048 case MAX_EXPR:
15049 /* Usually RECURSE (op0) || RECURSE (op1) but NaNs complicate
15050 things. */
15051 if (tree_expr_maybe_nan_p (op0) || tree_expr_maybe_nan_p (op1))
15052 return RECURSE (op0) && RECURSE (op1);
15053 return RECURSE (op0) || RECURSE (op1);
15055 case BIT_IOR_EXPR:
15056 case BIT_XOR_EXPR:
15057 case MIN_EXPR:
15058 case RDIV_EXPR:
15059 case TRUNC_DIV_EXPR:
15060 case CEIL_DIV_EXPR:
15061 case FLOOR_DIV_EXPR:
15062 case ROUND_DIV_EXPR:
15063 return RECURSE (op0) && RECURSE (op1);
15065 case TRUNC_MOD_EXPR:
15066 return RECURSE (op0);
15068 case FLOOR_MOD_EXPR:
15069 return RECURSE (op1);
15071 case CEIL_MOD_EXPR:
15072 case ROUND_MOD_EXPR:
15073 default:
15074 return tree_simple_nonnegative_warnv_p (code, type);
15077 /* We don't know sign of `t', so be conservative and return false. */
15078 return false;
15081 /* Return true if T is known to be non-negative. If the return
15082 value is based on the assumption that signed overflow is undefined,
15083 set *STRICT_OVERFLOW_P to true; otherwise, don't change
15084 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
15086 bool
15087 tree_single_nonnegative_warnv_p (tree t, bool *strict_overflow_p, int depth)
15089 if (TYPE_UNSIGNED (TREE_TYPE (t)))
15090 return true;
15092 switch (TREE_CODE (t))
15094 case INTEGER_CST:
15095 return tree_int_cst_sgn (t) >= 0;
15097 case REAL_CST:
15098 return ! REAL_VALUE_NEGATIVE (TREE_REAL_CST (t));
15100 case FIXED_CST:
15101 return ! FIXED_VALUE_NEGATIVE (TREE_FIXED_CST (t));
15103 case COND_EXPR:
15104 return RECURSE (TREE_OPERAND (t, 1)) && RECURSE (TREE_OPERAND (t, 2));
15106 case SSA_NAME:
15107 /* Limit the depth of recursion to avoid quadratic behavior.
15108 This is expected to catch almost all occurrences in practice.
15109 If this code misses important cases that unbounded recursion
15110 would not, passes that need this information could be revised
15111 to provide it through dataflow propagation. */
15112 return (!name_registered_for_update_p (t)
15113 && depth < param_max_ssa_name_query_depth
15114 && gimple_stmt_nonnegative_warnv_p (SSA_NAME_DEF_STMT (t),
15115 strict_overflow_p, depth));
15117 default:
15118 return tree_simple_nonnegative_warnv_p (TREE_CODE (t), TREE_TYPE (t));
15122 /* Return true if T is known to be non-negative. If the return
15123 value is based on the assumption that signed overflow is undefined,
15124 set *STRICT_OVERFLOW_P to true; otherwise, don't change
15125 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
15127 bool
15128 tree_call_nonnegative_warnv_p (tree type, combined_fn fn, tree arg0, tree arg1,
15129 bool *strict_overflow_p, int depth)
15131 switch (fn)
15133 CASE_CFN_ACOS:
15134 CASE_CFN_ACOS_FN:
15135 CASE_CFN_ACOSH:
15136 CASE_CFN_ACOSH_FN:
15137 CASE_CFN_CABS:
15138 CASE_CFN_CABS_FN:
15139 CASE_CFN_COSH:
15140 CASE_CFN_COSH_FN:
15141 CASE_CFN_ERFC:
15142 CASE_CFN_ERFC_FN:
15143 CASE_CFN_EXP:
15144 CASE_CFN_EXP_FN:
15145 CASE_CFN_EXP10:
15146 CASE_CFN_EXP2:
15147 CASE_CFN_EXP2_FN:
15148 CASE_CFN_FABS:
15149 CASE_CFN_FABS_FN:
15150 CASE_CFN_FDIM:
15151 CASE_CFN_FDIM_FN:
15152 CASE_CFN_HYPOT:
15153 CASE_CFN_HYPOT_FN:
15154 CASE_CFN_POW10:
15155 CASE_CFN_FFS:
15156 CASE_CFN_PARITY:
15157 CASE_CFN_POPCOUNT:
15158 CASE_CFN_CLZ:
15159 CASE_CFN_CLRSB:
15160 case CFN_BUILT_IN_BSWAP16:
15161 case CFN_BUILT_IN_BSWAP32:
15162 case CFN_BUILT_IN_BSWAP64:
15163 case CFN_BUILT_IN_BSWAP128:
15164 /* Always true. */
15165 return true;
15167 CASE_CFN_SQRT:
15168 CASE_CFN_SQRT_FN:
15169 /* sqrt(-0.0) is -0.0. */
15170 if (!HONOR_SIGNED_ZEROS (type))
15171 return true;
15172 return RECURSE (arg0);
15174 CASE_CFN_ASINH:
15175 CASE_CFN_ASINH_FN:
15176 CASE_CFN_ATAN:
15177 CASE_CFN_ATAN_FN:
15178 CASE_CFN_ATANH:
15179 CASE_CFN_ATANH_FN:
15180 CASE_CFN_CBRT:
15181 CASE_CFN_CBRT_FN:
15182 CASE_CFN_CEIL:
15183 CASE_CFN_CEIL_FN:
15184 CASE_CFN_ERF:
15185 CASE_CFN_ERF_FN:
15186 CASE_CFN_EXPM1:
15187 CASE_CFN_EXPM1_FN:
15188 CASE_CFN_FLOOR:
15189 CASE_CFN_FLOOR_FN:
15190 CASE_CFN_FMOD:
15191 CASE_CFN_FMOD_FN:
15192 CASE_CFN_FREXP:
15193 CASE_CFN_FREXP_FN:
15194 CASE_CFN_ICEIL:
15195 CASE_CFN_IFLOOR:
15196 CASE_CFN_IRINT:
15197 CASE_CFN_IROUND:
15198 CASE_CFN_LCEIL:
15199 CASE_CFN_LDEXP:
15200 CASE_CFN_LFLOOR:
15201 CASE_CFN_LLCEIL:
15202 CASE_CFN_LLFLOOR:
15203 CASE_CFN_LLRINT:
15204 CASE_CFN_LLRINT_FN:
15205 CASE_CFN_LLROUND:
15206 CASE_CFN_LLROUND_FN:
15207 CASE_CFN_LRINT:
15208 CASE_CFN_LRINT_FN:
15209 CASE_CFN_LROUND:
15210 CASE_CFN_LROUND_FN:
15211 CASE_CFN_MODF:
15212 CASE_CFN_MODF_FN:
15213 CASE_CFN_NEARBYINT:
15214 CASE_CFN_NEARBYINT_FN:
15215 CASE_CFN_RINT:
15216 CASE_CFN_RINT_FN:
15217 CASE_CFN_ROUND:
15218 CASE_CFN_ROUND_FN:
15219 CASE_CFN_ROUNDEVEN:
15220 CASE_CFN_ROUNDEVEN_FN:
15221 CASE_CFN_SCALB:
15222 CASE_CFN_SCALBLN:
15223 CASE_CFN_SCALBLN_FN:
15224 CASE_CFN_SCALBN:
15225 CASE_CFN_SCALBN_FN:
15226 CASE_CFN_SIGNBIT:
15227 CASE_CFN_SIGNIFICAND:
15228 CASE_CFN_SINH:
15229 CASE_CFN_SINH_FN:
15230 CASE_CFN_TANH:
15231 CASE_CFN_TANH_FN:
15232 CASE_CFN_TRUNC:
15233 CASE_CFN_TRUNC_FN:
15234 /* True if the 1st argument is nonnegative. */
15235 return RECURSE (arg0);
15237 CASE_CFN_FMAX:
15238 CASE_CFN_FMAX_FN:
15239 /* Usually RECURSE (arg0) || RECURSE (arg1) but NaNs complicate
15240 things. In the presence of sNaNs, we're only guaranteed to be
15241 non-negative if both operands are non-negative. In the presence
15242 of qNaNs, we're non-negative if either operand is non-negative
15243 and can't be a qNaN, or if both operands are non-negative. */
15244 if (tree_expr_maybe_signaling_nan_p (arg0) ||
15245 tree_expr_maybe_signaling_nan_p (arg1))
15246 return RECURSE (arg0) && RECURSE (arg1);
15247 return RECURSE (arg0) ? (!tree_expr_maybe_nan_p (arg0)
15248 || RECURSE (arg1))
15249 : (RECURSE (arg1)
15250 && !tree_expr_maybe_nan_p (arg1));
15252 CASE_CFN_FMIN:
15253 CASE_CFN_FMIN_FN:
15254 /* True if the 1st AND 2nd arguments are nonnegative. */
15255 return RECURSE (arg0) && RECURSE (arg1);
15257 CASE_CFN_COPYSIGN:
15258 CASE_CFN_COPYSIGN_FN:
15259 /* True if the 2nd argument is nonnegative. */
15260 return RECURSE (arg1);
15262 CASE_CFN_POWI:
15263 /* True if the 1st argument is nonnegative or the second
15264 argument is an even integer. */
15265 if (TREE_CODE (arg1) == INTEGER_CST
15266 && (TREE_INT_CST_LOW (arg1) & 1) == 0)
15267 return true;
15268 return RECURSE (arg0);
15270 CASE_CFN_POW:
15271 CASE_CFN_POW_FN:
15272 /* True if the 1st argument is nonnegative or the second
15273 argument is an even integer valued real. */
15274 if (TREE_CODE (arg1) == REAL_CST)
15276 REAL_VALUE_TYPE c;
15277 HOST_WIDE_INT n;
15279 c = TREE_REAL_CST (arg1);
15280 n = real_to_integer (&c);
15281 if ((n & 1) == 0)
15283 REAL_VALUE_TYPE cint;
15284 real_from_integer (&cint, VOIDmode, n, SIGNED);
15285 if (real_identical (&c, &cint))
15286 return true;
15289 return RECURSE (arg0);
15291 default:
15292 break;
15294 return tree_simple_nonnegative_warnv_p (CALL_EXPR, type);
15297 /* Return true if T is known to be non-negative. If the return
15298 value is based on the assumption that signed overflow is undefined,
15299 set *STRICT_OVERFLOW_P to true; otherwise, don't change
15300 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
15302 static bool
15303 tree_invalid_nonnegative_warnv_p (tree t, bool *strict_overflow_p, int depth)
15305 enum tree_code code = TREE_CODE (t);
15306 if (TYPE_UNSIGNED (TREE_TYPE (t)))
15307 return true;
15309 switch (code)
15311 case TARGET_EXPR:
15313 tree temp = TARGET_EXPR_SLOT (t);
15314 t = TARGET_EXPR_INITIAL (t);
15316 /* If the initializer is non-void, then it's a normal expression
15317 that will be assigned to the slot. */
15318 if (!VOID_TYPE_P (TREE_TYPE (t)))
15319 return RECURSE (t);
15321 /* Otherwise, the initializer sets the slot in some way. One common
15322 way is an assignment statement at the end of the initializer. */
15323 while (1)
15325 if (TREE_CODE (t) == BIND_EXPR)
15326 t = expr_last (BIND_EXPR_BODY (t));
15327 else if (TREE_CODE (t) == TRY_FINALLY_EXPR
15328 || TREE_CODE (t) == TRY_CATCH_EXPR)
15329 t = expr_last (TREE_OPERAND (t, 0));
15330 else if (TREE_CODE (t) == STATEMENT_LIST)
15331 t = expr_last (t);
15332 else
15333 break;
15335 if (TREE_CODE (t) == MODIFY_EXPR
15336 && TREE_OPERAND (t, 0) == temp)
15337 return RECURSE (TREE_OPERAND (t, 1));
15339 return false;
15342 case CALL_EXPR:
15344 tree arg0 = call_expr_nargs (t) > 0 ? CALL_EXPR_ARG (t, 0) : NULL_TREE;
15345 tree arg1 = call_expr_nargs (t) > 1 ? CALL_EXPR_ARG (t, 1) : NULL_TREE;
15347 return tree_call_nonnegative_warnv_p (TREE_TYPE (t),
15348 get_call_combined_fn (t),
15349 arg0,
15350 arg1,
15351 strict_overflow_p, depth);
15353 case COMPOUND_EXPR:
15354 case MODIFY_EXPR:
15355 return RECURSE (TREE_OPERAND (t, 1));
15357 case BIND_EXPR:
15358 return RECURSE (expr_last (TREE_OPERAND (t, 1)));
15360 case SAVE_EXPR:
15361 return RECURSE (TREE_OPERAND (t, 0));
15363 default:
15364 return tree_simple_nonnegative_warnv_p (TREE_CODE (t), TREE_TYPE (t));
15368 #undef RECURSE
15369 #undef tree_expr_nonnegative_warnv_p
15371 /* Return true if T is known to be non-negative. If the return
15372 value is based on the assumption that signed overflow is undefined,
15373 set *STRICT_OVERFLOW_P to true; otherwise, don't change
15374 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
15376 bool
15377 tree_expr_nonnegative_warnv_p (tree t, bool *strict_overflow_p, int depth)
15379 enum tree_code code;
15380 if (t == error_mark_node)
15381 return false;
15383 code = TREE_CODE (t);
15384 switch (TREE_CODE_CLASS (code))
15386 case tcc_binary:
15387 case tcc_comparison:
15388 return tree_binary_nonnegative_warnv_p (TREE_CODE (t),
15389 TREE_TYPE (t),
15390 TREE_OPERAND (t, 0),
15391 TREE_OPERAND (t, 1),
15392 strict_overflow_p, depth);
15394 case tcc_unary:
15395 return tree_unary_nonnegative_warnv_p (TREE_CODE (t),
15396 TREE_TYPE (t),
15397 TREE_OPERAND (t, 0),
15398 strict_overflow_p, depth);
15400 case tcc_constant:
15401 case tcc_declaration:
15402 case tcc_reference:
15403 return tree_single_nonnegative_warnv_p (t, strict_overflow_p, depth);
15405 default:
15406 break;
15409 switch (code)
15411 case TRUTH_AND_EXPR:
15412 case TRUTH_OR_EXPR:
15413 case TRUTH_XOR_EXPR:
15414 return tree_binary_nonnegative_warnv_p (TREE_CODE (t),
15415 TREE_TYPE (t),
15416 TREE_OPERAND (t, 0),
15417 TREE_OPERAND (t, 1),
15418 strict_overflow_p, depth);
15419 case TRUTH_NOT_EXPR:
15420 return tree_unary_nonnegative_warnv_p (TREE_CODE (t),
15421 TREE_TYPE (t),
15422 TREE_OPERAND (t, 0),
15423 strict_overflow_p, depth);
15425 case COND_EXPR:
15426 case CONSTRUCTOR:
15427 case OBJ_TYPE_REF:
15428 case ADDR_EXPR:
15429 case WITH_SIZE_EXPR:
15430 case SSA_NAME:
15431 return tree_single_nonnegative_warnv_p (t, strict_overflow_p, depth);
15433 default:
15434 return tree_invalid_nonnegative_warnv_p (t, strict_overflow_p, depth);
15438 /* Return true if `t' is known to be non-negative. Handle warnings
15439 about undefined signed overflow. */
15441 bool
15442 tree_expr_nonnegative_p (tree t)
15444 bool ret, strict_overflow_p;
15446 strict_overflow_p = false;
15447 ret = tree_expr_nonnegative_warnv_p (t, &strict_overflow_p);
15448 if (strict_overflow_p)
15449 fold_overflow_warning (("assuming signed overflow does not occur when "
15450 "determining that expression is always "
15451 "non-negative"),
15452 WARN_STRICT_OVERFLOW_MISC);
15453 return ret;
15457 /* Return true when (CODE OP0) is an address and is known to be nonzero.
15458 For floating point we further ensure that T is not denormal.
15459 Similar logic is present in nonzero_address in rtlanal.h.
15461 If the return value is based on the assumption that signed overflow
15462 is undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't
15463 change *STRICT_OVERFLOW_P. */
15465 bool
15466 tree_unary_nonzero_warnv_p (enum tree_code code, tree type, tree op0,
15467 bool *strict_overflow_p)
15469 switch (code)
15471 case ABS_EXPR:
15472 return tree_expr_nonzero_warnv_p (op0,
15473 strict_overflow_p);
15475 case NOP_EXPR:
15477 tree inner_type = TREE_TYPE (op0);
15478 tree outer_type = type;
15480 return (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
15481 && tree_expr_nonzero_warnv_p (op0,
15482 strict_overflow_p));
15484 break;
15486 case NON_LVALUE_EXPR:
15487 return tree_expr_nonzero_warnv_p (op0,
15488 strict_overflow_p);
15490 default:
15491 break;
15494 return false;
15497 /* Return true when (CODE OP0 OP1) is an address and is known to be nonzero.
15498 For floating point we further ensure that T is not denormal.
15499 Similar logic is present in nonzero_address in rtlanal.h.
15501 If the return value is based on the assumption that signed overflow
15502 is undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't
15503 change *STRICT_OVERFLOW_P. */
15505 bool
15506 tree_binary_nonzero_warnv_p (enum tree_code code,
15507 tree type,
15508 tree op0,
15509 tree op1, bool *strict_overflow_p)
15511 bool sub_strict_overflow_p;
15512 switch (code)
15514 case POINTER_PLUS_EXPR:
15515 case PLUS_EXPR:
15516 if (ANY_INTEGRAL_TYPE_P (type) && TYPE_OVERFLOW_UNDEFINED (type))
15518 /* With the presence of negative values it is hard
15519 to say something. */
15520 sub_strict_overflow_p = false;
15521 if (!tree_expr_nonnegative_warnv_p (op0,
15522 &sub_strict_overflow_p)
15523 || !tree_expr_nonnegative_warnv_p (op1,
15524 &sub_strict_overflow_p))
15525 return false;
15526 /* One of operands must be positive and the other non-negative. */
15527 /* We don't set *STRICT_OVERFLOW_P here: even if this value
15528 overflows, on a twos-complement machine the sum of two
15529 nonnegative numbers can never be zero. */
15530 return (tree_expr_nonzero_warnv_p (op0,
15531 strict_overflow_p)
15532 || tree_expr_nonzero_warnv_p (op1,
15533 strict_overflow_p));
15535 break;
15537 case MULT_EXPR:
15538 if (TYPE_OVERFLOW_UNDEFINED (type))
15540 if (tree_expr_nonzero_warnv_p (op0,
15541 strict_overflow_p)
15542 && tree_expr_nonzero_warnv_p (op1,
15543 strict_overflow_p))
15545 *strict_overflow_p = true;
15546 return true;
15549 break;
15551 case MIN_EXPR:
15552 sub_strict_overflow_p = false;
15553 if (tree_expr_nonzero_warnv_p (op0,
15554 &sub_strict_overflow_p)
15555 && tree_expr_nonzero_warnv_p (op1,
15556 &sub_strict_overflow_p))
15558 if (sub_strict_overflow_p)
15559 *strict_overflow_p = true;
15561 break;
15563 case MAX_EXPR:
15564 sub_strict_overflow_p = false;
15565 if (tree_expr_nonzero_warnv_p (op0,
15566 &sub_strict_overflow_p))
15568 if (sub_strict_overflow_p)
15569 *strict_overflow_p = true;
15571 /* When both operands are nonzero, then MAX must be too. */
15572 if (tree_expr_nonzero_warnv_p (op1,
15573 strict_overflow_p))
15574 return true;
15576 /* MAX where operand 0 is positive is positive. */
15577 return tree_expr_nonnegative_warnv_p (op0,
15578 strict_overflow_p);
15580 /* MAX where operand 1 is positive is positive. */
15581 else if (tree_expr_nonzero_warnv_p (op1,
15582 &sub_strict_overflow_p)
15583 && tree_expr_nonnegative_warnv_p (op1,
15584 &sub_strict_overflow_p))
15586 if (sub_strict_overflow_p)
15587 *strict_overflow_p = true;
15588 return true;
15590 break;
15592 case BIT_IOR_EXPR:
15593 return (tree_expr_nonzero_warnv_p (op1,
15594 strict_overflow_p)
15595 || tree_expr_nonzero_warnv_p (op0,
15596 strict_overflow_p));
15598 default:
15599 break;
15602 return false;
15605 /* Return true when T is an address and is known to be nonzero.
15606 For floating point we further ensure that T is not denormal.
15607 Similar logic is present in nonzero_address in rtlanal.h.
15609 If the return value is based on the assumption that signed overflow
15610 is undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't
15611 change *STRICT_OVERFLOW_P. */
15613 bool
15614 tree_single_nonzero_warnv_p (tree t, bool *strict_overflow_p)
15616 bool sub_strict_overflow_p;
15617 switch (TREE_CODE (t))
15619 case INTEGER_CST:
15620 return !integer_zerop (t);
15622 case ADDR_EXPR:
15624 tree base = TREE_OPERAND (t, 0);
15626 if (!DECL_P (base))
15627 base = get_base_address (base);
15629 if (base && TREE_CODE (base) == TARGET_EXPR)
15630 base = TARGET_EXPR_SLOT (base);
15632 if (!base)
15633 return false;
15635 /* For objects in symbol table check if we know they are non-zero.
15636 Don't do anything for variables and functions before symtab is built;
15637 it is quite possible that they will be declared weak later. */
15638 int nonzero_addr = maybe_nonzero_address (base);
15639 if (nonzero_addr >= 0)
15640 return nonzero_addr;
15642 /* Constants are never weak. */
15643 if (CONSTANT_CLASS_P (base))
15644 return true;
15646 return false;
15649 case COND_EXPR:
15650 sub_strict_overflow_p = false;
15651 if (tree_expr_nonzero_warnv_p (TREE_OPERAND (t, 1),
15652 &sub_strict_overflow_p)
15653 && tree_expr_nonzero_warnv_p (TREE_OPERAND (t, 2),
15654 &sub_strict_overflow_p))
15656 if (sub_strict_overflow_p)
15657 *strict_overflow_p = true;
15658 return true;
15660 break;
15662 case SSA_NAME:
15663 if (!INTEGRAL_TYPE_P (TREE_TYPE (t)))
15664 break;
15665 return expr_not_equal_to (t, wi::zero (TYPE_PRECISION (TREE_TYPE (t))));
15667 default:
15668 break;
15670 return false;
15673 #define integer_valued_real_p(X) \
15674 _Pragma ("GCC error \"Use RECURSE for recursive calls\"") 0
15676 #define RECURSE(X) \
15677 ((integer_valued_real_p) (X, depth + 1))
15679 /* Return true if the floating point result of (CODE OP0) has an
15680 integer value. We also allow +Inf, -Inf and NaN to be considered
15681 integer values. Return false for signaling NaN.
15683 DEPTH is the current nesting depth of the query. */
15685 bool
15686 integer_valued_real_unary_p (tree_code code, tree op0, int depth)
15688 switch (code)
15690 case FLOAT_EXPR:
15691 return true;
15693 case ABS_EXPR:
15694 return RECURSE (op0);
15696 CASE_CONVERT:
15698 tree type = TREE_TYPE (op0);
15699 if (TREE_CODE (type) == INTEGER_TYPE)
15700 return true;
15701 if (SCALAR_FLOAT_TYPE_P (type))
15702 return RECURSE (op0);
15703 break;
15706 default:
15707 break;
15709 return false;
15712 /* Return true if the floating point result of (CODE OP0 OP1) has an
15713 integer value. We also allow +Inf, -Inf and NaN to be considered
15714 integer values. Return false for signaling NaN.
15716 DEPTH is the current nesting depth of the query. */
15718 bool
15719 integer_valued_real_binary_p (tree_code code, tree op0, tree op1, int depth)
15721 switch (code)
15723 case PLUS_EXPR:
15724 case MINUS_EXPR:
15725 case MULT_EXPR:
15726 case MIN_EXPR:
15727 case MAX_EXPR:
15728 return RECURSE (op0) && RECURSE (op1);
15730 default:
15731 break;
15733 return false;
15736 /* Return true if the floating point result of calling FNDECL with arguments
15737 ARG0 and ARG1 has an integer value. We also allow +Inf, -Inf and NaN to be
15738 considered integer values. Return false for signaling NaN. If FNDECL
15739 takes fewer than 2 arguments, the remaining ARGn are null.
15741 DEPTH is the current nesting depth of the query. */
15743 bool
15744 integer_valued_real_call_p (combined_fn fn, tree arg0, tree arg1, int depth)
15746 switch (fn)
15748 CASE_CFN_CEIL:
15749 CASE_CFN_CEIL_FN:
15750 CASE_CFN_FLOOR:
15751 CASE_CFN_FLOOR_FN:
15752 CASE_CFN_NEARBYINT:
15753 CASE_CFN_NEARBYINT_FN:
15754 CASE_CFN_RINT:
15755 CASE_CFN_RINT_FN:
15756 CASE_CFN_ROUND:
15757 CASE_CFN_ROUND_FN:
15758 CASE_CFN_ROUNDEVEN:
15759 CASE_CFN_ROUNDEVEN_FN:
15760 CASE_CFN_TRUNC:
15761 CASE_CFN_TRUNC_FN:
15762 return true;
15764 CASE_CFN_FMIN:
15765 CASE_CFN_FMIN_FN:
15766 CASE_CFN_FMAX:
15767 CASE_CFN_FMAX_FN:
15768 return RECURSE (arg0) && RECURSE (arg1);
15770 default:
15771 break;
15773 return false;
15776 /* Return true if the floating point expression T (a GIMPLE_SINGLE_RHS)
15777 has an integer value. We also allow +Inf, -Inf and NaN to be
15778 considered integer values. Return false for signaling NaN.
15780 DEPTH is the current nesting depth of the query. */
15782 bool
15783 integer_valued_real_single_p (tree t, int depth)
15785 switch (TREE_CODE (t))
15787 case REAL_CST:
15788 return real_isinteger (TREE_REAL_CST_PTR (t), TYPE_MODE (TREE_TYPE (t)));
15790 case COND_EXPR:
15791 return RECURSE (TREE_OPERAND (t, 1)) && RECURSE (TREE_OPERAND (t, 2));
15793 case SSA_NAME:
15794 /* Limit the depth of recursion to avoid quadratic behavior.
15795 This is expected to catch almost all occurrences in practice.
15796 If this code misses important cases that unbounded recursion
15797 would not, passes that need this information could be revised
15798 to provide it through dataflow propagation. */
15799 return (!name_registered_for_update_p (t)
15800 && depth < param_max_ssa_name_query_depth
15801 && gimple_stmt_integer_valued_real_p (SSA_NAME_DEF_STMT (t),
15802 depth));
15804 default:
15805 break;
15807 return false;
15810 /* Return true if the floating point expression T (a GIMPLE_INVALID_RHS)
15811 has an integer value. We also allow +Inf, -Inf and NaN to be
15812 considered integer values. Return false for signaling NaN.
15814 DEPTH is the current nesting depth of the query. */
15816 static bool
15817 integer_valued_real_invalid_p (tree t, int depth)
15819 switch (TREE_CODE (t))
15821 case COMPOUND_EXPR:
15822 case MODIFY_EXPR:
15823 case BIND_EXPR:
15824 return RECURSE (TREE_OPERAND (t, 1));
15826 case SAVE_EXPR:
15827 return RECURSE (TREE_OPERAND (t, 0));
15829 default:
15830 break;
15832 return false;
15835 #undef RECURSE
15836 #undef integer_valued_real_p
15838 /* Return true if the floating point expression T has an integer value.
15839 We also allow +Inf, -Inf and NaN to be considered integer values.
15840 Return false for signaling NaN.
15842 DEPTH is the current nesting depth of the query. */
15844 bool
15845 integer_valued_real_p (tree t, int depth)
15847 if (t == error_mark_node)
15848 return false;
15850 STRIP_ANY_LOCATION_WRAPPER (t);
15852 tree_code code = TREE_CODE (t);
15853 switch (TREE_CODE_CLASS (code))
15855 case tcc_binary:
15856 case tcc_comparison:
15857 return integer_valued_real_binary_p (code, TREE_OPERAND (t, 0),
15858 TREE_OPERAND (t, 1), depth);
15860 case tcc_unary:
15861 return integer_valued_real_unary_p (code, TREE_OPERAND (t, 0), depth);
15863 case tcc_constant:
15864 case tcc_declaration:
15865 case tcc_reference:
15866 return integer_valued_real_single_p (t, depth);
15868 default:
15869 break;
15872 switch (code)
15874 case COND_EXPR:
15875 case SSA_NAME:
15876 return integer_valued_real_single_p (t, depth);
15878 case CALL_EXPR:
15880 tree arg0 = (call_expr_nargs (t) > 0
15881 ? CALL_EXPR_ARG (t, 0)
15882 : NULL_TREE);
15883 tree arg1 = (call_expr_nargs (t) > 1
15884 ? CALL_EXPR_ARG (t, 1)
15885 : NULL_TREE);
15886 return integer_valued_real_call_p (get_call_combined_fn (t),
15887 arg0, arg1, depth);
15890 default:
15891 return integer_valued_real_invalid_p (t, depth);
15895 /* Given the components of a binary expression CODE, TYPE, OP0 and OP1,
15896 attempt to fold the expression to a constant without modifying TYPE,
15897 OP0 or OP1.
15899 If the expression could be simplified to a constant, then return
15900 the constant. If the expression would not be simplified to a
15901 constant, then return NULL_TREE. */
15903 tree
15904 fold_binary_to_constant (enum tree_code code, tree type, tree op0, tree op1)
15906 tree tem = fold_binary (code, type, op0, op1);
15907 return (tem && TREE_CONSTANT (tem)) ? tem : NULL_TREE;
15910 /* Given the components of a unary expression CODE, TYPE and OP0,
15911 attempt to fold the expression to a constant without modifying
15912 TYPE or OP0.
15914 If the expression could be simplified to a constant, then return
15915 the constant. If the expression would not be simplified to a
15916 constant, then return NULL_TREE. */
15918 tree
15919 fold_unary_to_constant (enum tree_code code, tree type, tree op0)
15921 tree tem = fold_unary (code, type, op0);
15922 return (tem && TREE_CONSTANT (tem)) ? tem : NULL_TREE;
15925 /* If EXP represents referencing an element in a constant string
15926 (either via pointer arithmetic or array indexing), return the
15927 tree representing the value accessed, otherwise return NULL. */
15929 tree
15930 fold_read_from_constant_string (tree exp)
15932 if ((INDIRECT_REF_P (exp)
15933 || TREE_CODE (exp) == ARRAY_REF)
15934 && TREE_CODE (TREE_TYPE (exp)) == INTEGER_TYPE)
15936 tree exp1 = TREE_OPERAND (exp, 0);
15937 tree index;
15938 tree string;
15939 location_t loc = EXPR_LOCATION (exp);
15941 if (INDIRECT_REF_P (exp))
15942 string = string_constant (exp1, &index, NULL, NULL);
15943 else
15945 tree low_bound = array_ref_low_bound (exp);
15946 index = fold_convert_loc (loc, sizetype, TREE_OPERAND (exp, 1));
15948 /* Optimize the special-case of a zero lower bound.
15950 We convert the low_bound to sizetype to avoid some problems
15951 with constant folding. (E.g. suppose the lower bound is 1,
15952 and its mode is QI. Without the conversion,l (ARRAY
15953 +(INDEX-(unsigned char)1)) becomes ((ARRAY+(-(unsigned char)1))
15954 +INDEX), which becomes (ARRAY+255+INDEX). Oops!) */
15955 if (! integer_zerop (low_bound))
15956 index = size_diffop_loc (loc, index,
15957 fold_convert_loc (loc, sizetype, low_bound));
15959 string = exp1;
15962 scalar_int_mode char_mode;
15963 if (string
15964 && TYPE_MODE (TREE_TYPE (exp)) == TYPE_MODE (TREE_TYPE (TREE_TYPE (string)))
15965 && TREE_CODE (string) == STRING_CST
15966 && tree_fits_uhwi_p (index)
15967 && compare_tree_int (index, TREE_STRING_LENGTH (string)) < 0
15968 && is_int_mode (TYPE_MODE (TREE_TYPE (TREE_TYPE (string))),
15969 &char_mode)
15970 && GET_MODE_SIZE (char_mode) == 1)
15971 return build_int_cst_type (TREE_TYPE (exp),
15972 (TREE_STRING_POINTER (string)
15973 [TREE_INT_CST_LOW (index)]));
15975 return NULL;
15978 /* Folds a read from vector element at IDX of vector ARG. */
15980 tree
15981 fold_read_from_vector (tree arg, poly_uint64 idx)
15983 unsigned HOST_WIDE_INT i;
15984 if (known_lt (idx, TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg)))
15985 && known_ge (idx, 0u)
15986 && idx.is_constant (&i))
15988 if (TREE_CODE (arg) == VECTOR_CST)
15989 return VECTOR_CST_ELT (arg, i);
15990 else if (TREE_CODE (arg) == CONSTRUCTOR)
15992 if (CONSTRUCTOR_NELTS (arg)
15993 && VECTOR_TYPE_P (TREE_TYPE (CONSTRUCTOR_ELT (arg, 0)->value)))
15994 return NULL_TREE;
15995 if (i >= CONSTRUCTOR_NELTS (arg))
15996 return build_zero_cst (TREE_TYPE (TREE_TYPE (arg)));
15997 return CONSTRUCTOR_ELT (arg, i)->value;
16000 return NULL_TREE;
16003 /* Return the tree for neg (ARG0) when ARG0 is known to be either
16004 an integer constant, real, or fixed-point constant.
16006 TYPE is the type of the result. */
16008 static tree
16009 fold_negate_const (tree arg0, tree type)
16011 tree t = NULL_TREE;
16013 switch (TREE_CODE (arg0))
16015 case REAL_CST:
16016 t = build_real (type, real_value_negate (&TREE_REAL_CST (arg0)));
16017 break;
16019 case FIXED_CST:
16021 FIXED_VALUE_TYPE f;
16022 bool overflow_p = fixed_arithmetic (&f, NEGATE_EXPR,
16023 &(TREE_FIXED_CST (arg0)), NULL,
16024 TYPE_SATURATING (type));
16025 t = build_fixed (type, f);
16026 /* Propagate overflow flags. */
16027 if (overflow_p | TREE_OVERFLOW (arg0))
16028 TREE_OVERFLOW (t) = 1;
16029 break;
16032 default:
16033 if (poly_int_tree_p (arg0))
16035 wi::overflow_type overflow;
16036 poly_wide_int res = wi::neg (wi::to_poly_wide (arg0), &overflow);
16037 t = force_fit_type (type, res, 1,
16038 (overflow && ! TYPE_UNSIGNED (type))
16039 || TREE_OVERFLOW (arg0));
16040 break;
16043 gcc_unreachable ();
16046 return t;
16049 /* Return the tree for abs (ARG0) when ARG0 is known to be either
16050 an integer constant or real constant.
16052 TYPE is the type of the result. */
16054 tree
16055 fold_abs_const (tree arg0, tree type)
16057 tree t = NULL_TREE;
16059 switch (TREE_CODE (arg0))
16061 case INTEGER_CST:
16063 /* If the value is unsigned or non-negative, then the absolute value
16064 is the same as the ordinary value. */
16065 wide_int val = wi::to_wide (arg0);
16066 wi::overflow_type overflow = wi::OVF_NONE;
16067 if (!wi::neg_p (val, TYPE_SIGN (TREE_TYPE (arg0))))
16070 /* If the value is negative, then the absolute value is
16071 its negation. */
16072 else
16073 val = wi::neg (val, &overflow);
16075 /* Force to the destination type, set TREE_OVERFLOW for signed
16076 TYPE only. */
16077 t = force_fit_type (type, val, 1, overflow | TREE_OVERFLOW (arg0));
16079 break;
16081 case REAL_CST:
16082 if (REAL_VALUE_NEGATIVE (TREE_REAL_CST (arg0)))
16083 t = build_real (type, real_value_negate (&TREE_REAL_CST (arg0)));
16084 else
16085 t = arg0;
16086 break;
16088 default:
16089 gcc_unreachable ();
16092 return t;
16095 /* Return the tree for not (ARG0) when ARG0 is known to be an integer
16096 constant. TYPE is the type of the result. */
16098 static tree
16099 fold_not_const (const_tree arg0, tree type)
16101 gcc_assert (TREE_CODE (arg0) == INTEGER_CST);
16103 return force_fit_type (type, ~wi::to_wide (arg0), 0, TREE_OVERFLOW (arg0));
16106 /* Given CODE, a relational operator, the target type, TYPE and two
16107 constant operands OP0 and OP1, return the result of the
16108 relational operation. If the result is not a compile time
16109 constant, then return NULL_TREE. */
16111 static tree
16112 fold_relational_const (enum tree_code code, tree type, tree op0, tree op1)
16114 int result, invert;
16116 /* From here on, the only cases we handle are when the result is
16117 known to be a constant. */
16119 if (TREE_CODE (op0) == REAL_CST && TREE_CODE (op1) == REAL_CST)
16121 const REAL_VALUE_TYPE *c0 = TREE_REAL_CST_PTR (op0);
16122 const REAL_VALUE_TYPE *c1 = TREE_REAL_CST_PTR (op1);
16124 /* Handle the cases where either operand is a NaN. */
16125 if (real_isnan (c0) || real_isnan (c1))
16127 switch (code)
16129 case EQ_EXPR:
16130 case ORDERED_EXPR:
16131 result = 0;
16132 break;
16134 case NE_EXPR:
16135 case UNORDERED_EXPR:
16136 case UNLT_EXPR:
16137 case UNLE_EXPR:
16138 case UNGT_EXPR:
16139 case UNGE_EXPR:
16140 case UNEQ_EXPR:
16141 result = 1;
16142 break;
16144 case LT_EXPR:
16145 case LE_EXPR:
16146 case GT_EXPR:
16147 case GE_EXPR:
16148 case LTGT_EXPR:
16149 if (flag_trapping_math)
16150 return NULL_TREE;
16151 result = 0;
16152 break;
16154 default:
16155 gcc_unreachable ();
16158 return constant_boolean_node (result, type);
16161 return constant_boolean_node (real_compare (code, c0, c1), type);
16164 if (TREE_CODE (op0) == FIXED_CST && TREE_CODE (op1) == FIXED_CST)
16166 const FIXED_VALUE_TYPE *c0 = TREE_FIXED_CST_PTR (op0);
16167 const FIXED_VALUE_TYPE *c1 = TREE_FIXED_CST_PTR (op1);
16168 return constant_boolean_node (fixed_compare (code, c0, c1), type);
16171 /* Handle equality/inequality of complex constants. */
16172 if (TREE_CODE (op0) == COMPLEX_CST && TREE_CODE (op1) == COMPLEX_CST)
16174 tree rcond = fold_relational_const (code, type,
16175 TREE_REALPART (op0),
16176 TREE_REALPART (op1));
16177 tree icond = fold_relational_const (code, type,
16178 TREE_IMAGPART (op0),
16179 TREE_IMAGPART (op1));
16180 if (code == EQ_EXPR)
16181 return fold_build2 (TRUTH_ANDIF_EXPR, type, rcond, icond);
16182 else if (code == NE_EXPR)
16183 return fold_build2 (TRUTH_ORIF_EXPR, type, rcond, icond);
16184 else
16185 return NULL_TREE;
16188 if (TREE_CODE (op0) == VECTOR_CST && TREE_CODE (op1) == VECTOR_CST)
16190 if (!VECTOR_TYPE_P (type))
16192 /* Have vector comparison with scalar boolean result. */
16193 gcc_assert ((code == EQ_EXPR || code == NE_EXPR)
16194 && known_eq (VECTOR_CST_NELTS (op0),
16195 VECTOR_CST_NELTS (op1)));
16196 unsigned HOST_WIDE_INT nunits;
16197 if (!VECTOR_CST_NELTS (op0).is_constant (&nunits))
16198 return NULL_TREE;
16199 for (unsigned i = 0; i < nunits; i++)
16201 tree elem0 = VECTOR_CST_ELT (op0, i);
16202 tree elem1 = VECTOR_CST_ELT (op1, i);
16203 tree tmp = fold_relational_const (EQ_EXPR, type, elem0, elem1);
16204 if (tmp == NULL_TREE)
16205 return NULL_TREE;
16206 if (integer_zerop (tmp))
16207 return constant_boolean_node (code == NE_EXPR, type);
16209 return constant_boolean_node (code == EQ_EXPR, type);
16211 tree_vector_builder elts;
16212 if (!elts.new_binary_operation (type, op0, op1, false))
16213 return NULL_TREE;
16214 unsigned int count = elts.encoded_nelts ();
16215 for (unsigned i = 0; i < count; i++)
16217 tree elem_type = TREE_TYPE (type);
16218 tree elem0 = VECTOR_CST_ELT (op0, i);
16219 tree elem1 = VECTOR_CST_ELT (op1, i);
16221 tree tem = fold_relational_const (code, elem_type,
16222 elem0, elem1);
16224 if (tem == NULL_TREE)
16225 return NULL_TREE;
16227 elts.quick_push (build_int_cst (elem_type,
16228 integer_zerop (tem) ? 0 : -1));
16231 return elts.build ();
16234 /* From here on we only handle LT, LE, GT, GE, EQ and NE.
16236 To compute GT, swap the arguments and do LT.
16237 To compute GE, do LT and invert the result.
16238 To compute LE, swap the arguments, do LT and invert the result.
16239 To compute NE, do EQ and invert the result.
16241 Therefore, the code below must handle only EQ and LT. */
16243 if (code == LE_EXPR || code == GT_EXPR)
16245 std::swap (op0, op1);
16246 code = swap_tree_comparison (code);
16249 /* Note that it is safe to invert for real values here because we
16250 have already handled the one case that it matters. */
16252 invert = 0;
16253 if (code == NE_EXPR || code == GE_EXPR)
16255 invert = 1;
16256 code = invert_tree_comparison (code, false);
16259 /* Compute a result for LT or EQ if args permit;
16260 Otherwise return T. */
16261 if (TREE_CODE (op0) == INTEGER_CST && TREE_CODE (op1) == INTEGER_CST)
16263 if (code == EQ_EXPR)
16264 result = tree_int_cst_equal (op0, op1);
16265 else
16266 result = tree_int_cst_lt (op0, op1);
16268 else
16269 return NULL_TREE;
16271 if (invert)
16272 result ^= 1;
16273 return constant_boolean_node (result, type);
16276 /* If necessary, return a CLEANUP_POINT_EXPR for EXPR with the
16277 indicated TYPE. If no CLEANUP_POINT_EXPR is necessary, return EXPR
16278 itself. */
16280 tree
16281 fold_build_cleanup_point_expr (tree type, tree expr)
16283 /* If the expression does not have side effects then we don't have to wrap
16284 it with a cleanup point expression. */
16285 if (!TREE_SIDE_EFFECTS (expr))
16286 return expr;
16288 /* If the expression is a return, check to see if the expression inside the
16289 return has no side effects or the right hand side of the modify expression
16290 inside the return. If either don't have side effects set we don't need to
16291 wrap the expression in a cleanup point expression. Note we don't check the
16292 left hand side of the modify because it should always be a return decl. */
16293 if (TREE_CODE (expr) == RETURN_EXPR)
16295 tree op = TREE_OPERAND (expr, 0);
16296 if (!op || !TREE_SIDE_EFFECTS (op))
16297 return expr;
16298 op = TREE_OPERAND (op, 1);
16299 if (!TREE_SIDE_EFFECTS (op))
16300 return expr;
16303 return build1_loc (EXPR_LOCATION (expr), CLEANUP_POINT_EXPR, type, expr);
16306 /* Given a pointer value OP0 and a type TYPE, return a simplified version
16307 of an indirection through OP0, or NULL_TREE if no simplification is
16308 possible. */
16310 tree
16311 fold_indirect_ref_1 (location_t loc, tree type, tree op0)
16313 tree sub = op0;
16314 tree subtype;
16315 poly_uint64 const_op01;
16317 STRIP_NOPS (sub);
16318 subtype = TREE_TYPE (sub);
16319 if (!POINTER_TYPE_P (subtype)
16320 || TYPE_REF_CAN_ALIAS_ALL (TREE_TYPE (op0)))
16321 return NULL_TREE;
16323 if (TREE_CODE (sub) == ADDR_EXPR)
16325 tree op = TREE_OPERAND (sub, 0);
16326 tree optype = TREE_TYPE (op);
16328 /* *&CONST_DECL -> to the value of the const decl. */
16329 if (TREE_CODE (op) == CONST_DECL)
16330 return DECL_INITIAL (op);
16331 /* *&p => p; make sure to handle *&"str"[cst] here. */
16332 if (type == optype)
16334 tree fop = fold_read_from_constant_string (op);
16335 if (fop)
16336 return fop;
16337 else
16338 return op;
16340 /* *(foo *)&fooarray => fooarray[0] */
16341 else if (TREE_CODE (optype) == ARRAY_TYPE
16342 && type == TREE_TYPE (optype)
16343 && (!in_gimple_form
16344 || TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST))
16346 tree type_domain = TYPE_DOMAIN (optype);
16347 tree min_val = size_zero_node;
16348 if (type_domain && TYPE_MIN_VALUE (type_domain))
16349 min_val = TYPE_MIN_VALUE (type_domain);
16350 if (in_gimple_form
16351 && TREE_CODE (min_val) != INTEGER_CST)
16352 return NULL_TREE;
16353 return build4_loc (loc, ARRAY_REF, type, op, min_val,
16354 NULL_TREE, NULL_TREE);
16356 /* *(foo *)&complexfoo => __real__ complexfoo */
16357 else if (TREE_CODE (optype) == COMPLEX_TYPE
16358 && type == TREE_TYPE (optype))
16359 return fold_build1_loc (loc, REALPART_EXPR, type, op);
16360 /* *(foo *)&vectorfoo => BIT_FIELD_REF<vectorfoo,...> */
16361 else if (VECTOR_TYPE_P (optype)
16362 && type == TREE_TYPE (optype))
16364 tree part_width = TYPE_SIZE (type);
16365 tree index = bitsize_int (0);
16366 return fold_build3_loc (loc, BIT_FIELD_REF, type, op, part_width,
16367 index);
16371 if (TREE_CODE (sub) == POINTER_PLUS_EXPR
16372 && poly_int_tree_p (TREE_OPERAND (sub, 1), &const_op01))
16374 tree op00 = TREE_OPERAND (sub, 0);
16375 tree op01 = TREE_OPERAND (sub, 1);
16377 STRIP_NOPS (op00);
16378 if (TREE_CODE (op00) == ADDR_EXPR)
16380 tree op00type;
16381 op00 = TREE_OPERAND (op00, 0);
16382 op00type = TREE_TYPE (op00);
16384 /* ((foo*)&vectorfoo)[1] => BIT_FIELD_REF<vectorfoo,...> */
16385 if (VECTOR_TYPE_P (op00type)
16386 && type == TREE_TYPE (op00type)
16387 /* POINTER_PLUS_EXPR second operand is sizetype, unsigned,
16388 but we want to treat offsets with MSB set as negative.
16389 For the code below negative offsets are invalid and
16390 TYPE_SIZE of the element is something unsigned, so
16391 check whether op01 fits into poly_int64, which implies
16392 it is from 0 to INTTYPE_MAXIMUM (HOST_WIDE_INT), and
16393 then just use poly_uint64 because we want to treat the
16394 value as unsigned. */
16395 && tree_fits_poly_int64_p (op01))
16397 tree part_width = TYPE_SIZE (type);
16398 poly_uint64 max_offset
16399 = (tree_to_uhwi (part_width) / BITS_PER_UNIT
16400 * TYPE_VECTOR_SUBPARTS (op00type));
16401 if (known_lt (const_op01, max_offset))
16403 tree index = bitsize_int (const_op01 * BITS_PER_UNIT);
16404 return fold_build3_loc (loc,
16405 BIT_FIELD_REF, type, op00,
16406 part_width, index);
16409 /* ((foo*)&complexfoo)[1] => __imag__ complexfoo */
16410 else if (TREE_CODE (op00type) == COMPLEX_TYPE
16411 && type == TREE_TYPE (op00type))
16413 if (known_eq (wi::to_poly_offset (TYPE_SIZE_UNIT (type)),
16414 const_op01))
16415 return fold_build1_loc (loc, IMAGPART_EXPR, type, op00);
16417 /* ((foo *)&fooarray)[1] => fooarray[1] */
16418 else if (TREE_CODE (op00type) == ARRAY_TYPE
16419 && type == TREE_TYPE (op00type))
16421 tree type_domain = TYPE_DOMAIN (op00type);
16422 tree min_val = size_zero_node;
16423 if (type_domain && TYPE_MIN_VALUE (type_domain))
16424 min_val = TYPE_MIN_VALUE (type_domain);
16425 poly_uint64 type_size, index;
16426 if (poly_int_tree_p (min_val)
16427 && poly_int_tree_p (TYPE_SIZE_UNIT (type), &type_size)
16428 && multiple_p (const_op01, type_size, &index))
16430 poly_offset_int off = index + wi::to_poly_offset (min_val);
16431 op01 = wide_int_to_tree (sizetype, off);
16432 return build4_loc (loc, ARRAY_REF, type, op00, op01,
16433 NULL_TREE, NULL_TREE);
16439 /* *(foo *)fooarrptr => (*fooarrptr)[0] */
16440 if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
16441 && type == TREE_TYPE (TREE_TYPE (subtype))
16442 && (!in_gimple_form
16443 || TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST))
16445 tree type_domain;
16446 tree min_val = size_zero_node;
16447 sub = build_fold_indirect_ref_loc (loc, sub);
16448 type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
16449 if (type_domain && TYPE_MIN_VALUE (type_domain))
16450 min_val = TYPE_MIN_VALUE (type_domain);
16451 if (in_gimple_form
16452 && TREE_CODE (min_val) != INTEGER_CST)
16453 return NULL_TREE;
16454 return build4_loc (loc, ARRAY_REF, type, sub, min_val, NULL_TREE,
16455 NULL_TREE);
16458 return NULL_TREE;
16461 /* Builds an expression for an indirection through T, simplifying some
16462 cases. */
16464 tree
16465 build_fold_indirect_ref_loc (location_t loc, tree t)
16467 tree type = TREE_TYPE (TREE_TYPE (t));
16468 tree sub = fold_indirect_ref_1 (loc, type, t);
16470 if (sub)
16471 return sub;
16473 return build1_loc (loc, INDIRECT_REF, type, t);
16476 /* Given an INDIRECT_REF T, return either T or a simplified version. */
16478 tree
16479 fold_indirect_ref_loc (location_t loc, tree t)
16481 tree sub = fold_indirect_ref_1 (loc, TREE_TYPE (t), TREE_OPERAND (t, 0));
16483 if (sub)
16484 return sub;
16485 else
16486 return t;
16489 /* Strip non-trapping, non-side-effecting tree nodes from an expression
16490 whose result is ignored. The type of the returned tree need not be
16491 the same as the original expression. */
16493 tree
16494 fold_ignored_result (tree t)
16496 if (!TREE_SIDE_EFFECTS (t))
16497 return integer_zero_node;
16499 for (;;)
16500 switch (TREE_CODE_CLASS (TREE_CODE (t)))
16502 case tcc_unary:
16503 t = TREE_OPERAND (t, 0);
16504 break;
16506 case tcc_binary:
16507 case tcc_comparison:
16508 if (!TREE_SIDE_EFFECTS (TREE_OPERAND (t, 1)))
16509 t = TREE_OPERAND (t, 0);
16510 else if (!TREE_SIDE_EFFECTS (TREE_OPERAND (t, 0)))
16511 t = TREE_OPERAND (t, 1);
16512 else
16513 return t;
16514 break;
16516 case tcc_expression:
16517 switch (TREE_CODE (t))
16519 case COMPOUND_EXPR:
16520 if (TREE_SIDE_EFFECTS (TREE_OPERAND (t, 1)))
16521 return t;
16522 t = TREE_OPERAND (t, 0);
16523 break;
16525 case COND_EXPR:
16526 if (TREE_SIDE_EFFECTS (TREE_OPERAND (t, 1))
16527 || TREE_SIDE_EFFECTS (TREE_OPERAND (t, 2)))
16528 return t;
16529 t = TREE_OPERAND (t, 0);
16530 break;
16532 default:
16533 return t;
16535 break;
16537 default:
16538 return t;
16542 /* Return the value of VALUE, rounded up to a multiple of DIVISOR. */
16544 tree
16545 round_up_loc (location_t loc, tree value, unsigned int divisor)
16547 tree div = NULL_TREE;
16549 if (divisor == 1)
16550 return value;
16552 /* See if VALUE is already a multiple of DIVISOR. If so, we don't
16553 have to do anything. Only do this when we are not given a const,
16554 because in that case, this check is more expensive than just
16555 doing it. */
16556 if (TREE_CODE (value) != INTEGER_CST)
16558 div = build_int_cst (TREE_TYPE (value), divisor);
16560 if (multiple_of_p (TREE_TYPE (value), value, div))
16561 return value;
16564 /* If divisor is a power of two, simplify this to bit manipulation. */
16565 if (pow2_or_zerop (divisor))
16567 if (TREE_CODE (value) == INTEGER_CST)
16569 wide_int val = wi::to_wide (value);
16570 bool overflow_p;
16572 if ((val & (divisor - 1)) == 0)
16573 return value;
16575 overflow_p = TREE_OVERFLOW (value);
16576 val += divisor - 1;
16577 val &= (int) -divisor;
16578 if (val == 0)
16579 overflow_p = true;
16581 return force_fit_type (TREE_TYPE (value), val, -1, overflow_p);
16583 else
16585 tree t;
16587 t = build_int_cst (TREE_TYPE (value), divisor - 1);
16588 value = size_binop_loc (loc, PLUS_EXPR, value, t);
16589 t = build_int_cst (TREE_TYPE (value), - (int) divisor);
16590 value = size_binop_loc (loc, BIT_AND_EXPR, value, t);
16593 else
16595 if (!div)
16596 div = build_int_cst (TREE_TYPE (value), divisor);
16597 value = size_binop_loc (loc, CEIL_DIV_EXPR, value, div);
16598 value = size_binop_loc (loc, MULT_EXPR, value, div);
16601 return value;
16604 /* Likewise, but round down. */
16606 tree
16607 round_down_loc (location_t loc, tree value, int divisor)
16609 tree div = NULL_TREE;
16611 gcc_assert (divisor > 0);
16612 if (divisor == 1)
16613 return value;
16615 /* See if VALUE is already a multiple of DIVISOR. If so, we don't
16616 have to do anything. Only do this when we are not given a const,
16617 because in that case, this check is more expensive than just
16618 doing it. */
16619 if (TREE_CODE (value) != INTEGER_CST)
16621 div = build_int_cst (TREE_TYPE (value), divisor);
16623 if (multiple_of_p (TREE_TYPE (value), value, div))
16624 return value;
16627 /* If divisor is a power of two, simplify this to bit manipulation. */
16628 if (pow2_or_zerop (divisor))
16630 tree t;
16632 t = build_int_cst (TREE_TYPE (value), -divisor);
16633 value = size_binop_loc (loc, BIT_AND_EXPR, value, t);
16635 else
16637 if (!div)
16638 div = build_int_cst (TREE_TYPE (value), divisor);
16639 value = size_binop_loc (loc, FLOOR_DIV_EXPR, value, div);
16640 value = size_binop_loc (loc, MULT_EXPR, value, div);
16643 return value;
16646 /* Returns the pointer to the base of the object addressed by EXP and
16647 extracts the information about the offset of the access, storing it
16648 to PBITPOS and POFFSET. */
16650 static tree
16651 split_address_to_core_and_offset (tree exp,
16652 poly_int64 *pbitpos, tree *poffset)
16654 tree core;
16655 machine_mode mode;
16656 int unsignedp, reversep, volatilep;
16657 poly_int64 bitsize;
16658 location_t loc = EXPR_LOCATION (exp);
16660 if (TREE_CODE (exp) == SSA_NAME)
16661 if (gassign *def = dyn_cast <gassign *> (SSA_NAME_DEF_STMT (exp)))
16662 if (gimple_assign_rhs_code (def) == ADDR_EXPR)
16663 exp = gimple_assign_rhs1 (def);
16665 if (TREE_CODE (exp) == ADDR_EXPR)
16667 core = get_inner_reference (TREE_OPERAND (exp, 0), &bitsize, pbitpos,
16668 poffset, &mode, &unsignedp, &reversep,
16669 &volatilep);
16670 core = build_fold_addr_expr_loc (loc, core);
16672 else if (TREE_CODE (exp) == POINTER_PLUS_EXPR)
16674 core = TREE_OPERAND (exp, 0);
16675 STRIP_NOPS (core);
16676 *pbitpos = 0;
16677 *poffset = TREE_OPERAND (exp, 1);
16678 if (poly_int_tree_p (*poffset))
16680 poly_offset_int tem
16681 = wi::sext (wi::to_poly_offset (*poffset),
16682 TYPE_PRECISION (TREE_TYPE (*poffset)));
16683 tem <<= LOG2_BITS_PER_UNIT;
16684 if (tem.to_shwi (pbitpos))
16685 *poffset = NULL_TREE;
16688 else
16690 core = exp;
16691 *pbitpos = 0;
16692 *poffset = NULL_TREE;
16695 return core;
16698 /* Returns true if addresses of E1 and E2 differ by a constant, false
16699 otherwise. If they do, E1 - E2 is stored in *DIFF. */
16701 bool
16702 ptr_difference_const (tree e1, tree e2, poly_int64 *diff)
16704 tree core1, core2;
16705 poly_int64 bitpos1, bitpos2;
16706 tree toffset1, toffset2, tdiff, type;
16708 core1 = split_address_to_core_and_offset (e1, &bitpos1, &toffset1);
16709 core2 = split_address_to_core_and_offset (e2, &bitpos2, &toffset2);
16711 poly_int64 bytepos1, bytepos2;
16712 if (!multiple_p (bitpos1, BITS_PER_UNIT, &bytepos1)
16713 || !multiple_p (bitpos2, BITS_PER_UNIT, &bytepos2)
16714 || !operand_equal_p (core1, core2, 0))
16715 return false;
16717 if (toffset1 && toffset2)
16719 type = TREE_TYPE (toffset1);
16720 if (type != TREE_TYPE (toffset2))
16721 toffset2 = fold_convert (type, toffset2);
16723 tdiff = fold_build2 (MINUS_EXPR, type, toffset1, toffset2);
16724 if (!cst_and_fits_in_hwi (tdiff))
16725 return false;
16727 *diff = int_cst_value (tdiff);
16729 else if (toffset1 || toffset2)
16731 /* If only one of the offsets is non-constant, the difference cannot
16732 be a constant. */
16733 return false;
16735 else
16736 *diff = 0;
16738 *diff += bytepos1 - bytepos2;
16739 return true;
16742 /* Return OFF converted to a pointer offset type suitable as offset for
16743 POINTER_PLUS_EXPR. Use location LOC for this conversion. */
16744 tree
16745 convert_to_ptrofftype_loc (location_t loc, tree off)
16747 if (ptrofftype_p (TREE_TYPE (off)))
16748 return off;
16749 return fold_convert_loc (loc, sizetype, off);
16752 /* Build and fold a POINTER_PLUS_EXPR at LOC offsetting PTR by OFF. */
16753 tree
16754 fold_build_pointer_plus_loc (location_t loc, tree ptr, tree off)
16756 return fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (ptr),
16757 ptr, convert_to_ptrofftype_loc (loc, off));
16760 /* Build and fold a POINTER_PLUS_EXPR at LOC offsetting PTR by OFF. */
16761 tree
16762 fold_build_pointer_plus_hwi_loc (location_t loc, tree ptr, HOST_WIDE_INT off)
16764 return fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (ptr),
16765 ptr, size_int (off));
16768 /* Return a pointer to a NUL-terminated string containing the sequence
16769 of bytes corresponding to the representation of the object referred to
16770 by SRC (or a subsequence of such bytes within it if SRC is a reference
16771 to an initialized constant array plus some constant offset).
16772 Set *STRSIZE the number of bytes in the constant sequence including
16773 the terminating NUL byte. *STRSIZE is equal to sizeof(A) - OFFSET
16774 where A is the array that stores the constant sequence that SRC points
16775 to and OFFSET is the byte offset of SRC from the beginning of A. SRC
16776 need not point to a string or even an array of characters but may point
16777 to an object of any type. */
16779 const char *
16780 getbyterep (tree src, unsigned HOST_WIDE_INT *strsize)
16782 /* The offset into the array A storing the string, and A's byte size. */
16783 tree offset_node;
16784 tree mem_size;
16786 if (strsize)
16787 *strsize = 0;
16789 if (strsize)
16790 src = byte_representation (src, &offset_node, &mem_size, NULL);
16791 else
16792 src = string_constant (src, &offset_node, &mem_size, NULL);
16793 if (!src)
16794 return NULL;
16796 unsigned HOST_WIDE_INT offset = 0;
16797 if (offset_node != NULL_TREE)
16799 if (!tree_fits_uhwi_p (offset_node))
16800 return NULL;
16801 else
16802 offset = tree_to_uhwi (offset_node);
16805 if (!tree_fits_uhwi_p (mem_size))
16806 return NULL;
16808 /* ARRAY_SIZE is the byte size of the array the constant sequence
16809 is stored in and equal to sizeof A. INIT_BYTES is the number
16810 of bytes in the constant sequence used to initialize the array,
16811 including any embedded NULs as well as the terminating NUL (for
16812 strings), but not including any trailing zeros/NULs past
16813 the terminating one appended implicitly to a string literal to
16814 zero out the remainder of the array it's stored in. For example,
16815 given:
16816 const char a[7] = "abc\0d";
16817 n = strlen (a + 1);
16818 ARRAY_SIZE is 7, INIT_BYTES is 6, and OFFSET is 1. For a valid
16819 (i.e., nul-terminated) string with no embedded nuls, INIT_BYTES
16820 is equal to strlen (A) + 1. */
16821 const unsigned HOST_WIDE_INT array_size = tree_to_uhwi (mem_size);
16822 unsigned HOST_WIDE_INT init_bytes = TREE_STRING_LENGTH (src);
16823 const char *string = TREE_STRING_POINTER (src);
16825 /* Ideally this would turn into a gcc_checking_assert over time. */
16826 if (init_bytes > array_size)
16827 init_bytes = array_size;
16829 if (init_bytes == 0 || offset >= array_size)
16830 return NULL;
16832 if (strsize)
16834 /* Compute and store the number of characters from the beginning
16835 of the substring at OFFSET to the end, including the terminating
16836 nul. Offsets past the initial length refer to null strings. */
16837 if (offset < init_bytes)
16838 *strsize = init_bytes - offset;
16839 else
16840 *strsize = 1;
16842 else
16844 tree eltype = TREE_TYPE (TREE_TYPE (src));
16845 /* Support only properly NUL-terminated single byte strings. */
16846 if (tree_to_uhwi (TYPE_SIZE_UNIT (eltype)) != 1)
16847 return NULL;
16848 if (string[init_bytes - 1] != '\0')
16849 return NULL;
16852 return offset < init_bytes ? string + offset : "";
16855 /* Return a pointer to a NUL-terminated string corresponding to
16856 the expression STR referencing a constant string, possibly
16857 involving a constant offset. Return null if STR either doesn't
16858 reference a constant string or if it involves a nonconstant
16859 offset. */
16861 const char *
16862 c_getstr (tree str)
16864 return getbyterep (str, NULL);
16867 /* Given a tree T, compute which bits in T may be nonzero. */
16869 wide_int
16870 tree_nonzero_bits (const_tree t)
16872 switch (TREE_CODE (t))
16874 case INTEGER_CST:
16875 return wi::to_wide (t);
16876 case SSA_NAME:
16877 return get_nonzero_bits (t);
16878 case NON_LVALUE_EXPR:
16879 case SAVE_EXPR:
16880 return tree_nonzero_bits (TREE_OPERAND (t, 0));
16881 case BIT_AND_EXPR:
16882 return wi::bit_and (tree_nonzero_bits (TREE_OPERAND (t, 0)),
16883 tree_nonzero_bits (TREE_OPERAND (t, 1)));
16884 case BIT_IOR_EXPR:
16885 case BIT_XOR_EXPR:
16886 return wi::bit_or (tree_nonzero_bits (TREE_OPERAND (t, 0)),
16887 tree_nonzero_bits (TREE_OPERAND (t, 1)));
16888 case COND_EXPR:
16889 return wi::bit_or (tree_nonzero_bits (TREE_OPERAND (t, 1)),
16890 tree_nonzero_bits (TREE_OPERAND (t, 2)));
16891 CASE_CONVERT:
16892 return wide_int::from (tree_nonzero_bits (TREE_OPERAND (t, 0)),
16893 TYPE_PRECISION (TREE_TYPE (t)),
16894 TYPE_SIGN (TREE_TYPE (TREE_OPERAND (t, 0))));
16895 case PLUS_EXPR:
16896 if (INTEGRAL_TYPE_P (TREE_TYPE (t)))
16898 wide_int nzbits1 = tree_nonzero_bits (TREE_OPERAND (t, 0));
16899 wide_int nzbits2 = tree_nonzero_bits (TREE_OPERAND (t, 1));
16900 if (wi::bit_and (nzbits1, nzbits2) == 0)
16901 return wi::bit_or (nzbits1, nzbits2);
16903 break;
16904 case LSHIFT_EXPR:
16905 if (TREE_CODE (TREE_OPERAND (t, 1)) == INTEGER_CST)
16907 tree type = TREE_TYPE (t);
16908 wide_int nzbits = tree_nonzero_bits (TREE_OPERAND (t, 0));
16909 wide_int arg1 = wi::to_wide (TREE_OPERAND (t, 1),
16910 TYPE_PRECISION (type));
16911 return wi::neg_p (arg1)
16912 ? wi::rshift (nzbits, -arg1, TYPE_SIGN (type))
16913 : wi::lshift (nzbits, arg1);
16915 break;
16916 case RSHIFT_EXPR:
16917 if (TREE_CODE (TREE_OPERAND (t, 1)) == INTEGER_CST)
16919 tree type = TREE_TYPE (t);
16920 wide_int nzbits = tree_nonzero_bits (TREE_OPERAND (t, 0));
16921 wide_int arg1 = wi::to_wide (TREE_OPERAND (t, 1),
16922 TYPE_PRECISION (type));
16923 return wi::neg_p (arg1)
16924 ? wi::lshift (nzbits, -arg1)
16925 : wi::rshift (nzbits, arg1, TYPE_SIGN (type));
16927 break;
16928 default:
16929 break;
16932 return wi::shwi (-1, TYPE_PRECISION (TREE_TYPE (t)));
16935 /* Helper function for address compare simplifications in match.pd.
16936 OP0 and OP1 are ADDR_EXPR operands being compared by CODE.
16937 TYPE is the type of comparison operands.
16938 BASE0, BASE1, OFF0 and OFF1 are set by the function.
16939 GENERIC is true if GENERIC folding and false for GIMPLE folding.
16940 Returns 0 if OP0 is known to be unequal to OP1 regardless of OFF{0,1},
16941 1 if bases are known to be equal and OP0 cmp OP1 depends on OFF0 cmp OFF1,
16942 and 2 if unknown. */
16945 address_compare (tree_code code, tree type, tree op0, tree op1,
16946 tree &base0, tree &base1, poly_int64 &off0, poly_int64 &off1,
16947 bool generic)
16949 if (TREE_CODE (op0) == SSA_NAME)
16950 op0 = gimple_assign_rhs1 (SSA_NAME_DEF_STMT (op0));
16951 if (TREE_CODE (op1) == SSA_NAME)
16952 op1 = gimple_assign_rhs1 (SSA_NAME_DEF_STMT (op1));
16953 gcc_checking_assert (TREE_CODE (op0) == ADDR_EXPR);
16954 gcc_checking_assert (TREE_CODE (op1) == ADDR_EXPR);
16955 base0 = get_addr_base_and_unit_offset (TREE_OPERAND (op0, 0), &off0);
16956 base1 = get_addr_base_and_unit_offset (TREE_OPERAND (op1, 0), &off1);
16957 if (base0 && TREE_CODE (base0) == MEM_REF)
16959 off0 += mem_ref_offset (base0).force_shwi ();
16960 base0 = TREE_OPERAND (base0, 0);
16962 if (base1 && TREE_CODE (base1) == MEM_REF)
16964 off1 += mem_ref_offset (base1).force_shwi ();
16965 base1 = TREE_OPERAND (base1, 0);
16967 if (base0 == NULL_TREE || base1 == NULL_TREE)
16968 return 2;
16970 int equal = 2;
16971 /* Punt in GENERIC on variables with value expressions;
16972 the value expressions might point to fields/elements
16973 of other vars etc. */
16974 if (generic
16975 && ((VAR_P (base0) && DECL_HAS_VALUE_EXPR_P (base0))
16976 || (VAR_P (base1) && DECL_HAS_VALUE_EXPR_P (base1))))
16977 return 2;
16978 else if (decl_in_symtab_p (base0) && decl_in_symtab_p (base1))
16980 symtab_node *node0 = symtab_node::get_create (base0);
16981 symtab_node *node1 = symtab_node::get_create (base1);
16982 equal = node0->equal_address_to (node1);
16984 else if ((DECL_P (base0)
16985 || TREE_CODE (base0) == SSA_NAME
16986 || TREE_CODE (base0) == STRING_CST)
16987 && (DECL_P (base1)
16988 || TREE_CODE (base1) == SSA_NAME
16989 || TREE_CODE (base1) == STRING_CST))
16990 equal = (base0 == base1);
16991 /* Assume different STRING_CSTs with the same content will be
16992 merged. */
16993 if (equal == 0
16994 && TREE_CODE (base0) == STRING_CST
16995 && TREE_CODE (base1) == STRING_CST
16996 && TREE_STRING_LENGTH (base0) == TREE_STRING_LENGTH (base1)
16997 && memcmp (TREE_STRING_POINTER (base0), TREE_STRING_POINTER (base1),
16998 TREE_STRING_LENGTH (base0)) == 0)
16999 equal = 1;
17000 if (equal == 1)
17002 if (code == EQ_EXPR
17003 || code == NE_EXPR
17004 /* If the offsets are equal we can ignore overflow. */
17005 || known_eq (off0, off1)
17006 || TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (op0))
17007 /* Or if we compare using pointers to decls or strings. */
17008 || (POINTER_TYPE_P (type)
17009 && (DECL_P (base0) || TREE_CODE (base0) == STRING_CST)))
17010 return 1;
17011 return 2;
17013 if (equal != 0)
17014 return equal;
17015 if (code != EQ_EXPR && code != NE_EXPR)
17016 return 2;
17018 /* At this point we know (or assume) the two pointers point at
17019 different objects. */
17020 HOST_WIDE_INT ioff0 = -1, ioff1 = -1;
17021 off0.is_constant (&ioff0);
17022 off1.is_constant (&ioff1);
17023 /* Punt on non-zero offsets from functions. */
17024 if ((TREE_CODE (base0) == FUNCTION_DECL && ioff0)
17025 || (TREE_CODE (base1) == FUNCTION_DECL && ioff1))
17026 return 2;
17027 /* Or if the bases are neither decls nor string literals. */
17028 if (!DECL_P (base0) && TREE_CODE (base0) != STRING_CST)
17029 return 2;
17030 if (!DECL_P (base1) && TREE_CODE (base1) != STRING_CST)
17031 return 2;
17032 /* For initializers, assume addresses of different functions are
17033 different. */
17034 if (folding_initializer
17035 && TREE_CODE (base0) == FUNCTION_DECL
17036 && TREE_CODE (base1) == FUNCTION_DECL)
17037 return 0;
17039 /* Compute whether one address points to the start of one
17040 object and another one to the end of another one. */
17041 poly_int64 size0 = 0, size1 = 0;
17042 if (TREE_CODE (base0) == STRING_CST)
17044 if (ioff0 < 0 || ioff0 > TREE_STRING_LENGTH (base0))
17045 equal = 2;
17046 else
17047 size0 = TREE_STRING_LENGTH (base0);
17049 else if (TREE_CODE (base0) == FUNCTION_DECL)
17050 size0 = 1;
17051 else
17053 tree sz0 = DECL_SIZE_UNIT (base0);
17054 if (!tree_fits_poly_int64_p (sz0))
17055 equal = 2;
17056 else
17057 size0 = tree_to_poly_int64 (sz0);
17059 if (TREE_CODE (base1) == STRING_CST)
17061 if (ioff1 < 0 || ioff1 > TREE_STRING_LENGTH (base1))
17062 equal = 2;
17063 else
17064 size1 = TREE_STRING_LENGTH (base1);
17066 else if (TREE_CODE (base1) == FUNCTION_DECL)
17067 size1 = 1;
17068 else
17070 tree sz1 = DECL_SIZE_UNIT (base1);
17071 if (!tree_fits_poly_int64_p (sz1))
17072 equal = 2;
17073 else
17074 size1 = tree_to_poly_int64 (sz1);
17076 if (equal == 0)
17078 /* If one offset is pointing (or could be) to the beginning of one
17079 object and the other is pointing to one past the last byte of the
17080 other object, punt. */
17081 if (maybe_eq (off0, 0) && maybe_eq (off1, size1))
17082 equal = 2;
17083 else if (maybe_eq (off1, 0) && maybe_eq (off0, size0))
17084 equal = 2;
17085 /* If both offsets are the same, there are some cases we know that are
17086 ok. Either if we know they aren't zero, or if we know both sizes
17087 are no zero. */
17088 if (equal == 2
17089 && known_eq (off0, off1)
17090 && (known_ne (off0, 0)
17091 || (known_ne (size0, 0) && known_ne (size1, 0))))
17092 equal = 0;
17095 /* At this point, equal is 2 if either one or both pointers are out of
17096 bounds of their object, or one points to start of its object and the
17097 other points to end of its object. This is unspecified behavior
17098 e.g. in C++. Otherwise equal is 0. */
17099 if (folding_cxx_constexpr && equal)
17100 return equal;
17102 /* When both pointers point to string literals, even when equal is 0,
17103 due to tail merging of string literals the pointers might be the same. */
17104 if (TREE_CODE (base0) == STRING_CST && TREE_CODE (base1) == STRING_CST)
17106 if (ioff0 < 0
17107 || ioff1 < 0
17108 || ioff0 > TREE_STRING_LENGTH (base0)
17109 || ioff1 > TREE_STRING_LENGTH (base1))
17110 return 2;
17112 /* If the bytes in the string literals starting at the pointers
17113 differ, the pointers need to be different. */
17114 if (memcmp (TREE_STRING_POINTER (base0) + ioff0,
17115 TREE_STRING_POINTER (base1) + ioff1,
17116 MIN (TREE_STRING_LENGTH (base0) - ioff0,
17117 TREE_STRING_LENGTH (base1) - ioff1)) == 0)
17119 HOST_WIDE_INT ioffmin = MIN (ioff0, ioff1);
17120 if (memcmp (TREE_STRING_POINTER (base0) + ioff0 - ioffmin,
17121 TREE_STRING_POINTER (base1) + ioff1 - ioffmin,
17122 ioffmin) == 0)
17123 /* If even the bytes in the string literal before the
17124 pointers are the same, the string literals could be
17125 tail merged. */
17126 return 2;
17128 return 0;
17131 if (folding_cxx_constexpr)
17132 return 0;
17134 /* If this is a pointer comparison, ignore for now even
17135 valid equalities where one pointer is the offset zero
17136 of one object and the other to one past end of another one. */
17137 if (!INTEGRAL_TYPE_P (type))
17138 return 0;
17140 /* Assume that string literals can't be adjacent to variables
17141 (automatic or global). */
17142 if (TREE_CODE (base0) == STRING_CST || TREE_CODE (base1) == STRING_CST)
17143 return 0;
17145 /* Assume that automatic variables can't be adjacent to global
17146 variables. */
17147 if (is_global_var (base0) != is_global_var (base1))
17148 return 0;
17150 return equal;
17153 /* Return the single non-zero element of a CONSTRUCTOR or NULL_TREE. */
17154 tree
17155 ctor_single_nonzero_element (const_tree t)
17157 unsigned HOST_WIDE_INT idx;
17158 constructor_elt *ce;
17159 tree elt = NULL_TREE;
17161 if (TREE_CODE (t) != CONSTRUCTOR)
17162 return NULL_TREE;
17163 for (idx = 0; vec_safe_iterate (CONSTRUCTOR_ELTS (t), idx, &ce); idx++)
17164 if (!integer_zerop (ce->value) && !real_zerop (ce->value))
17166 if (elt)
17167 return NULL_TREE;
17168 elt = ce->value;
17170 return elt;
17173 #if CHECKING_P
17175 namespace selftest {
17177 /* Helper functions for writing tests of folding trees. */
17179 /* Verify that the binary op (LHS CODE RHS) folds to CONSTANT. */
17181 static void
17182 assert_binop_folds_to_const (tree lhs, enum tree_code code, tree rhs,
17183 tree constant)
17185 ASSERT_EQ (constant, fold_build2 (code, TREE_TYPE (lhs), lhs, rhs));
17188 /* Verify that the binary op (LHS CODE RHS) folds to an NON_LVALUE_EXPR
17189 wrapping WRAPPED_EXPR. */
17191 static void
17192 assert_binop_folds_to_nonlvalue (tree lhs, enum tree_code code, tree rhs,
17193 tree wrapped_expr)
17195 tree result = fold_build2 (code, TREE_TYPE (lhs), lhs, rhs);
17196 ASSERT_NE (wrapped_expr, result);
17197 ASSERT_EQ (NON_LVALUE_EXPR, TREE_CODE (result));
17198 ASSERT_EQ (wrapped_expr, TREE_OPERAND (result, 0));
17201 /* Verify that various arithmetic binary operations are folded
17202 correctly. */
17204 static void
17205 test_arithmetic_folding ()
17207 tree type = integer_type_node;
17208 tree x = create_tmp_var_raw (type, "x");
17209 tree zero = build_zero_cst (type);
17210 tree one = build_int_cst (type, 1);
17212 /* Addition. */
17213 /* 1 <-- (0 + 1) */
17214 assert_binop_folds_to_const (zero, PLUS_EXPR, one,
17215 one);
17216 assert_binop_folds_to_const (one, PLUS_EXPR, zero,
17217 one);
17219 /* (nonlvalue)x <-- (x + 0) */
17220 assert_binop_folds_to_nonlvalue (x, PLUS_EXPR, zero,
17223 /* Subtraction. */
17224 /* 0 <-- (x - x) */
17225 assert_binop_folds_to_const (x, MINUS_EXPR, x,
17226 zero);
17227 assert_binop_folds_to_nonlvalue (x, MINUS_EXPR, zero,
17230 /* Multiplication. */
17231 /* 0 <-- (x * 0) */
17232 assert_binop_folds_to_const (x, MULT_EXPR, zero,
17233 zero);
17235 /* (nonlvalue)x <-- (x * 1) */
17236 assert_binop_folds_to_nonlvalue (x, MULT_EXPR, one,
17240 namespace test_fold_vec_perm_cst {
17242 /* Build a VECTOR_CST corresponding to VMODE, and has
17243 encoding given by NPATTERNS, NELTS_PER_PATTERN and STEP.
17244 Fill it with randomized elements, using rand() % THRESHOLD. */
17246 static tree
17247 build_vec_cst_rand (machine_mode vmode, unsigned npatterns,
17248 unsigned nelts_per_pattern,
17249 int step = 0, bool natural_stepped = false,
17250 int threshold = 100)
17252 tree inner_type = lang_hooks.types.type_for_mode (GET_MODE_INNER (vmode), 1);
17253 tree vectype = build_vector_type_for_mode (inner_type, vmode);
17254 tree_vector_builder builder (vectype, npatterns, nelts_per_pattern);
17256 // Fill a0 for each pattern
17257 for (unsigned i = 0; i < npatterns; i++)
17258 builder.quick_push (build_int_cst (inner_type, rand () % threshold));
17260 if (nelts_per_pattern == 1)
17261 return builder.build ();
17263 // Fill a1 for each pattern
17264 for (unsigned i = 0; i < npatterns; i++)
17266 tree a1;
17267 if (natural_stepped)
17269 tree a0 = builder[i];
17270 wide_int a0_val = wi::to_wide (a0);
17271 wide_int a1_val = a0_val + step;
17272 a1 = wide_int_to_tree (inner_type, a1_val);
17274 else
17275 a1 = build_int_cst (inner_type, rand () % threshold);
17276 builder.quick_push (a1);
17278 if (nelts_per_pattern == 2)
17279 return builder.build ();
17281 for (unsigned i = npatterns * 2; i < npatterns * nelts_per_pattern; i++)
17283 tree prev_elem = builder[i - npatterns];
17284 wide_int prev_elem_val = wi::to_wide (prev_elem);
17285 wide_int val = prev_elem_val + step;
17286 builder.quick_push (wide_int_to_tree (inner_type, val));
17289 return builder.build ();
17292 /* Validate result of VEC_PERM_EXPR folding for the unit-tests below,
17293 when result is VLA. */
17295 static void
17296 validate_res (unsigned npatterns, unsigned nelts_per_pattern,
17297 tree res, tree *expected_res)
17299 /* Actual npatterns and encoded_elts in res may be less than expected due
17300 to canonicalization. */
17301 ASSERT_TRUE (res != NULL_TREE);
17302 ASSERT_TRUE (VECTOR_CST_NPATTERNS (res) <= npatterns);
17303 ASSERT_TRUE (vector_cst_encoded_nelts (res) <= npatterns * nelts_per_pattern);
17305 for (unsigned i = 0; i < npatterns * nelts_per_pattern; i++)
17306 ASSERT_TRUE (operand_equal_p (VECTOR_CST_ELT (res, i), expected_res[i], 0));
17309 /* Validate result of VEC_PERM_EXPR folding for the unit-tests below,
17310 when the result is VLS. */
17312 static void
17313 validate_res_vls (tree res, tree *expected_res, unsigned expected_nelts)
17315 ASSERT_TRUE (known_eq (VECTOR_CST_NELTS (res), expected_nelts));
17316 for (unsigned i = 0; i < expected_nelts; i++)
17317 ASSERT_TRUE (operand_equal_p (VECTOR_CST_ELT (res, i), expected_res[i], 0));
17320 /* Helper routine to push multiple elements into BUILDER. */
17321 template<unsigned N>
17322 static void builder_push_elems (vec_perm_builder& builder,
17323 poly_uint64 (&elems)[N])
17325 for (unsigned i = 0; i < N; i++)
17326 builder.quick_push (elems[i]);
17329 #define ARG0(index) vector_cst_elt (arg0, index)
17330 #define ARG1(index) vector_cst_elt (arg1, index)
17332 /* Test cases where result is VNx4SI and input vectors are V4SI. */
17334 static void
17335 test_vnx4si_v4si (machine_mode vnx4si_mode, machine_mode v4si_mode)
17337 for (int i = 0; i < 10; i++)
17339 /* Case 1:
17340 sel = { 0, 4, 1, 5, ... }
17341 res = { arg[0], arg1[0], arg0[1], arg1[1], ...} // (4, 1) */
17343 tree arg0 = build_vec_cst_rand (v4si_mode, 4, 1, 0);
17344 tree arg1 = build_vec_cst_rand (v4si_mode, 4, 1, 0);
17346 tree inner_type
17347 = lang_hooks.types.type_for_mode (GET_MODE_INNER (vnx4si_mode), 1);
17348 tree res_type = build_vector_type_for_mode (inner_type, vnx4si_mode);
17350 poly_uint64 res_len = TYPE_VECTOR_SUBPARTS (res_type);
17351 vec_perm_builder builder (res_len, 4, 1);
17352 poly_uint64 mask_elems[] = { 0, 4, 1, 5 };
17353 builder_push_elems (builder, mask_elems);
17355 vec_perm_indices sel (builder, 2, res_len);
17356 tree res = fold_vec_perm_cst (res_type, arg0, arg1, sel);
17358 tree expected_res[] = { ARG0(0), ARG1(0), ARG0(1), ARG1(1) };
17359 validate_res (4, 1, res, expected_res);
17362 /* Case 2: Same as case 1, but contains an out of bounds access which
17363 should wrap around.
17364 sel = {0, 8, 4, 12, ...} (4, 1)
17365 res = { arg0[0], arg0[0], arg1[0], arg1[0], ... } (4, 1). */
17367 tree arg0 = build_vec_cst_rand (v4si_mode, 4, 1, 0);
17368 tree arg1 = build_vec_cst_rand (v4si_mode, 4, 1, 0);
17370 tree inner_type
17371 = lang_hooks.types.type_for_mode (GET_MODE_INNER (vnx4si_mode), 1);
17372 tree res_type = build_vector_type_for_mode (inner_type, vnx4si_mode);
17374 poly_uint64 res_len = TYPE_VECTOR_SUBPARTS (res_type);
17375 vec_perm_builder builder (res_len, 4, 1);
17376 poly_uint64 mask_elems[] = { 0, 8, 4, 12 };
17377 builder_push_elems (builder, mask_elems);
17379 vec_perm_indices sel (builder, 2, res_len);
17380 tree res = fold_vec_perm_cst (res_type, arg0, arg1, sel);
17382 tree expected_res[] = { ARG0(0), ARG0(0), ARG1(0), ARG1(0) };
17383 validate_res (4, 1, res, expected_res);
17388 /* Test cases where result is V4SI and input vectors are VNx4SI. */
17390 static void
17391 test_v4si_vnx4si (machine_mode v4si_mode, machine_mode vnx4si_mode)
17393 for (int i = 0; i < 10; i++)
17395 /* Case 1:
17396 sel = { 0, 1, 2, 3}
17397 res = { arg0[0], arg0[1], arg0[2], arg0[3] }. */
17399 tree arg0 = build_vec_cst_rand (vnx4si_mode, 4, 1);
17400 tree arg1 = build_vec_cst_rand (vnx4si_mode, 4, 1);
17402 tree inner_type
17403 = lang_hooks.types.type_for_mode (GET_MODE_INNER (v4si_mode), 1);
17404 tree res_type = build_vector_type_for_mode (inner_type, v4si_mode);
17406 poly_uint64 res_len = TYPE_VECTOR_SUBPARTS (res_type);
17407 vec_perm_builder builder (res_len, 4, 1);
17408 poly_uint64 mask_elems[] = {0, 1, 2, 3};
17409 builder_push_elems (builder, mask_elems);
17411 vec_perm_indices sel (builder, 2, res_len);
17412 tree res = fold_vec_perm_cst (res_type, arg0, arg1, sel);
17414 tree expected_res[] = { ARG0(0), ARG0(1), ARG0(2), ARG0(3) };
17415 validate_res_vls (res, expected_res, 4);
17418 /* Case 2: Same as Case 1, but crossing input vector.
17419 sel = {0, 2, 4, 6}
17420 In this case,the index 4 is ambiguous since len = 4 + 4x.
17421 Since we cannot determine, which vector to choose from during
17422 compile time, should return NULL_TREE. */
17424 tree arg0 = build_vec_cst_rand (vnx4si_mode, 4, 1);
17425 tree arg1 = build_vec_cst_rand (vnx4si_mode, 4, 1);
17427 tree inner_type
17428 = lang_hooks.types.type_for_mode (GET_MODE_INNER (v4si_mode), 1);
17429 tree res_type = build_vector_type_for_mode (inner_type, v4si_mode);
17431 poly_uint64 res_len = TYPE_VECTOR_SUBPARTS (res_type);
17432 vec_perm_builder builder (res_len, 4, 1);
17433 poly_uint64 mask_elems[] = {0, 2, 4, 6};
17434 builder_push_elems (builder, mask_elems);
17436 vec_perm_indices sel (builder, 2, res_len);
17437 const char *reason;
17438 tree res = fold_vec_perm_cst (res_type, arg0, arg1, sel, &reason);
17440 ASSERT_TRUE (res == NULL_TREE);
17441 ASSERT_TRUE (!strcmp (reason, "cannot divide selector element by arg len"));
17446 /* Test all input vectors. */
17448 static void
17449 test_all_nunits (machine_mode vmode)
17451 /* Test with 10 different inputs. */
17452 for (int i = 0; i < 10; i++)
17454 tree arg0 = build_vec_cst_rand (vmode, 1, 3, 1);
17455 tree arg1 = build_vec_cst_rand (vmode, 1, 3, 1);
17456 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17458 /* Case 1: mask = {0, ...} // (1, 1)
17459 res = { arg0[0], ... } // (1, 1) */
17461 vec_perm_builder builder (len, 1, 1);
17462 builder.quick_push (0);
17463 vec_perm_indices sel (builder, 2, len);
17464 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17465 tree expected_res[] = { ARG0(0) };
17466 validate_res (1, 1, res, expected_res);
17469 /* Case 2: mask = {len, ...} // (1, 1)
17470 res = { arg1[0], ... } // (1, 1) */
17472 vec_perm_builder builder (len, 1, 1);
17473 builder.quick_push (len);
17474 vec_perm_indices sel (builder, 2, len);
17475 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17477 tree expected_res[] = { ARG1(0) };
17478 validate_res (1, 1, res, expected_res);
17483 /* Test all vectors which contain at-least 2 elements. */
17485 static void
17486 test_nunits_min_2 (machine_mode vmode)
17488 for (int i = 0; i < 10; i++)
17490 /* Case 1: mask = { 0, len, ... } // (2, 1)
17491 res = { arg0[0], arg1[0], ... } // (2, 1) */
17493 tree arg0 = build_vec_cst_rand (vmode, 1, 3, 1);
17494 tree arg1 = build_vec_cst_rand (vmode, 1, 3, 1);
17495 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17497 vec_perm_builder builder (len, 2, 1);
17498 poly_uint64 mask_elems[] = { 0, len };
17499 builder_push_elems (builder, mask_elems);
17501 vec_perm_indices sel (builder, 2, len);
17502 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17504 tree expected_res[] = { ARG0(0), ARG1(0) };
17505 validate_res (2, 1, res, expected_res);
17508 /* Case 2: mask = { 0, len, 1, len+1, ... } // (2, 2)
17509 res = { arg0[0], arg1[0], arg0[1], arg1[1], ... } // (2, 2) */
17511 tree arg0 = build_vec_cst_rand (vmode, 1, 3, 1);
17512 tree arg1 = build_vec_cst_rand (vmode, 1, 3, 1);
17513 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17515 vec_perm_builder builder (len, 2, 2);
17516 poly_uint64 mask_elems[] = { 0, len, 1, len + 1 };
17517 builder_push_elems (builder, mask_elems);
17519 vec_perm_indices sel (builder, 2, len);
17520 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17522 tree expected_res[] = { ARG0(0), ARG1(0), ARG0(1), ARG1(1) };
17523 validate_res (2, 2, res, expected_res);
17526 /* Case 4: mask = {0, 0, 1, ...} // (1, 3)
17527 Test that the stepped sequence of the pattern selects from
17528 same input pattern. Since input vectors have npatterns = 2,
17529 and step (a2 - a1) = 1, step is not a multiple of npatterns
17530 in input vector. So return NULL_TREE. */
17532 tree arg0 = build_vec_cst_rand (vmode, 2, 3, 1, true);
17533 tree arg1 = build_vec_cst_rand (vmode, 2, 3, 1);
17534 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17536 vec_perm_builder builder (len, 1, 3);
17537 poly_uint64 mask_elems[] = { 0, 0, 1 };
17538 builder_push_elems (builder, mask_elems);
17540 vec_perm_indices sel (builder, 2, len);
17541 const char *reason;
17542 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel,
17543 &reason);
17544 ASSERT_TRUE (res == NULL_TREE);
17545 ASSERT_TRUE (!strcmp (reason, "step is not multiple of npatterns"));
17548 /* Case 5: mask = {len, 0, 1, ...} // (1, 3)
17549 Test that stepped sequence of the pattern selects from arg0.
17550 res = { arg1[0], arg0[0], arg0[1], ... } // (1, 3) */
17552 tree arg0 = build_vec_cst_rand (vmode, 1, 3, 1, true);
17553 tree arg1 = build_vec_cst_rand (vmode, 1, 3, 1);
17554 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17556 vec_perm_builder builder (len, 1, 3);
17557 poly_uint64 mask_elems[] = { len, 0, 1 };
17558 builder_push_elems (builder, mask_elems);
17560 vec_perm_indices sel (builder, 2, len);
17561 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17563 tree expected_res[] = { ARG1(0), ARG0(0), ARG0(1) };
17564 validate_res (1, 3, res, expected_res);
17567 /* Case 6: PR111648 - a1 chooses base element from input vector arg.
17568 In this case ensure that arg has a natural stepped sequence
17569 to preserve arg's encoding.
17571 As a concrete example, consider:
17572 arg0: { -16, -9, -10, ... } // (1, 3)
17573 arg1: { -12, -5, -6, ... } // (1, 3)
17574 sel = { 0, len, len + 1, ... } // (1, 3)
17576 This will create res with following encoding:
17577 res = { arg0[0], arg1[0], arg1[1], ... } // (1, 3)
17578 = { -16, -12, -5, ... }
17580 The step in above encoding would be: (-5) - (-12) = 7
17581 And hence res[3] would be computed as -5 + 7 = 2.
17582 instead of arg1[2], ie, -6.
17583 Ensure that valid_mask_for_fold_vec_perm_cst returns false
17584 for this case. */
17586 tree arg0 = build_vec_cst_rand (vmode, 1, 3, 1);
17587 tree arg1 = build_vec_cst_rand (vmode, 1, 3, 1);
17588 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17590 vec_perm_builder builder (len, 1, 3);
17591 poly_uint64 mask_elems[] = { 0, len, len+1 };
17592 builder_push_elems (builder, mask_elems);
17594 vec_perm_indices sel (builder, 2, len);
17595 const char *reason;
17596 /* FIXME: It may happen that build_vec_cst_rand may build a natural
17597 stepped pattern, even if we didn't explicitly tell it to. So folding
17598 may not always fail, but if it does, ensure that's because arg1 does
17599 not have a natural stepped sequence (and not due to other reason) */
17600 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel, &reason);
17601 if (res == NULL_TREE)
17602 ASSERT_TRUE (!strcmp (reason, "not a natural stepped sequence"));
17605 /* Case 7: Same as Case 6, except that arg1 contains natural stepped
17606 sequence and thus folding should be valid for this case. */
17608 tree arg0 = build_vec_cst_rand (vmode, 1, 3, 1);
17609 tree arg1 = build_vec_cst_rand (vmode, 1, 3, 1, true);
17610 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17612 vec_perm_builder builder (len, 1, 3);
17613 poly_uint64 mask_elems[] = { 0, len, len+1 };
17614 builder_push_elems (builder, mask_elems);
17616 vec_perm_indices sel (builder, 2, len);
17617 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17619 tree expected_res[] = { ARG0(0), ARG1(0), ARG1(1) };
17620 validate_res (1, 3, res, expected_res);
17623 /* Case 8: Same as aarch64/sve/slp_3.c:
17624 arg0, arg1 are dup vectors.
17625 sel = { 0, len, 1, len+1, 2, len+2, ... } // (2, 3)
17626 So res = { arg0[0], arg1[0], ... } // (2, 1)
17628 In this case, since the input vectors are dup, only the first two
17629 elements per pattern in sel are considered significant. */
17631 tree arg0 = build_vec_cst_rand (vmode, 1, 1);
17632 tree arg1 = build_vec_cst_rand (vmode, 1, 1);
17633 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17635 vec_perm_builder builder (len, 2, 3);
17636 poly_uint64 mask_elems[] = { 0, len, 1, len + 1, 2, len + 2 };
17637 builder_push_elems (builder, mask_elems);
17639 vec_perm_indices sel (builder, 2, len);
17640 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17642 tree expected_res[] = { ARG0(0), ARG1(0) };
17643 validate_res (2, 1, res, expected_res);
17648 /* Test all vectors which contain at-least 4 elements. */
17650 static void
17651 test_nunits_min_4 (machine_mode vmode)
17653 for (int i = 0; i < 10; i++)
17655 /* Case 1: mask = { 0, len, 1, len+1, ... } // (4, 1)
17656 res: { arg0[0], arg1[0], arg0[1], arg1[1], ... } // (4, 1) */
17658 tree arg0 = build_vec_cst_rand (vmode, 1, 3, 1);
17659 tree arg1 = build_vec_cst_rand (vmode, 1, 3, 1);
17660 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17662 vec_perm_builder builder (len, 4, 1);
17663 poly_uint64 mask_elems[] = { 0, len, 1, len + 1 };
17664 builder_push_elems (builder, mask_elems);
17666 vec_perm_indices sel (builder, 2, len);
17667 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17669 tree expected_res[] = { ARG0(0), ARG1(0), ARG0(1), ARG1(1) };
17670 validate_res (4, 1, res, expected_res);
17673 /* Case 2: sel = {0, 1, 2, ...} // (1, 3)
17674 res: { arg0[0], arg0[1], arg0[2], ... } // (1, 3) */
17676 tree arg0 = build_vec_cst_rand (vmode, 1, 3, 2);
17677 tree arg1 = build_vec_cst_rand (vmode, 1, 3, 2);
17678 poly_uint64 arg0_len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17680 vec_perm_builder builder (arg0_len, 1, 3);
17681 poly_uint64 mask_elems[] = {0, 1, 2};
17682 builder_push_elems (builder, mask_elems);
17684 vec_perm_indices sel (builder, 2, arg0_len);
17685 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17686 tree expected_res[] = { ARG0(0), ARG0(1), ARG0(2) };
17687 validate_res (1, 3, res, expected_res);
17690 /* Case 3: sel = {len, len+1, len+2, ...} // (1, 3)
17691 res: { arg1[0], arg1[1], arg1[2], ... } // (1, 3) */
17693 tree arg0 = build_vec_cst_rand (vmode, 1, 3, 2);
17694 tree arg1 = build_vec_cst_rand (vmode, 1, 3, 2);
17695 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17697 vec_perm_builder builder (len, 1, 3);
17698 poly_uint64 mask_elems[] = {len, len + 1, len + 2};
17699 builder_push_elems (builder, mask_elems);
17701 vec_perm_indices sel (builder, 2, len);
17702 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17703 tree expected_res[] = { ARG1(0), ARG1(1), ARG1(2) };
17704 validate_res (1, 3, res, expected_res);
17707 /* Case 4:
17708 sel = { len, 0, 2, ... } // (1, 3)
17709 This should return NULL because we cross the input vectors.
17710 Because,
17711 Let's assume len = C + Cx
17712 a1 = 0
17713 S = 2
17714 esel = arg0_len / sel_npatterns = C + Cx
17715 ae = 0 + (esel - 2) * S
17716 = 0 + (C + Cx - 2) * 2
17717 = 2(C-2) + 2Cx
17719 For C >= 4:
17720 Let q1 = a1 / arg0_len = 0 / (C + Cx) = 0
17721 Let qe = ae / arg0_len = (2(C-2) + 2Cx) / (C + Cx) = 1
17722 Since q1 != qe, we cross input vectors.
17723 So return NULL_TREE. */
17725 tree arg0 = build_vec_cst_rand (vmode, 1, 3, 2);
17726 tree arg1 = build_vec_cst_rand (vmode, 1, 3, 2);
17727 poly_uint64 arg0_len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17729 vec_perm_builder builder (arg0_len, 1, 3);
17730 poly_uint64 mask_elems[] = { arg0_len, 0, 2 };
17731 builder_push_elems (builder, mask_elems);
17733 vec_perm_indices sel (builder, 2, arg0_len);
17734 const char *reason;
17735 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel, &reason);
17736 ASSERT_TRUE (res == NULL_TREE);
17737 ASSERT_TRUE (!strcmp (reason, "crossed input vectors"));
17740 /* Case 5: npatterns(arg0) = 4 > npatterns(sel) = 2
17741 mask = { 0, len, 1, len + 1, ...} // (2, 2)
17742 res = { arg0[0], arg1[0], arg0[1], arg1[1], ... } // (2, 2)
17744 Note that fold_vec_perm_cst will set
17745 res_npatterns = max(4, max(4, 2)) = 4
17746 However after canonicalizing, we will end up with shape (2, 2). */
17748 tree arg0 = build_vec_cst_rand (vmode, 4, 1);
17749 tree arg1 = build_vec_cst_rand (vmode, 4, 1);
17750 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17752 vec_perm_builder builder (len, 2, 2);
17753 poly_uint64 mask_elems[] = { 0, len, 1, len + 1 };
17754 builder_push_elems (builder, mask_elems);
17756 vec_perm_indices sel (builder, 2, len);
17757 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17758 tree expected_res[] = { ARG0(0), ARG1(0), ARG0(1), ARG1(1) };
17759 validate_res (2, 2, res, expected_res);
17762 /* Case 6: Test combination in sel, where one pattern is dup and other
17763 is stepped sequence.
17764 sel = { 0, 0, 0, 1, 0, 2, ... } // (2, 3)
17765 res = { arg0[0], arg0[0], arg0[0],
17766 arg0[1], arg0[0], arg0[2], ... } // (2, 3) */
17768 tree arg0 = build_vec_cst_rand (vmode, 1, 3, 1);
17769 tree arg1 = build_vec_cst_rand (vmode, 1, 3, 1);
17770 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17772 vec_perm_builder builder (len, 2, 3);
17773 poly_uint64 mask_elems[] = { 0, 0, 0, 1, 0, 2 };
17774 builder_push_elems (builder, mask_elems);
17776 vec_perm_indices sel (builder, 2, len);
17777 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17779 tree expected_res[] = { ARG0(0), ARG0(0), ARG0(0),
17780 ARG0(1), ARG0(0), ARG0(2) };
17781 validate_res (2, 3, res, expected_res);
17784 /* Case 7: PR111048: Check that we set arg_npatterns correctly,
17785 when arg0, arg1 and sel have different number of patterns.
17786 arg0 is of shape (1, 1)
17787 arg1 is of shape (4, 1)
17788 sel is of shape (2, 3) = {1, len, 2, len+1, 3, len+2, ...}
17790 In this case the pattern: {len, len+1, len+2, ...} chooses arg1.
17791 However,
17792 step = (len+2) - (len+1) = 1
17793 arg_npatterns = VECTOR_CST_NPATTERNS (arg1) = 4
17794 Since step is not a multiple of arg_npatterns,
17795 valid_mask_for_fold_vec_perm_cst should return false,
17796 and thus fold_vec_perm_cst should return NULL_TREE. */
17798 tree arg0 = build_vec_cst_rand (vmode, 1, 1);
17799 tree arg1 = build_vec_cst_rand (vmode, 4, 1);
17800 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17802 vec_perm_builder builder (len, 2, 3);
17803 poly_uint64 mask_elems[] = { 0, len, 1, len + 1, 2, len + 2 };
17804 builder_push_elems (builder, mask_elems);
17806 vec_perm_indices sel (builder, 2, len);
17807 const char *reason;
17808 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel, &reason);
17810 ASSERT_TRUE (res == NULL_TREE);
17811 ASSERT_TRUE (!strcmp (reason, "step is not multiple of npatterns"));
17814 /* Case 8: PR111754: When input vector is not a stepped sequence,
17815 check that the result is not a stepped sequence either, even
17816 if sel has a stepped sequence. */
17818 tree arg0 = build_vec_cst_rand (vmode, 1, 2);
17819 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17821 vec_perm_builder builder (len, 1, 3);
17822 poly_uint64 mask_elems[] = { 0, 1, 2 };
17823 builder_push_elems (builder, mask_elems);
17825 vec_perm_indices sel (builder, 1, len);
17826 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg0, sel);
17828 tree expected_res[] = { ARG0(0), ARG0(1) };
17829 validate_res (sel.encoding ().npatterns (), 2, res, expected_res);
17832 /* Case 9: If sel doesn't contain a stepped sequence,
17833 check that the result has same encoding as sel, irrespective
17834 of shape of input vectors. */
17836 tree arg0 = build_vec_cst_rand (vmode, 1, 3, 1);
17837 tree arg1 = build_vec_cst_rand (vmode, 1, 3, 1);
17838 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17840 vec_perm_builder builder (len, 1, 2);
17841 poly_uint64 mask_elems[] = { 0, len };
17842 builder_push_elems (builder, mask_elems);
17844 vec_perm_indices sel (builder, 2, len);
17845 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17847 tree expected_res[] = { ARG0(0), ARG1(0) };
17848 validate_res (sel.encoding ().npatterns (),
17849 sel.encoding ().nelts_per_pattern (), res, expected_res);
17854 /* Test all vectors which contain at-least 8 elements. */
17856 static void
17857 test_nunits_min_8 (machine_mode vmode)
17859 for (int i = 0; i < 10; i++)
17861 /* Case 1: sel_npatterns (4) > input npatterns (2)
17862 sel: { 0, 0, 1, len, 2, 0, 3, len, 4, 0, 5, len, ...} // (4, 3)
17863 res: { arg0[0], arg0[0], arg0[0], arg1[0],
17864 arg0[2], arg0[0], arg0[3], arg1[0],
17865 arg0[4], arg0[0], arg0[5], arg1[0], ... } // (4, 3) */
17867 tree arg0 = build_vec_cst_rand (vmode, 2, 3, 2);
17868 tree arg1 = build_vec_cst_rand (vmode, 2, 3, 2);
17869 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17871 vec_perm_builder builder(len, 4, 3);
17872 poly_uint64 mask_elems[] = { 0, 0, 1, len, 2, 0, 3, len,
17873 4, 0, 5, len };
17874 builder_push_elems (builder, mask_elems);
17876 vec_perm_indices sel (builder, 2, len);
17877 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17879 tree expected_res[] = { ARG0(0), ARG0(0), ARG0(1), ARG1(0),
17880 ARG0(2), ARG0(0), ARG0(3), ARG1(0),
17881 ARG0(4), ARG0(0), ARG0(5), ARG1(0) };
17882 validate_res (4, 3, res, expected_res);
17887 /* Test vectors for which nunits[0] <= 4. */
17889 static void
17890 test_nunits_max_4 (machine_mode vmode)
17892 /* Case 1: mask = {0, 4, ...} // (1, 2)
17893 This should return NULL_TREE because the index 4 may choose
17894 from either arg0 or arg1 depending on vector length. */
17896 tree arg0 = build_vec_cst_rand (vmode, 1, 3, 1);
17897 tree arg1 = build_vec_cst_rand (vmode, 1, 3, 1);
17898 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17900 vec_perm_builder builder (len, 1, 2);
17901 poly_uint64 mask_elems[] = {0, 4};
17902 builder_push_elems (builder, mask_elems);
17904 vec_perm_indices sel (builder, 2, len);
17905 const char *reason;
17906 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel, &reason);
17907 ASSERT_TRUE (res == NULL_TREE);
17908 ASSERT_TRUE (reason != NULL);
17909 ASSERT_TRUE (!strcmp (reason, "cannot divide selector element by arg len"));
17913 #undef ARG0
17914 #undef ARG1
17916 /* Return true if SIZE is of the form C + Cx and C is power of 2. */
17918 static bool
17919 is_simple_vla_size (poly_uint64 size)
17921 if (size.is_constant ()
17922 || !pow2p_hwi (size.coeffs[0]))
17923 return false;
17924 for (unsigned i = 1; i < ARRAY_SIZE (size.coeffs); ++i)
17925 if (size.coeffs[i] != (i <= 1 ? size.coeffs[0] : 0))
17926 return false;
17927 return true;
17930 /* Execute fold_vec_perm_cst unit tests. */
17932 static void
17933 test ()
17935 machine_mode vnx4si_mode = E_VOIDmode;
17936 machine_mode v4si_mode = E_VOIDmode;
17938 machine_mode vmode;
17939 FOR_EACH_MODE_IN_CLASS (vmode, MODE_VECTOR_INT)
17941 /* Obtain modes corresponding to VNx4SI and V4SI,
17942 to call mixed mode tests below.
17943 FIXME: Is there a better way to do this ? */
17944 if (GET_MODE_INNER (vmode) == SImode)
17946 poly_uint64 nunits = GET_MODE_NUNITS (vmode);
17947 if (is_simple_vla_size (nunits)
17948 && nunits.coeffs[0] == 4)
17949 vnx4si_mode = vmode;
17950 else if (known_eq (nunits, poly_uint64 (4)))
17951 v4si_mode = vmode;
17954 if (!is_simple_vla_size (GET_MODE_NUNITS (vmode))
17955 || !targetm.vector_mode_supported_p (vmode))
17956 continue;
17958 poly_uint64 nunits = GET_MODE_NUNITS (vmode);
17959 test_all_nunits (vmode);
17960 if (nunits.coeffs[0] >= 2)
17961 test_nunits_min_2 (vmode);
17962 if (nunits.coeffs[0] >= 4)
17963 test_nunits_min_4 (vmode);
17964 if (nunits.coeffs[0] >= 8)
17965 test_nunits_min_8 (vmode);
17967 if (nunits.coeffs[0] <= 4)
17968 test_nunits_max_4 (vmode);
17971 if (vnx4si_mode != E_VOIDmode && v4si_mode != E_VOIDmode
17972 && targetm.vector_mode_supported_p (vnx4si_mode)
17973 && targetm.vector_mode_supported_p (v4si_mode))
17975 test_vnx4si_v4si (vnx4si_mode, v4si_mode);
17976 test_v4si_vnx4si (v4si_mode, vnx4si_mode);
17979 } // end of test_fold_vec_perm_cst namespace
17981 /* Verify that various binary operations on vectors are folded
17982 correctly. */
17984 static void
17985 test_vector_folding ()
17987 tree inner_type = integer_type_node;
17988 tree type = build_vector_type (inner_type, 4);
17989 tree zero = build_zero_cst (type);
17990 tree one = build_one_cst (type);
17991 tree index = build_index_vector (type, 0, 1);
17993 /* Verify equality tests that return a scalar boolean result. */
17994 tree res_type = boolean_type_node;
17995 ASSERT_FALSE (integer_nonzerop (fold_build2 (EQ_EXPR, res_type, zero, one)));
17996 ASSERT_TRUE (integer_nonzerop (fold_build2 (EQ_EXPR, res_type, zero, zero)));
17997 ASSERT_TRUE (integer_nonzerop (fold_build2 (NE_EXPR, res_type, zero, one)));
17998 ASSERT_FALSE (integer_nonzerop (fold_build2 (NE_EXPR, res_type, one, one)));
17999 ASSERT_TRUE (integer_nonzerop (fold_build2 (NE_EXPR, res_type, index, one)));
18000 ASSERT_FALSE (integer_nonzerop (fold_build2 (EQ_EXPR, res_type,
18001 index, one)));
18002 ASSERT_FALSE (integer_nonzerop (fold_build2 (NE_EXPR, res_type,
18003 index, index)));
18004 ASSERT_TRUE (integer_nonzerop (fold_build2 (EQ_EXPR, res_type,
18005 index, index)));
18008 /* Verify folding of VEC_DUPLICATE_EXPRs. */
18010 static void
18011 test_vec_duplicate_folding ()
18013 scalar_int_mode int_mode = SCALAR_INT_TYPE_MODE (ssizetype);
18014 machine_mode vec_mode = targetm.vectorize.preferred_simd_mode (int_mode);
18015 /* This will be 1 if VEC_MODE isn't a vector mode. */
18016 poly_uint64 nunits = GET_MODE_NUNITS (vec_mode);
18018 tree type = build_vector_type (ssizetype, nunits);
18019 tree dup5_expr = fold_unary (VEC_DUPLICATE_EXPR, type, ssize_int (5));
18020 tree dup5_cst = build_vector_from_val (type, ssize_int (5));
18021 ASSERT_TRUE (operand_equal_p (dup5_expr, dup5_cst, 0));
18024 /* Run all of the selftests within this file. */
18026 void
18027 fold_const_cc_tests ()
18029 test_arithmetic_folding ();
18030 test_vector_folding ();
18031 test_vec_duplicate_folding ();
18032 test_fold_vec_perm_cst::test ();
18035 } // namespace selftest
18037 #endif /* CHECKING_P */