Fix cleanup location for try_finally_expr.
[platform/upstream/linaro-gcc.git] / gcc / fold-const.c
1 /* Fold a constant sub-tree into a single node for C-compiler
2    Copyright (C) 1987-2016 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
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.
10
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.
15
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/>.  */
19
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.  */
27
28 /* The entry points in this file are fold, size_int_wide and size_binop.
29
30    fold takes a tree as argument and returns a simplified tree.
31
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'.
35
36    size_int takes an integer value, and creates a tree constant
37    with type from `sizetype'.
38
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.  */
42
43 #include "config.h"
44 #include "system.h"
45 #include "coretypes.h"
46 #include "backend.h"
47 #include "target.h"
48 #include "rtl.h"
49 #include "tree.h"
50 #include "gimple.h"
51 #include "predict.h"
52 #include "tm_p.h"
53 #include "tree-ssa-operands.h"
54 #include "optabs-query.h"
55 #include "cgraph.h"
56 #include "diagnostic-core.h"
57 #include "flags.h"
58 #include "alias.h"
59 #include "fold-const.h"
60 #include "fold-const-call.h"
61 #include "stor-layout.h"
62 #include "calls.h"
63 #include "tree-iterator.h"
64 #include "expr.h"
65 #include "intl.h"
66 #include "langhooks.h"
67 #include "tree-eh.h"
68 #include "gimplify.h"
69 #include "tree-dfa.h"
70 #include "builtins.h"
71 #include "generic-match.h"
72 #include "gimple-fold.h"
73 #include "params.h"
74 #include "tree-into-ssa.h"
75 #include "md5.h"
76 #include "case-cfn-macros.h"
77 #include "stringpool.h"
78 #include "tree-ssanames.h"
79
80 #ifndef LOAD_EXTEND_OP
81 #define LOAD_EXTEND_OP(M) UNKNOWN
82 #endif
83
84 /* Nonzero if we are folding constants inside an initializer; zero
85    otherwise.  */
86 int folding_initializer = 0;
87
88 /* The following constants represent a bit based encoding of GCC's
89    comparison operators.  This encoding simplifies transformations
90    on relational comparison operators, such as AND and OR.  */
91 enum comparison_code {
92   COMPCODE_FALSE = 0,
93   COMPCODE_LT = 1,
94   COMPCODE_EQ = 2,
95   COMPCODE_LE = 3,
96   COMPCODE_GT = 4,
97   COMPCODE_LTGT = 5,
98   COMPCODE_GE = 6,
99   COMPCODE_ORD = 7,
100   COMPCODE_UNORD = 8,
101   COMPCODE_UNLT = 9,
102   COMPCODE_UNEQ = 10,
103   COMPCODE_UNLE = 11,
104   COMPCODE_UNGT = 12,
105   COMPCODE_NE = 13,
106   COMPCODE_UNGE = 14,
107   COMPCODE_TRUE = 15
108 };
109
110 static bool negate_expr_p (tree);
111 static tree negate_expr (tree);
112 static tree split_tree (location_t, tree, tree, enum tree_code,
113                         tree *, tree *, tree *, int);
114 static tree associate_trees (location_t, tree, tree, enum tree_code, tree);
115 static enum comparison_code comparison_to_compcode (enum tree_code);
116 static enum tree_code compcode_to_comparison (enum comparison_code);
117 static int operand_equal_for_comparison_p (tree, tree, tree);
118 static int twoval_comparison_p (tree, tree *, tree *, int *);
119 static tree eval_subst (location_t, tree, tree, tree, tree, tree);
120 static tree optimize_bit_field_compare (location_t, enum tree_code,
121                                         tree, tree, tree);
122 static int simple_operand_p (const_tree);
123 static bool simple_operand_p_2 (tree);
124 static tree range_binop (enum tree_code, tree, tree, int, tree, int);
125 static tree range_predecessor (tree);
126 static tree range_successor (tree);
127 static tree fold_range_test (location_t, enum tree_code, tree, tree, tree);
128 static tree fold_cond_expr_with_comparison (location_t, tree, tree, tree, tree);
129 static tree unextend (tree, int, int, tree);
130 static tree optimize_minmax_comparison (location_t, enum tree_code,
131                                         tree, tree, tree);
132 static tree extract_muldiv (tree, tree, enum tree_code, tree, bool *);
133 static tree extract_muldiv_1 (tree, tree, enum tree_code, tree, bool *);
134 static tree fold_binary_op_with_conditional_arg (location_t,
135                                                  enum tree_code, tree,
136                                                  tree, tree,
137                                                  tree, tree, int);
138 static tree fold_div_compare (location_t, enum tree_code, tree, tree, tree);
139 static bool reorder_operands_p (const_tree, const_tree);
140 static tree fold_negate_const (tree, tree);
141 static tree fold_not_const (const_tree, tree);
142 static tree fold_relational_const (enum tree_code, tree, tree, tree);
143 static tree fold_convert_const (enum tree_code, tree, tree);
144 static tree fold_view_convert_expr (tree, tree);
145 static bool vec_cst_ctor_to_array (tree, tree *);
146
147
148 /* Return EXPR_LOCATION of T if it is not UNKNOWN_LOCATION.
149    Otherwise, return LOC.  */
150
151 static location_t
152 expr_location_or (tree t, location_t loc)
153 {
154   location_t tloc = EXPR_LOCATION (t);
155   return tloc == UNKNOWN_LOCATION ? loc : tloc;
156 }
157
158 /* Similar to protected_set_expr_location, but never modify x in place,
159    if location can and needs to be set, unshare it.  */
160
161 static inline tree
162 protected_set_expr_location_unshare (tree x, location_t loc)
163 {
164   if (CAN_HAVE_LOCATION_P (x)
165       && EXPR_LOCATION (x) != loc
166       && !(TREE_CODE (x) == SAVE_EXPR
167            || TREE_CODE (x) == TARGET_EXPR
168            || TREE_CODE (x) == BIND_EXPR))
169     {
170       x = copy_node (x);
171       SET_EXPR_LOCATION (x, loc);
172     }
173   return x;
174 }
175 \f
176 /* If ARG2 divides ARG1 with zero remainder, carries out the exact
177    division and returns the quotient.  Otherwise returns
178    NULL_TREE.  */
179
180 tree
181 div_if_zero_remainder (const_tree arg1, const_tree arg2)
182 {
183   widest_int quo;
184
185   if (wi::multiple_of_p (wi::to_widest (arg1), wi::to_widest (arg2),
186                          SIGNED, &quo))
187     return wide_int_to_tree (TREE_TYPE (arg1), quo);
188
189   return NULL_TREE;
190 }
191 \f
192 /* This is nonzero if we should defer warnings about undefined
193    overflow.  This facility exists because these warnings are a
194    special case.  The code to estimate loop iterations does not want
195    to issue any warnings, since it works with expressions which do not
196    occur in user code.  Various bits of cleanup code call fold(), but
197    only use the result if it has certain characteristics (e.g., is a
198    constant); that code only wants to issue a warning if the result is
199    used.  */
200
201 static int fold_deferring_overflow_warnings;
202
203 /* If a warning about undefined overflow is deferred, this is the
204    warning.  Note that this may cause us to turn two warnings into
205    one, but that is fine since it is sufficient to only give one
206    warning per expression.  */
207
208 static const char* fold_deferred_overflow_warning;
209
210 /* If a warning about undefined overflow is deferred, this is the
211    level at which the warning should be emitted.  */
212
213 static enum warn_strict_overflow_code fold_deferred_overflow_code;
214
215 /* Start deferring overflow warnings.  We could use a stack here to
216    permit nested calls, but at present it is not necessary.  */
217
218 void
219 fold_defer_overflow_warnings (void)
220 {
221   ++fold_deferring_overflow_warnings;
222 }
223
224 /* Stop deferring overflow warnings.  If there is a pending warning,
225    and ISSUE is true, then issue the warning if appropriate.  STMT is
226    the statement with which the warning should be associated (used for
227    location information); STMT may be NULL.  CODE is the level of the
228    warning--a warn_strict_overflow_code value.  This function will use
229    the smaller of CODE and the deferred code when deciding whether to
230    issue the warning.  CODE may be zero to mean to always use the
231    deferred code.  */
232
233 void
234 fold_undefer_overflow_warnings (bool issue, const gimple *stmt, int code)
235 {
236   const char *warnmsg;
237   location_t locus;
238
239   gcc_assert (fold_deferring_overflow_warnings > 0);
240   --fold_deferring_overflow_warnings;
241   if (fold_deferring_overflow_warnings > 0)
242     {
243       if (fold_deferred_overflow_warning != NULL
244           && code != 0
245           && code < (int) fold_deferred_overflow_code)
246         fold_deferred_overflow_code = (enum warn_strict_overflow_code) code;
247       return;
248     }
249
250   warnmsg = fold_deferred_overflow_warning;
251   fold_deferred_overflow_warning = NULL;
252
253   if (!issue || warnmsg == NULL)
254     return;
255
256   if (gimple_no_warning_p (stmt))
257     return;
258
259   /* Use the smallest code level when deciding to issue the
260      warning.  */
261   if (code == 0 || code > (int) fold_deferred_overflow_code)
262     code = fold_deferred_overflow_code;
263
264   if (!issue_strict_overflow_warning (code))
265     return;
266
267   if (stmt == NULL)
268     locus = input_location;
269   else
270     locus = gimple_location (stmt);
271   warning_at (locus, OPT_Wstrict_overflow, "%s", warnmsg);
272 }
273
274 /* Stop deferring overflow warnings, ignoring any deferred
275    warnings.  */
276
277 void
278 fold_undefer_and_ignore_overflow_warnings (void)
279 {
280   fold_undefer_overflow_warnings (false, NULL, 0);
281 }
282
283 /* Whether we are deferring overflow warnings.  */
284
285 bool
286 fold_deferring_overflow_warnings_p (void)
287 {
288   return fold_deferring_overflow_warnings > 0;
289 }
290
291 /* This is called when we fold something based on the fact that signed
292    overflow is undefined.  */
293
294 static void
295 fold_overflow_warning (const char* gmsgid, enum warn_strict_overflow_code wc)
296 {
297   if (fold_deferring_overflow_warnings > 0)
298     {
299       if (fold_deferred_overflow_warning == NULL
300           || wc < fold_deferred_overflow_code)
301         {
302           fold_deferred_overflow_warning = gmsgid;
303           fold_deferred_overflow_code = wc;
304         }
305     }
306   else if (issue_strict_overflow_warning (wc))
307     warning (OPT_Wstrict_overflow, gmsgid);
308 }
309 \f
310 /* Return true if the built-in mathematical function specified by CODE
311    is odd, i.e. -f(x) == f(-x).  */
312
313 bool
314 negate_mathfn_p (combined_fn fn)
315 {
316   switch (fn)
317     {
318     CASE_CFN_ASIN:
319     CASE_CFN_ASINH:
320     CASE_CFN_ATAN:
321     CASE_CFN_ATANH:
322     CASE_CFN_CASIN:
323     CASE_CFN_CASINH:
324     CASE_CFN_CATAN:
325     CASE_CFN_CATANH:
326     CASE_CFN_CBRT:
327     CASE_CFN_CPROJ:
328     CASE_CFN_CSIN:
329     CASE_CFN_CSINH:
330     CASE_CFN_CTAN:
331     CASE_CFN_CTANH:
332     CASE_CFN_ERF:
333     CASE_CFN_LLROUND:
334     CASE_CFN_LROUND:
335     CASE_CFN_ROUND:
336     CASE_CFN_SIN:
337     CASE_CFN_SINH:
338     CASE_CFN_TAN:
339     CASE_CFN_TANH:
340     CASE_CFN_TRUNC:
341       return true;
342
343     CASE_CFN_LLRINT:
344     CASE_CFN_LRINT:
345     CASE_CFN_NEARBYINT:
346     CASE_CFN_RINT:
347       return !flag_rounding_math;
348
349     default:
350       break;
351     }
352   return false;
353 }
354
355 /* Check whether we may negate an integer constant T without causing
356    overflow.  */
357
358 bool
359 may_negate_without_overflow_p (const_tree t)
360 {
361   tree type;
362
363   gcc_assert (TREE_CODE (t) == INTEGER_CST);
364
365   type = TREE_TYPE (t);
366   if (TYPE_UNSIGNED (type))
367     return false;
368
369   return !wi::only_sign_bit_p (t);
370 }
371
372 /* Determine whether an expression T can be cheaply negated using
373    the function negate_expr without introducing undefined overflow.  */
374
375 static bool
376 negate_expr_p (tree t)
377 {
378   tree type;
379
380   if (t == 0)
381     return false;
382
383   type = TREE_TYPE (t);
384
385   STRIP_SIGN_NOPS (t);
386   switch (TREE_CODE (t))
387     {
388     case INTEGER_CST:
389       if (INTEGRAL_TYPE_P (type) && TYPE_OVERFLOW_WRAPS (type))
390         return true;
391
392       /* Check that -CST will not overflow type.  */
393       return may_negate_without_overflow_p (t);
394     case BIT_NOT_EXPR:
395       return (INTEGRAL_TYPE_P (type)
396               && TYPE_OVERFLOW_WRAPS (type));
397
398     case FIXED_CST:
399       return true;
400
401     case NEGATE_EXPR:
402       return !TYPE_OVERFLOW_SANITIZED (type);
403
404     case REAL_CST:
405       /* We want to canonicalize to positive real constants.  Pretend
406          that only negative ones can be easily negated.  */
407       return REAL_VALUE_NEGATIVE (TREE_REAL_CST (t));
408
409     case COMPLEX_CST:
410       return negate_expr_p (TREE_REALPART (t))
411              && negate_expr_p (TREE_IMAGPART (t));
412
413     case VECTOR_CST:
414       {
415         if (FLOAT_TYPE_P (TREE_TYPE (type)) || TYPE_OVERFLOW_WRAPS (type))
416           return true;
417
418         int count = TYPE_VECTOR_SUBPARTS (type), i;
419
420         for (i = 0; i < count; i++)
421           if (!negate_expr_p (VECTOR_CST_ELT (t, i)))
422             return false;
423
424         return true;
425       }
426
427     case COMPLEX_EXPR:
428       return negate_expr_p (TREE_OPERAND (t, 0))
429              && negate_expr_p (TREE_OPERAND (t, 1));
430
431     case CONJ_EXPR:
432       return negate_expr_p (TREE_OPERAND (t, 0));
433
434     case PLUS_EXPR:
435       if (HONOR_SIGN_DEPENDENT_ROUNDING (element_mode (type))
436           || HONOR_SIGNED_ZEROS (element_mode (type))
437           || (INTEGRAL_TYPE_P (type)
438               && ! TYPE_OVERFLOW_WRAPS (type)))
439         return false;
440       /* -(A + B) -> (-B) - A.  */
441       if (negate_expr_p (TREE_OPERAND (t, 1))
442           && reorder_operands_p (TREE_OPERAND (t, 0),
443                                  TREE_OPERAND (t, 1)))
444         return true;
445       /* -(A + B) -> (-A) - B.  */
446       return negate_expr_p (TREE_OPERAND (t, 0));
447
448     case MINUS_EXPR:
449       /* We can't turn -(A-B) into B-A when we honor signed zeros.  */
450       return !HONOR_SIGN_DEPENDENT_ROUNDING (element_mode (type))
451              && !HONOR_SIGNED_ZEROS (element_mode (type))
452              && (! INTEGRAL_TYPE_P (type)
453                  || TYPE_OVERFLOW_WRAPS (type))
454              && reorder_operands_p (TREE_OPERAND (t, 0),
455                                     TREE_OPERAND (t, 1));
456
457     case MULT_EXPR:
458       if (TYPE_UNSIGNED (type))
459         break;
460       /* INT_MIN/n * n doesn't overflow while negating one operand it does
461          if n is a (negative) power of two.  */
462       if (INTEGRAL_TYPE_P (TREE_TYPE (t))
463           && ! TYPE_OVERFLOW_WRAPS (TREE_TYPE (t))
464           && ! ((TREE_CODE (TREE_OPERAND (t, 0)) == INTEGER_CST
465                  && wi::popcount (wi::abs (TREE_OPERAND (t, 0))) != 1)
466                 || (TREE_CODE (TREE_OPERAND (t, 1)) == INTEGER_CST
467                     && wi::popcount (wi::abs (TREE_OPERAND (t, 1))) != 1)))
468         break;
469
470       /* Fall through.  */
471
472     case RDIV_EXPR:
473       if (! HONOR_SIGN_DEPENDENT_ROUNDING (element_mode (TREE_TYPE (t))))
474         return negate_expr_p (TREE_OPERAND (t, 1))
475                || negate_expr_p (TREE_OPERAND (t, 0));
476       break;
477
478     case TRUNC_DIV_EXPR:
479     case ROUND_DIV_EXPR:
480     case EXACT_DIV_EXPR:
481       if (TYPE_UNSIGNED (type))
482         break;
483       if (negate_expr_p (TREE_OPERAND (t, 0)))
484         return true;
485       /* In general we can't negate B in A / B, because if A is INT_MIN and
486          B is 1, we may turn this into INT_MIN / -1 which is undefined
487          and actually traps on some architectures.  */
488       if (! INTEGRAL_TYPE_P (TREE_TYPE (t))
489           || TYPE_OVERFLOW_WRAPS (TREE_TYPE (t))
490           || (TREE_CODE (TREE_OPERAND (t, 1)) == INTEGER_CST
491               && ! integer_onep (TREE_OPERAND (t, 1))))
492         return negate_expr_p (TREE_OPERAND (t, 1));
493       break;
494
495     case NOP_EXPR:
496       /* Negate -((double)float) as (double)(-float).  */
497       if (TREE_CODE (type) == REAL_TYPE)
498         {
499           tree tem = strip_float_extensions (t);
500           if (tem != t)
501             return negate_expr_p (tem);
502         }
503       break;
504
505     case CALL_EXPR:
506       /* Negate -f(x) as f(-x).  */
507       if (negate_mathfn_p (get_call_combined_fn (t)))
508         return negate_expr_p (CALL_EXPR_ARG (t, 0));
509       break;
510
511     case RSHIFT_EXPR:
512       /* Optimize -((int)x >> 31) into (unsigned)x >> 31 for int.  */
513       if (TREE_CODE (TREE_OPERAND (t, 1)) == INTEGER_CST)
514         {
515           tree op1 = TREE_OPERAND (t, 1);
516           if (wi::eq_p (op1, TYPE_PRECISION (type) - 1))
517             return true;
518         }
519       break;
520
521     default:
522       break;
523     }
524   return false;
525 }
526
527 /* Given T, an expression, return a folded tree for -T or NULL_TREE, if no
528    simplification is possible.
529    If negate_expr_p would return true for T, NULL_TREE will never be
530    returned.  */
531
532 static tree
533 fold_negate_expr (location_t loc, tree t)
534 {
535   tree type = TREE_TYPE (t);
536   tree tem;
537
538   switch (TREE_CODE (t))
539     {
540     /* Convert - (~A) to A + 1.  */
541     case BIT_NOT_EXPR:
542       if (INTEGRAL_TYPE_P (type))
543         return fold_build2_loc (loc, PLUS_EXPR, type, TREE_OPERAND (t, 0),
544                             build_one_cst (type));
545       break;
546
547     case INTEGER_CST:
548       tem = fold_negate_const (t, type);
549       if (TREE_OVERFLOW (tem) == TREE_OVERFLOW (t)
550           || (ANY_INTEGRAL_TYPE_P (type)
551               && !TYPE_OVERFLOW_TRAPS (type)
552               && TYPE_OVERFLOW_WRAPS (type))
553           || (flag_sanitize & SANITIZE_SI_OVERFLOW) == 0)
554         return tem;
555       break;
556
557     case REAL_CST:
558       tem = fold_negate_const (t, type);
559       return tem;
560
561     case FIXED_CST:
562       tem = fold_negate_const (t, type);
563       return tem;
564
565     case COMPLEX_CST:
566       {
567         tree rpart = fold_negate_expr (loc, TREE_REALPART (t));
568         tree ipart = fold_negate_expr (loc, TREE_IMAGPART (t));
569         if (rpart && ipart)
570           return build_complex (type, rpart, ipart);
571       }
572       break;
573
574     case VECTOR_CST:
575       {
576         int count = TYPE_VECTOR_SUBPARTS (type), i;
577         tree *elts = XALLOCAVEC (tree, count);
578
579         for (i = 0; i < count; i++)
580           {
581             elts[i] = fold_negate_expr (loc, VECTOR_CST_ELT (t, i));
582             if (elts[i] == NULL_TREE)
583               return NULL_TREE;
584           }
585
586         return build_vector (type, elts);
587       }
588
589     case COMPLEX_EXPR:
590       if (negate_expr_p (t))
591         return fold_build2_loc (loc, COMPLEX_EXPR, type,
592                             fold_negate_expr (loc, TREE_OPERAND (t, 0)),
593                             fold_negate_expr (loc, TREE_OPERAND (t, 1)));
594       break;
595
596     case CONJ_EXPR:
597       if (negate_expr_p (t))
598         return fold_build1_loc (loc, CONJ_EXPR, type,
599                             fold_negate_expr (loc, TREE_OPERAND (t, 0)));
600       break;
601
602     case NEGATE_EXPR:
603       if (!TYPE_OVERFLOW_SANITIZED (type))
604         return TREE_OPERAND (t, 0);
605       break;
606
607     case PLUS_EXPR:
608       if (!HONOR_SIGN_DEPENDENT_ROUNDING (element_mode (type))
609           && !HONOR_SIGNED_ZEROS (element_mode (type)))
610         {
611           /* -(A + B) -> (-B) - A.  */
612           if (negate_expr_p (TREE_OPERAND (t, 1))
613               && reorder_operands_p (TREE_OPERAND (t, 0),
614                                      TREE_OPERAND (t, 1)))
615             {
616               tem = negate_expr (TREE_OPERAND (t, 1));
617               return fold_build2_loc (loc, MINUS_EXPR, type,
618                                   tem, TREE_OPERAND (t, 0));
619             }
620
621           /* -(A + B) -> (-A) - B.  */
622           if (negate_expr_p (TREE_OPERAND (t, 0)))
623             {
624               tem = negate_expr (TREE_OPERAND (t, 0));
625               return fold_build2_loc (loc, MINUS_EXPR, type,
626                                   tem, TREE_OPERAND (t, 1));
627             }
628         }
629       break;
630
631     case MINUS_EXPR:
632       /* - (A - B) -> B - A  */
633       if (!HONOR_SIGN_DEPENDENT_ROUNDING (element_mode (type))
634           && !HONOR_SIGNED_ZEROS (element_mode (type))
635           && reorder_operands_p (TREE_OPERAND (t, 0), TREE_OPERAND (t, 1)))
636         return fold_build2_loc (loc, MINUS_EXPR, type,
637                             TREE_OPERAND (t, 1), TREE_OPERAND (t, 0));
638       break;
639
640     case MULT_EXPR:
641       if (TYPE_UNSIGNED (type))
642         break;
643
644       /* Fall through.  */
645
646     case RDIV_EXPR:
647       if (! HONOR_SIGN_DEPENDENT_ROUNDING (element_mode (type)))
648         {
649           tem = TREE_OPERAND (t, 1);
650           if (negate_expr_p (tem))
651             return fold_build2_loc (loc, TREE_CODE (t), type,
652                                 TREE_OPERAND (t, 0), negate_expr (tem));
653           tem = TREE_OPERAND (t, 0);
654           if (negate_expr_p (tem))
655             return fold_build2_loc (loc, TREE_CODE (t), type,
656                                 negate_expr (tem), TREE_OPERAND (t, 1));
657         }
658       break;
659
660     case TRUNC_DIV_EXPR:
661     case ROUND_DIV_EXPR:
662     case EXACT_DIV_EXPR:
663       if (TYPE_UNSIGNED (type))
664         break;
665       if (negate_expr_p (TREE_OPERAND (t, 0)))
666         return fold_build2_loc (loc, TREE_CODE (t), type,
667                                 negate_expr (TREE_OPERAND (t, 0)),
668                                 TREE_OPERAND (t, 1));
669       /* In general we can't negate B in A / B, because if A is INT_MIN and
670          B is 1, we may turn this into INT_MIN / -1 which is undefined
671          and actually traps on some architectures.  */
672       if ((! INTEGRAL_TYPE_P (TREE_TYPE (t))
673            || TYPE_OVERFLOW_WRAPS (TREE_TYPE (t))
674            || (TREE_CODE (TREE_OPERAND (t, 1)) == INTEGER_CST
675                && ! integer_onep (TREE_OPERAND (t, 1))))
676           && negate_expr_p (TREE_OPERAND (t, 1)))
677         return fold_build2_loc (loc, TREE_CODE (t), type,
678                                 TREE_OPERAND (t, 0),
679                                 negate_expr (TREE_OPERAND (t, 1)));
680       break;
681
682     case NOP_EXPR:
683       /* Convert -((double)float) into (double)(-float).  */
684       if (TREE_CODE (type) == REAL_TYPE)
685         {
686           tem = strip_float_extensions (t);
687           if (tem != t && negate_expr_p (tem))
688             return fold_convert_loc (loc, type, negate_expr (tem));
689         }
690       break;
691
692     case CALL_EXPR:
693       /* Negate -f(x) as f(-x).  */
694       if (negate_mathfn_p (get_call_combined_fn (t))
695           && negate_expr_p (CALL_EXPR_ARG (t, 0)))
696         {
697           tree fndecl, arg;
698
699           fndecl = get_callee_fndecl (t);
700           arg = negate_expr (CALL_EXPR_ARG (t, 0));
701           return build_call_expr_loc (loc, fndecl, 1, arg);
702         }
703       break;
704
705     case RSHIFT_EXPR:
706       /* Optimize -((int)x >> 31) into (unsigned)x >> 31 for int.  */
707       if (TREE_CODE (TREE_OPERAND (t, 1)) == INTEGER_CST)
708         {
709           tree op1 = TREE_OPERAND (t, 1);
710           if (wi::eq_p (op1, TYPE_PRECISION (type) - 1))
711             {
712               tree ntype = TYPE_UNSIGNED (type)
713                            ? signed_type_for (type)
714                            : unsigned_type_for (type);
715               tree temp = fold_convert_loc (loc, ntype, TREE_OPERAND (t, 0));
716               temp = fold_build2_loc (loc, RSHIFT_EXPR, ntype, temp, op1);
717               return fold_convert_loc (loc, type, temp);
718             }
719         }
720       break;
721
722     default:
723       break;
724     }
725
726   return NULL_TREE;
727 }
728
729 /* Like fold_negate_expr, but return a NEGATE_EXPR tree, if T can not be
730    negated in a simpler way.  Also allow for T to be NULL_TREE, in which case
731    return NULL_TREE. */
732
733 static tree
734 negate_expr (tree t)
735 {
736   tree type, tem;
737   location_t loc;
738
739   if (t == NULL_TREE)
740     return NULL_TREE;
741
742   loc = EXPR_LOCATION (t);
743   type = TREE_TYPE (t);
744   STRIP_SIGN_NOPS (t);
745
746   tem = fold_negate_expr (loc, t);
747   if (!tem)
748     tem = build1_loc (loc, NEGATE_EXPR, TREE_TYPE (t), t);
749   return fold_convert_loc (loc, type, tem);
750 }
751 \f
752 /* Split a tree IN into a constant, literal and variable parts that could be
753    combined with CODE to make IN.  "constant" means an expression with
754    TREE_CONSTANT but that isn't an actual constant.  CODE must be a
755    commutative arithmetic operation.  Store the constant part into *CONP,
756    the literal in *LITP and return the variable part.  If a part isn't
757    present, set it to null.  If the tree does not decompose in this way,
758    return the entire tree as the variable part and the other parts as null.
759
760    If CODE is PLUS_EXPR we also split trees that use MINUS_EXPR.  In that
761    case, we negate an operand that was subtracted.  Except if it is a
762    literal for which we use *MINUS_LITP instead.
763
764    If NEGATE_P is true, we are negating all of IN, again except a literal
765    for which we use *MINUS_LITP instead.  If a variable part is of pointer
766    type, it is negated after converting to TYPE.  This prevents us from
767    generating illegal MINUS pointer expression.  LOC is the location of
768    the converted variable part.
769
770    If IN is itself a literal or constant, return it as appropriate.
771
772    Note that we do not guarantee that any of the three values will be the
773    same type as IN, but they will have the same signedness and mode.  */
774
775 static tree
776 split_tree (location_t loc, tree in, tree type, enum tree_code code,
777             tree *conp, tree *litp, tree *minus_litp, int negate_p)
778 {
779   tree var = 0;
780
781   *conp = 0;
782   *litp = 0;
783   *minus_litp = 0;
784
785   /* Strip any conversions that don't change the machine mode or signedness.  */
786   STRIP_SIGN_NOPS (in);
787
788   if (TREE_CODE (in) == INTEGER_CST || TREE_CODE (in) == REAL_CST
789       || TREE_CODE (in) == FIXED_CST)
790     *litp = in;
791   else if (TREE_CODE (in) == code
792            || ((! FLOAT_TYPE_P (TREE_TYPE (in)) || flag_associative_math)
793                && ! SAT_FIXED_POINT_TYPE_P (TREE_TYPE (in))
794                /* We can associate addition and subtraction together (even
795                   though the C standard doesn't say so) for integers because
796                   the value is not affected.  For reals, the value might be
797                   affected, so we can't.  */
798                && ((code == PLUS_EXPR && TREE_CODE (in) == MINUS_EXPR)
799                    || (code == MINUS_EXPR && TREE_CODE (in) == PLUS_EXPR))))
800     {
801       tree op0 = TREE_OPERAND (in, 0);
802       tree op1 = TREE_OPERAND (in, 1);
803       int neg1_p = TREE_CODE (in) == MINUS_EXPR;
804       int neg_litp_p = 0, neg_conp_p = 0, neg_var_p = 0;
805
806       /* First see if either of the operands is a literal, then a constant.  */
807       if (TREE_CODE (op0) == INTEGER_CST || TREE_CODE (op0) == REAL_CST
808           || TREE_CODE (op0) == FIXED_CST)
809         *litp = op0, op0 = 0;
810       else if (TREE_CODE (op1) == INTEGER_CST || TREE_CODE (op1) == REAL_CST
811                || TREE_CODE (op1) == FIXED_CST)
812         *litp = op1, neg_litp_p = neg1_p, op1 = 0;
813
814       if (op0 != 0 && TREE_CONSTANT (op0))
815         *conp = op0, op0 = 0;
816       else if (op1 != 0 && TREE_CONSTANT (op1))
817         *conp = op1, neg_conp_p = neg1_p, op1 = 0;
818
819       /* If we haven't dealt with either operand, this is not a case we can
820          decompose.  Otherwise, VAR is either of the ones remaining, if any.  */
821       if (op0 != 0 && op1 != 0)
822         var = in;
823       else if (op0 != 0)
824         var = op0;
825       else
826         var = op1, neg_var_p = neg1_p;
827
828       /* Now do any needed negations.  */
829       if (neg_litp_p)
830         *minus_litp = *litp, *litp = 0;
831       if (neg_conp_p)
832         *conp = negate_expr (*conp);
833       if (neg_var_p && var)
834         {
835           /* Convert to TYPE before negating.  */
836           var = fold_convert_loc (loc, type, var);
837           var = negate_expr (var);
838         }
839     }
840   else if (TREE_CONSTANT (in))
841     *conp = in;
842   else if (TREE_CODE (in) == BIT_NOT_EXPR
843            && code == PLUS_EXPR)
844     {
845       /* -X - 1 is folded to ~X, undo that here.  Do _not_ do this
846          when IN is constant.  */
847       *minus_litp = build_one_cst (TREE_TYPE (in));
848       var = negate_expr (TREE_OPERAND (in, 0));
849     }
850   else
851     var = in;
852
853   if (negate_p)
854     {
855       if (*litp)
856         *minus_litp = *litp, *litp = 0;
857       else if (*minus_litp)
858         *litp = *minus_litp, *minus_litp = 0;
859       *conp = negate_expr (*conp);
860       if (var)
861         {
862           /* Convert to TYPE before negating.  */
863           var = fold_convert_loc (loc, type, var);
864           var = negate_expr (var);
865         }
866     }
867
868   return var;
869 }
870
871 /* Re-associate trees split by the above function.  T1 and T2 are
872    either expressions to associate or null.  Return the new
873    expression, if any.  LOC is the location of the new expression.  If
874    we build an operation, do it in TYPE and with CODE.  */
875
876 static tree
877 associate_trees (location_t loc, tree t1, tree t2, enum tree_code code, tree type)
878 {
879   if (t1 == 0)
880     return t2;
881   else if (t2 == 0)
882     return t1;
883
884   /* If either input is CODE, a PLUS_EXPR, or a MINUS_EXPR, don't
885      try to fold this since we will have infinite recursion.  But do
886      deal with any NEGATE_EXPRs.  */
887   if (TREE_CODE (t1) == code || TREE_CODE (t2) == code
888       || TREE_CODE (t1) == MINUS_EXPR || TREE_CODE (t2) == MINUS_EXPR)
889     {
890       if (code == PLUS_EXPR)
891         {
892           if (TREE_CODE (t1) == NEGATE_EXPR)
893             return build2_loc (loc, MINUS_EXPR, type,
894                                fold_convert_loc (loc, type, t2),
895                                fold_convert_loc (loc, type,
896                                                  TREE_OPERAND (t1, 0)));
897           else if (TREE_CODE (t2) == NEGATE_EXPR)
898             return build2_loc (loc, MINUS_EXPR, type,
899                                fold_convert_loc (loc, type, t1),
900                                fold_convert_loc (loc, type,
901                                                  TREE_OPERAND (t2, 0)));
902           else if (integer_zerop (t2))
903             return fold_convert_loc (loc, type, t1);
904         }
905       else if (code == MINUS_EXPR)
906         {
907           if (integer_zerop (t2))
908             return fold_convert_loc (loc, type, t1);
909         }
910
911       return build2_loc (loc, code, type, fold_convert_loc (loc, type, t1),
912                          fold_convert_loc (loc, type, t2));
913     }
914
915   return fold_build2_loc (loc, code, type, fold_convert_loc (loc, type, t1),
916                           fold_convert_loc (loc, type, t2));
917 }
918 \f
919 /* Check whether TYPE1 and TYPE2 are equivalent integer types, suitable
920    for use in int_const_binop, size_binop and size_diffop.  */
921
922 static bool
923 int_binop_types_match_p (enum tree_code code, const_tree type1, const_tree type2)
924 {
925   if (!INTEGRAL_TYPE_P (type1) && !POINTER_TYPE_P (type1))
926     return false;
927   if (!INTEGRAL_TYPE_P (type2) && !POINTER_TYPE_P (type2))
928     return false;
929
930   switch (code)
931     {
932     case LSHIFT_EXPR:
933     case RSHIFT_EXPR:
934     case LROTATE_EXPR:
935     case RROTATE_EXPR:
936       return true;
937
938     default:
939       break;
940     }
941
942   return TYPE_UNSIGNED (type1) == TYPE_UNSIGNED (type2)
943          && TYPE_PRECISION (type1) == TYPE_PRECISION (type2)
944          && TYPE_MODE (type1) == TYPE_MODE (type2);
945 }
946
947
948 /* Combine two integer constants ARG1 and ARG2 under operation CODE
949    to produce a new constant.  Return NULL_TREE if we don't know how
950    to evaluate CODE at compile-time.  */
951
952 static tree
953 int_const_binop_1 (enum tree_code code, const_tree arg1, const_tree parg2,
954                    int overflowable)
955 {
956   wide_int res;
957   tree t;
958   tree type = TREE_TYPE (arg1);
959   signop sign = TYPE_SIGN (type);
960   bool overflow = false;
961
962   wide_int arg2 = wide_int::from (parg2, TYPE_PRECISION (type),
963                                   TYPE_SIGN (TREE_TYPE (parg2)));
964
965   switch (code)
966     {
967     case BIT_IOR_EXPR:
968       res = wi::bit_or (arg1, arg2);
969       break;
970
971     case BIT_XOR_EXPR:
972       res = wi::bit_xor (arg1, arg2);
973       break;
974
975     case BIT_AND_EXPR:
976       res = wi::bit_and (arg1, arg2);
977       break;
978
979     case RSHIFT_EXPR:
980     case LSHIFT_EXPR:
981       if (wi::neg_p (arg2))
982         {
983           arg2 = -arg2;
984           if (code == RSHIFT_EXPR)
985             code = LSHIFT_EXPR;
986           else
987             code = RSHIFT_EXPR;
988         }
989
990       if (code == RSHIFT_EXPR)
991         /* It's unclear from the C standard whether shifts can overflow.
992            The following code ignores overflow; perhaps a C standard
993            interpretation ruling is needed.  */
994         res = wi::rshift (arg1, arg2, sign);
995       else
996         res = wi::lshift (arg1, arg2);
997       break;
998
999     case RROTATE_EXPR:
1000     case LROTATE_EXPR:
1001       if (wi::neg_p (arg2))
1002         {
1003           arg2 = -arg2;
1004           if (code == RROTATE_EXPR)
1005             code = LROTATE_EXPR;
1006           else
1007             code = RROTATE_EXPR;
1008         }
1009
1010       if (code == RROTATE_EXPR)
1011         res = wi::rrotate (arg1, arg2);
1012       else
1013         res = wi::lrotate (arg1, arg2);
1014       break;
1015
1016     case PLUS_EXPR:
1017       res = wi::add (arg1, arg2, sign, &overflow);
1018       break;
1019
1020     case MINUS_EXPR:
1021       res = wi::sub (arg1, arg2, sign, &overflow);
1022       break;
1023
1024     case MULT_EXPR:
1025       res = wi::mul (arg1, arg2, sign, &overflow);
1026       break;
1027
1028     case MULT_HIGHPART_EXPR:
1029       res = wi::mul_high (arg1, arg2, sign);
1030       break;
1031
1032     case TRUNC_DIV_EXPR:
1033     case EXACT_DIV_EXPR:
1034       if (arg2 == 0)
1035         return NULL_TREE;
1036       res = wi::div_trunc (arg1, arg2, sign, &overflow);
1037       break;
1038
1039     case FLOOR_DIV_EXPR:
1040       if (arg2 == 0)
1041         return NULL_TREE;
1042       res = wi::div_floor (arg1, arg2, sign, &overflow);
1043       break;
1044
1045     case CEIL_DIV_EXPR:
1046       if (arg2 == 0)
1047         return NULL_TREE;
1048       res = wi::div_ceil (arg1, arg2, sign, &overflow);
1049       break;
1050
1051     case ROUND_DIV_EXPR:
1052       if (arg2 == 0)
1053         return NULL_TREE;
1054       res = wi::div_round (arg1, arg2, sign, &overflow);
1055       break;
1056
1057     case TRUNC_MOD_EXPR:
1058       if (arg2 == 0)
1059         return NULL_TREE;
1060       res = wi::mod_trunc (arg1, arg2, sign, &overflow);
1061       break;
1062
1063     case FLOOR_MOD_EXPR:
1064       if (arg2 == 0)
1065         return NULL_TREE;
1066       res = wi::mod_floor (arg1, arg2, sign, &overflow);
1067       break;
1068
1069     case CEIL_MOD_EXPR:
1070       if (arg2 == 0)
1071         return NULL_TREE;
1072       res = wi::mod_ceil (arg1, arg2, sign, &overflow);
1073       break;
1074
1075     case ROUND_MOD_EXPR:
1076       if (arg2 == 0)
1077         return NULL_TREE;
1078       res = wi::mod_round (arg1, arg2, sign, &overflow);
1079       break;
1080
1081     case MIN_EXPR:
1082       res = wi::min (arg1, arg2, sign);
1083       break;
1084
1085     case MAX_EXPR:
1086       res = wi::max (arg1, arg2, sign);
1087       break;
1088
1089     default:
1090       return NULL_TREE;
1091     }
1092
1093   t = force_fit_type (type, res, overflowable,
1094                       (((sign == SIGNED || overflowable == -1)
1095                         && overflow)
1096                        | TREE_OVERFLOW (arg1) | TREE_OVERFLOW (parg2)));
1097
1098   return t;
1099 }
1100
1101 tree
1102 int_const_binop (enum tree_code code, const_tree arg1, const_tree arg2)
1103 {
1104   return int_const_binop_1 (code, arg1, arg2, 1);
1105 }
1106
1107 /* Combine two constants ARG1 and ARG2 under operation CODE to produce a new
1108    constant.  We assume ARG1 and ARG2 have the same data type, or at least
1109    are the same kind of constant and the same machine mode.  Return zero if
1110    combining the constants is not allowed in the current operating mode.  */
1111
1112 static tree
1113 const_binop (enum tree_code code, tree arg1, tree arg2)
1114 {
1115   /* Sanity check for the recursive cases.  */
1116   if (!arg1 || !arg2)
1117     return NULL_TREE;
1118
1119   STRIP_NOPS (arg1);
1120   STRIP_NOPS (arg2);
1121
1122   if (TREE_CODE (arg1) == INTEGER_CST && TREE_CODE (arg2) == INTEGER_CST)
1123     {
1124       if (code == POINTER_PLUS_EXPR)
1125         return int_const_binop (PLUS_EXPR,
1126                                 arg1, fold_convert (TREE_TYPE (arg1), arg2));
1127
1128       return int_const_binop (code, arg1, arg2);
1129     }
1130
1131   if (TREE_CODE (arg1) == REAL_CST && TREE_CODE (arg2) == REAL_CST)
1132     {
1133       machine_mode mode;
1134       REAL_VALUE_TYPE d1;
1135       REAL_VALUE_TYPE d2;
1136       REAL_VALUE_TYPE value;
1137       REAL_VALUE_TYPE result;
1138       bool inexact;
1139       tree t, type;
1140
1141       /* The following codes are handled by real_arithmetic.  */
1142       switch (code)
1143         {
1144         case PLUS_EXPR:
1145         case MINUS_EXPR:
1146         case MULT_EXPR:
1147         case RDIV_EXPR:
1148         case MIN_EXPR:
1149         case MAX_EXPR:
1150           break;
1151
1152         default:
1153           return NULL_TREE;
1154         }
1155
1156       d1 = TREE_REAL_CST (arg1);
1157       d2 = TREE_REAL_CST (arg2);
1158
1159       type = TREE_TYPE (arg1);
1160       mode = TYPE_MODE (type);
1161
1162       /* Don't perform operation if we honor signaling NaNs and
1163          either operand is a signaling NaN.  */
1164       if (HONOR_SNANS (mode)
1165           && (REAL_VALUE_ISSIGNALING_NAN (d1)
1166               || REAL_VALUE_ISSIGNALING_NAN (d2)))
1167         return NULL_TREE;
1168
1169       /* Don't perform operation if it would raise a division
1170          by zero exception.  */
1171       if (code == RDIV_EXPR
1172           && real_equal (&d2, &dconst0)
1173           && (flag_trapping_math || ! MODE_HAS_INFINITIES (mode)))
1174         return NULL_TREE;
1175
1176       /* If either operand is a NaN, just return it.  Otherwise, set up
1177          for floating-point trap; we return an overflow.  */
1178       if (REAL_VALUE_ISNAN (d1))
1179       {
1180         /* Make resulting NaN value to be qNaN when flag_signaling_nans
1181            is off.  */
1182         d1.signalling = 0;
1183         t = build_real (type, d1);
1184         return t;
1185       }
1186       else if (REAL_VALUE_ISNAN (d2))
1187       {
1188         /* Make resulting NaN value to be qNaN when flag_signaling_nans
1189            is off.  */
1190         d2.signalling = 0;
1191         t = build_real (type, d2);
1192         return t;
1193       }
1194
1195       inexact = real_arithmetic (&value, code, &d1, &d2);
1196       real_convert (&result, mode, &value);
1197
1198       /* Don't constant fold this floating point operation if
1199          the result has overflowed and flag_trapping_math.  */
1200       if (flag_trapping_math
1201           && MODE_HAS_INFINITIES (mode)
1202           && REAL_VALUE_ISINF (result)
1203           && !REAL_VALUE_ISINF (d1)
1204           && !REAL_VALUE_ISINF (d2))
1205         return NULL_TREE;
1206
1207       /* Don't constant fold this floating point operation if the
1208          result may dependent upon the run-time rounding mode and
1209          flag_rounding_math is set, or if GCC's software emulation
1210          is unable to accurately represent the result.  */
1211       if ((flag_rounding_math
1212            || (MODE_COMPOSITE_P (mode) && !flag_unsafe_math_optimizations))
1213           && (inexact || !real_identical (&result, &value)))
1214         return NULL_TREE;
1215
1216       t = build_real (type, result);
1217
1218       TREE_OVERFLOW (t) = TREE_OVERFLOW (arg1) | TREE_OVERFLOW (arg2);
1219       return t;
1220     }
1221
1222   if (TREE_CODE (arg1) == FIXED_CST)
1223     {
1224       FIXED_VALUE_TYPE f1;
1225       FIXED_VALUE_TYPE f2;
1226       FIXED_VALUE_TYPE result;
1227       tree t, type;
1228       int sat_p;
1229       bool overflow_p;
1230
1231       /* The following codes are handled by fixed_arithmetic.  */
1232       switch (code)
1233         {
1234         case PLUS_EXPR:
1235         case MINUS_EXPR:
1236         case MULT_EXPR:
1237         case TRUNC_DIV_EXPR:
1238           if (TREE_CODE (arg2) != FIXED_CST)
1239             return NULL_TREE;
1240           f2 = TREE_FIXED_CST (arg2);
1241           break;
1242
1243         case LSHIFT_EXPR:
1244         case RSHIFT_EXPR:
1245           {
1246             if (TREE_CODE (arg2) != INTEGER_CST)
1247               return NULL_TREE;
1248             wide_int w2 = arg2;
1249             f2.data.high = w2.elt (1);
1250             f2.data.low = w2.elt (0);
1251             f2.mode = SImode;
1252           }
1253           break;
1254
1255         default:
1256           return NULL_TREE;
1257         }
1258
1259       f1 = TREE_FIXED_CST (arg1);
1260       type = TREE_TYPE (arg1);
1261       sat_p = TYPE_SATURATING (type);
1262       overflow_p = fixed_arithmetic (&result, code, &f1, &f2, sat_p);
1263       t = build_fixed (type, result);
1264       /* Propagate overflow flags.  */
1265       if (overflow_p | TREE_OVERFLOW (arg1) | TREE_OVERFLOW (arg2))
1266         TREE_OVERFLOW (t) = 1;
1267       return t;
1268     }
1269
1270   if (TREE_CODE (arg1) == COMPLEX_CST && TREE_CODE (arg2) == COMPLEX_CST)
1271     {
1272       tree type = TREE_TYPE (arg1);
1273       tree r1 = TREE_REALPART (arg1);
1274       tree i1 = TREE_IMAGPART (arg1);
1275       tree r2 = TREE_REALPART (arg2);
1276       tree i2 = TREE_IMAGPART (arg2);
1277       tree real, imag;
1278
1279       switch (code)
1280         {
1281         case PLUS_EXPR:
1282         case MINUS_EXPR:
1283           real = const_binop (code, r1, r2);
1284           imag = const_binop (code, i1, i2);
1285           break;
1286
1287         case MULT_EXPR:
1288           if (COMPLEX_FLOAT_TYPE_P (type))
1289             return do_mpc_arg2 (arg1, arg2, type,
1290                                 /* do_nonfinite= */ folding_initializer,
1291                                 mpc_mul);
1292
1293           real = const_binop (MINUS_EXPR,
1294                               const_binop (MULT_EXPR, r1, r2),
1295                               const_binop (MULT_EXPR, i1, i2));
1296           imag = const_binop (PLUS_EXPR,
1297                               const_binop (MULT_EXPR, r1, i2),
1298                               const_binop (MULT_EXPR, i1, r2));
1299           break;
1300
1301         case RDIV_EXPR:
1302           if (COMPLEX_FLOAT_TYPE_P (type))
1303             return do_mpc_arg2 (arg1, arg2, type,
1304                                 /* do_nonfinite= */ folding_initializer,
1305                                 mpc_div);
1306           /* Fallthru ... */
1307         case TRUNC_DIV_EXPR:
1308         case CEIL_DIV_EXPR:
1309         case FLOOR_DIV_EXPR:
1310         case ROUND_DIV_EXPR:
1311           if (flag_complex_method == 0)
1312           {
1313             /* Keep this algorithm in sync with
1314                tree-complex.c:expand_complex_div_straight().
1315
1316                Expand complex division to scalars, straightforward algorithm.
1317                a / b = ((ar*br + ai*bi)/t) + i((ai*br - ar*bi)/t)
1318                t = br*br + bi*bi
1319             */
1320             tree magsquared
1321               = const_binop (PLUS_EXPR,
1322                              const_binop (MULT_EXPR, r2, r2),
1323                              const_binop (MULT_EXPR, i2, i2));
1324             tree t1
1325               = const_binop (PLUS_EXPR,
1326                              const_binop (MULT_EXPR, r1, r2),
1327                              const_binop (MULT_EXPR, i1, i2));
1328             tree t2
1329               = const_binop (MINUS_EXPR,
1330                              const_binop (MULT_EXPR, i1, r2),
1331                              const_binop (MULT_EXPR, r1, i2));
1332
1333             real = const_binop (code, t1, magsquared);
1334             imag = const_binop (code, t2, magsquared);
1335           }
1336           else
1337           {
1338             /* Keep this algorithm in sync with
1339                tree-complex.c:expand_complex_div_wide().
1340
1341                Expand complex division to scalars, modified algorithm to minimize
1342                overflow with wide input ranges.  */
1343             tree compare = fold_build2 (LT_EXPR, boolean_type_node,
1344                                         fold_abs_const (r2, TREE_TYPE (type)),
1345                                         fold_abs_const (i2, TREE_TYPE (type)));
1346
1347             if (integer_nonzerop (compare))
1348               {
1349                 /* In the TRUE branch, we compute
1350                    ratio = br/bi;
1351                    div = (br * ratio) + bi;
1352                    tr = (ar * ratio) + ai;
1353                    ti = (ai * ratio) - ar;
1354                    tr = tr / div;
1355                    ti = ti / div;  */
1356                 tree ratio = const_binop (code, r2, i2);
1357                 tree div = const_binop (PLUS_EXPR, i2,
1358                                         const_binop (MULT_EXPR, r2, ratio));
1359                 real = const_binop (MULT_EXPR, r1, ratio);
1360                 real = const_binop (PLUS_EXPR, real, i1);
1361                 real = const_binop (code, real, div);
1362
1363                 imag = const_binop (MULT_EXPR, i1, ratio);
1364                 imag = const_binop (MINUS_EXPR, imag, r1);
1365                 imag = const_binop (code, imag, div);
1366               }
1367             else
1368               {
1369                 /* In the FALSE branch, we compute
1370                    ratio = d/c;
1371                    divisor = (d * ratio) + c;
1372                    tr = (b * ratio) + a;
1373                    ti = b - (a * ratio);
1374                    tr = tr / div;
1375                    ti = ti / div;  */
1376                 tree ratio = const_binop (code, i2, r2);
1377                 tree div = const_binop (PLUS_EXPR, r2,
1378                                         const_binop (MULT_EXPR, i2, ratio));
1379
1380                 real = const_binop (MULT_EXPR, i1, ratio);
1381                 real = const_binop (PLUS_EXPR, real, r1);
1382                 real = const_binop (code, real, div);
1383
1384                 imag = const_binop (MULT_EXPR, r1, ratio);
1385                 imag = const_binop (MINUS_EXPR, i1, imag);
1386                 imag = const_binop (code, imag, div);
1387               }
1388           }
1389           break;
1390
1391         default:
1392           return NULL_TREE;
1393         }
1394
1395       if (real && imag)
1396         return build_complex (type, real, imag);
1397     }
1398
1399   if (TREE_CODE (arg1) == VECTOR_CST
1400       && TREE_CODE (arg2) == VECTOR_CST)
1401     {
1402       tree type = TREE_TYPE (arg1);
1403       int count = TYPE_VECTOR_SUBPARTS (type), i;
1404       tree *elts = XALLOCAVEC (tree, count);
1405
1406       for (i = 0; i < count; i++)
1407         {
1408           tree elem1 = VECTOR_CST_ELT (arg1, i);
1409           tree elem2 = VECTOR_CST_ELT (arg2, i);
1410
1411           elts[i] = const_binop (code, elem1, elem2);
1412
1413           /* It is possible that const_binop cannot handle the given
1414              code and return NULL_TREE */
1415           if (elts[i] == NULL_TREE)
1416             return NULL_TREE;
1417         }
1418
1419       return build_vector (type, elts);
1420     }
1421
1422   /* Shifts allow a scalar offset for a vector.  */
1423   if (TREE_CODE (arg1) == VECTOR_CST
1424       && TREE_CODE (arg2) == INTEGER_CST)
1425     {
1426       tree type = TREE_TYPE (arg1);
1427       int count = TYPE_VECTOR_SUBPARTS (type), i;
1428       tree *elts = XALLOCAVEC (tree, count);
1429
1430       for (i = 0; i < count; i++)
1431         {
1432           tree elem1 = VECTOR_CST_ELT (arg1, i);
1433
1434           elts[i] = const_binop (code, elem1, arg2);
1435
1436           /* It is possible that const_binop cannot handle the given
1437              code and return NULL_TREE.  */
1438           if (elts[i] == NULL_TREE)
1439             return NULL_TREE;
1440         }
1441
1442       return build_vector (type, elts);
1443     }
1444   return NULL_TREE;
1445 }
1446
1447 /* Overload that adds a TYPE parameter to be able to dispatch
1448    to fold_relational_const.  */
1449
1450 tree
1451 const_binop (enum tree_code code, tree type, tree arg1, tree arg2)
1452 {
1453   if (TREE_CODE_CLASS (code) == tcc_comparison)
1454     return fold_relational_const (code, type, arg1, arg2);
1455
1456   /* ???  Until we make the const_binop worker take the type of the
1457      result as argument put those cases that need it here.  */
1458   switch (code)
1459     {
1460     case COMPLEX_EXPR:
1461       if ((TREE_CODE (arg1) == REAL_CST
1462            && TREE_CODE (arg2) == REAL_CST)
1463           || (TREE_CODE (arg1) == INTEGER_CST
1464               && TREE_CODE (arg2) == INTEGER_CST))
1465         return build_complex (type, arg1, arg2);
1466       return NULL_TREE;
1467
1468     case VEC_PACK_TRUNC_EXPR:
1469     case VEC_PACK_FIX_TRUNC_EXPR:
1470       {
1471         unsigned int nelts = TYPE_VECTOR_SUBPARTS (type), i;
1472         tree *elts;
1473
1474         gcc_assert (TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg1)) == nelts / 2
1475                     && TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg2)) == nelts / 2);
1476         if (TREE_CODE (arg1) != VECTOR_CST
1477             || TREE_CODE (arg2) != VECTOR_CST)
1478           return NULL_TREE;
1479
1480         elts = XALLOCAVEC (tree, nelts);
1481         if (!vec_cst_ctor_to_array (arg1, elts)
1482             || !vec_cst_ctor_to_array (arg2, elts + nelts / 2))
1483           return NULL_TREE;
1484
1485         for (i = 0; i < nelts; i++)
1486           {
1487             elts[i] = fold_convert_const (code == VEC_PACK_TRUNC_EXPR
1488                                           ? NOP_EXPR : FIX_TRUNC_EXPR,
1489                                           TREE_TYPE (type), elts[i]);
1490             if (elts[i] == NULL_TREE || !CONSTANT_CLASS_P (elts[i]))
1491               return NULL_TREE;
1492           }
1493
1494         return build_vector (type, elts);
1495       }
1496
1497     case VEC_WIDEN_MULT_LO_EXPR:
1498     case VEC_WIDEN_MULT_HI_EXPR:
1499     case VEC_WIDEN_MULT_EVEN_EXPR:
1500     case VEC_WIDEN_MULT_ODD_EXPR:
1501       {
1502         unsigned int nelts = TYPE_VECTOR_SUBPARTS (type);
1503         unsigned int out, ofs, scale;
1504         tree *elts;
1505
1506         gcc_assert (TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg1)) == nelts * 2
1507                     && TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg2)) == nelts * 2);
1508         if (TREE_CODE (arg1) != VECTOR_CST || TREE_CODE (arg2) != VECTOR_CST)
1509           return NULL_TREE;
1510
1511         elts = XALLOCAVEC (tree, nelts * 4);
1512         if (!vec_cst_ctor_to_array (arg1, elts)
1513             || !vec_cst_ctor_to_array (arg2, elts + nelts * 2))
1514           return NULL_TREE;
1515
1516         if (code == VEC_WIDEN_MULT_LO_EXPR)
1517           scale = 0, ofs = BYTES_BIG_ENDIAN ? nelts : 0;
1518         else if (code == VEC_WIDEN_MULT_HI_EXPR)
1519           scale = 0, ofs = BYTES_BIG_ENDIAN ? 0 : nelts;
1520         else if (code == VEC_WIDEN_MULT_EVEN_EXPR)
1521           scale = 1, ofs = 0;
1522         else /* if (code == VEC_WIDEN_MULT_ODD_EXPR) */
1523           scale = 1, ofs = 1;
1524
1525         for (out = 0; out < nelts; out++)
1526           {
1527             unsigned int in1 = (out << scale) + ofs;
1528             unsigned int in2 = in1 + nelts * 2;
1529             tree t1, t2;
1530
1531             t1 = fold_convert_const (NOP_EXPR, TREE_TYPE (type), elts[in1]);
1532             t2 = fold_convert_const (NOP_EXPR, TREE_TYPE (type), elts[in2]);
1533
1534             if (t1 == NULL_TREE || t2 == NULL_TREE)
1535               return NULL_TREE;
1536             elts[out] = const_binop (MULT_EXPR, t1, t2);
1537             if (elts[out] == NULL_TREE || !CONSTANT_CLASS_P (elts[out]))
1538               return NULL_TREE;
1539           }
1540
1541         return build_vector (type, elts);
1542       }
1543
1544     default:;
1545     }
1546
1547   if (TREE_CODE_CLASS (code) != tcc_binary)
1548     return NULL_TREE;
1549
1550   /* Make sure type and arg0 have the same saturating flag.  */
1551   gcc_checking_assert (TYPE_SATURATING (type)
1552                        == TYPE_SATURATING (TREE_TYPE (arg1)));
1553
1554   return const_binop (code, arg1, arg2);
1555 }
1556
1557 /* Compute CODE ARG1 with resulting type TYPE with ARG1 being constant.
1558    Return zero if computing the constants is not possible.  */
1559
1560 tree
1561 const_unop (enum tree_code code, tree type, tree arg0)
1562 {
1563   /* Don't perform the operation, other than NEGATE and ABS, if
1564      flag_signaling_nans is on and the operand is a signaling NaN.  */
1565   if (TREE_CODE (arg0) == REAL_CST
1566       && HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg0)))
1567       && REAL_VALUE_ISSIGNALING_NAN (TREE_REAL_CST (arg0))
1568       && code != NEGATE_EXPR
1569       && code != ABS_EXPR)
1570     return NULL_TREE;
1571
1572   switch (code)
1573     {
1574     CASE_CONVERT:
1575     case FLOAT_EXPR:
1576     case FIX_TRUNC_EXPR:
1577     case FIXED_CONVERT_EXPR:
1578       return fold_convert_const (code, type, arg0);
1579
1580     case ADDR_SPACE_CONVERT_EXPR:
1581       /* If the source address is 0, and the source address space
1582          cannot have a valid object at 0, fold to dest type null.  */
1583       if (integer_zerop (arg0)
1584           && !(targetm.addr_space.zero_address_valid
1585                (TYPE_ADDR_SPACE (TREE_TYPE (TREE_TYPE (arg0))))))
1586         return fold_convert_const (code, type, arg0);
1587       break;
1588
1589     case VIEW_CONVERT_EXPR:
1590       return fold_view_convert_expr (type, arg0);
1591
1592     case NEGATE_EXPR:
1593       {
1594         /* Can't call fold_negate_const directly here as that doesn't
1595            handle all cases and we might not be able to negate some
1596            constants.  */
1597         tree tem = fold_negate_expr (UNKNOWN_LOCATION, arg0);
1598         if (tem && CONSTANT_CLASS_P (tem))
1599           return tem;
1600         break;
1601       }
1602
1603     case ABS_EXPR:
1604       if (TREE_CODE (arg0) == INTEGER_CST || TREE_CODE (arg0) == REAL_CST)
1605         return fold_abs_const (arg0, type);
1606       break;
1607
1608     case CONJ_EXPR:
1609       if (TREE_CODE (arg0) == COMPLEX_CST)
1610         {
1611           tree ipart = fold_negate_const (TREE_IMAGPART (arg0),
1612                                           TREE_TYPE (type));
1613           return build_complex (type, TREE_REALPART (arg0), ipart);
1614         }
1615       break;
1616
1617     case BIT_NOT_EXPR:
1618       if (TREE_CODE (arg0) == INTEGER_CST)
1619         return fold_not_const (arg0, type);
1620       /* Perform BIT_NOT_EXPR on each element individually.  */
1621       else if (TREE_CODE (arg0) == VECTOR_CST)
1622         {
1623           tree *elements;
1624           tree elem;
1625           unsigned count = VECTOR_CST_NELTS (arg0), i;
1626
1627           elements = XALLOCAVEC (tree, count);
1628           for (i = 0; i < count; i++)
1629             {
1630               elem = VECTOR_CST_ELT (arg0, i);
1631               elem = const_unop (BIT_NOT_EXPR, TREE_TYPE (type), elem);
1632               if (elem == NULL_TREE)
1633                 break;
1634               elements[i] = elem;
1635             }
1636           if (i == count)
1637             return build_vector (type, elements);
1638         }
1639       break;
1640
1641     case TRUTH_NOT_EXPR:
1642       if (TREE_CODE (arg0) == INTEGER_CST)
1643         return constant_boolean_node (integer_zerop (arg0), type);
1644       break;
1645
1646     case REALPART_EXPR:
1647       if (TREE_CODE (arg0) == COMPLEX_CST)
1648         return fold_convert (type, TREE_REALPART (arg0));
1649       break;
1650
1651     case IMAGPART_EXPR:
1652       if (TREE_CODE (arg0) == COMPLEX_CST)
1653         return fold_convert (type, TREE_IMAGPART (arg0));
1654       break;
1655
1656     case VEC_UNPACK_LO_EXPR:
1657     case VEC_UNPACK_HI_EXPR:
1658     case VEC_UNPACK_FLOAT_LO_EXPR:
1659     case VEC_UNPACK_FLOAT_HI_EXPR:
1660       {
1661         unsigned int nelts = TYPE_VECTOR_SUBPARTS (type), i;
1662         tree *elts;
1663         enum tree_code subcode;
1664
1665         gcc_assert (TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0)) == nelts * 2);
1666         if (TREE_CODE (arg0) != VECTOR_CST)
1667           return NULL_TREE;
1668
1669         elts = XALLOCAVEC (tree, nelts * 2);
1670         if (!vec_cst_ctor_to_array (arg0, elts))
1671           return NULL_TREE;
1672
1673         if ((!BYTES_BIG_ENDIAN) ^ (code == VEC_UNPACK_LO_EXPR
1674                                    || code == VEC_UNPACK_FLOAT_LO_EXPR))
1675           elts += nelts;
1676
1677         if (code == VEC_UNPACK_LO_EXPR || code == VEC_UNPACK_HI_EXPR)
1678           subcode = NOP_EXPR;
1679         else
1680           subcode = FLOAT_EXPR;
1681
1682         for (i = 0; i < nelts; i++)
1683           {
1684             elts[i] = fold_convert_const (subcode, TREE_TYPE (type), elts[i]);
1685             if (elts[i] == NULL_TREE || !CONSTANT_CLASS_P (elts[i]))
1686               return NULL_TREE;
1687           }
1688
1689         return build_vector (type, elts);
1690       }
1691
1692     case REDUC_MIN_EXPR:
1693     case REDUC_MAX_EXPR:
1694     case REDUC_PLUS_EXPR:
1695       {
1696         unsigned int nelts, i;
1697         tree *elts;
1698         enum tree_code subcode;
1699
1700         if (TREE_CODE (arg0) != VECTOR_CST)
1701           return NULL_TREE;
1702         nelts = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
1703
1704         elts = XALLOCAVEC (tree, nelts);
1705         if (!vec_cst_ctor_to_array (arg0, elts))
1706           return NULL_TREE;
1707
1708         switch (code)
1709           {
1710           case REDUC_MIN_EXPR: subcode = MIN_EXPR; break;
1711           case REDUC_MAX_EXPR: subcode = MAX_EXPR; break;
1712           case REDUC_PLUS_EXPR: subcode = PLUS_EXPR; break;
1713           default: gcc_unreachable ();
1714           }
1715
1716         for (i = 1; i < nelts; i++)
1717           {
1718             elts[0] = const_binop (subcode, elts[0], elts[i]);
1719             if (elts[0] == NULL_TREE || !CONSTANT_CLASS_P (elts[0]))
1720               return NULL_TREE;
1721           }
1722
1723         return elts[0];
1724       }
1725
1726     default:
1727       break;
1728     }
1729
1730   return NULL_TREE;
1731 }
1732
1733 /* Create a sizetype INT_CST node with NUMBER sign extended.  KIND
1734    indicates which particular sizetype to create.  */
1735
1736 tree
1737 size_int_kind (HOST_WIDE_INT number, enum size_type_kind kind)
1738 {
1739   return build_int_cst (sizetype_tab[(int) kind], number);
1740 }
1741 \f
1742 /* Combine operands OP1 and OP2 with arithmetic operation CODE.  CODE
1743    is a tree code.  The type of the result is taken from the operands.
1744    Both must be equivalent integer types, ala int_binop_types_match_p.
1745    If the operands are constant, so is the result.  */
1746
1747 tree
1748 size_binop_loc (location_t loc, enum tree_code code, tree arg0, tree arg1)
1749 {
1750   tree type = TREE_TYPE (arg0);
1751
1752   if (arg0 == error_mark_node || arg1 == error_mark_node)
1753     return error_mark_node;
1754
1755   gcc_assert (int_binop_types_match_p (code, TREE_TYPE (arg0),
1756                                        TREE_TYPE (arg1)));
1757
1758   /* Handle the special case of two integer constants faster.  */
1759   if (TREE_CODE (arg0) == INTEGER_CST && TREE_CODE (arg1) == INTEGER_CST)
1760     {
1761       /* And some specific cases even faster than that.  */
1762       if (code == PLUS_EXPR)
1763         {
1764           if (integer_zerop (arg0) && !TREE_OVERFLOW (arg0))
1765             return arg1;
1766           if (integer_zerop (arg1) && !TREE_OVERFLOW (arg1))
1767             return arg0;
1768         }
1769       else if (code == MINUS_EXPR)
1770         {
1771           if (integer_zerop (arg1) && !TREE_OVERFLOW (arg1))
1772             return arg0;
1773         }
1774       else if (code == MULT_EXPR)
1775         {
1776           if (integer_onep (arg0) && !TREE_OVERFLOW (arg0))
1777             return arg1;
1778         }
1779
1780       /* Handle general case of two integer constants.  For sizetype
1781          constant calculations we always want to know about overflow,
1782          even in the unsigned case.  */
1783       return int_const_binop_1 (code, arg0, arg1, -1);
1784     }
1785
1786   return fold_build2_loc (loc, code, type, arg0, arg1);
1787 }
1788
1789 /* Given two values, either both of sizetype or both of bitsizetype,
1790    compute the difference between the two values.  Return the value
1791    in signed type corresponding to the type of the operands.  */
1792
1793 tree
1794 size_diffop_loc (location_t loc, tree arg0, tree arg1)
1795 {
1796   tree type = TREE_TYPE (arg0);
1797   tree ctype;
1798
1799   gcc_assert (int_binop_types_match_p (MINUS_EXPR, TREE_TYPE (arg0),
1800                                        TREE_TYPE (arg1)));
1801
1802   /* If the type is already signed, just do the simple thing.  */
1803   if (!TYPE_UNSIGNED (type))
1804     return size_binop_loc (loc, MINUS_EXPR, arg0, arg1);
1805
1806   if (type == sizetype)
1807     ctype = ssizetype;
1808   else if (type == bitsizetype)
1809     ctype = sbitsizetype;
1810   else
1811     ctype = signed_type_for (type);
1812
1813   /* If either operand is not a constant, do the conversions to the signed
1814      type and subtract.  The hardware will do the right thing with any
1815      overflow in the subtraction.  */
1816   if (TREE_CODE (arg0) != INTEGER_CST || TREE_CODE (arg1) != INTEGER_CST)
1817     return size_binop_loc (loc, MINUS_EXPR,
1818                            fold_convert_loc (loc, ctype, arg0),
1819                            fold_convert_loc (loc, ctype, arg1));
1820
1821   /* If ARG0 is larger than ARG1, subtract and return the result in CTYPE.
1822      Otherwise, subtract the other way, convert to CTYPE (we know that can't
1823      overflow) and negate (which can't either).  Special-case a result
1824      of zero while we're here.  */
1825   if (tree_int_cst_equal (arg0, arg1))
1826     return build_int_cst (ctype, 0);
1827   else if (tree_int_cst_lt (arg1, arg0))
1828     return fold_convert_loc (loc, ctype,
1829                              size_binop_loc (loc, MINUS_EXPR, arg0, arg1));
1830   else
1831     return size_binop_loc (loc, MINUS_EXPR, build_int_cst (ctype, 0),
1832                            fold_convert_loc (loc, ctype,
1833                                              size_binop_loc (loc,
1834                                                              MINUS_EXPR,
1835                                                              arg1, arg0)));
1836 }
1837 \f
1838 /* A subroutine of fold_convert_const handling conversions of an
1839    INTEGER_CST to another integer type.  */
1840
1841 static tree
1842 fold_convert_const_int_from_int (tree type, const_tree arg1)
1843 {
1844   /* Given an integer constant, make new constant with new type,
1845      appropriately sign-extended or truncated.  Use widest_int
1846      so that any extension is done according ARG1's type.  */
1847   return force_fit_type (type, wi::to_widest (arg1),
1848                          !POINTER_TYPE_P (TREE_TYPE (arg1)),
1849                          TREE_OVERFLOW (arg1));
1850 }
1851
1852 /* A subroutine of fold_convert_const handling conversions a REAL_CST
1853    to an integer type.  */
1854
1855 static tree
1856 fold_convert_const_int_from_real (enum tree_code code, tree type, const_tree arg1)
1857 {
1858   bool overflow = false;
1859   tree t;
1860
1861   /* The following code implements the floating point to integer
1862      conversion rules required by the Java Language Specification,
1863      that IEEE NaNs are mapped to zero and values that overflow
1864      the target precision saturate, i.e. values greater than
1865      INT_MAX are mapped to INT_MAX, and values less than INT_MIN
1866      are mapped to INT_MIN.  These semantics are allowed by the
1867      C and C++ standards that simply state that the behavior of
1868      FP-to-integer conversion is unspecified upon overflow.  */
1869
1870   wide_int val;
1871   REAL_VALUE_TYPE r;
1872   REAL_VALUE_TYPE x = TREE_REAL_CST (arg1);
1873
1874   switch (code)
1875     {
1876     case FIX_TRUNC_EXPR:
1877       real_trunc (&r, VOIDmode, &x);
1878       break;
1879
1880     default:
1881       gcc_unreachable ();
1882     }
1883
1884   /* If R is NaN, return zero and show we have an overflow.  */
1885   if (REAL_VALUE_ISNAN (r))
1886     {
1887       overflow = true;
1888       val = wi::zero (TYPE_PRECISION (type));
1889     }
1890
1891   /* See if R is less than the lower bound or greater than the
1892      upper bound.  */
1893
1894   if (! overflow)
1895     {
1896       tree lt = TYPE_MIN_VALUE (type);
1897       REAL_VALUE_TYPE l = real_value_from_int_cst (NULL_TREE, lt);
1898       if (real_less (&r, &l))
1899         {
1900           overflow = true;
1901           val = lt;
1902         }
1903     }
1904
1905   if (! overflow)
1906     {
1907       tree ut = TYPE_MAX_VALUE (type);
1908       if (ut)
1909         {
1910           REAL_VALUE_TYPE u = real_value_from_int_cst (NULL_TREE, ut);
1911           if (real_less (&u, &r))
1912             {
1913               overflow = true;
1914               val = ut;
1915             }
1916         }
1917     }
1918
1919   if (! overflow)
1920     val = real_to_integer (&r, &overflow, TYPE_PRECISION (type));
1921
1922   t = force_fit_type (type, val, -1, overflow | TREE_OVERFLOW (arg1));
1923   return t;
1924 }
1925
1926 /* A subroutine of fold_convert_const handling conversions of a
1927    FIXED_CST to an integer type.  */
1928
1929 static tree
1930 fold_convert_const_int_from_fixed (tree type, const_tree arg1)
1931 {
1932   tree t;
1933   double_int temp, temp_trunc;
1934   unsigned int mode;
1935
1936   /* Right shift FIXED_CST to temp by fbit.  */
1937   temp = TREE_FIXED_CST (arg1).data;
1938   mode = TREE_FIXED_CST (arg1).mode;
1939   if (GET_MODE_FBIT (mode) < HOST_BITS_PER_DOUBLE_INT)
1940     {
1941       temp = temp.rshift (GET_MODE_FBIT (mode),
1942                           HOST_BITS_PER_DOUBLE_INT,
1943                           SIGNED_FIXED_POINT_MODE_P (mode));
1944
1945       /* Left shift temp to temp_trunc by fbit.  */
1946       temp_trunc = temp.lshift (GET_MODE_FBIT (mode),
1947                                 HOST_BITS_PER_DOUBLE_INT,
1948                                 SIGNED_FIXED_POINT_MODE_P (mode));
1949     }
1950   else
1951     {
1952       temp = double_int_zero;
1953       temp_trunc = double_int_zero;
1954     }
1955
1956   /* If FIXED_CST is negative, we need to round the value toward 0.
1957      By checking if the fractional bits are not zero to add 1 to temp.  */
1958   if (SIGNED_FIXED_POINT_MODE_P (mode)
1959       && temp_trunc.is_negative ()
1960       && TREE_FIXED_CST (arg1).data != temp_trunc)
1961     temp += double_int_one;
1962
1963   /* Given a fixed-point constant, make new constant with new type,
1964      appropriately sign-extended or truncated.  */
1965   t = force_fit_type (type, temp, -1,
1966                       (temp.is_negative ()
1967                        && (TYPE_UNSIGNED (type)
1968                            < TYPE_UNSIGNED (TREE_TYPE (arg1))))
1969                       | TREE_OVERFLOW (arg1));
1970
1971   return t;
1972 }
1973
1974 /* A subroutine of fold_convert_const handling conversions a REAL_CST
1975    to another floating point type.  */
1976
1977 static tree
1978 fold_convert_const_real_from_real (tree type, const_tree arg1)
1979 {
1980   REAL_VALUE_TYPE value;
1981   tree t;
1982
1983   /* Don't perform the operation if flag_signaling_nans is on
1984      and the operand is a signaling NaN.  */
1985   if (HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg1)))
1986       && REAL_VALUE_ISSIGNALING_NAN (TREE_REAL_CST (arg1)))
1987     return NULL_TREE;
1988
1989   real_convert (&value, TYPE_MODE (type), &TREE_REAL_CST (arg1));
1990   t = build_real (type, value);
1991
1992   /* If converting an infinity or NAN to a representation that doesn't
1993      have one, set the overflow bit so that we can produce some kind of
1994      error message at the appropriate point if necessary.  It's not the
1995      most user-friendly message, but it's better than nothing.  */
1996   if (REAL_VALUE_ISINF (TREE_REAL_CST (arg1))
1997       && !MODE_HAS_INFINITIES (TYPE_MODE (type)))
1998     TREE_OVERFLOW (t) = 1;
1999   else if (REAL_VALUE_ISNAN (TREE_REAL_CST (arg1))
2000            && !MODE_HAS_NANS (TYPE_MODE (type)))
2001     TREE_OVERFLOW (t) = 1;
2002   /* Regular overflow, conversion produced an infinity in a mode that
2003      can't represent them.  */
2004   else if (!MODE_HAS_INFINITIES (TYPE_MODE (type))
2005            && REAL_VALUE_ISINF (value)
2006            && !REAL_VALUE_ISINF (TREE_REAL_CST (arg1)))
2007     TREE_OVERFLOW (t) = 1;
2008   else
2009     TREE_OVERFLOW (t) = TREE_OVERFLOW (arg1);
2010   return t;
2011 }
2012
2013 /* A subroutine of fold_convert_const handling conversions a FIXED_CST
2014    to a floating point type.  */
2015
2016 static tree
2017 fold_convert_const_real_from_fixed (tree type, const_tree arg1)
2018 {
2019   REAL_VALUE_TYPE value;
2020   tree t;
2021
2022   real_convert_from_fixed (&value, TYPE_MODE (type), &TREE_FIXED_CST (arg1));
2023   t = build_real (type, value);
2024
2025   TREE_OVERFLOW (t) = TREE_OVERFLOW (arg1);
2026   return t;
2027 }
2028
2029 /* A subroutine of fold_convert_const handling conversions a FIXED_CST
2030    to another fixed-point type.  */
2031
2032 static tree
2033 fold_convert_const_fixed_from_fixed (tree type, const_tree arg1)
2034 {
2035   FIXED_VALUE_TYPE value;
2036   tree t;
2037   bool overflow_p;
2038
2039   overflow_p = fixed_convert (&value, TYPE_MODE (type), &TREE_FIXED_CST (arg1),
2040                               TYPE_SATURATING (type));
2041   t = build_fixed (type, value);
2042
2043   /* Propagate overflow flags.  */
2044   if (overflow_p | TREE_OVERFLOW (arg1))
2045     TREE_OVERFLOW (t) = 1;
2046   return t;
2047 }
2048
2049 /* A subroutine of fold_convert_const handling conversions an INTEGER_CST
2050    to a fixed-point type.  */
2051
2052 static tree
2053 fold_convert_const_fixed_from_int (tree type, const_tree arg1)
2054 {
2055   FIXED_VALUE_TYPE value;
2056   tree t;
2057   bool overflow_p;
2058   double_int di;
2059
2060   gcc_assert (TREE_INT_CST_NUNITS (arg1) <= 2);
2061
2062   di.low = TREE_INT_CST_ELT (arg1, 0);
2063   if (TREE_INT_CST_NUNITS (arg1) == 1)
2064     di.high = (HOST_WIDE_INT) di.low < 0 ? (HOST_WIDE_INT) -1 : 0;
2065   else
2066     di.high = TREE_INT_CST_ELT (arg1, 1);
2067
2068   overflow_p = fixed_convert_from_int (&value, TYPE_MODE (type), di,
2069                                        TYPE_UNSIGNED (TREE_TYPE (arg1)),
2070                                        TYPE_SATURATING (type));
2071   t = build_fixed (type, value);
2072
2073   /* Propagate overflow flags.  */
2074   if (overflow_p | TREE_OVERFLOW (arg1))
2075     TREE_OVERFLOW (t) = 1;
2076   return t;
2077 }
2078
2079 /* A subroutine of fold_convert_const handling conversions a REAL_CST
2080    to a fixed-point type.  */
2081
2082 static tree
2083 fold_convert_const_fixed_from_real (tree type, const_tree arg1)
2084 {
2085   FIXED_VALUE_TYPE value;
2086   tree t;
2087   bool overflow_p;
2088
2089   overflow_p = fixed_convert_from_real (&value, TYPE_MODE (type),
2090                                         &TREE_REAL_CST (arg1),
2091                                         TYPE_SATURATING (type));
2092   t = build_fixed (type, value);
2093
2094   /* Propagate overflow flags.  */
2095   if (overflow_p | TREE_OVERFLOW (arg1))
2096     TREE_OVERFLOW (t) = 1;
2097   return t;
2098 }
2099
2100 /* Attempt to fold type conversion operation CODE of expression ARG1 to
2101    type TYPE.  If no simplification can be done return NULL_TREE.  */
2102
2103 static tree
2104 fold_convert_const (enum tree_code code, tree type, tree arg1)
2105 {
2106   if (TREE_TYPE (arg1) == type)
2107     return arg1;
2108
2109   if (POINTER_TYPE_P (type) || INTEGRAL_TYPE_P (type)
2110       || TREE_CODE (type) == OFFSET_TYPE)
2111     {
2112       if (TREE_CODE (arg1) == INTEGER_CST)
2113         return fold_convert_const_int_from_int (type, arg1);
2114       else if (TREE_CODE (arg1) == REAL_CST)
2115         return fold_convert_const_int_from_real (code, type, arg1);
2116       else if (TREE_CODE (arg1) == FIXED_CST)
2117         return fold_convert_const_int_from_fixed (type, arg1);
2118     }
2119   else if (TREE_CODE (type) == REAL_TYPE)
2120     {
2121       if (TREE_CODE (arg1) == INTEGER_CST)
2122         return build_real_from_int_cst (type, arg1);
2123       else if (TREE_CODE (arg1) == REAL_CST)
2124         return fold_convert_const_real_from_real (type, arg1);
2125       else if (TREE_CODE (arg1) == FIXED_CST)
2126         return fold_convert_const_real_from_fixed (type, arg1);
2127     }
2128   else if (TREE_CODE (type) == FIXED_POINT_TYPE)
2129     {
2130       if (TREE_CODE (arg1) == FIXED_CST)
2131         return fold_convert_const_fixed_from_fixed (type, arg1);
2132       else if (TREE_CODE (arg1) == INTEGER_CST)
2133         return fold_convert_const_fixed_from_int (type, arg1);
2134       else if (TREE_CODE (arg1) == REAL_CST)
2135         return fold_convert_const_fixed_from_real (type, arg1);
2136     }
2137   else if (TREE_CODE (type) == VECTOR_TYPE)
2138     {
2139       if (TREE_CODE (arg1) == VECTOR_CST
2140           && TYPE_VECTOR_SUBPARTS (type) == VECTOR_CST_NELTS (arg1))
2141         {
2142           int len = TYPE_VECTOR_SUBPARTS (type);
2143           tree elttype = TREE_TYPE (type);
2144           tree *v = XALLOCAVEC (tree, len);
2145           for (int i = 0; i < len; ++i)
2146             {
2147               tree elt = VECTOR_CST_ELT (arg1, i);
2148               tree cvt = fold_convert_const (code, elttype, elt);
2149               if (cvt == NULL_TREE)
2150                 return NULL_TREE;
2151               v[i] = cvt;
2152             }
2153           return build_vector (type, v);
2154         }
2155     }
2156   return NULL_TREE;
2157 }
2158
2159 /* Construct a vector of zero elements of vector type TYPE.  */
2160
2161 static tree
2162 build_zero_vector (tree type)
2163 {
2164   tree t;
2165
2166   t = fold_convert_const (NOP_EXPR, TREE_TYPE (type), integer_zero_node);
2167   return build_vector_from_val (type, t);
2168 }
2169
2170 /* Returns true, if ARG is convertible to TYPE using a NOP_EXPR.  */
2171
2172 bool
2173 fold_convertible_p (const_tree type, const_tree arg)
2174 {
2175   tree orig = TREE_TYPE (arg);
2176
2177   if (type == orig)
2178     return true;
2179
2180   if (TREE_CODE (arg) == ERROR_MARK
2181       || TREE_CODE (type) == ERROR_MARK
2182       || TREE_CODE (orig) == ERROR_MARK)
2183     return false;
2184
2185   if (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (orig))
2186     return true;
2187
2188   switch (TREE_CODE (type))
2189     {
2190     case INTEGER_TYPE: case ENUMERAL_TYPE: case BOOLEAN_TYPE:
2191     case POINTER_TYPE: case REFERENCE_TYPE:
2192     case OFFSET_TYPE:
2193       return (INTEGRAL_TYPE_P (orig) || POINTER_TYPE_P (orig)
2194               || TREE_CODE (orig) == OFFSET_TYPE);
2195
2196     case REAL_TYPE:
2197     case FIXED_POINT_TYPE:
2198     case VECTOR_TYPE:
2199     case VOID_TYPE:
2200       return TREE_CODE (type) == TREE_CODE (orig);
2201
2202     default:
2203       return false;
2204     }
2205 }
2206
2207 /* Convert expression ARG to type TYPE.  Used by the middle-end for
2208    simple conversions in preference to calling the front-end's convert.  */
2209
2210 tree
2211 fold_convert_loc (location_t loc, tree type, tree arg)
2212 {
2213   tree orig = TREE_TYPE (arg);
2214   tree tem;
2215
2216   if (type == orig)
2217     return arg;
2218
2219   if (TREE_CODE (arg) == ERROR_MARK
2220       || TREE_CODE (type) == ERROR_MARK
2221       || TREE_CODE (orig) == ERROR_MARK)
2222     return error_mark_node;
2223
2224   switch (TREE_CODE (type))
2225     {
2226     case POINTER_TYPE:
2227     case REFERENCE_TYPE:
2228       /* Handle conversions between pointers to different address spaces.  */
2229       if (POINTER_TYPE_P (orig)
2230           && (TYPE_ADDR_SPACE (TREE_TYPE (type))
2231               != TYPE_ADDR_SPACE (TREE_TYPE (orig))))
2232         return fold_build1_loc (loc, ADDR_SPACE_CONVERT_EXPR, type, arg);
2233       /* fall through */
2234
2235     case INTEGER_TYPE: case ENUMERAL_TYPE: case BOOLEAN_TYPE:
2236     case OFFSET_TYPE:
2237       if (TREE_CODE (arg) == INTEGER_CST)
2238         {
2239           tem = fold_convert_const (NOP_EXPR, type, arg);
2240           if (tem != NULL_TREE)
2241             return tem;
2242         }
2243       if (INTEGRAL_TYPE_P (orig) || POINTER_TYPE_P (orig)
2244           || TREE_CODE (orig) == OFFSET_TYPE)
2245         return fold_build1_loc (loc, NOP_EXPR, type, arg);
2246       if (TREE_CODE (orig) == COMPLEX_TYPE)
2247         return fold_convert_loc (loc, type,
2248                                  fold_build1_loc (loc, REALPART_EXPR,
2249                                                   TREE_TYPE (orig), arg));
2250       gcc_assert (TREE_CODE (orig) == VECTOR_TYPE
2251                   && tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (orig)));
2252       return fold_build1_loc (loc, VIEW_CONVERT_EXPR, type, arg);
2253
2254     case REAL_TYPE:
2255       if (TREE_CODE (arg) == INTEGER_CST)
2256         {
2257           tem = fold_convert_const (FLOAT_EXPR, type, arg);
2258           if (tem != NULL_TREE)
2259             return tem;
2260         }
2261       else if (TREE_CODE (arg) == REAL_CST)
2262         {
2263           tem = fold_convert_const (NOP_EXPR, type, arg);
2264           if (tem != NULL_TREE)
2265             return tem;
2266         }
2267       else if (TREE_CODE (arg) == FIXED_CST)
2268         {
2269           tem = fold_convert_const (FIXED_CONVERT_EXPR, type, arg);
2270           if (tem != NULL_TREE)
2271             return tem;
2272         }
2273
2274       switch (TREE_CODE (orig))
2275         {
2276         case INTEGER_TYPE:
2277         case BOOLEAN_TYPE: case ENUMERAL_TYPE:
2278         case POINTER_TYPE: case REFERENCE_TYPE:
2279           return fold_build1_loc (loc, FLOAT_EXPR, type, arg);
2280
2281         case REAL_TYPE:
2282           return fold_build1_loc (loc, NOP_EXPR, type, arg);
2283
2284         case FIXED_POINT_TYPE:
2285           return fold_build1_loc (loc, FIXED_CONVERT_EXPR, type, arg);
2286
2287         case COMPLEX_TYPE:
2288           tem = fold_build1_loc (loc, REALPART_EXPR, TREE_TYPE (orig), arg);
2289           return fold_convert_loc (loc, type, tem);
2290
2291         default:
2292           gcc_unreachable ();
2293         }
2294
2295     case FIXED_POINT_TYPE:
2296       if (TREE_CODE (arg) == FIXED_CST || TREE_CODE (arg) == INTEGER_CST
2297           || TREE_CODE (arg) == REAL_CST)
2298         {
2299           tem = fold_convert_const (FIXED_CONVERT_EXPR, type, arg);
2300           if (tem != NULL_TREE)
2301             goto fold_convert_exit;
2302         }
2303
2304       switch (TREE_CODE (orig))
2305         {
2306         case FIXED_POINT_TYPE:
2307         case INTEGER_TYPE:
2308         case ENUMERAL_TYPE:
2309         case BOOLEAN_TYPE:
2310         case REAL_TYPE:
2311           return fold_build1_loc (loc, FIXED_CONVERT_EXPR, type, arg);
2312
2313         case COMPLEX_TYPE:
2314           tem = fold_build1_loc (loc, REALPART_EXPR, TREE_TYPE (orig), arg);
2315           return fold_convert_loc (loc, type, tem);
2316
2317         default:
2318           gcc_unreachable ();
2319         }
2320
2321     case COMPLEX_TYPE:
2322       switch (TREE_CODE (orig))
2323         {
2324         case INTEGER_TYPE:
2325         case BOOLEAN_TYPE: case ENUMERAL_TYPE:
2326         case POINTER_TYPE: case REFERENCE_TYPE:
2327         case REAL_TYPE:
2328         case FIXED_POINT_TYPE:
2329           return fold_build2_loc (loc, COMPLEX_EXPR, type,
2330                               fold_convert_loc (loc, TREE_TYPE (type), arg),
2331                               fold_convert_loc (loc, TREE_TYPE (type),
2332                                             integer_zero_node));
2333         case COMPLEX_TYPE:
2334           {
2335             tree rpart, ipart;
2336
2337             if (TREE_CODE (arg) == COMPLEX_EXPR)
2338               {
2339                 rpart = fold_convert_loc (loc, TREE_TYPE (type),
2340                                       TREE_OPERAND (arg, 0));
2341                 ipart = fold_convert_loc (loc, TREE_TYPE (type),
2342                                       TREE_OPERAND (arg, 1));
2343                 return fold_build2_loc (loc, COMPLEX_EXPR, type, rpart, ipart);
2344               }
2345
2346             arg = save_expr (arg);
2347             rpart = fold_build1_loc (loc, REALPART_EXPR, TREE_TYPE (orig), arg);
2348             ipart = fold_build1_loc (loc, IMAGPART_EXPR, TREE_TYPE (orig), arg);
2349             rpart = fold_convert_loc (loc, TREE_TYPE (type), rpart);
2350             ipart = fold_convert_loc (loc, TREE_TYPE (type), ipart);
2351             return fold_build2_loc (loc, COMPLEX_EXPR, type, rpart, ipart);
2352           }
2353
2354         default:
2355           gcc_unreachable ();
2356         }
2357
2358     case VECTOR_TYPE:
2359       if (integer_zerop (arg))
2360         return build_zero_vector (type);
2361       gcc_assert (tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (orig)));
2362       gcc_assert (INTEGRAL_TYPE_P (orig) || POINTER_TYPE_P (orig)
2363                   || TREE_CODE (orig) == VECTOR_TYPE);
2364       return fold_build1_loc (loc, VIEW_CONVERT_EXPR, type, arg);
2365
2366     case VOID_TYPE:
2367       tem = fold_ignored_result (arg);
2368       return fold_build1_loc (loc, NOP_EXPR, type, tem);
2369
2370     default:
2371       if (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (orig))
2372         return fold_build1_loc (loc, NOP_EXPR, type, arg);
2373       gcc_unreachable ();
2374     }
2375  fold_convert_exit:
2376   protected_set_expr_location_unshare (tem, loc);
2377   return tem;
2378 }
2379 \f
2380 /* Return false if expr can be assumed not to be an lvalue, true
2381    otherwise.  */
2382
2383 static bool
2384 maybe_lvalue_p (const_tree x)
2385 {
2386   /* We only need to wrap lvalue tree codes.  */
2387   switch (TREE_CODE (x))
2388   {
2389   case VAR_DECL:
2390   case PARM_DECL:
2391   case RESULT_DECL:
2392   case LABEL_DECL:
2393   case FUNCTION_DECL:
2394   case SSA_NAME:
2395
2396   case COMPONENT_REF:
2397   case MEM_REF:
2398   case INDIRECT_REF:
2399   case ARRAY_REF:
2400   case ARRAY_RANGE_REF:
2401   case BIT_FIELD_REF:
2402   case OBJ_TYPE_REF:
2403
2404   case REALPART_EXPR:
2405   case IMAGPART_EXPR:
2406   case PREINCREMENT_EXPR:
2407   case PREDECREMENT_EXPR:
2408   case SAVE_EXPR:
2409   case TRY_CATCH_EXPR:
2410   case WITH_CLEANUP_EXPR:
2411   case COMPOUND_EXPR:
2412   case MODIFY_EXPR:
2413   case TARGET_EXPR:
2414   case COND_EXPR:
2415   case BIND_EXPR:
2416     break;
2417
2418   default:
2419     /* Assume the worst for front-end tree codes.  */
2420     if ((int)TREE_CODE (x) >= NUM_TREE_CODES)
2421       break;
2422     return false;
2423   }
2424
2425   return true;
2426 }
2427
2428 /* Return an expr equal to X but certainly not valid as an lvalue.  */
2429
2430 tree
2431 non_lvalue_loc (location_t loc, tree x)
2432 {
2433   /* While we are in GIMPLE, NON_LVALUE_EXPR doesn't mean anything to
2434      us.  */
2435   if (in_gimple_form)
2436     return x;
2437
2438   if (! maybe_lvalue_p (x))
2439     return x;
2440   return build1_loc (loc, NON_LVALUE_EXPR, TREE_TYPE (x), x);
2441 }
2442
2443 /* When pedantic, return an expr equal to X but certainly not valid as a
2444    pedantic lvalue.  Otherwise, return X.  */
2445
2446 static tree
2447 pedantic_non_lvalue_loc (location_t loc, tree x)
2448 {
2449   return protected_set_expr_location_unshare (x, loc);
2450 }
2451 \f
2452 /* Given a tree comparison code, return the code that is the logical inverse.
2453    It is generally not safe to do this for floating-point comparisons, except
2454    for EQ_EXPR, NE_EXPR, ORDERED_EXPR and UNORDERED_EXPR, so we return
2455    ERROR_MARK in this case.  */
2456
2457 enum tree_code
2458 invert_tree_comparison (enum tree_code code, bool honor_nans)
2459 {
2460   if (honor_nans && flag_trapping_math && code != EQ_EXPR && code != NE_EXPR
2461       && code != ORDERED_EXPR && code != UNORDERED_EXPR)
2462     return ERROR_MARK;
2463
2464   switch (code)
2465     {
2466     case EQ_EXPR:
2467       return NE_EXPR;
2468     case NE_EXPR:
2469       return EQ_EXPR;
2470     case GT_EXPR:
2471       return honor_nans ? UNLE_EXPR : LE_EXPR;
2472     case GE_EXPR:
2473       return honor_nans ? UNLT_EXPR : LT_EXPR;
2474     case LT_EXPR:
2475       return honor_nans ? UNGE_EXPR : GE_EXPR;
2476     case LE_EXPR:
2477       return honor_nans ? UNGT_EXPR : GT_EXPR;
2478     case LTGT_EXPR:
2479       return UNEQ_EXPR;
2480     case UNEQ_EXPR:
2481       return LTGT_EXPR;
2482     case UNGT_EXPR:
2483       return LE_EXPR;
2484     case UNGE_EXPR:
2485       return LT_EXPR;
2486     case UNLT_EXPR:
2487       return GE_EXPR;
2488     case UNLE_EXPR:
2489       return GT_EXPR;
2490     case ORDERED_EXPR:
2491       return UNORDERED_EXPR;
2492     case UNORDERED_EXPR:
2493       return ORDERED_EXPR;
2494     default:
2495       gcc_unreachable ();
2496     }
2497 }
2498
2499 /* Similar, but return the comparison that results if the operands are
2500    swapped.  This is safe for floating-point.  */
2501
2502 enum tree_code
2503 swap_tree_comparison (enum tree_code code)
2504 {
2505   switch (code)
2506     {
2507     case EQ_EXPR:
2508     case NE_EXPR:
2509     case ORDERED_EXPR:
2510     case UNORDERED_EXPR:
2511     case LTGT_EXPR:
2512     case UNEQ_EXPR:
2513       return code;
2514     case GT_EXPR:
2515       return LT_EXPR;
2516     case GE_EXPR:
2517       return LE_EXPR;
2518     case LT_EXPR:
2519       return GT_EXPR;
2520     case LE_EXPR:
2521       return GE_EXPR;
2522     case UNGT_EXPR:
2523       return UNLT_EXPR;
2524     case UNGE_EXPR:
2525       return UNLE_EXPR;
2526     case UNLT_EXPR:
2527       return UNGT_EXPR;
2528     case UNLE_EXPR:
2529       return UNGE_EXPR;
2530     default:
2531       gcc_unreachable ();
2532     }
2533 }
2534
2535
2536 /* Convert a comparison tree code from an enum tree_code representation
2537    into a compcode bit-based encoding.  This function is the inverse of
2538    compcode_to_comparison.  */
2539
2540 static enum comparison_code
2541 comparison_to_compcode (enum tree_code code)
2542 {
2543   switch (code)
2544     {
2545     case LT_EXPR:
2546       return COMPCODE_LT;
2547     case EQ_EXPR:
2548       return COMPCODE_EQ;
2549     case LE_EXPR:
2550       return COMPCODE_LE;
2551     case GT_EXPR:
2552       return COMPCODE_GT;
2553     case NE_EXPR:
2554       return COMPCODE_NE;
2555     case GE_EXPR:
2556       return COMPCODE_GE;
2557     case ORDERED_EXPR:
2558       return COMPCODE_ORD;
2559     case UNORDERED_EXPR:
2560       return COMPCODE_UNORD;
2561     case UNLT_EXPR:
2562       return COMPCODE_UNLT;
2563     case UNEQ_EXPR:
2564       return COMPCODE_UNEQ;
2565     case UNLE_EXPR:
2566       return COMPCODE_UNLE;
2567     case UNGT_EXPR:
2568       return COMPCODE_UNGT;
2569     case LTGT_EXPR:
2570       return COMPCODE_LTGT;
2571     case UNGE_EXPR:
2572       return COMPCODE_UNGE;
2573     default:
2574       gcc_unreachable ();
2575     }
2576 }
2577
2578 /* Convert a compcode bit-based encoding of a comparison operator back
2579    to GCC's enum tree_code representation.  This function is the
2580    inverse of comparison_to_compcode.  */
2581
2582 static enum tree_code
2583 compcode_to_comparison (enum comparison_code code)
2584 {
2585   switch (code)
2586     {
2587     case COMPCODE_LT:
2588       return LT_EXPR;
2589     case COMPCODE_EQ:
2590       return EQ_EXPR;
2591     case COMPCODE_LE:
2592       return LE_EXPR;
2593     case COMPCODE_GT:
2594       return GT_EXPR;
2595     case COMPCODE_NE:
2596       return NE_EXPR;
2597     case COMPCODE_GE:
2598       return GE_EXPR;
2599     case COMPCODE_ORD:
2600       return ORDERED_EXPR;
2601     case COMPCODE_UNORD:
2602       return UNORDERED_EXPR;
2603     case COMPCODE_UNLT:
2604       return UNLT_EXPR;
2605     case COMPCODE_UNEQ:
2606       return UNEQ_EXPR;
2607     case COMPCODE_UNLE:
2608       return UNLE_EXPR;
2609     case COMPCODE_UNGT:
2610       return UNGT_EXPR;
2611     case COMPCODE_LTGT:
2612       return LTGT_EXPR;
2613     case COMPCODE_UNGE:
2614       return UNGE_EXPR;
2615     default:
2616       gcc_unreachable ();
2617     }
2618 }
2619
2620 /* Return a tree for the comparison which is the combination of
2621    doing the AND or OR (depending on CODE) of the two operations LCODE
2622    and RCODE on the identical operands LL_ARG and LR_ARG.  Take into account
2623    the possibility of trapping if the mode has NaNs, and return NULL_TREE
2624    if this makes the transformation invalid.  */
2625
2626 tree
2627 combine_comparisons (location_t loc,
2628                      enum tree_code code, enum tree_code lcode,
2629                      enum tree_code rcode, tree truth_type,
2630                      tree ll_arg, tree lr_arg)
2631 {
2632   bool honor_nans = HONOR_NANS (ll_arg);
2633   enum comparison_code lcompcode = comparison_to_compcode (lcode);
2634   enum comparison_code rcompcode = comparison_to_compcode (rcode);
2635   int compcode;
2636
2637   switch (code)
2638     {
2639     case TRUTH_AND_EXPR: case TRUTH_ANDIF_EXPR:
2640       compcode = lcompcode & rcompcode;
2641       break;
2642
2643     case TRUTH_OR_EXPR: case TRUTH_ORIF_EXPR:
2644       compcode = lcompcode | rcompcode;
2645       break;
2646
2647     default:
2648       return NULL_TREE;
2649     }
2650
2651   if (!honor_nans)
2652     {
2653       /* Eliminate unordered comparisons, as well as LTGT and ORD
2654          which are not used unless the mode has NaNs.  */
2655       compcode &= ~COMPCODE_UNORD;
2656       if (compcode == COMPCODE_LTGT)
2657         compcode = COMPCODE_NE;
2658       else if (compcode == COMPCODE_ORD)
2659         compcode = COMPCODE_TRUE;
2660     }
2661    else if (flag_trapping_math)
2662      {
2663         /* Check that the original operation and the optimized ones will trap
2664            under the same condition.  */
2665         bool ltrap = (lcompcode & COMPCODE_UNORD) == 0
2666                      && (lcompcode != COMPCODE_EQ)
2667                      && (lcompcode != COMPCODE_ORD);
2668         bool rtrap = (rcompcode & COMPCODE_UNORD) == 0
2669                      && (rcompcode != COMPCODE_EQ)
2670                      && (rcompcode != COMPCODE_ORD);
2671         bool trap = (compcode & COMPCODE_UNORD) == 0
2672                     && (compcode != COMPCODE_EQ)
2673                     && (compcode != COMPCODE_ORD);
2674
2675         /* In a short-circuited boolean expression the LHS might be
2676            such that the RHS, if evaluated, will never trap.  For
2677            example, in ORD (x, y) && (x < y), we evaluate the RHS only
2678            if neither x nor y is NaN.  (This is a mixed blessing: for
2679            example, the expression above will never trap, hence
2680            optimizing it to x < y would be invalid).  */
2681         if ((code == TRUTH_ORIF_EXPR && (lcompcode & COMPCODE_UNORD))
2682             || (code == TRUTH_ANDIF_EXPR && !(lcompcode & COMPCODE_UNORD)))
2683           rtrap = false;
2684
2685         /* If the comparison was short-circuited, and only the RHS
2686            trapped, we may now generate a spurious trap.  */
2687         if (rtrap && !ltrap
2688             && (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR))
2689           return NULL_TREE;
2690
2691         /* If we changed the conditions that cause a trap, we lose.  */
2692         if ((ltrap || rtrap) != trap)
2693           return NULL_TREE;
2694       }
2695
2696   if (compcode == COMPCODE_TRUE)
2697     return constant_boolean_node (true, truth_type);
2698   else if (compcode == COMPCODE_FALSE)
2699     return constant_boolean_node (false, truth_type);
2700   else
2701     {
2702       enum tree_code tcode;
2703
2704       tcode = compcode_to_comparison ((enum comparison_code) compcode);
2705       return fold_build2_loc (loc, tcode, truth_type, ll_arg, lr_arg);
2706     }
2707 }
2708 \f
2709 /* Return nonzero if two operands (typically of the same tree node)
2710    are necessarily equal. FLAGS modifies behavior as follows:
2711
2712    If OEP_ONLY_CONST is set, only return nonzero for constants.
2713    This function tests whether the operands are indistinguishable;
2714    it does not test whether they are equal using C's == operation.
2715    The distinction is important for IEEE floating point, because
2716    (1) -0.0 and 0.0 are distinguishable, but -0.0==0.0, and
2717    (2) two NaNs may be indistinguishable, but NaN!=NaN.
2718
2719    If OEP_ONLY_CONST is unset, a VAR_DECL is considered equal to itself
2720    even though it may hold multiple values during a function.
2721    This is because a GCC tree node guarantees that nothing else is
2722    executed between the evaluation of its "operands" (which may often
2723    be evaluated in arbitrary order).  Hence if the operands themselves
2724    don't side-effect, the VAR_DECLs, PARM_DECLs etc... must hold the
2725    same value in each operand/subexpression.  Hence leaving OEP_ONLY_CONST
2726    unset means assuming isochronic (or instantaneous) tree equivalence.
2727    Unless comparing arbitrary expression trees, such as from different
2728    statements, this flag can usually be left unset.
2729
2730    If OEP_PURE_SAME is set, then pure functions with identical arguments
2731    are considered the same.  It is used when the caller has other ways
2732    to ensure that global memory is unchanged in between.
2733
2734    If OEP_ADDRESS_OF is set, we are actually comparing addresses of objects,
2735    not values of expressions.
2736
2737    Unless OEP_MATCH_SIDE_EFFECTS is set, the function returns false on
2738    any operand with side effect.  This is unnecesarily conservative in the
2739    case we know that arg0 and arg1 are in disjoint code paths (such as in
2740    ?: operator).  In addition OEP_MATCH_SIDE_EFFECTS is used when comparing
2741    addresses with TREE_CONSTANT flag set so we know that &var == &var
2742    even if var is volatile.  */
2743
2744 int
2745 operand_equal_p (const_tree arg0, const_tree arg1, unsigned int flags)
2746 {
2747   /* If either is ERROR_MARK, they aren't equal.  */
2748   if (TREE_CODE (arg0) == ERROR_MARK || TREE_CODE (arg1) == ERROR_MARK
2749       || TREE_TYPE (arg0) == error_mark_node
2750       || TREE_TYPE (arg1) == error_mark_node)
2751     return 0;
2752
2753   /* Similar, if either does not have a type (like a released SSA name),
2754      they aren't equal.  */
2755   if (!TREE_TYPE (arg0) || !TREE_TYPE (arg1))
2756     return 0;
2757
2758   /* We cannot consider pointers to different address space equal.  */
2759   if (POINTER_TYPE_P (TREE_TYPE (arg0))
2760       && POINTER_TYPE_P (TREE_TYPE (arg1))
2761       && (TYPE_ADDR_SPACE (TREE_TYPE (TREE_TYPE (arg0)))
2762           != TYPE_ADDR_SPACE (TREE_TYPE (TREE_TYPE (arg1)))))
2763     return 0;
2764
2765   /* Check equality of integer constants before bailing out due to
2766      precision differences.  */
2767   if (TREE_CODE (arg0) == INTEGER_CST && TREE_CODE (arg1) == INTEGER_CST)
2768     {
2769       /* Address of INTEGER_CST is not defined; check that we did not forget
2770          to drop the OEP_ADDRESS_OF flags.  */
2771       gcc_checking_assert (!(flags & OEP_ADDRESS_OF));
2772       return tree_int_cst_equal (arg0, arg1);
2773     }
2774
2775   if (!(flags & OEP_ADDRESS_OF))
2776     {
2777       /* If both types don't have the same signedness, then we can't consider
2778          them equal.  We must check this before the STRIP_NOPS calls
2779          because they may change the signedness of the arguments.  As pointers
2780          strictly don't have a signedness, require either two pointers or
2781          two non-pointers as well.  */
2782       if (TYPE_UNSIGNED (TREE_TYPE (arg0)) != TYPE_UNSIGNED (TREE_TYPE (arg1))
2783           || POINTER_TYPE_P (TREE_TYPE (arg0))
2784                              != POINTER_TYPE_P (TREE_TYPE (arg1)))
2785         return 0;
2786
2787       /* If both types don't have the same precision, then it is not safe
2788          to strip NOPs.  */
2789       if (element_precision (TREE_TYPE (arg0))
2790           != element_precision (TREE_TYPE (arg1)))
2791         return 0;
2792
2793       STRIP_NOPS (arg0);
2794       STRIP_NOPS (arg1);
2795     }
2796 #if 0
2797   /* FIXME: Fortran FE currently produce ADDR_EXPR of NOP_EXPR. Enable the
2798      sanity check once the issue is solved.  */
2799   else
2800     /* Addresses of conversions and SSA_NAMEs (and many other things)
2801        are not defined.  Check that we did not forget to drop the
2802        OEP_ADDRESS_OF/OEP_CONSTANT_ADDRESS_OF flags.  */
2803     gcc_checking_assert (!CONVERT_EXPR_P (arg0) && !CONVERT_EXPR_P (arg1)
2804                          && TREE_CODE (arg0) != SSA_NAME);
2805 #endif
2806
2807   /* In case both args are comparisons but with different comparison
2808      code, try to swap the comparison operands of one arg to produce
2809      a match and compare that variant.  */
2810   if (TREE_CODE (arg0) != TREE_CODE (arg1)
2811       && COMPARISON_CLASS_P (arg0)
2812       && COMPARISON_CLASS_P (arg1))
2813     {
2814       enum tree_code swap_code = swap_tree_comparison (TREE_CODE (arg1));
2815
2816       if (TREE_CODE (arg0) == swap_code)
2817         return operand_equal_p (TREE_OPERAND (arg0, 0),
2818                                 TREE_OPERAND (arg1, 1), flags)
2819                && operand_equal_p (TREE_OPERAND (arg0, 1),
2820                                    TREE_OPERAND (arg1, 0), flags);
2821     }
2822
2823   if (TREE_CODE (arg0) != TREE_CODE (arg1))
2824     {
2825       /* NOP_EXPR and CONVERT_EXPR are considered equal.  */
2826       if (CONVERT_EXPR_P (arg0) && CONVERT_EXPR_P (arg1))
2827         ;
2828       else if (flags & OEP_ADDRESS_OF)
2829         {
2830           /* If we are interested in comparing addresses ignore
2831              MEM_REF wrappings of the base that can appear just for
2832              TBAA reasons.  */
2833           if (TREE_CODE (arg0) == MEM_REF
2834               && DECL_P (arg1)
2835               && TREE_CODE (TREE_OPERAND (arg0, 0)) == ADDR_EXPR
2836               && TREE_OPERAND (TREE_OPERAND (arg0, 0), 0) == arg1
2837               && integer_zerop (TREE_OPERAND (arg0, 1)))
2838             return 1;
2839           else if (TREE_CODE (arg1) == MEM_REF
2840                    && DECL_P (arg0)
2841                    && TREE_CODE (TREE_OPERAND (arg1, 0)) == ADDR_EXPR
2842                    && TREE_OPERAND (TREE_OPERAND (arg1, 0), 0) == arg0
2843                    && integer_zerop (TREE_OPERAND (arg1, 1)))
2844             return 1;
2845           return 0;
2846         }
2847       else
2848         return 0;
2849     }
2850
2851   /* When not checking adddresses, this is needed for conversions and for
2852      COMPONENT_REF.  Might as well play it safe and always test this.  */
2853   if (TREE_CODE (TREE_TYPE (arg0)) == ERROR_MARK
2854       || TREE_CODE (TREE_TYPE (arg1)) == ERROR_MARK
2855       || (TYPE_MODE (TREE_TYPE (arg0)) != TYPE_MODE (TREE_TYPE (arg1))
2856           && !(flags & OEP_ADDRESS_OF)))
2857     return 0;
2858
2859   /* If ARG0 and ARG1 are the same SAVE_EXPR, they are necessarily equal.
2860      We don't care about side effects in that case because the SAVE_EXPR
2861      takes care of that for us. In all other cases, two expressions are
2862      equal if they have no side effects.  If we have two identical
2863      expressions with side effects that should be treated the same due
2864      to the only side effects being identical SAVE_EXPR's, that will
2865      be detected in the recursive calls below.
2866      If we are taking an invariant address of two identical objects
2867      they are necessarily equal as well.  */
2868   if (arg0 == arg1 && ! (flags & OEP_ONLY_CONST)
2869       && (TREE_CODE (arg0) == SAVE_EXPR
2870           || (flags & OEP_MATCH_SIDE_EFFECTS)
2871           || (! TREE_SIDE_EFFECTS (arg0) && ! TREE_SIDE_EFFECTS (arg1))))
2872     return 1;
2873
2874   /* Next handle constant cases, those for which we can return 1 even
2875      if ONLY_CONST is set.  */
2876   if (TREE_CONSTANT (arg0) && TREE_CONSTANT (arg1))
2877     switch (TREE_CODE (arg0))
2878       {
2879       case INTEGER_CST:
2880         return tree_int_cst_equal (arg0, arg1);
2881
2882       case FIXED_CST:
2883         return FIXED_VALUES_IDENTICAL (TREE_FIXED_CST (arg0),
2884                                        TREE_FIXED_CST (arg1));
2885
2886       case REAL_CST:
2887         if (real_identical (&TREE_REAL_CST (arg0), &TREE_REAL_CST (arg1)))
2888           return 1;
2889
2890
2891         if (!HONOR_SIGNED_ZEROS (arg0))
2892           {
2893             /* If we do not distinguish between signed and unsigned zero,
2894                consider them equal.  */
2895             if (real_zerop (arg0) && real_zerop (arg1))
2896               return 1;
2897           }
2898         return 0;
2899
2900       case VECTOR_CST:
2901         {
2902           unsigned i;
2903
2904           if (VECTOR_CST_NELTS (arg0) != VECTOR_CST_NELTS (arg1))
2905             return 0;
2906
2907           for (i = 0; i < VECTOR_CST_NELTS (arg0); ++i)
2908             {
2909               if (!operand_equal_p (VECTOR_CST_ELT (arg0, i),
2910                                     VECTOR_CST_ELT (arg1, i), flags))
2911                 return 0;
2912             }
2913           return 1;
2914         }
2915
2916       case COMPLEX_CST:
2917         return (operand_equal_p (TREE_REALPART (arg0), TREE_REALPART (arg1),
2918                                  flags)
2919                 && operand_equal_p (TREE_IMAGPART (arg0), TREE_IMAGPART (arg1),
2920                                     flags));
2921
2922       case STRING_CST:
2923         return (TREE_STRING_LENGTH (arg0) == TREE_STRING_LENGTH (arg1)
2924                 && ! memcmp (TREE_STRING_POINTER (arg0),
2925                               TREE_STRING_POINTER (arg1),
2926                               TREE_STRING_LENGTH (arg0)));
2927
2928       case ADDR_EXPR:
2929         gcc_checking_assert (!(flags & OEP_ADDRESS_OF));
2930         return operand_equal_p (TREE_OPERAND (arg0, 0), TREE_OPERAND (arg1, 0),
2931                                 flags | OEP_ADDRESS_OF
2932                                 | OEP_MATCH_SIDE_EFFECTS);
2933       case CONSTRUCTOR:
2934         /* In GIMPLE empty constructors are allowed in initializers of
2935            aggregates.  */
2936         return (!vec_safe_length (CONSTRUCTOR_ELTS (arg0))
2937                 && !vec_safe_length (CONSTRUCTOR_ELTS (arg1)));
2938       default:
2939         break;
2940       }
2941
2942   if (flags & OEP_ONLY_CONST)
2943     return 0;
2944
2945 /* Define macros to test an operand from arg0 and arg1 for equality and a
2946    variant that allows null and views null as being different from any
2947    non-null value.  In the latter case, if either is null, the both
2948    must be; otherwise, do the normal comparison.  */
2949 #define OP_SAME(N) operand_equal_p (TREE_OPERAND (arg0, N),     \
2950                                     TREE_OPERAND (arg1, N), flags)
2951
2952 #define OP_SAME_WITH_NULL(N)                            \
2953   ((!TREE_OPERAND (arg0, N) || !TREE_OPERAND (arg1, N)) \
2954    ? TREE_OPERAND (arg0, N) == TREE_OPERAND (arg1, N) : OP_SAME (N))
2955
2956   switch (TREE_CODE_CLASS (TREE_CODE (arg0)))
2957     {
2958     case tcc_unary:
2959       /* Two conversions are equal only if signedness and modes match.  */
2960       switch (TREE_CODE (arg0))
2961         {
2962         CASE_CONVERT:
2963         case FIX_TRUNC_EXPR:
2964           if (TYPE_UNSIGNED (TREE_TYPE (arg0))
2965               != TYPE_UNSIGNED (TREE_TYPE (arg1)))
2966             return 0;
2967           break;
2968         default:
2969           break;
2970         }
2971
2972       return OP_SAME (0);
2973
2974
2975     case tcc_comparison:
2976     case tcc_binary:
2977       if (OP_SAME (0) && OP_SAME (1))
2978         return 1;
2979
2980       /* For commutative ops, allow the other order.  */
2981       return (commutative_tree_code (TREE_CODE (arg0))
2982               && operand_equal_p (TREE_OPERAND (arg0, 0),
2983                                   TREE_OPERAND (arg1, 1), flags)
2984               && operand_equal_p (TREE_OPERAND (arg0, 1),
2985                                   TREE_OPERAND (arg1, 0), flags));
2986
2987     case tcc_reference:
2988       /* If either of the pointer (or reference) expressions we are
2989          dereferencing contain a side effect, these cannot be equal,
2990          but their addresses can be.  */
2991       if ((flags & OEP_MATCH_SIDE_EFFECTS) == 0
2992           && (TREE_SIDE_EFFECTS (arg0)
2993               || TREE_SIDE_EFFECTS (arg1)))
2994         return 0;
2995
2996       switch (TREE_CODE (arg0))
2997         {
2998         case INDIRECT_REF:
2999           if (!(flags & OEP_ADDRESS_OF)
3000               && (TYPE_ALIGN (TREE_TYPE (arg0))
3001                   != TYPE_ALIGN (TREE_TYPE (arg1))))
3002             return 0;
3003           flags &= ~OEP_ADDRESS_OF;
3004           return OP_SAME (0);
3005
3006         case IMAGPART_EXPR:
3007           /* Require the same offset.  */
3008           if (!operand_equal_p (TYPE_SIZE (TREE_TYPE (arg0)),
3009                                 TYPE_SIZE (TREE_TYPE (arg1)),
3010                                 flags & ~OEP_ADDRESS_OF))
3011             return 0;
3012
3013         /* Fallthru.  */
3014         case REALPART_EXPR:
3015         case VIEW_CONVERT_EXPR:
3016           return OP_SAME (0);
3017
3018         case TARGET_MEM_REF:
3019         case MEM_REF:
3020           if (!(flags & OEP_ADDRESS_OF))
3021             {
3022               /* Require equal access sizes */
3023               if (TYPE_SIZE (TREE_TYPE (arg0)) != TYPE_SIZE (TREE_TYPE (arg1))
3024                   && (!TYPE_SIZE (TREE_TYPE (arg0))
3025                       || !TYPE_SIZE (TREE_TYPE (arg1))
3026                       || !operand_equal_p (TYPE_SIZE (TREE_TYPE (arg0)),
3027                                            TYPE_SIZE (TREE_TYPE (arg1)),
3028                                            flags)))
3029                 return 0;
3030               /* Verify that access happens in similar types.  */
3031               if (!types_compatible_p (TREE_TYPE (arg0), TREE_TYPE (arg1)))
3032                 return 0;
3033               /* Verify that accesses are TBAA compatible.  */
3034               if (!alias_ptr_types_compatible_p
3035                     (TREE_TYPE (TREE_OPERAND (arg0, 1)),
3036                      TREE_TYPE (TREE_OPERAND (arg1, 1)))
3037                   || (MR_DEPENDENCE_CLIQUE (arg0)
3038                       != MR_DEPENDENCE_CLIQUE (arg1))
3039                   || (MR_DEPENDENCE_BASE (arg0)
3040                       != MR_DEPENDENCE_BASE (arg1)))
3041                 return 0;
3042              /* Verify that alignment is compatible.  */
3043              if (TYPE_ALIGN (TREE_TYPE (arg0))
3044                  != TYPE_ALIGN (TREE_TYPE (arg1)))
3045                 return 0;
3046             }
3047           flags &= ~OEP_ADDRESS_OF;
3048           return (OP_SAME (0) && OP_SAME (1)
3049                   /* TARGET_MEM_REF require equal extra operands.  */
3050                   && (TREE_CODE (arg0) != TARGET_MEM_REF
3051                       || (OP_SAME_WITH_NULL (2)
3052                           && OP_SAME_WITH_NULL (3)
3053                           && OP_SAME_WITH_NULL (4))));
3054
3055         case ARRAY_REF:
3056         case ARRAY_RANGE_REF:
3057           if (!OP_SAME (0))
3058             return 0;
3059           flags &= ~OEP_ADDRESS_OF;
3060           /* Compare the array index by value if it is constant first as we
3061              may have different types but same value here.  */
3062           return ((tree_int_cst_equal (TREE_OPERAND (arg0, 1),
3063                                        TREE_OPERAND (arg1, 1))
3064                    || OP_SAME (1))
3065                   && OP_SAME_WITH_NULL (2)
3066                   && OP_SAME_WITH_NULL (3)
3067                   /* Compare low bound and element size as with OEP_ADDRESS_OF
3068                      we have to account for the offset of the ref.  */
3069                   && (TREE_TYPE (TREE_OPERAND (arg0, 0))
3070                       == TREE_TYPE (TREE_OPERAND (arg1, 0))
3071                       || (operand_equal_p (array_ref_low_bound
3072                                              (CONST_CAST_TREE (arg0)),
3073                                            array_ref_low_bound
3074                                              (CONST_CAST_TREE (arg1)), flags)
3075                           && operand_equal_p (array_ref_element_size
3076                                                 (CONST_CAST_TREE (arg0)),
3077                                               array_ref_element_size
3078                                                 (CONST_CAST_TREE (arg1)),
3079                                               flags))));
3080
3081         case COMPONENT_REF:
3082           /* Handle operand 2 the same as for ARRAY_REF.  Operand 0
3083              may be NULL when we're called to compare MEM_EXPRs.  */
3084           if (!OP_SAME_WITH_NULL (0)
3085               || !OP_SAME (1))
3086             return 0;
3087           flags &= ~OEP_ADDRESS_OF;
3088           return OP_SAME_WITH_NULL (2);
3089
3090         case BIT_FIELD_REF:
3091           if (!OP_SAME (0))
3092             return 0;
3093           flags &= ~OEP_ADDRESS_OF;
3094           return OP_SAME (1) && OP_SAME (2);
3095
3096         default:
3097           return 0;
3098         }
3099
3100     case tcc_expression:
3101       switch (TREE_CODE (arg0))
3102         {
3103         case ADDR_EXPR:
3104           /* Be sure we pass right ADDRESS_OF flag.  */
3105           gcc_checking_assert (!(flags & OEP_ADDRESS_OF));
3106           return operand_equal_p (TREE_OPERAND (arg0, 0),
3107                                   TREE_OPERAND (arg1, 0),
3108                                   flags | OEP_ADDRESS_OF);
3109
3110         case TRUTH_NOT_EXPR:
3111           return OP_SAME (0);
3112
3113         case TRUTH_ANDIF_EXPR:
3114         case TRUTH_ORIF_EXPR:
3115           return OP_SAME (0) && OP_SAME (1);
3116
3117         case FMA_EXPR:
3118         case WIDEN_MULT_PLUS_EXPR:
3119         case WIDEN_MULT_MINUS_EXPR:
3120           if (!OP_SAME (2))
3121             return 0;
3122           /* The multiplcation operands are commutative.  */
3123           /* FALLTHRU */
3124
3125         case TRUTH_AND_EXPR:
3126         case TRUTH_OR_EXPR:
3127         case TRUTH_XOR_EXPR:
3128           if (OP_SAME (0) && OP_SAME (1))
3129             return 1;
3130
3131           /* Otherwise take into account this is a commutative operation.  */
3132           return (operand_equal_p (TREE_OPERAND (arg0, 0),
3133                                    TREE_OPERAND (arg1, 1), flags)
3134                   && operand_equal_p (TREE_OPERAND (arg0, 1),
3135                                       TREE_OPERAND (arg1, 0), flags));
3136
3137         case COND_EXPR:
3138           if (! OP_SAME (1) || ! OP_SAME (2))
3139             return 0;
3140           flags &= ~OEP_ADDRESS_OF;
3141           return OP_SAME (0);
3142
3143         case VEC_COND_EXPR:
3144         case DOT_PROD_EXPR:
3145           return OP_SAME (0) && OP_SAME (1) && OP_SAME (2);
3146
3147         case STATEMENT_LIST_END:
3148           return 1;
3149           /* All STATEMENT_LIST_END are equal */
3150
3151         default:
3152           return 0;
3153         }
3154
3155     case tcc_vl_exp:
3156       switch (TREE_CODE (arg0))
3157         {
3158         case CALL_EXPR:
3159           if ((CALL_EXPR_FN (arg0) == NULL_TREE)
3160               != (CALL_EXPR_FN (arg1) == NULL_TREE))
3161             /* If not both CALL_EXPRs are either internal or normal function
3162                functions, then they are not equal.  */
3163             return 0;
3164           else if (CALL_EXPR_FN (arg0) == NULL_TREE)
3165             {
3166               /* If the CALL_EXPRs call different internal functions, then they
3167                  are not equal.  */
3168               if (CALL_EXPR_IFN (arg0) != CALL_EXPR_IFN (arg1))
3169                 return 0;
3170             }
3171           else
3172             {
3173               /* If the CALL_EXPRs call different functions, then they are not
3174                  equal.  */
3175               if (! operand_equal_p (CALL_EXPR_FN (arg0), CALL_EXPR_FN (arg1),
3176                                      flags))
3177                 return 0;
3178             }
3179
3180           /* FIXME: We could skip this test for OEP_MATCH_SIDE_EFFECTS.  */
3181           {
3182             unsigned int cef = call_expr_flags (arg0);
3183             if (flags & OEP_PURE_SAME)
3184               cef &= ECF_CONST | ECF_PURE;
3185             else
3186               cef &= ECF_CONST;
3187             if (!cef)
3188               return 0;
3189           }
3190
3191           /* Now see if all the arguments are the same.  */
3192           {
3193             const_call_expr_arg_iterator iter0, iter1;
3194             const_tree a0, a1;
3195             for (a0 = first_const_call_expr_arg (arg0, &iter0),
3196                    a1 = first_const_call_expr_arg (arg1, &iter1);
3197                  a0 && a1;
3198                  a0 = next_const_call_expr_arg (&iter0),
3199                    a1 = next_const_call_expr_arg (&iter1))
3200               if (! operand_equal_p (a0, a1, flags))
3201                 return 0;
3202
3203             /* If we get here and both argument lists are exhausted
3204                then the CALL_EXPRs are equal.  */
3205             return ! (a0 || a1);
3206           }
3207         default:
3208           return 0;
3209         }
3210
3211     case tcc_declaration:
3212       /* Consider __builtin_sqrt equal to sqrt.  */
3213       return (TREE_CODE (arg0) == FUNCTION_DECL
3214               && DECL_BUILT_IN (arg0) && DECL_BUILT_IN (arg1)
3215               && DECL_BUILT_IN_CLASS (arg0) == DECL_BUILT_IN_CLASS (arg1)
3216               && DECL_FUNCTION_CODE (arg0) == DECL_FUNCTION_CODE (arg1));
3217
3218     case tcc_exceptional:
3219       if (TREE_CODE (arg0) == CONSTRUCTOR)
3220         {
3221           /* In GIMPLE constructors are used only to build vectors from
3222              elements.  Individual elements in the constructor must be
3223              indexed in increasing order and form an initial sequence.
3224
3225              We make no effort to compare constructors in generic.
3226              (see sem_variable::equals in ipa-icf which can do so for
3227               constants).  */
3228           if (!VECTOR_TYPE_P (TREE_TYPE (arg0))
3229               || !VECTOR_TYPE_P (TREE_TYPE (arg1)))
3230             return 0;
3231
3232           /* Be sure that vectors constructed have the same representation.
3233              We only tested element precision and modes to match.
3234              Vectors may be BLKmode and thus also check that the number of
3235              parts match.  */
3236           if (TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0))
3237               != TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg1)))
3238             return 0;
3239
3240           vec<constructor_elt, va_gc> *v0 = CONSTRUCTOR_ELTS (arg0);
3241           vec<constructor_elt, va_gc> *v1 = CONSTRUCTOR_ELTS (arg1);
3242           unsigned int len = vec_safe_length (v0);
3243
3244           if (len != vec_safe_length (v1))
3245             return 0;
3246
3247           for (unsigned int i = 0; i < len; i++)
3248             {
3249               constructor_elt *c0 = &(*v0)[i];
3250               constructor_elt *c1 = &(*v1)[i];
3251
3252               if (!operand_equal_p (c0->value, c1->value, flags)
3253                   /* In GIMPLE the indexes can be either NULL or matching i.
3254                      Double check this so we won't get false
3255                      positives for GENERIC.  */
3256                   || (c0->index
3257                       && (TREE_CODE (c0->index) != INTEGER_CST
3258                           || !compare_tree_int (c0->index, i)))
3259                   || (c1->index
3260                       && (TREE_CODE (c1->index) != INTEGER_CST
3261                           || !compare_tree_int (c1->index, i))))
3262                 return 0;
3263             }
3264           return 1;
3265         }
3266       return 0;
3267
3268     default:
3269       return 0;
3270     }
3271
3272 #undef OP_SAME
3273 #undef OP_SAME_WITH_NULL
3274 }
3275 \f
3276 /* Similar to operand_equal_p, but see if ARG0 might have been made by
3277    shorten_compare from ARG1 when ARG1 was being compared with OTHER.
3278
3279    When in doubt, return 0.  */
3280
3281 static int
3282 operand_equal_for_comparison_p (tree arg0, tree arg1, tree other)
3283 {
3284   int unsignedp1, unsignedpo;
3285   tree primarg0, primarg1, primother;
3286   unsigned int correct_width;
3287
3288   if (operand_equal_p (arg0, arg1, 0))
3289     return 1;
3290
3291   if (! INTEGRAL_TYPE_P (TREE_TYPE (arg0))
3292       || ! INTEGRAL_TYPE_P (TREE_TYPE (arg1)))
3293     return 0;
3294
3295   /* Discard any conversions that don't change the modes of ARG0 and ARG1
3296      and see if the inner values are the same.  This removes any
3297      signedness comparison, which doesn't matter here.  */
3298   primarg0 = arg0, primarg1 = arg1;
3299   STRIP_NOPS (primarg0);
3300   STRIP_NOPS (primarg1);
3301   if (operand_equal_p (primarg0, primarg1, 0))
3302     return 1;
3303
3304   /* Duplicate what shorten_compare does to ARG1 and see if that gives the
3305      actual comparison operand, ARG0.
3306
3307      First throw away any conversions to wider types
3308      already present in the operands.  */
3309
3310   primarg1 = get_narrower (arg1, &unsignedp1);
3311   primother = get_narrower (other, &unsignedpo);
3312
3313   correct_width = TYPE_PRECISION (TREE_TYPE (arg1));
3314   if (unsignedp1 == unsignedpo
3315       && TYPE_PRECISION (TREE_TYPE (primarg1)) < correct_width
3316       && TYPE_PRECISION (TREE_TYPE (primother)) < correct_width)
3317     {
3318       tree type = TREE_TYPE (arg0);
3319
3320       /* Make sure shorter operand is extended the right way
3321          to match the longer operand.  */
3322       primarg1 = fold_convert (signed_or_unsigned_type_for
3323                                (unsignedp1, TREE_TYPE (primarg1)), primarg1);
3324
3325       if (operand_equal_p (arg0, fold_convert (type, primarg1), 0))
3326         return 1;
3327     }
3328
3329   return 0;
3330 }
3331 \f
3332 /* See if ARG is an expression that is either a comparison or is performing
3333    arithmetic on comparisons.  The comparisons must only be comparing
3334    two different values, which will be stored in *CVAL1 and *CVAL2; if
3335    they are nonzero it means that some operands have already been found.
3336    No variables may be used anywhere else in the expression except in the
3337    comparisons.  If SAVE_P is true it means we removed a SAVE_EXPR around
3338    the expression and save_expr needs to be called with CVAL1 and CVAL2.
3339
3340    If this is true, return 1.  Otherwise, return zero.  */
3341
3342 static int
3343 twoval_comparison_p (tree arg, tree *cval1, tree *cval2, int *save_p)
3344 {
3345   enum tree_code code = TREE_CODE (arg);
3346   enum tree_code_class tclass = TREE_CODE_CLASS (code);
3347
3348   /* We can handle some of the tcc_expression cases here.  */
3349   if (tclass == tcc_expression && code == TRUTH_NOT_EXPR)
3350     tclass = tcc_unary;
3351   else if (tclass == tcc_expression
3352            && (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR
3353                || code == COMPOUND_EXPR))
3354     tclass = tcc_binary;
3355
3356   else if (tclass == tcc_expression && code == SAVE_EXPR
3357            && ! TREE_SIDE_EFFECTS (TREE_OPERAND (arg, 0)))
3358     {
3359       /* If we've already found a CVAL1 or CVAL2, this expression is
3360          two complex to handle.  */
3361       if (*cval1 || *cval2)
3362         return 0;
3363
3364       tclass = tcc_unary;
3365       *save_p = 1;
3366     }
3367
3368   switch (tclass)
3369     {
3370     case tcc_unary:
3371       return twoval_comparison_p (TREE_OPERAND (arg, 0), cval1, cval2, save_p);
3372
3373     case tcc_binary:
3374       return (twoval_comparison_p (TREE_OPERAND (arg, 0), cval1, cval2, save_p)
3375               && twoval_comparison_p (TREE_OPERAND (arg, 1),
3376                                       cval1, cval2, save_p));
3377
3378     case tcc_constant:
3379       return 1;
3380
3381     case tcc_expression:
3382       if (code == COND_EXPR)
3383         return (twoval_comparison_p (TREE_OPERAND (arg, 0),
3384                                      cval1, cval2, save_p)
3385                 && twoval_comparison_p (TREE_OPERAND (arg, 1),
3386                                         cval1, cval2, save_p)
3387                 && twoval_comparison_p (TREE_OPERAND (arg, 2),
3388                                         cval1, cval2, save_p));
3389       return 0;
3390
3391     case tcc_comparison:
3392       /* First see if we can handle the first operand, then the second.  For
3393          the second operand, we know *CVAL1 can't be zero.  It must be that
3394          one side of the comparison is each of the values; test for the
3395          case where this isn't true by failing if the two operands
3396          are the same.  */
3397
3398       if (operand_equal_p (TREE_OPERAND (arg, 0),
3399                            TREE_OPERAND (arg, 1), 0))
3400         return 0;
3401
3402       if (*cval1 == 0)
3403         *cval1 = TREE_OPERAND (arg, 0);
3404       else if (operand_equal_p (*cval1, TREE_OPERAND (arg, 0), 0))
3405         ;
3406       else if (*cval2 == 0)
3407         *cval2 = TREE_OPERAND (arg, 0);
3408       else if (operand_equal_p (*cval2, TREE_OPERAND (arg, 0), 0))
3409         ;
3410       else
3411         return 0;
3412
3413       if (operand_equal_p (*cval1, TREE_OPERAND (arg, 1), 0))
3414         ;
3415       else if (*cval2 == 0)
3416         *cval2 = TREE_OPERAND (arg, 1);
3417       else if (operand_equal_p (*cval2, TREE_OPERAND (arg, 1), 0))
3418         ;
3419       else
3420         return 0;
3421
3422       return 1;
3423
3424     default:
3425       return 0;
3426     }
3427 }
3428 \f
3429 /* ARG is a tree that is known to contain just arithmetic operations and
3430    comparisons.  Evaluate the operations in the tree substituting NEW0 for
3431    any occurrence of OLD0 as an operand of a comparison and likewise for
3432    NEW1 and OLD1.  */
3433
3434 static tree
3435 eval_subst (location_t loc, tree arg, tree old0, tree new0,
3436             tree old1, tree new1)
3437 {
3438   tree type = TREE_TYPE (arg);
3439   enum tree_code code = TREE_CODE (arg);
3440   enum tree_code_class tclass = TREE_CODE_CLASS (code);
3441
3442   /* We can handle some of the tcc_expression cases here.  */
3443   if (tclass == tcc_expression && code == TRUTH_NOT_EXPR)
3444     tclass = tcc_unary;
3445   else if (tclass == tcc_expression
3446            && (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR))
3447     tclass = tcc_binary;
3448
3449   switch (tclass)
3450     {
3451     case tcc_unary:
3452       return fold_build1_loc (loc, code, type,
3453                           eval_subst (loc, TREE_OPERAND (arg, 0),
3454                                       old0, new0, old1, new1));
3455
3456     case tcc_binary:
3457       return fold_build2_loc (loc, code, type,
3458                           eval_subst (loc, TREE_OPERAND (arg, 0),
3459                                       old0, new0, old1, new1),
3460                           eval_subst (loc, TREE_OPERAND (arg, 1),
3461                                       old0, new0, old1, new1));
3462
3463     case tcc_expression:
3464       switch (code)
3465         {
3466         case SAVE_EXPR:
3467           return eval_subst (loc, TREE_OPERAND (arg, 0), old0, new0,
3468                              old1, new1);
3469
3470         case COMPOUND_EXPR:
3471           return eval_subst (loc, TREE_OPERAND (arg, 1), old0, new0,
3472                              old1, new1);
3473
3474         case COND_EXPR:
3475           return fold_build3_loc (loc, code, type,
3476                               eval_subst (loc, TREE_OPERAND (arg, 0),
3477                                           old0, new0, old1, new1),
3478                               eval_subst (loc, TREE_OPERAND (arg, 1),
3479                                           old0, new0, old1, new1),
3480                               eval_subst (loc, TREE_OPERAND (arg, 2),
3481                                           old0, new0, old1, new1));
3482         default:
3483           break;
3484         }
3485       /* Fall through - ???  */
3486
3487     case tcc_comparison:
3488       {
3489         tree arg0 = TREE_OPERAND (arg, 0);
3490         tree arg1 = TREE_OPERAND (arg, 1);
3491
3492         /* We need to check both for exact equality and tree equality.  The
3493            former will be true if the operand has a side-effect.  In that
3494            case, we know the operand occurred exactly once.  */
3495
3496         if (arg0 == old0 || operand_equal_p (arg0, old0, 0))
3497           arg0 = new0;
3498         else if (arg0 == old1 || operand_equal_p (arg0, old1, 0))
3499           arg0 = new1;
3500
3501         if (arg1 == old0 || operand_equal_p (arg1, old0, 0))
3502           arg1 = new0;
3503         else if (arg1 == old1 || operand_equal_p (arg1, old1, 0))
3504           arg1 = new1;
3505
3506         return fold_build2_loc (loc, code, type, arg0, arg1);
3507       }
3508
3509     default:
3510       return arg;
3511     }
3512 }
3513 \f
3514 /* Return a tree for the case when the result of an expression is RESULT
3515    converted to TYPE and OMITTED was previously an operand of the expression
3516    but is now not needed (e.g., we folded OMITTED * 0).
3517
3518    If OMITTED has side effects, we must evaluate it.  Otherwise, just do
3519    the conversion of RESULT to TYPE.  */
3520
3521 tree
3522 omit_one_operand_loc (location_t loc, tree type, tree result, tree omitted)
3523 {
3524   tree t = fold_convert_loc (loc, type, result);
3525
3526   /* If the resulting operand is an empty statement, just return the omitted
3527      statement casted to void. */
3528   if (IS_EMPTY_STMT (t) && TREE_SIDE_EFFECTS (omitted))
3529     return build1_loc (loc, NOP_EXPR, void_type_node,
3530                        fold_ignored_result (omitted));
3531
3532   if (TREE_SIDE_EFFECTS (omitted))
3533     return build2_loc (loc, COMPOUND_EXPR, type,
3534                        fold_ignored_result (omitted), t);
3535
3536   return non_lvalue_loc (loc, t);
3537 }
3538
3539 /* Return a tree for the case when the result of an expression is RESULT
3540    converted to TYPE and OMITTED1 and OMITTED2 were previously operands
3541    of the expression but are now not needed.
3542
3543    If OMITTED1 or OMITTED2 has side effects, they must be evaluated.
3544    If both OMITTED1 and OMITTED2 have side effects, OMITTED1 is
3545    evaluated before OMITTED2.  Otherwise, if neither has side effects,
3546    just do the conversion of RESULT to TYPE.  */
3547
3548 tree
3549 omit_two_operands_loc (location_t loc, tree type, tree result,
3550                        tree omitted1, tree omitted2)
3551 {
3552   tree t = fold_convert_loc (loc, type, result);
3553
3554   if (TREE_SIDE_EFFECTS (omitted2))
3555     t = build2_loc (loc, COMPOUND_EXPR, type, omitted2, t);
3556   if (TREE_SIDE_EFFECTS (omitted1))
3557     t = build2_loc (loc, COMPOUND_EXPR, type, omitted1, t);
3558
3559   return TREE_CODE (t) != COMPOUND_EXPR ? non_lvalue_loc (loc, t) : t;
3560 }
3561
3562 \f
3563 /* Return a simplified tree node for the truth-negation of ARG.  This
3564    never alters ARG itself.  We assume that ARG is an operation that
3565    returns a truth value (0 or 1).
3566
3567    FIXME: one would think we would fold the result, but it causes
3568    problems with the dominator optimizer.  */
3569
3570 static tree
3571 fold_truth_not_expr (location_t loc, tree arg)
3572 {
3573   tree type = TREE_TYPE (arg);
3574   enum tree_code code = TREE_CODE (arg);
3575   location_t loc1, loc2;
3576
3577   /* If this is a comparison, we can simply invert it, except for
3578      floating-point non-equality comparisons, in which case we just
3579      enclose a TRUTH_NOT_EXPR around what we have.  */
3580
3581   if (TREE_CODE_CLASS (code) == tcc_comparison)
3582     {
3583       tree op_type = TREE_TYPE (TREE_OPERAND (arg, 0));
3584       if (FLOAT_TYPE_P (op_type)
3585           && flag_trapping_math
3586           && code != ORDERED_EXPR && code != UNORDERED_EXPR
3587           && code != NE_EXPR && code != EQ_EXPR)
3588         return NULL_TREE;
3589
3590       code = invert_tree_comparison (code, HONOR_NANS (op_type));
3591       if (code == ERROR_MARK)
3592         return NULL_TREE;
3593
3594       tree ret = build2_loc (loc, code, type, TREE_OPERAND (arg, 0),
3595                              TREE_OPERAND (arg, 1));
3596       if (TREE_NO_WARNING (arg))
3597         TREE_NO_WARNING (ret) = 1;
3598       return ret;
3599     }
3600
3601   switch (code)
3602     {
3603     case INTEGER_CST:
3604       return constant_boolean_node (integer_zerop (arg), type);
3605
3606     case TRUTH_AND_EXPR:
3607       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3608       loc2 = expr_location_or (TREE_OPERAND (arg, 1), loc);
3609       return build2_loc (loc, TRUTH_OR_EXPR, type,
3610                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)),
3611                          invert_truthvalue_loc (loc2, TREE_OPERAND (arg, 1)));
3612
3613     case TRUTH_OR_EXPR:
3614       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3615       loc2 = expr_location_or (TREE_OPERAND (arg, 1), loc);
3616       return build2_loc (loc, TRUTH_AND_EXPR, type,
3617                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)),
3618                          invert_truthvalue_loc (loc2, TREE_OPERAND (arg, 1)));
3619
3620     case TRUTH_XOR_EXPR:
3621       /* Here we can invert either operand.  We invert the first operand
3622          unless the second operand is a TRUTH_NOT_EXPR in which case our
3623          result is the XOR of the first operand with the inside of the
3624          negation of the second operand.  */
3625
3626       if (TREE_CODE (TREE_OPERAND (arg, 1)) == TRUTH_NOT_EXPR)
3627         return build2_loc (loc, TRUTH_XOR_EXPR, type, TREE_OPERAND (arg, 0),
3628                            TREE_OPERAND (TREE_OPERAND (arg, 1), 0));
3629       else
3630         return build2_loc (loc, TRUTH_XOR_EXPR, type,
3631                            invert_truthvalue_loc (loc, TREE_OPERAND (arg, 0)),
3632                            TREE_OPERAND (arg, 1));
3633
3634     case TRUTH_ANDIF_EXPR:
3635       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3636       loc2 = expr_location_or (TREE_OPERAND (arg, 1), loc);
3637       return build2_loc (loc, TRUTH_ORIF_EXPR, type,
3638                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)),
3639                          invert_truthvalue_loc (loc2, TREE_OPERAND (arg, 1)));
3640
3641     case TRUTH_ORIF_EXPR:
3642       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3643       loc2 = expr_location_or (TREE_OPERAND (arg, 1), loc);
3644       return build2_loc (loc, TRUTH_ANDIF_EXPR, type,
3645                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)),
3646                          invert_truthvalue_loc (loc2, TREE_OPERAND (arg, 1)));
3647
3648     case TRUTH_NOT_EXPR:
3649       return TREE_OPERAND (arg, 0);
3650
3651     case COND_EXPR:
3652       {
3653         tree arg1 = TREE_OPERAND (arg, 1);
3654         tree arg2 = TREE_OPERAND (arg, 2);
3655
3656         loc1 = expr_location_or (TREE_OPERAND (arg, 1), loc);
3657         loc2 = expr_location_or (TREE_OPERAND (arg, 2), loc);
3658
3659         /* A COND_EXPR may have a throw as one operand, which
3660            then has void type.  Just leave void operands
3661            as they are.  */
3662         return build3_loc (loc, COND_EXPR, type, TREE_OPERAND (arg, 0),
3663                            VOID_TYPE_P (TREE_TYPE (arg1))
3664                            ? arg1 : invert_truthvalue_loc (loc1, arg1),
3665                            VOID_TYPE_P (TREE_TYPE (arg2))
3666                            ? arg2 : invert_truthvalue_loc (loc2, arg2));
3667       }
3668
3669     case COMPOUND_EXPR:
3670       loc1 = expr_location_or (TREE_OPERAND (arg, 1), loc);
3671       return build2_loc (loc, COMPOUND_EXPR, type,
3672                          TREE_OPERAND (arg, 0),
3673                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 1)));
3674
3675     case NON_LVALUE_EXPR:
3676       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3677       return invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0));
3678
3679     CASE_CONVERT:
3680       if (TREE_CODE (TREE_TYPE (arg)) == BOOLEAN_TYPE)
3681         return build1_loc (loc, TRUTH_NOT_EXPR, type, arg);
3682
3683       /* ... fall through ...  */
3684
3685     case FLOAT_EXPR:
3686       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3687       return build1_loc (loc, TREE_CODE (arg), type,
3688                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)));
3689
3690     case BIT_AND_EXPR:
3691       if (!integer_onep (TREE_OPERAND (arg, 1)))
3692         return NULL_TREE;
3693       return build2_loc (loc, EQ_EXPR, type, arg, build_int_cst (type, 0));
3694
3695     case SAVE_EXPR:
3696       return build1_loc (loc, TRUTH_NOT_EXPR, type, arg);
3697
3698     case CLEANUP_POINT_EXPR:
3699       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3700       return build1_loc (loc, CLEANUP_POINT_EXPR, type,
3701                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)));
3702
3703     default:
3704       return NULL_TREE;
3705     }
3706 }
3707
3708 /* Fold the truth-negation of ARG.  This never alters ARG itself.  We
3709    assume that ARG is an operation that returns a truth value (0 or 1
3710    for scalars, 0 or -1 for vectors).  Return the folded expression if
3711    folding is successful.  Otherwise, return NULL_TREE.  */
3712
3713 static tree
3714 fold_invert_truthvalue (location_t loc, tree arg)
3715 {
3716   tree type = TREE_TYPE (arg);
3717   return fold_unary_loc (loc, VECTOR_TYPE_P (type)
3718                               ? BIT_NOT_EXPR
3719                               : TRUTH_NOT_EXPR,
3720                          type, arg);
3721 }
3722
3723 /* Return a simplified tree node for the truth-negation of ARG.  This
3724    never alters ARG itself.  We assume that ARG is an operation that
3725    returns a truth value (0 or 1 for scalars, 0 or -1 for vectors).  */
3726
3727 tree
3728 invert_truthvalue_loc (location_t loc, tree arg)
3729 {
3730   if (TREE_CODE (arg) == ERROR_MARK)
3731     return arg;
3732
3733   tree type = TREE_TYPE (arg);
3734   return fold_build1_loc (loc, VECTOR_TYPE_P (type)
3735                                ? BIT_NOT_EXPR
3736                                : TRUTH_NOT_EXPR,
3737                           type, arg);
3738 }
3739
3740 /* Knowing that ARG0 and ARG1 are both RDIV_EXPRs, simplify a binary operation
3741    with code CODE.  This optimization is unsafe.  */
3742 static tree
3743 distribute_real_division (location_t loc, enum tree_code code, tree type,
3744                           tree arg0, tree arg1)
3745 {
3746   bool mul0 = TREE_CODE (arg0) == MULT_EXPR;
3747   bool mul1 = TREE_CODE (arg1) == MULT_EXPR;
3748
3749   /* (A / C) +- (B / C) -> (A +- B) / C.  */
3750   if (mul0 == mul1
3751       && operand_equal_p (TREE_OPERAND (arg0, 1),
3752                        TREE_OPERAND (arg1, 1), 0))
3753     return fold_build2_loc (loc, mul0 ? MULT_EXPR : RDIV_EXPR, type,
3754                         fold_build2_loc (loc, code, type,
3755                                      TREE_OPERAND (arg0, 0),
3756                                      TREE_OPERAND (arg1, 0)),
3757                         TREE_OPERAND (arg0, 1));
3758
3759   /* (A / C1) +- (A / C2) -> A * (1 / C1 +- 1 / C2).  */
3760   if (operand_equal_p (TREE_OPERAND (arg0, 0),
3761                        TREE_OPERAND (arg1, 0), 0)
3762       && TREE_CODE (TREE_OPERAND (arg0, 1)) == REAL_CST
3763       && TREE_CODE (TREE_OPERAND (arg1, 1)) == REAL_CST)
3764     {
3765       REAL_VALUE_TYPE r0, r1;
3766       r0 = TREE_REAL_CST (TREE_OPERAND (arg0, 1));
3767       r1 = TREE_REAL_CST (TREE_OPERAND (arg1, 1));
3768       if (!mul0)
3769         real_arithmetic (&r0, RDIV_EXPR, &dconst1, &r0);
3770       if (!mul1)
3771         real_arithmetic (&r1, RDIV_EXPR, &dconst1, &r1);
3772       real_arithmetic (&r0, code, &r0, &r1);
3773       return fold_build2_loc (loc, MULT_EXPR, type,
3774                           TREE_OPERAND (arg0, 0),
3775                           build_real (type, r0));
3776     }
3777
3778   return NULL_TREE;
3779 }
3780 \f
3781 /* Return a BIT_FIELD_REF of type TYPE to refer to BITSIZE bits of INNER
3782    starting at BITPOS.  The field is unsigned if UNSIGNEDP is nonzero
3783    and uses reverse storage order if REVERSEP is nonzero.  ORIG_INNER
3784    is the original memory reference used to preserve the alias set of
3785    the access.  */
3786
3787 static tree
3788 make_bit_field_ref (location_t loc, tree inner, tree orig_inner, tree type,
3789                     HOST_WIDE_INT bitsize, HOST_WIDE_INT bitpos,
3790                     int unsignedp, int reversep)
3791 {
3792   tree result, bftype;
3793
3794   alias_set_type iset = get_alias_set (orig_inner);
3795   if (iset == 0 && get_alias_set (inner) != iset)
3796     inner = fold_build2 (MEM_REF, TREE_TYPE (inner),
3797                          build_fold_addr_expr (inner),
3798                          build_int_cst (ptr_type_node, 0));
3799
3800   if (bitpos == 0 && !reversep)
3801     {
3802       tree size = TYPE_SIZE (TREE_TYPE (inner));
3803       if ((INTEGRAL_TYPE_P (TREE_TYPE (inner))
3804            || POINTER_TYPE_P (TREE_TYPE (inner)))
3805           && tree_fits_shwi_p (size)
3806           && tree_to_shwi (size) == bitsize)
3807         return fold_convert_loc (loc, type, inner);
3808     }
3809
3810   bftype = type;
3811   if (TYPE_PRECISION (bftype) != bitsize
3812       || TYPE_UNSIGNED (bftype) == !unsignedp)
3813     bftype = build_nonstandard_integer_type (bitsize, 0);
3814
3815   result = build3_loc (loc, BIT_FIELD_REF, bftype, inner,
3816                        size_int (bitsize), bitsize_int (bitpos));
3817   REF_REVERSE_STORAGE_ORDER (result) = reversep;
3818
3819   if (bftype != type)
3820     result = fold_convert_loc (loc, type, result);
3821
3822   return result;
3823 }
3824
3825 /* Optimize a bit-field compare.
3826
3827    There are two cases:  First is a compare against a constant and the
3828    second is a comparison of two items where the fields are at the same
3829    bit position relative to the start of a chunk (byte, halfword, word)
3830    large enough to contain it.  In these cases we can avoid the shift
3831    implicit in bitfield extractions.
3832
3833    For constants, we emit a compare of the shifted constant with the
3834    BIT_AND_EXPR of a mask and a byte, halfword, or word of the operand being
3835    compared.  For two fields at the same position, we do the ANDs with the
3836    similar mask and compare the result of the ANDs.
3837
3838    CODE is the comparison code, known to be either NE_EXPR or EQ_EXPR.
3839    COMPARE_TYPE is the type of the comparison, and LHS and RHS
3840    are the left and right operands of the comparison, respectively.
3841
3842    If the optimization described above can be done, we return the resulting
3843    tree.  Otherwise we return zero.  */
3844
3845 static tree
3846 optimize_bit_field_compare (location_t loc, enum tree_code code,
3847                             tree compare_type, tree lhs, tree rhs)
3848 {
3849   HOST_WIDE_INT lbitpos, lbitsize, rbitpos, rbitsize, nbitpos, nbitsize;
3850   tree type = TREE_TYPE (lhs);
3851   tree unsigned_type;
3852   int const_p = TREE_CODE (rhs) == INTEGER_CST;
3853   machine_mode lmode, rmode, nmode;
3854   int lunsignedp, runsignedp;
3855   int lreversep, rreversep;
3856   int lvolatilep = 0, rvolatilep = 0;
3857   tree linner, rinner = NULL_TREE;
3858   tree mask;
3859   tree offset;
3860
3861   /* Get all the information about the extractions being done.  If the bit size
3862      if the same as the size of the underlying object, we aren't doing an
3863      extraction at all and so can do nothing.  We also don't want to
3864      do anything if the inner expression is a PLACEHOLDER_EXPR since we
3865      then will no longer be able to replace it.  */
3866   linner = get_inner_reference (lhs, &lbitsize, &lbitpos, &offset, &lmode,
3867                                 &lunsignedp, &lreversep, &lvolatilep, false);
3868   if (linner == lhs || lbitsize == GET_MODE_BITSIZE (lmode) || lbitsize < 0
3869       || offset != 0 || TREE_CODE (linner) == PLACEHOLDER_EXPR || lvolatilep)
3870     return 0;
3871
3872   if (const_p)
3873     rreversep = lreversep;
3874   else
3875    {
3876      /* If this is not a constant, we can only do something if bit positions,
3877         sizes, signedness and storage order are the same.  */
3878      rinner
3879        = get_inner_reference (rhs, &rbitsize, &rbitpos, &offset, &rmode,
3880                               &runsignedp, &rreversep, &rvolatilep, false);
3881
3882      if (rinner == rhs || lbitpos != rbitpos || lbitsize != rbitsize
3883          || lunsignedp != runsignedp || lreversep != rreversep || offset != 0
3884          || TREE_CODE (rinner) == PLACEHOLDER_EXPR || rvolatilep)
3885        return 0;
3886    }
3887
3888   /* See if we can find a mode to refer to this field.  We should be able to,
3889      but fail if we can't.  */
3890   nmode = get_best_mode (lbitsize, lbitpos, 0, 0,
3891                          const_p ? TYPE_ALIGN (TREE_TYPE (linner))
3892                          : MIN (TYPE_ALIGN (TREE_TYPE (linner)),
3893                                 TYPE_ALIGN (TREE_TYPE (rinner))),
3894                          word_mode, false);
3895   if (nmode == VOIDmode)
3896     return 0;
3897
3898   /* Set signed and unsigned types of the precision of this mode for the
3899      shifts below.  */
3900   unsigned_type = lang_hooks.types.type_for_mode (nmode, 1);
3901
3902   /* Compute the bit position and size for the new reference and our offset
3903      within it. If the new reference is the same size as the original, we
3904      won't optimize anything, so return zero.  */
3905   nbitsize = GET_MODE_BITSIZE (nmode);
3906   nbitpos = lbitpos & ~ (nbitsize - 1);
3907   lbitpos -= nbitpos;
3908   if (nbitsize == lbitsize)
3909     return 0;
3910
3911   if (lreversep ? !BYTES_BIG_ENDIAN : BYTES_BIG_ENDIAN)
3912     lbitpos = nbitsize - lbitsize - lbitpos;
3913
3914   /* Make the mask to be used against the extracted field.  */
3915   mask = build_int_cst_type (unsigned_type, -1);
3916   mask = const_binop (LSHIFT_EXPR, mask, size_int (nbitsize - lbitsize));
3917   mask = const_binop (RSHIFT_EXPR, mask,
3918                       size_int (nbitsize - lbitsize - lbitpos));
3919
3920   if (! const_p)
3921     /* If not comparing with constant, just rework the comparison
3922        and return.  */
3923     return fold_build2_loc (loc, code, compare_type,
3924                         fold_build2_loc (loc, BIT_AND_EXPR, unsigned_type,
3925                                      make_bit_field_ref (loc, linner, lhs,
3926                                                          unsigned_type,
3927                                                          nbitsize, nbitpos,
3928                                                          1, lreversep),
3929                                      mask),
3930                         fold_build2_loc (loc, BIT_AND_EXPR, unsigned_type,
3931                                      make_bit_field_ref (loc, rinner, rhs,
3932                                                          unsigned_type,
3933                                                          nbitsize, nbitpos,
3934                                                          1, rreversep),
3935                                      mask));
3936
3937   /* Otherwise, we are handling the constant case.  See if the constant is too
3938      big for the field.  Warn and return a tree for 0 (false) if so.  We do
3939      this not only for its own sake, but to avoid having to test for this
3940      error case below.  If we didn't, we might generate wrong code.
3941
3942      For unsigned fields, the constant shifted right by the field length should
3943      be all zero.  For signed fields, the high-order bits should agree with
3944      the sign bit.  */
3945
3946   if (lunsignedp)
3947     {
3948       if (wi::lrshift (rhs, lbitsize) != 0)
3949         {
3950           warning (0, "comparison is always %d due to width of bit-field",
3951                    code == NE_EXPR);
3952           return constant_boolean_node (code == NE_EXPR, compare_type);
3953         }
3954     }
3955   else
3956     {
3957       wide_int tem = wi::arshift (rhs, lbitsize - 1);
3958       if (tem != 0 && tem != -1)
3959         {
3960           warning (0, "comparison is always %d due to width of bit-field",
3961                    code == NE_EXPR);
3962           return constant_boolean_node (code == NE_EXPR, compare_type);
3963         }
3964     }
3965
3966   /* Single-bit compares should always be against zero.  */
3967   if (lbitsize == 1 && ! integer_zerop (rhs))
3968     {
3969       code = code == EQ_EXPR ? NE_EXPR : EQ_EXPR;
3970       rhs = build_int_cst (type, 0);
3971     }
3972
3973   /* Make a new bitfield reference, shift the constant over the
3974      appropriate number of bits and mask it with the computed mask
3975      (in case this was a signed field).  If we changed it, make a new one.  */
3976   lhs = make_bit_field_ref (loc, linner, lhs, unsigned_type,
3977                             nbitsize, nbitpos, 1, lreversep);
3978
3979   rhs = const_binop (BIT_AND_EXPR,
3980                      const_binop (LSHIFT_EXPR,
3981                                   fold_convert_loc (loc, unsigned_type, rhs),
3982                                   size_int (lbitpos)),
3983                      mask);
3984
3985   lhs = build2_loc (loc, code, compare_type,
3986                     build2 (BIT_AND_EXPR, unsigned_type, lhs, mask), rhs);
3987   return lhs;
3988 }
3989 \f
3990 /* Subroutine for fold_truth_andor_1: decode a field reference.
3991
3992    If EXP is a comparison reference, we return the innermost reference.
3993
3994    *PBITSIZE is set to the number of bits in the reference, *PBITPOS is
3995    set to the starting bit number.
3996
3997    If the innermost field can be completely contained in a mode-sized
3998    unit, *PMODE is set to that mode.  Otherwise, it is set to VOIDmode.
3999
4000    *PVOLATILEP is set to 1 if the any expression encountered is volatile;
4001    otherwise it is not changed.
4002
4003    *PUNSIGNEDP is set to the signedness of the field.
4004
4005    *PREVERSEP is set to the storage order of the field.
4006
4007    *PMASK is set to the mask used.  This is either contained in a
4008    BIT_AND_EXPR or derived from the width of the field.
4009
4010    *PAND_MASK is set to the mask found in a BIT_AND_EXPR, if any.
4011
4012    Return 0 if this is not a component reference or is one that we can't
4013    do anything with.  */
4014
4015 static tree
4016 decode_field_reference (location_t loc, tree *exp_, HOST_WIDE_INT *pbitsize,
4017                         HOST_WIDE_INT *pbitpos, machine_mode *pmode,
4018                         int *punsignedp, int *preversep, int *pvolatilep,
4019                         tree *pmask, tree *pand_mask)
4020 {
4021   tree exp = *exp_;
4022   tree outer_type = 0;
4023   tree and_mask = 0;
4024   tree mask, inner, offset;
4025   tree unsigned_type;
4026   unsigned int precision;
4027
4028   /* All the optimizations using this function assume integer fields.
4029      There are problems with FP fields since the type_for_size call
4030      below can fail for, e.g., XFmode.  */
4031   if (! INTEGRAL_TYPE_P (TREE_TYPE (exp)))
4032     return 0;
4033
4034   /* We are interested in the bare arrangement of bits, so strip everything
4035      that doesn't affect the machine mode.  However, record the type of the
4036      outermost expression if it may matter below.  */
4037   if (CONVERT_EXPR_P (exp)
4038       || TREE_CODE (exp) == NON_LVALUE_EXPR)
4039     outer_type = TREE_TYPE (exp);
4040   STRIP_NOPS (exp);
4041
4042   if (TREE_CODE (exp) == BIT_AND_EXPR)
4043     {
4044       and_mask = TREE_OPERAND (exp, 1);
4045       exp = TREE_OPERAND (exp, 0);
4046       STRIP_NOPS (exp); STRIP_NOPS (and_mask);
4047       if (TREE_CODE (and_mask) != INTEGER_CST)
4048         return 0;
4049     }
4050
4051   inner = get_inner_reference (exp, pbitsize, pbitpos, &offset, pmode,
4052                                punsignedp, preversep, pvolatilep, false);
4053   if ((inner == exp && and_mask == 0)
4054       || *pbitsize < 0 || offset != 0
4055       || TREE_CODE (inner) == PLACEHOLDER_EXPR)
4056     return 0;
4057
4058   *exp_ = exp;
4059
4060   /* If the number of bits in the reference is the same as the bitsize of
4061      the outer type, then the outer type gives the signedness. Otherwise
4062      (in case of a small bitfield) the signedness is unchanged.  */
4063   if (outer_type && *pbitsize == TYPE_PRECISION (outer_type))
4064     *punsignedp = TYPE_UNSIGNED (outer_type);
4065
4066   /* Compute the mask to access the bitfield.  */
4067   unsigned_type = lang_hooks.types.type_for_size (*pbitsize, 1);
4068   precision = TYPE_PRECISION (unsigned_type);
4069
4070   mask = build_int_cst_type (unsigned_type, -1);
4071
4072   mask = const_binop (LSHIFT_EXPR, mask, size_int (precision - *pbitsize));
4073   mask = const_binop (RSHIFT_EXPR, mask, size_int (precision - *pbitsize));
4074
4075   /* Merge it with the mask we found in the BIT_AND_EXPR, if any.  */
4076   if (and_mask != 0)
4077     mask = fold_build2_loc (loc, BIT_AND_EXPR, unsigned_type,
4078                         fold_convert_loc (loc, unsigned_type, and_mask), mask);
4079
4080   *pmask = mask;
4081   *pand_mask = and_mask;
4082   return inner;
4083 }
4084
4085 /* Return nonzero if MASK represents a mask of SIZE ones in the low-order
4086    bit positions and MASK is SIGNED.  */
4087
4088 static int
4089 all_ones_mask_p (const_tree mask, unsigned int size)
4090 {
4091   tree type = TREE_TYPE (mask);
4092   unsigned int precision = TYPE_PRECISION (type);
4093
4094   /* If this function returns true when the type of the mask is
4095      UNSIGNED, then there will be errors.  In particular see
4096      gcc.c-torture/execute/990326-1.c.  There does not appear to be
4097      any documentation paper trail as to why this is so.  But the pre
4098      wide-int worked with that restriction and it has been preserved
4099      here.  */
4100   if (size > precision || TYPE_SIGN (type) == UNSIGNED)
4101     return false;
4102
4103   return wi::mask (size, false, precision) == mask;
4104 }
4105
4106 /* Subroutine for fold: determine if VAL is the INTEGER_CONST that
4107    represents the sign bit of EXP's type.  If EXP represents a sign
4108    or zero extension, also test VAL against the unextended type.
4109    The return value is the (sub)expression whose sign bit is VAL,
4110    or NULL_TREE otherwise.  */
4111
4112 tree
4113 sign_bit_p (tree exp, const_tree val)
4114 {
4115   int width;
4116   tree t;
4117
4118   /* Tree EXP must have an integral type.  */
4119   t = TREE_TYPE (exp);
4120   if (! INTEGRAL_TYPE_P (t))
4121     return NULL_TREE;
4122
4123   /* Tree VAL must be an integer constant.  */
4124   if (TREE_CODE (val) != INTEGER_CST
4125       || TREE_OVERFLOW (val))
4126     return NULL_TREE;
4127
4128   width = TYPE_PRECISION (t);
4129   if (wi::only_sign_bit_p (val, width))
4130     return exp;
4131
4132   /* Handle extension from a narrower type.  */
4133   if (TREE_CODE (exp) == NOP_EXPR
4134       && TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (exp, 0))) < width)
4135     return sign_bit_p (TREE_OPERAND (exp, 0), val);
4136
4137   return NULL_TREE;
4138 }
4139
4140 /* Subroutine for fold_truth_andor_1: determine if an operand is simple enough
4141    to be evaluated unconditionally.  */
4142
4143 static int
4144 simple_operand_p (const_tree exp)
4145 {
4146   /* Strip any conversions that don't change the machine mode.  */
4147   STRIP_NOPS (exp);
4148
4149   return (CONSTANT_CLASS_P (exp)
4150           || TREE_CODE (exp) == SSA_NAME
4151           || (DECL_P (exp)
4152               && ! TREE_ADDRESSABLE (exp)
4153               && ! TREE_THIS_VOLATILE (exp)
4154               && ! DECL_NONLOCAL (exp)
4155               /* Don't regard global variables as simple.  They may be
4156                  allocated in ways unknown to the compiler (shared memory,
4157                  #pragma weak, etc).  */
4158               && ! TREE_PUBLIC (exp)
4159               && ! DECL_EXTERNAL (exp)
4160               /* Weakrefs are not safe to be read, since they can be NULL.
4161                  They are !TREE_PUBLIC && !DECL_EXTERNAL but still
4162                  have DECL_WEAK flag set.  */
4163               && (! VAR_OR_FUNCTION_DECL_P (exp) || ! DECL_WEAK (exp))
4164               /* Loading a static variable is unduly expensive, but global
4165                  registers aren't expensive.  */
4166               && (! TREE_STATIC (exp) || DECL_REGISTER (exp))));
4167 }
4168
4169 /* Subroutine for fold_truth_andor: determine if an operand is simple enough
4170    to be evaluated unconditionally.
4171    I addition to simple_operand_p, we assume that comparisons, conversions,
4172    and logic-not operations are simple, if their operands are simple, too.  */
4173
4174 static bool
4175 simple_operand_p_2 (tree exp)
4176 {
4177   enum tree_code code;
4178
4179   if (TREE_SIDE_EFFECTS (exp)
4180       || tree_could_trap_p (exp))
4181     return false;
4182
4183   while (CONVERT_EXPR_P (exp))
4184     exp = TREE_OPERAND (exp, 0);
4185
4186   code = TREE_CODE (exp);
4187
4188   if (TREE_CODE_CLASS (code) == tcc_comparison)
4189     return (simple_operand_p (TREE_OPERAND (exp, 0))
4190             && simple_operand_p (TREE_OPERAND (exp, 1)));
4191
4192   if (code == TRUTH_NOT_EXPR)
4193       return simple_operand_p_2 (TREE_OPERAND (exp, 0));
4194
4195   return simple_operand_p (exp);
4196 }
4197
4198 \f
4199 /* The following functions are subroutines to fold_range_test and allow it to
4200    try to change a logical combination of comparisons into a range test.
4201
4202    For example, both
4203         X == 2 || X == 3 || X == 4 || X == 5
4204    and
4205         X >= 2 && X <= 5
4206    are converted to
4207         (unsigned) (X - 2) <= 3
4208
4209    We describe each set of comparisons as being either inside or outside
4210    a range, using a variable named like IN_P, and then describe the
4211    range with a lower and upper bound.  If one of the bounds is omitted,
4212    it represents either the highest or lowest value of the type.
4213
4214    In the comments below, we represent a range by two numbers in brackets
4215    preceded by a "+" to designate being inside that range, or a "-" to
4216    designate being outside that range, so the condition can be inverted by
4217    flipping the prefix.  An omitted bound is represented by a "-".  For
4218    example, "- [-, 10]" means being outside the range starting at the lowest
4219    possible value and ending at 10, in other words, being greater than 10.
4220    The range "+ [-, -]" is always true and hence the range "- [-, -]" is
4221    always false.
4222
4223    We set up things so that the missing bounds are handled in a consistent
4224    manner so neither a missing bound nor "true" and "false" need to be
4225    handled using a special case.  */
4226
4227 /* Return the result of applying CODE to ARG0 and ARG1, but handle the case
4228    of ARG0 and/or ARG1 being omitted, meaning an unlimited range. UPPER0_P
4229    and UPPER1_P are nonzero if the respective argument is an upper bound
4230    and zero for a lower.  TYPE, if nonzero, is the type of the result; it
4231    must be specified for a comparison.  ARG1 will be converted to ARG0's
4232    type if both are specified.  */
4233
4234 static tree
4235 range_binop (enum tree_code code, tree type, tree arg0, int upper0_p,
4236              tree arg1, int upper1_p)
4237 {
4238   tree tem;
4239   int result;
4240   int sgn0, sgn1;
4241
4242   /* If neither arg represents infinity, do the normal operation.
4243      Else, if not a comparison, return infinity.  Else handle the special
4244      comparison rules. Note that most of the cases below won't occur, but
4245      are handled for consistency.  */
4246
4247   if (arg0 != 0 && arg1 != 0)
4248     {
4249       tem = fold_build2 (code, type != 0 ? type : TREE_TYPE (arg0),
4250                          arg0, fold_convert (TREE_TYPE (arg0), arg1));
4251       STRIP_NOPS (tem);
4252       return TREE_CODE (tem) == INTEGER_CST ? tem : 0;
4253     }
4254
4255   if (TREE_CODE_CLASS (code) != tcc_comparison)
4256     return 0;
4257
4258   /* Set SGN[01] to -1 if ARG[01] is a lower bound, 1 for upper, and 0
4259      for neither.  In real maths, we cannot assume open ended ranges are
4260      the same. But, this is computer arithmetic, where numbers are finite.
4261      We can therefore make the transformation of any unbounded range with
4262      the value Z, Z being greater than any representable number. This permits
4263      us to treat unbounded ranges as equal.  */
4264   sgn0 = arg0 != 0 ? 0 : (upper0_p ? 1 : -1);
4265   sgn1 = arg1 != 0 ? 0 : (upper1_p ? 1 : -1);
4266   switch (code)
4267     {
4268     case EQ_EXPR:
4269       result = sgn0 == sgn1;
4270       break;
4271     case NE_EXPR:
4272       result = sgn0 != sgn1;
4273       break;
4274     case LT_EXPR:
4275       result = sgn0 < sgn1;
4276       break;
4277     case LE_EXPR:
4278       result = sgn0 <= sgn1;
4279       break;
4280     case GT_EXPR:
4281       result = sgn0 > sgn1;
4282       break;
4283     case GE_EXPR:
4284       result = sgn0 >= sgn1;
4285       break;
4286     default:
4287       gcc_unreachable ();
4288     }
4289
4290   return constant_boolean_node (result, type);
4291 }
4292 \f
4293 /* Helper routine for make_range.  Perform one step for it, return
4294    new expression if the loop should continue or NULL_TREE if it should
4295    stop.  */
4296
4297 tree
4298 make_range_step (location_t loc, enum tree_code code, tree arg0, tree arg1,
4299                  tree exp_type, tree *p_low, tree *p_high, int *p_in_p,
4300                  bool *strict_overflow_p)
4301 {
4302   tree arg0_type = TREE_TYPE (arg0);
4303   tree n_low, n_high, low = *p_low, high = *p_high;
4304   int in_p = *p_in_p, n_in_p;
4305
4306   switch (code)
4307     {
4308     case TRUTH_NOT_EXPR:
4309       /* We can only do something if the range is testing for zero.  */
4310       if (low == NULL_TREE || high == NULL_TREE
4311           || ! integer_zerop (low) || ! integer_zerop (high))
4312         return NULL_TREE;
4313       *p_in_p = ! in_p;
4314       return arg0;
4315
4316     case EQ_EXPR: case NE_EXPR:
4317     case LT_EXPR: case LE_EXPR: case GE_EXPR: case GT_EXPR:
4318       /* We can only do something if the range is testing for zero
4319          and if the second operand is an integer constant.  Note that
4320          saying something is "in" the range we make is done by
4321          complementing IN_P since it will set in the initial case of
4322          being not equal to zero; "out" is leaving it alone.  */
4323       if (low == NULL_TREE || high == NULL_TREE
4324           || ! integer_zerop (low) || ! integer_zerop (high)
4325           || TREE_CODE (arg1) != INTEGER_CST)
4326         return NULL_TREE;
4327
4328       switch (code)
4329         {
4330         case NE_EXPR:  /* - [c, c]  */
4331           low = high = arg1;
4332           break;
4333         case EQ_EXPR:  /* + [c, c]  */
4334           in_p = ! in_p, low = high = arg1;
4335           break;
4336         case GT_EXPR:  /* - [-, c] */
4337           low = 0, high = arg1;
4338           break;
4339         case GE_EXPR:  /* + [c, -] */
4340           in_p = ! in_p, low = arg1, high = 0;
4341           break;
4342         case LT_EXPR:  /* - [c, -] */
4343           low = arg1, high = 0;
4344           break;
4345         case LE_EXPR:  /* + [-, c] */
4346           in_p = ! in_p, low = 0, high = arg1;
4347           break;
4348         default:
4349           gcc_unreachable ();
4350         }
4351
4352       /* If this is an unsigned comparison, we also know that EXP is
4353          greater than or equal to zero.  We base the range tests we make
4354          on that fact, so we record it here so we can parse existing
4355          range tests.  We test arg0_type since often the return type
4356          of, e.g. EQ_EXPR, is boolean.  */
4357       if (TYPE_UNSIGNED (arg0_type) && (low == 0 || high == 0))
4358         {
4359           if (! merge_ranges (&n_in_p, &n_low, &n_high,
4360                               in_p, low, high, 1,
4361                               build_int_cst (arg0_type, 0),
4362                               NULL_TREE))
4363             return NULL_TREE;
4364
4365           in_p = n_in_p, low = n_low, high = n_high;
4366
4367           /* If the high bound is missing, but we have a nonzero low
4368              bound, reverse the range so it goes from zero to the low bound
4369              minus 1.  */
4370           if (high == 0 && low && ! integer_zerop (low))
4371             {
4372               in_p = ! in_p;
4373               high = range_binop (MINUS_EXPR, NULL_TREE, low, 0,
4374                                   build_int_cst (TREE_TYPE (low), 1), 0);
4375               low = build_int_cst (arg0_type, 0);
4376             }
4377         }
4378
4379       *p_low = low;
4380       *p_high = high;
4381       *p_in_p = in_p;
4382       return arg0;
4383
4384     case NEGATE_EXPR:
4385       /* If flag_wrapv and ARG0_TYPE is signed, make sure
4386          low and high are non-NULL, then normalize will DTRT.  */
4387       if (!TYPE_UNSIGNED (arg0_type)
4388           && !TYPE_OVERFLOW_UNDEFINED (arg0_type))
4389         {
4390           if (low == NULL_TREE)
4391             low = TYPE_MIN_VALUE (arg0_type);
4392           if (high == NULL_TREE)
4393             high = TYPE_MAX_VALUE (arg0_type);
4394         }
4395
4396       /* (-x) IN [a,b] -> x in [-b, -a]  */
4397       n_low = range_binop (MINUS_EXPR, exp_type,
4398                            build_int_cst (exp_type, 0),
4399                            0, high, 1);
4400       n_high = range_binop (MINUS_EXPR, exp_type,
4401                             build_int_cst (exp_type, 0),
4402                             0, low, 0);
4403       if (n_high != 0 && TREE_OVERFLOW (n_high))
4404         return NULL_TREE;
4405       goto normalize;
4406
4407     case BIT_NOT_EXPR:
4408       /* ~ X -> -X - 1  */
4409       return build2_loc (loc, MINUS_EXPR, exp_type, negate_expr (arg0),
4410                          build_int_cst (exp_type, 1));
4411
4412     case PLUS_EXPR:
4413     case MINUS_EXPR:
4414       if (TREE_CODE (arg1) != INTEGER_CST)
4415         return NULL_TREE;
4416
4417       /* If flag_wrapv and ARG0_TYPE is signed, then we cannot
4418          move a constant to the other side.  */
4419       if (!TYPE_UNSIGNED (arg0_type)
4420           && !TYPE_OVERFLOW_UNDEFINED (arg0_type))
4421         return NULL_TREE;
4422
4423       /* If EXP is signed, any overflow in the computation is undefined,
4424          so we don't worry about it so long as our computations on
4425          the bounds don't overflow.  For unsigned, overflow is defined
4426          and this is exactly the right thing.  */
4427       n_low = range_binop (code == MINUS_EXPR ? PLUS_EXPR : MINUS_EXPR,
4428                            arg0_type, low, 0, arg1, 0);
4429       n_high = range_binop (code == MINUS_EXPR ? PLUS_EXPR : MINUS_EXPR,
4430                             arg0_type, high, 1, arg1, 0);
4431       if ((n_low != 0 && TREE_OVERFLOW (n_low))
4432           || (n_high != 0 && TREE_OVERFLOW (n_high)))
4433         return NULL_TREE;
4434
4435       if (TYPE_OVERFLOW_UNDEFINED (arg0_type))
4436         *strict_overflow_p = true;
4437
4438       normalize:
4439         /* Check for an unsigned range which has wrapped around the maximum
4440            value thus making n_high < n_low, and normalize it.  */
4441         if (n_low && n_high && tree_int_cst_lt (n_high, n_low))
4442           {
4443             low = range_binop (PLUS_EXPR, arg0_type, n_high, 0,
4444                                build_int_cst (TREE_TYPE (n_high), 1), 0);
4445             high = range_binop (MINUS_EXPR, arg0_type, n_low, 0,
4446                                 build_int_cst (TREE_TYPE (n_low), 1), 0);
4447
4448             /* If the range is of the form +/- [ x+1, x ], we won't
4449                be able to normalize it.  But then, it represents the
4450                whole range or the empty set, so make it
4451                +/- [ -, - ].  */
4452             if (tree_int_cst_equal (n_low, low)
4453                 && tree_int_cst_equal (n_high, high))
4454               low = high = 0;
4455             else
4456               in_p = ! in_p;
4457           }
4458         else
4459           low = n_low, high = n_high;
4460
4461         *p_low = low;
4462         *p_high = high;
4463         *p_in_p = in_p;
4464         return arg0;
4465
4466     CASE_CONVERT:
4467     case NON_LVALUE_EXPR:
4468       if (TYPE_PRECISION (arg0_type) > TYPE_PRECISION (exp_type))
4469         return NULL_TREE;
4470
4471       if (! INTEGRAL_TYPE_P (arg0_type)
4472           || (low != 0 && ! int_fits_type_p (low, arg0_type))
4473           || (high != 0 && ! int_fits_type_p (high, arg0_type)))
4474         return NULL_TREE;
4475
4476       n_low = low, n_high = high;
4477
4478       if (n_low != 0)
4479         n_low = fold_convert_loc (loc, arg0_type, n_low);
4480
4481       if (n_high != 0)
4482         n_high = fold_convert_loc (loc, arg0_type, n_high);
4483
4484       /* If we're converting arg0 from an unsigned type, to exp,
4485          a signed type,  we will be doing the comparison as unsigned.
4486          The tests above have already verified that LOW and HIGH
4487          are both positive.
4488
4489          So we have to ensure that we will handle large unsigned
4490          values the same way that the current signed bounds treat
4491          negative values.  */
4492
4493       if (!TYPE_UNSIGNED (exp_type) && TYPE_UNSIGNED (arg0_type))
4494         {
4495           tree high_positive;
4496           tree equiv_type;
4497           /* For fixed-point modes, we need to pass the saturating flag
4498              as the 2nd parameter.  */
4499           if (ALL_FIXED_POINT_MODE_P (TYPE_MODE (arg0_type)))
4500             equiv_type
4501               = lang_hooks.types.type_for_mode (TYPE_MODE (arg0_type),
4502                                                 TYPE_SATURATING (arg0_type));
4503           else
4504             equiv_type
4505               = lang_hooks.types.type_for_mode (TYPE_MODE (arg0_type), 1);
4506
4507           /* A range without an upper bound is, naturally, unbounded.
4508              Since convert would have cropped a very large value, use
4509              the max value for the destination type.  */
4510           high_positive
4511             = TYPE_MAX_VALUE (equiv_type) ? TYPE_MAX_VALUE (equiv_type)
4512               : TYPE_MAX_VALUE (arg0_type);
4513
4514           if (TYPE_PRECISION (exp_type) == TYPE_PRECISION (arg0_type))
4515             high_positive = fold_build2_loc (loc, RSHIFT_EXPR, arg0_type,
4516                                              fold_convert_loc (loc, arg0_type,
4517                                                                high_positive),
4518                                              build_int_cst (arg0_type, 1));
4519
4520           /* If the low bound is specified, "and" the range with the
4521              range for which the original unsigned value will be
4522              positive.  */
4523           if (low != 0)
4524             {
4525               if (! merge_ranges (&n_in_p, &n_low, &n_high, 1, n_low, n_high,
4526                                   1, fold_convert_loc (loc, arg0_type,
4527                                                        integer_zero_node),
4528                                   high_positive))
4529                 return NULL_TREE;
4530
4531               in_p = (n_in_p == in_p);
4532             }
4533           else
4534             {
4535               /* Otherwise, "or" the range with the range of the input
4536                  that will be interpreted as negative.  */
4537               if (! merge_ranges (&n_in_p, &n_low, &n_high, 0, n_low, n_high,
4538                                   1, fold_convert_loc (loc, arg0_type,
4539                                                        integer_zero_node),
4540                                   high_positive))
4541                 return NULL_TREE;
4542
4543               in_p = (in_p != n_in_p);
4544             }
4545         }
4546
4547       *p_low = n_low;
4548       *p_high = n_high;
4549       *p_in_p = in_p;
4550       return arg0;
4551
4552     default:
4553       return NULL_TREE;
4554     }
4555 }
4556
4557 /* Given EXP, a logical expression, set the range it is testing into
4558    variables denoted by PIN_P, PLOW, and PHIGH.  Return the expression
4559    actually being tested.  *PLOW and *PHIGH will be made of the same
4560    type as the returned expression.  If EXP is not a comparison, we
4561    will most likely not be returning a useful value and range.  Set
4562    *STRICT_OVERFLOW_P to true if the return value is only valid
4563    because signed overflow is undefined; otherwise, do not change
4564    *STRICT_OVERFLOW_P.  */
4565
4566 tree
4567 make_range (tree exp, int *pin_p, tree *plow, tree *phigh,
4568             bool *strict_overflow_p)
4569 {
4570   enum tree_code code;
4571   tree arg0, arg1 = NULL_TREE;
4572   tree exp_type, nexp;
4573   int in_p;
4574   tree low, high;
4575   location_t loc = EXPR_LOCATION (exp);
4576
4577   /* Start with simply saying "EXP != 0" and then look at the code of EXP
4578      and see if we can refine the range.  Some of the cases below may not
4579      happen, but it doesn't seem worth worrying about this.  We "continue"
4580      the outer loop when we've changed something; otherwise we "break"
4581      the switch, which will "break" the while.  */
4582
4583   in_p = 0;
4584   low = high = build_int_cst (TREE_TYPE (exp), 0);
4585
4586   while (1)
4587     {
4588       code = TREE_CODE (exp);
4589       exp_type = TREE_TYPE (exp);
4590       arg0 = NULL_TREE;
4591
4592       if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (code)))
4593         {
4594           if (TREE_OPERAND_LENGTH (exp) > 0)
4595             arg0 = TREE_OPERAND (exp, 0);
4596           if (TREE_CODE_CLASS (code) == tcc_binary
4597               || TREE_CODE_CLASS (code) == tcc_comparison
4598               || (TREE_CODE_CLASS (code) == tcc_expression
4599                   && TREE_OPERAND_LENGTH (exp) > 1))
4600             arg1 = TREE_OPERAND (exp, 1);
4601         }
4602       if (arg0 == NULL_TREE)
4603         break;
4604
4605       nexp = make_range_step (loc, code, arg0, arg1, exp_type, &low,
4606                               &high, &in_p, strict_overflow_p);
4607       if (nexp == NULL_TREE)
4608         break;
4609       exp = nexp;
4610     }
4611
4612   /* If EXP is a constant, we can evaluate whether this is true or false.  */
4613   if (TREE_CODE (exp) == INTEGER_CST)
4614     {
4615       in_p = in_p == (integer_onep (range_binop (GE_EXPR, integer_type_node,
4616                                                  exp, 0, low, 0))
4617                       && integer_onep (range_binop (LE_EXPR, integer_type_node,
4618                                                     exp, 1, high, 1)));
4619       low = high = 0;
4620       exp = 0;
4621     }
4622
4623   *pin_p = in_p, *plow = low, *phigh = high;
4624   return exp;
4625 }
4626 \f
4627 /* Given a range, LOW, HIGH, and IN_P, an expression, EXP, and a result
4628    type, TYPE, return an expression to test if EXP is in (or out of, depending
4629    on IN_P) the range.  Return 0 if the test couldn't be created.  */
4630
4631 tree
4632 build_range_check (location_t loc, tree type, tree exp, int in_p,
4633                    tree low, tree high)
4634 {
4635   tree etype = TREE_TYPE (exp), value;
4636
4637   /* Disable this optimization for function pointer expressions
4638      on targets that require function pointer canonicalization.  */
4639   if (targetm.have_canonicalize_funcptr_for_compare ()
4640       && TREE_CODE (etype) == POINTER_TYPE
4641       && TREE_CODE (TREE_TYPE (etype)) == FUNCTION_TYPE)
4642     return NULL_TREE;
4643
4644   if (! in_p)
4645     {
4646       value = build_range_check (loc, type, exp, 1, low, high);
4647       if (value != 0)
4648         return invert_truthvalue_loc (loc, value);
4649
4650       return 0;
4651     }
4652
4653   if (low == 0 && high == 0)
4654     return omit_one_operand_loc (loc, type, build_int_cst (type, 1), exp);
4655
4656   if (low == 0)
4657     return fold_build2_loc (loc, LE_EXPR, type, exp,
4658                         fold_convert_loc (loc, etype, high));
4659
4660   if (high == 0)
4661     return fold_build2_loc (loc, GE_EXPR, type, exp,
4662                         fold_convert_loc (loc, etype, low));
4663
4664   if (operand_equal_p (low, high, 0))
4665     return fold_build2_loc (loc, EQ_EXPR, type, exp,
4666                         fold_convert_loc (loc, etype, low));
4667
4668   if (integer_zerop (low))
4669     {
4670       if (! TYPE_UNSIGNED (etype))
4671         {
4672           etype = unsigned_type_for (etype);
4673           high = fold_convert_loc (loc, etype, high);
4674           exp = fold_convert_loc (loc, etype, exp);
4675         }
4676       return build_range_check (loc, type, exp, 1, 0, high);
4677     }
4678
4679   /* Optimize (c>=1) && (c<=127) into (signed char)c > 0.  */
4680   if (integer_onep (low) && TREE_CODE (high) == INTEGER_CST)
4681     {
4682       int prec = TYPE_PRECISION (etype);
4683
4684       if (wi::mask (prec - 1, false, prec) == high)
4685         {
4686           if (TYPE_UNSIGNED (etype))
4687             {
4688               tree signed_etype = signed_type_for (etype);
4689               if (TYPE_PRECISION (signed_etype) != TYPE_PRECISION (etype))
4690                 etype
4691                   = build_nonstandard_integer_type (TYPE_PRECISION (etype), 0);
4692               else
4693                 etype = signed_etype;
4694               exp = fold_convert_loc (loc, etype, exp);
4695             }
4696           return fold_build2_loc (loc, GT_EXPR, type, exp,
4697                               build_int_cst (etype, 0));
4698         }
4699     }
4700
4701   /* Optimize (c>=low) && (c<=high) into (c-low>=0) && (c-low<=high-low).
4702      This requires wrap-around arithmetics for the type of the expression.
4703      First make sure that arithmetics in this type is valid, then make sure
4704      that it wraps around.  */
4705   if (TREE_CODE (etype) == ENUMERAL_TYPE || TREE_CODE (etype) == BOOLEAN_TYPE)
4706     etype = lang_hooks.types.type_for_size (TYPE_PRECISION (etype),
4707                                             TYPE_UNSIGNED (etype));
4708
4709   if (TREE_CODE (etype) == INTEGER_TYPE && !TYPE_OVERFLOW_WRAPS (etype))
4710     {
4711       tree utype, minv, maxv;
4712
4713       /* Check if (unsigned) INT_MAX + 1 == (unsigned) INT_MIN
4714          for the type in question, as we rely on this here.  */
4715       utype = unsigned_type_for (etype);
4716       maxv = fold_convert_loc (loc, utype, TYPE_MAX_VALUE (etype));
4717       maxv = range_binop (PLUS_EXPR, NULL_TREE, maxv, 1,
4718                           build_int_cst (TREE_TYPE (maxv), 1), 1);
4719       minv = fold_convert_loc (loc, utype, TYPE_MIN_VALUE (etype));
4720
4721       if (integer_zerop (range_binop (NE_EXPR, integer_type_node,
4722                                       minv, 1, maxv, 1)))
4723         etype = utype;
4724       else
4725         return 0;
4726     }
4727
4728   high = fold_convert_loc (loc, etype, high);
4729   low = fold_convert_loc (loc, etype, low);
4730   exp = fold_convert_loc (loc, etype, exp);
4731
4732   value = const_binop (MINUS_EXPR, high, low);
4733
4734
4735   if (POINTER_TYPE_P (etype))
4736     {
4737       if (value != 0 && !TREE_OVERFLOW (value))
4738         {
4739           low = fold_build1_loc (loc, NEGATE_EXPR, TREE_TYPE (low), low);
4740           return build_range_check (loc, type,
4741                                     fold_build_pointer_plus_loc (loc, exp, low),
4742                                     1, build_int_cst (etype, 0), value);
4743         }
4744       return 0;
4745     }
4746
4747   if (value != 0 && !TREE_OVERFLOW (value))
4748     return build_range_check (loc, type,
4749                               fold_build2_loc (loc, MINUS_EXPR, etype, exp, low),
4750                               1, build_int_cst (etype, 0), value);
4751
4752   return 0;
4753 }
4754 \f
4755 /* Return the predecessor of VAL in its type, handling the infinite case.  */
4756
4757 static tree
4758 range_predecessor (tree val)
4759 {
4760   tree type = TREE_TYPE (val);
4761
4762   if (INTEGRAL_TYPE_P (type)
4763       && operand_equal_p (val, TYPE_MIN_VALUE (type), 0))
4764     return 0;
4765   else
4766     return range_binop (MINUS_EXPR, NULL_TREE, val, 0,
4767                         build_int_cst (TREE_TYPE (val), 1), 0);
4768 }
4769
4770 /* Return the successor of VAL in its type, handling the infinite case.  */
4771
4772 static tree
4773 range_successor (tree val)
4774 {
4775   tree type = TREE_TYPE (val);
4776
4777   if (INTEGRAL_TYPE_P (type)
4778       && operand_equal_p (val, TYPE_MAX_VALUE (type), 0))
4779     return 0;
4780   else
4781     return range_binop (PLUS_EXPR, NULL_TREE, val, 0,
4782                         build_int_cst (TREE_TYPE (val), 1), 0);
4783 }
4784
4785 /* Given two ranges, see if we can merge them into one.  Return 1 if we
4786    can, 0 if we can't.  Set the output range into the specified parameters.  */
4787
4788 bool
4789 merge_ranges (int *pin_p, tree *plow, tree *phigh, int in0_p, tree low0,
4790               tree high0, int in1_p, tree low1, tree high1)
4791 {
4792   int no_overlap;
4793   int subset;
4794   int temp;
4795   tree tem;
4796   int in_p;
4797   tree low, high;
4798   int lowequal = ((low0 == 0 && low1 == 0)
4799                   || integer_onep (range_binop (EQ_EXPR, integer_type_node,
4800                                                 low0, 0, low1, 0)));
4801   int highequal = ((high0 == 0 && high1 == 0)
4802                    || integer_onep (range_binop (EQ_EXPR, integer_type_node,
4803                                                  high0, 1, high1, 1)));
4804
4805   /* Make range 0 be the range that starts first, or ends last if they
4806      start at the same value.  Swap them if it isn't.  */
4807   if (integer_onep (range_binop (GT_EXPR, integer_type_node,
4808                                  low0, 0, low1, 0))
4809       || (lowequal
4810           && integer_onep (range_binop (GT_EXPR, integer_type_node,
4811                                         high1, 1, high0, 1))))
4812     {
4813       temp = in0_p, in0_p = in1_p, in1_p = temp;
4814       tem = low0, low0 = low1, low1 = tem;
4815       tem = high0, high0 = high1, high1 = tem;
4816     }
4817
4818   /* Now flag two cases, whether the ranges are disjoint or whether the
4819      second range is totally subsumed in the first.  Note that the tests
4820      below are simplified by the ones above.  */
4821   no_overlap = integer_onep (range_binop (LT_EXPR, integer_type_node,
4822                                           high0, 1, low1, 0));
4823   subset = integer_onep (range_binop (LE_EXPR, integer_type_node,
4824                                       high1, 1, high0, 1));
4825
4826   /* We now have four cases, depending on whether we are including or
4827      excluding the two ranges.  */
4828   if (in0_p && in1_p)
4829     {
4830       /* If they don't overlap, the result is false.  If the second range
4831          is a subset it is the result.  Otherwise, the range is from the start
4832          of the second to the end of the first.  */
4833       if (no_overlap)
4834         in_p = 0, low = high = 0;
4835       else if (subset)
4836         in_p = 1, low = low1, high = high1;
4837       else
4838         in_p = 1, low = low1, high = high0;
4839     }
4840
4841   else if (in0_p && ! in1_p)
4842     {
4843       /* If they don't overlap, the result is the first range.  If they are
4844          equal, the result is false.  If the second range is a subset of the
4845          first, and the ranges begin at the same place, we go from just after
4846          the end of the second range to the end of the first.  If the second
4847          range is not a subset of the first, or if it is a subset and both
4848          ranges end at the same place, the range starts at the start of the
4849          first range and ends just before the second range.
4850          Otherwise, we can't describe this as a single range.  */
4851       if (no_overlap)
4852         in_p = 1, low = low0, high = high0;
4853       else if (lowequal && highequal)
4854         in_p = 0, low = high = 0;
4855       else if (subset && lowequal)
4856         {
4857           low = range_successor (high1);
4858           high = high0;
4859           in_p = 1;
4860           if (low == 0)
4861             {
4862               /* We are in the weird situation where high0 > high1 but
4863                  high1 has no successor.  Punt.  */
4864               return 0;
4865             }
4866         }
4867       else if (! subset || highequal)
4868         {
4869           low = low0;
4870           high = range_predecessor (low1);
4871           in_p = 1;
4872           if (high == 0)
4873             {
4874               /* low0 < low1 but low1 has no predecessor.  Punt.  */
4875               return 0;
4876             }
4877         }
4878       else
4879         return 0;
4880     }
4881
4882   else if (! in0_p && in1_p)
4883     {
4884       /* If they don't overlap, the result is the second range.  If the second
4885          is a subset of the first, the result is false.  Otherwise,
4886          the range starts just after the first range and ends at the
4887          end of the second.  */
4888       if (no_overlap)
4889         in_p = 1, low = low1, high = high1;
4890       else if (subset || highequal)
4891         in_p = 0, low = high = 0;
4892       else
4893         {
4894           low = range_successor (high0);
4895           high = high1;
4896           in_p = 1;
4897           if (low == 0)
4898             {
4899               /* high1 > high0 but high0 has no successor.  Punt.  */
4900               return 0;
4901             }
4902         }
4903     }
4904
4905   else
4906     {
4907       /* The case where we are excluding both ranges.  Here the complex case
4908          is if they don't overlap.  In that case, the only time we have a
4909          range is if they are adjacent.  If the second is a subset of the
4910          first, the result is the first.  Otherwise, the range to exclude
4911          starts at the beginning of the first range and ends at the end of the
4912          second.  */
4913       if (no_overlap)
4914         {
4915           if (integer_onep (range_binop (EQ_EXPR, integer_type_node,
4916                                          range_successor (high0),
4917                                          1, low1, 0)))
4918             in_p = 0, low = low0, high = high1;
4919           else
4920             {
4921               /* Canonicalize - [min, x] into - [-, x].  */
4922               if (low0 && TREE_CODE (low0) == INTEGER_CST)
4923                 switch (TREE_CODE (TREE_TYPE (low0)))
4924                   {
4925                   case ENUMERAL_TYPE:
4926                     if (TYPE_PRECISION (TREE_TYPE (low0))
4927                         != GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE (low0))))
4928                       break;
4929                     /* FALLTHROUGH */
4930                   case INTEGER_TYPE:
4931                     if (tree_int_cst_equal (low0,
4932                                             TYPE_MIN_VALUE (TREE_TYPE (low0))))
4933                       low0 = 0;
4934                     break;
4935                   case POINTER_TYPE:
4936                     if (TYPE_UNSIGNED (TREE_TYPE (low0))
4937                         && integer_zerop (low0))
4938                       low0 = 0;
4939                     break;
4940                   default:
4941                     break;
4942                   }
4943
4944               /* Canonicalize - [x, max] into - [x, -].  */
4945               if (high1 && TREE_CODE (high1) == INTEGER_CST)
4946                 switch (TREE_CODE (TREE_TYPE (high1)))
4947                   {
4948                   case ENUMERAL_TYPE:
4949                     if (TYPE_PRECISION (TREE_TYPE (high1))
4950                         != GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE (high1))))
4951                       break;
4952                     /* FALLTHROUGH */
4953                   case INTEGER_TYPE:
4954                     if (tree_int_cst_equal (high1,
4955                                             TYPE_MAX_VALUE (TREE_TYPE (high1))))
4956                       high1 = 0;
4957                     break;
4958                   case POINTER_TYPE:
4959                     if (TYPE_UNSIGNED (TREE_TYPE (high1))
4960                         && integer_zerop (range_binop (PLUS_EXPR, NULL_TREE,
4961                                                        high1, 1,
4962                                                        build_int_cst (TREE_TYPE (high1), 1),
4963                                                        1)))
4964                       high1 = 0;
4965                     break;
4966                   default:
4967                     break;
4968                   }
4969
4970               /* The ranges might be also adjacent between the maximum and
4971                  minimum values of the given type.  For
4972                  - [{min,-}, x] and - [y, {max,-}] ranges where x + 1 < y
4973                  return + [x + 1, y - 1].  */
4974               if (low0 == 0 && high1 == 0)
4975                 {
4976                   low = range_successor (high0);
4977                   high = range_predecessor (low1);
4978                   if (low == 0 || high == 0)
4979                     return 0;
4980
4981                   in_p = 1;
4982                 }
4983               else
4984                 return 0;
4985             }
4986         }
4987       else if (subset)
4988         in_p = 0, low = low0, high = high0;
4989       else
4990         in_p = 0, low = low0, high = high1;
4991     }
4992
4993   *pin_p = in_p, *plow = low, *phigh = high;
4994   return 1;
4995 }
4996 \f
4997
4998 /* Subroutine of fold, looking inside expressions of the form
4999    A op B ? A : C, where ARG0, ARG1 and ARG2 are the three operands
5000    of the COND_EXPR.  This function is being used also to optimize
5001    A op B ? C : A, by reversing the comparison first.
5002
5003    Return a folded expression whose code is not a COND_EXPR
5004    anymore, or NULL_TREE if no folding opportunity is found.  */
5005
5006 static tree
5007 fold_cond_expr_with_comparison (location_t loc, tree type,
5008                                 tree arg0, tree arg1, tree arg2)
5009 {
5010   enum tree_code comp_code = TREE_CODE (arg0);
5011   tree arg00 = TREE_OPERAND (arg0, 0);
5012   tree arg01 = TREE_OPERAND (arg0, 1);
5013   tree arg1_type = TREE_TYPE (arg1);
5014   tree tem;
5015
5016   STRIP_NOPS (arg1);
5017   STRIP_NOPS (arg2);
5018
5019   /* If we have A op 0 ? A : -A, consider applying the following
5020      transformations:
5021
5022      A == 0? A : -A    same as -A
5023      A != 0? A : -A    same as A
5024      A >= 0? A : -A    same as abs (A)
5025      A > 0?  A : -A    same as abs (A)
5026      A <= 0? A : -A    same as -abs (A)
5027      A < 0?  A : -A    same as -abs (A)
5028
5029      None of these transformations work for modes with signed
5030      zeros.  If A is +/-0, the first two transformations will
5031      change the sign of the result (from +0 to -0, or vice
5032      versa).  The last four will fix the sign of the result,
5033      even though the original expressions could be positive or
5034      negative, depending on the sign of A.
5035
5036      Note that all these transformations are correct if A is
5037      NaN, since the two alternatives (A and -A) are also NaNs.  */
5038   if (!HONOR_SIGNED_ZEROS (element_mode (type))
5039       && (FLOAT_TYPE_P (TREE_TYPE (arg01))
5040           ? real_zerop (arg01)
5041           : integer_zerop (arg01))
5042       && ((TREE_CODE (arg2) == NEGATE_EXPR
5043            && operand_equal_p (TREE_OPERAND (arg2, 0), arg1, 0))
5044              /* In the case that A is of the form X-Y, '-A' (arg2) may
5045                 have already been folded to Y-X, check for that. */
5046           || (TREE_CODE (arg1) == MINUS_EXPR
5047               && TREE_CODE (arg2) == MINUS_EXPR
5048               && operand_equal_p (TREE_OPERAND (arg1, 0),
5049                                   TREE_OPERAND (arg2, 1), 0)
5050               && operand_equal_p (TREE_OPERAND (arg1, 1),
5051                                   TREE_OPERAND (arg2, 0), 0))))
5052     switch (comp_code)
5053       {
5054       case EQ_EXPR:
5055       case UNEQ_EXPR:
5056         tem = fold_convert_loc (loc, arg1_type, arg1);
5057         return pedantic_non_lvalue_loc (loc,
5058                                     fold_convert_loc (loc, type,
5059                                                   negate_expr (tem)));
5060       case NE_EXPR:
5061       case LTGT_EXPR:
5062         return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, arg1));
5063       case UNGE_EXPR:
5064       case UNGT_EXPR:
5065         if (flag_trapping_math)
5066           break;
5067         /* Fall through.  */
5068       case GE_EXPR:
5069       case GT_EXPR:
5070         if (TYPE_UNSIGNED (TREE_TYPE (arg1)))
5071           break;
5072         tem = fold_build1_loc (loc, ABS_EXPR, TREE_TYPE (arg1), arg1);
5073         return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, tem));
5074       case UNLE_EXPR:
5075       case UNLT_EXPR:
5076         if (flag_trapping_math)
5077           break;
5078       case LE_EXPR:
5079       case LT_EXPR:
5080         if (TYPE_UNSIGNED (TREE_TYPE (arg1)))
5081           break;
5082         tem = fold_build1_loc (loc, ABS_EXPR, TREE_TYPE (arg1), arg1);
5083         return negate_expr (fold_convert_loc (loc, type, tem));
5084       default:
5085         gcc_assert (TREE_CODE_CLASS (comp_code) == tcc_comparison);
5086         break;
5087       }
5088
5089   /* A != 0 ? A : 0 is simply A, unless A is -0.  Likewise
5090      A == 0 ? A : 0 is always 0 unless A is -0.  Note that
5091      both transformations are correct when A is NaN: A != 0
5092      is then true, and A == 0 is false.  */
5093
5094   if (!HONOR_SIGNED_ZEROS (element_mode (type))
5095       && integer_zerop (arg01) && integer_zerop (arg2))
5096     {
5097       if (comp_code == NE_EXPR)
5098         return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, arg1));
5099       else if (comp_code == EQ_EXPR)
5100         return build_zero_cst (type);
5101     }
5102
5103   /* Try some transformations of A op B ? A : B.
5104
5105      A == B? A : B    same as B
5106      A != B? A : B    same as A
5107      A >= B? A : B    same as max (A, B)
5108      A > B?  A : B    same as max (B, A)
5109      A <= B? A : B    same as min (A, B)
5110      A < B?  A : B    same as min (B, A)
5111
5112      As above, these transformations don't work in the presence
5113      of signed zeros.  For example, if A and B are zeros of
5114      opposite sign, the first two transformations will change
5115      the sign of the result.  In the last four, the original
5116      expressions give different results for (A=+0, B=-0) and
5117      (A=-0, B=+0), but the transformed expressions do not.
5118
5119      The first two transformations are correct if either A or B
5120      is a NaN.  In the first transformation, the condition will
5121      be false, and B will indeed be chosen.  In the case of the
5122      second transformation, the condition A != B will be true,
5123      and A will be chosen.
5124
5125      The conversions to max() and min() are not correct if B is
5126      a number and A is not.  The conditions in the original
5127      expressions will be false, so all four give B.  The min()
5128      and max() versions would give a NaN instead.  */
5129   if (!HONOR_SIGNED_ZEROS (element_mode (type))
5130       && operand_equal_for_comparison_p (arg01, arg2, arg00)
5131       /* Avoid these transformations if the COND_EXPR may be used
5132          as an lvalue in the C++ front-end.  PR c++/19199.  */
5133       && (in_gimple_form
5134           || VECTOR_TYPE_P (type)
5135           || (! lang_GNU_CXX ()
5136               && strcmp (lang_hooks.name, "GNU Objective-C++") != 0)
5137           || ! maybe_lvalue_p (arg1)
5138           || ! maybe_lvalue_p (arg2)))
5139     {
5140       tree comp_op0 = arg00;
5141       tree comp_op1 = arg01;
5142       tree comp_type = TREE_TYPE (comp_op0);
5143
5144       /* Avoid adding NOP_EXPRs in case this is an lvalue.  */
5145       if (TYPE_MAIN_VARIANT (comp_type) == TYPE_MAIN_VARIANT (type))
5146         {
5147           comp_type = type;
5148           comp_op0 = arg1;
5149           comp_op1 = arg2;
5150         }
5151
5152       switch (comp_code)
5153         {
5154         case EQ_EXPR:
5155           return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, arg2));
5156         case NE_EXPR:
5157           return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, arg1));
5158         case LE_EXPR:
5159         case LT_EXPR:
5160         case UNLE_EXPR:
5161         case UNLT_EXPR:
5162           /* In C++ a ?: expression can be an lvalue, so put the
5163              operand which will be used if they are equal first
5164              so that we can convert this back to the
5165              corresponding COND_EXPR.  */
5166           if (!HONOR_NANS (arg1))
5167             {
5168               comp_op0 = fold_convert_loc (loc, comp_type, comp_op0);
5169               comp_op1 = fold_convert_loc (loc, comp_type, comp_op1);
5170               tem = (comp_code == LE_EXPR || comp_code == UNLE_EXPR)
5171                     ? fold_build2_loc (loc, MIN_EXPR, comp_type, comp_op0, comp_op1)
5172                     : fold_build2_loc (loc, MIN_EXPR, comp_type,
5173                                    comp_op1, comp_op0);
5174               return pedantic_non_lvalue_loc (loc,
5175                                           fold_convert_loc (loc, type, tem));
5176             }
5177           break;
5178         case GE_EXPR:
5179         case GT_EXPR:
5180         case UNGE_EXPR:
5181         case UNGT_EXPR:
5182           if (!HONOR_NANS (arg1))
5183             {
5184               comp_op0 = fold_convert_loc (loc, comp_type, comp_op0);
5185               comp_op1 = fold_convert_loc (loc, comp_type, comp_op1);
5186               tem = (comp_code == GE_EXPR || comp_code == UNGE_EXPR)
5187                     ? fold_build2_loc (loc, MAX_EXPR, comp_type, comp_op0, comp_op1)
5188                     : fold_build2_loc (loc, MAX_EXPR, comp_type,
5189                                    comp_op1, comp_op0);
5190               return pedantic_non_lvalue_loc (loc,
5191                                           fold_convert_loc (loc, type, tem));
5192             }
5193           break;
5194         case UNEQ_EXPR:
5195           if (!HONOR_NANS (arg1))
5196             return pedantic_non_lvalue_loc (loc,
5197                                         fold_convert_loc (loc, type, arg2));
5198           break;
5199         case LTGT_EXPR:
5200           if (!HONOR_NANS (arg1))
5201             return pedantic_non_lvalue_loc (loc,
5202                                         fold_convert_loc (loc, type, arg1));
5203           break;
5204         default:
5205           gcc_assert (TREE_CODE_CLASS (comp_code) == tcc_comparison);
5206           break;
5207         }
5208     }
5209
5210   /* If this is A op C1 ? A : C2 with C1 and C2 constant integers,
5211      we might still be able to simplify this.  For example,
5212      if C1 is one less or one more than C2, this might have started
5213      out as a MIN or MAX and been transformed by this function.
5214      Only good for INTEGER_TYPEs, because we need TYPE_MAX_VALUE.  */
5215
5216   if (INTEGRAL_TYPE_P (type)
5217       && TREE_CODE (arg01) == INTEGER_CST
5218       && TREE_CODE (arg2) == INTEGER_CST)
5219     switch (comp_code)
5220       {
5221       case EQ_EXPR:
5222         if (TREE_CODE (arg1) == INTEGER_CST)
5223           break;
5224         /* We can replace A with C1 in this case.  */
5225         arg1 = fold_convert_loc (loc, type, arg01);
5226         return fold_build3_loc (loc, COND_EXPR, type, arg0, arg1, arg2);
5227
5228       case LT_EXPR:
5229         /* If C1 is C2 + 1, this is min(A, C2), but use ARG00's type for
5230            MIN_EXPR, to preserve the signedness of the comparison.  */
5231         if (! operand_equal_p (arg2, TYPE_MAX_VALUE (type),
5232                                OEP_ONLY_CONST)
5233             && operand_equal_p (arg01,
5234                                 const_binop (PLUS_EXPR, arg2,
5235                                              build_int_cst (type, 1)),
5236                                 OEP_ONLY_CONST))
5237           {
5238             tem = fold_build2_loc (loc, MIN_EXPR, TREE_TYPE (arg00), arg00,
5239                                    fold_convert_loc (loc, TREE_TYPE (arg00),
5240                                                      arg2));
5241             return pedantic_non_lvalue_loc (loc,
5242                                             fold_convert_loc (loc, type, tem));
5243           }
5244         break;
5245
5246       case LE_EXPR:
5247         /* If C1 is C2 - 1, this is min(A, C2), with the same care
5248            as above.  */
5249         if (! operand_equal_p (arg2, TYPE_MIN_VALUE (type),
5250                                OEP_ONLY_CONST)
5251             && operand_equal_p (arg01,
5252                                 const_binop (MINUS_EXPR, arg2,
5253                                              build_int_cst (type, 1)),
5254                                 OEP_ONLY_CONST))
5255           {
5256             tem = fold_build2_loc (loc, MIN_EXPR, TREE_TYPE (arg00), arg00,
5257                                    fold_convert_loc (loc, TREE_TYPE (arg00),
5258                                                      arg2));
5259             return pedantic_non_lvalue_loc (loc,
5260                                             fold_convert_loc (loc, type, tem));
5261           }
5262         break;
5263
5264       case GT_EXPR:
5265         /* If C1 is C2 - 1, this is max(A, C2), but use ARG00's type for
5266            MAX_EXPR, to preserve the signedness of the comparison.  */
5267         if (! operand_equal_p (arg2, TYPE_MIN_VALUE (type),
5268                                OEP_ONLY_CONST)
5269             && operand_equal_p (arg01,
5270                                 const_binop (MINUS_EXPR, arg2,
5271                                              build_int_cst (type, 1)),
5272                                 OEP_ONLY_CONST))
5273           {
5274             tem = fold_build2_loc (loc, MAX_EXPR, TREE_TYPE (arg00), arg00,
5275                                    fold_convert_loc (loc, TREE_TYPE (arg00),
5276                                                      arg2));
5277             return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, tem));
5278           }
5279         break;
5280
5281       case GE_EXPR:
5282         /* If C1 is C2 + 1, this is max(A, C2), with the same care as above.  */
5283         if (! operand_equal_p (arg2, TYPE_MAX_VALUE (type),
5284                                OEP_ONLY_CONST)
5285             && operand_equal_p (arg01,
5286                                 const_binop (PLUS_EXPR, arg2,
5287                                              build_int_cst (type, 1)),
5288                                 OEP_ONLY_CONST))
5289           {
5290             tem = fold_build2_loc (loc, MAX_EXPR, TREE_TYPE (arg00), arg00,
5291                                    fold_convert_loc (loc, TREE_TYPE (arg00),
5292                                                      arg2));
5293             return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, tem));
5294           }
5295         break;
5296       case NE_EXPR:
5297         break;
5298       default:
5299         gcc_unreachable ();
5300       }
5301
5302   return NULL_TREE;
5303 }
5304
5305
5306 \f
5307 #ifndef LOGICAL_OP_NON_SHORT_CIRCUIT
5308 #define LOGICAL_OP_NON_SHORT_CIRCUIT \
5309   (BRANCH_COST (optimize_function_for_speed_p (cfun), \
5310                 false) >= 2)
5311 #endif
5312
5313 /* EXP is some logical combination of boolean tests.  See if we can
5314    merge it into some range test.  Return the new tree if so.  */
5315
5316 static tree
5317 fold_range_test (location_t loc, enum tree_code code, tree type,
5318                  tree op0, tree op1)
5319 {
5320   int or_op = (code == TRUTH_ORIF_EXPR
5321                || code == TRUTH_OR_EXPR);
5322   int in0_p, in1_p, in_p;
5323   tree low0, low1, low, high0, high1, high;
5324   bool strict_overflow_p = false;
5325   tree tem, lhs, rhs;
5326   const char * const warnmsg = G_("assuming signed overflow does not occur "
5327                                   "when simplifying range test");
5328
5329   if (!INTEGRAL_TYPE_P (type))
5330     return 0;
5331
5332   lhs = make_range (op0, &in0_p, &low0, &high0, &strict_overflow_p);
5333   rhs = make_range (op1, &in1_p, &low1, &high1, &strict_overflow_p);
5334
5335   /* If this is an OR operation, invert both sides; we will invert
5336      again at the end.  */
5337   if (or_op)
5338     in0_p = ! in0_p, in1_p = ! in1_p;
5339
5340   /* If both expressions are the same, if we can merge the ranges, and we
5341      can build the range test, return it or it inverted.  If one of the
5342      ranges is always true or always false, consider it to be the same
5343      expression as the other.  */
5344   if ((lhs == 0 || rhs == 0 || operand_equal_p (lhs, rhs, 0))
5345       && merge_ranges (&in_p, &low, &high, in0_p, low0, high0,
5346                        in1_p, low1, high1)
5347       && 0 != (tem = (build_range_check (loc, type,
5348                                          lhs != 0 ? lhs
5349                                          : rhs != 0 ? rhs : integer_zero_node,
5350                                          in_p, low, high))))
5351     {
5352       if (strict_overflow_p)
5353         fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_COMPARISON);
5354       return or_op ? invert_truthvalue_loc (loc, tem) : tem;
5355     }
5356
5357   /* On machines where the branch cost is expensive, if this is a
5358      short-circuited branch and the underlying object on both sides
5359      is the same, make a non-short-circuit operation.  */
5360   else if (LOGICAL_OP_NON_SHORT_CIRCUIT
5361            && lhs != 0 && rhs != 0
5362            && (code == TRUTH_ANDIF_EXPR
5363                || code == TRUTH_ORIF_EXPR)
5364            && operand_equal_p (lhs, rhs, 0))
5365     {
5366       /* If simple enough, just rewrite.  Otherwise, make a SAVE_EXPR
5367          unless we are at top level or LHS contains a PLACEHOLDER_EXPR, in
5368          which cases we can't do this.  */
5369       if (simple_operand_p (lhs))
5370         return build2_loc (loc, code == TRUTH_ANDIF_EXPR
5371                            ? TRUTH_AND_EXPR : TRUTH_OR_EXPR,
5372                            type, op0, op1);
5373
5374       else if (!lang_hooks.decls.global_bindings_p ()
5375                && !CONTAINS_PLACEHOLDER_P (lhs))
5376         {
5377           tree common = save_expr (lhs);
5378
5379           if (0 != (lhs = build_range_check (loc, type, common,
5380                                              or_op ? ! in0_p : in0_p,
5381                                              low0, high0))
5382               && (0 != (rhs = build_range_check (loc, type, common,
5383                                                  or_op ? ! in1_p : in1_p,
5384                                                  low1, high1))))
5385             {
5386               if (strict_overflow_p)
5387                 fold_overflow_warning (warnmsg,
5388                                        WARN_STRICT_OVERFLOW_COMPARISON);
5389               return build2_loc (loc, code == TRUTH_ANDIF_EXPR
5390                                  ? TRUTH_AND_EXPR : TRUTH_OR_EXPR,
5391                                  type, lhs, rhs);
5392             }
5393         }
5394     }
5395
5396   return 0;
5397 }
5398 \f
5399 /* Subroutine for fold_truth_andor_1: C is an INTEGER_CST interpreted as a P
5400    bit value.  Arrange things so the extra bits will be set to zero if and
5401    only if C is signed-extended to its full width.  If MASK is nonzero,
5402    it is an INTEGER_CST that should be AND'ed with the extra bits.  */
5403
5404 static tree
5405 unextend (tree c, int p, int unsignedp, tree mask)
5406 {
5407   tree type = TREE_TYPE (c);
5408   int modesize = GET_MODE_BITSIZE (TYPE_MODE (type));
5409   tree temp;
5410
5411   if (p == modesize || unsignedp)
5412     return c;
5413
5414   /* We work by getting just the sign bit into the low-order bit, then
5415      into the high-order bit, then sign-extend.  We then XOR that value
5416      with C.  */
5417   temp = build_int_cst (TREE_TYPE (c), wi::extract_uhwi (c, p - 1, 1));
5418
5419   /* We must use a signed type in order to get an arithmetic right shift.
5420      However, we must also avoid introducing accidental overflows, so that
5421      a subsequent call to integer_zerop will work.  Hence we must
5422      do the type conversion here.  At this point, the constant is either
5423      zero or one, and the conversion to a signed type can never overflow.
5424      We could get an overflow if this conversion is done anywhere else.  */
5425   if (TYPE_UNSIGNED (type))
5426     temp = fold_convert (signed_type_for (type), temp);
5427
5428   temp = const_binop (LSHIFT_EXPR, temp, size_int (modesize - 1));
5429   temp = const_binop (RSHIFT_EXPR, temp, size_int (modesize - p - 1));
5430   if (mask != 0)
5431     temp = const_binop (BIT_AND_EXPR, temp,
5432                         fold_convert (TREE_TYPE (c), mask));
5433   /* If necessary, convert the type back to match the type of C.  */
5434   if (TYPE_UNSIGNED (type))
5435     temp = fold_convert (type, temp);
5436
5437   return fold_convert (type, const_binop (BIT_XOR_EXPR, c, temp));
5438 }
5439 \f
5440 /* For an expression that has the form
5441      (A && B) || ~B
5442    or
5443      (A || B) && ~B,
5444    we can drop one of the inner expressions and simplify to
5445      A || ~B
5446    or
5447      A && ~B
5448    LOC is the location of the resulting expression.  OP is the inner
5449    logical operation; the left-hand side in the examples above, while CMPOP
5450    is the right-hand side.  RHS_ONLY is used to prevent us from accidentally
5451    removing a condition that guards another, as in
5452      (A != NULL && A->...) || A == NULL
5453    which we must not transform.  If RHS_ONLY is true, only eliminate the
5454    right-most operand of the inner logical operation.  */
5455
5456 static tree
5457 merge_truthop_with_opposite_arm (location_t loc, tree op, tree cmpop,
5458                                  bool rhs_only)
5459 {
5460   tree type = TREE_TYPE (cmpop);
5461   enum tree_code code = TREE_CODE (cmpop);
5462   enum tree_code truthop_code = TREE_CODE (op);
5463   tree lhs = TREE_OPERAND (op, 0);
5464   tree rhs = TREE_OPERAND (op, 1);
5465   tree orig_lhs = lhs, orig_rhs = rhs;
5466   enum tree_code rhs_code = TREE_CODE (rhs);
5467   enum tree_code lhs_code = TREE_CODE (lhs);
5468   enum tree_code inv_code;
5469
5470   if (TREE_SIDE_EFFECTS (op) || TREE_SIDE_EFFECTS (cmpop))
5471     return NULL_TREE;
5472
5473   if (TREE_CODE_CLASS (code) != tcc_comparison)
5474     return NULL_TREE;
5475
5476   if (rhs_code == truthop_code)
5477     {
5478       tree newrhs = merge_truthop_with_opposite_arm (loc, rhs, cmpop, rhs_only);
5479       if (newrhs != NULL_TREE)
5480         {
5481           rhs = newrhs;
5482           rhs_code = TREE_CODE (rhs);
5483         }
5484     }
5485   if (lhs_code == truthop_code && !rhs_only)
5486     {
5487       tree newlhs = merge_truthop_with_opposite_arm (loc, lhs, cmpop, false);
5488       if (newlhs != NULL_TREE)
5489         {
5490           lhs = newlhs;
5491           lhs_code = TREE_CODE (lhs);
5492         }
5493     }
5494
5495   inv_code = invert_tree_comparison (code, HONOR_NANS (type));
5496   if (inv_code == rhs_code
5497       && operand_equal_p (TREE_OPERAND (rhs, 0), TREE_OPERAND (cmpop, 0), 0)
5498       && operand_equal_p (TREE_OPERAND (rhs, 1), TREE_OPERAND (cmpop, 1), 0))
5499     return lhs;
5500   if (!rhs_only && inv_code == lhs_code
5501       && operand_equal_p (TREE_OPERAND (lhs, 0), TREE_OPERAND (cmpop, 0), 0)
5502       && operand_equal_p (TREE_OPERAND (lhs, 1), TREE_OPERAND (cmpop, 1), 0))
5503     return rhs;
5504   if (rhs != orig_rhs || lhs != orig_lhs)
5505     return fold_build2_loc (loc, truthop_code, TREE_TYPE (cmpop),
5506                             lhs, rhs);
5507   return NULL_TREE;
5508 }
5509
5510 /* Find ways of folding logical expressions of LHS and RHS:
5511    Try to merge two comparisons to the same innermost item.
5512    Look for range tests like "ch >= '0' && ch <= '9'".
5513    Look for combinations of simple terms on machines with expensive branches
5514    and evaluate the RHS unconditionally.
5515
5516    For example, if we have p->a == 2 && p->b == 4 and we can make an
5517    object large enough to span both A and B, we can do this with a comparison
5518    against the object ANDed with the a mask.
5519
5520    If we have p->a == q->a && p->b == q->b, we may be able to use bit masking
5521    operations to do this with one comparison.
5522
5523    We check for both normal comparisons and the BIT_AND_EXPRs made this by
5524    function and the one above.
5525
5526    CODE is the logical operation being done.  It can be TRUTH_ANDIF_EXPR,
5527    TRUTH_AND_EXPR, TRUTH_ORIF_EXPR, or TRUTH_OR_EXPR.
5528
5529    TRUTH_TYPE is the type of the logical operand and LHS and RHS are its
5530    two operands.
5531
5532    We return the simplified tree or 0 if no optimization is possible.  */
5533
5534 static tree
5535 fold_truth_andor_1 (location_t loc, enum tree_code code, tree truth_type,
5536                     tree lhs, tree rhs)
5537 {
5538   /* If this is the "or" of two comparisons, we can do something if
5539      the comparisons are NE_EXPR.  If this is the "and", we can do something
5540      if the comparisons are EQ_EXPR.  I.e.,
5541         (a->b == 2 && a->c == 4) can become (a->new == NEW).
5542
5543      WANTED_CODE is this operation code.  For single bit fields, we can
5544      convert EQ_EXPR to NE_EXPR so we need not reject the "wrong"
5545      comparison for one-bit fields.  */
5546
5547   enum tree_code wanted_code;
5548   enum tree_code lcode, rcode;
5549   tree ll_arg, lr_arg, rl_arg, rr_arg;
5550   tree ll_inner, lr_inner, rl_inner, rr_inner;
5551   HOST_WIDE_INT ll_bitsize, ll_bitpos, lr_bitsize, lr_bitpos;
5552   HOST_WIDE_INT rl_bitsize, rl_bitpos, rr_bitsize, rr_bitpos;
5553   HOST_WIDE_INT xll_bitpos, xlr_bitpos, xrl_bitpos, xrr_bitpos;
5554   HOST_WIDE_INT lnbitsize, lnbitpos, rnbitsize, rnbitpos;
5555   int ll_unsignedp, lr_unsignedp, rl_unsignedp, rr_unsignedp;
5556   int ll_reversep, lr_reversep, rl_reversep, rr_reversep;
5557   machine_mode ll_mode, lr_mode, rl_mode, rr_mode;
5558   machine_mode lnmode, rnmode;
5559   tree ll_mask, lr_mask, rl_mask, rr_mask;
5560   tree ll_and_mask, lr_and_mask, rl_and_mask, rr_and_mask;
5561   tree l_const, r_const;
5562   tree lntype, rntype, result;
5563   HOST_WIDE_INT first_bit, end_bit;
5564   int volatilep;
5565
5566   /* Start by getting the comparison codes.  Fail if anything is volatile.
5567      If one operand is a BIT_AND_EXPR with the constant one, treat it as if
5568      it were surrounded with a NE_EXPR.  */
5569
5570   if (TREE_SIDE_EFFECTS (lhs) || TREE_SIDE_EFFECTS (rhs))
5571     return 0;
5572
5573   lcode = TREE_CODE (lhs);
5574   rcode = TREE_CODE (rhs);
5575
5576   if (lcode == BIT_AND_EXPR && integer_onep (TREE_OPERAND (lhs, 1)))
5577     {
5578       lhs = build2 (NE_EXPR, truth_type, lhs,
5579                     build_int_cst (TREE_TYPE (lhs), 0));
5580       lcode = NE_EXPR;
5581     }
5582
5583   if (rcode == BIT_AND_EXPR && integer_onep (TREE_OPERAND (rhs, 1)))
5584     {
5585       rhs = build2 (NE_EXPR, truth_type, rhs,
5586                     build_int_cst (TREE_TYPE (rhs), 0));
5587       rcode = NE_EXPR;
5588     }
5589
5590   if (TREE_CODE_CLASS (lcode) != tcc_comparison
5591       || TREE_CODE_CLASS (rcode) != tcc_comparison)
5592     return 0;
5593
5594   ll_arg = TREE_OPERAND (lhs, 0);
5595   lr_arg = TREE_OPERAND (lhs, 1);
5596   rl_arg = TREE_OPERAND (rhs, 0);
5597   rr_arg = TREE_OPERAND (rhs, 1);
5598
5599   /* Simplify (x<y) && (x==y) into (x<=y) and related optimizations.  */
5600   if (simple_operand_p (ll_arg)
5601       && simple_operand_p (lr_arg))
5602     {
5603       if (operand_equal_p (ll_arg, rl_arg, 0)
5604           && operand_equal_p (lr_arg, rr_arg, 0))
5605         {
5606           result = combine_comparisons (loc, code, lcode, rcode,
5607                                         truth_type, ll_arg, lr_arg);
5608           if (result)
5609             return result;
5610         }
5611       else if (operand_equal_p (ll_arg, rr_arg, 0)
5612                && operand_equal_p (lr_arg, rl_arg, 0))
5613         {
5614           result = combine_comparisons (loc, code, lcode,
5615                                         swap_tree_comparison (rcode),
5616                                         truth_type, ll_arg, lr_arg);
5617           if (result)
5618             return result;
5619         }
5620     }
5621
5622   code = ((code == TRUTH_AND_EXPR || code == TRUTH_ANDIF_EXPR)
5623           ? TRUTH_AND_EXPR : TRUTH_OR_EXPR);
5624
5625   /* If the RHS can be evaluated unconditionally and its operands are
5626      simple, it wins to evaluate the RHS unconditionally on machines
5627      with expensive branches.  In this case, this isn't a comparison
5628      that can be merged.  */
5629
5630   if (BRANCH_COST (optimize_function_for_speed_p (cfun),
5631                    false) >= 2
5632       && ! FLOAT_TYPE_P (TREE_TYPE (rl_arg))
5633       && simple_operand_p (rl_arg)
5634       && simple_operand_p (rr_arg))
5635     {
5636       /* Convert (a != 0) || (b != 0) into (a | b) != 0.  */
5637       if (code == TRUTH_OR_EXPR
5638           && lcode == NE_EXPR && integer_zerop (lr_arg)
5639           && rcode == NE_EXPR && integer_zerop (rr_arg)
5640           && TREE_TYPE (ll_arg) == TREE_TYPE (rl_arg)
5641           && INTEGRAL_TYPE_P (TREE_TYPE (ll_arg)))
5642         return build2_loc (loc, NE_EXPR, truth_type,
5643                            build2 (BIT_IOR_EXPR, TREE_TYPE (ll_arg),
5644                                    ll_arg, rl_arg),
5645                            build_int_cst (TREE_TYPE (ll_arg), 0));
5646
5647       /* Convert (a == 0) && (b == 0) into (a | b) == 0.  */
5648       if (code == TRUTH_AND_EXPR
5649           && lcode == EQ_EXPR && integer_zerop (lr_arg)
5650           && rcode == EQ_EXPR && integer_zerop (rr_arg)
5651           && TREE_TYPE (ll_arg) == TREE_TYPE (rl_arg)
5652           && INTEGRAL_TYPE_P (TREE_TYPE (ll_arg)))
5653         return build2_loc (loc, EQ_EXPR, truth_type,
5654                            build2 (BIT_IOR_EXPR, TREE_TYPE (ll_arg),
5655                                    ll_arg, rl_arg),
5656                            build_int_cst (TREE_TYPE (ll_arg), 0));
5657     }
5658
5659   /* See if the comparisons can be merged.  Then get all the parameters for
5660      each side.  */
5661
5662   if ((lcode != EQ_EXPR && lcode != NE_EXPR)
5663       || (rcode != EQ_EXPR && rcode != NE_EXPR))
5664     return 0;
5665
5666   ll_reversep = lr_reversep = rl_reversep = rr_reversep = 0;
5667   volatilep = 0;
5668   ll_inner = decode_field_reference (loc, &ll_arg,
5669                                      &ll_bitsize, &ll_bitpos, &ll_mode,
5670                                      &ll_unsignedp, &ll_reversep, &volatilep,
5671                                      &ll_mask, &ll_and_mask);
5672   lr_inner = decode_field_reference (loc, &lr_arg,
5673                                      &lr_bitsize, &lr_bitpos, &lr_mode,
5674                                      &lr_unsignedp, &lr_reversep, &volatilep,
5675                                      &lr_mask, &lr_and_mask);
5676   rl_inner = decode_field_reference (loc, &rl_arg,
5677                                      &rl_bitsize, &rl_bitpos, &rl_mode,
5678                                      &rl_unsignedp, &rl_reversep, &volatilep,
5679                                      &rl_mask, &rl_and_mask);
5680   rr_inner = decode_field_reference (loc, &rr_arg,
5681                                      &rr_bitsize, &rr_bitpos, &rr_mode,
5682                                      &rr_unsignedp, &rr_reversep, &volatilep,
5683                                      &rr_mask, &rr_and_mask);
5684
5685   /* It must be true that the inner operation on the lhs of each
5686      comparison must be the same if we are to be able to do anything.
5687      Then see if we have constants.  If not, the same must be true for
5688      the rhs's.  */
5689   if (volatilep
5690       || ll_reversep != rl_reversep
5691       || ll_inner == 0 || rl_inner == 0
5692       || ! operand_equal_p (ll_inner, rl_inner, 0))
5693     return 0;
5694
5695   if (TREE_CODE (lr_arg) == INTEGER_CST
5696       && TREE_CODE (rr_arg) == INTEGER_CST)
5697     {
5698       l_const = lr_arg, r_const = rr_arg;
5699       lr_reversep = ll_reversep;
5700     }
5701   else if (lr_reversep != rr_reversep
5702            || lr_inner == 0 || rr_inner == 0
5703            || ! operand_equal_p (lr_inner, rr_inner, 0))
5704     return 0;
5705   else
5706     l_const = r_const = 0;
5707
5708   /* If either comparison code is not correct for our logical operation,
5709      fail.  However, we can convert a one-bit comparison against zero into
5710      the opposite comparison against that bit being set in the field.  */
5711
5712   wanted_code = (code == TRUTH_AND_EXPR ? EQ_EXPR : NE_EXPR);
5713   if (lcode != wanted_code)
5714     {
5715       if (l_const && integer_zerop (l_const) && integer_pow2p (ll_mask))
5716         {
5717           /* Make the left operand unsigned, since we are only interested
5718              in the value of one bit.  Otherwise we are doing the wrong
5719              thing below.  */
5720           ll_unsignedp = 1;
5721           l_const = ll_mask;
5722         }
5723       else
5724         return 0;
5725     }
5726
5727   /* This is analogous to the code for l_const above.  */
5728   if (rcode != wanted_code)
5729     {
5730       if (r_const && integer_zerop (r_const) && integer_pow2p (rl_mask))
5731         {
5732           rl_unsignedp = 1;
5733           r_const = rl_mask;
5734         }
5735       else
5736         return 0;
5737     }
5738
5739   /* See if we can find a mode that contains both fields being compared on
5740      the left.  If we can't, fail.  Otherwise, update all constants and masks
5741      to be relative to a field of that size.  */
5742   first_bit = MIN (ll_bitpos, rl_bitpos);
5743   end_bit = MAX (ll_bitpos + ll_bitsize, rl_bitpos + rl_bitsize);
5744   lnmode = get_best_mode (end_bit - first_bit, first_bit, 0, 0,
5745                           TYPE_ALIGN (TREE_TYPE (ll_inner)), word_mode,
5746                           volatilep);
5747   if (lnmode == VOIDmode)
5748     return 0;
5749
5750   lnbitsize = GET_MODE_BITSIZE (lnmode);
5751   lnbitpos = first_bit & ~ (lnbitsize - 1);
5752   lntype = lang_hooks.types.type_for_size (lnbitsize, 1);
5753   xll_bitpos = ll_bitpos - lnbitpos, xrl_bitpos = rl_bitpos - lnbitpos;
5754
5755   if (ll_reversep ? !BYTES_BIG_ENDIAN : BYTES_BIG_ENDIAN)
5756     {
5757       xll_bitpos = lnbitsize - xll_bitpos - ll_bitsize;
5758       xrl_bitpos = lnbitsize - xrl_bitpos - rl_bitsize;
5759     }
5760
5761   ll_mask = const_binop (LSHIFT_EXPR, fold_convert_loc (loc, lntype, ll_mask),
5762                          size_int (xll_bitpos));
5763   rl_mask = const_binop (LSHIFT_EXPR, fold_convert_loc (loc, lntype, rl_mask),
5764                          size_int (xrl_bitpos));
5765
5766   if (l_const)
5767     {
5768       l_const = fold_convert_loc (loc, lntype, l_const);
5769       l_const = unextend (l_const, ll_bitsize, ll_unsignedp, ll_and_mask);
5770       l_const = const_binop (LSHIFT_EXPR, l_const, size_int (xll_bitpos));
5771       if (! integer_zerop (const_binop (BIT_AND_EXPR, l_const,
5772                                         fold_build1_loc (loc, BIT_NOT_EXPR,
5773                                                      lntype, ll_mask))))
5774         {
5775           warning (0, "comparison is always %d", wanted_code == NE_EXPR);
5776
5777           return constant_boolean_node (wanted_code == NE_EXPR, truth_type);
5778         }
5779     }
5780   if (r_const)
5781     {
5782       r_const = fold_convert_loc (loc, lntype, r_const);
5783       r_const = unextend (r_const, rl_bitsize, rl_unsignedp, rl_and_mask);
5784       r_const = const_binop (LSHIFT_EXPR, r_const, size_int (xrl_bitpos));
5785       if (! integer_zerop (const_binop (BIT_AND_EXPR, r_const,
5786                                         fold_build1_loc (loc, BIT_NOT_EXPR,
5787                                                      lntype, rl_mask))))
5788         {
5789           warning (0, "comparison is always %d", wanted_code == NE_EXPR);
5790
5791           return constant_boolean_node (wanted_code == NE_EXPR, truth_type);
5792         }
5793     }
5794
5795   /* If the right sides are not constant, do the same for it.  Also,
5796      disallow this optimization if a size or signedness mismatch occurs
5797      between the left and right sides.  */
5798   if (l_const == 0)
5799     {
5800       if (ll_bitsize != lr_bitsize || rl_bitsize != rr_bitsize
5801           || ll_unsignedp != lr_unsignedp || rl_unsignedp != rr_unsignedp
5802           /* Make sure the two fields on the right
5803              correspond to the left without being swapped.  */
5804           || ll_bitpos - rl_bitpos != lr_bitpos - rr_bitpos)
5805         return 0;
5806
5807       first_bit = MIN (lr_bitpos, rr_bitpos);
5808       end_bit = MAX (lr_bitpos + lr_bitsize, rr_bitpos + rr_bitsize);
5809       rnmode = get_best_mode (end_bit - first_bit, first_bit, 0, 0,
5810                               TYPE_ALIGN (TREE_TYPE (lr_inner)), word_mode,
5811                               volatilep);
5812       if (rnmode == VOIDmode)
5813         return 0;
5814
5815       rnbitsize = GET_MODE_BITSIZE (rnmode);
5816       rnbitpos = first_bit & ~ (rnbitsize - 1);
5817       rntype = lang_hooks.types.type_for_size (rnbitsize, 1);
5818       xlr_bitpos = lr_bitpos - rnbitpos, xrr_bitpos = rr_bitpos - rnbitpos;
5819
5820       if (lr_reversep ? !BYTES_BIG_ENDIAN : BYTES_BIG_ENDIAN)
5821         {
5822           xlr_bitpos = rnbitsize - xlr_bitpos - lr_bitsize;
5823           xrr_bitpos = rnbitsize - xrr_bitpos - rr_bitsize;
5824         }
5825
5826       lr_mask = const_binop (LSHIFT_EXPR, fold_convert_loc (loc,
5827                                                             rntype, lr_mask),
5828                              size_int (xlr_bitpos));
5829       rr_mask = const_binop (LSHIFT_EXPR, fold_convert_loc (loc,
5830                                                             rntype, rr_mask),
5831                              size_int (xrr_bitpos));
5832
5833       /* Make a mask that corresponds to both fields being compared.
5834          Do this for both items being compared.  If the operands are the
5835          same size and the bits being compared are in the same position
5836          then we can do this by masking both and comparing the masked
5837          results.  */
5838       ll_mask = const_binop (BIT_IOR_EXPR, ll_mask, rl_mask);
5839       lr_mask = const_binop (BIT_IOR_EXPR, lr_mask, rr_mask);
5840       if (lnbitsize == rnbitsize && xll_bitpos == xlr_bitpos)
5841         {
5842           lhs = make_bit_field_ref (loc, ll_inner, ll_arg,
5843                                     lntype, lnbitsize, lnbitpos,
5844                                     ll_unsignedp || rl_unsignedp, ll_reversep);
5845           if (! all_ones_mask_p (ll_mask, lnbitsize))
5846             lhs = build2 (BIT_AND_EXPR, lntype, lhs, ll_mask);
5847
5848           rhs = make_bit_field_ref (loc, lr_inner, lr_arg,
5849                                     rntype, rnbitsize, rnbitpos,
5850                                     lr_unsignedp || rr_unsignedp, lr_reversep);
5851           if (! all_ones_mask_p (lr_mask, rnbitsize))
5852             rhs = build2 (BIT_AND_EXPR, rntype, rhs, lr_mask);
5853
5854           return build2_loc (loc, wanted_code, truth_type, lhs, rhs);
5855         }
5856
5857       /* There is still another way we can do something:  If both pairs of
5858          fields being compared are adjacent, we may be able to make a wider
5859          field containing them both.
5860
5861          Note that we still must mask the lhs/rhs expressions.  Furthermore,
5862          the mask must be shifted to account for the shift done by
5863          make_bit_field_ref.  */
5864       if ((ll_bitsize + ll_bitpos == rl_bitpos
5865            && lr_bitsize + lr_bitpos == rr_bitpos)
5866           || (ll_bitpos == rl_bitpos + rl_bitsize
5867               && lr_bitpos == rr_bitpos + rr_bitsize))
5868         {
5869           tree type;
5870
5871           lhs = make_bit_field_ref (loc, ll_inner, ll_arg, lntype,
5872                                     ll_bitsize + rl_bitsize,
5873                                     MIN (ll_bitpos, rl_bitpos),
5874                                     ll_unsignedp, ll_reversep);
5875           rhs = make_bit_field_ref (loc, lr_inner, lr_arg, rntype,
5876                                     lr_bitsize + rr_bitsize,
5877                                     MIN (lr_bitpos, rr_bitpos),
5878                                     lr_unsignedp, lr_reversep);
5879
5880           ll_mask = const_binop (RSHIFT_EXPR, ll_mask,
5881                                  size_int (MIN (xll_bitpos, xrl_bitpos)));
5882           lr_mask = const_binop (RSHIFT_EXPR, lr_mask,
5883                                  size_int (MIN (xlr_bitpos, xrr_bitpos)));
5884
5885           /* Convert to the smaller type before masking out unwanted bits.  */
5886           type = lntype;
5887           if (lntype != rntype)
5888             {
5889               if (lnbitsize > rnbitsize)
5890                 {
5891                   lhs = fold_convert_loc (loc, rntype, lhs);
5892                   ll_mask = fold_convert_loc (loc, rntype, ll_mask);
5893                   type = rntype;
5894                 }
5895               else if (lnbitsize < rnbitsize)
5896                 {
5897                   rhs = fold_convert_loc (loc, lntype, rhs);
5898                   lr_mask = fold_convert_loc (loc, lntype, lr_mask);
5899                   type = lntype;
5900                 }
5901             }
5902
5903           if (! all_ones_mask_p (ll_mask, ll_bitsize + rl_bitsize))
5904             lhs = build2 (BIT_AND_EXPR, type, lhs, ll_mask);
5905
5906           if (! all_ones_mask_p (lr_mask, lr_bitsize + rr_bitsize))
5907             rhs = build2 (BIT_AND_EXPR, type, rhs, lr_mask);
5908
5909           return build2_loc (loc, wanted_code, truth_type, lhs, rhs);
5910         }
5911
5912       return 0;
5913     }
5914
5915   /* Handle the case of comparisons with constants.  If there is something in
5916      common between the masks, those bits of the constants must be the same.
5917      If not, the condition is always false.  Test for this to avoid generating
5918      incorrect code below.  */
5919   result = const_binop (BIT_AND_EXPR, ll_mask, rl_mask);
5920   if (! integer_zerop (result)
5921       && simple_cst_equal (const_binop (BIT_AND_EXPR, result, l_const),
5922                            const_binop (BIT_AND_EXPR, result, r_const)) != 1)
5923     {
5924       if (wanted_code == NE_EXPR)
5925         {
5926           warning (0, "%<or%> of unmatched not-equal tests is always 1");
5927           return constant_boolean_node (true, truth_type);
5928         }
5929       else
5930         {
5931           warning (0, "%<and%> of mutually exclusive equal-tests is always 0");
5932           return constant_boolean_node (false, truth_type);
5933         }
5934     }
5935
5936   /* Construct the expression we will return.  First get the component
5937      reference we will make.  Unless the mask is all ones the width of
5938      that field, perform the mask operation.  Then compare with the
5939      merged constant.  */
5940   result = make_bit_field_ref (loc, ll_inner, ll_arg,
5941                                lntype, lnbitsize, lnbitpos,
5942                                ll_unsignedp || rl_unsignedp, ll_reversep);
5943
5944   ll_mask = const_binop (BIT_IOR_EXPR, ll_mask, rl_mask);
5945   if (! all_ones_mask_p (ll_mask, lnbitsize))
5946     result = build2_loc (loc, BIT_AND_EXPR, lntype, result, ll_mask);
5947
5948   return build2_loc (loc, wanted_code, truth_type, result,
5949                      const_binop (BIT_IOR_EXPR, l_const, r_const));
5950 }
5951 \f
5952 /* Optimize T, which is a comparison of a MIN_EXPR or MAX_EXPR with a
5953    constant.  */
5954
5955 static tree
5956 optimize_minmax_comparison (location_t loc, enum tree_code code, tree type,
5957                             tree op0, tree op1)
5958 {
5959   tree arg0 = op0;
5960   enum tree_code op_code;
5961   tree comp_const;
5962   tree minmax_const;
5963   int consts_equal, consts_lt;
5964   tree inner;
5965
5966   STRIP_SIGN_NOPS (arg0);
5967
5968   op_code = TREE_CODE (arg0);
5969   minmax_const = TREE_OPERAND (arg0, 1);
5970   comp_const = fold_convert_loc (loc, TREE_TYPE (arg0), op1);
5971   consts_equal = tree_int_cst_equal (minmax_const, comp_const);
5972   consts_lt = tree_int_cst_lt (minmax_const, comp_const);
5973   inner = TREE_OPERAND (arg0, 0);
5974
5975   /* If something does not permit us to optimize, return the original tree.  */
5976   if ((op_code != MIN_EXPR && op_code != MAX_EXPR)
5977       || TREE_CODE (comp_const) != INTEGER_CST
5978       || TREE_OVERFLOW (comp_const)
5979       || TREE_CODE (minmax_const) != INTEGER_CST
5980       || TREE_OVERFLOW (minmax_const))
5981     return NULL_TREE;
5982
5983   /* Now handle all the various comparison codes.  We only handle EQ_EXPR
5984      and GT_EXPR, doing the rest with recursive calls using logical
5985      simplifications.  */
5986   switch (code)
5987     {
5988     case NE_EXPR:  case LT_EXPR:  case LE_EXPR:
5989       {
5990         tree tem
5991           = optimize_minmax_comparison (loc,
5992                                         invert_tree_comparison (code, false),
5993                                         type, op0, op1);
5994         if (tem)
5995           return invert_truthvalue_loc (loc, tem);
5996         return NULL_TREE;
5997       }
5998
5999     case GE_EXPR:
6000       return
6001         fold_build2_loc (loc, TRUTH_ORIF_EXPR, type,
6002                      optimize_minmax_comparison
6003                      (loc, EQ_EXPR, type, arg0, comp_const),
6004                      optimize_minmax_comparison
6005                      (loc, GT_EXPR, type, arg0, comp_const));
6006
6007     case EQ_EXPR:
6008       if (op_code == MAX_EXPR && consts_equal)
6009         /* MAX (X, 0) == 0  ->  X <= 0  */
6010         return fold_build2_loc (loc, LE_EXPR, type, inner, comp_const);
6011
6012       else if (op_code == MAX_EXPR && consts_lt)
6013         /* MAX (X, 0) == 5  ->  X == 5   */
6014         return fold_build2_loc (loc, EQ_EXPR, type, inner, comp_const);
6015
6016       else if (op_code == MAX_EXPR)
6017         /* MAX (X, 0) == -1  ->  false  */
6018         return omit_one_operand_loc (loc, type, integer_zero_node, inner);
6019
6020       else if (consts_equal)
6021         /* MIN (X, 0) == 0  ->  X >= 0  */
6022         return fold_build2_loc (loc, GE_EXPR, type, inner, comp_const);
6023
6024       else if (consts_lt)
6025         /* MIN (X, 0) == 5  ->  false  */
6026         return omit_one_operand_loc (loc, type, integer_zero_node, inner);
6027
6028       else
6029         /* MIN (X, 0) == -1  ->  X == -1  */
6030         return fold_build2_loc (loc, EQ_EXPR, type, inner, comp_const);
6031
6032     case GT_EXPR:
6033       if (op_code == MAX_EXPR && (consts_equal || consts_lt))
6034         /* MAX (X, 0) > 0  ->  X > 0
6035            MAX (X, 0) > 5  ->  X > 5  */
6036         return fold_build2_loc (loc, GT_EXPR, type, inner, comp_const);
6037
6038       else if (op_code == MAX_EXPR)
6039         /* MAX (X, 0) > -1  ->  true  */
6040         return omit_one_operand_loc (loc, type, integer_one_node, inner);
6041
6042       else if (op_code == MIN_EXPR && (consts_equal || consts_lt))
6043         /* MIN (X, 0) > 0  ->  false
6044            MIN (X, 0) > 5  ->  false  */
6045         return omit_one_operand_loc (loc, type, integer_zero_node, inner);
6046
6047       else
6048         /* MIN (X, 0) > -1  ->  X > -1  */
6049         return fold_build2_loc (loc, GT_EXPR, type, inner, comp_const);
6050
6051     default:
6052       return NULL_TREE;
6053     }
6054 }
6055 \f
6056 /* T is an integer expression that is being multiplied, divided, or taken a
6057    modulus (CODE says which and what kind of divide or modulus) by a
6058    constant C.  See if we can eliminate that operation by folding it with
6059    other operations already in T.  WIDE_TYPE, if non-null, is a type that
6060    should be used for the computation if wider than our type.
6061
6062    For example, if we are dividing (X * 8) + (Y * 16) by 4, we can return
6063    (X * 2) + (Y * 4).  We must, however, be assured that either the original
6064    expression would not overflow or that overflow is undefined for the type
6065    in the language in question.
6066
6067    If we return a non-null expression, it is an equivalent form of the
6068    original computation, but need not be in the original type.
6069
6070    We set *STRICT_OVERFLOW_P to true if the return values depends on
6071    signed overflow being undefined.  Otherwise we do not change
6072    *STRICT_OVERFLOW_P.  */
6073
6074 static tree
6075 extract_muldiv (tree t, tree c, enum tree_code code, tree wide_type,
6076                 bool *strict_overflow_p)
6077 {
6078   /* To avoid exponential search depth, refuse to allow recursion past
6079      three levels.  Beyond that (1) it's highly unlikely that we'll find
6080      something interesting and (2) we've probably processed it before
6081      when we built the inner expression.  */
6082
6083   static int depth;
6084   tree ret;
6085
6086   if (depth > 3)
6087     return NULL;
6088
6089   depth++;
6090   ret = extract_muldiv_1 (t, c, code, wide_type, strict_overflow_p);
6091   depth--;
6092
6093   return ret;
6094 }
6095
6096 static tree
6097 extract_muldiv_1 (tree t, tree c, enum tree_code code, tree wide_type,
6098                   bool *strict_overflow_p)
6099 {
6100   tree type = TREE_TYPE (t);
6101   enum tree_code tcode = TREE_CODE (t);
6102   tree ctype = (wide_type != 0 && (GET_MODE_SIZE (TYPE_MODE (wide_type))
6103                                    > GET_MODE_SIZE (TYPE_MODE (type)))
6104                 ? wide_type : type);
6105   tree t1, t2;
6106   int same_p = tcode == code;
6107   tree op0 = NULL_TREE, op1 = NULL_TREE;
6108   bool sub_strict_overflow_p;
6109
6110   /* Don't deal with constants of zero here; they confuse the code below.  */
6111   if (integer_zerop (c))
6112     return NULL_TREE;
6113
6114   if (TREE_CODE_CLASS (tcode) == tcc_unary)
6115     op0 = TREE_OPERAND (t, 0);
6116
6117   if (TREE_CODE_CLASS (tcode) == tcc_binary)
6118     op0 = TREE_OPERAND (t, 0), op1 = TREE_OPERAND (t, 1);
6119
6120   /* Note that we need not handle conditional operations here since fold
6121      already handles those cases.  So just do arithmetic here.  */
6122   switch (tcode)
6123     {
6124     case INTEGER_CST:
6125       /* For a constant, we can always simplify if we are a multiply
6126          or (for divide and modulus) if it is a multiple of our constant.  */
6127       if (code == MULT_EXPR
6128           || wi::multiple_of_p (t, c, TYPE_SIGN (type)))
6129         {
6130           tree tem = const_binop (code, fold_convert (ctype, t),
6131                                   fold_convert (ctype, c));
6132           /* If the multiplication overflowed, we lost information on it.
6133              See PR68142 and PR69845.  */
6134           if (TREE_OVERFLOW (tem))
6135             return NULL_TREE;
6136           return tem;
6137         }
6138       break;
6139
6140     CASE_CONVERT: case NON_LVALUE_EXPR:
6141       /* If op0 is an expression ...  */
6142       if ((COMPARISON_CLASS_P (op0)
6143            || UNARY_CLASS_P (op0)
6144            || BINARY_CLASS_P (op0)
6145            || VL_EXP_CLASS_P (op0)
6146            || EXPRESSION_CLASS_P (op0))
6147           /* ... and has wrapping overflow, and its type is smaller
6148              than ctype, then we cannot pass through as widening.  */
6149           && (((ANY_INTEGRAL_TYPE_P (TREE_TYPE (op0))
6150                 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
6151                && (TYPE_PRECISION (ctype)
6152                    > TYPE_PRECISION (TREE_TYPE (op0))))
6153               /* ... or this is a truncation (t is narrower than op0),
6154                  then we cannot pass through this narrowing.  */
6155               || (TYPE_PRECISION (type)
6156                   < TYPE_PRECISION (TREE_TYPE (op0)))
6157               /* ... or signedness changes for division or modulus,
6158                  then we cannot pass through this conversion.  */
6159               || (code != MULT_EXPR
6160                   && (TYPE_UNSIGNED (ctype)
6161                       != TYPE_UNSIGNED (TREE_TYPE (op0))))
6162               /* ... or has undefined overflow while the converted to
6163                  type has not, we cannot do the operation in the inner type
6164                  as that would introduce undefined overflow.  */
6165               || ((ANY_INTEGRAL_TYPE_P (TREE_TYPE (op0))
6166                    && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (op0)))
6167                   && !TYPE_OVERFLOW_UNDEFINED (type))))
6168         break;
6169
6170       /* Pass the constant down and see if we can make a simplification.  If
6171          we can, replace this expression with the inner simplification for
6172          possible later conversion to our or some other type.  */
6173       if ((t2 = fold_convert (TREE_TYPE (op0), c)) != 0
6174           && TREE_CODE (t2) == INTEGER_CST
6175           && !TREE_OVERFLOW (t2)
6176           && (0 != (t1 = extract_muldiv (op0, t2, code,
6177                                          code == MULT_EXPR
6178                                          ? ctype : NULL_TREE,
6179                                          strict_overflow_p))))
6180         return t1;
6181       break;
6182
6183     case ABS_EXPR:
6184       /* If widening the type changes it from signed to unsigned, then we
6185          must avoid building ABS_EXPR itself as unsigned.  */
6186       if (TYPE_UNSIGNED (ctype) && !TYPE_UNSIGNED (type))
6187         {
6188           tree cstype = (*signed_type_for) (ctype);
6189           if ((t1 = extract_muldiv (op0, c, code, cstype, strict_overflow_p))
6190               != 0)
6191             {
6192               t1 = fold_build1 (tcode, cstype, fold_convert (cstype, t1));
6193               return fold_convert (ctype, t1);
6194             }
6195           break;
6196         }
6197       /* If the constant is negative, we cannot simplify this.  */
6198       if (tree_int_cst_sgn (c) == -1)
6199         break;
6200       /* FALLTHROUGH */
6201     case NEGATE_EXPR:
6202       /* For division and modulus, type can't be unsigned, as e.g.
6203          (-(x / 2U)) / 2U isn't equal to -((x / 2U) / 2U) for x >= 2.
6204          For signed types, even with wrapping overflow, this is fine.  */
6205       if (code != MULT_EXPR && TYPE_UNSIGNED (type))
6206         break;
6207       if ((t1 = extract_muldiv (op0, c, code, wide_type, strict_overflow_p))
6208           != 0)
6209         return fold_build1 (tcode, ctype, fold_convert (ctype, t1));
6210       break;
6211
6212     case MIN_EXPR:  case MAX_EXPR:
6213       /* If widening the type changes the signedness, then we can't perform
6214          this optimization as that changes the result.  */
6215       if (TYPE_UNSIGNED (ctype) != TYPE_UNSIGNED (type))
6216         break;
6217
6218       /* MIN (a, b) / 5 -> MIN (a / 5, b / 5)  */
6219       sub_strict_overflow_p = false;
6220       if ((t1 = extract_muldiv (op0, c, code, wide_type,
6221                                 &sub_strict_overflow_p)) != 0
6222           && (t2 = extract_muldiv (op1, c, code, wide_type,
6223                                    &sub_strict_overflow_p)) != 0)
6224         {
6225           if (tree_int_cst_sgn (c) < 0)
6226             tcode = (tcode == MIN_EXPR ? MAX_EXPR : MIN_EXPR);
6227           if (sub_strict_overflow_p)
6228             *strict_overflow_p = true;
6229           return fold_build2 (tcode, ctype, fold_convert (ctype, t1),
6230                               fold_convert (ctype, t2));
6231         }
6232       break;
6233
6234     case LSHIFT_EXPR:  case RSHIFT_EXPR:
6235       /* If the second operand is constant, this is a multiplication
6236          or floor division, by a power of two, so we can treat it that
6237          way unless the multiplier or divisor overflows.  Signed
6238          left-shift overflow is implementation-defined rather than
6239          undefined in C90, so do not convert signed left shift into
6240          multiplication.  */
6241       if (TREE_CODE (op1) == INTEGER_CST
6242           && (tcode == RSHIFT_EXPR || TYPE_UNSIGNED (TREE_TYPE (op0)))
6243           /* const_binop may not detect overflow correctly,
6244              so check for it explicitly here.  */
6245           && wi::gtu_p (TYPE_PRECISION (TREE_TYPE (size_one_node)), op1)
6246           && 0 != (t1 = fold_convert (ctype,
6247                                       const_binop (LSHIFT_EXPR,
6248                                                    size_one_node,
6249                                                    op1)))
6250           && !TREE_OVERFLOW (t1))
6251         return extract_muldiv (build2 (tcode == LSHIFT_EXPR
6252                                        ? MULT_EXPR : FLOOR_DIV_EXPR,
6253                                        ctype,
6254                                        fold_convert (ctype, op0),
6255                                        t1),
6256                                c, code, wide_type, strict_overflow_p);
6257       break;
6258
6259     case PLUS_EXPR:  case MINUS_EXPR:
6260       /* See if we can eliminate the operation on both sides.  If we can, we
6261          can return a new PLUS or MINUS.  If we can't, the only remaining
6262          cases where we can do anything are if the second operand is a
6263          constant.  */
6264       sub_strict_overflow_p = false;
6265       t1 = extract_muldiv (op0, c, code, wide_type, &sub_strict_overflow_p);
6266       t2 = extract_muldiv (op1, c, code, wide_type, &sub_strict_overflow_p);
6267       if (t1 != 0 && t2 != 0
6268           && (code == MULT_EXPR
6269               /* If not multiplication, we can only do this if both operands
6270                  are divisible by c.  */
6271               || (multiple_of_p (ctype, op0, c)
6272                   && multiple_of_p (ctype, op1, c))))
6273         {
6274           if (sub_strict_overflow_p)
6275             *strict_overflow_p = true;
6276           return fold_build2 (tcode, ctype, fold_convert (ctype, t1),
6277                               fold_convert (ctype, t2));
6278         }
6279
6280       /* If this was a subtraction, negate OP1 and set it to be an addition.
6281          This simplifies the logic below.  */
6282       if (tcode == MINUS_EXPR)
6283         {
6284           tcode = PLUS_EXPR, op1 = negate_expr (op1);
6285           /* If OP1 was not easily negatable, the constant may be OP0.  */
6286           if (TREE_CODE (op0) == INTEGER_CST)
6287             {
6288               std::swap (op0, op1);
6289               std::swap (t1, t2);
6290             }
6291         }
6292
6293       if (TREE_CODE (op1) != INTEGER_CST)
6294         break;
6295
6296       /* If either OP1 or C are negative, this optimization is not safe for
6297          some of the division and remainder types while for others we need
6298          to change the code.  */
6299       if (tree_int_cst_sgn (op1) < 0 || tree_int_cst_sgn (c) < 0)
6300         {
6301           if (code == CEIL_DIV_EXPR)
6302             code = FLOOR_DIV_EXPR;
6303           else if (code == FLOOR_DIV_EXPR)
6304             code = CEIL_DIV_EXPR;
6305           else if (code != MULT_EXPR
6306                    && code != CEIL_MOD_EXPR && code != FLOOR_MOD_EXPR)
6307             break;
6308         }
6309
6310       /* If it's a multiply or a division/modulus operation of a multiple
6311          of our constant, do the operation and verify it doesn't overflow.  */
6312       if (code == MULT_EXPR
6313           || wi::multiple_of_p (op1, c, TYPE_SIGN (type)))
6314         {
6315           op1 = const_binop (code, fold_convert (ctype, op1),
6316                              fold_convert (ctype, c));
6317           /* We allow the constant to overflow with wrapping semantics.  */
6318           if (op1 == 0
6319               || (TREE_OVERFLOW (op1) && !TYPE_OVERFLOW_WRAPS (ctype)))
6320             break;
6321         }
6322       else
6323         break;
6324
6325       /* If we have an unsigned type, we cannot widen the operation since it
6326          will change the result if the original computation overflowed.  */
6327       if (TYPE_UNSIGNED (ctype) && ctype != type)
6328         break;
6329
6330       /* If we were able to eliminate our operation from the first side,
6331          apply our operation to the second side and reform the PLUS.  */
6332       if (t1 != 0 && (TREE_CODE (t1) != code || code == MULT_EXPR))
6333         return fold_build2 (tcode, ctype, fold_convert (ctype, t1), op1);
6334
6335       /* The last case is if we are a multiply.  In that case, we can
6336          apply the distributive law to commute the multiply and addition
6337          if the multiplication of the constants doesn't overflow
6338          and overflow is defined.  With undefined overflow
6339          op0 * c might overflow, while (op0 + orig_op1) * c doesn't.  */
6340       if (code == MULT_EXPR && TYPE_OVERFLOW_WRAPS (ctype))
6341         return fold_build2 (tcode, ctype,
6342                             fold_build2 (code, ctype,
6343                                          fold_convert (ctype, op0),
6344                                          fold_convert (ctype, c)),
6345                             op1);
6346
6347       break;
6348
6349     case MULT_EXPR:
6350       /* We have a special case here if we are doing something like
6351          (C * 8) % 4 since we know that's zero.  */
6352       if ((code == TRUNC_MOD_EXPR || code == CEIL_MOD_EXPR
6353            || code == FLOOR_MOD_EXPR || code == ROUND_MOD_EXPR)
6354           /* If the multiplication can overflow we cannot optimize this.  */
6355           && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (t))
6356           && TREE_CODE (TREE_OPERAND (t, 1)) == INTEGER_CST
6357           && wi::multiple_of_p (op1, c, TYPE_SIGN (type)))
6358         {
6359           *strict_overflow_p = true;
6360           return omit_one_operand (type, integer_zero_node, op0);
6361         }
6362
6363       /* ... fall through ...  */
6364
6365     case TRUNC_DIV_EXPR:  case CEIL_DIV_EXPR:  case FLOOR_DIV_EXPR:
6366     case ROUND_DIV_EXPR:  case EXACT_DIV_EXPR:
6367       /* If we can extract our operation from the LHS, do so and return a
6368          new operation.  Likewise for the RHS from a MULT_EXPR.  Otherwise,
6369          do something only if the second operand is a constant.  */
6370       if (same_p
6371           && (t1 = extract_muldiv (op0, c, code, wide_type,
6372                                    strict_overflow_p)) != 0)
6373         return fold_build2 (tcode, ctype, fold_convert (ctype, t1),
6374                             fold_convert (ctype, op1));
6375       else if (tcode == MULT_EXPR && code == MULT_EXPR
6376                && (t1 = extract_muldiv (op1, c, code, wide_type,
6377                                         strict_overflow_p)) != 0)
6378         return fold_build2 (tcode, ctype, fold_convert (ctype, op0),
6379                             fold_convert (ctype, t1));
6380       else if (TREE_CODE (op1) != INTEGER_CST)
6381         return 0;
6382
6383       /* If these are the same operation types, we can associate them
6384          assuming no overflow.  */
6385       if (tcode == code)
6386         {
6387           bool overflow_p = false;
6388           bool overflow_mul_p;
6389           signop sign = TYPE_SIGN (ctype);
6390           unsigned prec = TYPE_PRECISION (ctype);
6391           wide_int mul = wi::mul (wide_int::from (op1, prec,
6392                                                   TYPE_SIGN (TREE_TYPE (op1))),
6393                                   wide_int::from (c, prec,
6394                                                   TYPE_SIGN (TREE_TYPE (c))),
6395                                   sign, &overflow_mul_p);
6396           overflow_p = TREE_OVERFLOW (c) | TREE_OVERFLOW (op1);
6397           if (overflow_mul_p
6398               && ((sign == UNSIGNED && tcode != MULT_EXPR) || sign == SIGNED))
6399             overflow_p = true;
6400           if (!overflow_p)
6401             return fold_build2 (tcode, ctype, fold_convert (ctype, op0),
6402                                 wide_int_to_tree (ctype, mul));
6403         }
6404
6405       /* If these operations "cancel" each other, we have the main
6406          optimizations of this pass, which occur when either constant is a
6407          multiple of the other, in which case we replace this with either an
6408          operation or CODE or TCODE.
6409
6410          If we have an unsigned type, we cannot do this since it will change
6411          the result if the original computation overflowed.  */
6412       if (TYPE_OVERFLOW_UNDEFINED (ctype)
6413           && ((code == MULT_EXPR && tcode == EXACT_DIV_EXPR)
6414               || (tcode == MULT_EXPR
6415                   && code != TRUNC_MOD_EXPR && code != CEIL_MOD_EXPR
6416                   && code != FLOOR_MOD_EXPR && code != ROUND_MOD_EXPR
6417                   && code != MULT_EXPR)))
6418         {
6419           if (wi::multiple_of_p (op1, c, TYPE_SIGN (type)))
6420             {
6421               if (TYPE_OVERFLOW_UNDEFINED (ctype))
6422                 *strict_overflow_p = true;
6423               return fold_build2 (tcode, ctype, fold_convert (ctype, op0),
6424                                   fold_convert (ctype,
6425                                                 const_binop (TRUNC_DIV_EXPR,
6426                                                              op1, c)));
6427             }
6428           else if (wi::multiple_of_p (c, op1, TYPE_SIGN (type)))
6429             {
6430               if (TYPE_OVERFLOW_UNDEFINED (ctype))
6431                 *strict_overflow_p = true;
6432               return fold_build2 (code, ctype, fold_convert (ctype, op0),
6433                                   fold_convert (ctype,
6434                                                 const_binop (TRUNC_DIV_EXPR,
6435                                                              c, op1)));
6436             }
6437         }
6438       break;
6439
6440     default:
6441       break;
6442     }
6443
6444   return 0;
6445 }
6446 \f
6447 /* Return a node which has the indicated constant VALUE (either 0 or
6448    1 for scalars or {-1,-1,..} or {0,0,...} for vectors),
6449    and is of the indicated TYPE.  */
6450
6451 tree
6452 constant_boolean_node (bool value, tree type)
6453 {
6454   if (type == integer_type_node)
6455     return value ? integer_one_node : integer_zero_node;
6456   else if (type == boolean_type_node)
6457     return value ? boolean_true_node : boolean_false_node;
6458   else if (TREE_CODE (type) == VECTOR_TYPE)
6459     return build_vector_from_val (type,
6460                                   build_int_cst (TREE_TYPE (type),
6461                                                  value ? -1 : 0));
6462   else
6463     return fold_convert (type, value ? integer_one_node : integer_zero_node);
6464 }
6465
6466
6467 /* Transform `a + (b ? x : y)' into `b ? (a + x) : (a + y)'.
6468    Transform, `a + (x < y)' into `(x < y) ? (a + 1) : (a + 0)'.  Here
6469    CODE corresponds to the `+', COND to the `(b ? x : y)' or `(x < y)'
6470    expression, and ARG to `a'.  If COND_FIRST_P is nonzero, then the
6471    COND is the first argument to CODE; otherwise (as in the example
6472    given here), it is the second argument.  TYPE is the type of the
6473    original expression.  Return NULL_TREE if no simplification is
6474    possible.  */
6475
6476 static tree
6477 fold_binary_op_with_conditional_arg (location_t loc,
6478                                      enum tree_code code,
6479                                      tree type, tree op0, tree op1,
6480                                      tree cond, tree arg, int cond_first_p)
6481 {
6482   tree cond_type = cond_first_p ? TREE_TYPE (op0) : TREE_TYPE (op1);
6483   tree arg_type = cond_first_p ? TREE_TYPE (op1) : TREE_TYPE (op0);
6484   tree test, true_value, false_value;
6485   tree lhs = NULL_TREE;
6486   tree rhs = NULL_TREE;
6487   enum tree_code cond_code = COND_EXPR;
6488
6489   if (TREE_CODE (cond) == COND_EXPR
6490       || TREE_CODE (cond) == VEC_COND_EXPR)
6491     {
6492       test = TREE_OPERAND (cond, 0);
6493       true_value = TREE_OPERAND (cond, 1);
6494       false_value = TREE_OPERAND (cond, 2);
6495       /* If this operand throws an expression, then it does not make
6496          sense to try to perform a logical or arithmetic operation
6497          involving it.  */
6498       if (VOID_TYPE_P (TREE_TYPE (true_value)))
6499         lhs = true_value;
6500       if (VOID_TYPE_P (TREE_TYPE (false_value)))
6501         rhs = false_value;
6502     }
6503   else if (!(TREE_CODE (type) != VECTOR_TYPE
6504              && TREE_CODE (TREE_TYPE (cond)) == VECTOR_TYPE))
6505     {
6506       tree testtype = TREE_TYPE (cond);
6507       test = cond;
6508       true_value = constant_boolean_node (true, testtype);
6509       false_value = constant_boolean_node (false, testtype);
6510     }
6511   else
6512     /* Detect the case of mixing vector and scalar types - bail out.  */
6513     return NULL_TREE;
6514
6515   if (TREE_CODE (TREE_TYPE (test)) == VECTOR_TYPE)
6516     cond_code = VEC_COND_EXPR;
6517
6518   /* This transformation is only worthwhile if we don't have to wrap ARG
6519      in a SAVE_EXPR and the operation can be simplified without recursing
6520      on at least one of the branches once its pushed inside the COND_EXPR.  */
6521   if (!TREE_CONSTANT (arg)
6522       && (TREE_SIDE_EFFECTS (arg)
6523           || TREE_CODE (arg) == COND_EXPR || TREE_CODE (arg) == VEC_COND_EXPR
6524           || TREE_CONSTANT (true_value) || TREE_CONSTANT (false_value)))
6525     return NULL_TREE;
6526
6527   arg = fold_convert_loc (loc, arg_type, arg);
6528   if (lhs == 0)
6529     {
6530       true_value = fold_convert_loc (loc, cond_type, true_value);
6531       if (cond_first_p)
6532         lhs = fold_build2_loc (loc, code, type, true_value, arg);
6533       else
6534         lhs = fold_build2_loc (loc, code, type, arg, true_value);
6535     }
6536   if (rhs == 0)
6537     {
6538       false_value = fold_convert_loc (loc, cond_type, false_value);
6539       if (cond_first_p)
6540         rhs = fold_build2_loc (loc, code, type, false_value, arg);
6541       else
6542         rhs = fold_build2_loc (loc, code, type, arg, false_value);
6543     }
6544
6545   /* Check that we have simplified at least one of the branches.  */
6546   if (!TREE_CONSTANT (arg) && !TREE_CONSTANT (lhs) && !TREE_CONSTANT (rhs))
6547     return NULL_TREE;
6548
6549   return fold_build3_loc (loc, cond_code, type, test, lhs, rhs);
6550 }
6551
6552 \f
6553 /* Subroutine of fold() that checks for the addition of +/- 0.0.
6554
6555    If !NEGATE, return true if ADDEND is +/-0.0 and, for all X of type
6556    TYPE, X + ADDEND is the same as X.  If NEGATE, return true if X -
6557    ADDEND is the same as X.
6558
6559    X + 0 and X - 0 both give X when X is NaN, infinite, or nonzero
6560    and finite.  The problematic cases are when X is zero, and its mode
6561    has signed zeros.  In the case of rounding towards -infinity,
6562    X - 0 is not the same as X because 0 - 0 is -0.  In other rounding
6563    modes, X + 0 is not the same as X because -0 + 0 is 0.  */
6564
6565 bool
6566 fold_real_zero_addition_p (const_tree type, const_tree addend, int negate)
6567 {
6568   if (!real_zerop (addend))
6569     return false;
6570
6571   /* Don't allow the fold with -fsignaling-nans.  */
6572   if (HONOR_SNANS (element_mode (type)))
6573     return false;
6574
6575   /* Allow the fold if zeros aren't signed, or their sign isn't important.  */
6576   if (!HONOR_SIGNED_ZEROS (element_mode (type)))
6577     return true;
6578
6579   /* In a vector or complex, we would need to check the sign of all zeros.  */
6580   if (TREE_CODE (addend) != REAL_CST)
6581     return false;
6582
6583   /* Treat x + -0 as x - 0 and x - -0 as x + 0.  */
6584   if (REAL_VALUE_MINUS_ZERO (TREE_REAL_CST (addend)))
6585     negate = !negate;
6586
6587   /* The mode has signed zeros, and we have to honor their sign.
6588      In this situation, there is only one case we can return true for.
6589      X - 0 is the same as X unless rounding towards -infinity is
6590      supported.  */
6591   return negate && !HONOR_SIGN_DEPENDENT_ROUNDING (element_mode (type));
6592 }
6593
6594 /* Subroutine of fold() that optimizes comparisons of a division by
6595    a nonzero integer constant against an integer constant, i.e.
6596    X/C1 op C2.
6597
6598    CODE is the comparison operator: EQ_EXPR, NE_EXPR, GT_EXPR, LT_EXPR,
6599    GE_EXPR or LE_EXPR.  TYPE is the type of the result and ARG0 and ARG1
6600    are the operands of the comparison.  ARG1 must be a TREE_REAL_CST.
6601
6602    The function returns the constant folded tree if a simplification
6603    can be made, and NULL_TREE otherwise.  */
6604
6605 static tree
6606 fold_div_compare (location_t loc,
6607                   enum tree_code code, tree type, tree arg0, tree arg1)
6608 {
6609   tree prod, tmp, hi, lo;
6610   tree arg00 = TREE_OPERAND (arg0, 0);
6611   tree arg01 = TREE_OPERAND (arg0, 1);
6612   signop sign = TYPE_SIGN (TREE_TYPE (arg0));
6613   bool neg_overflow = false;
6614   bool overflow;
6615
6616   /* We have to do this the hard way to detect unsigned overflow.
6617      prod = int_const_binop (MULT_EXPR, arg01, arg1);  */
6618   wide_int val = wi::mul (arg01, arg1, sign, &overflow);
6619   prod = force_fit_type (TREE_TYPE (arg00), val, -1, overflow);
6620   neg_overflow = false;
6621
6622   if (sign == UNSIGNED)
6623     {
6624       tmp = int_const_binop (MINUS_EXPR, arg01,
6625                              build_int_cst (TREE_TYPE (arg01), 1));
6626       lo = prod;
6627
6628       /* Likewise hi = int_const_binop (PLUS_EXPR, prod, tmp).  */
6629       val = wi::add (prod, tmp, sign, &overflow);
6630       hi = force_fit_type (TREE_TYPE (arg00), val,
6631                            -1, overflow | TREE_OVERFLOW (prod));
6632     }
6633   else if (tree_int_cst_sgn (arg01) >= 0)
6634     {
6635       tmp = int_const_binop (MINUS_EXPR, arg01,
6636                              build_int_cst (TREE_TYPE (arg01), 1));
6637       switch (tree_int_cst_sgn (arg1))
6638         {
6639         case -1:
6640           neg_overflow = true;
6641           lo = int_const_binop (MINUS_EXPR, prod, tmp);
6642           hi = prod;
6643           break;
6644
6645         case  0:
6646           lo = fold_negate_const (tmp, TREE_TYPE (arg0));
6647           hi = tmp;
6648           break;
6649
6650         case  1:
6651           hi = int_const_binop (PLUS_EXPR, prod, tmp);
6652           lo = prod;
6653           break;
6654
6655         default:
6656           gcc_unreachable ();
6657         }
6658     }
6659   else
6660     {
6661       /* A negative divisor reverses the relational operators.  */
6662       code = swap_tree_comparison (code);
6663
6664       tmp = int_const_binop (PLUS_EXPR, arg01,
6665                              build_int_cst (TREE_TYPE (arg01), 1));
6666       switch (tree_int_cst_sgn (arg1))
6667         {
6668         case -1:
6669           hi = int_const_binop (MINUS_EXPR, prod, tmp);
6670           lo = prod;
6671           break;
6672
6673         case  0:
6674           hi = fold_negate_const (tmp, TREE_TYPE (arg0));
6675           lo = tmp;
6676           break;
6677
6678         case  1:
6679           neg_overflow = true;
6680           lo = int_const_binop (PLUS_EXPR, prod, tmp);
6681           hi = prod;
6682           break;
6683
6684         default:
6685           gcc_unreachable ();
6686         }
6687     }
6688
6689   switch (code)
6690     {
6691     case EQ_EXPR:
6692       if (TREE_OVERFLOW (lo) && TREE_OVERFLOW (hi))
6693         return omit_one_operand_loc (loc, type, integer_zero_node, arg00);
6694       if (TREE_OVERFLOW (hi))
6695         return fold_build2_loc (loc, GE_EXPR, type, arg00, lo);
6696       if (TREE_OVERFLOW (lo))
6697         return fold_build2_loc (loc, LE_EXPR, type, arg00, hi);
6698       return build_range_check (loc, type, arg00, 1, lo, hi);
6699
6700     case NE_EXPR:
6701       if (TREE_OVERFLOW (lo) && TREE_OVERFLOW (hi))
6702         return omit_one_operand_loc (loc, type, integer_one_node, arg00);
6703       if (TREE_OVERFLOW (hi))
6704         return fold_build2_loc (loc, LT_EXPR, type, arg00, lo);
6705       if (TREE_OVERFLOW (lo))
6706         return fold_build2_loc (loc, GT_EXPR, type, arg00, hi);
6707       return build_range_check (loc, type, arg00, 0, lo, hi);
6708
6709     case LT_EXPR:
6710       if (TREE_OVERFLOW (lo))
6711         {
6712           tmp = neg_overflow ? integer_zero_node : integer_one_node;
6713           return omit_one_operand_loc (loc, type, tmp, arg00);
6714         }
6715       return fold_build2_loc (loc, LT_EXPR, type, arg00, lo);
6716
6717     case LE_EXPR:
6718       if (TREE_OVERFLOW (hi))
6719         {
6720           tmp = neg_overflow ? integer_zero_node : integer_one_node;
6721           return omit_one_operand_loc (loc, type, tmp, arg00);
6722         }
6723       return fold_build2_loc (loc, LE_EXPR, type, arg00, hi);
6724
6725     case GT_EXPR:
6726       if (TREE_OVERFLOW (hi))
6727         {
6728           tmp = neg_overflow ? integer_one_node : integer_zero_node;
6729           return omit_one_operand_loc (loc, type, tmp, arg00);
6730         }
6731       return fold_build2_loc (loc, GT_EXPR, type, arg00, hi);
6732
6733     case GE_EXPR:
6734       if (TREE_OVERFLOW (lo))
6735         {
6736           tmp = neg_overflow ? integer_one_node : integer_zero_node;
6737           return omit_one_operand_loc (loc, type, tmp, arg00);
6738         }
6739       return fold_build2_loc (loc, GE_EXPR, type, arg00, lo);
6740
6741     default:
6742       break;
6743     }
6744
6745   return NULL_TREE;
6746 }
6747
6748
6749 /* If CODE with arguments ARG0 and ARG1 represents a single bit
6750    equality/inequality test, then return a simplified form of the test
6751    using a sign testing.  Otherwise return NULL.  TYPE is the desired
6752    result type.  */
6753
6754 static tree
6755 fold_single_bit_test_into_sign_test (location_t loc,
6756                                      enum tree_code code, tree arg0, tree arg1,
6757                                      tree result_type)
6758 {
6759   /* If this is testing a single bit, we can optimize the test.  */
6760   if ((code == NE_EXPR || code == EQ_EXPR)
6761       && TREE_CODE (arg0) == BIT_AND_EXPR && integer_zerop (arg1)
6762       && integer_pow2p (TREE_OPERAND (arg0, 1)))
6763     {
6764       /* If we have (A & C) != 0 where C is the sign bit of A, convert
6765          this into A < 0.  Similarly for (A & C) == 0 into A >= 0.  */
6766       tree arg00 = sign_bit_p (TREE_OPERAND (arg0, 0), TREE_OPERAND (arg0, 1));
6767
6768       if (arg00 != NULL_TREE
6769           /* This is only a win if casting to a signed type is cheap,
6770              i.e. when arg00's type is not a partial mode.  */
6771           && TYPE_PRECISION (TREE_TYPE (arg00))
6772              == GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (arg00))))
6773         {
6774           tree stype = signed_type_for (TREE_TYPE (arg00));
6775           return fold_build2_loc (loc, code == EQ_EXPR ? GE_EXPR : LT_EXPR,
6776                               result_type,
6777                               fold_convert_loc (loc, stype, arg00),
6778                               build_int_cst (stype, 0));
6779         }
6780     }
6781
6782   return NULL_TREE;
6783 }
6784
6785 /* If CODE with arguments ARG0 and ARG1 represents a single bit
6786    equality/inequality test, then return a simplified form of
6787    the test using shifts and logical operations.  Otherwise return
6788    NULL.  TYPE is the desired result type.  */
6789
6790 tree
6791 fold_single_bit_test (location_t loc, enum tree_code code,
6792                       tree arg0, tree arg1, tree result_type)
6793 {
6794   /* If this is testing a single bit, we can optimize the test.  */
6795   if ((code == NE_EXPR || code == EQ_EXPR)
6796       && TREE_CODE (arg0) == BIT_AND_EXPR && integer_zerop (arg1)
6797       && integer_pow2p (TREE_OPERAND (arg0, 1)))
6798     {
6799       tree inner = TREE_OPERAND (arg0, 0);
6800       tree type = TREE_TYPE (arg0);
6801       int bitnum = tree_log2 (TREE_OPERAND (arg0, 1));
6802       machine_mode operand_mode = TYPE_MODE (type);
6803       int ops_unsigned;
6804       tree signed_type, unsigned_type, intermediate_type;
6805       tree tem, one;
6806
6807       /* First, see if we can fold the single bit test into a sign-bit
6808          test.  */
6809       tem = fold_single_bit_test_into_sign_test (loc, code, arg0, arg1,
6810                                                  result_type);
6811       if (tem)
6812         return tem;
6813
6814       /* Otherwise we have (A & C) != 0 where C is a single bit,
6815          convert that into ((A >> C2) & 1).  Where C2 = log2(C).
6816          Similarly for (A & C) == 0.  */
6817
6818       /* If INNER is a right shift of a constant and it plus BITNUM does
6819          not overflow, adjust BITNUM and INNER.  */
6820       if (TREE_CODE (inner) == RSHIFT_EXPR
6821           && TREE_CODE (TREE_OPERAND (inner, 1)) == INTEGER_CST
6822           && bitnum < TYPE_PRECISION (type)
6823           && wi::ltu_p (TREE_OPERAND (inner, 1),
6824                         TYPE_PRECISION (type) - bitnum))
6825         {
6826           bitnum += tree_to_uhwi (TREE_OPERAND (inner, 1));
6827           inner = TREE_OPERAND (inner, 0);
6828         }
6829
6830       /* If we are going to be able to omit the AND below, we must do our
6831          operations as unsigned.  If we must use the AND, we have a choice.
6832          Normally unsigned is faster, but for some machines signed is.  */
6833       ops_unsigned = (LOAD_EXTEND_OP (operand_mode) == SIGN_EXTEND
6834                       && !flag_syntax_only) ? 0 : 1;
6835
6836       signed_type = lang_hooks.types.type_for_mode (operand_mode, 0);
6837       unsigned_type = lang_hooks.types.type_for_mode (operand_mode, 1);
6838       intermediate_type = ops_unsigned ? unsigned_type : signed_type;
6839       inner = fold_convert_loc (loc, intermediate_type, inner);
6840
6841       if (bitnum != 0)
6842         inner = build2 (RSHIFT_EXPR, intermediate_type,
6843                         inner, size_int (bitnum));
6844
6845       one = build_int_cst (intermediate_type, 1);
6846
6847       if (code == EQ_EXPR)
6848         inner = fold_build2_loc (loc, BIT_XOR_EXPR, intermediate_type, inner, one);
6849
6850       /* Put the AND last so it can combine with more things.  */
6851       inner = build2 (BIT_AND_EXPR, intermediate_type, inner, one);
6852
6853       /* Make sure to return the proper type.  */
6854       inner = fold_convert_loc (loc, result_type, inner);
6855
6856       return inner;
6857     }
6858   return NULL_TREE;
6859 }
6860
6861 /* Check whether we are allowed to reorder operands arg0 and arg1,
6862    such that the evaluation of arg1 occurs before arg0.  */
6863
6864 static bool
6865 reorder_operands_p (const_tree arg0, const_tree arg1)
6866 {
6867   if (! flag_evaluation_order)
6868       return true;
6869   if (TREE_CONSTANT (arg0) || TREE_CONSTANT (arg1))
6870     return true;
6871   return ! TREE_SIDE_EFFECTS (arg0)
6872          && ! TREE_SIDE_EFFECTS (arg1);
6873 }
6874
6875 /* Test whether it is preferable two swap two operands, ARG0 and
6876    ARG1, for example because ARG0 is an integer constant and ARG1
6877    isn't.  If REORDER is true, only recommend swapping if we can
6878    evaluate the operands in reverse order.  */
6879
6880 bool
6881 tree_swap_operands_p (const_tree arg0, const_tree arg1, bool reorder)
6882 {
6883   if (CONSTANT_CLASS_P (arg1))
6884     return 0;
6885   if (CONSTANT_CLASS_P (arg0))
6886     return 1;
6887
6888   STRIP_NOPS (arg0);
6889   STRIP_NOPS (arg1);
6890
6891   if (TREE_CONSTANT (arg1))
6892     return 0;
6893   if (TREE_CONSTANT (arg0))
6894     return 1;
6895
6896   if (reorder && flag_evaluation_order
6897       && (TREE_SIDE_EFFECTS (arg0) || TREE_SIDE_EFFECTS (arg1)))
6898     return 0;
6899
6900   /* It is preferable to swap two SSA_NAME to ensure a canonical form
6901      for commutative and comparison operators.  Ensuring a canonical
6902      form allows the optimizers to find additional redundancies without
6903      having to explicitly check for both orderings.  */
6904   if (TREE_CODE (arg0) == SSA_NAME
6905       && TREE_CODE (arg1) == SSA_NAME
6906       && SSA_NAME_VERSION (arg0) > SSA_NAME_VERSION (arg1))
6907     return 1;
6908
6909   /* Put SSA_NAMEs last.  */
6910   if (TREE_CODE (arg1) == SSA_NAME)
6911     return 0;
6912   if (TREE_CODE (arg0) == SSA_NAME)
6913     return 1;
6914
6915   /* Put variables last.  */
6916   if (DECL_P (arg1))
6917     return 0;
6918   if (DECL_P (arg0))
6919     return 1;
6920
6921   return 0;
6922 }
6923
6924
6925 /* Fold A < X && A + 1 > Y to A < X && A >= Y.  Normally A + 1 > Y
6926    means A >= Y && A != MAX, but in this case we know that
6927    A < X <= MAX.  INEQ is A + 1 > Y, BOUND is A < X.  */
6928
6929 static tree
6930 fold_to_nonsharp_ineq_using_bound (location_t loc, tree ineq, tree bound)
6931 {
6932   tree a, typea, type = TREE_TYPE (ineq), a1, diff, y;
6933
6934   if (TREE_CODE (bound) == LT_EXPR)
6935     a = TREE_OPERAND (bound, 0);
6936   else if (TREE_CODE (bound) == GT_EXPR)
6937     a = TREE_OPERAND (bound, 1);
6938   else
6939     return NULL_TREE;
6940
6941   typea = TREE_TYPE (a);
6942   if (!INTEGRAL_TYPE_P (typea)
6943       && !POINTER_TYPE_P (typea))
6944     return NULL_TREE;
6945
6946   if (TREE_CODE (ineq) == LT_EXPR)
6947     {
6948       a1 = TREE_OPERAND (ineq, 1);
6949       y = TREE_OPERAND (ineq, 0);
6950     }
6951   else if (TREE_CODE (ineq) == GT_EXPR)
6952     {
6953       a1 = TREE_OPERAND (ineq, 0);
6954       y = TREE_OPERAND (ineq, 1);
6955     }
6956   else
6957     return NULL_TREE;
6958
6959   if (TREE_TYPE (a1) != typea)
6960     return NULL_TREE;
6961
6962   if (POINTER_TYPE_P (typea))
6963     {
6964       /* Convert the pointer types into integer before taking the difference.  */
6965       tree ta = fold_convert_loc (loc, ssizetype, a);
6966       tree ta1 = fold_convert_loc (loc, ssizetype, a1);
6967       diff = fold_binary_loc (loc, MINUS_EXPR, ssizetype, ta1, ta);
6968     }
6969   else
6970     diff = fold_binary_loc (loc, MINUS_EXPR, typea, a1, a);
6971
6972   if (!diff || !integer_onep (diff))
6973    return NULL_TREE;
6974
6975   return fold_build2_loc (loc, GE_EXPR, type, a, y);
6976 }
6977
6978 /* Fold a sum or difference of at least one multiplication.
6979    Returns the folded tree or NULL if no simplification could be made.  */
6980
6981 static tree
6982 fold_plusminus_mult_expr (location_t loc, enum tree_code code, tree type,
6983                           tree arg0, tree arg1)
6984 {
6985   tree arg00, arg01, arg10, arg11;
6986   tree alt0 = NULL_TREE, alt1 = NULL_TREE, same;
6987
6988   /* (A * C) +- (B * C) -> (A+-B) * C.
6989      (A * C) +- A -> A * (C+-1).
6990      We are most concerned about the case where C is a constant,
6991      but other combinations show up during loop reduction.  Since
6992      it is not difficult, try all four possibilities.  */
6993
6994   if (TREE_CODE (arg0) == MULT_EXPR)
6995     {
6996       arg00 = TREE_OPERAND (arg0, 0);
6997       arg01 = TREE_OPERAND (arg0, 1);
6998     }
6999   else if (TREE_CODE (arg0) == INTEGER_CST)
7000     {
7001       arg00 = build_one_cst (type);
7002       arg01 = arg0;
7003     }
7004   else
7005     {
7006       /* We cannot generate constant 1 for fract.  */
7007       if (ALL_FRACT_MODE_P (TYPE_MODE (type)))
7008         return NULL_TREE;
7009       arg00 = arg0;
7010       arg01 = build_one_cst (type);
7011     }
7012   if (TREE_CODE (arg1) == MULT_EXPR)
7013     {
7014       arg10 = TREE_OPERAND (arg1, 0);
7015       arg11 = TREE_OPERAND (arg1, 1);
7016     }
7017   else if (TREE_CODE (arg1) == INTEGER_CST)
7018     {
7019       arg10 = build_one_cst (type);
7020       /* As we canonicalize A - 2 to A + -2 get rid of that sign for
7021          the purpose of this canonicalization.  */
7022       if (wi::neg_p (arg1, TYPE_SIGN (TREE_TYPE (arg1)))
7023           && negate_expr_p (arg1)
7024           && code == PLUS_EXPR)
7025         {
7026           arg11 = negate_expr (arg1);
7027           code = MINUS_EXPR;
7028         }
7029       else
7030         arg11 = arg1;
7031     }
7032   else
7033     {
7034       /* We cannot generate constant 1 for fract.  */
7035       if (ALL_FRACT_MODE_P (TYPE_MODE (type)))
7036         return NULL_TREE;
7037       arg10 = arg1;
7038       arg11 = build_one_cst (type);
7039     }
7040   same = NULL_TREE;
7041
7042   if (operand_equal_p (arg01, arg11, 0))
7043     same = arg01, alt0 = arg00, alt1 = arg10;
7044   else if (operand_equal_p (arg00, arg10, 0))
7045     same = arg00, alt0 = arg01, alt1 = arg11;
7046   else if (operand_equal_p (arg00, arg11, 0))
7047     same = arg00, alt0 = arg01, alt1 = arg10;
7048   else if (operand_equal_p (arg01, arg10, 0))
7049     same = arg01, alt0 = arg00, alt1 = arg11;
7050
7051   /* No identical multiplicands; see if we can find a common
7052      power-of-two factor in non-power-of-two multiplies.  This
7053      can help in multi-dimensional array access.  */
7054   else if (tree_fits_shwi_p (arg01)
7055            && tree_fits_shwi_p (arg11))
7056     {
7057       HOST_WIDE_INT int01, int11, tmp;
7058       bool swap = false;
7059       tree maybe_same;
7060       int01 = tree_to_shwi (arg01);
7061       int11 = tree_to_shwi (arg11);
7062
7063       /* Move min of absolute values to int11.  */
7064       if (absu_hwi (int01) < absu_hwi (int11))
7065         {
7066           tmp = int01, int01 = int11, int11 = tmp;
7067           alt0 = arg00, arg00 = arg10, arg10 = alt0;
7068           maybe_same = arg01;
7069           swap = true;
7070         }
7071       else
7072         maybe_same = arg11;
7073
7074       if (exact_log2 (absu_hwi (int11)) > 0 && int01 % int11 == 0
7075           /* The remainder should not be a constant, otherwise we
7076              end up folding i * 4 + 2 to (i * 2 + 1) * 2 which has
7077              increased the number of multiplications necessary.  */
7078           && TREE_CODE (arg10) != INTEGER_CST)
7079         {
7080           alt0 = fold_build2_loc (loc, MULT_EXPR, TREE_TYPE (arg00), arg00,
7081                               build_int_cst (TREE_TYPE (arg00),
7082                                              int01 / int11));
7083           alt1 = arg10;
7084           same = maybe_same;
7085           if (swap)
7086             maybe_same = alt0, alt0 = alt1, alt1 = maybe_same;
7087         }
7088     }
7089
7090   if (same)
7091     return fold_build2_loc (loc, MULT_EXPR, type,
7092                         fold_build2_loc (loc, code, type,
7093                                      fold_convert_loc (loc, type, alt0),
7094                                      fold_convert_loc (loc, type, alt1)),
7095                         fold_convert_loc (loc, type, same));
7096
7097   return NULL_TREE;
7098 }
7099
7100 /* Subroutine of native_encode_expr.  Encode the INTEGER_CST
7101    specified by EXPR into the buffer PTR of length LEN bytes.
7102    Return the number of bytes placed in the buffer, or zero
7103    upon failure.  */
7104
7105 static int
7106 native_encode_int (const_tree expr, unsigned char *ptr, int len, int off)
7107 {
7108   tree type = TREE_TYPE (expr);
7109   int total_bytes = GET_MODE_SIZE (TYPE_MODE (type));
7110   int byte, offset, word, words;
7111   unsigned char value;
7112
7113   if ((off == -1 && total_bytes > len)
7114       || off >= total_bytes)
7115     return 0;
7116   if (off == -1)
7117     off = 0;
7118   words = total_bytes / UNITS_PER_WORD;
7119
7120   for (byte = 0; byte < total_bytes; byte++)
7121     {
7122       int bitpos = byte * BITS_PER_UNIT;
7123       /* Extend EXPR according to TYPE_SIGN if the precision isn't a whole
7124          number of bytes.  */
7125       value = wi::extract_uhwi (wi::to_widest (expr), bitpos, BITS_PER_UNIT);
7126
7127       if (total_bytes > UNITS_PER_WORD)
7128         {
7129           word = byte / UNITS_PER_WORD;
7130           if (WORDS_BIG_ENDIAN)
7131             word = (words - 1) - word;
7132           offset = word * UNITS_PER_WORD;
7133           if (BYTES_BIG_ENDIAN)
7134             offset += (UNITS_PER_WORD - 1) - (byte % UNITS_PER_WORD);
7135           else
7136             offset += byte % UNITS_PER_WORD;
7137         }
7138       else
7139         offset = BYTES_BIG_ENDIAN ? (total_bytes - 1) - byte : byte;
7140       if (offset >= off
7141           && offset - off < len)
7142         ptr[offset - off] = value;
7143     }
7144   return MIN (len, total_bytes - off);
7145 }
7146
7147
7148 /* Subroutine of native_encode_expr.  Encode the FIXED_CST
7149    specified by EXPR into the buffer PTR of length LEN bytes.
7150    Return the number of bytes placed in the buffer, or zero
7151    upon failure.  */
7152
7153 static int
7154 native_encode_fixed (const_tree expr, unsigned char *ptr, int len, int off)
7155 {
7156   tree type = TREE_TYPE (expr);
7157   machine_mode mode = TYPE_MODE (type);
7158   int total_bytes = GET_MODE_SIZE (mode);
7159   FIXED_VALUE_TYPE value;
7160   tree i_value, i_type;
7161
7162   if (total_bytes * BITS_PER_UNIT > HOST_BITS_PER_DOUBLE_INT)
7163     return 0;
7164
7165   i_type = lang_hooks.types.type_for_size (GET_MODE_BITSIZE (mode), 1);
7166
7167   if (NULL_TREE == i_type
7168       || TYPE_PRECISION (i_type) != total_bytes)
7169     return 0;
7170
7171   value = TREE_FIXED_CST (expr);
7172   i_value = double_int_to_tree (i_type, value.data);
7173
7174   return native_encode_int (i_value, ptr, len, off);
7175 }
7176
7177
7178 /* Subroutine of native_encode_expr.  Encode the REAL_CST
7179    specified by EXPR into the buffer PTR of length LEN bytes.
7180    Return the number of bytes placed in the buffer, or zero
7181    upon failure.  */
7182
7183 static int
7184 native_encode_real (const_tree expr, unsigned char *ptr, int len, int off)
7185 {
7186   tree type = TREE_TYPE (expr);
7187   int total_bytes = GET_MODE_SIZE (TYPE_MODE (type));
7188   int byte, offset, word, words, bitpos;
7189   unsigned char value;
7190
7191   /* There are always 32 bits in each long, no matter the size of
7192      the hosts long.  We handle floating point representations with
7193      up to 192 bits.  */
7194   long tmp[6];
7195
7196   if ((off == -1 && total_bytes > len)
7197       || off >= total_bytes)
7198     return 0;
7199   if (off == -1)
7200     off = 0;
7201   words = (32 / BITS_PER_UNIT) / UNITS_PER_WORD;
7202
7203   real_to_target (tmp, TREE_REAL_CST_PTR (expr), TYPE_MODE (type));
7204
7205   for (bitpos = 0; bitpos < total_bytes * BITS_PER_UNIT;
7206        bitpos += BITS_PER_UNIT)
7207     {
7208       byte = (bitpos / BITS_PER_UNIT) & 3;
7209       value = (unsigned char) (tmp[bitpos / 32] >> (bitpos & 31));
7210
7211       if (UNITS_PER_WORD < 4)
7212         {
7213           word = byte / UNITS_PER_WORD;
7214           if (WORDS_BIG_ENDIAN)
7215             word = (words - 1) - word;
7216           offset = word * UNITS_PER_WORD;
7217           if (BYTES_BIG_ENDIAN)
7218             offset += (UNITS_PER_WORD - 1) - (byte % UNITS_PER_WORD);
7219           else
7220             offset += byte % UNITS_PER_WORD;
7221         }
7222       else
7223         {
7224           offset = byte;
7225           if (BYTES_BIG_ENDIAN)
7226             {
7227               /* Reverse bytes within each long, or within the entire float
7228                  if it's smaller than a long (for HFmode).  */
7229               offset = MIN (3, total_bytes - 1) - offset;
7230               gcc_assert (offset >= 0);
7231             }
7232         }
7233       offset = offset + ((bitpos / BITS_PER_UNIT) & ~3);
7234       if (offset >= off
7235           && offset - off < len)
7236         ptr[offset - off] = value;
7237     }
7238   return MIN (len, total_bytes - off);
7239 }
7240
7241 /* Subroutine of native_encode_expr.  Encode the COMPLEX_CST
7242    specified by EXPR into the buffer PTR of length LEN bytes.
7243    Return the number of bytes placed in the buffer, or zero
7244    upon failure.  */
7245
7246 static int
7247 native_encode_complex (const_tree expr, unsigned char *ptr, int len, int off)
7248 {
7249   int rsize, isize;
7250   tree part;
7251
7252   part = TREE_REALPART (expr);
7253   rsize = native_encode_expr (part, ptr, len, off);
7254   if (off == -1
7255       && rsize == 0)
7256     return 0;
7257   part = TREE_IMAGPART (expr);
7258   if (off != -1)
7259     off = MAX (0, off - GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (part))));
7260   isize = native_encode_expr (part, ptr+rsize, len-rsize, off);
7261   if (off == -1
7262       && isize != rsize)
7263     return 0;
7264   return rsize + isize;
7265 }
7266
7267
7268 /* Subroutine of native_encode_expr.  Encode the VECTOR_CST
7269    specified by EXPR into the buffer PTR of length LEN bytes.
7270    Return the number of bytes placed in the buffer, or zero
7271    upon failure.  */
7272
7273 static int
7274 native_encode_vector (const_tree expr, unsigned char *ptr, int len, int off)
7275 {
7276   unsigned i, count;
7277   int size, offset;
7278   tree itype, elem;
7279
7280   offset = 0;
7281   count = VECTOR_CST_NELTS (expr);
7282   itype = TREE_TYPE (TREE_TYPE (expr));
7283   size = GET_MODE_SIZE (TYPE_MODE (itype));
7284   for (i = 0; i < count; i++)
7285     {
7286       if (off >= size)
7287         {
7288           off -= size;
7289           continue;
7290         }
7291       elem = VECTOR_CST_ELT (expr, i);
7292       int res = native_encode_expr (elem, ptr+offset, len-offset, off);
7293       if ((off == -1 && res != size)
7294           || res == 0)
7295         return 0;
7296       offset += res;
7297       if (offset >= len)
7298         return offset;
7299       if (off != -1)
7300         off = 0;
7301     }
7302   return offset;
7303 }
7304
7305
7306 /* Subroutine of native_encode_expr.  Encode the STRING_CST
7307    specified by EXPR into the buffer PTR of length LEN bytes.
7308    Return the number of bytes placed in the buffer, or zero
7309    upon failure.  */
7310
7311 static int
7312 native_encode_string (const_tree expr, unsigned char *ptr, int len, int off)
7313 {
7314   tree type = TREE_TYPE (expr);
7315   HOST_WIDE_INT total_bytes;
7316
7317   if (TREE_CODE (type) != ARRAY_TYPE
7318       || TREE_CODE (TREE_TYPE (type)) != INTEGER_TYPE
7319       || GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE (type))) != BITS_PER_UNIT
7320       || !tree_fits_shwi_p (TYPE_SIZE_UNIT (type)))
7321     return 0;
7322   total_bytes = tree_to_shwi (TYPE_SIZE_UNIT (type));
7323   if ((off == -1 && total_bytes > len)
7324       || off >= total_bytes)
7325     return 0;
7326   if (off == -1)
7327     off = 0;
7328   if (TREE_STRING_LENGTH (expr) - off < MIN (total_bytes, len))
7329     {
7330       int written = 0;
7331       if (off < TREE_STRING_LENGTH (expr))
7332         {
7333           written = MIN (len, TREE_STRING_LENGTH (expr) - off);
7334           memcpy (ptr, TREE_STRING_POINTER (expr) + off, written);
7335         }
7336       memset (ptr + written, 0,
7337               MIN (total_bytes - written, len - written));
7338     }
7339   else
7340     memcpy (ptr, TREE_STRING_POINTER (expr) + off, MIN (total_bytes, len));
7341   return MIN (total_bytes - off, len);
7342 }
7343
7344
7345 /* Subroutine of fold_view_convert_expr.  Encode the INTEGER_CST,
7346    REAL_CST, COMPLEX_CST or VECTOR_CST specified by EXPR into the
7347    buffer PTR of length LEN bytes.  If OFF is not -1 then start
7348    the encoding at byte offset OFF and encode at most LEN bytes.
7349    Return the number of bytes placed in the buffer, or zero upon failure.  */
7350
7351 int
7352 native_encode_expr (const_tree expr, unsigned char *ptr, int len, int off)
7353 {
7354   /* We don't support starting at negative offset and -1 is special.  */
7355   if (off < -1)
7356     return 0;
7357
7358   switch (TREE_CODE (expr))
7359     {
7360     case INTEGER_CST:
7361       return native_encode_int (expr, ptr, len, off);
7362
7363     case REAL_CST:
7364       return native_encode_real (expr, ptr, len, off);
7365
7366     case FIXED_CST:
7367       return native_encode_fixed (expr, ptr, len, off);
7368
7369     case COMPLEX_CST:
7370       return native_encode_complex (expr, ptr, len, off);
7371
7372     case VECTOR_CST:
7373       return native_encode_vector (expr, ptr, len, off);
7374
7375     case STRING_CST:
7376       return native_encode_string (expr, ptr, len, off);
7377
7378     default:
7379       return 0;
7380     }
7381 }
7382
7383
7384 /* Subroutine of native_interpret_expr.  Interpret the contents of
7385    the buffer PTR of length LEN as an INTEGER_CST of type TYPE.
7386    If the buffer cannot be interpreted, return NULL_TREE.  */
7387
7388 static tree
7389 native_interpret_int (tree type, const unsigned char *ptr, int len)
7390 {
7391   int total_bytes = GET_MODE_SIZE (TYPE_MODE (type));
7392
7393   if (total_bytes > len
7394       || total_bytes * BITS_PER_UNIT > HOST_BITS_PER_DOUBLE_INT)
7395     return NULL_TREE;
7396
7397   wide_int result = wi::from_buffer (ptr, total_bytes);
7398
7399   return wide_int_to_tree (type, result);
7400 }
7401
7402
7403 /* Subroutine of native_interpret_expr.  Interpret the contents of
7404    the buffer PTR of length LEN as a FIXED_CST of type TYPE.
7405    If the buffer cannot be interpreted, return NULL_TREE.  */
7406
7407 static tree
7408 native_interpret_fixed (tree type, const unsigned char *ptr, int len)
7409 {
7410   int total_bytes = GET_MODE_SIZE (TYPE_MODE (type));
7411   double_int result;
7412   FIXED_VALUE_TYPE fixed_value;
7413
7414   if (total_bytes > len
7415       || total_bytes * BITS_PER_UNIT > HOST_BITS_PER_DOUBLE_INT)
7416     return NULL_TREE;
7417
7418   result = double_int::from_buffer (ptr, total_bytes);
7419   fixed_value = fixed_from_double_int (result, TYPE_MODE (type));
7420
7421   return build_fixed (type, fixed_value);
7422 }
7423
7424
7425 /* Subroutine of native_interpret_expr.  Interpret the contents of
7426    the buffer PTR of length LEN as a REAL_CST of type TYPE.
7427    If the buffer cannot be interpreted, return NULL_TREE.  */
7428
7429 static tree
7430 native_interpret_real (tree type, const unsigned char *ptr, int len)
7431 {
7432   machine_mode mode = TYPE_MODE (type);
7433   int total_bytes = GET_MODE_SIZE (mode);
7434   unsigned char value;
7435   /* There are always 32 bits in each long, no matter the size of
7436      the hosts long.  We handle floating point representations with
7437      up to 192 bits.  */
7438   REAL_VALUE_TYPE r;
7439   long tmp[6];
7440
7441   total_bytes = GET_MODE_SIZE (TYPE_MODE (type));
7442   if (total_bytes > len || total_bytes > 24)
7443     return NULL_TREE;
7444   int words = (32 / BITS_PER_UNIT) / UNITS_PER_WORD;
7445
7446   memset (tmp, 0, sizeof (tmp));
7447   for (int bitpos = 0; bitpos < total_bytes * BITS_PER_UNIT;
7448        bitpos += BITS_PER_UNIT)
7449     {
7450       /* Both OFFSET and BYTE index within a long;
7451          bitpos indexes the whole float.  */
7452       int offset, byte = (bitpos / BITS_PER_UNIT) & 3;
7453       if (UNITS_PER_WORD < 4)
7454         {
7455           int word = byte / UNITS_PER_WORD;
7456           if (WORDS_BIG_ENDIAN)
7457             word = (words - 1) - word;
7458           offset = word * UNITS_PER_WORD;
7459           if (BYTES_BIG_ENDIAN)
7460             offset += (UNITS_PER_WORD - 1) - (byte % UNITS_PER_WORD);
7461           else
7462             offset += byte % UNITS_PER_WORD;
7463         }
7464       else
7465         {
7466           offset = byte;
7467           if (BYTES_BIG_ENDIAN)
7468             {
7469               /* Reverse bytes within each long, or within the entire float
7470                  if it's smaller than a long (for HFmode).  */
7471               offset = MIN (3, total_bytes - 1) - offset;
7472               gcc_assert (offset >= 0);
7473             }
7474         }
7475       value = ptr[offset + ((bitpos / BITS_PER_UNIT) & ~3)];
7476
7477       tmp[bitpos / 32] |= (unsigned long)value << (bitpos & 31);
7478     }
7479
7480   real_from_target (&r, tmp, mode);
7481   return build_real (type, r);
7482 }
7483
7484
7485 /* Subroutine of native_interpret_expr.  Interpret the contents of
7486    the buffer PTR of length LEN as a COMPLEX_CST of type TYPE.
7487    If the buffer cannot be interpreted, return NULL_TREE.  */
7488
7489 static tree
7490 native_interpret_complex (tree type, const unsigned char *ptr, int len)
7491 {
7492   tree etype, rpart, ipart;
7493   int size;
7494
7495   etype = TREE_TYPE (type);
7496   size = GET_MODE_SIZE (TYPE_MODE (etype));
7497   if (size * 2 > len)
7498     return NULL_TREE;
7499   rpart = native_interpret_expr (etype, ptr, size);
7500   if (!rpart)
7501     return NULL_TREE;
7502   ipart = native_interpret_expr (etype, ptr+size, size);
7503   if (!ipart)
7504     return NULL_TREE;
7505   return build_complex (type, rpart, ipart);
7506 }
7507
7508
7509 /* Subroutine of native_interpret_expr.  Interpret the contents of
7510    the buffer PTR of length LEN as a VECTOR_CST of type TYPE.
7511    If the buffer cannot be interpreted, return NULL_TREE.  */
7512
7513 static tree
7514 native_interpret_vector (tree type, const unsigned char *ptr, int len)
7515 {
7516   tree etype, elem;
7517   int i, size, count;
7518   tree *elements;
7519
7520   etype = TREE_TYPE (type);
7521   size = GET_MODE_SIZE (TYPE_MODE (etype));
7522   count = TYPE_VECTOR_SUBPARTS (type);
7523   if (size * count > len)
7524     return NULL_TREE;
7525
7526   elements = XALLOCAVEC (tree, count);
7527   for (i = count - 1; i >= 0; i--)
7528     {
7529       elem = native_interpret_expr (etype, ptr+(i*size), size);
7530       if (!elem)
7531         return NULL_TREE;
7532       elements[i] = elem;
7533     }
7534   return build_vector (type, elements);
7535 }
7536
7537
7538 /* Subroutine of fold_view_convert_expr.  Interpret the contents of
7539    the buffer PTR of length LEN as a constant of type TYPE.  For
7540    INTEGRAL_TYPE_P we return an INTEGER_CST, for SCALAR_FLOAT_TYPE_P
7541    we return a REAL_CST, etc...  If the buffer cannot be interpreted,
7542    return NULL_TREE.  */
7543
7544 tree
7545 native_interpret_expr (tree type, const unsigned char *ptr, int len)
7546 {
7547   switch (TREE_CODE (type))
7548     {
7549     case INTEGER_TYPE:
7550     case ENUMERAL_TYPE:
7551     case BOOLEAN_TYPE:
7552     case POINTER_TYPE:
7553     case REFERENCE_TYPE:
7554       return native_interpret_int (type, ptr, len);
7555
7556     case REAL_TYPE:
7557       return native_interpret_real (type, ptr, len);
7558
7559     case FIXED_POINT_TYPE:
7560       return native_interpret_fixed (type, ptr, len);
7561
7562     case COMPLEX_TYPE:
7563       return native_interpret_complex (type, ptr, len);
7564
7565     case VECTOR_TYPE:
7566       return native_interpret_vector (type, ptr, len);
7567
7568     default:
7569       return NULL_TREE;
7570     }
7571 }
7572
7573 /* Returns true if we can interpret the contents of a native encoding
7574    as TYPE.  */
7575
7576 static bool
7577 can_native_interpret_type_p (tree type)
7578 {
7579   switch (TREE_CODE (type))
7580     {
7581     case INTEGER_TYPE:
7582     case ENUMERAL_TYPE:
7583     case BOOLEAN_TYPE:
7584     case POINTER_TYPE:
7585     case REFERENCE_TYPE:
7586     case FIXED_POINT_TYPE:
7587     case REAL_TYPE:
7588     case COMPLEX_TYPE:
7589     case VECTOR_TYPE:
7590       return true;
7591     default:
7592       return false;
7593     }
7594 }
7595
7596 /* Fold a VIEW_CONVERT_EXPR of a constant expression EXPR to type
7597    TYPE at compile-time.  If we're unable to perform the conversion
7598    return NULL_TREE.  */
7599
7600 static tree
7601 fold_view_convert_expr (tree type, tree expr)
7602 {
7603   /* We support up to 512-bit values (for V8DFmode).  */
7604   unsigned char buffer[64];
7605   int len;
7606
7607   /* Check that the host and target are sane.  */
7608   if (CHAR_BIT != 8 || BITS_PER_UNIT != 8)
7609     return NULL_TREE;
7610
7611   len = native_encode_expr (expr, buffer, sizeof (buffer));
7612   if (len == 0)
7613     return NULL_TREE;
7614
7615   return native_interpret_expr (type, buffer, len);
7616 }
7617
7618 /* Build an expression for the address of T.  Folds away INDIRECT_REF
7619    to avoid confusing the gimplify process.  */
7620
7621 tree
7622 build_fold_addr_expr_with_type_loc (location_t loc, tree t, tree ptrtype)
7623 {
7624   /* The size of the object is not relevant when talking about its address.  */
7625   if (TREE_CODE (t) == WITH_SIZE_EXPR)
7626     t = TREE_OPERAND (t, 0);
7627
7628   if (TREE_CODE (t) == INDIRECT_REF)
7629     {
7630       t = TREE_OPERAND (t, 0);
7631
7632       if (TREE_TYPE (t) != ptrtype)
7633         t = build1_loc (loc, NOP_EXPR, ptrtype, t);
7634     }
7635   else if (TREE_CODE (t) == MEM_REF
7636            && integer_zerop (TREE_OPERAND (t, 1)))
7637     return TREE_OPERAND (t, 0);
7638   else if (TREE_CODE (t) == MEM_REF
7639            && TREE_CODE (TREE_OPERAND (t, 0)) == INTEGER_CST)
7640     return fold_binary (POINTER_PLUS_EXPR, ptrtype,
7641                         TREE_OPERAND (t, 0),
7642                         convert_to_ptrofftype (TREE_OPERAND (t, 1)));
7643   else if (TREE_CODE (t) == VIEW_CONVERT_EXPR)
7644     {
7645       t = build_fold_addr_expr_loc (loc, TREE_OPERAND (t, 0));
7646
7647       if (TREE_TYPE (t) != ptrtype)
7648         t = fold_convert_loc (loc, ptrtype, t);
7649     }
7650   else
7651     t = build1_loc (loc, ADDR_EXPR, ptrtype, t);
7652
7653   return t;
7654 }
7655
7656 /* Build an expression for the address of T.  */
7657
7658 tree
7659 build_fold_addr_expr_loc (location_t loc, tree t)
7660 {
7661   tree ptrtype = build_pointer_type (TREE_TYPE (t));
7662
7663   return build_fold_addr_expr_with_type_loc (loc, t, ptrtype);
7664 }
7665
7666 /* Fold a unary expression of code CODE and type TYPE with operand
7667    OP0.  Return the folded expression if folding is successful.
7668    Otherwise, return NULL_TREE.  */
7669
7670 tree
7671 fold_unary_loc (location_t loc, enum tree_code code, tree type, tree op0)
7672 {
7673   tree tem;
7674   tree arg0;
7675   enum tree_code_class kind = TREE_CODE_CLASS (code);
7676
7677   gcc_assert (IS_EXPR_CODE_CLASS (kind)
7678               && TREE_CODE_LENGTH (code) == 1);
7679
7680   arg0 = op0;
7681   if (arg0)
7682     {
7683       if (CONVERT_EXPR_CODE_P (code)
7684           || code == FLOAT_EXPR || code == ABS_EXPR || code == NEGATE_EXPR)
7685         {
7686           /* Don't use STRIP_NOPS, because signedness of argument type
7687              matters.  */
7688           STRIP_SIGN_NOPS (arg0);
7689         }
7690       else
7691         {
7692           /* Strip any conversions that don't change the mode.  This
7693              is safe for every expression, except for a comparison
7694              expression because its signedness is derived from its
7695              operands.
7696
7697              Note that this is done as an internal manipulation within
7698              the constant folder, in order to find the simplest
7699              representation of the arguments so that their form can be
7700              studied.  In any cases, the appropriate type conversions
7701              should be put back in the tree that will get out of the
7702              constant folder.  */
7703           STRIP_NOPS (arg0);
7704         }
7705
7706       if (CONSTANT_CLASS_P (arg0))
7707         {
7708           tree tem = const_unop (code, type, arg0);
7709           if (tem)
7710             {
7711               if (TREE_TYPE (tem) != type)
7712                 tem = fold_convert_loc (loc, type, tem);
7713               return tem;
7714             }
7715         }
7716     }
7717
7718   tem = generic_simplify (loc, code, type, op0);
7719   if (tem)
7720     return tem;
7721
7722   if (TREE_CODE_CLASS (code) == tcc_unary)
7723     {
7724       if (TREE_CODE (arg0) == COMPOUND_EXPR)
7725         return build2 (COMPOUND_EXPR, type, TREE_OPERAND (arg0, 0),
7726                        fold_build1_loc (loc, code, type,
7727                                     fold_convert_loc (loc, TREE_TYPE (op0),
7728                                                       TREE_OPERAND (arg0, 1))));
7729       else if (TREE_CODE (arg0) == COND_EXPR)
7730         {
7731           tree arg01 = TREE_OPERAND (arg0, 1);
7732           tree arg02 = TREE_OPERAND (arg0, 2);
7733           if (! VOID_TYPE_P (TREE_TYPE (arg01)))
7734             arg01 = fold_build1_loc (loc, code, type,
7735                                  fold_convert_loc (loc,
7736                                                    TREE_TYPE (op0), arg01));
7737           if (! VOID_TYPE_P (TREE_TYPE (arg02)))
7738             arg02 = fold_build1_loc (loc, code, type,
7739                                  fold_convert_loc (loc,
7740                                                    TREE_TYPE (op0), arg02));
7741           tem = fold_build3_loc (loc, COND_EXPR, type, TREE_OPERAND (arg0, 0),
7742                              arg01, arg02);
7743
7744           /* If this was a conversion, and all we did was to move into
7745              inside the COND_EXPR, bring it back out.  But leave it if
7746              it is a conversion from integer to integer and the
7747              result precision is no wider than a word since such a
7748              conversion is cheap and may be optimized away by combine,
7749              while it couldn't if it were outside the COND_EXPR.  Then return
7750              so we don't get into an infinite recursion loop taking the
7751              conversion out and then back in.  */
7752
7753           if ((CONVERT_EXPR_CODE_P (code)
7754                || code == NON_LVALUE_EXPR)
7755               && TREE_CODE (tem) == COND_EXPR
7756               && TREE_CODE (TREE_OPERAND (tem, 1)) == code
7757               && TREE_CODE (TREE_OPERAND (tem, 2)) == code
7758               && ! VOID_TYPE_P (TREE_OPERAND (tem, 1))
7759               && ! VOID_TYPE_P (TREE_OPERAND (tem, 2))
7760               && (TREE_TYPE (TREE_OPERAND (TREE_OPERAND (tem, 1), 0))
7761                   == TREE_TYPE (TREE_OPERAND (TREE_OPERAND (tem, 2), 0)))
7762               && (! (INTEGRAL_TYPE_P (TREE_TYPE (tem))
7763                      && (INTEGRAL_TYPE_P
7764                          (TREE_TYPE (TREE_OPERAND (TREE_OPERAND (tem, 1), 0))))
7765                      && TYPE_PRECISION (TREE_TYPE (tem)) <= BITS_PER_WORD)
7766                   || flag_syntax_only))
7767             tem = build1_loc (loc, code, type,
7768                               build3 (COND_EXPR,
7769                                       TREE_TYPE (TREE_OPERAND
7770                                                  (TREE_OPERAND (tem, 1), 0)),
7771                                       TREE_OPERAND (tem, 0),
7772                                       TREE_OPERAND (TREE_OPERAND (tem, 1), 0),
7773                                       TREE_OPERAND (TREE_OPERAND (tem, 2),
7774                                                     0)));
7775           return tem;
7776         }
7777    }
7778
7779   switch (code)
7780     {
7781     case NON_LVALUE_EXPR:
7782       if (!maybe_lvalue_p (op0))
7783         return fold_convert_loc (loc, type, op0);
7784       return NULL_TREE;
7785
7786     CASE_CONVERT:
7787     case FLOAT_EXPR:
7788     case FIX_TRUNC_EXPR:
7789       if (COMPARISON_CLASS_P (op0))
7790         {
7791           /* If we have (type) (a CMP b) and type is an integral type, return
7792              new expression involving the new type.  Canonicalize
7793              (type) (a CMP b) to (a CMP b) ? (type) true : (type) false for
7794              non-integral type.
7795              Do not fold the result as that would not simplify further, also
7796              folding again results in recursions.  */
7797           if (TREE_CODE (type) == BOOLEAN_TYPE)
7798             return build2_loc (loc, TREE_CODE (op0), type,
7799                                TREE_OPERAND (op0, 0),
7800                                TREE_OPERAND (op0, 1));
7801           else if (!INTEGRAL_TYPE_P (type) && !VOID_TYPE_P (type)
7802                    && TREE_CODE (type) != VECTOR_TYPE)
7803             return build3_loc (loc, COND_EXPR, type, op0,
7804                                constant_boolean_node (true, type),
7805                                constant_boolean_node (false, type));
7806         }
7807
7808       /* Handle (T *)&A.B.C for A being of type T and B and C
7809          living at offset zero.  This occurs frequently in
7810          C++ upcasting and then accessing the base.  */
7811       if (TREE_CODE (op0) == ADDR_EXPR
7812           && POINTER_TYPE_P (type)
7813           && handled_component_p (TREE_OPERAND (op0, 0)))
7814         {
7815           HOST_WIDE_INT bitsize, bitpos;
7816           tree offset;
7817           machine_mode mode;
7818           int unsignedp, reversep, volatilep;
7819           tree base
7820             = get_inner_reference (TREE_OPERAND (op0, 0), &bitsize, &bitpos,
7821                                    &offset, &mode, &unsignedp, &reversep,
7822                                    &volatilep, false);
7823           /* If the reference was to a (constant) zero offset, we can use
7824              the address of the base if it has the same base type
7825              as the result type and the pointer type is unqualified.  */
7826           if (! offset && bitpos == 0
7827               && (TYPE_MAIN_VARIANT (TREE_TYPE (type))
7828                   == TYPE_MAIN_VARIANT (TREE_TYPE (base)))
7829               && TYPE_QUALS (type) == TYPE_UNQUALIFIED)
7830             return fold_convert_loc (loc, type,
7831                                      build_fold_addr_expr_loc (loc, base));
7832         }
7833
7834       if (TREE_CODE (op0) == MODIFY_EXPR
7835           && TREE_CONSTANT (TREE_OPERAND (op0, 1))
7836           /* Detect assigning a bitfield.  */
7837           && !(TREE_CODE (TREE_OPERAND (op0, 0)) == COMPONENT_REF
7838                && DECL_BIT_FIELD
7839                (TREE_OPERAND (TREE_OPERAND (op0, 0), 1))))
7840         {
7841           /* Don't leave an assignment inside a conversion
7842              unless assigning a bitfield.  */
7843           tem = fold_build1_loc (loc, code, type, TREE_OPERAND (op0, 1));
7844           /* First do the assignment, then return converted constant.  */
7845           tem = build2_loc (loc, COMPOUND_EXPR, TREE_TYPE (tem), op0, tem);
7846           TREE_NO_WARNING (tem) = 1;
7847           TREE_USED (tem) = 1;
7848           return tem;
7849         }
7850
7851       /* Convert (T)(x & c) into (T)x & (T)c, if c is an integer
7852          constants (if x has signed type, the sign bit cannot be set
7853          in c).  This folds extension into the BIT_AND_EXPR.
7854          ??? We don't do it for BOOLEAN_TYPE or ENUMERAL_TYPE because they
7855          very likely don't have maximal range for their precision and this
7856          transformation effectively doesn't preserve non-maximal ranges.  */
7857       if (TREE_CODE (type) == INTEGER_TYPE
7858           && TREE_CODE (op0) == BIT_AND_EXPR
7859           && TREE_CODE (TREE_OPERAND (op0, 1)) == INTEGER_CST)
7860         {
7861           tree and_expr = op0;
7862           tree and0 = TREE_OPERAND (and_expr, 0);
7863           tree and1 = TREE_OPERAND (and_expr, 1);
7864           int change = 0;
7865
7866           if (TYPE_UNSIGNED (TREE_TYPE (and_expr))
7867               || (TYPE_PRECISION (type)
7868                   <= TYPE_PRECISION (TREE_TYPE (and_expr))))
7869             change = 1;
7870           else if (TYPE_PRECISION (TREE_TYPE (and1))
7871                    <= HOST_BITS_PER_WIDE_INT
7872                    && tree_fits_uhwi_p (and1))
7873             {
7874               unsigned HOST_WIDE_INT cst;
7875
7876               cst = tree_to_uhwi (and1);
7877               cst &= HOST_WIDE_INT_M1U
7878                      << (TYPE_PRECISION (TREE_TYPE (and1)) - 1);
7879               change = (cst == 0);
7880               if (change
7881                   && !flag_syntax_only
7882                   && (LOAD_EXTEND_OP (TYPE_MODE (TREE_TYPE (and0)))
7883                       == ZERO_EXTEND))
7884                 {
7885                   tree uns = unsigned_type_for (TREE_TYPE (and0));
7886                   and0 = fold_convert_loc (loc, uns, and0);
7887                   and1 = fold_convert_loc (loc, uns, and1);
7888                 }
7889             }
7890           if (change)
7891             {
7892               tem = force_fit_type (type, wi::to_widest (and1), 0,
7893                                     TREE_OVERFLOW (and1));
7894               return fold_build2_loc (loc, BIT_AND_EXPR, type,
7895                                       fold_convert_loc (loc, type, and0), tem);
7896             }
7897         }
7898
7899       /* Convert (T1)(X p+ Y) into ((T1)X p+ Y), for pointer type, when the new
7900          cast (T1)X will fold away.  We assume that this happens when X itself
7901          is a cast.  */
7902       if (POINTER_TYPE_P (type)
7903           && TREE_CODE (arg0) == POINTER_PLUS_EXPR
7904           && CONVERT_EXPR_P (TREE_OPERAND (arg0, 0)))
7905         {
7906           tree arg00 = TREE_OPERAND (arg0, 0);
7907           tree arg01 = TREE_OPERAND (arg0, 1);
7908
7909           return fold_build_pointer_plus_loc
7910                    (loc, fold_convert_loc (loc, type, arg00), arg01);
7911         }
7912
7913       /* Convert (T1)(~(T2)X) into ~(T1)X if T1 and T2 are integral types
7914          of the same precision, and X is an integer type not narrower than
7915          types T1 or T2, i.e. the cast (T2)X isn't an extension.  */
7916       if (INTEGRAL_TYPE_P (type)
7917           && TREE_CODE (op0) == BIT_NOT_EXPR
7918           && INTEGRAL_TYPE_P (TREE_TYPE (op0))
7919           && CONVERT_EXPR_P (TREE_OPERAND (op0, 0))
7920           && TYPE_PRECISION (type) == TYPE_PRECISION (TREE_TYPE (op0)))
7921         {
7922           tem = TREE_OPERAND (TREE_OPERAND (op0, 0), 0);
7923           if (INTEGRAL_TYPE_P (TREE_TYPE (tem))
7924               && TYPE_PRECISION (type) <= TYPE_PRECISION (TREE_TYPE (tem)))
7925             return fold_build1_loc (loc, BIT_NOT_EXPR, type,
7926                                 fold_convert_loc (loc, type, tem));
7927         }
7928
7929       /* Convert (T1)(X * Y) into (T1)X * (T1)Y if T1 is narrower than the
7930          type of X and Y (integer types only).  */
7931       if (INTEGRAL_TYPE_P (type)
7932           && TREE_CODE (op0) == MULT_EXPR
7933           && INTEGRAL_TYPE_P (TREE_TYPE (op0))
7934           && TYPE_PRECISION (type) < TYPE_PRECISION (TREE_TYPE (op0)))
7935         {
7936           /* Be careful not to introduce new overflows.  */
7937           tree mult_type;
7938           if (TYPE_OVERFLOW_WRAPS (type))
7939             mult_type = type;
7940           else
7941             mult_type = unsigned_type_for (type);
7942
7943           if (TYPE_PRECISION (mult_type) < TYPE_PRECISION (TREE_TYPE (op0)))
7944             {
7945               tem = fold_build2_loc (loc, MULT_EXPR, mult_type,
7946                                  fold_convert_loc (loc, mult_type,
7947                                                    TREE_OPERAND (op0, 0)),
7948                                  fold_convert_loc (loc, mult_type,
7949                                                    TREE_OPERAND (op0, 1)));
7950               return fold_convert_loc (loc, type, tem);
7951             }
7952         }
7953
7954       return NULL_TREE;
7955
7956     case VIEW_CONVERT_EXPR:
7957       if (TREE_CODE (op0) == MEM_REF)
7958         {
7959           if (TYPE_ALIGN (TREE_TYPE (op0)) != TYPE_ALIGN (type))
7960             type = build_aligned_type (type, TYPE_ALIGN (TREE_TYPE (op0)));
7961           tem = fold_build2_loc (loc, MEM_REF, type,
7962                                  TREE_OPERAND (op0, 0), TREE_OPERAND (op0, 1));
7963           REF_REVERSE_STORAGE_ORDER (tem) = REF_REVERSE_STORAGE_ORDER (op0);
7964           return tem;
7965         }
7966
7967       return NULL_TREE;
7968
7969     case NEGATE_EXPR:
7970       tem = fold_negate_expr (loc, arg0);
7971       if (tem)
7972         return fold_convert_loc (loc, type, tem);
7973       return NULL_TREE;
7974
7975     case ABS_EXPR:
7976       /* Convert fabs((double)float) into (double)fabsf(float).  */
7977       if (TREE_CODE (arg0) == NOP_EXPR
7978           && TREE_CODE (type) == REAL_TYPE)
7979         {
7980           tree targ0 = strip_float_extensions (arg0);
7981           if (targ0 != arg0)
7982             return fold_convert_loc (loc, type,
7983                                      fold_build1_loc (loc, ABS_EXPR,
7984                                                   TREE_TYPE (targ0),
7985                                                   targ0));
7986         }
7987       return NULL_TREE;
7988
7989     case BIT_NOT_EXPR:
7990       /* Convert ~(X ^ Y) to ~X ^ Y or X ^ ~Y if ~X or ~Y simplify.  */
7991       if (TREE_CODE (arg0) == BIT_XOR_EXPR
7992           && (tem = fold_unary_loc (loc, BIT_NOT_EXPR, type,
7993                                     fold_convert_loc (loc, type,
7994                                                       TREE_OPERAND (arg0, 0)))))
7995         return fold_build2_loc (loc, BIT_XOR_EXPR, type, tem,
7996                                 fold_convert_loc (loc, type,
7997                                                   TREE_OPERAND (arg0, 1)));
7998       else if (TREE_CODE (arg0) == BIT_XOR_EXPR
7999                && (tem = fold_unary_loc (loc, BIT_NOT_EXPR, type,
8000                                      fold_convert_loc (loc, type,
8001                                                        TREE_OPERAND (arg0, 1)))))
8002         return fold_build2_loc (loc, BIT_XOR_EXPR, type,
8003                             fold_convert_loc (loc, type,
8004                                               TREE_OPERAND (arg0, 0)), tem);
8005
8006       return NULL_TREE;
8007
8008     case TRUTH_NOT_EXPR:
8009       /* Note that the operand of this must be an int
8010          and its values must be 0 or 1.
8011          ("true" is a fixed value perhaps depending on the language,
8012          but we don't handle values other than 1 correctly yet.)  */
8013       tem = fold_truth_not_expr (loc, arg0);
8014       if (!tem)
8015         return NULL_TREE;
8016       return fold_convert_loc (loc, type, tem);
8017
8018     case INDIRECT_REF:
8019       /* Fold *&X to X if X is an lvalue.  */
8020       if (TREE_CODE (op0) == ADDR_EXPR)
8021         {
8022           tree op00 = TREE_OPERAND (op0, 0);
8023           if ((TREE_CODE (op00) == VAR_DECL
8024                || TREE_CODE (op00) == PARM_DECL
8025                || TREE_CODE (op00) == RESULT_DECL)
8026               && !TREE_READONLY (op00))
8027             return op00;
8028         }
8029       return NULL_TREE;
8030
8031     default:
8032       return NULL_TREE;
8033     } /* switch (code) */
8034 }
8035
8036
8037 /* If the operation was a conversion do _not_ mark a resulting constant
8038    with TREE_OVERFLOW if the original constant was not.  These conversions
8039    have implementation defined behavior and retaining the TREE_OVERFLOW
8040    flag here would confuse later passes such as VRP.  */
8041 tree
8042 fold_unary_ignore_overflow_loc (location_t loc, enum tree_code code,
8043                                 tree type, tree op0)
8044 {
8045   tree res = fold_unary_loc (loc, code, type, op0);
8046   if (res
8047       && TREE_CODE (res) == INTEGER_CST
8048       && TREE_CODE (op0) == INTEGER_CST
8049       && CONVERT_EXPR_CODE_P (code))
8050     TREE_OVERFLOW (res) = TREE_OVERFLOW (op0);
8051
8052   return res;
8053 }
8054
8055 /* Fold a binary bitwise/truth expression of code CODE and type TYPE with
8056    operands OP0 and OP1.  LOC is the location of the resulting expression.
8057    ARG0 and ARG1 are the NOP_STRIPed results of OP0 and OP1.
8058    Return the folded expression if folding is successful.  Otherwise,
8059    return NULL_TREE.  */
8060 static tree
8061 fold_truth_andor (location_t loc, enum tree_code code, tree type,
8062                   tree arg0, tree arg1, tree op0, tree op1)
8063 {
8064   tree tem;
8065
8066   /* We only do these simplifications if we are optimizing.  */
8067   if (!optimize)
8068     return NULL_TREE;
8069
8070   /* Check for things like (A || B) && (A || C).  We can convert this
8071      to A || (B && C).  Note that either operator can be any of the four
8072      truth and/or operations and the transformation will still be
8073      valid.   Also note that we only care about order for the
8074      ANDIF and ORIF operators.  If B contains side effects, this
8075      might change the truth-value of A.  */
8076   if (TREE_CODE (arg0) == TREE_CODE (arg1)
8077       && (TREE_CODE (arg0) == TRUTH_ANDIF_EXPR
8078           || TREE_CODE (arg0) == TRUTH_ORIF_EXPR
8079           || TREE_CODE (arg0) == TRUTH_AND_EXPR
8080           || TREE_CODE (arg0) == TRUTH_OR_EXPR)
8081       && ! TREE_SIDE_EFFECTS (TREE_OPERAND (arg0, 1)))
8082     {
8083       tree a00 = TREE_OPERAND (arg0, 0);
8084       tree a01 = TREE_OPERAND (arg0, 1);
8085       tree a10 = TREE_OPERAND (arg1, 0);
8086       tree a11 = TREE_OPERAND (arg1, 1);
8087       int commutative = ((TREE_CODE (arg0) == TRUTH_OR_EXPR
8088                           || TREE_CODE (arg0) == TRUTH_AND_EXPR)
8089                          && (code == TRUTH_AND_EXPR
8090                              || code == TRUTH_OR_EXPR));
8091
8092       if (operand_equal_p (a00, a10, 0))
8093         return fold_build2_loc (loc, TREE_CODE (arg0), type, a00,
8094                             fold_build2_loc (loc, code, type, a01, a11));
8095       else if (commutative && operand_equal_p (a00, a11, 0))
8096         return fold_build2_loc (loc, TREE_CODE (arg0), type, a00,
8097                             fold_build2_loc (loc, code, type, a01, a10));
8098       else if (commutative && operand_equal_p (a01, a10, 0))
8099         return fold_build2_loc (loc, TREE_CODE (arg0), type, a01,
8100                             fold_build2_loc (loc, code, type, a00, a11));
8101
8102       /* This case if tricky because we must either have commutative
8103          operators or else A10 must not have side-effects.  */
8104
8105       else if ((commutative || ! TREE_SIDE_EFFECTS (a10))
8106                && operand_equal_p (a01, a11, 0))
8107         return fold_build2_loc (loc, TREE_CODE (arg0), type,
8108                             fold_build2_loc (loc, code, type, a00, a10),
8109                             a01);
8110     }
8111
8112   /* See if we can build a range comparison.  */
8113   if (0 != (tem = fold_range_test (loc, code, type, op0, op1)))
8114     return tem;
8115
8116   if ((code == TRUTH_ANDIF_EXPR && TREE_CODE (arg0) == TRUTH_ORIF_EXPR)
8117       || (code == TRUTH_ORIF_EXPR && TREE_CODE (arg0) == TRUTH_ANDIF_EXPR))
8118     {
8119       tem = merge_truthop_with_opposite_arm (loc, arg0, arg1, true);
8120       if (tem)
8121         return fold_build2_loc (loc, code, type, tem, arg1);
8122     }
8123
8124   if ((code == TRUTH_ANDIF_EXPR && TREE_CODE (arg1) == TRUTH_ORIF_EXPR)
8125       || (code == TRUTH_ORIF_EXPR && TREE_CODE (arg1) == TRUTH_ANDIF_EXPR))
8126     {
8127       tem = merge_truthop_with_opposite_arm (loc, arg1, arg0, false);
8128       if (tem)
8129         return fold_build2_loc (loc, code, type, arg0, tem);
8130     }
8131
8132   /* Check for the possibility of merging component references.  If our
8133      lhs is another similar operation, try to merge its rhs with our
8134      rhs.  Then try to merge our lhs and rhs.  */
8135   if (TREE_CODE (arg0) == code
8136       && 0 != (tem = fold_truth_andor_1 (loc, code, type,
8137                                          TREE_OPERAND (arg0, 1), arg1)))
8138     return fold_build2_loc (loc, code, type, TREE_OPERAND (arg0, 0), tem);
8139
8140   if ((tem = fold_truth_andor_1 (loc, code, type, arg0, arg1)) != 0)
8141     return tem;
8142
8143   if (LOGICAL_OP_NON_SHORT_CIRCUIT
8144       && (code == TRUTH_AND_EXPR
8145           || code == TRUTH_ANDIF_EXPR
8146           || code == TRUTH_OR_EXPR
8147           || code == TRUTH_ORIF_EXPR))
8148     {
8149       enum tree_code ncode, icode;
8150
8151       ncode = (code == TRUTH_ANDIF_EXPR || code == TRUTH_AND_EXPR)
8152               ? TRUTH_AND_EXPR : TRUTH_OR_EXPR;
8153       icode = ncode == TRUTH_AND_EXPR ? TRUTH_ANDIF_EXPR : TRUTH_ORIF_EXPR;
8154
8155       /* Transform ((A AND-IF B) AND[-IF] C) into (A AND-IF (B AND C)),
8156          or ((A OR-IF B) OR[-IF] C) into (A OR-IF (B OR C))
8157          We don't want to pack more than two leafs to a non-IF AND/OR
8158          expression.
8159          If tree-code of left-hand operand isn't an AND/OR-IF code and not
8160          equal to IF-CODE, then we don't want to add right-hand operand.
8161          If the inner right-hand side of left-hand operand has
8162          side-effects, or isn't simple, then we can't add to it,
8163          as otherwise we might destroy if-sequence.  */
8164       if (TREE_CODE (arg0) == icode
8165           && simple_operand_p_2 (arg1)
8166           /* Needed for sequence points to handle trappings, and
8167              side-effects.  */
8168           && simple_operand_p_2 (TREE_OPERAND (arg0, 1)))
8169         {
8170           tem = fold_build2_loc (loc, ncode, type, TREE_OPERAND (arg0, 1),
8171                                  arg1);
8172           return fold_build2_loc (loc, icode, type, TREE_OPERAND (arg0, 0),
8173                                   tem);
8174         }
8175         /* Same as abouve but for (A AND[-IF] (B AND-IF C)) -> ((A AND B) AND-IF C),
8176            or (A OR[-IF] (B OR-IF C) -> ((A OR B) OR-IF C).  */
8177       else if (TREE_CODE (arg1) == icode
8178           && simple_operand_p_2 (arg0)
8179           /* Needed for sequence points to handle trappings, and
8180              side-effects.  */
8181           && simple_operand_p_2 (TREE_OPERAND (arg1, 0)))
8182         {
8183           tem = fold_build2_loc (loc, ncode, type,
8184                                  arg0, TREE_OPERAND (arg1, 0));
8185           return fold_build2_loc (loc, icode, type, tem,
8186                                   TREE_OPERAND (arg1, 1));
8187         }
8188       /* Transform (A AND-IF B) into (A AND B), or (A OR-IF B)
8189          into (A OR B).
8190          For sequence point consistancy, we need to check for trapping,
8191          and side-effects.  */
8192       else if (code == icode && simple_operand_p_2 (arg0)
8193                && simple_operand_p_2 (arg1))
8194         return fold_build2_loc (loc, ncode, type, arg0, arg1);
8195     }
8196
8197   return NULL_TREE;
8198 }
8199
8200 /* Helper that tries to canonicalize the comparison ARG0 CODE ARG1
8201    by changing CODE to reduce the magnitude of constants involved in
8202    ARG0 of the comparison.
8203    Returns a canonicalized comparison tree if a simplification was
8204    possible, otherwise returns NULL_TREE.
8205    Set *STRICT_OVERFLOW_P to true if the canonicalization is only
8206    valid if signed overflow is undefined.  */
8207
8208 static tree
8209 maybe_canonicalize_comparison_1 (location_t loc, enum tree_code code, tree type,
8210                                  tree arg0, tree arg1,
8211                                  bool *strict_overflow_p)
8212 {
8213   enum tree_code code0 = TREE_CODE (arg0);
8214   tree t, cst0 = NULL_TREE;
8215   int sgn0;
8216
8217   /* Match A +- CST code arg1.  We can change this only if overflow
8218      is undefined.  */
8219   if (!((ANY_INTEGRAL_TYPE_P (TREE_TYPE (arg0))
8220          && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg0)))
8221         /* In principle pointers also have undefined overflow behavior,
8222            but that causes problems elsewhere.  */
8223         && !POINTER_TYPE_P (TREE_TYPE (arg0))
8224         && (code0 == MINUS_EXPR
8225             || code0 == PLUS_EXPR)
8226         && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST))
8227     return NULL_TREE;
8228
8229   /* Identify the constant in arg0 and its sign.  */
8230   cst0 = TREE_OPERAND (arg0, 1);
8231   sgn0 = tree_int_cst_sgn (cst0);
8232
8233   /* Overflowed constants and zero will cause problems.  */
8234   if (integer_zerop (cst0)
8235       || TREE_OVERFLOW (cst0))
8236     return NULL_TREE;
8237
8238   /* See if we can reduce the magnitude of the constant in
8239      arg0 by changing the comparison code.  */
8240   /* A - CST < arg1  ->  A - CST-1 <= arg1.  */
8241   if (code == LT_EXPR
8242       && code0 == ((sgn0 == -1) ? PLUS_EXPR : MINUS_EXPR))
8243     code = LE_EXPR;
8244   /* A + CST > arg1  ->  A + CST-1 >= arg1.  */
8245   else if (code == GT_EXPR
8246            && code0 == ((sgn0 == -1) ? MINUS_EXPR : PLUS_EXPR))
8247     code = GE_EXPR;
8248   /* A + CST <= arg1  ->  A + CST-1 < arg1.  */
8249   else if (code == LE_EXPR
8250            && code0 == ((sgn0 == -1) ? MINUS_EXPR : PLUS_EXPR))
8251     code = LT_EXPR;
8252   /* A - CST >= arg1  ->  A - CST-1 > arg1.  */
8253   else if (code == GE_EXPR
8254            && code0 == ((sgn0 == -1) ? PLUS_EXPR : MINUS_EXPR))
8255     code = GT_EXPR;
8256   else
8257     return NULL_TREE;
8258   *strict_overflow_p = true;
8259
8260   /* Now build the constant reduced in magnitude.  But not if that
8261      would produce one outside of its types range.  */
8262   if (INTEGRAL_TYPE_P (TREE_TYPE (cst0))
8263       && ((sgn0 == 1
8264            && TYPE_MIN_VALUE (TREE_TYPE (cst0))
8265            && tree_int_cst_equal (cst0, TYPE_MIN_VALUE (TREE_TYPE (cst0))))
8266           || (sgn0 == -1
8267               && TYPE_MAX_VALUE (TREE_TYPE (cst0))
8268               && tree_int_cst_equal (cst0, TYPE_MAX_VALUE (TREE_TYPE (cst0))))))
8269     return NULL_TREE;
8270
8271   t = int_const_binop (sgn0 == -1 ? PLUS_EXPR : MINUS_EXPR,
8272                        cst0, build_int_cst (TREE_TYPE (cst0), 1));
8273   t = fold_build2_loc (loc, code0, TREE_TYPE (arg0), TREE_OPERAND (arg0, 0), t);
8274   t = fold_convert (TREE_TYPE (arg1), t);
8275
8276   return fold_build2_loc (loc, code, type, t, arg1);
8277 }
8278
8279 /* Canonicalize the comparison ARG0 CODE ARG1 with type TYPE with undefined
8280    overflow further.  Try to decrease the magnitude of constants involved
8281    by changing LE_EXPR and GE_EXPR to LT_EXPR and GT_EXPR or vice versa
8282    and put sole constants at the second argument position.
8283    Returns the canonicalized tree if changed, otherwise NULL_TREE.  */
8284
8285 static tree
8286 maybe_canonicalize_comparison (location_t loc, enum tree_code code, tree type,
8287                                tree arg0, tree arg1)
8288 {
8289   tree t;
8290   bool strict_overflow_p;
8291   const char * const warnmsg = G_("assuming signed overflow does not occur "
8292                                   "when reducing constant in comparison");
8293
8294   /* Try canonicalization by simplifying arg0.  */
8295   strict_overflow_p = false;
8296   t = maybe_canonicalize_comparison_1 (loc, code, type, arg0, arg1,
8297                                        &strict_overflow_p);
8298   if (t)
8299     {
8300       if (strict_overflow_p)
8301         fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_MAGNITUDE);
8302       return t;
8303     }
8304
8305   /* Try canonicalization by simplifying arg1 using the swapped
8306      comparison.  */
8307   code = swap_tree_comparison (code);
8308   strict_overflow_p = false;
8309   t = maybe_canonicalize_comparison_1 (loc, code, type, arg1, arg0,
8310                                        &strict_overflow_p);
8311   if (t && strict_overflow_p)
8312     fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_MAGNITUDE);
8313   return t;
8314 }
8315
8316 /* Return whether BASE + OFFSET + BITPOS may wrap around the address
8317    space.  This is used to avoid issuing overflow warnings for
8318    expressions like &p->x which can not wrap.  */
8319
8320 static bool
8321 pointer_may_wrap_p (tree base, tree offset, HOST_WIDE_INT bitpos)
8322 {
8323   if (!POINTER_TYPE_P (TREE_TYPE (base)))
8324     return true;
8325
8326   if (bitpos < 0)
8327     return true;
8328
8329   wide_int wi_offset;
8330   int precision = TYPE_PRECISION (TREE_TYPE (base));
8331   if (offset == NULL_TREE)
8332     wi_offset = wi::zero (precision);
8333   else if (TREE_CODE (offset) != INTEGER_CST || TREE_OVERFLOW (offset))
8334     return true;
8335   else
8336     wi_offset = offset;
8337
8338   bool overflow;
8339   wide_int units = wi::shwi (bitpos / BITS_PER_UNIT, precision);
8340   wide_int total = wi::add (wi_offset, units, UNSIGNED, &overflow);
8341   if (overflow)
8342     return true;
8343
8344   if (!wi::fits_uhwi_p (total))
8345     return true;
8346
8347   HOST_WIDE_INT size = int_size_in_bytes (TREE_TYPE (TREE_TYPE (base)));
8348   if (size <= 0)
8349     return true;
8350
8351   /* We can do slightly better for SIZE if we have an ADDR_EXPR of an
8352      array.  */
8353   if (TREE_CODE (base) == ADDR_EXPR)
8354     {
8355       HOST_WIDE_INT base_size;
8356
8357       base_size = int_size_in_bytes (TREE_TYPE (TREE_OPERAND (base, 0)));
8358       if (base_size > 0 && size < base_size)
8359         size = base_size;
8360     }
8361
8362   return total.to_uhwi () > (unsigned HOST_WIDE_INT) size;
8363 }
8364
8365 /* Return a positive integer when the symbol DECL is known to have
8366    a nonzero address, zero when it's known not to (e.g., it's a weak
8367    symbol), and a negative integer when the symbol is not yet in the
8368    symbol table and so whether or not its address is zero is unknown.  */
8369 static int
8370 maybe_nonzero_address (tree decl)
8371 {
8372   if (DECL_P (decl) && decl_in_symtab_p (decl))
8373     if (struct symtab_node *symbol = symtab_node::get_create (decl))
8374       return symbol->nonzero_address ();
8375
8376   return -1;
8377 }
8378
8379 /* Subroutine of fold_binary.  This routine performs all of the
8380    transformations that are common to the equality/inequality
8381    operators (EQ_EXPR and NE_EXPR) and the ordering operators
8382    (LT_EXPR, LE_EXPR, GE_EXPR and GT_EXPR).  Callers other than
8383    fold_binary should call fold_binary.  Fold a comparison with
8384    tree code CODE and type TYPE with operands OP0 and OP1.  Return
8385    the folded comparison or NULL_TREE.  */
8386
8387 static tree
8388 fold_comparison (location_t loc, enum tree_code code, tree type,
8389                  tree op0, tree op1)
8390 {
8391   const bool equality_code = (code == EQ_EXPR || code == NE_EXPR);
8392   tree arg0, arg1, tem;
8393
8394   arg0 = op0;
8395   arg1 = op1;
8396
8397   STRIP_SIGN_NOPS (arg0);
8398   STRIP_SIGN_NOPS (arg1);
8399
8400   /* Transform comparisons of the form X +- C1 CMP C2 to X CMP C2 -+ C1.  */
8401   if ((TREE_CODE (arg0) == PLUS_EXPR || TREE_CODE (arg0) == MINUS_EXPR)
8402       && (equality_code
8403           || (ANY_INTEGRAL_TYPE_P (TREE_TYPE (arg0))
8404               && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg0))))
8405       && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
8406       && !TREE_OVERFLOW (TREE_OPERAND (arg0, 1))
8407       && TREE_CODE (arg1) == INTEGER_CST
8408       && !TREE_OVERFLOW (arg1))
8409     {
8410       const enum tree_code
8411         reverse_op = TREE_CODE (arg0) == PLUS_EXPR ? MINUS_EXPR : PLUS_EXPR;
8412       tree const1 = TREE_OPERAND (arg0, 1);
8413       tree const2 = fold_convert_loc (loc, TREE_TYPE (const1), arg1);
8414       tree variable = TREE_OPERAND (arg0, 0);
8415       tree new_const = int_const_binop (reverse_op, const2, const1);
8416
8417       /* If the constant operation overflowed this can be
8418          simplified as a comparison against INT_MAX/INT_MIN.  */
8419       if (TREE_OVERFLOW (new_const)
8420           && !TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg0)))
8421         {
8422           int const1_sgn = tree_int_cst_sgn (const1);
8423           enum tree_code code2 = code;
8424
8425           /* Get the sign of the constant on the lhs if the
8426              operation were VARIABLE + CONST1.  */
8427           if (TREE_CODE (arg0) == MINUS_EXPR)
8428             const1_sgn = -const1_sgn;
8429
8430           /* The sign of the constant determines if we overflowed
8431              INT_MAX (const1_sgn == -1) or INT_MIN (const1_sgn == 1).
8432              Canonicalize to the INT_MIN overflow by swapping the comparison
8433              if necessary.  */
8434           if (const1_sgn == -1)
8435             code2 = swap_tree_comparison (code);
8436
8437           /* We now can look at the canonicalized case
8438                VARIABLE + 1  CODE2  INT_MIN
8439              and decide on the result.  */
8440           switch (code2)
8441             {
8442             case EQ_EXPR:
8443             case LT_EXPR:
8444             case LE_EXPR:
8445               return
8446                 omit_one_operand_loc (loc, type, boolean_false_node, variable);
8447
8448             case NE_EXPR:
8449             case GE_EXPR:
8450             case GT_EXPR:
8451               return
8452                 omit_one_operand_loc (loc, type, boolean_true_node, variable);
8453
8454             default:
8455               gcc_unreachable ();
8456             }
8457         }
8458       else
8459         {
8460           if (!equality_code)
8461             fold_overflow_warning ("assuming signed overflow does not occur "
8462                                    "when changing X +- C1 cmp C2 to "
8463                                    "X cmp C2 -+ C1",
8464                                    WARN_STRICT_OVERFLOW_COMPARISON);
8465           return fold_build2_loc (loc, code, type, variable, new_const);
8466         }
8467     }
8468
8469   /* For comparisons of pointers we can decompose it to a compile time
8470      comparison of the base objects and the offsets into the object.
8471      This requires at least one operand being an ADDR_EXPR or a
8472      POINTER_PLUS_EXPR to do more than the operand_equal_p test below.  */
8473   if (POINTER_TYPE_P (TREE_TYPE (arg0))
8474       && (TREE_CODE (arg0) == ADDR_EXPR
8475           || TREE_CODE (arg1) == ADDR_EXPR
8476           || TREE_CODE (arg0) == POINTER_PLUS_EXPR
8477           || TREE_CODE (arg1) == POINTER_PLUS_EXPR))
8478     {
8479       tree base0, base1, offset0 = NULL_TREE, offset1 = NULL_TREE;
8480       HOST_WIDE_INT bitsize, bitpos0 = 0, bitpos1 = 0;
8481       machine_mode mode;
8482       int volatilep, reversep, unsignedp;
8483       bool indirect_base0 = false, indirect_base1 = false;
8484
8485       /* Get base and offset for the access.  Strip ADDR_EXPR for
8486          get_inner_reference, but put it back by stripping INDIRECT_REF
8487          off the base object if possible.  indirect_baseN will be true
8488          if baseN is not an address but refers to the object itself.  */
8489       base0 = arg0;
8490       if (TREE_CODE (arg0) == ADDR_EXPR)
8491         {
8492           base0
8493             = get_inner_reference (TREE_OPERAND (arg0, 0),
8494                                    &bitsize, &bitpos0, &offset0, &mode,
8495                                    &unsignedp, &reversep, &volatilep, false);
8496           if (TREE_CODE (base0) == INDIRECT_REF)
8497             base0 = TREE_OPERAND (base0, 0);
8498           else
8499             indirect_base0 = true;
8500         }
8501       else if (TREE_CODE (arg0) == POINTER_PLUS_EXPR)
8502         {
8503           base0 = TREE_OPERAND (arg0, 0);
8504           STRIP_SIGN_NOPS (base0);
8505           if (TREE_CODE (base0) == ADDR_EXPR)
8506             {
8507               base0
8508                 = get_inner_reference (TREE_OPERAND (base0, 0),
8509                                        &bitsize, &bitpos0, &offset0, &mode,
8510                                        &unsignedp, &reversep, &volatilep,
8511                                        false);
8512               if (TREE_CODE (base0) == INDIRECT_REF)
8513                 base0 = TREE_OPERAND (base0, 0);
8514               else
8515                 indirect_base0 = true;
8516             }
8517           if (offset0 == NULL_TREE || integer_zerop (offset0))
8518             offset0 = TREE_OPERAND (arg0, 1);
8519           else
8520             offset0 = size_binop (PLUS_EXPR, offset0,
8521                                   TREE_OPERAND (arg0, 1));
8522           if (TREE_CODE (offset0) == INTEGER_CST)
8523             {
8524               offset_int tem = wi::sext (wi::to_offset (offset0),
8525                                          TYPE_PRECISION (sizetype));
8526               tem = wi::lshift (tem, LOG2_BITS_PER_UNIT);
8527               tem += bitpos0;
8528               if (wi::fits_shwi_p (tem))
8529                 {
8530                   bitpos0 = tem.to_shwi ();
8531                   offset0 = NULL_TREE;
8532                 }
8533             }
8534         }
8535
8536       base1 = arg1;
8537       if (TREE_CODE (arg1) == ADDR_EXPR)
8538         {
8539           base1
8540             = get_inner_reference (TREE_OPERAND (arg1, 0),
8541                                    &bitsize, &bitpos1, &offset1, &mode,
8542                                    &unsignedp, &reversep, &volatilep, false);
8543           if (TREE_CODE (base1) == INDIRECT_REF)
8544             base1 = TREE_OPERAND (base1, 0);
8545           else
8546             indirect_base1 = true;
8547         }
8548       else if (TREE_CODE (arg1) == POINTER_PLUS_EXPR)
8549         {
8550           base1 = TREE_OPERAND (arg1, 0);
8551           STRIP_SIGN_NOPS (base1);
8552           if (TREE_CODE (base1) == ADDR_EXPR)
8553             {
8554               base1
8555                 = get_inner_reference (TREE_OPERAND (base1, 0),
8556                                        &bitsize, &bitpos1, &offset1, &mode,
8557                                        &unsignedp, &reversep, &volatilep,
8558                                        false);
8559               if (TREE_CODE (base1) == INDIRECT_REF)
8560                 base1 = TREE_OPERAND (base1, 0);
8561               else
8562                 indirect_base1 = true;
8563             }
8564           if (offset1 == NULL_TREE || integer_zerop (offset1))
8565             offset1 = TREE_OPERAND (arg1, 1);
8566           else
8567             offset1 = size_binop (PLUS_EXPR, offset1,
8568                                   TREE_OPERAND (arg1, 1));
8569           if (TREE_CODE (offset1) == INTEGER_CST)
8570             {
8571               offset_int tem = wi::sext (wi::to_offset (offset1),
8572                                          TYPE_PRECISION (sizetype));
8573               tem = wi::lshift (tem, LOG2_BITS_PER_UNIT);
8574               tem += bitpos1;
8575               if (wi::fits_shwi_p (tem))
8576                 {
8577                   bitpos1 = tem.to_shwi ();
8578                   offset1 = NULL_TREE;
8579                 }
8580             }
8581         }
8582
8583       /* If we have equivalent bases we might be able to simplify.  */
8584       if (indirect_base0 == indirect_base1
8585           && operand_equal_p (base0, base1,
8586                               indirect_base0 ? OEP_ADDRESS_OF : 0))
8587         {
8588           /* We can fold this expression to a constant if the non-constant
8589              offset parts are equal.  */
8590           if ((offset0 == offset1
8591                || (offset0 && offset1
8592                    && operand_equal_p (offset0, offset1, 0)))
8593               && (equality_code
8594                   || (indirect_base0
8595                       && (DECL_P (base0) || CONSTANT_CLASS_P (base0)))
8596                   || POINTER_TYPE_OVERFLOW_UNDEFINED))
8597
8598             {
8599               if (!equality_code
8600                   && bitpos0 != bitpos1
8601                   && (pointer_may_wrap_p (base0, offset0, bitpos0)
8602                       || pointer_may_wrap_p (base1, offset1, bitpos1)))
8603                 fold_overflow_warning (("assuming pointer wraparound does not "
8604                                         "occur when comparing P +- C1 with "
8605                                         "P +- C2"),
8606                                        WARN_STRICT_OVERFLOW_CONDITIONAL);
8607
8608               switch (code)
8609                 {
8610                 case EQ_EXPR:
8611                   return constant_boolean_node (bitpos0 == bitpos1, type);
8612                 case NE_EXPR:
8613                   return constant_boolean_node (bitpos0 != bitpos1, type);
8614                 case LT_EXPR:
8615                   return constant_boolean_node (bitpos0 < bitpos1, type);
8616                 case LE_EXPR:
8617                   return constant_boolean_node (bitpos0 <= bitpos1, type);
8618                 case GE_EXPR:
8619                   return constant_boolean_node (bitpos0 >= bitpos1, type);
8620                 case GT_EXPR:
8621                   return constant_boolean_node (bitpos0 > bitpos1, type);
8622                 default:;
8623                 }
8624             }
8625           /* We can simplify the comparison to a comparison of the variable
8626              offset parts if the constant offset parts are equal.
8627              Be careful to use signed sizetype here because otherwise we
8628              mess with array offsets in the wrong way.  This is possible
8629              because pointer arithmetic is restricted to retain within an
8630              object and overflow on pointer differences is undefined as of
8631              6.5.6/8 and /9 with respect to the signed ptrdiff_t.  */
8632           else if (bitpos0 == bitpos1
8633                    && (equality_code
8634                        || (indirect_base0
8635                            && (DECL_P (base0) || CONSTANT_CLASS_P (base0)))
8636                        || POINTER_TYPE_OVERFLOW_UNDEFINED))
8637             {
8638               /* By converting to signed sizetype we cover middle-end pointer
8639                  arithmetic which operates on unsigned pointer types of size
8640                  type size and ARRAY_REF offsets which are properly sign or
8641                  zero extended from their type in case it is narrower than
8642                  sizetype.  */
8643               if (offset0 == NULL_TREE)
8644                 offset0 = build_int_cst (ssizetype, 0);
8645               else
8646                 offset0 = fold_convert_loc (loc, ssizetype, offset0);
8647               if (offset1 == NULL_TREE)
8648                 offset1 = build_int_cst (ssizetype, 0);
8649               else
8650                 offset1 = fold_convert_loc (loc, ssizetype, offset1);
8651
8652               if (!equality_code
8653                   && (pointer_may_wrap_p (base0, offset0, bitpos0)
8654                       || pointer_may_wrap_p (base1, offset1, bitpos1)))
8655                 fold_overflow_warning (("assuming pointer wraparound does not "
8656                                         "occur when comparing P +- C1 with "
8657                                         "P +- C2"),
8658                                        WARN_STRICT_OVERFLOW_COMPARISON);
8659
8660               return fold_build2_loc (loc, code, type, offset0, offset1);
8661             }
8662         }
8663       /* For equal offsets we can simplify to a comparison of the
8664          base addresses.  */
8665       else if (bitpos0 == bitpos1
8666                && (indirect_base0
8667                    ? base0 != TREE_OPERAND (arg0, 0) : base0 != arg0)
8668                && (indirect_base1
8669                    ? base1 != TREE_OPERAND (arg1, 0) : base1 != arg1)
8670                && ((offset0 == offset1)
8671                    || (offset0 && offset1
8672                        && operand_equal_p (offset0, offset1, 0))))
8673         {
8674           if (indirect_base0)
8675             base0 = build_fold_addr_expr_loc (loc, base0);
8676           if (indirect_base1)
8677             base1 = build_fold_addr_expr_loc (loc, base1);
8678           return fold_build2_loc (loc, code, type, base0, base1);
8679         }
8680       /* Comparison between an ordinary (non-weak) symbol and a null
8681          pointer can be eliminated since such symbols must have a non
8682          null address.  In C, relational expressions between pointers
8683          to objects and null pointers are undefined.  The results
8684          below follow the C++ rules with the additional property that
8685          every object pointer compares greater than a null pointer.
8686       */
8687       else if (DECL_P (base0)
8688                && maybe_nonzero_address (base0) > 0
8689                /* Avoid folding references to struct members at offset 0 to
8690                   prevent tests like '&ptr->firstmember == 0' from getting
8691                   eliminated.  When ptr is null, although the -> expression
8692                   is strictly speaking invalid, GCC retains it as a matter
8693                   of QoI.  See PR c/44555. */
8694                && (offset0 == NULL_TREE && bitpos0 != 0)
8695                /* The caller guarantees that when one of the arguments is
8696                   constant (i.e., null in this case) it is second.  */
8697                && integer_zerop (arg1))
8698         {
8699           switch (code)
8700             {
8701             case EQ_EXPR:
8702             case LE_EXPR:
8703             case LT_EXPR:
8704               return constant_boolean_node (false, type);
8705             case GE_EXPR:
8706             case GT_EXPR:
8707             case NE_EXPR:
8708               return constant_boolean_node (true, type);
8709             default:
8710               gcc_unreachable ();
8711             }
8712         }
8713     }
8714
8715   /* Transform comparisons of the form X +- C1 CMP Y +- C2 to
8716      X CMP Y +- C2 +- C1 for signed X, Y.  This is valid if
8717      the resulting offset is smaller in absolute value than the
8718      original one and has the same sign.  */
8719   if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (arg0))
8720       && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg0))
8721       && (TREE_CODE (arg0) == PLUS_EXPR || TREE_CODE (arg0) == MINUS_EXPR)
8722       && (TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
8723           && !TREE_OVERFLOW (TREE_OPERAND (arg0, 1)))
8724       && (TREE_CODE (arg1) == PLUS_EXPR || TREE_CODE (arg1) == MINUS_EXPR)
8725       && (TREE_CODE (TREE_OPERAND (arg1, 1)) == INTEGER_CST
8726           && !TREE_OVERFLOW (TREE_OPERAND (arg1, 1))))
8727     {
8728       tree const1 = TREE_OPERAND (arg0, 1);
8729       tree const2 = TREE_OPERAND (arg1, 1);
8730       tree variable1 = TREE_OPERAND (arg0, 0);
8731       tree variable2 = TREE_OPERAND (arg1, 0);
8732       tree cst;
8733       const char * const warnmsg = G_("assuming signed overflow does not "
8734                                       "occur when combining constants around "
8735                                       "a comparison");
8736
8737       /* Put the constant on the side where it doesn't overflow and is
8738          of lower absolute value and of same sign than before.  */
8739       cst = int_const_binop (TREE_CODE (arg0) == TREE_CODE (arg1)
8740                              ? MINUS_EXPR : PLUS_EXPR,
8741                              const2, const1);
8742       if (!TREE_OVERFLOW (cst)
8743           && tree_int_cst_compare (const2, cst) == tree_int_cst_sgn (const2)
8744           && tree_int_cst_sgn (cst) == tree_int_cst_sgn (const2))
8745         {
8746           fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_COMPARISON);
8747           return fold_build2_loc (loc, code, type,
8748                                   variable1,
8749                                   fold_build2_loc (loc, TREE_CODE (arg1),
8750                                                    TREE_TYPE (arg1),
8751                                                    variable2, cst));
8752         }
8753
8754       cst = int_const_binop (TREE_CODE (arg0) == TREE_CODE (arg1)
8755                              ? MINUS_EXPR : PLUS_EXPR,
8756                              const1, const2);
8757       if (!TREE_OVERFLOW (cst)
8758           && tree_int_cst_compare (const1, cst) == tree_int_cst_sgn (const1)
8759           && tree_int_cst_sgn (cst) == tree_int_cst_sgn (const1))
8760         {
8761           fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_COMPARISON);
8762           return fold_build2_loc (loc, code, type,
8763                                   fold_build2_loc (loc, TREE_CODE (arg0),
8764                                                    TREE_TYPE (arg0),
8765                                                    variable1, cst),
8766                                   variable2);
8767         }
8768     }
8769
8770   tem = maybe_canonicalize_comparison (loc, code, type, arg0, arg1);
8771   if (tem)
8772     return tem;
8773
8774   /* If this is comparing a constant with a MIN_EXPR or a MAX_EXPR of a
8775      constant, we can simplify it.  */
8776   if (TREE_CODE (arg1) == INTEGER_CST
8777       && (TREE_CODE (arg0) == MIN_EXPR
8778           || TREE_CODE (arg0) == MAX_EXPR)
8779       && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
8780     {
8781       tem = optimize_minmax_comparison (loc, code, type, op0, op1);
8782       if (tem)
8783         return tem;
8784     }
8785
8786   /* If we are comparing an expression that just has comparisons
8787      of two integer values, arithmetic expressions of those comparisons,
8788      and constants, we can simplify it.  There are only three cases
8789      to check: the two values can either be equal, the first can be
8790      greater, or the second can be greater.  Fold the expression for
8791      those three values.  Since each value must be 0 or 1, we have
8792      eight possibilities, each of which corresponds to the constant 0
8793      or 1 or one of the six possible comparisons.
8794
8795      This handles common cases like (a > b) == 0 but also handles
8796      expressions like  ((x > y) - (y > x)) > 0, which supposedly
8797      occur in macroized code.  */
8798
8799   if (TREE_CODE (arg1) == INTEGER_CST && TREE_CODE (arg0) != INTEGER_CST)
8800     {
8801       tree cval1 = 0, cval2 = 0;
8802       int save_p = 0;
8803
8804       if (twoval_comparison_p (arg0, &cval1, &cval2, &save_p)
8805           /* Don't handle degenerate cases here; they should already
8806              have been handled anyway.  */
8807           && cval1 != 0 && cval2 != 0
8808           && ! (TREE_CONSTANT (cval1) && TREE_CONSTANT (cval2))
8809           && TREE_TYPE (cval1) == TREE_TYPE (cval2)
8810           && INTEGRAL_TYPE_P (TREE_TYPE (cval1))
8811           && TYPE_MAX_VALUE (TREE_TYPE (cval1))
8812           && TYPE_MAX_VALUE (TREE_TYPE (cval2))
8813           && ! operand_equal_p (TYPE_MIN_VALUE (TREE_TYPE (cval1)),
8814                                 TYPE_MAX_VALUE (TREE_TYPE (cval2)), 0))
8815         {
8816           tree maxval = TYPE_MAX_VALUE (TREE_TYPE (cval1));
8817           tree minval = TYPE_MIN_VALUE (TREE_TYPE (cval1));
8818
8819           /* We can't just pass T to eval_subst in case cval1 or cval2
8820              was the same as ARG1.  */
8821
8822           tree high_result
8823                 = fold_build2_loc (loc, code, type,
8824                                eval_subst (loc, arg0, cval1, maxval,
8825                                            cval2, minval),
8826                                arg1);
8827           tree equal_result
8828                 = fold_build2_loc (loc, code, type,
8829                                eval_subst (loc, arg0, cval1, maxval,
8830                                            cval2, maxval),
8831                                arg1);
8832           tree low_result
8833                 = fold_build2_loc (loc, code, type,
8834                                eval_subst (loc, arg0, cval1, minval,
8835                                            cval2, maxval),
8836                                arg1);
8837
8838           /* All three of these results should be 0 or 1.  Confirm they are.
8839              Then use those values to select the proper code to use.  */
8840
8841           if (TREE_CODE (high_result) == INTEGER_CST
8842               && TREE_CODE (equal_result) == INTEGER_CST
8843               && TREE_CODE (low_result) == INTEGER_CST)
8844             {
8845               /* Make a 3-bit mask with the high-order bit being the
8846                  value for `>', the next for '=', and the low for '<'.  */
8847               switch ((integer_onep (high_result) * 4)
8848                       + (integer_onep (equal_result) * 2)
8849                       + integer_onep (low_result))
8850                 {
8851                 case 0:
8852                   /* Always false.  */
8853                   return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
8854                 case 1:
8855                   code = LT_EXPR;
8856                   break;
8857                 case 2:
8858                   code = EQ_EXPR;
8859                   break;
8860                 case 3:
8861                   code = LE_EXPR;
8862                   break;
8863                 case 4:
8864                   code = GT_EXPR;
8865                   break;
8866                 case 5:
8867                   code = NE_EXPR;
8868                   break;
8869                 case 6:
8870                   code = GE_EXPR;
8871                   break;
8872                 case 7:
8873                   /* Always true.  */
8874                   return omit_one_operand_loc (loc, type, integer_one_node, arg0);
8875                 }
8876
8877               if (save_p)
8878                 {
8879                   tem = save_expr (build2 (code, type, cval1, cval2));
8880                   SET_EXPR_LOCATION (tem, loc);
8881                   return tem;
8882                 }
8883               return fold_build2_loc (loc, code, type, cval1, cval2);
8884             }
8885         }
8886     }
8887
8888   /* We can fold X/C1 op C2 where C1 and C2 are integer constants
8889      into a single range test.  */
8890   if ((TREE_CODE (arg0) == TRUNC_DIV_EXPR
8891        || TREE_CODE (arg0) == EXACT_DIV_EXPR)
8892       && TREE_CODE (arg1) == INTEGER_CST
8893       && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
8894       && !integer_zerop (TREE_OPERAND (arg0, 1))
8895       && !TREE_OVERFLOW (TREE_OPERAND (arg0, 1))
8896       && !TREE_OVERFLOW (arg1))
8897     {
8898       tem = fold_div_compare (loc, code, type, arg0, arg1);
8899       if (tem != NULL_TREE)
8900         return tem;
8901     }
8902
8903   return NULL_TREE;
8904 }
8905
8906
8907 /* Subroutine of fold_binary.  Optimize complex multiplications of the
8908    form z * conj(z), as pow(realpart(z),2) + pow(imagpart(z),2).  The
8909    argument EXPR represents the expression "z" of type TYPE.  */
8910
8911 static tree
8912 fold_mult_zconjz (location_t loc, tree type, tree expr)
8913 {
8914   tree itype = TREE_TYPE (type);
8915   tree rpart, ipart, tem;
8916
8917   if (TREE_CODE (expr) == COMPLEX_EXPR)
8918     {
8919       rpart = TREE_OPERAND (expr, 0);
8920       ipart = TREE_OPERAND (expr, 1);
8921     }
8922   else if (TREE_CODE (expr) == COMPLEX_CST)
8923     {
8924       rpart = TREE_REALPART (expr);
8925       ipart = TREE_IMAGPART (expr);
8926     }
8927   else
8928     {
8929       expr = save_expr (expr);
8930       rpart = fold_build1_loc (loc, REALPART_EXPR, itype, expr);
8931       ipart = fold_build1_loc (loc, IMAGPART_EXPR, itype, expr);
8932     }
8933
8934   rpart = save_expr (rpart);
8935   ipart = save_expr (ipart);
8936   tem = fold_build2_loc (loc, PLUS_EXPR, itype,
8937                      fold_build2_loc (loc, MULT_EXPR, itype, rpart, rpart),
8938                      fold_build2_loc (loc, MULT_EXPR, itype, ipart, ipart));
8939   return fold_build2_loc (loc, COMPLEX_EXPR, type, tem,
8940                           build_zero_cst (itype));
8941 }
8942
8943
8944 /* Helper function for fold_vec_perm.  Store elements of VECTOR_CST or
8945    CONSTRUCTOR ARG into array ELTS and return true if successful.  */
8946
8947 static bool
8948 vec_cst_ctor_to_array (tree arg, tree *elts)
8949 {
8950   unsigned int nelts = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg)), i;
8951
8952   if (TREE_CODE (arg) == VECTOR_CST)
8953     {
8954       for (i = 0; i < VECTOR_CST_NELTS (arg); ++i)
8955         elts[i] = VECTOR_CST_ELT (arg, i);
8956     }
8957   else if (TREE_CODE (arg) == CONSTRUCTOR)
8958     {
8959       constructor_elt *elt;
8960
8961       FOR_EACH_VEC_SAFE_ELT (CONSTRUCTOR_ELTS (arg), i, elt)
8962         if (i >= nelts || TREE_CODE (TREE_TYPE (elt->value)) == VECTOR_TYPE)
8963           return false;
8964         else
8965           elts[i] = elt->value;
8966     }
8967   else
8968     return false;
8969   for (; i < nelts; i++)
8970     elts[i]
8971       = fold_convert (TREE_TYPE (TREE_TYPE (arg)), integer_zero_node);
8972   return true;
8973 }
8974
8975 /* Attempt to fold vector permutation of ARG0 and ARG1 vectors using SEL
8976    selector.  Return the folded VECTOR_CST or CONSTRUCTOR if successful,
8977    NULL_TREE otherwise.  */
8978
8979 static tree
8980 fold_vec_perm (tree type, tree arg0, tree arg1, const unsigned char *sel)
8981 {
8982   unsigned int nelts = TYPE_VECTOR_SUBPARTS (type), i;
8983   tree *elts;
8984   bool need_ctor = false;
8985
8986   gcc_assert (TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0)) == nelts
8987               && TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg1)) == nelts);
8988   if (TREE_TYPE (TREE_TYPE (arg0)) != TREE_TYPE (type)
8989       || TREE_TYPE (TREE_TYPE (arg1)) != TREE_TYPE (type))
8990     return NULL_TREE;
8991
8992   elts = XALLOCAVEC (tree, nelts * 3);
8993   if (!vec_cst_ctor_to_array (arg0, elts)
8994       || !vec_cst_ctor_to_array (arg1, elts + nelts))
8995     return NULL_TREE;
8996
8997   for (i = 0; i < nelts; i++)
8998     {
8999       if (!CONSTANT_CLASS_P (elts[sel[i]]))
9000         need_ctor = true;
9001       elts[i + 2 * nelts] = unshare_expr (elts[sel[i]]);
9002     }
9003
9004   if (need_ctor)
9005     {
9006       vec<constructor_elt, va_gc> *v;
9007       vec_alloc (v, nelts);
9008       for (i = 0; i < nelts; i++)
9009         CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, elts[2 * nelts + i]);
9010       return build_constructor (type, v);
9011     }
9012   else
9013     return build_vector (type, &elts[2 * nelts]);
9014 }
9015
9016 /* Try to fold a pointer difference of type TYPE two address expressions of
9017    array references AREF0 and AREF1 using location LOC.  Return a
9018    simplified expression for the difference or NULL_TREE.  */
9019
9020 static tree
9021 fold_addr_of_array_ref_difference (location_t loc, tree type,
9022                                    tree aref0, tree aref1)
9023 {
9024   tree base0 = TREE_OPERAND (aref0, 0);
9025   tree base1 = TREE_OPERAND (aref1, 0);
9026   tree base_offset = build_int_cst (type, 0);
9027
9028   /* If the bases are array references as well, recurse.  If the bases
9029      are pointer indirections compute the difference of the pointers.
9030      If the bases are equal, we are set.  */
9031   if ((TREE_CODE (base0) == ARRAY_REF
9032        && TREE_CODE (base1) == ARRAY_REF
9033        && (base_offset
9034            = fold_addr_of_array_ref_difference (loc, type, base0, base1)))
9035       || (INDIRECT_REF_P (base0)
9036           && INDIRECT_REF_P (base1)
9037           && (base_offset
9038                 = fold_binary_loc (loc, MINUS_EXPR, type,
9039                                    fold_convert (type, TREE_OPERAND (base0, 0)),
9040                                    fold_convert (type,
9041                                                  TREE_OPERAND (base1, 0)))))
9042       || operand_equal_p (base0, base1, OEP_ADDRESS_OF))
9043     {
9044       tree op0 = fold_convert_loc (loc, type, TREE_OPERAND (aref0, 1));
9045       tree op1 = fold_convert_loc (loc, type, TREE_OPERAND (aref1, 1));
9046       tree esz = fold_convert_loc (loc, type, array_ref_element_size (aref0));
9047       tree diff = build2 (MINUS_EXPR, type, op0, op1);
9048       return fold_build2_loc (loc, PLUS_EXPR, type,
9049                               base_offset,
9050                               fold_build2_loc (loc, MULT_EXPR, type,
9051                                                diff, esz));
9052     }
9053   return NULL_TREE;
9054 }
9055
9056 /* If the real or vector real constant CST of type TYPE has an exact
9057    inverse, return it, else return NULL.  */
9058
9059 tree
9060 exact_inverse (tree type, tree cst)
9061 {
9062   REAL_VALUE_TYPE r;
9063   tree unit_type, *elts;
9064   machine_mode mode;
9065   unsigned vec_nelts, i;
9066
9067   switch (TREE_CODE (cst))
9068     {
9069     case REAL_CST:
9070       r = TREE_REAL_CST (cst);
9071
9072       if (exact_real_inverse (TYPE_MODE (type), &r))
9073         return build_real (type, r);
9074
9075       return NULL_TREE;
9076
9077     case VECTOR_CST:
9078       vec_nelts = VECTOR_CST_NELTS (cst);
9079       elts = XALLOCAVEC (tree, vec_nelts);
9080       unit_type = TREE_TYPE (type);
9081       mode = TYPE_MODE (unit_type);
9082
9083       for (i = 0; i < vec_nelts; i++)
9084         {
9085           r = TREE_REAL_CST (VECTOR_CST_ELT (cst, i));
9086           if (!exact_real_inverse (mode, &r))
9087             return NULL_TREE;
9088           elts[i] = build_real (unit_type, r);
9089         }
9090
9091       return build_vector (type, elts);
9092
9093     default:
9094       return NULL_TREE;
9095     }
9096 }
9097
9098 /*  Mask out the tz least significant bits of X of type TYPE where
9099     tz is the number of trailing zeroes in Y.  */
9100 static wide_int
9101 mask_with_tz (tree type, const wide_int &x, const wide_int &y)
9102 {
9103   int tz = wi::ctz (y);
9104   if (tz > 0)
9105     return wi::mask (tz, true, TYPE_PRECISION (type)) & x;
9106   return x;
9107 }
9108
9109 /* Return true when T is an address and is known to be nonzero.
9110    For floating point we further ensure that T is not denormal.
9111    Similar logic is present in nonzero_address in rtlanal.h.
9112
9113    If the return value is based on the assumption that signed overflow
9114    is undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't
9115    change *STRICT_OVERFLOW_P.  */
9116
9117 static bool
9118 tree_expr_nonzero_warnv_p (tree t, bool *strict_overflow_p)
9119 {
9120   tree type = TREE_TYPE (t);
9121   enum tree_code code;
9122
9123   /* Doing something useful for floating point would need more work.  */
9124   if (!INTEGRAL_TYPE_P (type) && !POINTER_TYPE_P (type))
9125     return false;
9126
9127   code = TREE_CODE (t);
9128   switch (TREE_CODE_CLASS (code))
9129     {
9130     case tcc_unary:
9131       return tree_unary_nonzero_warnv_p (code, type, TREE_OPERAND (t, 0),
9132                                               strict_overflow_p);
9133     case tcc_binary:
9134     case tcc_comparison:
9135       return tree_binary_nonzero_warnv_p (code, type,
9136                                                TREE_OPERAND (t, 0),
9137                                                TREE_OPERAND (t, 1),
9138                                                strict_overflow_p);
9139     case tcc_constant:
9140     case tcc_declaration:
9141     case tcc_reference:
9142       return tree_single_nonzero_warnv_p (t, strict_overflow_p);
9143
9144     default:
9145       break;
9146     }
9147
9148   switch (code)
9149     {
9150     case TRUTH_NOT_EXPR:
9151       return tree_unary_nonzero_warnv_p (code, type, TREE_OPERAND (t, 0),
9152                                               strict_overflow_p);
9153
9154     case TRUTH_AND_EXPR:
9155     case TRUTH_OR_EXPR:
9156     case TRUTH_XOR_EXPR:
9157       return tree_binary_nonzero_warnv_p (code, type,
9158                                                TREE_OPERAND (t, 0),
9159                                                TREE_OPERAND (t, 1),
9160                                                strict_overflow_p);
9161
9162     case COND_EXPR:
9163     case CONSTRUCTOR:
9164     case OBJ_TYPE_REF:
9165     case ASSERT_EXPR:
9166     case ADDR_EXPR:
9167     case WITH_SIZE_EXPR:
9168     case SSA_NAME:
9169       return tree_single_nonzero_warnv_p (t, strict_overflow_p);
9170
9171     case COMPOUND_EXPR:
9172     case MODIFY_EXPR:
9173     case BIND_EXPR:
9174       return tree_expr_nonzero_warnv_p (TREE_OPERAND (t, 1),
9175                                         strict_overflow_p);
9176
9177     case SAVE_EXPR:
9178       return tree_expr_nonzero_warnv_p (TREE_OPERAND (t, 0),
9179                                         strict_overflow_p);
9180
9181     case CALL_EXPR:
9182       {
9183         tree fndecl = get_callee_fndecl (t);
9184         if (!fndecl) return false;
9185         if (flag_delete_null_pointer_checks && !flag_check_new
9186             && DECL_IS_OPERATOR_NEW (fndecl)
9187             && !TREE_NOTHROW (fndecl))
9188           return true;
9189         if (flag_delete_null_pointer_checks
9190             && lookup_attribute ("returns_nonnull",
9191                  TYPE_ATTRIBUTES (TREE_TYPE (fndecl))))
9192           return true;
9193         return alloca_call_p (t);
9194       }
9195
9196     default:
9197       break;
9198     }
9199   return false;
9200 }
9201
9202 /* Return true when T is an address and is known to be nonzero.
9203    Handle warnings about undefined signed overflow.  */
9204
9205 static bool
9206 tree_expr_nonzero_p (tree t)
9207 {
9208   bool ret, strict_overflow_p;
9209
9210   strict_overflow_p = false;
9211   ret = tree_expr_nonzero_warnv_p (t, &strict_overflow_p);
9212   if (strict_overflow_p)
9213     fold_overflow_warning (("assuming signed overflow does not occur when "
9214                             "determining that expression is always "
9215                             "non-zero"),
9216                            WARN_STRICT_OVERFLOW_MISC);
9217   return ret;
9218 }
9219
9220 /* Return true if T is known not to be equal to an integer W.  */
9221
9222 bool
9223 expr_not_equal_to (tree t, const wide_int &w)
9224 {
9225   wide_int min, max, nz;
9226   value_range_type rtype;
9227   switch (TREE_CODE (t))
9228     {
9229     case INTEGER_CST:
9230       return wi::ne_p (t, w);
9231
9232     case SSA_NAME:
9233       if (!INTEGRAL_TYPE_P (TREE_TYPE (t)))
9234         return false;
9235       rtype = get_range_info (t, &min, &max);
9236       if (rtype == VR_RANGE)
9237         {
9238           if (wi::lt_p (max, w, TYPE_SIGN (TREE_TYPE (t))))
9239             return true;
9240           if (wi::lt_p (w, min, TYPE_SIGN (TREE_TYPE (t))))
9241             return true;
9242         }
9243       else if (rtype == VR_ANTI_RANGE
9244                && wi::le_p (min, w, TYPE_SIGN (TREE_TYPE (t)))
9245                && wi::le_p (w, max, TYPE_SIGN (TREE_TYPE (t))))
9246         return true;
9247       /* If T has some known zero bits and W has any of those bits set,
9248          then T is known not to be equal to W.  */
9249       if (wi::ne_p (wi::zext (wi::bit_and_not (w, get_nonzero_bits (t)),
9250                               TYPE_PRECISION (TREE_TYPE (t))), 0))
9251         return true;
9252       return false;
9253
9254     default:
9255       return false;
9256     }
9257 }
9258
9259 /* Fold a binary expression of code CODE and type TYPE with operands
9260    OP0 and OP1.  LOC is the location of the resulting expression.
9261    Return the folded expression if folding is successful.  Otherwise,
9262    return NULL_TREE.  */
9263
9264 tree
9265 fold_binary_loc (location_t loc,
9266              enum tree_code code, tree type, tree op0, tree op1)
9267 {
9268   enum tree_code_class kind = TREE_CODE_CLASS (code);
9269   tree arg0, arg1, tem;
9270   tree t1 = NULL_TREE;
9271   bool strict_overflow_p;
9272   unsigned int prec;
9273
9274   gcc_assert (IS_EXPR_CODE_CLASS (kind)
9275               && TREE_CODE_LENGTH (code) == 2
9276               && op0 != NULL_TREE
9277               && op1 != NULL_TREE);
9278
9279   arg0 = op0;
9280   arg1 = op1;
9281
9282   /* Strip any conversions that don't change the mode.  This is
9283      safe for every expression, except for a comparison expression
9284      because its signedness is derived from its operands.  So, in
9285      the latter case, only strip conversions that don't change the
9286      signedness.  MIN_EXPR/MAX_EXPR also need signedness of arguments
9287      preserved.
9288
9289      Note that this is done as an internal manipulation within the
9290      constant folder, in order to find the simplest representation
9291      of the arguments so that their form can be studied.  In any
9292      cases, the appropriate type conversions should be put back in
9293      the tree that will get out of the constant folder.  */
9294
9295   if (kind == tcc_comparison || code == MIN_EXPR || code == MAX_EXPR)
9296     {
9297       STRIP_SIGN_NOPS (arg0);
9298       STRIP_SIGN_NOPS (arg1);
9299     }
9300   else
9301     {
9302       STRIP_NOPS (arg0);
9303       STRIP_NOPS (arg1);
9304     }
9305
9306   /* Note that TREE_CONSTANT isn't enough: static var addresses are
9307      constant but we can't do arithmetic on them.  */
9308   if (CONSTANT_CLASS_P (arg0) && CONSTANT_CLASS_P (arg1))
9309     {
9310       tem = const_binop (code, type, arg0, arg1);
9311       if (tem != NULL_TREE)
9312         {
9313           if (TREE_TYPE (tem) != type)
9314             tem = fold_convert_loc (loc, type, tem);
9315           return tem;
9316         }
9317     }
9318
9319   /* If this is a commutative operation, and ARG0 is a constant, move it
9320      to ARG1 to reduce the number of tests below.  */
9321   if (commutative_tree_code (code)
9322       && tree_swap_operands_p (arg0, arg1, true))
9323     return fold_build2_loc (loc, code, type, op1, op0);
9324
9325   /* Likewise if this is a comparison, and ARG0 is a constant, move it
9326      to ARG1 to reduce the number of tests below.  */
9327   if (kind == tcc_comparison
9328       && tree_swap_operands_p (arg0, arg1, true))
9329     return fold_build2_loc (loc, swap_tree_comparison (code), type, op1, op0);
9330
9331   tem = generic_simplify (loc, code, type, op0, op1);
9332   if (tem)
9333     return tem;
9334
9335   /* ARG0 is the first operand of EXPR, and ARG1 is the second operand.
9336
9337      First check for cases where an arithmetic operation is applied to a
9338      compound, conditional, or comparison operation.  Push the arithmetic
9339      operation inside the compound or conditional to see if any folding
9340      can then be done.  Convert comparison to conditional for this purpose.
9341      The also optimizes non-constant cases that used to be done in
9342      expand_expr.
9343
9344      Before we do that, see if this is a BIT_AND_EXPR or a BIT_IOR_EXPR,
9345      one of the operands is a comparison and the other is a comparison, a
9346      BIT_AND_EXPR with the constant 1, or a truth value.  In that case, the
9347      code below would make the expression more complex.  Change it to a
9348      TRUTH_{AND,OR}_EXPR.  Likewise, convert a similar NE_EXPR to
9349      TRUTH_XOR_EXPR and an EQ_EXPR to the inversion of a TRUTH_XOR_EXPR.  */
9350
9351   if ((code == BIT_AND_EXPR || code == BIT_IOR_EXPR
9352        || code == EQ_EXPR || code == NE_EXPR)
9353       && TREE_CODE (type) != VECTOR_TYPE
9354       && ((truth_value_p (TREE_CODE (arg0))
9355            && (truth_value_p (TREE_CODE (arg1))
9356                || (TREE_CODE (arg1) == BIT_AND_EXPR
9357                    && integer_onep (TREE_OPERAND (arg1, 1)))))
9358           || (truth_value_p (TREE_CODE (arg1))
9359               && (truth_value_p (TREE_CODE (arg0))
9360                   || (TREE_CODE (arg0) == BIT_AND_EXPR
9361                       && integer_onep (TREE_OPERAND (arg0, 1)))))))
9362     {
9363       tem = fold_build2_loc (loc, code == BIT_AND_EXPR ? TRUTH_AND_EXPR
9364                          : code == BIT_IOR_EXPR ? TRUTH_OR_EXPR
9365                          : TRUTH_XOR_EXPR,
9366                          boolean_type_node,
9367                          fold_convert_loc (loc, boolean_type_node, arg0),
9368                          fold_convert_loc (loc, boolean_type_node, arg1));
9369
9370       if (code == EQ_EXPR)
9371         tem = invert_truthvalue_loc (loc, tem);
9372
9373       return fold_convert_loc (loc, type, tem);
9374     }
9375
9376   if (TREE_CODE_CLASS (code) == tcc_binary
9377       || TREE_CODE_CLASS (code) == tcc_comparison)
9378     {
9379       if (TREE_CODE (arg0) == COMPOUND_EXPR)
9380         {
9381           tem = fold_build2_loc (loc, code, type,
9382                              fold_convert_loc (loc, TREE_TYPE (op0),
9383                                                TREE_OPERAND (arg0, 1)), op1);
9384           return build2_loc (loc, COMPOUND_EXPR, type, TREE_OPERAND (arg0, 0),
9385                              tem);
9386         }
9387       if (TREE_CODE (arg1) == COMPOUND_EXPR
9388           && reorder_operands_p (arg0, TREE_OPERAND (arg1, 0)))
9389         {
9390           tem = fold_build2_loc (loc, code, type, op0,
9391                              fold_convert_loc (loc, TREE_TYPE (op1),
9392                                                TREE_OPERAND (arg1, 1)));
9393           return build2_loc (loc, COMPOUND_EXPR, type, TREE_OPERAND (arg1, 0),
9394                              tem);
9395         }
9396
9397       if (TREE_CODE (arg0) == COND_EXPR
9398           || TREE_CODE (arg0) == VEC_COND_EXPR
9399           || COMPARISON_CLASS_P (arg0))
9400         {
9401           tem = fold_binary_op_with_conditional_arg (loc, code, type, op0, op1,
9402                                                      arg0, arg1,
9403                                                      /*cond_first_p=*/1);
9404           if (tem != NULL_TREE)
9405             return tem;
9406         }
9407
9408       if (TREE_CODE (arg1) == COND_EXPR
9409           || TREE_CODE (arg1) == VEC_COND_EXPR
9410           || COMPARISON_CLASS_P (arg1))
9411         {
9412           tem = fold_binary_op_with_conditional_arg (loc, code, type, op0, op1,
9413                                                      arg1, arg0,
9414                                                      /*cond_first_p=*/0);
9415           if (tem != NULL_TREE)
9416             return tem;
9417         }
9418     }
9419
9420   switch (code)
9421     {
9422     case MEM_REF:
9423       /* MEM[&MEM[p, CST1], CST2] -> MEM[p, CST1 + CST2].  */
9424       if (TREE_CODE (arg0) == ADDR_EXPR
9425           && TREE_CODE (TREE_OPERAND (arg0, 0)) == MEM_REF)
9426         {
9427           tree iref = TREE_OPERAND (arg0, 0);
9428           return fold_build2 (MEM_REF, type,
9429                               TREE_OPERAND (iref, 0),
9430                               int_const_binop (PLUS_EXPR, arg1,
9431                                                TREE_OPERAND (iref, 1)));
9432         }
9433
9434       /* MEM[&a.b, CST2] -> MEM[&a, offsetof (a, b) + CST2].  */
9435       if (TREE_CODE (arg0) == ADDR_EXPR
9436           && handled_component_p (TREE_OPERAND (arg0, 0)))
9437         {
9438           tree base;
9439           HOST_WIDE_INT coffset;
9440           base = get_addr_base_and_unit_offset (TREE_OPERAND (arg0, 0),
9441                                                 &coffset);
9442           if (!base)
9443             return NULL_TREE;
9444           return fold_build2 (MEM_REF, type,
9445                               build_fold_addr_expr (base),
9446                               int_const_binop (PLUS_EXPR, arg1,
9447                                                size_int (coffset)));
9448         }
9449
9450       return NULL_TREE;
9451
9452     case POINTER_PLUS_EXPR:
9453       /* INT +p INT -> (PTR)(INT + INT).  Stripping types allows for this. */
9454       if (INTEGRAL_TYPE_P (TREE_TYPE (arg1))
9455            && INTEGRAL_TYPE_P (TREE_TYPE (arg0)))
9456         return fold_convert_loc (loc, type,
9457                                  fold_build2_loc (loc, PLUS_EXPR, sizetype,
9458                                               fold_convert_loc (loc, sizetype,
9459                                                                 arg1),
9460                                               fold_convert_loc (loc, sizetype,
9461                                                                 arg0)));
9462
9463       return NULL_TREE;
9464
9465     case PLUS_EXPR:
9466       if (INTEGRAL_TYPE_P (type) || VECTOR_INTEGER_TYPE_P (type))
9467         {
9468           /* X + (X / CST) * -CST is X % CST.  */
9469           if (TREE_CODE (arg1) == MULT_EXPR
9470               && TREE_CODE (TREE_OPERAND (arg1, 0)) == TRUNC_DIV_EXPR
9471               && operand_equal_p (arg0,
9472                                   TREE_OPERAND (TREE_OPERAND (arg1, 0), 0), 0))
9473             {
9474               tree cst0 = TREE_OPERAND (TREE_OPERAND (arg1, 0), 1);
9475               tree cst1 = TREE_OPERAND (arg1, 1);
9476               tree sum = fold_binary_loc (loc, PLUS_EXPR, TREE_TYPE (cst1),
9477                                       cst1, cst0);
9478               if (sum && integer_zerop (sum))
9479                 return fold_convert_loc (loc, type,
9480                                          fold_build2_loc (loc, TRUNC_MOD_EXPR,
9481                                                       TREE_TYPE (arg0), arg0,
9482                                                       cst0));
9483             }
9484         }
9485
9486       /* Handle (A1 * C1) + (A2 * C2) with A1, A2 or C1, C2 being the same or
9487          one.  Make sure the type is not saturating and has the signedness of
9488          the stripped operands, as fold_plusminus_mult_expr will re-associate.
9489          ??? The latter condition should use TYPE_OVERFLOW_* flags instead.  */
9490       if ((TREE_CODE (arg0) == MULT_EXPR
9491            || TREE_CODE (arg1) == MULT_EXPR)
9492           && !TYPE_SATURATING (type)
9493           && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (TREE_TYPE (arg0))
9494           && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (TREE_TYPE (arg1))
9495           && (!FLOAT_TYPE_P (type) || flag_associative_math))
9496         {
9497           tree tem = fold_plusminus_mult_expr (loc, code, type, arg0, arg1);
9498           if (tem)
9499             return tem;
9500         }
9501
9502       if (! FLOAT_TYPE_P (type))
9503         {
9504           /* Reassociate (plus (plus (mult) (foo)) (mult)) as
9505              (plus (plus (mult) (mult)) (foo)) so that we can
9506              take advantage of the factoring cases below.  */
9507           if (ANY_INTEGRAL_TYPE_P (type)
9508               && TYPE_OVERFLOW_WRAPS (type)
9509               && (((TREE_CODE (arg0) == PLUS_EXPR
9510                     || TREE_CODE (arg0) == MINUS_EXPR)
9511                    && TREE_CODE (arg1) == MULT_EXPR)
9512                   || ((TREE_CODE (arg1) == PLUS_EXPR
9513                        || TREE_CODE (arg1) == MINUS_EXPR)
9514                       && TREE_CODE (arg0) == MULT_EXPR)))
9515             {
9516               tree parg0, parg1, parg, marg;
9517               enum tree_code pcode;
9518
9519               if (TREE_CODE (arg1) == MULT_EXPR)
9520                 parg = arg0, marg = arg1;
9521               else
9522                 parg = arg1, marg = arg0;
9523               pcode = TREE_CODE (parg);
9524               parg0 = TREE_OPERAND (parg, 0);
9525               parg1 = TREE_OPERAND (parg, 1);
9526               STRIP_NOPS (parg0);
9527               STRIP_NOPS (parg1);
9528
9529               if (TREE_CODE (parg0) == MULT_EXPR
9530                   && TREE_CODE (parg1) != MULT_EXPR)
9531                 return fold_build2_loc (loc, pcode, type,
9532                                     fold_build2_loc (loc, PLUS_EXPR, type,
9533                                                  fold_convert_loc (loc, type,
9534                                                                    parg0),
9535                                                  fold_convert_loc (loc, type,
9536                                                                    marg)),
9537                                     fold_convert_loc (loc, type, parg1));
9538               if (TREE_CODE (parg0) != MULT_EXPR
9539                   && TREE_CODE (parg1) == MULT_EXPR)
9540                 return
9541                   fold_build2_loc (loc, PLUS_EXPR, type,
9542                                fold_convert_loc (loc, type, parg0),
9543                                fold_build2_loc (loc, pcode, type,
9544                                             fold_convert_loc (loc, type, marg),
9545                                             fold_convert_loc (loc, type,
9546                                                               parg1)));
9547             }
9548         }
9549       else
9550         {
9551           /* Fold __complex__ ( x, 0 ) + __complex__ ( 0, y )
9552              to __complex__ ( x, y ).  This is not the same for SNaNs or
9553              if signed zeros are involved.  */
9554           if (!HONOR_SNANS (element_mode (arg0))
9555               && !HONOR_SIGNED_ZEROS (element_mode (arg0))
9556               && COMPLEX_FLOAT_TYPE_P (TREE_TYPE (arg0)))
9557             {
9558               tree rtype = TREE_TYPE (TREE_TYPE (arg0));
9559               tree arg0r = fold_unary_loc (loc, REALPART_EXPR, rtype, arg0);
9560               tree arg0i = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg0);
9561               bool arg0rz = false, arg0iz = false;
9562               if ((arg0r && (arg0rz = real_zerop (arg0r)))
9563                   || (arg0i && (arg0iz = real_zerop (arg0i))))
9564                 {
9565                   tree arg1r = fold_unary_loc (loc, REALPART_EXPR, rtype, arg1);
9566                   tree arg1i = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg1);
9567                   if (arg0rz && arg1i && real_zerop (arg1i))
9568                     {
9569                       tree rp = arg1r ? arg1r
9570                                   : build1 (REALPART_EXPR, rtype, arg1);
9571                       tree ip = arg0i ? arg0i
9572                                   : build1 (IMAGPART_EXPR, rtype, arg0);
9573                       return fold_build2_loc (loc, COMPLEX_EXPR, type, rp, ip);
9574                     }
9575                   else if (arg0iz && arg1r && real_zerop (arg1r))
9576                     {
9577                       tree rp = arg0r ? arg0r
9578                                   : build1 (REALPART_EXPR, rtype, arg0);
9579                       tree ip = arg1i ? arg1i
9580                                   : build1 (IMAGPART_EXPR, rtype, arg1);
9581                       return fold_build2_loc (loc, COMPLEX_EXPR, type, rp, ip);
9582                     }
9583                 }
9584             }
9585
9586           if (flag_unsafe_math_optimizations
9587               && (TREE_CODE (arg0) == RDIV_EXPR || TREE_CODE (arg0) == MULT_EXPR)
9588               && (TREE_CODE (arg1) == RDIV_EXPR || TREE_CODE (arg1) == MULT_EXPR)
9589               && (tem = distribute_real_division (loc, code, type, arg0, arg1)))
9590             return tem;
9591
9592           /* Convert a + (b*c + d*e) into (a + b*c) + d*e.
9593              We associate floats only if the user has specified
9594              -fassociative-math.  */
9595           if (flag_associative_math
9596               && TREE_CODE (arg1) == PLUS_EXPR
9597               && TREE_CODE (arg0) != MULT_EXPR)
9598             {
9599               tree tree10 = TREE_OPERAND (arg1, 0);
9600               tree tree11 = TREE_OPERAND (arg1, 1);
9601               if (TREE_CODE (tree11) == MULT_EXPR
9602                   && TREE_CODE (tree10) == MULT_EXPR)
9603                 {
9604                   tree tree0;
9605                   tree0 = fold_build2_loc (loc, PLUS_EXPR, type, arg0, tree10);
9606                   return fold_build2_loc (loc, PLUS_EXPR, type, tree0, tree11);
9607                 }
9608             }
9609           /* Convert (b*c + d*e) + a into b*c + (d*e +a).
9610              We associate floats only if the user has specified
9611              -fassociative-math.  */
9612           if (flag_associative_math
9613               && TREE_CODE (arg0) == PLUS_EXPR
9614               && TREE_CODE (arg1) != MULT_EXPR)
9615             {
9616               tree tree00 = TREE_OPERAND (arg0, 0);
9617               tree tree01 = TREE_OPERAND (arg0, 1);
9618               if (TREE_CODE (tree01) == MULT_EXPR
9619                   && TREE_CODE (tree00) == MULT_EXPR)
9620                 {
9621                   tree tree0;
9622                   tree0 = fold_build2_loc (loc, PLUS_EXPR, type, tree01, arg1);
9623                   return fold_build2_loc (loc, PLUS_EXPR, type, tree00, tree0);
9624                 }
9625             }
9626         }
9627
9628      bit_rotate:
9629       /* (A << C1) + (A >> C2) if A is unsigned and C1+C2 is the size of A
9630          is a rotate of A by C1 bits.  */
9631       /* (A << B) + (A >> (Z - B)) if A is unsigned and Z is the size of A
9632          is a rotate of A by B bits.  */
9633       {
9634         enum tree_code code0, code1;
9635         tree rtype;
9636         code0 = TREE_CODE (arg0);
9637         code1 = TREE_CODE (arg1);
9638         if (((code0 == RSHIFT_EXPR && code1 == LSHIFT_EXPR)
9639              || (code1 == RSHIFT_EXPR && code0 == LSHIFT_EXPR))
9640             && operand_equal_p (TREE_OPERAND (arg0, 0),
9641                                 TREE_OPERAND (arg1, 0), 0)
9642             && (rtype = TREE_TYPE (TREE_OPERAND (arg0, 0)),
9643                 TYPE_UNSIGNED (rtype))
9644             /* Only create rotates in complete modes.  Other cases are not
9645                expanded properly.  */
9646             && (element_precision (rtype)
9647                 == GET_MODE_UNIT_PRECISION (TYPE_MODE (rtype))))
9648           {
9649             tree tree01, tree11;
9650             enum tree_code code01, code11;
9651
9652             tree01 = TREE_OPERAND (arg0, 1);
9653             tree11 = TREE_OPERAND (arg1, 1);
9654             STRIP_NOPS (tree01);
9655             STRIP_NOPS (tree11);
9656             code01 = TREE_CODE (tree01);
9657             code11 = TREE_CODE (tree11);
9658             if (code01 == INTEGER_CST
9659                 && code11 == INTEGER_CST
9660                 && (wi::to_widest (tree01) + wi::to_widest (tree11)
9661                     == element_precision (TREE_TYPE (TREE_OPERAND (arg0, 0)))))
9662               {
9663                 tem = build2_loc (loc, LROTATE_EXPR,
9664                                   TREE_TYPE (TREE_OPERAND (arg0, 0)),
9665                                   TREE_OPERAND (arg0, 0),
9666                                   code0 == LSHIFT_EXPR
9667                                   ? TREE_OPERAND (arg0, 1)
9668                                   : TREE_OPERAND (arg1, 1));
9669                 return fold_convert_loc (loc, type, tem);
9670               }
9671             else if (code11 == MINUS_EXPR)
9672               {
9673                 tree tree110, tree111;
9674                 tree110 = TREE_OPERAND (tree11, 0);
9675                 tree111 = TREE_OPERAND (tree11, 1);
9676                 STRIP_NOPS (tree110);
9677                 STRIP_NOPS (tree111);
9678                 if (TREE_CODE (tree110) == INTEGER_CST
9679                     && 0 == compare_tree_int (tree110,
9680                                               element_precision
9681                                               (TREE_TYPE (TREE_OPERAND
9682                                                           (arg0, 0))))
9683                     && operand_equal_p (tree01, tree111, 0))
9684                   return
9685                     fold_convert_loc (loc, type,
9686                                       build2 ((code0 == LSHIFT_EXPR
9687                                                ? LROTATE_EXPR
9688                                                : RROTATE_EXPR),
9689                                               TREE_TYPE (TREE_OPERAND (arg0, 0)),
9690                                               TREE_OPERAND (arg0, 0),
9691                                               TREE_OPERAND (arg0, 1)));
9692               }
9693             else if (code01 == MINUS_EXPR)
9694               {
9695                 tree tree010, tree011;
9696                 tree010 = TREE_OPERAND (tree01, 0);
9697                 tree011 = TREE_OPERAND (tree01, 1);
9698                 STRIP_NOPS (tree010);
9699                 STRIP_NOPS (tree011);
9700                 if (TREE_CODE (tree010) == INTEGER_CST
9701                     && 0 == compare_tree_int (tree010,
9702                                               element_precision
9703                                               (TREE_TYPE (TREE_OPERAND
9704                                                           (arg0, 0))))
9705                     && operand_equal_p (tree11, tree011, 0))
9706                     return fold_convert_loc
9707                       (loc, type,
9708                        build2 ((code0 != LSHIFT_EXPR
9709                                 ? LROTATE_EXPR
9710                                 : RROTATE_EXPR),
9711                                TREE_TYPE (TREE_OPERAND (arg0, 0)),
9712                                TREE_OPERAND (arg0, 0), TREE_OPERAND (arg1, 1)));
9713               }
9714           }
9715       }
9716
9717     associate:
9718       /* In most languages, can't associate operations on floats through
9719          parentheses.  Rather than remember where the parentheses were, we
9720          don't associate floats at all, unless the user has specified
9721          -fassociative-math.
9722          And, we need to make sure type is not saturating.  */
9723
9724       if ((! FLOAT_TYPE_P (type) || flag_associative_math)
9725           && !TYPE_SATURATING (type))
9726         {
9727           tree var0, con0, lit0, minus_lit0;
9728           tree var1, con1, lit1, minus_lit1;
9729           tree atype = type;
9730           bool ok = true;
9731
9732           /* Split both trees into variables, constants, and literals.  Then
9733              associate each group together, the constants with literals,
9734              then the result with variables.  This increases the chances of
9735              literals being recombined later and of generating relocatable
9736              expressions for the sum of a constant and literal.  */
9737           var0 = split_tree (loc, arg0, type, code,
9738                              &con0, &lit0, &minus_lit0, 0);
9739           var1 = split_tree (loc, arg1, type, code,
9740                              &con1, &lit1, &minus_lit1, code == MINUS_EXPR);
9741
9742           /* Recombine MINUS_EXPR operands by using PLUS_EXPR.  */
9743           if (code == MINUS_EXPR)
9744             code = PLUS_EXPR;
9745
9746           /* With undefined overflow prefer doing association in a type
9747              which wraps on overflow, if that is one of the operand types.  */
9748           if ((POINTER_TYPE_P (type) && POINTER_TYPE_OVERFLOW_UNDEFINED)
9749               || (INTEGRAL_TYPE_P (type) && !TYPE_OVERFLOW_WRAPS (type)))
9750             {
9751               if (INTEGRAL_TYPE_P (TREE_TYPE (arg0))
9752                   && TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg0)))
9753                 atype = TREE_TYPE (arg0);
9754               else if (INTEGRAL_TYPE_P (TREE_TYPE (arg1))
9755                        && TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg1)))
9756                 atype = TREE_TYPE (arg1);
9757               gcc_assert (TYPE_PRECISION (atype) == TYPE_PRECISION (type));
9758             }
9759
9760           /* With undefined overflow we can only associate constants with one
9761              variable, and constants whose association doesn't overflow.  */
9762           if ((POINTER_TYPE_P (atype) && POINTER_TYPE_OVERFLOW_UNDEFINED)
9763               || (INTEGRAL_TYPE_P (atype) && !TYPE_OVERFLOW_WRAPS (atype)))
9764             {
9765               if (var0 && var1)
9766                 {
9767                   tree tmp0 = var0;
9768                   tree tmp1 = var1;
9769                   bool one_neg = false;
9770
9771                   if (TREE_CODE (tmp0) == NEGATE_EXPR)
9772                     {
9773                       tmp0 = TREE_OPERAND (tmp0, 0);
9774                       one_neg = !one_neg;
9775                     }
9776                   if (CONVERT_EXPR_P (tmp0)
9777                       && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (tmp0, 0)))
9778                       && (TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (tmp0, 0)))
9779                           <= TYPE_PRECISION (atype)))
9780                     tmp0 = TREE_OPERAND (tmp0, 0);
9781                   if (TREE_CODE (tmp1) == NEGATE_EXPR)
9782                     {
9783                       tmp1 = TREE_OPERAND (tmp1, 0);
9784                       one_neg = !one_neg;
9785                     }
9786                   if (CONVERT_EXPR_P (tmp1)
9787                       && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (tmp1, 0)))
9788                       && (TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (tmp1, 0)))
9789                           <= TYPE_PRECISION (atype)))
9790                     tmp1 = TREE_OPERAND (tmp1, 0);
9791                   /* The only case we can still associate with two variables
9792                      is if they cancel out.  */
9793                   if (!one_neg
9794                       || !operand_equal_p (tmp0, tmp1, 0))
9795                     ok = false;
9796                 }
9797             }
9798
9799           /* Only do something if we found more than two objects.  Otherwise,
9800              nothing has changed and we risk infinite recursion.  */
9801           if (ok
9802               && (2 < ((var0 != 0) + (var1 != 0)
9803                        + (con0 != 0) + (con1 != 0)
9804                        + (lit0 != 0) + (lit1 != 0)
9805                        + (minus_lit0 != 0) + (minus_lit1 != 0))))
9806             {
9807               bool any_overflows = false;
9808               if (lit0) any_overflows |= TREE_OVERFLOW (lit0);
9809               if (lit1) any_overflows |= TREE_OVERFLOW (lit1);
9810               if (minus_lit0) any_overflows |= TREE_OVERFLOW (minus_lit0);
9811               if (minus_lit1) any_overflows |= TREE_OVERFLOW (minus_lit1);
9812               var0 = associate_trees (loc, var0, var1, code, atype);
9813               con0 = associate_trees (loc, con0, con1, code, atype);
9814               lit0 = associate_trees (loc, lit0, lit1, code, atype);
9815               minus_lit0 = associate_trees (loc, minus_lit0, minus_lit1,
9816                                             code, atype);
9817
9818               /* Preserve the MINUS_EXPR if the negative part of the literal is
9819                  greater than the positive part.  Otherwise, the multiplicative
9820                  folding code (i.e extract_muldiv) may be fooled in case
9821                  unsigned constants are subtracted, like in the following
9822                  example: ((X*2 + 4) - 8U)/2.  */
9823               if (minus_lit0 && lit0)
9824                 {
9825                   if (TREE_CODE (lit0) == INTEGER_CST
9826                       && TREE_CODE (minus_lit0) == INTEGER_CST
9827                       && tree_int_cst_lt (lit0, minus_lit0))
9828                     {
9829                       minus_lit0 = associate_trees (loc, minus_lit0, lit0,
9830                                                     MINUS_EXPR, atype);
9831                       lit0 = 0;
9832                     }
9833                   else
9834                     {
9835                       lit0 = associate_trees (loc, lit0, minus_lit0,
9836                                               MINUS_EXPR, atype);
9837                       minus_lit0 = 0;
9838                     }
9839                 }
9840
9841               /* Don't introduce overflows through reassociation.  */
9842               if (!any_overflows
9843                   && ((lit0 && TREE_OVERFLOW_P (lit0))
9844                       || (minus_lit0 && TREE_OVERFLOW_P (minus_lit0))))
9845                 return NULL_TREE;
9846
9847               if (minus_lit0)
9848                 {
9849                   if (con0 == 0)
9850                     return
9851                       fold_convert_loc (loc, type,
9852                                         associate_trees (loc, var0, minus_lit0,
9853                                                          MINUS_EXPR, atype));
9854                   else
9855                     {
9856                       con0 = associate_trees (loc, con0, minus_lit0,
9857                                               MINUS_EXPR, atype);
9858                       return
9859                         fold_convert_loc (loc, type,
9860                                           associate_trees (loc, var0, con0,
9861                                                            PLUS_EXPR, atype));
9862                     }
9863                 }
9864
9865               con0 = associate_trees (loc, con0, lit0, code, atype);
9866               return
9867                 fold_convert_loc (loc, type, associate_trees (loc, var0, con0,
9868                                                               code, atype));
9869             }
9870         }
9871
9872       return NULL_TREE;
9873
9874     case MINUS_EXPR:
9875       /* (-A) - B -> (-B) - A  where B is easily negated and we can swap.  */
9876       if (TREE_CODE (arg0) == NEGATE_EXPR
9877           && negate_expr_p (op1)
9878           && reorder_operands_p (arg0, arg1))
9879         return fold_build2_loc (loc, MINUS_EXPR, type,
9880                                 negate_expr (op1),
9881                                 fold_convert_loc (loc, type,
9882                                                   TREE_OPERAND (arg0, 0)));
9883
9884       /* Fold __complex__ ( x, 0 ) - __complex__ ( 0, y ) to
9885          __complex__ ( x, -y ).  This is not the same for SNaNs or if
9886          signed zeros are involved.  */
9887       if (!HONOR_SNANS (element_mode (arg0))
9888           && !HONOR_SIGNED_ZEROS (element_mode (arg0))
9889           && COMPLEX_FLOAT_TYPE_P (TREE_TYPE (arg0)))
9890         {
9891           tree rtype = TREE_TYPE (TREE_TYPE (arg0));
9892           tree arg0r = fold_unary_loc (loc, REALPART_EXPR, rtype, arg0);
9893           tree arg0i = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg0);
9894           bool arg0rz = false, arg0iz = false;
9895           if ((arg0r && (arg0rz = real_zerop (arg0r)))
9896               || (arg0i && (arg0iz = real_zerop (arg0i))))
9897             {
9898               tree arg1r = fold_unary_loc (loc, REALPART_EXPR, rtype, arg1);
9899               tree arg1i = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg1);
9900               if (arg0rz && arg1i && real_zerop (arg1i))
9901                 {
9902                   tree rp = fold_build1_loc (loc, NEGATE_EXPR, rtype,
9903                                          arg1r ? arg1r
9904                                          : build1 (REALPART_EXPR, rtype, arg1));
9905                   tree ip = arg0i ? arg0i
9906                     : build1 (IMAGPART_EXPR, rtype, arg0);
9907                   return fold_build2_loc (loc, COMPLEX_EXPR, type, rp, ip);
9908                 }
9909               else if (arg0iz && arg1r && real_zerop (arg1r))
9910                 {
9911                   tree rp = arg0r ? arg0r
9912                     : build1 (REALPART_EXPR, rtype, arg0);
9913                   tree ip = fold_build1_loc (loc, NEGATE_EXPR, rtype,
9914                                          arg1i ? arg1i
9915                                          : build1 (IMAGPART_EXPR, rtype, arg1));
9916                   return fold_build2_loc (loc, COMPLEX_EXPR, type, rp, ip);
9917                 }
9918             }
9919         }
9920
9921       /* A - B -> A + (-B) if B is easily negatable.  */
9922       if (negate_expr_p (op1)
9923           && ! TYPE_OVERFLOW_SANITIZED (type)
9924           && ((FLOAT_TYPE_P (type)
9925                /* Avoid this transformation if B is a positive REAL_CST.  */
9926                && (TREE_CODE (op1) != REAL_CST
9927                    || REAL_VALUE_NEGATIVE (TREE_REAL_CST (op1))))
9928               || INTEGRAL_TYPE_P (type)))
9929         return fold_build2_loc (loc, PLUS_EXPR, type,
9930                                 fold_convert_loc (loc, type, arg0),
9931                                 negate_expr (op1));
9932
9933       /* Fold &a[i] - &a[j] to i-j.  */
9934       if (TREE_CODE (arg0) == ADDR_EXPR
9935           && TREE_CODE (TREE_OPERAND (arg0, 0)) == ARRAY_REF
9936           && TREE_CODE (arg1) == ADDR_EXPR
9937           && TREE_CODE (TREE_OPERAND (arg1, 0)) == ARRAY_REF)
9938         {
9939           tree tem = fold_addr_of_array_ref_difference (loc, type,
9940                                                         TREE_OPERAND (arg0, 0),
9941                                                         TREE_OPERAND (arg1, 0));
9942           if (tem)
9943             return tem;
9944         }
9945
9946       if (FLOAT_TYPE_P (type)
9947           && flag_unsafe_math_optimizations
9948           && (TREE_CODE (arg0) == RDIV_EXPR || TREE_CODE (arg0) == MULT_EXPR)
9949           && (TREE_CODE (arg1) == RDIV_EXPR || TREE_CODE (arg1) == MULT_EXPR)
9950           && (tem = distribute_real_division (loc, code, type, arg0, arg1)))
9951         return tem;
9952
9953       /* Handle (A1 * C1) - (A2 * C2) with A1, A2 or C1, C2 being the same or
9954          one.  Make sure the type is not saturating and has the signedness of
9955          the stripped operands, as fold_plusminus_mult_expr will re-associate.
9956          ??? The latter condition should use TYPE_OVERFLOW_* flags instead.  */
9957       if ((TREE_CODE (arg0) == MULT_EXPR
9958            || TREE_CODE (arg1) == MULT_EXPR)
9959           && !TYPE_SATURATING (type)
9960           && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (TREE_TYPE (arg0))
9961           && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (TREE_TYPE (arg1))
9962           && (!FLOAT_TYPE_P (type) || flag_associative_math))
9963         {
9964           tree tem = fold_plusminus_mult_expr (loc, code, type, arg0, arg1);
9965           if (tem)
9966             return tem;
9967         }
9968
9969       goto associate;
9970
9971     case MULT_EXPR:
9972       if (! FLOAT_TYPE_P (type))
9973         {
9974           /* Transform x * -C into -x * C if x is easily negatable.  */
9975           if (TREE_CODE (op1) == INTEGER_CST
9976               && tree_int_cst_sgn (op1) == -1
9977               && negate_expr_p (op0)
9978               && (tem = negate_expr (op1)) != op1
9979               && ! TREE_OVERFLOW (tem))
9980             return fold_build2_loc (loc, MULT_EXPR, type,
9981                                     fold_convert_loc (loc, type,
9982                                                       negate_expr (op0)), tem);
9983
9984           /* (A + A) * C -> A * 2 * C  */
9985           if (TREE_CODE (arg0) == PLUS_EXPR
9986               && TREE_CODE (arg1) == INTEGER_CST
9987               && operand_equal_p (TREE_OPERAND (arg0, 0),
9988                                   TREE_OPERAND (arg0, 1), 0))
9989             return fold_build2_loc (loc, MULT_EXPR, type,
9990                                 omit_one_operand_loc (loc, type,
9991                                                   TREE_OPERAND (arg0, 0),
9992                                                   TREE_OPERAND (arg0, 1)),
9993                                 fold_build2_loc (loc, MULT_EXPR, type,
9994                                              build_int_cst (type, 2) , arg1));
9995
9996           /* ((T) (X /[ex] C)) * C cancels out if the conversion is
9997              sign-changing only.  */
9998           if (TREE_CODE (arg1) == INTEGER_CST
9999               && TREE_CODE (arg0) == EXACT_DIV_EXPR
10000               && operand_equal_p (arg1, TREE_OPERAND (arg0, 1), 0))
10001             return fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
10002
10003           strict_overflow_p = false;
10004           if (TREE_CODE (arg1) == INTEGER_CST
10005               && 0 != (tem = extract_muldiv (op0, arg1, code, NULL_TREE,
10006                                              &strict_overflow_p)))
10007             {
10008               if (strict_overflow_p)
10009                 fold_overflow_warning (("assuming signed overflow does not "
10010                                         "occur when simplifying "
10011                                         "multiplication"),
10012                                        WARN_STRICT_OVERFLOW_MISC);
10013               return fold_convert_loc (loc, type, tem);
10014             }
10015
10016           /* Optimize z * conj(z) for integer complex numbers.  */
10017           if (TREE_CODE (arg0) == CONJ_EXPR
10018               && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
10019             return fold_mult_zconjz (loc, type, arg1);
10020           if (TREE_CODE (arg1) == CONJ_EXPR
10021               && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
10022             return fold_mult_zconjz (loc, type, arg0);
10023         }
10024       else
10025         {
10026           /* Fold z * +-I to __complex__ (-+__imag z, +-__real z).
10027              This is not the same for NaNs or if signed zeros are
10028              involved.  */
10029           if (!HONOR_NANS (arg0)
10030               && !HONOR_SIGNED_ZEROS (element_mode (arg0))
10031               && COMPLEX_FLOAT_TYPE_P (TREE_TYPE (arg0))
10032               && TREE_CODE (arg1) == COMPLEX_CST
10033               && real_zerop (TREE_REALPART (arg1)))
10034             {
10035               tree rtype = TREE_TYPE (TREE_TYPE (arg0));
10036               if (real_onep (TREE_IMAGPART (arg1)))
10037                 return
10038                   fold_build2_loc (loc, COMPLEX_EXPR, type,
10039                                negate_expr (fold_build1_loc (loc, IMAGPART_EXPR,
10040                                                              rtype, arg0)),
10041                                fold_build1_loc (loc, REALPART_EXPR, rtype, arg0));
10042               else if (real_minus_onep (TREE_IMAGPART (arg1)))
10043                 return
10044                   fold_build2_loc (loc, COMPLEX_EXPR, type,
10045                                fold_build1_loc (loc, IMAGPART_EXPR, rtype, arg0),
10046                                negate_expr (fold_build1_loc (loc, REALPART_EXPR,
10047                                                              rtype, arg0)));
10048             }
10049
10050           /* Optimize z * conj(z) for floating point complex numbers.
10051              Guarded by flag_unsafe_math_optimizations as non-finite
10052              imaginary components don't produce scalar results.  */
10053           if (flag_unsafe_math_optimizations
10054               && TREE_CODE (arg0) == CONJ_EXPR
10055               && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
10056             return fold_mult_zconjz (loc, type, arg1);
10057           if (flag_unsafe_math_optimizations
10058               && TREE_CODE (arg1) == CONJ_EXPR
10059               && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
10060             return fold_mult_zconjz (loc, type, arg0);
10061
10062           if (flag_unsafe_math_optimizations)
10063             {
10064
10065               /* Canonicalize x*x as pow(x,2.0), which is expanded as x*x.  */
10066               if (!in_gimple_form
10067                   && optimize
10068                   && operand_equal_p (arg0, arg1, 0))
10069                 {
10070                   tree powfn = mathfn_built_in (type, BUILT_IN_POW);
10071
10072                   if (powfn)
10073                     {
10074                       tree arg = build_real (type, dconst2);
10075                       return build_call_expr_loc (loc, powfn, 2, arg0, arg);
10076                     }
10077                 }
10078             }
10079         }
10080       goto associate;
10081
10082     case BIT_IOR_EXPR:
10083       /* Canonicalize (X & C1) | C2.  */
10084       if (TREE_CODE (arg0) == BIT_AND_EXPR
10085           && TREE_CODE (arg1) == INTEGER_CST
10086           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
10087         {
10088           int width = TYPE_PRECISION (type), w;
10089           wide_int c1 = TREE_OPERAND (arg0, 1);
10090           wide_int c2 = arg1;
10091
10092           /* If (C1&C2) == C1, then (X&C1)|C2 becomes (X,C2).  */
10093           if ((c1 & c2) == c1)
10094             return omit_one_operand_loc (loc, type, arg1,
10095                                          TREE_OPERAND (arg0, 0));
10096
10097           wide_int msk = wi::mask (width, false,
10098                                    TYPE_PRECISION (TREE_TYPE (arg1)));
10099
10100           /* If (C1|C2) == ~0 then (X&C1)|C2 becomes X|C2.  */
10101           if (msk.and_not (c1 | c2) == 0)
10102             return fold_build2_loc (loc, BIT_IOR_EXPR, type,
10103                                     TREE_OPERAND (arg0, 0), arg1);
10104
10105           /* Minimize the number of bits set in C1, i.e. C1 := C1 & ~C2,
10106              unless (C1 & ~C2) | (C2 & C3) for some C3 is a mask of some
10107              mode which allows further optimizations.  */
10108           c1 &= msk;
10109           c2 &= msk;
10110           wide_int c3 = c1.and_not (c2);
10111           for (w = BITS_PER_UNIT; w <= width; w <<= 1)
10112             {
10113               wide_int mask = wi::mask (w, false,
10114                                         TYPE_PRECISION (type));
10115               if (((c1 | c2) & mask) == mask && c1.and_not (mask) == 0)
10116                 {
10117                   c3 = mask;
10118                   break;
10119                 }
10120             }
10121
10122           if (c3 != c1)
10123             return fold_build2_loc (loc, BIT_IOR_EXPR, type,
10124                                     fold_build2_loc (loc, BIT_AND_EXPR, type,
10125                                                      TREE_OPERAND (arg0, 0),
10126                                                      wide_int_to_tree (type,
10127                                                                        c3)),
10128                                     arg1);
10129         }
10130
10131       /* See if this can be simplified into a rotate first.  If that
10132          is unsuccessful continue in the association code.  */
10133       goto bit_rotate;
10134
10135     case BIT_XOR_EXPR:
10136       /* Fold (X & 1) ^ 1 as (X & 1) == 0.  */
10137       if (TREE_CODE (arg0) == BIT_AND_EXPR
10138           && INTEGRAL_TYPE_P (type)
10139           && integer_onep (TREE_OPERAND (arg0, 1))
10140           && integer_onep (arg1))
10141         return fold_build2_loc (loc, EQ_EXPR, type, arg0,
10142                                 build_zero_cst (TREE_TYPE (arg0)));
10143
10144       /* See if this can be simplified into a rotate first.  If that
10145          is unsuccessful continue in the association code.  */
10146       goto bit_rotate;
10147
10148     case BIT_AND_EXPR:
10149       /* Fold (X ^ 1) & 1 as (X & 1) == 0.  */
10150       if (TREE_CODE (arg0) == BIT_XOR_EXPR
10151           && INTEGRAL_TYPE_P (type)
10152           && integer_onep (TREE_OPERAND (arg0, 1))
10153           && integer_onep (arg1))
10154         {
10155           tree tem2;
10156           tem = TREE_OPERAND (arg0, 0);
10157           tem2 = fold_convert_loc (loc, TREE_TYPE (tem), arg1);
10158           tem2 = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (tem),
10159                                   tem, tem2);
10160           return fold_build2_loc (loc, EQ_EXPR, type, tem2,
10161                                   build_zero_cst (TREE_TYPE (tem)));
10162         }
10163       /* Fold ~X & 1 as (X & 1) == 0.  */
10164       if (TREE_CODE (arg0) == BIT_NOT_EXPR
10165           && INTEGRAL_TYPE_P (type)
10166           && integer_onep (arg1))
10167         {
10168           tree tem2;
10169           tem = TREE_OPERAND (arg0, 0);
10170           tem2 = fold_convert_loc (loc, TREE_TYPE (tem), arg1);
10171           tem2 = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (tem),
10172                                   tem, tem2);
10173           return fold_build2_loc (loc, EQ_EXPR, type, tem2,
10174                                   build_zero_cst (TREE_TYPE (tem)));
10175         }
10176       /* Fold !X & 1 as X == 0.  */
10177       if (TREE_CODE (arg0) == TRUTH_NOT_EXPR
10178           && integer_onep (arg1))
10179         {
10180           tem = TREE_OPERAND (arg0, 0);
10181           return fold_build2_loc (loc, EQ_EXPR, type, tem,
10182                                   build_zero_cst (TREE_TYPE (tem)));
10183         }
10184
10185       /* Fold (X ^ Y) & Y as ~X & Y.  */
10186       if (TREE_CODE (arg0) == BIT_XOR_EXPR
10187           && operand_equal_p (TREE_OPERAND (arg0, 1), arg1, 0))
10188         {
10189           tem = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
10190           return fold_build2_loc (loc, BIT_AND_EXPR, type,
10191                               fold_build1_loc (loc, BIT_NOT_EXPR, type, tem),
10192                               fold_convert_loc (loc, type, arg1));
10193         }
10194       /* Fold (X ^ Y) & X as ~Y & X.  */
10195       if (TREE_CODE (arg0) == BIT_XOR_EXPR
10196           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0)
10197           && reorder_operands_p (TREE_OPERAND (arg0, 1), arg1))
10198         {
10199           tem = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 1));
10200           return fold_build2_loc (loc, BIT_AND_EXPR, type,
10201                               fold_build1_loc (loc, BIT_NOT_EXPR, type, tem),
10202                               fold_convert_loc (loc, type, arg1));
10203         }
10204       /* Fold X & (X ^ Y) as X & ~Y.  */
10205       if (TREE_CODE (arg1) == BIT_XOR_EXPR
10206           && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
10207         {
10208           tem = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 1));
10209           return fold_build2_loc (loc, BIT_AND_EXPR, type,
10210                               fold_convert_loc (loc, type, arg0),
10211                               fold_build1_loc (loc, BIT_NOT_EXPR, type, tem));
10212         }
10213       /* Fold X & (Y ^ X) as ~Y & X.  */
10214       if (TREE_CODE (arg1) == BIT_XOR_EXPR
10215           && operand_equal_p (arg0, TREE_OPERAND (arg1, 1), 0)
10216           && reorder_operands_p (arg0, TREE_OPERAND (arg1, 0)))
10217         {
10218           tem = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 0));
10219           return fold_build2_loc (loc, BIT_AND_EXPR, type,
10220                               fold_build1_loc (loc, BIT_NOT_EXPR, type, tem),
10221                               fold_convert_loc (loc, type, arg0));
10222         }
10223
10224       /* Fold (X * Y) & -(1 << CST) to X * Y if Y is a constant
10225          multiple of 1 << CST.  */
10226       if (TREE_CODE (arg1) == INTEGER_CST)
10227         {
10228           wide_int cst1 = arg1;
10229           wide_int ncst1 = -cst1;
10230           if ((cst1 & ncst1) == ncst1
10231               && multiple_of_p (type, arg0,
10232                                 wide_int_to_tree (TREE_TYPE (arg1), ncst1)))
10233             return fold_convert_loc (loc, type, arg0);
10234         }
10235
10236       /* Fold (X * CST1) & CST2 to zero if we can, or drop known zero
10237          bits from CST2.  */
10238       if (TREE_CODE (arg1) == INTEGER_CST
10239           && TREE_CODE (arg0) == MULT_EXPR
10240           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
10241         {
10242           wide_int warg1 = arg1;
10243           wide_int masked = mask_with_tz (type, warg1, TREE_OPERAND (arg0, 1));
10244
10245           if (masked == 0)
10246             return omit_two_operands_loc (loc, type, build_zero_cst (type),
10247                                           arg0, arg1);
10248           else if (masked != warg1)
10249             {
10250               /* Avoid the transform if arg1 is a mask of some
10251                  mode which allows further optimizations.  */
10252               int pop = wi::popcount (warg1);
10253               if (!(pop >= BITS_PER_UNIT
10254                     && exact_log2 (pop) != -1
10255                     && wi::mask (pop, false, warg1.get_precision ()) == warg1))
10256                 return fold_build2_loc (loc, code, type, op0,
10257                                         wide_int_to_tree (type, masked));
10258             }
10259         }
10260
10261       /* For constants M and N, if M == (1LL << cst) - 1 && (N & M) == M,
10262          ((A & N) + B) & M -> (A + B) & M
10263          Similarly if (N & M) == 0,
10264          ((A | N) + B) & M -> (A + B) & M
10265          and for - instead of + (or unary - instead of +)
10266          and/or ^ instead of |.
10267          If B is constant and (B & M) == 0, fold into A & M.  */
10268       if (TREE_CODE (arg1) == INTEGER_CST)
10269         {
10270           wide_int cst1 = arg1;
10271           if ((~cst1 != 0) && (cst1 & (cst1 + 1)) == 0
10272               && INTEGRAL_TYPE_P (TREE_TYPE (arg0))
10273               && (TREE_CODE (arg0) == PLUS_EXPR
10274                   || TREE_CODE (arg0) == MINUS_EXPR
10275                   || TREE_CODE (arg0) == NEGATE_EXPR)
10276               && (TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg0))
10277                   || TREE_CODE (TREE_TYPE (arg0)) == INTEGER_TYPE))
10278             {
10279               tree pmop[2];
10280               int which = 0;
10281               wide_int cst0;
10282
10283               /* Now we know that arg0 is (C + D) or (C - D) or
10284                  -C and arg1 (M) is == (1LL << cst) - 1.
10285                  Store C into PMOP[0] and D into PMOP[1].  */
10286               pmop[0] = TREE_OPERAND (arg0, 0);
10287               pmop[1] = NULL;
10288               if (TREE_CODE (arg0) != NEGATE_EXPR)
10289                 {
10290                   pmop[1] = TREE_OPERAND (arg0, 1);
10291                   which = 1;
10292                 }
10293
10294               if ((wi::max_value (TREE_TYPE (arg0)) & cst1) != cst1)
10295                 which = -1;
10296
10297               for (; which >= 0; which--)
10298                 switch (TREE_CODE (pmop[which]))
10299                   {
10300                   case BIT_AND_EXPR:
10301                   case BIT_IOR_EXPR:
10302                   case BIT_XOR_EXPR:
10303                     if (TREE_CODE (TREE_OPERAND (pmop[which], 1))
10304                         != INTEGER_CST)
10305                       break;
10306                     cst0 = TREE_OPERAND (pmop[which], 1);
10307                     cst0 &= cst1;
10308                     if (TREE_CODE (pmop[which]) == BIT_AND_EXPR)
10309                       {
10310                         if (cst0 != cst1)
10311                           break;
10312                       }
10313                     else if (cst0 != 0)
10314                       break;
10315                     /* If C or D is of the form (A & N) where
10316                        (N & M) == M, or of the form (A | N) or
10317                        (A ^ N) where (N & M) == 0, replace it with A.  */
10318                     pmop[which] = TREE_OPERAND (pmop[which], 0);
10319                     break;
10320                   case INTEGER_CST:
10321                     /* If C or D is a N where (N & M) == 0, it can be
10322                        omitted (assumed 0).  */
10323                     if ((TREE_CODE (arg0) == PLUS_EXPR
10324                          || (TREE_CODE (arg0) == MINUS_EXPR && which == 0))
10325                         && (cst1 & pmop[which]) == 0)
10326                       pmop[which] = NULL;
10327                     break;
10328                   default:
10329                     break;
10330                   }
10331
10332               /* Only build anything new if we optimized one or both arguments
10333                  above.  */
10334               if (pmop[0] != TREE_OPERAND (arg0, 0)
10335                   || (TREE_CODE (arg0) != NEGATE_EXPR
10336                       && pmop[1] != TREE_OPERAND (arg0, 1)))
10337                 {
10338                   tree utype = TREE_TYPE (arg0);
10339                   if (! TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg0)))
10340                     {
10341                       /* Perform the operations in a type that has defined
10342                          overflow behavior.  */
10343                       utype = unsigned_type_for (TREE_TYPE (arg0));
10344                       if (pmop[0] != NULL)
10345                         pmop[0] = fold_convert_loc (loc, utype, pmop[0]);
10346                       if (pmop[1] != NULL)
10347                         pmop[1] = fold_convert_loc (loc, utype, pmop[1]);
10348                     }
10349
10350                   if (TREE_CODE (arg0) == NEGATE_EXPR)
10351                     tem = fold_build1_loc (loc, NEGATE_EXPR, utype, pmop[0]);
10352                   else if (TREE_CODE (arg0) == PLUS_EXPR)
10353                     {
10354                       if (pmop[0] != NULL && pmop[1] != NULL)
10355                         tem = fold_build2_loc (loc, PLUS_EXPR, utype,
10356                                                pmop[0], pmop[1]);
10357                       else if (pmop[0] != NULL)
10358                         tem = pmop[0];
10359                       else if (pmop[1] != NULL)
10360                         tem = pmop[1];
10361                       else
10362                         return build_int_cst (type, 0);
10363                     }
10364                   else if (pmop[0] == NULL)
10365                     tem = fold_build1_loc (loc, NEGATE_EXPR, utype, pmop[1]);
10366                   else
10367                     tem = fold_build2_loc (loc, MINUS_EXPR, utype,
10368                                            pmop[0], pmop[1]);
10369                   /* TEM is now the new binary +, - or unary - replacement.  */
10370                   tem = fold_build2_loc (loc, BIT_AND_EXPR, utype, tem,
10371                                          fold_convert_loc (loc, utype, arg1));
10372                   return fold_convert_loc (loc, type, tem);
10373                 }
10374             }
10375         }
10376
10377       /* Simplify ((int)c & 0377) into (int)c, if c is unsigned char.  */
10378       if (TREE_CODE (arg1) == INTEGER_CST && TREE_CODE (arg0) == NOP_EXPR
10379           && TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (arg0, 0))))
10380         {
10381           prec = element_precision (TREE_TYPE (TREE_OPERAND (arg0, 0)));
10382
10383           wide_int mask = wide_int::from (arg1, prec, UNSIGNED);
10384           if (mask == -1)
10385             return
10386               fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
10387         }
10388
10389       goto associate;
10390
10391     case RDIV_EXPR:
10392       /* Don't touch a floating-point divide by zero unless the mode
10393          of the constant can represent infinity.  */
10394       if (TREE_CODE (arg1) == REAL_CST
10395           && !MODE_HAS_INFINITIES (TYPE_MODE (TREE_TYPE (arg1)))
10396           && real_zerop (arg1))
10397         return NULL_TREE;
10398
10399       /* (-A) / (-B) -> A / B  */
10400       if (TREE_CODE (arg0) == NEGATE_EXPR && negate_expr_p (arg1))
10401         return fold_build2_loc (loc, RDIV_EXPR, type,
10402                             TREE_OPERAND (arg0, 0),
10403                             negate_expr (arg1));
10404       if (TREE_CODE (arg1) == NEGATE_EXPR && negate_expr_p (arg0))
10405         return fold_build2_loc (loc, RDIV_EXPR, type,
10406                             negate_expr (arg0),
10407                             TREE_OPERAND (arg1, 0));
10408       return NULL_TREE;
10409
10410     case TRUNC_DIV_EXPR:
10411       /* Fall through */
10412
10413     case FLOOR_DIV_EXPR:
10414       /* Simplify A / (B << N) where A and B are positive and B is
10415          a power of 2, to A >> (N + log2(B)).  */
10416       strict_overflow_p = false;
10417       if (TREE_CODE (arg1) == LSHIFT_EXPR
10418           && (TYPE_UNSIGNED (type)
10419               || tree_expr_nonnegative_warnv_p (op0, &strict_overflow_p)))
10420         {
10421           tree sval = TREE_OPERAND (arg1, 0);
10422           if (integer_pow2p (sval) && tree_int_cst_sgn (sval) > 0)
10423             {
10424               tree sh_cnt = TREE_OPERAND (arg1, 1);
10425               tree pow2 = build_int_cst (TREE_TYPE (sh_cnt),
10426                                          wi::exact_log2 (sval));
10427
10428               if (strict_overflow_p)
10429                 fold_overflow_warning (("assuming signed overflow does not "
10430                                         "occur when simplifying A / (B << N)"),
10431                                        WARN_STRICT_OVERFLOW_MISC);
10432
10433               sh_cnt = fold_build2_loc (loc, PLUS_EXPR, TREE_TYPE (sh_cnt),
10434                                         sh_cnt, pow2);
10435               return fold_build2_loc (loc, RSHIFT_EXPR, type,
10436                                       fold_convert_loc (loc, type, arg0), sh_cnt);
10437             }
10438         }
10439
10440       /* Fall through */
10441
10442     case ROUND_DIV_EXPR:
10443     case CEIL_DIV_EXPR:
10444     case EXACT_DIV_EXPR:
10445       if (integer_zerop (arg1))
10446         return NULL_TREE;
10447
10448       /* Convert -A / -B to A / B when the type is signed and overflow is
10449          undefined.  */
10450       if ((!INTEGRAL_TYPE_P (type) || TYPE_OVERFLOW_UNDEFINED (type))
10451           && TREE_CODE (arg0) == NEGATE_EXPR
10452           && negate_expr_p (op1))
10453         {
10454           if (INTEGRAL_TYPE_P (type))
10455             fold_overflow_warning (("assuming signed overflow does not occur "
10456                                     "when distributing negation across "
10457                                     "division"),
10458                                    WARN_STRICT_OVERFLOW_MISC);
10459           return fold_build2_loc (loc, code, type,
10460                                   fold_convert_loc (loc, type,
10461                                                     TREE_OPERAND (arg0, 0)),
10462                                   negate_expr (op1));
10463         }
10464       if ((!INTEGRAL_TYPE_P (type) || TYPE_OVERFLOW_UNDEFINED (type))
10465           && TREE_CODE (arg1) == NEGATE_EXPR
10466           && negate_expr_p (op0))
10467         {
10468           if (INTEGRAL_TYPE_P (type))
10469             fold_overflow_warning (("assuming signed overflow does not occur "
10470                                     "when distributing negation across "
10471                                     "division"),
10472                                    WARN_STRICT_OVERFLOW_MISC);
10473           return fold_build2_loc (loc, code, type,
10474                                   negate_expr (op0),
10475                                   fold_convert_loc (loc, type,
10476                                                     TREE_OPERAND (arg1, 0)));
10477         }
10478
10479       /* If arg0 is a multiple of arg1, then rewrite to the fastest div
10480          operation, EXACT_DIV_EXPR.
10481
10482          Note that only CEIL_DIV_EXPR and FLOOR_DIV_EXPR are rewritten now.
10483          At one time others generated faster code, it's not clear if they do
10484          after the last round to changes to the DIV code in expmed.c.  */
10485       if ((code == CEIL_DIV_EXPR || code == FLOOR_DIV_EXPR)
10486           && multiple_of_p (type, arg0, arg1))
10487         return fold_build2_loc (loc, EXACT_DIV_EXPR, type,
10488                                 fold_convert (type, arg0),
10489                                 fold_convert (type, arg1));
10490
10491       strict_overflow_p = false;
10492       if (TREE_CODE (arg1) == INTEGER_CST
10493           && 0 != (tem = extract_muldiv (op0, arg1, code, NULL_TREE,
10494                                          &strict_overflow_p)))
10495         {
10496           if (strict_overflow_p)
10497             fold_overflow_warning (("assuming signed overflow does not occur "
10498                                     "when simplifying division"),
10499                                    WARN_STRICT_OVERFLOW_MISC);
10500           return fold_convert_loc (loc, type, tem);
10501         }
10502
10503       return NULL_TREE;
10504
10505     case CEIL_MOD_EXPR:
10506     case FLOOR_MOD_EXPR:
10507     case ROUND_MOD_EXPR:
10508     case TRUNC_MOD_EXPR:
10509       strict_overflow_p = false;
10510       if (TREE_CODE (arg1) == INTEGER_CST
10511           && 0 != (tem = extract_muldiv (op0, arg1, code, NULL_TREE,
10512                                          &strict_overflow_p)))
10513         {
10514           if (strict_overflow_p)
10515             fold_overflow_warning (("assuming signed overflow does not occur "
10516                                     "when simplifying modulus"),
10517                                    WARN_STRICT_OVERFLOW_MISC);
10518           return fold_convert_loc (loc, type, tem);
10519         }
10520
10521       return NULL_TREE;
10522
10523     case LROTATE_EXPR:
10524     case RROTATE_EXPR:
10525     case RSHIFT_EXPR:
10526     case LSHIFT_EXPR:
10527       /* Since negative shift count is not well-defined,
10528          don't try to compute it in the compiler.  */
10529       if (TREE_CODE (arg1) == INTEGER_CST && tree_int_cst_sgn (arg1) < 0)
10530         return NULL_TREE;
10531
10532       prec = element_precision (type);
10533
10534       /* If we have a rotate of a bit operation with the rotate count and
10535          the second operand of the bit operation both constant,
10536          permute the two operations.  */
10537       if (code == RROTATE_EXPR && TREE_CODE (arg1) == INTEGER_CST
10538           && (TREE_CODE (arg0) == BIT_AND_EXPR
10539               || TREE_CODE (arg0) == BIT_IOR_EXPR
10540               || TREE_CODE (arg0) == BIT_XOR_EXPR)
10541           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
10542         {
10543           tree arg00 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
10544           tree arg01 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 1));
10545           return fold_build2_loc (loc, TREE_CODE (arg0), type,
10546                                   fold_build2_loc (loc, code, type,
10547                                                    arg00, arg1),
10548                                   fold_build2_loc (loc, code, type,
10549                                                    arg01, arg1));
10550         }
10551
10552       /* Two consecutive rotates adding up to the some integer
10553          multiple of the precision of the type can be ignored.  */
10554       if (code == RROTATE_EXPR && TREE_CODE (arg1) == INTEGER_CST
10555           && TREE_CODE (arg0) == RROTATE_EXPR
10556           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
10557           && wi::umod_trunc (wi::add (arg1, TREE_OPERAND (arg0, 1)),
10558                              prec) == 0)
10559         return fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
10560
10561       return NULL_TREE;
10562
10563     case MIN_EXPR:
10564     case MAX_EXPR:
10565       goto associate;
10566
10567     case TRUTH_ANDIF_EXPR:
10568       /* Note that the operands of this must be ints
10569          and their values must be 0 or 1.
10570          ("true" is a fixed value perhaps depending on the language.)  */
10571       /* If first arg is constant zero, return it.  */
10572       if (integer_zerop (arg0))
10573         return fold_convert_loc (loc, type, arg0);
10574     case TRUTH_AND_EXPR:
10575       /* If either arg is constant true, drop it.  */
10576       if (TREE_CODE (arg0) == INTEGER_CST && ! integer_zerop (arg0))
10577         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg1));
10578       if (TREE_CODE (arg1) == INTEGER_CST && ! integer_zerop (arg1)
10579           /* Preserve sequence points.  */
10580           && (code != TRUTH_ANDIF_EXPR || ! TREE_SIDE_EFFECTS (arg0)))
10581         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
10582       /* If second arg is constant zero, result is zero, but first arg
10583          must be evaluated.  */
10584       if (integer_zerop (arg1))
10585         return omit_one_operand_loc (loc, type, arg1, arg0);
10586       /* Likewise for first arg, but note that only the TRUTH_AND_EXPR
10587          case will be handled here.  */
10588       if (integer_zerop (arg0))
10589         return omit_one_operand_loc (loc, type, arg0, arg1);
10590
10591       /* !X && X is always false.  */
10592       if (TREE_CODE (arg0) == TRUTH_NOT_EXPR
10593           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
10594         return omit_one_operand_loc (loc, type, integer_zero_node, arg1);
10595       /* X && !X is always false.  */
10596       if (TREE_CODE (arg1) == TRUTH_NOT_EXPR
10597           && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
10598         return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
10599
10600       /* A < X && A + 1 > Y ==> A < X && A >= Y.  Normally A + 1 > Y
10601          means A >= Y && A != MAX, but in this case we know that
10602          A < X <= MAX.  */
10603
10604       if (!TREE_SIDE_EFFECTS (arg0)
10605           && !TREE_SIDE_EFFECTS (arg1))
10606         {
10607           tem = fold_to_nonsharp_ineq_using_bound (loc, arg0, arg1);
10608           if (tem && !operand_equal_p (tem, arg0, 0))
10609             return fold_build2_loc (loc, code, type, tem, arg1);
10610
10611           tem = fold_to_nonsharp_ineq_using_bound (loc, arg1, arg0);
10612           if (tem && !operand_equal_p (tem, arg1, 0))
10613             return fold_build2_loc (loc, code, type, arg0, tem);
10614         }
10615
10616       if ((tem = fold_truth_andor (loc, code, type, arg0, arg1, op0, op1))
10617           != NULL_TREE)
10618         return tem;
10619
10620       return NULL_TREE;
10621
10622     case TRUTH_ORIF_EXPR:
10623       /* Note that the operands of this must be ints
10624          and their values must be 0 or true.
10625          ("true" is a fixed value perhaps depending on the language.)  */
10626       /* If first arg is constant true, return it.  */
10627       if (TREE_CODE (arg0) == INTEGER_CST && ! integer_zerop (arg0))
10628         return fold_convert_loc (loc, type, arg0);
10629     case TRUTH_OR_EXPR:
10630       /* If either arg is constant zero, drop it.  */
10631       if (TREE_CODE (arg0) == INTEGER_CST && integer_zerop (arg0))
10632         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg1));
10633       if (TREE_CODE (arg1) == INTEGER_CST && integer_zerop (arg1)
10634           /* Preserve sequence points.  */
10635           && (code != TRUTH_ORIF_EXPR || ! TREE_SIDE_EFFECTS (arg0)))
10636         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
10637       /* If second arg is constant true, result is true, but we must
10638          evaluate first arg.  */
10639       if (TREE_CODE (arg1) == INTEGER_CST && ! integer_zerop (arg1))
10640         return omit_one_operand_loc (loc, type, arg1, arg0);
10641       /* Likewise for first arg, but note this only occurs here for
10642          TRUTH_OR_EXPR.  */
10643       if (TREE_CODE (arg0) == INTEGER_CST && ! integer_zerop (arg0))
10644         return omit_one_operand_loc (loc, type, arg0, arg1);
10645
10646       /* !X || X is always true.  */
10647       if (TREE_CODE (arg0) == TRUTH_NOT_EXPR
10648           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
10649         return omit_one_operand_loc (loc, type, integer_one_node, arg1);
10650       /* X || !X is always true.  */
10651       if (TREE_CODE (arg1) == TRUTH_NOT_EXPR
10652           && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
10653         return omit_one_operand_loc (loc, type, integer_one_node, arg0);
10654
10655       /* (X && !Y) || (!X && Y) is X ^ Y */
10656       if (TREE_CODE (arg0) == TRUTH_AND_EXPR
10657           && TREE_CODE (arg1) == TRUTH_AND_EXPR)
10658         {
10659           tree a0, a1, l0, l1, n0, n1;
10660
10661           a0 = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 0));
10662           a1 = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 1));
10663
10664           l0 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
10665           l1 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 1));
10666
10667           n0 = fold_build1_loc (loc, TRUTH_NOT_EXPR, type, l0);
10668           n1 = fold_build1_loc (loc, TRUTH_NOT_EXPR, type, l1);
10669
10670           if ((operand_equal_p (n0, a0, 0)
10671                && operand_equal_p (n1, a1, 0))
10672               || (operand_equal_p (n0, a1, 0)
10673                   && operand_equal_p (n1, a0, 0)))
10674             return fold_build2_loc (loc, TRUTH_XOR_EXPR, type, l0, n1);
10675         }
10676
10677       if ((tem = fold_truth_andor (loc, code, type, arg0, arg1, op0, op1))
10678           != NULL_TREE)
10679         return tem;
10680
10681       return NULL_TREE;
10682
10683     case TRUTH_XOR_EXPR:
10684       /* If the second arg is constant zero, drop it.  */
10685       if (integer_zerop (arg1))
10686         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
10687       /* If the second arg is constant true, this is a logical inversion.  */
10688       if (integer_onep (arg1))
10689         {
10690           tem = invert_truthvalue_loc (loc, arg0);
10691           return non_lvalue_loc (loc, fold_convert_loc (loc, type, tem));
10692         }
10693       /* Identical arguments cancel to zero.  */
10694       if (operand_equal_p (arg0, arg1, 0))
10695         return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
10696
10697       /* !X ^ X is always true.  */
10698       if (TREE_CODE (arg0) == TRUTH_NOT_EXPR
10699           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
10700         return omit_one_operand_loc (loc, type, integer_one_node, arg1);
10701
10702       /* X ^ !X is always true.  */
10703       if (TREE_CODE (arg1) == TRUTH_NOT_EXPR
10704           && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
10705         return omit_one_operand_loc (loc, type, integer_one_node, arg0);
10706
10707       return NULL_TREE;
10708
10709     case EQ_EXPR:
10710     case NE_EXPR:
10711       STRIP_NOPS (arg0);
10712       STRIP_NOPS (arg1);
10713
10714       tem = fold_comparison (loc, code, type, op0, op1);
10715       if (tem != NULL_TREE)
10716         return tem;
10717
10718       /* bool_var != 1 becomes !bool_var. */
10719       if (TREE_CODE (TREE_TYPE (arg0)) == BOOLEAN_TYPE && integer_onep (arg1)
10720           && code == NE_EXPR)
10721         return fold_convert_loc (loc, type,
10722                                  fold_build1_loc (loc, TRUTH_NOT_EXPR,
10723                                                   TREE_TYPE (arg0), arg0));
10724
10725       /* bool_var == 0 becomes !bool_var. */
10726       if (TREE_CODE (TREE_TYPE (arg0)) == BOOLEAN_TYPE && integer_zerop (arg1)
10727           && code == EQ_EXPR)
10728         return fold_convert_loc (loc, type,
10729                                  fold_build1_loc (loc, TRUTH_NOT_EXPR,
10730                                                   TREE_TYPE (arg0), arg0));
10731
10732       /* !exp != 0 becomes !exp */
10733       if (TREE_CODE (arg0) == TRUTH_NOT_EXPR && integer_zerop (arg1)
10734           && code == NE_EXPR)
10735         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
10736
10737       /* Transform comparisons of the form X +- Y CMP X to Y CMP 0.  */
10738       if ((TREE_CODE (arg0) == PLUS_EXPR
10739            || TREE_CODE (arg0) == POINTER_PLUS_EXPR
10740            || TREE_CODE (arg0) == MINUS_EXPR)
10741           && operand_equal_p (tree_strip_nop_conversions (TREE_OPERAND (arg0,
10742                                                                         0)),
10743                               arg1, 0)
10744           && (INTEGRAL_TYPE_P (TREE_TYPE (arg0))
10745               || POINTER_TYPE_P (TREE_TYPE (arg0))))
10746         {
10747           tree val = TREE_OPERAND (arg0, 1);
10748           val = fold_build2_loc (loc, code, type, val,
10749                                  build_int_cst (TREE_TYPE (val), 0));
10750           return omit_two_operands_loc (loc, type, val,
10751                                         TREE_OPERAND (arg0, 0), arg1);
10752         }
10753
10754       /* Transform comparisons of the form X CMP X +- Y to Y CMP 0.  */
10755       if ((TREE_CODE (arg1) == PLUS_EXPR
10756            || TREE_CODE (arg1) == POINTER_PLUS_EXPR
10757            || TREE_CODE (arg1) == MINUS_EXPR)
10758           && operand_equal_p (tree_strip_nop_conversions (TREE_OPERAND (arg1,
10759                                                                         0)),
10760                               arg0, 0)
10761           && (INTEGRAL_TYPE_P (TREE_TYPE (arg1))
10762               || POINTER_TYPE_P (TREE_TYPE (arg1))))
10763         {
10764           tree val = TREE_OPERAND (arg1, 1);
10765           val = fold_build2_loc (loc, code, type, val,
10766                                  build_int_cst (TREE_TYPE (val), 0));
10767           return omit_two_operands_loc (loc, type, val,
10768                                         TREE_OPERAND (arg1, 0), arg0);
10769         }
10770
10771       /* Transform comparisons of the form C - X CMP X if C % 2 == 1.  */
10772       if (TREE_CODE (arg0) == MINUS_EXPR
10773           && TREE_CODE (TREE_OPERAND (arg0, 0)) == INTEGER_CST
10774           && operand_equal_p (tree_strip_nop_conversions (TREE_OPERAND (arg0,
10775                                                                         1)),
10776                               arg1, 0)
10777           && wi::extract_uhwi (TREE_OPERAND (arg0, 0), 0, 1) == 1)
10778         return omit_two_operands_loc (loc, type,
10779                                       code == NE_EXPR
10780                                       ? boolean_true_node : boolean_false_node,
10781                                       TREE_OPERAND (arg0, 1), arg1);
10782
10783       /* Transform comparisons of the form X CMP C - X if C % 2 == 1.  */
10784       if (TREE_CODE (arg1) == MINUS_EXPR
10785           && TREE_CODE (TREE_OPERAND (arg1, 0)) == INTEGER_CST
10786           && operand_equal_p (tree_strip_nop_conversions (TREE_OPERAND (arg1,
10787                                                                         1)),
10788                               arg0, 0)
10789           && wi::extract_uhwi (TREE_OPERAND (arg1, 0), 0, 1) == 1)
10790         return omit_two_operands_loc (loc, type,
10791                                       code == NE_EXPR
10792                                       ? boolean_true_node : boolean_false_node,
10793                                       TREE_OPERAND (arg1, 1), arg0);
10794
10795       /* If this is an EQ or NE comparison with zero and ARG0 is
10796          (1 << foo) & bar, convert it to (bar >> foo) & 1.  Both require
10797          two operations, but the latter can be done in one less insn
10798          on machines that have only two-operand insns or on which a
10799          constant cannot be the first operand.  */
10800       if (TREE_CODE (arg0) == BIT_AND_EXPR
10801           && integer_zerop (arg1))
10802         {
10803           tree arg00 = TREE_OPERAND (arg0, 0);
10804           tree arg01 = TREE_OPERAND (arg0, 1);
10805           if (TREE_CODE (arg00) == LSHIFT_EXPR
10806               && integer_onep (TREE_OPERAND (arg00, 0)))
10807             {
10808               tree tem = fold_build2_loc (loc, RSHIFT_EXPR, TREE_TYPE (arg00),
10809                                       arg01, TREE_OPERAND (arg00, 1));
10810               tem = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg0), tem,
10811                                  build_int_cst (TREE_TYPE (arg0), 1));
10812               return fold_build2_loc (loc, code, type,
10813                                   fold_convert_loc (loc, TREE_TYPE (arg1), tem),
10814                                   arg1);
10815             }
10816           else if (TREE_CODE (arg01) == LSHIFT_EXPR
10817                    && integer_onep (TREE_OPERAND (arg01, 0)))
10818             {
10819               tree tem = fold_build2_loc (loc, RSHIFT_EXPR, TREE_TYPE (arg01),
10820                                       arg00, TREE_OPERAND (arg01, 1));
10821               tem = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg0), tem,
10822                                  build_int_cst (TREE_TYPE (arg0), 1));
10823               return fold_build2_loc (loc, code, type,
10824                                   fold_convert_loc (loc, TREE_TYPE (arg1), tem),
10825                                   arg1);
10826             }
10827         }
10828
10829       /* If this is an NE or EQ comparison of zero against the result of a
10830          signed MOD operation whose second operand is a power of 2, make
10831          the MOD operation unsigned since it is simpler and equivalent.  */
10832       if (integer_zerop (arg1)
10833           && !TYPE_UNSIGNED (TREE_TYPE (arg0))
10834           && (TREE_CODE (arg0) == TRUNC_MOD_EXPR
10835               || TREE_CODE (arg0) == CEIL_MOD_EXPR
10836               || TREE_CODE (arg0) == FLOOR_MOD_EXPR
10837               || TREE_CODE (arg0) == ROUND_MOD_EXPR)
10838           && integer_pow2p (TREE_OPERAND (arg0, 1)))
10839         {
10840           tree newtype = unsigned_type_for (TREE_TYPE (arg0));
10841           tree newmod = fold_build2_loc (loc, TREE_CODE (arg0), newtype,
10842                                      fold_convert_loc (loc, newtype,
10843                                                        TREE_OPERAND (arg0, 0)),
10844                                      fold_convert_loc (loc, newtype,
10845                                                        TREE_OPERAND (arg0, 1)));
10846
10847           return fold_build2_loc (loc, code, type, newmod,
10848                               fold_convert_loc (loc, newtype, arg1));
10849         }
10850
10851       /* Fold ((X >> C1) & C2) == 0 and ((X >> C1) & C2) != 0 where
10852          C1 is a valid shift constant, and C2 is a power of two, i.e.
10853          a single bit.  */
10854       if (TREE_CODE (arg0) == BIT_AND_EXPR
10855           && TREE_CODE (TREE_OPERAND (arg0, 0)) == RSHIFT_EXPR
10856           && TREE_CODE (TREE_OPERAND (TREE_OPERAND (arg0, 0), 1))
10857              == INTEGER_CST
10858           && integer_pow2p (TREE_OPERAND (arg0, 1))
10859           && integer_zerop (arg1))
10860         {
10861           tree itype = TREE_TYPE (arg0);
10862           tree arg001 = TREE_OPERAND (TREE_OPERAND (arg0, 0), 1);
10863           prec = TYPE_PRECISION (itype);
10864
10865           /* Check for a valid shift count.  */
10866           if (wi::ltu_p (arg001, prec))
10867             {
10868               tree arg01 = TREE_OPERAND (arg0, 1);
10869               tree arg000 = TREE_OPERAND (TREE_OPERAND (arg0, 0), 0);
10870               unsigned HOST_WIDE_INT log2 = tree_log2 (arg01);
10871               /* If (C2 << C1) doesn't overflow, then ((X >> C1) & C2) != 0
10872                  can be rewritten as (X & (C2 << C1)) != 0.  */
10873               if ((log2 + TREE_INT_CST_LOW (arg001)) < prec)
10874                 {
10875                   tem = fold_build2_loc (loc, LSHIFT_EXPR, itype, arg01, arg001);
10876                   tem = fold_build2_loc (loc, BIT_AND_EXPR, itype, arg000, tem);
10877                   return fold_build2_loc (loc, code, type, tem,
10878                                           fold_convert_loc (loc, itype, arg1));
10879                 }
10880               /* Otherwise, for signed (arithmetic) shifts,
10881                  ((X >> C1) & C2) != 0 is rewritten as X < 0, and
10882                  ((X >> C1) & C2) == 0 is rewritten as X >= 0.  */
10883               else if (!TYPE_UNSIGNED (itype))
10884                 return fold_build2_loc (loc, code == EQ_EXPR ? GE_EXPR : LT_EXPR, type,
10885                                     arg000, build_int_cst (itype, 0));
10886               /* Otherwise, of unsigned (logical) shifts,
10887                  ((X >> C1) & C2) != 0 is rewritten as (X,false), and
10888                  ((X >> C1) & C2) == 0 is rewritten as (X,true).  */
10889               else
10890                 return omit_one_operand_loc (loc, type,
10891                                          code == EQ_EXPR ? integer_one_node
10892                                                          : integer_zero_node,
10893                                          arg000);
10894             }
10895         }
10896
10897       /* If we have (A & C) == D where D & ~C != 0, convert this into 0.
10898          Similarly for NE_EXPR.  */
10899       if (TREE_CODE (arg0) == BIT_AND_EXPR
10900           && TREE_CODE (arg1) == INTEGER_CST
10901           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
10902         {
10903           tree notc = fold_build1_loc (loc, BIT_NOT_EXPR,
10904                                    TREE_TYPE (TREE_OPERAND (arg0, 1)),
10905                                    TREE_OPERAND (arg0, 1));
10906           tree dandnotc
10907             = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg0),
10908                                fold_convert_loc (loc, TREE_TYPE (arg0), arg1),
10909                                notc);
10910           tree rslt = code == EQ_EXPR ? integer_zero_node : integer_one_node;
10911           if (integer_nonzerop (dandnotc))
10912             return omit_one_operand_loc (loc, type, rslt, arg0);
10913         }
10914
10915       /* If this is a comparison of a field, we may be able to simplify it.  */
10916       if ((TREE_CODE (arg0) == COMPONENT_REF
10917            || TREE_CODE (arg0) == BIT_FIELD_REF)
10918           /* Handle the constant case even without -O
10919              to make sure the warnings are given.  */
10920           && (optimize || TREE_CODE (arg1) == INTEGER_CST))
10921         {
10922           t1 = optimize_bit_field_compare (loc, code, type, arg0, arg1);
10923           if (t1)
10924             return t1;
10925         }
10926
10927       /* Optimize comparisons of strlen vs zero to a compare of the
10928          first character of the string vs zero.  To wit,
10929                 strlen(ptr) == 0   =>  *ptr == 0
10930                 strlen(ptr) != 0   =>  *ptr != 0
10931          Other cases should reduce to one of these two (or a constant)
10932          due to the return value of strlen being unsigned.  */
10933       if (TREE_CODE (arg0) == CALL_EXPR
10934           && integer_zerop (arg1))
10935         {
10936           tree fndecl = get_callee_fndecl (arg0);
10937
10938           if (fndecl
10939               && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
10940               && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STRLEN
10941               && call_expr_nargs (arg0) == 1
10942               && TREE_CODE (TREE_TYPE (CALL_EXPR_ARG (arg0, 0))) == POINTER_TYPE)
10943             {
10944               tree iref = build_fold_indirect_ref_loc (loc,
10945                                                    CALL_EXPR_ARG (arg0, 0));
10946               return fold_build2_loc (loc, code, type, iref,
10947                                   build_int_cst (TREE_TYPE (iref), 0));
10948             }
10949         }
10950
10951       /* Fold (X >> C) != 0 into X < 0 if C is one less than the width
10952          of X.  Similarly fold (X >> C) == 0 into X >= 0.  */
10953       if (TREE_CODE (arg0) == RSHIFT_EXPR
10954           && integer_zerop (arg1)
10955           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
10956         {
10957           tree arg00 = TREE_OPERAND (arg0, 0);
10958           tree arg01 = TREE_OPERAND (arg0, 1);
10959           tree itype = TREE_TYPE (arg00);
10960           if (wi::eq_p (arg01, element_precision (itype) - 1))
10961             {
10962               if (TYPE_UNSIGNED (itype))
10963                 {
10964                   itype = signed_type_for (itype);
10965                   arg00 = fold_convert_loc (loc, itype, arg00);
10966                 }
10967               return fold_build2_loc (loc, code == EQ_EXPR ? GE_EXPR : LT_EXPR,
10968                                   type, arg00, build_zero_cst (itype));
10969             }
10970         }
10971
10972       /* Fold (~X & C) == 0 into (X & C) != 0 and (~X & C) != 0 into
10973          (X & C) == 0 when C is a single bit.  */
10974       if (TREE_CODE (arg0) == BIT_AND_EXPR
10975           && TREE_CODE (TREE_OPERAND (arg0, 0)) == BIT_NOT_EXPR
10976           && integer_zerop (arg1)
10977           && integer_pow2p (TREE_OPERAND (arg0, 1)))
10978         {
10979           tem = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg0),
10980                                  TREE_OPERAND (TREE_OPERAND (arg0, 0), 0),
10981                                  TREE_OPERAND (arg0, 1));
10982           return fold_build2_loc (loc, code == EQ_EXPR ? NE_EXPR : EQ_EXPR,
10983                                   type, tem,
10984                                   fold_convert_loc (loc, TREE_TYPE (arg0),
10985                                                     arg1));
10986         }
10987
10988       /* Fold ((X & C) ^ C) eq/ne 0 into (X & C) ne/eq 0, when the
10989          constant C is a power of two, i.e. a single bit.  */
10990       if (TREE_CODE (arg0) == BIT_XOR_EXPR
10991           && TREE_CODE (TREE_OPERAND (arg0, 0)) == BIT_AND_EXPR
10992           && integer_zerop (arg1)
10993           && integer_pow2p (TREE_OPERAND (arg0, 1))
10994           && operand_equal_p (TREE_OPERAND (TREE_OPERAND (arg0, 0), 1),
10995                               TREE_OPERAND (arg0, 1), OEP_ONLY_CONST))
10996         {
10997           tree arg00 = TREE_OPERAND (arg0, 0);
10998           return fold_build2_loc (loc, code == EQ_EXPR ? NE_EXPR : EQ_EXPR, type,
10999                               arg00, build_int_cst (TREE_TYPE (arg00), 0));
11000         }
11001
11002       /* Likewise, fold ((X ^ C) & C) eq/ne 0 into (X & C) ne/eq 0,
11003          when is C is a power of two, i.e. a single bit.  */
11004       if (TREE_CODE (arg0) == BIT_AND_EXPR
11005           && TREE_CODE (TREE_OPERAND (arg0, 0)) == BIT_XOR_EXPR
11006           && integer_zerop (arg1)
11007           && integer_pow2p (TREE_OPERAND (arg0, 1))
11008           && operand_equal_p (TREE_OPERAND (TREE_OPERAND (arg0, 0), 1),
11009                               TREE_OPERAND (arg0, 1), OEP_ONLY_CONST))
11010         {
11011           tree arg000 = TREE_OPERAND (TREE_OPERAND (arg0, 0), 0);
11012           tem = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg000),
11013                              arg000, TREE_OPERAND (arg0, 1));
11014           return fold_build2_loc (loc, code == EQ_EXPR ? NE_EXPR : EQ_EXPR, type,
11015                               tem, build_int_cst (TREE_TYPE (tem), 0));
11016         }
11017
11018       if (integer_zerop (arg1)
11019           && tree_expr_nonzero_p (arg0))
11020         {
11021           tree res = constant_boolean_node (code==NE_EXPR, type);
11022           return omit_one_operand_loc (loc, type, res, arg0);
11023         }
11024
11025       /* Fold (X & C) op (Y & C) as (X ^ Y) & C op 0", and symmetries.  */
11026       if (TREE_CODE (arg0) == BIT_AND_EXPR
11027           && TREE_CODE (arg1) == BIT_AND_EXPR)
11028         {
11029           tree arg00 = TREE_OPERAND (arg0, 0);
11030           tree arg01 = TREE_OPERAND (arg0, 1);
11031           tree arg10 = TREE_OPERAND (arg1, 0);
11032           tree arg11 = TREE_OPERAND (arg1, 1);
11033           tree itype = TREE_TYPE (arg0);
11034
11035           if (operand_equal_p (arg01, arg11, 0))
11036             return fold_build2_loc (loc, code, type,
11037                                 fold_build2_loc (loc, BIT_AND_EXPR, itype,
11038                                              fold_build2_loc (loc,
11039                                                           BIT_XOR_EXPR, itype,
11040                                                           arg00, arg10),
11041                                              arg01),
11042                                 build_zero_cst (itype));
11043
11044           if (operand_equal_p (arg01, arg10, 0))
11045             return fold_build2_loc (loc, code, type,
11046                                 fold_build2_loc (loc, BIT_AND_EXPR, itype,
11047                                              fold_build2_loc (loc,
11048                                                           BIT_XOR_EXPR, itype,
11049                                                           arg00, arg11),
11050                                              arg01),
11051                                 build_zero_cst (itype));
11052
11053           if (operand_equal_p (arg00, arg11, 0))
11054             return fold_build2_loc (loc, code, type,
11055                                 fold_build2_loc (loc, BIT_AND_EXPR, itype,
11056                                              fold_build2_loc (loc,
11057                                                           BIT_XOR_EXPR, itype,
11058                                                           arg01, arg10),
11059                                              arg00),
11060                                 build_zero_cst (itype));
11061
11062           if (operand_equal_p (arg00, arg10, 0))
11063             return fold_build2_loc (loc, code, type,
11064                                 fold_build2_loc (loc, BIT_AND_EXPR, itype,
11065                                              fold_build2_loc (loc,
11066                                                           BIT_XOR_EXPR, itype,
11067                                                           arg01, arg11),
11068                                              arg00),
11069                                 build_zero_cst (itype));
11070         }
11071
11072       if (TREE_CODE (arg0) == BIT_XOR_EXPR
11073           && TREE_CODE (arg1) == BIT_XOR_EXPR)
11074         {
11075           tree arg00 = TREE_OPERAND (arg0, 0);
11076           tree arg01 = TREE_OPERAND (arg0, 1);
11077           tree arg10 = TREE_OPERAND (arg1, 0);
11078           tree arg11 = TREE_OPERAND (arg1, 1);
11079           tree itype = TREE_TYPE (arg0);
11080
11081           /* Optimize (X ^ Z) op (Y ^ Z) as X op Y, and symmetries.
11082              operand_equal_p guarantees no side-effects so we don't need
11083              to use omit_one_operand on Z.  */
11084           if (operand_equal_p (arg01, arg11, 0))
11085             return fold_build2_loc (loc, code, type, arg00,
11086                                     fold_convert_loc (loc, TREE_TYPE (arg00),
11087                                                       arg10));
11088           if (operand_equal_p (arg01, arg10, 0))
11089             return fold_build2_loc (loc, code, type, arg00,
11090                                     fold_convert_loc (loc, TREE_TYPE (arg00),
11091                                                       arg11));
11092           if (operand_equal_p (arg00, arg11, 0))
11093             return fold_build2_loc (loc, code, type, arg01,
11094                                     fold_convert_loc (loc, TREE_TYPE (arg01),
11095                                                       arg10));
11096           if (operand_equal_p (arg00, arg10, 0))
11097             return fold_build2_loc (loc, code, type, arg01,
11098                                     fold_convert_loc (loc, TREE_TYPE (arg01),
11099                                                       arg11));
11100
11101           /* Optimize (X ^ C1) op (Y ^ C2) as (X ^ (C1 ^ C2)) op Y.  */
11102           if (TREE_CODE (arg01) == INTEGER_CST
11103               && TREE_CODE (arg11) == INTEGER_CST)
11104             {
11105               tem = fold_build2_loc (loc, BIT_XOR_EXPR, itype, arg01,
11106                                      fold_convert_loc (loc, itype, arg11));
11107               tem = fold_build2_loc (loc, BIT_XOR_EXPR, itype, arg00, tem);
11108               return fold_build2_loc (loc, code, type, tem,
11109                                       fold_convert_loc (loc, itype, arg10));
11110             }
11111         }
11112
11113       /* Attempt to simplify equality/inequality comparisons of complex
11114          values.  Only lower the comparison if the result is known or
11115          can be simplified to a single scalar comparison.  */
11116       if ((TREE_CODE (arg0) == COMPLEX_EXPR
11117            || TREE_CODE (arg0) == COMPLEX_CST)
11118           && (TREE_CODE (arg1) == COMPLEX_EXPR
11119               || TREE_CODE (arg1) == COMPLEX_CST))
11120         {
11121           tree real0, imag0, real1, imag1;
11122           tree rcond, icond;
11123
11124           if (TREE_CODE (arg0) == COMPLEX_EXPR)
11125             {
11126               real0 = TREE_OPERAND (arg0, 0);
11127               imag0 = TREE_OPERAND (arg0, 1);
11128             }
11129           else
11130             {
11131               real0 = TREE_REALPART (arg0);
11132               imag0 = TREE_IMAGPART (arg0);
11133             }
11134
11135           if (TREE_CODE (arg1) == COMPLEX_EXPR)
11136             {
11137               real1 = TREE_OPERAND (arg1, 0);
11138               imag1 = TREE_OPERAND (arg1, 1);
11139             }
11140           else
11141             {
11142               real1 = TREE_REALPART (arg1);
11143               imag1 = TREE_IMAGPART (arg1);
11144             }
11145
11146           rcond = fold_binary_loc (loc, code, type, real0, real1);
11147           if (rcond && TREE_CODE (rcond) == INTEGER_CST)
11148             {
11149               if (integer_zerop (rcond))
11150                 {
11151                   if (code == EQ_EXPR)
11152                     return omit_two_operands_loc (loc, type, boolean_false_node,
11153                                               imag0, imag1);
11154                   return fold_build2_loc (loc, NE_EXPR, type, imag0, imag1);
11155                 }
11156               else
11157                 {
11158                   if (code == NE_EXPR)
11159                     return omit_two_operands_loc (loc, type, boolean_true_node,
11160                                               imag0, imag1);
11161                   return fold_build2_loc (loc, EQ_EXPR, type, imag0, imag1);
11162                 }
11163             }
11164
11165           icond = fold_binary_loc (loc, code, type, imag0, imag1);
11166           if (icond && TREE_CODE (icond) == INTEGER_CST)
11167             {
11168               if (integer_zerop (icond))
11169                 {
11170                   if (code == EQ_EXPR)
11171                     return omit_two_operands_loc (loc, type, boolean_false_node,
11172                                               real0, real1);
11173                   return fold_build2_loc (loc, NE_EXPR, type, real0, real1);
11174                 }
11175               else
11176                 {
11177                   if (code == NE_EXPR)
11178                     return omit_two_operands_loc (loc, type, boolean_true_node,
11179                                               real0, real1);
11180                   return fold_build2_loc (loc, EQ_EXPR, type, real0, real1);
11181                 }
11182             }
11183         }
11184
11185       return NULL_TREE;
11186
11187     case LT_EXPR:
11188     case GT_EXPR:
11189     case LE_EXPR:
11190     case GE_EXPR:
11191       tem = fold_comparison (loc, code, type, op0, op1);
11192       if (tem != NULL_TREE)
11193         return tem;
11194
11195       /* Transform comparisons of the form X +- C CMP X.  */
11196       if ((TREE_CODE (arg0) == PLUS_EXPR || TREE_CODE (arg0) == MINUS_EXPR)
11197           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0)
11198           && ((TREE_CODE (TREE_OPERAND (arg0, 1)) == REAL_CST
11199                && !HONOR_SNANS (arg0))
11200               || (TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
11201                   && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))))
11202         {
11203           tree arg01 = TREE_OPERAND (arg0, 1);
11204           enum tree_code code0 = TREE_CODE (arg0);
11205           int is_positive;
11206
11207           if (TREE_CODE (arg01) == REAL_CST)
11208             is_positive = REAL_VALUE_NEGATIVE (TREE_REAL_CST (arg01)) ? -1 : 1;
11209           else
11210             is_positive = tree_int_cst_sgn (arg01);
11211
11212           /* (X - c) > X becomes false.  */
11213           if (code == GT_EXPR
11214               && ((code0 == MINUS_EXPR && is_positive >= 0)
11215                   || (code0 == PLUS_EXPR && is_positive <= 0)))
11216             {
11217               if (TREE_CODE (arg01) == INTEGER_CST
11218                   && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
11219                 fold_overflow_warning (("assuming signed overflow does not "
11220                                         "occur when assuming that (X - c) > X "
11221                                         "is always false"),
11222                                        WARN_STRICT_OVERFLOW_ALL);
11223               return constant_boolean_node (0, type);
11224             }
11225
11226           /* Likewise (X + c) < X becomes false.  */
11227           if (code == LT_EXPR
11228               && ((code0 == PLUS_EXPR && is_positive >= 0)
11229                   || (code0 == MINUS_EXPR && is_positive <= 0)))
11230             {
11231               if (TREE_CODE (arg01) == INTEGER_CST
11232                   && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
11233                 fold_overflow_warning (("assuming signed overflow does not "
11234                                         "occur when assuming that "
11235                                         "(X + c) < X is always false"),
11236                                        WARN_STRICT_OVERFLOW_ALL);
11237               return constant_boolean_node (0, type);
11238             }
11239
11240           /* Convert (X - c) <= X to true.  */
11241           if (!HONOR_NANS (arg1)
11242               && code == LE_EXPR
11243               && ((code0 == MINUS_EXPR && is_positive >= 0)
11244                   || (code0 == PLUS_EXPR && is_positive <= 0)))
11245             {
11246               if (TREE_CODE (arg01) == INTEGER_CST
11247                   && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
11248                 fold_overflow_warning (("assuming signed overflow does not "
11249                                         "occur when assuming that "
11250                                         "(X - c) <= X is always true"),
11251                                        WARN_STRICT_OVERFLOW_ALL);
11252               return constant_boolean_node (1, type);
11253             }
11254
11255           /* Convert (X + c) >= X to true.  */
11256           if (!HONOR_NANS (arg1)
11257               && code == GE_EXPR
11258               && ((code0 == PLUS_EXPR && is_positive >= 0)
11259                   || (code0 == MINUS_EXPR && is_positive <= 0)))
11260             {
11261               if (TREE_CODE (arg01) == INTEGER_CST
11262                   && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
11263                 fold_overflow_warning (("assuming signed overflow does not "
11264                                         "occur when assuming that "
11265                                         "(X + c) >= X is always true"),
11266                                        WARN_STRICT_OVERFLOW_ALL);
11267               return constant_boolean_node (1, type);
11268             }
11269
11270           if (TREE_CODE (arg01) == INTEGER_CST)
11271             {
11272               /* Convert X + c > X and X - c < X to true for integers.  */
11273               if (code == GT_EXPR
11274                   && ((code0 == PLUS_EXPR && is_positive > 0)
11275                       || (code0 == MINUS_EXPR && is_positive < 0)))
11276                 {
11277                   if (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
11278                     fold_overflow_warning (("assuming signed overflow does "
11279                                             "not occur when assuming that "
11280                                             "(X + c) > X is always true"),
11281                                            WARN_STRICT_OVERFLOW_ALL);
11282                   return constant_boolean_node (1, type);
11283                 }
11284
11285               if (code == LT_EXPR
11286                   && ((code0 == MINUS_EXPR && is_positive > 0)
11287                       || (code0 == PLUS_EXPR && is_positive < 0)))
11288                 {
11289                   if (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
11290                     fold_overflow_warning (("assuming signed overflow does "
11291                                             "not occur when assuming that "
11292                                             "(X - c) < X is always true"),
11293                                            WARN_STRICT_OVERFLOW_ALL);
11294                   return constant_boolean_node (1, type);
11295                 }
11296
11297               /* Convert X + c <= X and X - c >= X to false for integers.  */
11298               if (code == LE_EXPR
11299                   && ((code0 == PLUS_EXPR && is_positive > 0)
11300                       || (code0 == MINUS_EXPR && is_positive < 0)))
11301                 {
11302                   if (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
11303                     fold_overflow_warning (("assuming signed overflow does "
11304                                             "not occur when assuming that "
11305                                             "(X + c) <= X is always false"),
11306                                            WARN_STRICT_OVERFLOW_ALL);
11307                   return constant_boolean_node (0, type);
11308                 }
11309
11310               if (code == GE_EXPR
11311                   && ((code0 == MINUS_EXPR && is_positive > 0)
11312                       || (code0 == PLUS_EXPR && is_positive < 0)))
11313                 {
11314                   if (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
11315                     fold_overflow_warning (("assuming signed overflow does "
11316                                             "not occur when assuming that "
11317                                             "(X - c) >= X is always false"),
11318                                            WARN_STRICT_OVERFLOW_ALL);
11319                   return constant_boolean_node (0, type);
11320                 }
11321             }
11322         }
11323
11324       /* If we are comparing an ABS_EXPR with a constant, we can
11325          convert all the cases into explicit comparisons, but they may
11326          well not be faster than doing the ABS and one comparison.
11327          But ABS (X) <= C is a range comparison, which becomes a subtraction
11328          and a comparison, and is probably faster.  */
11329       if (code == LE_EXPR
11330           && TREE_CODE (arg1) == INTEGER_CST
11331           && TREE_CODE (arg0) == ABS_EXPR
11332           && ! TREE_SIDE_EFFECTS (arg0)
11333           && (0 != (tem = negate_expr (arg1)))
11334           && TREE_CODE (tem) == INTEGER_CST
11335           && !TREE_OVERFLOW (tem))
11336         return fold_build2_loc (loc, TRUTH_ANDIF_EXPR, type,
11337                             build2 (GE_EXPR, type,
11338                                     TREE_OPERAND (arg0, 0), tem),
11339                             build2 (LE_EXPR, type,
11340                                     TREE_OPERAND (arg0, 0), arg1));
11341
11342       /* Convert ABS_EXPR<x> >= 0 to true.  */
11343       strict_overflow_p = false;
11344       if (code == GE_EXPR
11345           && (integer_zerop (arg1)
11346               || (! HONOR_NANS (arg0)
11347                   && real_zerop (arg1)))
11348           && tree_expr_nonnegative_warnv_p (arg0, &strict_overflow_p))
11349         {
11350           if (strict_overflow_p)
11351             fold_overflow_warning (("assuming signed overflow does not occur "
11352                                     "when simplifying comparison of "
11353                                     "absolute value and zero"),
11354                                    WARN_STRICT_OVERFLOW_CONDITIONAL);
11355           return omit_one_operand_loc (loc, type,
11356                                        constant_boolean_node (true, type),
11357                                        arg0);
11358         }
11359
11360       /* Convert ABS_EXPR<x> < 0 to false.  */
11361       strict_overflow_p = false;
11362       if (code == LT_EXPR
11363           && (integer_zerop (arg1) || real_zerop (arg1))
11364           && tree_expr_nonnegative_warnv_p (arg0, &strict_overflow_p))
11365         {
11366           if (strict_overflow_p)
11367             fold_overflow_warning (("assuming signed overflow does not occur "
11368                                     "when simplifying comparison of "
11369                                     "absolute value and zero"),
11370                                    WARN_STRICT_OVERFLOW_CONDITIONAL);
11371           return omit_one_operand_loc (loc, type,
11372                                        constant_boolean_node (false, type),
11373                                        arg0);
11374         }
11375
11376       /* If X is unsigned, convert X < (1 << Y) into X >> Y == 0
11377          and similarly for >= into !=.  */
11378       if ((code == LT_EXPR || code == GE_EXPR)
11379           && TYPE_UNSIGNED (TREE_TYPE (arg0))
11380           && TREE_CODE (arg1) == LSHIFT_EXPR
11381           && integer_onep (TREE_OPERAND (arg1, 0)))
11382         return build2_loc (loc, code == LT_EXPR ? EQ_EXPR : NE_EXPR, type,
11383                            build2 (RSHIFT_EXPR, TREE_TYPE (arg0), arg0,
11384                                    TREE_OPERAND (arg1, 1)),
11385                            build_zero_cst (TREE_TYPE (arg0)));
11386
11387       /* Similarly for X < (cast) (1 << Y).  But cast can't be narrowing,
11388          otherwise Y might be >= # of bits in X's type and thus e.g.
11389          (unsigned char) (1 << Y) for Y 15 might be 0.
11390          If the cast is widening, then 1 << Y should have unsigned type,
11391          otherwise if Y is number of bits in the signed shift type minus 1,
11392          we can't optimize this.  E.g. (unsigned long long) (1 << Y) for Y
11393          31 might be 0xffffffff80000000.  */
11394       if ((code == LT_EXPR || code == GE_EXPR)
11395           && TYPE_UNSIGNED (TREE_TYPE (arg0))
11396           && CONVERT_EXPR_P (arg1)
11397           && TREE_CODE (TREE_OPERAND (arg1, 0)) == LSHIFT_EXPR
11398           && (element_precision (TREE_TYPE (arg1))
11399               >= element_precision (TREE_TYPE (TREE_OPERAND (arg1, 0))))
11400           && (TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (arg1, 0)))
11401               || (element_precision (TREE_TYPE (arg1))
11402                   == element_precision (TREE_TYPE (TREE_OPERAND (arg1, 0)))))
11403           && integer_onep (TREE_OPERAND (TREE_OPERAND (arg1, 0), 0)))
11404         {
11405           tem = build2 (RSHIFT_EXPR, TREE_TYPE (arg0), arg0,
11406                         TREE_OPERAND (TREE_OPERAND (arg1, 0), 1));
11407           return build2_loc (loc, code == LT_EXPR ? EQ_EXPR : NE_EXPR, type,
11408                              fold_convert_loc (loc, TREE_TYPE (arg0), tem),
11409                              build_zero_cst (TREE_TYPE (arg0)));
11410         }
11411
11412       return NULL_TREE;
11413
11414     case UNORDERED_EXPR:
11415     case ORDERED_EXPR:
11416     case UNLT_EXPR:
11417     case UNLE_EXPR:
11418     case UNGT_EXPR:
11419     case UNGE_EXPR:
11420     case UNEQ_EXPR:
11421     case LTGT_EXPR:
11422       /* Fold (double)float1 CMP (double)float2 into float1 CMP float2.  */
11423       {
11424         tree targ0 = strip_float_extensions (arg0);
11425         tree targ1 = strip_float_extensions (arg1);
11426         tree newtype = TREE_TYPE (targ0);
11427
11428         if (TYPE_PRECISION (TREE_TYPE (targ1)) > TYPE_PRECISION (newtype))
11429           newtype = TREE_TYPE (targ1);
11430
11431         if (TYPE_PRECISION (newtype) < TYPE_PRECISION (TREE_TYPE (arg0)))
11432           return fold_build2_loc (loc, code, type,
11433                               fold_convert_loc (loc, newtype, targ0),
11434                               fold_convert_loc (loc, newtype, targ1));
11435       }
11436
11437       return NULL_TREE;
11438
11439     case COMPOUND_EXPR:
11440       /* When pedantic, a compound expression can be neither an lvalue
11441          nor an integer constant expression.  */
11442       if (TREE_SIDE_EFFECTS (arg0) || TREE_CONSTANT (arg1))
11443         return NULL_TREE;
11444       /* Don't let (0, 0) be null pointer constant.  */
11445       tem = integer_zerop (arg1) ? build1 (NOP_EXPR, type, arg1)
11446                                  : fold_convert_loc (loc, type, arg1);
11447       return pedantic_non_lvalue_loc (loc, tem);
11448
11449     case ASSERT_EXPR:
11450       /* An ASSERT_EXPR should never be passed to fold_binary.  */
11451       gcc_unreachable ();
11452
11453     default:
11454       return NULL_TREE;
11455     } /* switch (code) */
11456 }
11457
11458 /* Callback for walk_tree, looking for LABEL_EXPR.  Return *TP if it is
11459    a LABEL_EXPR; otherwise return NULL_TREE.  Do not check the subtrees
11460    of GOTO_EXPR.  */
11461
11462 static tree
11463 contains_label_1 (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED)
11464 {
11465   switch (TREE_CODE (*tp))
11466     {
11467     case LABEL_EXPR:
11468       return *tp;
11469
11470     case GOTO_EXPR:
11471       *walk_subtrees = 0;
11472
11473       /* ... fall through ...  */
11474
11475     default:
11476       return NULL_TREE;
11477     }
11478 }
11479
11480 /* Return whether the sub-tree ST contains a label which is accessible from
11481    outside the sub-tree.  */
11482
11483 static bool
11484 contains_label_p (tree st)
11485 {
11486   return
11487    (walk_tree_without_duplicates (&st, contains_label_1 , NULL) != NULL_TREE);
11488 }
11489
11490 /* Fold a ternary expression of code CODE and type TYPE with operands
11491    OP0, OP1, and OP2.  Return the folded expression if folding is
11492    successful.  Otherwise, return NULL_TREE.  */
11493
11494 tree
11495 fold_ternary_loc (location_t loc, enum tree_code code, tree type,
11496                   tree op0, tree op1, tree op2)
11497 {
11498   tree tem;
11499   tree arg0 = NULL_TREE, arg1 = NULL_TREE, arg2 = NULL_TREE;
11500   enum tree_code_class kind = TREE_CODE_CLASS (code);
11501
11502   gcc_assert (IS_EXPR_CODE_CLASS (kind)
11503               && TREE_CODE_LENGTH (code) == 3);
11504
11505   /* If this is a commutative operation, and OP0 is a constant, move it
11506      to OP1 to reduce the number of tests below.  */
11507   if (commutative_ternary_tree_code (code)
11508       && tree_swap_operands_p (op0, op1, true))
11509     return fold_build3_loc (loc, code, type, op1, op0, op2);
11510
11511   tem = generic_simplify (loc, code, type, op0, op1, op2);
11512   if (tem)
11513     return tem;
11514
11515   /* Strip any conversions that don't change the mode.  This is safe
11516      for every expression, except for a comparison expression because
11517      its signedness is derived from its operands.  So, in the latter
11518      case, only strip conversions that don't change the signedness.
11519
11520      Note that this is done as an internal manipulation within the
11521      constant folder, in order to find the simplest representation of
11522      the arguments so that their form can be studied.  In any cases,
11523      the appropriate type conversions should be put back in the tree
11524      that will get out of the constant folder.  */
11525   if (op0)
11526     {
11527       arg0 = op0;
11528       STRIP_NOPS (arg0);
11529     }
11530
11531   if (op1)
11532     {
11533       arg1 = op1;
11534       STRIP_NOPS (arg1);
11535     }
11536
11537   if (op2)
11538     {
11539       arg2 = op2;
11540       STRIP_NOPS (arg2);
11541     }
11542
11543   switch (code)
11544     {
11545     case COMPONENT_REF:
11546       if (TREE_CODE (arg0) == CONSTRUCTOR
11547           && ! type_contains_placeholder_p (TREE_TYPE (arg0)))
11548         {
11549           unsigned HOST_WIDE_INT idx;
11550           tree field, value;
11551           FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg0), idx, field, value)
11552             if (field == arg1)
11553               return value;
11554         }
11555       return NULL_TREE;
11556
11557     case COND_EXPR:
11558     case VEC_COND_EXPR:
11559       /* Pedantic ANSI C says that a conditional expression is never an lvalue,
11560          so all simple results must be passed through pedantic_non_lvalue.  */
11561       if (TREE_CODE (arg0) == INTEGER_CST)
11562         {
11563           tree unused_op = integer_zerop (arg0) ? op1 : op2;
11564           tem = integer_zerop (arg0) ? op2 : op1;
11565           /* Only optimize constant conditions when the selected branch
11566              has the same type as the COND_EXPR.  This avoids optimizing
11567              away "c ? x : throw", where the throw has a void type.
11568              Avoid throwing away that operand which contains label.  */
11569           if ((!TREE_SIDE_EFFECTS (unused_op)
11570                || !contains_label_p (unused_op))
11571               && (! VOID_TYPE_P (TREE_TYPE (tem))
11572                   || VOID_TYPE_P (type)))
11573             return pedantic_non_lvalue_loc (loc, tem);
11574           return NULL_TREE;
11575         }
11576       else if (TREE_CODE (arg0) == VECTOR_CST)
11577         {
11578           if ((TREE_CODE (arg1) == VECTOR_CST
11579                || TREE_CODE (arg1) == CONSTRUCTOR)
11580               && (TREE_CODE (arg2) == VECTOR_CST
11581                   || TREE_CODE (arg2) == CONSTRUCTOR))
11582             {
11583               unsigned int nelts = TYPE_VECTOR_SUBPARTS (type), i;
11584               unsigned char *sel = XALLOCAVEC (unsigned char, nelts);
11585               gcc_assert (nelts == VECTOR_CST_NELTS (arg0));
11586               for (i = 0; i < nelts; i++)
11587                 {
11588                   tree val = VECTOR_CST_ELT (arg0, i);
11589                   if (integer_all_onesp (val))
11590                     sel[i] = i;
11591                   else if (integer_zerop (val))
11592                     sel[i] = nelts + i;
11593                   else /* Currently unreachable.  */
11594                     return NULL_TREE;
11595                 }
11596               tree t = fold_vec_perm (type, arg1, arg2, sel);
11597               if (t != NULL_TREE)
11598                 return t;
11599             }
11600         }
11601
11602       /* If we have A op B ? A : C, we may be able to convert this to a
11603          simpler expression, depending on the operation and the values
11604          of B and C.  Signed zeros prevent all of these transformations,
11605          for reasons given above each one.
11606
11607          Also try swapping the arguments and inverting the conditional.  */
11608       if (COMPARISON_CLASS_P (arg0)
11609           && operand_equal_for_comparison_p (TREE_OPERAND (arg0, 0),
11610                                              arg1, TREE_OPERAND (arg0, 1))
11611           && !HONOR_SIGNED_ZEROS (element_mode (arg1)))
11612         {
11613           tem = fold_cond_expr_with_comparison (loc, type, arg0, op1, op2);
11614           if (tem)
11615             return tem;
11616         }
11617
11618       if (COMPARISON_CLASS_P (arg0)
11619           && operand_equal_for_comparison_p (TREE_OPERAND (arg0, 0),
11620                                              op2,
11621                                              TREE_OPERAND (arg0, 1))
11622           && !HONOR_SIGNED_ZEROS (element_mode (op2)))
11623         {
11624           location_t loc0 = expr_location_or (arg0, loc);
11625           tem = fold_invert_truthvalue (loc0, arg0);
11626           if (tem && COMPARISON_CLASS_P (tem))
11627             {
11628               tem = fold_cond_expr_with_comparison (loc, type, tem, op2, op1);
11629               if (tem)
11630                 return tem;
11631             }
11632         }
11633
11634       /* If the second operand is simpler than the third, swap them
11635          since that produces better jump optimization results.  */
11636       if (truth_value_p (TREE_CODE (arg0))
11637           && tree_swap_operands_p (op1, op2, false))
11638         {
11639           location_t loc0 = expr_location_or (arg0, loc);
11640           /* See if this can be inverted.  If it can't, possibly because
11641              it was a floating-point inequality comparison, don't do
11642              anything.  */
11643           tem = fold_invert_truthvalue (loc0, arg0);
11644           if (tem)
11645             return fold_build3_loc (loc, code, type, tem, op2, op1);
11646         }
11647
11648       /* Convert A ? 1 : 0 to simply A.  */
11649       if ((code == VEC_COND_EXPR ? integer_all_onesp (op1)
11650                                  : (integer_onep (op1)
11651                                     && !VECTOR_TYPE_P (type)))
11652           && integer_zerop (op2)
11653           /* If we try to convert OP0 to our type, the
11654              call to fold will try to move the conversion inside
11655              a COND, which will recurse.  In that case, the COND_EXPR
11656              is probably the best choice, so leave it alone.  */
11657           && type == TREE_TYPE (arg0))
11658         return pedantic_non_lvalue_loc (loc, arg0);
11659
11660       /* Convert A ? 0 : 1 to !A.  This prefers the use of NOT_EXPR
11661          over COND_EXPR in cases such as floating point comparisons.  */
11662       if (integer_zerop (op1)
11663           && code == COND_EXPR
11664           && integer_onep (op2)
11665           && !VECTOR_TYPE_P (type)
11666           && truth_value_p (TREE_CODE (arg0)))
11667         return pedantic_non_lvalue_loc (loc,
11668                                     fold_convert_loc (loc, type,
11669                                               invert_truthvalue_loc (loc,
11670                                                                      arg0)));
11671
11672       /* A < 0 ? <sign bit of A> : 0 is simply (A & <sign bit of A>).  */
11673       if (TREE_CODE (arg0) == LT_EXPR
11674           && integer_zerop (TREE_OPERAND (arg0, 1))
11675           && integer_zerop (op2)
11676           && (tem = sign_bit_p (TREE_OPERAND (arg0, 0), arg1)))
11677         {
11678           /* sign_bit_p looks through both zero and sign extensions,
11679              but for this optimization only sign extensions are
11680              usable.  */
11681           tree tem2 = TREE_OPERAND (arg0, 0);
11682           while (tem != tem2)
11683             {
11684               if (TREE_CODE (tem2) != NOP_EXPR
11685                   || TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (tem2, 0))))
11686                 {
11687                   tem = NULL_TREE;
11688                   break;
11689                 }
11690               tem2 = TREE_OPERAND (tem2, 0);
11691             }
11692           /* sign_bit_p only checks ARG1 bits within A's precision.
11693              If <sign bit of A> has wider type than A, bits outside
11694              of A's precision in <sign bit of A> need to be checked.
11695              If they are all 0, this optimization needs to be done
11696              in unsigned A's type, if they are all 1 in signed A's type,
11697              otherwise this can't be done.  */
11698           if (tem
11699               && TYPE_PRECISION (TREE_TYPE (tem))
11700                  < TYPE_PRECISION (TREE_TYPE (arg1))
11701               && TYPE_PRECISION (TREE_TYPE (tem))
11702                  < TYPE_PRECISION (type))
11703             {
11704               int inner_width, outer_width;
11705               tree tem_type;
11706
11707               inner_width = TYPE_PRECISION (TREE_TYPE (tem));
11708               outer_width = TYPE_PRECISION (TREE_TYPE (arg1));
11709               if (outer_width > TYPE_PRECISION (type))
11710                 outer_width = TYPE_PRECISION (type);
11711
11712               wide_int mask = wi::shifted_mask
11713                 (inner_width, outer_width - inner_width, false,
11714                  TYPE_PRECISION (TREE_TYPE (arg1)));
11715
11716               wide_int common = mask & arg1;
11717               if (common == mask)
11718                 {
11719                   tem_type = signed_type_for (TREE_TYPE (tem));
11720                   tem = fold_convert_loc (loc, tem_type, tem);
11721                 }
11722               else if (common == 0)
11723                 {
11724                   tem_type = unsigned_type_for (TREE_TYPE (tem));
11725                   tem = fold_convert_loc (loc, tem_type, tem);
11726                 }
11727               else
11728                 tem = NULL;
11729             }
11730
11731           if (tem)
11732             return
11733               fold_convert_loc (loc, type,
11734                                 fold_build2_loc (loc, BIT_AND_EXPR,
11735                                              TREE_TYPE (tem), tem,
11736                                              fold_convert_loc (loc,
11737                                                                TREE_TYPE (tem),
11738                                                                arg1)));
11739         }
11740
11741       /* (A >> N) & 1 ? (1 << N) : 0 is simply A & (1 << N).  A & 1 was
11742          already handled above.  */
11743       if (TREE_CODE (arg0) == BIT_AND_EXPR
11744           && integer_onep (TREE_OPERAND (arg0, 1))
11745           && integer_zerop (op2)
11746           && integer_pow2p (arg1))
11747         {
11748           tree tem = TREE_OPERAND (arg0, 0);
11749           STRIP_NOPS (tem);
11750           if (TREE_CODE (tem) == RSHIFT_EXPR
11751               && tree_fits_uhwi_p (TREE_OPERAND (tem, 1))
11752               && (unsigned HOST_WIDE_INT) tree_log2 (arg1) ==
11753                  tree_to_uhwi (TREE_OPERAND (tem, 1)))
11754             return fold_build2_loc (loc, BIT_AND_EXPR, type,
11755                                 TREE_OPERAND (tem, 0), arg1);
11756         }
11757
11758       /* A & N ? N : 0 is simply A & N if N is a power of two.  This
11759          is probably obsolete because the first operand should be a
11760          truth value (that's why we have the two cases above), but let's
11761          leave it in until we can confirm this for all front-ends.  */
11762       if (integer_zerop (op2)
11763           && TREE_CODE (arg0) == NE_EXPR
11764           && integer_zerop (TREE_OPERAND (arg0, 1))
11765           && integer_pow2p (arg1)
11766           && TREE_CODE (TREE_OPERAND (arg0, 0)) == BIT_AND_EXPR
11767           && operand_equal_p (TREE_OPERAND (TREE_OPERAND (arg0, 0), 1),
11768                               arg1, OEP_ONLY_CONST))
11769         return pedantic_non_lvalue_loc (loc,
11770                                     fold_convert_loc (loc, type,
11771                                                       TREE_OPERAND (arg0, 0)));
11772
11773       /* Disable the transformations below for vectors, since
11774          fold_binary_op_with_conditional_arg may undo them immediately,
11775          yielding an infinite loop.  */
11776       if (code == VEC_COND_EXPR)
11777         return NULL_TREE;
11778
11779       /* Convert A ? B : 0 into A && B if A and B are truth values.  */
11780       if (integer_zerop (op2)
11781           && truth_value_p (TREE_CODE (arg0))
11782           && truth_value_p (TREE_CODE (arg1))
11783           && (code == VEC_COND_EXPR || !VECTOR_TYPE_P (type)))
11784         return fold_build2_loc (loc, code == VEC_COND_EXPR ? BIT_AND_EXPR
11785                                                            : TRUTH_ANDIF_EXPR,
11786                                 type, fold_convert_loc (loc, type, arg0), arg1);
11787
11788       /* Convert A ? B : 1 into !A || B if A and B are truth values.  */
11789       if (code == VEC_COND_EXPR ? integer_all_onesp (op2) : integer_onep (op2)
11790           && truth_value_p (TREE_CODE (arg0))
11791           && truth_value_p (TREE_CODE (arg1))
11792           && (code == VEC_COND_EXPR || !VECTOR_TYPE_P (type)))
11793         {
11794           location_t loc0 = expr_location_or (arg0, loc);
11795           /* Only perform transformation if ARG0 is easily inverted.  */
11796           tem = fold_invert_truthvalue (loc0, arg0);
11797           if (tem)
11798             return fold_build2_loc (loc, code == VEC_COND_EXPR
11799                                          ? BIT_IOR_EXPR
11800                                          : TRUTH_ORIF_EXPR,
11801                                     type, fold_convert_loc (loc, type, tem),
11802                                     arg1);
11803         }
11804
11805       /* Convert A ? 0 : B into !A && B if A and B are truth values.  */
11806       if (integer_zerop (arg1)
11807           && truth_value_p (TREE_CODE (arg0))
11808           && truth_value_p (TREE_CODE (op2))
11809           && (code == VEC_COND_EXPR || !VECTOR_TYPE_P (type)))
11810         {
11811           location_t loc0 = expr_location_or (arg0, loc);
11812           /* Only perform transformation if ARG0 is easily inverted.  */
11813           tem = fold_invert_truthvalue (loc0, arg0);
11814           if (tem)
11815             return fold_build2_loc (loc, code == VEC_COND_EXPR
11816                                          ? BIT_AND_EXPR : TRUTH_ANDIF_EXPR,
11817                                     type, fold_convert_loc (loc, type, tem),
11818                                     op2);
11819         }
11820
11821       /* Convert A ? 1 : B into A || B if A and B are truth values.  */
11822       if (code == VEC_COND_EXPR ? integer_all_onesp (arg1) : integer_onep (arg1)
11823           && truth_value_p (TREE_CODE (arg0))
11824           && truth_value_p (TREE_CODE (op2))
11825           && (code == VEC_COND_EXPR || !VECTOR_TYPE_P (type)))
11826         return fold_build2_loc (loc, code == VEC_COND_EXPR
11827                                      ? BIT_IOR_EXPR : TRUTH_ORIF_EXPR,
11828                                 type, fold_convert_loc (loc, type, arg0), op2);
11829
11830       return NULL_TREE;
11831
11832     case CALL_EXPR:
11833       /* CALL_EXPRs used to be ternary exprs.  Catch any mistaken uses
11834          of fold_ternary on them.  */
11835       gcc_unreachable ();
11836
11837     case BIT_FIELD_REF:
11838       if ((TREE_CODE (arg0) == VECTOR_CST
11839            || (TREE_CODE (arg0) == CONSTRUCTOR
11840                && TREE_CODE (TREE_TYPE (arg0)) == VECTOR_TYPE))
11841           && (type == TREE_TYPE (TREE_TYPE (arg0))
11842               || (TREE_CODE (type) == VECTOR_TYPE
11843                   && TREE_TYPE (type) == TREE_TYPE (TREE_TYPE (arg0)))))
11844         {
11845           tree eltype = TREE_TYPE (TREE_TYPE (arg0));
11846           unsigned HOST_WIDE_INT width = tree_to_uhwi (TYPE_SIZE (eltype));
11847           unsigned HOST_WIDE_INT n = tree_to_uhwi (arg1);
11848           unsigned HOST_WIDE_INT idx = tree_to_uhwi (op2);
11849
11850           if (n != 0
11851               && (idx % width) == 0
11852               && (n % width) == 0
11853               && ((idx + n) / width) <= TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0)))
11854             {
11855               idx = idx / width;
11856               n = n / width;
11857
11858               if (TREE_CODE (arg0) == VECTOR_CST)
11859                 {
11860                   if (n == 1)
11861                     return VECTOR_CST_ELT (arg0, idx);
11862
11863                   tree *vals = XALLOCAVEC (tree, n);
11864                   for (unsigned i = 0; i < n; ++i)
11865                     vals[i] = VECTOR_CST_ELT (arg0, idx + i);
11866                   return build_vector (type, vals);
11867                 }
11868
11869               /* Constructor elements can be subvectors.  */
11870               unsigned HOST_WIDE_INT k = 1;
11871               if (CONSTRUCTOR_NELTS (arg0) != 0)
11872                 {
11873                   tree cons_elem = TREE_TYPE (CONSTRUCTOR_ELT (arg0, 0)->value);
11874                   if (TREE_CODE (cons_elem) == VECTOR_TYPE)
11875                     k = TYPE_VECTOR_SUBPARTS (cons_elem);
11876                 }
11877
11878               /* We keep an exact subset of the constructor elements.  */
11879               if ((idx % k) == 0 && (n % k) == 0)
11880                 {
11881                   if (CONSTRUCTOR_NELTS (arg0) == 0)
11882                     return build_constructor (type, NULL);
11883                   idx /= k;
11884                   n /= k;
11885                   if (n == 1)
11886                     {
11887                       if (idx < CONSTRUCTOR_NELTS (arg0))
11888                         return CONSTRUCTOR_ELT (arg0, idx)->value;
11889                       return build_zero_cst (type);
11890                     }
11891
11892                   vec<constructor_elt, va_gc> *vals;
11893                   vec_alloc (vals, n);
11894                   for (unsigned i = 0;
11895                        i < n && idx + i < CONSTRUCTOR_NELTS (arg0);
11896                        ++i)
11897                     CONSTRUCTOR_APPEND_ELT (vals, NULL_TREE,
11898                                             CONSTRUCTOR_ELT
11899                                               (arg0, idx + i)->value);
11900                   return build_constructor (type, vals);
11901                 }
11902               /* The bitfield references a single constructor element.  */
11903               else if (idx + n <= (idx / k + 1) * k)
11904                 {
11905                   if (CONSTRUCTOR_NELTS (arg0) <= idx / k)
11906                     return build_zero_cst (type);
11907                   else if (n == k)
11908                     return CONSTRUCTOR_ELT (arg0, idx / k)->value;
11909                   else
11910                     return fold_build3_loc (loc, code, type,
11911                       CONSTRUCTOR_ELT (arg0, idx / k)->value, op1,
11912                       build_int_cst (TREE_TYPE (op2), (idx % k) * width));
11913                 }
11914             }
11915         }
11916
11917       /* A bit-field-ref that referenced the full argument can be stripped.  */
11918       if (INTEGRAL_TYPE_P (TREE_TYPE (arg0))
11919           && TYPE_PRECISION (TREE_TYPE (arg0)) == tree_to_uhwi (arg1)
11920           && integer_zerop (op2))
11921         return fold_convert_loc (loc, type, arg0);
11922
11923       /* On constants we can use native encode/interpret to constant
11924          fold (nearly) all BIT_FIELD_REFs.  */
11925       if (CONSTANT_CLASS_P (arg0)
11926           && can_native_interpret_type_p (type)
11927           && tree_fits_uhwi_p (TYPE_SIZE_UNIT (TREE_TYPE (arg0)))
11928           /* This limitation should not be necessary, we just need to
11929              round this up to mode size.  */
11930           && tree_to_uhwi (op1) % BITS_PER_UNIT == 0
11931           /* Need bit-shifting of the buffer to relax the following.  */
11932           && tree_to_uhwi (op2) % BITS_PER_UNIT == 0)
11933         {
11934           unsigned HOST_WIDE_INT bitpos = tree_to_uhwi (op2);
11935           unsigned HOST_WIDE_INT bitsize = tree_to_uhwi (op1);
11936           unsigned HOST_WIDE_INT clen;
11937           clen = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (arg0)));
11938           /* ???  We cannot tell native_encode_expr to start at
11939              some random byte only.  So limit us to a reasonable amount
11940              of work.  */
11941           if (clen <= 4096)
11942             {
11943               unsigned char *b = XALLOCAVEC (unsigned char, clen);
11944               unsigned HOST_WIDE_INT len = native_encode_expr (arg0, b, clen);
11945               if (len > 0
11946                   && len * BITS_PER_UNIT >= bitpos + bitsize)
11947                 {
11948                   tree v = native_interpret_expr (type,
11949                                                   b + bitpos / BITS_PER_UNIT,
11950                                                   bitsize / BITS_PER_UNIT);
11951                   if (v)
11952                     return v;
11953                 }
11954             }
11955         }
11956
11957       return NULL_TREE;
11958
11959     case FMA_EXPR:
11960       /* For integers we can decompose the FMA if possible.  */
11961       if (TREE_CODE (arg0) == INTEGER_CST
11962           && TREE_CODE (arg1) == INTEGER_CST)
11963         return fold_build2_loc (loc, PLUS_EXPR, type,
11964                                 const_binop (MULT_EXPR, arg0, arg1), arg2);
11965       if (integer_zerop (arg2))
11966         return fold_build2_loc (loc, MULT_EXPR, type, arg0, arg1);
11967
11968       return fold_fma (loc, type, arg0, arg1, arg2);
11969
11970     case VEC_PERM_EXPR:
11971       if (TREE_CODE (arg2) == VECTOR_CST)
11972         {
11973           unsigned int nelts = TYPE_VECTOR_SUBPARTS (type), i, mask, mask2;
11974           unsigned char *sel = XALLOCAVEC (unsigned char, 2 * nelts);
11975           unsigned char *sel2 = sel + nelts;
11976           bool need_mask_canon = false;
11977           bool need_mask_canon2 = false;
11978           bool all_in_vec0 = true;
11979           bool all_in_vec1 = true;
11980           bool maybe_identity = true;
11981           bool single_arg = (op0 == op1);
11982           bool changed = false;
11983
11984           mask2 = 2 * nelts - 1;
11985           mask = single_arg ? (nelts - 1) : mask2;
11986           gcc_assert (nelts == VECTOR_CST_NELTS (arg2));
11987           for (i = 0; i < nelts; i++)
11988             {
11989               tree val = VECTOR_CST_ELT (arg2, i);
11990               if (TREE_CODE (val) != INTEGER_CST)
11991                 return NULL_TREE;
11992
11993               /* Make sure that the perm value is in an acceptable
11994                  range.  */
11995               wide_int t = val;
11996               need_mask_canon |= wi::gtu_p (t, mask);
11997               need_mask_canon2 |= wi::gtu_p (t, mask2);
11998               sel[i] = t.to_uhwi () & mask;
11999               sel2[i] = t.to_uhwi () & mask2;
12000
12001               if (sel[i] < nelts)
12002                 all_in_vec1 = false;
12003               else
12004                 all_in_vec0 = false;
12005
12006               if ((sel[i] & (nelts-1)) != i)
12007                 maybe_identity = false;
12008             }
12009
12010           if (maybe_identity)
12011             {
12012               if (all_in_vec0)
12013                 return op0;
12014               if (all_in_vec1)
12015                 return op1;
12016             }
12017
12018           if (all_in_vec0)
12019             op1 = op0;
12020           else if (all_in_vec1)
12021             {
12022               op0 = op1;
12023               for (i = 0; i < nelts; i++)
12024                 sel[i] -= nelts;
12025               need_mask_canon = true;
12026             }
12027
12028           if ((TREE_CODE (op0) == VECTOR_CST
12029                || TREE_CODE (op0) == CONSTRUCTOR)
12030               && (TREE_CODE (op1) == VECTOR_CST
12031                   || TREE_CODE (op1) == CONSTRUCTOR))
12032             {
12033               tree t = fold_vec_perm (type, op0, op1, sel);
12034               if (t != NULL_TREE)
12035                 return t;
12036             }
12037
12038           if (op0 == op1 && !single_arg)
12039             changed = true;
12040
12041           /* Some targets are deficient and fail to expand a single
12042              argument permutation while still allowing an equivalent
12043              2-argument version.  */
12044           if (need_mask_canon && arg2 == op2
12045               && !can_vec_perm_p (TYPE_MODE (type), false, sel)
12046               && can_vec_perm_p (TYPE_MODE (type), false, sel2))
12047             {
12048               need_mask_canon = need_mask_canon2;
12049               sel = sel2;
12050             }
12051
12052           if (need_mask_canon && arg2 == op2)
12053             {
12054               tree *tsel = XALLOCAVEC (tree, nelts);
12055               tree eltype = TREE_TYPE (TREE_TYPE (arg2));
12056               for (i = 0; i < nelts; i++)
12057                 tsel[i] = build_int_cst (eltype, sel[i]);
12058               op2 = build_vector (TREE_TYPE (arg2), tsel);
12059               changed = true;
12060             }
12061
12062           if (changed)
12063             return build3_loc (loc, VEC_PERM_EXPR, type, op0, op1, op2);
12064         }
12065       return NULL_TREE;
12066
12067     default:
12068       return NULL_TREE;
12069     } /* switch (code) */
12070 }
12071
12072 /* Gets the element ACCESS_INDEX from CTOR, which must be a CONSTRUCTOR
12073    of an array (or vector).  */
12074
12075 tree
12076 get_array_ctor_element_at_index (tree ctor, offset_int access_index)
12077 {
12078   tree index_type = NULL_TREE;
12079   offset_int low_bound = 0;
12080
12081   if (TREE_CODE (TREE_TYPE (ctor)) == ARRAY_TYPE)
12082     {
12083       tree domain_type = TYPE_DOMAIN (TREE_TYPE (ctor));
12084       if (domain_type && TYPE_MIN_VALUE (domain_type))
12085         {
12086           /* Static constructors for variably sized objects makes no sense.  */
12087           gcc_assert (TREE_CODE (TYPE_MIN_VALUE (domain_type)) == INTEGER_CST);
12088           index_type = TREE_TYPE (TYPE_MIN_VALUE (domain_type));
12089           low_bound = wi::to_offset (TYPE_MIN_VALUE (domain_type));
12090         }
12091     }
12092
12093   if (index_type)
12094     access_index = wi::ext (access_index, TYPE_PRECISION (index_type),
12095                             TYPE_SIGN (index_type));
12096
12097   offset_int index = low_bound - 1;
12098   if (index_type)
12099     index = wi::ext (index, TYPE_PRECISION (index_type),
12100                      TYPE_SIGN (index_type));
12101
12102   offset_int max_index;
12103   unsigned HOST_WIDE_INT cnt;
12104   tree cfield, cval;
12105
12106   FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), cnt, cfield, cval)
12107     {
12108       /* Array constructor might explicitly set index, or specify a range,
12109          or leave index NULL meaning that it is next index after previous
12110          one.  */
12111       if (cfield)
12112         {
12113           if (TREE_CODE (cfield) == INTEGER_CST)
12114             max_index = index = wi::to_offset (cfield);
12115           else
12116             {
12117               gcc_assert (TREE_CODE (cfield) == RANGE_EXPR);
12118               index = wi::to_offset (TREE_OPERAND (cfield, 0));
12119               max_index = wi::to_offset (TREE_OPERAND (cfield, 1));
12120             }
12121         }
12122       else
12123         {
12124           index += 1;
12125           if (index_type)
12126             index = wi::ext (index, TYPE_PRECISION (index_type),
12127                              TYPE_SIGN (index_type));
12128           max_index = index;
12129         }
12130
12131     /* Do we have match?  */
12132     if (wi::cmpu (access_index, index) >= 0
12133         && wi::cmpu (access_index, max_index) <= 0)
12134       return cval;
12135   }
12136   return NULL_TREE;
12137 }
12138
12139 /* Perform constant folding and related simplification of EXPR.
12140    The related simplifications include x*1 => x, x*0 => 0, etc.,
12141    and application of the associative law.
12142    NOP_EXPR conversions may be removed freely (as long as we
12143    are careful not to change the type of the overall expression).
12144    We cannot simplify through a CONVERT_EXPR, FIX_EXPR or FLOAT_EXPR,
12145    but we can constant-fold them if they have constant operands.  */
12146
12147 #ifdef ENABLE_FOLD_CHECKING
12148 # define fold(x) fold_1 (x)
12149 static tree fold_1 (tree);
12150 static
12151 #endif
12152 tree
12153 fold (tree expr)
12154 {
12155   const tree t = expr;
12156   enum tree_code code = TREE_CODE (t);
12157   enum tree_code_class kind = TREE_CODE_CLASS (code);
12158   tree tem;
12159   location_t loc = EXPR_LOCATION (expr);
12160
12161   /* Return right away if a constant.  */
12162   if (kind == tcc_constant)
12163     return t;
12164
12165   /* CALL_EXPR-like objects with variable numbers of operands are
12166      treated specially.  */
12167   if (kind == tcc_vl_exp)
12168     {
12169       if (code == CALL_EXPR)
12170         {
12171           tem = fold_call_expr (loc, expr, false);
12172           return tem ? tem : expr;
12173         }
12174       return expr;
12175     }
12176
12177   if (IS_EXPR_CODE_CLASS (kind))
12178     {
12179       tree type = TREE_TYPE (t);
12180       tree op0, op1, op2;
12181
12182       switch (TREE_CODE_LENGTH (code))
12183         {
12184         case 1:
12185           op0 = TREE_OPERAND (t, 0);
12186           tem = fold_unary_loc (loc, code, type, op0);
12187           return tem ? tem : expr;
12188         case 2:
12189           op0 = TREE_OPERAND (t, 0);
12190           op1 = TREE_OPERAND (t, 1);
12191           tem = fold_binary_loc (loc, code, type, op0, op1);
12192           return tem ? tem : expr;
12193         case 3:
12194           op0 = TREE_OPERAND (t, 0);
12195           op1 = TREE_OPERAND (t, 1);
12196           op2 = TREE_OPERAND (t, 2);
12197           tem = fold_ternary_loc (loc, code, type, op0, op1, op2);
12198           return tem ? tem : expr;
12199         default:
12200           break;
12201         }
12202     }
12203
12204   switch (code)
12205     {
12206     case ARRAY_REF:
12207       {
12208         tree op0 = TREE_OPERAND (t, 0);
12209         tree op1 = TREE_OPERAND (t, 1);
12210
12211         if (TREE_CODE (op1) == INTEGER_CST
12212             && TREE_CODE (op0) == CONSTRUCTOR
12213             && ! type_contains_placeholder_p (TREE_TYPE (op0)))
12214           {
12215             tree val = get_array_ctor_element_at_index (op0,
12216                                                         wi::to_offset (op1));
12217             if (val)
12218               return val;
12219           }
12220
12221         return t;
12222       }
12223
12224       /* Return a VECTOR_CST if possible.  */
12225     case CONSTRUCTOR:
12226       {
12227         tree type = TREE_TYPE (t);
12228         if (TREE_CODE (type) != VECTOR_TYPE)
12229           return t;
12230
12231         unsigned i;
12232         tree val;
12233         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (t), i, val)
12234           if (! CONSTANT_CLASS_P (val))
12235             return t;
12236
12237         return build_vector_from_ctor (type, CONSTRUCTOR_ELTS (t));
12238       }
12239
12240     case CONST_DECL:
12241       return fold (DECL_INITIAL (t));
12242
12243     default:
12244       return t;
12245     } /* switch (code) */
12246 }
12247
12248 #ifdef ENABLE_FOLD_CHECKING
12249 #undef fold
12250
12251 static void fold_checksum_tree (const_tree, struct md5_ctx *,
12252                                 hash_table<nofree_ptr_hash<const tree_node> > *);
12253 static void fold_check_failed (const_tree, const_tree);
12254 void print_fold_checksum (const_tree);
12255
12256 /* When --enable-checking=fold, compute a digest of expr before
12257    and after actual fold call to see if fold did not accidentally
12258    change original expr.  */
12259
12260 tree
12261 fold (tree expr)
12262 {
12263   tree ret;
12264   struct md5_ctx ctx;
12265   unsigned char checksum_before[16], checksum_after[16];
12266   hash_table<nofree_ptr_hash<const tree_node> > ht (32);
12267
12268   md5_init_ctx (&ctx);
12269   fold_checksum_tree (expr, &ctx, &ht);
12270   md5_finish_ctx (&ctx, checksum_before);
12271   ht.empty ();
12272
12273   ret = fold_1 (expr);
12274
12275   md5_init_ctx (&ctx);
12276   fold_checksum_tree (expr, &ctx, &ht);
12277   md5_finish_ctx (&ctx, checksum_after);
12278
12279   if (memcmp (checksum_before, checksum_after, 16))
12280     fold_check_failed (expr, ret);
12281
12282   return ret;
12283 }
12284
12285 void
12286 print_fold_checksum (const_tree expr)
12287 {
12288   struct md5_ctx ctx;
12289   unsigned char checksum[16], cnt;
12290   hash_table<nofree_ptr_hash<const tree_node> > ht (32);
12291
12292   md5_init_ctx (&ctx);
12293   fold_checksum_tree (expr, &ctx, &ht);
12294   md5_finish_ctx (&ctx, checksum);
12295   for (cnt = 0; cnt < 16; ++cnt)
12296     fprintf (stderr, "%02x", checksum[cnt]);
12297   putc ('\n', stderr);
12298 }
12299
12300 static void
12301 fold_check_failed (const_tree expr ATTRIBUTE_UNUSED, const_tree ret ATTRIBUTE_UNUSED)
12302 {
12303   internal_error ("fold check: original tree changed by fold");
12304 }
12305
12306 static void
12307 fold_checksum_tree (const_tree expr, struct md5_ctx *ctx,
12308                     hash_table<nofree_ptr_hash <const tree_node> > *ht)
12309 {
12310   const tree_node **slot;
12311   enum tree_code code;
12312   union tree_node buf;
12313   int i, len;
12314
12315  recursive_label:
12316   if (expr == NULL)
12317     return;
12318   slot = ht->find_slot (expr, INSERT);
12319   if (*slot != NULL)
12320     return;
12321   *slot = expr;
12322   code = TREE_CODE (expr);
12323   if (TREE_CODE_CLASS (code) == tcc_declaration
12324       && HAS_DECL_ASSEMBLER_NAME_P (expr))
12325     {
12326       /* Allow DECL_ASSEMBLER_NAME and symtab_node to be modified.  */
12327       memcpy ((char *) &buf, expr, tree_size (expr));
12328       SET_DECL_ASSEMBLER_NAME ((tree)&buf, NULL);
12329       buf.decl_with_vis.symtab_node = NULL;
12330       expr = (tree) &buf;
12331     }
12332   else if (TREE_CODE_CLASS (code) == tcc_type
12333            && (TYPE_POINTER_TO (expr)
12334                || TYPE_REFERENCE_TO (expr)
12335                || TYPE_CACHED_VALUES_P (expr)
12336                || TYPE_CONTAINS_PLACEHOLDER_INTERNAL (expr)
12337                || TYPE_NEXT_VARIANT (expr)
12338                || TYPE_ALIAS_SET_KNOWN_P (expr)))
12339     {
12340       /* Allow these fields to be modified.  */
12341       tree tmp;
12342       memcpy ((char *) &buf, expr, tree_size (expr));
12343       expr = tmp = (tree) &buf;
12344       TYPE_CONTAINS_PLACEHOLDER_INTERNAL (tmp) = 0;
12345       TYPE_POINTER_TO (tmp) = NULL;
12346       TYPE_REFERENCE_TO (tmp) = NULL;
12347       TYPE_NEXT_VARIANT (tmp) = NULL;
12348       TYPE_ALIAS_SET (tmp) = -1;
12349       if (TYPE_CACHED_VALUES_P (tmp))
12350         {
12351           TYPE_CACHED_VALUES_P (tmp) = 0;
12352           TYPE_CACHED_VALUES (tmp) = NULL;
12353         }
12354     }
12355   md5_process_bytes (expr, tree_size (expr), ctx);
12356   if (CODE_CONTAINS_STRUCT (code, TS_TYPED))
12357     fold_checksum_tree (TREE_TYPE (expr), ctx, ht);
12358   if (TREE_CODE_CLASS (code) != tcc_type
12359       && TREE_CODE_CLASS (code) != tcc_declaration
12360       && code != TREE_LIST
12361       && code != SSA_NAME
12362       && CODE_CONTAINS_STRUCT (code, TS_COMMON))
12363     fold_checksum_tree (TREE_CHAIN (expr), ctx, ht);
12364   switch (TREE_CODE_CLASS (code))
12365     {
12366     case tcc_constant:
12367       switch (code)
12368         {
12369         case STRING_CST:
12370           md5_process_bytes (TREE_STRING_POINTER (expr),
12371                              TREE_STRING_LENGTH (expr), ctx);
12372           break;
12373         case COMPLEX_CST:
12374           fold_checksum_tree (TREE_REALPART (expr), ctx, ht);
12375           fold_checksum_tree (TREE_IMAGPART (expr), ctx, ht);
12376           break;
12377         case VECTOR_CST:
12378           for (i = 0; i < (int) VECTOR_CST_NELTS (expr); ++i)
12379             fold_checksum_tree (VECTOR_CST_ELT (expr, i), ctx, ht);
12380           break;
12381         default:
12382           break;
12383         }
12384       break;
12385     case tcc_exceptional:
12386       switch (code)
12387         {
12388         case TREE_LIST:
12389           fold_checksum_tree (TREE_PURPOSE (expr), ctx, ht);
12390           fold_checksum_tree (TREE_VALUE (expr), ctx, ht);
12391           expr = TREE_CHAIN (expr);
12392           goto recursive_label;
12393           break;
12394         case TREE_VEC:
12395           for (i = 0; i < TREE_VEC_LENGTH (expr); ++i)
12396             fold_checksum_tree (TREE_VEC_ELT (expr, i), ctx, ht);
12397           break;
12398         default:
12399           break;
12400         }
12401       break;
12402     case tcc_expression:
12403     case tcc_reference:
12404     case tcc_comparison:
12405     case tcc_unary:
12406     case tcc_binary:
12407     case tcc_statement:
12408     case tcc_vl_exp:
12409       len = TREE_OPERAND_LENGTH (expr);
12410       for (i = 0; i < len; ++i)
12411         fold_checksum_tree (TREE_OPERAND (expr, i), ctx, ht);
12412       break;
12413     case tcc_declaration:
12414       fold_checksum_tree (DECL_NAME (expr), ctx, ht);
12415       fold_checksum_tree (DECL_CONTEXT (expr), ctx, ht);
12416       if (CODE_CONTAINS_STRUCT (TREE_CODE (expr), TS_DECL_COMMON))
12417         {
12418           fold_checksum_tree (DECL_SIZE (expr), ctx, ht);
12419           fold_checksum_tree (DECL_SIZE_UNIT (expr), ctx, ht);
12420           fold_checksum_tree (DECL_INITIAL (expr), ctx, ht);
12421           fold_checksum_tree (DECL_ABSTRACT_ORIGIN (expr), ctx, ht);
12422           fold_checksum_tree (DECL_ATTRIBUTES (expr), ctx, ht);
12423         }
12424
12425       if (CODE_CONTAINS_STRUCT (TREE_CODE (expr), TS_DECL_NON_COMMON))
12426         {
12427           if (TREE_CODE (expr) == FUNCTION_DECL)
12428             {
12429               fold_checksum_tree (DECL_VINDEX (expr), ctx, ht);
12430               fold_checksum_tree (DECL_ARGUMENTS (expr), ctx, ht);
12431             }
12432           fold_checksum_tree (DECL_RESULT_FLD (expr), ctx, ht);
12433         }
12434       break;
12435     case tcc_type:
12436       if (TREE_CODE (expr) == ENUMERAL_TYPE)
12437         fold_checksum_tree (TYPE_VALUES (expr), ctx, ht);
12438       fold_checksum_tree (TYPE_SIZE (expr), ctx, ht);
12439       fold_checksum_tree (TYPE_SIZE_UNIT (expr), ctx, ht);
12440       fold_checksum_tree (TYPE_ATTRIBUTES (expr), ctx, ht);
12441       fold_checksum_tree (TYPE_NAME (expr), ctx, ht);
12442       if (INTEGRAL_TYPE_P (expr)
12443           || SCALAR_FLOAT_TYPE_P (expr))
12444         {
12445           fold_checksum_tree (TYPE_MIN_VALUE (expr), ctx, ht);
12446           fold_checksum_tree (TYPE_MAX_VALUE (expr), ctx, ht);
12447         }
12448       fold_checksum_tree (TYPE_MAIN_VARIANT (expr), ctx, ht);
12449       if (TREE_CODE (expr) == RECORD_TYPE
12450           || TREE_CODE (expr) == UNION_TYPE
12451           || TREE_CODE (expr) == QUAL_UNION_TYPE)
12452         fold_checksum_tree (TYPE_BINFO (expr), ctx, ht);
12453       fold_checksum_tree (TYPE_CONTEXT (expr), ctx, ht);
12454       break;
12455     default:
12456       break;
12457     }
12458 }
12459
12460 /* Helper function for outputting the checksum of a tree T.  When
12461    debugging with gdb, you can "define mynext" to be "next" followed
12462    by "call debug_fold_checksum (op0)", then just trace down till the
12463    outputs differ.  */
12464
12465 DEBUG_FUNCTION void
12466 debug_fold_checksum (const_tree t)
12467 {
12468   int i;
12469   unsigned char checksum[16];
12470   struct md5_ctx ctx;
12471   hash_table<nofree_ptr_hash<const tree_node> > ht (32);
12472
12473   md5_init_ctx (&ctx);
12474   fold_checksum_tree (t, &ctx, &ht);
12475   md5_finish_ctx (&ctx, checksum);
12476   ht.empty ();
12477
12478   for (i = 0; i < 16; i++)
12479     fprintf (stderr, "%d ", checksum[i]);
12480
12481   fprintf (stderr, "\n");
12482 }
12483
12484 #endif
12485
12486 /* Fold a unary tree expression with code CODE of type TYPE with an
12487    operand OP0.  LOC is the location of the resulting expression.
12488    Return a folded expression if successful.  Otherwise, return a tree
12489    expression with code CODE of type TYPE with an operand OP0.  */
12490
12491 tree
12492 fold_build1_stat_loc (location_t loc,
12493                       enum tree_code code, tree type, tree op0 MEM_STAT_DECL)
12494 {
12495   tree tem;
12496 #ifdef ENABLE_FOLD_CHECKING
12497   unsigned char checksum_before[16], checksum_after[16];
12498   struct md5_ctx ctx;
12499   hash_table<nofree_ptr_hash<const tree_node> > ht (32);
12500
12501   md5_init_ctx (&ctx);
12502   fold_checksum_tree (op0, &ctx, &ht);
12503   md5_finish_ctx (&ctx, checksum_before);
12504   ht.empty ();
12505 #endif
12506
12507   tem = fold_unary_loc (loc, code, type, op0);
12508   if (!tem)
12509     tem = build1_stat_loc (loc, code, type, op0 PASS_MEM_STAT);
12510
12511 #ifdef ENABLE_FOLD_CHECKING
12512   md5_init_ctx (&ctx);
12513   fold_checksum_tree (op0, &ctx, &ht);
12514   md5_finish_ctx (&ctx, checksum_after);
12515
12516   if (memcmp (checksum_before, checksum_after, 16))
12517     fold_check_failed (op0, tem);
12518 #endif
12519   return tem;
12520 }
12521
12522 /* Fold a binary tree expression with code CODE of type TYPE with
12523    operands OP0 and OP1.  LOC is the location of the resulting
12524    expression.  Return a folded expression if successful.  Otherwise,
12525    return a tree expression with code CODE of type TYPE with operands
12526    OP0 and OP1.  */
12527
12528 tree
12529 fold_build2_stat_loc (location_t loc,
12530                       enum tree_code code, tree type, tree op0, tree op1
12531                       MEM_STAT_DECL)
12532 {
12533   tree tem;
12534 #ifdef ENABLE_FOLD_CHECKING
12535   unsigned char checksum_before_op0[16],
12536                 checksum_before_op1[16],
12537                 checksum_after_op0[16],
12538                 checksum_after_op1[16];
12539   struct md5_ctx ctx;
12540   hash_table<nofree_ptr_hash<const tree_node> > ht (32);
12541
12542   md5_init_ctx (&ctx);
12543   fold_checksum_tree (op0, &ctx, &ht);
12544   md5_finish_ctx (&ctx, checksum_before_op0);
12545   ht.empty ();
12546
12547   md5_init_ctx (&ctx);
12548   fold_checksum_tree (op1, &ctx, &ht);
12549   md5_finish_ctx (&ctx, checksum_before_op1);
12550   ht.empty ();
12551 #endif
12552
12553   tem = fold_binary_loc (loc, code, type, op0, op1);
12554   if (!tem)
12555     tem = build2_stat_loc (loc, code, type, op0, op1 PASS_MEM_STAT);
12556
12557 #ifdef ENABLE_FOLD_CHECKING
12558   md5_init_ctx (&ctx);
12559   fold_checksum_tree (op0, &ctx, &ht);
12560   md5_finish_ctx (&ctx, checksum_after_op0);
12561   ht.empty ();
12562
12563   if (memcmp (checksum_before_op0, checksum_after_op0, 16))
12564     fold_check_failed (op0, tem);
12565
12566   md5_init_ctx (&ctx);
12567   fold_checksum_tree (op1, &ctx, &ht);
12568   md5_finish_ctx (&ctx, checksum_after_op1);
12569
12570   if (memcmp (checksum_before_op1, checksum_after_op1, 16))
12571     fold_check_failed (op1, tem);
12572 #endif
12573   return tem;
12574 }
12575
12576 /* Fold a ternary tree expression with code CODE of type TYPE with
12577    operands OP0, OP1, and OP2.  Return a folded expression if
12578    successful.  Otherwise, return a tree expression with code CODE of
12579    type TYPE with operands OP0, OP1, and OP2.  */
12580
12581 tree
12582 fold_build3_stat_loc (location_t loc, enum tree_code code, tree type,
12583                       tree op0, tree op1, tree op2 MEM_STAT_DECL)
12584 {
12585   tree tem;
12586 #ifdef ENABLE_FOLD_CHECKING
12587   unsigned char checksum_before_op0[16],
12588                 checksum_before_op1[16],
12589                 checksum_before_op2[16],
12590                 checksum_after_op0[16],
12591                 checksum_after_op1[16],
12592                 checksum_after_op2[16];
12593   struct md5_ctx ctx;
12594   hash_table<nofree_ptr_hash<const tree_node> > ht (32);
12595
12596   md5_init_ctx (&ctx);
12597   fold_checksum_tree (op0, &ctx, &ht);
12598   md5_finish_ctx (&ctx, checksum_before_op0);
12599   ht.empty ();
12600
12601   md5_init_ctx (&ctx);
12602   fold_checksum_tree (op1, &ctx, &ht);
12603   md5_finish_ctx (&ctx, checksum_before_op1);
12604   ht.empty ();
12605
12606   md5_init_ctx (&ctx);
12607   fold_checksum_tree (op2, &ctx, &ht);
12608   md5_finish_ctx (&ctx, checksum_before_op2);
12609   ht.empty ();
12610 #endif
12611
12612   gcc_assert (TREE_CODE_CLASS (code) != tcc_vl_exp);
12613   tem = fold_ternary_loc (loc, code, type, op0, op1, op2);
12614   if (!tem)
12615     tem = build3_stat_loc (loc, code, type, op0, op1, op2 PASS_MEM_STAT);
12616
12617 #ifdef ENABLE_FOLD_CHECKING
12618   md5_init_ctx (&ctx);
12619   fold_checksum_tree (op0, &ctx, &ht);
12620   md5_finish_ctx (&ctx, checksum_after_op0);
12621   ht.empty ();
12622
12623   if (memcmp (checksum_before_op0, checksum_after_op0, 16))
12624     fold_check_failed (op0, tem);
12625
12626   md5_init_ctx (&ctx);
12627   fold_checksum_tree (op1, &ctx, &ht);
12628   md5_finish_ctx (&ctx, checksum_after_op1);
12629   ht.empty ();
12630
12631   if (memcmp (checksum_before_op1, checksum_after_op1, 16))
12632     fold_check_failed (op1, tem);
12633
12634   md5_init_ctx (&ctx);
12635   fold_checksum_tree (op2, &ctx, &ht);
12636   md5_finish_ctx (&ctx, checksum_after_op2);
12637
12638   if (memcmp (checksum_before_op2, checksum_after_op2, 16))
12639     fold_check_failed (op2, tem);
12640 #endif
12641   return tem;
12642 }
12643
12644 /* Fold a CALL_EXPR expression of type TYPE with operands FN and NARGS
12645    arguments in ARGARRAY, and a null static chain.
12646    Return a folded expression if successful.  Otherwise, return a CALL_EXPR
12647    of type TYPE from the given operands as constructed by build_call_array.  */
12648
12649 tree
12650 fold_build_call_array_loc (location_t loc, tree type, tree fn,
12651                            int nargs, tree *argarray)
12652 {
12653   tree tem;
12654 #ifdef ENABLE_FOLD_CHECKING
12655   unsigned char checksum_before_fn[16],
12656                 checksum_before_arglist[16],
12657                 checksum_after_fn[16],
12658                 checksum_after_arglist[16];
12659   struct md5_ctx ctx;
12660   hash_table<nofree_ptr_hash<const tree_node> > ht (32);
12661   int i;
12662
12663   md5_init_ctx (&ctx);
12664   fold_checksum_tree (fn, &ctx, &ht);
12665   md5_finish_ctx (&ctx, checksum_before_fn);
12666   ht.empty ();
12667
12668   md5_init_ctx (&ctx);
12669   for (i = 0; i < nargs; i++)
12670     fold_checksum_tree (argarray[i], &ctx, &ht);
12671   md5_finish_ctx (&ctx, checksum_before_arglist);
12672   ht.empty ();
12673 #endif
12674
12675   tem = fold_builtin_call_array (loc, type, fn, nargs, argarray);
12676   if (!tem)
12677     tem = build_call_array_loc (loc, type, fn, nargs, argarray);
12678
12679 #ifdef ENABLE_FOLD_CHECKING
12680   md5_init_ctx (&ctx);
12681   fold_checksum_tree (fn, &ctx, &ht);
12682   md5_finish_ctx (&ctx, checksum_after_fn);
12683   ht.empty ();
12684
12685   if (memcmp (checksum_before_fn, checksum_after_fn, 16))
12686     fold_check_failed (fn, tem);
12687
12688   md5_init_ctx (&ctx);
12689   for (i = 0; i < nargs; i++)
12690     fold_checksum_tree (argarray[i], &ctx, &ht);
12691   md5_finish_ctx (&ctx, checksum_after_arglist);
12692
12693   if (memcmp (checksum_before_arglist, checksum_after_arglist, 16))
12694     fold_check_failed (NULL_TREE, tem);
12695 #endif
12696   return tem;
12697 }
12698
12699 /* Perform constant folding and related simplification of initializer
12700    expression EXPR.  These behave identically to "fold_buildN" but ignore
12701    potential run-time traps and exceptions that fold must preserve.  */
12702
12703 #define START_FOLD_INIT \
12704   int saved_signaling_nans = flag_signaling_nans;\
12705   int saved_trapping_math = flag_trapping_math;\
12706   int saved_rounding_math = flag_rounding_math;\
12707   int saved_trapv = flag_trapv;\
12708   int saved_folding_initializer = folding_initializer;\
12709   flag_signaling_nans = 0;\
12710   flag_trapping_math = 0;\
12711   flag_rounding_math = 0;\
12712   flag_trapv = 0;\
12713   folding_initializer = 1;
12714
12715 #define END_FOLD_INIT \
12716   flag_signaling_nans = saved_signaling_nans;\
12717   flag_trapping_math = saved_trapping_math;\
12718   flag_rounding_math = saved_rounding_math;\
12719   flag_trapv = saved_trapv;\
12720   folding_initializer = saved_folding_initializer;
12721
12722 tree
12723 fold_build1_initializer_loc (location_t loc, enum tree_code code,
12724                              tree type, tree op)
12725 {
12726   tree result;
12727   START_FOLD_INIT;
12728
12729   result = fold_build1_loc (loc, code, type, op);
12730
12731   END_FOLD_INIT;
12732   return result;
12733 }
12734
12735 tree
12736 fold_build2_initializer_loc (location_t loc, enum tree_code code,
12737                              tree type, tree op0, tree op1)
12738 {
12739   tree result;
12740   START_FOLD_INIT;
12741
12742   result = fold_build2_loc (loc, code, type, op0, op1);
12743
12744   END_FOLD_INIT;
12745   return result;
12746 }
12747
12748 tree
12749 fold_build_call_array_initializer_loc (location_t loc, tree type, tree fn,
12750                                        int nargs, tree *argarray)
12751 {
12752   tree result;
12753   START_FOLD_INIT;
12754
12755   result = fold_build_call_array_loc (loc, type, fn, nargs, argarray);
12756
12757   END_FOLD_INIT;
12758   return result;
12759 }
12760
12761 #undef START_FOLD_INIT
12762 #undef END_FOLD_INIT
12763
12764 /* Determine if first argument is a multiple of second argument.  Return 0 if
12765    it is not, or we cannot easily determined it to be.
12766
12767    An example of the sort of thing we care about (at this point; this routine
12768    could surely be made more general, and expanded to do what the *_DIV_EXPR's
12769    fold cases do now) is discovering that
12770
12771      SAVE_EXPR (I) * SAVE_EXPR (J * 8)
12772
12773    is a multiple of
12774
12775      SAVE_EXPR (J * 8)
12776
12777    when we know that the two SAVE_EXPR (J * 8) nodes are the same node.
12778
12779    This code also handles discovering that
12780
12781      SAVE_EXPR (I) * SAVE_EXPR (J * 8)
12782
12783    is a multiple of 8 so we don't have to worry about dealing with a
12784    possible remainder.
12785
12786    Note that we *look* inside a SAVE_EXPR only to determine how it was
12787    calculated; it is not safe for fold to do much of anything else with the
12788    internals of a SAVE_EXPR, since it cannot know when it will be evaluated
12789    at run time.  For example, the latter example above *cannot* be implemented
12790    as SAVE_EXPR (I) * J or any variant thereof, since the value of J at
12791    evaluation time of the original SAVE_EXPR is not necessarily the same at
12792    the time the new expression is evaluated.  The only optimization of this
12793    sort that would be valid is changing
12794
12795      SAVE_EXPR (I) * SAVE_EXPR (SAVE_EXPR (J) * 8)
12796
12797    divided by 8 to
12798
12799      SAVE_EXPR (I) * SAVE_EXPR (J)
12800
12801    (where the same SAVE_EXPR (J) is used in the original and the
12802    transformed version).  */
12803
12804 int
12805 multiple_of_p (tree type, const_tree top, const_tree bottom)
12806 {
12807   if (operand_equal_p (top, bottom, 0))
12808     return 1;
12809
12810   if (TREE_CODE (type) != INTEGER_TYPE)
12811     return 0;
12812
12813   switch (TREE_CODE (top))
12814     {
12815     case BIT_AND_EXPR:
12816       /* Bitwise and provides a power of two multiple.  If the mask is
12817          a multiple of BOTTOM then TOP is a multiple of BOTTOM.  */
12818       if (!integer_pow2p (bottom))
12819         return 0;
12820       /* FALLTHRU */
12821
12822     case MULT_EXPR:
12823       return (multiple_of_p (type, TREE_OPERAND (top, 0), bottom)
12824               || multiple_of_p (type, TREE_OPERAND (top, 1), bottom));
12825
12826     case PLUS_EXPR:
12827     case MINUS_EXPR:
12828       return (multiple_of_p (type, TREE_OPERAND (top, 0), bottom)
12829               && multiple_of_p (type, TREE_OPERAND (top, 1), bottom));
12830
12831     case LSHIFT_EXPR:
12832       if (TREE_CODE (TREE_OPERAND (top, 1)) == INTEGER_CST)
12833         {
12834           tree op1, t1;
12835
12836           op1 = TREE_OPERAND (top, 1);
12837           /* const_binop may not detect overflow correctly,
12838              so check for it explicitly here.  */
12839           if (wi::gtu_p (TYPE_PRECISION (TREE_TYPE (size_one_node)), op1)
12840               && 0 != (t1 = fold_convert (type,
12841                                           const_binop (LSHIFT_EXPR,
12842                                                        size_one_node,
12843                                                        op1)))
12844               && !TREE_OVERFLOW (t1))
12845             return multiple_of_p (type, t1, bottom);
12846         }
12847       return 0;
12848
12849     case NOP_EXPR:
12850       /* Can't handle conversions from non-integral or wider integral type.  */
12851       if ((TREE_CODE (TREE_TYPE (TREE_OPERAND (top, 0))) != INTEGER_TYPE)
12852           || (TYPE_PRECISION (type)
12853               < TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (top, 0)))))
12854         return 0;
12855
12856       /* .. fall through ...  */
12857
12858     case SAVE_EXPR:
12859       return multiple_of_p (type, TREE_OPERAND (top, 0), bottom);
12860
12861     case COND_EXPR:
12862       return (multiple_of_p (type, TREE_OPERAND (top, 1), bottom)
12863               && multiple_of_p (type, TREE_OPERAND (top, 2), bottom));
12864
12865     case INTEGER_CST:
12866       if (TREE_CODE (bottom) != INTEGER_CST
12867           || integer_zerop (bottom)
12868           || (TYPE_UNSIGNED (type)
12869               && (tree_int_cst_sgn (top) < 0
12870                   || tree_int_cst_sgn (bottom) < 0)))
12871         return 0;
12872       return wi::multiple_of_p (wi::to_widest (top), wi::to_widest (bottom),
12873                                 SIGNED);
12874
12875     default:
12876       return 0;
12877     }
12878 }
12879
12880 #define tree_expr_nonnegative_warnv_p(X, Y) \
12881   _Pragma ("GCC error \"Use RECURSE for recursive calls\"") 0
12882
12883 #define RECURSE(X) \
12884   ((tree_expr_nonnegative_warnv_p) (X, strict_overflow_p, depth + 1))
12885
12886 /* Return true if CODE or TYPE is known to be non-negative. */
12887
12888 static bool
12889 tree_simple_nonnegative_warnv_p (enum tree_code code, tree type)
12890 {
12891   if ((TYPE_PRECISION (type) != 1 || TYPE_UNSIGNED (type))
12892       && truth_value_p (code))
12893     /* Truth values evaluate to 0 or 1, which is nonnegative unless we
12894        have a signed:1 type (where the value is -1 and 0).  */
12895     return true;
12896   return false;
12897 }
12898
12899 /* Return true if (CODE OP0) is known to be non-negative.  If the return
12900    value is based on the assumption that signed overflow is undefined,
12901    set *STRICT_OVERFLOW_P to true; otherwise, don't change
12902    *STRICT_OVERFLOW_P.  DEPTH is the current nesting depth of the query.  */
12903
12904 bool
12905 tree_unary_nonnegative_warnv_p (enum tree_code code, tree type, tree op0,
12906                                 bool *strict_overflow_p, int depth)
12907 {
12908   if (TYPE_UNSIGNED (type))
12909     return true;
12910
12911   switch (code)
12912     {
12913     case ABS_EXPR:
12914       /* We can't return 1 if flag_wrapv is set because
12915          ABS_EXPR<INT_MIN> = INT_MIN.  */
12916       if (!ANY_INTEGRAL_TYPE_P (type))
12917         return true;
12918       if (TYPE_OVERFLOW_UNDEFINED (type))
12919         {
12920           *strict_overflow_p = true;
12921           return true;
12922         }
12923       break;
12924
12925     case NON_LVALUE_EXPR:
12926     case FLOAT_EXPR:
12927     case FIX_TRUNC_EXPR:
12928       return RECURSE (op0);
12929
12930     CASE_CONVERT:
12931       {
12932         tree inner_type = TREE_TYPE (op0);
12933         tree outer_type = type;
12934
12935         if (TREE_CODE (outer_type) == REAL_TYPE)
12936           {
12937             if (TREE_CODE (inner_type) == REAL_TYPE)
12938               return RECURSE (op0);
12939             if (INTEGRAL_TYPE_P (inner_type))
12940               {
12941                 if (TYPE_UNSIGNED (inner_type))
12942                   return true;
12943                 return RECURSE (op0);
12944               }
12945           }
12946         else if (INTEGRAL_TYPE_P (outer_type))
12947           {
12948             if (TREE_CODE (inner_type) == REAL_TYPE)
12949               return RECURSE (op0);
12950             if (INTEGRAL_TYPE_P (inner_type))
12951               return TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type)
12952                       && TYPE_UNSIGNED (inner_type);
12953           }
12954       }
12955       break;
12956
12957     default:
12958       return tree_simple_nonnegative_warnv_p (code, type);
12959     }
12960
12961   /* We don't know sign of `t', so be conservative and return false.  */
12962   return false;
12963 }
12964
12965 /* Return true if (CODE OP0 OP1) is known to be non-negative.  If the return
12966    value is based on the assumption that signed overflow is undefined,
12967    set *STRICT_OVERFLOW_P to true; otherwise, don't change
12968    *STRICT_OVERFLOW_P.  DEPTH is the current nesting depth of the query.  */
12969
12970 bool
12971 tree_binary_nonnegative_warnv_p (enum tree_code code, tree type, tree op0,
12972                                  tree op1, bool *strict_overflow_p,
12973                                  int depth)
12974 {
12975   if (TYPE_UNSIGNED (type))
12976     return true;
12977
12978   switch (code)
12979     {
12980     case POINTER_PLUS_EXPR:
12981     case PLUS_EXPR:
12982       if (FLOAT_TYPE_P (type))
12983         return RECURSE (op0) && RECURSE (op1);
12984
12985       /* zero_extend(x) + zero_extend(y) is non-negative if x and y are
12986          both unsigned and at least 2 bits shorter than the result.  */
12987       if (TREE_CODE (type) == INTEGER_TYPE
12988           && TREE_CODE (op0) == NOP_EXPR
12989           && TREE_CODE (op1) == NOP_EXPR)
12990         {
12991           tree inner1 = TREE_TYPE (TREE_OPERAND (op0, 0));
12992           tree inner2 = TREE_TYPE (TREE_OPERAND (op1, 0));
12993           if (TREE_CODE (inner1) == INTEGER_TYPE && TYPE_UNSIGNED (inner1)
12994               && TREE_CODE (inner2) == INTEGER_TYPE && TYPE_UNSIGNED (inner2))
12995             {
12996               unsigned int prec = MAX (TYPE_PRECISION (inner1),
12997                                        TYPE_PRECISION (inner2)) + 1;
12998               return prec < TYPE_PRECISION (type);
12999             }
13000         }
13001       break;
13002
13003     case MULT_EXPR:
13004       if (FLOAT_TYPE_P (type) || TYPE_OVERFLOW_UNDEFINED (type))
13005         {
13006           /* x * x is always non-negative for floating point x
13007              or without overflow.  */
13008           if (operand_equal_p (op0, op1, 0)
13009               || (RECURSE (op0) && RECURSE (op1)))
13010             {
13011               if (ANY_INTEGRAL_TYPE_P (type)
13012                   && TYPE_OVERFLOW_UNDEFINED (type))
13013                 *strict_overflow_p = true;
13014               return true;
13015             }
13016         }
13017
13018       /* zero_extend(x) * zero_extend(y) is non-negative if x and y are
13019          both unsigned and their total bits is shorter than the result.  */
13020       if (TREE_CODE (type) == INTEGER_TYPE
13021           && (TREE_CODE (op0) == NOP_EXPR || TREE_CODE (op0) == INTEGER_CST)
13022           && (TREE_CODE (op1) == NOP_EXPR || TREE_CODE (op1) == INTEGER_CST))
13023         {
13024           tree inner0 = (TREE_CODE (op0) == NOP_EXPR)
13025             ? TREE_TYPE (TREE_OPERAND (op0, 0))
13026             : TREE_TYPE (op0);
13027           tree inner1 = (TREE_CODE (op1) == NOP_EXPR)
13028             ? TREE_TYPE (TREE_OPERAND (op1, 0))
13029             : TREE_TYPE (op1);
13030
13031           bool unsigned0 = TYPE_UNSIGNED (inner0);
13032           bool unsigned1 = TYPE_UNSIGNED (inner1);
13033
13034           if (TREE_CODE (op0) == INTEGER_CST)
13035             unsigned0 = unsigned0 || tree_int_cst_sgn (op0) >= 0;
13036
13037           if (TREE_CODE (op1) == INTEGER_CST)
13038             unsigned1 = unsigned1 || tree_int_cst_sgn (op1) >= 0;
13039
13040           if (TREE_CODE (inner0) == INTEGER_TYPE && unsigned0
13041               && TREE_CODE (inner1) == INTEGER_TYPE && unsigned1)
13042             {
13043               unsigned int precision0 = (TREE_CODE (op0) == INTEGER_CST)
13044                 ? tree_int_cst_min_precision (op0, UNSIGNED)
13045                 : TYPE_PRECISION (inner0);
13046
13047               unsigned int precision1 = (TREE_CODE (op1) == INTEGER_CST)
13048                 ? tree_int_cst_min_precision (op1, UNSIGNED)
13049                 : TYPE_PRECISION (inner1);
13050
13051               return precision0 + precision1 < TYPE_PRECISION (type);
13052             }
13053         }
13054       return false;
13055
13056     case BIT_AND_EXPR:
13057     case MAX_EXPR:
13058       return RECURSE (op0) || RECURSE (op1);
13059
13060     case BIT_IOR_EXPR:
13061     case BIT_XOR_EXPR:
13062     case MIN_EXPR:
13063     case RDIV_EXPR:
13064     case TRUNC_DIV_EXPR:
13065     case CEIL_DIV_EXPR:
13066     case FLOOR_DIV_EXPR:
13067     case ROUND_DIV_EXPR:
13068       return RECURSE (op0) && RECURSE (op1);
13069
13070     case TRUNC_MOD_EXPR:
13071       return RECURSE (op0);
13072
13073     case FLOOR_MOD_EXPR:
13074       return RECURSE (op1);
13075
13076     case CEIL_MOD_EXPR:
13077     case ROUND_MOD_EXPR:
13078     default:
13079       return tree_simple_nonnegative_warnv_p (code, type);
13080     }
13081
13082   /* We don't know sign of `t', so be conservative and return false.  */
13083   return false;
13084 }
13085
13086 /* Return true if T is known to be non-negative.  If the return
13087    value is based on the assumption that signed overflow is undefined,
13088    set *STRICT_OVERFLOW_P to true; otherwise, don't change
13089    *STRICT_OVERFLOW_P.  DEPTH is the current nesting depth of the query.  */
13090
13091 bool
13092 tree_single_nonnegative_warnv_p (tree t, bool *strict_overflow_p, int depth)
13093 {
13094   if (TYPE_UNSIGNED (TREE_TYPE (t)))
13095     return true;
13096
13097   switch (TREE_CODE (t))
13098     {
13099     case INTEGER_CST:
13100       return tree_int_cst_sgn (t) >= 0;
13101
13102     case REAL_CST:
13103       return ! REAL_VALUE_NEGATIVE (TREE_REAL_CST (t));
13104
13105     case FIXED_CST:
13106       return ! FIXED_VALUE_NEGATIVE (TREE_FIXED_CST (t));
13107
13108     case COND_EXPR:
13109       return RECURSE (TREE_OPERAND (t, 1)) && RECURSE (TREE_OPERAND (t, 2));
13110
13111     case SSA_NAME:
13112       /* Limit the depth of recursion to avoid quadratic behavior.
13113          This is expected to catch almost all occurrences in practice.
13114          If this code misses important cases that unbounded recursion
13115          would not, passes that need this information could be revised
13116          to provide it through dataflow propagation.  */
13117       return (!name_registered_for_update_p (t)
13118               && depth < PARAM_VALUE (PARAM_MAX_SSA_NAME_QUERY_DEPTH)
13119               && gimple_stmt_nonnegative_warnv_p (SSA_NAME_DEF_STMT (t),
13120                                                   strict_overflow_p, depth));
13121
13122     default:
13123       return tree_simple_nonnegative_warnv_p (TREE_CODE (t), TREE_TYPE (t));
13124     }
13125 }
13126
13127 /* Return true if T is known to be non-negative.  If the return
13128    value is based on the assumption that signed overflow is undefined,
13129    set *STRICT_OVERFLOW_P to true; otherwise, don't change
13130    *STRICT_OVERFLOW_P.  DEPTH is the current nesting depth of the query.  */
13131
13132 bool
13133 tree_call_nonnegative_warnv_p (tree type, combined_fn fn, tree arg0, tree arg1,
13134                                bool *strict_overflow_p, int depth)
13135 {
13136   switch (fn)
13137     {
13138     CASE_CFN_ACOS:
13139     CASE_CFN_ACOSH:
13140     CASE_CFN_CABS:
13141     CASE_CFN_COSH:
13142     CASE_CFN_ERFC:
13143     CASE_CFN_EXP:
13144     CASE_CFN_EXP10:
13145     CASE_CFN_EXP2:
13146     CASE_CFN_FABS:
13147     CASE_CFN_FDIM:
13148     CASE_CFN_HYPOT:
13149     CASE_CFN_POW10:
13150     CASE_CFN_FFS:
13151     CASE_CFN_PARITY:
13152     CASE_CFN_POPCOUNT:
13153     CASE_CFN_CLZ:
13154     CASE_CFN_CLRSB:
13155     case CFN_BUILT_IN_BSWAP32:
13156     case CFN_BUILT_IN_BSWAP64:
13157       /* Always true.  */
13158       return true;
13159
13160     CASE_CFN_SQRT:
13161       /* sqrt(-0.0) is -0.0.  */
13162       if (!HONOR_SIGNED_ZEROS (element_mode (type)))
13163         return true;
13164       return RECURSE (arg0);
13165
13166     CASE_CFN_ASINH:
13167     CASE_CFN_ATAN:
13168     CASE_CFN_ATANH:
13169     CASE_CFN_CBRT:
13170     CASE_CFN_CEIL:
13171     CASE_CFN_ERF:
13172     CASE_CFN_EXPM1:
13173     CASE_CFN_FLOOR:
13174     CASE_CFN_FMOD:
13175     CASE_CFN_FREXP:
13176     CASE_CFN_ICEIL:
13177     CASE_CFN_IFLOOR:
13178     CASE_CFN_IRINT:
13179     CASE_CFN_IROUND:
13180     CASE_CFN_LCEIL:
13181     CASE_CFN_LDEXP:
13182     CASE_CFN_LFLOOR:
13183     CASE_CFN_LLCEIL:
13184     CASE_CFN_LLFLOOR:
13185     CASE_CFN_LLRINT:
13186     CASE_CFN_LLROUND:
13187     CASE_CFN_LRINT:
13188     CASE_CFN_LROUND:
13189     CASE_CFN_MODF:
13190     CASE_CFN_NEARBYINT:
13191     CASE_CFN_RINT:
13192     CASE_CFN_ROUND:
13193     CASE_CFN_SCALB:
13194     CASE_CFN_SCALBLN:
13195     CASE_CFN_SCALBN:
13196     CASE_CFN_SIGNBIT:
13197     CASE_CFN_SIGNIFICAND:
13198     CASE_CFN_SINH:
13199     CASE_CFN_TANH:
13200     CASE_CFN_TRUNC:
13201       /* True if the 1st argument is nonnegative.  */
13202       return RECURSE (arg0);
13203
13204     CASE_CFN_FMAX:
13205       /* True if the 1st OR 2nd arguments are nonnegative.  */
13206       return RECURSE (arg0) || RECURSE (arg1);
13207
13208     CASE_CFN_FMIN:
13209       /* True if the 1st AND 2nd arguments are nonnegative.  */
13210       return RECURSE (arg0) && RECURSE (arg1);
13211
13212     CASE_CFN_COPYSIGN:
13213       /* True if the 2nd argument is nonnegative.  */
13214       return RECURSE (arg1);
13215
13216     CASE_CFN_POWI:
13217       /* True if the 1st argument is nonnegative or the second
13218          argument is an even integer.  */
13219       if (TREE_CODE (arg1) == INTEGER_CST
13220           && (TREE_INT_CST_LOW (arg1) & 1) == 0)
13221         return true;
13222       return RECURSE (arg0);
13223
13224     CASE_CFN_POW:
13225       /* True if the 1st argument is nonnegative or the second
13226          argument is an even integer valued real.  */
13227       if (TREE_CODE (arg1) == REAL_CST)
13228         {
13229           REAL_VALUE_TYPE c;
13230           HOST_WIDE_INT n;
13231
13232           c = TREE_REAL_CST (arg1);
13233           n = real_to_integer (&c);
13234           if ((n & 1) == 0)
13235             {
13236               REAL_VALUE_TYPE cint;
13237               real_from_integer (&cint, VOIDmode, n, SIGNED);
13238               if (real_identical (&c, &cint))
13239                 return true;
13240             }
13241         }
13242       return RECURSE (arg0);
13243
13244     default:
13245       break;
13246     }
13247   return tree_simple_nonnegative_warnv_p (CALL_EXPR, type);
13248 }
13249
13250 /* Return true if T is known to be non-negative.  If the return
13251    value is based on the assumption that signed overflow is undefined,
13252    set *STRICT_OVERFLOW_P to true; otherwise, don't change
13253    *STRICT_OVERFLOW_P.  DEPTH is the current nesting depth of the query.  */
13254
13255 static bool
13256 tree_invalid_nonnegative_warnv_p (tree t, bool *strict_overflow_p, int depth)
13257 {
13258   enum tree_code code = TREE_CODE (t);
13259   if (TYPE_UNSIGNED (TREE_TYPE (t)))
13260     return true;
13261
13262   switch (code)
13263     {
13264     case TARGET_EXPR:
13265       {
13266         tree temp = TARGET_EXPR_SLOT (t);
13267         t = TARGET_EXPR_INITIAL (t);
13268
13269         /* If the initializer is non-void, then it's a normal expression
13270            that will be assigned to the slot.  */
13271         if (!VOID_TYPE_P (t))
13272           return RECURSE (t);
13273
13274         /* Otherwise, the initializer sets the slot in some way.  One common
13275            way is an assignment statement at the end of the initializer.  */
13276         while (1)
13277           {
13278             if (TREE_CODE (t) == BIND_EXPR)
13279               t = expr_last (BIND_EXPR_BODY (t));
13280             else if (TREE_CODE (t) == TRY_FINALLY_EXPR
13281                      || TREE_CODE (t) == TRY_CATCH_EXPR)
13282               t = expr_last (TREE_OPERAND (t, 0));
13283             else if (TREE_CODE (t) == STATEMENT_LIST)
13284               t = expr_last (t);
13285             else
13286               break;
13287           }
13288         if (TREE_CODE (t) == MODIFY_EXPR
13289             && TREE_OPERAND (t, 0) == temp)
13290           return RECURSE (TREE_OPERAND (t, 1));
13291
13292         return false;
13293       }
13294
13295     case CALL_EXPR:
13296       {
13297         tree arg0 = call_expr_nargs (t) > 0 ?  CALL_EXPR_ARG (t, 0) : NULL_TREE;
13298         tree arg1 = call_expr_nargs (t) > 1 ?  CALL_EXPR_ARG (t, 1) : NULL_TREE;
13299
13300         return tree_call_nonnegative_warnv_p (TREE_TYPE (t),
13301                                               get_call_combined_fn (t),
13302                                               arg0,
13303                                               arg1,
13304                                               strict_overflow_p, depth);
13305       }
13306     case COMPOUND_EXPR:
13307     case MODIFY_EXPR:
13308       return RECURSE (TREE_OPERAND (t, 1));
13309
13310     case BIND_EXPR:
13311       return RECURSE (expr_last (TREE_OPERAND (t, 1)));
13312
13313     case SAVE_EXPR:
13314       return RECURSE (TREE_OPERAND (t, 0));
13315
13316     default:
13317       return tree_simple_nonnegative_warnv_p (TREE_CODE (t), TREE_TYPE (t));
13318     }
13319 }
13320
13321 #undef RECURSE
13322 #undef tree_expr_nonnegative_warnv_p
13323
13324 /* Return true if T is known to be non-negative.  If the return
13325    value is based on the assumption that signed overflow is undefined,
13326    set *STRICT_OVERFLOW_P to true; otherwise, don't change
13327    *STRICT_OVERFLOW_P.  DEPTH is the current nesting depth of the query.  */
13328
13329 bool
13330 tree_expr_nonnegative_warnv_p (tree t, bool *strict_overflow_p, int depth)
13331 {
13332   enum tree_code code;
13333   if (t == error_mark_node)
13334     return false;
13335
13336   code = TREE_CODE (t);
13337   switch (TREE_CODE_CLASS (code))
13338     {
13339     case tcc_binary:
13340     case tcc_comparison:
13341       return tree_binary_nonnegative_warnv_p (TREE_CODE (t),
13342                                               TREE_TYPE (t),
13343                                               TREE_OPERAND (t, 0),
13344                                               TREE_OPERAND (t, 1),
13345                                               strict_overflow_p, depth);
13346
13347     case tcc_unary:
13348       return tree_unary_nonnegative_warnv_p (TREE_CODE (t),
13349                                              TREE_TYPE (t),
13350                                              TREE_OPERAND (t, 0),
13351                                              strict_overflow_p, depth);
13352
13353     case tcc_constant:
13354     case tcc_declaration:
13355     case tcc_reference:
13356       return tree_single_nonnegative_warnv_p (t, strict_overflow_p, depth);
13357
13358     default:
13359       break;
13360     }
13361
13362   switch (code)
13363     {
13364     case TRUTH_AND_EXPR:
13365     case TRUTH_OR_EXPR:
13366     case TRUTH_XOR_EXPR:
13367       return tree_binary_nonnegative_warnv_p (TREE_CODE (t),
13368                                               TREE_TYPE (t),
13369                                               TREE_OPERAND (t, 0),
13370                                               TREE_OPERAND (t, 1),
13371                                               strict_overflow_p, depth);
13372     case TRUTH_NOT_EXPR:
13373       return tree_unary_nonnegative_warnv_p (TREE_CODE (t),
13374                                              TREE_TYPE (t),
13375                                              TREE_OPERAND (t, 0),
13376                                              strict_overflow_p, depth);
13377
13378     case COND_EXPR:
13379     case CONSTRUCTOR:
13380     case OBJ_TYPE_REF:
13381     case ASSERT_EXPR:
13382     case ADDR_EXPR:
13383     case WITH_SIZE_EXPR:
13384     case SSA_NAME:
13385       return tree_single_nonnegative_warnv_p (t, strict_overflow_p, depth);
13386
13387     default:
13388       return tree_invalid_nonnegative_warnv_p (t, strict_overflow_p, depth);
13389     }
13390 }
13391
13392 /* Return true if `t' is known to be non-negative.  Handle warnings
13393    about undefined signed overflow.  */
13394
13395 bool
13396 tree_expr_nonnegative_p (tree t)
13397 {
13398   bool ret, strict_overflow_p;
13399
13400   strict_overflow_p = false;
13401   ret = tree_expr_nonnegative_warnv_p (t, &strict_overflow_p);
13402   if (strict_overflow_p)
13403     fold_overflow_warning (("assuming signed overflow does not occur when "
13404                             "determining that expression is always "
13405                             "non-negative"),
13406                            WARN_STRICT_OVERFLOW_MISC);
13407   return ret;
13408 }
13409
13410
13411 /* Return true when (CODE OP0) is an address and is known to be nonzero.
13412    For floating point we further ensure that T is not denormal.
13413    Similar logic is present in nonzero_address in rtlanal.h.
13414
13415    If the return value is based on the assumption that signed overflow
13416    is undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't
13417    change *STRICT_OVERFLOW_P.  */
13418
13419 bool
13420 tree_unary_nonzero_warnv_p (enum tree_code code, tree type, tree op0,
13421                                  bool *strict_overflow_p)
13422 {
13423   switch (code)
13424     {
13425     case ABS_EXPR:
13426       return tree_expr_nonzero_warnv_p (op0,
13427                                         strict_overflow_p);
13428
13429     case NOP_EXPR:
13430       {
13431         tree inner_type = TREE_TYPE (op0);
13432         tree outer_type = type;
13433
13434         return (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
13435                 && tree_expr_nonzero_warnv_p (op0,
13436                                               strict_overflow_p));
13437       }
13438       break;
13439
13440     case NON_LVALUE_EXPR:
13441       return tree_expr_nonzero_warnv_p (op0,
13442                                         strict_overflow_p);
13443
13444     default:
13445       break;
13446   }
13447
13448   return false;
13449 }
13450
13451 /* Return true when (CODE OP0 OP1) is an address and is known to be nonzero.
13452    For floating point we further ensure that T is not denormal.
13453    Similar logic is present in nonzero_address in rtlanal.h.
13454
13455    If the return value is based on the assumption that signed overflow
13456    is undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't
13457    change *STRICT_OVERFLOW_P.  */
13458
13459 bool
13460 tree_binary_nonzero_warnv_p (enum tree_code code,
13461                              tree type,
13462                              tree op0,
13463                              tree op1, bool *strict_overflow_p)
13464 {
13465   bool sub_strict_overflow_p;
13466   switch (code)
13467     {
13468     case POINTER_PLUS_EXPR:
13469     case PLUS_EXPR:
13470       if (ANY_INTEGRAL_TYPE_P (type) && TYPE_OVERFLOW_UNDEFINED (type))
13471         {
13472           /* With the presence of negative values it is hard
13473              to say something.  */
13474           sub_strict_overflow_p = false;
13475           if (!tree_expr_nonnegative_warnv_p (op0,
13476                                               &sub_strict_overflow_p)
13477               || !tree_expr_nonnegative_warnv_p (op1,
13478                                                  &sub_strict_overflow_p))
13479             return false;
13480           /* One of operands must be positive and the other non-negative.  */
13481           /* We don't set *STRICT_OVERFLOW_P here: even if this value
13482              overflows, on a twos-complement machine the sum of two
13483              nonnegative numbers can never be zero.  */
13484           return (tree_expr_nonzero_warnv_p (op0,
13485                                              strict_overflow_p)
13486                   || tree_expr_nonzero_warnv_p (op1,
13487                                                 strict_overflow_p));
13488         }
13489       break;
13490
13491     case MULT_EXPR:
13492       if (TYPE_OVERFLOW_UNDEFINED (type))
13493         {
13494           if (tree_expr_nonzero_warnv_p (op0,
13495                                          strict_overflow_p)
13496               && tree_expr_nonzero_warnv_p (op1,
13497                                             strict_overflow_p))
13498             {
13499               *strict_overflow_p = true;
13500               return true;
13501             }
13502         }
13503       break;
13504
13505     case MIN_EXPR:
13506       sub_strict_overflow_p = false;
13507       if (tree_expr_nonzero_warnv_p (op0,
13508                                      &sub_strict_overflow_p)
13509           && tree_expr_nonzero_warnv_p (op1,
13510                                         &sub_strict_overflow_p))
13511         {
13512           if (sub_strict_overflow_p)
13513             *strict_overflow_p = true;
13514         }
13515       break;
13516
13517     case MAX_EXPR:
13518       sub_strict_overflow_p = false;
13519       if (tree_expr_nonzero_warnv_p (op0,
13520                                      &sub_strict_overflow_p))
13521         {
13522           if (sub_strict_overflow_p)
13523             *strict_overflow_p = true;
13524
13525           /* When both operands are nonzero, then MAX must be too.  */
13526           if (tree_expr_nonzero_warnv_p (op1,
13527                                          strict_overflow_p))
13528             return true;
13529
13530           /* MAX where operand 0 is positive is positive.  */
13531           return tree_expr_nonnegative_warnv_p (op0,
13532                                                strict_overflow_p);
13533         }
13534       /* MAX where operand 1 is positive is positive.  */
13535       else if (tree_expr_nonzero_warnv_p (op1,
13536                                           &sub_strict_overflow_p)
13537                && tree_expr_nonnegative_warnv_p (op1,
13538                                                  &sub_strict_overflow_p))
13539         {
13540           if (sub_strict_overflow_p)
13541             *strict_overflow_p = true;
13542           return true;
13543         }
13544       break;
13545
13546     case BIT_IOR_EXPR:
13547       return (tree_expr_nonzero_warnv_p (op1,
13548                                          strict_overflow_p)
13549               || tree_expr_nonzero_warnv_p (op0,
13550                                             strict_overflow_p));
13551
13552     default:
13553       break;
13554   }
13555
13556   return false;
13557 }
13558
13559 /* Return true when T is an address and is known to be nonzero.
13560    For floating point we further ensure that T is not denormal.
13561    Similar logic is present in nonzero_address in rtlanal.h.
13562
13563    If the return value is based on the assumption that signed overflow
13564    is undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't
13565    change *STRICT_OVERFLOW_P.  */
13566
13567 bool
13568 tree_single_nonzero_warnv_p (tree t, bool *strict_overflow_p)
13569 {
13570   bool sub_strict_overflow_p;
13571   switch (TREE_CODE (t))
13572     {
13573     case INTEGER_CST:
13574       return !integer_zerop (t);
13575
13576     case ADDR_EXPR:
13577       {
13578         tree base = TREE_OPERAND (t, 0);
13579
13580         if (!DECL_P (base))
13581           base = get_base_address (base);
13582
13583         if (base && TREE_CODE (base) == TARGET_EXPR)
13584           base = TARGET_EXPR_SLOT (base);
13585
13586         if (!base)
13587           return false;
13588
13589         /* For objects in symbol table check if we know they are non-zero.
13590            Don't do anything for variables and functions before symtab is built;
13591            it is quite possible that they will be declared weak later.  */
13592         int nonzero_addr = maybe_nonzero_address (base);
13593         if (nonzero_addr >= 0)
13594           return nonzero_addr;
13595
13596         /* Function local objects are never NULL.  */
13597         if (DECL_P (base)
13598             && (DECL_CONTEXT (base)
13599                 && TREE_CODE (DECL_CONTEXT (base)) == FUNCTION_DECL
13600                 && auto_var_in_fn_p (base, DECL_CONTEXT (base))))
13601           return true;
13602
13603         /* Constants are never weak.  */
13604         if (CONSTANT_CLASS_P (base))
13605           return true;
13606
13607         return false;
13608       }
13609
13610     case COND_EXPR:
13611       sub_strict_overflow_p = false;
13612       if (tree_expr_nonzero_warnv_p (TREE_OPERAND (t, 1),
13613                                      &sub_strict_overflow_p)
13614           && tree_expr_nonzero_warnv_p (TREE_OPERAND (t, 2),
13615                                         &sub_strict_overflow_p))
13616         {
13617           if (sub_strict_overflow_p)
13618             *strict_overflow_p = true;
13619           return true;
13620         }
13621       break;
13622
13623     default:
13624       break;
13625     }
13626   return false;
13627 }
13628
13629 #define integer_valued_real_p(X) \
13630   _Pragma ("GCC error \"Use RECURSE for recursive calls\"") 0
13631
13632 #define RECURSE(X) \
13633   ((integer_valued_real_p) (X, depth + 1))
13634
13635 /* Return true if the floating point result of (CODE OP0) has an
13636    integer value.  We also allow +Inf, -Inf and NaN to be considered
13637    integer values. Return false for signaling NaN.
13638
13639    DEPTH is the current nesting depth of the query.  */
13640
13641 bool
13642 integer_valued_real_unary_p (tree_code code, tree op0, int depth)
13643 {
13644   switch (code)
13645     {
13646     case FLOAT_EXPR:
13647       return true;
13648
13649     case ABS_EXPR:
13650       return RECURSE (op0);
13651
13652     CASE_CONVERT:
13653       {
13654         tree type = TREE_TYPE (op0);
13655         if (TREE_CODE (type) == INTEGER_TYPE)
13656           return true;
13657         if (TREE_CODE (type) == REAL_TYPE)
13658           return RECURSE (op0);
13659         break;
13660       }
13661
13662     default:
13663       break;
13664     }
13665   return false;
13666 }
13667
13668 /* Return true if the floating point result of (CODE OP0 OP1) has an
13669    integer value.  We also allow +Inf, -Inf and NaN to be considered
13670    integer values. Return false for signaling NaN.
13671
13672    DEPTH is the current nesting depth of the query.  */
13673
13674 bool
13675 integer_valued_real_binary_p (tree_code code, tree op0, tree op1, int depth)
13676 {
13677   switch (code)
13678     {
13679     case PLUS_EXPR:
13680     case MINUS_EXPR:
13681     case MULT_EXPR:
13682     case MIN_EXPR:
13683     case MAX_EXPR:
13684       return RECURSE (op0) && RECURSE (op1);
13685
13686     default:
13687       break;
13688     }
13689   return false;
13690 }
13691
13692 /* Return true if the floating point result of calling FNDECL with arguments
13693    ARG0 and ARG1 has an integer value.  We also allow +Inf, -Inf and NaN to be
13694    considered integer values. Return false for signaling NaN.  If FNDECL
13695    takes fewer than 2 arguments, the remaining ARGn are null.
13696
13697    DEPTH is the current nesting depth of the query.  */
13698
13699 bool
13700 integer_valued_real_call_p (combined_fn fn, tree arg0, tree arg1, int depth)
13701 {
13702   switch (fn)
13703     {
13704     CASE_CFN_CEIL:
13705     CASE_CFN_FLOOR:
13706     CASE_CFN_NEARBYINT:
13707     CASE_CFN_RINT:
13708     CASE_CFN_ROUND:
13709     CASE_CFN_TRUNC:
13710       return true;
13711
13712     CASE_CFN_FMIN:
13713     CASE_CFN_FMAX:
13714       return RECURSE (arg0) && RECURSE (arg1);
13715
13716     default:
13717       break;
13718     }
13719   return false;
13720 }
13721
13722 /* Return true if the floating point expression T (a GIMPLE_SINGLE_RHS)
13723    has an integer value.  We also allow +Inf, -Inf and NaN to be
13724    considered integer values. Return false for signaling NaN.
13725
13726    DEPTH is the current nesting depth of the query.  */
13727
13728 bool
13729 integer_valued_real_single_p (tree t, int depth)
13730 {
13731   switch (TREE_CODE (t))
13732     {
13733     case REAL_CST:
13734       return real_isinteger (TREE_REAL_CST_PTR (t), TYPE_MODE (TREE_TYPE (t)));
13735
13736     case COND_EXPR:
13737       return RECURSE (TREE_OPERAND (t, 1)) && RECURSE (TREE_OPERAND (t, 2));
13738
13739     case SSA_NAME:
13740       /* Limit the depth of recursion to avoid quadratic behavior.
13741          This is expected to catch almost all occurrences in practice.
13742          If this code misses important cases that unbounded recursion
13743          would not, passes that need this information could be revised
13744          to provide it through dataflow propagation.  */
13745       return (!name_registered_for_update_p (t)
13746               && depth < PARAM_VALUE (PARAM_MAX_SSA_NAME_QUERY_DEPTH)
13747               && gimple_stmt_integer_valued_real_p (SSA_NAME_DEF_STMT (t),
13748                                                     depth));
13749
13750     default:
13751       break;
13752     }
13753   return false;
13754 }
13755
13756 /* Return true if the floating point expression T (a GIMPLE_INVALID_RHS)
13757    has an integer value.  We also allow +Inf, -Inf and NaN to be
13758    considered integer values. Return false for signaling NaN.
13759
13760    DEPTH is the current nesting depth of the query.  */
13761
13762 static bool
13763 integer_valued_real_invalid_p (tree t, int depth)
13764 {
13765   switch (TREE_CODE (t))
13766     {
13767     case COMPOUND_EXPR:
13768     case MODIFY_EXPR:
13769     case BIND_EXPR:
13770       return RECURSE (TREE_OPERAND (t, 1));
13771
13772     case SAVE_EXPR:
13773       return RECURSE (TREE_OPERAND (t, 0));
13774
13775     default:
13776       break;
13777     }
13778   return false;
13779 }
13780
13781 #undef RECURSE
13782 #undef integer_valued_real_p
13783
13784 /* Return true if the floating point expression T has an integer value.
13785    We also allow +Inf, -Inf and NaN to be considered integer values.
13786    Return false for signaling NaN.
13787
13788    DEPTH is the current nesting depth of the query.  */
13789
13790 bool
13791 integer_valued_real_p (tree t, int depth)
13792 {
13793   if (t == error_mark_node)
13794     return false;
13795
13796   tree_code code = TREE_CODE (t);
13797   switch (TREE_CODE_CLASS (code))
13798     {
13799     case tcc_binary:
13800     case tcc_comparison:
13801       return integer_valued_real_binary_p (code, TREE_OPERAND (t, 0),
13802                                            TREE_OPERAND (t, 1), depth);
13803
13804     case tcc_unary:
13805       return integer_valued_real_unary_p (code, TREE_OPERAND (t, 0), depth);
13806
13807     case tcc_constant:
13808     case tcc_declaration:
13809     case tcc_reference:
13810       return integer_valued_real_single_p (t, depth);
13811
13812     default:
13813       break;
13814     }
13815
13816   switch (code)
13817     {
13818     case COND_EXPR:
13819     case SSA_NAME:
13820       return integer_valued_real_single_p (t, depth);
13821
13822     case CALL_EXPR:
13823       {
13824         tree arg0 = (call_expr_nargs (t) > 0
13825                      ? CALL_EXPR_ARG (t, 0)
13826                      : NULL_TREE);
13827         tree arg1 = (call_expr_nargs (t) > 1
13828                      ? CALL_EXPR_ARG (t, 1)
13829                      : NULL_TREE);
13830         return integer_valued_real_call_p (get_call_combined_fn (t),
13831                                            arg0, arg1, depth);
13832       }
13833
13834     default:
13835       return integer_valued_real_invalid_p (t, depth);
13836     }
13837 }
13838
13839 /* Given the components of a binary expression CODE, TYPE, OP0 and OP1,
13840    attempt to fold the expression to a constant without modifying TYPE,
13841    OP0 or OP1.
13842
13843    If the expression could be simplified to a constant, then return
13844    the constant.  If the expression would not be simplified to a
13845    constant, then return NULL_TREE.  */
13846
13847 tree
13848 fold_binary_to_constant (enum tree_code code, tree type, tree op0, tree op1)
13849 {
13850   tree tem = fold_binary (code, type, op0, op1);
13851   return (tem && TREE_CONSTANT (tem)) ? tem : NULL_TREE;
13852 }
13853
13854 /* Given the components of a unary expression CODE, TYPE and OP0,
13855    attempt to fold the expression to a constant without modifying
13856    TYPE or OP0.
13857
13858    If the expression could be simplified to a constant, then return
13859    the constant.  If the expression would not be simplified to a
13860    constant, then return NULL_TREE.  */
13861
13862 tree
13863 fold_unary_to_constant (enum tree_code code, tree type, tree op0)
13864 {
13865   tree tem = fold_unary (code, type, op0);
13866   return (tem && TREE_CONSTANT (tem)) ? tem : NULL_TREE;
13867 }
13868
13869 /* If EXP represents referencing an element in a constant string
13870    (either via pointer arithmetic or array indexing), return the
13871    tree representing the value accessed, otherwise return NULL.  */
13872
13873 tree
13874 fold_read_from_constant_string (tree exp)
13875 {
13876   if ((TREE_CODE (exp) == INDIRECT_REF
13877        || TREE_CODE (exp) == ARRAY_REF)
13878       && TREE_CODE (TREE_TYPE (exp)) == INTEGER_TYPE)
13879     {
13880       tree exp1 = TREE_OPERAND (exp, 0);
13881       tree index;
13882       tree string;
13883       location_t loc = EXPR_LOCATION (exp);
13884
13885       if (TREE_CODE (exp) == INDIRECT_REF)
13886         string = string_constant (exp1, &index);
13887       else
13888         {
13889           tree low_bound = array_ref_low_bound (exp);
13890           index = fold_convert_loc (loc, sizetype, TREE_OPERAND (exp, 1));
13891
13892           /* Optimize the special-case of a zero lower bound.
13893
13894              We convert the low_bound to sizetype to avoid some problems
13895              with constant folding.  (E.g. suppose the lower bound is 1,
13896              and its mode is QI.  Without the conversion,l (ARRAY
13897              +(INDEX-(unsigned char)1)) becomes ((ARRAY+(-(unsigned char)1))
13898              +INDEX), which becomes (ARRAY+255+INDEX).  Oops!)  */
13899           if (! integer_zerop (low_bound))
13900             index = size_diffop_loc (loc, index,
13901                                  fold_convert_loc (loc, sizetype, low_bound));
13902
13903           string = exp1;
13904         }
13905
13906       if (string
13907           && TYPE_MODE (TREE_TYPE (exp)) == TYPE_MODE (TREE_TYPE (TREE_TYPE (string)))
13908           && TREE_CODE (string) == STRING_CST
13909           && TREE_CODE (index) == INTEGER_CST
13910           && compare_tree_int (index, TREE_STRING_LENGTH (string)) < 0
13911           && (GET_MODE_CLASS (TYPE_MODE (TREE_TYPE (TREE_TYPE (string))))
13912               == MODE_INT)
13913           && (GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (TREE_TYPE (string)))) == 1))
13914         return build_int_cst_type (TREE_TYPE (exp),
13915                                    (TREE_STRING_POINTER (string)
13916                                     [TREE_INT_CST_LOW (index)]));
13917     }
13918   return NULL;
13919 }
13920
13921 /* Return the tree for neg (ARG0) when ARG0 is known to be either
13922    an integer constant, real, or fixed-point constant.
13923
13924    TYPE is the type of the result.  */
13925
13926 static tree
13927 fold_negate_const (tree arg0, tree type)
13928 {
13929   tree t = NULL_TREE;
13930
13931   switch (TREE_CODE (arg0))
13932     {
13933     case INTEGER_CST:
13934       {
13935         bool overflow;
13936         wide_int val = wi::neg (arg0, &overflow);
13937         t = force_fit_type (type, val, 1,
13938                             (overflow | TREE_OVERFLOW (arg0))
13939                             && !TYPE_UNSIGNED (type));
13940         break;
13941       }
13942
13943     case REAL_CST:
13944       t = build_real (type, real_value_negate (&TREE_REAL_CST (arg0)));
13945       break;
13946
13947     case FIXED_CST:
13948       {
13949         FIXED_VALUE_TYPE f;
13950         bool overflow_p = fixed_arithmetic (&f, NEGATE_EXPR,
13951                                             &(TREE_FIXED_CST (arg0)), NULL,
13952                                             TYPE_SATURATING (type));
13953         t = build_fixed (type, f);
13954         /* Propagate overflow flags.  */
13955         if (overflow_p | TREE_OVERFLOW (arg0))
13956           TREE_OVERFLOW (t) = 1;
13957         break;
13958       }
13959
13960     default:
13961       gcc_unreachable ();
13962     }
13963
13964   return t;
13965 }
13966
13967 /* Return the tree for abs (ARG0) when ARG0 is known to be either
13968    an integer constant or real constant.
13969
13970    TYPE is the type of the result.  */
13971
13972 tree
13973 fold_abs_const (tree arg0, tree type)
13974 {
13975   tree t = NULL_TREE;
13976
13977   switch (TREE_CODE (arg0))
13978     {
13979     case INTEGER_CST:
13980       {
13981         /* If the value is unsigned or non-negative, then the absolute value
13982            is the same as the ordinary value.  */
13983         if (!wi::neg_p (arg0, TYPE_SIGN (type)))
13984           t = arg0;
13985
13986         /* If the value is negative, then the absolute value is
13987            its negation.  */
13988         else
13989           {
13990             bool overflow;
13991             wide_int val = wi::neg (arg0, &overflow);
13992             t = force_fit_type (type, val, -1,
13993                                 overflow | TREE_OVERFLOW (arg0));
13994           }
13995       }
13996       break;
13997
13998     case REAL_CST:
13999       if (REAL_VALUE_NEGATIVE (TREE_REAL_CST (arg0)))
14000         t = build_real (type, real_value_negate (&TREE_REAL_CST (arg0)));
14001       else
14002         t =  arg0;
14003       break;
14004
14005     default:
14006       gcc_unreachable ();
14007     }
14008
14009   return t;
14010 }
14011
14012 /* Return the tree for not (ARG0) when ARG0 is known to be an integer
14013    constant.  TYPE is the type of the result.  */
14014
14015 static tree
14016 fold_not_const (const_tree arg0, tree type)
14017 {
14018   gcc_assert (TREE_CODE (arg0) == INTEGER_CST);
14019
14020   return force_fit_type (type, wi::bit_not (arg0), 0, TREE_OVERFLOW (arg0));
14021 }
14022
14023 /* Given CODE, a relational operator, the target type, TYPE and two
14024    constant operands OP0 and OP1, return the result of the
14025    relational operation.  If the result is not a compile time
14026    constant, then return NULL_TREE.  */
14027
14028 static tree
14029 fold_relational_const (enum tree_code code, tree type, tree op0, tree op1)
14030 {
14031   int result, invert;
14032
14033   /* From here on, the only cases we handle are when the result is
14034      known to be a constant.  */
14035
14036   if (TREE_CODE (op0) == REAL_CST && TREE_CODE (op1) == REAL_CST)
14037     {
14038       const REAL_VALUE_TYPE *c0 = TREE_REAL_CST_PTR (op0);
14039       const REAL_VALUE_TYPE *c1 = TREE_REAL_CST_PTR (op1);
14040
14041       /* Handle the cases where either operand is a NaN.  */
14042       if (real_isnan (c0) || real_isnan (c1))
14043         {
14044           switch (code)
14045             {
14046             case EQ_EXPR:
14047             case ORDERED_EXPR:
14048               result = 0;
14049               break;
14050
14051             case NE_EXPR:
14052             case UNORDERED_EXPR:
14053             case UNLT_EXPR:
14054             case UNLE_EXPR:
14055             case UNGT_EXPR:
14056             case UNGE_EXPR:
14057             case UNEQ_EXPR:
14058               result = 1;
14059               break;
14060
14061             case LT_EXPR:
14062             case LE_EXPR:
14063             case GT_EXPR:
14064             case GE_EXPR:
14065             case LTGT_EXPR:
14066               if (flag_trapping_math)
14067                 return NULL_TREE;
14068               result = 0;
14069               break;
14070
14071             default:
14072               gcc_unreachable ();
14073             }
14074
14075           return constant_boolean_node (result, type);
14076         }
14077
14078       return constant_boolean_node (real_compare (code, c0, c1), type);
14079     }
14080
14081   if (TREE_CODE (op0) == FIXED_CST && TREE_CODE (op1) == FIXED_CST)
14082     {
14083       const FIXED_VALUE_TYPE *c0 = TREE_FIXED_CST_PTR (op0);
14084       const FIXED_VALUE_TYPE *c1 = TREE_FIXED_CST_PTR (op1);
14085       return constant_boolean_node (fixed_compare (code, c0, c1), type);
14086     }
14087
14088   /* Handle equality/inequality of complex constants.  */
14089   if (TREE_CODE (op0) == COMPLEX_CST && TREE_CODE (op1) == COMPLEX_CST)
14090     {
14091       tree rcond = fold_relational_const (code, type,
14092                                           TREE_REALPART (op0),
14093                                           TREE_REALPART (op1));
14094       tree icond = fold_relational_const (code, type,
14095                                           TREE_IMAGPART (op0),
14096                                           TREE_IMAGPART (op1));
14097       if (code == EQ_EXPR)
14098         return fold_build2 (TRUTH_ANDIF_EXPR, type, rcond, icond);
14099       else if (code == NE_EXPR)
14100         return fold_build2 (TRUTH_ORIF_EXPR, type, rcond, icond);
14101       else
14102         return NULL_TREE;
14103     }
14104
14105   if (TREE_CODE (op0) == VECTOR_CST && TREE_CODE (op1) == VECTOR_CST)
14106     {
14107       if (!VECTOR_TYPE_P (type))
14108         {
14109           /* Have vector comparison with scalar boolean result.  */
14110           gcc_assert ((code == EQ_EXPR || code == NE_EXPR)
14111                       && VECTOR_CST_NELTS (op0) == VECTOR_CST_NELTS (op1));
14112           for (unsigned i = 0; i < VECTOR_CST_NELTS (op0); i++)
14113             {
14114               tree elem0 = VECTOR_CST_ELT (op0, i);
14115               tree elem1 = VECTOR_CST_ELT (op1, i);
14116               tree tmp = fold_relational_const (code, type, elem0, elem1);
14117               if (tmp == NULL_TREE)
14118                 return NULL_TREE;
14119               if (integer_zerop (tmp))
14120                 return constant_boolean_node (false, type);
14121             }
14122           return constant_boolean_node (true, type);
14123         }
14124       unsigned count = VECTOR_CST_NELTS (op0);
14125       tree *elts =  XALLOCAVEC (tree, count);
14126       gcc_assert (VECTOR_CST_NELTS (op1) == count
14127                   && TYPE_VECTOR_SUBPARTS (type) == count);
14128
14129       for (unsigned i = 0; i < count; i++)
14130         {
14131           tree elem_type = TREE_TYPE (type);
14132           tree elem0 = VECTOR_CST_ELT (op0, i);
14133           tree elem1 = VECTOR_CST_ELT (op1, i);
14134
14135           tree tem = fold_relational_const (code, elem_type,
14136                                             elem0, elem1);
14137
14138           if (tem == NULL_TREE)
14139             return NULL_TREE;
14140
14141           elts[i] = build_int_cst (elem_type, integer_zerop (tem) ? 0 : -1);
14142         }
14143
14144       return build_vector (type, elts);
14145     }
14146
14147   /* From here on we only handle LT, LE, GT, GE, EQ and NE.
14148
14149      To compute GT, swap the arguments and do LT.
14150      To compute GE, do LT and invert the result.
14151      To compute LE, swap the arguments, do LT and invert the result.
14152      To compute NE, do EQ and invert the result.
14153
14154      Therefore, the code below must handle only EQ and LT.  */
14155
14156   if (code == LE_EXPR || code == GT_EXPR)
14157     {
14158       std::swap (op0, op1);
14159       code = swap_tree_comparison (code);
14160     }
14161
14162   /* Note that it is safe to invert for real values here because we
14163      have already handled the one case that it matters.  */
14164
14165   invert = 0;
14166   if (code == NE_EXPR || code == GE_EXPR)
14167     {
14168       invert = 1;
14169       code = invert_tree_comparison (code, false);
14170     }
14171
14172   /* Compute a result for LT or EQ if args permit;
14173      Otherwise return T.  */
14174   if (TREE_CODE (op0) == INTEGER_CST && TREE_CODE (op1) == INTEGER_CST)
14175     {
14176       if (code == EQ_EXPR)
14177         result = tree_int_cst_equal (op0, op1);
14178       else
14179         result = tree_int_cst_lt (op0, op1);
14180     }
14181   else
14182     return NULL_TREE;
14183
14184   if (invert)
14185     result ^= 1;
14186   return constant_boolean_node (result, type);
14187 }
14188
14189 /* If necessary, return a CLEANUP_POINT_EXPR for EXPR with the
14190    indicated TYPE.  If no CLEANUP_POINT_EXPR is necessary, return EXPR
14191    itself.  */
14192
14193 tree
14194 fold_build_cleanup_point_expr (tree type, tree expr)
14195 {
14196   /* If the expression does not have side effects then we don't have to wrap
14197      it with a cleanup point expression.  */
14198   if (!TREE_SIDE_EFFECTS (expr))
14199     return expr;
14200
14201   /* If the expression is a return, check to see if the expression inside the
14202      return has no side effects or the right hand side of the modify expression
14203      inside the return. If either don't have side effects set we don't need to
14204      wrap the expression in a cleanup point expression.  Note we don't check the
14205      left hand side of the modify because it should always be a return decl.  */
14206   if (TREE_CODE (expr) == RETURN_EXPR)
14207     {
14208       tree op = TREE_OPERAND (expr, 0);
14209       if (!op || !TREE_SIDE_EFFECTS (op))
14210         return expr;
14211       op = TREE_OPERAND (op, 1);
14212       if (!TREE_SIDE_EFFECTS (op))
14213         return expr;
14214     }
14215
14216   return build1 (CLEANUP_POINT_EXPR, type, expr);
14217 }
14218
14219 /* Given a pointer value OP0 and a type TYPE, return a simplified version
14220    of an indirection through OP0, or NULL_TREE if no simplification is
14221    possible.  */
14222
14223 tree
14224 fold_indirect_ref_1 (location_t loc, tree type, tree op0)
14225 {
14226   tree sub = op0;
14227   tree subtype;
14228
14229   STRIP_NOPS (sub);
14230   subtype = TREE_TYPE (sub);
14231   if (!POINTER_TYPE_P (subtype))
14232     return NULL_TREE;
14233
14234   if (TREE_CODE (sub) == ADDR_EXPR)
14235     {
14236       tree op = TREE_OPERAND (sub, 0);
14237       tree optype = TREE_TYPE (op);
14238       /* *&CONST_DECL -> to the value of the const decl.  */
14239       if (TREE_CODE (op) == CONST_DECL)
14240         return DECL_INITIAL (op);
14241       /* *&p => p;  make sure to handle *&"str"[cst] here.  */
14242       if (type == optype)
14243         {
14244           tree fop = fold_read_from_constant_string (op);
14245           if (fop)
14246             return fop;
14247           else
14248             return op;
14249         }
14250       /* *(foo *)&fooarray => fooarray[0] */
14251       else if (TREE_CODE (optype) == ARRAY_TYPE
14252                && type == TREE_TYPE (optype)
14253                && (!in_gimple_form
14254                    || TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST))
14255         {
14256           tree type_domain = TYPE_DOMAIN (optype);
14257           tree min_val = size_zero_node;
14258           if (type_domain && TYPE_MIN_VALUE (type_domain))
14259             min_val = TYPE_MIN_VALUE (type_domain);
14260           if (in_gimple_form
14261               && TREE_CODE (min_val) != INTEGER_CST)
14262             return NULL_TREE;
14263           return build4_loc (loc, ARRAY_REF, type, op, min_val,
14264                              NULL_TREE, NULL_TREE);
14265         }
14266       /* *(foo *)&complexfoo => __real__ complexfoo */
14267       else if (TREE_CODE (optype) == COMPLEX_TYPE
14268                && type == TREE_TYPE (optype))
14269         return fold_build1_loc (loc, REALPART_EXPR, type, op);
14270       /* *(foo *)&vectorfoo => BIT_FIELD_REF<vectorfoo,...> */
14271       else if (TREE_CODE (optype) == VECTOR_TYPE
14272                && type == TREE_TYPE (optype))
14273         {
14274           tree part_width = TYPE_SIZE (type);
14275           tree index = bitsize_int (0);
14276           return fold_build3_loc (loc, BIT_FIELD_REF, type, op, part_width, index);
14277         }
14278     }
14279
14280   if (TREE_CODE (sub) == POINTER_PLUS_EXPR
14281       && TREE_CODE (TREE_OPERAND (sub, 1)) == INTEGER_CST)
14282     {
14283       tree op00 = TREE_OPERAND (sub, 0);
14284       tree op01 = TREE_OPERAND (sub, 1);
14285
14286       STRIP_NOPS (op00);
14287       if (TREE_CODE (op00) == ADDR_EXPR)
14288         {
14289           tree op00type;
14290           op00 = TREE_OPERAND (op00, 0);
14291           op00type = TREE_TYPE (op00);
14292
14293           /* ((foo*)&vectorfoo)[1] => BIT_FIELD_REF<vectorfoo,...> */
14294           if (TREE_CODE (op00type) == VECTOR_TYPE
14295               && type == TREE_TYPE (op00type))
14296             {
14297               tree part_width = TYPE_SIZE (type);
14298               unsigned HOST_WIDE_INT max_offset
14299                 = (tree_to_uhwi (part_width) / BITS_PER_UNIT
14300                    * TYPE_VECTOR_SUBPARTS (op00type));
14301               if (tree_int_cst_sign_bit (op01) == 0
14302                   && compare_tree_int (op01, max_offset) == -1)
14303                 {
14304                   unsigned HOST_WIDE_INT offset = tree_to_uhwi (op01);
14305                   unsigned HOST_WIDE_INT indexi = offset * BITS_PER_UNIT;
14306                   tree index = bitsize_int (indexi);
14307                   return fold_build3_loc (loc,
14308                                           BIT_FIELD_REF, type, op00,
14309                                           part_width, index);
14310                 }
14311             }
14312           /* ((foo*)&complexfoo)[1] => __imag__ complexfoo */
14313           else if (TREE_CODE (op00type) == COMPLEX_TYPE
14314                    && type == TREE_TYPE (op00type))
14315             {
14316               tree size = TYPE_SIZE_UNIT (type);
14317               if (tree_int_cst_equal (size, op01))
14318                 return fold_build1_loc (loc, IMAGPART_EXPR, type, op00);
14319             }
14320           /* ((foo *)&fooarray)[1] => fooarray[1] */
14321           else if (TREE_CODE (op00type) == ARRAY_TYPE
14322                    && type == TREE_TYPE (op00type))
14323             {
14324               tree type_domain = TYPE_DOMAIN (op00type);
14325               tree min_val = size_zero_node;
14326               if (type_domain && TYPE_MIN_VALUE (type_domain))
14327                 min_val = TYPE_MIN_VALUE (type_domain);
14328               op01 = size_binop_loc (loc, EXACT_DIV_EXPR, op01,
14329                                      TYPE_SIZE_UNIT (type));
14330               op01 = size_binop_loc (loc, PLUS_EXPR, op01, min_val);
14331               return build4_loc (loc, ARRAY_REF, type, op00, op01,
14332                                  NULL_TREE, NULL_TREE);
14333             }
14334         }
14335     }
14336
14337   /* *(foo *)fooarrptr => (*fooarrptr)[0] */
14338   if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
14339       && type == TREE_TYPE (TREE_TYPE (subtype))
14340       && (!in_gimple_form
14341           || TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST))
14342     {
14343       tree type_domain;
14344       tree min_val = size_zero_node;
14345       sub = build_fold_indirect_ref_loc (loc, sub);
14346       type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
14347       if (type_domain && TYPE_MIN_VALUE (type_domain))
14348         min_val = TYPE_MIN_VALUE (type_domain);
14349       if (in_gimple_form
14350           && TREE_CODE (min_val) != INTEGER_CST)
14351         return NULL_TREE;
14352       return build4_loc (loc, ARRAY_REF, type, sub, min_val, NULL_TREE,
14353                          NULL_TREE);
14354     }
14355
14356   return NULL_TREE;
14357 }
14358
14359 /* Builds an expression for an indirection through T, simplifying some
14360    cases.  */
14361
14362 tree
14363 build_fold_indirect_ref_loc (location_t loc, tree t)
14364 {
14365   tree type = TREE_TYPE (TREE_TYPE (t));
14366   tree sub = fold_indirect_ref_1 (loc, type, t);
14367
14368   if (sub)
14369     return sub;
14370
14371   return build1_loc (loc, INDIRECT_REF, type, t);
14372 }
14373
14374 /* Given an INDIRECT_REF T, return either T or a simplified version.  */
14375
14376 tree
14377 fold_indirect_ref_loc (location_t loc, tree t)
14378 {
14379   tree sub = fold_indirect_ref_1 (loc, TREE_TYPE (t), TREE_OPERAND (t, 0));
14380
14381   if (sub)
14382     return sub;
14383   else
14384     return t;
14385 }
14386
14387 /* Strip non-trapping, non-side-effecting tree nodes from an expression
14388    whose result is ignored.  The type of the returned tree need not be
14389    the same as the original expression.  */
14390
14391 tree
14392 fold_ignored_result (tree t)
14393 {
14394   if (!TREE_SIDE_EFFECTS (t))
14395     return integer_zero_node;
14396
14397   for (;;)
14398     switch (TREE_CODE_CLASS (TREE_CODE (t)))
14399       {
14400       case tcc_unary:
14401         t = TREE_OPERAND (t, 0);
14402         break;
14403
14404       case tcc_binary:
14405       case tcc_comparison:
14406         if (!TREE_SIDE_EFFECTS (TREE_OPERAND (t, 1)))
14407           t = TREE_OPERAND (t, 0);
14408         else if (!TREE_SIDE_EFFECTS (TREE_OPERAND (t, 0)))
14409           t = TREE_OPERAND (t, 1);
14410         else
14411           return t;
14412         break;
14413
14414       case tcc_expression:
14415         switch (TREE_CODE (t))
14416           {
14417           case COMPOUND_EXPR:
14418             if (TREE_SIDE_EFFECTS (TREE_OPERAND (t, 1)))
14419               return t;
14420             t = TREE_OPERAND (t, 0);
14421             break;
14422
14423           case COND_EXPR:
14424             if (TREE_SIDE_EFFECTS (TREE_OPERAND (t, 1))
14425                 || TREE_SIDE_EFFECTS (TREE_OPERAND (t, 2)))
14426               return t;
14427             t = TREE_OPERAND (t, 0);
14428             break;
14429
14430           default:
14431             return t;
14432           }
14433         break;
14434
14435       default:
14436         return t;
14437       }
14438 }
14439
14440 /* Return the value of VALUE, rounded up to a multiple of DIVISOR. */
14441
14442 tree
14443 round_up_loc (location_t loc, tree value, unsigned int divisor)
14444 {
14445   tree div = NULL_TREE;
14446
14447   if (divisor == 1)
14448     return value;
14449
14450   /* See if VALUE is already a multiple of DIVISOR.  If so, we don't
14451      have to do anything.  Only do this when we are not given a const,
14452      because in that case, this check is more expensive than just
14453      doing it.  */
14454   if (TREE_CODE (value) != INTEGER_CST)
14455     {
14456       div = build_int_cst (TREE_TYPE (value), divisor);
14457
14458       if (multiple_of_p (TREE_TYPE (value), value, div))
14459         return value;
14460     }
14461
14462   /* If divisor is a power of two, simplify this to bit manipulation.  */
14463   if (divisor == (divisor & -divisor))
14464     {
14465       if (TREE_CODE (value) == INTEGER_CST)
14466         {
14467           wide_int val = value;
14468           bool overflow_p;
14469
14470           if ((val & (divisor - 1)) == 0)
14471             return value;
14472
14473           overflow_p = TREE_OVERFLOW (value);
14474           val += divisor - 1;
14475           val &= - (int) divisor;
14476           if (val == 0)
14477             overflow_p = true;
14478
14479           return force_fit_type (TREE_TYPE (value), val, -1, overflow_p);
14480         }
14481       else
14482         {
14483           tree t;
14484
14485           t = build_int_cst (TREE_TYPE (value), divisor - 1);
14486           value = size_binop_loc (loc, PLUS_EXPR, value, t);
14487           t = build_int_cst (TREE_TYPE (value), - (int) divisor);
14488           value = size_binop_loc (loc, BIT_AND_EXPR, value, t);
14489         }
14490     }
14491   else
14492     {
14493       if (!div)
14494         div = build_int_cst (TREE_TYPE (value), divisor);
14495       value = size_binop_loc (loc, CEIL_DIV_EXPR, value, div);
14496       value = size_binop_loc (loc, MULT_EXPR, value, div);
14497     }
14498
14499   return value;
14500 }
14501
14502 /* Likewise, but round down.  */
14503
14504 tree
14505 round_down_loc (location_t loc, tree value, int divisor)
14506 {
14507   tree div = NULL_TREE;
14508
14509   gcc_assert (divisor > 0);
14510   if (divisor == 1)
14511     return value;
14512
14513   /* See if VALUE is already a multiple of DIVISOR.  If so, we don't
14514      have to do anything.  Only do this when we are not given a const,
14515      because in that case, this check is more expensive than just
14516      doing it.  */
14517   if (TREE_CODE (value) != INTEGER_CST)
14518     {
14519       div = build_int_cst (TREE_TYPE (value), divisor);
14520
14521       if (multiple_of_p (TREE_TYPE (value), value, div))
14522         return value;
14523     }
14524
14525   /* If divisor is a power of two, simplify this to bit manipulation.  */
14526   if (divisor == (divisor & -divisor))
14527     {
14528       tree t;
14529
14530       t = build_int_cst (TREE_TYPE (value), -divisor);
14531       value = size_binop_loc (loc, BIT_AND_EXPR, value, t);
14532     }
14533   else
14534     {
14535       if (!div)
14536         div = build_int_cst (TREE_TYPE (value), divisor);
14537       value = size_binop_loc (loc, FLOOR_DIV_EXPR, value, div);
14538       value = size_binop_loc (loc, MULT_EXPR, value, div);
14539     }
14540
14541   return value;
14542 }
14543
14544 /* Returns the pointer to the base of the object addressed by EXP and
14545    extracts the information about the offset of the access, storing it
14546    to PBITPOS and POFFSET.  */
14547
14548 static tree
14549 split_address_to_core_and_offset (tree exp,
14550                                   HOST_WIDE_INT *pbitpos, tree *poffset)
14551 {
14552   tree core;
14553   machine_mode mode;
14554   int unsignedp, reversep, volatilep;
14555   HOST_WIDE_INT bitsize;
14556   location_t loc = EXPR_LOCATION (exp);
14557
14558   if (TREE_CODE (exp) == ADDR_EXPR)
14559     {
14560       core = get_inner_reference (TREE_OPERAND (exp, 0), &bitsize, pbitpos,
14561                                   poffset, &mode, &unsignedp, &reversep,
14562                                   &volatilep, false);
14563       core = build_fold_addr_expr_loc (loc, core);
14564     }
14565   else
14566     {
14567       core = exp;
14568       *pbitpos = 0;
14569       *poffset = NULL_TREE;
14570     }
14571
14572   return core;
14573 }
14574
14575 /* Returns true if addresses of E1 and E2 differ by a constant, false
14576    otherwise.  If they do, E1 - E2 is stored in *DIFF.  */
14577
14578 bool
14579 ptr_difference_const (tree e1, tree e2, HOST_WIDE_INT *diff)
14580 {
14581   tree core1, core2;
14582   HOST_WIDE_INT bitpos1, bitpos2;
14583   tree toffset1, toffset2, tdiff, type;
14584
14585   core1 = split_address_to_core_and_offset (e1, &bitpos1, &toffset1);
14586   core2 = split_address_to_core_and_offset (e2, &bitpos2, &toffset2);
14587
14588   if (bitpos1 % BITS_PER_UNIT != 0
14589       || bitpos2 % BITS_PER_UNIT != 0
14590       || !operand_equal_p (core1, core2, 0))
14591     return false;
14592
14593   if (toffset1 && toffset2)
14594     {
14595       type = TREE_TYPE (toffset1);
14596       if (type != TREE_TYPE (toffset2))
14597         toffset2 = fold_convert (type, toffset2);
14598
14599       tdiff = fold_build2 (MINUS_EXPR, type, toffset1, toffset2);
14600       if (!cst_and_fits_in_hwi (tdiff))
14601         return false;
14602
14603       *diff = int_cst_value (tdiff);
14604     }
14605   else if (toffset1 || toffset2)
14606     {
14607       /* If only one of the offsets is non-constant, the difference cannot
14608          be a constant.  */
14609       return false;
14610     }
14611   else
14612     *diff = 0;
14613
14614   *diff += (bitpos1 - bitpos2) / BITS_PER_UNIT;
14615   return true;
14616 }
14617
14618 /* Return OFF converted to a pointer offset type suitable as offset for
14619    POINTER_PLUS_EXPR.  Use location LOC for this conversion.  */
14620 tree
14621 convert_to_ptrofftype_loc (location_t loc, tree off)
14622 {
14623   return fold_convert_loc (loc, sizetype, off);
14624 }
14625
14626 /* Build and fold a POINTER_PLUS_EXPR at LOC offsetting PTR by OFF.  */
14627 tree
14628 fold_build_pointer_plus_loc (location_t loc, tree ptr, tree off)
14629 {
14630   return fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (ptr),
14631                           ptr, convert_to_ptrofftype_loc (loc, off));
14632 }
14633
14634 /* Build and fold a POINTER_PLUS_EXPR at LOC offsetting PTR by OFF.  */
14635 tree
14636 fold_build_pointer_plus_hwi_loc (location_t loc, tree ptr, HOST_WIDE_INT off)
14637 {
14638   return fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (ptr),
14639                           ptr, size_int (off));
14640 }
14641
14642 /* Return a char pointer for a C string if it is a string constant
14643    or sum of string constant and integer constant.  */
14644
14645 const char *
14646 c_getstr (tree src)
14647 {
14648   tree offset_node;
14649
14650   src = string_constant (src, &offset_node);
14651   if (src == 0)
14652     return 0;
14653
14654   if (offset_node == 0)
14655     return TREE_STRING_POINTER (src);
14656   else if (!tree_fits_uhwi_p (offset_node)
14657            || compare_tree_int (offset_node, TREE_STRING_LENGTH (src) - 1) > 0)
14658     return 0;
14659
14660   return TREE_STRING_POINTER (src) + tree_to_uhwi (offset_node);
14661 }