xfail scan-tree-dump-not throw in g++.dg/pr99966.C on hppa*64*-*-*
[official-gcc.git] / gcc / fold-const.cc
blob385e4a69ab38d54e3f4ed8af31835e0cd91fa98a
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 || total_bytes * BITS_PER_UNIT > HOST_BITS_PER_DOUBLE_INT)
8778 return NULL_TREE;
8780 wide_int result = wi::from_buffer (ptr, total_bytes);
8782 return wide_int_to_tree (type, result);
8786 /* Subroutine of native_interpret_expr. Interpret the contents of
8787 the buffer PTR of length LEN as a FIXED_CST of type TYPE.
8788 If the buffer cannot be interpreted, return NULL_TREE. */
8790 static tree
8791 native_interpret_fixed (tree type, const unsigned char *ptr, int len)
8793 scalar_mode mode = SCALAR_TYPE_MODE (type);
8794 int total_bytes = GET_MODE_SIZE (mode);
8795 double_int result;
8796 FIXED_VALUE_TYPE fixed_value;
8798 if (total_bytes > len
8799 || total_bytes * BITS_PER_UNIT > HOST_BITS_PER_DOUBLE_INT)
8800 return NULL_TREE;
8802 result = double_int::from_buffer (ptr, total_bytes);
8803 fixed_value = fixed_from_double_int (result, mode);
8805 return build_fixed (type, fixed_value);
8809 /* Subroutine of native_interpret_expr. Interpret the contents of
8810 the buffer PTR of length LEN as a REAL_CST of type TYPE.
8811 If the buffer cannot be interpreted, return NULL_TREE. */
8813 tree
8814 native_interpret_real (tree type, const unsigned char *ptr, int len)
8816 scalar_float_mode mode = SCALAR_FLOAT_TYPE_MODE (type);
8817 int total_bytes = GET_MODE_SIZE (mode);
8818 unsigned char value;
8819 /* There are always 32 bits in each long, no matter the size of
8820 the hosts long. We handle floating point representations with
8821 up to 192 bits. */
8822 REAL_VALUE_TYPE r;
8823 long tmp[6];
8825 if (total_bytes > len || total_bytes > 24)
8826 return NULL_TREE;
8827 int words = (32 / BITS_PER_UNIT) / UNITS_PER_WORD;
8829 memset (tmp, 0, sizeof (tmp));
8830 for (int bitpos = 0; bitpos < total_bytes * BITS_PER_UNIT;
8831 bitpos += BITS_PER_UNIT)
8833 /* Both OFFSET and BYTE index within a long;
8834 bitpos indexes the whole float. */
8835 int offset, byte = (bitpos / BITS_PER_UNIT) & 3;
8836 if (UNITS_PER_WORD < 4)
8838 int word = byte / UNITS_PER_WORD;
8839 if (WORDS_BIG_ENDIAN)
8840 word = (words - 1) - word;
8841 offset = word * UNITS_PER_WORD;
8842 if (BYTES_BIG_ENDIAN)
8843 offset += (UNITS_PER_WORD - 1) - (byte % UNITS_PER_WORD);
8844 else
8845 offset += byte % UNITS_PER_WORD;
8847 else
8849 offset = byte;
8850 if (BYTES_BIG_ENDIAN)
8852 /* Reverse bytes within each long, or within the entire float
8853 if it's smaller than a long (for HFmode). */
8854 offset = MIN (3, total_bytes - 1) - offset;
8855 gcc_assert (offset >= 0);
8858 value = ptr[offset + ((bitpos / BITS_PER_UNIT) & ~3)];
8860 tmp[bitpos / 32] |= (unsigned long)value << (bitpos & 31);
8863 real_from_target (&r, tmp, mode);
8864 return build_real (type, r);
8868 /* Subroutine of native_interpret_expr. Interpret the contents of
8869 the buffer PTR of length LEN as a COMPLEX_CST of type TYPE.
8870 If the buffer cannot be interpreted, return NULL_TREE. */
8872 static tree
8873 native_interpret_complex (tree type, const unsigned char *ptr, int len)
8875 tree etype, rpart, ipart;
8876 int size;
8878 etype = TREE_TYPE (type);
8879 size = GET_MODE_SIZE (SCALAR_TYPE_MODE (etype));
8880 if (size * 2 > len)
8881 return NULL_TREE;
8882 rpart = native_interpret_expr (etype, ptr, size);
8883 if (!rpart)
8884 return NULL_TREE;
8885 ipart = native_interpret_expr (etype, ptr+size, size);
8886 if (!ipart)
8887 return NULL_TREE;
8888 return build_complex (type, rpart, ipart);
8891 /* Read a vector of type TYPE from the target memory image given by BYTES,
8892 which contains LEN bytes. The vector is known to be encodable using
8893 NPATTERNS interleaved patterns with NELTS_PER_PATTERN elements each.
8895 Return the vector on success, otherwise return null. */
8897 static tree
8898 native_interpret_vector_part (tree type, const unsigned char *bytes,
8899 unsigned int len, unsigned int npatterns,
8900 unsigned int nelts_per_pattern)
8902 tree elt_type = TREE_TYPE (type);
8903 if (VECTOR_BOOLEAN_TYPE_P (type)
8904 && TYPE_PRECISION (elt_type) <= BITS_PER_UNIT)
8906 /* This is the only case in which elements can be smaller than a byte.
8907 Element 0 is always in the lsb of the containing byte. */
8908 unsigned int elt_bits = TYPE_PRECISION (elt_type);
8909 if (elt_bits * npatterns * nelts_per_pattern > len * BITS_PER_UNIT)
8910 return NULL_TREE;
8912 tree_vector_builder builder (type, npatterns, nelts_per_pattern);
8913 for (unsigned int i = 0; i < builder.encoded_nelts (); ++i)
8915 unsigned int bit_index = i * elt_bits;
8916 unsigned int byte_index = bit_index / BITS_PER_UNIT;
8917 unsigned int lsb = bit_index % BITS_PER_UNIT;
8918 builder.quick_push (bytes[byte_index] & (1 << lsb)
8919 ? build_all_ones_cst (elt_type)
8920 : build_zero_cst (elt_type));
8922 return builder.build ();
8925 unsigned int elt_bytes = tree_to_uhwi (TYPE_SIZE_UNIT (elt_type));
8926 if (elt_bytes * npatterns * nelts_per_pattern > len)
8927 return NULL_TREE;
8929 tree_vector_builder builder (type, npatterns, nelts_per_pattern);
8930 for (unsigned int i = 0; i < builder.encoded_nelts (); ++i)
8932 tree elt = native_interpret_expr (elt_type, bytes, elt_bytes);
8933 if (!elt)
8934 return NULL_TREE;
8935 builder.quick_push (elt);
8936 bytes += elt_bytes;
8938 return builder.build ();
8941 /* Subroutine of native_interpret_expr. Interpret the contents of
8942 the buffer PTR of length LEN as a VECTOR_CST of type TYPE.
8943 If the buffer cannot be interpreted, return NULL_TREE. */
8945 static tree
8946 native_interpret_vector (tree type, const unsigned char *ptr, unsigned int len)
8948 unsigned HOST_WIDE_INT size;
8950 if (!tree_to_poly_uint64 (TYPE_SIZE_UNIT (type)).is_constant (&size)
8951 || size > len)
8952 return NULL_TREE;
8954 unsigned HOST_WIDE_INT count = TYPE_VECTOR_SUBPARTS (type).to_constant ();
8955 return native_interpret_vector_part (type, ptr, len, count, 1);
8959 /* Subroutine of fold_view_convert_expr. Interpret the contents of
8960 the buffer PTR of length LEN as a constant of type TYPE. For
8961 INTEGRAL_TYPE_P we return an INTEGER_CST, for SCALAR_FLOAT_TYPE_P
8962 we return a REAL_CST, etc... If the buffer cannot be interpreted,
8963 return NULL_TREE. */
8965 tree
8966 native_interpret_expr (tree type, const unsigned char *ptr, int len)
8968 switch (TREE_CODE (type))
8970 case INTEGER_TYPE:
8971 case ENUMERAL_TYPE:
8972 case BOOLEAN_TYPE:
8973 case POINTER_TYPE:
8974 case REFERENCE_TYPE:
8975 case OFFSET_TYPE:
8976 case BITINT_TYPE:
8977 return native_interpret_int (type, ptr, len);
8979 case REAL_TYPE:
8980 if (tree ret = native_interpret_real (type, ptr, len))
8982 /* For floating point values in composite modes, punt if this
8983 folding doesn't preserve bit representation. As the mode doesn't
8984 have fixed precision while GCC pretends it does, there could be
8985 valid values that GCC can't really represent accurately.
8986 See PR95450. Even for other modes, e.g. x86 XFmode can have some
8987 bit combinationations which GCC doesn't preserve. */
8988 unsigned char buf[24 * 2];
8989 scalar_float_mode mode = SCALAR_FLOAT_TYPE_MODE (type);
8990 int total_bytes = GET_MODE_SIZE (mode);
8991 memcpy (buf + 24, ptr, total_bytes);
8992 clear_type_padding_in_mask (type, buf + 24);
8993 if (native_encode_expr (ret, buf, total_bytes, 0) != total_bytes
8994 || memcmp (buf + 24, buf, total_bytes) != 0)
8995 return NULL_TREE;
8996 return ret;
8998 return NULL_TREE;
9000 case FIXED_POINT_TYPE:
9001 return native_interpret_fixed (type, ptr, len);
9003 case COMPLEX_TYPE:
9004 return native_interpret_complex (type, ptr, len);
9006 case VECTOR_TYPE:
9007 return native_interpret_vector (type, ptr, len);
9009 default:
9010 return NULL_TREE;
9014 /* Returns true if we can interpret the contents of a native encoding
9015 as TYPE. */
9017 bool
9018 can_native_interpret_type_p (tree type)
9020 switch (TREE_CODE (type))
9022 case INTEGER_TYPE:
9023 case ENUMERAL_TYPE:
9024 case BOOLEAN_TYPE:
9025 case POINTER_TYPE:
9026 case REFERENCE_TYPE:
9027 case FIXED_POINT_TYPE:
9028 case REAL_TYPE:
9029 case COMPLEX_TYPE:
9030 case VECTOR_TYPE:
9031 case OFFSET_TYPE:
9032 return true;
9033 default:
9034 return false;
9038 /* Attempt to interpret aggregate of TYPE from bytes encoded in target
9039 byte order at PTR + OFF with LEN bytes. Does not handle unions. */
9041 tree
9042 native_interpret_aggregate (tree type, const unsigned char *ptr, int off,
9043 int len)
9045 vec<constructor_elt, va_gc> *elts = NULL;
9046 if (TREE_CODE (type) == ARRAY_TYPE)
9048 HOST_WIDE_INT eltsz = int_size_in_bytes (TREE_TYPE (type));
9049 if (eltsz < 0 || eltsz > len || TYPE_DOMAIN (type) == NULL_TREE)
9050 return NULL_TREE;
9052 HOST_WIDE_INT cnt = 0;
9053 if (TYPE_MAX_VALUE (TYPE_DOMAIN (type)))
9055 if (!tree_fits_shwi_p (TYPE_MAX_VALUE (TYPE_DOMAIN (type))))
9056 return NULL_TREE;
9057 cnt = tree_to_shwi (TYPE_MAX_VALUE (TYPE_DOMAIN (type))) + 1;
9059 if (eltsz == 0)
9060 cnt = 0;
9061 HOST_WIDE_INT pos = 0;
9062 for (HOST_WIDE_INT i = 0; i < cnt; i++, pos += eltsz)
9064 tree v = NULL_TREE;
9065 if (pos >= len || pos + eltsz > len)
9066 return NULL_TREE;
9067 if (can_native_interpret_type_p (TREE_TYPE (type)))
9069 v = native_interpret_expr (TREE_TYPE (type),
9070 ptr + off + pos, eltsz);
9071 if (v == NULL_TREE)
9072 return NULL_TREE;
9074 else if (TREE_CODE (TREE_TYPE (type)) == RECORD_TYPE
9075 || TREE_CODE (TREE_TYPE (type)) == ARRAY_TYPE)
9076 v = native_interpret_aggregate (TREE_TYPE (type), ptr, off + pos,
9077 eltsz);
9078 if (v == NULL_TREE)
9079 return NULL_TREE;
9080 CONSTRUCTOR_APPEND_ELT (elts, size_int (i), v);
9082 return build_constructor (type, elts);
9084 if (TREE_CODE (type) != RECORD_TYPE)
9085 return NULL_TREE;
9086 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
9088 if (TREE_CODE (field) != FIELD_DECL || DECL_PADDING_P (field)
9089 || is_empty_type (TREE_TYPE (field)))
9090 continue;
9091 tree fld = field;
9092 HOST_WIDE_INT bitoff = 0, pos = 0, sz = 0;
9093 int diff = 0;
9094 tree v = NULL_TREE;
9095 if (DECL_BIT_FIELD (field))
9097 fld = DECL_BIT_FIELD_REPRESENTATIVE (field);
9098 if (fld && INTEGRAL_TYPE_P (TREE_TYPE (fld)))
9100 poly_int64 bitoffset;
9101 poly_uint64 field_offset, fld_offset;
9102 if (poly_int_tree_p (DECL_FIELD_OFFSET (field), &field_offset)
9103 && poly_int_tree_p (DECL_FIELD_OFFSET (fld), &fld_offset))
9104 bitoffset = (field_offset - fld_offset) * BITS_PER_UNIT;
9105 else
9106 bitoffset = 0;
9107 bitoffset += (tree_to_uhwi (DECL_FIELD_BIT_OFFSET (field))
9108 - tree_to_uhwi (DECL_FIELD_BIT_OFFSET (fld)));
9109 diff = (TYPE_PRECISION (TREE_TYPE (fld))
9110 - TYPE_PRECISION (TREE_TYPE (field)));
9111 if (!bitoffset.is_constant (&bitoff)
9112 || bitoff < 0
9113 || bitoff > diff)
9114 return NULL_TREE;
9116 else
9118 if (!tree_fits_uhwi_p (DECL_FIELD_BIT_OFFSET (field)))
9119 return NULL_TREE;
9120 int fieldsize = TYPE_PRECISION (TREE_TYPE (field));
9121 int bpos = tree_to_uhwi (DECL_FIELD_BIT_OFFSET (field));
9122 bpos %= BITS_PER_UNIT;
9123 fieldsize += bpos;
9124 fieldsize += BITS_PER_UNIT - 1;
9125 fieldsize /= BITS_PER_UNIT;
9126 tree repr_type = find_bitfield_repr_type (fieldsize, len);
9127 if (repr_type == NULL_TREE)
9128 return NULL_TREE;
9129 sz = int_size_in_bytes (repr_type);
9130 if (sz < 0 || sz > len)
9131 return NULL_TREE;
9132 pos = int_byte_position (field);
9133 if (pos < 0 || pos > len || pos + fieldsize > len)
9134 return NULL_TREE;
9135 HOST_WIDE_INT rpos;
9136 if (pos + sz <= len)
9137 rpos = pos;
9138 else
9140 rpos = len - sz;
9141 gcc_assert (rpos <= pos);
9143 bitoff = (HOST_WIDE_INT) (pos - rpos) * BITS_PER_UNIT + bpos;
9144 pos = rpos;
9145 diff = (TYPE_PRECISION (repr_type)
9146 - TYPE_PRECISION (TREE_TYPE (field)));
9147 v = native_interpret_expr (repr_type, ptr + off + pos, sz);
9148 if (v == NULL_TREE)
9149 return NULL_TREE;
9150 fld = NULL_TREE;
9154 if (fld)
9156 sz = int_size_in_bytes (TREE_TYPE (fld));
9157 if (sz < 0 || sz > len)
9158 return NULL_TREE;
9159 tree byte_pos = byte_position (fld);
9160 if (!tree_fits_shwi_p (byte_pos))
9161 return NULL_TREE;
9162 pos = tree_to_shwi (byte_pos);
9163 if (pos < 0 || pos > len || pos + sz > len)
9164 return NULL_TREE;
9166 if (fld == NULL_TREE)
9167 /* Already handled above. */;
9168 else if (can_native_interpret_type_p (TREE_TYPE (fld)))
9170 v = native_interpret_expr (TREE_TYPE (fld),
9171 ptr + off + pos, sz);
9172 if (v == NULL_TREE)
9173 return NULL_TREE;
9175 else if (TREE_CODE (TREE_TYPE (fld)) == RECORD_TYPE
9176 || TREE_CODE (TREE_TYPE (fld)) == ARRAY_TYPE)
9177 v = native_interpret_aggregate (TREE_TYPE (fld), ptr, off + pos, sz);
9178 if (v == NULL_TREE)
9179 return NULL_TREE;
9180 if (fld != field)
9182 if (TREE_CODE (v) != INTEGER_CST)
9183 return NULL_TREE;
9185 /* FIXME: Figure out how to handle PDP endian bitfields. */
9186 if (BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN)
9187 return NULL_TREE;
9188 if (!BYTES_BIG_ENDIAN)
9189 v = wide_int_to_tree (TREE_TYPE (field),
9190 wi::lrshift (wi::to_wide (v), bitoff));
9191 else
9192 v = wide_int_to_tree (TREE_TYPE (field),
9193 wi::lrshift (wi::to_wide (v),
9194 diff - bitoff));
9196 CONSTRUCTOR_APPEND_ELT (elts, field, v);
9198 return build_constructor (type, elts);
9201 /* Routines for manipulation of native_encode_expr encoded data if the encoded
9202 or extracted constant positions and/or sizes aren't byte aligned. */
9204 /* Shift left the bytes in PTR of SZ elements by AMNT bits, carrying over the
9205 bits between adjacent elements. AMNT should be within
9206 [0, BITS_PER_UNIT).
9207 Example, AMNT = 2:
9208 00011111|11100000 << 2 = 01111111|10000000
9209 PTR[1] | PTR[0] PTR[1] | PTR[0]. */
9211 void
9212 shift_bytes_in_array_left (unsigned char *ptr, unsigned int sz,
9213 unsigned int amnt)
9215 if (amnt == 0)
9216 return;
9218 unsigned char carry_over = 0U;
9219 unsigned char carry_mask = (~0U) << (unsigned char) (BITS_PER_UNIT - amnt);
9220 unsigned char clear_mask = (~0U) << amnt;
9222 for (unsigned int i = 0; i < sz; i++)
9224 unsigned prev_carry_over = carry_over;
9225 carry_over = (ptr[i] & carry_mask) >> (BITS_PER_UNIT - amnt);
9227 ptr[i] <<= amnt;
9228 if (i != 0)
9230 ptr[i] &= clear_mask;
9231 ptr[i] |= prev_carry_over;
9236 /* Like shift_bytes_in_array_left but for big-endian.
9237 Shift right the bytes in PTR of SZ elements by AMNT bits, carrying over the
9238 bits between adjacent elements. AMNT should be within
9239 [0, BITS_PER_UNIT).
9240 Example, AMNT = 2:
9241 00011111|11100000 >> 2 = 00000111|11111000
9242 PTR[0] | PTR[1] PTR[0] | PTR[1]. */
9244 void
9245 shift_bytes_in_array_right (unsigned char *ptr, unsigned int sz,
9246 unsigned int amnt)
9248 if (amnt == 0)
9249 return;
9251 unsigned char carry_over = 0U;
9252 unsigned char carry_mask = ~(~0U << amnt);
9254 for (unsigned int i = 0; i < sz; i++)
9256 unsigned prev_carry_over = carry_over;
9257 carry_over = ptr[i] & carry_mask;
9259 carry_over <<= (unsigned char) BITS_PER_UNIT - amnt;
9260 ptr[i] >>= amnt;
9261 ptr[i] |= prev_carry_over;
9265 /* Try to view-convert VECTOR_CST EXPR to VECTOR_TYPE TYPE by operating
9266 directly on the VECTOR_CST encoding, in a way that works for variable-
9267 length vectors. Return the resulting VECTOR_CST on success or null
9268 on failure. */
9270 static tree
9271 fold_view_convert_vector_encoding (tree type, tree expr)
9273 tree expr_type = TREE_TYPE (expr);
9274 poly_uint64 type_bits, expr_bits;
9275 if (!poly_int_tree_p (TYPE_SIZE (type), &type_bits)
9276 || !poly_int_tree_p (TYPE_SIZE (expr_type), &expr_bits))
9277 return NULL_TREE;
9279 poly_uint64 type_units = TYPE_VECTOR_SUBPARTS (type);
9280 poly_uint64 expr_units = TYPE_VECTOR_SUBPARTS (expr_type);
9281 unsigned int type_elt_bits = vector_element_size (type_bits, type_units);
9282 unsigned int expr_elt_bits = vector_element_size (expr_bits, expr_units);
9284 /* We can only preserve the semantics of a stepped pattern if the new
9285 vector element is an integer of the same size. */
9286 if (VECTOR_CST_STEPPED_P (expr)
9287 && (!INTEGRAL_TYPE_P (type) || type_elt_bits != expr_elt_bits))
9288 return NULL_TREE;
9290 /* The number of bits needed to encode one element from every pattern
9291 of the original vector. */
9292 unsigned int expr_sequence_bits
9293 = VECTOR_CST_NPATTERNS (expr) * expr_elt_bits;
9295 /* The number of bits needed to encode one element from every pattern
9296 of the result. */
9297 unsigned int type_sequence_bits
9298 = least_common_multiple (expr_sequence_bits, type_elt_bits);
9300 /* Don't try to read more bytes than are available, which can happen
9301 for constant-sized vectors if TYPE has larger elements than EXPR_TYPE.
9302 The general VIEW_CONVERT handling can cope with that case, so there's
9303 no point complicating things here. */
9304 unsigned int nelts_per_pattern = VECTOR_CST_NELTS_PER_PATTERN (expr);
9305 unsigned int buffer_bytes = CEIL (nelts_per_pattern * type_sequence_bits,
9306 BITS_PER_UNIT);
9307 unsigned int buffer_bits = buffer_bytes * BITS_PER_UNIT;
9308 if (known_gt (buffer_bits, expr_bits))
9309 return NULL_TREE;
9311 /* Get enough bytes of EXPR to form the new encoding. */
9312 auto_vec<unsigned char, 128> buffer (buffer_bytes);
9313 buffer.quick_grow (buffer_bytes);
9314 if (native_encode_vector_part (expr, buffer.address (), buffer_bytes, 0,
9315 buffer_bits / expr_elt_bits)
9316 != (int) buffer_bytes)
9317 return NULL_TREE;
9319 /* Reencode the bytes as TYPE. */
9320 unsigned int type_npatterns = type_sequence_bits / type_elt_bits;
9321 return native_interpret_vector_part (type, &buffer[0], buffer.length (),
9322 type_npatterns, nelts_per_pattern);
9325 /* Fold a VIEW_CONVERT_EXPR of a constant expression EXPR to type
9326 TYPE at compile-time. If we're unable to perform the conversion
9327 return NULL_TREE. */
9329 static tree
9330 fold_view_convert_expr (tree type, tree expr)
9332 /* We support up to 1024-bit values (for GCN/RISC-V V128QImode). */
9333 unsigned char buffer[128];
9334 int len;
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 len = native_encode_expr (expr, buffer, sizeof (buffer));
9345 if (len == 0)
9346 return NULL_TREE;
9348 return native_interpret_expr (type, buffer, len);
9351 /* Build an expression for the address of T. Folds away INDIRECT_REF
9352 to avoid confusing the gimplify process. */
9354 tree
9355 build_fold_addr_expr_with_type_loc (location_t loc, tree t, tree ptrtype)
9357 /* The size of the object is not relevant when talking about its address. */
9358 if (TREE_CODE (t) == WITH_SIZE_EXPR)
9359 t = TREE_OPERAND (t, 0);
9361 if (INDIRECT_REF_P (t))
9363 t = TREE_OPERAND (t, 0);
9365 if (TREE_TYPE (t) != ptrtype)
9366 t = build1_loc (loc, NOP_EXPR, ptrtype, t);
9368 else if (TREE_CODE (t) == MEM_REF
9369 && integer_zerop (TREE_OPERAND (t, 1)))
9371 t = TREE_OPERAND (t, 0);
9373 if (TREE_TYPE (t) != ptrtype)
9374 t = fold_convert_loc (loc, ptrtype, t);
9376 else if (TREE_CODE (t) == MEM_REF
9377 && TREE_CODE (TREE_OPERAND (t, 0)) == INTEGER_CST)
9378 return fold_binary (POINTER_PLUS_EXPR, ptrtype,
9379 TREE_OPERAND (t, 0),
9380 convert_to_ptrofftype (TREE_OPERAND (t, 1)));
9381 else if (TREE_CODE (t) == VIEW_CONVERT_EXPR)
9383 t = build_fold_addr_expr_loc (loc, TREE_OPERAND (t, 0));
9385 if (TREE_TYPE (t) != ptrtype)
9386 t = fold_convert_loc (loc, ptrtype, t);
9388 else
9389 t = build1_loc (loc, ADDR_EXPR, ptrtype, t);
9391 return t;
9394 /* Build an expression for the address of T. */
9396 tree
9397 build_fold_addr_expr_loc (location_t loc, tree t)
9399 tree ptrtype = build_pointer_type (TREE_TYPE (t));
9401 return build_fold_addr_expr_with_type_loc (loc, t, ptrtype);
9404 /* Fold a unary expression of code CODE and type TYPE with operand
9405 OP0. Return the folded expression if folding is successful.
9406 Otherwise, return NULL_TREE. */
9408 tree
9409 fold_unary_loc (location_t loc, enum tree_code code, tree type, tree op0)
9411 tree tem;
9412 tree arg0;
9413 enum tree_code_class kind = TREE_CODE_CLASS (code);
9415 gcc_assert (IS_EXPR_CODE_CLASS (kind)
9416 && TREE_CODE_LENGTH (code) == 1);
9418 arg0 = op0;
9419 if (arg0)
9421 if (CONVERT_EXPR_CODE_P (code)
9422 || code == FLOAT_EXPR || code == ABS_EXPR || code == NEGATE_EXPR)
9424 /* Don't use STRIP_NOPS, because signedness of argument type
9425 matters. */
9426 STRIP_SIGN_NOPS (arg0);
9428 else
9430 /* Strip any conversions that don't change the mode. This
9431 is safe for every expression, except for a comparison
9432 expression because its signedness is derived from its
9433 operands.
9435 Note that this is done as an internal manipulation within
9436 the constant folder, in order to find the simplest
9437 representation of the arguments so that their form can be
9438 studied. In any cases, the appropriate type conversions
9439 should be put back in the tree that will get out of the
9440 constant folder. */
9441 STRIP_NOPS (arg0);
9444 if (CONSTANT_CLASS_P (arg0))
9446 tree tem = const_unop (code, type, arg0);
9447 if (tem)
9449 if (TREE_TYPE (tem) != type)
9450 tem = fold_convert_loc (loc, type, tem);
9451 return tem;
9456 tem = generic_simplify (loc, code, type, op0);
9457 if (tem)
9458 return tem;
9460 if (TREE_CODE_CLASS (code) == tcc_unary)
9462 if (TREE_CODE (arg0) == COMPOUND_EXPR)
9463 return build2 (COMPOUND_EXPR, type, TREE_OPERAND (arg0, 0),
9464 fold_build1_loc (loc, code, type,
9465 fold_convert_loc (loc, TREE_TYPE (op0),
9466 TREE_OPERAND (arg0, 1))));
9467 else if (TREE_CODE (arg0) == COND_EXPR)
9469 tree arg01 = TREE_OPERAND (arg0, 1);
9470 tree arg02 = TREE_OPERAND (arg0, 2);
9471 if (! VOID_TYPE_P (TREE_TYPE (arg01)))
9472 arg01 = fold_build1_loc (loc, code, type,
9473 fold_convert_loc (loc,
9474 TREE_TYPE (op0), arg01));
9475 if (! VOID_TYPE_P (TREE_TYPE (arg02)))
9476 arg02 = fold_build1_loc (loc, code, type,
9477 fold_convert_loc (loc,
9478 TREE_TYPE (op0), arg02));
9479 tem = fold_build3_loc (loc, COND_EXPR, type, TREE_OPERAND (arg0, 0),
9480 arg01, arg02);
9482 /* If this was a conversion, and all we did was to move into
9483 inside the COND_EXPR, bring it back out. But leave it if
9484 it is a conversion from integer to integer and the
9485 result precision is no wider than a word since such a
9486 conversion is cheap and may be optimized away by combine,
9487 while it couldn't if it were outside the COND_EXPR. Then return
9488 so we don't get into an infinite recursion loop taking the
9489 conversion out and then back in. */
9491 if ((CONVERT_EXPR_CODE_P (code)
9492 || code == NON_LVALUE_EXPR)
9493 && TREE_CODE (tem) == COND_EXPR
9494 && TREE_CODE (TREE_OPERAND (tem, 1)) == code
9495 && TREE_CODE (TREE_OPERAND (tem, 2)) == code
9496 && ! VOID_TYPE_P (TREE_TYPE (TREE_OPERAND (tem, 1)))
9497 && ! VOID_TYPE_P (TREE_TYPE (TREE_OPERAND (tem, 2)))
9498 && (TREE_TYPE (TREE_OPERAND (TREE_OPERAND (tem, 1), 0))
9499 == TREE_TYPE (TREE_OPERAND (TREE_OPERAND (tem, 2), 0)))
9500 && (! (INTEGRAL_TYPE_P (TREE_TYPE (tem))
9501 && (INTEGRAL_TYPE_P
9502 (TREE_TYPE (TREE_OPERAND (TREE_OPERAND (tem, 1), 0))))
9503 && TYPE_PRECISION (TREE_TYPE (tem)) <= BITS_PER_WORD)
9504 || flag_syntax_only))
9505 tem = build1_loc (loc, code, type,
9506 build3 (COND_EXPR,
9507 TREE_TYPE (TREE_OPERAND
9508 (TREE_OPERAND (tem, 1), 0)),
9509 TREE_OPERAND (tem, 0),
9510 TREE_OPERAND (TREE_OPERAND (tem, 1), 0),
9511 TREE_OPERAND (TREE_OPERAND (tem, 2),
9512 0)));
9513 return tem;
9517 switch (code)
9519 case NON_LVALUE_EXPR:
9520 if (!maybe_lvalue_p (op0))
9521 return fold_convert_loc (loc, type, op0);
9522 return NULL_TREE;
9524 CASE_CONVERT:
9525 case FLOAT_EXPR:
9526 case FIX_TRUNC_EXPR:
9527 if (COMPARISON_CLASS_P (op0))
9529 /* If we have (type) (a CMP b) and type is an integral type, return
9530 new expression involving the new type. Canonicalize
9531 (type) (a CMP b) to (a CMP b) ? (type) true : (type) false for
9532 non-integral type.
9533 Do not fold the result as that would not simplify further, also
9534 folding again results in recursions. */
9535 if (TREE_CODE (type) == BOOLEAN_TYPE)
9536 return build2_loc (loc, TREE_CODE (op0), type,
9537 TREE_OPERAND (op0, 0),
9538 TREE_OPERAND (op0, 1));
9539 else if (!INTEGRAL_TYPE_P (type) && !VOID_TYPE_P (type)
9540 && TREE_CODE (type) != VECTOR_TYPE)
9541 return build3_loc (loc, COND_EXPR, type, op0,
9542 constant_boolean_node (true, type),
9543 constant_boolean_node (false, type));
9546 /* Handle (T *)&A.B.C for A being of type T and B and C
9547 living at offset zero. This occurs frequently in
9548 C++ upcasting and then accessing the base. */
9549 if (TREE_CODE (op0) == ADDR_EXPR
9550 && POINTER_TYPE_P (type)
9551 && handled_component_p (TREE_OPERAND (op0, 0)))
9553 poly_int64 bitsize, bitpos;
9554 tree offset;
9555 machine_mode mode;
9556 int unsignedp, reversep, volatilep;
9557 tree base
9558 = get_inner_reference (TREE_OPERAND (op0, 0), &bitsize, &bitpos,
9559 &offset, &mode, &unsignedp, &reversep,
9560 &volatilep);
9561 /* If the reference was to a (constant) zero offset, we can use
9562 the address of the base if it has the same base type
9563 as the result type and the pointer type is unqualified. */
9564 if (!offset
9565 && known_eq (bitpos, 0)
9566 && (TYPE_MAIN_VARIANT (TREE_TYPE (type))
9567 == TYPE_MAIN_VARIANT (TREE_TYPE (base)))
9568 && TYPE_QUALS (type) == TYPE_UNQUALIFIED)
9569 return fold_convert_loc (loc, type,
9570 build_fold_addr_expr_loc (loc, base));
9573 if (TREE_CODE (op0) == MODIFY_EXPR
9574 && TREE_CONSTANT (TREE_OPERAND (op0, 1))
9575 /* Detect assigning a bitfield. */
9576 && !(TREE_CODE (TREE_OPERAND (op0, 0)) == COMPONENT_REF
9577 && DECL_BIT_FIELD
9578 (TREE_OPERAND (TREE_OPERAND (op0, 0), 1))))
9580 /* Don't leave an assignment inside a conversion
9581 unless assigning a bitfield. */
9582 tem = fold_build1_loc (loc, code, type, TREE_OPERAND (op0, 1));
9583 /* First do the assignment, then return converted constant. */
9584 tem = build2_loc (loc, COMPOUND_EXPR, TREE_TYPE (tem), op0, tem);
9585 suppress_warning (tem /* What warning? */);
9586 TREE_USED (tem) = 1;
9587 return tem;
9590 /* Convert (T)(x & c) into (T)x & (T)c, if c is an integer
9591 constants (if x has signed type, the sign bit cannot be set
9592 in c). This folds extension into the BIT_AND_EXPR.
9593 ??? We don't do it for BOOLEAN_TYPE or ENUMERAL_TYPE because they
9594 very likely don't have maximal range for their precision and this
9595 transformation effectively doesn't preserve non-maximal ranges. */
9596 if (TREE_CODE (type) == INTEGER_TYPE
9597 && TREE_CODE (op0) == BIT_AND_EXPR
9598 && TREE_CODE (TREE_OPERAND (op0, 1)) == INTEGER_CST)
9600 tree and_expr = op0;
9601 tree and0 = TREE_OPERAND (and_expr, 0);
9602 tree and1 = TREE_OPERAND (and_expr, 1);
9603 int change = 0;
9605 if (TYPE_UNSIGNED (TREE_TYPE (and_expr))
9606 || (TYPE_PRECISION (type)
9607 <= TYPE_PRECISION (TREE_TYPE (and_expr))))
9608 change = 1;
9609 else if (TYPE_PRECISION (TREE_TYPE (and1))
9610 <= HOST_BITS_PER_WIDE_INT
9611 && tree_fits_uhwi_p (and1))
9613 unsigned HOST_WIDE_INT cst;
9615 cst = tree_to_uhwi (and1);
9616 cst &= HOST_WIDE_INT_M1U
9617 << (TYPE_PRECISION (TREE_TYPE (and1)) - 1);
9618 change = (cst == 0);
9619 if (change
9620 && !flag_syntax_only
9621 && (load_extend_op (TYPE_MODE (TREE_TYPE (and0)))
9622 == ZERO_EXTEND))
9624 tree uns = unsigned_type_for (TREE_TYPE (and0));
9625 and0 = fold_convert_loc (loc, uns, and0);
9626 and1 = fold_convert_loc (loc, uns, and1);
9629 if (change)
9631 tree and1_type = TREE_TYPE (and1);
9632 unsigned prec = MAX (TYPE_PRECISION (and1_type),
9633 TYPE_PRECISION (type));
9634 tem = force_fit_type (type,
9635 wide_int::from (wi::to_wide (and1), prec,
9636 TYPE_SIGN (and1_type)),
9637 0, TREE_OVERFLOW (and1));
9638 return fold_build2_loc (loc, BIT_AND_EXPR, type,
9639 fold_convert_loc (loc, type, and0), tem);
9643 /* Convert (T1)(X p+ Y) into ((T1)X p+ Y), for pointer type, when the new
9644 cast (T1)X will fold away. We assume that this happens when X itself
9645 is a cast. */
9646 if (POINTER_TYPE_P (type)
9647 && TREE_CODE (arg0) == POINTER_PLUS_EXPR
9648 && CONVERT_EXPR_P (TREE_OPERAND (arg0, 0)))
9650 tree arg00 = TREE_OPERAND (arg0, 0);
9651 tree arg01 = TREE_OPERAND (arg0, 1);
9653 /* If -fsanitize=alignment, avoid this optimization in GENERIC
9654 when the pointed type needs higher alignment than
9655 the p+ first operand's pointed type. */
9656 if (!in_gimple_form
9657 && sanitize_flags_p (SANITIZE_ALIGNMENT)
9658 && (min_align_of_type (TREE_TYPE (type))
9659 > min_align_of_type (TREE_TYPE (TREE_TYPE (arg00)))))
9660 return NULL_TREE;
9662 /* Similarly, avoid this optimization in GENERIC for -fsanitize=null
9663 when type is a reference type and arg00's type is not,
9664 because arg00 could be validly nullptr and if arg01 doesn't return,
9665 we don't want false positive binding of reference to nullptr. */
9666 if (TREE_CODE (type) == REFERENCE_TYPE
9667 && !in_gimple_form
9668 && sanitize_flags_p (SANITIZE_NULL)
9669 && TREE_CODE (TREE_TYPE (arg00)) != REFERENCE_TYPE)
9670 return NULL_TREE;
9672 arg00 = fold_convert_loc (loc, type, arg00);
9673 return fold_build_pointer_plus_loc (loc, arg00, arg01);
9676 /* Convert (T1)(~(T2)X) into ~(T1)X if T1 and T2 are integral types
9677 of the same precision, and X is an integer type not narrower than
9678 types T1 or T2, i.e. the cast (T2)X isn't an extension. */
9679 if (INTEGRAL_TYPE_P (type)
9680 && TREE_CODE (op0) == BIT_NOT_EXPR
9681 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
9682 && CONVERT_EXPR_P (TREE_OPERAND (op0, 0))
9683 && TYPE_PRECISION (type) == TYPE_PRECISION (TREE_TYPE (op0)))
9685 tem = TREE_OPERAND (TREE_OPERAND (op0, 0), 0);
9686 if (INTEGRAL_TYPE_P (TREE_TYPE (tem))
9687 && TYPE_PRECISION (type) <= TYPE_PRECISION (TREE_TYPE (tem)))
9688 return fold_build1_loc (loc, BIT_NOT_EXPR, type,
9689 fold_convert_loc (loc, type, tem));
9692 /* Convert (T1)(X * Y) into (T1)X * (T1)Y if T1 is narrower than the
9693 type of X and Y (integer types only). */
9694 if (INTEGRAL_TYPE_P (type)
9695 && TREE_CODE (op0) == MULT_EXPR
9696 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
9697 && TYPE_PRECISION (type) < TYPE_PRECISION (TREE_TYPE (op0))
9698 && (TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0))
9699 || !sanitize_flags_p (SANITIZE_SI_OVERFLOW)))
9701 /* Be careful not to introduce new overflows. */
9702 tree mult_type;
9703 if (TYPE_OVERFLOW_WRAPS (type))
9704 mult_type = type;
9705 else
9706 mult_type = unsigned_type_for (type);
9708 if (TYPE_PRECISION (mult_type) < TYPE_PRECISION (TREE_TYPE (op0)))
9710 tem = fold_build2_loc (loc, MULT_EXPR, mult_type,
9711 fold_convert_loc (loc, mult_type,
9712 TREE_OPERAND (op0, 0)),
9713 fold_convert_loc (loc, mult_type,
9714 TREE_OPERAND (op0, 1)));
9715 return fold_convert_loc (loc, type, tem);
9719 return NULL_TREE;
9721 case VIEW_CONVERT_EXPR:
9722 if (TREE_CODE (op0) == MEM_REF)
9724 if (TYPE_ALIGN (TREE_TYPE (op0)) != TYPE_ALIGN (type))
9725 type = build_aligned_type (type, TYPE_ALIGN (TREE_TYPE (op0)));
9726 tem = fold_build2_loc (loc, MEM_REF, type,
9727 TREE_OPERAND (op0, 0), TREE_OPERAND (op0, 1));
9728 REF_REVERSE_STORAGE_ORDER (tem) = REF_REVERSE_STORAGE_ORDER (op0);
9729 return tem;
9732 return NULL_TREE;
9734 case NEGATE_EXPR:
9735 tem = fold_negate_expr (loc, arg0);
9736 if (tem)
9737 return fold_convert_loc (loc, type, tem);
9738 return NULL_TREE;
9740 case ABS_EXPR:
9741 /* Convert fabs((double)float) into (double)fabsf(float). */
9742 if (TREE_CODE (arg0) == NOP_EXPR
9743 && TREE_CODE (type) == REAL_TYPE)
9745 tree targ0 = strip_float_extensions (arg0);
9746 if (targ0 != arg0)
9747 return fold_convert_loc (loc, type,
9748 fold_build1_loc (loc, ABS_EXPR,
9749 TREE_TYPE (targ0),
9750 targ0));
9752 return NULL_TREE;
9754 case BIT_NOT_EXPR:
9755 /* Convert ~(X ^ Y) to ~X ^ Y or X ^ ~Y if ~X or ~Y simplify. */
9756 if (TREE_CODE (arg0) == BIT_XOR_EXPR
9757 && (tem = fold_unary_loc (loc, BIT_NOT_EXPR, type,
9758 fold_convert_loc (loc, type,
9759 TREE_OPERAND (arg0, 0)))))
9760 return fold_build2_loc (loc, BIT_XOR_EXPR, type, tem,
9761 fold_convert_loc (loc, type,
9762 TREE_OPERAND (arg0, 1)));
9763 else if (TREE_CODE (arg0) == BIT_XOR_EXPR
9764 && (tem = fold_unary_loc (loc, BIT_NOT_EXPR, type,
9765 fold_convert_loc (loc, type,
9766 TREE_OPERAND (arg0, 1)))))
9767 return fold_build2_loc (loc, BIT_XOR_EXPR, type,
9768 fold_convert_loc (loc, type,
9769 TREE_OPERAND (arg0, 0)), tem);
9771 return NULL_TREE;
9773 case TRUTH_NOT_EXPR:
9774 /* Note that the operand of this must be an int
9775 and its values must be 0 or 1.
9776 ("true" is a fixed value perhaps depending on the language,
9777 but we don't handle values other than 1 correctly yet.) */
9778 tem = fold_truth_not_expr (loc, arg0);
9779 if (!tem)
9780 return NULL_TREE;
9781 return fold_convert_loc (loc, type, tem);
9783 case INDIRECT_REF:
9784 /* Fold *&X to X if X is an lvalue. */
9785 if (TREE_CODE (op0) == ADDR_EXPR)
9787 tree op00 = TREE_OPERAND (op0, 0);
9788 if ((VAR_P (op00)
9789 || TREE_CODE (op00) == PARM_DECL
9790 || TREE_CODE (op00) == RESULT_DECL)
9791 && !TREE_READONLY (op00))
9792 return op00;
9794 return NULL_TREE;
9796 default:
9797 return NULL_TREE;
9798 } /* switch (code) */
9802 /* If the operation was a conversion do _not_ mark a resulting constant
9803 with TREE_OVERFLOW if the original constant was not. These conversions
9804 have implementation defined behavior and retaining the TREE_OVERFLOW
9805 flag here would confuse later passes such as VRP. */
9806 tree
9807 fold_unary_ignore_overflow_loc (location_t loc, enum tree_code code,
9808 tree type, tree op0)
9810 tree res = fold_unary_loc (loc, code, type, op0);
9811 if (res
9812 && TREE_CODE (res) == INTEGER_CST
9813 && TREE_CODE (op0) == INTEGER_CST
9814 && CONVERT_EXPR_CODE_P (code))
9815 TREE_OVERFLOW (res) = TREE_OVERFLOW (op0);
9817 return res;
9820 /* Fold a binary bitwise/truth expression of code CODE and type TYPE with
9821 operands OP0 and OP1. LOC is the location of the resulting expression.
9822 ARG0 and ARG1 are the NOP_STRIPed results of OP0 and OP1.
9823 Return the folded expression if folding is successful. Otherwise,
9824 return NULL_TREE. */
9825 static tree
9826 fold_truth_andor (location_t loc, enum tree_code code, tree type,
9827 tree arg0, tree arg1, tree op0, tree op1)
9829 tree tem;
9831 /* We only do these simplifications if we are optimizing. */
9832 if (!optimize)
9833 return NULL_TREE;
9835 /* Check for things like (A || B) && (A || C). We can convert this
9836 to A || (B && C). Note that either operator can be any of the four
9837 truth and/or operations and the transformation will still be
9838 valid. Also note that we only care about order for the
9839 ANDIF and ORIF operators. If B contains side effects, this
9840 might change the truth-value of A. */
9841 if (TREE_CODE (arg0) == TREE_CODE (arg1)
9842 && (TREE_CODE (arg0) == TRUTH_ANDIF_EXPR
9843 || TREE_CODE (arg0) == TRUTH_ORIF_EXPR
9844 || TREE_CODE (arg0) == TRUTH_AND_EXPR
9845 || TREE_CODE (arg0) == TRUTH_OR_EXPR)
9846 && ! TREE_SIDE_EFFECTS (TREE_OPERAND (arg0, 1)))
9848 tree a00 = TREE_OPERAND (arg0, 0);
9849 tree a01 = TREE_OPERAND (arg0, 1);
9850 tree a10 = TREE_OPERAND (arg1, 0);
9851 tree a11 = TREE_OPERAND (arg1, 1);
9852 bool commutative = ((TREE_CODE (arg0) == TRUTH_OR_EXPR
9853 || TREE_CODE (arg0) == TRUTH_AND_EXPR)
9854 && (code == TRUTH_AND_EXPR
9855 || code == TRUTH_OR_EXPR));
9857 if (operand_equal_p (a00, a10, 0))
9858 return fold_build2_loc (loc, TREE_CODE (arg0), type, a00,
9859 fold_build2_loc (loc, code, type, a01, a11));
9860 else if (commutative && operand_equal_p (a00, a11, 0))
9861 return fold_build2_loc (loc, TREE_CODE (arg0), type, a00,
9862 fold_build2_loc (loc, code, type, a01, a10));
9863 else if (commutative && operand_equal_p (a01, a10, 0))
9864 return fold_build2_loc (loc, TREE_CODE (arg0), type, a01,
9865 fold_build2_loc (loc, code, type, a00, a11));
9867 /* This case if tricky because we must either have commutative
9868 operators or else A10 must not have side-effects. */
9870 else if ((commutative || ! TREE_SIDE_EFFECTS (a10))
9871 && operand_equal_p (a01, a11, 0))
9872 return fold_build2_loc (loc, TREE_CODE (arg0), type,
9873 fold_build2_loc (loc, code, type, a00, a10),
9874 a01);
9877 /* See if we can build a range comparison. */
9878 if ((tem = fold_range_test (loc, code, type, op0, op1)) != 0)
9879 return tem;
9881 if ((code == TRUTH_ANDIF_EXPR && TREE_CODE (arg0) == TRUTH_ORIF_EXPR)
9882 || (code == TRUTH_ORIF_EXPR && TREE_CODE (arg0) == TRUTH_ANDIF_EXPR))
9884 tem = merge_truthop_with_opposite_arm (loc, arg0, arg1, true);
9885 if (tem)
9886 return fold_build2_loc (loc, code, type, tem, arg1);
9889 if ((code == TRUTH_ANDIF_EXPR && TREE_CODE (arg1) == TRUTH_ORIF_EXPR)
9890 || (code == TRUTH_ORIF_EXPR && TREE_CODE (arg1) == TRUTH_ANDIF_EXPR))
9892 tem = merge_truthop_with_opposite_arm (loc, arg1, arg0, false);
9893 if (tem)
9894 return fold_build2_loc (loc, code, type, arg0, tem);
9897 /* Check for the possibility of merging component references. If our
9898 lhs is another similar operation, try to merge its rhs with our
9899 rhs. Then try to merge our lhs and rhs. */
9900 if (TREE_CODE (arg0) == code
9901 && (tem = fold_truth_andor_1 (loc, code, type,
9902 TREE_OPERAND (arg0, 1), arg1)) != 0)
9903 return fold_build2_loc (loc, code, type, TREE_OPERAND (arg0, 0), tem);
9905 if ((tem = fold_truth_andor_1 (loc, code, type, arg0, arg1)) != 0)
9906 return tem;
9908 bool logical_op_non_short_circuit = LOGICAL_OP_NON_SHORT_CIRCUIT;
9909 if (param_logical_op_non_short_circuit != -1)
9910 logical_op_non_short_circuit
9911 = param_logical_op_non_short_circuit;
9912 if (logical_op_non_short_circuit
9913 && !sanitize_coverage_p ()
9914 && (code == TRUTH_AND_EXPR
9915 || code == TRUTH_ANDIF_EXPR
9916 || code == TRUTH_OR_EXPR
9917 || code == TRUTH_ORIF_EXPR))
9919 enum tree_code ncode, icode;
9921 ncode = (code == TRUTH_ANDIF_EXPR || code == TRUTH_AND_EXPR)
9922 ? TRUTH_AND_EXPR : TRUTH_OR_EXPR;
9923 icode = ncode == TRUTH_AND_EXPR ? TRUTH_ANDIF_EXPR : TRUTH_ORIF_EXPR;
9925 /* Transform ((A AND-IF B) AND[-IF] C) into (A AND-IF (B AND C)),
9926 or ((A OR-IF B) OR[-IF] C) into (A OR-IF (B OR C))
9927 We don't want to pack more than two leafs to a non-IF AND/OR
9928 expression.
9929 If tree-code of left-hand operand isn't an AND/OR-IF code and not
9930 equal to IF-CODE, then we don't want to add right-hand operand.
9931 If the inner right-hand side of left-hand operand has
9932 side-effects, or isn't simple, then we can't add to it,
9933 as otherwise we might destroy if-sequence. */
9934 if (TREE_CODE (arg0) == icode
9935 && simple_condition_p (arg1)
9936 /* Needed for sequence points to handle trappings, and
9937 side-effects. */
9938 && simple_condition_p (TREE_OPERAND (arg0, 1)))
9940 tem = fold_build2_loc (loc, ncode, type, TREE_OPERAND (arg0, 1),
9941 arg1);
9942 return fold_build2_loc (loc, icode, type, TREE_OPERAND (arg0, 0),
9943 tem);
9945 /* Same as above but for (A AND[-IF] (B AND-IF C)) -> ((A AND B) AND-IF C),
9946 or (A OR[-IF] (B OR-IF C) -> ((A OR B) OR-IF C). */
9947 else if (TREE_CODE (arg1) == icode
9948 && simple_condition_p (arg0)
9949 /* Needed for sequence points to handle trappings, and
9950 side-effects. */
9951 && simple_condition_p (TREE_OPERAND (arg1, 0)))
9953 tem = fold_build2_loc (loc, ncode, type,
9954 arg0, TREE_OPERAND (arg1, 0));
9955 return fold_build2_loc (loc, icode, type, tem,
9956 TREE_OPERAND (arg1, 1));
9958 /* Transform (A AND-IF B) into (A AND B), or (A OR-IF B)
9959 into (A OR B).
9960 For sequence point consistancy, we need to check for trapping,
9961 and side-effects. */
9962 else if (code == icode && simple_condition_p (arg0)
9963 && simple_condition_p (arg1))
9964 return fold_build2_loc (loc, ncode, type, arg0, arg1);
9967 return NULL_TREE;
9970 /* Helper that tries to canonicalize the comparison ARG0 CODE ARG1
9971 by changing CODE to reduce the magnitude of constants involved in
9972 ARG0 of the comparison.
9973 Returns a canonicalized comparison tree if a simplification was
9974 possible, otherwise returns NULL_TREE.
9975 Set *STRICT_OVERFLOW_P to true if the canonicalization is only
9976 valid if signed overflow is undefined. */
9978 static tree
9979 maybe_canonicalize_comparison_1 (location_t loc, enum tree_code code, tree type,
9980 tree arg0, tree arg1,
9981 bool *strict_overflow_p)
9983 enum tree_code code0 = TREE_CODE (arg0);
9984 tree t, cst0 = NULL_TREE;
9985 int sgn0;
9987 /* Match A +- CST code arg1. We can change this only if overflow
9988 is undefined. */
9989 if (!((ANY_INTEGRAL_TYPE_P (TREE_TYPE (arg0))
9990 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg0)))
9991 /* In principle pointers also have undefined overflow behavior,
9992 but that causes problems elsewhere. */
9993 && !POINTER_TYPE_P (TREE_TYPE (arg0))
9994 && (code0 == MINUS_EXPR
9995 || code0 == PLUS_EXPR)
9996 && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST))
9997 return NULL_TREE;
9999 /* Identify the constant in arg0 and its sign. */
10000 cst0 = TREE_OPERAND (arg0, 1);
10001 sgn0 = tree_int_cst_sgn (cst0);
10003 /* Overflowed constants and zero will cause problems. */
10004 if (integer_zerop (cst0)
10005 || TREE_OVERFLOW (cst0))
10006 return NULL_TREE;
10008 /* See if we can reduce the magnitude of the constant in
10009 arg0 by changing the comparison code. */
10010 /* A - CST < arg1 -> A - CST-1 <= arg1. */
10011 if (code == LT_EXPR
10012 && code0 == ((sgn0 == -1) ? PLUS_EXPR : MINUS_EXPR))
10013 code = LE_EXPR;
10014 /* A + CST > arg1 -> A + CST-1 >= arg1. */
10015 else if (code == GT_EXPR
10016 && code0 == ((sgn0 == -1) ? MINUS_EXPR : PLUS_EXPR))
10017 code = GE_EXPR;
10018 /* A + CST <= arg1 -> A + CST-1 < arg1. */
10019 else if (code == LE_EXPR
10020 && code0 == ((sgn0 == -1) ? MINUS_EXPR : PLUS_EXPR))
10021 code = LT_EXPR;
10022 /* A - CST >= arg1 -> A - CST-1 > arg1. */
10023 else if (code == GE_EXPR
10024 && code0 == ((sgn0 == -1) ? PLUS_EXPR : MINUS_EXPR))
10025 code = GT_EXPR;
10026 else
10027 return NULL_TREE;
10028 *strict_overflow_p = true;
10030 /* Now build the constant reduced in magnitude. But not if that
10031 would produce one outside of its types range. */
10032 if (INTEGRAL_TYPE_P (TREE_TYPE (cst0))
10033 && ((sgn0 == 1
10034 && TYPE_MIN_VALUE (TREE_TYPE (cst0))
10035 && tree_int_cst_equal (cst0, TYPE_MIN_VALUE (TREE_TYPE (cst0))))
10036 || (sgn0 == -1
10037 && TYPE_MAX_VALUE (TREE_TYPE (cst0))
10038 && tree_int_cst_equal (cst0, TYPE_MAX_VALUE (TREE_TYPE (cst0))))))
10039 return NULL_TREE;
10041 t = int_const_binop (sgn0 == -1 ? PLUS_EXPR : MINUS_EXPR,
10042 cst0, build_int_cst (TREE_TYPE (cst0), 1));
10043 t = fold_build2_loc (loc, code0, TREE_TYPE (arg0), TREE_OPERAND (arg0, 0), t);
10044 t = fold_convert (TREE_TYPE (arg1), t);
10046 return fold_build2_loc (loc, code, type, t, arg1);
10049 /* Canonicalize the comparison ARG0 CODE ARG1 with type TYPE with undefined
10050 overflow further. Try to decrease the magnitude of constants involved
10051 by changing LE_EXPR and GE_EXPR to LT_EXPR and GT_EXPR or vice versa
10052 and put sole constants at the second argument position.
10053 Returns the canonicalized tree if changed, otherwise NULL_TREE. */
10055 static tree
10056 maybe_canonicalize_comparison (location_t loc, enum tree_code code, tree type,
10057 tree arg0, tree arg1)
10059 tree t;
10060 bool strict_overflow_p;
10061 const char * const warnmsg = G_("assuming signed overflow does not occur "
10062 "when reducing constant in comparison");
10064 /* Try canonicalization by simplifying arg0. */
10065 strict_overflow_p = false;
10066 t = maybe_canonicalize_comparison_1 (loc, code, type, arg0, arg1,
10067 &strict_overflow_p);
10068 if (t)
10070 if (strict_overflow_p)
10071 fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_MAGNITUDE);
10072 return t;
10075 /* Try canonicalization by simplifying arg1 using the swapped
10076 comparison. */
10077 code = swap_tree_comparison (code);
10078 strict_overflow_p = false;
10079 t = maybe_canonicalize_comparison_1 (loc, code, type, arg1, arg0,
10080 &strict_overflow_p);
10081 if (t && strict_overflow_p)
10082 fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_MAGNITUDE);
10083 return t;
10086 /* Return whether BASE + OFFSET + BITPOS may wrap around the address
10087 space. This is used to avoid issuing overflow warnings for
10088 expressions like &p->x which cannot wrap. */
10090 static bool
10091 pointer_may_wrap_p (tree base, tree offset, poly_int64 bitpos)
10093 if (!POINTER_TYPE_P (TREE_TYPE (base)))
10094 return true;
10096 if (maybe_lt (bitpos, 0))
10097 return true;
10099 poly_wide_int wi_offset;
10100 int precision = TYPE_PRECISION (TREE_TYPE (base));
10101 if (offset == NULL_TREE)
10102 wi_offset = wi::zero (precision);
10103 else if (!poly_int_tree_p (offset) || TREE_OVERFLOW (offset))
10104 return true;
10105 else
10106 wi_offset = wi::to_poly_wide (offset);
10108 wi::overflow_type overflow;
10109 poly_wide_int units = wi::shwi (bits_to_bytes_round_down (bitpos),
10110 precision);
10111 poly_wide_int total = wi::add (wi_offset, units, UNSIGNED, &overflow);
10112 if (overflow)
10113 return true;
10115 poly_uint64 total_hwi, size;
10116 if (!total.to_uhwi (&total_hwi)
10117 || !poly_int_tree_p (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (base))),
10118 &size)
10119 || known_eq (size, 0U))
10120 return true;
10122 if (known_le (total_hwi, size))
10123 return false;
10125 /* We can do slightly better for SIZE if we have an ADDR_EXPR of an
10126 array. */
10127 if (TREE_CODE (base) == ADDR_EXPR
10128 && poly_int_tree_p (TYPE_SIZE_UNIT (TREE_TYPE (TREE_OPERAND (base, 0))),
10129 &size)
10130 && maybe_ne (size, 0U)
10131 && known_le (total_hwi, size))
10132 return false;
10134 return true;
10137 /* Return a positive integer when the symbol DECL is known to have
10138 a nonzero address, zero when it's known not to (e.g., it's a weak
10139 symbol), and a negative integer when the symbol is not yet in the
10140 symbol table and so whether or not its address is zero is unknown.
10141 For function local objects always return positive integer. */
10142 static int
10143 maybe_nonzero_address (tree decl)
10145 /* Normally, don't do anything for variables and functions before symtab is
10146 built; it is quite possible that DECL will be declared weak later.
10147 But if folding_initializer, we need a constant answer now, so create
10148 the symtab entry and prevent later weak declaration. */
10149 if (DECL_P (decl) && decl_in_symtab_p (decl))
10150 if (struct symtab_node *symbol
10151 = (folding_initializer
10152 ? symtab_node::get_create (decl)
10153 : symtab_node::get (decl)))
10154 return symbol->nonzero_address ();
10156 /* Function local objects are never NULL. */
10157 if (DECL_P (decl)
10158 && (DECL_CONTEXT (decl)
10159 && TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL
10160 && auto_var_in_fn_p (decl, DECL_CONTEXT (decl))))
10161 return 1;
10163 return -1;
10166 /* Subroutine of fold_binary. This routine performs all of the
10167 transformations that are common to the equality/inequality
10168 operators (EQ_EXPR and NE_EXPR) and the ordering operators
10169 (LT_EXPR, LE_EXPR, GE_EXPR and GT_EXPR). Callers other than
10170 fold_binary should call fold_binary. Fold a comparison with
10171 tree code CODE and type TYPE with operands OP0 and OP1. Return
10172 the folded comparison or NULL_TREE. */
10174 static tree
10175 fold_comparison (location_t loc, enum tree_code code, tree type,
10176 tree op0, tree op1)
10178 const bool equality_code = (code == EQ_EXPR || code == NE_EXPR);
10179 tree arg0, arg1, tem;
10181 arg0 = op0;
10182 arg1 = op1;
10184 STRIP_SIGN_NOPS (arg0);
10185 STRIP_SIGN_NOPS (arg1);
10187 /* For comparisons of pointers we can decompose it to a compile time
10188 comparison of the base objects and the offsets into the object.
10189 This requires at least one operand being an ADDR_EXPR or a
10190 POINTER_PLUS_EXPR to do more than the operand_equal_p test below. */
10191 if (POINTER_TYPE_P (TREE_TYPE (arg0))
10192 && (TREE_CODE (arg0) == ADDR_EXPR
10193 || TREE_CODE (arg1) == ADDR_EXPR
10194 || TREE_CODE (arg0) == POINTER_PLUS_EXPR
10195 || TREE_CODE (arg1) == POINTER_PLUS_EXPR))
10197 tree base0, base1, offset0 = NULL_TREE, offset1 = NULL_TREE;
10198 poly_int64 bitsize, bitpos0 = 0, bitpos1 = 0;
10199 machine_mode mode;
10200 int volatilep, reversep, unsignedp;
10201 bool indirect_base0 = false, indirect_base1 = false;
10203 /* Get base and offset for the access. Strip ADDR_EXPR for
10204 get_inner_reference, but put it back by stripping INDIRECT_REF
10205 off the base object if possible. indirect_baseN will be true
10206 if baseN is not an address but refers to the object itself. */
10207 base0 = arg0;
10208 if (TREE_CODE (arg0) == ADDR_EXPR)
10210 base0
10211 = get_inner_reference (TREE_OPERAND (arg0, 0),
10212 &bitsize, &bitpos0, &offset0, &mode,
10213 &unsignedp, &reversep, &volatilep);
10214 if (INDIRECT_REF_P (base0))
10215 base0 = TREE_OPERAND (base0, 0);
10216 else
10217 indirect_base0 = true;
10219 else if (TREE_CODE (arg0) == POINTER_PLUS_EXPR)
10221 base0 = TREE_OPERAND (arg0, 0);
10222 STRIP_SIGN_NOPS (base0);
10223 if (TREE_CODE (base0) == ADDR_EXPR)
10225 base0
10226 = get_inner_reference (TREE_OPERAND (base0, 0),
10227 &bitsize, &bitpos0, &offset0, &mode,
10228 &unsignedp, &reversep, &volatilep);
10229 if (INDIRECT_REF_P (base0))
10230 base0 = TREE_OPERAND (base0, 0);
10231 else
10232 indirect_base0 = true;
10234 if (offset0 == NULL_TREE || integer_zerop (offset0))
10235 offset0 = TREE_OPERAND (arg0, 1);
10236 else
10237 offset0 = size_binop (PLUS_EXPR, offset0,
10238 TREE_OPERAND (arg0, 1));
10239 if (poly_int_tree_p (offset0))
10241 poly_offset_int tem = wi::sext (wi::to_poly_offset (offset0),
10242 TYPE_PRECISION (sizetype));
10243 tem <<= LOG2_BITS_PER_UNIT;
10244 tem += bitpos0;
10245 if (tem.to_shwi (&bitpos0))
10246 offset0 = NULL_TREE;
10250 base1 = arg1;
10251 if (TREE_CODE (arg1) == ADDR_EXPR)
10253 base1
10254 = get_inner_reference (TREE_OPERAND (arg1, 0),
10255 &bitsize, &bitpos1, &offset1, &mode,
10256 &unsignedp, &reversep, &volatilep);
10257 if (INDIRECT_REF_P (base1))
10258 base1 = TREE_OPERAND (base1, 0);
10259 else
10260 indirect_base1 = true;
10262 else if (TREE_CODE (arg1) == POINTER_PLUS_EXPR)
10264 base1 = TREE_OPERAND (arg1, 0);
10265 STRIP_SIGN_NOPS (base1);
10266 if (TREE_CODE (base1) == ADDR_EXPR)
10268 base1
10269 = get_inner_reference (TREE_OPERAND (base1, 0),
10270 &bitsize, &bitpos1, &offset1, &mode,
10271 &unsignedp, &reversep, &volatilep);
10272 if (INDIRECT_REF_P (base1))
10273 base1 = TREE_OPERAND (base1, 0);
10274 else
10275 indirect_base1 = true;
10277 if (offset1 == NULL_TREE || integer_zerop (offset1))
10278 offset1 = TREE_OPERAND (arg1, 1);
10279 else
10280 offset1 = size_binop (PLUS_EXPR, offset1,
10281 TREE_OPERAND (arg1, 1));
10282 if (poly_int_tree_p (offset1))
10284 poly_offset_int tem = wi::sext (wi::to_poly_offset (offset1),
10285 TYPE_PRECISION (sizetype));
10286 tem <<= LOG2_BITS_PER_UNIT;
10287 tem += bitpos1;
10288 if (tem.to_shwi (&bitpos1))
10289 offset1 = NULL_TREE;
10293 /* If we have equivalent bases we might be able to simplify. */
10294 if (indirect_base0 == indirect_base1
10295 && operand_equal_p (base0, base1,
10296 indirect_base0 ? OEP_ADDRESS_OF : 0))
10298 /* We can fold this expression to a constant if the non-constant
10299 offset parts are equal. */
10300 if ((offset0 == offset1
10301 || (offset0 && offset1
10302 && operand_equal_p (offset0, offset1, 0)))
10303 && (equality_code
10304 || (indirect_base0
10305 && (DECL_P (base0) || CONSTANT_CLASS_P (base0)))
10306 || TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg0))))
10308 if (!equality_code
10309 && maybe_ne (bitpos0, bitpos1)
10310 && (pointer_may_wrap_p (base0, offset0, bitpos0)
10311 || pointer_may_wrap_p (base1, offset1, bitpos1)))
10312 fold_overflow_warning (("assuming pointer wraparound does not "
10313 "occur when comparing P +- C1 with "
10314 "P +- C2"),
10315 WARN_STRICT_OVERFLOW_CONDITIONAL);
10317 switch (code)
10319 case EQ_EXPR:
10320 if (known_eq (bitpos0, bitpos1))
10321 return constant_boolean_node (true, type);
10322 if (known_ne (bitpos0, bitpos1))
10323 return constant_boolean_node (false, type);
10324 break;
10325 case NE_EXPR:
10326 if (known_ne (bitpos0, bitpos1))
10327 return constant_boolean_node (true, type);
10328 if (known_eq (bitpos0, bitpos1))
10329 return constant_boolean_node (false, type);
10330 break;
10331 case LT_EXPR:
10332 if (known_lt (bitpos0, bitpos1))
10333 return constant_boolean_node (true, type);
10334 if (known_ge (bitpos0, bitpos1))
10335 return constant_boolean_node (false, type);
10336 break;
10337 case LE_EXPR:
10338 if (known_le (bitpos0, bitpos1))
10339 return constant_boolean_node (true, type);
10340 if (known_gt (bitpos0, bitpos1))
10341 return constant_boolean_node (false, type);
10342 break;
10343 case GE_EXPR:
10344 if (known_ge (bitpos0, bitpos1))
10345 return constant_boolean_node (true, type);
10346 if (known_lt (bitpos0, bitpos1))
10347 return constant_boolean_node (false, type);
10348 break;
10349 case GT_EXPR:
10350 if (known_gt (bitpos0, bitpos1))
10351 return constant_boolean_node (true, type);
10352 if (known_le (bitpos0, bitpos1))
10353 return constant_boolean_node (false, type);
10354 break;
10355 default:;
10358 /* We can simplify the comparison to a comparison of the variable
10359 offset parts if the constant offset parts are equal.
10360 Be careful to use signed sizetype here because otherwise we
10361 mess with array offsets in the wrong way. This is possible
10362 because pointer arithmetic is restricted to retain within an
10363 object and overflow on pointer differences is undefined as of
10364 6.5.6/8 and /9 with respect to the signed ptrdiff_t. */
10365 else if (known_eq (bitpos0, bitpos1)
10366 && (equality_code
10367 || (indirect_base0
10368 && (DECL_P (base0) || CONSTANT_CLASS_P (base0)))
10369 || TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg0))))
10371 /* By converting to signed sizetype we cover middle-end pointer
10372 arithmetic which operates on unsigned pointer types of size
10373 type size and ARRAY_REF offsets which are properly sign or
10374 zero extended from their type in case it is narrower than
10375 sizetype. */
10376 if (offset0 == NULL_TREE)
10377 offset0 = build_int_cst (ssizetype, 0);
10378 else
10379 offset0 = fold_convert_loc (loc, ssizetype, offset0);
10380 if (offset1 == NULL_TREE)
10381 offset1 = build_int_cst (ssizetype, 0);
10382 else
10383 offset1 = fold_convert_loc (loc, ssizetype, offset1);
10385 if (!equality_code
10386 && (pointer_may_wrap_p (base0, offset0, bitpos0)
10387 || pointer_may_wrap_p (base1, offset1, bitpos1)))
10388 fold_overflow_warning (("assuming pointer wraparound does not "
10389 "occur when comparing P +- C1 with "
10390 "P +- C2"),
10391 WARN_STRICT_OVERFLOW_COMPARISON);
10393 return fold_build2_loc (loc, code, type, offset0, offset1);
10396 /* For equal offsets we can simplify to a comparison of the
10397 base addresses. */
10398 else if (known_eq (bitpos0, bitpos1)
10399 && (indirect_base0
10400 ? base0 != TREE_OPERAND (arg0, 0) : base0 != arg0)
10401 && (indirect_base1
10402 ? base1 != TREE_OPERAND (arg1, 0) : base1 != arg1)
10403 && ((offset0 == offset1)
10404 || (offset0 && offset1
10405 && operand_equal_p (offset0, offset1, 0))))
10407 if (indirect_base0)
10408 base0 = build_fold_addr_expr_loc (loc, base0);
10409 if (indirect_base1)
10410 base1 = build_fold_addr_expr_loc (loc, base1);
10411 return fold_build2_loc (loc, code, type, base0, base1);
10413 /* Comparison between an ordinary (non-weak) symbol and a null
10414 pointer can be eliminated since such symbols must have a non
10415 null address. In C, relational expressions between pointers
10416 to objects and null pointers are undefined. The results
10417 below follow the C++ rules with the additional property that
10418 every object pointer compares greater than a null pointer.
10420 else if (((DECL_P (base0)
10421 && maybe_nonzero_address (base0) > 0
10422 /* Avoid folding references to struct members at offset 0 to
10423 prevent tests like '&ptr->firstmember == 0' from getting
10424 eliminated. When ptr is null, although the -> expression
10425 is strictly speaking invalid, GCC retains it as a matter
10426 of QoI. See PR c/44555. */
10427 && (offset0 == NULL_TREE && known_ne (bitpos0, 0)))
10428 || CONSTANT_CLASS_P (base0))
10429 && indirect_base0
10430 /* The caller guarantees that when one of the arguments is
10431 constant (i.e., null in this case) it is second. */
10432 && integer_zerop (arg1))
10434 switch (code)
10436 case EQ_EXPR:
10437 case LE_EXPR:
10438 case LT_EXPR:
10439 return constant_boolean_node (false, type);
10440 case GE_EXPR:
10441 case GT_EXPR:
10442 case NE_EXPR:
10443 return constant_boolean_node (true, type);
10444 default:
10445 gcc_unreachable ();
10450 /* Transform comparisons of the form X +- C1 CMP Y +- C2 to
10451 X CMP Y +- C2 +- C1 for signed X, Y. This is valid if
10452 the resulting offset is smaller in absolute value than the
10453 original one and has the same sign. */
10454 if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (arg0))
10455 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg0))
10456 && (TREE_CODE (arg0) == PLUS_EXPR || TREE_CODE (arg0) == MINUS_EXPR)
10457 && (TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
10458 && !TREE_OVERFLOW (TREE_OPERAND (arg0, 1)))
10459 && (TREE_CODE (arg1) == PLUS_EXPR || TREE_CODE (arg1) == MINUS_EXPR)
10460 && (TREE_CODE (TREE_OPERAND (arg1, 1)) == INTEGER_CST
10461 && !TREE_OVERFLOW (TREE_OPERAND (arg1, 1))))
10463 tree const1 = TREE_OPERAND (arg0, 1);
10464 tree const2 = TREE_OPERAND (arg1, 1);
10465 tree variable1 = TREE_OPERAND (arg0, 0);
10466 tree variable2 = TREE_OPERAND (arg1, 0);
10467 tree cst;
10468 const char * const warnmsg = G_("assuming signed overflow does not "
10469 "occur when combining constants around "
10470 "a comparison");
10472 /* Put the constant on the side where it doesn't overflow and is
10473 of lower absolute value and of same sign than before. */
10474 cst = int_const_binop (TREE_CODE (arg0) == TREE_CODE (arg1)
10475 ? MINUS_EXPR : PLUS_EXPR,
10476 const2, const1);
10477 if (!TREE_OVERFLOW (cst)
10478 && tree_int_cst_compare (const2, cst) == tree_int_cst_sgn (const2)
10479 && tree_int_cst_sgn (cst) == tree_int_cst_sgn (const2))
10481 fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_COMPARISON);
10482 return fold_build2_loc (loc, code, type,
10483 variable1,
10484 fold_build2_loc (loc, TREE_CODE (arg1),
10485 TREE_TYPE (arg1),
10486 variable2, cst));
10489 cst = int_const_binop (TREE_CODE (arg0) == TREE_CODE (arg1)
10490 ? MINUS_EXPR : PLUS_EXPR,
10491 const1, const2);
10492 if (!TREE_OVERFLOW (cst)
10493 && tree_int_cst_compare (const1, cst) == tree_int_cst_sgn (const1)
10494 && tree_int_cst_sgn (cst) == tree_int_cst_sgn (const1))
10496 fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_COMPARISON);
10497 return fold_build2_loc (loc, code, type,
10498 fold_build2_loc (loc, TREE_CODE (arg0),
10499 TREE_TYPE (arg0),
10500 variable1, cst),
10501 variable2);
10505 tem = maybe_canonicalize_comparison (loc, code, type, arg0, arg1);
10506 if (tem)
10507 return tem;
10509 /* If we are comparing an expression that just has comparisons
10510 of two integer values, arithmetic expressions of those comparisons,
10511 and constants, we can simplify it. There are only three cases
10512 to check: the two values can either be equal, the first can be
10513 greater, or the second can be greater. Fold the expression for
10514 those three values. Since each value must be 0 or 1, we have
10515 eight possibilities, each of which corresponds to the constant 0
10516 or 1 or one of the six possible comparisons.
10518 This handles common cases like (a > b) == 0 but also handles
10519 expressions like ((x > y) - (y > x)) > 0, which supposedly
10520 occur in macroized code. */
10522 if (TREE_CODE (arg1) == INTEGER_CST && TREE_CODE (arg0) != INTEGER_CST)
10524 tree cval1 = 0, cval2 = 0;
10526 if (twoval_comparison_p (arg0, &cval1, &cval2)
10527 /* Don't handle degenerate cases here; they should already
10528 have been handled anyway. */
10529 && cval1 != 0 && cval2 != 0
10530 && ! (TREE_CONSTANT (cval1) && TREE_CONSTANT (cval2))
10531 && TREE_TYPE (cval1) == TREE_TYPE (cval2)
10532 && INTEGRAL_TYPE_P (TREE_TYPE (cval1))
10533 && TYPE_MAX_VALUE (TREE_TYPE (cval1))
10534 && TYPE_MAX_VALUE (TREE_TYPE (cval2))
10535 && ! operand_equal_p (TYPE_MIN_VALUE (TREE_TYPE (cval1)),
10536 TYPE_MAX_VALUE (TREE_TYPE (cval2)), 0))
10538 tree maxval = TYPE_MAX_VALUE (TREE_TYPE (cval1));
10539 tree minval = TYPE_MIN_VALUE (TREE_TYPE (cval1));
10541 /* We can't just pass T to eval_subst in case cval1 or cval2
10542 was the same as ARG1. */
10544 tree high_result
10545 = fold_build2_loc (loc, code, type,
10546 eval_subst (loc, arg0, cval1, maxval,
10547 cval2, minval),
10548 arg1);
10549 tree equal_result
10550 = fold_build2_loc (loc, code, type,
10551 eval_subst (loc, arg0, cval1, maxval,
10552 cval2, maxval),
10553 arg1);
10554 tree low_result
10555 = fold_build2_loc (loc, code, type,
10556 eval_subst (loc, arg0, cval1, minval,
10557 cval2, maxval),
10558 arg1);
10560 /* All three of these results should be 0 or 1. Confirm they are.
10561 Then use those values to select the proper code to use. */
10563 if (TREE_CODE (high_result) == INTEGER_CST
10564 && TREE_CODE (equal_result) == INTEGER_CST
10565 && TREE_CODE (low_result) == INTEGER_CST)
10567 /* Make a 3-bit mask with the high-order bit being the
10568 value for `>', the next for '=', and the low for '<'. */
10569 switch ((integer_onep (high_result) * 4)
10570 + (integer_onep (equal_result) * 2)
10571 + integer_onep (low_result))
10573 case 0:
10574 /* Always false. */
10575 return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
10576 case 1:
10577 code = LT_EXPR;
10578 break;
10579 case 2:
10580 code = EQ_EXPR;
10581 break;
10582 case 3:
10583 code = LE_EXPR;
10584 break;
10585 case 4:
10586 code = GT_EXPR;
10587 break;
10588 case 5:
10589 code = NE_EXPR;
10590 break;
10591 case 6:
10592 code = GE_EXPR;
10593 break;
10594 case 7:
10595 /* Always true. */
10596 return omit_one_operand_loc (loc, type, integer_one_node, arg0);
10599 return fold_build2_loc (loc, code, type, cval1, cval2);
10604 return NULL_TREE;
10608 /* Subroutine of fold_binary. Optimize complex multiplications of the
10609 form z * conj(z), as pow(realpart(z),2) + pow(imagpart(z),2). The
10610 argument EXPR represents the expression "z" of type TYPE. */
10612 static tree
10613 fold_mult_zconjz (location_t loc, tree type, tree expr)
10615 tree itype = TREE_TYPE (type);
10616 tree rpart, ipart, tem;
10618 if (TREE_CODE (expr) == COMPLEX_EXPR)
10620 rpart = TREE_OPERAND (expr, 0);
10621 ipart = TREE_OPERAND (expr, 1);
10623 else if (TREE_CODE (expr) == COMPLEX_CST)
10625 rpart = TREE_REALPART (expr);
10626 ipart = TREE_IMAGPART (expr);
10628 else
10630 expr = save_expr (expr);
10631 rpart = fold_build1_loc (loc, REALPART_EXPR, itype, expr);
10632 ipart = fold_build1_loc (loc, IMAGPART_EXPR, itype, expr);
10635 rpart = save_expr (rpart);
10636 ipart = save_expr (ipart);
10637 tem = fold_build2_loc (loc, PLUS_EXPR, itype,
10638 fold_build2_loc (loc, MULT_EXPR, itype, rpart, rpart),
10639 fold_build2_loc (loc, MULT_EXPR, itype, ipart, ipart));
10640 return fold_build2_loc (loc, COMPLEX_EXPR, type, tem,
10641 build_zero_cst (itype));
10645 /* Helper function for fold_vec_perm. Store elements of VECTOR_CST or
10646 CONSTRUCTOR ARG into array ELTS, which has NELTS elements, and return
10647 true if successful. */
10649 static bool
10650 vec_cst_ctor_to_array (tree arg, unsigned int nelts, tree *elts)
10652 unsigned HOST_WIDE_INT i, nunits;
10654 if (TREE_CODE (arg) == VECTOR_CST
10655 && VECTOR_CST_NELTS (arg).is_constant (&nunits))
10657 for (i = 0; i < nunits; ++i)
10658 elts[i] = VECTOR_CST_ELT (arg, i);
10660 else if (TREE_CODE (arg) == CONSTRUCTOR)
10662 constructor_elt *elt;
10664 FOR_EACH_VEC_SAFE_ELT (CONSTRUCTOR_ELTS (arg), i, elt)
10665 if (i >= nelts || TREE_CODE (TREE_TYPE (elt->value)) == VECTOR_TYPE)
10666 return false;
10667 else
10668 elts[i] = elt->value;
10670 else
10671 return false;
10672 for (; i < nelts; i++)
10673 elts[i]
10674 = fold_convert (TREE_TYPE (TREE_TYPE (arg)), integer_zero_node);
10675 return true;
10678 /* Helper routine for fold_vec_perm_cst to check if SEL is a suitable
10679 mask for VLA vec_perm folding.
10680 REASON if specified, will contain the reason why SEL is not suitable.
10681 Used only for debugging and unit-testing. */
10683 static bool
10684 valid_mask_for_fold_vec_perm_cst_p (tree arg0, tree arg1,
10685 const vec_perm_indices &sel,
10686 const char **reason = NULL)
10688 unsigned sel_npatterns = sel.encoding ().npatterns ();
10689 unsigned sel_nelts_per_pattern = sel.encoding ().nelts_per_pattern ();
10691 if (!(pow2p_hwi (sel_npatterns)
10692 && pow2p_hwi (VECTOR_CST_NPATTERNS (arg0))
10693 && pow2p_hwi (VECTOR_CST_NPATTERNS (arg1))))
10695 if (reason)
10696 *reason = "npatterns is not power of 2";
10697 return false;
10700 /* We want to avoid cases where sel.length is not a multiple of npatterns.
10701 For eg: sel.length = 2 + 2x, and sel npatterns = 4. */
10702 poly_uint64 esel;
10703 if (!multiple_p (sel.length (), sel_npatterns, &esel))
10705 if (reason)
10706 *reason = "sel.length is not multiple of sel_npatterns";
10707 return false;
10710 if (sel_nelts_per_pattern < 3)
10711 return true;
10713 for (unsigned pattern = 0; pattern < sel_npatterns; pattern++)
10715 poly_uint64 a1 = sel[pattern + sel_npatterns];
10716 poly_uint64 a2 = sel[pattern + 2 * sel_npatterns];
10717 HOST_WIDE_INT step;
10718 if (!poly_int64 (a2 - a1).is_constant (&step))
10720 if (reason)
10721 *reason = "step is not constant";
10722 return false;
10724 // FIXME: Punt on step < 0 for now, revisit later.
10725 if (step < 0)
10726 return false;
10727 if (step == 0)
10728 continue;
10730 if (!pow2p_hwi (step))
10732 if (reason)
10733 *reason = "step is not power of 2";
10734 return false;
10737 /* Ensure that stepped sequence of the pattern selects elements
10738 only from the same input vector. */
10739 uint64_t q1, qe;
10740 poly_uint64 r1, re;
10741 poly_uint64 ae = a1 + (esel - 2) * step;
10742 poly_uint64 arg_len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
10744 if (!(can_div_trunc_p (a1, arg_len, &q1, &r1)
10745 && can_div_trunc_p (ae, arg_len, &qe, &re)
10746 && q1 == qe))
10748 if (reason)
10749 *reason = "crossed input vectors";
10750 return false;
10753 /* Ensure that the stepped sequence always selects from the same
10754 input pattern. */
10755 tree arg = ((q1 & 1) == 0) ? arg0 : arg1;
10756 unsigned arg_npatterns = VECTOR_CST_NPATTERNS (arg);
10758 if (!multiple_p (step, arg_npatterns))
10760 if (reason)
10761 *reason = "step is not multiple of npatterns";
10762 return false;
10765 /* If a1 chooses base element from arg, ensure that it's a natural
10766 stepped sequence, ie, (arg[2] - arg[1]) == (arg[1] - arg[0])
10767 to preserve arg's encoding. */
10769 if (maybe_lt (r1, arg_npatterns))
10771 unsigned HOST_WIDE_INT index;
10772 if (!r1.is_constant (&index))
10773 return false;
10775 tree arg_elem0 = vector_cst_elt (arg, index);
10776 tree arg_elem1 = vector_cst_elt (arg, index + arg_npatterns);
10777 tree arg_elem2 = vector_cst_elt (arg, index + arg_npatterns * 2);
10779 tree step1, step2;
10780 if (!(step1 = const_binop (MINUS_EXPR, arg_elem1, arg_elem0))
10781 || !(step2 = const_binop (MINUS_EXPR, arg_elem2, arg_elem1))
10782 || !operand_equal_p (step1, step2, 0))
10784 if (reason)
10785 *reason = "not a natural stepped sequence";
10786 return false;
10791 return true;
10794 /* Try to fold permutation of ARG0 and ARG1 with SEL selector when
10795 the input vectors are VECTOR_CST. Return NULL_TREE otherwise.
10796 REASON has same purpose as described in
10797 valid_mask_for_fold_vec_perm_cst_p. */
10799 static tree
10800 fold_vec_perm_cst (tree type, tree arg0, tree arg1, const vec_perm_indices &sel,
10801 const char **reason = NULL)
10803 unsigned res_npatterns, res_nelts_per_pattern;
10804 unsigned HOST_WIDE_INT res_nelts;
10806 /* First try to implement the fold in a VLA-friendly way.
10808 (1) If the selector is simply a duplication of N elements, the
10809 result is likewise a duplication of N elements.
10811 (2) If the selector is N elements followed by a duplication
10812 of N elements, the result is too.
10814 (3) If the selector is N elements followed by an interleaving
10815 of N linear series, the situation is more complex.
10817 valid_mask_for_fold_vec_perm_cst_p detects whether we
10818 can handle this case. If we can, then each of the N linear
10819 series either (a) selects the same element each time or
10820 (b) selects a linear series from one of the input patterns.
10822 If (b) holds for one of the linear series, the result
10823 will contain a linear series, and so the result will have
10824 the same shape as the selector. If (a) holds for all of
10825 the linear series, the result will be the same as (2) above.
10827 (b) can only hold if one of the input patterns has a
10828 stepped encoding. */
10830 if (valid_mask_for_fold_vec_perm_cst_p (arg0, arg1, sel, reason))
10832 res_npatterns = sel.encoding ().npatterns ();
10833 res_nelts_per_pattern = sel.encoding ().nelts_per_pattern ();
10834 if (res_nelts_per_pattern == 3
10835 && VECTOR_CST_NELTS_PER_PATTERN (arg0) < 3
10836 && VECTOR_CST_NELTS_PER_PATTERN (arg1) < 3)
10837 res_nelts_per_pattern = 2;
10838 res_nelts = res_npatterns * res_nelts_per_pattern;
10840 else if (TYPE_VECTOR_SUBPARTS (type).is_constant (&res_nelts))
10842 res_npatterns = res_nelts;
10843 res_nelts_per_pattern = 1;
10845 else
10846 return NULL_TREE;
10848 tree_vector_builder out_elts (type, res_npatterns, res_nelts_per_pattern);
10849 for (unsigned i = 0; i < res_nelts; i++)
10851 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
10852 uint64_t q;
10853 poly_uint64 r;
10854 unsigned HOST_WIDE_INT index;
10856 /* Punt if sel[i] /trunc_div len cannot be determined,
10857 because the input vector to be chosen will depend on
10858 runtime vector length.
10859 For example if len == 4 + 4x, and sel[i] == 4,
10860 If len at runtime equals 4, we choose arg1[0].
10861 For any other value of len > 4 at runtime, we choose arg0[4].
10862 which makes the element choice dependent on runtime vector length. */
10863 if (!can_div_trunc_p (sel[i], len, &q, &r))
10865 if (reason)
10866 *reason = "cannot divide selector element by arg len";
10867 return NULL_TREE;
10870 /* sel[i] % len will give the index of element in the chosen input
10871 vector. For example if sel[i] == 5 + 4x and len == 4 + 4x,
10872 we will choose arg1[1] since (5 + 4x) % (4 + 4x) == 1. */
10873 if (!r.is_constant (&index))
10875 if (reason)
10876 *reason = "remainder is not constant";
10877 return NULL_TREE;
10880 tree arg = ((q & 1) == 0) ? arg0 : arg1;
10881 tree elem = vector_cst_elt (arg, index);
10882 out_elts.quick_push (elem);
10885 return out_elts.build ();
10888 /* Attempt to fold vector permutation of ARG0 and ARG1 vectors using SEL
10889 selector. Return the folded VECTOR_CST or CONSTRUCTOR if successful,
10890 NULL_TREE otherwise. */
10892 tree
10893 fold_vec_perm (tree type, tree arg0, tree arg1, const vec_perm_indices &sel)
10895 unsigned int i;
10896 unsigned HOST_WIDE_INT nelts;
10898 gcc_assert (known_eq (TYPE_VECTOR_SUBPARTS (type), sel.length ())
10899 && known_eq (TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0)),
10900 TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg1))));
10902 if (TREE_TYPE (TREE_TYPE (arg0)) != TREE_TYPE (type)
10903 || TREE_TYPE (TREE_TYPE (arg1)) != TREE_TYPE (type))
10904 return NULL_TREE;
10906 if (TREE_CODE (arg0) == VECTOR_CST
10907 && TREE_CODE (arg1) == VECTOR_CST)
10908 return fold_vec_perm_cst (type, arg0, arg1, sel);
10910 /* For fall back case, we want to ensure we have VLS vectors
10911 with equal length. */
10912 if (!sel.length ().is_constant (&nelts))
10913 return NULL_TREE;
10915 gcc_assert (known_eq (sel.length (),
10916 TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0))));
10917 tree *in_elts = XALLOCAVEC (tree, nelts * 2);
10918 if (!vec_cst_ctor_to_array (arg0, nelts, in_elts)
10919 || !vec_cst_ctor_to_array (arg1, nelts, in_elts + nelts))
10920 return NULL_TREE;
10922 vec<constructor_elt, va_gc> *v;
10923 vec_alloc (v, nelts);
10924 for (i = 0; i < nelts; i++)
10926 HOST_WIDE_INT index;
10927 if (!sel[i].is_constant (&index))
10928 return NULL_TREE;
10929 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, in_elts[index]);
10931 return build_constructor (type, v);
10934 /* Try to fold a pointer difference of type TYPE two address expressions of
10935 array references AREF0 and AREF1 using location LOC. Return a
10936 simplified expression for the difference or NULL_TREE. */
10938 static tree
10939 fold_addr_of_array_ref_difference (location_t loc, tree type,
10940 tree aref0, tree aref1,
10941 bool use_pointer_diff)
10943 tree base0 = TREE_OPERAND (aref0, 0);
10944 tree base1 = TREE_OPERAND (aref1, 0);
10945 tree base_offset = build_int_cst (type, 0);
10947 /* If the bases are array references as well, recurse. If the bases
10948 are pointer indirections compute the difference of the pointers.
10949 If the bases are equal, we are set. */
10950 if ((TREE_CODE (base0) == ARRAY_REF
10951 && TREE_CODE (base1) == ARRAY_REF
10952 && (base_offset
10953 = fold_addr_of_array_ref_difference (loc, type, base0, base1,
10954 use_pointer_diff)))
10955 || (INDIRECT_REF_P (base0)
10956 && INDIRECT_REF_P (base1)
10957 && (base_offset
10958 = use_pointer_diff
10959 ? fold_binary_loc (loc, POINTER_DIFF_EXPR, type,
10960 TREE_OPERAND (base0, 0),
10961 TREE_OPERAND (base1, 0))
10962 : fold_binary_loc (loc, MINUS_EXPR, type,
10963 fold_convert (type,
10964 TREE_OPERAND (base0, 0)),
10965 fold_convert (type,
10966 TREE_OPERAND (base1, 0)))))
10967 || operand_equal_p (base0, base1, OEP_ADDRESS_OF))
10969 tree op0 = fold_convert_loc (loc, type, TREE_OPERAND (aref0, 1));
10970 tree op1 = fold_convert_loc (loc, type, TREE_OPERAND (aref1, 1));
10971 tree esz = fold_convert_loc (loc, type, array_ref_element_size (aref0));
10972 tree diff = fold_build2_loc (loc, MINUS_EXPR, type, op0, op1);
10973 return fold_build2_loc (loc, PLUS_EXPR, type,
10974 base_offset,
10975 fold_build2_loc (loc, MULT_EXPR, type,
10976 diff, esz));
10978 return NULL_TREE;
10981 /* If the real or vector real constant CST of type TYPE has an exact
10982 inverse, return it, else return NULL. */
10984 tree
10985 exact_inverse (tree type, tree cst)
10987 REAL_VALUE_TYPE r;
10988 tree unit_type;
10989 machine_mode mode;
10991 switch (TREE_CODE (cst))
10993 case REAL_CST:
10994 r = TREE_REAL_CST (cst);
10996 if (exact_real_inverse (TYPE_MODE (type), &r))
10997 return build_real (type, r);
10999 return NULL_TREE;
11001 case VECTOR_CST:
11003 unit_type = TREE_TYPE (type);
11004 mode = TYPE_MODE (unit_type);
11006 tree_vector_builder elts;
11007 if (!elts.new_unary_operation (type, cst, false))
11008 return NULL_TREE;
11009 unsigned int count = elts.encoded_nelts ();
11010 for (unsigned int i = 0; i < count; ++i)
11012 r = TREE_REAL_CST (VECTOR_CST_ELT (cst, i));
11013 if (!exact_real_inverse (mode, &r))
11014 return NULL_TREE;
11015 elts.quick_push (build_real (unit_type, r));
11018 return elts.build ();
11021 default:
11022 return NULL_TREE;
11026 /* Mask out the tz least significant bits of X of type TYPE where
11027 tz is the number of trailing zeroes in Y. */
11028 static wide_int
11029 mask_with_tz (tree type, const wide_int &x, const wide_int &y)
11031 int tz = wi::ctz (y);
11032 if (tz > 0)
11033 return wi::mask (tz, true, TYPE_PRECISION (type)) & x;
11034 return x;
11037 /* Return true when T is an address and is known to be nonzero.
11038 For floating point we further ensure that T is not denormal.
11039 Similar logic is present in nonzero_address in rtlanal.h.
11041 If the return value is based on the assumption that signed overflow
11042 is undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't
11043 change *STRICT_OVERFLOW_P. */
11045 static bool
11046 tree_expr_nonzero_warnv_p (tree t, bool *strict_overflow_p)
11048 tree type = TREE_TYPE (t);
11049 enum tree_code code;
11051 /* Doing something useful for floating point would need more work. */
11052 if (!INTEGRAL_TYPE_P (type) && !POINTER_TYPE_P (type))
11053 return false;
11055 code = TREE_CODE (t);
11056 switch (TREE_CODE_CLASS (code))
11058 case tcc_unary:
11059 return tree_unary_nonzero_warnv_p (code, type, TREE_OPERAND (t, 0),
11060 strict_overflow_p);
11061 case tcc_binary:
11062 case tcc_comparison:
11063 return tree_binary_nonzero_warnv_p (code, type,
11064 TREE_OPERAND (t, 0),
11065 TREE_OPERAND (t, 1),
11066 strict_overflow_p);
11067 case tcc_constant:
11068 case tcc_declaration:
11069 case tcc_reference:
11070 return tree_single_nonzero_warnv_p (t, strict_overflow_p);
11072 default:
11073 break;
11076 switch (code)
11078 case TRUTH_NOT_EXPR:
11079 return tree_unary_nonzero_warnv_p (code, type, TREE_OPERAND (t, 0),
11080 strict_overflow_p);
11082 case TRUTH_AND_EXPR:
11083 case TRUTH_OR_EXPR:
11084 case TRUTH_XOR_EXPR:
11085 return tree_binary_nonzero_warnv_p (code, type,
11086 TREE_OPERAND (t, 0),
11087 TREE_OPERAND (t, 1),
11088 strict_overflow_p);
11090 case COND_EXPR:
11091 case CONSTRUCTOR:
11092 case OBJ_TYPE_REF:
11093 case ADDR_EXPR:
11094 case WITH_SIZE_EXPR:
11095 case SSA_NAME:
11096 return tree_single_nonzero_warnv_p (t, strict_overflow_p);
11098 case COMPOUND_EXPR:
11099 case MODIFY_EXPR:
11100 case BIND_EXPR:
11101 return tree_expr_nonzero_warnv_p (TREE_OPERAND (t, 1),
11102 strict_overflow_p);
11104 case SAVE_EXPR:
11105 return tree_expr_nonzero_warnv_p (TREE_OPERAND (t, 0),
11106 strict_overflow_p);
11108 case CALL_EXPR:
11110 tree fndecl = get_callee_fndecl (t);
11111 if (!fndecl) return false;
11112 if (flag_delete_null_pointer_checks && !flag_check_new
11113 && DECL_IS_OPERATOR_NEW_P (fndecl)
11114 && !TREE_NOTHROW (fndecl))
11115 return true;
11116 if (flag_delete_null_pointer_checks
11117 && lookup_attribute ("returns_nonnull",
11118 TYPE_ATTRIBUTES (TREE_TYPE (fndecl))))
11119 return true;
11120 return alloca_call_p (t);
11123 default:
11124 break;
11126 return false;
11129 /* Return true when T is an address and is known to be nonzero.
11130 Handle warnings about undefined signed overflow. */
11132 bool
11133 tree_expr_nonzero_p (tree t)
11135 bool ret, strict_overflow_p;
11137 strict_overflow_p = false;
11138 ret = tree_expr_nonzero_warnv_p (t, &strict_overflow_p);
11139 if (strict_overflow_p)
11140 fold_overflow_warning (("assuming signed overflow does not occur when "
11141 "determining that expression is always "
11142 "non-zero"),
11143 WARN_STRICT_OVERFLOW_MISC);
11144 return ret;
11147 /* Return true if T is known not to be equal to an integer W. */
11149 bool
11150 expr_not_equal_to (tree t, const wide_int &w)
11152 int_range_max vr;
11153 switch (TREE_CODE (t))
11155 case INTEGER_CST:
11156 return wi::to_wide (t) != w;
11158 case SSA_NAME:
11159 if (!INTEGRAL_TYPE_P (TREE_TYPE (t)))
11160 return false;
11162 get_range_query (cfun)->range_of_expr (vr, t);
11163 if (!vr.undefined_p () && !vr.contains_p (w))
11164 return true;
11165 /* If T has some known zero bits and W has any of those bits set,
11166 then T is known not to be equal to W. */
11167 if (wi::ne_p (wi::zext (wi::bit_and_not (w, get_nonzero_bits (t)),
11168 TYPE_PRECISION (TREE_TYPE (t))), 0))
11169 return true;
11170 return false;
11172 default:
11173 return false;
11177 /* Fold a binary expression of code CODE and type TYPE with operands
11178 OP0 and OP1. LOC is the location of the resulting expression.
11179 Return the folded expression if folding is successful. Otherwise,
11180 return NULL_TREE. */
11182 tree
11183 fold_binary_loc (location_t loc, enum tree_code code, tree type,
11184 tree op0, tree op1)
11186 enum tree_code_class kind = TREE_CODE_CLASS (code);
11187 tree arg0, arg1, tem;
11188 tree t1 = NULL_TREE;
11189 bool strict_overflow_p;
11190 unsigned int prec;
11192 gcc_assert (IS_EXPR_CODE_CLASS (kind)
11193 && TREE_CODE_LENGTH (code) == 2
11194 && op0 != NULL_TREE
11195 && op1 != NULL_TREE);
11197 arg0 = op0;
11198 arg1 = op1;
11200 /* Strip any conversions that don't change the mode. This is
11201 safe for every expression, except for a comparison expression
11202 because its signedness is derived from its operands. So, in
11203 the latter case, only strip conversions that don't change the
11204 signedness. MIN_EXPR/MAX_EXPR also need signedness of arguments
11205 preserved.
11207 Note that this is done as an internal manipulation within the
11208 constant folder, in order to find the simplest representation
11209 of the arguments so that their form can be studied. In any
11210 cases, the appropriate type conversions should be put back in
11211 the tree that will get out of the constant folder. */
11213 if (kind == tcc_comparison || code == MIN_EXPR || code == MAX_EXPR)
11215 STRIP_SIGN_NOPS (arg0);
11216 STRIP_SIGN_NOPS (arg1);
11218 else
11220 STRIP_NOPS (arg0);
11221 STRIP_NOPS (arg1);
11224 /* Note that TREE_CONSTANT isn't enough: static var addresses are
11225 constant but we can't do arithmetic on them. */
11226 if (CONSTANT_CLASS_P (arg0) && CONSTANT_CLASS_P (arg1))
11228 tem = const_binop (code, type, arg0, arg1);
11229 if (tem != NULL_TREE)
11231 if (TREE_TYPE (tem) != type)
11232 tem = fold_convert_loc (loc, type, tem);
11233 return tem;
11237 /* If this is a commutative operation, and ARG0 is a constant, move it
11238 to ARG1 to reduce the number of tests below. */
11239 if (commutative_tree_code (code)
11240 && tree_swap_operands_p (arg0, arg1))
11241 return fold_build2_loc (loc, code, type, op1, op0);
11243 /* Likewise if this is a comparison, and ARG0 is a constant, move it
11244 to ARG1 to reduce the number of tests below. */
11245 if (kind == tcc_comparison
11246 && tree_swap_operands_p (arg0, arg1))
11247 return fold_build2_loc (loc, swap_tree_comparison (code), type, op1, op0);
11249 tem = generic_simplify (loc, code, type, op0, op1);
11250 if (tem)
11251 return tem;
11253 /* ARG0 is the first operand of EXPR, and ARG1 is the second operand.
11255 First check for cases where an arithmetic operation is applied to a
11256 compound, conditional, or comparison operation. Push the arithmetic
11257 operation inside the compound or conditional to see if any folding
11258 can then be done. Convert comparison to conditional for this purpose.
11259 The also optimizes non-constant cases that used to be done in
11260 expand_expr.
11262 Before we do that, see if this is a BIT_AND_EXPR or a BIT_IOR_EXPR,
11263 one of the operands is a comparison and the other is a comparison, a
11264 BIT_AND_EXPR with the constant 1, or a truth value. In that case, the
11265 code below would make the expression more complex. Change it to a
11266 TRUTH_{AND,OR}_EXPR. Likewise, convert a similar NE_EXPR to
11267 TRUTH_XOR_EXPR and an EQ_EXPR to the inversion of a TRUTH_XOR_EXPR. */
11269 if ((code == BIT_AND_EXPR || code == BIT_IOR_EXPR
11270 || code == EQ_EXPR || code == NE_EXPR)
11271 && !VECTOR_TYPE_P (TREE_TYPE (arg0))
11272 && ((truth_value_p (TREE_CODE (arg0))
11273 && (truth_value_p (TREE_CODE (arg1))
11274 || (TREE_CODE (arg1) == BIT_AND_EXPR
11275 && integer_onep (TREE_OPERAND (arg1, 1)))))
11276 || (truth_value_p (TREE_CODE (arg1))
11277 && (truth_value_p (TREE_CODE (arg0))
11278 || (TREE_CODE (arg0) == BIT_AND_EXPR
11279 && integer_onep (TREE_OPERAND (arg0, 1)))))))
11281 tem = fold_build2_loc (loc, code == BIT_AND_EXPR ? TRUTH_AND_EXPR
11282 : code == BIT_IOR_EXPR ? TRUTH_OR_EXPR
11283 : TRUTH_XOR_EXPR,
11284 boolean_type_node,
11285 fold_convert_loc (loc, boolean_type_node, arg0),
11286 fold_convert_loc (loc, boolean_type_node, arg1));
11288 if (code == EQ_EXPR)
11289 tem = invert_truthvalue_loc (loc, tem);
11291 return fold_convert_loc (loc, type, tem);
11294 if (TREE_CODE_CLASS (code) == tcc_binary
11295 || TREE_CODE_CLASS (code) == tcc_comparison)
11297 if (TREE_CODE (arg0) == COMPOUND_EXPR)
11299 tem = fold_build2_loc (loc, code, type,
11300 fold_convert_loc (loc, TREE_TYPE (op0),
11301 TREE_OPERAND (arg0, 1)), op1);
11302 return build2_loc (loc, COMPOUND_EXPR, type, TREE_OPERAND (arg0, 0),
11303 tem);
11305 if (TREE_CODE (arg1) == COMPOUND_EXPR)
11307 tem = fold_build2_loc (loc, code, type, op0,
11308 fold_convert_loc (loc, TREE_TYPE (op1),
11309 TREE_OPERAND (arg1, 1)));
11310 return build2_loc (loc, COMPOUND_EXPR, type, TREE_OPERAND (arg1, 0),
11311 tem);
11314 if (TREE_CODE (arg0) == COND_EXPR
11315 || TREE_CODE (arg0) == VEC_COND_EXPR
11316 || COMPARISON_CLASS_P (arg0))
11318 tem = fold_binary_op_with_conditional_arg (loc, code, type, op0, op1,
11319 arg0, arg1,
11320 /*cond_first_p=*/1);
11321 if (tem != NULL_TREE)
11322 return tem;
11325 if (TREE_CODE (arg1) == COND_EXPR
11326 || TREE_CODE (arg1) == VEC_COND_EXPR
11327 || COMPARISON_CLASS_P (arg1))
11329 tem = fold_binary_op_with_conditional_arg (loc, code, type, op0, op1,
11330 arg1, arg0,
11331 /*cond_first_p=*/0);
11332 if (tem != NULL_TREE)
11333 return tem;
11337 switch (code)
11339 case MEM_REF:
11340 /* MEM[&MEM[p, CST1], CST2] -> MEM[p, CST1 + CST2]. */
11341 if (TREE_CODE (arg0) == ADDR_EXPR
11342 && TREE_CODE (TREE_OPERAND (arg0, 0)) == MEM_REF)
11344 tree iref = TREE_OPERAND (arg0, 0);
11345 return fold_build2 (MEM_REF, type,
11346 TREE_OPERAND (iref, 0),
11347 int_const_binop (PLUS_EXPR, arg1,
11348 TREE_OPERAND (iref, 1)));
11351 /* MEM[&a.b, CST2] -> MEM[&a, offsetof (a, b) + CST2]. */
11352 if (TREE_CODE (arg0) == ADDR_EXPR
11353 && handled_component_p (TREE_OPERAND (arg0, 0)))
11355 tree base;
11356 poly_int64 coffset;
11357 base = get_addr_base_and_unit_offset (TREE_OPERAND (arg0, 0),
11358 &coffset);
11359 if (!base)
11360 return NULL_TREE;
11361 return fold_build2 (MEM_REF, type,
11362 build1 (ADDR_EXPR, TREE_TYPE (arg0), base),
11363 int_const_binop (PLUS_EXPR, arg1,
11364 size_int (coffset)));
11367 return NULL_TREE;
11369 case POINTER_PLUS_EXPR:
11370 /* INT +p INT -> (PTR)(INT + INT). Stripping types allows for this. */
11371 if (INTEGRAL_TYPE_P (TREE_TYPE (arg1))
11372 && INTEGRAL_TYPE_P (TREE_TYPE (arg0)))
11373 return fold_convert_loc (loc, type,
11374 fold_build2_loc (loc, PLUS_EXPR, sizetype,
11375 fold_convert_loc (loc, sizetype,
11376 arg1),
11377 fold_convert_loc (loc, sizetype,
11378 arg0)));
11380 return NULL_TREE;
11382 case PLUS_EXPR:
11383 if (INTEGRAL_TYPE_P (type) || VECTOR_INTEGER_TYPE_P (type))
11385 /* X + (X / CST) * -CST is X % CST. */
11386 if (TREE_CODE (arg1) == MULT_EXPR
11387 && TREE_CODE (TREE_OPERAND (arg1, 0)) == TRUNC_DIV_EXPR
11388 && operand_equal_p (arg0,
11389 TREE_OPERAND (TREE_OPERAND (arg1, 0), 0), 0))
11391 tree cst0 = TREE_OPERAND (TREE_OPERAND (arg1, 0), 1);
11392 tree cst1 = TREE_OPERAND (arg1, 1);
11393 tree sum = fold_binary_loc (loc, PLUS_EXPR, TREE_TYPE (cst1),
11394 cst1, cst0);
11395 if (sum && integer_zerop (sum))
11396 return fold_convert_loc (loc, type,
11397 fold_build2_loc (loc, TRUNC_MOD_EXPR,
11398 TREE_TYPE (arg0), arg0,
11399 cst0));
11403 /* Handle (A1 * C1) + (A2 * C2) with A1, A2 or C1, C2 being the same or
11404 one. Make sure the type is not saturating and has the signedness of
11405 the stripped operands, as fold_plusminus_mult_expr will re-associate.
11406 ??? The latter condition should use TYPE_OVERFLOW_* flags instead. */
11407 if ((TREE_CODE (arg0) == MULT_EXPR
11408 || TREE_CODE (arg1) == MULT_EXPR)
11409 && !TYPE_SATURATING (type)
11410 && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (TREE_TYPE (arg0))
11411 && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (TREE_TYPE (arg1))
11412 && (!FLOAT_TYPE_P (type) || flag_associative_math))
11414 tree tem = fold_plusminus_mult_expr (loc, code, type, arg0, arg1);
11415 if (tem)
11416 return tem;
11419 if (! FLOAT_TYPE_P (type))
11421 /* Reassociate (plus (plus (mult) (foo)) (mult)) as
11422 (plus (plus (mult) (mult)) (foo)) so that we can
11423 take advantage of the factoring cases below. */
11424 if (ANY_INTEGRAL_TYPE_P (type)
11425 && TYPE_OVERFLOW_WRAPS (type)
11426 && (((TREE_CODE (arg0) == PLUS_EXPR
11427 || TREE_CODE (arg0) == MINUS_EXPR)
11428 && TREE_CODE (arg1) == MULT_EXPR)
11429 || ((TREE_CODE (arg1) == PLUS_EXPR
11430 || TREE_CODE (arg1) == MINUS_EXPR)
11431 && TREE_CODE (arg0) == MULT_EXPR)))
11433 tree parg0, parg1, parg, marg;
11434 enum tree_code pcode;
11436 if (TREE_CODE (arg1) == MULT_EXPR)
11437 parg = arg0, marg = arg1;
11438 else
11439 parg = arg1, marg = arg0;
11440 pcode = TREE_CODE (parg);
11441 parg0 = TREE_OPERAND (parg, 0);
11442 parg1 = TREE_OPERAND (parg, 1);
11443 STRIP_NOPS (parg0);
11444 STRIP_NOPS (parg1);
11446 if (TREE_CODE (parg0) == MULT_EXPR
11447 && TREE_CODE (parg1) != MULT_EXPR)
11448 return fold_build2_loc (loc, pcode, type,
11449 fold_build2_loc (loc, PLUS_EXPR, type,
11450 fold_convert_loc (loc, type,
11451 parg0),
11452 fold_convert_loc (loc, type,
11453 marg)),
11454 fold_convert_loc (loc, type, parg1));
11455 if (TREE_CODE (parg0) != MULT_EXPR
11456 && TREE_CODE (parg1) == MULT_EXPR)
11457 return
11458 fold_build2_loc (loc, PLUS_EXPR, type,
11459 fold_convert_loc (loc, type, parg0),
11460 fold_build2_loc (loc, pcode, type,
11461 fold_convert_loc (loc, type, marg),
11462 fold_convert_loc (loc, type,
11463 parg1)));
11466 else
11468 /* Fold __complex__ ( x, 0 ) + __complex__ ( 0, y )
11469 to __complex__ ( x, y ). This is not the same for SNaNs or
11470 if signed zeros are involved. */
11471 if (!HONOR_SNANS (arg0)
11472 && !HONOR_SIGNED_ZEROS (arg0)
11473 && COMPLEX_FLOAT_TYPE_P (TREE_TYPE (arg0)))
11475 tree rtype = TREE_TYPE (TREE_TYPE (arg0));
11476 tree arg0r = fold_unary_loc (loc, REALPART_EXPR, rtype, arg0);
11477 tree arg0i = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg0);
11478 bool arg0rz = false, arg0iz = false;
11479 if ((arg0r && (arg0rz = real_zerop (arg0r)))
11480 || (arg0i && (arg0iz = real_zerop (arg0i))))
11482 tree arg1r = fold_unary_loc (loc, REALPART_EXPR, rtype, arg1);
11483 tree arg1i = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg1);
11484 if (arg0rz && arg1i && real_zerop (arg1i))
11486 tree rp = arg1r ? arg1r
11487 : build1 (REALPART_EXPR, rtype, arg1);
11488 tree ip = arg0i ? arg0i
11489 : build1 (IMAGPART_EXPR, rtype, arg0);
11490 return fold_build2_loc (loc, COMPLEX_EXPR, type, rp, ip);
11492 else if (arg0iz && arg1r && real_zerop (arg1r))
11494 tree rp = arg0r ? arg0r
11495 : build1 (REALPART_EXPR, rtype, arg0);
11496 tree ip = arg1i ? arg1i
11497 : build1 (IMAGPART_EXPR, rtype, arg1);
11498 return fold_build2_loc (loc, COMPLEX_EXPR, type, rp, ip);
11503 /* Convert a + (b*c + d*e) into (a + b*c) + d*e.
11504 We associate floats only if the user has specified
11505 -fassociative-math. */
11506 if (flag_associative_math
11507 && TREE_CODE (arg1) == PLUS_EXPR
11508 && TREE_CODE (arg0) != MULT_EXPR)
11510 tree tree10 = TREE_OPERAND (arg1, 0);
11511 tree tree11 = TREE_OPERAND (arg1, 1);
11512 if (TREE_CODE (tree11) == MULT_EXPR
11513 && TREE_CODE (tree10) == MULT_EXPR)
11515 tree tree0;
11516 tree0 = fold_build2_loc (loc, PLUS_EXPR, type, arg0, tree10);
11517 return fold_build2_loc (loc, PLUS_EXPR, type, tree0, tree11);
11520 /* Convert (b*c + d*e) + a into b*c + (d*e +a).
11521 We associate floats only if the user has specified
11522 -fassociative-math. */
11523 if (flag_associative_math
11524 && TREE_CODE (arg0) == PLUS_EXPR
11525 && TREE_CODE (arg1) != MULT_EXPR)
11527 tree tree00 = TREE_OPERAND (arg0, 0);
11528 tree tree01 = TREE_OPERAND (arg0, 1);
11529 if (TREE_CODE (tree01) == MULT_EXPR
11530 && TREE_CODE (tree00) == MULT_EXPR)
11532 tree tree0;
11533 tree0 = fold_build2_loc (loc, PLUS_EXPR, type, tree01, arg1);
11534 return fold_build2_loc (loc, PLUS_EXPR, type, tree00, tree0);
11539 bit_rotate:
11540 /* (A << C1) + (A >> C2) if A is unsigned and C1+C2 is the size of A
11541 is a rotate of A by C1 bits. */
11542 /* (A << B) + (A >> (Z - B)) if A is unsigned and Z is the size of A
11543 is a rotate of A by B bits.
11544 Similarly for (A << B) | (A >> (-B & C3)) where C3 is Z-1,
11545 though in this case CODE must be | and not + or ^, otherwise
11546 it doesn't return A when B is 0. */
11548 enum tree_code code0, code1;
11549 tree rtype;
11550 code0 = TREE_CODE (arg0);
11551 code1 = TREE_CODE (arg1);
11552 if (((code0 == RSHIFT_EXPR && code1 == LSHIFT_EXPR)
11553 || (code1 == RSHIFT_EXPR && code0 == LSHIFT_EXPR))
11554 && operand_equal_p (TREE_OPERAND (arg0, 0),
11555 TREE_OPERAND (arg1, 0), 0)
11556 && (rtype = TREE_TYPE (TREE_OPERAND (arg0, 0)),
11557 TYPE_UNSIGNED (rtype))
11558 /* Only create rotates in complete modes. Other cases are not
11559 expanded properly. */
11560 && (element_precision (rtype)
11561 == GET_MODE_UNIT_PRECISION (TYPE_MODE (rtype))))
11563 tree tree01, tree11;
11564 tree orig_tree01, orig_tree11;
11565 enum tree_code code01, code11;
11567 tree01 = orig_tree01 = TREE_OPERAND (arg0, 1);
11568 tree11 = orig_tree11 = TREE_OPERAND (arg1, 1);
11569 STRIP_NOPS (tree01);
11570 STRIP_NOPS (tree11);
11571 code01 = TREE_CODE (tree01);
11572 code11 = TREE_CODE (tree11);
11573 if (code11 != MINUS_EXPR
11574 && (code01 == MINUS_EXPR || code01 == BIT_AND_EXPR))
11576 std::swap (code0, code1);
11577 std::swap (code01, code11);
11578 std::swap (tree01, tree11);
11579 std::swap (orig_tree01, orig_tree11);
11581 if (code01 == INTEGER_CST
11582 && code11 == INTEGER_CST
11583 && (wi::to_widest (tree01) + wi::to_widest (tree11)
11584 == element_precision (rtype)))
11586 tem = build2_loc (loc, LROTATE_EXPR,
11587 rtype, TREE_OPERAND (arg0, 0),
11588 code0 == LSHIFT_EXPR
11589 ? orig_tree01 : orig_tree11);
11590 return fold_convert_loc (loc, type, tem);
11592 else if (code11 == MINUS_EXPR)
11594 tree tree110, tree111;
11595 tree110 = TREE_OPERAND (tree11, 0);
11596 tree111 = TREE_OPERAND (tree11, 1);
11597 STRIP_NOPS (tree110);
11598 STRIP_NOPS (tree111);
11599 if (TREE_CODE (tree110) == INTEGER_CST
11600 && compare_tree_int (tree110,
11601 element_precision (rtype)) == 0
11602 && operand_equal_p (tree01, tree111, 0))
11604 tem = build2_loc (loc, (code0 == LSHIFT_EXPR
11605 ? LROTATE_EXPR : RROTATE_EXPR),
11606 rtype, TREE_OPERAND (arg0, 0),
11607 orig_tree01);
11608 return fold_convert_loc (loc, type, tem);
11611 else if (code == BIT_IOR_EXPR
11612 && code11 == BIT_AND_EXPR
11613 && pow2p_hwi (element_precision (rtype)))
11615 tree tree110, tree111;
11616 tree110 = TREE_OPERAND (tree11, 0);
11617 tree111 = TREE_OPERAND (tree11, 1);
11618 STRIP_NOPS (tree110);
11619 STRIP_NOPS (tree111);
11620 if (TREE_CODE (tree110) == NEGATE_EXPR
11621 && TREE_CODE (tree111) == INTEGER_CST
11622 && compare_tree_int (tree111,
11623 element_precision (rtype) - 1) == 0
11624 && operand_equal_p (tree01, TREE_OPERAND (tree110, 0), 0))
11626 tem = build2_loc (loc, (code0 == LSHIFT_EXPR
11627 ? LROTATE_EXPR : RROTATE_EXPR),
11628 rtype, TREE_OPERAND (arg0, 0),
11629 orig_tree01);
11630 return fold_convert_loc (loc, type, tem);
11636 associate:
11637 /* In most languages, can't associate operations on floats through
11638 parentheses. Rather than remember where the parentheses were, we
11639 don't associate floats at all, unless the user has specified
11640 -fassociative-math.
11641 And, we need to make sure type is not saturating. */
11643 if ((! FLOAT_TYPE_P (type) || flag_associative_math)
11644 && !TYPE_SATURATING (type)
11645 && !TYPE_OVERFLOW_SANITIZED (type))
11647 tree var0, minus_var0, con0, minus_con0, lit0, minus_lit0;
11648 tree var1, minus_var1, con1, minus_con1, lit1, minus_lit1;
11649 tree atype = type;
11650 bool ok = true;
11652 /* Split both trees into variables, constants, and literals. Then
11653 associate each group together, the constants with literals,
11654 then the result with variables. This increases the chances of
11655 literals being recombined later and of generating relocatable
11656 expressions for the sum of a constant and literal. */
11657 var0 = split_tree (arg0, type, code,
11658 &minus_var0, &con0, &minus_con0,
11659 &lit0, &minus_lit0, 0);
11660 var1 = split_tree (arg1, type, code,
11661 &minus_var1, &con1, &minus_con1,
11662 &lit1, &minus_lit1, code == MINUS_EXPR);
11664 /* Recombine MINUS_EXPR operands by using PLUS_EXPR. */
11665 if (code == MINUS_EXPR)
11666 code = PLUS_EXPR;
11668 /* With undefined overflow prefer doing association in a type
11669 which wraps on overflow, if that is one of the operand types. */
11670 if ((POINTER_TYPE_P (type) || INTEGRAL_TYPE_P (type))
11671 && !TYPE_OVERFLOW_WRAPS (type))
11673 if (INTEGRAL_TYPE_P (TREE_TYPE (arg0))
11674 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg0)))
11675 atype = TREE_TYPE (arg0);
11676 else if (INTEGRAL_TYPE_P (TREE_TYPE (arg1))
11677 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg1)))
11678 atype = TREE_TYPE (arg1);
11679 gcc_assert (TYPE_PRECISION (atype) == TYPE_PRECISION (type));
11682 /* With undefined overflow we can only associate constants with one
11683 variable, and constants whose association doesn't overflow. */
11684 if ((POINTER_TYPE_P (atype) || INTEGRAL_TYPE_P (atype))
11685 && !TYPE_OVERFLOW_WRAPS (atype))
11687 if ((var0 && var1) || (minus_var0 && minus_var1))
11689 /* ??? If split_tree would handle NEGATE_EXPR we could
11690 simply reject these cases and the allowed cases would
11691 be the var0/minus_var1 ones. */
11692 tree tmp0 = var0 ? var0 : minus_var0;
11693 tree tmp1 = var1 ? var1 : minus_var1;
11694 bool one_neg = false;
11696 if (TREE_CODE (tmp0) == NEGATE_EXPR)
11698 tmp0 = TREE_OPERAND (tmp0, 0);
11699 one_neg = !one_neg;
11701 if (CONVERT_EXPR_P (tmp0)
11702 && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (tmp0, 0)))
11703 && (TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (tmp0, 0)))
11704 <= TYPE_PRECISION (atype)))
11705 tmp0 = TREE_OPERAND (tmp0, 0);
11706 if (TREE_CODE (tmp1) == NEGATE_EXPR)
11708 tmp1 = TREE_OPERAND (tmp1, 0);
11709 one_neg = !one_neg;
11711 if (CONVERT_EXPR_P (tmp1)
11712 && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (tmp1, 0)))
11713 && (TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (tmp1, 0)))
11714 <= TYPE_PRECISION (atype)))
11715 tmp1 = TREE_OPERAND (tmp1, 0);
11716 /* The only case we can still associate with two variables
11717 is if they cancel out. */
11718 if (!one_neg
11719 || !operand_equal_p (tmp0, tmp1, 0))
11720 ok = false;
11722 else if ((var0 && minus_var1
11723 && ! operand_equal_p (var0, minus_var1, 0))
11724 || (minus_var0 && var1
11725 && ! operand_equal_p (minus_var0, var1, 0)))
11726 ok = false;
11729 /* Only do something if we found more than two objects. Otherwise,
11730 nothing has changed and we risk infinite recursion. */
11731 if (ok
11732 && ((var0 != 0) + (var1 != 0)
11733 + (minus_var0 != 0) + (minus_var1 != 0)
11734 + (con0 != 0) + (con1 != 0)
11735 + (minus_con0 != 0) + (minus_con1 != 0)
11736 + (lit0 != 0) + (lit1 != 0)
11737 + (minus_lit0 != 0) + (minus_lit1 != 0)) > 2)
11739 var0 = associate_trees (loc, var0, var1, code, atype);
11740 minus_var0 = associate_trees (loc, minus_var0, minus_var1,
11741 code, atype);
11742 con0 = associate_trees (loc, con0, con1, code, atype);
11743 minus_con0 = associate_trees (loc, minus_con0, minus_con1,
11744 code, atype);
11745 lit0 = associate_trees (loc, lit0, lit1, code, atype);
11746 minus_lit0 = associate_trees (loc, minus_lit0, minus_lit1,
11747 code, atype);
11749 if (minus_var0 && var0)
11751 var0 = associate_trees (loc, var0, minus_var0,
11752 MINUS_EXPR, atype);
11753 minus_var0 = 0;
11755 if (minus_con0 && con0)
11757 con0 = associate_trees (loc, con0, minus_con0,
11758 MINUS_EXPR, atype);
11759 minus_con0 = 0;
11762 /* Preserve the MINUS_EXPR if the negative part of the literal is
11763 greater than the positive part. Otherwise, the multiplicative
11764 folding code (i.e extract_muldiv) may be fooled in case
11765 unsigned constants are subtracted, like in the following
11766 example: ((X*2 + 4) - 8U)/2. */
11767 if (minus_lit0 && lit0)
11769 if (TREE_CODE (lit0) == INTEGER_CST
11770 && TREE_CODE (minus_lit0) == INTEGER_CST
11771 && tree_int_cst_lt (lit0, minus_lit0)
11772 /* But avoid ending up with only negated parts. */
11773 && (var0 || con0))
11775 minus_lit0 = associate_trees (loc, minus_lit0, lit0,
11776 MINUS_EXPR, atype);
11777 lit0 = 0;
11779 else
11781 lit0 = associate_trees (loc, lit0, minus_lit0,
11782 MINUS_EXPR, atype);
11783 minus_lit0 = 0;
11787 /* Don't introduce overflows through reassociation. */
11788 if ((lit0 && TREE_OVERFLOW_P (lit0))
11789 || (minus_lit0 && TREE_OVERFLOW_P (minus_lit0)))
11790 return NULL_TREE;
11792 /* Eliminate lit0 and minus_lit0 to con0 and minus_con0. */
11793 con0 = associate_trees (loc, con0, lit0, code, atype);
11794 lit0 = 0;
11795 minus_con0 = associate_trees (loc, minus_con0, minus_lit0,
11796 code, atype);
11797 minus_lit0 = 0;
11799 /* Eliminate minus_con0. */
11800 if (minus_con0)
11802 if (con0)
11803 con0 = associate_trees (loc, con0, minus_con0,
11804 MINUS_EXPR, atype);
11805 else if (var0)
11806 var0 = associate_trees (loc, var0, minus_con0,
11807 MINUS_EXPR, atype);
11808 else
11809 gcc_unreachable ();
11810 minus_con0 = 0;
11813 /* Eliminate minus_var0. */
11814 if (minus_var0)
11816 if (con0)
11817 con0 = associate_trees (loc, con0, minus_var0,
11818 MINUS_EXPR, atype);
11819 else
11820 gcc_unreachable ();
11821 minus_var0 = 0;
11824 return
11825 fold_convert_loc (loc, type, associate_trees (loc, var0, con0,
11826 code, atype));
11830 return NULL_TREE;
11832 case POINTER_DIFF_EXPR:
11833 case MINUS_EXPR:
11834 /* Fold &a[i] - &a[j] to i-j. */
11835 if (TREE_CODE (arg0) == ADDR_EXPR
11836 && TREE_CODE (TREE_OPERAND (arg0, 0)) == ARRAY_REF
11837 && TREE_CODE (arg1) == ADDR_EXPR
11838 && TREE_CODE (TREE_OPERAND (arg1, 0)) == ARRAY_REF)
11840 tree tem = fold_addr_of_array_ref_difference (loc, type,
11841 TREE_OPERAND (arg0, 0),
11842 TREE_OPERAND (arg1, 0),
11843 code
11844 == POINTER_DIFF_EXPR);
11845 if (tem)
11846 return tem;
11849 /* Further transformations are not for pointers. */
11850 if (code == POINTER_DIFF_EXPR)
11851 return NULL_TREE;
11853 /* (-A) - B -> (-B) - A where B is easily negated and we can swap. */
11854 if (TREE_CODE (arg0) == NEGATE_EXPR
11855 && negate_expr_p (op1)
11856 /* If arg0 is e.g. unsigned int and type is int, then this could
11857 introduce UB, because if A is INT_MIN at runtime, the original
11858 expression can be well defined while the latter is not.
11859 See PR83269. */
11860 && !(ANY_INTEGRAL_TYPE_P (type)
11861 && TYPE_OVERFLOW_UNDEFINED (type)
11862 && ANY_INTEGRAL_TYPE_P (TREE_TYPE (arg0))
11863 && !TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg0))))
11864 return fold_build2_loc (loc, MINUS_EXPR, type, negate_expr (op1),
11865 fold_convert_loc (loc, type,
11866 TREE_OPERAND (arg0, 0)));
11868 /* Fold __complex__ ( x, 0 ) - __complex__ ( 0, y ) to
11869 __complex__ ( x, -y ). This is not the same for SNaNs or if
11870 signed zeros are involved. */
11871 if (!HONOR_SNANS (arg0)
11872 && !HONOR_SIGNED_ZEROS (arg0)
11873 && COMPLEX_FLOAT_TYPE_P (TREE_TYPE (arg0)))
11875 tree rtype = TREE_TYPE (TREE_TYPE (arg0));
11876 tree arg0r = fold_unary_loc (loc, REALPART_EXPR, rtype, arg0);
11877 tree arg0i = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg0);
11878 bool arg0rz = false, arg0iz = false;
11879 if ((arg0r && (arg0rz = real_zerop (arg0r)))
11880 || (arg0i && (arg0iz = real_zerop (arg0i))))
11882 tree arg1r = fold_unary_loc (loc, REALPART_EXPR, rtype, arg1);
11883 tree arg1i = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg1);
11884 if (arg0rz && arg1i && real_zerop (arg1i))
11886 tree rp = fold_build1_loc (loc, NEGATE_EXPR, rtype,
11887 arg1r ? arg1r
11888 : build1 (REALPART_EXPR, rtype, arg1));
11889 tree ip = arg0i ? arg0i
11890 : build1 (IMAGPART_EXPR, rtype, arg0);
11891 return fold_build2_loc (loc, COMPLEX_EXPR, type, rp, ip);
11893 else if (arg0iz && arg1r && real_zerop (arg1r))
11895 tree rp = arg0r ? arg0r
11896 : build1 (REALPART_EXPR, rtype, arg0);
11897 tree ip = fold_build1_loc (loc, NEGATE_EXPR, rtype,
11898 arg1i ? arg1i
11899 : build1 (IMAGPART_EXPR, rtype, arg1));
11900 return fold_build2_loc (loc, COMPLEX_EXPR, type, rp, ip);
11905 /* A - B -> A + (-B) if B is easily negatable. */
11906 if (negate_expr_p (op1)
11907 && ! TYPE_OVERFLOW_SANITIZED (type)
11908 && ((FLOAT_TYPE_P (type)
11909 /* Avoid this transformation if B is a positive REAL_CST. */
11910 && (TREE_CODE (op1) != REAL_CST
11911 || REAL_VALUE_NEGATIVE (TREE_REAL_CST (op1))))
11912 || INTEGRAL_TYPE_P (type)))
11913 return fold_build2_loc (loc, PLUS_EXPR, type,
11914 fold_convert_loc (loc, type, arg0),
11915 negate_expr (op1));
11917 /* Handle (A1 * C1) - (A2 * C2) with A1, A2 or C1, C2 being the same or
11918 one. Make sure the type is not saturating and has the signedness of
11919 the stripped operands, as fold_plusminus_mult_expr will re-associate.
11920 ??? The latter condition should use TYPE_OVERFLOW_* flags instead. */
11921 if ((TREE_CODE (arg0) == MULT_EXPR
11922 || TREE_CODE (arg1) == MULT_EXPR)
11923 && !TYPE_SATURATING (type)
11924 && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (TREE_TYPE (arg0))
11925 && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (TREE_TYPE (arg1))
11926 && (!FLOAT_TYPE_P (type) || flag_associative_math))
11928 tree tem = fold_plusminus_mult_expr (loc, code, type, arg0, arg1);
11929 if (tem)
11930 return tem;
11933 goto associate;
11935 case MULT_EXPR:
11936 if (! FLOAT_TYPE_P (type))
11938 /* Transform x * -C into -x * C if x is easily negatable. */
11939 if (TREE_CODE (op1) == INTEGER_CST
11940 && tree_int_cst_sgn (op1) == -1
11941 && negate_expr_p (op0)
11942 && negate_expr_p (op1)
11943 && (tem = negate_expr (op1)) != op1
11944 && ! TREE_OVERFLOW (tem))
11945 return fold_build2_loc (loc, MULT_EXPR, type,
11946 fold_convert_loc (loc, type,
11947 negate_expr (op0)), tem);
11949 strict_overflow_p = false;
11950 if (TREE_CODE (arg1) == INTEGER_CST
11951 && (tem = extract_muldiv (op0, arg1, code, NULL_TREE,
11952 &strict_overflow_p)) != 0)
11954 if (strict_overflow_p)
11955 fold_overflow_warning (("assuming signed overflow does not "
11956 "occur when simplifying "
11957 "multiplication"),
11958 WARN_STRICT_OVERFLOW_MISC);
11959 return fold_convert_loc (loc, type, tem);
11962 /* Optimize z * conj(z) for integer complex numbers. */
11963 if (TREE_CODE (arg0) == CONJ_EXPR
11964 && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
11965 return fold_mult_zconjz (loc, type, arg1);
11966 if (TREE_CODE (arg1) == CONJ_EXPR
11967 && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
11968 return fold_mult_zconjz (loc, type, arg0);
11970 else
11972 /* Fold z * +-I to __complex__ (-+__imag z, +-__real z).
11973 This is not the same for NaNs or if signed zeros are
11974 involved. */
11975 if (!HONOR_NANS (arg0)
11976 && !HONOR_SIGNED_ZEROS (arg0)
11977 && COMPLEX_FLOAT_TYPE_P (TREE_TYPE (arg0))
11978 && TREE_CODE (arg1) == COMPLEX_CST
11979 && real_zerop (TREE_REALPART (arg1)))
11981 tree rtype = TREE_TYPE (TREE_TYPE (arg0));
11982 if (real_onep (TREE_IMAGPART (arg1)))
11983 return
11984 fold_build2_loc (loc, COMPLEX_EXPR, type,
11985 negate_expr (fold_build1_loc (loc, IMAGPART_EXPR,
11986 rtype, arg0)),
11987 fold_build1_loc (loc, REALPART_EXPR, rtype, arg0));
11988 else if (real_minus_onep (TREE_IMAGPART (arg1)))
11989 return
11990 fold_build2_loc (loc, COMPLEX_EXPR, type,
11991 fold_build1_loc (loc, IMAGPART_EXPR, rtype, arg0),
11992 negate_expr (fold_build1_loc (loc, REALPART_EXPR,
11993 rtype, arg0)));
11996 /* Optimize z * conj(z) for floating point complex numbers.
11997 Guarded by flag_unsafe_math_optimizations as non-finite
11998 imaginary components don't produce scalar results. */
11999 if (flag_unsafe_math_optimizations
12000 && TREE_CODE (arg0) == CONJ_EXPR
12001 && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
12002 return fold_mult_zconjz (loc, type, arg1);
12003 if (flag_unsafe_math_optimizations
12004 && TREE_CODE (arg1) == CONJ_EXPR
12005 && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
12006 return fold_mult_zconjz (loc, type, arg0);
12008 goto associate;
12010 case BIT_IOR_EXPR:
12011 /* Canonicalize (X & C1) | C2. */
12012 if (TREE_CODE (arg0) == BIT_AND_EXPR
12013 && TREE_CODE (arg1) == INTEGER_CST
12014 && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
12016 int width = TYPE_PRECISION (type), w;
12017 wide_int c1 = wi::to_wide (TREE_OPERAND (arg0, 1));
12018 wide_int c2 = wi::to_wide (arg1);
12020 /* If (C1&C2) == C1, then (X&C1)|C2 becomes (X,C2). */
12021 if ((c1 & c2) == c1)
12022 return omit_one_operand_loc (loc, type, arg1,
12023 TREE_OPERAND (arg0, 0));
12025 wide_int msk = wi::mask (width, false,
12026 TYPE_PRECISION (TREE_TYPE (arg1)));
12028 /* If (C1|C2) == ~0 then (X&C1)|C2 becomes X|C2. */
12029 if (wi::bit_and_not (msk, c1 | c2) == 0)
12031 tem = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
12032 return fold_build2_loc (loc, BIT_IOR_EXPR, type, tem, arg1);
12035 /* Minimize the number of bits set in C1, i.e. C1 := C1 & ~C2,
12036 unless (C1 & ~C2) | (C2 & C3) for some C3 is a mask of some
12037 mode which allows further optimizations. */
12038 c1 &= msk;
12039 c2 &= msk;
12040 wide_int c3 = wi::bit_and_not (c1, c2);
12041 for (w = BITS_PER_UNIT; w <= width; w <<= 1)
12043 wide_int mask = wi::mask (w, false,
12044 TYPE_PRECISION (type));
12045 if (((c1 | c2) & mask) == mask
12046 && wi::bit_and_not (c1, mask) == 0)
12048 c3 = mask;
12049 break;
12053 if (c3 != c1)
12055 tem = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
12056 tem = fold_build2_loc (loc, BIT_AND_EXPR, type, tem,
12057 wide_int_to_tree (type, c3));
12058 return fold_build2_loc (loc, BIT_IOR_EXPR, type, tem, arg1);
12062 /* See if this can be simplified into a rotate first. If that
12063 is unsuccessful continue in the association code. */
12064 goto bit_rotate;
12066 case BIT_XOR_EXPR:
12067 /* Fold (X & 1) ^ 1 as (X & 1) == 0. */
12068 if (TREE_CODE (arg0) == BIT_AND_EXPR
12069 && INTEGRAL_TYPE_P (type)
12070 && integer_onep (TREE_OPERAND (arg0, 1))
12071 && integer_onep (arg1))
12072 return fold_build2_loc (loc, EQ_EXPR, type, arg0,
12073 build_zero_cst (TREE_TYPE (arg0)));
12075 /* See if this can be simplified into a rotate first. If that
12076 is unsuccessful continue in the association code. */
12077 goto bit_rotate;
12079 case BIT_AND_EXPR:
12080 /* Fold !X & 1 as X == 0. */
12081 if (TREE_CODE (arg0) == TRUTH_NOT_EXPR
12082 && integer_onep (arg1))
12084 tem = TREE_OPERAND (arg0, 0);
12085 return fold_build2_loc (loc, EQ_EXPR, type, tem,
12086 build_zero_cst (TREE_TYPE (tem)));
12089 /* Fold (X * Y) & -(1 << CST) to X * Y if Y is a constant
12090 multiple of 1 << CST. */
12091 if (TREE_CODE (arg1) == INTEGER_CST)
12093 wi::tree_to_wide_ref cst1 = wi::to_wide (arg1);
12094 wide_int ncst1 = -cst1;
12095 if ((cst1 & ncst1) == ncst1
12096 && multiple_of_p (type, arg0,
12097 wide_int_to_tree (TREE_TYPE (arg1), ncst1)))
12098 return fold_convert_loc (loc, type, arg0);
12101 /* Fold (X * CST1) & CST2 to zero if we can, or drop known zero
12102 bits from CST2. */
12103 if (TREE_CODE (arg1) == INTEGER_CST
12104 && TREE_CODE (arg0) == MULT_EXPR
12105 && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
12107 wi::tree_to_wide_ref warg1 = wi::to_wide (arg1);
12108 wide_int masked
12109 = mask_with_tz (type, warg1, wi::to_wide (TREE_OPERAND (arg0, 1)));
12111 if (masked == 0)
12112 return omit_two_operands_loc (loc, type, build_zero_cst (type),
12113 arg0, arg1);
12114 else if (masked != warg1)
12116 /* Avoid the transform if arg1 is a mask of some
12117 mode which allows further optimizations. */
12118 int pop = wi::popcount (warg1);
12119 if (!(pop >= BITS_PER_UNIT
12120 && pow2p_hwi (pop)
12121 && wi::mask (pop, false, warg1.get_precision ()) == warg1))
12122 return fold_build2_loc (loc, code, type, op0,
12123 wide_int_to_tree (type, masked));
12127 /* Simplify ((int)c & 0377) into (int)c, if c is unsigned char. */
12128 if (TREE_CODE (arg1) == INTEGER_CST && TREE_CODE (arg0) == NOP_EXPR
12129 && TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (arg0, 0))))
12131 prec = element_precision (TREE_TYPE (TREE_OPERAND (arg0, 0)));
12133 wide_int mask = wide_int::from (wi::to_wide (arg1), prec, UNSIGNED);
12134 if (mask == -1)
12135 return
12136 fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
12139 goto associate;
12141 case RDIV_EXPR:
12142 /* Don't touch a floating-point divide by zero unless the mode
12143 of the constant can represent infinity. */
12144 if (TREE_CODE (arg1) == REAL_CST
12145 && !MODE_HAS_INFINITIES (TYPE_MODE (TREE_TYPE (arg1)))
12146 && real_zerop (arg1))
12147 return NULL_TREE;
12149 /* (-A) / (-B) -> A / B */
12150 if (TREE_CODE (arg0) == NEGATE_EXPR && negate_expr_p (arg1))
12151 return fold_build2_loc (loc, RDIV_EXPR, type,
12152 TREE_OPERAND (arg0, 0),
12153 negate_expr (arg1));
12154 if (TREE_CODE (arg1) == NEGATE_EXPR && negate_expr_p (arg0))
12155 return fold_build2_loc (loc, RDIV_EXPR, type,
12156 negate_expr (arg0),
12157 TREE_OPERAND (arg1, 0));
12158 return NULL_TREE;
12160 case TRUNC_DIV_EXPR:
12161 /* Fall through */
12163 case FLOOR_DIV_EXPR:
12164 /* Simplify A / (B << N) where A and B are positive and B is
12165 a power of 2, to A >> (N + log2(B)). */
12166 strict_overflow_p = false;
12167 if (TREE_CODE (arg1) == LSHIFT_EXPR
12168 && (TYPE_UNSIGNED (type)
12169 || tree_expr_nonnegative_warnv_p (op0, &strict_overflow_p)))
12171 tree sval = TREE_OPERAND (arg1, 0);
12172 if (integer_pow2p (sval) && tree_int_cst_sgn (sval) > 0)
12174 tree sh_cnt = TREE_OPERAND (arg1, 1);
12175 tree pow2 = build_int_cst (TREE_TYPE (sh_cnt),
12176 wi::exact_log2 (wi::to_wide (sval)));
12178 if (strict_overflow_p)
12179 fold_overflow_warning (("assuming signed overflow does not "
12180 "occur when simplifying A / (B << N)"),
12181 WARN_STRICT_OVERFLOW_MISC);
12183 sh_cnt = fold_build2_loc (loc, PLUS_EXPR, TREE_TYPE (sh_cnt),
12184 sh_cnt, pow2);
12185 return fold_build2_loc (loc, RSHIFT_EXPR, type,
12186 fold_convert_loc (loc, type, arg0), sh_cnt);
12190 /* Fall through */
12192 case ROUND_DIV_EXPR:
12193 case CEIL_DIV_EXPR:
12194 case EXACT_DIV_EXPR:
12195 if (integer_zerop (arg1))
12196 return NULL_TREE;
12198 /* Convert -A / -B to A / B when the type is signed and overflow is
12199 undefined. */
12200 if ((!ANY_INTEGRAL_TYPE_P (type) || TYPE_OVERFLOW_UNDEFINED (type))
12201 && TREE_CODE (op0) == NEGATE_EXPR
12202 && negate_expr_p (op1))
12204 if (ANY_INTEGRAL_TYPE_P (type))
12205 fold_overflow_warning (("assuming signed overflow does not occur "
12206 "when distributing negation across "
12207 "division"),
12208 WARN_STRICT_OVERFLOW_MISC);
12209 return fold_build2_loc (loc, code, type,
12210 fold_convert_loc (loc, type,
12211 TREE_OPERAND (arg0, 0)),
12212 negate_expr (op1));
12214 if ((!ANY_INTEGRAL_TYPE_P (type) || TYPE_OVERFLOW_UNDEFINED (type))
12215 && TREE_CODE (arg1) == NEGATE_EXPR
12216 && negate_expr_p (op0))
12218 if (ANY_INTEGRAL_TYPE_P (type))
12219 fold_overflow_warning (("assuming signed overflow does not occur "
12220 "when distributing negation across "
12221 "division"),
12222 WARN_STRICT_OVERFLOW_MISC);
12223 return fold_build2_loc (loc, code, type,
12224 negate_expr (op0),
12225 fold_convert_loc (loc, type,
12226 TREE_OPERAND (arg1, 0)));
12229 /* If arg0 is a multiple of arg1, then rewrite to the fastest div
12230 operation, EXACT_DIV_EXPR.
12232 Note that only CEIL_DIV_EXPR and FLOOR_DIV_EXPR are rewritten now.
12233 At one time others generated faster code, it's not clear if they do
12234 after the last round to changes to the DIV code in expmed.cc. */
12235 if ((code == CEIL_DIV_EXPR || code == FLOOR_DIV_EXPR)
12236 && multiple_of_p (type, arg0, arg1))
12237 return fold_build2_loc (loc, EXACT_DIV_EXPR, type,
12238 fold_convert (type, arg0),
12239 fold_convert (type, arg1));
12241 strict_overflow_p = false;
12242 if (TREE_CODE (arg1) == INTEGER_CST
12243 && (tem = extract_muldiv (op0, arg1, code, NULL_TREE,
12244 &strict_overflow_p)) != 0)
12246 if (strict_overflow_p)
12247 fold_overflow_warning (("assuming signed overflow does not occur "
12248 "when simplifying division"),
12249 WARN_STRICT_OVERFLOW_MISC);
12250 return fold_convert_loc (loc, type, tem);
12253 return NULL_TREE;
12255 case CEIL_MOD_EXPR:
12256 case FLOOR_MOD_EXPR:
12257 case ROUND_MOD_EXPR:
12258 case TRUNC_MOD_EXPR:
12259 strict_overflow_p = false;
12260 if (TREE_CODE (arg1) == INTEGER_CST
12261 && (tem = extract_muldiv (op0, arg1, code, NULL_TREE,
12262 &strict_overflow_p)) != 0)
12264 if (strict_overflow_p)
12265 fold_overflow_warning (("assuming signed overflow does not occur "
12266 "when simplifying modulus"),
12267 WARN_STRICT_OVERFLOW_MISC);
12268 return fold_convert_loc (loc, type, tem);
12271 return NULL_TREE;
12273 case LROTATE_EXPR:
12274 case RROTATE_EXPR:
12275 case RSHIFT_EXPR:
12276 case LSHIFT_EXPR:
12277 /* Since negative shift count is not well-defined,
12278 don't try to compute it in the compiler. */
12279 if (TREE_CODE (arg1) == INTEGER_CST && tree_int_cst_sgn (arg1) < 0)
12280 return NULL_TREE;
12282 prec = element_precision (type);
12284 /* If we have a rotate of a bit operation with the rotate count and
12285 the second operand of the bit operation both constant,
12286 permute the two operations. */
12287 if (code == RROTATE_EXPR && TREE_CODE (arg1) == INTEGER_CST
12288 && (TREE_CODE (arg0) == BIT_AND_EXPR
12289 || TREE_CODE (arg0) == BIT_IOR_EXPR
12290 || TREE_CODE (arg0) == BIT_XOR_EXPR)
12291 && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
12293 tree arg00 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
12294 tree arg01 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 1));
12295 return fold_build2_loc (loc, TREE_CODE (arg0), type,
12296 fold_build2_loc (loc, code, type,
12297 arg00, arg1),
12298 fold_build2_loc (loc, code, type,
12299 arg01, arg1));
12302 /* Two consecutive rotates adding up to the some integer
12303 multiple of the precision of the type can be ignored. */
12304 if (code == RROTATE_EXPR && TREE_CODE (arg1) == INTEGER_CST
12305 && TREE_CODE (arg0) == RROTATE_EXPR
12306 && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
12307 && wi::umod_trunc (wi::to_wide (arg1)
12308 + wi::to_wide (TREE_OPERAND (arg0, 1)),
12309 prec) == 0)
12310 return fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
12312 return NULL_TREE;
12314 case MIN_EXPR:
12315 case MAX_EXPR:
12316 goto associate;
12318 case TRUTH_ANDIF_EXPR:
12319 /* Note that the operands of this must be ints
12320 and their values must be 0 or 1.
12321 ("true" is a fixed value perhaps depending on the language.) */
12322 /* If first arg is constant zero, return it. */
12323 if (integer_zerop (arg0))
12324 return fold_convert_loc (loc, type, arg0);
12325 /* FALLTHRU */
12326 case TRUTH_AND_EXPR:
12327 /* If either arg is constant true, drop it. */
12328 if (TREE_CODE (arg0) == INTEGER_CST && ! integer_zerop (arg0))
12329 return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg1));
12330 if (TREE_CODE (arg1) == INTEGER_CST && ! integer_zerop (arg1)
12331 /* Preserve sequence points. */
12332 && (code != TRUTH_ANDIF_EXPR || ! TREE_SIDE_EFFECTS (arg0)))
12333 return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
12334 /* If second arg is constant zero, result is zero, but first arg
12335 must be evaluated. */
12336 if (integer_zerop (arg1))
12337 return omit_one_operand_loc (loc, type, arg1, arg0);
12338 /* Likewise for first arg, but note that only the TRUTH_AND_EXPR
12339 case will be handled here. */
12340 if (integer_zerop (arg0))
12341 return omit_one_operand_loc (loc, type, arg0, arg1);
12343 /* !X && X is always false. */
12344 if (TREE_CODE (arg0) == TRUTH_NOT_EXPR
12345 && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
12346 return omit_one_operand_loc (loc, type, integer_zero_node, arg1);
12347 /* X && !X is always false. */
12348 if (TREE_CODE (arg1) == TRUTH_NOT_EXPR
12349 && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
12350 return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
12352 /* A < X && A + 1 > Y ==> A < X && A >= Y. Normally A + 1 > Y
12353 means A >= Y && A != MAX, but in this case we know that
12354 A < X <= MAX. */
12356 if (!TREE_SIDE_EFFECTS (arg0)
12357 && !TREE_SIDE_EFFECTS (arg1))
12359 tem = fold_to_nonsharp_ineq_using_bound (loc, arg0, arg1);
12360 if (tem && !operand_equal_p (tem, arg0, 0))
12361 return fold_convert (type,
12362 fold_build2_loc (loc, code, TREE_TYPE (arg1),
12363 tem, arg1));
12365 tem = fold_to_nonsharp_ineq_using_bound (loc, arg1, arg0);
12366 if (tem && !operand_equal_p (tem, arg1, 0))
12367 return fold_convert (type,
12368 fold_build2_loc (loc, code, TREE_TYPE (arg0),
12369 arg0, tem));
12372 if ((tem = fold_truth_andor (loc, code, type, arg0, arg1, op0, op1))
12373 != NULL_TREE)
12374 return tem;
12376 return NULL_TREE;
12378 case TRUTH_ORIF_EXPR:
12379 /* Note that the operands of this must be ints
12380 and their values must be 0 or true.
12381 ("true" is a fixed value perhaps depending on the language.) */
12382 /* If first arg is constant true, return it. */
12383 if (TREE_CODE (arg0) == INTEGER_CST && ! integer_zerop (arg0))
12384 return fold_convert_loc (loc, type, arg0);
12385 /* FALLTHRU */
12386 case TRUTH_OR_EXPR:
12387 /* If either arg is constant zero, drop it. */
12388 if (TREE_CODE (arg0) == INTEGER_CST && integer_zerop (arg0))
12389 return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg1));
12390 if (TREE_CODE (arg1) == INTEGER_CST && integer_zerop (arg1)
12391 /* Preserve sequence points. */
12392 && (code != TRUTH_ORIF_EXPR || ! TREE_SIDE_EFFECTS (arg0)))
12393 return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
12394 /* If second arg is constant true, result is true, but we must
12395 evaluate first arg. */
12396 if (TREE_CODE (arg1) == INTEGER_CST && ! integer_zerop (arg1))
12397 return omit_one_operand_loc (loc, type, arg1, arg0);
12398 /* Likewise for first arg, but note this only occurs here for
12399 TRUTH_OR_EXPR. */
12400 if (TREE_CODE (arg0) == INTEGER_CST && ! integer_zerop (arg0))
12401 return omit_one_operand_loc (loc, type, arg0, arg1);
12403 /* !X || X is always true. */
12404 if (TREE_CODE (arg0) == TRUTH_NOT_EXPR
12405 && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
12406 return omit_one_operand_loc (loc, type, integer_one_node, arg1);
12407 /* X || !X is always true. */
12408 if (TREE_CODE (arg1) == TRUTH_NOT_EXPR
12409 && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
12410 return omit_one_operand_loc (loc, type, integer_one_node, arg0);
12412 /* (X && !Y) || (!X && Y) is X ^ Y */
12413 if (TREE_CODE (arg0) == TRUTH_AND_EXPR
12414 && TREE_CODE (arg1) == TRUTH_AND_EXPR)
12416 tree a0, a1, l0, l1, n0, n1;
12418 a0 = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 0));
12419 a1 = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 1));
12421 l0 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
12422 l1 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 1));
12424 n0 = fold_build1_loc (loc, TRUTH_NOT_EXPR, type, l0);
12425 n1 = fold_build1_loc (loc, TRUTH_NOT_EXPR, type, l1);
12427 if ((operand_equal_p (n0, a0, 0)
12428 && operand_equal_p (n1, a1, 0))
12429 || (operand_equal_p (n0, a1, 0)
12430 && operand_equal_p (n1, a0, 0)))
12431 return fold_build2_loc (loc, TRUTH_XOR_EXPR, type, l0, n1);
12434 if ((tem = fold_truth_andor (loc, code, type, arg0, arg1, op0, op1))
12435 != NULL_TREE)
12436 return tem;
12438 return NULL_TREE;
12440 case TRUTH_XOR_EXPR:
12441 /* If the second arg is constant zero, drop it. */
12442 if (integer_zerop (arg1))
12443 return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
12444 /* If the second arg is constant true, this is a logical inversion. */
12445 if (integer_onep (arg1))
12447 tem = invert_truthvalue_loc (loc, arg0);
12448 return non_lvalue_loc (loc, fold_convert_loc (loc, type, tem));
12450 /* Identical arguments cancel to zero. */
12451 if (operand_equal_p (arg0, arg1, 0))
12452 return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
12454 /* !X ^ X is always true. */
12455 if (TREE_CODE (arg0) == TRUTH_NOT_EXPR
12456 && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
12457 return omit_one_operand_loc (loc, type, integer_one_node, arg1);
12459 /* X ^ !X is always true. */
12460 if (TREE_CODE (arg1) == TRUTH_NOT_EXPR
12461 && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
12462 return omit_one_operand_loc (loc, type, integer_one_node, arg0);
12464 return NULL_TREE;
12466 case EQ_EXPR:
12467 case NE_EXPR:
12468 STRIP_NOPS (arg0);
12469 STRIP_NOPS (arg1);
12471 tem = fold_comparison (loc, code, type, op0, op1);
12472 if (tem != NULL_TREE)
12473 return tem;
12475 /* bool_var != 1 becomes !bool_var. */
12476 if (TREE_CODE (TREE_TYPE (arg0)) == BOOLEAN_TYPE && integer_onep (arg1)
12477 && code == NE_EXPR)
12478 return fold_convert_loc (loc, type,
12479 fold_build1_loc (loc, TRUTH_NOT_EXPR,
12480 TREE_TYPE (arg0), arg0));
12482 /* bool_var == 0 becomes !bool_var. */
12483 if (TREE_CODE (TREE_TYPE (arg0)) == BOOLEAN_TYPE && integer_zerop (arg1)
12484 && code == EQ_EXPR)
12485 return fold_convert_loc (loc, type,
12486 fold_build1_loc (loc, TRUTH_NOT_EXPR,
12487 TREE_TYPE (arg0), arg0));
12489 /* !exp != 0 becomes !exp */
12490 if (TREE_CODE (arg0) == TRUTH_NOT_EXPR && integer_zerop (arg1)
12491 && code == NE_EXPR)
12492 return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
12494 /* If this is an EQ or NE comparison with zero and ARG0 is
12495 (1 << foo) & bar, convert it to (bar >> foo) & 1. Both require
12496 two operations, but the latter can be done in one less insn
12497 on machines that have only two-operand insns or on which a
12498 constant cannot be the first operand. */
12499 if (TREE_CODE (arg0) == BIT_AND_EXPR
12500 && integer_zerop (arg1))
12502 tree arg00 = TREE_OPERAND (arg0, 0);
12503 tree arg01 = TREE_OPERAND (arg0, 1);
12504 if (TREE_CODE (arg00) == LSHIFT_EXPR
12505 && integer_onep (TREE_OPERAND (arg00, 0)))
12507 tree tem = fold_build2_loc (loc, RSHIFT_EXPR, TREE_TYPE (arg00),
12508 arg01, TREE_OPERAND (arg00, 1));
12509 tem = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg0), tem,
12510 build_one_cst (TREE_TYPE (arg0)));
12511 return fold_build2_loc (loc, code, type,
12512 fold_convert_loc (loc, TREE_TYPE (arg1),
12513 tem), arg1);
12515 else if (TREE_CODE (arg01) == LSHIFT_EXPR
12516 && integer_onep (TREE_OPERAND (arg01, 0)))
12518 tree tem = fold_build2_loc (loc, RSHIFT_EXPR, TREE_TYPE (arg01),
12519 arg00, TREE_OPERAND (arg01, 1));
12520 tem = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg0), tem,
12521 build_one_cst (TREE_TYPE (arg0)));
12522 return fold_build2_loc (loc, code, type,
12523 fold_convert_loc (loc, TREE_TYPE (arg1),
12524 tem), arg1);
12528 /* If this is a comparison of a field, we may be able to simplify it. */
12529 if ((TREE_CODE (arg0) == COMPONENT_REF
12530 || TREE_CODE (arg0) == BIT_FIELD_REF)
12531 /* Handle the constant case even without -O
12532 to make sure the warnings are given. */
12533 && (optimize || TREE_CODE (arg1) == INTEGER_CST))
12535 t1 = optimize_bit_field_compare (loc, code, type, arg0, arg1);
12536 if (t1)
12537 return t1;
12540 /* Optimize comparisons of strlen vs zero to a compare of the
12541 first character of the string vs zero. To wit,
12542 strlen(ptr) == 0 => *ptr == 0
12543 strlen(ptr) != 0 => *ptr != 0
12544 Other cases should reduce to one of these two (or a constant)
12545 due to the return value of strlen being unsigned. */
12546 if (TREE_CODE (arg0) == CALL_EXPR && integer_zerop (arg1))
12548 tree fndecl = get_callee_fndecl (arg0);
12550 if (fndecl
12551 && fndecl_built_in_p (fndecl, BUILT_IN_STRLEN)
12552 && call_expr_nargs (arg0) == 1
12553 && (TREE_CODE (TREE_TYPE (CALL_EXPR_ARG (arg0, 0)))
12554 == POINTER_TYPE))
12556 tree ptrtype
12557 = build_pointer_type (build_qualified_type (char_type_node,
12558 TYPE_QUAL_CONST));
12559 tree ptr = fold_convert_loc (loc, ptrtype,
12560 CALL_EXPR_ARG (arg0, 0));
12561 tree iref = build_fold_indirect_ref_loc (loc, ptr);
12562 return fold_build2_loc (loc, code, type, iref,
12563 build_int_cst (TREE_TYPE (iref), 0));
12567 /* Fold (X >> C) != 0 into X < 0 if C is one less than the width
12568 of X. Similarly fold (X >> C) == 0 into X >= 0. */
12569 if (TREE_CODE (arg0) == RSHIFT_EXPR
12570 && integer_zerop (arg1)
12571 && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
12573 tree arg00 = TREE_OPERAND (arg0, 0);
12574 tree arg01 = TREE_OPERAND (arg0, 1);
12575 tree itype = TREE_TYPE (arg00);
12576 if (wi::to_wide (arg01) == element_precision (itype) - 1)
12578 if (TYPE_UNSIGNED (itype))
12580 itype = signed_type_for (itype);
12581 arg00 = fold_convert_loc (loc, itype, arg00);
12583 return fold_build2_loc (loc, code == EQ_EXPR ? GE_EXPR : LT_EXPR,
12584 type, arg00, build_zero_cst (itype));
12588 /* Fold (~X & C) == 0 into (X & C) != 0 and (~X & C) != 0 into
12589 (X & C) == 0 when C is a single bit. */
12590 if (TREE_CODE (arg0) == BIT_AND_EXPR
12591 && TREE_CODE (TREE_OPERAND (arg0, 0)) == BIT_NOT_EXPR
12592 && integer_zerop (arg1)
12593 && integer_pow2p (TREE_OPERAND (arg0, 1)))
12595 tem = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg0),
12596 TREE_OPERAND (TREE_OPERAND (arg0, 0), 0),
12597 TREE_OPERAND (arg0, 1));
12598 return fold_build2_loc (loc, code == EQ_EXPR ? NE_EXPR : EQ_EXPR,
12599 type, tem,
12600 fold_convert_loc (loc, TREE_TYPE (arg0),
12601 arg1));
12604 /* Fold ((X & C) ^ C) eq/ne 0 into (X & C) ne/eq 0, when the
12605 constant C is a power of two, i.e. a single bit. */
12606 if (TREE_CODE (arg0) == BIT_XOR_EXPR
12607 && TREE_CODE (TREE_OPERAND (arg0, 0)) == BIT_AND_EXPR
12608 && integer_zerop (arg1)
12609 && integer_pow2p (TREE_OPERAND (arg0, 1))
12610 && operand_equal_p (TREE_OPERAND (TREE_OPERAND (arg0, 0), 1),
12611 TREE_OPERAND (arg0, 1), OEP_ONLY_CONST))
12613 tree arg00 = TREE_OPERAND (arg0, 0);
12614 return fold_build2_loc (loc, code == EQ_EXPR ? NE_EXPR : EQ_EXPR, type,
12615 arg00, build_int_cst (TREE_TYPE (arg00), 0));
12618 /* Likewise, fold ((X ^ C) & C) eq/ne 0 into (X & C) ne/eq 0,
12619 when is C is a power of two, i.e. a single bit. */
12620 if (TREE_CODE (arg0) == BIT_AND_EXPR
12621 && TREE_CODE (TREE_OPERAND (arg0, 0)) == BIT_XOR_EXPR
12622 && integer_zerop (arg1)
12623 && integer_pow2p (TREE_OPERAND (arg0, 1))
12624 && operand_equal_p (TREE_OPERAND (TREE_OPERAND (arg0, 0), 1),
12625 TREE_OPERAND (arg0, 1), OEP_ONLY_CONST))
12627 tree arg000 = TREE_OPERAND (TREE_OPERAND (arg0, 0), 0);
12628 tem = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg000),
12629 arg000, TREE_OPERAND (arg0, 1));
12630 return fold_build2_loc (loc, code == EQ_EXPR ? NE_EXPR : EQ_EXPR, type,
12631 tem, build_int_cst (TREE_TYPE (tem), 0));
12634 if (TREE_CODE (arg0) == BIT_XOR_EXPR
12635 && TREE_CODE (arg1) == BIT_XOR_EXPR)
12637 tree arg00 = TREE_OPERAND (arg0, 0);
12638 tree arg01 = TREE_OPERAND (arg0, 1);
12639 tree arg10 = TREE_OPERAND (arg1, 0);
12640 tree arg11 = TREE_OPERAND (arg1, 1);
12641 tree itype = TREE_TYPE (arg0);
12643 /* Optimize (X ^ Z) op (Y ^ Z) as X op Y, and symmetries.
12644 operand_equal_p guarantees no side-effects so we don't need
12645 to use omit_one_operand on Z. */
12646 if (operand_equal_p (arg01, arg11, 0))
12647 return fold_build2_loc (loc, code, type, arg00,
12648 fold_convert_loc (loc, TREE_TYPE (arg00),
12649 arg10));
12650 if (operand_equal_p (arg01, arg10, 0))
12651 return fold_build2_loc (loc, code, type, arg00,
12652 fold_convert_loc (loc, TREE_TYPE (arg00),
12653 arg11));
12654 if (operand_equal_p (arg00, arg11, 0))
12655 return fold_build2_loc (loc, code, type, arg01,
12656 fold_convert_loc (loc, TREE_TYPE (arg01),
12657 arg10));
12658 if (operand_equal_p (arg00, arg10, 0))
12659 return fold_build2_loc (loc, code, type, arg01,
12660 fold_convert_loc (loc, TREE_TYPE (arg01),
12661 arg11));
12663 /* Optimize (X ^ C1) op (Y ^ C2) as (X ^ (C1 ^ C2)) op Y. */
12664 if (TREE_CODE (arg01) == INTEGER_CST
12665 && TREE_CODE (arg11) == INTEGER_CST)
12667 tem = fold_build2_loc (loc, BIT_XOR_EXPR, itype, arg01,
12668 fold_convert_loc (loc, itype, arg11));
12669 tem = fold_build2_loc (loc, BIT_XOR_EXPR, itype, arg00, tem);
12670 return fold_build2_loc (loc, code, type, tem,
12671 fold_convert_loc (loc, itype, arg10));
12675 /* Attempt to simplify equality/inequality comparisons of complex
12676 values. Only lower the comparison if the result is known or
12677 can be simplified to a single scalar comparison. */
12678 if ((TREE_CODE (arg0) == COMPLEX_EXPR
12679 || TREE_CODE (arg0) == COMPLEX_CST)
12680 && (TREE_CODE (arg1) == COMPLEX_EXPR
12681 || TREE_CODE (arg1) == COMPLEX_CST))
12683 tree real0, imag0, real1, imag1;
12684 tree rcond, icond;
12686 if (TREE_CODE (arg0) == COMPLEX_EXPR)
12688 real0 = TREE_OPERAND (arg0, 0);
12689 imag0 = TREE_OPERAND (arg0, 1);
12691 else
12693 real0 = TREE_REALPART (arg0);
12694 imag0 = TREE_IMAGPART (arg0);
12697 if (TREE_CODE (arg1) == COMPLEX_EXPR)
12699 real1 = TREE_OPERAND (arg1, 0);
12700 imag1 = TREE_OPERAND (arg1, 1);
12702 else
12704 real1 = TREE_REALPART (arg1);
12705 imag1 = TREE_IMAGPART (arg1);
12708 rcond = fold_binary_loc (loc, code, type, real0, real1);
12709 if (rcond && TREE_CODE (rcond) == INTEGER_CST)
12711 if (integer_zerop (rcond))
12713 if (code == EQ_EXPR)
12714 return omit_two_operands_loc (loc, type, boolean_false_node,
12715 imag0, imag1);
12716 return fold_build2_loc (loc, NE_EXPR, type, imag0, imag1);
12718 else
12720 if (code == NE_EXPR)
12721 return omit_two_operands_loc (loc, type, boolean_true_node,
12722 imag0, imag1);
12723 return fold_build2_loc (loc, EQ_EXPR, type, imag0, imag1);
12727 icond = fold_binary_loc (loc, code, type, imag0, imag1);
12728 if (icond && TREE_CODE (icond) == INTEGER_CST)
12730 if (integer_zerop (icond))
12732 if (code == EQ_EXPR)
12733 return omit_two_operands_loc (loc, type, boolean_false_node,
12734 real0, real1);
12735 return fold_build2_loc (loc, NE_EXPR, type, real0, real1);
12737 else
12739 if (code == NE_EXPR)
12740 return omit_two_operands_loc (loc, type, boolean_true_node,
12741 real0, real1);
12742 return fold_build2_loc (loc, EQ_EXPR, type, real0, real1);
12747 return NULL_TREE;
12749 case LT_EXPR:
12750 case GT_EXPR:
12751 case LE_EXPR:
12752 case GE_EXPR:
12753 tem = fold_comparison (loc, code, type, op0, op1);
12754 if (tem != NULL_TREE)
12755 return tem;
12757 /* Transform comparisons of the form X +- C CMP X. */
12758 if ((TREE_CODE (arg0) == PLUS_EXPR || TREE_CODE (arg0) == MINUS_EXPR)
12759 && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0)
12760 && TREE_CODE (TREE_OPERAND (arg0, 1)) == REAL_CST
12761 && !HONOR_SNANS (arg0))
12763 tree arg01 = TREE_OPERAND (arg0, 1);
12764 enum tree_code code0 = TREE_CODE (arg0);
12765 int is_positive = REAL_VALUE_NEGATIVE (TREE_REAL_CST (arg01)) ? -1 : 1;
12767 /* (X - c) > X becomes false. */
12768 if (code == GT_EXPR
12769 && ((code0 == MINUS_EXPR && is_positive >= 0)
12770 || (code0 == PLUS_EXPR && is_positive <= 0)))
12771 return constant_boolean_node (0, type);
12773 /* Likewise (X + c) < X becomes false. */
12774 if (code == LT_EXPR
12775 && ((code0 == PLUS_EXPR && is_positive >= 0)
12776 || (code0 == MINUS_EXPR && is_positive <= 0)))
12777 return constant_boolean_node (0, type);
12779 /* Convert (X - c) <= X to true. */
12780 if (!HONOR_NANS (arg1)
12781 && code == LE_EXPR
12782 && ((code0 == MINUS_EXPR && is_positive >= 0)
12783 || (code0 == PLUS_EXPR && is_positive <= 0)))
12784 return constant_boolean_node (1, type);
12786 /* Convert (X + c) >= X to true. */
12787 if (!HONOR_NANS (arg1)
12788 && code == GE_EXPR
12789 && ((code0 == PLUS_EXPR && is_positive >= 0)
12790 || (code0 == MINUS_EXPR && is_positive <= 0)))
12791 return constant_boolean_node (1, type);
12794 /* If we are comparing an ABS_EXPR with a constant, we can
12795 convert all the cases into explicit comparisons, but they may
12796 well not be faster than doing the ABS and one comparison.
12797 But ABS (X) <= C is a range comparison, which becomes a subtraction
12798 and a comparison, and is probably faster. */
12799 if (code == LE_EXPR
12800 && TREE_CODE (arg1) == INTEGER_CST
12801 && TREE_CODE (arg0) == ABS_EXPR
12802 && ! TREE_SIDE_EFFECTS (arg0)
12803 && (tem = negate_expr (arg1)) != 0
12804 && TREE_CODE (tem) == INTEGER_CST
12805 && !TREE_OVERFLOW (tem))
12806 return fold_build2_loc (loc, TRUTH_ANDIF_EXPR, type,
12807 build2 (GE_EXPR, type,
12808 TREE_OPERAND (arg0, 0), tem),
12809 build2 (LE_EXPR, type,
12810 TREE_OPERAND (arg0, 0), arg1));
12812 /* Convert ABS_EXPR<x> >= 0 to true. */
12813 strict_overflow_p = false;
12814 if (code == GE_EXPR
12815 && (integer_zerop (arg1)
12816 || (! HONOR_NANS (arg0)
12817 && real_zerop (arg1)))
12818 && tree_expr_nonnegative_warnv_p (arg0, &strict_overflow_p))
12820 if (strict_overflow_p)
12821 fold_overflow_warning (("assuming signed overflow does not occur "
12822 "when simplifying comparison of "
12823 "absolute value and zero"),
12824 WARN_STRICT_OVERFLOW_CONDITIONAL);
12825 return omit_one_operand_loc (loc, type,
12826 constant_boolean_node (true, type),
12827 arg0);
12830 /* Convert ABS_EXPR<x> < 0 to false. */
12831 strict_overflow_p = false;
12832 if (code == LT_EXPR
12833 && (integer_zerop (arg1) || real_zerop (arg1))
12834 && tree_expr_nonnegative_warnv_p (arg0, &strict_overflow_p))
12836 if (strict_overflow_p)
12837 fold_overflow_warning (("assuming signed overflow does not occur "
12838 "when simplifying comparison of "
12839 "absolute value and zero"),
12840 WARN_STRICT_OVERFLOW_CONDITIONAL);
12841 return omit_one_operand_loc (loc, type,
12842 constant_boolean_node (false, type),
12843 arg0);
12846 /* If X is unsigned, convert X < (1 << Y) into X >> Y == 0
12847 and similarly for >= into !=. */
12848 if ((code == LT_EXPR || code == GE_EXPR)
12849 && TYPE_UNSIGNED (TREE_TYPE (arg0))
12850 && TREE_CODE (arg1) == LSHIFT_EXPR
12851 && integer_onep (TREE_OPERAND (arg1, 0)))
12852 return build2_loc (loc, code == LT_EXPR ? EQ_EXPR : NE_EXPR, type,
12853 build2 (RSHIFT_EXPR, TREE_TYPE (arg0), arg0,
12854 TREE_OPERAND (arg1, 1)),
12855 build_zero_cst (TREE_TYPE (arg0)));
12857 /* Similarly for X < (cast) (1 << Y). But cast can't be narrowing,
12858 otherwise Y might be >= # of bits in X's type and thus e.g.
12859 (unsigned char) (1 << Y) for Y 15 might be 0.
12860 If the cast is widening, then 1 << Y should have unsigned type,
12861 otherwise if Y is number of bits in the signed shift type minus 1,
12862 we can't optimize this. E.g. (unsigned long long) (1 << Y) for Y
12863 31 might be 0xffffffff80000000. */
12864 if ((code == LT_EXPR || code == GE_EXPR)
12865 && (INTEGRAL_TYPE_P (TREE_TYPE (arg0))
12866 || VECTOR_INTEGER_TYPE_P (TREE_TYPE (arg0)))
12867 && TYPE_UNSIGNED (TREE_TYPE (arg0))
12868 && CONVERT_EXPR_P (arg1)
12869 && TREE_CODE (TREE_OPERAND (arg1, 0)) == LSHIFT_EXPR
12870 && (element_precision (TREE_TYPE (arg1))
12871 >= element_precision (TREE_TYPE (TREE_OPERAND (arg1, 0))))
12872 && (TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (arg1, 0)))
12873 || (element_precision (TREE_TYPE (arg1))
12874 == element_precision (TREE_TYPE (TREE_OPERAND (arg1, 0)))))
12875 && integer_onep (TREE_OPERAND (TREE_OPERAND (arg1, 0), 0)))
12877 tem = build2 (RSHIFT_EXPR, TREE_TYPE (arg0), arg0,
12878 TREE_OPERAND (TREE_OPERAND (arg1, 0), 1));
12879 return build2_loc (loc, code == LT_EXPR ? EQ_EXPR : NE_EXPR, type,
12880 fold_convert_loc (loc, TREE_TYPE (arg0), tem),
12881 build_zero_cst (TREE_TYPE (arg0)));
12884 return NULL_TREE;
12886 case UNORDERED_EXPR:
12887 case ORDERED_EXPR:
12888 case UNLT_EXPR:
12889 case UNLE_EXPR:
12890 case UNGT_EXPR:
12891 case UNGE_EXPR:
12892 case UNEQ_EXPR:
12893 case LTGT_EXPR:
12894 /* Fold (double)float1 CMP (double)float2 into float1 CMP float2. */
12896 tree targ0 = strip_float_extensions (arg0);
12897 tree targ1 = strip_float_extensions (arg1);
12898 tree newtype = TREE_TYPE (targ0);
12900 if (element_precision (TREE_TYPE (targ1)) > element_precision (newtype))
12901 newtype = TREE_TYPE (targ1);
12903 if (element_precision (newtype) < element_precision (TREE_TYPE (arg0))
12904 && (!VECTOR_TYPE_P (type) || is_truth_type_for (newtype, type)))
12905 return fold_build2_loc (loc, code, type,
12906 fold_convert_loc (loc, newtype, targ0),
12907 fold_convert_loc (loc, newtype, targ1));
12910 return NULL_TREE;
12912 case COMPOUND_EXPR:
12913 /* When pedantic, a compound expression can be neither an lvalue
12914 nor an integer constant expression. */
12915 if (TREE_SIDE_EFFECTS (arg0) || TREE_CONSTANT (arg1))
12916 return NULL_TREE;
12917 /* Don't let (0, 0) be null pointer constant. */
12918 tem = integer_zerop (arg1) ? build1_loc (loc, NOP_EXPR, type, arg1)
12919 : fold_convert_loc (loc, type, arg1);
12920 return tem;
12922 default:
12923 return NULL_TREE;
12924 } /* switch (code) */
12927 /* For constants M and N, if M == (1LL << cst) - 1 && (N & M) == M,
12928 ((A & N) + B) & M -> (A + B) & M
12929 Similarly if (N & M) == 0,
12930 ((A | N) + B) & M -> (A + B) & M
12931 and for - instead of + (or unary - instead of +)
12932 and/or ^ instead of |.
12933 If B is constant and (B & M) == 0, fold into A & M.
12935 This function is a helper for match.pd patterns. Return non-NULL
12936 type in which the simplified operation should be performed only
12937 if any optimization is possible.
12939 ARG1 is M above, ARG00 is left operand of +/-, if CODE00 is BIT_*_EXPR,
12940 then ARG00{0,1} are operands of that bitop, otherwise CODE00 is ERROR_MARK.
12941 Similarly for ARG01, CODE01 and ARG01{0,1}, just for the right operand of
12942 +/-. */
12943 tree
12944 fold_bit_and_mask (tree type, tree arg1, enum tree_code code,
12945 tree arg00, enum tree_code code00, tree arg000, tree arg001,
12946 tree arg01, enum tree_code code01, tree arg010, tree arg011,
12947 tree *pmop)
12949 gcc_assert (TREE_CODE (arg1) == INTEGER_CST);
12950 gcc_assert (code == PLUS_EXPR || code == MINUS_EXPR || code == NEGATE_EXPR);
12951 wi::tree_to_wide_ref cst1 = wi::to_wide (arg1);
12952 if (~cst1 == 0
12953 || (cst1 & (cst1 + 1)) != 0
12954 || !INTEGRAL_TYPE_P (type)
12955 || (!TYPE_OVERFLOW_WRAPS (type)
12956 && TREE_CODE (type) != INTEGER_TYPE)
12957 || (wi::max_value (type) & cst1) != cst1)
12958 return NULL_TREE;
12960 enum tree_code codes[2] = { code00, code01 };
12961 tree arg0xx[4] = { arg000, arg001, arg010, arg011 };
12962 int which = 0;
12963 wide_int cst0;
12965 /* Now we know that arg0 is (C + D) or (C - D) or -C and
12966 arg1 (M) is == (1LL << cst) - 1.
12967 Store C into PMOP[0] and D into PMOP[1]. */
12968 pmop[0] = arg00;
12969 pmop[1] = arg01;
12970 which = code != NEGATE_EXPR;
12972 for (; which >= 0; which--)
12973 switch (codes[which])
12975 case BIT_AND_EXPR:
12976 case BIT_IOR_EXPR:
12977 case BIT_XOR_EXPR:
12978 gcc_assert (TREE_CODE (arg0xx[2 * which + 1]) == INTEGER_CST);
12979 cst0 = wi::to_wide (arg0xx[2 * which + 1]) & cst1;
12980 if (codes[which] == BIT_AND_EXPR)
12982 if (cst0 != cst1)
12983 break;
12985 else if (cst0 != 0)
12986 break;
12987 /* If C or D is of the form (A & N) where
12988 (N & M) == M, or of the form (A | N) or
12989 (A ^ N) where (N & M) == 0, replace it with A. */
12990 pmop[which] = arg0xx[2 * which];
12991 break;
12992 case ERROR_MARK:
12993 if (TREE_CODE (pmop[which]) != INTEGER_CST)
12994 break;
12995 /* If C or D is a N where (N & M) == 0, it can be
12996 omitted (replaced with 0). */
12997 if ((code == PLUS_EXPR
12998 || (code == MINUS_EXPR && which == 0))
12999 && (cst1 & wi::to_wide (pmop[which])) == 0)
13000 pmop[which] = build_int_cst (type, 0);
13001 /* Similarly, with C - N where (-N & M) == 0. */
13002 if (code == MINUS_EXPR
13003 && which == 1
13004 && (cst1 & -wi::to_wide (pmop[which])) == 0)
13005 pmop[which] = build_int_cst (type, 0);
13006 break;
13007 default:
13008 gcc_unreachable ();
13011 /* Only build anything new if we optimized one or both arguments above. */
13012 if (pmop[0] == arg00 && pmop[1] == arg01)
13013 return NULL_TREE;
13015 if (TYPE_OVERFLOW_WRAPS (type))
13016 return type;
13017 else
13018 return unsigned_type_for (type);
13021 /* Used by contains_label_[p1]. */
13023 struct contains_label_data
13025 hash_set<tree> *pset;
13026 bool inside_switch_p;
13029 /* Callback for walk_tree, looking for LABEL_EXPR. Return *TP if it is
13030 a LABEL_EXPR or CASE_LABEL_EXPR not inside of another SWITCH_EXPR; otherwise
13031 return NULL_TREE. Do not check the subtrees of GOTO_EXPR. */
13033 static tree
13034 contains_label_1 (tree *tp, int *walk_subtrees, void *data)
13036 contains_label_data *d = (contains_label_data *) data;
13037 switch (TREE_CODE (*tp))
13039 case LABEL_EXPR:
13040 return *tp;
13042 case CASE_LABEL_EXPR:
13043 if (!d->inside_switch_p)
13044 return *tp;
13045 return NULL_TREE;
13047 case SWITCH_EXPR:
13048 if (!d->inside_switch_p)
13050 if (walk_tree (&SWITCH_COND (*tp), contains_label_1, data, d->pset))
13051 return *tp;
13052 d->inside_switch_p = true;
13053 if (walk_tree (&SWITCH_BODY (*tp), contains_label_1, data, d->pset))
13054 return *tp;
13055 d->inside_switch_p = false;
13056 *walk_subtrees = 0;
13058 return NULL_TREE;
13060 case GOTO_EXPR:
13061 *walk_subtrees = 0;
13062 return NULL_TREE;
13064 default:
13065 return NULL_TREE;
13069 /* Return whether the sub-tree ST contains a label which is accessible from
13070 outside the sub-tree. */
13072 static bool
13073 contains_label_p (tree st)
13075 hash_set<tree> pset;
13076 contains_label_data data = { &pset, false };
13077 return walk_tree (&st, contains_label_1, &data, &pset) != NULL_TREE;
13080 /* Fold a ternary expression of code CODE and type TYPE with operands
13081 OP0, OP1, and OP2. Return the folded expression if folding is
13082 successful. Otherwise, return NULL_TREE. */
13084 tree
13085 fold_ternary_loc (location_t loc, enum tree_code code, tree type,
13086 tree op0, tree op1, tree op2)
13088 tree tem;
13089 tree arg0 = NULL_TREE, arg1 = NULL_TREE, arg2 = NULL_TREE;
13090 enum tree_code_class kind = TREE_CODE_CLASS (code);
13092 gcc_assert (IS_EXPR_CODE_CLASS (kind)
13093 && TREE_CODE_LENGTH (code) == 3);
13095 /* If this is a commutative operation, and OP0 is a constant, move it
13096 to OP1 to reduce the number of tests below. */
13097 if (commutative_ternary_tree_code (code)
13098 && tree_swap_operands_p (op0, op1))
13099 return fold_build3_loc (loc, code, type, op1, op0, op2);
13101 tem = generic_simplify (loc, code, type, op0, op1, op2);
13102 if (tem)
13103 return tem;
13105 /* Strip any conversions that don't change the mode. This is safe
13106 for every expression, except for a comparison expression because
13107 its signedness is derived from its operands. So, in the latter
13108 case, only strip conversions that don't change the signedness.
13110 Note that this is done as an internal manipulation within the
13111 constant folder, in order to find the simplest representation of
13112 the arguments so that their form can be studied. In any cases,
13113 the appropriate type conversions should be put back in the tree
13114 that will get out of the constant folder. */
13115 if (op0)
13117 arg0 = op0;
13118 STRIP_NOPS (arg0);
13121 if (op1)
13123 arg1 = op1;
13124 STRIP_NOPS (arg1);
13127 if (op2)
13129 arg2 = op2;
13130 STRIP_NOPS (arg2);
13133 switch (code)
13135 case COMPONENT_REF:
13136 if (TREE_CODE (arg0) == CONSTRUCTOR
13137 && ! type_contains_placeholder_p (TREE_TYPE (arg0)))
13139 unsigned HOST_WIDE_INT idx;
13140 tree field, value;
13141 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg0), idx, field, value)
13142 if (field == arg1)
13143 return value;
13145 return NULL_TREE;
13147 case COND_EXPR:
13148 case VEC_COND_EXPR:
13149 /* Pedantic ANSI C says that a conditional expression is never an lvalue,
13150 so all simple results must be passed through pedantic_non_lvalue. */
13151 if (TREE_CODE (arg0) == INTEGER_CST)
13153 tree unused_op = integer_zerop (arg0) ? op1 : op2;
13154 tem = integer_zerop (arg0) ? op2 : op1;
13155 /* Only optimize constant conditions when the selected branch
13156 has the same type as the COND_EXPR. This avoids optimizing
13157 away "c ? x : throw", where the throw has a void type.
13158 Avoid throwing away that operand which contains label. */
13159 if ((!TREE_SIDE_EFFECTS (unused_op)
13160 || !contains_label_p (unused_op))
13161 && (! VOID_TYPE_P (TREE_TYPE (tem))
13162 || VOID_TYPE_P (type)))
13163 return protected_set_expr_location_unshare (tem, loc);
13164 return NULL_TREE;
13166 else if (TREE_CODE (arg0) == VECTOR_CST)
13168 unsigned HOST_WIDE_INT nelts;
13169 if ((TREE_CODE (arg1) == VECTOR_CST
13170 || TREE_CODE (arg1) == CONSTRUCTOR)
13171 && (TREE_CODE (arg2) == VECTOR_CST
13172 || TREE_CODE (arg2) == CONSTRUCTOR)
13173 && TYPE_VECTOR_SUBPARTS (type).is_constant (&nelts))
13175 vec_perm_builder sel (nelts, nelts, 1);
13176 for (unsigned int i = 0; i < nelts; i++)
13178 tree val = VECTOR_CST_ELT (arg0, i);
13179 if (integer_all_onesp (val))
13180 sel.quick_push (i);
13181 else if (integer_zerop (val))
13182 sel.quick_push (nelts + i);
13183 else /* Currently unreachable. */
13184 return NULL_TREE;
13186 vec_perm_indices indices (sel, 2, nelts);
13187 tree t = fold_vec_perm (type, arg1, arg2, indices);
13188 if (t != NULL_TREE)
13189 return t;
13193 /* If we have A op B ? A : C, we may be able to convert this to a
13194 simpler expression, depending on the operation and the values
13195 of B and C. Signed zeros prevent all of these transformations,
13196 for reasons given above each one.
13198 Also try swapping the arguments and inverting the conditional. */
13199 if (COMPARISON_CLASS_P (arg0)
13200 && operand_equal_for_comparison_p (TREE_OPERAND (arg0, 0), op1)
13201 && !HONOR_SIGNED_ZEROS (op1))
13203 tem = fold_cond_expr_with_comparison (loc, type, TREE_CODE (arg0),
13204 TREE_OPERAND (arg0, 0),
13205 TREE_OPERAND (arg0, 1),
13206 op1, op2);
13207 if (tem)
13208 return tem;
13211 if (COMPARISON_CLASS_P (arg0)
13212 && operand_equal_for_comparison_p (TREE_OPERAND (arg0, 0), op2)
13213 && !HONOR_SIGNED_ZEROS (op2))
13215 enum tree_code comp_code = TREE_CODE (arg0);
13216 tree arg00 = TREE_OPERAND (arg0, 0);
13217 tree arg01 = TREE_OPERAND (arg0, 1);
13218 comp_code = invert_tree_comparison (comp_code, HONOR_NANS (arg00));
13219 if (comp_code != ERROR_MARK)
13220 tem = fold_cond_expr_with_comparison (loc, type, comp_code,
13221 arg00,
13222 arg01,
13223 op2, op1);
13224 if (tem)
13225 return tem;
13228 /* If the second operand is simpler than the third, swap them
13229 since that produces better jump optimization results. */
13230 if (truth_value_p (TREE_CODE (arg0))
13231 && tree_swap_operands_p (op1, op2))
13233 location_t loc0 = expr_location_or (arg0, loc);
13234 /* See if this can be inverted. If it can't, possibly because
13235 it was a floating-point inequality comparison, don't do
13236 anything. */
13237 tem = fold_invert_truthvalue (loc0, arg0);
13238 if (tem)
13239 return fold_build3_loc (loc, code, type, tem, op2, op1);
13242 /* Convert A ? 1 : 0 to simply A. */
13243 if ((code == VEC_COND_EXPR ? integer_all_onesp (op1)
13244 : (integer_onep (op1)
13245 && !VECTOR_TYPE_P (type)))
13246 && integer_zerop (op2)
13247 /* If we try to convert OP0 to our type, the
13248 call to fold will try to move the conversion inside
13249 a COND, which will recurse. In that case, the COND_EXPR
13250 is probably the best choice, so leave it alone. */
13251 && type == TREE_TYPE (arg0))
13252 return protected_set_expr_location_unshare (arg0, loc);
13254 /* Convert A ? 0 : 1 to !A. This prefers the use of NOT_EXPR
13255 over COND_EXPR in cases such as floating point comparisons. */
13256 if (integer_zerop (op1)
13257 && code == COND_EXPR
13258 && integer_onep (op2)
13259 && !VECTOR_TYPE_P (type)
13260 && truth_value_p (TREE_CODE (arg0)))
13261 return fold_convert_loc (loc, type,
13262 invert_truthvalue_loc (loc, arg0));
13264 /* A < 0 ? <sign bit of A> : 0 is simply (A & <sign bit of A>). */
13265 if (TREE_CODE (arg0) == LT_EXPR
13266 && integer_zerop (TREE_OPERAND (arg0, 1))
13267 && integer_zerop (op2)
13268 && (tem = sign_bit_p (TREE_OPERAND (arg0, 0), arg1)))
13270 /* sign_bit_p looks through both zero and sign extensions,
13271 but for this optimization only sign extensions are
13272 usable. */
13273 tree tem2 = TREE_OPERAND (arg0, 0);
13274 while (tem != tem2)
13276 if (TREE_CODE (tem2) != NOP_EXPR
13277 || TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (tem2, 0))))
13279 tem = NULL_TREE;
13280 break;
13282 tem2 = TREE_OPERAND (tem2, 0);
13284 /* sign_bit_p only checks ARG1 bits within A's precision.
13285 If <sign bit of A> has wider type than A, bits outside
13286 of A's precision in <sign bit of A> need to be checked.
13287 If they are all 0, this optimization needs to be done
13288 in unsigned A's type, if they are all 1 in signed A's type,
13289 otherwise this can't be done. */
13290 if (tem
13291 && TYPE_PRECISION (TREE_TYPE (tem))
13292 < TYPE_PRECISION (TREE_TYPE (arg1))
13293 && TYPE_PRECISION (TREE_TYPE (tem))
13294 < TYPE_PRECISION (type))
13296 int inner_width, outer_width;
13297 tree tem_type;
13299 inner_width = TYPE_PRECISION (TREE_TYPE (tem));
13300 outer_width = TYPE_PRECISION (TREE_TYPE (arg1));
13301 if (outer_width > TYPE_PRECISION (type))
13302 outer_width = TYPE_PRECISION (type);
13304 wide_int mask = wi::shifted_mask
13305 (inner_width, outer_width - inner_width, false,
13306 TYPE_PRECISION (TREE_TYPE (arg1)));
13308 wide_int common = mask & wi::to_wide (arg1);
13309 if (common == mask)
13311 tem_type = signed_type_for (TREE_TYPE (tem));
13312 tem = fold_convert_loc (loc, tem_type, tem);
13314 else if (common == 0)
13316 tem_type = unsigned_type_for (TREE_TYPE (tem));
13317 tem = fold_convert_loc (loc, tem_type, tem);
13319 else
13320 tem = NULL;
13323 if (tem)
13324 return
13325 fold_convert_loc (loc, type,
13326 fold_build2_loc (loc, BIT_AND_EXPR,
13327 TREE_TYPE (tem), tem,
13328 fold_convert_loc (loc,
13329 TREE_TYPE (tem),
13330 arg1)));
13333 /* (A >> N) & 1 ? (1 << N) : 0 is simply A & (1 << N). A & 1 was
13334 already handled above. */
13335 if (TREE_CODE (arg0) == BIT_AND_EXPR
13336 && integer_onep (TREE_OPERAND (arg0, 1))
13337 && integer_zerop (op2)
13338 && integer_pow2p (arg1))
13340 tree tem = TREE_OPERAND (arg0, 0);
13341 STRIP_NOPS (tem);
13342 if (TREE_CODE (tem) == RSHIFT_EXPR
13343 && tree_fits_uhwi_p (TREE_OPERAND (tem, 1))
13344 && (unsigned HOST_WIDE_INT) tree_log2 (arg1)
13345 == tree_to_uhwi (TREE_OPERAND (tem, 1)))
13346 return fold_build2_loc (loc, BIT_AND_EXPR, type,
13347 fold_convert_loc (loc, type,
13348 TREE_OPERAND (tem, 0)),
13349 op1);
13352 /* A & N ? N : 0 is simply A & N if N is a power of two. This
13353 is probably obsolete because the first operand should be a
13354 truth value (that's why we have the two cases above), but let's
13355 leave it in until we can confirm this for all front-ends. */
13356 if (integer_zerop (op2)
13357 && TREE_CODE (arg0) == NE_EXPR
13358 && integer_zerop (TREE_OPERAND (arg0, 1))
13359 && integer_pow2p (arg1)
13360 && TREE_CODE (TREE_OPERAND (arg0, 0)) == BIT_AND_EXPR
13361 && operand_equal_p (TREE_OPERAND (TREE_OPERAND (arg0, 0), 1),
13362 arg1, OEP_ONLY_CONST)
13363 /* operand_equal_p compares just value, not precision, so e.g.
13364 arg1 could be 8-bit -128 and be power of two, but BIT_AND_EXPR
13365 second operand 32-bit -128, which is not a power of two (or vice
13366 versa. */
13367 && integer_pow2p (TREE_OPERAND (TREE_OPERAND (arg0, 0), 1)))
13368 return fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
13370 /* Disable the transformations below for vectors, since
13371 fold_binary_op_with_conditional_arg may undo them immediately,
13372 yielding an infinite loop. */
13373 if (code == VEC_COND_EXPR)
13374 return NULL_TREE;
13376 /* Convert A ? B : 0 into A && B if A and B are truth values. */
13377 if (integer_zerop (op2)
13378 && truth_value_p (TREE_CODE (arg0))
13379 && truth_value_p (TREE_CODE (arg1))
13380 && (code == VEC_COND_EXPR || !VECTOR_TYPE_P (type)))
13381 return fold_build2_loc (loc, code == VEC_COND_EXPR ? BIT_AND_EXPR
13382 : TRUTH_ANDIF_EXPR,
13383 type, fold_convert_loc (loc, type, arg0), op1);
13385 /* Convert A ? B : 1 into !A || B if A and B are truth values. */
13386 if (code == VEC_COND_EXPR ? integer_all_onesp (op2) : integer_onep (op2)
13387 && truth_value_p (TREE_CODE (arg0))
13388 && truth_value_p (TREE_CODE (arg1))
13389 && (code == VEC_COND_EXPR || !VECTOR_TYPE_P (type)))
13391 location_t loc0 = expr_location_or (arg0, loc);
13392 /* Only perform transformation if ARG0 is easily inverted. */
13393 tem = fold_invert_truthvalue (loc0, arg0);
13394 if (tem)
13395 return fold_build2_loc (loc, code == VEC_COND_EXPR
13396 ? BIT_IOR_EXPR
13397 : TRUTH_ORIF_EXPR,
13398 type, fold_convert_loc (loc, type, tem),
13399 op1);
13402 /* Convert A ? 0 : B into !A && B if A and B are truth values. */
13403 if (integer_zerop (arg1)
13404 && truth_value_p (TREE_CODE (arg0))
13405 && truth_value_p (TREE_CODE (op2))
13406 && (code == VEC_COND_EXPR || !VECTOR_TYPE_P (type)))
13408 location_t loc0 = expr_location_or (arg0, loc);
13409 /* Only perform transformation if ARG0 is easily inverted. */
13410 tem = fold_invert_truthvalue (loc0, arg0);
13411 if (tem)
13412 return fold_build2_loc (loc, code == VEC_COND_EXPR
13413 ? BIT_AND_EXPR : TRUTH_ANDIF_EXPR,
13414 type, fold_convert_loc (loc, type, tem),
13415 op2);
13418 /* Convert A ? 1 : B into A || B if A and B are truth values. */
13419 if (code == VEC_COND_EXPR ? integer_all_onesp (arg1) : integer_onep (arg1)
13420 && truth_value_p (TREE_CODE (arg0))
13421 && truth_value_p (TREE_CODE (op2))
13422 && (code == VEC_COND_EXPR || !VECTOR_TYPE_P (type)))
13423 return fold_build2_loc (loc, code == VEC_COND_EXPR
13424 ? BIT_IOR_EXPR : TRUTH_ORIF_EXPR,
13425 type, fold_convert_loc (loc, type, arg0), op2);
13427 return NULL_TREE;
13429 case CALL_EXPR:
13430 /* CALL_EXPRs used to be ternary exprs. Catch any mistaken uses
13431 of fold_ternary on them. */
13432 gcc_unreachable ();
13434 case BIT_FIELD_REF:
13435 if (TREE_CODE (arg0) == VECTOR_CST
13436 && (type == TREE_TYPE (TREE_TYPE (arg0))
13437 || (VECTOR_TYPE_P (type)
13438 && TREE_TYPE (type) == TREE_TYPE (TREE_TYPE (arg0))))
13439 && tree_fits_uhwi_p (op1)
13440 && tree_fits_uhwi_p (op2))
13442 tree eltype = TREE_TYPE (TREE_TYPE (arg0));
13443 unsigned HOST_WIDE_INT width
13444 = (TREE_CODE (eltype) == BOOLEAN_TYPE
13445 ? TYPE_PRECISION (eltype) : tree_to_uhwi (TYPE_SIZE (eltype)));
13446 unsigned HOST_WIDE_INT n = tree_to_uhwi (arg1);
13447 unsigned HOST_WIDE_INT idx = tree_to_uhwi (op2);
13449 if (n != 0
13450 && (idx % width) == 0
13451 && (n % width) == 0
13452 && known_le ((idx + n) / width,
13453 TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0))))
13455 idx = idx / width;
13456 n = n / width;
13458 if (TREE_CODE (arg0) == VECTOR_CST)
13460 if (n == 1)
13462 tem = VECTOR_CST_ELT (arg0, idx);
13463 if (VECTOR_TYPE_P (type))
13464 tem = fold_build1 (VIEW_CONVERT_EXPR, type, tem);
13465 return tem;
13468 tree_vector_builder vals (type, n, 1);
13469 for (unsigned i = 0; i < n; ++i)
13470 vals.quick_push (VECTOR_CST_ELT (arg0, idx + i));
13471 return vals.build ();
13476 /* On constants we can use native encode/interpret to constant
13477 fold (nearly) all BIT_FIELD_REFs. */
13478 if (CONSTANT_CLASS_P (arg0)
13479 && can_native_interpret_type_p (type)
13480 && BITS_PER_UNIT == 8
13481 && tree_fits_uhwi_p (op1)
13482 && tree_fits_uhwi_p (op2))
13484 unsigned HOST_WIDE_INT bitpos = tree_to_uhwi (op2);
13485 unsigned HOST_WIDE_INT bitsize = tree_to_uhwi (op1);
13486 /* Limit us to a reasonable amount of work. To relax the
13487 other limitations we need bit-shifting of the buffer
13488 and rounding up the size. */
13489 if (bitpos % BITS_PER_UNIT == 0
13490 && bitsize % BITS_PER_UNIT == 0
13491 && bitsize <= MAX_BITSIZE_MODE_ANY_MODE)
13493 unsigned char b[MAX_BITSIZE_MODE_ANY_MODE / BITS_PER_UNIT];
13494 unsigned HOST_WIDE_INT len
13495 = native_encode_expr (arg0, b, bitsize / BITS_PER_UNIT,
13496 bitpos / BITS_PER_UNIT);
13497 if (len > 0
13498 && len * BITS_PER_UNIT >= bitsize)
13500 tree v = native_interpret_expr (type, b,
13501 bitsize / BITS_PER_UNIT);
13502 if (v)
13503 return v;
13508 return NULL_TREE;
13510 case VEC_PERM_EXPR:
13511 /* Perform constant folding of BIT_INSERT_EXPR. */
13512 if (TREE_CODE (arg2) == VECTOR_CST
13513 && TREE_CODE (op0) == VECTOR_CST
13514 && TREE_CODE (op1) == VECTOR_CST)
13516 /* Build a vector of integers from the tree mask. */
13517 vec_perm_builder builder;
13518 if (!tree_to_vec_perm_builder (&builder, arg2))
13519 return NULL_TREE;
13521 /* Create a vec_perm_indices for the integer vector. */
13522 poly_uint64 nelts = TYPE_VECTOR_SUBPARTS (type);
13523 bool single_arg = (op0 == op1);
13524 vec_perm_indices sel (builder, single_arg ? 1 : 2, nelts);
13525 return fold_vec_perm (type, op0, op1, sel);
13527 return NULL_TREE;
13529 case BIT_INSERT_EXPR:
13530 /* Perform (partial) constant folding of BIT_INSERT_EXPR. */
13531 if (TREE_CODE (arg0) == INTEGER_CST
13532 && TREE_CODE (arg1) == INTEGER_CST)
13534 unsigned HOST_WIDE_INT bitpos = tree_to_uhwi (op2);
13535 unsigned bitsize = TYPE_PRECISION (TREE_TYPE (arg1));
13536 wide_int tem = (wi::to_wide (arg0)
13537 & wi::shifted_mask (bitpos, bitsize, true,
13538 TYPE_PRECISION (type)));
13539 wide_int tem2
13540 = wi::lshift (wi::zext (wi::to_wide (arg1, TYPE_PRECISION (type)),
13541 bitsize), bitpos);
13542 return wide_int_to_tree (type, wi::bit_or (tem, tem2));
13544 else if (TREE_CODE (arg0) == VECTOR_CST
13545 && CONSTANT_CLASS_P (arg1)
13546 && types_compatible_p (TREE_TYPE (TREE_TYPE (arg0)),
13547 TREE_TYPE (arg1)))
13549 unsigned HOST_WIDE_INT bitpos = tree_to_uhwi (op2);
13550 unsigned HOST_WIDE_INT elsize
13551 = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (arg1)));
13552 if (bitpos % elsize == 0)
13554 unsigned k = bitpos / elsize;
13555 unsigned HOST_WIDE_INT nelts;
13556 if (operand_equal_p (VECTOR_CST_ELT (arg0, k), arg1, 0))
13557 return arg0;
13558 else if (VECTOR_CST_NELTS (arg0).is_constant (&nelts))
13560 tree_vector_builder elts (type, nelts, 1);
13561 elts.quick_grow (nelts);
13562 for (unsigned HOST_WIDE_INT i = 0; i < nelts; ++i)
13563 elts[i] = (i == k ? arg1 : VECTOR_CST_ELT (arg0, i));
13564 return elts.build ();
13568 return NULL_TREE;
13570 default:
13571 return NULL_TREE;
13572 } /* switch (code) */
13575 /* Gets the element ACCESS_INDEX from CTOR, which must be a CONSTRUCTOR
13576 of an array (or vector). *CTOR_IDX if non-NULL is updated with the
13577 constructor element index of the value returned. If the element is
13578 not found NULL_TREE is returned and *CTOR_IDX is updated to
13579 the index of the element after the ACCESS_INDEX position (which
13580 may be outside of the CTOR array). */
13582 tree
13583 get_array_ctor_element_at_index (tree ctor, offset_int access_index,
13584 unsigned *ctor_idx)
13586 tree index_type = NULL_TREE;
13587 signop index_sgn = UNSIGNED;
13588 offset_int low_bound = 0;
13590 if (TREE_CODE (TREE_TYPE (ctor)) == ARRAY_TYPE)
13592 tree domain_type = TYPE_DOMAIN (TREE_TYPE (ctor));
13593 if (domain_type && TYPE_MIN_VALUE (domain_type))
13595 /* Static constructors for variably sized objects makes no sense. */
13596 gcc_assert (TREE_CODE (TYPE_MIN_VALUE (domain_type)) == INTEGER_CST);
13597 index_type = TREE_TYPE (TYPE_MIN_VALUE (domain_type));
13598 /* ??? When it is obvious that the range is signed, treat it so. */
13599 if (TYPE_UNSIGNED (index_type)
13600 && TYPE_MAX_VALUE (domain_type)
13601 && tree_int_cst_lt (TYPE_MAX_VALUE (domain_type),
13602 TYPE_MIN_VALUE (domain_type)))
13604 index_sgn = SIGNED;
13605 low_bound
13606 = offset_int::from (wi::to_wide (TYPE_MIN_VALUE (domain_type)),
13607 SIGNED);
13609 else
13611 index_sgn = TYPE_SIGN (index_type);
13612 low_bound = wi::to_offset (TYPE_MIN_VALUE (domain_type));
13617 if (index_type)
13618 access_index = wi::ext (access_index, TYPE_PRECISION (index_type),
13619 index_sgn);
13621 offset_int index = low_bound;
13622 if (index_type)
13623 index = wi::ext (index, TYPE_PRECISION (index_type), index_sgn);
13625 offset_int max_index = index;
13626 unsigned cnt;
13627 tree cfield, cval;
13628 bool first_p = true;
13630 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), cnt, cfield, cval)
13632 /* Array constructor might explicitly set index, or specify a range,
13633 or leave index NULL meaning that it is next index after previous
13634 one. */
13635 if (cfield)
13637 if (TREE_CODE (cfield) == INTEGER_CST)
13638 max_index = index
13639 = offset_int::from (wi::to_wide (cfield), index_sgn);
13640 else
13642 gcc_assert (TREE_CODE (cfield) == RANGE_EXPR);
13643 index = offset_int::from (wi::to_wide (TREE_OPERAND (cfield, 0)),
13644 index_sgn);
13645 max_index
13646 = offset_int::from (wi::to_wide (TREE_OPERAND (cfield, 1)),
13647 index_sgn);
13648 gcc_checking_assert (wi::le_p (index, max_index, index_sgn));
13651 else if (!first_p)
13653 index = max_index + 1;
13654 if (index_type)
13655 index = wi::ext (index, TYPE_PRECISION (index_type), index_sgn);
13656 gcc_checking_assert (wi::gt_p (index, max_index, index_sgn));
13657 max_index = index;
13659 else
13660 first_p = false;
13662 /* Do we have match? */
13663 if (wi::cmp (access_index, index, index_sgn) >= 0)
13665 if (wi::cmp (access_index, max_index, index_sgn) <= 0)
13667 if (ctor_idx)
13668 *ctor_idx = cnt;
13669 return cval;
13672 else if (in_gimple_form)
13673 /* We're past the element we search for. Note during parsing
13674 the elements might not be sorted.
13675 ??? We should use a binary search and a flag on the
13676 CONSTRUCTOR as to whether elements are sorted in declaration
13677 order. */
13678 break;
13680 if (ctor_idx)
13681 *ctor_idx = cnt;
13682 return NULL_TREE;
13685 /* Perform constant folding and related simplification of EXPR.
13686 The related simplifications include x*1 => x, x*0 => 0, etc.,
13687 and application of the associative law.
13688 NOP_EXPR conversions may be removed freely (as long as we
13689 are careful not to change the type of the overall expression).
13690 We cannot simplify through a CONVERT_EXPR, FIX_EXPR or FLOAT_EXPR,
13691 but we can constant-fold them if they have constant operands. */
13693 #ifdef ENABLE_FOLD_CHECKING
13694 # define fold(x) fold_1 (x)
13695 static tree fold_1 (tree);
13696 static
13697 #endif
13698 tree
13699 fold (tree expr)
13701 const tree t = expr;
13702 enum tree_code code = TREE_CODE (t);
13703 enum tree_code_class kind = TREE_CODE_CLASS (code);
13704 tree tem;
13705 location_t loc = EXPR_LOCATION (expr);
13707 /* Return right away if a constant. */
13708 if (kind == tcc_constant)
13709 return t;
13711 /* CALL_EXPR-like objects with variable numbers of operands are
13712 treated specially. */
13713 if (kind == tcc_vl_exp)
13715 if (code == CALL_EXPR)
13717 tem = fold_call_expr (loc, expr, false);
13718 return tem ? tem : expr;
13720 return expr;
13723 if (IS_EXPR_CODE_CLASS (kind))
13725 tree type = TREE_TYPE (t);
13726 tree op0, op1, op2;
13728 switch (TREE_CODE_LENGTH (code))
13730 case 1:
13731 op0 = TREE_OPERAND (t, 0);
13732 tem = fold_unary_loc (loc, code, type, op0);
13733 return tem ? tem : expr;
13734 case 2:
13735 op0 = TREE_OPERAND (t, 0);
13736 op1 = TREE_OPERAND (t, 1);
13737 tem = fold_binary_loc (loc, code, type, op0, op1);
13738 return tem ? tem : expr;
13739 case 3:
13740 op0 = TREE_OPERAND (t, 0);
13741 op1 = TREE_OPERAND (t, 1);
13742 op2 = TREE_OPERAND (t, 2);
13743 tem = fold_ternary_loc (loc, code, type, op0, op1, op2);
13744 return tem ? tem : expr;
13745 default:
13746 break;
13750 switch (code)
13752 case ARRAY_REF:
13754 tree op0 = TREE_OPERAND (t, 0);
13755 tree op1 = TREE_OPERAND (t, 1);
13757 if (TREE_CODE (op1) == INTEGER_CST
13758 && TREE_CODE (op0) == CONSTRUCTOR
13759 && ! type_contains_placeholder_p (TREE_TYPE (op0)))
13761 tree val = get_array_ctor_element_at_index (op0,
13762 wi::to_offset (op1));
13763 if (val)
13764 return val;
13767 return t;
13770 /* Return a VECTOR_CST if possible. */
13771 case CONSTRUCTOR:
13773 tree type = TREE_TYPE (t);
13774 if (TREE_CODE (type) != VECTOR_TYPE)
13775 return t;
13777 unsigned i;
13778 tree val;
13779 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (t), i, val)
13780 if (! CONSTANT_CLASS_P (val))
13781 return t;
13783 return build_vector_from_ctor (type, CONSTRUCTOR_ELTS (t));
13786 case CONST_DECL:
13787 return fold (DECL_INITIAL (t));
13789 default:
13790 return t;
13791 } /* switch (code) */
13794 #ifdef ENABLE_FOLD_CHECKING
13795 #undef fold
13797 static void fold_checksum_tree (const_tree, struct md5_ctx *,
13798 hash_table<nofree_ptr_hash<const tree_node> > *);
13799 static void fold_check_failed (const_tree, const_tree);
13800 void print_fold_checksum (const_tree);
13802 /* When --enable-checking=fold, compute a digest of expr before
13803 and after actual fold call to see if fold did not accidentally
13804 change original expr. */
13806 tree
13807 fold (tree expr)
13809 tree ret;
13810 struct md5_ctx ctx;
13811 unsigned char checksum_before[16], checksum_after[16];
13812 hash_table<nofree_ptr_hash<const tree_node> > ht (32);
13814 md5_init_ctx (&ctx);
13815 fold_checksum_tree (expr, &ctx, &ht);
13816 md5_finish_ctx (&ctx, checksum_before);
13817 ht.empty ();
13819 ret = fold_1 (expr);
13821 md5_init_ctx (&ctx);
13822 fold_checksum_tree (expr, &ctx, &ht);
13823 md5_finish_ctx (&ctx, checksum_after);
13825 if (memcmp (checksum_before, checksum_after, 16))
13826 fold_check_failed (expr, ret);
13828 return ret;
13831 void
13832 print_fold_checksum (const_tree expr)
13834 struct md5_ctx ctx;
13835 unsigned char checksum[16], cnt;
13836 hash_table<nofree_ptr_hash<const tree_node> > ht (32);
13838 md5_init_ctx (&ctx);
13839 fold_checksum_tree (expr, &ctx, &ht);
13840 md5_finish_ctx (&ctx, checksum);
13841 for (cnt = 0; cnt < 16; ++cnt)
13842 fprintf (stderr, "%02x", checksum[cnt]);
13843 putc ('\n', stderr);
13846 static void
13847 fold_check_failed (const_tree expr ATTRIBUTE_UNUSED, const_tree ret ATTRIBUTE_UNUSED)
13849 internal_error ("fold check: original tree changed by fold");
13852 static void
13853 fold_checksum_tree (const_tree expr, struct md5_ctx *ctx,
13854 hash_table<nofree_ptr_hash <const tree_node> > *ht)
13856 const tree_node **slot;
13857 enum tree_code code;
13858 union tree_node *buf;
13859 int i, len;
13861 recursive_label:
13862 if (expr == NULL)
13863 return;
13864 slot = ht->find_slot (expr, INSERT);
13865 if (*slot != NULL)
13866 return;
13867 *slot = expr;
13868 code = TREE_CODE (expr);
13869 if (TREE_CODE_CLASS (code) == tcc_declaration
13870 && HAS_DECL_ASSEMBLER_NAME_P (expr))
13872 /* Allow DECL_ASSEMBLER_NAME and symtab_node to be modified. */
13873 size_t sz = tree_size (expr);
13874 buf = XALLOCAVAR (union tree_node, sz);
13875 memcpy ((char *) buf, expr, sz);
13876 SET_DECL_ASSEMBLER_NAME ((tree) buf, NULL);
13877 buf->decl_with_vis.symtab_node = NULL;
13878 buf->base.nowarning_flag = 0;
13879 expr = (tree) buf;
13881 else if (TREE_CODE_CLASS (code) == tcc_type
13882 && (TYPE_POINTER_TO (expr)
13883 || TYPE_REFERENCE_TO (expr)
13884 || TYPE_CACHED_VALUES_P (expr)
13885 || TYPE_CONTAINS_PLACEHOLDER_INTERNAL (expr)
13886 || TYPE_NEXT_VARIANT (expr)
13887 || TYPE_ALIAS_SET_KNOWN_P (expr)))
13889 /* Allow these fields to be modified. */
13890 tree tmp;
13891 size_t sz = tree_size (expr);
13892 buf = XALLOCAVAR (union tree_node, sz);
13893 memcpy ((char *) buf, expr, sz);
13894 expr = tmp = (tree) buf;
13895 TYPE_CONTAINS_PLACEHOLDER_INTERNAL (tmp) = 0;
13896 TYPE_POINTER_TO (tmp) = NULL;
13897 TYPE_REFERENCE_TO (tmp) = NULL;
13898 TYPE_NEXT_VARIANT (tmp) = NULL;
13899 TYPE_ALIAS_SET (tmp) = -1;
13900 if (TYPE_CACHED_VALUES_P (tmp))
13902 TYPE_CACHED_VALUES_P (tmp) = 0;
13903 TYPE_CACHED_VALUES (tmp) = NULL;
13906 else if (warning_suppressed_p (expr) && (DECL_P (expr) || EXPR_P (expr)))
13908 /* Allow the no-warning bit to be set. Perhaps we shouldn't allow
13909 that and change builtins.cc etc. instead - see PR89543. */
13910 size_t sz = tree_size (expr);
13911 buf = XALLOCAVAR (union tree_node, sz);
13912 memcpy ((char *) buf, expr, sz);
13913 buf->base.nowarning_flag = 0;
13914 expr = (tree) buf;
13916 md5_process_bytes (expr, tree_size (expr), ctx);
13917 if (CODE_CONTAINS_STRUCT (code, TS_TYPED))
13918 fold_checksum_tree (TREE_TYPE (expr), ctx, ht);
13919 if (TREE_CODE_CLASS (code) != tcc_type
13920 && TREE_CODE_CLASS (code) != tcc_declaration
13921 && code != TREE_LIST
13922 && code != SSA_NAME
13923 && CODE_CONTAINS_STRUCT (code, TS_COMMON))
13924 fold_checksum_tree (TREE_CHAIN (expr), ctx, ht);
13925 switch (TREE_CODE_CLASS (code))
13927 case tcc_constant:
13928 switch (code)
13930 case STRING_CST:
13931 md5_process_bytes (TREE_STRING_POINTER (expr),
13932 TREE_STRING_LENGTH (expr), ctx);
13933 break;
13934 case COMPLEX_CST:
13935 fold_checksum_tree (TREE_REALPART (expr), ctx, ht);
13936 fold_checksum_tree (TREE_IMAGPART (expr), ctx, ht);
13937 break;
13938 case VECTOR_CST:
13939 len = vector_cst_encoded_nelts (expr);
13940 for (i = 0; i < len; ++i)
13941 fold_checksum_tree (VECTOR_CST_ENCODED_ELT (expr, i), ctx, ht);
13942 break;
13943 default:
13944 break;
13946 break;
13947 case tcc_exceptional:
13948 switch (code)
13950 case TREE_LIST:
13951 fold_checksum_tree (TREE_PURPOSE (expr), ctx, ht);
13952 fold_checksum_tree (TREE_VALUE (expr), ctx, ht);
13953 expr = TREE_CHAIN (expr);
13954 goto recursive_label;
13955 break;
13956 case TREE_VEC:
13957 for (i = 0; i < TREE_VEC_LENGTH (expr); ++i)
13958 fold_checksum_tree (TREE_VEC_ELT (expr, i), ctx, ht);
13959 break;
13960 default:
13961 break;
13963 break;
13964 case tcc_expression:
13965 case tcc_reference:
13966 case tcc_comparison:
13967 case tcc_unary:
13968 case tcc_binary:
13969 case tcc_statement:
13970 case tcc_vl_exp:
13971 len = TREE_OPERAND_LENGTH (expr);
13972 for (i = 0; i < len; ++i)
13973 fold_checksum_tree (TREE_OPERAND (expr, i), ctx, ht);
13974 break;
13975 case tcc_declaration:
13976 fold_checksum_tree (DECL_NAME (expr), ctx, ht);
13977 fold_checksum_tree (DECL_CONTEXT (expr), ctx, ht);
13978 if (CODE_CONTAINS_STRUCT (TREE_CODE (expr), TS_DECL_COMMON))
13980 fold_checksum_tree (DECL_SIZE (expr), ctx, ht);
13981 fold_checksum_tree (DECL_SIZE_UNIT (expr), ctx, ht);
13982 fold_checksum_tree (DECL_INITIAL (expr), ctx, ht);
13983 fold_checksum_tree (DECL_ABSTRACT_ORIGIN (expr), ctx, ht);
13984 fold_checksum_tree (DECL_ATTRIBUTES (expr), ctx, ht);
13987 if (CODE_CONTAINS_STRUCT (TREE_CODE (expr), TS_DECL_NON_COMMON))
13989 if (TREE_CODE (expr) == FUNCTION_DECL)
13991 fold_checksum_tree (DECL_VINDEX (expr), ctx, ht);
13992 fold_checksum_tree (DECL_ARGUMENTS (expr), ctx, ht);
13994 fold_checksum_tree (DECL_RESULT_FLD (expr), ctx, ht);
13996 break;
13997 case tcc_type:
13998 if (TREE_CODE (expr) == ENUMERAL_TYPE)
13999 fold_checksum_tree (TYPE_VALUES (expr), ctx, ht);
14000 fold_checksum_tree (TYPE_SIZE (expr), ctx, ht);
14001 fold_checksum_tree (TYPE_SIZE_UNIT (expr), ctx, ht);
14002 fold_checksum_tree (TYPE_ATTRIBUTES (expr), ctx, ht);
14003 fold_checksum_tree (TYPE_NAME (expr), ctx, ht);
14004 if (INTEGRAL_TYPE_P (expr)
14005 || SCALAR_FLOAT_TYPE_P (expr))
14007 fold_checksum_tree (TYPE_MIN_VALUE (expr), ctx, ht);
14008 fold_checksum_tree (TYPE_MAX_VALUE (expr), ctx, ht);
14010 fold_checksum_tree (TYPE_MAIN_VARIANT (expr), ctx, ht);
14011 if (RECORD_OR_UNION_TYPE_P (expr))
14012 fold_checksum_tree (TYPE_BINFO (expr), ctx, ht);
14013 fold_checksum_tree (TYPE_CONTEXT (expr), ctx, ht);
14014 break;
14015 default:
14016 break;
14020 /* Helper function for outputting the checksum of a tree T. When
14021 debugging with gdb, you can "define mynext" to be "next" followed
14022 by "call debug_fold_checksum (op0)", then just trace down till the
14023 outputs differ. */
14025 DEBUG_FUNCTION void
14026 debug_fold_checksum (const_tree t)
14028 int i;
14029 unsigned char checksum[16];
14030 struct md5_ctx ctx;
14031 hash_table<nofree_ptr_hash<const tree_node> > ht (32);
14033 md5_init_ctx (&ctx);
14034 fold_checksum_tree (t, &ctx, &ht);
14035 md5_finish_ctx (&ctx, checksum);
14036 ht.empty ();
14038 for (i = 0; i < 16; i++)
14039 fprintf (stderr, "%d ", checksum[i]);
14041 fprintf (stderr, "\n");
14044 #endif
14046 /* Fold a unary tree expression with code CODE of type TYPE with an
14047 operand OP0. LOC is the location of the resulting expression.
14048 Return a folded expression if successful. Otherwise, return a tree
14049 expression with code CODE of type TYPE with an operand OP0. */
14051 tree
14052 fold_build1_loc (location_t loc,
14053 enum tree_code code, tree type, tree op0 MEM_STAT_DECL)
14055 tree tem;
14056 #ifdef ENABLE_FOLD_CHECKING
14057 unsigned char checksum_before[16], checksum_after[16];
14058 struct md5_ctx ctx;
14059 hash_table<nofree_ptr_hash<const tree_node> > ht (32);
14061 md5_init_ctx (&ctx);
14062 fold_checksum_tree (op0, &ctx, &ht);
14063 md5_finish_ctx (&ctx, checksum_before);
14064 ht.empty ();
14065 #endif
14067 tem = fold_unary_loc (loc, code, type, op0);
14068 if (!tem)
14069 tem = build1_loc (loc, code, type, op0 PASS_MEM_STAT);
14071 #ifdef ENABLE_FOLD_CHECKING
14072 md5_init_ctx (&ctx);
14073 fold_checksum_tree (op0, &ctx, &ht);
14074 md5_finish_ctx (&ctx, checksum_after);
14076 if (memcmp (checksum_before, checksum_after, 16))
14077 fold_check_failed (op0, tem);
14078 #endif
14079 return tem;
14082 /* Fold a binary tree expression with code CODE of type TYPE with
14083 operands OP0 and OP1. LOC is the location of the resulting
14084 expression. Return a folded expression if successful. Otherwise,
14085 return a tree expression with code CODE of type TYPE with operands
14086 OP0 and OP1. */
14088 tree
14089 fold_build2_loc (location_t loc,
14090 enum tree_code code, tree type, tree op0, tree op1
14091 MEM_STAT_DECL)
14093 tree tem;
14094 #ifdef ENABLE_FOLD_CHECKING
14095 unsigned char checksum_before_op0[16],
14096 checksum_before_op1[16],
14097 checksum_after_op0[16],
14098 checksum_after_op1[16];
14099 struct md5_ctx ctx;
14100 hash_table<nofree_ptr_hash<const tree_node> > ht (32);
14102 md5_init_ctx (&ctx);
14103 fold_checksum_tree (op0, &ctx, &ht);
14104 md5_finish_ctx (&ctx, checksum_before_op0);
14105 ht.empty ();
14107 md5_init_ctx (&ctx);
14108 fold_checksum_tree (op1, &ctx, &ht);
14109 md5_finish_ctx (&ctx, checksum_before_op1);
14110 ht.empty ();
14111 #endif
14113 tem = fold_binary_loc (loc, code, type, op0, op1);
14114 if (!tem)
14115 tem = build2_loc (loc, code, type, op0, op1 PASS_MEM_STAT);
14117 #ifdef ENABLE_FOLD_CHECKING
14118 md5_init_ctx (&ctx);
14119 fold_checksum_tree (op0, &ctx, &ht);
14120 md5_finish_ctx (&ctx, checksum_after_op0);
14121 ht.empty ();
14123 if (memcmp (checksum_before_op0, checksum_after_op0, 16))
14124 fold_check_failed (op0, tem);
14126 md5_init_ctx (&ctx);
14127 fold_checksum_tree (op1, &ctx, &ht);
14128 md5_finish_ctx (&ctx, checksum_after_op1);
14130 if (memcmp (checksum_before_op1, checksum_after_op1, 16))
14131 fold_check_failed (op1, tem);
14132 #endif
14133 return tem;
14136 /* Fold a ternary tree expression with code CODE of type TYPE with
14137 operands OP0, OP1, and OP2. Return a folded expression if
14138 successful. Otherwise, return a tree expression with code CODE of
14139 type TYPE with operands OP0, OP1, and OP2. */
14141 tree
14142 fold_build3_loc (location_t loc, enum tree_code code, tree type,
14143 tree op0, tree op1, tree op2 MEM_STAT_DECL)
14145 tree tem;
14146 #ifdef ENABLE_FOLD_CHECKING
14147 unsigned char checksum_before_op0[16],
14148 checksum_before_op1[16],
14149 checksum_before_op2[16],
14150 checksum_after_op0[16],
14151 checksum_after_op1[16],
14152 checksum_after_op2[16];
14153 struct md5_ctx ctx;
14154 hash_table<nofree_ptr_hash<const tree_node> > ht (32);
14156 md5_init_ctx (&ctx);
14157 fold_checksum_tree (op0, &ctx, &ht);
14158 md5_finish_ctx (&ctx, checksum_before_op0);
14159 ht.empty ();
14161 md5_init_ctx (&ctx);
14162 fold_checksum_tree (op1, &ctx, &ht);
14163 md5_finish_ctx (&ctx, checksum_before_op1);
14164 ht.empty ();
14166 md5_init_ctx (&ctx);
14167 fold_checksum_tree (op2, &ctx, &ht);
14168 md5_finish_ctx (&ctx, checksum_before_op2);
14169 ht.empty ();
14170 #endif
14172 gcc_assert (TREE_CODE_CLASS (code) != tcc_vl_exp);
14173 tem = fold_ternary_loc (loc, code, type, op0, op1, op2);
14174 if (!tem)
14175 tem = build3_loc (loc, code, type, op0, op1, op2 PASS_MEM_STAT);
14177 #ifdef ENABLE_FOLD_CHECKING
14178 md5_init_ctx (&ctx);
14179 fold_checksum_tree (op0, &ctx, &ht);
14180 md5_finish_ctx (&ctx, checksum_after_op0);
14181 ht.empty ();
14183 if (memcmp (checksum_before_op0, checksum_after_op0, 16))
14184 fold_check_failed (op0, tem);
14186 md5_init_ctx (&ctx);
14187 fold_checksum_tree (op1, &ctx, &ht);
14188 md5_finish_ctx (&ctx, checksum_after_op1);
14189 ht.empty ();
14191 if (memcmp (checksum_before_op1, checksum_after_op1, 16))
14192 fold_check_failed (op1, tem);
14194 md5_init_ctx (&ctx);
14195 fold_checksum_tree (op2, &ctx, &ht);
14196 md5_finish_ctx (&ctx, checksum_after_op2);
14198 if (memcmp (checksum_before_op2, checksum_after_op2, 16))
14199 fold_check_failed (op2, tem);
14200 #endif
14201 return tem;
14204 /* Fold a CALL_EXPR expression of type TYPE with operands FN and NARGS
14205 arguments in ARGARRAY, and a null static chain.
14206 Return a folded expression if successful. Otherwise, return a CALL_EXPR
14207 of type TYPE from the given operands as constructed by build_call_array. */
14209 tree
14210 fold_build_call_array_loc (location_t loc, tree type, tree fn,
14211 int nargs, tree *argarray)
14213 tree tem;
14214 #ifdef ENABLE_FOLD_CHECKING
14215 unsigned char checksum_before_fn[16],
14216 checksum_before_arglist[16],
14217 checksum_after_fn[16],
14218 checksum_after_arglist[16];
14219 struct md5_ctx ctx;
14220 hash_table<nofree_ptr_hash<const tree_node> > ht (32);
14221 int i;
14223 md5_init_ctx (&ctx);
14224 fold_checksum_tree (fn, &ctx, &ht);
14225 md5_finish_ctx (&ctx, checksum_before_fn);
14226 ht.empty ();
14228 md5_init_ctx (&ctx);
14229 for (i = 0; i < nargs; i++)
14230 fold_checksum_tree (argarray[i], &ctx, &ht);
14231 md5_finish_ctx (&ctx, checksum_before_arglist);
14232 ht.empty ();
14233 #endif
14235 tem = fold_builtin_call_array (loc, type, fn, nargs, argarray);
14236 if (!tem)
14237 tem = build_call_array_loc (loc, type, fn, nargs, argarray);
14239 #ifdef ENABLE_FOLD_CHECKING
14240 md5_init_ctx (&ctx);
14241 fold_checksum_tree (fn, &ctx, &ht);
14242 md5_finish_ctx (&ctx, checksum_after_fn);
14243 ht.empty ();
14245 if (memcmp (checksum_before_fn, checksum_after_fn, 16))
14246 fold_check_failed (fn, tem);
14248 md5_init_ctx (&ctx);
14249 for (i = 0; i < nargs; i++)
14250 fold_checksum_tree (argarray[i], &ctx, &ht);
14251 md5_finish_ctx (&ctx, checksum_after_arglist);
14253 if (memcmp (checksum_before_arglist, checksum_after_arglist, 16))
14254 fold_check_failed (NULL_TREE, tem);
14255 #endif
14256 return tem;
14259 /* Perform constant folding and related simplification of initializer
14260 expression EXPR. These behave identically to "fold_buildN" but ignore
14261 potential run-time traps and exceptions that fold must preserve. */
14263 #define START_FOLD_INIT \
14264 int saved_signaling_nans = flag_signaling_nans;\
14265 int saved_trapping_math = flag_trapping_math;\
14266 int saved_rounding_math = flag_rounding_math;\
14267 int saved_trapv = flag_trapv;\
14268 int saved_folding_initializer = folding_initializer;\
14269 flag_signaling_nans = 0;\
14270 flag_trapping_math = 0;\
14271 flag_rounding_math = 0;\
14272 flag_trapv = 0;\
14273 folding_initializer = 1;
14275 #define END_FOLD_INIT \
14276 flag_signaling_nans = saved_signaling_nans;\
14277 flag_trapping_math = saved_trapping_math;\
14278 flag_rounding_math = saved_rounding_math;\
14279 flag_trapv = saved_trapv;\
14280 folding_initializer = saved_folding_initializer;
14282 tree
14283 fold_init (tree expr)
14285 tree result;
14286 START_FOLD_INIT;
14288 result = fold (expr);
14290 END_FOLD_INIT;
14291 return result;
14294 tree
14295 fold_build1_initializer_loc (location_t loc, enum tree_code code,
14296 tree type, tree op)
14298 tree result;
14299 START_FOLD_INIT;
14301 result = fold_build1_loc (loc, code, type, op);
14303 END_FOLD_INIT;
14304 return result;
14307 tree
14308 fold_build2_initializer_loc (location_t loc, enum tree_code code,
14309 tree type, tree op0, tree op1)
14311 tree result;
14312 START_FOLD_INIT;
14314 result = fold_build2_loc (loc, code, type, op0, op1);
14316 END_FOLD_INIT;
14317 return result;
14320 tree
14321 fold_build_call_array_initializer_loc (location_t loc, tree type, tree fn,
14322 int nargs, tree *argarray)
14324 tree result;
14325 START_FOLD_INIT;
14327 result = fold_build_call_array_loc (loc, type, fn, nargs, argarray);
14329 END_FOLD_INIT;
14330 return result;
14333 tree
14334 fold_binary_initializer_loc (location_t loc, tree_code code, tree type,
14335 tree lhs, tree rhs)
14337 tree result;
14338 START_FOLD_INIT;
14340 result = fold_binary_loc (loc, code, type, lhs, rhs);
14342 END_FOLD_INIT;
14343 return result;
14346 #undef START_FOLD_INIT
14347 #undef END_FOLD_INIT
14349 /* Determine if first argument is a multiple of second argument. Return
14350 false if it is not, or we cannot easily determined it to be.
14352 An example of the sort of thing we care about (at this point; this routine
14353 could surely be made more general, and expanded to do what the *_DIV_EXPR's
14354 fold cases do now) is discovering that
14356 SAVE_EXPR (I) * SAVE_EXPR (J * 8)
14358 is a multiple of
14360 SAVE_EXPR (J * 8)
14362 when we know that the two SAVE_EXPR (J * 8) nodes are the same node.
14364 This code also handles discovering that
14366 SAVE_EXPR (I) * SAVE_EXPR (J * 8)
14368 is a multiple of 8 so we don't have to worry about dealing with a
14369 possible remainder.
14371 Note that we *look* inside a SAVE_EXPR only to determine how it was
14372 calculated; it is not safe for fold to do much of anything else with the
14373 internals of a SAVE_EXPR, since it cannot know when it will be evaluated
14374 at run time. For example, the latter example above *cannot* be implemented
14375 as SAVE_EXPR (I) * J or any variant thereof, since the value of J at
14376 evaluation time of the original SAVE_EXPR is not necessarily the same at
14377 the time the new expression is evaluated. The only optimization of this
14378 sort that would be valid is changing
14380 SAVE_EXPR (I) * SAVE_EXPR (SAVE_EXPR (J) * 8)
14382 divided by 8 to
14384 SAVE_EXPR (I) * SAVE_EXPR (J)
14386 (where the same SAVE_EXPR (J) is used in the original and the
14387 transformed version).
14389 NOWRAP specifies whether all outer operations in TYPE should
14390 be considered not wrapping. Any type conversion within TOP acts
14391 as a barrier and we will fall back to NOWRAP being false.
14392 NOWRAP is mostly used to treat expressions in TYPE_SIZE and friends
14393 as not wrapping even though they are generally using unsigned arithmetic. */
14395 bool
14396 multiple_of_p (tree type, const_tree top, const_tree bottom, bool nowrap)
14398 gimple *stmt;
14399 tree op1, op2;
14401 if (operand_equal_p (top, bottom, 0))
14402 return true;
14404 if (TREE_CODE (type) != INTEGER_TYPE)
14405 return false;
14407 switch (TREE_CODE (top))
14409 case BIT_AND_EXPR:
14410 /* Bitwise and provides a power of two multiple. If the mask is
14411 a multiple of BOTTOM then TOP is a multiple of BOTTOM. */
14412 if (!integer_pow2p (bottom))
14413 return false;
14414 return (multiple_of_p (type, TREE_OPERAND (top, 1), bottom, nowrap)
14415 || multiple_of_p (type, TREE_OPERAND (top, 0), bottom, nowrap));
14417 case MULT_EXPR:
14418 /* If the multiplication can wrap we cannot recurse further unless
14419 the bottom is a power of two which is where wrapping does not
14420 matter. */
14421 if (!nowrap
14422 && !TYPE_OVERFLOW_UNDEFINED (type)
14423 && !integer_pow2p (bottom))
14424 return false;
14425 if (TREE_CODE (bottom) == INTEGER_CST)
14427 op1 = TREE_OPERAND (top, 0);
14428 op2 = TREE_OPERAND (top, 1);
14429 if (TREE_CODE (op1) == INTEGER_CST)
14430 std::swap (op1, op2);
14431 if (TREE_CODE (op2) == INTEGER_CST)
14433 if (multiple_of_p (type, op2, bottom, nowrap))
14434 return true;
14435 /* Handle multiple_of_p ((x * 2 + 2) * 4, 8). */
14436 if (multiple_of_p (type, bottom, op2, nowrap))
14438 widest_int w = wi::sdiv_trunc (wi::to_widest (bottom),
14439 wi::to_widest (op2));
14440 if (wi::fits_to_tree_p (w, TREE_TYPE (bottom)))
14442 op2 = wide_int_to_tree (TREE_TYPE (bottom), w);
14443 return multiple_of_p (type, op1, op2, nowrap);
14446 return multiple_of_p (type, op1, bottom, nowrap);
14449 return (multiple_of_p (type, TREE_OPERAND (top, 1), bottom, nowrap)
14450 || multiple_of_p (type, TREE_OPERAND (top, 0), bottom, nowrap));
14452 case LSHIFT_EXPR:
14453 /* Handle X << CST as X * (1 << CST) and only process the constant. */
14454 if (TREE_CODE (TREE_OPERAND (top, 1)) == INTEGER_CST)
14456 op1 = TREE_OPERAND (top, 1);
14457 if (wi::to_widest (op1) < TYPE_PRECISION (type))
14459 wide_int mul_op
14460 = wi::one (TYPE_PRECISION (type)) << wi::to_wide (op1);
14461 return multiple_of_p (type,
14462 wide_int_to_tree (type, mul_op), bottom,
14463 nowrap);
14466 return false;
14468 case MINUS_EXPR:
14469 case PLUS_EXPR:
14470 /* If the addition or subtraction can wrap we cannot recurse further
14471 unless bottom is a power of two which is where wrapping does not
14472 matter. */
14473 if (!nowrap
14474 && !TYPE_OVERFLOW_UNDEFINED (type)
14475 && !integer_pow2p (bottom))
14476 return false;
14478 /* Handle cases like op0 + 0xfffffffd as op0 - 3 if the expression has
14479 unsigned type. For example, (X / 3) + 0xfffffffd is multiple of 3,
14480 but 0xfffffffd is not. */
14481 op1 = TREE_OPERAND (top, 1);
14482 if (TREE_CODE (top) == PLUS_EXPR
14483 && nowrap
14484 && TYPE_UNSIGNED (type)
14485 && TREE_CODE (op1) == INTEGER_CST && tree_int_cst_sign_bit (op1))
14486 op1 = fold_build1 (NEGATE_EXPR, type, op1);
14488 /* It is impossible to prove if op0 +- op1 is multiple of bottom
14489 precisely, so be conservative here checking if both op0 and op1
14490 are multiple of bottom. Note we check the second operand first
14491 since it's usually simpler. */
14492 return (multiple_of_p (type, op1, bottom, nowrap)
14493 && multiple_of_p (type, TREE_OPERAND (top, 0), bottom, nowrap));
14495 CASE_CONVERT:
14496 /* Can't handle conversions from non-integral or wider integral type. */
14497 if ((TREE_CODE (TREE_TYPE (TREE_OPERAND (top, 0))) != INTEGER_TYPE)
14498 || (TYPE_PRECISION (type)
14499 < TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (top, 0)))))
14500 return false;
14501 /* NOWRAP only extends to operations in the outermost type so
14502 make sure to strip it off here. */
14503 return multiple_of_p (TREE_TYPE (TREE_OPERAND (top, 0)),
14504 TREE_OPERAND (top, 0), bottom, false);
14506 case SAVE_EXPR:
14507 return multiple_of_p (type, TREE_OPERAND (top, 0), bottom, nowrap);
14509 case COND_EXPR:
14510 return (multiple_of_p (type, TREE_OPERAND (top, 1), bottom, nowrap)
14511 && multiple_of_p (type, TREE_OPERAND (top, 2), bottom, nowrap));
14513 case INTEGER_CST:
14514 if (TREE_CODE (bottom) != INTEGER_CST || integer_zerop (bottom))
14515 return false;
14516 return wi::multiple_of_p (wi::to_widest (top), wi::to_widest (bottom),
14517 SIGNED);
14519 case SSA_NAME:
14520 if (TREE_CODE (bottom) == INTEGER_CST
14521 && (stmt = SSA_NAME_DEF_STMT (top)) != NULL
14522 && gimple_code (stmt) == GIMPLE_ASSIGN)
14524 enum tree_code code = gimple_assign_rhs_code (stmt);
14526 /* Check for special cases to see if top is defined as multiple
14527 of bottom:
14529 top = (X & ~(bottom - 1) ; bottom is power of 2
14533 Y = X % bottom
14534 top = X - Y. */
14535 if (code == BIT_AND_EXPR
14536 && (op2 = gimple_assign_rhs2 (stmt)) != NULL_TREE
14537 && TREE_CODE (op2) == INTEGER_CST
14538 && integer_pow2p (bottom)
14539 && wi::multiple_of_p (wi::to_widest (op2),
14540 wi::to_widest (bottom), SIGNED))
14541 return true;
14543 op1 = gimple_assign_rhs1 (stmt);
14544 if (code == MINUS_EXPR
14545 && (op2 = gimple_assign_rhs2 (stmt)) != NULL_TREE
14546 && TREE_CODE (op2) == SSA_NAME
14547 && (stmt = SSA_NAME_DEF_STMT (op2)) != NULL
14548 && gimple_code (stmt) == GIMPLE_ASSIGN
14549 && (code = gimple_assign_rhs_code (stmt)) == TRUNC_MOD_EXPR
14550 && operand_equal_p (op1, gimple_assign_rhs1 (stmt), 0)
14551 && operand_equal_p (bottom, gimple_assign_rhs2 (stmt), 0))
14552 return true;
14555 /* fall through */
14557 default:
14558 if (POLY_INT_CST_P (top) && poly_int_tree_p (bottom))
14559 return multiple_p (wi::to_poly_widest (top),
14560 wi::to_poly_widest (bottom));
14562 return false;
14566 /* Return true if expression X cannot be (or contain) a NaN or infinity.
14567 This function returns true for integer expressions, and returns
14568 false if uncertain. */
14570 bool
14571 tree_expr_finite_p (const_tree x)
14573 machine_mode mode = element_mode (x);
14574 if (!HONOR_NANS (mode) && !HONOR_INFINITIES (mode))
14575 return true;
14576 switch (TREE_CODE (x))
14578 case REAL_CST:
14579 return real_isfinite (TREE_REAL_CST_PTR (x));
14580 case COMPLEX_CST:
14581 return tree_expr_finite_p (TREE_REALPART (x))
14582 && tree_expr_finite_p (TREE_IMAGPART (x));
14583 case FLOAT_EXPR:
14584 return true;
14585 case ABS_EXPR:
14586 case CONVERT_EXPR:
14587 case NON_LVALUE_EXPR:
14588 case NEGATE_EXPR:
14589 case SAVE_EXPR:
14590 return tree_expr_finite_p (TREE_OPERAND (x, 0));
14591 case MIN_EXPR:
14592 case MAX_EXPR:
14593 return tree_expr_finite_p (TREE_OPERAND (x, 0))
14594 && tree_expr_finite_p (TREE_OPERAND (x, 1));
14595 case COND_EXPR:
14596 return tree_expr_finite_p (TREE_OPERAND (x, 1))
14597 && tree_expr_finite_p (TREE_OPERAND (x, 2));
14598 case CALL_EXPR:
14599 switch (get_call_combined_fn (x))
14601 CASE_CFN_FABS:
14602 CASE_CFN_FABS_FN:
14603 return tree_expr_finite_p (CALL_EXPR_ARG (x, 0));
14604 CASE_CFN_FMAX:
14605 CASE_CFN_FMAX_FN:
14606 CASE_CFN_FMIN:
14607 CASE_CFN_FMIN_FN:
14608 return tree_expr_finite_p (CALL_EXPR_ARG (x, 0))
14609 && tree_expr_finite_p (CALL_EXPR_ARG (x, 1));
14610 default:
14611 return false;
14614 default:
14615 return false;
14619 /* Return true if expression X evaluates to an infinity.
14620 This function returns false for integer expressions. */
14622 bool
14623 tree_expr_infinite_p (const_tree x)
14625 if (!HONOR_INFINITIES (x))
14626 return false;
14627 switch (TREE_CODE (x))
14629 case REAL_CST:
14630 return real_isinf (TREE_REAL_CST_PTR (x));
14631 case ABS_EXPR:
14632 case NEGATE_EXPR:
14633 case NON_LVALUE_EXPR:
14634 case SAVE_EXPR:
14635 return tree_expr_infinite_p (TREE_OPERAND (x, 0));
14636 case COND_EXPR:
14637 return tree_expr_infinite_p (TREE_OPERAND (x, 1))
14638 && tree_expr_infinite_p (TREE_OPERAND (x, 2));
14639 default:
14640 return false;
14644 /* Return true if expression X could evaluate to an infinity.
14645 This function returns false for integer expressions, and returns
14646 true if uncertain. */
14648 bool
14649 tree_expr_maybe_infinite_p (const_tree x)
14651 if (!HONOR_INFINITIES (x))
14652 return false;
14653 switch (TREE_CODE (x))
14655 case REAL_CST:
14656 return real_isinf (TREE_REAL_CST_PTR (x));
14657 case FLOAT_EXPR:
14658 return false;
14659 case ABS_EXPR:
14660 case NEGATE_EXPR:
14661 return tree_expr_maybe_infinite_p (TREE_OPERAND (x, 0));
14662 case COND_EXPR:
14663 return tree_expr_maybe_infinite_p (TREE_OPERAND (x, 1))
14664 || tree_expr_maybe_infinite_p (TREE_OPERAND (x, 2));
14665 default:
14666 return true;
14670 /* Return true if expression X evaluates to a signaling NaN.
14671 This function returns false for integer expressions. */
14673 bool
14674 tree_expr_signaling_nan_p (const_tree x)
14676 if (!HONOR_SNANS (x))
14677 return false;
14678 switch (TREE_CODE (x))
14680 case REAL_CST:
14681 return real_issignaling_nan (TREE_REAL_CST_PTR (x));
14682 case NON_LVALUE_EXPR:
14683 case SAVE_EXPR:
14684 return tree_expr_signaling_nan_p (TREE_OPERAND (x, 0));
14685 case COND_EXPR:
14686 return tree_expr_signaling_nan_p (TREE_OPERAND (x, 1))
14687 && tree_expr_signaling_nan_p (TREE_OPERAND (x, 2));
14688 default:
14689 return false;
14693 /* Return true if expression X could evaluate to a signaling NaN.
14694 This function returns false for integer expressions, and returns
14695 true if uncertain. */
14697 bool
14698 tree_expr_maybe_signaling_nan_p (const_tree x)
14700 if (!HONOR_SNANS (x))
14701 return false;
14702 switch (TREE_CODE (x))
14704 case REAL_CST:
14705 return real_issignaling_nan (TREE_REAL_CST_PTR (x));
14706 case FLOAT_EXPR:
14707 return false;
14708 case ABS_EXPR:
14709 case CONVERT_EXPR:
14710 case NEGATE_EXPR:
14711 case NON_LVALUE_EXPR:
14712 case SAVE_EXPR:
14713 return tree_expr_maybe_signaling_nan_p (TREE_OPERAND (x, 0));
14714 case MIN_EXPR:
14715 case MAX_EXPR:
14716 return tree_expr_maybe_signaling_nan_p (TREE_OPERAND (x, 0))
14717 || tree_expr_maybe_signaling_nan_p (TREE_OPERAND (x, 1));
14718 case COND_EXPR:
14719 return tree_expr_maybe_signaling_nan_p (TREE_OPERAND (x, 1))
14720 || tree_expr_maybe_signaling_nan_p (TREE_OPERAND (x, 2));
14721 case CALL_EXPR:
14722 switch (get_call_combined_fn (x))
14724 CASE_CFN_FABS:
14725 CASE_CFN_FABS_FN:
14726 return tree_expr_maybe_signaling_nan_p (CALL_EXPR_ARG (x, 0));
14727 CASE_CFN_FMAX:
14728 CASE_CFN_FMAX_FN:
14729 CASE_CFN_FMIN:
14730 CASE_CFN_FMIN_FN:
14731 return tree_expr_maybe_signaling_nan_p (CALL_EXPR_ARG (x, 0))
14732 || tree_expr_maybe_signaling_nan_p (CALL_EXPR_ARG (x, 1));
14733 default:
14734 return true;
14736 default:
14737 return true;
14741 /* Return true if expression X evaluates to a NaN.
14742 This function returns false for integer expressions. */
14744 bool
14745 tree_expr_nan_p (const_tree x)
14747 if (!HONOR_NANS (x))
14748 return false;
14749 switch (TREE_CODE (x))
14751 case REAL_CST:
14752 return real_isnan (TREE_REAL_CST_PTR (x));
14753 case NON_LVALUE_EXPR:
14754 case SAVE_EXPR:
14755 return tree_expr_nan_p (TREE_OPERAND (x, 0));
14756 case COND_EXPR:
14757 return tree_expr_nan_p (TREE_OPERAND (x, 1))
14758 && tree_expr_nan_p (TREE_OPERAND (x, 2));
14759 default:
14760 return false;
14764 /* Return true if expression X could evaluate to a NaN.
14765 This function returns false for integer expressions, and returns
14766 true if uncertain. */
14768 bool
14769 tree_expr_maybe_nan_p (const_tree x)
14771 if (!HONOR_NANS (x))
14772 return false;
14773 switch (TREE_CODE (x))
14775 case REAL_CST:
14776 return real_isnan (TREE_REAL_CST_PTR (x));
14777 case FLOAT_EXPR:
14778 return false;
14779 case PLUS_EXPR:
14780 case MINUS_EXPR:
14781 case MULT_EXPR:
14782 return !tree_expr_finite_p (TREE_OPERAND (x, 0))
14783 || !tree_expr_finite_p (TREE_OPERAND (x, 1));
14784 case ABS_EXPR:
14785 case CONVERT_EXPR:
14786 case NEGATE_EXPR:
14787 case NON_LVALUE_EXPR:
14788 case SAVE_EXPR:
14789 return tree_expr_maybe_nan_p (TREE_OPERAND (x, 0));
14790 case MIN_EXPR:
14791 case MAX_EXPR:
14792 return tree_expr_maybe_nan_p (TREE_OPERAND (x, 0))
14793 || tree_expr_maybe_nan_p (TREE_OPERAND (x, 1));
14794 case COND_EXPR:
14795 return tree_expr_maybe_nan_p (TREE_OPERAND (x, 1))
14796 || tree_expr_maybe_nan_p (TREE_OPERAND (x, 2));
14797 case CALL_EXPR:
14798 switch (get_call_combined_fn (x))
14800 CASE_CFN_FABS:
14801 CASE_CFN_FABS_FN:
14802 return tree_expr_maybe_nan_p (CALL_EXPR_ARG (x, 0));
14803 CASE_CFN_FMAX:
14804 CASE_CFN_FMAX_FN:
14805 CASE_CFN_FMIN:
14806 CASE_CFN_FMIN_FN:
14807 return tree_expr_maybe_nan_p (CALL_EXPR_ARG (x, 0))
14808 || tree_expr_maybe_nan_p (CALL_EXPR_ARG (x, 1));
14809 default:
14810 return true;
14812 default:
14813 return true;
14817 /* Return true if expression X could evaluate to -0.0.
14818 This function returns true if uncertain. */
14820 bool
14821 tree_expr_maybe_real_minus_zero_p (const_tree x)
14823 if (!HONOR_SIGNED_ZEROS (x))
14824 return false;
14825 switch (TREE_CODE (x))
14827 case REAL_CST:
14828 return REAL_VALUE_MINUS_ZERO (TREE_REAL_CST (x));
14829 case INTEGER_CST:
14830 case FLOAT_EXPR:
14831 case ABS_EXPR:
14832 return false;
14833 case NON_LVALUE_EXPR:
14834 case SAVE_EXPR:
14835 return tree_expr_maybe_real_minus_zero_p (TREE_OPERAND (x, 0));
14836 case COND_EXPR:
14837 return tree_expr_maybe_real_minus_zero_p (TREE_OPERAND (x, 1))
14838 || tree_expr_maybe_real_minus_zero_p (TREE_OPERAND (x, 2));
14839 case CALL_EXPR:
14840 switch (get_call_combined_fn (x))
14842 CASE_CFN_FABS:
14843 CASE_CFN_FABS_FN:
14844 return false;
14845 default:
14846 break;
14848 default:
14849 break;
14851 /* Ideally !(tree_expr_nonzero_p (X) || tree_expr_nonnegative_p (X))
14852 * but currently those predicates require tree and not const_tree. */
14853 return true;
14856 #define tree_expr_nonnegative_warnv_p(X, Y) \
14857 _Pragma ("GCC error \"Use RECURSE for recursive calls\"") 0
14859 #define RECURSE(X) \
14860 ((tree_expr_nonnegative_warnv_p) (X, strict_overflow_p, depth + 1))
14862 /* Return true if CODE or TYPE is known to be non-negative. */
14864 static bool
14865 tree_simple_nonnegative_warnv_p (enum tree_code code, tree type)
14867 if (!VECTOR_TYPE_P (type)
14868 && (TYPE_PRECISION (type) != 1 || TYPE_UNSIGNED (type))
14869 && truth_value_p (code))
14870 /* Truth values evaluate to 0 or 1, which is nonnegative unless we
14871 have a signed:1 type (where the value is -1 and 0). */
14872 return true;
14873 return false;
14876 /* Return true if (CODE OP0) is known to be non-negative. If the return
14877 value is based on the assumption that signed overflow is undefined,
14878 set *STRICT_OVERFLOW_P to true; otherwise, don't change
14879 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
14881 bool
14882 tree_unary_nonnegative_warnv_p (enum tree_code code, tree type, tree op0,
14883 bool *strict_overflow_p, int depth)
14885 if (TYPE_UNSIGNED (type))
14886 return true;
14888 switch (code)
14890 case ABS_EXPR:
14891 /* We can't return 1 if flag_wrapv is set because
14892 ABS_EXPR<INT_MIN> = INT_MIN. */
14893 if (!ANY_INTEGRAL_TYPE_P (type))
14894 return true;
14895 if (TYPE_OVERFLOW_UNDEFINED (type))
14897 *strict_overflow_p = true;
14898 return true;
14900 break;
14902 case NON_LVALUE_EXPR:
14903 case FLOAT_EXPR:
14904 case FIX_TRUNC_EXPR:
14905 return RECURSE (op0);
14907 CASE_CONVERT:
14909 tree inner_type = TREE_TYPE (op0);
14910 tree outer_type = type;
14912 if (SCALAR_FLOAT_TYPE_P (outer_type))
14914 if (SCALAR_FLOAT_TYPE_P (inner_type))
14915 return RECURSE (op0);
14916 if (INTEGRAL_TYPE_P (inner_type))
14918 if (TYPE_UNSIGNED (inner_type))
14919 return true;
14920 return RECURSE (op0);
14923 else if (INTEGRAL_TYPE_P (outer_type))
14925 if (SCALAR_FLOAT_TYPE_P (inner_type))
14926 return RECURSE (op0);
14927 if (INTEGRAL_TYPE_P (inner_type))
14928 return TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type)
14929 && TYPE_UNSIGNED (inner_type);
14932 break;
14934 default:
14935 return tree_simple_nonnegative_warnv_p (code, type);
14938 /* We don't know sign of `t', so be conservative and return false. */
14939 return false;
14942 /* Return true if (CODE OP0 OP1) is known to be non-negative. If the return
14943 value is based on the assumption that signed overflow is undefined,
14944 set *STRICT_OVERFLOW_P to true; otherwise, don't change
14945 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
14947 bool
14948 tree_binary_nonnegative_warnv_p (enum tree_code code, tree type, tree op0,
14949 tree op1, bool *strict_overflow_p,
14950 int depth)
14952 if (TYPE_UNSIGNED (type))
14953 return true;
14955 switch (code)
14957 case POINTER_PLUS_EXPR:
14958 case PLUS_EXPR:
14959 if (FLOAT_TYPE_P (type))
14960 return RECURSE (op0) && RECURSE (op1);
14962 /* zero_extend(x) + zero_extend(y) is non-negative if x and y are
14963 both unsigned and at least 2 bits shorter than the result. */
14964 if (TREE_CODE (type) == INTEGER_TYPE
14965 && TREE_CODE (op0) == NOP_EXPR
14966 && TREE_CODE (op1) == NOP_EXPR)
14968 tree inner1 = TREE_TYPE (TREE_OPERAND (op0, 0));
14969 tree inner2 = TREE_TYPE (TREE_OPERAND (op1, 0));
14970 if (TREE_CODE (inner1) == INTEGER_TYPE && TYPE_UNSIGNED (inner1)
14971 && TREE_CODE (inner2) == INTEGER_TYPE && TYPE_UNSIGNED (inner2))
14973 unsigned int prec = MAX (TYPE_PRECISION (inner1),
14974 TYPE_PRECISION (inner2)) + 1;
14975 return prec < TYPE_PRECISION (type);
14978 break;
14980 case MULT_EXPR:
14981 if (FLOAT_TYPE_P (type) || TYPE_OVERFLOW_UNDEFINED (type))
14983 /* x * x is always non-negative for floating point x
14984 or without overflow. */
14985 if (operand_equal_p (op0, op1, 0)
14986 || (RECURSE (op0) && RECURSE (op1)))
14988 if (ANY_INTEGRAL_TYPE_P (type)
14989 && TYPE_OVERFLOW_UNDEFINED (type))
14990 *strict_overflow_p = true;
14991 return true;
14995 /* zero_extend(x) * zero_extend(y) is non-negative if x and y are
14996 both unsigned and their total bits is shorter than the result. */
14997 if (TREE_CODE (type) == INTEGER_TYPE
14998 && (TREE_CODE (op0) == NOP_EXPR || TREE_CODE (op0) == INTEGER_CST)
14999 && (TREE_CODE (op1) == NOP_EXPR || TREE_CODE (op1) == INTEGER_CST))
15001 tree inner0 = (TREE_CODE (op0) == NOP_EXPR)
15002 ? TREE_TYPE (TREE_OPERAND (op0, 0))
15003 : TREE_TYPE (op0);
15004 tree inner1 = (TREE_CODE (op1) == NOP_EXPR)
15005 ? TREE_TYPE (TREE_OPERAND (op1, 0))
15006 : TREE_TYPE (op1);
15008 bool unsigned0 = TYPE_UNSIGNED (inner0);
15009 bool unsigned1 = TYPE_UNSIGNED (inner1);
15011 if (TREE_CODE (op0) == INTEGER_CST)
15012 unsigned0 = unsigned0 || tree_int_cst_sgn (op0) >= 0;
15014 if (TREE_CODE (op1) == INTEGER_CST)
15015 unsigned1 = unsigned1 || tree_int_cst_sgn (op1) >= 0;
15017 if (TREE_CODE (inner0) == INTEGER_TYPE && unsigned0
15018 && TREE_CODE (inner1) == INTEGER_TYPE && unsigned1)
15020 unsigned int precision0 = (TREE_CODE (op0) == INTEGER_CST)
15021 ? tree_int_cst_min_precision (op0, UNSIGNED)
15022 : TYPE_PRECISION (inner0);
15024 unsigned int precision1 = (TREE_CODE (op1) == INTEGER_CST)
15025 ? tree_int_cst_min_precision (op1, UNSIGNED)
15026 : TYPE_PRECISION (inner1);
15028 return precision0 + precision1 < TYPE_PRECISION (type);
15031 return false;
15033 case BIT_AND_EXPR:
15034 return RECURSE (op0) || RECURSE (op1);
15036 case MAX_EXPR:
15037 /* Usually RECURSE (op0) || RECURSE (op1) but NaNs complicate
15038 things. */
15039 if (tree_expr_maybe_nan_p (op0) || tree_expr_maybe_nan_p (op1))
15040 return RECURSE (op0) && RECURSE (op1);
15041 return RECURSE (op0) || RECURSE (op1);
15043 case BIT_IOR_EXPR:
15044 case BIT_XOR_EXPR:
15045 case MIN_EXPR:
15046 case RDIV_EXPR:
15047 case TRUNC_DIV_EXPR:
15048 case CEIL_DIV_EXPR:
15049 case FLOOR_DIV_EXPR:
15050 case ROUND_DIV_EXPR:
15051 return RECURSE (op0) && RECURSE (op1);
15053 case TRUNC_MOD_EXPR:
15054 return RECURSE (op0);
15056 case FLOOR_MOD_EXPR:
15057 return RECURSE (op1);
15059 case CEIL_MOD_EXPR:
15060 case ROUND_MOD_EXPR:
15061 default:
15062 return tree_simple_nonnegative_warnv_p (code, type);
15065 /* We don't know sign of `t', so be conservative and return false. */
15066 return false;
15069 /* Return true if T is known to be non-negative. If the return
15070 value is based on the assumption that signed overflow is undefined,
15071 set *STRICT_OVERFLOW_P to true; otherwise, don't change
15072 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
15074 bool
15075 tree_single_nonnegative_warnv_p (tree t, bool *strict_overflow_p, int depth)
15077 if (TYPE_UNSIGNED (TREE_TYPE (t)))
15078 return true;
15080 switch (TREE_CODE (t))
15082 case INTEGER_CST:
15083 return tree_int_cst_sgn (t) >= 0;
15085 case REAL_CST:
15086 return ! REAL_VALUE_NEGATIVE (TREE_REAL_CST (t));
15088 case FIXED_CST:
15089 return ! FIXED_VALUE_NEGATIVE (TREE_FIXED_CST (t));
15091 case COND_EXPR:
15092 return RECURSE (TREE_OPERAND (t, 1)) && RECURSE (TREE_OPERAND (t, 2));
15094 case SSA_NAME:
15095 /* Limit the depth of recursion to avoid quadratic behavior.
15096 This is expected to catch almost all occurrences in practice.
15097 If this code misses important cases that unbounded recursion
15098 would not, passes that need this information could be revised
15099 to provide it through dataflow propagation. */
15100 return (!name_registered_for_update_p (t)
15101 && depth < param_max_ssa_name_query_depth
15102 && gimple_stmt_nonnegative_warnv_p (SSA_NAME_DEF_STMT (t),
15103 strict_overflow_p, depth));
15105 default:
15106 return tree_simple_nonnegative_warnv_p (TREE_CODE (t), TREE_TYPE (t));
15110 /* Return true if T is known to be non-negative. If the return
15111 value is based on the assumption that signed overflow is undefined,
15112 set *STRICT_OVERFLOW_P to true; otherwise, don't change
15113 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
15115 bool
15116 tree_call_nonnegative_warnv_p (tree type, combined_fn fn, tree arg0, tree arg1,
15117 bool *strict_overflow_p, int depth)
15119 switch (fn)
15121 CASE_CFN_ACOS:
15122 CASE_CFN_ACOS_FN:
15123 CASE_CFN_ACOSH:
15124 CASE_CFN_ACOSH_FN:
15125 CASE_CFN_CABS:
15126 CASE_CFN_CABS_FN:
15127 CASE_CFN_COSH:
15128 CASE_CFN_COSH_FN:
15129 CASE_CFN_ERFC:
15130 CASE_CFN_ERFC_FN:
15131 CASE_CFN_EXP:
15132 CASE_CFN_EXP_FN:
15133 CASE_CFN_EXP10:
15134 CASE_CFN_EXP2:
15135 CASE_CFN_EXP2_FN:
15136 CASE_CFN_FABS:
15137 CASE_CFN_FABS_FN:
15138 CASE_CFN_FDIM:
15139 CASE_CFN_FDIM_FN:
15140 CASE_CFN_HYPOT:
15141 CASE_CFN_HYPOT_FN:
15142 CASE_CFN_POW10:
15143 CASE_CFN_FFS:
15144 CASE_CFN_PARITY:
15145 CASE_CFN_POPCOUNT:
15146 CASE_CFN_CLZ:
15147 CASE_CFN_CLRSB:
15148 case CFN_BUILT_IN_BSWAP16:
15149 case CFN_BUILT_IN_BSWAP32:
15150 case CFN_BUILT_IN_BSWAP64:
15151 case CFN_BUILT_IN_BSWAP128:
15152 /* Always true. */
15153 return true;
15155 CASE_CFN_SQRT:
15156 CASE_CFN_SQRT_FN:
15157 /* sqrt(-0.0) is -0.0. */
15158 if (!HONOR_SIGNED_ZEROS (type))
15159 return true;
15160 return RECURSE (arg0);
15162 CASE_CFN_ASINH:
15163 CASE_CFN_ASINH_FN:
15164 CASE_CFN_ATAN:
15165 CASE_CFN_ATAN_FN:
15166 CASE_CFN_ATANH:
15167 CASE_CFN_ATANH_FN:
15168 CASE_CFN_CBRT:
15169 CASE_CFN_CBRT_FN:
15170 CASE_CFN_CEIL:
15171 CASE_CFN_CEIL_FN:
15172 CASE_CFN_ERF:
15173 CASE_CFN_ERF_FN:
15174 CASE_CFN_EXPM1:
15175 CASE_CFN_EXPM1_FN:
15176 CASE_CFN_FLOOR:
15177 CASE_CFN_FLOOR_FN:
15178 CASE_CFN_FMOD:
15179 CASE_CFN_FMOD_FN:
15180 CASE_CFN_FREXP:
15181 CASE_CFN_FREXP_FN:
15182 CASE_CFN_ICEIL:
15183 CASE_CFN_IFLOOR:
15184 CASE_CFN_IRINT:
15185 CASE_CFN_IROUND:
15186 CASE_CFN_LCEIL:
15187 CASE_CFN_LDEXP:
15188 CASE_CFN_LFLOOR:
15189 CASE_CFN_LLCEIL:
15190 CASE_CFN_LLFLOOR:
15191 CASE_CFN_LLRINT:
15192 CASE_CFN_LLRINT_FN:
15193 CASE_CFN_LLROUND:
15194 CASE_CFN_LLROUND_FN:
15195 CASE_CFN_LRINT:
15196 CASE_CFN_LRINT_FN:
15197 CASE_CFN_LROUND:
15198 CASE_CFN_LROUND_FN:
15199 CASE_CFN_MODF:
15200 CASE_CFN_MODF_FN:
15201 CASE_CFN_NEARBYINT:
15202 CASE_CFN_NEARBYINT_FN:
15203 CASE_CFN_RINT:
15204 CASE_CFN_RINT_FN:
15205 CASE_CFN_ROUND:
15206 CASE_CFN_ROUND_FN:
15207 CASE_CFN_ROUNDEVEN:
15208 CASE_CFN_ROUNDEVEN_FN:
15209 CASE_CFN_SCALB:
15210 CASE_CFN_SCALBLN:
15211 CASE_CFN_SCALBLN_FN:
15212 CASE_CFN_SCALBN:
15213 CASE_CFN_SCALBN_FN:
15214 CASE_CFN_SIGNBIT:
15215 CASE_CFN_SIGNIFICAND:
15216 CASE_CFN_SINH:
15217 CASE_CFN_SINH_FN:
15218 CASE_CFN_TANH:
15219 CASE_CFN_TANH_FN:
15220 CASE_CFN_TRUNC:
15221 CASE_CFN_TRUNC_FN:
15222 /* True if the 1st argument is nonnegative. */
15223 return RECURSE (arg0);
15225 CASE_CFN_FMAX:
15226 CASE_CFN_FMAX_FN:
15227 /* Usually RECURSE (arg0) || RECURSE (arg1) but NaNs complicate
15228 things. In the presence of sNaNs, we're only guaranteed to be
15229 non-negative if both operands are non-negative. In the presence
15230 of qNaNs, we're non-negative if either operand is non-negative
15231 and can't be a qNaN, or if both operands are non-negative. */
15232 if (tree_expr_maybe_signaling_nan_p (arg0) ||
15233 tree_expr_maybe_signaling_nan_p (arg1))
15234 return RECURSE (arg0) && RECURSE (arg1);
15235 return RECURSE (arg0) ? (!tree_expr_maybe_nan_p (arg0)
15236 || RECURSE (arg1))
15237 : (RECURSE (arg1)
15238 && !tree_expr_maybe_nan_p (arg1));
15240 CASE_CFN_FMIN:
15241 CASE_CFN_FMIN_FN:
15242 /* True if the 1st AND 2nd arguments are nonnegative. */
15243 return RECURSE (arg0) && RECURSE (arg1);
15245 CASE_CFN_COPYSIGN:
15246 CASE_CFN_COPYSIGN_FN:
15247 /* True if the 2nd argument is nonnegative. */
15248 return RECURSE (arg1);
15250 CASE_CFN_POWI:
15251 /* True if the 1st argument is nonnegative or the second
15252 argument is an even integer. */
15253 if (TREE_CODE (arg1) == INTEGER_CST
15254 && (TREE_INT_CST_LOW (arg1) & 1) == 0)
15255 return true;
15256 return RECURSE (arg0);
15258 CASE_CFN_POW:
15259 CASE_CFN_POW_FN:
15260 /* True if the 1st argument is nonnegative or the second
15261 argument is an even integer valued real. */
15262 if (TREE_CODE (arg1) == REAL_CST)
15264 REAL_VALUE_TYPE c;
15265 HOST_WIDE_INT n;
15267 c = TREE_REAL_CST (arg1);
15268 n = real_to_integer (&c);
15269 if ((n & 1) == 0)
15271 REAL_VALUE_TYPE cint;
15272 real_from_integer (&cint, VOIDmode, n, SIGNED);
15273 if (real_identical (&c, &cint))
15274 return true;
15277 return RECURSE (arg0);
15279 default:
15280 break;
15282 return tree_simple_nonnegative_warnv_p (CALL_EXPR, type);
15285 /* Return true if T is known to be non-negative. If the return
15286 value is based on the assumption that signed overflow is undefined,
15287 set *STRICT_OVERFLOW_P to true; otherwise, don't change
15288 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
15290 static bool
15291 tree_invalid_nonnegative_warnv_p (tree t, bool *strict_overflow_p, int depth)
15293 enum tree_code code = TREE_CODE (t);
15294 if (TYPE_UNSIGNED (TREE_TYPE (t)))
15295 return true;
15297 switch (code)
15299 case TARGET_EXPR:
15301 tree temp = TARGET_EXPR_SLOT (t);
15302 t = TARGET_EXPR_INITIAL (t);
15304 /* If the initializer is non-void, then it's a normal expression
15305 that will be assigned to the slot. */
15306 if (!VOID_TYPE_P (TREE_TYPE (t)))
15307 return RECURSE (t);
15309 /* Otherwise, the initializer sets the slot in some way. One common
15310 way is an assignment statement at the end of the initializer. */
15311 while (1)
15313 if (TREE_CODE (t) == BIND_EXPR)
15314 t = expr_last (BIND_EXPR_BODY (t));
15315 else if (TREE_CODE (t) == TRY_FINALLY_EXPR
15316 || TREE_CODE (t) == TRY_CATCH_EXPR)
15317 t = expr_last (TREE_OPERAND (t, 0));
15318 else if (TREE_CODE (t) == STATEMENT_LIST)
15319 t = expr_last (t);
15320 else
15321 break;
15323 if (TREE_CODE (t) == MODIFY_EXPR
15324 && TREE_OPERAND (t, 0) == temp)
15325 return RECURSE (TREE_OPERAND (t, 1));
15327 return false;
15330 case CALL_EXPR:
15332 tree arg0 = call_expr_nargs (t) > 0 ? CALL_EXPR_ARG (t, 0) : NULL_TREE;
15333 tree arg1 = call_expr_nargs (t) > 1 ? CALL_EXPR_ARG (t, 1) : NULL_TREE;
15335 return tree_call_nonnegative_warnv_p (TREE_TYPE (t),
15336 get_call_combined_fn (t),
15337 arg0,
15338 arg1,
15339 strict_overflow_p, depth);
15341 case COMPOUND_EXPR:
15342 case MODIFY_EXPR:
15343 return RECURSE (TREE_OPERAND (t, 1));
15345 case BIND_EXPR:
15346 return RECURSE (expr_last (TREE_OPERAND (t, 1)));
15348 case SAVE_EXPR:
15349 return RECURSE (TREE_OPERAND (t, 0));
15351 default:
15352 return tree_simple_nonnegative_warnv_p (TREE_CODE (t), TREE_TYPE (t));
15356 #undef RECURSE
15357 #undef tree_expr_nonnegative_warnv_p
15359 /* Return true if T is known to be non-negative. If the return
15360 value is based on the assumption that signed overflow is undefined,
15361 set *STRICT_OVERFLOW_P to true; otherwise, don't change
15362 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
15364 bool
15365 tree_expr_nonnegative_warnv_p (tree t, bool *strict_overflow_p, int depth)
15367 enum tree_code code;
15368 if (t == error_mark_node)
15369 return false;
15371 code = TREE_CODE (t);
15372 switch (TREE_CODE_CLASS (code))
15374 case tcc_binary:
15375 case tcc_comparison:
15376 return tree_binary_nonnegative_warnv_p (TREE_CODE (t),
15377 TREE_TYPE (t),
15378 TREE_OPERAND (t, 0),
15379 TREE_OPERAND (t, 1),
15380 strict_overflow_p, depth);
15382 case tcc_unary:
15383 return tree_unary_nonnegative_warnv_p (TREE_CODE (t),
15384 TREE_TYPE (t),
15385 TREE_OPERAND (t, 0),
15386 strict_overflow_p, depth);
15388 case tcc_constant:
15389 case tcc_declaration:
15390 case tcc_reference:
15391 return tree_single_nonnegative_warnv_p (t, strict_overflow_p, depth);
15393 default:
15394 break;
15397 switch (code)
15399 case TRUTH_AND_EXPR:
15400 case TRUTH_OR_EXPR:
15401 case TRUTH_XOR_EXPR:
15402 return tree_binary_nonnegative_warnv_p (TREE_CODE (t),
15403 TREE_TYPE (t),
15404 TREE_OPERAND (t, 0),
15405 TREE_OPERAND (t, 1),
15406 strict_overflow_p, depth);
15407 case TRUTH_NOT_EXPR:
15408 return tree_unary_nonnegative_warnv_p (TREE_CODE (t),
15409 TREE_TYPE (t),
15410 TREE_OPERAND (t, 0),
15411 strict_overflow_p, depth);
15413 case COND_EXPR:
15414 case CONSTRUCTOR:
15415 case OBJ_TYPE_REF:
15416 case ADDR_EXPR:
15417 case WITH_SIZE_EXPR:
15418 case SSA_NAME:
15419 return tree_single_nonnegative_warnv_p (t, strict_overflow_p, depth);
15421 default:
15422 return tree_invalid_nonnegative_warnv_p (t, strict_overflow_p, depth);
15426 /* Return true if `t' is known to be non-negative. Handle warnings
15427 about undefined signed overflow. */
15429 bool
15430 tree_expr_nonnegative_p (tree t)
15432 bool ret, strict_overflow_p;
15434 strict_overflow_p = false;
15435 ret = tree_expr_nonnegative_warnv_p (t, &strict_overflow_p);
15436 if (strict_overflow_p)
15437 fold_overflow_warning (("assuming signed overflow does not occur when "
15438 "determining that expression is always "
15439 "non-negative"),
15440 WARN_STRICT_OVERFLOW_MISC);
15441 return ret;
15445 /* Return true when (CODE OP0) is an address and is known to be nonzero.
15446 For floating point we further ensure that T is not denormal.
15447 Similar logic is present in nonzero_address in rtlanal.h.
15449 If the return value is based on the assumption that signed overflow
15450 is undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't
15451 change *STRICT_OVERFLOW_P. */
15453 bool
15454 tree_unary_nonzero_warnv_p (enum tree_code code, tree type, tree op0,
15455 bool *strict_overflow_p)
15457 switch (code)
15459 case ABS_EXPR:
15460 return tree_expr_nonzero_warnv_p (op0,
15461 strict_overflow_p);
15463 case NOP_EXPR:
15465 tree inner_type = TREE_TYPE (op0);
15466 tree outer_type = type;
15468 return (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
15469 && tree_expr_nonzero_warnv_p (op0,
15470 strict_overflow_p));
15472 break;
15474 case NON_LVALUE_EXPR:
15475 return tree_expr_nonzero_warnv_p (op0,
15476 strict_overflow_p);
15478 default:
15479 break;
15482 return false;
15485 /* Return true when (CODE OP0 OP1) is an address and is known to be nonzero.
15486 For floating point we further ensure that T is not denormal.
15487 Similar logic is present in nonzero_address in rtlanal.h.
15489 If the return value is based on the assumption that signed overflow
15490 is undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't
15491 change *STRICT_OVERFLOW_P. */
15493 bool
15494 tree_binary_nonzero_warnv_p (enum tree_code code,
15495 tree type,
15496 tree op0,
15497 tree op1, bool *strict_overflow_p)
15499 bool sub_strict_overflow_p;
15500 switch (code)
15502 case POINTER_PLUS_EXPR:
15503 case PLUS_EXPR:
15504 if (ANY_INTEGRAL_TYPE_P (type) && TYPE_OVERFLOW_UNDEFINED (type))
15506 /* With the presence of negative values it is hard
15507 to say something. */
15508 sub_strict_overflow_p = false;
15509 if (!tree_expr_nonnegative_warnv_p (op0,
15510 &sub_strict_overflow_p)
15511 || !tree_expr_nonnegative_warnv_p (op1,
15512 &sub_strict_overflow_p))
15513 return false;
15514 /* One of operands must be positive and the other non-negative. */
15515 /* We don't set *STRICT_OVERFLOW_P here: even if this value
15516 overflows, on a twos-complement machine the sum of two
15517 nonnegative numbers can never be zero. */
15518 return (tree_expr_nonzero_warnv_p (op0,
15519 strict_overflow_p)
15520 || tree_expr_nonzero_warnv_p (op1,
15521 strict_overflow_p));
15523 break;
15525 case MULT_EXPR:
15526 if (TYPE_OVERFLOW_UNDEFINED (type))
15528 if (tree_expr_nonzero_warnv_p (op0,
15529 strict_overflow_p)
15530 && tree_expr_nonzero_warnv_p (op1,
15531 strict_overflow_p))
15533 *strict_overflow_p = true;
15534 return true;
15537 break;
15539 case MIN_EXPR:
15540 sub_strict_overflow_p = false;
15541 if (tree_expr_nonzero_warnv_p (op0,
15542 &sub_strict_overflow_p)
15543 && tree_expr_nonzero_warnv_p (op1,
15544 &sub_strict_overflow_p))
15546 if (sub_strict_overflow_p)
15547 *strict_overflow_p = true;
15549 break;
15551 case MAX_EXPR:
15552 sub_strict_overflow_p = false;
15553 if (tree_expr_nonzero_warnv_p (op0,
15554 &sub_strict_overflow_p))
15556 if (sub_strict_overflow_p)
15557 *strict_overflow_p = true;
15559 /* When both operands are nonzero, then MAX must be too. */
15560 if (tree_expr_nonzero_warnv_p (op1,
15561 strict_overflow_p))
15562 return true;
15564 /* MAX where operand 0 is positive is positive. */
15565 return tree_expr_nonnegative_warnv_p (op0,
15566 strict_overflow_p);
15568 /* MAX where operand 1 is positive is positive. */
15569 else if (tree_expr_nonzero_warnv_p (op1,
15570 &sub_strict_overflow_p)
15571 && tree_expr_nonnegative_warnv_p (op1,
15572 &sub_strict_overflow_p))
15574 if (sub_strict_overflow_p)
15575 *strict_overflow_p = true;
15576 return true;
15578 break;
15580 case BIT_IOR_EXPR:
15581 return (tree_expr_nonzero_warnv_p (op1,
15582 strict_overflow_p)
15583 || tree_expr_nonzero_warnv_p (op0,
15584 strict_overflow_p));
15586 default:
15587 break;
15590 return false;
15593 /* Return true when T is an address and is known to be nonzero.
15594 For floating point we further ensure that T is not denormal.
15595 Similar logic is present in nonzero_address in rtlanal.h.
15597 If the return value is based on the assumption that signed overflow
15598 is undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't
15599 change *STRICT_OVERFLOW_P. */
15601 bool
15602 tree_single_nonzero_warnv_p (tree t, bool *strict_overflow_p)
15604 bool sub_strict_overflow_p;
15605 switch (TREE_CODE (t))
15607 case INTEGER_CST:
15608 return !integer_zerop (t);
15610 case ADDR_EXPR:
15612 tree base = TREE_OPERAND (t, 0);
15614 if (!DECL_P (base))
15615 base = get_base_address (base);
15617 if (base && TREE_CODE (base) == TARGET_EXPR)
15618 base = TARGET_EXPR_SLOT (base);
15620 if (!base)
15621 return false;
15623 /* For objects in symbol table check if we know they are non-zero.
15624 Don't do anything for variables and functions before symtab is built;
15625 it is quite possible that they will be declared weak later. */
15626 int nonzero_addr = maybe_nonzero_address (base);
15627 if (nonzero_addr >= 0)
15628 return nonzero_addr;
15630 /* Constants are never weak. */
15631 if (CONSTANT_CLASS_P (base))
15632 return true;
15634 return false;
15637 case COND_EXPR:
15638 sub_strict_overflow_p = false;
15639 if (tree_expr_nonzero_warnv_p (TREE_OPERAND (t, 1),
15640 &sub_strict_overflow_p)
15641 && tree_expr_nonzero_warnv_p (TREE_OPERAND (t, 2),
15642 &sub_strict_overflow_p))
15644 if (sub_strict_overflow_p)
15645 *strict_overflow_p = true;
15646 return true;
15648 break;
15650 case SSA_NAME:
15651 if (!INTEGRAL_TYPE_P (TREE_TYPE (t)))
15652 break;
15653 return expr_not_equal_to (t, wi::zero (TYPE_PRECISION (TREE_TYPE (t))));
15655 default:
15656 break;
15658 return false;
15661 #define integer_valued_real_p(X) \
15662 _Pragma ("GCC error \"Use RECURSE for recursive calls\"") 0
15664 #define RECURSE(X) \
15665 ((integer_valued_real_p) (X, depth + 1))
15667 /* Return true if the floating point result of (CODE OP0) has an
15668 integer value. We also allow +Inf, -Inf and NaN to be considered
15669 integer values. Return false for signaling NaN.
15671 DEPTH is the current nesting depth of the query. */
15673 bool
15674 integer_valued_real_unary_p (tree_code code, tree op0, int depth)
15676 switch (code)
15678 case FLOAT_EXPR:
15679 return true;
15681 case ABS_EXPR:
15682 return RECURSE (op0);
15684 CASE_CONVERT:
15686 tree type = TREE_TYPE (op0);
15687 if (TREE_CODE (type) == INTEGER_TYPE)
15688 return true;
15689 if (SCALAR_FLOAT_TYPE_P (type))
15690 return RECURSE (op0);
15691 break;
15694 default:
15695 break;
15697 return false;
15700 /* Return true if the floating point result of (CODE OP0 OP1) has an
15701 integer value. We also allow +Inf, -Inf and NaN to be considered
15702 integer values. Return false for signaling NaN.
15704 DEPTH is the current nesting depth of the query. */
15706 bool
15707 integer_valued_real_binary_p (tree_code code, tree op0, tree op1, int depth)
15709 switch (code)
15711 case PLUS_EXPR:
15712 case MINUS_EXPR:
15713 case MULT_EXPR:
15714 case MIN_EXPR:
15715 case MAX_EXPR:
15716 return RECURSE (op0) && RECURSE (op1);
15718 default:
15719 break;
15721 return false;
15724 /* Return true if the floating point result of calling FNDECL with arguments
15725 ARG0 and ARG1 has an integer value. We also allow +Inf, -Inf and NaN to be
15726 considered integer values. Return false for signaling NaN. If FNDECL
15727 takes fewer than 2 arguments, the remaining ARGn are null.
15729 DEPTH is the current nesting depth of the query. */
15731 bool
15732 integer_valued_real_call_p (combined_fn fn, tree arg0, tree arg1, int depth)
15734 switch (fn)
15736 CASE_CFN_CEIL:
15737 CASE_CFN_CEIL_FN:
15738 CASE_CFN_FLOOR:
15739 CASE_CFN_FLOOR_FN:
15740 CASE_CFN_NEARBYINT:
15741 CASE_CFN_NEARBYINT_FN:
15742 CASE_CFN_RINT:
15743 CASE_CFN_RINT_FN:
15744 CASE_CFN_ROUND:
15745 CASE_CFN_ROUND_FN:
15746 CASE_CFN_ROUNDEVEN:
15747 CASE_CFN_ROUNDEVEN_FN:
15748 CASE_CFN_TRUNC:
15749 CASE_CFN_TRUNC_FN:
15750 return true;
15752 CASE_CFN_FMIN:
15753 CASE_CFN_FMIN_FN:
15754 CASE_CFN_FMAX:
15755 CASE_CFN_FMAX_FN:
15756 return RECURSE (arg0) && RECURSE (arg1);
15758 default:
15759 break;
15761 return false;
15764 /* Return true if the floating point expression T (a GIMPLE_SINGLE_RHS)
15765 has an integer value. We also allow +Inf, -Inf and NaN to be
15766 considered integer values. Return false for signaling NaN.
15768 DEPTH is the current nesting depth of the query. */
15770 bool
15771 integer_valued_real_single_p (tree t, int depth)
15773 switch (TREE_CODE (t))
15775 case REAL_CST:
15776 return real_isinteger (TREE_REAL_CST_PTR (t), TYPE_MODE (TREE_TYPE (t)));
15778 case COND_EXPR:
15779 return RECURSE (TREE_OPERAND (t, 1)) && RECURSE (TREE_OPERAND (t, 2));
15781 case SSA_NAME:
15782 /* Limit the depth of recursion to avoid quadratic behavior.
15783 This is expected to catch almost all occurrences in practice.
15784 If this code misses important cases that unbounded recursion
15785 would not, passes that need this information could be revised
15786 to provide it through dataflow propagation. */
15787 return (!name_registered_for_update_p (t)
15788 && depth < param_max_ssa_name_query_depth
15789 && gimple_stmt_integer_valued_real_p (SSA_NAME_DEF_STMT (t),
15790 depth));
15792 default:
15793 break;
15795 return false;
15798 /* Return true if the floating point expression T (a GIMPLE_INVALID_RHS)
15799 has an integer value. We also allow +Inf, -Inf and NaN to be
15800 considered integer values. Return false for signaling NaN.
15802 DEPTH is the current nesting depth of the query. */
15804 static bool
15805 integer_valued_real_invalid_p (tree t, int depth)
15807 switch (TREE_CODE (t))
15809 case COMPOUND_EXPR:
15810 case MODIFY_EXPR:
15811 case BIND_EXPR:
15812 return RECURSE (TREE_OPERAND (t, 1));
15814 case SAVE_EXPR:
15815 return RECURSE (TREE_OPERAND (t, 0));
15817 default:
15818 break;
15820 return false;
15823 #undef RECURSE
15824 #undef integer_valued_real_p
15826 /* Return true if the floating point expression T has an integer value.
15827 We also allow +Inf, -Inf and NaN to be considered integer values.
15828 Return false for signaling NaN.
15830 DEPTH is the current nesting depth of the query. */
15832 bool
15833 integer_valued_real_p (tree t, int depth)
15835 if (t == error_mark_node)
15836 return false;
15838 STRIP_ANY_LOCATION_WRAPPER (t);
15840 tree_code code = TREE_CODE (t);
15841 switch (TREE_CODE_CLASS (code))
15843 case tcc_binary:
15844 case tcc_comparison:
15845 return integer_valued_real_binary_p (code, TREE_OPERAND (t, 0),
15846 TREE_OPERAND (t, 1), depth);
15848 case tcc_unary:
15849 return integer_valued_real_unary_p (code, TREE_OPERAND (t, 0), depth);
15851 case tcc_constant:
15852 case tcc_declaration:
15853 case tcc_reference:
15854 return integer_valued_real_single_p (t, depth);
15856 default:
15857 break;
15860 switch (code)
15862 case COND_EXPR:
15863 case SSA_NAME:
15864 return integer_valued_real_single_p (t, depth);
15866 case CALL_EXPR:
15868 tree arg0 = (call_expr_nargs (t) > 0
15869 ? CALL_EXPR_ARG (t, 0)
15870 : NULL_TREE);
15871 tree arg1 = (call_expr_nargs (t) > 1
15872 ? CALL_EXPR_ARG (t, 1)
15873 : NULL_TREE);
15874 return integer_valued_real_call_p (get_call_combined_fn (t),
15875 arg0, arg1, depth);
15878 default:
15879 return integer_valued_real_invalid_p (t, depth);
15883 /* Given the components of a binary expression CODE, TYPE, OP0 and OP1,
15884 attempt to fold the expression to a constant without modifying TYPE,
15885 OP0 or OP1.
15887 If the expression could be simplified to a constant, then return
15888 the constant. If the expression would not be simplified to a
15889 constant, then return NULL_TREE. */
15891 tree
15892 fold_binary_to_constant (enum tree_code code, tree type, tree op0, tree op1)
15894 tree tem = fold_binary (code, type, op0, op1);
15895 return (tem && TREE_CONSTANT (tem)) ? tem : NULL_TREE;
15898 /* Given the components of a unary expression CODE, TYPE and OP0,
15899 attempt to fold the expression to a constant without modifying
15900 TYPE or OP0.
15902 If the expression could be simplified to a constant, then return
15903 the constant. If the expression would not be simplified to a
15904 constant, then return NULL_TREE. */
15906 tree
15907 fold_unary_to_constant (enum tree_code code, tree type, tree op0)
15909 tree tem = fold_unary (code, type, op0);
15910 return (tem && TREE_CONSTANT (tem)) ? tem : NULL_TREE;
15913 /* If EXP represents referencing an element in a constant string
15914 (either via pointer arithmetic or array indexing), return the
15915 tree representing the value accessed, otherwise return NULL. */
15917 tree
15918 fold_read_from_constant_string (tree exp)
15920 if ((INDIRECT_REF_P (exp)
15921 || TREE_CODE (exp) == ARRAY_REF)
15922 && TREE_CODE (TREE_TYPE (exp)) == INTEGER_TYPE)
15924 tree exp1 = TREE_OPERAND (exp, 0);
15925 tree index;
15926 tree string;
15927 location_t loc = EXPR_LOCATION (exp);
15929 if (INDIRECT_REF_P (exp))
15930 string = string_constant (exp1, &index, NULL, NULL);
15931 else
15933 tree low_bound = array_ref_low_bound (exp);
15934 index = fold_convert_loc (loc, sizetype, TREE_OPERAND (exp, 1));
15936 /* Optimize the special-case of a zero lower bound.
15938 We convert the low_bound to sizetype to avoid some problems
15939 with constant folding. (E.g. suppose the lower bound is 1,
15940 and its mode is QI. Without the conversion,l (ARRAY
15941 +(INDEX-(unsigned char)1)) becomes ((ARRAY+(-(unsigned char)1))
15942 +INDEX), which becomes (ARRAY+255+INDEX). Oops!) */
15943 if (! integer_zerop (low_bound))
15944 index = size_diffop_loc (loc, index,
15945 fold_convert_loc (loc, sizetype, low_bound));
15947 string = exp1;
15950 scalar_int_mode char_mode;
15951 if (string
15952 && TYPE_MODE (TREE_TYPE (exp)) == TYPE_MODE (TREE_TYPE (TREE_TYPE (string)))
15953 && TREE_CODE (string) == STRING_CST
15954 && tree_fits_uhwi_p (index)
15955 && compare_tree_int (index, TREE_STRING_LENGTH (string)) < 0
15956 && is_int_mode (TYPE_MODE (TREE_TYPE (TREE_TYPE (string))),
15957 &char_mode)
15958 && GET_MODE_SIZE (char_mode) == 1)
15959 return build_int_cst_type (TREE_TYPE (exp),
15960 (TREE_STRING_POINTER (string)
15961 [TREE_INT_CST_LOW (index)]));
15963 return NULL;
15966 /* Folds a read from vector element at IDX of vector ARG. */
15968 tree
15969 fold_read_from_vector (tree arg, poly_uint64 idx)
15971 unsigned HOST_WIDE_INT i;
15972 if (known_lt (idx, TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg)))
15973 && known_ge (idx, 0u)
15974 && idx.is_constant (&i))
15976 if (TREE_CODE (arg) == VECTOR_CST)
15977 return VECTOR_CST_ELT (arg, i);
15978 else if (TREE_CODE (arg) == CONSTRUCTOR)
15980 if (CONSTRUCTOR_NELTS (arg)
15981 && VECTOR_TYPE_P (TREE_TYPE (CONSTRUCTOR_ELT (arg, 0)->value)))
15982 return NULL_TREE;
15983 if (i >= CONSTRUCTOR_NELTS (arg))
15984 return build_zero_cst (TREE_TYPE (TREE_TYPE (arg)));
15985 return CONSTRUCTOR_ELT (arg, i)->value;
15988 return NULL_TREE;
15991 /* Return the tree for neg (ARG0) when ARG0 is known to be either
15992 an integer constant, real, or fixed-point constant.
15994 TYPE is the type of the result. */
15996 static tree
15997 fold_negate_const (tree arg0, tree type)
15999 tree t = NULL_TREE;
16001 switch (TREE_CODE (arg0))
16003 case REAL_CST:
16004 t = build_real (type, real_value_negate (&TREE_REAL_CST (arg0)));
16005 break;
16007 case FIXED_CST:
16009 FIXED_VALUE_TYPE f;
16010 bool overflow_p = fixed_arithmetic (&f, NEGATE_EXPR,
16011 &(TREE_FIXED_CST (arg0)), NULL,
16012 TYPE_SATURATING (type));
16013 t = build_fixed (type, f);
16014 /* Propagate overflow flags. */
16015 if (overflow_p | TREE_OVERFLOW (arg0))
16016 TREE_OVERFLOW (t) = 1;
16017 break;
16020 default:
16021 if (poly_int_tree_p (arg0))
16023 wi::overflow_type overflow;
16024 poly_wide_int res = wi::neg (wi::to_poly_wide (arg0), &overflow);
16025 t = force_fit_type (type, res, 1,
16026 (overflow && ! TYPE_UNSIGNED (type))
16027 || TREE_OVERFLOW (arg0));
16028 break;
16031 gcc_unreachable ();
16034 return t;
16037 /* Return the tree for abs (ARG0) when ARG0 is known to be either
16038 an integer constant or real constant.
16040 TYPE is the type of the result. */
16042 tree
16043 fold_abs_const (tree arg0, tree type)
16045 tree t = NULL_TREE;
16047 switch (TREE_CODE (arg0))
16049 case INTEGER_CST:
16051 /* If the value is unsigned or non-negative, then the absolute value
16052 is the same as the ordinary value. */
16053 wide_int val = wi::to_wide (arg0);
16054 wi::overflow_type overflow = wi::OVF_NONE;
16055 if (!wi::neg_p (val, TYPE_SIGN (TREE_TYPE (arg0))))
16058 /* If the value is negative, then the absolute value is
16059 its negation. */
16060 else
16061 val = wi::neg (val, &overflow);
16063 /* Force to the destination type, set TREE_OVERFLOW for signed
16064 TYPE only. */
16065 t = force_fit_type (type, val, 1, overflow | TREE_OVERFLOW (arg0));
16067 break;
16069 case REAL_CST:
16070 if (REAL_VALUE_NEGATIVE (TREE_REAL_CST (arg0)))
16071 t = build_real (type, real_value_negate (&TREE_REAL_CST (arg0)));
16072 else
16073 t = arg0;
16074 break;
16076 default:
16077 gcc_unreachable ();
16080 return t;
16083 /* Return the tree for not (ARG0) when ARG0 is known to be an integer
16084 constant. TYPE is the type of the result. */
16086 static tree
16087 fold_not_const (const_tree arg0, tree type)
16089 gcc_assert (TREE_CODE (arg0) == INTEGER_CST);
16091 return force_fit_type (type, ~wi::to_wide (arg0), 0, TREE_OVERFLOW (arg0));
16094 /* Given CODE, a relational operator, the target type, TYPE and two
16095 constant operands OP0 and OP1, return the result of the
16096 relational operation. If the result is not a compile time
16097 constant, then return NULL_TREE. */
16099 static tree
16100 fold_relational_const (enum tree_code code, tree type, tree op0, tree op1)
16102 int result, invert;
16104 /* From here on, the only cases we handle are when the result is
16105 known to be a constant. */
16107 if (TREE_CODE (op0) == REAL_CST && TREE_CODE (op1) == REAL_CST)
16109 const REAL_VALUE_TYPE *c0 = TREE_REAL_CST_PTR (op0);
16110 const REAL_VALUE_TYPE *c1 = TREE_REAL_CST_PTR (op1);
16112 /* Handle the cases where either operand is a NaN. */
16113 if (real_isnan (c0) || real_isnan (c1))
16115 switch (code)
16117 case EQ_EXPR:
16118 case ORDERED_EXPR:
16119 result = 0;
16120 break;
16122 case NE_EXPR:
16123 case UNORDERED_EXPR:
16124 case UNLT_EXPR:
16125 case UNLE_EXPR:
16126 case UNGT_EXPR:
16127 case UNGE_EXPR:
16128 case UNEQ_EXPR:
16129 result = 1;
16130 break;
16132 case LT_EXPR:
16133 case LE_EXPR:
16134 case GT_EXPR:
16135 case GE_EXPR:
16136 case LTGT_EXPR:
16137 if (flag_trapping_math)
16138 return NULL_TREE;
16139 result = 0;
16140 break;
16142 default:
16143 gcc_unreachable ();
16146 return constant_boolean_node (result, type);
16149 return constant_boolean_node (real_compare (code, c0, c1), type);
16152 if (TREE_CODE (op0) == FIXED_CST && TREE_CODE (op1) == FIXED_CST)
16154 const FIXED_VALUE_TYPE *c0 = TREE_FIXED_CST_PTR (op0);
16155 const FIXED_VALUE_TYPE *c1 = TREE_FIXED_CST_PTR (op1);
16156 return constant_boolean_node (fixed_compare (code, c0, c1), type);
16159 /* Handle equality/inequality of complex constants. */
16160 if (TREE_CODE (op0) == COMPLEX_CST && TREE_CODE (op1) == COMPLEX_CST)
16162 tree rcond = fold_relational_const (code, type,
16163 TREE_REALPART (op0),
16164 TREE_REALPART (op1));
16165 tree icond = fold_relational_const (code, type,
16166 TREE_IMAGPART (op0),
16167 TREE_IMAGPART (op1));
16168 if (code == EQ_EXPR)
16169 return fold_build2 (TRUTH_ANDIF_EXPR, type, rcond, icond);
16170 else if (code == NE_EXPR)
16171 return fold_build2 (TRUTH_ORIF_EXPR, type, rcond, icond);
16172 else
16173 return NULL_TREE;
16176 if (TREE_CODE (op0) == VECTOR_CST && TREE_CODE (op1) == VECTOR_CST)
16178 if (!VECTOR_TYPE_P (type))
16180 /* Have vector comparison with scalar boolean result. */
16181 gcc_assert ((code == EQ_EXPR || code == NE_EXPR)
16182 && known_eq (VECTOR_CST_NELTS (op0),
16183 VECTOR_CST_NELTS (op1)));
16184 unsigned HOST_WIDE_INT nunits;
16185 if (!VECTOR_CST_NELTS (op0).is_constant (&nunits))
16186 return NULL_TREE;
16187 for (unsigned i = 0; i < nunits; i++)
16189 tree elem0 = VECTOR_CST_ELT (op0, i);
16190 tree elem1 = VECTOR_CST_ELT (op1, i);
16191 tree tmp = fold_relational_const (EQ_EXPR, type, elem0, elem1);
16192 if (tmp == NULL_TREE)
16193 return NULL_TREE;
16194 if (integer_zerop (tmp))
16195 return constant_boolean_node (code == NE_EXPR, type);
16197 return constant_boolean_node (code == EQ_EXPR, type);
16199 tree_vector_builder elts;
16200 if (!elts.new_binary_operation (type, op0, op1, false))
16201 return NULL_TREE;
16202 unsigned int count = elts.encoded_nelts ();
16203 for (unsigned i = 0; i < count; i++)
16205 tree elem_type = TREE_TYPE (type);
16206 tree elem0 = VECTOR_CST_ELT (op0, i);
16207 tree elem1 = VECTOR_CST_ELT (op1, i);
16209 tree tem = fold_relational_const (code, elem_type,
16210 elem0, elem1);
16212 if (tem == NULL_TREE)
16213 return NULL_TREE;
16215 elts.quick_push (build_int_cst (elem_type,
16216 integer_zerop (tem) ? 0 : -1));
16219 return elts.build ();
16222 /* From here on we only handle LT, LE, GT, GE, EQ and NE.
16224 To compute GT, swap the arguments and do LT.
16225 To compute GE, do LT and invert the result.
16226 To compute LE, swap the arguments, do LT and invert the result.
16227 To compute NE, do EQ and invert the result.
16229 Therefore, the code below must handle only EQ and LT. */
16231 if (code == LE_EXPR || code == GT_EXPR)
16233 std::swap (op0, op1);
16234 code = swap_tree_comparison (code);
16237 /* Note that it is safe to invert for real values here because we
16238 have already handled the one case that it matters. */
16240 invert = 0;
16241 if (code == NE_EXPR || code == GE_EXPR)
16243 invert = 1;
16244 code = invert_tree_comparison (code, false);
16247 /* Compute a result for LT or EQ if args permit;
16248 Otherwise return T. */
16249 if (TREE_CODE (op0) == INTEGER_CST && TREE_CODE (op1) == INTEGER_CST)
16251 if (code == EQ_EXPR)
16252 result = tree_int_cst_equal (op0, op1);
16253 else
16254 result = tree_int_cst_lt (op0, op1);
16256 else
16257 return NULL_TREE;
16259 if (invert)
16260 result ^= 1;
16261 return constant_boolean_node (result, type);
16264 /* If necessary, return a CLEANUP_POINT_EXPR for EXPR with the
16265 indicated TYPE. If no CLEANUP_POINT_EXPR is necessary, return EXPR
16266 itself. */
16268 tree
16269 fold_build_cleanup_point_expr (tree type, tree expr)
16271 /* If the expression does not have side effects then we don't have to wrap
16272 it with a cleanup point expression. */
16273 if (!TREE_SIDE_EFFECTS (expr))
16274 return expr;
16276 /* If the expression is a return, check to see if the expression inside the
16277 return has no side effects or the right hand side of the modify expression
16278 inside the return. If either don't have side effects set we don't need to
16279 wrap the expression in a cleanup point expression. Note we don't check the
16280 left hand side of the modify because it should always be a return decl. */
16281 if (TREE_CODE (expr) == RETURN_EXPR)
16283 tree op = TREE_OPERAND (expr, 0);
16284 if (!op || !TREE_SIDE_EFFECTS (op))
16285 return expr;
16286 op = TREE_OPERAND (op, 1);
16287 if (!TREE_SIDE_EFFECTS (op))
16288 return expr;
16291 return build1_loc (EXPR_LOCATION (expr), CLEANUP_POINT_EXPR, type, expr);
16294 /* Given a pointer value OP0 and a type TYPE, return a simplified version
16295 of an indirection through OP0, or NULL_TREE if no simplification is
16296 possible. */
16298 tree
16299 fold_indirect_ref_1 (location_t loc, tree type, tree op0)
16301 tree sub = op0;
16302 tree subtype;
16303 poly_uint64 const_op01;
16305 STRIP_NOPS (sub);
16306 subtype = TREE_TYPE (sub);
16307 if (!POINTER_TYPE_P (subtype)
16308 || TYPE_REF_CAN_ALIAS_ALL (TREE_TYPE (op0)))
16309 return NULL_TREE;
16311 if (TREE_CODE (sub) == ADDR_EXPR)
16313 tree op = TREE_OPERAND (sub, 0);
16314 tree optype = TREE_TYPE (op);
16316 /* *&CONST_DECL -> to the value of the const decl. */
16317 if (TREE_CODE (op) == CONST_DECL)
16318 return DECL_INITIAL (op);
16319 /* *&p => p; make sure to handle *&"str"[cst] here. */
16320 if (type == optype)
16322 tree fop = fold_read_from_constant_string (op);
16323 if (fop)
16324 return fop;
16325 else
16326 return op;
16328 /* *(foo *)&fooarray => fooarray[0] */
16329 else if (TREE_CODE (optype) == ARRAY_TYPE
16330 && type == TREE_TYPE (optype)
16331 && (!in_gimple_form
16332 || TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST))
16334 tree type_domain = TYPE_DOMAIN (optype);
16335 tree min_val = size_zero_node;
16336 if (type_domain && TYPE_MIN_VALUE (type_domain))
16337 min_val = TYPE_MIN_VALUE (type_domain);
16338 if (in_gimple_form
16339 && TREE_CODE (min_val) != INTEGER_CST)
16340 return NULL_TREE;
16341 return build4_loc (loc, ARRAY_REF, type, op, min_val,
16342 NULL_TREE, NULL_TREE);
16344 /* *(foo *)&complexfoo => __real__ complexfoo */
16345 else if (TREE_CODE (optype) == COMPLEX_TYPE
16346 && type == TREE_TYPE (optype))
16347 return fold_build1_loc (loc, REALPART_EXPR, type, op);
16348 /* *(foo *)&vectorfoo => BIT_FIELD_REF<vectorfoo,...> */
16349 else if (VECTOR_TYPE_P (optype)
16350 && type == TREE_TYPE (optype))
16352 tree part_width = TYPE_SIZE (type);
16353 tree index = bitsize_int (0);
16354 return fold_build3_loc (loc, BIT_FIELD_REF, type, op, part_width,
16355 index);
16359 if (TREE_CODE (sub) == POINTER_PLUS_EXPR
16360 && poly_int_tree_p (TREE_OPERAND (sub, 1), &const_op01))
16362 tree op00 = TREE_OPERAND (sub, 0);
16363 tree op01 = TREE_OPERAND (sub, 1);
16365 STRIP_NOPS (op00);
16366 if (TREE_CODE (op00) == ADDR_EXPR)
16368 tree op00type;
16369 op00 = TREE_OPERAND (op00, 0);
16370 op00type = TREE_TYPE (op00);
16372 /* ((foo*)&vectorfoo)[1] => BIT_FIELD_REF<vectorfoo,...> */
16373 if (VECTOR_TYPE_P (op00type)
16374 && type == TREE_TYPE (op00type)
16375 /* POINTER_PLUS_EXPR second operand is sizetype, unsigned,
16376 but we want to treat offsets with MSB set as negative.
16377 For the code below negative offsets are invalid and
16378 TYPE_SIZE of the element is something unsigned, so
16379 check whether op01 fits into poly_int64, which implies
16380 it is from 0 to INTTYPE_MAXIMUM (HOST_WIDE_INT), and
16381 then just use poly_uint64 because we want to treat the
16382 value as unsigned. */
16383 && tree_fits_poly_int64_p (op01))
16385 tree part_width = TYPE_SIZE (type);
16386 poly_uint64 max_offset
16387 = (tree_to_uhwi (part_width) / BITS_PER_UNIT
16388 * TYPE_VECTOR_SUBPARTS (op00type));
16389 if (known_lt (const_op01, max_offset))
16391 tree index = bitsize_int (const_op01 * BITS_PER_UNIT);
16392 return fold_build3_loc (loc,
16393 BIT_FIELD_REF, type, op00,
16394 part_width, index);
16397 /* ((foo*)&complexfoo)[1] => __imag__ complexfoo */
16398 else if (TREE_CODE (op00type) == COMPLEX_TYPE
16399 && type == TREE_TYPE (op00type))
16401 if (known_eq (wi::to_poly_offset (TYPE_SIZE_UNIT (type)),
16402 const_op01))
16403 return fold_build1_loc (loc, IMAGPART_EXPR, type, op00);
16405 /* ((foo *)&fooarray)[1] => fooarray[1] */
16406 else if (TREE_CODE (op00type) == ARRAY_TYPE
16407 && type == TREE_TYPE (op00type))
16409 tree type_domain = TYPE_DOMAIN (op00type);
16410 tree min_val = size_zero_node;
16411 if (type_domain && TYPE_MIN_VALUE (type_domain))
16412 min_val = TYPE_MIN_VALUE (type_domain);
16413 poly_uint64 type_size, index;
16414 if (poly_int_tree_p (min_val)
16415 && poly_int_tree_p (TYPE_SIZE_UNIT (type), &type_size)
16416 && multiple_p (const_op01, type_size, &index))
16418 poly_offset_int off = index + wi::to_poly_offset (min_val);
16419 op01 = wide_int_to_tree (sizetype, off);
16420 return build4_loc (loc, ARRAY_REF, type, op00, op01,
16421 NULL_TREE, NULL_TREE);
16427 /* *(foo *)fooarrptr => (*fooarrptr)[0] */
16428 if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
16429 && type == TREE_TYPE (TREE_TYPE (subtype))
16430 && (!in_gimple_form
16431 || TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST))
16433 tree type_domain;
16434 tree min_val = size_zero_node;
16435 sub = build_fold_indirect_ref_loc (loc, sub);
16436 type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
16437 if (type_domain && TYPE_MIN_VALUE (type_domain))
16438 min_val = TYPE_MIN_VALUE (type_domain);
16439 if (in_gimple_form
16440 && TREE_CODE (min_val) != INTEGER_CST)
16441 return NULL_TREE;
16442 return build4_loc (loc, ARRAY_REF, type, sub, min_val, NULL_TREE,
16443 NULL_TREE);
16446 return NULL_TREE;
16449 /* Builds an expression for an indirection through T, simplifying some
16450 cases. */
16452 tree
16453 build_fold_indirect_ref_loc (location_t loc, tree t)
16455 tree type = TREE_TYPE (TREE_TYPE (t));
16456 tree sub = fold_indirect_ref_1 (loc, type, t);
16458 if (sub)
16459 return sub;
16461 return build1_loc (loc, INDIRECT_REF, type, t);
16464 /* Given an INDIRECT_REF T, return either T or a simplified version. */
16466 tree
16467 fold_indirect_ref_loc (location_t loc, tree t)
16469 tree sub = fold_indirect_ref_1 (loc, TREE_TYPE (t), TREE_OPERAND (t, 0));
16471 if (sub)
16472 return sub;
16473 else
16474 return t;
16477 /* Strip non-trapping, non-side-effecting tree nodes from an expression
16478 whose result is ignored. The type of the returned tree need not be
16479 the same as the original expression. */
16481 tree
16482 fold_ignored_result (tree t)
16484 if (!TREE_SIDE_EFFECTS (t))
16485 return integer_zero_node;
16487 for (;;)
16488 switch (TREE_CODE_CLASS (TREE_CODE (t)))
16490 case tcc_unary:
16491 t = TREE_OPERAND (t, 0);
16492 break;
16494 case tcc_binary:
16495 case tcc_comparison:
16496 if (!TREE_SIDE_EFFECTS (TREE_OPERAND (t, 1)))
16497 t = TREE_OPERAND (t, 0);
16498 else if (!TREE_SIDE_EFFECTS (TREE_OPERAND (t, 0)))
16499 t = TREE_OPERAND (t, 1);
16500 else
16501 return t;
16502 break;
16504 case tcc_expression:
16505 switch (TREE_CODE (t))
16507 case COMPOUND_EXPR:
16508 if (TREE_SIDE_EFFECTS (TREE_OPERAND (t, 1)))
16509 return t;
16510 t = TREE_OPERAND (t, 0);
16511 break;
16513 case COND_EXPR:
16514 if (TREE_SIDE_EFFECTS (TREE_OPERAND (t, 1))
16515 || TREE_SIDE_EFFECTS (TREE_OPERAND (t, 2)))
16516 return t;
16517 t = TREE_OPERAND (t, 0);
16518 break;
16520 default:
16521 return t;
16523 break;
16525 default:
16526 return t;
16530 /* Return the value of VALUE, rounded up to a multiple of DIVISOR. */
16532 tree
16533 round_up_loc (location_t loc, tree value, unsigned int divisor)
16535 tree div = NULL_TREE;
16537 if (divisor == 1)
16538 return value;
16540 /* See if VALUE is already a multiple of DIVISOR. If so, we don't
16541 have to do anything. Only do this when we are not given a const,
16542 because in that case, this check is more expensive than just
16543 doing it. */
16544 if (TREE_CODE (value) != INTEGER_CST)
16546 div = build_int_cst (TREE_TYPE (value), divisor);
16548 if (multiple_of_p (TREE_TYPE (value), value, div))
16549 return value;
16552 /* If divisor is a power of two, simplify this to bit manipulation. */
16553 if (pow2_or_zerop (divisor))
16555 if (TREE_CODE (value) == INTEGER_CST)
16557 wide_int val = wi::to_wide (value);
16558 bool overflow_p;
16560 if ((val & (divisor - 1)) == 0)
16561 return value;
16563 overflow_p = TREE_OVERFLOW (value);
16564 val += divisor - 1;
16565 val &= (int) -divisor;
16566 if (val == 0)
16567 overflow_p = true;
16569 return force_fit_type (TREE_TYPE (value), val, -1, overflow_p);
16571 else
16573 tree t;
16575 t = build_int_cst (TREE_TYPE (value), divisor - 1);
16576 value = size_binop_loc (loc, PLUS_EXPR, value, t);
16577 t = build_int_cst (TREE_TYPE (value), - (int) divisor);
16578 value = size_binop_loc (loc, BIT_AND_EXPR, value, t);
16581 else
16583 if (!div)
16584 div = build_int_cst (TREE_TYPE (value), divisor);
16585 value = size_binop_loc (loc, CEIL_DIV_EXPR, value, div);
16586 value = size_binop_loc (loc, MULT_EXPR, value, div);
16589 return value;
16592 /* Likewise, but round down. */
16594 tree
16595 round_down_loc (location_t loc, tree value, int divisor)
16597 tree div = NULL_TREE;
16599 gcc_assert (divisor > 0);
16600 if (divisor == 1)
16601 return value;
16603 /* See if VALUE is already a multiple of DIVISOR. If so, we don't
16604 have to do anything. Only do this when we are not given a const,
16605 because in that case, this check is more expensive than just
16606 doing it. */
16607 if (TREE_CODE (value) != INTEGER_CST)
16609 div = build_int_cst (TREE_TYPE (value), divisor);
16611 if (multiple_of_p (TREE_TYPE (value), value, div))
16612 return value;
16615 /* If divisor is a power of two, simplify this to bit manipulation. */
16616 if (pow2_or_zerop (divisor))
16618 tree t;
16620 t = build_int_cst (TREE_TYPE (value), -divisor);
16621 value = size_binop_loc (loc, BIT_AND_EXPR, value, t);
16623 else
16625 if (!div)
16626 div = build_int_cst (TREE_TYPE (value), divisor);
16627 value = size_binop_loc (loc, FLOOR_DIV_EXPR, value, div);
16628 value = size_binop_loc (loc, MULT_EXPR, value, div);
16631 return value;
16634 /* Returns the pointer to the base of the object addressed by EXP and
16635 extracts the information about the offset of the access, storing it
16636 to PBITPOS and POFFSET. */
16638 static tree
16639 split_address_to_core_and_offset (tree exp,
16640 poly_int64 *pbitpos, tree *poffset)
16642 tree core;
16643 machine_mode mode;
16644 int unsignedp, reversep, volatilep;
16645 poly_int64 bitsize;
16646 location_t loc = EXPR_LOCATION (exp);
16648 if (TREE_CODE (exp) == SSA_NAME)
16649 if (gassign *def = dyn_cast <gassign *> (SSA_NAME_DEF_STMT (exp)))
16650 if (gimple_assign_rhs_code (def) == ADDR_EXPR)
16651 exp = gimple_assign_rhs1 (def);
16653 if (TREE_CODE (exp) == ADDR_EXPR)
16655 core = get_inner_reference (TREE_OPERAND (exp, 0), &bitsize, pbitpos,
16656 poffset, &mode, &unsignedp, &reversep,
16657 &volatilep);
16658 core = build_fold_addr_expr_loc (loc, core);
16660 else if (TREE_CODE (exp) == POINTER_PLUS_EXPR)
16662 core = TREE_OPERAND (exp, 0);
16663 STRIP_NOPS (core);
16664 *pbitpos = 0;
16665 *poffset = TREE_OPERAND (exp, 1);
16666 if (poly_int_tree_p (*poffset))
16668 poly_offset_int tem
16669 = wi::sext (wi::to_poly_offset (*poffset),
16670 TYPE_PRECISION (TREE_TYPE (*poffset)));
16671 tem <<= LOG2_BITS_PER_UNIT;
16672 if (tem.to_shwi (pbitpos))
16673 *poffset = NULL_TREE;
16676 else
16678 core = exp;
16679 *pbitpos = 0;
16680 *poffset = NULL_TREE;
16683 return core;
16686 /* Returns true if addresses of E1 and E2 differ by a constant, false
16687 otherwise. If they do, E1 - E2 is stored in *DIFF. */
16689 bool
16690 ptr_difference_const (tree e1, tree e2, poly_int64 *diff)
16692 tree core1, core2;
16693 poly_int64 bitpos1, bitpos2;
16694 tree toffset1, toffset2, tdiff, type;
16696 core1 = split_address_to_core_and_offset (e1, &bitpos1, &toffset1);
16697 core2 = split_address_to_core_and_offset (e2, &bitpos2, &toffset2);
16699 poly_int64 bytepos1, bytepos2;
16700 if (!multiple_p (bitpos1, BITS_PER_UNIT, &bytepos1)
16701 || !multiple_p (bitpos2, BITS_PER_UNIT, &bytepos2)
16702 || !operand_equal_p (core1, core2, 0))
16703 return false;
16705 if (toffset1 && toffset2)
16707 type = TREE_TYPE (toffset1);
16708 if (type != TREE_TYPE (toffset2))
16709 toffset2 = fold_convert (type, toffset2);
16711 tdiff = fold_build2 (MINUS_EXPR, type, toffset1, toffset2);
16712 if (!cst_and_fits_in_hwi (tdiff))
16713 return false;
16715 *diff = int_cst_value (tdiff);
16717 else if (toffset1 || toffset2)
16719 /* If only one of the offsets is non-constant, the difference cannot
16720 be a constant. */
16721 return false;
16723 else
16724 *diff = 0;
16726 *diff += bytepos1 - bytepos2;
16727 return true;
16730 /* Return OFF converted to a pointer offset type suitable as offset for
16731 POINTER_PLUS_EXPR. Use location LOC for this conversion. */
16732 tree
16733 convert_to_ptrofftype_loc (location_t loc, tree off)
16735 if (ptrofftype_p (TREE_TYPE (off)))
16736 return off;
16737 return fold_convert_loc (loc, sizetype, off);
16740 /* Build and fold a POINTER_PLUS_EXPR at LOC offsetting PTR by OFF. */
16741 tree
16742 fold_build_pointer_plus_loc (location_t loc, tree ptr, tree off)
16744 return fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (ptr),
16745 ptr, convert_to_ptrofftype_loc (loc, off));
16748 /* Build and fold a POINTER_PLUS_EXPR at LOC offsetting PTR by OFF. */
16749 tree
16750 fold_build_pointer_plus_hwi_loc (location_t loc, tree ptr, HOST_WIDE_INT off)
16752 return fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (ptr),
16753 ptr, size_int (off));
16756 /* Return a pointer to a NUL-terminated string containing the sequence
16757 of bytes corresponding to the representation of the object referred to
16758 by SRC (or a subsequence of such bytes within it if SRC is a reference
16759 to an initialized constant array plus some constant offset).
16760 Set *STRSIZE the number of bytes in the constant sequence including
16761 the terminating NUL byte. *STRSIZE is equal to sizeof(A) - OFFSET
16762 where A is the array that stores the constant sequence that SRC points
16763 to and OFFSET is the byte offset of SRC from the beginning of A. SRC
16764 need not point to a string or even an array of characters but may point
16765 to an object of any type. */
16767 const char *
16768 getbyterep (tree src, unsigned HOST_WIDE_INT *strsize)
16770 /* The offset into the array A storing the string, and A's byte size. */
16771 tree offset_node;
16772 tree mem_size;
16774 if (strsize)
16775 *strsize = 0;
16777 if (strsize)
16778 src = byte_representation (src, &offset_node, &mem_size, NULL);
16779 else
16780 src = string_constant (src, &offset_node, &mem_size, NULL);
16781 if (!src)
16782 return NULL;
16784 unsigned HOST_WIDE_INT offset = 0;
16785 if (offset_node != NULL_TREE)
16787 if (!tree_fits_uhwi_p (offset_node))
16788 return NULL;
16789 else
16790 offset = tree_to_uhwi (offset_node);
16793 if (!tree_fits_uhwi_p (mem_size))
16794 return NULL;
16796 /* ARRAY_SIZE is the byte size of the array the constant sequence
16797 is stored in and equal to sizeof A. INIT_BYTES is the number
16798 of bytes in the constant sequence used to initialize the array,
16799 including any embedded NULs as well as the terminating NUL (for
16800 strings), but not including any trailing zeros/NULs past
16801 the terminating one appended implicitly to a string literal to
16802 zero out the remainder of the array it's stored in. For example,
16803 given:
16804 const char a[7] = "abc\0d";
16805 n = strlen (a + 1);
16806 ARRAY_SIZE is 7, INIT_BYTES is 6, and OFFSET is 1. For a valid
16807 (i.e., nul-terminated) string with no embedded nuls, INIT_BYTES
16808 is equal to strlen (A) + 1. */
16809 const unsigned HOST_WIDE_INT array_size = tree_to_uhwi (mem_size);
16810 unsigned HOST_WIDE_INT init_bytes = TREE_STRING_LENGTH (src);
16811 const char *string = TREE_STRING_POINTER (src);
16813 /* Ideally this would turn into a gcc_checking_assert over time. */
16814 if (init_bytes > array_size)
16815 init_bytes = array_size;
16817 if (init_bytes == 0 || offset >= array_size)
16818 return NULL;
16820 if (strsize)
16822 /* Compute and store the number of characters from the beginning
16823 of the substring at OFFSET to the end, including the terminating
16824 nul. Offsets past the initial length refer to null strings. */
16825 if (offset < init_bytes)
16826 *strsize = init_bytes - offset;
16827 else
16828 *strsize = 1;
16830 else
16832 tree eltype = TREE_TYPE (TREE_TYPE (src));
16833 /* Support only properly NUL-terminated single byte strings. */
16834 if (tree_to_uhwi (TYPE_SIZE_UNIT (eltype)) != 1)
16835 return NULL;
16836 if (string[init_bytes - 1] != '\0')
16837 return NULL;
16840 return offset < init_bytes ? string + offset : "";
16843 /* Return a pointer to a NUL-terminated string corresponding to
16844 the expression STR referencing a constant string, possibly
16845 involving a constant offset. Return null if STR either doesn't
16846 reference a constant string or if it involves a nonconstant
16847 offset. */
16849 const char *
16850 c_getstr (tree str)
16852 return getbyterep (str, NULL);
16855 /* Given a tree T, compute which bits in T may be nonzero. */
16857 wide_int
16858 tree_nonzero_bits (const_tree t)
16860 switch (TREE_CODE (t))
16862 case INTEGER_CST:
16863 return wi::to_wide (t);
16864 case SSA_NAME:
16865 return get_nonzero_bits (t);
16866 case NON_LVALUE_EXPR:
16867 case SAVE_EXPR:
16868 return tree_nonzero_bits (TREE_OPERAND (t, 0));
16869 case BIT_AND_EXPR:
16870 return wi::bit_and (tree_nonzero_bits (TREE_OPERAND (t, 0)),
16871 tree_nonzero_bits (TREE_OPERAND (t, 1)));
16872 case BIT_IOR_EXPR:
16873 case BIT_XOR_EXPR:
16874 return wi::bit_or (tree_nonzero_bits (TREE_OPERAND (t, 0)),
16875 tree_nonzero_bits (TREE_OPERAND (t, 1)));
16876 case COND_EXPR:
16877 return wi::bit_or (tree_nonzero_bits (TREE_OPERAND (t, 1)),
16878 tree_nonzero_bits (TREE_OPERAND (t, 2)));
16879 CASE_CONVERT:
16880 return wide_int::from (tree_nonzero_bits (TREE_OPERAND (t, 0)),
16881 TYPE_PRECISION (TREE_TYPE (t)),
16882 TYPE_SIGN (TREE_TYPE (TREE_OPERAND (t, 0))));
16883 case PLUS_EXPR:
16884 if (INTEGRAL_TYPE_P (TREE_TYPE (t)))
16886 wide_int nzbits1 = tree_nonzero_bits (TREE_OPERAND (t, 0));
16887 wide_int nzbits2 = tree_nonzero_bits (TREE_OPERAND (t, 1));
16888 if (wi::bit_and (nzbits1, nzbits2) == 0)
16889 return wi::bit_or (nzbits1, nzbits2);
16891 break;
16892 case LSHIFT_EXPR:
16893 if (TREE_CODE (TREE_OPERAND (t, 1)) == INTEGER_CST)
16895 tree type = TREE_TYPE (t);
16896 wide_int nzbits = tree_nonzero_bits (TREE_OPERAND (t, 0));
16897 wide_int arg1 = wi::to_wide (TREE_OPERAND (t, 1),
16898 TYPE_PRECISION (type));
16899 return wi::neg_p (arg1)
16900 ? wi::rshift (nzbits, -arg1, TYPE_SIGN (type))
16901 : wi::lshift (nzbits, arg1);
16903 break;
16904 case RSHIFT_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::lshift (nzbits, -arg1)
16913 : wi::rshift (nzbits, arg1, TYPE_SIGN (type));
16915 break;
16916 default:
16917 break;
16920 return wi::shwi (-1, TYPE_PRECISION (TREE_TYPE (t)));
16923 /* Helper function for address compare simplifications in match.pd.
16924 OP0 and OP1 are ADDR_EXPR operands being compared by CODE.
16925 TYPE is the type of comparison operands.
16926 BASE0, BASE1, OFF0 and OFF1 are set by the function.
16927 GENERIC is true if GENERIC folding and false for GIMPLE folding.
16928 Returns 0 if OP0 is known to be unequal to OP1 regardless of OFF{0,1},
16929 1 if bases are known to be equal and OP0 cmp OP1 depends on OFF0 cmp OFF1,
16930 and 2 if unknown. */
16933 address_compare (tree_code code, tree type, tree op0, tree op1,
16934 tree &base0, tree &base1, poly_int64 &off0, poly_int64 &off1,
16935 bool generic)
16937 if (TREE_CODE (op0) == SSA_NAME)
16938 op0 = gimple_assign_rhs1 (SSA_NAME_DEF_STMT (op0));
16939 if (TREE_CODE (op1) == SSA_NAME)
16940 op1 = gimple_assign_rhs1 (SSA_NAME_DEF_STMT (op1));
16941 gcc_checking_assert (TREE_CODE (op0) == ADDR_EXPR);
16942 gcc_checking_assert (TREE_CODE (op1) == ADDR_EXPR);
16943 base0 = get_addr_base_and_unit_offset (TREE_OPERAND (op0, 0), &off0);
16944 base1 = get_addr_base_and_unit_offset (TREE_OPERAND (op1, 0), &off1);
16945 if (base0 && TREE_CODE (base0) == MEM_REF)
16947 off0 += mem_ref_offset (base0).force_shwi ();
16948 base0 = TREE_OPERAND (base0, 0);
16950 if (base1 && TREE_CODE (base1) == MEM_REF)
16952 off1 += mem_ref_offset (base1).force_shwi ();
16953 base1 = TREE_OPERAND (base1, 0);
16955 if (base0 == NULL_TREE || base1 == NULL_TREE)
16956 return 2;
16958 int equal = 2;
16959 /* Punt in GENERIC on variables with value expressions;
16960 the value expressions might point to fields/elements
16961 of other vars etc. */
16962 if (generic
16963 && ((VAR_P (base0) && DECL_HAS_VALUE_EXPR_P (base0))
16964 || (VAR_P (base1) && DECL_HAS_VALUE_EXPR_P (base1))))
16965 return 2;
16966 else if (decl_in_symtab_p (base0) && decl_in_symtab_p (base1))
16968 symtab_node *node0 = symtab_node::get_create (base0);
16969 symtab_node *node1 = symtab_node::get_create (base1);
16970 equal = node0->equal_address_to (node1);
16972 else if ((DECL_P (base0)
16973 || TREE_CODE (base0) == SSA_NAME
16974 || TREE_CODE (base0) == STRING_CST)
16975 && (DECL_P (base1)
16976 || TREE_CODE (base1) == SSA_NAME
16977 || TREE_CODE (base1) == STRING_CST))
16978 equal = (base0 == base1);
16979 /* Assume different STRING_CSTs with the same content will be
16980 merged. */
16981 if (equal == 0
16982 && TREE_CODE (base0) == STRING_CST
16983 && TREE_CODE (base1) == STRING_CST
16984 && TREE_STRING_LENGTH (base0) == TREE_STRING_LENGTH (base1)
16985 && memcmp (TREE_STRING_POINTER (base0), TREE_STRING_POINTER (base1),
16986 TREE_STRING_LENGTH (base0)) == 0)
16987 equal = 1;
16988 if (equal == 1)
16990 if (code == EQ_EXPR
16991 || code == NE_EXPR
16992 /* If the offsets are equal we can ignore overflow. */
16993 || known_eq (off0, off1)
16994 || TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (op0))
16995 /* Or if we compare using pointers to decls or strings. */
16996 || (POINTER_TYPE_P (type)
16997 && (DECL_P (base0) || TREE_CODE (base0) == STRING_CST)))
16998 return 1;
16999 return 2;
17001 if (equal != 0)
17002 return equal;
17003 if (code != EQ_EXPR && code != NE_EXPR)
17004 return 2;
17006 /* At this point we know (or assume) the two pointers point at
17007 different objects. */
17008 HOST_WIDE_INT ioff0 = -1, ioff1 = -1;
17009 off0.is_constant (&ioff0);
17010 off1.is_constant (&ioff1);
17011 /* Punt on non-zero offsets from functions. */
17012 if ((TREE_CODE (base0) == FUNCTION_DECL && ioff0)
17013 || (TREE_CODE (base1) == FUNCTION_DECL && ioff1))
17014 return 2;
17015 /* Or if the bases are neither decls nor string literals. */
17016 if (!DECL_P (base0) && TREE_CODE (base0) != STRING_CST)
17017 return 2;
17018 if (!DECL_P (base1) && TREE_CODE (base1) != STRING_CST)
17019 return 2;
17020 /* For initializers, assume addresses of different functions are
17021 different. */
17022 if (folding_initializer
17023 && TREE_CODE (base0) == FUNCTION_DECL
17024 && TREE_CODE (base1) == FUNCTION_DECL)
17025 return 0;
17027 /* Compute whether one address points to the start of one
17028 object and another one to the end of another one. */
17029 poly_int64 size0 = 0, size1 = 0;
17030 if (TREE_CODE (base0) == STRING_CST)
17032 if (ioff0 < 0 || ioff0 > TREE_STRING_LENGTH (base0))
17033 equal = 2;
17034 else
17035 size0 = TREE_STRING_LENGTH (base0);
17037 else if (TREE_CODE (base0) == FUNCTION_DECL)
17038 size0 = 1;
17039 else
17041 tree sz0 = DECL_SIZE_UNIT (base0);
17042 if (!tree_fits_poly_int64_p (sz0))
17043 equal = 2;
17044 else
17045 size0 = tree_to_poly_int64 (sz0);
17047 if (TREE_CODE (base1) == STRING_CST)
17049 if (ioff1 < 0 || ioff1 > TREE_STRING_LENGTH (base1))
17050 equal = 2;
17051 else
17052 size1 = TREE_STRING_LENGTH (base1);
17054 else if (TREE_CODE (base1) == FUNCTION_DECL)
17055 size1 = 1;
17056 else
17058 tree sz1 = DECL_SIZE_UNIT (base1);
17059 if (!tree_fits_poly_int64_p (sz1))
17060 equal = 2;
17061 else
17062 size1 = tree_to_poly_int64 (sz1);
17064 if (equal == 0)
17066 /* If one offset is pointing (or could be) to the beginning of one
17067 object and the other is pointing to one past the last byte of the
17068 other object, punt. */
17069 if (maybe_eq (off0, 0) && maybe_eq (off1, size1))
17070 equal = 2;
17071 else if (maybe_eq (off1, 0) && maybe_eq (off0, size0))
17072 equal = 2;
17073 /* If both offsets are the same, there are some cases we know that are
17074 ok. Either if we know they aren't zero, or if we know both sizes
17075 are no zero. */
17076 if (equal == 2
17077 && known_eq (off0, off1)
17078 && (known_ne (off0, 0)
17079 || (known_ne (size0, 0) && known_ne (size1, 0))))
17080 equal = 0;
17083 /* At this point, equal is 2 if either one or both pointers are out of
17084 bounds of their object, or one points to start of its object and the
17085 other points to end of its object. This is unspecified behavior
17086 e.g. in C++. Otherwise equal is 0. */
17087 if (folding_cxx_constexpr && equal)
17088 return equal;
17090 /* When both pointers point to string literals, even when equal is 0,
17091 due to tail merging of string literals the pointers might be the same. */
17092 if (TREE_CODE (base0) == STRING_CST && TREE_CODE (base1) == STRING_CST)
17094 if (ioff0 < 0
17095 || ioff1 < 0
17096 || ioff0 > TREE_STRING_LENGTH (base0)
17097 || ioff1 > TREE_STRING_LENGTH (base1))
17098 return 2;
17100 /* If the bytes in the string literals starting at the pointers
17101 differ, the pointers need to be different. */
17102 if (memcmp (TREE_STRING_POINTER (base0) + ioff0,
17103 TREE_STRING_POINTER (base1) + ioff1,
17104 MIN (TREE_STRING_LENGTH (base0) - ioff0,
17105 TREE_STRING_LENGTH (base1) - ioff1)) == 0)
17107 HOST_WIDE_INT ioffmin = MIN (ioff0, ioff1);
17108 if (memcmp (TREE_STRING_POINTER (base0) + ioff0 - ioffmin,
17109 TREE_STRING_POINTER (base1) + ioff1 - ioffmin,
17110 ioffmin) == 0)
17111 /* If even the bytes in the string literal before the
17112 pointers are the same, the string literals could be
17113 tail merged. */
17114 return 2;
17116 return 0;
17119 if (folding_cxx_constexpr)
17120 return 0;
17122 /* If this is a pointer comparison, ignore for now even
17123 valid equalities where one pointer is the offset zero
17124 of one object and the other to one past end of another one. */
17125 if (!INTEGRAL_TYPE_P (type))
17126 return 0;
17128 /* Assume that string literals can't be adjacent to variables
17129 (automatic or global). */
17130 if (TREE_CODE (base0) == STRING_CST || TREE_CODE (base1) == STRING_CST)
17131 return 0;
17133 /* Assume that automatic variables can't be adjacent to global
17134 variables. */
17135 if (is_global_var (base0) != is_global_var (base1))
17136 return 0;
17138 return equal;
17141 /* Return the single non-zero element of a CONSTRUCTOR or NULL_TREE. */
17142 tree
17143 ctor_single_nonzero_element (const_tree t)
17145 unsigned HOST_WIDE_INT idx;
17146 constructor_elt *ce;
17147 tree elt = NULL_TREE;
17149 if (TREE_CODE (t) != CONSTRUCTOR)
17150 return NULL_TREE;
17151 for (idx = 0; vec_safe_iterate (CONSTRUCTOR_ELTS (t), idx, &ce); idx++)
17152 if (!integer_zerop (ce->value) && !real_zerop (ce->value))
17154 if (elt)
17155 return NULL_TREE;
17156 elt = ce->value;
17158 return elt;
17161 #if CHECKING_P
17163 namespace selftest {
17165 /* Helper functions for writing tests of folding trees. */
17167 /* Verify that the binary op (LHS CODE RHS) folds to CONSTANT. */
17169 static void
17170 assert_binop_folds_to_const (tree lhs, enum tree_code code, tree rhs,
17171 tree constant)
17173 ASSERT_EQ (constant, fold_build2 (code, TREE_TYPE (lhs), lhs, rhs));
17176 /* Verify that the binary op (LHS CODE RHS) folds to an NON_LVALUE_EXPR
17177 wrapping WRAPPED_EXPR. */
17179 static void
17180 assert_binop_folds_to_nonlvalue (tree lhs, enum tree_code code, tree rhs,
17181 tree wrapped_expr)
17183 tree result = fold_build2 (code, TREE_TYPE (lhs), lhs, rhs);
17184 ASSERT_NE (wrapped_expr, result);
17185 ASSERT_EQ (NON_LVALUE_EXPR, TREE_CODE (result));
17186 ASSERT_EQ (wrapped_expr, TREE_OPERAND (result, 0));
17189 /* Verify that various arithmetic binary operations are folded
17190 correctly. */
17192 static void
17193 test_arithmetic_folding ()
17195 tree type = integer_type_node;
17196 tree x = create_tmp_var_raw (type, "x");
17197 tree zero = build_zero_cst (type);
17198 tree one = build_int_cst (type, 1);
17200 /* Addition. */
17201 /* 1 <-- (0 + 1) */
17202 assert_binop_folds_to_const (zero, PLUS_EXPR, one,
17203 one);
17204 assert_binop_folds_to_const (one, PLUS_EXPR, zero,
17205 one);
17207 /* (nonlvalue)x <-- (x + 0) */
17208 assert_binop_folds_to_nonlvalue (x, PLUS_EXPR, zero,
17211 /* Subtraction. */
17212 /* 0 <-- (x - x) */
17213 assert_binop_folds_to_const (x, MINUS_EXPR, x,
17214 zero);
17215 assert_binop_folds_to_nonlvalue (x, MINUS_EXPR, zero,
17218 /* Multiplication. */
17219 /* 0 <-- (x * 0) */
17220 assert_binop_folds_to_const (x, MULT_EXPR, zero,
17221 zero);
17223 /* (nonlvalue)x <-- (x * 1) */
17224 assert_binop_folds_to_nonlvalue (x, MULT_EXPR, one,
17228 namespace test_fold_vec_perm_cst {
17230 /* Build a VECTOR_CST corresponding to VMODE, and has
17231 encoding given by NPATTERNS, NELTS_PER_PATTERN and STEP.
17232 Fill it with randomized elements, using rand() % THRESHOLD. */
17234 static tree
17235 build_vec_cst_rand (machine_mode vmode, unsigned npatterns,
17236 unsigned nelts_per_pattern,
17237 int step = 0, bool natural_stepped = false,
17238 int threshold = 100)
17240 tree inner_type = lang_hooks.types.type_for_mode (GET_MODE_INNER (vmode), 1);
17241 tree vectype = build_vector_type_for_mode (inner_type, vmode);
17242 tree_vector_builder builder (vectype, npatterns, nelts_per_pattern);
17244 // Fill a0 for each pattern
17245 for (unsigned i = 0; i < npatterns; i++)
17246 builder.quick_push (build_int_cst (inner_type, rand () % threshold));
17248 if (nelts_per_pattern == 1)
17249 return builder.build ();
17251 // Fill a1 for each pattern
17252 for (unsigned i = 0; i < npatterns; i++)
17254 tree a1;
17255 if (natural_stepped)
17257 tree a0 = builder[i];
17258 wide_int a0_val = wi::to_wide (a0);
17259 wide_int a1_val = a0_val + step;
17260 a1 = wide_int_to_tree (inner_type, a1_val);
17262 else
17263 a1 = build_int_cst (inner_type, rand () % threshold);
17264 builder.quick_push (a1);
17266 if (nelts_per_pattern == 2)
17267 return builder.build ();
17269 for (unsigned i = npatterns * 2; i < npatterns * nelts_per_pattern; i++)
17271 tree prev_elem = builder[i - npatterns];
17272 wide_int prev_elem_val = wi::to_wide (prev_elem);
17273 wide_int val = prev_elem_val + step;
17274 builder.quick_push (wide_int_to_tree (inner_type, val));
17277 return builder.build ();
17280 /* Validate result of VEC_PERM_EXPR folding for the unit-tests below,
17281 when result is VLA. */
17283 static void
17284 validate_res (unsigned npatterns, unsigned nelts_per_pattern,
17285 tree res, tree *expected_res)
17287 /* Actual npatterns and encoded_elts in res may be less than expected due
17288 to canonicalization. */
17289 ASSERT_TRUE (res != NULL_TREE);
17290 ASSERT_TRUE (VECTOR_CST_NPATTERNS (res) <= npatterns);
17291 ASSERT_TRUE (vector_cst_encoded_nelts (res) <= npatterns * nelts_per_pattern);
17293 for (unsigned i = 0; i < npatterns * nelts_per_pattern; i++)
17294 ASSERT_TRUE (operand_equal_p (VECTOR_CST_ELT (res, i), expected_res[i], 0));
17297 /* Validate result of VEC_PERM_EXPR folding for the unit-tests below,
17298 when the result is VLS. */
17300 static void
17301 validate_res_vls (tree res, tree *expected_res, unsigned expected_nelts)
17303 ASSERT_TRUE (known_eq (VECTOR_CST_NELTS (res), expected_nelts));
17304 for (unsigned i = 0; i < expected_nelts; i++)
17305 ASSERT_TRUE (operand_equal_p (VECTOR_CST_ELT (res, i), expected_res[i], 0));
17308 /* Helper routine to push multiple elements into BUILDER. */
17309 template<unsigned N>
17310 static void builder_push_elems (vec_perm_builder& builder,
17311 poly_uint64 (&elems)[N])
17313 for (unsigned i = 0; i < N; i++)
17314 builder.quick_push (elems[i]);
17317 #define ARG0(index) vector_cst_elt (arg0, index)
17318 #define ARG1(index) vector_cst_elt (arg1, index)
17320 /* Test cases where result is VNx4SI and input vectors are V4SI. */
17322 static void
17323 test_vnx4si_v4si (machine_mode vnx4si_mode, machine_mode v4si_mode)
17325 for (int i = 0; i < 10; i++)
17327 /* Case 1:
17328 sel = { 0, 4, 1, 5, ... }
17329 res = { arg[0], arg1[0], arg0[1], arg1[1], ...} // (4, 1) */
17331 tree arg0 = build_vec_cst_rand (v4si_mode, 4, 1, 0);
17332 tree arg1 = build_vec_cst_rand (v4si_mode, 4, 1, 0);
17334 tree inner_type
17335 = lang_hooks.types.type_for_mode (GET_MODE_INNER (vnx4si_mode), 1);
17336 tree res_type = build_vector_type_for_mode (inner_type, vnx4si_mode);
17338 poly_uint64 res_len = TYPE_VECTOR_SUBPARTS (res_type);
17339 vec_perm_builder builder (res_len, 4, 1);
17340 poly_uint64 mask_elems[] = { 0, 4, 1, 5 };
17341 builder_push_elems (builder, mask_elems);
17343 vec_perm_indices sel (builder, 2, res_len);
17344 tree res = fold_vec_perm_cst (res_type, arg0, arg1, sel);
17346 tree expected_res[] = { ARG0(0), ARG1(0), ARG0(1), ARG1(1) };
17347 validate_res (4, 1, res, expected_res);
17350 /* Case 2: Same as case 1, but contains an out of bounds access which
17351 should wrap around.
17352 sel = {0, 8, 4, 12, ...} (4, 1)
17353 res = { arg0[0], arg0[0], arg1[0], arg1[0], ... } (4, 1). */
17355 tree arg0 = build_vec_cst_rand (v4si_mode, 4, 1, 0);
17356 tree arg1 = build_vec_cst_rand (v4si_mode, 4, 1, 0);
17358 tree inner_type
17359 = lang_hooks.types.type_for_mode (GET_MODE_INNER (vnx4si_mode), 1);
17360 tree res_type = build_vector_type_for_mode (inner_type, vnx4si_mode);
17362 poly_uint64 res_len = TYPE_VECTOR_SUBPARTS (res_type);
17363 vec_perm_builder builder (res_len, 4, 1);
17364 poly_uint64 mask_elems[] = { 0, 8, 4, 12 };
17365 builder_push_elems (builder, mask_elems);
17367 vec_perm_indices sel (builder, 2, res_len);
17368 tree res = fold_vec_perm_cst (res_type, arg0, arg1, sel);
17370 tree expected_res[] = { ARG0(0), ARG0(0), ARG1(0), ARG1(0) };
17371 validate_res (4, 1, res, expected_res);
17376 /* Test cases where result is V4SI and input vectors are VNx4SI. */
17378 static void
17379 test_v4si_vnx4si (machine_mode v4si_mode, machine_mode vnx4si_mode)
17381 for (int i = 0; i < 10; i++)
17383 /* Case 1:
17384 sel = { 0, 1, 2, 3}
17385 res = { arg0[0], arg0[1], arg0[2], arg0[3] }. */
17387 tree arg0 = build_vec_cst_rand (vnx4si_mode, 4, 1);
17388 tree arg1 = build_vec_cst_rand (vnx4si_mode, 4, 1);
17390 tree inner_type
17391 = lang_hooks.types.type_for_mode (GET_MODE_INNER (v4si_mode), 1);
17392 tree res_type = build_vector_type_for_mode (inner_type, v4si_mode);
17394 poly_uint64 res_len = TYPE_VECTOR_SUBPARTS (res_type);
17395 vec_perm_builder builder (res_len, 4, 1);
17396 poly_uint64 mask_elems[] = {0, 1, 2, 3};
17397 builder_push_elems (builder, mask_elems);
17399 vec_perm_indices sel (builder, 2, res_len);
17400 tree res = fold_vec_perm_cst (res_type, arg0, arg1, sel);
17402 tree expected_res[] = { ARG0(0), ARG0(1), ARG0(2), ARG0(3) };
17403 validate_res_vls (res, expected_res, 4);
17406 /* Case 2: Same as Case 1, but crossing input vector.
17407 sel = {0, 2, 4, 6}
17408 In this case,the index 4 is ambiguous since len = 4 + 4x.
17409 Since we cannot determine, which vector to choose from during
17410 compile time, should return NULL_TREE. */
17412 tree arg0 = build_vec_cst_rand (vnx4si_mode, 4, 1);
17413 tree arg1 = build_vec_cst_rand (vnx4si_mode, 4, 1);
17415 tree inner_type
17416 = lang_hooks.types.type_for_mode (GET_MODE_INNER (v4si_mode), 1);
17417 tree res_type = build_vector_type_for_mode (inner_type, v4si_mode);
17419 poly_uint64 res_len = TYPE_VECTOR_SUBPARTS (res_type);
17420 vec_perm_builder builder (res_len, 4, 1);
17421 poly_uint64 mask_elems[] = {0, 2, 4, 6};
17422 builder_push_elems (builder, mask_elems);
17424 vec_perm_indices sel (builder, 2, res_len);
17425 const char *reason;
17426 tree res = fold_vec_perm_cst (res_type, arg0, arg1, sel, &reason);
17428 ASSERT_TRUE (res == NULL_TREE);
17429 ASSERT_TRUE (!strcmp (reason, "cannot divide selector element by arg len"));
17434 /* Test all input vectors. */
17436 static void
17437 test_all_nunits (machine_mode vmode)
17439 /* Test with 10 different inputs. */
17440 for (int i = 0; i < 10; i++)
17442 tree arg0 = build_vec_cst_rand (vmode, 1, 3, 1);
17443 tree arg1 = build_vec_cst_rand (vmode, 1, 3, 1);
17444 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17446 /* Case 1: mask = {0, ...} // (1, 1)
17447 res = { arg0[0], ... } // (1, 1) */
17449 vec_perm_builder builder (len, 1, 1);
17450 builder.quick_push (0);
17451 vec_perm_indices sel (builder, 2, len);
17452 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17453 tree expected_res[] = { ARG0(0) };
17454 validate_res (1, 1, res, expected_res);
17457 /* Case 2: mask = {len, ...} // (1, 1)
17458 res = { arg1[0], ... } // (1, 1) */
17460 vec_perm_builder builder (len, 1, 1);
17461 builder.quick_push (len);
17462 vec_perm_indices sel (builder, 2, len);
17463 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17465 tree expected_res[] = { ARG1(0) };
17466 validate_res (1, 1, res, expected_res);
17471 /* Test all vectors which contain at-least 2 elements. */
17473 static void
17474 test_nunits_min_2 (machine_mode vmode)
17476 for (int i = 0; i < 10; i++)
17478 /* Case 1: mask = { 0, len, ... } // (2, 1)
17479 res = { arg0[0], arg1[0], ... } // (2, 1) */
17481 tree arg0 = build_vec_cst_rand (vmode, 1, 3, 1);
17482 tree arg1 = build_vec_cst_rand (vmode, 1, 3, 1);
17483 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17485 vec_perm_builder builder (len, 2, 1);
17486 poly_uint64 mask_elems[] = { 0, len };
17487 builder_push_elems (builder, mask_elems);
17489 vec_perm_indices sel (builder, 2, len);
17490 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17492 tree expected_res[] = { ARG0(0), ARG1(0) };
17493 validate_res (2, 1, res, expected_res);
17496 /* Case 2: mask = { 0, len, 1, len+1, ... } // (2, 2)
17497 res = { arg0[0], arg1[0], arg0[1], arg1[1], ... } // (2, 2) */
17499 tree arg0 = build_vec_cst_rand (vmode, 1, 3, 1);
17500 tree arg1 = build_vec_cst_rand (vmode, 1, 3, 1);
17501 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17503 vec_perm_builder builder (len, 2, 2);
17504 poly_uint64 mask_elems[] = { 0, len, 1, len + 1 };
17505 builder_push_elems (builder, mask_elems);
17507 vec_perm_indices sel (builder, 2, len);
17508 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17510 tree expected_res[] = { ARG0(0), ARG1(0), ARG0(1), ARG1(1) };
17511 validate_res (2, 2, res, expected_res);
17514 /* Case 4: mask = {0, 0, 1, ...} // (1, 3)
17515 Test that the stepped sequence of the pattern selects from
17516 same input pattern. Since input vectors have npatterns = 2,
17517 and step (a2 - a1) = 1, step is not a multiple of npatterns
17518 in input vector. So return NULL_TREE. */
17520 tree arg0 = build_vec_cst_rand (vmode, 2, 3, 1, true);
17521 tree arg1 = build_vec_cst_rand (vmode, 2, 3, 1);
17522 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17524 vec_perm_builder builder (len, 1, 3);
17525 poly_uint64 mask_elems[] = { 0, 0, 1 };
17526 builder_push_elems (builder, mask_elems);
17528 vec_perm_indices sel (builder, 2, len);
17529 const char *reason;
17530 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel,
17531 &reason);
17532 ASSERT_TRUE (res == NULL_TREE);
17533 ASSERT_TRUE (!strcmp (reason, "step is not multiple of npatterns"));
17536 /* Case 5: mask = {len, 0, 1, ...} // (1, 3)
17537 Test that stepped sequence of the pattern selects from arg0.
17538 res = { arg1[0], arg0[0], arg0[1], ... } // (1, 3) */
17540 tree arg0 = build_vec_cst_rand (vmode, 1, 3, 1, true);
17541 tree arg1 = build_vec_cst_rand (vmode, 1, 3, 1);
17542 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17544 vec_perm_builder builder (len, 1, 3);
17545 poly_uint64 mask_elems[] = { len, 0, 1 };
17546 builder_push_elems (builder, mask_elems);
17548 vec_perm_indices sel (builder, 2, len);
17549 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17551 tree expected_res[] = { ARG1(0), ARG0(0), ARG0(1) };
17552 validate_res (1, 3, res, expected_res);
17555 /* Case 6: PR111648 - a1 chooses base element from input vector arg.
17556 In this case ensure that arg has a natural stepped sequence
17557 to preserve arg's encoding.
17559 As a concrete example, consider:
17560 arg0: { -16, -9, -10, ... } // (1, 3)
17561 arg1: { -12, -5, -6, ... } // (1, 3)
17562 sel = { 0, len, len + 1, ... } // (1, 3)
17564 This will create res with following encoding:
17565 res = { arg0[0], arg1[0], arg1[1], ... } // (1, 3)
17566 = { -16, -12, -5, ... }
17568 The step in above encoding would be: (-5) - (-12) = 7
17569 And hence res[3] would be computed as -5 + 7 = 2.
17570 instead of arg1[2], ie, -6.
17571 Ensure that valid_mask_for_fold_vec_perm_cst returns false
17572 for this case. */
17574 tree arg0 = build_vec_cst_rand (vmode, 1, 3, 1);
17575 tree arg1 = build_vec_cst_rand (vmode, 1, 3, 1);
17576 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17578 vec_perm_builder builder (len, 1, 3);
17579 poly_uint64 mask_elems[] = { 0, len, len+1 };
17580 builder_push_elems (builder, mask_elems);
17582 vec_perm_indices sel (builder, 2, len);
17583 const char *reason;
17584 /* FIXME: It may happen that build_vec_cst_rand may build a natural
17585 stepped pattern, even if we didn't explicitly tell it to. So folding
17586 may not always fail, but if it does, ensure that's because arg1 does
17587 not have a natural stepped sequence (and not due to other reason) */
17588 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel, &reason);
17589 if (res == NULL_TREE)
17590 ASSERT_TRUE (!strcmp (reason, "not a natural stepped sequence"));
17593 /* Case 7: Same as Case 6, except that arg1 contains natural stepped
17594 sequence and thus folding should be valid for this case. */
17596 tree arg0 = build_vec_cst_rand (vmode, 1, 3, 1);
17597 tree arg1 = build_vec_cst_rand (vmode, 1, 3, 1, true);
17598 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17600 vec_perm_builder builder (len, 1, 3);
17601 poly_uint64 mask_elems[] = { 0, len, len+1 };
17602 builder_push_elems (builder, mask_elems);
17604 vec_perm_indices sel (builder, 2, len);
17605 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17607 tree expected_res[] = { ARG0(0), ARG1(0), ARG1(1) };
17608 validate_res (1, 3, res, expected_res);
17611 /* Case 8: Same as aarch64/sve/slp_3.c:
17612 arg0, arg1 are dup vectors.
17613 sel = { 0, len, 1, len+1, 2, len+2, ... } // (2, 3)
17614 So res = { arg0[0], arg1[0], ... } // (2, 1)
17616 In this case, since the input vectors are dup, only the first two
17617 elements per pattern in sel are considered significant. */
17619 tree arg0 = build_vec_cst_rand (vmode, 1, 1);
17620 tree arg1 = build_vec_cst_rand (vmode, 1, 1);
17621 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17623 vec_perm_builder builder (len, 2, 3);
17624 poly_uint64 mask_elems[] = { 0, len, 1, len + 1, 2, len + 2 };
17625 builder_push_elems (builder, mask_elems);
17627 vec_perm_indices sel (builder, 2, len);
17628 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17630 tree expected_res[] = { ARG0(0), ARG1(0) };
17631 validate_res (2, 1, res, expected_res);
17636 /* Test all vectors which contain at-least 4 elements. */
17638 static void
17639 test_nunits_min_4 (machine_mode vmode)
17641 for (int i = 0; i < 10; i++)
17643 /* Case 1: mask = { 0, len, 1, len+1, ... } // (4, 1)
17644 res: { arg0[0], arg1[0], arg0[1], arg1[1], ... } // (4, 1) */
17646 tree arg0 = build_vec_cst_rand (vmode, 1, 3, 1);
17647 tree arg1 = build_vec_cst_rand (vmode, 1, 3, 1);
17648 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17650 vec_perm_builder builder (len, 4, 1);
17651 poly_uint64 mask_elems[] = { 0, len, 1, len + 1 };
17652 builder_push_elems (builder, mask_elems);
17654 vec_perm_indices sel (builder, 2, len);
17655 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17657 tree expected_res[] = { ARG0(0), ARG1(0), ARG0(1), ARG1(1) };
17658 validate_res (4, 1, res, expected_res);
17661 /* Case 2: sel = {0, 1, 2, ...} // (1, 3)
17662 res: { arg0[0], arg0[1], arg0[2], ... } // (1, 3) */
17664 tree arg0 = build_vec_cst_rand (vmode, 1, 3, 2);
17665 tree arg1 = build_vec_cst_rand (vmode, 1, 3, 2);
17666 poly_uint64 arg0_len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17668 vec_perm_builder builder (arg0_len, 1, 3);
17669 poly_uint64 mask_elems[] = {0, 1, 2};
17670 builder_push_elems (builder, mask_elems);
17672 vec_perm_indices sel (builder, 2, arg0_len);
17673 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17674 tree expected_res[] = { ARG0(0), ARG0(1), ARG0(2) };
17675 validate_res (1, 3, res, expected_res);
17678 /* Case 3: sel = {len, len+1, len+2, ...} // (1, 3)
17679 res: { arg1[0], arg1[1], arg1[2], ... } // (1, 3) */
17681 tree arg0 = build_vec_cst_rand (vmode, 1, 3, 2);
17682 tree arg1 = build_vec_cst_rand (vmode, 1, 3, 2);
17683 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17685 vec_perm_builder builder (len, 1, 3);
17686 poly_uint64 mask_elems[] = {len, len + 1, len + 2};
17687 builder_push_elems (builder, mask_elems);
17689 vec_perm_indices sel (builder, 2, len);
17690 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17691 tree expected_res[] = { ARG1(0), ARG1(1), ARG1(2) };
17692 validate_res (1, 3, res, expected_res);
17695 /* Case 4:
17696 sel = { len, 0, 2, ... } // (1, 3)
17697 This should return NULL because we cross the input vectors.
17698 Because,
17699 Let's assume len = C + Cx
17700 a1 = 0
17701 S = 2
17702 esel = arg0_len / sel_npatterns = C + Cx
17703 ae = 0 + (esel - 2) * S
17704 = 0 + (C + Cx - 2) * 2
17705 = 2(C-2) + 2Cx
17707 For C >= 4:
17708 Let q1 = a1 / arg0_len = 0 / (C + Cx) = 0
17709 Let qe = ae / arg0_len = (2(C-2) + 2Cx) / (C + Cx) = 1
17710 Since q1 != qe, we cross input vectors.
17711 So return NULL_TREE. */
17713 tree arg0 = build_vec_cst_rand (vmode, 1, 3, 2);
17714 tree arg1 = build_vec_cst_rand (vmode, 1, 3, 2);
17715 poly_uint64 arg0_len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17717 vec_perm_builder builder (arg0_len, 1, 3);
17718 poly_uint64 mask_elems[] = { arg0_len, 0, 2 };
17719 builder_push_elems (builder, mask_elems);
17721 vec_perm_indices sel (builder, 2, arg0_len);
17722 const char *reason;
17723 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel, &reason);
17724 ASSERT_TRUE (res == NULL_TREE);
17725 ASSERT_TRUE (!strcmp (reason, "crossed input vectors"));
17728 /* Case 5: npatterns(arg0) = 4 > npatterns(sel) = 2
17729 mask = { 0, len, 1, len + 1, ...} // (2, 2)
17730 res = { arg0[0], arg1[0], arg0[1], arg1[1], ... } // (2, 2)
17732 Note that fold_vec_perm_cst will set
17733 res_npatterns = max(4, max(4, 2)) = 4
17734 However after canonicalizing, we will end up with shape (2, 2). */
17736 tree arg0 = build_vec_cst_rand (vmode, 4, 1);
17737 tree arg1 = build_vec_cst_rand (vmode, 4, 1);
17738 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17740 vec_perm_builder builder (len, 2, 2);
17741 poly_uint64 mask_elems[] = { 0, len, 1, len + 1 };
17742 builder_push_elems (builder, mask_elems);
17744 vec_perm_indices sel (builder, 2, len);
17745 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17746 tree expected_res[] = { ARG0(0), ARG1(0), ARG0(1), ARG1(1) };
17747 validate_res (2, 2, res, expected_res);
17750 /* Case 6: Test combination in sel, where one pattern is dup and other
17751 is stepped sequence.
17752 sel = { 0, 0, 0, 1, 0, 2, ... } // (2, 3)
17753 res = { arg0[0], arg0[0], arg0[0],
17754 arg0[1], arg0[0], arg0[2], ... } // (2, 3) */
17756 tree arg0 = build_vec_cst_rand (vmode, 1, 3, 1);
17757 tree arg1 = build_vec_cst_rand (vmode, 1, 3, 1);
17758 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17760 vec_perm_builder builder (len, 2, 3);
17761 poly_uint64 mask_elems[] = { 0, 0, 0, 1, 0, 2 };
17762 builder_push_elems (builder, mask_elems);
17764 vec_perm_indices sel (builder, 2, len);
17765 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17767 tree expected_res[] = { ARG0(0), ARG0(0), ARG0(0),
17768 ARG0(1), ARG0(0), ARG0(2) };
17769 validate_res (2, 3, res, expected_res);
17772 /* Case 7: PR111048: Check that we set arg_npatterns correctly,
17773 when arg0, arg1 and sel have different number of patterns.
17774 arg0 is of shape (1, 1)
17775 arg1 is of shape (4, 1)
17776 sel is of shape (2, 3) = {1, len, 2, len+1, 3, len+2, ...}
17778 In this case the pattern: {len, len+1, len+2, ...} chooses arg1.
17779 However,
17780 step = (len+2) - (len+1) = 1
17781 arg_npatterns = VECTOR_CST_NPATTERNS (arg1) = 4
17782 Since step is not a multiple of arg_npatterns,
17783 valid_mask_for_fold_vec_perm_cst should return false,
17784 and thus fold_vec_perm_cst should return NULL_TREE. */
17786 tree arg0 = build_vec_cst_rand (vmode, 1, 1);
17787 tree arg1 = build_vec_cst_rand (vmode, 4, 1);
17788 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17790 vec_perm_builder builder (len, 2, 3);
17791 poly_uint64 mask_elems[] = { 0, len, 1, len + 1, 2, len + 2 };
17792 builder_push_elems (builder, mask_elems);
17794 vec_perm_indices sel (builder, 2, len);
17795 const char *reason;
17796 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel, &reason);
17798 ASSERT_TRUE (res == NULL_TREE);
17799 ASSERT_TRUE (!strcmp (reason, "step is not multiple of npatterns"));
17802 /* Case 8: PR111754: When input vector is not a stepped sequence,
17803 check that the result is not a stepped sequence either, even
17804 if sel has a stepped sequence. */
17806 tree arg0 = build_vec_cst_rand (vmode, 1, 2);
17807 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17809 vec_perm_builder builder (len, 1, 3);
17810 poly_uint64 mask_elems[] = { 0, 1, 2 };
17811 builder_push_elems (builder, mask_elems);
17813 vec_perm_indices sel (builder, 1, len);
17814 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg0, sel);
17816 tree expected_res[] = { ARG0(0), ARG0(1) };
17817 validate_res (sel.encoding ().npatterns (), 2, res, expected_res);
17820 /* Case 9: If sel doesn't contain a stepped sequence,
17821 check that the result has same encoding as sel, irrespective
17822 of shape of input vectors. */
17824 tree arg0 = build_vec_cst_rand (vmode, 1, 3, 1);
17825 tree arg1 = build_vec_cst_rand (vmode, 1, 3, 1);
17826 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17828 vec_perm_builder builder (len, 1, 2);
17829 poly_uint64 mask_elems[] = { 0, len };
17830 builder_push_elems (builder, mask_elems);
17832 vec_perm_indices sel (builder, 2, len);
17833 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17835 tree expected_res[] = { ARG0(0), ARG1(0) };
17836 validate_res (sel.encoding ().npatterns (),
17837 sel.encoding ().nelts_per_pattern (), res, expected_res);
17842 /* Test all vectors which contain at-least 8 elements. */
17844 static void
17845 test_nunits_min_8 (machine_mode vmode)
17847 for (int i = 0; i < 10; i++)
17849 /* Case 1: sel_npatterns (4) > input npatterns (2)
17850 sel: { 0, 0, 1, len, 2, 0, 3, len, 4, 0, 5, len, ...} // (4, 3)
17851 res: { arg0[0], arg0[0], arg0[0], arg1[0],
17852 arg0[2], arg0[0], arg0[3], arg1[0],
17853 arg0[4], arg0[0], arg0[5], arg1[0], ... } // (4, 3) */
17855 tree arg0 = build_vec_cst_rand (vmode, 2, 3, 2);
17856 tree arg1 = build_vec_cst_rand (vmode, 2, 3, 2);
17857 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17859 vec_perm_builder builder(len, 4, 3);
17860 poly_uint64 mask_elems[] = { 0, 0, 1, len, 2, 0, 3, len,
17861 4, 0, 5, len };
17862 builder_push_elems (builder, mask_elems);
17864 vec_perm_indices sel (builder, 2, len);
17865 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel);
17867 tree expected_res[] = { ARG0(0), ARG0(0), ARG0(1), ARG1(0),
17868 ARG0(2), ARG0(0), ARG0(3), ARG1(0),
17869 ARG0(4), ARG0(0), ARG0(5), ARG1(0) };
17870 validate_res (4, 3, res, expected_res);
17875 /* Test vectors for which nunits[0] <= 4. */
17877 static void
17878 test_nunits_max_4 (machine_mode vmode)
17880 /* Case 1: mask = {0, 4, ...} // (1, 2)
17881 This should return NULL_TREE because the index 4 may choose
17882 from either arg0 or arg1 depending on vector length. */
17884 tree arg0 = build_vec_cst_rand (vmode, 1, 3, 1);
17885 tree arg1 = build_vec_cst_rand (vmode, 1, 3, 1);
17886 poly_uint64 len = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
17888 vec_perm_builder builder (len, 1, 2);
17889 poly_uint64 mask_elems[] = {0, 4};
17890 builder_push_elems (builder, mask_elems);
17892 vec_perm_indices sel (builder, 2, len);
17893 const char *reason;
17894 tree res = fold_vec_perm_cst (TREE_TYPE (arg0), arg0, arg1, sel, &reason);
17895 ASSERT_TRUE (res == NULL_TREE);
17896 ASSERT_TRUE (reason != NULL);
17897 ASSERT_TRUE (!strcmp (reason, "cannot divide selector element by arg len"));
17901 #undef ARG0
17902 #undef ARG1
17904 /* Return true if SIZE is of the form C + Cx and C is power of 2. */
17906 static bool
17907 is_simple_vla_size (poly_uint64 size)
17909 if (size.is_constant ()
17910 || !pow2p_hwi (size.coeffs[0]))
17911 return false;
17912 for (unsigned i = 1; i < ARRAY_SIZE (size.coeffs); ++i)
17913 if (size.coeffs[i] != (i <= 1 ? size.coeffs[0] : 0))
17914 return false;
17915 return true;
17918 /* Execute fold_vec_perm_cst unit tests. */
17920 static void
17921 test ()
17923 machine_mode vnx4si_mode = E_VOIDmode;
17924 machine_mode v4si_mode = E_VOIDmode;
17926 machine_mode vmode;
17927 FOR_EACH_MODE_IN_CLASS (vmode, MODE_VECTOR_INT)
17929 /* Obtain modes corresponding to VNx4SI and V4SI,
17930 to call mixed mode tests below.
17931 FIXME: Is there a better way to do this ? */
17932 if (GET_MODE_INNER (vmode) == SImode)
17934 poly_uint64 nunits = GET_MODE_NUNITS (vmode);
17935 if (is_simple_vla_size (nunits)
17936 && nunits.coeffs[0] == 4)
17937 vnx4si_mode = vmode;
17938 else if (known_eq (nunits, poly_uint64 (4)))
17939 v4si_mode = vmode;
17942 if (!is_simple_vla_size (GET_MODE_NUNITS (vmode))
17943 || !targetm.vector_mode_supported_p (vmode))
17944 continue;
17946 poly_uint64 nunits = GET_MODE_NUNITS (vmode);
17947 test_all_nunits (vmode);
17948 if (nunits.coeffs[0] >= 2)
17949 test_nunits_min_2 (vmode);
17950 if (nunits.coeffs[0] >= 4)
17951 test_nunits_min_4 (vmode);
17952 if (nunits.coeffs[0] >= 8)
17953 test_nunits_min_8 (vmode);
17955 if (nunits.coeffs[0] <= 4)
17956 test_nunits_max_4 (vmode);
17959 if (vnx4si_mode != E_VOIDmode && v4si_mode != E_VOIDmode
17960 && targetm.vector_mode_supported_p (vnx4si_mode)
17961 && targetm.vector_mode_supported_p (v4si_mode))
17963 test_vnx4si_v4si (vnx4si_mode, v4si_mode);
17964 test_v4si_vnx4si (v4si_mode, vnx4si_mode);
17967 } // end of test_fold_vec_perm_cst namespace
17969 /* Verify that various binary operations on vectors are folded
17970 correctly. */
17972 static void
17973 test_vector_folding ()
17975 tree inner_type = integer_type_node;
17976 tree type = build_vector_type (inner_type, 4);
17977 tree zero = build_zero_cst (type);
17978 tree one = build_one_cst (type);
17979 tree index = build_index_vector (type, 0, 1);
17981 /* Verify equality tests that return a scalar boolean result. */
17982 tree res_type = boolean_type_node;
17983 ASSERT_FALSE (integer_nonzerop (fold_build2 (EQ_EXPR, res_type, zero, one)));
17984 ASSERT_TRUE (integer_nonzerop (fold_build2 (EQ_EXPR, res_type, zero, zero)));
17985 ASSERT_TRUE (integer_nonzerop (fold_build2 (NE_EXPR, res_type, zero, one)));
17986 ASSERT_FALSE (integer_nonzerop (fold_build2 (NE_EXPR, res_type, one, one)));
17987 ASSERT_TRUE (integer_nonzerop (fold_build2 (NE_EXPR, res_type, index, one)));
17988 ASSERT_FALSE (integer_nonzerop (fold_build2 (EQ_EXPR, res_type,
17989 index, one)));
17990 ASSERT_FALSE (integer_nonzerop (fold_build2 (NE_EXPR, res_type,
17991 index, index)));
17992 ASSERT_TRUE (integer_nonzerop (fold_build2 (EQ_EXPR, res_type,
17993 index, index)));
17996 /* Verify folding of VEC_DUPLICATE_EXPRs. */
17998 static void
17999 test_vec_duplicate_folding ()
18001 scalar_int_mode int_mode = SCALAR_INT_TYPE_MODE (ssizetype);
18002 machine_mode vec_mode = targetm.vectorize.preferred_simd_mode (int_mode);
18003 /* This will be 1 if VEC_MODE isn't a vector mode. */
18004 poly_uint64 nunits = GET_MODE_NUNITS (vec_mode);
18006 tree type = build_vector_type (ssizetype, nunits);
18007 tree dup5_expr = fold_unary (VEC_DUPLICATE_EXPR, type, ssize_int (5));
18008 tree dup5_cst = build_vector_from_val (type, ssize_int (5));
18009 ASSERT_TRUE (operand_equal_p (dup5_expr, dup5_cst, 0));
18012 /* Run all of the selftests within this file. */
18014 void
18015 fold_const_cc_tests ()
18017 test_arithmetic_folding ();
18018 test_vector_folding ();
18019 test_vec_duplicate_folding ();
18020 test_fold_vec_perm_cst::test ();
18023 } // namespace selftest
18025 #endif /* CHECKING_P */