match.pd: Add tcc_comparison...
[platform/upstream/gcc.git] / gcc / fold-const.c
1 /* Fold a constant sub-tree into a single node for C-compiler
2    Copyright (C) 1987-2014 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 "tm.h"
47 #include "flags.h"
48 #include "tree.h"
49 #include "stor-layout.h"
50 #include "calls.h"
51 #include "tree-iterator.h"
52 #include "realmpfr.h"
53 #include "rtl.h"
54 #include "expr.h"
55 #include "tm_p.h"
56 #include "target.h"
57 #include "diagnostic-core.h"
58 #include "intl.h"
59 #include "langhooks.h"
60 #include "md5.h"
61 #include "predict.h"
62 #include "vec.h"
63 #include "hashtab.h"
64 #include "hash-set.h"
65 #include "machmode.h"
66 #include "hard-reg-set.h"
67 #include "input.h"
68 #include "function.h"
69 #include "basic-block.h"
70 #include "tree-ssa-alias.h"
71 #include "internal-fn.h"
72 #include "tree-eh.h"
73 #include "gimple-expr.h"
74 #include "is-a.h"
75 #include "gimple.h"
76 #include "gimplify.h"
77 #include "tree-dfa.h"
78 #include "hash-table.h"  /* Required for ENABLE_FOLD_CHECKING.  */
79 #include "builtins.h"
80 #include "hash-map.h"
81 #include "plugin-api.h"
82 #include "ipa-ref.h"
83 #include "cgraph.h"
84 #include "generic-match.h"
85 #include "optabs.h"
86
87 /* Nonzero if we are folding constants inside an initializer; zero
88    otherwise.  */
89 int folding_initializer = 0;
90
91 /* The following constants represent a bit based encoding of GCC's
92    comparison operators.  This encoding simplifies transformations
93    on relational comparison operators, such as AND and OR.  */
94 enum comparison_code {
95   COMPCODE_FALSE = 0,
96   COMPCODE_LT = 1,
97   COMPCODE_EQ = 2,
98   COMPCODE_LE = 3,
99   COMPCODE_GT = 4,
100   COMPCODE_LTGT = 5,
101   COMPCODE_GE = 6,
102   COMPCODE_ORD = 7,
103   COMPCODE_UNORD = 8,
104   COMPCODE_UNLT = 9,
105   COMPCODE_UNEQ = 10,
106   COMPCODE_UNLE = 11,
107   COMPCODE_UNGT = 12,
108   COMPCODE_NE = 13,
109   COMPCODE_UNGE = 14,
110   COMPCODE_TRUE = 15
111 };
112
113 static bool negate_mathfn_p (enum built_in_function);
114 static bool negate_expr_p (tree);
115 static tree negate_expr (tree);
116 static tree split_tree (tree, enum tree_code, tree *, tree *, tree *, int);
117 static tree associate_trees (location_t, tree, tree, enum tree_code, tree);
118 static tree const_binop (enum tree_code, tree, tree);
119 static enum comparison_code comparison_to_compcode (enum tree_code);
120 static enum tree_code compcode_to_comparison (enum comparison_code);
121 static int operand_equal_for_comparison_p (tree, tree, tree);
122 static int twoval_comparison_p (tree, tree *, tree *, int *);
123 static tree eval_subst (location_t, tree, tree, tree, tree, tree);
124 static tree distribute_bit_expr (location_t, enum tree_code, tree, tree, tree);
125 static tree make_bit_field_ref (location_t, tree, tree,
126                                 HOST_WIDE_INT, HOST_WIDE_INT, int);
127 static tree optimize_bit_field_compare (location_t, enum tree_code,
128                                         tree, tree, tree);
129 static tree decode_field_reference (location_t, tree, HOST_WIDE_INT *,
130                                     HOST_WIDE_INT *,
131                                     machine_mode *, int *, int *,
132                                     tree *, tree *);
133 static tree sign_bit_p (tree, const_tree);
134 static int simple_operand_p (const_tree);
135 static bool simple_operand_p_2 (tree);
136 static tree range_binop (enum tree_code, tree, tree, int, tree, int);
137 static tree range_predecessor (tree);
138 static tree range_successor (tree);
139 static tree fold_range_test (location_t, enum tree_code, tree, tree, tree);
140 static tree fold_cond_expr_with_comparison (location_t, tree, tree, tree, tree);
141 static tree unextend (tree, int, int, tree);
142 static tree optimize_minmax_comparison (location_t, enum tree_code,
143                                         tree, tree, tree);
144 static tree extract_muldiv (tree, tree, enum tree_code, tree, bool *);
145 static tree extract_muldiv_1 (tree, tree, enum tree_code, tree, bool *);
146 static tree fold_binary_op_with_conditional_arg (location_t,
147                                                  enum tree_code, tree,
148                                                  tree, tree,
149                                                  tree, tree, int);
150 static tree fold_mathfn_compare (location_t,
151                                  enum built_in_function, enum tree_code,
152                                  tree, tree, tree);
153 static tree fold_inf_compare (location_t, enum tree_code, tree, tree, tree);
154 static tree fold_div_compare (location_t, enum tree_code, tree, tree, tree);
155 static bool reorder_operands_p (const_tree, const_tree);
156 static tree fold_negate_const (tree, tree);
157 static tree fold_not_const (const_tree, tree);
158 static tree fold_relational_const (enum tree_code, tree, tree, tree);
159 static tree fold_convert_const (enum tree_code, tree, tree);
160
161 /* Return EXPR_LOCATION of T if it is not UNKNOWN_LOCATION.
162    Otherwise, return LOC.  */
163
164 static location_t
165 expr_location_or (tree t, location_t loc)
166 {
167   location_t tloc = EXPR_LOCATION (t);
168   return tloc == UNKNOWN_LOCATION ? loc : tloc;
169 }
170
171 /* Similar to protected_set_expr_location, but never modify x in place,
172    if location can and needs to be set, unshare it.  */
173
174 static inline tree
175 protected_set_expr_location_unshare (tree x, location_t loc)
176 {
177   if (CAN_HAVE_LOCATION_P (x)
178       && EXPR_LOCATION (x) != loc
179       && !(TREE_CODE (x) == SAVE_EXPR
180            || TREE_CODE (x) == TARGET_EXPR
181            || TREE_CODE (x) == BIND_EXPR))
182     {
183       x = copy_node (x);
184       SET_EXPR_LOCATION (x, loc);
185     }
186   return x;
187 }
188 \f
189 /* If ARG2 divides ARG1 with zero remainder, carries out the exact
190    division and returns the quotient.  Otherwise returns
191    NULL_TREE.  */
192
193 tree
194 div_if_zero_remainder (const_tree arg1, const_tree arg2)
195 {
196   widest_int quo;
197
198   if (wi::multiple_of_p (wi::to_widest (arg1), wi::to_widest (arg2),
199                          SIGNED, &quo))
200     return wide_int_to_tree (TREE_TYPE (arg1), quo);
201
202   return NULL_TREE; 
203 }
204 \f
205 /* This is nonzero if we should defer warnings about undefined
206    overflow.  This facility exists because these warnings are a
207    special case.  The code to estimate loop iterations does not want
208    to issue any warnings, since it works with expressions which do not
209    occur in user code.  Various bits of cleanup code call fold(), but
210    only use the result if it has certain characteristics (e.g., is a
211    constant); that code only wants to issue a warning if the result is
212    used.  */
213
214 static int fold_deferring_overflow_warnings;
215
216 /* If a warning about undefined overflow is deferred, this is the
217    warning.  Note that this may cause us to turn two warnings into
218    one, but that is fine since it is sufficient to only give one
219    warning per expression.  */
220
221 static const char* fold_deferred_overflow_warning;
222
223 /* If a warning about undefined overflow is deferred, this is the
224    level at which the warning should be emitted.  */
225
226 static enum warn_strict_overflow_code fold_deferred_overflow_code;
227
228 /* Start deferring overflow warnings.  We could use a stack here to
229    permit nested calls, but at present it is not necessary.  */
230
231 void
232 fold_defer_overflow_warnings (void)
233 {
234   ++fold_deferring_overflow_warnings;
235 }
236
237 /* Stop deferring overflow warnings.  If there is a pending warning,
238    and ISSUE is true, then issue the warning if appropriate.  STMT is
239    the statement with which the warning should be associated (used for
240    location information); STMT may be NULL.  CODE is the level of the
241    warning--a warn_strict_overflow_code value.  This function will use
242    the smaller of CODE and the deferred code when deciding whether to
243    issue the warning.  CODE may be zero to mean to always use the
244    deferred code.  */
245
246 void
247 fold_undefer_overflow_warnings (bool issue, const_gimple stmt, int code)
248 {
249   const char *warnmsg;
250   location_t locus;
251
252   gcc_assert (fold_deferring_overflow_warnings > 0);
253   --fold_deferring_overflow_warnings;
254   if (fold_deferring_overflow_warnings > 0)
255     {
256       if (fold_deferred_overflow_warning != NULL
257           && code != 0
258           && code < (int) fold_deferred_overflow_code)
259         fold_deferred_overflow_code = (enum warn_strict_overflow_code) code;
260       return;
261     }
262
263   warnmsg = fold_deferred_overflow_warning;
264   fold_deferred_overflow_warning = NULL;
265
266   if (!issue || warnmsg == NULL)
267     return;
268
269   if (gimple_no_warning_p (stmt))
270     return;
271
272   /* Use the smallest code level when deciding to issue the
273      warning.  */
274   if (code == 0 || code > (int) fold_deferred_overflow_code)
275     code = fold_deferred_overflow_code;
276
277   if (!issue_strict_overflow_warning (code))
278     return;
279
280   if (stmt == NULL)
281     locus = input_location;
282   else
283     locus = gimple_location (stmt);
284   warning_at (locus, OPT_Wstrict_overflow, "%s", warnmsg);
285 }
286
287 /* Stop deferring overflow warnings, ignoring any deferred
288    warnings.  */
289
290 void
291 fold_undefer_and_ignore_overflow_warnings (void)
292 {
293   fold_undefer_overflow_warnings (false, NULL, 0);
294 }
295
296 /* Whether we are deferring overflow warnings.  */
297
298 bool
299 fold_deferring_overflow_warnings_p (void)
300 {
301   return fold_deferring_overflow_warnings > 0;
302 }
303
304 /* This is called when we fold something based on the fact that signed
305    overflow is undefined.  */
306
307 static void
308 fold_overflow_warning (const char* gmsgid, enum warn_strict_overflow_code wc)
309 {
310   if (fold_deferring_overflow_warnings > 0)
311     {
312       if (fold_deferred_overflow_warning == NULL
313           || wc < fold_deferred_overflow_code)
314         {
315           fold_deferred_overflow_warning = gmsgid;
316           fold_deferred_overflow_code = wc;
317         }
318     }
319   else if (issue_strict_overflow_warning (wc))
320     warning (OPT_Wstrict_overflow, gmsgid);
321 }
322 \f
323 /* Return true if the built-in mathematical function specified by CODE
324    is odd, i.e. -f(x) == f(-x).  */
325
326 static bool
327 negate_mathfn_p (enum built_in_function code)
328 {
329   switch (code)
330     {
331     CASE_FLT_FN (BUILT_IN_ASIN):
332     CASE_FLT_FN (BUILT_IN_ASINH):
333     CASE_FLT_FN (BUILT_IN_ATAN):
334     CASE_FLT_FN (BUILT_IN_ATANH):
335     CASE_FLT_FN (BUILT_IN_CASIN):
336     CASE_FLT_FN (BUILT_IN_CASINH):
337     CASE_FLT_FN (BUILT_IN_CATAN):
338     CASE_FLT_FN (BUILT_IN_CATANH):
339     CASE_FLT_FN (BUILT_IN_CBRT):
340     CASE_FLT_FN (BUILT_IN_CPROJ):
341     CASE_FLT_FN (BUILT_IN_CSIN):
342     CASE_FLT_FN (BUILT_IN_CSINH):
343     CASE_FLT_FN (BUILT_IN_CTAN):
344     CASE_FLT_FN (BUILT_IN_CTANH):
345     CASE_FLT_FN (BUILT_IN_ERF):
346     CASE_FLT_FN (BUILT_IN_LLROUND):
347     CASE_FLT_FN (BUILT_IN_LROUND):
348     CASE_FLT_FN (BUILT_IN_ROUND):
349     CASE_FLT_FN (BUILT_IN_SIN):
350     CASE_FLT_FN (BUILT_IN_SINH):
351     CASE_FLT_FN (BUILT_IN_TAN):
352     CASE_FLT_FN (BUILT_IN_TANH):
353     CASE_FLT_FN (BUILT_IN_TRUNC):
354       return true;
355
356     CASE_FLT_FN (BUILT_IN_LLRINT):
357     CASE_FLT_FN (BUILT_IN_LRINT):
358     CASE_FLT_FN (BUILT_IN_NEARBYINT):
359     CASE_FLT_FN (BUILT_IN_RINT):
360       return !flag_rounding_math;
361
362     default:
363       break;
364     }
365   return false;
366 }
367
368 /* Check whether we may negate an integer constant T without causing
369    overflow.  */
370
371 bool
372 may_negate_without_overflow_p (const_tree t)
373 {
374   tree type;
375
376   gcc_assert (TREE_CODE (t) == INTEGER_CST);
377
378   type = TREE_TYPE (t);
379   if (TYPE_UNSIGNED (type))
380     return false;
381
382   return !wi::only_sign_bit_p (t);
383 }
384
385 /* Determine whether an expression T can be cheaply negated using
386    the function negate_expr without introducing undefined overflow.  */
387
388 static bool
389 negate_expr_p (tree t)
390 {
391   tree type;
392
393   if (t == 0)
394     return false;
395
396   type = TREE_TYPE (t);
397
398   STRIP_SIGN_NOPS (t);
399   switch (TREE_CODE (t))
400     {
401     case INTEGER_CST:
402       if (TYPE_OVERFLOW_WRAPS (type))
403         return true;
404
405       /* Check that -CST will not overflow type.  */
406       return may_negate_without_overflow_p (t);
407     case BIT_NOT_EXPR:
408       return (INTEGRAL_TYPE_P (type)
409               && TYPE_OVERFLOW_WRAPS (type));
410
411     case FIXED_CST:
412     case NEGATE_EXPR:
413       return true;
414
415     case REAL_CST:
416       /* We want to canonicalize to positive real constants.  Pretend
417          that only negative ones can be easily negated.  */
418       return REAL_VALUE_NEGATIVE (TREE_REAL_CST (t));
419
420     case COMPLEX_CST:
421       return negate_expr_p (TREE_REALPART (t))
422              && negate_expr_p (TREE_IMAGPART (t));
423
424     case VECTOR_CST:
425       {
426         if (FLOAT_TYPE_P (TREE_TYPE (type)) || TYPE_OVERFLOW_WRAPS (type))
427           return true;
428
429         int count = TYPE_VECTOR_SUBPARTS (type), i;
430
431         for (i = 0; i < count; i++)
432           if (!negate_expr_p (VECTOR_CST_ELT (t, i)))
433             return false;
434
435         return true;
436       }
437
438     case COMPLEX_EXPR:
439       return negate_expr_p (TREE_OPERAND (t, 0))
440              && negate_expr_p (TREE_OPERAND (t, 1));
441
442     case CONJ_EXPR:
443       return negate_expr_p (TREE_OPERAND (t, 0));
444
445     case PLUS_EXPR:
446       if (HONOR_SIGN_DEPENDENT_ROUNDING (TYPE_MODE (type))
447           || HONOR_SIGNED_ZEROS (TYPE_MODE (type)))
448         return false;
449       /* -(A + B) -> (-B) - A.  */
450       if (negate_expr_p (TREE_OPERAND (t, 1))
451           && reorder_operands_p (TREE_OPERAND (t, 0),
452                                  TREE_OPERAND (t, 1)))
453         return true;
454       /* -(A + B) -> (-A) - B.  */
455       return negate_expr_p (TREE_OPERAND (t, 0));
456
457     case MINUS_EXPR:
458       /* We can't turn -(A-B) into B-A when we honor signed zeros.  */
459       return !HONOR_SIGN_DEPENDENT_ROUNDING (TYPE_MODE (type))
460              && !HONOR_SIGNED_ZEROS (TYPE_MODE (type))
461              && reorder_operands_p (TREE_OPERAND (t, 0),
462                                     TREE_OPERAND (t, 1));
463
464     case MULT_EXPR:
465       if (TYPE_UNSIGNED (TREE_TYPE (t)))
466         break;
467
468       /* Fall through.  */
469
470     case RDIV_EXPR:
471       if (! HONOR_SIGN_DEPENDENT_ROUNDING (TYPE_MODE (TREE_TYPE (t))))
472         return negate_expr_p (TREE_OPERAND (t, 1))
473                || negate_expr_p (TREE_OPERAND (t, 0));
474       break;
475
476     case TRUNC_DIV_EXPR:
477     case ROUND_DIV_EXPR:
478     case EXACT_DIV_EXPR:
479       /* In general we can't negate A / B, because if A is INT_MIN and
480          B is 1, we may turn this into INT_MIN / -1 which is undefined
481          and actually traps on some architectures.  But if overflow is
482          undefined, we can negate, because - (INT_MIN / 1) is an
483          overflow.  */
484       if (INTEGRAL_TYPE_P (TREE_TYPE (t)))
485         {
486           if (!TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (t)))
487             break;
488           /* If overflow is undefined then we have to be careful because
489              we ask whether it's ok to associate the negate with the
490              division which is not ok for example for
491              -((a - b) / c) where (-(a - b)) / c may invoke undefined
492              overflow because of negating INT_MIN.  So do not use
493              negate_expr_p here but open-code the two important cases.  */
494           if (TREE_CODE (TREE_OPERAND (t, 0)) == NEGATE_EXPR
495               || (TREE_CODE (TREE_OPERAND (t, 0)) == INTEGER_CST
496                   && may_negate_without_overflow_p (TREE_OPERAND (t, 0))))
497             return true;
498         }
499       else if (negate_expr_p (TREE_OPERAND (t, 0)))
500         return true;
501       return negate_expr_p (TREE_OPERAND (t, 1));
502
503     case NOP_EXPR:
504       /* Negate -((double)float) as (double)(-float).  */
505       if (TREE_CODE (type) == REAL_TYPE)
506         {
507           tree tem = strip_float_extensions (t);
508           if (tem != t)
509             return negate_expr_p (tem);
510         }
511       break;
512
513     case CALL_EXPR:
514       /* Negate -f(x) as f(-x).  */
515       if (negate_mathfn_p (builtin_mathfn_code (t)))
516         return negate_expr_p (CALL_EXPR_ARG (t, 0));
517       break;
518
519     case RSHIFT_EXPR:
520       /* Optimize -((int)x >> 31) into (unsigned)x >> 31 for int.  */
521       if (TREE_CODE (TREE_OPERAND (t, 1)) == INTEGER_CST)
522         {
523           tree op1 = TREE_OPERAND (t, 1);
524           if (wi::eq_p (op1, TYPE_PRECISION (type) - 1))
525             return true;
526         }
527       break;
528
529     default:
530       break;
531     }
532   return false;
533 }
534
535 /* Given T, an expression, return a folded tree for -T or NULL_TREE, if no
536    simplification is possible.
537    If negate_expr_p would return true for T, NULL_TREE will never be
538    returned.  */
539
540 static tree
541 fold_negate_expr (location_t loc, tree t)
542 {
543   tree type = TREE_TYPE (t);
544   tree tem;
545
546   switch (TREE_CODE (t))
547     {
548     /* Convert - (~A) to A + 1.  */
549     case BIT_NOT_EXPR:
550       if (INTEGRAL_TYPE_P (type))
551         return fold_build2_loc (loc, PLUS_EXPR, type, TREE_OPERAND (t, 0),
552                             build_one_cst (type));
553       break;
554
555     case INTEGER_CST:
556       tem = fold_negate_const (t, type);
557       if (TREE_OVERFLOW (tem) == TREE_OVERFLOW (t)
558           || !TYPE_OVERFLOW_TRAPS (type))
559         return tem;
560       break;
561
562     case REAL_CST:
563       tem = fold_negate_const (t, type);
564       /* Two's complement FP formats, such as c4x, may overflow.  */
565       if (!TREE_OVERFLOW (tem) || !flag_trapping_math)
566         return tem;
567       break;
568
569     case FIXED_CST:
570       tem = fold_negate_const (t, type);
571       return tem;
572
573     case COMPLEX_CST:
574       {
575         tree rpart = negate_expr (TREE_REALPART (t));
576         tree ipart = negate_expr (TREE_IMAGPART (t));
577
578         if ((TREE_CODE (rpart) == REAL_CST
579              && TREE_CODE (ipart) == REAL_CST)
580             || (TREE_CODE (rpart) == INTEGER_CST
581                 && TREE_CODE (ipart) == INTEGER_CST))
582           return build_complex (type, rpart, ipart);
583       }
584       break;
585
586     case VECTOR_CST:
587       {
588         int count = TYPE_VECTOR_SUBPARTS (type), i;
589         tree *elts = XALLOCAVEC (tree, count);
590
591         for (i = 0; i < count; i++)
592           {
593             elts[i] = fold_negate_expr (loc, VECTOR_CST_ELT (t, i));
594             if (elts[i] == NULL_TREE)
595               return NULL_TREE;
596           }
597
598         return build_vector (type, elts);
599       }
600
601     case COMPLEX_EXPR:
602       if (negate_expr_p (t))
603         return fold_build2_loc (loc, COMPLEX_EXPR, type,
604                             fold_negate_expr (loc, TREE_OPERAND (t, 0)),
605                             fold_negate_expr (loc, TREE_OPERAND (t, 1)));
606       break;
607
608     case CONJ_EXPR:
609       if (negate_expr_p (t))
610         return fold_build1_loc (loc, CONJ_EXPR, type,
611                             fold_negate_expr (loc, TREE_OPERAND (t, 0)));
612       break;
613
614     case NEGATE_EXPR:
615       return TREE_OPERAND (t, 0);
616
617     case PLUS_EXPR:
618       if (!HONOR_SIGN_DEPENDENT_ROUNDING (TYPE_MODE (type))
619           && !HONOR_SIGNED_ZEROS (TYPE_MODE (type)))
620         {
621           /* -(A + B) -> (-B) - A.  */
622           if (negate_expr_p (TREE_OPERAND (t, 1))
623               && reorder_operands_p (TREE_OPERAND (t, 0),
624                                      TREE_OPERAND (t, 1)))
625             {
626               tem = negate_expr (TREE_OPERAND (t, 1));
627               return fold_build2_loc (loc, MINUS_EXPR, type,
628                                   tem, TREE_OPERAND (t, 0));
629             }
630
631           /* -(A + B) -> (-A) - B.  */
632           if (negate_expr_p (TREE_OPERAND (t, 0)))
633             {
634               tem = negate_expr (TREE_OPERAND (t, 0));
635               return fold_build2_loc (loc, MINUS_EXPR, type,
636                                   tem, TREE_OPERAND (t, 1));
637             }
638         }
639       break;
640
641     case MINUS_EXPR:
642       /* - (A - B) -> B - A  */
643       if (!HONOR_SIGN_DEPENDENT_ROUNDING (TYPE_MODE (type))
644           && !HONOR_SIGNED_ZEROS (TYPE_MODE (type))
645           && reorder_operands_p (TREE_OPERAND (t, 0), TREE_OPERAND (t, 1)))
646         return fold_build2_loc (loc, MINUS_EXPR, type,
647                             TREE_OPERAND (t, 1), TREE_OPERAND (t, 0));
648       break;
649
650     case MULT_EXPR:
651       if (TYPE_UNSIGNED (type))
652         break;
653
654       /* Fall through.  */
655
656     case RDIV_EXPR:
657       if (! HONOR_SIGN_DEPENDENT_ROUNDING (TYPE_MODE (type)))
658         {
659           tem = TREE_OPERAND (t, 1);
660           if (negate_expr_p (tem))
661             return fold_build2_loc (loc, TREE_CODE (t), type,
662                                 TREE_OPERAND (t, 0), negate_expr (tem));
663           tem = TREE_OPERAND (t, 0);
664           if (negate_expr_p (tem))
665             return fold_build2_loc (loc, TREE_CODE (t), type,
666                                 negate_expr (tem), TREE_OPERAND (t, 1));
667         }
668       break;
669
670     case TRUNC_DIV_EXPR:
671     case ROUND_DIV_EXPR:
672     case EXACT_DIV_EXPR:
673       /* In general we can't negate A / B, because if A is INT_MIN and
674          B is 1, we may turn this into INT_MIN / -1 which is undefined
675          and actually traps on some architectures.  But if overflow is
676          undefined, we can negate, because - (INT_MIN / 1) is an
677          overflow.  */
678       if (!INTEGRAL_TYPE_P (type) || TYPE_OVERFLOW_UNDEFINED (type))
679         {
680           const char * const warnmsg = G_("assuming signed overflow does not "
681                                           "occur when negating a division");
682           tem = TREE_OPERAND (t, 1);
683           if (negate_expr_p (tem))
684             {
685               if (INTEGRAL_TYPE_P (type)
686                   && (TREE_CODE (tem) != INTEGER_CST
687                       || integer_onep (tem)))
688                 fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_MISC);
689               return fold_build2_loc (loc, TREE_CODE (t), type,
690                                   TREE_OPERAND (t, 0), negate_expr (tem));
691             }
692           /* If overflow is undefined then we have to be careful because
693              we ask whether it's ok to associate the negate with the
694              division which is not ok for example for
695              -((a - b) / c) where (-(a - b)) / c may invoke undefined
696              overflow because of negating INT_MIN.  So do not use
697              negate_expr_p here but open-code the two important cases.  */
698           tem = TREE_OPERAND (t, 0);
699           if ((INTEGRAL_TYPE_P (type)
700                && (TREE_CODE (tem) == NEGATE_EXPR
701                    || (TREE_CODE (tem) == INTEGER_CST
702                        && may_negate_without_overflow_p (tem))))
703               || !INTEGRAL_TYPE_P (type))
704             return fold_build2_loc (loc, TREE_CODE (t), type,
705                                     negate_expr (tem), TREE_OPERAND (t, 1));
706         }
707       break;
708
709     case NOP_EXPR:
710       /* Convert -((double)float) into (double)(-float).  */
711       if (TREE_CODE (type) == REAL_TYPE)
712         {
713           tem = strip_float_extensions (t);
714           if (tem != t && negate_expr_p (tem))
715             return fold_convert_loc (loc, type, negate_expr (tem));
716         }
717       break;
718
719     case CALL_EXPR:
720       /* Negate -f(x) as f(-x).  */
721       if (negate_mathfn_p (builtin_mathfn_code (t))
722           && negate_expr_p (CALL_EXPR_ARG (t, 0)))
723         {
724           tree fndecl, arg;
725
726           fndecl = get_callee_fndecl (t);
727           arg = negate_expr (CALL_EXPR_ARG (t, 0));
728           return build_call_expr_loc (loc, fndecl, 1, arg);
729         }
730       break;
731
732     case RSHIFT_EXPR:
733       /* Optimize -((int)x >> 31) into (unsigned)x >> 31 for int.  */
734       if (TREE_CODE (TREE_OPERAND (t, 1)) == INTEGER_CST)
735         {
736           tree op1 = TREE_OPERAND (t, 1);
737           if (wi::eq_p (op1, TYPE_PRECISION (type) - 1))
738             {
739               tree ntype = TYPE_UNSIGNED (type)
740                            ? signed_type_for (type)
741                            : unsigned_type_for (type);
742               tree temp = fold_convert_loc (loc, ntype, TREE_OPERAND (t, 0));
743               temp = fold_build2_loc (loc, RSHIFT_EXPR, ntype, temp, op1);
744               return fold_convert_loc (loc, type, temp);
745             }
746         }
747       break;
748
749     default:
750       break;
751     }
752
753   return NULL_TREE;
754 }
755
756 /* Like fold_negate_expr, but return a NEGATE_EXPR tree, if T can not be
757    negated in a simpler way.  Also allow for T to be NULL_TREE, in which case
758    return NULL_TREE. */
759
760 static tree
761 negate_expr (tree t)
762 {
763   tree type, tem;
764   location_t loc;
765
766   if (t == NULL_TREE)
767     return NULL_TREE;
768
769   loc = EXPR_LOCATION (t);
770   type = TREE_TYPE (t);
771   STRIP_SIGN_NOPS (t);
772
773   tem = fold_negate_expr (loc, t);
774   if (!tem)
775     tem = build1_loc (loc, NEGATE_EXPR, TREE_TYPE (t), t);
776   return fold_convert_loc (loc, type, tem);
777 }
778 \f
779 /* Split a tree IN into a constant, literal and variable parts that could be
780    combined with CODE to make IN.  "constant" means an expression with
781    TREE_CONSTANT but that isn't an actual constant.  CODE must be a
782    commutative arithmetic operation.  Store the constant part into *CONP,
783    the literal in *LITP and return the variable part.  If a part isn't
784    present, set it to null.  If the tree does not decompose in this way,
785    return the entire tree as the variable part and the other parts as null.
786
787    If CODE is PLUS_EXPR we also split trees that use MINUS_EXPR.  In that
788    case, we negate an operand that was subtracted.  Except if it is a
789    literal for which we use *MINUS_LITP instead.
790
791    If NEGATE_P is true, we are negating all of IN, again except a literal
792    for which we use *MINUS_LITP instead.
793
794    If IN is itself a literal or constant, return it as appropriate.
795
796    Note that we do not guarantee that any of the three values will be the
797    same type as IN, but they will have the same signedness and mode.  */
798
799 static tree
800 split_tree (tree in, enum tree_code code, tree *conp, tree *litp,
801             tree *minus_litp, int negate_p)
802 {
803   tree var = 0;
804
805   *conp = 0;
806   *litp = 0;
807   *minus_litp = 0;
808
809   /* Strip any conversions that don't change the machine mode or signedness.  */
810   STRIP_SIGN_NOPS (in);
811
812   if (TREE_CODE (in) == INTEGER_CST || TREE_CODE (in) == REAL_CST
813       || TREE_CODE (in) == FIXED_CST)
814     *litp = in;
815   else if (TREE_CODE (in) == code
816            || ((! FLOAT_TYPE_P (TREE_TYPE (in)) || flag_associative_math)
817                && ! SAT_FIXED_POINT_TYPE_P (TREE_TYPE (in))
818                /* We can associate addition and subtraction together (even
819                   though the C standard doesn't say so) for integers because
820                   the value is not affected.  For reals, the value might be
821                   affected, so we can't.  */
822                && ((code == PLUS_EXPR && TREE_CODE (in) == MINUS_EXPR)
823                    || (code == MINUS_EXPR && TREE_CODE (in) == PLUS_EXPR))))
824     {
825       tree op0 = TREE_OPERAND (in, 0);
826       tree op1 = TREE_OPERAND (in, 1);
827       int neg1_p = TREE_CODE (in) == MINUS_EXPR;
828       int neg_litp_p = 0, neg_conp_p = 0, neg_var_p = 0;
829
830       /* First see if either of the operands is a literal, then a constant.  */
831       if (TREE_CODE (op0) == INTEGER_CST || TREE_CODE (op0) == REAL_CST
832           || TREE_CODE (op0) == FIXED_CST)
833         *litp = op0, op0 = 0;
834       else if (TREE_CODE (op1) == INTEGER_CST || TREE_CODE (op1) == REAL_CST
835                || TREE_CODE (op1) == FIXED_CST)
836         *litp = op1, neg_litp_p = neg1_p, op1 = 0;
837
838       if (op0 != 0 && TREE_CONSTANT (op0))
839         *conp = op0, op0 = 0;
840       else if (op1 != 0 && TREE_CONSTANT (op1))
841         *conp = op1, neg_conp_p = neg1_p, op1 = 0;
842
843       /* If we haven't dealt with either operand, this is not a case we can
844          decompose.  Otherwise, VAR is either of the ones remaining, if any.  */
845       if (op0 != 0 && op1 != 0)
846         var = in;
847       else if (op0 != 0)
848         var = op0;
849       else
850         var = op1, neg_var_p = neg1_p;
851
852       /* Now do any needed negations.  */
853       if (neg_litp_p)
854         *minus_litp = *litp, *litp = 0;
855       if (neg_conp_p)
856         *conp = negate_expr (*conp);
857       if (neg_var_p)
858         var = negate_expr (var);
859     }
860   else if (TREE_CODE (in) == BIT_NOT_EXPR
861            && code == PLUS_EXPR)
862     {
863       /* -X - 1 is folded to ~X, undo that here.  */
864       *minus_litp = build_one_cst (TREE_TYPE (in));
865       var = negate_expr (TREE_OPERAND (in, 0));
866     }
867   else if (TREE_CONSTANT (in))
868     *conp = in;
869   else
870     var = in;
871
872   if (negate_p)
873     {
874       if (*litp)
875         *minus_litp = *litp, *litp = 0;
876       else if (*minus_litp)
877         *litp = *minus_litp, *minus_litp = 0;
878       *conp = negate_expr (*conp);
879       var = negate_expr (var);
880     }
881
882   return var;
883 }
884
885 /* Re-associate trees split by the above function.  T1 and T2 are
886    either expressions to associate or null.  Return the new
887    expression, if any.  LOC is the location of the new expression.  If
888    we build an operation, do it in TYPE and with CODE.  */
889
890 static tree
891 associate_trees (location_t loc, tree t1, tree t2, enum tree_code code, tree type)
892 {
893   if (t1 == 0)
894     return t2;
895   else if (t2 == 0)
896     return t1;
897
898   /* If either input is CODE, a PLUS_EXPR, or a MINUS_EXPR, don't
899      try to fold this since we will have infinite recursion.  But do
900      deal with any NEGATE_EXPRs.  */
901   if (TREE_CODE (t1) == code || TREE_CODE (t2) == code
902       || TREE_CODE (t1) == MINUS_EXPR || TREE_CODE (t2) == MINUS_EXPR)
903     {
904       if (code == PLUS_EXPR)
905         {
906           if (TREE_CODE (t1) == NEGATE_EXPR)
907             return build2_loc (loc, MINUS_EXPR, type,
908                                fold_convert_loc (loc, type, t2),
909                                fold_convert_loc (loc, type,
910                                                  TREE_OPERAND (t1, 0)));
911           else if (TREE_CODE (t2) == NEGATE_EXPR)
912             return build2_loc (loc, MINUS_EXPR, type,
913                                fold_convert_loc (loc, type, t1),
914                                fold_convert_loc (loc, type,
915                                                  TREE_OPERAND (t2, 0)));
916           else if (integer_zerop (t2))
917             return fold_convert_loc (loc, type, t1);
918         }
919       else if (code == MINUS_EXPR)
920         {
921           if (integer_zerop (t2))
922             return fold_convert_loc (loc, type, t1);
923         }
924
925       return build2_loc (loc, code, type, fold_convert_loc (loc, type, t1),
926                          fold_convert_loc (loc, type, t2));
927     }
928
929   return fold_build2_loc (loc, code, type, fold_convert_loc (loc, type, t1),
930                           fold_convert_loc (loc, type, t2));
931 }
932 \f
933 /* Check whether TYPE1 and TYPE2 are equivalent integer types, suitable
934    for use in int_const_binop, size_binop and size_diffop.  */
935
936 static bool
937 int_binop_types_match_p (enum tree_code code, const_tree type1, const_tree type2)
938 {
939   if (!INTEGRAL_TYPE_P (type1) && !POINTER_TYPE_P (type1))
940     return false;
941   if (!INTEGRAL_TYPE_P (type2) && !POINTER_TYPE_P (type2))
942     return false;
943
944   switch (code)
945     {
946     case LSHIFT_EXPR:
947     case RSHIFT_EXPR:
948     case LROTATE_EXPR:
949     case RROTATE_EXPR:
950       return true;
951
952     default:
953       break;
954     }
955
956   return TYPE_UNSIGNED (type1) == TYPE_UNSIGNED (type2)
957          && TYPE_PRECISION (type1) == TYPE_PRECISION (type2)
958          && TYPE_MODE (type1) == TYPE_MODE (type2);
959 }
960
961
962 /* Combine two integer constants ARG1 and ARG2 under operation CODE
963    to produce a new constant.  Return NULL_TREE if we don't know how
964    to evaluate CODE at compile-time.  */
965
966 static tree
967 int_const_binop_1 (enum tree_code code, const_tree arg1, const_tree parg2,
968                    int overflowable)
969 {
970   wide_int res;
971   tree t;
972   tree type = TREE_TYPE (arg1);
973   signop sign = TYPE_SIGN (type);
974   bool overflow = false;
975
976   wide_int arg2 = wide_int::from (parg2, TYPE_PRECISION (type),
977                                   TYPE_SIGN (TREE_TYPE (parg2)));
978
979   switch (code)
980     {
981     case BIT_IOR_EXPR:
982       res = wi::bit_or (arg1, arg2);
983       break;
984
985     case BIT_XOR_EXPR:
986       res = wi::bit_xor (arg1, arg2);
987       break;
988
989     case BIT_AND_EXPR:
990       res = wi::bit_and (arg1, arg2);
991       break;
992
993     case RSHIFT_EXPR:
994     case LSHIFT_EXPR:
995       if (wi::neg_p (arg2))
996         {
997           arg2 = -arg2;
998           if (code == RSHIFT_EXPR)
999             code = LSHIFT_EXPR;
1000           else
1001             code = RSHIFT_EXPR;
1002         }
1003
1004       if (code == RSHIFT_EXPR)
1005         /* It's unclear from the C standard whether shifts can overflow.
1006            The following code ignores overflow; perhaps a C standard
1007            interpretation ruling is needed.  */
1008         res = wi::rshift (arg1, arg2, sign);
1009       else
1010         res = wi::lshift (arg1, arg2);
1011       break;
1012
1013     case RROTATE_EXPR:
1014     case LROTATE_EXPR:
1015       if (wi::neg_p (arg2))
1016         {
1017           arg2 = -arg2;
1018           if (code == RROTATE_EXPR)
1019             code = LROTATE_EXPR;
1020           else
1021             code = RROTATE_EXPR;
1022         }
1023
1024       if (code == RROTATE_EXPR)
1025         res = wi::rrotate (arg1, arg2);
1026       else
1027         res = wi::lrotate (arg1, arg2);
1028       break;
1029
1030     case PLUS_EXPR:
1031       res = wi::add (arg1, arg2, sign, &overflow);
1032       break;
1033
1034     case MINUS_EXPR:
1035       res = wi::sub (arg1, arg2, sign, &overflow);
1036       break;
1037
1038     case MULT_EXPR:
1039       res = wi::mul (arg1, arg2, sign, &overflow);
1040       break;
1041
1042     case MULT_HIGHPART_EXPR:
1043       res = wi::mul_high (arg1, arg2, sign);
1044       break;
1045
1046     case TRUNC_DIV_EXPR:
1047     case EXACT_DIV_EXPR:
1048       if (arg2 == 0)
1049         return NULL_TREE;
1050       res = wi::div_trunc (arg1, arg2, sign, &overflow);
1051       break;
1052
1053     case FLOOR_DIV_EXPR:
1054       if (arg2 == 0)
1055         return NULL_TREE;
1056       res = wi::div_floor (arg1, arg2, sign, &overflow);
1057       break;
1058
1059     case CEIL_DIV_EXPR:
1060       if (arg2 == 0)
1061         return NULL_TREE;
1062       res = wi::div_ceil (arg1, arg2, sign, &overflow);
1063       break;
1064
1065     case ROUND_DIV_EXPR:
1066       if (arg2 == 0)
1067         return NULL_TREE;
1068       res = wi::div_round (arg1, arg2, sign, &overflow);
1069       break;
1070
1071     case TRUNC_MOD_EXPR:
1072       if (arg2 == 0)
1073         return NULL_TREE;
1074       res = wi::mod_trunc (arg1, arg2, sign, &overflow);
1075       break;
1076
1077     case FLOOR_MOD_EXPR:
1078       if (arg2 == 0)
1079         return NULL_TREE;
1080       res = wi::mod_floor (arg1, arg2, sign, &overflow);
1081       break;
1082
1083     case CEIL_MOD_EXPR:
1084       if (arg2 == 0)
1085         return NULL_TREE;
1086       res = wi::mod_ceil (arg1, arg2, sign, &overflow);
1087       break;
1088
1089     case ROUND_MOD_EXPR:
1090       if (arg2 == 0)
1091         return NULL_TREE;
1092       res = wi::mod_round (arg1, arg2, sign, &overflow);
1093       break;
1094
1095     case MIN_EXPR:
1096       res = wi::min (arg1, arg2, sign);
1097       break;
1098
1099     case MAX_EXPR:
1100       res = wi::max (arg1, arg2, sign);
1101       break;
1102
1103     default:
1104       return NULL_TREE;
1105     }
1106
1107   t = force_fit_type (type, res, overflowable,
1108                       (((sign == SIGNED || overflowable == -1)
1109                         && overflow)
1110                        | TREE_OVERFLOW (arg1) | TREE_OVERFLOW (parg2)));
1111
1112   return t;
1113 }
1114
1115 tree
1116 int_const_binop (enum tree_code code, const_tree arg1, const_tree arg2)
1117 {
1118   return int_const_binop_1 (code, arg1, arg2, 1);
1119 }
1120
1121 /* Combine two constants ARG1 and ARG2 under operation CODE to produce a new
1122    constant.  We assume ARG1 and ARG2 have the same data type, or at least
1123    are the same kind of constant and the same machine mode.  Return zero if
1124    combining the constants is not allowed in the current operating mode.  */
1125
1126 static tree
1127 const_binop (enum tree_code code, tree arg1, tree arg2)
1128 {
1129   /* Sanity check for the recursive cases.  */
1130   if (!arg1 || !arg2)
1131     return NULL_TREE;
1132
1133   STRIP_NOPS (arg1);
1134   STRIP_NOPS (arg2);
1135
1136   if (TREE_CODE (arg1) == INTEGER_CST)
1137     return int_const_binop (code, arg1, arg2);
1138
1139   if (TREE_CODE (arg1) == REAL_CST)
1140     {
1141       machine_mode mode;
1142       REAL_VALUE_TYPE d1;
1143       REAL_VALUE_TYPE d2;
1144       REAL_VALUE_TYPE value;
1145       REAL_VALUE_TYPE result;
1146       bool inexact;
1147       tree t, type;
1148
1149       /* The following codes are handled by real_arithmetic.  */
1150       switch (code)
1151         {
1152         case PLUS_EXPR:
1153         case MINUS_EXPR:
1154         case MULT_EXPR:
1155         case RDIV_EXPR:
1156         case MIN_EXPR:
1157         case MAX_EXPR:
1158           break;
1159
1160         default:
1161           return NULL_TREE;
1162         }
1163
1164       d1 = TREE_REAL_CST (arg1);
1165       d2 = TREE_REAL_CST (arg2);
1166
1167       type = TREE_TYPE (arg1);
1168       mode = TYPE_MODE (type);
1169
1170       /* Don't perform operation if we honor signaling NaNs and
1171          either operand is a NaN.  */
1172       if (HONOR_SNANS (mode)
1173           && (REAL_VALUE_ISNAN (d1) || REAL_VALUE_ISNAN (d2)))
1174         return NULL_TREE;
1175
1176       /* Don't perform operation if it would raise a division
1177          by zero exception.  */
1178       if (code == RDIV_EXPR
1179           && REAL_VALUES_EQUAL (d2, dconst0)
1180           && (flag_trapping_math || ! MODE_HAS_INFINITIES (mode)))
1181         return NULL_TREE;
1182
1183       /* If either operand is a NaN, just return it.  Otherwise, set up
1184          for floating-point trap; we return an overflow.  */
1185       if (REAL_VALUE_ISNAN (d1))
1186         return arg1;
1187       else if (REAL_VALUE_ISNAN (d2))
1188         return arg2;
1189
1190       inexact = real_arithmetic (&value, code, &d1, &d2);
1191       real_convert (&result, mode, &value);
1192
1193       /* Don't constant fold this floating point operation if
1194          the result has overflowed and flag_trapping_math.  */
1195       if (flag_trapping_math
1196           && MODE_HAS_INFINITIES (mode)
1197           && REAL_VALUE_ISINF (result)
1198           && !REAL_VALUE_ISINF (d1)
1199           && !REAL_VALUE_ISINF (d2))
1200         return NULL_TREE;
1201
1202       /* Don't constant fold this floating point operation if the
1203          result may dependent upon the run-time rounding mode and
1204          flag_rounding_math is set, or if GCC's software emulation
1205          is unable to accurately represent the result.  */
1206       if ((flag_rounding_math
1207            || (MODE_COMPOSITE_P (mode) && !flag_unsafe_math_optimizations))
1208           && (inexact || !real_identical (&result, &value)))
1209         return NULL_TREE;
1210
1211       t = build_real (type, result);
1212
1213       TREE_OVERFLOW (t) = TREE_OVERFLOW (arg1) | TREE_OVERFLOW (arg2);
1214       return t;
1215     }
1216
1217   if (TREE_CODE (arg1) == FIXED_CST)
1218     {
1219       FIXED_VALUE_TYPE f1;
1220       FIXED_VALUE_TYPE f2;
1221       FIXED_VALUE_TYPE result;
1222       tree t, type;
1223       int sat_p;
1224       bool overflow_p;
1225
1226       /* The following codes are handled by fixed_arithmetic.  */
1227       switch (code)
1228         {
1229         case PLUS_EXPR:
1230         case MINUS_EXPR:
1231         case MULT_EXPR:
1232         case TRUNC_DIV_EXPR:
1233           f2 = TREE_FIXED_CST (arg2);
1234           break;
1235
1236         case LSHIFT_EXPR:
1237         case RSHIFT_EXPR:
1238           {
1239             wide_int w2 = arg2;
1240             f2.data.high = w2.elt (1);
1241             f2.data.low = w2.elt (0);
1242             f2.mode = SImode;
1243           }
1244           break;
1245
1246         default:
1247           return NULL_TREE;
1248         }
1249
1250       f1 = TREE_FIXED_CST (arg1);
1251       type = TREE_TYPE (arg1);
1252       sat_p = TYPE_SATURATING (type);
1253       overflow_p = fixed_arithmetic (&result, code, &f1, &f2, sat_p);
1254       t = build_fixed (type, result);
1255       /* Propagate overflow flags.  */
1256       if (overflow_p | TREE_OVERFLOW (arg1) | TREE_OVERFLOW (arg2))
1257         TREE_OVERFLOW (t) = 1;
1258       return t;
1259     }
1260
1261   if (TREE_CODE (arg1) == COMPLEX_CST)
1262     {
1263       tree type = TREE_TYPE (arg1);
1264       tree r1 = TREE_REALPART (arg1);
1265       tree i1 = TREE_IMAGPART (arg1);
1266       tree r2 = TREE_REALPART (arg2);
1267       tree i2 = TREE_IMAGPART (arg2);
1268       tree real, imag;
1269
1270       switch (code)
1271         {
1272         case PLUS_EXPR:
1273         case MINUS_EXPR:
1274           real = const_binop (code, r1, r2);
1275           imag = const_binop (code, i1, i2);
1276           break;
1277
1278         case MULT_EXPR:
1279           if (COMPLEX_FLOAT_TYPE_P (type))
1280             return do_mpc_arg2 (arg1, arg2, type,
1281                                 /* do_nonfinite= */ folding_initializer,
1282                                 mpc_mul);
1283
1284           real = const_binop (MINUS_EXPR,
1285                               const_binop (MULT_EXPR, r1, r2),
1286                               const_binop (MULT_EXPR, i1, i2));
1287           imag = const_binop (PLUS_EXPR,
1288                               const_binop (MULT_EXPR, r1, i2),
1289                               const_binop (MULT_EXPR, i1, r2));
1290           break;
1291
1292         case RDIV_EXPR:
1293           if (COMPLEX_FLOAT_TYPE_P (type))
1294             return do_mpc_arg2 (arg1, arg2, type,
1295                                 /* do_nonfinite= */ folding_initializer,
1296                                 mpc_div);
1297           /* Fallthru ... */
1298         case TRUNC_DIV_EXPR:
1299         case CEIL_DIV_EXPR:
1300         case FLOOR_DIV_EXPR:
1301         case ROUND_DIV_EXPR:
1302           if (flag_complex_method == 0)
1303           {
1304             /* Keep this algorithm in sync with
1305                tree-complex.c:expand_complex_div_straight().
1306
1307                Expand complex division to scalars, straightforward algorithm.
1308                a / b = ((ar*br + ai*bi)/t) + i((ai*br - ar*bi)/t)
1309                t = br*br + bi*bi
1310             */
1311             tree magsquared
1312               = const_binop (PLUS_EXPR,
1313                              const_binop (MULT_EXPR, r2, r2),
1314                              const_binop (MULT_EXPR, i2, i2));
1315             tree t1
1316               = const_binop (PLUS_EXPR,
1317                              const_binop (MULT_EXPR, r1, r2),
1318                              const_binop (MULT_EXPR, i1, i2));
1319             tree t2
1320               = const_binop (MINUS_EXPR,
1321                              const_binop (MULT_EXPR, i1, r2),
1322                              const_binop (MULT_EXPR, r1, i2));
1323
1324             real = const_binop (code, t1, magsquared);
1325             imag = const_binop (code, t2, magsquared);
1326           }
1327           else
1328           {
1329             /* Keep this algorithm in sync with
1330                tree-complex.c:expand_complex_div_wide().
1331
1332                Expand complex division to scalars, modified algorithm to minimize
1333                overflow with wide input ranges.  */
1334             tree compare = fold_build2 (LT_EXPR, boolean_type_node,
1335                                         fold_abs_const (r2, TREE_TYPE (type)),
1336                                         fold_abs_const (i2, TREE_TYPE (type)));
1337
1338             if (integer_nonzerop (compare))
1339               {
1340                 /* In the TRUE branch, we compute
1341                    ratio = br/bi;
1342                    div = (br * ratio) + bi;
1343                    tr = (ar * ratio) + ai;
1344                    ti = (ai * ratio) - ar;
1345                    tr = tr / div;
1346                    ti = ti / div;  */
1347                 tree ratio = const_binop (code, r2, i2);
1348                 tree div = const_binop (PLUS_EXPR, i2,
1349                                         const_binop (MULT_EXPR, r2, ratio));
1350                 real = const_binop (MULT_EXPR, r1, ratio);
1351                 real = const_binop (PLUS_EXPR, real, i1);
1352                 real = const_binop (code, real, div);
1353
1354                 imag = const_binop (MULT_EXPR, i1, ratio);
1355                 imag = const_binop (MINUS_EXPR, imag, r1);
1356                 imag = const_binop (code, imag, div);
1357               }
1358             else
1359               {
1360                 /* In the FALSE branch, we compute
1361                    ratio = d/c;
1362                    divisor = (d * ratio) + c;
1363                    tr = (b * ratio) + a;
1364                    ti = b - (a * ratio);
1365                    tr = tr / div;
1366                    ti = ti / div;  */
1367                 tree ratio = const_binop (code, i2, r2);
1368                 tree div = const_binop (PLUS_EXPR, r2,
1369                                         const_binop (MULT_EXPR, i2, ratio));
1370
1371                 real = const_binop (MULT_EXPR, i1, ratio);
1372                 real = const_binop (PLUS_EXPR, real, r1);
1373                 real = const_binop (code, real, div);
1374
1375                 imag = const_binop (MULT_EXPR, r1, ratio);
1376                 imag = const_binop (MINUS_EXPR, i1, imag);
1377                 imag = const_binop (code, imag, div);
1378               }
1379           }
1380           break;
1381
1382         default:
1383           return NULL_TREE;
1384         }
1385
1386       if (real && imag)
1387         return build_complex (type, real, imag);
1388     }
1389
1390   if (TREE_CODE (arg1) == VECTOR_CST
1391       && TREE_CODE (arg2) == VECTOR_CST)
1392     {
1393       tree type = TREE_TYPE (arg1);
1394       int count = TYPE_VECTOR_SUBPARTS (type), i;
1395       tree *elts = XALLOCAVEC (tree, count);
1396
1397       for (i = 0; i < count; i++)
1398         {
1399           tree elem1 = VECTOR_CST_ELT (arg1, i);
1400           tree elem2 = VECTOR_CST_ELT (arg2, i);
1401
1402           elts[i] = const_binop (code, elem1, elem2);
1403
1404           /* It is possible that const_binop cannot handle the given
1405              code and return NULL_TREE */
1406           if (elts[i] == NULL_TREE)
1407             return NULL_TREE;
1408         }
1409
1410       return build_vector (type, elts);
1411     }
1412
1413   /* Shifts allow a scalar offset for a vector.  */
1414   if (TREE_CODE (arg1) == VECTOR_CST
1415       && TREE_CODE (arg2) == INTEGER_CST)
1416     {
1417       tree type = TREE_TYPE (arg1);
1418       int count = TYPE_VECTOR_SUBPARTS (type), i;
1419       tree *elts = XALLOCAVEC (tree, count);
1420
1421       if (code == VEC_RSHIFT_EXPR)
1422         {
1423           if (!tree_fits_uhwi_p (arg2))
1424             return NULL_TREE;
1425
1426           unsigned HOST_WIDE_INT shiftc = tree_to_uhwi (arg2);
1427           unsigned HOST_WIDE_INT outerc = tree_to_uhwi (TYPE_SIZE (type));
1428           unsigned HOST_WIDE_INT innerc
1429             = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (type)));
1430           if (shiftc >= outerc || (shiftc % innerc) != 0)
1431             return NULL_TREE;
1432           int offset = shiftc / innerc;
1433           /* The direction of VEC_RSHIFT_EXPR is endian dependent.
1434              For reductions, if !BYTES_BIG_ENDIAN then compiler picks first
1435              vector element, but last element if BYTES_BIG_ENDIAN.  */
1436           if (BYTES_BIG_ENDIAN)
1437             offset = -offset;
1438           tree zero = build_zero_cst (TREE_TYPE (type));
1439           for (i = 0; i < count; i++)
1440             {
1441               if (i + offset < 0 || i + offset >= count)
1442                 elts[i] = zero;
1443               else
1444                 elts[i] = VECTOR_CST_ELT (arg1, i + offset);
1445             }
1446         }
1447       else
1448         for (i = 0; i < count; i++)
1449           {
1450             tree elem1 = VECTOR_CST_ELT (arg1, i);
1451
1452             elts[i] = const_binop (code, elem1, arg2);
1453
1454             /* It is possible that const_binop cannot handle the given
1455                code and return NULL_TREE */
1456             if (elts[i] == NULL_TREE)
1457               return NULL_TREE;
1458           }
1459
1460       return build_vector (type, elts);
1461     }
1462   return NULL_TREE;
1463 }
1464
1465 /* Create a sizetype INT_CST node with NUMBER sign extended.  KIND
1466    indicates which particular sizetype to create.  */
1467
1468 tree
1469 size_int_kind (HOST_WIDE_INT number, enum size_type_kind kind)
1470 {
1471   return build_int_cst (sizetype_tab[(int) kind], number);
1472 }
1473 \f
1474 /* Combine operands OP1 and OP2 with arithmetic operation CODE.  CODE
1475    is a tree code.  The type of the result is taken from the operands.
1476    Both must be equivalent integer types, ala int_binop_types_match_p.
1477    If the operands are constant, so is the result.  */
1478
1479 tree
1480 size_binop_loc (location_t loc, enum tree_code code, tree arg0, tree arg1)
1481 {
1482   tree type = TREE_TYPE (arg0);
1483
1484   if (arg0 == error_mark_node || arg1 == error_mark_node)
1485     return error_mark_node;
1486
1487   gcc_assert (int_binop_types_match_p (code, TREE_TYPE (arg0),
1488                                        TREE_TYPE (arg1)));
1489
1490   /* Handle the special case of two integer constants faster.  */
1491   if (TREE_CODE (arg0) == INTEGER_CST && TREE_CODE (arg1) == INTEGER_CST)
1492     {
1493       /* And some specific cases even faster than that.  */
1494       if (code == PLUS_EXPR)
1495         {
1496           if (integer_zerop (arg0) && !TREE_OVERFLOW (arg0))
1497             return arg1;
1498           if (integer_zerop (arg1) && !TREE_OVERFLOW (arg1))
1499             return arg0;
1500         }
1501       else if (code == MINUS_EXPR)
1502         {
1503           if (integer_zerop (arg1) && !TREE_OVERFLOW (arg1))
1504             return arg0;
1505         }
1506       else if (code == MULT_EXPR)
1507         {
1508           if (integer_onep (arg0) && !TREE_OVERFLOW (arg0))
1509             return arg1;
1510         }
1511
1512       /* Handle general case of two integer constants.  For sizetype
1513          constant calculations we always want to know about overflow,
1514          even in the unsigned case.  */
1515       return int_const_binop_1 (code, arg0, arg1, -1);
1516     }
1517
1518   return fold_build2_loc (loc, code, type, arg0, arg1);
1519 }
1520
1521 /* Given two values, either both of sizetype or both of bitsizetype,
1522    compute the difference between the two values.  Return the value
1523    in signed type corresponding to the type of the operands.  */
1524
1525 tree
1526 size_diffop_loc (location_t loc, tree arg0, tree arg1)
1527 {
1528   tree type = TREE_TYPE (arg0);
1529   tree ctype;
1530
1531   gcc_assert (int_binop_types_match_p (MINUS_EXPR, TREE_TYPE (arg0),
1532                                        TREE_TYPE (arg1)));
1533
1534   /* If the type is already signed, just do the simple thing.  */
1535   if (!TYPE_UNSIGNED (type))
1536     return size_binop_loc (loc, MINUS_EXPR, arg0, arg1);
1537
1538   if (type == sizetype)
1539     ctype = ssizetype;
1540   else if (type == bitsizetype)
1541     ctype = sbitsizetype;
1542   else
1543     ctype = signed_type_for (type);
1544
1545   /* If either operand is not a constant, do the conversions to the signed
1546      type and subtract.  The hardware will do the right thing with any
1547      overflow in the subtraction.  */
1548   if (TREE_CODE (arg0) != INTEGER_CST || TREE_CODE (arg1) != INTEGER_CST)
1549     return size_binop_loc (loc, MINUS_EXPR,
1550                            fold_convert_loc (loc, ctype, arg0),
1551                            fold_convert_loc (loc, ctype, arg1));
1552
1553   /* If ARG0 is larger than ARG1, subtract and return the result in CTYPE.
1554      Otherwise, subtract the other way, convert to CTYPE (we know that can't
1555      overflow) and negate (which can't either).  Special-case a result
1556      of zero while we're here.  */
1557   if (tree_int_cst_equal (arg0, arg1))
1558     return build_int_cst (ctype, 0);
1559   else if (tree_int_cst_lt (arg1, arg0))
1560     return fold_convert_loc (loc, ctype,
1561                              size_binop_loc (loc, MINUS_EXPR, arg0, arg1));
1562   else
1563     return size_binop_loc (loc, MINUS_EXPR, build_int_cst (ctype, 0),
1564                            fold_convert_loc (loc, ctype,
1565                                              size_binop_loc (loc,
1566                                                              MINUS_EXPR,
1567                                                              arg1, arg0)));
1568 }
1569 \f
1570 /* A subroutine of fold_convert_const handling conversions of an
1571    INTEGER_CST to another integer type.  */
1572
1573 static tree
1574 fold_convert_const_int_from_int (tree type, const_tree arg1)
1575 {
1576   /* Given an integer constant, make new constant with new type,
1577      appropriately sign-extended or truncated.  Use widest_int
1578      so that any extension is done according ARG1's type.  */
1579   return force_fit_type (type, wi::to_widest (arg1),
1580                          !POINTER_TYPE_P (TREE_TYPE (arg1)),
1581                          TREE_OVERFLOW (arg1));
1582 }
1583
1584 /* A subroutine of fold_convert_const handling conversions a REAL_CST
1585    to an integer type.  */
1586
1587 static tree
1588 fold_convert_const_int_from_real (enum tree_code code, tree type, const_tree arg1)
1589 {
1590   bool overflow = false;
1591   tree t;
1592
1593   /* The following code implements the floating point to integer
1594      conversion rules required by the Java Language Specification,
1595      that IEEE NaNs are mapped to zero and values that overflow
1596      the target precision saturate, i.e. values greater than
1597      INT_MAX are mapped to INT_MAX, and values less than INT_MIN
1598      are mapped to INT_MIN.  These semantics are allowed by the
1599      C and C++ standards that simply state that the behavior of
1600      FP-to-integer conversion is unspecified upon overflow.  */
1601
1602   wide_int val;
1603   REAL_VALUE_TYPE r;
1604   REAL_VALUE_TYPE x = TREE_REAL_CST (arg1);
1605
1606   switch (code)
1607     {
1608     case FIX_TRUNC_EXPR:
1609       real_trunc (&r, VOIDmode, &x);
1610       break;
1611
1612     default:
1613       gcc_unreachable ();
1614     }
1615
1616   /* If R is NaN, return zero and show we have an overflow.  */
1617   if (REAL_VALUE_ISNAN (r))
1618     {
1619       overflow = true;
1620       val = wi::zero (TYPE_PRECISION (type));
1621     }
1622
1623   /* See if R is less than the lower bound or greater than the
1624      upper bound.  */
1625
1626   if (! overflow)
1627     {
1628       tree lt = TYPE_MIN_VALUE (type);
1629       REAL_VALUE_TYPE l = real_value_from_int_cst (NULL_TREE, lt);
1630       if (REAL_VALUES_LESS (r, l))
1631         {
1632           overflow = true;
1633           val = lt;
1634         }
1635     }
1636
1637   if (! overflow)
1638     {
1639       tree ut = TYPE_MAX_VALUE (type);
1640       if (ut)
1641         {
1642           REAL_VALUE_TYPE u = real_value_from_int_cst (NULL_TREE, ut);
1643           if (REAL_VALUES_LESS (u, r))
1644             {
1645               overflow = true;
1646               val = ut;
1647             }
1648         }
1649     }
1650
1651   if (! overflow)
1652     val = real_to_integer (&r, &overflow, TYPE_PRECISION (type));
1653
1654   t = force_fit_type (type, val, -1, overflow | TREE_OVERFLOW (arg1));
1655   return t;
1656 }
1657
1658 /* A subroutine of fold_convert_const handling conversions of a
1659    FIXED_CST to an integer type.  */
1660
1661 static tree
1662 fold_convert_const_int_from_fixed (tree type, const_tree arg1)
1663 {
1664   tree t;
1665   double_int temp, temp_trunc;
1666   unsigned int mode;
1667
1668   /* Right shift FIXED_CST to temp by fbit.  */
1669   temp = TREE_FIXED_CST (arg1).data;
1670   mode = TREE_FIXED_CST (arg1).mode;
1671   if (GET_MODE_FBIT (mode) < HOST_BITS_PER_DOUBLE_INT)
1672     {
1673       temp = temp.rshift (GET_MODE_FBIT (mode),
1674                           HOST_BITS_PER_DOUBLE_INT,
1675                           SIGNED_FIXED_POINT_MODE_P (mode));
1676
1677       /* Left shift temp to temp_trunc by fbit.  */
1678       temp_trunc = temp.lshift (GET_MODE_FBIT (mode),
1679                                 HOST_BITS_PER_DOUBLE_INT,
1680                                 SIGNED_FIXED_POINT_MODE_P (mode));
1681     }
1682   else
1683     {
1684       temp = double_int_zero;
1685       temp_trunc = double_int_zero;
1686     }
1687
1688   /* If FIXED_CST is negative, we need to round the value toward 0.
1689      By checking if the fractional bits are not zero to add 1 to temp.  */
1690   if (SIGNED_FIXED_POINT_MODE_P (mode)
1691       && temp_trunc.is_negative ()
1692       && TREE_FIXED_CST (arg1).data != temp_trunc)
1693     temp += double_int_one;
1694
1695   /* Given a fixed-point constant, make new constant with new type,
1696      appropriately sign-extended or truncated.  */
1697   t = force_fit_type (type, temp, -1,
1698                       (temp.is_negative ()
1699                        && (TYPE_UNSIGNED (type)
1700                            < TYPE_UNSIGNED (TREE_TYPE (arg1))))
1701                       | TREE_OVERFLOW (arg1));
1702
1703   return t;
1704 }
1705
1706 /* A subroutine of fold_convert_const handling conversions a REAL_CST
1707    to another floating point type.  */
1708
1709 static tree
1710 fold_convert_const_real_from_real (tree type, const_tree arg1)
1711 {
1712   REAL_VALUE_TYPE value;
1713   tree t;
1714
1715   real_convert (&value, TYPE_MODE (type), &TREE_REAL_CST (arg1));
1716   t = build_real (type, value);
1717
1718   /* If converting an infinity or NAN to a representation that doesn't
1719      have one, set the overflow bit so that we can produce some kind of
1720      error message at the appropriate point if necessary.  It's not the
1721      most user-friendly message, but it's better than nothing.  */
1722   if (REAL_VALUE_ISINF (TREE_REAL_CST (arg1))
1723       && !MODE_HAS_INFINITIES (TYPE_MODE (type)))
1724     TREE_OVERFLOW (t) = 1;
1725   else if (REAL_VALUE_ISNAN (TREE_REAL_CST (arg1))
1726            && !MODE_HAS_NANS (TYPE_MODE (type)))
1727     TREE_OVERFLOW (t) = 1;
1728   /* Regular overflow, conversion produced an infinity in a mode that
1729      can't represent them.  */
1730   else if (!MODE_HAS_INFINITIES (TYPE_MODE (type))
1731            && REAL_VALUE_ISINF (value)
1732            && !REAL_VALUE_ISINF (TREE_REAL_CST (arg1)))
1733     TREE_OVERFLOW (t) = 1;
1734   else
1735     TREE_OVERFLOW (t) = TREE_OVERFLOW (arg1);
1736   return t;
1737 }
1738
1739 /* A subroutine of fold_convert_const handling conversions a FIXED_CST
1740    to a floating point type.  */
1741
1742 static tree
1743 fold_convert_const_real_from_fixed (tree type, const_tree arg1)
1744 {
1745   REAL_VALUE_TYPE value;
1746   tree t;
1747
1748   real_convert_from_fixed (&value, TYPE_MODE (type), &TREE_FIXED_CST (arg1));
1749   t = build_real (type, value);
1750
1751   TREE_OVERFLOW (t) = TREE_OVERFLOW (arg1);
1752   return t;
1753 }
1754
1755 /* A subroutine of fold_convert_const handling conversions a FIXED_CST
1756    to another fixed-point type.  */
1757
1758 static tree
1759 fold_convert_const_fixed_from_fixed (tree type, const_tree arg1)
1760 {
1761   FIXED_VALUE_TYPE value;
1762   tree t;
1763   bool overflow_p;
1764
1765   overflow_p = fixed_convert (&value, TYPE_MODE (type), &TREE_FIXED_CST (arg1),
1766                               TYPE_SATURATING (type));
1767   t = build_fixed (type, value);
1768
1769   /* Propagate overflow flags.  */
1770   if (overflow_p | TREE_OVERFLOW (arg1))
1771     TREE_OVERFLOW (t) = 1;
1772   return t;
1773 }
1774
1775 /* A subroutine of fold_convert_const handling conversions an INTEGER_CST
1776    to a fixed-point type.  */
1777
1778 static tree
1779 fold_convert_const_fixed_from_int (tree type, const_tree arg1)
1780 {
1781   FIXED_VALUE_TYPE value;
1782   tree t;
1783   bool overflow_p;
1784   double_int di;
1785
1786   gcc_assert (TREE_INT_CST_NUNITS (arg1) <= 2);
1787
1788   di.low = TREE_INT_CST_ELT (arg1, 0);
1789   if (TREE_INT_CST_NUNITS (arg1) == 1)
1790     di.high = (HOST_WIDE_INT) di.low < 0 ? (HOST_WIDE_INT) -1 : 0;
1791   else
1792     di.high = TREE_INT_CST_ELT (arg1, 1);
1793
1794   overflow_p = fixed_convert_from_int (&value, TYPE_MODE (type), di,
1795                                        TYPE_UNSIGNED (TREE_TYPE (arg1)),
1796                                        TYPE_SATURATING (type));
1797   t = build_fixed (type, value);
1798
1799   /* Propagate overflow flags.  */
1800   if (overflow_p | TREE_OVERFLOW (arg1))
1801     TREE_OVERFLOW (t) = 1;
1802   return t;
1803 }
1804
1805 /* A subroutine of fold_convert_const handling conversions a REAL_CST
1806    to a fixed-point type.  */
1807
1808 static tree
1809 fold_convert_const_fixed_from_real (tree type, const_tree arg1)
1810 {
1811   FIXED_VALUE_TYPE value;
1812   tree t;
1813   bool overflow_p;
1814
1815   overflow_p = fixed_convert_from_real (&value, TYPE_MODE (type),
1816                                         &TREE_REAL_CST (arg1),
1817                                         TYPE_SATURATING (type));
1818   t = build_fixed (type, value);
1819
1820   /* Propagate overflow flags.  */
1821   if (overflow_p | TREE_OVERFLOW (arg1))
1822     TREE_OVERFLOW (t) = 1;
1823   return t;
1824 }
1825
1826 /* Attempt to fold type conversion operation CODE of expression ARG1 to
1827    type TYPE.  If no simplification can be done return NULL_TREE.  */
1828
1829 static tree
1830 fold_convert_const (enum tree_code code, tree type, tree arg1)
1831 {
1832   if (TREE_TYPE (arg1) == type)
1833     return arg1;
1834
1835   if (POINTER_TYPE_P (type) || INTEGRAL_TYPE_P (type)
1836       || TREE_CODE (type) == OFFSET_TYPE)
1837     {
1838       if (TREE_CODE (arg1) == INTEGER_CST)
1839         return fold_convert_const_int_from_int (type, arg1);
1840       else if (TREE_CODE (arg1) == REAL_CST)
1841         return fold_convert_const_int_from_real (code, type, arg1);
1842       else if (TREE_CODE (arg1) == FIXED_CST)
1843         return fold_convert_const_int_from_fixed (type, arg1);
1844     }
1845   else if (TREE_CODE (type) == REAL_TYPE)
1846     {
1847       if (TREE_CODE (arg1) == INTEGER_CST)
1848         return build_real_from_int_cst (type, arg1);
1849       else if (TREE_CODE (arg1) == REAL_CST)
1850         return fold_convert_const_real_from_real (type, arg1);
1851       else if (TREE_CODE (arg1) == FIXED_CST)
1852         return fold_convert_const_real_from_fixed (type, arg1);
1853     }
1854   else if (TREE_CODE (type) == FIXED_POINT_TYPE)
1855     {
1856       if (TREE_CODE (arg1) == FIXED_CST)
1857         return fold_convert_const_fixed_from_fixed (type, arg1);
1858       else if (TREE_CODE (arg1) == INTEGER_CST)
1859         return fold_convert_const_fixed_from_int (type, arg1);
1860       else if (TREE_CODE (arg1) == REAL_CST)
1861         return fold_convert_const_fixed_from_real (type, arg1);
1862     }
1863   return NULL_TREE;
1864 }
1865
1866 /* Construct a vector of zero elements of vector type TYPE.  */
1867
1868 static tree
1869 build_zero_vector (tree type)
1870 {
1871   tree t;
1872
1873   t = fold_convert_const (NOP_EXPR, TREE_TYPE (type), integer_zero_node);
1874   return build_vector_from_val (type, t);
1875 }
1876
1877 /* Returns true, if ARG is convertible to TYPE using a NOP_EXPR.  */
1878
1879 bool
1880 fold_convertible_p (const_tree type, const_tree arg)
1881 {
1882   tree orig = TREE_TYPE (arg);
1883
1884   if (type == orig)
1885     return true;
1886
1887   if (TREE_CODE (arg) == ERROR_MARK
1888       || TREE_CODE (type) == ERROR_MARK
1889       || TREE_CODE (orig) == ERROR_MARK)
1890     return false;
1891
1892   if (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (orig))
1893     return true;
1894
1895   switch (TREE_CODE (type))
1896     {
1897     case INTEGER_TYPE: case ENUMERAL_TYPE: case BOOLEAN_TYPE:
1898     case POINTER_TYPE: case REFERENCE_TYPE:
1899     case OFFSET_TYPE:
1900       if (INTEGRAL_TYPE_P (orig) || POINTER_TYPE_P (orig)
1901           || TREE_CODE (orig) == OFFSET_TYPE)
1902         return true;
1903       return (TREE_CODE (orig) == VECTOR_TYPE
1904               && tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (orig)));
1905
1906     case REAL_TYPE:
1907     case FIXED_POINT_TYPE:
1908     case COMPLEX_TYPE:
1909     case VECTOR_TYPE:
1910     case VOID_TYPE:
1911       return TREE_CODE (type) == TREE_CODE (orig);
1912
1913     default:
1914       return false;
1915     }
1916 }
1917
1918 /* Convert expression ARG to type TYPE.  Used by the middle-end for
1919    simple conversions in preference to calling the front-end's convert.  */
1920
1921 tree
1922 fold_convert_loc (location_t loc, tree type, tree arg)
1923 {
1924   tree orig = TREE_TYPE (arg);
1925   tree tem;
1926
1927   if (type == orig)
1928     return arg;
1929
1930   if (TREE_CODE (arg) == ERROR_MARK
1931       || TREE_CODE (type) == ERROR_MARK
1932       || TREE_CODE (orig) == ERROR_MARK)
1933     return error_mark_node;
1934
1935   switch (TREE_CODE (type))
1936     {
1937     case POINTER_TYPE:
1938     case REFERENCE_TYPE:
1939       /* Handle conversions between pointers to different address spaces.  */
1940       if (POINTER_TYPE_P (orig)
1941           && (TYPE_ADDR_SPACE (TREE_TYPE (type))
1942               != TYPE_ADDR_SPACE (TREE_TYPE (orig))))
1943         return fold_build1_loc (loc, ADDR_SPACE_CONVERT_EXPR, type, arg);
1944       /* fall through */
1945
1946     case INTEGER_TYPE: case ENUMERAL_TYPE: case BOOLEAN_TYPE:
1947     case OFFSET_TYPE:
1948       if (TREE_CODE (arg) == INTEGER_CST)
1949         {
1950           tem = fold_convert_const (NOP_EXPR, type, arg);
1951           if (tem != NULL_TREE)
1952             return tem;
1953         }
1954       if (INTEGRAL_TYPE_P (orig) || POINTER_TYPE_P (orig)
1955           || TREE_CODE (orig) == OFFSET_TYPE)
1956         return fold_build1_loc (loc, NOP_EXPR, type, arg);
1957       if (TREE_CODE (orig) == COMPLEX_TYPE)
1958         return fold_convert_loc (loc, type,
1959                              fold_build1_loc (loc, REALPART_EXPR,
1960                                           TREE_TYPE (orig), arg));
1961       gcc_assert (TREE_CODE (orig) == VECTOR_TYPE
1962                   && tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (orig)));
1963       return fold_build1_loc (loc, NOP_EXPR, type, arg);
1964
1965     case REAL_TYPE:
1966       if (TREE_CODE (arg) == INTEGER_CST)
1967         {
1968           tem = fold_convert_const (FLOAT_EXPR, type, arg);
1969           if (tem != NULL_TREE)
1970             return tem;
1971         }
1972       else if (TREE_CODE (arg) == REAL_CST)
1973         {
1974           tem = fold_convert_const (NOP_EXPR, type, arg);
1975           if (tem != NULL_TREE)
1976             return tem;
1977         }
1978       else if (TREE_CODE (arg) == FIXED_CST)
1979         {
1980           tem = fold_convert_const (FIXED_CONVERT_EXPR, type, arg);
1981           if (tem != NULL_TREE)
1982             return tem;
1983         }
1984
1985       switch (TREE_CODE (orig))
1986         {
1987         case INTEGER_TYPE:
1988         case BOOLEAN_TYPE: case ENUMERAL_TYPE:
1989         case POINTER_TYPE: case REFERENCE_TYPE:
1990           return fold_build1_loc (loc, FLOAT_EXPR, type, arg);
1991
1992         case REAL_TYPE:
1993           return fold_build1_loc (loc, NOP_EXPR, type, arg);
1994
1995         case FIXED_POINT_TYPE:
1996           return fold_build1_loc (loc, FIXED_CONVERT_EXPR, type, arg);
1997
1998         case COMPLEX_TYPE:
1999           tem = fold_build1_loc (loc, REALPART_EXPR, TREE_TYPE (orig), arg);
2000           return fold_convert_loc (loc, type, tem);
2001
2002         default:
2003           gcc_unreachable ();
2004         }
2005
2006     case FIXED_POINT_TYPE:
2007       if (TREE_CODE (arg) == FIXED_CST || TREE_CODE (arg) == INTEGER_CST
2008           || TREE_CODE (arg) == REAL_CST)
2009         {
2010           tem = fold_convert_const (FIXED_CONVERT_EXPR, type, arg);
2011           if (tem != NULL_TREE)
2012             goto fold_convert_exit;
2013         }
2014
2015       switch (TREE_CODE (orig))
2016         {
2017         case FIXED_POINT_TYPE:
2018         case INTEGER_TYPE:
2019         case ENUMERAL_TYPE:
2020         case BOOLEAN_TYPE:
2021         case REAL_TYPE:
2022           return fold_build1_loc (loc, FIXED_CONVERT_EXPR, type, arg);
2023
2024         case COMPLEX_TYPE:
2025           tem = fold_build1_loc (loc, REALPART_EXPR, TREE_TYPE (orig), arg);
2026           return fold_convert_loc (loc, type, tem);
2027
2028         default:
2029           gcc_unreachable ();
2030         }
2031
2032     case COMPLEX_TYPE:
2033       switch (TREE_CODE (orig))
2034         {
2035         case INTEGER_TYPE:
2036         case BOOLEAN_TYPE: case ENUMERAL_TYPE:
2037         case POINTER_TYPE: case REFERENCE_TYPE:
2038         case REAL_TYPE:
2039         case FIXED_POINT_TYPE:
2040           return fold_build2_loc (loc, COMPLEX_EXPR, type,
2041                               fold_convert_loc (loc, TREE_TYPE (type), arg),
2042                               fold_convert_loc (loc, TREE_TYPE (type),
2043                                             integer_zero_node));
2044         case COMPLEX_TYPE:
2045           {
2046             tree rpart, ipart;
2047
2048             if (TREE_CODE (arg) == COMPLEX_EXPR)
2049               {
2050                 rpart = fold_convert_loc (loc, TREE_TYPE (type),
2051                                       TREE_OPERAND (arg, 0));
2052                 ipart = fold_convert_loc (loc, TREE_TYPE (type),
2053                                       TREE_OPERAND (arg, 1));
2054                 return fold_build2_loc (loc, COMPLEX_EXPR, type, rpart, ipart);
2055               }
2056
2057             arg = save_expr (arg);
2058             rpart = fold_build1_loc (loc, REALPART_EXPR, TREE_TYPE (orig), arg);
2059             ipart = fold_build1_loc (loc, IMAGPART_EXPR, TREE_TYPE (orig), arg);
2060             rpart = fold_convert_loc (loc, TREE_TYPE (type), rpart);
2061             ipart = fold_convert_loc (loc, TREE_TYPE (type), ipart);
2062             return fold_build2_loc (loc, COMPLEX_EXPR, type, rpart, ipart);
2063           }
2064
2065         default:
2066           gcc_unreachable ();
2067         }
2068
2069     case VECTOR_TYPE:
2070       if (integer_zerop (arg))
2071         return build_zero_vector (type);
2072       gcc_assert (tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (orig)));
2073       gcc_assert (INTEGRAL_TYPE_P (orig) || POINTER_TYPE_P (orig)
2074                   || TREE_CODE (orig) == VECTOR_TYPE);
2075       return fold_build1_loc (loc, VIEW_CONVERT_EXPR, type, arg);
2076
2077     case VOID_TYPE:
2078       tem = fold_ignored_result (arg);
2079       return fold_build1_loc (loc, NOP_EXPR, type, tem);
2080
2081     default:
2082       if (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (orig))
2083         return fold_build1_loc (loc, NOP_EXPR, type, arg);
2084       gcc_unreachable ();
2085     }
2086  fold_convert_exit:
2087   protected_set_expr_location_unshare (tem, loc);
2088   return tem;
2089 }
2090 \f
2091 /* Return false if expr can be assumed not to be an lvalue, true
2092    otherwise.  */
2093
2094 static bool
2095 maybe_lvalue_p (const_tree x)
2096 {
2097   /* We only need to wrap lvalue tree codes.  */
2098   switch (TREE_CODE (x))
2099   {
2100   case VAR_DECL:
2101   case PARM_DECL:
2102   case RESULT_DECL:
2103   case LABEL_DECL:
2104   case FUNCTION_DECL:
2105   case SSA_NAME:
2106
2107   case COMPONENT_REF:
2108   case MEM_REF:
2109   case INDIRECT_REF:
2110   case ARRAY_REF:
2111   case ARRAY_RANGE_REF:
2112   case BIT_FIELD_REF:
2113   case OBJ_TYPE_REF:
2114
2115   case REALPART_EXPR:
2116   case IMAGPART_EXPR:
2117   case PREINCREMENT_EXPR:
2118   case PREDECREMENT_EXPR:
2119   case SAVE_EXPR:
2120   case TRY_CATCH_EXPR:
2121   case WITH_CLEANUP_EXPR:
2122   case COMPOUND_EXPR:
2123   case MODIFY_EXPR:
2124   case TARGET_EXPR:
2125   case COND_EXPR:
2126   case BIND_EXPR:
2127     break;
2128
2129   default:
2130     /* Assume the worst for front-end tree codes.  */
2131     if ((int)TREE_CODE (x) >= NUM_TREE_CODES)
2132       break;
2133     return false;
2134   }
2135
2136   return true;
2137 }
2138
2139 /* Return an expr equal to X but certainly not valid as an lvalue.  */
2140
2141 tree
2142 non_lvalue_loc (location_t loc, tree x)
2143 {
2144   /* While we are in GIMPLE, NON_LVALUE_EXPR doesn't mean anything to
2145      us.  */
2146   if (in_gimple_form)
2147     return x;
2148
2149   if (! maybe_lvalue_p (x))
2150     return x;
2151   return build1_loc (loc, NON_LVALUE_EXPR, TREE_TYPE (x), x);
2152 }
2153
2154 /* When pedantic, return an expr equal to X but certainly not valid as a
2155    pedantic lvalue.  Otherwise, return X.  */
2156
2157 static tree
2158 pedantic_non_lvalue_loc (location_t loc, tree x)
2159 {
2160   return protected_set_expr_location_unshare (x, loc);
2161 }
2162 \f
2163 /* Given a tree comparison code, return the code that is the logical inverse.
2164    It is generally not safe to do this for floating-point comparisons, except
2165    for EQ_EXPR, NE_EXPR, ORDERED_EXPR and UNORDERED_EXPR, so we return
2166    ERROR_MARK in this case.  */
2167
2168 enum tree_code
2169 invert_tree_comparison (enum tree_code code, bool honor_nans)
2170 {
2171   if (honor_nans && flag_trapping_math && code != EQ_EXPR && code != NE_EXPR
2172       && code != ORDERED_EXPR && code != UNORDERED_EXPR)
2173     return ERROR_MARK;
2174
2175   switch (code)
2176     {
2177     case EQ_EXPR:
2178       return NE_EXPR;
2179     case NE_EXPR:
2180       return EQ_EXPR;
2181     case GT_EXPR:
2182       return honor_nans ? UNLE_EXPR : LE_EXPR;
2183     case GE_EXPR:
2184       return honor_nans ? UNLT_EXPR : LT_EXPR;
2185     case LT_EXPR:
2186       return honor_nans ? UNGE_EXPR : GE_EXPR;
2187     case LE_EXPR:
2188       return honor_nans ? UNGT_EXPR : GT_EXPR;
2189     case LTGT_EXPR:
2190       return UNEQ_EXPR;
2191     case UNEQ_EXPR:
2192       return LTGT_EXPR;
2193     case UNGT_EXPR:
2194       return LE_EXPR;
2195     case UNGE_EXPR:
2196       return LT_EXPR;
2197     case UNLT_EXPR:
2198       return GE_EXPR;
2199     case UNLE_EXPR:
2200       return GT_EXPR;
2201     case ORDERED_EXPR:
2202       return UNORDERED_EXPR;
2203     case UNORDERED_EXPR:
2204       return ORDERED_EXPR;
2205     default:
2206       gcc_unreachable ();
2207     }
2208 }
2209
2210 /* Similar, but return the comparison that results if the operands are
2211    swapped.  This is safe for floating-point.  */
2212
2213 enum tree_code
2214 swap_tree_comparison (enum tree_code code)
2215 {
2216   switch (code)
2217     {
2218     case EQ_EXPR:
2219     case NE_EXPR:
2220     case ORDERED_EXPR:
2221     case UNORDERED_EXPR:
2222     case LTGT_EXPR:
2223     case UNEQ_EXPR:
2224       return code;
2225     case GT_EXPR:
2226       return LT_EXPR;
2227     case GE_EXPR:
2228       return LE_EXPR;
2229     case LT_EXPR:
2230       return GT_EXPR;
2231     case LE_EXPR:
2232       return GE_EXPR;
2233     case UNGT_EXPR:
2234       return UNLT_EXPR;
2235     case UNGE_EXPR:
2236       return UNLE_EXPR;
2237     case UNLT_EXPR:
2238       return UNGT_EXPR;
2239     case UNLE_EXPR:
2240       return UNGE_EXPR;
2241     default:
2242       gcc_unreachable ();
2243     }
2244 }
2245
2246
2247 /* Convert a comparison tree code from an enum tree_code representation
2248    into a compcode bit-based encoding.  This function is the inverse of
2249    compcode_to_comparison.  */
2250
2251 static enum comparison_code
2252 comparison_to_compcode (enum tree_code code)
2253 {
2254   switch (code)
2255     {
2256     case LT_EXPR:
2257       return COMPCODE_LT;
2258     case EQ_EXPR:
2259       return COMPCODE_EQ;
2260     case LE_EXPR:
2261       return COMPCODE_LE;
2262     case GT_EXPR:
2263       return COMPCODE_GT;
2264     case NE_EXPR:
2265       return COMPCODE_NE;
2266     case GE_EXPR:
2267       return COMPCODE_GE;
2268     case ORDERED_EXPR:
2269       return COMPCODE_ORD;
2270     case UNORDERED_EXPR:
2271       return COMPCODE_UNORD;
2272     case UNLT_EXPR:
2273       return COMPCODE_UNLT;
2274     case UNEQ_EXPR:
2275       return COMPCODE_UNEQ;
2276     case UNLE_EXPR:
2277       return COMPCODE_UNLE;
2278     case UNGT_EXPR:
2279       return COMPCODE_UNGT;
2280     case LTGT_EXPR:
2281       return COMPCODE_LTGT;
2282     case UNGE_EXPR:
2283       return COMPCODE_UNGE;
2284     default:
2285       gcc_unreachable ();
2286     }
2287 }
2288
2289 /* Convert a compcode bit-based encoding of a comparison operator back
2290    to GCC's enum tree_code representation.  This function is the
2291    inverse of comparison_to_compcode.  */
2292
2293 static enum tree_code
2294 compcode_to_comparison (enum comparison_code code)
2295 {
2296   switch (code)
2297     {
2298     case COMPCODE_LT:
2299       return LT_EXPR;
2300     case COMPCODE_EQ:
2301       return EQ_EXPR;
2302     case COMPCODE_LE:
2303       return LE_EXPR;
2304     case COMPCODE_GT:
2305       return GT_EXPR;
2306     case COMPCODE_NE:
2307       return NE_EXPR;
2308     case COMPCODE_GE:
2309       return GE_EXPR;
2310     case COMPCODE_ORD:
2311       return ORDERED_EXPR;
2312     case COMPCODE_UNORD:
2313       return UNORDERED_EXPR;
2314     case COMPCODE_UNLT:
2315       return UNLT_EXPR;
2316     case COMPCODE_UNEQ:
2317       return UNEQ_EXPR;
2318     case COMPCODE_UNLE:
2319       return UNLE_EXPR;
2320     case COMPCODE_UNGT:
2321       return UNGT_EXPR;
2322     case COMPCODE_LTGT:
2323       return LTGT_EXPR;
2324     case COMPCODE_UNGE:
2325       return UNGE_EXPR;
2326     default:
2327       gcc_unreachable ();
2328     }
2329 }
2330
2331 /* Return a tree for the comparison which is the combination of
2332    doing the AND or OR (depending on CODE) of the two operations LCODE
2333    and RCODE on the identical operands LL_ARG and LR_ARG.  Take into account
2334    the possibility of trapping if the mode has NaNs, and return NULL_TREE
2335    if this makes the transformation invalid.  */
2336
2337 tree
2338 combine_comparisons (location_t loc,
2339                      enum tree_code code, enum tree_code lcode,
2340                      enum tree_code rcode, tree truth_type,
2341                      tree ll_arg, tree lr_arg)
2342 {
2343   bool honor_nans = HONOR_NANS (TYPE_MODE (TREE_TYPE (ll_arg)));
2344   enum comparison_code lcompcode = comparison_to_compcode (lcode);
2345   enum comparison_code rcompcode = comparison_to_compcode (rcode);
2346   int compcode;
2347
2348   switch (code)
2349     {
2350     case TRUTH_AND_EXPR: case TRUTH_ANDIF_EXPR:
2351       compcode = lcompcode & rcompcode;
2352       break;
2353
2354     case TRUTH_OR_EXPR: case TRUTH_ORIF_EXPR:
2355       compcode = lcompcode | rcompcode;
2356       break;
2357
2358     default:
2359       return NULL_TREE;
2360     }
2361
2362   if (!honor_nans)
2363     {
2364       /* Eliminate unordered comparisons, as well as LTGT and ORD
2365          which are not used unless the mode has NaNs.  */
2366       compcode &= ~COMPCODE_UNORD;
2367       if (compcode == COMPCODE_LTGT)
2368         compcode = COMPCODE_NE;
2369       else if (compcode == COMPCODE_ORD)
2370         compcode = COMPCODE_TRUE;
2371     }
2372    else if (flag_trapping_math)
2373      {
2374         /* Check that the original operation and the optimized ones will trap
2375            under the same condition.  */
2376         bool ltrap = (lcompcode & COMPCODE_UNORD) == 0
2377                      && (lcompcode != COMPCODE_EQ)
2378                      && (lcompcode != COMPCODE_ORD);
2379         bool rtrap = (rcompcode & COMPCODE_UNORD) == 0
2380                      && (rcompcode != COMPCODE_EQ)
2381                      && (rcompcode != COMPCODE_ORD);
2382         bool trap = (compcode & COMPCODE_UNORD) == 0
2383                     && (compcode != COMPCODE_EQ)
2384                     && (compcode != COMPCODE_ORD);
2385
2386         /* In a short-circuited boolean expression the LHS might be
2387            such that the RHS, if evaluated, will never trap.  For
2388            example, in ORD (x, y) && (x < y), we evaluate the RHS only
2389            if neither x nor y is NaN.  (This is a mixed blessing: for
2390            example, the expression above will never trap, hence
2391            optimizing it to x < y would be invalid).  */
2392         if ((code == TRUTH_ORIF_EXPR && (lcompcode & COMPCODE_UNORD))
2393             || (code == TRUTH_ANDIF_EXPR && !(lcompcode & COMPCODE_UNORD)))
2394           rtrap = false;
2395
2396         /* If the comparison was short-circuited, and only the RHS
2397            trapped, we may now generate a spurious trap.  */
2398         if (rtrap && !ltrap
2399             && (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR))
2400           return NULL_TREE;
2401
2402         /* If we changed the conditions that cause a trap, we lose.  */
2403         if ((ltrap || rtrap) != trap)
2404           return NULL_TREE;
2405       }
2406
2407   if (compcode == COMPCODE_TRUE)
2408     return constant_boolean_node (true, truth_type);
2409   else if (compcode == COMPCODE_FALSE)
2410     return constant_boolean_node (false, truth_type);
2411   else
2412     {
2413       enum tree_code tcode;
2414
2415       tcode = compcode_to_comparison ((enum comparison_code) compcode);
2416       return fold_build2_loc (loc, tcode, truth_type, ll_arg, lr_arg);
2417     }
2418 }
2419 \f
2420 /* Return nonzero if two operands (typically of the same tree node)
2421    are necessarily equal.  If either argument has side-effects this
2422    function returns zero.  FLAGS modifies behavior as follows:
2423
2424    If OEP_ONLY_CONST is set, only return nonzero for constants.
2425    This function tests whether the operands are indistinguishable;
2426    it does not test whether they are equal using C's == operation.
2427    The distinction is important for IEEE floating point, because
2428    (1) -0.0 and 0.0 are distinguishable, but -0.0==0.0, and
2429    (2) two NaNs may be indistinguishable, but NaN!=NaN.
2430
2431    If OEP_ONLY_CONST is unset, a VAR_DECL is considered equal to itself
2432    even though it may hold multiple values during a function.
2433    This is because a GCC tree node guarantees that nothing else is
2434    executed between the evaluation of its "operands" (which may often
2435    be evaluated in arbitrary order).  Hence if the operands themselves
2436    don't side-effect, the VAR_DECLs, PARM_DECLs etc... must hold the
2437    same value in each operand/subexpression.  Hence leaving OEP_ONLY_CONST
2438    unset means assuming isochronic (or instantaneous) tree equivalence.
2439    Unless comparing arbitrary expression trees, such as from different
2440    statements, this flag can usually be left unset.
2441
2442    If OEP_PURE_SAME is set, then pure functions with identical arguments
2443    are considered the same.  It is used when the caller has other ways
2444    to ensure that global memory is unchanged in between.  */
2445
2446 int
2447 operand_equal_p (const_tree arg0, const_tree arg1, unsigned int flags)
2448 {
2449   /* If either is ERROR_MARK, they aren't equal.  */
2450   if (TREE_CODE (arg0) == ERROR_MARK || TREE_CODE (arg1) == ERROR_MARK
2451       || TREE_TYPE (arg0) == error_mark_node
2452       || TREE_TYPE (arg1) == error_mark_node)
2453     return 0;
2454
2455   /* Similar, if either does not have a type (like a released SSA name), 
2456      they aren't equal.  */
2457   if (!TREE_TYPE (arg0) || !TREE_TYPE (arg1))
2458     return 0;
2459
2460   /* Check equality of integer constants before bailing out due to
2461      precision differences.  */
2462   if (TREE_CODE (arg0) == INTEGER_CST && TREE_CODE (arg1) == INTEGER_CST)
2463     return tree_int_cst_equal (arg0, arg1);
2464
2465   /* If both types don't have the same signedness, then we can't consider
2466      them equal.  We must check this before the STRIP_NOPS calls
2467      because they may change the signedness of the arguments.  As pointers
2468      strictly don't have a signedness, require either two pointers or
2469      two non-pointers as well.  */
2470   if (TYPE_UNSIGNED (TREE_TYPE (arg0)) != TYPE_UNSIGNED (TREE_TYPE (arg1))
2471       || POINTER_TYPE_P (TREE_TYPE (arg0)) != POINTER_TYPE_P (TREE_TYPE (arg1)))
2472     return 0;
2473
2474   /* We cannot consider pointers to different address space equal.  */
2475   if (POINTER_TYPE_P (TREE_TYPE (arg0)) && POINTER_TYPE_P (TREE_TYPE (arg1))
2476       && (TYPE_ADDR_SPACE (TREE_TYPE (TREE_TYPE (arg0)))
2477           != TYPE_ADDR_SPACE (TREE_TYPE (TREE_TYPE (arg1)))))
2478     return 0;
2479
2480   /* If both types don't have the same precision, then it is not safe
2481      to strip NOPs.  */
2482   if (element_precision (TREE_TYPE (arg0))
2483       != element_precision (TREE_TYPE (arg1)))
2484     return 0;
2485
2486   STRIP_NOPS (arg0);
2487   STRIP_NOPS (arg1);
2488
2489   /* In case both args are comparisons but with different comparison
2490      code, try to swap the comparison operands of one arg to produce
2491      a match and compare that variant.  */
2492   if (TREE_CODE (arg0) != TREE_CODE (arg1)
2493       && COMPARISON_CLASS_P (arg0)
2494       && COMPARISON_CLASS_P (arg1))
2495     {
2496       enum tree_code swap_code = swap_tree_comparison (TREE_CODE (arg1));
2497
2498       if (TREE_CODE (arg0) == swap_code)
2499         return operand_equal_p (TREE_OPERAND (arg0, 0),
2500                                 TREE_OPERAND (arg1, 1), flags)
2501                && operand_equal_p (TREE_OPERAND (arg0, 1),
2502                                    TREE_OPERAND (arg1, 0), flags);
2503     }
2504
2505   if (TREE_CODE (arg0) != TREE_CODE (arg1)
2506       /* NOP_EXPR and CONVERT_EXPR are considered equal.  */
2507       && !(CONVERT_EXPR_P (arg0) && CONVERT_EXPR_P (arg1)))
2508     return 0;
2509
2510   /* This is needed for conversions and for COMPONENT_REF.
2511      Might as well play it safe and always test this.  */
2512   if (TREE_CODE (TREE_TYPE (arg0)) == ERROR_MARK
2513       || TREE_CODE (TREE_TYPE (arg1)) == ERROR_MARK
2514       || TYPE_MODE (TREE_TYPE (arg0)) != TYPE_MODE (TREE_TYPE (arg1)))
2515     return 0;
2516
2517   /* If ARG0 and ARG1 are the same SAVE_EXPR, they are necessarily equal.
2518      We don't care about side effects in that case because the SAVE_EXPR
2519      takes care of that for us. In all other cases, two expressions are
2520      equal if they have no side effects.  If we have two identical
2521      expressions with side effects that should be treated the same due
2522      to the only side effects being identical SAVE_EXPR's, that will
2523      be detected in the recursive calls below.
2524      If we are taking an invariant address of two identical objects
2525      they are necessarily equal as well.  */
2526   if (arg0 == arg1 && ! (flags & OEP_ONLY_CONST)
2527       && (TREE_CODE (arg0) == SAVE_EXPR
2528           || (flags & OEP_CONSTANT_ADDRESS_OF)
2529           || (! TREE_SIDE_EFFECTS (arg0) && ! TREE_SIDE_EFFECTS (arg1))))
2530     return 1;
2531
2532   /* Next handle constant cases, those for which we can return 1 even
2533      if ONLY_CONST is set.  */
2534   if (TREE_CONSTANT (arg0) && TREE_CONSTANT (arg1))
2535     switch (TREE_CODE (arg0))
2536       {
2537       case INTEGER_CST:
2538         return tree_int_cst_equal (arg0, arg1);
2539
2540       case FIXED_CST:
2541         return FIXED_VALUES_IDENTICAL (TREE_FIXED_CST (arg0),
2542                                        TREE_FIXED_CST (arg1));
2543
2544       case REAL_CST:
2545         if (REAL_VALUES_IDENTICAL (TREE_REAL_CST (arg0),
2546                                    TREE_REAL_CST (arg1)))
2547           return 1;
2548
2549
2550         if (!HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (arg0))))
2551           {
2552             /* If we do not distinguish between signed and unsigned zero,
2553                consider them equal.  */
2554             if (real_zerop (arg0) && real_zerop (arg1))
2555               return 1;
2556           }
2557         return 0;
2558
2559       case VECTOR_CST:
2560         {
2561           unsigned i;
2562
2563           if (VECTOR_CST_NELTS (arg0) != VECTOR_CST_NELTS (arg1))
2564             return 0;
2565
2566           for (i = 0; i < VECTOR_CST_NELTS (arg0); ++i)
2567             {
2568               if (!operand_equal_p (VECTOR_CST_ELT (arg0, i),
2569                                     VECTOR_CST_ELT (arg1, i), flags))
2570                 return 0;
2571             }
2572           return 1;
2573         }
2574
2575       case COMPLEX_CST:
2576         return (operand_equal_p (TREE_REALPART (arg0), TREE_REALPART (arg1),
2577                                  flags)
2578                 && operand_equal_p (TREE_IMAGPART (arg0), TREE_IMAGPART (arg1),
2579                                     flags));
2580
2581       case STRING_CST:
2582         return (TREE_STRING_LENGTH (arg0) == TREE_STRING_LENGTH (arg1)
2583                 && ! memcmp (TREE_STRING_POINTER (arg0),
2584                               TREE_STRING_POINTER (arg1),
2585                               TREE_STRING_LENGTH (arg0)));
2586
2587       case ADDR_EXPR:
2588         return operand_equal_p (TREE_OPERAND (arg0, 0), TREE_OPERAND (arg1, 0),
2589                                 TREE_CONSTANT (arg0) && TREE_CONSTANT (arg1)
2590                                 ? OEP_CONSTANT_ADDRESS_OF : 0);
2591       default:
2592         break;
2593       }
2594
2595   if (flags & OEP_ONLY_CONST)
2596     return 0;
2597
2598 /* Define macros to test an operand from arg0 and arg1 for equality and a
2599    variant that allows null and views null as being different from any
2600    non-null value.  In the latter case, if either is null, the both
2601    must be; otherwise, do the normal comparison.  */
2602 #define OP_SAME(N) operand_equal_p (TREE_OPERAND (arg0, N),     \
2603                                     TREE_OPERAND (arg1, N), flags)
2604
2605 #define OP_SAME_WITH_NULL(N)                            \
2606   ((!TREE_OPERAND (arg0, N) || !TREE_OPERAND (arg1, N)) \
2607    ? TREE_OPERAND (arg0, N) == TREE_OPERAND (arg1, N) : OP_SAME (N))
2608
2609   switch (TREE_CODE_CLASS (TREE_CODE (arg0)))
2610     {
2611     case tcc_unary:
2612       /* Two conversions are equal only if signedness and modes match.  */
2613       switch (TREE_CODE (arg0))
2614         {
2615         CASE_CONVERT:
2616         case FIX_TRUNC_EXPR:
2617           if (TYPE_UNSIGNED (TREE_TYPE (arg0))
2618               != TYPE_UNSIGNED (TREE_TYPE (arg1)))
2619             return 0;
2620           break;
2621         default:
2622           break;
2623         }
2624
2625       return OP_SAME (0);
2626
2627
2628     case tcc_comparison:
2629     case tcc_binary:
2630       if (OP_SAME (0) && OP_SAME (1))
2631         return 1;
2632
2633       /* For commutative ops, allow the other order.  */
2634       return (commutative_tree_code (TREE_CODE (arg0))
2635               && operand_equal_p (TREE_OPERAND (arg0, 0),
2636                                   TREE_OPERAND (arg1, 1), flags)
2637               && operand_equal_p (TREE_OPERAND (arg0, 1),
2638                                   TREE_OPERAND (arg1, 0), flags));
2639
2640     case tcc_reference:
2641       /* If either of the pointer (or reference) expressions we are
2642          dereferencing contain a side effect, these cannot be equal,
2643          but their addresses can be.  */
2644       if ((flags & OEP_CONSTANT_ADDRESS_OF) == 0
2645           && (TREE_SIDE_EFFECTS (arg0)
2646               || TREE_SIDE_EFFECTS (arg1)))
2647         return 0;
2648
2649       switch (TREE_CODE (arg0))
2650         {
2651         case INDIRECT_REF:
2652           flags &= ~OEP_CONSTANT_ADDRESS_OF;
2653           return OP_SAME (0);
2654
2655         case REALPART_EXPR:
2656         case IMAGPART_EXPR:
2657           return OP_SAME (0);
2658
2659         case TARGET_MEM_REF:
2660           flags &= ~OEP_CONSTANT_ADDRESS_OF;
2661           /* Require equal extra operands and then fall through to MEM_REF
2662              handling of the two common operands.  */
2663           if (!OP_SAME_WITH_NULL (2)
2664               || !OP_SAME_WITH_NULL (3)
2665               || !OP_SAME_WITH_NULL (4))
2666             return 0;
2667           /* Fallthru.  */
2668         case MEM_REF:
2669           flags &= ~OEP_CONSTANT_ADDRESS_OF;
2670           /* Require equal access sizes, and similar pointer types.
2671              We can have incomplete types for array references of
2672              variable-sized arrays from the Fortran frontend
2673              though.  Also verify the types are compatible.  */
2674           return ((TYPE_SIZE (TREE_TYPE (arg0)) == TYPE_SIZE (TREE_TYPE (arg1))
2675                    || (TYPE_SIZE (TREE_TYPE (arg0))
2676                        && TYPE_SIZE (TREE_TYPE (arg1))
2677                        && operand_equal_p (TYPE_SIZE (TREE_TYPE (arg0)),
2678                                            TYPE_SIZE (TREE_TYPE (arg1)), flags)))
2679                   && types_compatible_p (TREE_TYPE (arg0), TREE_TYPE (arg1))
2680                   && alias_ptr_types_compatible_p
2681                        (TREE_TYPE (TREE_OPERAND (arg0, 1)),
2682                         TREE_TYPE (TREE_OPERAND (arg1, 1)))
2683                   && OP_SAME (0) && OP_SAME (1));
2684
2685         case ARRAY_REF:
2686         case ARRAY_RANGE_REF:
2687           /* Operands 2 and 3 may be null.
2688              Compare the array index by value if it is constant first as we
2689              may have different types but same value here.  */
2690           if (!OP_SAME (0))
2691             return 0;
2692           flags &= ~OEP_CONSTANT_ADDRESS_OF;
2693           return ((tree_int_cst_equal (TREE_OPERAND (arg0, 1),
2694                                        TREE_OPERAND (arg1, 1))
2695                    || OP_SAME (1))
2696                   && OP_SAME_WITH_NULL (2)
2697                   && OP_SAME_WITH_NULL (3));
2698
2699         case COMPONENT_REF:
2700           /* Handle operand 2 the same as for ARRAY_REF.  Operand 0
2701              may be NULL when we're called to compare MEM_EXPRs.  */
2702           if (!OP_SAME_WITH_NULL (0)
2703               || !OP_SAME (1))
2704             return 0;
2705           flags &= ~OEP_CONSTANT_ADDRESS_OF;
2706           return OP_SAME_WITH_NULL (2);
2707
2708         case BIT_FIELD_REF:
2709           if (!OP_SAME (0))
2710             return 0;
2711           flags &= ~OEP_CONSTANT_ADDRESS_OF;
2712           return OP_SAME (1) && OP_SAME (2);
2713
2714         default:
2715           return 0;
2716         }
2717
2718     case tcc_expression:
2719       switch (TREE_CODE (arg0))
2720         {
2721         case ADDR_EXPR:
2722         case TRUTH_NOT_EXPR:
2723           return OP_SAME (0);
2724
2725         case TRUTH_ANDIF_EXPR:
2726         case TRUTH_ORIF_EXPR:
2727           return OP_SAME (0) && OP_SAME (1);
2728
2729         case FMA_EXPR:
2730         case WIDEN_MULT_PLUS_EXPR:
2731         case WIDEN_MULT_MINUS_EXPR:
2732           if (!OP_SAME (2))
2733             return 0;
2734           /* The multiplcation operands are commutative.  */
2735           /* FALLTHRU */
2736
2737         case TRUTH_AND_EXPR:
2738         case TRUTH_OR_EXPR:
2739         case TRUTH_XOR_EXPR:
2740           if (OP_SAME (0) && OP_SAME (1))
2741             return 1;
2742
2743           /* Otherwise take into account this is a commutative operation.  */
2744           return (operand_equal_p (TREE_OPERAND (arg0, 0),
2745                                    TREE_OPERAND (arg1, 1), flags)
2746                   && operand_equal_p (TREE_OPERAND (arg0, 1),
2747                                       TREE_OPERAND (arg1, 0), flags));
2748
2749         case COND_EXPR:
2750         case VEC_COND_EXPR:
2751         case DOT_PROD_EXPR:
2752           return OP_SAME (0) && OP_SAME (1) && OP_SAME (2);
2753
2754         default:
2755           return 0;
2756         }
2757
2758     case tcc_vl_exp:
2759       switch (TREE_CODE (arg0))
2760         {
2761         case CALL_EXPR:
2762           /* If the CALL_EXPRs call different functions, then they
2763              clearly can not be equal.  */
2764           if (! operand_equal_p (CALL_EXPR_FN (arg0), CALL_EXPR_FN (arg1),
2765                                  flags))
2766             return 0;
2767
2768           {
2769             unsigned int cef = call_expr_flags (arg0);
2770             if (flags & OEP_PURE_SAME)
2771               cef &= ECF_CONST | ECF_PURE;
2772             else
2773               cef &= ECF_CONST;
2774             if (!cef)
2775               return 0;
2776           }
2777
2778           /* Now see if all the arguments are the same.  */
2779           {
2780             const_call_expr_arg_iterator iter0, iter1;
2781             const_tree a0, a1;
2782             for (a0 = first_const_call_expr_arg (arg0, &iter0),
2783                    a1 = first_const_call_expr_arg (arg1, &iter1);
2784                  a0 && a1;
2785                  a0 = next_const_call_expr_arg (&iter0),
2786                    a1 = next_const_call_expr_arg (&iter1))
2787               if (! operand_equal_p (a0, a1, flags))
2788                 return 0;
2789
2790             /* If we get here and both argument lists are exhausted
2791                then the CALL_EXPRs are equal.  */
2792             return ! (a0 || a1);
2793           }
2794         default:
2795           return 0;
2796         }
2797
2798     case tcc_declaration:
2799       /* Consider __builtin_sqrt equal to sqrt.  */
2800       return (TREE_CODE (arg0) == FUNCTION_DECL
2801               && DECL_BUILT_IN (arg0) && DECL_BUILT_IN (arg1)
2802               && DECL_BUILT_IN_CLASS (arg0) == DECL_BUILT_IN_CLASS (arg1)
2803               && DECL_FUNCTION_CODE (arg0) == DECL_FUNCTION_CODE (arg1));
2804
2805     default:
2806       return 0;
2807     }
2808
2809 #undef OP_SAME
2810 #undef OP_SAME_WITH_NULL
2811 }
2812 \f
2813 /* Similar to operand_equal_p, but see if ARG0 might have been made by
2814    shorten_compare from ARG1 when ARG1 was being compared with OTHER.
2815
2816    When in doubt, return 0.  */
2817
2818 static int
2819 operand_equal_for_comparison_p (tree arg0, tree arg1, tree other)
2820 {
2821   int unsignedp1, unsignedpo;
2822   tree primarg0, primarg1, primother;
2823   unsigned int correct_width;
2824
2825   if (operand_equal_p (arg0, arg1, 0))
2826     return 1;
2827
2828   if (! INTEGRAL_TYPE_P (TREE_TYPE (arg0))
2829       || ! INTEGRAL_TYPE_P (TREE_TYPE (arg1)))
2830     return 0;
2831
2832   /* Discard any conversions that don't change the modes of ARG0 and ARG1
2833      and see if the inner values are the same.  This removes any
2834      signedness comparison, which doesn't matter here.  */
2835   primarg0 = arg0, primarg1 = arg1;
2836   STRIP_NOPS (primarg0);
2837   STRIP_NOPS (primarg1);
2838   if (operand_equal_p (primarg0, primarg1, 0))
2839     return 1;
2840
2841   /* Duplicate what shorten_compare does to ARG1 and see if that gives the
2842      actual comparison operand, ARG0.
2843
2844      First throw away any conversions to wider types
2845      already present in the operands.  */
2846
2847   primarg1 = get_narrower (arg1, &unsignedp1);
2848   primother = get_narrower (other, &unsignedpo);
2849
2850   correct_width = TYPE_PRECISION (TREE_TYPE (arg1));
2851   if (unsignedp1 == unsignedpo
2852       && TYPE_PRECISION (TREE_TYPE (primarg1)) < correct_width
2853       && TYPE_PRECISION (TREE_TYPE (primother)) < correct_width)
2854     {
2855       tree type = TREE_TYPE (arg0);
2856
2857       /* Make sure shorter operand is extended the right way
2858          to match the longer operand.  */
2859       primarg1 = fold_convert (signed_or_unsigned_type_for
2860                                (unsignedp1, TREE_TYPE (primarg1)), primarg1);
2861
2862       if (operand_equal_p (arg0, fold_convert (type, primarg1), 0))
2863         return 1;
2864     }
2865
2866   return 0;
2867 }
2868 \f
2869 /* See if ARG is an expression that is either a comparison or is performing
2870    arithmetic on comparisons.  The comparisons must only be comparing
2871    two different values, which will be stored in *CVAL1 and *CVAL2; if
2872    they are nonzero it means that some operands have already been found.
2873    No variables may be used anywhere else in the expression except in the
2874    comparisons.  If SAVE_P is true it means we removed a SAVE_EXPR around
2875    the expression and save_expr needs to be called with CVAL1 and CVAL2.
2876
2877    If this is true, return 1.  Otherwise, return zero.  */
2878
2879 static int
2880 twoval_comparison_p (tree arg, tree *cval1, tree *cval2, int *save_p)
2881 {
2882   enum tree_code code = TREE_CODE (arg);
2883   enum tree_code_class tclass = TREE_CODE_CLASS (code);
2884
2885   /* We can handle some of the tcc_expression cases here.  */
2886   if (tclass == tcc_expression && code == TRUTH_NOT_EXPR)
2887     tclass = tcc_unary;
2888   else if (tclass == tcc_expression
2889            && (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR
2890                || code == COMPOUND_EXPR))
2891     tclass = tcc_binary;
2892
2893   else if (tclass == tcc_expression && code == SAVE_EXPR
2894            && ! TREE_SIDE_EFFECTS (TREE_OPERAND (arg, 0)))
2895     {
2896       /* If we've already found a CVAL1 or CVAL2, this expression is
2897          two complex to handle.  */
2898       if (*cval1 || *cval2)
2899         return 0;
2900
2901       tclass = tcc_unary;
2902       *save_p = 1;
2903     }
2904
2905   switch (tclass)
2906     {
2907     case tcc_unary:
2908       return twoval_comparison_p (TREE_OPERAND (arg, 0), cval1, cval2, save_p);
2909
2910     case tcc_binary:
2911       return (twoval_comparison_p (TREE_OPERAND (arg, 0), cval1, cval2, save_p)
2912               && twoval_comparison_p (TREE_OPERAND (arg, 1),
2913                                       cval1, cval2, save_p));
2914
2915     case tcc_constant:
2916       return 1;
2917
2918     case tcc_expression:
2919       if (code == COND_EXPR)
2920         return (twoval_comparison_p (TREE_OPERAND (arg, 0),
2921                                      cval1, cval2, save_p)
2922                 && twoval_comparison_p (TREE_OPERAND (arg, 1),
2923                                         cval1, cval2, save_p)
2924                 && twoval_comparison_p (TREE_OPERAND (arg, 2),
2925                                         cval1, cval2, save_p));
2926       return 0;
2927
2928     case tcc_comparison:
2929       /* First see if we can handle the first operand, then the second.  For
2930          the second operand, we know *CVAL1 can't be zero.  It must be that
2931          one side of the comparison is each of the values; test for the
2932          case where this isn't true by failing if the two operands
2933          are the same.  */
2934
2935       if (operand_equal_p (TREE_OPERAND (arg, 0),
2936                            TREE_OPERAND (arg, 1), 0))
2937         return 0;
2938
2939       if (*cval1 == 0)
2940         *cval1 = TREE_OPERAND (arg, 0);
2941       else if (operand_equal_p (*cval1, TREE_OPERAND (arg, 0), 0))
2942         ;
2943       else if (*cval2 == 0)
2944         *cval2 = TREE_OPERAND (arg, 0);
2945       else if (operand_equal_p (*cval2, TREE_OPERAND (arg, 0), 0))
2946         ;
2947       else
2948         return 0;
2949
2950       if (operand_equal_p (*cval1, TREE_OPERAND (arg, 1), 0))
2951         ;
2952       else if (*cval2 == 0)
2953         *cval2 = TREE_OPERAND (arg, 1);
2954       else if (operand_equal_p (*cval2, TREE_OPERAND (arg, 1), 0))
2955         ;
2956       else
2957         return 0;
2958
2959       return 1;
2960
2961     default:
2962       return 0;
2963     }
2964 }
2965 \f
2966 /* ARG is a tree that is known to contain just arithmetic operations and
2967    comparisons.  Evaluate the operations in the tree substituting NEW0 for
2968    any occurrence of OLD0 as an operand of a comparison and likewise for
2969    NEW1 and OLD1.  */
2970
2971 static tree
2972 eval_subst (location_t loc, tree arg, tree old0, tree new0,
2973             tree old1, tree new1)
2974 {
2975   tree type = TREE_TYPE (arg);
2976   enum tree_code code = TREE_CODE (arg);
2977   enum tree_code_class tclass = TREE_CODE_CLASS (code);
2978
2979   /* We can handle some of the tcc_expression cases here.  */
2980   if (tclass == tcc_expression && code == TRUTH_NOT_EXPR)
2981     tclass = tcc_unary;
2982   else if (tclass == tcc_expression
2983            && (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR))
2984     tclass = tcc_binary;
2985
2986   switch (tclass)
2987     {
2988     case tcc_unary:
2989       return fold_build1_loc (loc, code, type,
2990                           eval_subst (loc, TREE_OPERAND (arg, 0),
2991                                       old0, new0, old1, new1));
2992
2993     case tcc_binary:
2994       return fold_build2_loc (loc, code, type,
2995                           eval_subst (loc, TREE_OPERAND (arg, 0),
2996                                       old0, new0, old1, new1),
2997                           eval_subst (loc, TREE_OPERAND (arg, 1),
2998                                       old0, new0, old1, new1));
2999
3000     case tcc_expression:
3001       switch (code)
3002         {
3003         case SAVE_EXPR:
3004           return eval_subst (loc, TREE_OPERAND (arg, 0), old0, new0,
3005                              old1, new1);
3006
3007         case COMPOUND_EXPR:
3008           return eval_subst (loc, TREE_OPERAND (arg, 1), old0, new0,
3009                              old1, new1);
3010
3011         case COND_EXPR:
3012           return fold_build3_loc (loc, code, type,
3013                               eval_subst (loc, TREE_OPERAND (arg, 0),
3014                                           old0, new0, old1, new1),
3015                               eval_subst (loc, TREE_OPERAND (arg, 1),
3016                                           old0, new0, old1, new1),
3017                               eval_subst (loc, TREE_OPERAND (arg, 2),
3018                                           old0, new0, old1, new1));
3019         default:
3020           break;
3021         }
3022       /* Fall through - ???  */
3023
3024     case tcc_comparison:
3025       {
3026         tree arg0 = TREE_OPERAND (arg, 0);
3027         tree arg1 = TREE_OPERAND (arg, 1);
3028
3029         /* We need to check both for exact equality and tree equality.  The
3030            former will be true if the operand has a side-effect.  In that
3031            case, we know the operand occurred exactly once.  */
3032
3033         if (arg0 == old0 || operand_equal_p (arg0, old0, 0))
3034           arg0 = new0;
3035         else if (arg0 == old1 || operand_equal_p (arg0, old1, 0))
3036           arg0 = new1;
3037
3038         if (arg1 == old0 || operand_equal_p (arg1, old0, 0))
3039           arg1 = new0;
3040         else if (arg1 == old1 || operand_equal_p (arg1, old1, 0))
3041           arg1 = new1;
3042
3043         return fold_build2_loc (loc, code, type, arg0, arg1);
3044       }
3045
3046     default:
3047       return arg;
3048     }
3049 }
3050 \f
3051 /* Return a tree for the case when the result of an expression is RESULT
3052    converted to TYPE and OMITTED was previously an operand of the expression
3053    but is now not needed (e.g., we folded OMITTED * 0).
3054
3055    If OMITTED has side effects, we must evaluate it.  Otherwise, just do
3056    the conversion of RESULT to TYPE.  */
3057
3058 tree
3059 omit_one_operand_loc (location_t loc, tree type, tree result, tree omitted)
3060 {
3061   tree t = fold_convert_loc (loc, type, result);
3062
3063   /* If the resulting operand is an empty statement, just return the omitted
3064      statement casted to void. */
3065   if (IS_EMPTY_STMT (t) && TREE_SIDE_EFFECTS (omitted))
3066     return build1_loc (loc, NOP_EXPR, void_type_node,
3067                        fold_ignored_result (omitted));
3068
3069   if (TREE_SIDE_EFFECTS (omitted))
3070     return build2_loc (loc, COMPOUND_EXPR, type,
3071                        fold_ignored_result (omitted), t);
3072
3073   return non_lvalue_loc (loc, t);
3074 }
3075
3076 /* Return a tree for the case when the result of an expression is RESULT
3077    converted to TYPE and OMITTED1 and OMITTED2 were previously operands
3078    of the expression but are now not needed.
3079
3080    If OMITTED1 or OMITTED2 has side effects, they must be evaluated.
3081    If both OMITTED1 and OMITTED2 have side effects, OMITTED1 is
3082    evaluated before OMITTED2.  Otherwise, if neither has side effects,
3083    just do the conversion of RESULT to TYPE.  */
3084
3085 tree
3086 omit_two_operands_loc (location_t loc, tree type, tree result,
3087                        tree omitted1, tree omitted2)
3088 {
3089   tree t = fold_convert_loc (loc, type, result);
3090
3091   if (TREE_SIDE_EFFECTS (omitted2))
3092     t = build2_loc (loc, COMPOUND_EXPR, type, omitted2, t);
3093   if (TREE_SIDE_EFFECTS (omitted1))
3094     t = build2_loc (loc, COMPOUND_EXPR, type, omitted1, t);
3095
3096   return TREE_CODE (t) != COMPOUND_EXPR ? non_lvalue_loc (loc, t) : t;
3097 }
3098
3099 \f
3100 /* Return a simplified tree node for the truth-negation of ARG.  This
3101    never alters ARG itself.  We assume that ARG is an operation that
3102    returns a truth value (0 or 1).
3103
3104    FIXME: one would think we would fold the result, but it causes
3105    problems with the dominator optimizer.  */
3106
3107 static tree
3108 fold_truth_not_expr (location_t loc, tree arg)
3109 {
3110   tree type = TREE_TYPE (arg);
3111   enum tree_code code = TREE_CODE (arg);
3112   location_t loc1, loc2;
3113
3114   /* If this is a comparison, we can simply invert it, except for
3115      floating-point non-equality comparisons, in which case we just
3116      enclose a TRUTH_NOT_EXPR around what we have.  */
3117
3118   if (TREE_CODE_CLASS (code) == tcc_comparison)
3119     {
3120       tree op_type = TREE_TYPE (TREE_OPERAND (arg, 0));
3121       if (FLOAT_TYPE_P (op_type)
3122           && flag_trapping_math
3123           && code != ORDERED_EXPR && code != UNORDERED_EXPR
3124           && code != NE_EXPR && code != EQ_EXPR)
3125         return NULL_TREE;
3126
3127       code = invert_tree_comparison (code, HONOR_NANS (TYPE_MODE (op_type)));
3128       if (code == ERROR_MARK)
3129         return NULL_TREE;
3130
3131       return build2_loc (loc, code, type, TREE_OPERAND (arg, 0),
3132                          TREE_OPERAND (arg, 1));
3133     }
3134
3135   switch (code)
3136     {
3137     case INTEGER_CST:
3138       return constant_boolean_node (integer_zerop (arg), type);
3139
3140     case TRUTH_AND_EXPR:
3141       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3142       loc2 = expr_location_or (TREE_OPERAND (arg, 1), loc);
3143       return build2_loc (loc, TRUTH_OR_EXPR, type,
3144                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)),
3145                          invert_truthvalue_loc (loc2, TREE_OPERAND (arg, 1)));
3146
3147     case TRUTH_OR_EXPR:
3148       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3149       loc2 = expr_location_or (TREE_OPERAND (arg, 1), loc);
3150       return build2_loc (loc, TRUTH_AND_EXPR, type,
3151                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)),
3152                          invert_truthvalue_loc (loc2, TREE_OPERAND (arg, 1)));
3153
3154     case TRUTH_XOR_EXPR:
3155       /* Here we can invert either operand.  We invert the first operand
3156          unless the second operand is a TRUTH_NOT_EXPR in which case our
3157          result is the XOR of the first operand with the inside of the
3158          negation of the second operand.  */
3159
3160       if (TREE_CODE (TREE_OPERAND (arg, 1)) == TRUTH_NOT_EXPR)
3161         return build2_loc (loc, TRUTH_XOR_EXPR, type, TREE_OPERAND (arg, 0),
3162                            TREE_OPERAND (TREE_OPERAND (arg, 1), 0));
3163       else
3164         return build2_loc (loc, TRUTH_XOR_EXPR, type,
3165                            invert_truthvalue_loc (loc, TREE_OPERAND (arg, 0)),
3166                            TREE_OPERAND (arg, 1));
3167
3168     case TRUTH_ANDIF_EXPR:
3169       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3170       loc2 = expr_location_or (TREE_OPERAND (arg, 1), loc);
3171       return build2_loc (loc, TRUTH_ORIF_EXPR, type,
3172                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)),
3173                          invert_truthvalue_loc (loc2, TREE_OPERAND (arg, 1)));
3174
3175     case TRUTH_ORIF_EXPR:
3176       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3177       loc2 = expr_location_or (TREE_OPERAND (arg, 1), loc);
3178       return build2_loc (loc, TRUTH_ANDIF_EXPR, type,
3179                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)),
3180                          invert_truthvalue_loc (loc2, TREE_OPERAND (arg, 1)));
3181
3182     case TRUTH_NOT_EXPR:
3183       return TREE_OPERAND (arg, 0);
3184
3185     case COND_EXPR:
3186       {
3187         tree arg1 = TREE_OPERAND (arg, 1);
3188         tree arg2 = TREE_OPERAND (arg, 2);
3189
3190         loc1 = expr_location_or (TREE_OPERAND (arg, 1), loc);
3191         loc2 = expr_location_or (TREE_OPERAND (arg, 2), loc);
3192
3193         /* A COND_EXPR may have a throw as one operand, which
3194            then has void type.  Just leave void operands
3195            as they are.  */
3196         return build3_loc (loc, COND_EXPR, type, TREE_OPERAND (arg, 0),
3197                            VOID_TYPE_P (TREE_TYPE (arg1))
3198                            ? arg1 : invert_truthvalue_loc (loc1, arg1),
3199                            VOID_TYPE_P (TREE_TYPE (arg2))
3200                            ? arg2 : invert_truthvalue_loc (loc2, arg2));
3201       }
3202
3203     case COMPOUND_EXPR:
3204       loc1 = expr_location_or (TREE_OPERAND (arg, 1), loc);
3205       return build2_loc (loc, COMPOUND_EXPR, type,
3206                          TREE_OPERAND (arg, 0),
3207                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 1)));
3208
3209     case NON_LVALUE_EXPR:
3210       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3211       return invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0));
3212
3213     CASE_CONVERT:
3214       if (TREE_CODE (TREE_TYPE (arg)) == BOOLEAN_TYPE)
3215         return build1_loc (loc, TRUTH_NOT_EXPR, type, arg);
3216
3217       /* ... fall through ...  */
3218
3219     case FLOAT_EXPR:
3220       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3221       return build1_loc (loc, TREE_CODE (arg), type,
3222                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)));
3223
3224     case BIT_AND_EXPR:
3225       if (!integer_onep (TREE_OPERAND (arg, 1)))
3226         return NULL_TREE;
3227       return build2_loc (loc, EQ_EXPR, type, arg, build_int_cst (type, 0));
3228
3229     case SAVE_EXPR:
3230       return build1_loc (loc, TRUTH_NOT_EXPR, type, arg);
3231
3232     case CLEANUP_POINT_EXPR:
3233       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3234       return build1_loc (loc, CLEANUP_POINT_EXPR, type,
3235                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)));
3236
3237     default:
3238       return NULL_TREE;
3239     }
3240 }
3241
3242 /* Fold the truth-negation of ARG.  This never alters ARG itself.  We
3243    assume that ARG is an operation that returns a truth value (0 or 1
3244    for scalars, 0 or -1 for vectors).  Return the folded expression if
3245    folding is successful.  Otherwise, return NULL_TREE.  */
3246
3247 static tree
3248 fold_invert_truthvalue (location_t loc, tree arg)
3249 {
3250   tree type = TREE_TYPE (arg);
3251   return fold_unary_loc (loc, VECTOR_TYPE_P (type)
3252                               ? BIT_NOT_EXPR
3253                               : TRUTH_NOT_EXPR,
3254                          type, arg);
3255 }
3256
3257 /* Return a simplified tree node for the truth-negation of ARG.  This
3258    never alters ARG itself.  We assume that ARG is an operation that
3259    returns a truth value (0 or 1 for scalars, 0 or -1 for vectors).  */
3260
3261 tree
3262 invert_truthvalue_loc (location_t loc, tree arg)
3263 {
3264   if (TREE_CODE (arg) == ERROR_MARK)
3265     return arg;
3266
3267   tree type = TREE_TYPE (arg);
3268   return fold_build1_loc (loc, VECTOR_TYPE_P (type)
3269                                ? BIT_NOT_EXPR
3270                                : TRUTH_NOT_EXPR,
3271                           type, arg);
3272 }
3273
3274 /* Given a bit-wise operation CODE applied to ARG0 and ARG1, see if both
3275    operands are another bit-wise operation with a common input.  If so,
3276    distribute the bit operations to save an operation and possibly two if
3277    constants are involved.  For example, convert
3278         (A | B) & (A | C) into A | (B & C)
3279    Further simplification will occur if B and C are constants.
3280
3281    If this optimization cannot be done, 0 will be returned.  */
3282
3283 static tree
3284 distribute_bit_expr (location_t loc, enum tree_code code, tree type,
3285                      tree arg0, tree arg1)
3286 {
3287   tree common;
3288   tree left, right;
3289
3290   if (TREE_CODE (arg0) != TREE_CODE (arg1)
3291       || TREE_CODE (arg0) == code
3292       || (TREE_CODE (arg0) != BIT_AND_EXPR
3293           && TREE_CODE (arg0) != BIT_IOR_EXPR))
3294     return 0;
3295
3296   if (operand_equal_p (TREE_OPERAND (arg0, 0), TREE_OPERAND (arg1, 0), 0))
3297     {
3298       common = TREE_OPERAND (arg0, 0);
3299       left = TREE_OPERAND (arg0, 1);
3300       right = TREE_OPERAND (arg1, 1);
3301     }
3302   else if (operand_equal_p (TREE_OPERAND (arg0, 0), TREE_OPERAND (arg1, 1), 0))
3303     {
3304       common = TREE_OPERAND (arg0, 0);
3305       left = TREE_OPERAND (arg0, 1);
3306       right = TREE_OPERAND (arg1, 0);
3307     }
3308   else if (operand_equal_p (TREE_OPERAND (arg0, 1), TREE_OPERAND (arg1, 0), 0))
3309     {
3310       common = TREE_OPERAND (arg0, 1);
3311       left = TREE_OPERAND (arg0, 0);
3312       right = TREE_OPERAND (arg1, 1);
3313     }
3314   else if (operand_equal_p (TREE_OPERAND (arg0, 1), TREE_OPERAND (arg1, 1), 0))
3315     {
3316       common = TREE_OPERAND (arg0, 1);
3317       left = TREE_OPERAND (arg0, 0);
3318       right = TREE_OPERAND (arg1, 0);
3319     }
3320   else
3321     return 0;
3322
3323   common = fold_convert_loc (loc, type, common);
3324   left = fold_convert_loc (loc, type, left);
3325   right = fold_convert_loc (loc, type, right);
3326   return fold_build2_loc (loc, TREE_CODE (arg0), type, common,
3327                       fold_build2_loc (loc, code, type, left, right));
3328 }
3329
3330 /* Knowing that ARG0 and ARG1 are both RDIV_EXPRs, simplify a binary operation
3331    with code CODE.  This optimization is unsafe.  */
3332 static tree
3333 distribute_real_division (location_t loc, enum tree_code code, tree type,
3334                           tree arg0, tree arg1)
3335 {
3336   bool mul0 = TREE_CODE (arg0) == MULT_EXPR;
3337   bool mul1 = TREE_CODE (arg1) == MULT_EXPR;
3338
3339   /* (A / C) +- (B / C) -> (A +- B) / C.  */
3340   if (mul0 == mul1
3341       && operand_equal_p (TREE_OPERAND (arg0, 1),
3342                        TREE_OPERAND (arg1, 1), 0))
3343     return fold_build2_loc (loc, mul0 ? MULT_EXPR : RDIV_EXPR, type,
3344                         fold_build2_loc (loc, code, type,
3345                                      TREE_OPERAND (arg0, 0),
3346                                      TREE_OPERAND (arg1, 0)),
3347                         TREE_OPERAND (arg0, 1));
3348
3349   /* (A / C1) +- (A / C2) -> A * (1 / C1 +- 1 / C2).  */
3350   if (operand_equal_p (TREE_OPERAND (arg0, 0),
3351                        TREE_OPERAND (arg1, 0), 0)
3352       && TREE_CODE (TREE_OPERAND (arg0, 1)) == REAL_CST
3353       && TREE_CODE (TREE_OPERAND (arg1, 1)) == REAL_CST)
3354     {
3355       REAL_VALUE_TYPE r0, r1;
3356       r0 = TREE_REAL_CST (TREE_OPERAND (arg0, 1));
3357       r1 = TREE_REAL_CST (TREE_OPERAND (arg1, 1));
3358       if (!mul0)
3359         real_arithmetic (&r0, RDIV_EXPR, &dconst1, &r0);
3360       if (!mul1)
3361         real_arithmetic (&r1, RDIV_EXPR, &dconst1, &r1);
3362       real_arithmetic (&r0, code, &r0, &r1);
3363       return fold_build2_loc (loc, MULT_EXPR, type,
3364                           TREE_OPERAND (arg0, 0),
3365                           build_real (type, r0));
3366     }
3367
3368   return NULL_TREE;
3369 }
3370 \f
3371 /* Return a BIT_FIELD_REF of type TYPE to refer to BITSIZE bits of INNER
3372    starting at BITPOS.  The field is unsigned if UNSIGNEDP is nonzero.  */
3373
3374 static tree
3375 make_bit_field_ref (location_t loc, tree inner, tree type,
3376                     HOST_WIDE_INT bitsize, HOST_WIDE_INT bitpos, int unsignedp)
3377 {
3378   tree result, bftype;
3379
3380   if (bitpos == 0)
3381     {
3382       tree size = TYPE_SIZE (TREE_TYPE (inner));
3383       if ((INTEGRAL_TYPE_P (TREE_TYPE (inner))
3384            || POINTER_TYPE_P (TREE_TYPE (inner)))
3385           && tree_fits_shwi_p (size)
3386           && tree_to_shwi (size) == bitsize)
3387         return fold_convert_loc (loc, type, inner);
3388     }
3389
3390   bftype = type;
3391   if (TYPE_PRECISION (bftype) != bitsize
3392       || TYPE_UNSIGNED (bftype) == !unsignedp)
3393     bftype = build_nonstandard_integer_type (bitsize, 0);
3394
3395   result = build3_loc (loc, BIT_FIELD_REF, bftype, inner,
3396                        size_int (bitsize), bitsize_int (bitpos));
3397
3398   if (bftype != type)
3399     result = fold_convert_loc (loc, type, result);
3400
3401   return result;
3402 }
3403
3404 /* Optimize a bit-field compare.
3405
3406    There are two cases:  First is a compare against a constant and the
3407    second is a comparison of two items where the fields are at the same
3408    bit position relative to the start of a chunk (byte, halfword, word)
3409    large enough to contain it.  In these cases we can avoid the shift
3410    implicit in bitfield extractions.
3411
3412    For constants, we emit a compare of the shifted constant with the
3413    BIT_AND_EXPR of a mask and a byte, halfword, or word of the operand being
3414    compared.  For two fields at the same position, we do the ANDs with the
3415    similar mask and compare the result of the ANDs.
3416
3417    CODE is the comparison code, known to be either NE_EXPR or EQ_EXPR.
3418    COMPARE_TYPE is the type of the comparison, and LHS and RHS
3419    are the left and right operands of the comparison, respectively.
3420
3421    If the optimization described above can be done, we return the resulting
3422    tree.  Otherwise we return zero.  */
3423
3424 static tree
3425 optimize_bit_field_compare (location_t loc, enum tree_code code,
3426                             tree compare_type, tree lhs, tree rhs)
3427 {
3428   HOST_WIDE_INT lbitpos, lbitsize, rbitpos, rbitsize, nbitpos, nbitsize;
3429   tree type = TREE_TYPE (lhs);
3430   tree unsigned_type;
3431   int const_p = TREE_CODE (rhs) == INTEGER_CST;
3432   machine_mode lmode, rmode, nmode;
3433   int lunsignedp, runsignedp;
3434   int lvolatilep = 0, rvolatilep = 0;
3435   tree linner, rinner = NULL_TREE;
3436   tree mask;
3437   tree offset;
3438
3439   /* Get all the information about the extractions being done.  If the bit size
3440      if the same as the size of the underlying object, we aren't doing an
3441      extraction at all and so can do nothing.  We also don't want to
3442      do anything if the inner expression is a PLACEHOLDER_EXPR since we
3443      then will no longer be able to replace it.  */
3444   linner = get_inner_reference (lhs, &lbitsize, &lbitpos, &offset, &lmode,
3445                                 &lunsignedp, &lvolatilep, false);
3446   if (linner == lhs || lbitsize == GET_MODE_BITSIZE (lmode) || lbitsize < 0
3447       || offset != 0 || TREE_CODE (linner) == PLACEHOLDER_EXPR || lvolatilep)
3448     return 0;
3449
3450  if (!const_p)
3451    {
3452      /* If this is not a constant, we can only do something if bit positions,
3453         sizes, and signedness are the same.  */
3454      rinner = get_inner_reference (rhs, &rbitsize, &rbitpos, &offset, &rmode,
3455                                    &runsignedp, &rvolatilep, false);
3456
3457      if (rinner == rhs || lbitpos != rbitpos || lbitsize != rbitsize
3458          || lunsignedp != runsignedp || offset != 0
3459          || TREE_CODE (rinner) == PLACEHOLDER_EXPR || rvolatilep)
3460        return 0;
3461    }
3462
3463   /* See if we can find a mode to refer to this field.  We should be able to,
3464      but fail if we can't.  */
3465   nmode = get_best_mode (lbitsize, lbitpos, 0, 0,
3466                          const_p ? TYPE_ALIGN (TREE_TYPE (linner))
3467                          : MIN (TYPE_ALIGN (TREE_TYPE (linner)),
3468                                 TYPE_ALIGN (TREE_TYPE (rinner))),
3469                          word_mode, false);
3470   if (nmode == VOIDmode)
3471     return 0;
3472
3473   /* Set signed and unsigned types of the precision of this mode for the
3474      shifts below.  */
3475   unsigned_type = lang_hooks.types.type_for_mode (nmode, 1);
3476
3477   /* Compute the bit position and size for the new reference and our offset
3478      within it. If the new reference is the same size as the original, we
3479      won't optimize anything, so return zero.  */
3480   nbitsize = GET_MODE_BITSIZE (nmode);
3481   nbitpos = lbitpos & ~ (nbitsize - 1);
3482   lbitpos -= nbitpos;
3483   if (nbitsize == lbitsize)
3484     return 0;
3485
3486   if (BYTES_BIG_ENDIAN)
3487     lbitpos = nbitsize - lbitsize - lbitpos;
3488
3489   /* Make the mask to be used against the extracted field.  */
3490   mask = build_int_cst_type (unsigned_type, -1);
3491   mask = const_binop (LSHIFT_EXPR, mask, size_int (nbitsize - lbitsize));
3492   mask = const_binop (RSHIFT_EXPR, mask,
3493                       size_int (nbitsize - lbitsize - lbitpos));
3494
3495   if (! const_p)
3496     /* If not comparing with constant, just rework the comparison
3497        and return.  */
3498     return fold_build2_loc (loc, code, compare_type,
3499                         fold_build2_loc (loc, BIT_AND_EXPR, unsigned_type,
3500                                      make_bit_field_ref (loc, linner,
3501                                                          unsigned_type,
3502                                                          nbitsize, nbitpos,
3503                                                          1),
3504                                      mask),
3505                         fold_build2_loc (loc, BIT_AND_EXPR, unsigned_type,
3506                                      make_bit_field_ref (loc, rinner,
3507                                                          unsigned_type,
3508                                                          nbitsize, nbitpos,
3509                                                          1),
3510                                      mask));
3511
3512   /* Otherwise, we are handling the constant case. See if the constant is too
3513      big for the field.  Warn and return a tree of for 0 (false) if so.  We do
3514      this not only for its own sake, but to avoid having to test for this
3515      error case below.  If we didn't, we might generate wrong code.
3516
3517      For unsigned fields, the constant shifted right by the field length should
3518      be all zero.  For signed fields, the high-order bits should agree with
3519      the sign bit.  */
3520
3521   if (lunsignedp)
3522     {
3523       if (wi::lrshift (rhs, lbitsize) != 0)
3524         {
3525           warning (0, "comparison is always %d due to width of bit-field",
3526                    code == NE_EXPR);
3527           return constant_boolean_node (code == NE_EXPR, compare_type);
3528         }
3529     }
3530   else
3531     {
3532       wide_int tem = wi::arshift (rhs, lbitsize - 1);
3533       if (tem != 0 && tem != -1)
3534         {
3535           warning (0, "comparison is always %d due to width of bit-field",
3536                    code == NE_EXPR);
3537           return constant_boolean_node (code == NE_EXPR, compare_type);
3538         }
3539     }
3540
3541   /* Single-bit compares should always be against zero.  */
3542   if (lbitsize == 1 && ! integer_zerop (rhs))
3543     {
3544       code = code == EQ_EXPR ? NE_EXPR : EQ_EXPR;
3545       rhs = build_int_cst (type, 0);
3546     }
3547
3548   /* Make a new bitfield reference, shift the constant over the
3549      appropriate number of bits and mask it with the computed mask
3550      (in case this was a signed field).  If we changed it, make a new one.  */
3551   lhs = make_bit_field_ref (loc, linner, unsigned_type, nbitsize, nbitpos, 1);
3552
3553   rhs = const_binop (BIT_AND_EXPR,
3554                      const_binop (LSHIFT_EXPR,
3555                                   fold_convert_loc (loc, unsigned_type, rhs),
3556                                   size_int (lbitpos)),
3557                      mask);
3558
3559   lhs = build2_loc (loc, code, compare_type,
3560                     build2 (BIT_AND_EXPR, unsigned_type, lhs, mask), rhs);
3561   return lhs;
3562 }
3563 \f
3564 /* Subroutine for fold_truth_andor_1: decode a field reference.
3565
3566    If EXP is a comparison reference, we return the innermost reference.
3567
3568    *PBITSIZE is set to the number of bits in the reference, *PBITPOS is
3569    set to the starting bit number.
3570
3571    If the innermost field can be completely contained in a mode-sized
3572    unit, *PMODE is set to that mode.  Otherwise, it is set to VOIDmode.
3573
3574    *PVOLATILEP is set to 1 if the any expression encountered is volatile;
3575    otherwise it is not changed.
3576
3577    *PUNSIGNEDP is set to the signedness of the field.
3578
3579    *PMASK is set to the mask used.  This is either contained in a
3580    BIT_AND_EXPR or derived from the width of the field.
3581
3582    *PAND_MASK is set to the mask found in a BIT_AND_EXPR, if any.
3583
3584    Return 0 if this is not a component reference or is one that we can't
3585    do anything with.  */
3586
3587 static tree
3588 decode_field_reference (location_t loc, tree exp, HOST_WIDE_INT *pbitsize,
3589                         HOST_WIDE_INT *pbitpos, machine_mode *pmode,
3590                         int *punsignedp, int *pvolatilep,
3591                         tree *pmask, tree *pand_mask)
3592 {
3593   tree outer_type = 0;
3594   tree and_mask = 0;
3595   tree mask, inner, offset;
3596   tree unsigned_type;
3597   unsigned int precision;
3598
3599   /* All the optimizations using this function assume integer fields.
3600      There are problems with FP fields since the type_for_size call
3601      below can fail for, e.g., XFmode.  */
3602   if (! INTEGRAL_TYPE_P (TREE_TYPE (exp)))
3603     return 0;
3604
3605   /* We are interested in the bare arrangement of bits, so strip everything
3606      that doesn't affect the machine mode.  However, record the type of the
3607      outermost expression if it may matter below.  */
3608   if (CONVERT_EXPR_P (exp)
3609       || TREE_CODE (exp) == NON_LVALUE_EXPR)
3610     outer_type = TREE_TYPE (exp);
3611   STRIP_NOPS (exp);
3612
3613   if (TREE_CODE (exp) == BIT_AND_EXPR)
3614     {
3615       and_mask = TREE_OPERAND (exp, 1);
3616       exp = TREE_OPERAND (exp, 0);
3617       STRIP_NOPS (exp); STRIP_NOPS (and_mask);
3618       if (TREE_CODE (and_mask) != INTEGER_CST)
3619         return 0;
3620     }
3621
3622   inner = get_inner_reference (exp, pbitsize, pbitpos, &offset, pmode,
3623                                punsignedp, pvolatilep, false);
3624   if ((inner == exp && and_mask == 0)
3625       || *pbitsize < 0 || offset != 0
3626       || TREE_CODE (inner) == PLACEHOLDER_EXPR)
3627     return 0;
3628
3629   /* If the number of bits in the reference is the same as the bitsize of
3630      the outer type, then the outer type gives the signedness. Otherwise
3631      (in case of a small bitfield) the signedness is unchanged.  */
3632   if (outer_type && *pbitsize == TYPE_PRECISION (outer_type))
3633     *punsignedp = TYPE_UNSIGNED (outer_type);
3634
3635   /* Compute the mask to access the bitfield.  */
3636   unsigned_type = lang_hooks.types.type_for_size (*pbitsize, 1);
3637   precision = TYPE_PRECISION (unsigned_type);
3638
3639   mask = build_int_cst_type (unsigned_type, -1);
3640
3641   mask = const_binop (LSHIFT_EXPR, mask, size_int (precision - *pbitsize));
3642   mask = const_binop (RSHIFT_EXPR, mask, size_int (precision - *pbitsize));
3643
3644   /* Merge it with the mask we found in the BIT_AND_EXPR, if any.  */
3645   if (and_mask != 0)
3646     mask = fold_build2_loc (loc, BIT_AND_EXPR, unsigned_type,
3647                         fold_convert_loc (loc, unsigned_type, and_mask), mask);
3648
3649   *pmask = mask;
3650   *pand_mask = and_mask;
3651   return inner;
3652 }
3653
3654 /* Return nonzero if MASK represents a mask of SIZE ones in the low-order
3655    bit positions and MASK is SIGNED.  */
3656
3657 static int
3658 all_ones_mask_p (const_tree mask, unsigned int size)
3659 {
3660   tree type = TREE_TYPE (mask);
3661   unsigned int precision = TYPE_PRECISION (type);
3662
3663   /* If this function returns true when the type of the mask is
3664      UNSIGNED, then there will be errors.  In particular see
3665      gcc.c-torture/execute/990326-1.c.  There does not appear to be
3666      any documentation paper trail as to why this is so.  But the pre
3667      wide-int worked with that restriction and it has been preserved
3668      here.  */
3669   if (size > precision || TYPE_SIGN (type) == UNSIGNED)
3670     return false;
3671
3672   return wi::mask (size, false, precision) == mask;
3673 }
3674
3675 /* Subroutine for fold: determine if VAL is the INTEGER_CONST that
3676    represents the sign bit of EXP's type.  If EXP represents a sign
3677    or zero extension, also test VAL against the unextended type.
3678    The return value is the (sub)expression whose sign bit is VAL,
3679    or NULL_TREE otherwise.  */
3680
3681 static tree
3682 sign_bit_p (tree exp, const_tree val)
3683 {
3684   int width;
3685   tree t;
3686
3687   /* Tree EXP must have an integral type.  */
3688   t = TREE_TYPE (exp);
3689   if (! INTEGRAL_TYPE_P (t))
3690     return NULL_TREE;
3691
3692   /* Tree VAL must be an integer constant.  */
3693   if (TREE_CODE (val) != INTEGER_CST
3694       || TREE_OVERFLOW (val))
3695     return NULL_TREE;
3696
3697   width = TYPE_PRECISION (t);
3698   if (wi::only_sign_bit_p (val, width))
3699     return exp;
3700
3701   /* Handle extension from a narrower type.  */
3702   if (TREE_CODE (exp) == NOP_EXPR
3703       && TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (exp, 0))) < width)
3704     return sign_bit_p (TREE_OPERAND (exp, 0), val);
3705
3706   return NULL_TREE;
3707 }
3708
3709 /* Subroutine for fold_truth_andor_1: determine if an operand is simple enough
3710    to be evaluated unconditionally.  */
3711
3712 static int
3713 simple_operand_p (const_tree exp)
3714 {
3715   /* Strip any conversions that don't change the machine mode.  */
3716   STRIP_NOPS (exp);
3717
3718   return (CONSTANT_CLASS_P (exp)
3719           || TREE_CODE (exp) == SSA_NAME
3720           || (DECL_P (exp)
3721               && ! TREE_ADDRESSABLE (exp)
3722               && ! TREE_THIS_VOLATILE (exp)
3723               && ! DECL_NONLOCAL (exp)
3724               /* Don't regard global variables as simple.  They may be
3725                  allocated in ways unknown to the compiler (shared memory,
3726                  #pragma weak, etc).  */
3727               && ! TREE_PUBLIC (exp)
3728               && ! DECL_EXTERNAL (exp)
3729               /* Weakrefs are not safe to be read, since they can be NULL.
3730                  They are !TREE_PUBLIC && !DECL_EXTERNAL but still
3731                  have DECL_WEAK flag set.  */
3732               && (! VAR_OR_FUNCTION_DECL_P (exp) || ! DECL_WEAK (exp))
3733               /* Loading a static variable is unduly expensive, but global
3734                  registers aren't expensive.  */
3735               && (! TREE_STATIC (exp) || DECL_REGISTER (exp))));
3736 }
3737
3738 /* Subroutine for fold_truth_andor: determine if an operand is simple enough
3739    to be evaluated unconditionally.
3740    I addition to simple_operand_p, we assume that comparisons, conversions,
3741    and logic-not operations are simple, if their operands are simple, too.  */
3742
3743 static bool
3744 simple_operand_p_2 (tree exp)
3745 {
3746   enum tree_code code;
3747
3748   if (TREE_SIDE_EFFECTS (exp)
3749       || tree_could_trap_p (exp))
3750     return false;
3751
3752   while (CONVERT_EXPR_P (exp))
3753     exp = TREE_OPERAND (exp, 0);
3754
3755   code = TREE_CODE (exp);
3756
3757   if (TREE_CODE_CLASS (code) == tcc_comparison)
3758     return (simple_operand_p (TREE_OPERAND (exp, 0))
3759             && simple_operand_p (TREE_OPERAND (exp, 1)));
3760
3761   if (code == TRUTH_NOT_EXPR)
3762       return simple_operand_p_2 (TREE_OPERAND (exp, 0));
3763
3764   return simple_operand_p (exp);
3765 }
3766
3767 \f
3768 /* The following functions are subroutines to fold_range_test and allow it to
3769    try to change a logical combination of comparisons into a range test.
3770
3771    For example, both
3772         X == 2 || X == 3 || X == 4 || X == 5
3773    and
3774         X >= 2 && X <= 5
3775    are converted to
3776         (unsigned) (X - 2) <= 3
3777
3778    We describe each set of comparisons as being either inside or outside
3779    a range, using a variable named like IN_P, and then describe the
3780    range with a lower and upper bound.  If one of the bounds is omitted,
3781    it represents either the highest or lowest value of the type.
3782
3783    In the comments below, we represent a range by two numbers in brackets
3784    preceded by a "+" to designate being inside that range, or a "-" to
3785    designate being outside that range, so the condition can be inverted by
3786    flipping the prefix.  An omitted bound is represented by a "-".  For
3787    example, "- [-, 10]" means being outside the range starting at the lowest
3788    possible value and ending at 10, in other words, being greater than 10.
3789    The range "+ [-, -]" is always true and hence the range "- [-, -]" is
3790    always false.
3791
3792    We set up things so that the missing bounds are handled in a consistent
3793    manner so neither a missing bound nor "true" and "false" need to be
3794    handled using a special case.  */
3795
3796 /* Return the result of applying CODE to ARG0 and ARG1, but handle the case
3797    of ARG0 and/or ARG1 being omitted, meaning an unlimited range. UPPER0_P
3798    and UPPER1_P are nonzero if the respective argument is an upper bound
3799    and zero for a lower.  TYPE, if nonzero, is the type of the result; it
3800    must be specified for a comparison.  ARG1 will be converted to ARG0's
3801    type if both are specified.  */
3802
3803 static tree
3804 range_binop (enum tree_code code, tree type, tree arg0, int upper0_p,
3805              tree arg1, int upper1_p)
3806 {
3807   tree tem;
3808   int result;
3809   int sgn0, sgn1;
3810
3811   /* If neither arg represents infinity, do the normal operation.
3812      Else, if not a comparison, return infinity.  Else handle the special
3813      comparison rules. Note that most of the cases below won't occur, but
3814      are handled for consistency.  */
3815
3816   if (arg0 != 0 && arg1 != 0)
3817     {
3818       tem = fold_build2 (code, type != 0 ? type : TREE_TYPE (arg0),
3819                          arg0, fold_convert (TREE_TYPE (arg0), arg1));
3820       STRIP_NOPS (tem);
3821       return TREE_CODE (tem) == INTEGER_CST ? tem : 0;
3822     }
3823
3824   if (TREE_CODE_CLASS (code) != tcc_comparison)
3825     return 0;
3826
3827   /* Set SGN[01] to -1 if ARG[01] is a lower bound, 1 for upper, and 0
3828      for neither.  In real maths, we cannot assume open ended ranges are
3829      the same. But, this is computer arithmetic, where numbers are finite.
3830      We can therefore make the transformation of any unbounded range with
3831      the value Z, Z being greater than any representable number. This permits
3832      us to treat unbounded ranges as equal.  */
3833   sgn0 = arg0 != 0 ? 0 : (upper0_p ? 1 : -1);
3834   sgn1 = arg1 != 0 ? 0 : (upper1_p ? 1 : -1);
3835   switch (code)
3836     {
3837     case EQ_EXPR:
3838       result = sgn0 == sgn1;
3839       break;
3840     case NE_EXPR:
3841       result = sgn0 != sgn1;
3842       break;
3843     case LT_EXPR:
3844       result = sgn0 < sgn1;
3845       break;
3846     case LE_EXPR:
3847       result = sgn0 <= sgn1;
3848       break;
3849     case GT_EXPR:
3850       result = sgn0 > sgn1;
3851       break;
3852     case GE_EXPR:
3853       result = sgn0 >= sgn1;
3854       break;
3855     default:
3856       gcc_unreachable ();
3857     }
3858
3859   return constant_boolean_node (result, type);
3860 }
3861 \f
3862 /* Helper routine for make_range.  Perform one step for it, return
3863    new expression if the loop should continue or NULL_TREE if it should
3864    stop.  */
3865
3866 tree
3867 make_range_step (location_t loc, enum tree_code code, tree arg0, tree arg1,
3868                  tree exp_type, tree *p_low, tree *p_high, int *p_in_p,
3869                  bool *strict_overflow_p)
3870 {
3871   tree arg0_type = TREE_TYPE (arg0);
3872   tree n_low, n_high, low = *p_low, high = *p_high;
3873   int in_p = *p_in_p, n_in_p;
3874
3875   switch (code)
3876     {
3877     case TRUTH_NOT_EXPR:
3878       /* We can only do something if the range is testing for zero.  */
3879       if (low == NULL_TREE || high == NULL_TREE
3880           || ! integer_zerop (low) || ! integer_zerop (high))
3881         return NULL_TREE;
3882       *p_in_p = ! in_p;
3883       return arg0;
3884
3885     case EQ_EXPR: case NE_EXPR:
3886     case LT_EXPR: case LE_EXPR: case GE_EXPR: case GT_EXPR:
3887       /* We can only do something if the range is testing for zero
3888          and if the second operand is an integer constant.  Note that
3889          saying something is "in" the range we make is done by
3890          complementing IN_P since it will set in the initial case of
3891          being not equal to zero; "out" is leaving it alone.  */
3892       if (low == NULL_TREE || high == NULL_TREE
3893           || ! integer_zerop (low) || ! integer_zerop (high)
3894           || TREE_CODE (arg1) != INTEGER_CST)
3895         return NULL_TREE;
3896
3897       switch (code)
3898         {
3899         case NE_EXPR:  /* - [c, c]  */
3900           low = high = arg1;
3901           break;
3902         case EQ_EXPR:  /* + [c, c]  */
3903           in_p = ! in_p, low = high = arg1;
3904           break;
3905         case GT_EXPR:  /* - [-, c] */
3906           low = 0, high = arg1;
3907           break;
3908         case GE_EXPR:  /* + [c, -] */
3909           in_p = ! in_p, low = arg1, high = 0;
3910           break;
3911         case LT_EXPR:  /* - [c, -] */
3912           low = arg1, high = 0;
3913           break;
3914         case LE_EXPR:  /* + [-, c] */
3915           in_p = ! in_p, low = 0, high = arg1;
3916           break;
3917         default:
3918           gcc_unreachable ();
3919         }
3920
3921       /* If this is an unsigned comparison, we also know that EXP is
3922          greater than or equal to zero.  We base the range tests we make
3923          on that fact, so we record it here so we can parse existing
3924          range tests.  We test arg0_type since often the return type
3925          of, e.g. EQ_EXPR, is boolean.  */
3926       if (TYPE_UNSIGNED (arg0_type) && (low == 0 || high == 0))
3927         {
3928           if (! merge_ranges (&n_in_p, &n_low, &n_high,
3929                               in_p, low, high, 1,
3930                               build_int_cst (arg0_type, 0),
3931                               NULL_TREE))
3932             return NULL_TREE;
3933
3934           in_p = n_in_p, low = n_low, high = n_high;
3935
3936           /* If the high bound is missing, but we have a nonzero low
3937              bound, reverse the range so it goes from zero to the low bound
3938              minus 1.  */
3939           if (high == 0 && low && ! integer_zerop (low))
3940             {
3941               in_p = ! in_p;
3942               high = range_binop (MINUS_EXPR, NULL_TREE, low, 0,
3943                                   build_int_cst (TREE_TYPE (low), 1), 0);
3944               low = build_int_cst (arg0_type, 0);
3945             }
3946         }
3947
3948       *p_low = low;
3949       *p_high = high;
3950       *p_in_p = in_p;
3951       return arg0;
3952
3953     case NEGATE_EXPR:
3954       /* If flag_wrapv and ARG0_TYPE is signed, make sure
3955          low and high are non-NULL, then normalize will DTRT.  */
3956       if (!TYPE_UNSIGNED (arg0_type)
3957           && !TYPE_OVERFLOW_UNDEFINED (arg0_type))
3958         {
3959           if (low == NULL_TREE)
3960             low = TYPE_MIN_VALUE (arg0_type);
3961           if (high == NULL_TREE)
3962             high = TYPE_MAX_VALUE (arg0_type);
3963         }
3964
3965       /* (-x) IN [a,b] -> x in [-b, -a]  */
3966       n_low = range_binop (MINUS_EXPR, exp_type,
3967                            build_int_cst (exp_type, 0),
3968                            0, high, 1);
3969       n_high = range_binop (MINUS_EXPR, exp_type,
3970                             build_int_cst (exp_type, 0),
3971                             0, low, 0);
3972       if (n_high != 0 && TREE_OVERFLOW (n_high))
3973         return NULL_TREE;
3974       goto normalize;
3975
3976     case BIT_NOT_EXPR:
3977       /* ~ X -> -X - 1  */
3978       return build2_loc (loc, MINUS_EXPR, exp_type, negate_expr (arg0),
3979                          build_int_cst (exp_type, 1));
3980
3981     case PLUS_EXPR:
3982     case MINUS_EXPR:
3983       if (TREE_CODE (arg1) != INTEGER_CST)
3984         return NULL_TREE;
3985
3986       /* If flag_wrapv and ARG0_TYPE is signed, then we cannot
3987          move a constant to the other side.  */
3988       if (!TYPE_UNSIGNED (arg0_type)
3989           && !TYPE_OVERFLOW_UNDEFINED (arg0_type))
3990         return NULL_TREE;
3991
3992       /* If EXP is signed, any overflow in the computation is undefined,
3993          so we don't worry about it so long as our computations on
3994          the bounds don't overflow.  For unsigned, overflow is defined
3995          and this is exactly the right thing.  */
3996       n_low = range_binop (code == MINUS_EXPR ? PLUS_EXPR : MINUS_EXPR,
3997                            arg0_type, low, 0, arg1, 0);
3998       n_high = range_binop (code == MINUS_EXPR ? PLUS_EXPR : MINUS_EXPR,
3999                             arg0_type, high, 1, arg1, 0);
4000       if ((n_low != 0 && TREE_OVERFLOW (n_low))
4001           || (n_high != 0 && TREE_OVERFLOW (n_high)))
4002         return NULL_TREE;
4003
4004       if (TYPE_OVERFLOW_UNDEFINED (arg0_type))
4005         *strict_overflow_p = true;
4006
4007       normalize:
4008         /* Check for an unsigned range which has wrapped around the maximum
4009            value thus making n_high < n_low, and normalize it.  */
4010         if (n_low && n_high && tree_int_cst_lt (n_high, n_low))
4011           {
4012             low = range_binop (PLUS_EXPR, arg0_type, n_high, 0,
4013                                build_int_cst (TREE_TYPE (n_high), 1), 0);
4014             high = range_binop (MINUS_EXPR, arg0_type, n_low, 0,
4015                                 build_int_cst (TREE_TYPE (n_low), 1), 0);
4016
4017             /* If the range is of the form +/- [ x+1, x ], we won't
4018                be able to normalize it.  But then, it represents the
4019                whole range or the empty set, so make it
4020                +/- [ -, - ].  */
4021             if (tree_int_cst_equal (n_low, low)
4022                 && tree_int_cst_equal (n_high, high))
4023               low = high = 0;
4024             else
4025               in_p = ! in_p;
4026           }
4027         else
4028           low = n_low, high = n_high;
4029
4030         *p_low = low;
4031         *p_high = high;
4032         *p_in_p = in_p;
4033         return arg0;
4034
4035     CASE_CONVERT:
4036     case NON_LVALUE_EXPR:
4037       if (TYPE_PRECISION (arg0_type) > TYPE_PRECISION (exp_type))
4038         return NULL_TREE;
4039
4040       if (! INTEGRAL_TYPE_P (arg0_type)
4041           || (low != 0 && ! int_fits_type_p (low, arg0_type))
4042           || (high != 0 && ! int_fits_type_p (high, arg0_type)))
4043         return NULL_TREE;
4044
4045       n_low = low, n_high = high;
4046
4047       if (n_low != 0)
4048         n_low = fold_convert_loc (loc, arg0_type, n_low);
4049
4050       if (n_high != 0)
4051         n_high = fold_convert_loc (loc, arg0_type, n_high);
4052
4053       /* If we're converting arg0 from an unsigned type, to exp,
4054          a signed type,  we will be doing the comparison as unsigned.
4055          The tests above have already verified that LOW and HIGH
4056          are both positive.
4057
4058          So we have to ensure that we will handle large unsigned
4059          values the same way that the current signed bounds treat
4060          negative values.  */
4061
4062       if (!TYPE_UNSIGNED (exp_type) && TYPE_UNSIGNED (arg0_type))
4063         {
4064           tree high_positive;
4065           tree equiv_type;
4066           /* For fixed-point modes, we need to pass the saturating flag
4067              as the 2nd parameter.  */
4068           if (ALL_FIXED_POINT_MODE_P (TYPE_MODE (arg0_type)))
4069             equiv_type
4070               = lang_hooks.types.type_for_mode (TYPE_MODE (arg0_type),
4071                                                 TYPE_SATURATING (arg0_type));
4072           else
4073             equiv_type
4074               = lang_hooks.types.type_for_mode (TYPE_MODE (arg0_type), 1);
4075
4076           /* A range without an upper bound is, naturally, unbounded.
4077              Since convert would have cropped a very large value, use
4078              the max value for the destination type.  */
4079           high_positive
4080             = TYPE_MAX_VALUE (equiv_type) ? TYPE_MAX_VALUE (equiv_type)
4081               : TYPE_MAX_VALUE (arg0_type);
4082
4083           if (TYPE_PRECISION (exp_type) == TYPE_PRECISION (arg0_type))
4084             high_positive = fold_build2_loc (loc, RSHIFT_EXPR, arg0_type,
4085                                              fold_convert_loc (loc, arg0_type,
4086                                                                high_positive),
4087                                              build_int_cst (arg0_type, 1));
4088
4089           /* If the low bound is specified, "and" the range with the
4090              range for which the original unsigned value will be
4091              positive.  */
4092           if (low != 0)
4093             {
4094               if (! merge_ranges (&n_in_p, &n_low, &n_high, 1, n_low, n_high,
4095                                   1, fold_convert_loc (loc, arg0_type,
4096                                                        integer_zero_node),
4097                                   high_positive))
4098                 return NULL_TREE;
4099
4100               in_p = (n_in_p == in_p);
4101             }
4102           else
4103             {
4104               /* Otherwise, "or" the range with the range of the input
4105                  that will be interpreted as negative.  */
4106               if (! merge_ranges (&n_in_p, &n_low, &n_high, 0, n_low, n_high,
4107                                   1, fold_convert_loc (loc, arg0_type,
4108                                                        integer_zero_node),
4109                                   high_positive))
4110                 return NULL_TREE;
4111
4112               in_p = (in_p != n_in_p);
4113             }
4114         }
4115
4116       *p_low = n_low;
4117       *p_high = n_high;
4118       *p_in_p = in_p;
4119       return arg0;
4120
4121     default:
4122       return NULL_TREE;
4123     }
4124 }
4125
4126 /* Given EXP, a logical expression, set the range it is testing into
4127    variables denoted by PIN_P, PLOW, and PHIGH.  Return the expression
4128    actually being tested.  *PLOW and *PHIGH will be made of the same
4129    type as the returned expression.  If EXP is not a comparison, we
4130    will most likely not be returning a useful value and range.  Set
4131    *STRICT_OVERFLOW_P to true if the return value is only valid
4132    because signed overflow is undefined; otherwise, do not change
4133    *STRICT_OVERFLOW_P.  */
4134
4135 tree
4136 make_range (tree exp, int *pin_p, tree *plow, tree *phigh,
4137             bool *strict_overflow_p)
4138 {
4139   enum tree_code code;
4140   tree arg0, arg1 = NULL_TREE;
4141   tree exp_type, nexp;
4142   int in_p;
4143   tree low, high;
4144   location_t loc = EXPR_LOCATION (exp);
4145
4146   /* Start with simply saying "EXP != 0" and then look at the code of EXP
4147      and see if we can refine the range.  Some of the cases below may not
4148      happen, but it doesn't seem worth worrying about this.  We "continue"
4149      the outer loop when we've changed something; otherwise we "break"
4150      the switch, which will "break" the while.  */
4151
4152   in_p = 0;
4153   low = high = build_int_cst (TREE_TYPE (exp), 0);
4154
4155   while (1)
4156     {
4157       code = TREE_CODE (exp);
4158       exp_type = TREE_TYPE (exp);
4159       arg0 = NULL_TREE;
4160
4161       if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (code)))
4162         {
4163           if (TREE_OPERAND_LENGTH (exp) > 0)
4164             arg0 = TREE_OPERAND (exp, 0);
4165           if (TREE_CODE_CLASS (code) == tcc_binary
4166               || TREE_CODE_CLASS (code) == tcc_comparison
4167               || (TREE_CODE_CLASS (code) == tcc_expression
4168                   && TREE_OPERAND_LENGTH (exp) > 1))
4169             arg1 = TREE_OPERAND (exp, 1);
4170         }
4171       if (arg0 == NULL_TREE)
4172         break;
4173
4174       nexp = make_range_step (loc, code, arg0, arg1, exp_type, &low,
4175                               &high, &in_p, strict_overflow_p);
4176       if (nexp == NULL_TREE)
4177         break;
4178       exp = nexp;
4179     }
4180
4181   /* If EXP is a constant, we can evaluate whether this is true or false.  */
4182   if (TREE_CODE (exp) == INTEGER_CST)
4183     {
4184       in_p = in_p == (integer_onep (range_binop (GE_EXPR, integer_type_node,
4185                                                  exp, 0, low, 0))
4186                       && integer_onep (range_binop (LE_EXPR, integer_type_node,
4187                                                     exp, 1, high, 1)));
4188       low = high = 0;
4189       exp = 0;
4190     }
4191
4192   *pin_p = in_p, *plow = low, *phigh = high;
4193   return exp;
4194 }
4195 \f
4196 /* Given a range, LOW, HIGH, and IN_P, an expression, EXP, and a result
4197    type, TYPE, return an expression to test if EXP is in (or out of, depending
4198    on IN_P) the range.  Return 0 if the test couldn't be created.  */
4199
4200 tree
4201 build_range_check (location_t loc, tree type, tree exp, int in_p,
4202                    tree low, tree high)
4203 {
4204   tree etype = TREE_TYPE (exp), value;
4205
4206 #ifdef HAVE_canonicalize_funcptr_for_compare
4207   /* Disable this optimization for function pointer expressions
4208      on targets that require function pointer canonicalization.  */
4209   if (HAVE_canonicalize_funcptr_for_compare
4210       && TREE_CODE (etype) == POINTER_TYPE
4211       && TREE_CODE (TREE_TYPE (etype)) == FUNCTION_TYPE)
4212     return NULL_TREE;
4213 #endif
4214
4215   if (! in_p)
4216     {
4217       value = build_range_check (loc, type, exp, 1, low, high);
4218       if (value != 0)
4219         return invert_truthvalue_loc (loc, value);
4220
4221       return 0;
4222     }
4223
4224   if (low == 0 && high == 0)
4225     return omit_one_operand_loc (loc, type, build_int_cst (type, 1), exp);
4226
4227   if (low == 0)
4228     return fold_build2_loc (loc, LE_EXPR, type, exp,
4229                         fold_convert_loc (loc, etype, high));
4230
4231   if (high == 0)
4232     return fold_build2_loc (loc, GE_EXPR, type, exp,
4233                         fold_convert_loc (loc, etype, low));
4234
4235   if (operand_equal_p (low, high, 0))
4236     return fold_build2_loc (loc, EQ_EXPR, type, exp,
4237                         fold_convert_loc (loc, etype, low));
4238
4239   if (integer_zerop (low))
4240     {
4241       if (! TYPE_UNSIGNED (etype))
4242         {
4243           etype = unsigned_type_for (etype);
4244           high = fold_convert_loc (loc, etype, high);
4245           exp = fold_convert_loc (loc, etype, exp);
4246         }
4247       return build_range_check (loc, type, exp, 1, 0, high);
4248     }
4249
4250   /* Optimize (c>=1) && (c<=127) into (signed char)c > 0.  */
4251   if (integer_onep (low) && TREE_CODE (high) == INTEGER_CST)
4252     {
4253       int prec = TYPE_PRECISION (etype);
4254
4255       if (wi::mask (prec - 1, false, prec) == high)
4256         {
4257           if (TYPE_UNSIGNED (etype))
4258             {
4259               tree signed_etype = signed_type_for (etype);
4260               if (TYPE_PRECISION (signed_etype) != TYPE_PRECISION (etype))
4261                 etype
4262                   = build_nonstandard_integer_type (TYPE_PRECISION (etype), 0);
4263               else
4264                 etype = signed_etype;
4265               exp = fold_convert_loc (loc, etype, exp);
4266             }
4267           return fold_build2_loc (loc, GT_EXPR, type, exp,
4268                               build_int_cst (etype, 0));
4269         }
4270     }
4271
4272   /* Optimize (c>=low) && (c<=high) into (c-low>=0) && (c-low<=high-low).
4273      This requires wrap-around arithmetics for the type of the expression.
4274      First make sure that arithmetics in this type is valid, then make sure
4275      that it wraps around.  */
4276   if (TREE_CODE (etype) == ENUMERAL_TYPE || TREE_CODE (etype) == BOOLEAN_TYPE)
4277     etype = lang_hooks.types.type_for_size (TYPE_PRECISION (etype),
4278                                             TYPE_UNSIGNED (etype));
4279
4280   if (TREE_CODE (etype) == INTEGER_TYPE && !TYPE_OVERFLOW_WRAPS (etype))
4281     {
4282       tree utype, minv, maxv;
4283
4284       /* Check if (unsigned) INT_MAX + 1 == (unsigned) INT_MIN
4285          for the type in question, as we rely on this here.  */
4286       utype = unsigned_type_for (etype);
4287       maxv = fold_convert_loc (loc, utype, TYPE_MAX_VALUE (etype));
4288       maxv = range_binop (PLUS_EXPR, NULL_TREE, maxv, 1,
4289                           build_int_cst (TREE_TYPE (maxv), 1), 1);
4290       minv = fold_convert_loc (loc, utype, TYPE_MIN_VALUE (etype));
4291
4292       if (integer_zerop (range_binop (NE_EXPR, integer_type_node,
4293                                       minv, 1, maxv, 1)))
4294         etype = utype;
4295       else
4296         return 0;
4297     }
4298
4299   high = fold_convert_loc (loc, etype, high);
4300   low = fold_convert_loc (loc, etype, low);
4301   exp = fold_convert_loc (loc, etype, exp);
4302
4303   value = const_binop (MINUS_EXPR, high, low);
4304
4305
4306   if (POINTER_TYPE_P (etype))
4307     {
4308       if (value != 0 && !TREE_OVERFLOW (value))
4309         {
4310           low = fold_build1_loc (loc, NEGATE_EXPR, TREE_TYPE (low), low);
4311           return build_range_check (loc, type,
4312                                     fold_build_pointer_plus_loc (loc, exp, low),
4313                                     1, build_int_cst (etype, 0), value);
4314         }
4315       return 0;
4316     }
4317
4318   if (value != 0 && !TREE_OVERFLOW (value))
4319     return build_range_check (loc, type,
4320                               fold_build2_loc (loc, MINUS_EXPR, etype, exp, low),
4321                               1, build_int_cst (etype, 0), value);
4322
4323   return 0;
4324 }
4325 \f
4326 /* Return the predecessor of VAL in its type, handling the infinite case.  */
4327
4328 static tree
4329 range_predecessor (tree val)
4330 {
4331   tree type = TREE_TYPE (val);
4332
4333   if (INTEGRAL_TYPE_P (type)
4334       && operand_equal_p (val, TYPE_MIN_VALUE (type), 0))
4335     return 0;
4336   else
4337     return range_binop (MINUS_EXPR, NULL_TREE, val, 0,
4338                         build_int_cst (TREE_TYPE (val), 1), 0);
4339 }
4340
4341 /* Return the successor of VAL in its type, handling the infinite case.  */
4342
4343 static tree
4344 range_successor (tree val)
4345 {
4346   tree type = TREE_TYPE (val);
4347
4348   if (INTEGRAL_TYPE_P (type)
4349       && operand_equal_p (val, TYPE_MAX_VALUE (type), 0))
4350     return 0;
4351   else
4352     return range_binop (PLUS_EXPR, NULL_TREE, val, 0,
4353                         build_int_cst (TREE_TYPE (val), 1), 0);
4354 }
4355
4356 /* Given two ranges, see if we can merge them into one.  Return 1 if we
4357    can, 0 if we can't.  Set the output range into the specified parameters.  */
4358
4359 bool
4360 merge_ranges (int *pin_p, tree *plow, tree *phigh, int in0_p, tree low0,
4361               tree high0, int in1_p, tree low1, tree high1)
4362 {
4363   int no_overlap;
4364   int subset;
4365   int temp;
4366   tree tem;
4367   int in_p;
4368   tree low, high;
4369   int lowequal = ((low0 == 0 && low1 == 0)
4370                   || integer_onep (range_binop (EQ_EXPR, integer_type_node,
4371                                                 low0, 0, low1, 0)));
4372   int highequal = ((high0 == 0 && high1 == 0)
4373                    || integer_onep (range_binop (EQ_EXPR, integer_type_node,
4374                                                  high0, 1, high1, 1)));
4375
4376   /* Make range 0 be the range that starts first, or ends last if they
4377      start at the same value.  Swap them if it isn't.  */
4378   if (integer_onep (range_binop (GT_EXPR, integer_type_node,
4379                                  low0, 0, low1, 0))
4380       || (lowequal
4381           && integer_onep (range_binop (GT_EXPR, integer_type_node,
4382                                         high1, 1, high0, 1))))
4383     {
4384       temp = in0_p, in0_p = in1_p, in1_p = temp;
4385       tem = low0, low0 = low1, low1 = tem;
4386       tem = high0, high0 = high1, high1 = tem;
4387     }
4388
4389   /* Now flag two cases, whether the ranges are disjoint or whether the
4390      second range is totally subsumed in the first.  Note that the tests
4391      below are simplified by the ones above.  */
4392   no_overlap = integer_onep (range_binop (LT_EXPR, integer_type_node,
4393                                           high0, 1, low1, 0));
4394   subset = integer_onep (range_binop (LE_EXPR, integer_type_node,
4395                                       high1, 1, high0, 1));
4396
4397   /* We now have four cases, depending on whether we are including or
4398      excluding the two ranges.  */
4399   if (in0_p && in1_p)
4400     {
4401       /* If they don't overlap, the result is false.  If the second range
4402          is a subset it is the result.  Otherwise, the range is from the start
4403          of the second to the end of the first.  */
4404       if (no_overlap)
4405         in_p = 0, low = high = 0;
4406       else if (subset)
4407         in_p = 1, low = low1, high = high1;
4408       else
4409         in_p = 1, low = low1, high = high0;
4410     }
4411
4412   else if (in0_p && ! in1_p)
4413     {
4414       /* If they don't overlap, the result is the first range.  If they are
4415          equal, the result is false.  If the second range is a subset of the
4416          first, and the ranges begin at the same place, we go from just after
4417          the end of the second range to the end of the first.  If the second
4418          range is not a subset of the first, or if it is a subset and both
4419          ranges end at the same place, the range starts at the start of the
4420          first range and ends just before the second range.
4421          Otherwise, we can't describe this as a single range.  */
4422       if (no_overlap)
4423         in_p = 1, low = low0, high = high0;
4424       else if (lowequal && highequal)
4425         in_p = 0, low = high = 0;
4426       else if (subset && lowequal)
4427         {
4428           low = range_successor (high1);
4429           high = high0;
4430           in_p = 1;
4431           if (low == 0)
4432             {
4433               /* We are in the weird situation where high0 > high1 but
4434                  high1 has no successor.  Punt.  */
4435               return 0;
4436             }
4437         }
4438       else if (! subset || highequal)
4439         {
4440           low = low0;
4441           high = range_predecessor (low1);
4442           in_p = 1;
4443           if (high == 0)
4444             {
4445               /* low0 < low1 but low1 has no predecessor.  Punt.  */
4446               return 0;
4447             }
4448         }
4449       else
4450         return 0;
4451     }
4452
4453   else if (! in0_p && in1_p)
4454     {
4455       /* If they don't overlap, the result is the second range.  If the second
4456          is a subset of the first, the result is false.  Otherwise,
4457          the range starts just after the first range and ends at the
4458          end of the second.  */
4459       if (no_overlap)
4460         in_p = 1, low = low1, high = high1;
4461       else if (subset || highequal)
4462         in_p = 0, low = high = 0;
4463       else
4464         {
4465           low = range_successor (high0);
4466           high = high1;
4467           in_p = 1;
4468           if (low == 0)
4469             {
4470               /* high1 > high0 but high0 has no successor.  Punt.  */
4471               return 0;
4472             }
4473         }
4474     }
4475
4476   else
4477     {
4478       /* The case where we are excluding both ranges.  Here the complex case
4479          is if they don't overlap.  In that case, the only time we have a
4480          range is if they are adjacent.  If the second is a subset of the
4481          first, the result is the first.  Otherwise, the range to exclude
4482          starts at the beginning of the first range and ends at the end of the
4483          second.  */
4484       if (no_overlap)
4485         {
4486           if (integer_onep (range_binop (EQ_EXPR, integer_type_node,
4487                                          range_successor (high0),
4488                                          1, low1, 0)))
4489             in_p = 0, low = low0, high = high1;
4490           else
4491             {
4492               /* Canonicalize - [min, x] into - [-, x].  */
4493               if (low0 && TREE_CODE (low0) == INTEGER_CST)
4494                 switch (TREE_CODE (TREE_TYPE (low0)))
4495                   {
4496                   case ENUMERAL_TYPE:
4497                     if (TYPE_PRECISION (TREE_TYPE (low0))
4498                         != GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE (low0))))
4499                       break;
4500                     /* FALLTHROUGH */
4501                   case INTEGER_TYPE:
4502                     if (tree_int_cst_equal (low0,
4503                                             TYPE_MIN_VALUE (TREE_TYPE (low0))))
4504                       low0 = 0;
4505                     break;
4506                   case POINTER_TYPE:
4507                     if (TYPE_UNSIGNED (TREE_TYPE (low0))
4508                         && integer_zerop (low0))
4509                       low0 = 0;
4510                     break;
4511                   default:
4512                     break;
4513                   }
4514
4515               /* Canonicalize - [x, max] into - [x, -].  */
4516               if (high1 && TREE_CODE (high1) == INTEGER_CST)
4517                 switch (TREE_CODE (TREE_TYPE (high1)))
4518                   {
4519                   case ENUMERAL_TYPE:
4520                     if (TYPE_PRECISION (TREE_TYPE (high1))
4521                         != GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE (high1))))
4522                       break;
4523                     /* FALLTHROUGH */
4524                   case INTEGER_TYPE:
4525                     if (tree_int_cst_equal (high1,
4526                                             TYPE_MAX_VALUE (TREE_TYPE (high1))))
4527                       high1 = 0;
4528                     break;
4529                   case POINTER_TYPE:
4530                     if (TYPE_UNSIGNED (TREE_TYPE (high1))
4531                         && integer_zerop (range_binop (PLUS_EXPR, NULL_TREE,
4532                                                        high1, 1,
4533                                                        build_int_cst (TREE_TYPE (high1), 1),
4534                                                        1)))
4535                       high1 = 0;
4536                     break;
4537                   default:
4538                     break;
4539                   }
4540
4541               /* The ranges might be also adjacent between the maximum and
4542                  minimum values of the given type.  For
4543                  - [{min,-}, x] and - [y, {max,-}] ranges where x + 1 < y
4544                  return + [x + 1, y - 1].  */
4545               if (low0 == 0 && high1 == 0)
4546                 {
4547                   low = range_successor (high0);
4548                   high = range_predecessor (low1);
4549                   if (low == 0 || high == 0)
4550                     return 0;
4551
4552                   in_p = 1;
4553                 }
4554               else
4555                 return 0;
4556             }
4557         }
4558       else if (subset)
4559         in_p = 0, low = low0, high = high0;
4560       else
4561         in_p = 0, low = low0, high = high1;
4562     }
4563
4564   *pin_p = in_p, *plow = low, *phigh = high;
4565   return 1;
4566 }
4567 \f
4568
4569 /* Subroutine of fold, looking inside expressions of the form
4570    A op B ? A : C, where ARG0, ARG1 and ARG2 are the three operands
4571    of the COND_EXPR.  This function is being used also to optimize
4572    A op B ? C : A, by reversing the comparison first.
4573
4574    Return a folded expression whose code is not a COND_EXPR
4575    anymore, or NULL_TREE if no folding opportunity is found.  */
4576
4577 static tree
4578 fold_cond_expr_with_comparison (location_t loc, tree type,
4579                                 tree arg0, tree arg1, tree arg2)
4580 {
4581   enum tree_code comp_code = TREE_CODE (arg0);
4582   tree arg00 = TREE_OPERAND (arg0, 0);
4583   tree arg01 = TREE_OPERAND (arg0, 1);
4584   tree arg1_type = TREE_TYPE (arg1);
4585   tree tem;
4586
4587   STRIP_NOPS (arg1);
4588   STRIP_NOPS (arg2);
4589
4590   /* If we have A op 0 ? A : -A, consider applying the following
4591      transformations:
4592
4593      A == 0? A : -A    same as -A
4594      A != 0? A : -A    same as A
4595      A >= 0? A : -A    same as abs (A)
4596      A > 0?  A : -A    same as abs (A)
4597      A <= 0? A : -A    same as -abs (A)
4598      A < 0?  A : -A    same as -abs (A)
4599
4600      None of these transformations work for modes with signed
4601      zeros.  If A is +/-0, the first two transformations will
4602      change the sign of the result (from +0 to -0, or vice
4603      versa).  The last four will fix the sign of the result,
4604      even though the original expressions could be positive or
4605      negative, depending on the sign of A.
4606
4607      Note that all these transformations are correct if A is
4608      NaN, since the two alternatives (A and -A) are also NaNs.  */
4609   if (!HONOR_SIGNED_ZEROS (TYPE_MODE (type))
4610       && (FLOAT_TYPE_P (TREE_TYPE (arg01))
4611           ? real_zerop (arg01)
4612           : integer_zerop (arg01))
4613       && ((TREE_CODE (arg2) == NEGATE_EXPR
4614            && operand_equal_p (TREE_OPERAND (arg2, 0), arg1, 0))
4615              /* In the case that A is of the form X-Y, '-A' (arg2) may
4616                 have already been folded to Y-X, check for that. */
4617           || (TREE_CODE (arg1) == MINUS_EXPR
4618               && TREE_CODE (arg2) == MINUS_EXPR
4619               && operand_equal_p (TREE_OPERAND (arg1, 0),
4620                                   TREE_OPERAND (arg2, 1), 0)
4621               && operand_equal_p (TREE_OPERAND (arg1, 1),
4622                                   TREE_OPERAND (arg2, 0), 0))))
4623     switch (comp_code)
4624       {
4625       case EQ_EXPR:
4626       case UNEQ_EXPR:
4627         tem = fold_convert_loc (loc, arg1_type, arg1);
4628         return pedantic_non_lvalue_loc (loc,
4629                                     fold_convert_loc (loc, type,
4630                                                   negate_expr (tem)));
4631       case NE_EXPR:
4632       case LTGT_EXPR:
4633         return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, arg1));
4634       case UNGE_EXPR:
4635       case UNGT_EXPR:
4636         if (flag_trapping_math)
4637           break;
4638         /* Fall through.  */
4639       case GE_EXPR:
4640       case GT_EXPR:
4641         if (TYPE_UNSIGNED (TREE_TYPE (arg1)))
4642           arg1 = fold_convert_loc (loc, signed_type_for
4643                                (TREE_TYPE (arg1)), arg1);
4644         tem = fold_build1_loc (loc, ABS_EXPR, TREE_TYPE (arg1), arg1);
4645         return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, tem));
4646       case UNLE_EXPR:
4647       case UNLT_EXPR:
4648         if (flag_trapping_math)
4649           break;
4650       case LE_EXPR:
4651       case LT_EXPR:
4652         if (TYPE_UNSIGNED (TREE_TYPE (arg1)))
4653           arg1 = fold_convert_loc (loc, signed_type_for
4654                                (TREE_TYPE (arg1)), arg1);
4655         tem = fold_build1_loc (loc, ABS_EXPR, TREE_TYPE (arg1), arg1);
4656         return negate_expr (fold_convert_loc (loc, type, tem));
4657       default:
4658         gcc_assert (TREE_CODE_CLASS (comp_code) == tcc_comparison);
4659         break;
4660       }
4661
4662   /* A != 0 ? A : 0 is simply A, unless A is -0.  Likewise
4663      A == 0 ? A : 0 is always 0 unless A is -0.  Note that
4664      both transformations are correct when A is NaN: A != 0
4665      is then true, and A == 0 is false.  */
4666
4667   if (!HONOR_SIGNED_ZEROS (TYPE_MODE (type))
4668       && integer_zerop (arg01) && integer_zerop (arg2))
4669     {
4670       if (comp_code == NE_EXPR)
4671         return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, arg1));
4672       else if (comp_code == EQ_EXPR)
4673         return build_zero_cst (type);
4674     }
4675
4676   /* Try some transformations of A op B ? A : B.
4677
4678      A == B? A : B    same as B
4679      A != B? A : B    same as A
4680      A >= B? A : B    same as max (A, B)
4681      A > B?  A : B    same as max (B, A)
4682      A <= B? A : B    same as min (A, B)
4683      A < B?  A : B    same as min (B, A)
4684
4685      As above, these transformations don't work in the presence
4686      of signed zeros.  For example, if A and B are zeros of
4687      opposite sign, the first two transformations will change
4688      the sign of the result.  In the last four, the original
4689      expressions give different results for (A=+0, B=-0) and
4690      (A=-0, B=+0), but the transformed expressions do not.
4691
4692      The first two transformations are correct if either A or B
4693      is a NaN.  In the first transformation, the condition will
4694      be false, and B will indeed be chosen.  In the case of the
4695      second transformation, the condition A != B will be true,
4696      and A will be chosen.
4697
4698      The conversions to max() and min() are not correct if B is
4699      a number and A is not.  The conditions in the original
4700      expressions will be false, so all four give B.  The min()
4701      and max() versions would give a NaN instead.  */
4702   if (!HONOR_SIGNED_ZEROS (TYPE_MODE (type))
4703       && operand_equal_for_comparison_p (arg01, arg2, arg00)
4704       /* Avoid these transformations if the COND_EXPR may be used
4705          as an lvalue in the C++ front-end.  PR c++/19199.  */
4706       && (in_gimple_form
4707           || VECTOR_TYPE_P (type)
4708           || (strcmp (lang_hooks.name, "GNU C++") != 0
4709               && strcmp (lang_hooks.name, "GNU Objective-C++") != 0)
4710           || ! maybe_lvalue_p (arg1)
4711           || ! maybe_lvalue_p (arg2)))
4712     {
4713       tree comp_op0 = arg00;
4714       tree comp_op1 = arg01;
4715       tree comp_type = TREE_TYPE (comp_op0);
4716
4717       /* Avoid adding NOP_EXPRs in case this is an lvalue.  */
4718       if (TYPE_MAIN_VARIANT (comp_type) == TYPE_MAIN_VARIANT (type))
4719         {
4720           comp_type = type;
4721           comp_op0 = arg1;
4722           comp_op1 = arg2;
4723         }
4724
4725       switch (comp_code)
4726         {
4727         case EQ_EXPR:
4728           return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, arg2));
4729         case NE_EXPR:
4730           return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, arg1));
4731         case LE_EXPR:
4732         case LT_EXPR:
4733         case UNLE_EXPR:
4734         case UNLT_EXPR:
4735           /* In C++ a ?: expression can be an lvalue, so put the
4736              operand which will be used if they are equal first
4737              so that we can convert this back to the
4738              corresponding COND_EXPR.  */
4739           if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg1))))
4740             {
4741               comp_op0 = fold_convert_loc (loc, comp_type, comp_op0);
4742               comp_op1 = fold_convert_loc (loc, comp_type, comp_op1);
4743               tem = (comp_code == LE_EXPR || comp_code == UNLE_EXPR)
4744                     ? fold_build2_loc (loc, MIN_EXPR, comp_type, comp_op0, comp_op1)
4745                     : fold_build2_loc (loc, MIN_EXPR, comp_type,
4746                                    comp_op1, comp_op0);
4747               return pedantic_non_lvalue_loc (loc,
4748                                           fold_convert_loc (loc, type, tem));
4749             }
4750           break;
4751         case GE_EXPR:
4752         case GT_EXPR:
4753         case UNGE_EXPR:
4754         case UNGT_EXPR:
4755           if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg1))))
4756             {
4757               comp_op0 = fold_convert_loc (loc, comp_type, comp_op0);
4758               comp_op1 = fold_convert_loc (loc, comp_type, comp_op1);
4759               tem = (comp_code == GE_EXPR || comp_code == UNGE_EXPR)
4760                     ? fold_build2_loc (loc, MAX_EXPR, comp_type, comp_op0, comp_op1)
4761                     : fold_build2_loc (loc, MAX_EXPR, comp_type,
4762                                    comp_op1, comp_op0);
4763               return pedantic_non_lvalue_loc (loc,
4764                                           fold_convert_loc (loc, type, tem));
4765             }
4766           break;
4767         case UNEQ_EXPR:
4768           if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg1))))
4769             return pedantic_non_lvalue_loc (loc,
4770                                         fold_convert_loc (loc, type, arg2));
4771           break;
4772         case LTGT_EXPR:
4773           if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg1))))
4774             return pedantic_non_lvalue_loc (loc,
4775                                         fold_convert_loc (loc, type, arg1));
4776           break;
4777         default:
4778           gcc_assert (TREE_CODE_CLASS (comp_code) == tcc_comparison);
4779           break;
4780         }
4781     }
4782
4783   /* If this is A op C1 ? A : C2 with C1 and C2 constant integers,
4784      we might still be able to simplify this.  For example,
4785      if C1 is one less or one more than C2, this might have started
4786      out as a MIN or MAX and been transformed by this function.
4787      Only good for INTEGER_TYPEs, because we need TYPE_MAX_VALUE.  */
4788
4789   if (INTEGRAL_TYPE_P (type)
4790       && TREE_CODE (arg01) == INTEGER_CST
4791       && TREE_CODE (arg2) == INTEGER_CST)
4792     switch (comp_code)
4793       {
4794       case EQ_EXPR:
4795         if (TREE_CODE (arg1) == INTEGER_CST)
4796           break;
4797         /* We can replace A with C1 in this case.  */
4798         arg1 = fold_convert_loc (loc, type, arg01);
4799         return fold_build3_loc (loc, COND_EXPR, type, arg0, arg1, arg2);
4800
4801       case LT_EXPR:
4802         /* If C1 is C2 + 1, this is min(A, C2), but use ARG00's type for
4803            MIN_EXPR, to preserve the signedness of the comparison.  */
4804         if (! operand_equal_p (arg2, TYPE_MAX_VALUE (type),
4805                                OEP_ONLY_CONST)
4806             && operand_equal_p (arg01,
4807                                 const_binop (PLUS_EXPR, arg2,
4808                                              build_int_cst (type, 1)),
4809                                 OEP_ONLY_CONST))
4810           {
4811             tem = fold_build2_loc (loc, MIN_EXPR, TREE_TYPE (arg00), arg00,
4812                                    fold_convert_loc (loc, TREE_TYPE (arg00),
4813                                                      arg2));
4814             return pedantic_non_lvalue_loc (loc,
4815                                             fold_convert_loc (loc, type, tem));
4816           }
4817         break;
4818
4819       case LE_EXPR:
4820         /* If C1 is C2 - 1, this is min(A, C2), with the same care
4821            as above.  */
4822         if (! operand_equal_p (arg2, TYPE_MIN_VALUE (type),
4823                                OEP_ONLY_CONST)
4824             && operand_equal_p (arg01,
4825                                 const_binop (MINUS_EXPR, arg2,
4826                                              build_int_cst (type, 1)),
4827                                 OEP_ONLY_CONST))
4828           {
4829             tem = fold_build2_loc (loc, MIN_EXPR, TREE_TYPE (arg00), arg00,
4830                                    fold_convert_loc (loc, TREE_TYPE (arg00),
4831                                                      arg2));
4832             return pedantic_non_lvalue_loc (loc,
4833                                             fold_convert_loc (loc, type, tem));
4834           }
4835         break;
4836
4837       case GT_EXPR:
4838         /* If C1 is C2 - 1, this is max(A, C2), but use ARG00's type for
4839            MAX_EXPR, to preserve the signedness of the comparison.  */
4840         if (! operand_equal_p (arg2, TYPE_MIN_VALUE (type),
4841                                OEP_ONLY_CONST)
4842             && operand_equal_p (arg01,
4843                                 const_binop (MINUS_EXPR, arg2,
4844                                              build_int_cst (type, 1)),
4845                                 OEP_ONLY_CONST))
4846           {
4847             tem = fold_build2_loc (loc, MAX_EXPR, TREE_TYPE (arg00), arg00,
4848                                    fold_convert_loc (loc, TREE_TYPE (arg00),
4849                                                      arg2));
4850             return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, tem));
4851           }
4852         break;
4853
4854       case GE_EXPR:
4855         /* If C1 is C2 + 1, this is max(A, C2), with the same care as above.  */
4856         if (! operand_equal_p (arg2, TYPE_MAX_VALUE (type),
4857                                OEP_ONLY_CONST)
4858             && operand_equal_p (arg01,
4859                                 const_binop (PLUS_EXPR, arg2,
4860                                              build_int_cst (type, 1)),
4861                                 OEP_ONLY_CONST))
4862           {
4863             tem = fold_build2_loc (loc, MAX_EXPR, TREE_TYPE (arg00), arg00,
4864                                    fold_convert_loc (loc, TREE_TYPE (arg00),
4865                                                      arg2));
4866             return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, tem));
4867           }
4868         break;
4869       case NE_EXPR:
4870         break;
4871       default:
4872         gcc_unreachable ();
4873       }
4874
4875   return NULL_TREE;
4876 }
4877
4878
4879 \f
4880 #ifndef LOGICAL_OP_NON_SHORT_CIRCUIT
4881 #define LOGICAL_OP_NON_SHORT_CIRCUIT \
4882   (BRANCH_COST (optimize_function_for_speed_p (cfun), \
4883                 false) >= 2)
4884 #endif
4885
4886 /* EXP is some logical combination of boolean tests.  See if we can
4887    merge it into some range test.  Return the new tree if so.  */
4888
4889 static tree
4890 fold_range_test (location_t loc, enum tree_code code, tree type,
4891                  tree op0, tree op1)
4892 {
4893   int or_op = (code == TRUTH_ORIF_EXPR
4894                || code == TRUTH_OR_EXPR);
4895   int in0_p, in1_p, in_p;
4896   tree low0, low1, low, high0, high1, high;
4897   bool strict_overflow_p = false;
4898   tree tem, lhs, rhs;
4899   const char * const warnmsg = G_("assuming signed overflow does not occur "
4900                                   "when simplifying range test");
4901
4902   if (!INTEGRAL_TYPE_P (type))
4903     return 0;
4904
4905   lhs = make_range (op0, &in0_p, &low0, &high0, &strict_overflow_p);
4906   rhs = make_range (op1, &in1_p, &low1, &high1, &strict_overflow_p);
4907
4908   /* If this is an OR operation, invert both sides; we will invert
4909      again at the end.  */
4910   if (or_op)
4911     in0_p = ! in0_p, in1_p = ! in1_p;
4912
4913   /* If both expressions are the same, if we can merge the ranges, and we
4914      can build the range test, return it or it inverted.  If one of the
4915      ranges is always true or always false, consider it to be the same
4916      expression as the other.  */
4917   if ((lhs == 0 || rhs == 0 || operand_equal_p (lhs, rhs, 0))
4918       && merge_ranges (&in_p, &low, &high, in0_p, low0, high0,
4919                        in1_p, low1, high1)
4920       && 0 != (tem = (build_range_check (loc, type,
4921                                          lhs != 0 ? lhs
4922                                          : rhs != 0 ? rhs : integer_zero_node,
4923                                          in_p, low, high))))
4924     {
4925       if (strict_overflow_p)
4926         fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_COMPARISON);
4927       return or_op ? invert_truthvalue_loc (loc, tem) : tem;
4928     }
4929
4930   /* On machines where the branch cost is expensive, if this is a
4931      short-circuited branch and the underlying object on both sides
4932      is the same, make a non-short-circuit operation.  */
4933   else if (LOGICAL_OP_NON_SHORT_CIRCUIT
4934            && lhs != 0 && rhs != 0
4935            && (code == TRUTH_ANDIF_EXPR
4936                || code == TRUTH_ORIF_EXPR)
4937            && operand_equal_p (lhs, rhs, 0))
4938     {
4939       /* If simple enough, just rewrite.  Otherwise, make a SAVE_EXPR
4940          unless we are at top level or LHS contains a PLACEHOLDER_EXPR, in
4941          which cases we can't do this.  */
4942       if (simple_operand_p (lhs))
4943         return build2_loc (loc, code == TRUTH_ANDIF_EXPR
4944                            ? TRUTH_AND_EXPR : TRUTH_OR_EXPR,
4945                            type, op0, op1);
4946
4947       else if (!lang_hooks.decls.global_bindings_p ()
4948                && !CONTAINS_PLACEHOLDER_P (lhs))
4949         {
4950           tree common = save_expr (lhs);
4951
4952           if (0 != (lhs = build_range_check (loc, type, common,
4953                                              or_op ? ! in0_p : in0_p,
4954                                              low0, high0))
4955               && (0 != (rhs = build_range_check (loc, type, common,
4956                                                  or_op ? ! in1_p : in1_p,
4957                                                  low1, high1))))
4958             {
4959               if (strict_overflow_p)
4960                 fold_overflow_warning (warnmsg,
4961                                        WARN_STRICT_OVERFLOW_COMPARISON);
4962               return build2_loc (loc, code == TRUTH_ANDIF_EXPR
4963                                  ? TRUTH_AND_EXPR : TRUTH_OR_EXPR,
4964                                  type, lhs, rhs);
4965             }
4966         }
4967     }
4968
4969   return 0;
4970 }
4971 \f
4972 /* Subroutine for fold_truth_andor_1: C is an INTEGER_CST interpreted as a P
4973    bit value.  Arrange things so the extra bits will be set to zero if and
4974    only if C is signed-extended to its full width.  If MASK is nonzero,
4975    it is an INTEGER_CST that should be AND'ed with the extra bits.  */
4976
4977 static tree
4978 unextend (tree c, int p, int unsignedp, tree mask)
4979 {
4980   tree type = TREE_TYPE (c);
4981   int modesize = GET_MODE_BITSIZE (TYPE_MODE (type));
4982   tree temp;
4983
4984   if (p == modesize || unsignedp)
4985     return c;
4986
4987   /* We work by getting just the sign bit into the low-order bit, then
4988      into the high-order bit, then sign-extend.  We then XOR that value
4989      with C.  */
4990   temp = build_int_cst (TREE_TYPE (c), wi::extract_uhwi (c, p - 1, 1));
4991
4992   /* We must use a signed type in order to get an arithmetic right shift.
4993      However, we must also avoid introducing accidental overflows, so that
4994      a subsequent call to integer_zerop will work.  Hence we must
4995      do the type conversion here.  At this point, the constant is either
4996      zero or one, and the conversion to a signed type can never overflow.
4997      We could get an overflow if this conversion is done anywhere else.  */
4998   if (TYPE_UNSIGNED (type))
4999     temp = fold_convert (signed_type_for (type), temp);
5000
5001   temp = const_binop (LSHIFT_EXPR, temp, size_int (modesize - 1));
5002   temp = const_binop (RSHIFT_EXPR, temp, size_int (modesize - p - 1));
5003   if (mask != 0)
5004     temp = const_binop (BIT_AND_EXPR, temp,
5005                         fold_convert (TREE_TYPE (c), mask));
5006   /* If necessary, convert the type back to match the type of C.  */
5007   if (TYPE_UNSIGNED (type))
5008     temp = fold_convert (type, temp);
5009
5010   return fold_convert (type, const_binop (BIT_XOR_EXPR, c, temp));
5011 }
5012 \f
5013 /* For an expression that has the form
5014      (A && B) || ~B
5015    or
5016      (A || B) && ~B,
5017    we can drop one of the inner expressions and simplify to
5018      A || ~B
5019    or
5020      A && ~B
5021    LOC is the location of the resulting expression.  OP is the inner 
5022    logical operation; the left-hand side in the examples above, while CMPOP
5023    is the right-hand side.  RHS_ONLY is used to prevent us from accidentally
5024    removing a condition that guards another, as in
5025      (A != NULL && A->...) || A == NULL
5026    which we must not transform.  If RHS_ONLY is true, only eliminate the
5027    right-most operand of the inner logical operation.  */
5028
5029 static tree
5030 merge_truthop_with_opposite_arm (location_t loc, tree op, tree cmpop,
5031                                  bool rhs_only)
5032 {
5033   tree type = TREE_TYPE (cmpop);
5034   enum tree_code code = TREE_CODE (cmpop);
5035   enum tree_code truthop_code = TREE_CODE (op);
5036   tree lhs = TREE_OPERAND (op, 0);
5037   tree rhs = TREE_OPERAND (op, 1);
5038   tree orig_lhs = lhs, orig_rhs = rhs;
5039   enum tree_code rhs_code = TREE_CODE (rhs);
5040   enum tree_code lhs_code = TREE_CODE (lhs);
5041   enum tree_code inv_code;
5042
5043   if (TREE_SIDE_EFFECTS (op) || TREE_SIDE_EFFECTS (cmpop))
5044     return NULL_TREE;
5045
5046   if (TREE_CODE_CLASS (code) != tcc_comparison)
5047     return NULL_TREE;
5048
5049   if (rhs_code == truthop_code)
5050     {
5051       tree newrhs = merge_truthop_with_opposite_arm (loc, rhs, cmpop, rhs_only);
5052       if (newrhs != NULL_TREE)
5053         {
5054           rhs = newrhs;
5055           rhs_code = TREE_CODE (rhs);
5056         }
5057     }
5058   if (lhs_code == truthop_code && !rhs_only)
5059     {
5060       tree newlhs = merge_truthop_with_opposite_arm (loc, lhs, cmpop, false);
5061       if (newlhs != NULL_TREE)
5062         {
5063           lhs = newlhs;
5064           lhs_code = TREE_CODE (lhs);
5065         }
5066     }
5067
5068   inv_code = invert_tree_comparison (code, HONOR_NANS (TYPE_MODE (type)));
5069   if (inv_code == rhs_code
5070       && operand_equal_p (TREE_OPERAND (rhs, 0), TREE_OPERAND (cmpop, 0), 0)
5071       && operand_equal_p (TREE_OPERAND (rhs, 1), TREE_OPERAND (cmpop, 1), 0))
5072     return lhs;
5073   if (!rhs_only && inv_code == lhs_code
5074       && operand_equal_p (TREE_OPERAND (lhs, 0), TREE_OPERAND (cmpop, 0), 0)
5075       && operand_equal_p (TREE_OPERAND (lhs, 1), TREE_OPERAND (cmpop, 1), 0))
5076     return rhs;
5077   if (rhs != orig_rhs || lhs != orig_lhs)
5078     return fold_build2_loc (loc, truthop_code, TREE_TYPE (cmpop),
5079                             lhs, rhs);
5080   return NULL_TREE;
5081 }
5082
5083 /* Find ways of folding logical expressions of LHS and RHS:
5084    Try to merge two comparisons to the same innermost item.
5085    Look for range tests like "ch >= '0' && ch <= '9'".
5086    Look for combinations of simple terms on machines with expensive branches
5087    and evaluate the RHS unconditionally.
5088
5089    For example, if we have p->a == 2 && p->b == 4 and we can make an
5090    object large enough to span both A and B, we can do this with a comparison
5091    against the object ANDed with the a mask.
5092
5093    If we have p->a == q->a && p->b == q->b, we may be able to use bit masking
5094    operations to do this with one comparison.
5095
5096    We check for both normal comparisons and the BIT_AND_EXPRs made this by
5097    function and the one above.
5098
5099    CODE is the logical operation being done.  It can be TRUTH_ANDIF_EXPR,
5100    TRUTH_AND_EXPR, TRUTH_ORIF_EXPR, or TRUTH_OR_EXPR.
5101
5102    TRUTH_TYPE is the type of the logical operand and LHS and RHS are its
5103    two operands.
5104
5105    We return the simplified tree or 0 if no optimization is possible.  */
5106
5107 static tree
5108 fold_truth_andor_1 (location_t loc, enum tree_code code, tree truth_type,
5109                     tree lhs, tree rhs)
5110 {
5111   /* If this is the "or" of two comparisons, we can do something if
5112      the comparisons are NE_EXPR.  If this is the "and", we can do something
5113      if the comparisons are EQ_EXPR.  I.e.,
5114         (a->b == 2 && a->c == 4) can become (a->new == NEW).
5115
5116      WANTED_CODE is this operation code.  For single bit fields, we can
5117      convert EQ_EXPR to NE_EXPR so we need not reject the "wrong"
5118      comparison for one-bit fields.  */
5119
5120   enum tree_code wanted_code;
5121   enum tree_code lcode, rcode;
5122   tree ll_arg, lr_arg, rl_arg, rr_arg;
5123   tree ll_inner, lr_inner, rl_inner, rr_inner;
5124   HOST_WIDE_INT ll_bitsize, ll_bitpos, lr_bitsize, lr_bitpos;
5125   HOST_WIDE_INT rl_bitsize, rl_bitpos, rr_bitsize, rr_bitpos;
5126   HOST_WIDE_INT xll_bitpos, xlr_bitpos, xrl_bitpos, xrr_bitpos;
5127   HOST_WIDE_INT lnbitsize, lnbitpos, rnbitsize, rnbitpos;
5128   int ll_unsignedp, lr_unsignedp, rl_unsignedp, rr_unsignedp;
5129   machine_mode ll_mode, lr_mode, rl_mode, rr_mode;
5130   machine_mode lnmode, rnmode;
5131   tree ll_mask, lr_mask, rl_mask, rr_mask;
5132   tree ll_and_mask, lr_and_mask, rl_and_mask, rr_and_mask;
5133   tree l_const, r_const;
5134   tree lntype, rntype, result;
5135   HOST_WIDE_INT first_bit, end_bit;
5136   int volatilep;
5137
5138   /* Start by getting the comparison codes.  Fail if anything is volatile.
5139      If one operand is a BIT_AND_EXPR with the constant one, treat it as if
5140      it were surrounded with a NE_EXPR.  */
5141
5142   if (TREE_SIDE_EFFECTS (lhs) || TREE_SIDE_EFFECTS (rhs))
5143     return 0;
5144
5145   lcode = TREE_CODE (lhs);
5146   rcode = TREE_CODE (rhs);
5147
5148   if (lcode == BIT_AND_EXPR && integer_onep (TREE_OPERAND (lhs, 1)))
5149     {
5150       lhs = build2 (NE_EXPR, truth_type, lhs,
5151                     build_int_cst (TREE_TYPE (lhs), 0));
5152       lcode = NE_EXPR;
5153     }
5154
5155   if (rcode == BIT_AND_EXPR && integer_onep (TREE_OPERAND (rhs, 1)))
5156     {
5157       rhs = build2 (NE_EXPR, truth_type, rhs,
5158                     build_int_cst (TREE_TYPE (rhs), 0));
5159       rcode = NE_EXPR;
5160     }
5161
5162   if (TREE_CODE_CLASS (lcode) != tcc_comparison
5163       || TREE_CODE_CLASS (rcode) != tcc_comparison)
5164     return 0;
5165
5166   ll_arg = TREE_OPERAND (lhs, 0);
5167   lr_arg = TREE_OPERAND (lhs, 1);
5168   rl_arg = TREE_OPERAND (rhs, 0);
5169   rr_arg = TREE_OPERAND (rhs, 1);
5170
5171   /* Simplify (x<y) && (x==y) into (x<=y) and related optimizations.  */
5172   if (simple_operand_p (ll_arg)
5173       && simple_operand_p (lr_arg))
5174     {
5175       if (operand_equal_p (ll_arg, rl_arg, 0)
5176           && operand_equal_p (lr_arg, rr_arg, 0))
5177         {
5178           result = combine_comparisons (loc, code, lcode, rcode,
5179                                         truth_type, ll_arg, lr_arg);
5180           if (result)
5181             return result;
5182         }
5183       else if (operand_equal_p (ll_arg, rr_arg, 0)
5184                && operand_equal_p (lr_arg, rl_arg, 0))
5185         {
5186           result = combine_comparisons (loc, code, lcode,
5187                                         swap_tree_comparison (rcode),
5188                                         truth_type, ll_arg, lr_arg);
5189           if (result)
5190             return result;
5191         }
5192     }
5193
5194   code = ((code == TRUTH_AND_EXPR || code == TRUTH_ANDIF_EXPR)
5195           ? TRUTH_AND_EXPR : TRUTH_OR_EXPR);
5196
5197   /* If the RHS can be evaluated unconditionally and its operands are
5198      simple, it wins to evaluate the RHS unconditionally on machines
5199      with expensive branches.  In this case, this isn't a comparison
5200      that can be merged.  */
5201
5202   if (BRANCH_COST (optimize_function_for_speed_p (cfun),
5203                    false) >= 2
5204       && ! FLOAT_TYPE_P (TREE_TYPE (rl_arg))
5205       && simple_operand_p (rl_arg)
5206       && simple_operand_p (rr_arg))
5207     {
5208       /* Convert (a != 0) || (b != 0) into (a | b) != 0.  */
5209       if (code == TRUTH_OR_EXPR
5210           && lcode == NE_EXPR && integer_zerop (lr_arg)
5211           && rcode == NE_EXPR && integer_zerop (rr_arg)
5212           && TREE_TYPE (ll_arg) == TREE_TYPE (rl_arg)
5213           && INTEGRAL_TYPE_P (TREE_TYPE (ll_arg)))
5214         return build2_loc (loc, NE_EXPR, truth_type,
5215                            build2 (BIT_IOR_EXPR, TREE_TYPE (ll_arg),
5216                                    ll_arg, rl_arg),
5217                            build_int_cst (TREE_TYPE (ll_arg), 0));
5218
5219       /* Convert (a == 0) && (b == 0) into (a | b) == 0.  */
5220       if (code == TRUTH_AND_EXPR
5221           && lcode == EQ_EXPR && integer_zerop (lr_arg)
5222           && rcode == EQ_EXPR && integer_zerop (rr_arg)
5223           && TREE_TYPE (ll_arg) == TREE_TYPE (rl_arg)
5224           && INTEGRAL_TYPE_P (TREE_TYPE (ll_arg)))
5225         return build2_loc (loc, EQ_EXPR, truth_type,
5226                            build2 (BIT_IOR_EXPR, TREE_TYPE (ll_arg),
5227                                    ll_arg, rl_arg),
5228                            build_int_cst (TREE_TYPE (ll_arg), 0));
5229     }
5230
5231   /* See if the comparisons can be merged.  Then get all the parameters for
5232      each side.  */
5233
5234   if ((lcode != EQ_EXPR && lcode != NE_EXPR)
5235       || (rcode != EQ_EXPR && rcode != NE_EXPR))
5236     return 0;
5237
5238   volatilep = 0;
5239   ll_inner = decode_field_reference (loc, ll_arg,
5240                                      &ll_bitsize, &ll_bitpos, &ll_mode,
5241                                      &ll_unsignedp, &volatilep, &ll_mask,
5242                                      &ll_and_mask);
5243   lr_inner = decode_field_reference (loc, lr_arg,
5244                                      &lr_bitsize, &lr_bitpos, &lr_mode,
5245                                      &lr_unsignedp, &volatilep, &lr_mask,
5246                                      &lr_and_mask);
5247   rl_inner = decode_field_reference (loc, rl_arg,
5248                                      &rl_bitsize, &rl_bitpos, &rl_mode,
5249                                      &rl_unsignedp, &volatilep, &rl_mask,
5250                                      &rl_and_mask);
5251   rr_inner = decode_field_reference (loc, rr_arg,
5252                                      &rr_bitsize, &rr_bitpos, &rr_mode,
5253                                      &rr_unsignedp, &volatilep, &rr_mask,
5254                                      &rr_and_mask);
5255
5256   /* It must be true that the inner operation on the lhs of each
5257      comparison must be the same if we are to be able to do anything.
5258      Then see if we have constants.  If not, the same must be true for
5259      the rhs's.  */
5260   if (volatilep || ll_inner == 0 || rl_inner == 0
5261       || ! operand_equal_p (ll_inner, rl_inner, 0))
5262     return 0;
5263
5264   if (TREE_CODE (lr_arg) == INTEGER_CST
5265       && TREE_CODE (rr_arg) == INTEGER_CST)
5266     l_const = lr_arg, r_const = rr_arg;
5267   else if (lr_inner == 0 || rr_inner == 0
5268            || ! operand_equal_p (lr_inner, rr_inner, 0))
5269     return 0;
5270   else
5271     l_const = r_const = 0;
5272
5273   /* If either comparison code is not correct for our logical operation,
5274      fail.  However, we can convert a one-bit comparison against zero into
5275      the opposite comparison against that bit being set in the field.  */
5276
5277   wanted_code = (code == TRUTH_AND_EXPR ? EQ_EXPR : NE_EXPR);
5278   if (lcode != wanted_code)
5279     {
5280       if (l_const && integer_zerop (l_const) && integer_pow2p (ll_mask))
5281         {
5282           /* Make the left operand unsigned, since we are only interested
5283              in the value of one bit.  Otherwise we are doing the wrong
5284              thing below.  */
5285           ll_unsignedp = 1;
5286           l_const = ll_mask;
5287         }
5288       else
5289         return 0;
5290     }
5291
5292   /* This is analogous to the code for l_const above.  */
5293   if (rcode != wanted_code)
5294     {
5295       if (r_const && integer_zerop (r_const) && integer_pow2p (rl_mask))
5296         {
5297           rl_unsignedp = 1;
5298           r_const = rl_mask;
5299         }
5300       else
5301         return 0;
5302     }
5303
5304   /* See if we can find a mode that contains both fields being compared on
5305      the left.  If we can't, fail.  Otherwise, update all constants and masks
5306      to be relative to a field of that size.  */
5307   first_bit = MIN (ll_bitpos, rl_bitpos);
5308   end_bit = MAX (ll_bitpos + ll_bitsize, rl_bitpos + rl_bitsize);
5309   lnmode = get_best_mode (end_bit - first_bit, first_bit, 0, 0,
5310                           TYPE_ALIGN (TREE_TYPE (ll_inner)), word_mode,
5311                           volatilep);
5312   if (lnmode == VOIDmode)
5313     return 0;
5314
5315   lnbitsize = GET_MODE_BITSIZE (lnmode);
5316   lnbitpos = first_bit & ~ (lnbitsize - 1);
5317   lntype = lang_hooks.types.type_for_size (lnbitsize, 1);
5318   xll_bitpos = ll_bitpos - lnbitpos, xrl_bitpos = rl_bitpos - lnbitpos;
5319
5320   if (BYTES_BIG_ENDIAN)
5321     {
5322       xll_bitpos = lnbitsize - xll_bitpos - ll_bitsize;
5323       xrl_bitpos = lnbitsize - xrl_bitpos - rl_bitsize;
5324     }
5325
5326   ll_mask = const_binop (LSHIFT_EXPR, fold_convert_loc (loc, lntype, ll_mask),
5327                          size_int (xll_bitpos));
5328   rl_mask = const_binop (LSHIFT_EXPR, fold_convert_loc (loc, lntype, rl_mask),
5329                          size_int (xrl_bitpos));
5330
5331   if (l_const)
5332     {
5333       l_const = fold_convert_loc (loc, lntype, l_const);
5334       l_const = unextend (l_const, ll_bitsize, ll_unsignedp, ll_and_mask);
5335       l_const = const_binop (LSHIFT_EXPR, l_const, size_int (xll_bitpos));
5336       if (! integer_zerop (const_binop (BIT_AND_EXPR, l_const,
5337                                         fold_build1_loc (loc, BIT_NOT_EXPR,
5338                                                      lntype, ll_mask))))
5339         {
5340           warning (0, "comparison is always %d", wanted_code == NE_EXPR);
5341
5342           return constant_boolean_node (wanted_code == NE_EXPR, truth_type);
5343         }
5344     }
5345   if (r_const)
5346     {
5347       r_const = fold_convert_loc (loc, lntype, r_const);
5348       r_const = unextend (r_const, rl_bitsize, rl_unsignedp, rl_and_mask);
5349       r_const = const_binop (LSHIFT_EXPR, r_const, size_int (xrl_bitpos));
5350       if (! integer_zerop (const_binop (BIT_AND_EXPR, r_const,
5351                                         fold_build1_loc (loc, BIT_NOT_EXPR,
5352                                                      lntype, rl_mask))))
5353         {
5354           warning (0, "comparison is always %d", wanted_code == NE_EXPR);
5355
5356           return constant_boolean_node (wanted_code == NE_EXPR, truth_type);
5357         }
5358     }
5359
5360   /* If the right sides are not constant, do the same for it.  Also,
5361      disallow this optimization if a size or signedness mismatch occurs
5362      between the left and right sides.  */
5363   if (l_const == 0)
5364     {
5365       if (ll_bitsize != lr_bitsize || rl_bitsize != rr_bitsize
5366           || ll_unsignedp != lr_unsignedp || rl_unsignedp != rr_unsignedp
5367           /* Make sure the two fields on the right
5368              correspond to the left without being swapped.  */
5369           || ll_bitpos - rl_bitpos != lr_bitpos - rr_bitpos)
5370         return 0;
5371
5372       first_bit = MIN (lr_bitpos, rr_bitpos);
5373       end_bit = MAX (lr_bitpos + lr_bitsize, rr_bitpos + rr_bitsize);
5374       rnmode = get_best_mode (end_bit - first_bit, first_bit, 0, 0,
5375                               TYPE_ALIGN (TREE_TYPE (lr_inner)), word_mode,
5376                               volatilep);
5377       if (rnmode == VOIDmode)
5378         return 0;
5379
5380       rnbitsize = GET_MODE_BITSIZE (rnmode);
5381       rnbitpos = first_bit & ~ (rnbitsize - 1);
5382       rntype = lang_hooks.types.type_for_size (rnbitsize, 1);
5383       xlr_bitpos = lr_bitpos - rnbitpos, xrr_bitpos = rr_bitpos - rnbitpos;
5384
5385       if (BYTES_BIG_ENDIAN)
5386         {
5387           xlr_bitpos = rnbitsize - xlr_bitpos - lr_bitsize;
5388           xrr_bitpos = rnbitsize - xrr_bitpos - rr_bitsize;
5389         }
5390
5391       lr_mask = const_binop (LSHIFT_EXPR, fold_convert_loc (loc,
5392                                                             rntype, lr_mask),
5393                              size_int (xlr_bitpos));
5394       rr_mask = const_binop (LSHIFT_EXPR, fold_convert_loc (loc,
5395                                                             rntype, rr_mask),
5396                              size_int (xrr_bitpos));
5397
5398       /* Make a mask that corresponds to both fields being compared.
5399          Do this for both items being compared.  If the operands are the
5400          same size and the bits being compared are in the same position
5401          then we can do this by masking both and comparing the masked
5402          results.  */
5403       ll_mask = const_binop (BIT_IOR_EXPR, ll_mask, rl_mask);
5404       lr_mask = const_binop (BIT_IOR_EXPR, lr_mask, rr_mask);
5405       if (lnbitsize == rnbitsize && xll_bitpos == xlr_bitpos)
5406         {
5407           lhs = make_bit_field_ref (loc, ll_inner, lntype, lnbitsize, lnbitpos,
5408                                     ll_unsignedp || rl_unsignedp);
5409           if (! all_ones_mask_p (ll_mask, lnbitsize))
5410             lhs = build2 (BIT_AND_EXPR, lntype, lhs, ll_mask);
5411
5412           rhs = make_bit_field_ref (loc, lr_inner, rntype, rnbitsize, rnbitpos,
5413                                     lr_unsignedp || rr_unsignedp);
5414           if (! all_ones_mask_p (lr_mask, rnbitsize))
5415             rhs = build2 (BIT_AND_EXPR, rntype, rhs, lr_mask);
5416
5417           return build2_loc (loc, wanted_code, truth_type, lhs, rhs);
5418         }
5419
5420       /* There is still another way we can do something:  If both pairs of
5421          fields being compared are adjacent, we may be able to make a wider
5422          field containing them both.
5423
5424          Note that we still must mask the lhs/rhs expressions.  Furthermore,
5425          the mask must be shifted to account for the shift done by
5426          make_bit_field_ref.  */
5427       if ((ll_bitsize + ll_bitpos == rl_bitpos
5428            && lr_bitsize + lr_bitpos == rr_bitpos)
5429           || (ll_bitpos == rl_bitpos + rl_bitsize
5430               && lr_bitpos == rr_bitpos + rr_bitsize))
5431         {
5432           tree type;
5433
5434           lhs = make_bit_field_ref (loc, ll_inner, lntype,
5435                                     ll_bitsize + rl_bitsize,
5436                                     MIN (ll_bitpos, rl_bitpos), ll_unsignedp);
5437           rhs = make_bit_field_ref (loc, lr_inner, rntype,
5438                                     lr_bitsize + rr_bitsize,
5439                                     MIN (lr_bitpos, rr_bitpos), lr_unsignedp);
5440
5441           ll_mask = const_binop (RSHIFT_EXPR, ll_mask,
5442                                  size_int (MIN (xll_bitpos, xrl_bitpos)));
5443           lr_mask = const_binop (RSHIFT_EXPR, lr_mask,
5444                                  size_int (MIN (xlr_bitpos, xrr_bitpos)));
5445
5446           /* Convert to the smaller type before masking out unwanted bits.  */
5447           type = lntype;
5448           if (lntype != rntype)
5449             {
5450               if (lnbitsize > rnbitsize)
5451                 {
5452                   lhs = fold_convert_loc (loc, rntype, lhs);
5453                   ll_mask = fold_convert_loc (loc, rntype, ll_mask);
5454                   type = rntype;
5455                 }
5456               else if (lnbitsize < rnbitsize)
5457                 {
5458                   rhs = fold_convert_loc (loc, lntype, rhs);
5459                   lr_mask = fold_convert_loc (loc, lntype, lr_mask);
5460                   type = lntype;
5461                 }
5462             }
5463
5464           if (! all_ones_mask_p (ll_mask, ll_bitsize + rl_bitsize))
5465             lhs = build2 (BIT_AND_EXPR, type, lhs, ll_mask);
5466
5467           if (! all_ones_mask_p (lr_mask, lr_bitsize + rr_bitsize))
5468             rhs = build2 (BIT_AND_EXPR, type, rhs, lr_mask);
5469
5470           return build2_loc (loc, wanted_code, truth_type, lhs, rhs);
5471         }
5472
5473       return 0;
5474     }
5475
5476   /* Handle the case of comparisons with constants.  If there is something in
5477      common between the masks, those bits of the constants must be the same.
5478      If not, the condition is always false.  Test for this to avoid generating
5479      incorrect code below.  */
5480   result = const_binop (BIT_AND_EXPR, ll_mask, rl_mask);
5481   if (! integer_zerop (result)
5482       && simple_cst_equal (const_binop (BIT_AND_EXPR, result, l_const),
5483                            const_binop (BIT_AND_EXPR, result, r_const)) != 1)
5484     {
5485       if (wanted_code == NE_EXPR)
5486         {
5487           warning (0, "%<or%> of unmatched not-equal tests is always 1");
5488           return constant_boolean_node (true, truth_type);
5489         }
5490       else
5491         {
5492           warning (0, "%<and%> of mutually exclusive equal-tests is always 0");
5493           return constant_boolean_node (false, truth_type);
5494         }
5495     }
5496
5497   /* Construct the expression we will return.  First get the component
5498      reference we will make.  Unless the mask is all ones the width of
5499      that field, perform the mask operation.  Then compare with the
5500      merged constant.  */
5501   result = make_bit_field_ref (loc, ll_inner, lntype, lnbitsize, lnbitpos,
5502                                ll_unsignedp || rl_unsignedp);
5503
5504   ll_mask = const_binop (BIT_IOR_EXPR, ll_mask, rl_mask);
5505   if (! all_ones_mask_p (ll_mask, lnbitsize))
5506     result = build2_loc (loc, BIT_AND_EXPR, lntype, result, ll_mask);
5507
5508   return build2_loc (loc, wanted_code, truth_type, result,
5509                      const_binop (BIT_IOR_EXPR, l_const, r_const));
5510 }
5511 \f
5512 /* Optimize T, which is a comparison of a MIN_EXPR or MAX_EXPR with a
5513    constant.  */
5514
5515 static tree
5516 optimize_minmax_comparison (location_t loc, enum tree_code code, tree type,
5517                             tree op0, tree op1)
5518 {
5519   tree arg0 = op0;
5520   enum tree_code op_code;
5521   tree comp_const;
5522   tree minmax_const;
5523   int consts_equal, consts_lt;
5524   tree inner;
5525
5526   STRIP_SIGN_NOPS (arg0);
5527
5528   op_code = TREE_CODE (arg0);
5529   minmax_const = TREE_OPERAND (arg0, 1);
5530   comp_const = fold_convert_loc (loc, TREE_TYPE (arg0), op1);
5531   consts_equal = tree_int_cst_equal (minmax_const, comp_const);
5532   consts_lt = tree_int_cst_lt (minmax_const, comp_const);
5533   inner = TREE_OPERAND (arg0, 0);
5534
5535   /* If something does not permit us to optimize, return the original tree.  */
5536   if ((op_code != MIN_EXPR && op_code != MAX_EXPR)
5537       || TREE_CODE (comp_const) != INTEGER_CST
5538       || TREE_OVERFLOW (comp_const)
5539       || TREE_CODE (minmax_const) != INTEGER_CST
5540       || TREE_OVERFLOW (minmax_const))
5541     return NULL_TREE;
5542
5543   /* Now handle all the various comparison codes.  We only handle EQ_EXPR
5544      and GT_EXPR, doing the rest with recursive calls using logical
5545      simplifications.  */
5546   switch (code)
5547     {
5548     case NE_EXPR:  case LT_EXPR:  case LE_EXPR:
5549       {
5550         tree tem
5551           = optimize_minmax_comparison (loc,
5552                                         invert_tree_comparison (code, false),
5553                                         type, op0, op1);
5554         if (tem)
5555           return invert_truthvalue_loc (loc, tem);
5556         return NULL_TREE;
5557       }
5558
5559     case GE_EXPR:
5560       return
5561         fold_build2_loc (loc, TRUTH_ORIF_EXPR, type,
5562                      optimize_minmax_comparison
5563                      (loc, EQ_EXPR, type, arg0, comp_const),
5564                      optimize_minmax_comparison
5565                      (loc, GT_EXPR, type, arg0, comp_const));
5566
5567     case EQ_EXPR:
5568       if (op_code == MAX_EXPR && consts_equal)
5569         /* MAX (X, 0) == 0  ->  X <= 0  */
5570         return fold_build2_loc (loc, LE_EXPR, type, inner, comp_const);
5571
5572       else if (op_code == MAX_EXPR && consts_lt)
5573         /* MAX (X, 0) == 5  ->  X == 5   */
5574         return fold_build2_loc (loc, EQ_EXPR, type, inner, comp_const);
5575
5576       else if (op_code == MAX_EXPR)
5577         /* MAX (X, 0) == -1  ->  false  */
5578         return omit_one_operand_loc (loc, type, integer_zero_node, inner);
5579
5580       else if (consts_equal)
5581         /* MIN (X, 0) == 0  ->  X >= 0  */
5582         return fold_build2_loc (loc, GE_EXPR, type, inner, comp_const);
5583
5584       else if (consts_lt)
5585         /* MIN (X, 0) == 5  ->  false  */
5586         return omit_one_operand_loc (loc, type, integer_zero_node, inner);
5587
5588       else
5589         /* MIN (X, 0) == -1  ->  X == -1  */
5590         return fold_build2_loc (loc, EQ_EXPR, type, inner, comp_const);
5591
5592     case GT_EXPR:
5593       if (op_code == MAX_EXPR && (consts_equal || consts_lt))
5594         /* MAX (X, 0) > 0  ->  X > 0
5595            MAX (X, 0) > 5  ->  X > 5  */
5596         return fold_build2_loc (loc, GT_EXPR, type, inner, comp_const);
5597
5598       else if (op_code == MAX_EXPR)
5599         /* MAX (X, 0) > -1  ->  true  */
5600         return omit_one_operand_loc (loc, type, integer_one_node, inner);
5601
5602       else if (op_code == MIN_EXPR && (consts_equal || consts_lt))
5603         /* MIN (X, 0) > 0  ->  false
5604            MIN (X, 0) > 5  ->  false  */
5605         return omit_one_operand_loc (loc, type, integer_zero_node, inner);
5606
5607       else
5608         /* MIN (X, 0) > -1  ->  X > -1  */
5609         return fold_build2_loc (loc, GT_EXPR, type, inner, comp_const);
5610
5611     default:
5612       return NULL_TREE;
5613     }
5614 }
5615 \f
5616 /* T is an integer expression that is being multiplied, divided, or taken a
5617    modulus (CODE says which and what kind of divide or modulus) by a
5618    constant C.  See if we can eliminate that operation by folding it with
5619    other operations already in T.  WIDE_TYPE, if non-null, is a type that
5620    should be used for the computation if wider than our type.
5621
5622    For example, if we are dividing (X * 8) + (Y * 16) by 4, we can return
5623    (X * 2) + (Y * 4).  We must, however, be assured that either the original
5624    expression would not overflow or that overflow is undefined for the type
5625    in the language in question.
5626
5627    If we return a non-null expression, it is an equivalent form of the
5628    original computation, but need not be in the original type.
5629
5630    We set *STRICT_OVERFLOW_P to true if the return values depends on
5631    signed overflow being undefined.  Otherwise we do not change
5632    *STRICT_OVERFLOW_P.  */
5633
5634 static tree
5635 extract_muldiv (tree t, tree c, enum tree_code code, tree wide_type,
5636                 bool *strict_overflow_p)
5637 {
5638   /* To avoid exponential search depth, refuse to allow recursion past
5639      three levels.  Beyond that (1) it's highly unlikely that we'll find
5640      something interesting and (2) we've probably processed it before
5641      when we built the inner expression.  */
5642
5643   static int depth;
5644   tree ret;
5645
5646   if (depth > 3)
5647     return NULL;
5648
5649   depth++;
5650   ret = extract_muldiv_1 (t, c, code, wide_type, strict_overflow_p);
5651   depth--;
5652
5653   return ret;
5654 }
5655
5656 static tree
5657 extract_muldiv_1 (tree t, tree c, enum tree_code code, tree wide_type,
5658                   bool *strict_overflow_p)
5659 {
5660   tree type = TREE_TYPE (t);
5661   enum tree_code tcode = TREE_CODE (t);
5662   tree ctype = (wide_type != 0 && (GET_MODE_SIZE (TYPE_MODE (wide_type))
5663                                    > GET_MODE_SIZE (TYPE_MODE (type)))
5664                 ? wide_type : type);
5665   tree t1, t2;
5666   int same_p = tcode == code;
5667   tree op0 = NULL_TREE, op1 = NULL_TREE;
5668   bool sub_strict_overflow_p;
5669
5670   /* Don't deal with constants of zero here; they confuse the code below.  */
5671   if (integer_zerop (c))
5672     return NULL_TREE;
5673
5674   if (TREE_CODE_CLASS (tcode) == tcc_unary)
5675     op0 = TREE_OPERAND (t, 0);
5676
5677   if (TREE_CODE_CLASS (tcode) == tcc_binary)
5678     op0 = TREE_OPERAND (t, 0), op1 = TREE_OPERAND (t, 1);
5679
5680   /* Note that we need not handle conditional operations here since fold
5681      already handles those cases.  So just do arithmetic here.  */
5682   switch (tcode)
5683     {
5684     case INTEGER_CST:
5685       /* For a constant, we can always simplify if we are a multiply
5686          or (for divide and modulus) if it is a multiple of our constant.  */
5687       if (code == MULT_EXPR
5688           || wi::multiple_of_p (t, c, TYPE_SIGN (type)))
5689         return const_binop (code, fold_convert (ctype, t),
5690                             fold_convert (ctype, c));
5691       break;
5692
5693     CASE_CONVERT: case NON_LVALUE_EXPR:
5694       /* If op0 is an expression ...  */
5695       if ((COMPARISON_CLASS_P (op0)
5696            || UNARY_CLASS_P (op0)
5697            || BINARY_CLASS_P (op0)
5698            || VL_EXP_CLASS_P (op0)
5699            || EXPRESSION_CLASS_P (op0))
5700           /* ... and has wrapping overflow, and its type is smaller
5701              than ctype, then we cannot pass through as widening.  */
5702           && ((TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0))
5703                && (TYPE_PRECISION (ctype)
5704                    > TYPE_PRECISION (TREE_TYPE (op0))))
5705               /* ... or this is a truncation (t is narrower than op0),
5706                  then we cannot pass through this narrowing.  */
5707               || (TYPE_PRECISION (type)
5708                   < TYPE_PRECISION (TREE_TYPE (op0)))
5709               /* ... or signedness changes for division or modulus,
5710                  then we cannot pass through this conversion.  */
5711               || (code != MULT_EXPR
5712                   && (TYPE_UNSIGNED (ctype)
5713                       != TYPE_UNSIGNED (TREE_TYPE (op0))))
5714               /* ... or has undefined overflow while the converted to
5715                  type has not, we cannot do the operation in the inner type
5716                  as that would introduce undefined overflow.  */
5717               || (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (op0))
5718                   && !TYPE_OVERFLOW_UNDEFINED (type))))
5719         break;
5720
5721       /* Pass the constant down and see if we can make a simplification.  If
5722          we can, replace this expression with the inner simplification for
5723          possible later conversion to our or some other type.  */
5724       if ((t2 = fold_convert (TREE_TYPE (op0), c)) != 0
5725           && TREE_CODE (t2) == INTEGER_CST
5726           && !TREE_OVERFLOW (t2)
5727           && (0 != (t1 = extract_muldiv (op0, t2, code,
5728                                          code == MULT_EXPR
5729                                          ? ctype : NULL_TREE,
5730                                          strict_overflow_p))))
5731         return t1;
5732       break;
5733
5734     case ABS_EXPR:
5735       /* If widening the type changes it from signed to unsigned, then we
5736          must avoid building ABS_EXPR itself as unsigned.  */
5737       if (TYPE_UNSIGNED (ctype) && !TYPE_UNSIGNED (type))
5738         {
5739           tree cstype = (*signed_type_for) (ctype);
5740           if ((t1 = extract_muldiv (op0, c, code, cstype, strict_overflow_p))
5741               != 0)
5742             {
5743               t1 = fold_build1 (tcode, cstype, fold_convert (cstype, t1));
5744               return fold_convert (ctype, t1);
5745             }
5746           break;
5747         }
5748       /* If the constant is negative, we cannot simplify this.  */
5749       if (tree_int_cst_sgn (c) == -1)
5750         break;
5751       /* FALLTHROUGH */
5752     case NEGATE_EXPR:
5753       /* For division and modulus, type can't be unsigned, as e.g.
5754          (-(x / 2U)) / 2U isn't equal to -((x / 2U) / 2U) for x >= 2.
5755          For signed types, even with wrapping overflow, this is fine.  */
5756       if (code != MULT_EXPR && TYPE_UNSIGNED (type))
5757         break;
5758       if ((t1 = extract_muldiv (op0, c, code, wide_type, strict_overflow_p))
5759           != 0)
5760         return fold_build1 (tcode, ctype, fold_convert (ctype, t1));
5761       break;
5762
5763     case MIN_EXPR:  case MAX_EXPR:
5764       /* If widening the type changes the signedness, then we can't perform
5765          this optimization as that changes the result.  */
5766       if (TYPE_UNSIGNED (ctype) != TYPE_UNSIGNED (type))
5767         break;
5768
5769       /* MIN (a, b) / 5 -> MIN (a / 5, b / 5)  */
5770       sub_strict_overflow_p = false;
5771       if ((t1 = extract_muldiv (op0, c, code, wide_type,
5772                                 &sub_strict_overflow_p)) != 0
5773           && (t2 = extract_muldiv (op1, c, code, wide_type,
5774                                    &sub_strict_overflow_p)) != 0)
5775         {
5776           if (tree_int_cst_sgn (c) < 0)
5777             tcode = (tcode == MIN_EXPR ? MAX_EXPR : MIN_EXPR);
5778           if (sub_strict_overflow_p)
5779             *strict_overflow_p = true;
5780           return fold_build2 (tcode, ctype, fold_convert (ctype, t1),
5781                               fold_convert (ctype, t2));
5782         }
5783       break;
5784
5785     case LSHIFT_EXPR:  case RSHIFT_EXPR:
5786       /* If the second operand is constant, this is a multiplication
5787          or floor division, by a power of two, so we can treat it that
5788          way unless the multiplier or divisor overflows.  Signed
5789          left-shift overflow is implementation-defined rather than
5790          undefined in C90, so do not convert signed left shift into
5791          multiplication.  */
5792       if (TREE_CODE (op1) == INTEGER_CST
5793           && (tcode == RSHIFT_EXPR || TYPE_UNSIGNED (TREE_TYPE (op0)))
5794           /* const_binop may not detect overflow correctly,
5795              so check for it explicitly here.  */
5796           && wi::gtu_p (TYPE_PRECISION (TREE_TYPE (size_one_node)), op1)
5797           && 0 != (t1 = fold_convert (ctype,
5798                                       const_binop (LSHIFT_EXPR,
5799                                                    size_one_node,
5800                                                    op1)))
5801           && !TREE_OVERFLOW (t1))
5802         return extract_muldiv (build2 (tcode == LSHIFT_EXPR
5803                                        ? MULT_EXPR : FLOOR_DIV_EXPR,
5804                                        ctype,
5805                                        fold_convert (ctype, op0),
5806                                        t1),
5807                                c, code, wide_type, strict_overflow_p);
5808       break;
5809
5810     case PLUS_EXPR:  case MINUS_EXPR:
5811       /* See if we can eliminate the operation on both sides.  If we can, we
5812          can return a new PLUS or MINUS.  If we can't, the only remaining
5813          cases where we can do anything are if the second operand is a
5814          constant.  */
5815       sub_strict_overflow_p = false;
5816       t1 = extract_muldiv (op0, c, code, wide_type, &sub_strict_overflow_p);
5817       t2 = extract_muldiv (op1, c, code, wide_type, &sub_strict_overflow_p);
5818       if (t1 != 0 && t2 != 0
5819           && (code == MULT_EXPR
5820               /* If not multiplication, we can only do this if both operands
5821                  are divisible by c.  */
5822               || (multiple_of_p (ctype, op0, c)
5823                   && multiple_of_p (ctype, op1, c))))
5824         {
5825           if (sub_strict_overflow_p)
5826             *strict_overflow_p = true;
5827           return fold_build2 (tcode, ctype, fold_convert (ctype, t1),
5828                               fold_convert (ctype, t2));
5829         }
5830
5831       /* If this was a subtraction, negate OP1 and set it to be an addition.
5832          This simplifies the logic below.  */
5833       if (tcode == MINUS_EXPR)
5834         {
5835           tcode = PLUS_EXPR, op1 = negate_expr (op1);
5836           /* If OP1 was not easily negatable, the constant may be OP0.  */
5837           if (TREE_CODE (op0) == INTEGER_CST)
5838             {
5839               tree tem = op0;
5840               op0 = op1;
5841               op1 = tem;
5842               tem = t1;
5843               t1 = t2;
5844               t2 = tem;
5845             }
5846         }
5847
5848       if (TREE_CODE (op1) != INTEGER_CST)
5849         break;
5850
5851       /* If either OP1 or C are negative, this optimization is not safe for
5852          some of the division and remainder types while for others we need
5853          to change the code.  */
5854       if (tree_int_cst_sgn (op1) < 0 || tree_int_cst_sgn (c) < 0)
5855         {
5856           if (code == CEIL_DIV_EXPR)
5857             code = FLOOR_DIV_EXPR;
5858           else if (code == FLOOR_DIV_EXPR)
5859             code = CEIL_DIV_EXPR;
5860           else if (code != MULT_EXPR
5861                    && code != CEIL_MOD_EXPR && code != FLOOR_MOD_EXPR)
5862             break;
5863         }
5864
5865       /* If it's a multiply or a division/modulus operation of a multiple
5866          of our constant, do the operation and verify it doesn't overflow.  */
5867       if (code == MULT_EXPR
5868           || wi::multiple_of_p (op1, c, TYPE_SIGN (type)))
5869         {
5870           op1 = const_binop (code, fold_convert (ctype, op1),
5871                              fold_convert (ctype, c));
5872           /* We allow the constant to overflow with wrapping semantics.  */
5873           if (op1 == 0
5874               || (TREE_OVERFLOW (op1) && !TYPE_OVERFLOW_WRAPS (ctype)))
5875             break;
5876         }
5877       else
5878         break;
5879
5880       /* If we have an unsigned type, we cannot widen the operation since it
5881          will change the result if the original computation overflowed.  */
5882       if (TYPE_UNSIGNED (ctype) && ctype != type)
5883         break;
5884
5885       /* If we were able to eliminate our operation from the first side,
5886          apply our operation to the second side and reform the PLUS.  */
5887       if (t1 != 0 && (TREE_CODE (t1) != code || code == MULT_EXPR))
5888         return fold_build2 (tcode, ctype, fold_convert (ctype, t1), op1);
5889
5890       /* The last case is if we are a multiply.  In that case, we can
5891          apply the distributive law to commute the multiply and addition
5892          if the multiplication of the constants doesn't overflow
5893          and overflow is defined.  With undefined overflow
5894          op0 * c might overflow, while (op0 + orig_op1) * c doesn't.  */
5895       if (code == MULT_EXPR && TYPE_OVERFLOW_WRAPS (ctype))
5896         return fold_build2 (tcode, ctype,
5897                             fold_build2 (code, ctype,
5898                                          fold_convert (ctype, op0),
5899                                          fold_convert (ctype, c)),
5900                             op1);
5901
5902       break;
5903
5904     case MULT_EXPR:
5905       /* We have a special case here if we are doing something like
5906          (C * 8) % 4 since we know that's zero.  */
5907       if ((code == TRUNC_MOD_EXPR || code == CEIL_MOD_EXPR
5908            || code == FLOOR_MOD_EXPR || code == ROUND_MOD_EXPR)
5909           /* If the multiplication can overflow we cannot optimize this.  */
5910           && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (t))
5911           && TREE_CODE (TREE_OPERAND (t, 1)) == INTEGER_CST
5912           && wi::multiple_of_p (op1, c, TYPE_SIGN (type)))
5913         {
5914           *strict_overflow_p = true;
5915           return omit_one_operand (type, integer_zero_node, op0);
5916         }
5917
5918       /* ... fall through ...  */
5919
5920     case TRUNC_DIV_EXPR:  case CEIL_DIV_EXPR:  case FLOOR_DIV_EXPR:
5921     case ROUND_DIV_EXPR:  case EXACT_DIV_EXPR:
5922       /* If we can extract our operation from the LHS, do so and return a
5923          new operation.  Likewise for the RHS from a MULT_EXPR.  Otherwise,
5924          do something only if the second operand is a constant.  */
5925       if (same_p
5926           && (t1 = extract_muldiv (op0, c, code, wide_type,
5927                                    strict_overflow_p)) != 0)
5928         return fold_build2 (tcode, ctype, fold_convert (ctype, t1),
5929                             fold_convert (ctype, op1));
5930       else if (tcode == MULT_EXPR && code == MULT_EXPR
5931                && (t1 = extract_muldiv (op1, c, code, wide_type,
5932                                         strict_overflow_p)) != 0)
5933         return fold_build2 (tcode, ctype, fold_convert (ctype, op0),
5934                             fold_convert (ctype, t1));
5935       else if (TREE_CODE (op1) != INTEGER_CST)
5936         return 0;
5937
5938       /* If these are the same operation types, we can associate them
5939          assuming no overflow.  */
5940       if (tcode == code)
5941         {
5942           bool overflow_p = false;
5943           bool overflow_mul_p;
5944           signop sign = TYPE_SIGN (ctype);
5945           wide_int mul = wi::mul (op1, c, sign, &overflow_mul_p);
5946           overflow_p = TREE_OVERFLOW (c) | TREE_OVERFLOW (op1);
5947           if (overflow_mul_p
5948               && ((sign == UNSIGNED && tcode != MULT_EXPR) || sign == SIGNED))
5949             overflow_p = true;
5950           if (!overflow_p)
5951             return fold_build2 (tcode, ctype, fold_convert (ctype, op0),
5952                                 wide_int_to_tree (ctype, mul));
5953         }
5954
5955       /* If these operations "cancel" each other, we have the main
5956          optimizations of this pass, which occur when either constant is a
5957          multiple of the other, in which case we replace this with either an
5958          operation or CODE or TCODE.
5959
5960          If we have an unsigned type, we cannot do this since it will change
5961          the result if the original computation overflowed.  */
5962       if (TYPE_OVERFLOW_UNDEFINED (ctype)
5963           && ((code == MULT_EXPR && tcode == EXACT_DIV_EXPR)
5964               || (tcode == MULT_EXPR
5965                   && code != TRUNC_MOD_EXPR && code != CEIL_MOD_EXPR
5966                   && code != FLOOR_MOD_EXPR && code != ROUND_MOD_EXPR
5967                   && code != MULT_EXPR)))
5968         {
5969           if (wi::multiple_of_p (op1, c, TYPE_SIGN (type)))
5970             {
5971               if (TYPE_OVERFLOW_UNDEFINED (ctype))
5972                 *strict_overflow_p = true;
5973               return fold_build2 (tcode, ctype, fold_convert (ctype, op0),
5974                                   fold_convert (ctype,
5975                                                 const_binop (TRUNC_DIV_EXPR,
5976                                                              op1, c)));
5977             }
5978           else if (wi::multiple_of_p (c, op1, TYPE_SIGN (type)))
5979             {
5980               if (TYPE_OVERFLOW_UNDEFINED (ctype))
5981                 *strict_overflow_p = true;
5982               return fold_build2 (code, ctype, fold_convert (ctype, op0),
5983                                   fold_convert (ctype,
5984                                                 const_binop (TRUNC_DIV_EXPR,
5985                                                              c, op1)));
5986             }
5987         }
5988       break;
5989
5990     default:
5991       break;
5992     }
5993
5994   return 0;
5995 }
5996 \f
5997 /* Return a node which has the indicated constant VALUE (either 0 or
5998    1 for scalars or {-1,-1,..} or {0,0,...} for vectors),
5999    and is of the indicated TYPE.  */
6000
6001 tree
6002 constant_boolean_node (bool value, tree type)
6003 {
6004   if (type == integer_type_node)
6005     return value ? integer_one_node : integer_zero_node;
6006   else if (type == boolean_type_node)
6007     return value ? boolean_true_node : boolean_false_node;
6008   else if (TREE_CODE (type) == VECTOR_TYPE)
6009     return build_vector_from_val (type,
6010                                   build_int_cst (TREE_TYPE (type),
6011                                                  value ? -1 : 0));
6012   else
6013     return fold_convert (type, value ? integer_one_node : integer_zero_node);
6014 }
6015
6016
6017 /* Transform `a + (b ? x : y)' into `b ? (a + x) : (a + y)'.
6018    Transform, `a + (x < y)' into `(x < y) ? (a + 1) : (a + 0)'.  Here
6019    CODE corresponds to the `+', COND to the `(b ? x : y)' or `(x < y)'
6020    expression, and ARG to `a'.  If COND_FIRST_P is nonzero, then the
6021    COND is the first argument to CODE; otherwise (as in the example
6022    given here), it is the second argument.  TYPE is the type of the
6023    original expression.  Return NULL_TREE if no simplification is
6024    possible.  */
6025
6026 static tree
6027 fold_binary_op_with_conditional_arg (location_t loc,
6028                                      enum tree_code code,
6029                                      tree type, tree op0, tree op1,
6030                                      tree cond, tree arg, int cond_first_p)
6031 {
6032   tree cond_type = cond_first_p ? TREE_TYPE (op0) : TREE_TYPE (op1);
6033   tree arg_type = cond_first_p ? TREE_TYPE (op1) : TREE_TYPE (op0);
6034   tree test, true_value, false_value;
6035   tree lhs = NULL_TREE;
6036   tree rhs = NULL_TREE;
6037   enum tree_code cond_code = COND_EXPR;
6038
6039   if (TREE_CODE (cond) == COND_EXPR
6040       || TREE_CODE (cond) == VEC_COND_EXPR)
6041     {
6042       test = TREE_OPERAND (cond, 0);
6043       true_value = TREE_OPERAND (cond, 1);
6044       false_value = TREE_OPERAND (cond, 2);
6045       /* If this operand throws an expression, then it does not make
6046          sense to try to perform a logical or arithmetic operation
6047          involving it.  */
6048       if (VOID_TYPE_P (TREE_TYPE (true_value)))
6049         lhs = true_value;
6050       if (VOID_TYPE_P (TREE_TYPE (false_value)))
6051         rhs = false_value;
6052     }
6053   else
6054     {
6055       tree testtype = TREE_TYPE (cond);
6056       test = cond;
6057       true_value = constant_boolean_node (true, testtype);
6058       false_value = constant_boolean_node (false, testtype);
6059     }
6060
6061   if (TREE_CODE (TREE_TYPE (test)) == VECTOR_TYPE)
6062     cond_code = VEC_COND_EXPR;
6063
6064   /* This transformation is only worthwhile if we don't have to wrap ARG
6065      in a SAVE_EXPR and the operation can be simplified without recursing
6066      on at least one of the branches once its pushed inside the COND_EXPR.  */
6067   if (!TREE_CONSTANT (arg)
6068       && (TREE_SIDE_EFFECTS (arg)
6069           || TREE_CODE (arg) == COND_EXPR || TREE_CODE (arg) == VEC_COND_EXPR
6070           || TREE_CONSTANT (true_value) || TREE_CONSTANT (false_value)))
6071     return NULL_TREE;
6072
6073   arg = fold_convert_loc (loc, arg_type, arg);
6074   if (lhs == 0)
6075     {
6076       true_value = fold_convert_loc (loc, cond_type, true_value);
6077       if (cond_first_p)
6078         lhs = fold_build2_loc (loc, code, type, true_value, arg);
6079       else
6080         lhs = fold_build2_loc (loc, code, type, arg, true_value);
6081     }
6082   if (rhs == 0)
6083     {
6084       false_value = fold_convert_loc (loc, cond_type, false_value);
6085       if (cond_first_p)
6086         rhs = fold_build2_loc (loc, code, type, false_value, arg);
6087       else
6088         rhs = fold_build2_loc (loc, code, type, arg, false_value);
6089     }
6090
6091   /* Check that we have simplified at least one of the branches.  */
6092   if (!TREE_CONSTANT (arg) && !TREE_CONSTANT (lhs) && !TREE_CONSTANT (rhs))
6093     return NULL_TREE;
6094
6095   return fold_build3_loc (loc, cond_code, type, test, lhs, rhs);
6096 }
6097
6098 \f
6099 /* Subroutine of fold() that checks for the addition of +/- 0.0.
6100
6101    If !NEGATE, return true if ADDEND is +/-0.0 and, for all X of type
6102    TYPE, X + ADDEND is the same as X.  If NEGATE, return true if X -
6103    ADDEND is the same as X.
6104
6105    X + 0 and X - 0 both give X when X is NaN, infinite, or nonzero
6106    and finite.  The problematic cases are when X is zero, and its mode
6107    has signed zeros.  In the case of rounding towards -infinity,
6108    X - 0 is not the same as X because 0 - 0 is -0.  In other rounding
6109    modes, X + 0 is not the same as X because -0 + 0 is 0.  */
6110
6111 bool
6112 fold_real_zero_addition_p (const_tree type, const_tree addend, int negate)
6113 {
6114   if (!real_zerop (addend))
6115     return false;
6116
6117   /* Don't allow the fold with -fsignaling-nans.  */
6118   if (HONOR_SNANS (TYPE_MODE (type)))
6119     return false;
6120
6121   /* Allow the fold if zeros aren't signed, or their sign isn't important.  */
6122   if (!HONOR_SIGNED_ZEROS (TYPE_MODE (type)))
6123     return true;
6124
6125   /* In a vector or complex, we would need to check the sign of all zeros.  */
6126   if (TREE_CODE (addend) != REAL_CST)
6127     return false;
6128
6129   /* Treat x + -0 as x - 0 and x - -0 as x + 0.  */
6130   if (REAL_VALUE_MINUS_ZERO (TREE_REAL_CST (addend)))
6131     negate = !negate;
6132
6133   /* The mode has signed zeros, and we have to honor their sign.
6134      In this situation, there is only one case we can return true for.
6135      X - 0 is the same as X unless rounding towards -infinity is
6136      supported.  */
6137   return negate && !HONOR_SIGN_DEPENDENT_ROUNDING (TYPE_MODE (type));
6138 }
6139
6140 /* Subroutine of fold() that checks comparisons of built-in math
6141    functions against real constants.
6142
6143    FCODE is the DECL_FUNCTION_CODE of the built-in, CODE is the comparison
6144    operator: EQ_EXPR, NE_EXPR, GT_EXPR, LT_EXPR, GE_EXPR or LE_EXPR.  TYPE
6145    is the type of the result and ARG0 and ARG1 are the operands of the
6146    comparison.  ARG1 must be a TREE_REAL_CST.
6147
6148    The function returns the constant folded tree if a simplification
6149    can be made, and NULL_TREE otherwise.  */
6150
6151 static tree
6152 fold_mathfn_compare (location_t loc,
6153                      enum built_in_function fcode, enum tree_code code,
6154                      tree type, tree arg0, tree arg1)
6155 {
6156   REAL_VALUE_TYPE c;
6157
6158   if (BUILTIN_SQRT_P (fcode))
6159     {
6160       tree arg = CALL_EXPR_ARG (arg0, 0);
6161       machine_mode mode = TYPE_MODE (TREE_TYPE (arg0));
6162
6163       c = TREE_REAL_CST (arg1);
6164       if (REAL_VALUE_NEGATIVE (c))
6165         {
6166           /* sqrt(x) < y is always false, if y is negative.  */
6167           if (code == EQ_EXPR || code == LT_EXPR || code == LE_EXPR)
6168             return omit_one_operand_loc (loc, type, integer_zero_node, arg);
6169
6170           /* sqrt(x) > y is always true, if y is negative and we
6171              don't care about NaNs, i.e. negative values of x.  */
6172           if (code == NE_EXPR || !HONOR_NANS (mode))
6173             return omit_one_operand_loc (loc, type, integer_one_node, arg);
6174
6175           /* sqrt(x) > y is the same as x >= 0, if y is negative.  */
6176           return fold_build2_loc (loc, GE_EXPR, type, arg,
6177                               build_real (TREE_TYPE (arg), dconst0));
6178         }
6179       else if (code == GT_EXPR || code == GE_EXPR)
6180         {
6181           REAL_VALUE_TYPE c2;
6182
6183           REAL_ARITHMETIC (c2, MULT_EXPR, c, c);
6184           real_convert (&c2, mode, &c2);
6185
6186           if (REAL_VALUE_ISINF (c2))
6187             {
6188               /* sqrt(x) > y is x == +Inf, when y is very large.  */
6189               if (HONOR_INFINITIES (mode))
6190                 return fold_build2_loc (loc, EQ_EXPR, type, arg,
6191                                     build_real (TREE_TYPE (arg), c2));
6192
6193               /* sqrt(x) > y is always false, when y is very large
6194                  and we don't care about infinities.  */
6195               return omit_one_operand_loc (loc, type, integer_zero_node, arg);
6196             }
6197
6198           /* sqrt(x) > c is the same as x > c*c.  */
6199           return fold_build2_loc (loc, code, type, arg,
6200                               build_real (TREE_TYPE (arg), c2));
6201         }
6202       else if (code == LT_EXPR || code == LE_EXPR)
6203         {
6204           REAL_VALUE_TYPE c2;
6205
6206           REAL_ARITHMETIC (c2, MULT_EXPR, c, c);
6207           real_convert (&c2, mode, &c2);
6208
6209           if (REAL_VALUE_ISINF (c2))
6210             {
6211               /* sqrt(x) < y is always true, when y is a very large
6212                  value and we don't care about NaNs or Infinities.  */
6213               if (! HONOR_NANS (mode) && ! HONOR_INFINITIES (mode))
6214                 return omit_one_operand_loc (loc, type, integer_one_node, arg);
6215
6216               /* sqrt(x) < y is x != +Inf when y is very large and we
6217                  don't care about NaNs.  */
6218               if (! HONOR_NANS (mode))
6219                 return fold_build2_loc (loc, NE_EXPR, type, arg,
6220                                     build_real (TREE_TYPE (arg), c2));
6221
6222               /* sqrt(x) < y is x >= 0 when y is very large and we
6223                  don't care about Infinities.  */
6224               if (! HONOR_INFINITIES (mode))
6225                 return fold_build2_loc (loc, GE_EXPR, type, arg,
6226                                     build_real (TREE_TYPE (arg), dconst0));
6227
6228               /* sqrt(x) < y is x >= 0 && x != +Inf, when y is large.  */
6229               arg = save_expr (arg);
6230               return fold_build2_loc (loc, TRUTH_ANDIF_EXPR, type,
6231                                   fold_build2_loc (loc, GE_EXPR, type, arg,
6232                                                build_real (TREE_TYPE (arg),
6233                                                            dconst0)),
6234                                   fold_build2_loc (loc, NE_EXPR, type, arg,
6235                                                build_real (TREE_TYPE (arg),
6236                                                            c2)));
6237             }
6238
6239           /* sqrt(x) < c is the same as x < c*c, if we ignore NaNs.  */
6240           if (! HONOR_NANS (mode))
6241             return fold_build2_loc (loc, code, type, arg,
6242                                 build_real (TREE_TYPE (arg), c2));
6243
6244           /* sqrt(x) < c is the same as x >= 0 && x < c*c.  */
6245           arg = save_expr (arg);
6246           return fold_build2_loc (loc, TRUTH_ANDIF_EXPR, type,
6247                                   fold_build2_loc (loc, GE_EXPR, type, arg,
6248                                                build_real (TREE_TYPE (arg),
6249                                                            dconst0)),
6250                                   fold_build2_loc (loc, code, type, arg,
6251                                                build_real (TREE_TYPE (arg),
6252                                                            c2)));
6253         }
6254     }
6255
6256   return NULL_TREE;
6257 }
6258
6259 /* Subroutine of fold() that optimizes comparisons against Infinities,
6260    either +Inf or -Inf.
6261
6262    CODE is the comparison operator: EQ_EXPR, NE_EXPR, GT_EXPR, LT_EXPR,
6263    GE_EXPR or LE_EXPR.  TYPE is the type of the result and ARG0 and ARG1
6264    are the operands of the comparison.  ARG1 must be a TREE_REAL_CST.
6265
6266    The function returns the constant folded tree if a simplification
6267    can be made, and NULL_TREE otherwise.  */
6268
6269 static tree
6270 fold_inf_compare (location_t loc, enum tree_code code, tree type,
6271                   tree arg0, tree arg1)
6272 {
6273   machine_mode mode;
6274   REAL_VALUE_TYPE max;
6275   tree temp;
6276   bool neg;
6277
6278   mode = TYPE_MODE (TREE_TYPE (arg0));
6279
6280   /* For negative infinity swap the sense of the comparison.  */
6281   neg = REAL_VALUE_NEGATIVE (TREE_REAL_CST (arg1));
6282   if (neg)
6283     code = swap_tree_comparison (code);
6284
6285   switch (code)
6286     {
6287     case GT_EXPR:
6288       /* x > +Inf is always false, if with ignore sNANs.  */
6289       if (HONOR_SNANS (mode))
6290         return NULL_TREE;
6291       return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
6292
6293     case LE_EXPR:
6294       /* x <= +Inf is always true, if we don't case about NaNs.  */
6295       if (! HONOR_NANS (mode))
6296         return omit_one_operand_loc (loc, type, integer_one_node, arg0);
6297
6298       /* x <= +Inf is the same as x == x, i.e. isfinite(x).  */
6299       arg0 = save_expr (arg0);
6300       return fold_build2_loc (loc, EQ_EXPR, type, arg0, arg0);
6301
6302     case EQ_EXPR:
6303     case GE_EXPR:
6304       /* x == +Inf and x >= +Inf are always equal to x > DBL_MAX.  */
6305       real_maxval (&max, neg, mode);
6306       return fold_build2_loc (loc, neg ? LT_EXPR : GT_EXPR, type,
6307                           arg0, build_real (TREE_TYPE (arg0), max));
6308
6309     case LT_EXPR:
6310       /* x < +Inf is always equal to x <= DBL_MAX.  */
6311       real_maxval (&max, neg, mode);
6312       return fold_build2_loc (loc, neg ? GE_EXPR : LE_EXPR, type,
6313                           arg0, build_real (TREE_TYPE (arg0), max));
6314
6315     case NE_EXPR:
6316       /* x != +Inf is always equal to !(x > DBL_MAX).  */
6317       real_maxval (&max, neg, mode);
6318       if (! HONOR_NANS (mode))
6319         return fold_build2_loc (loc, neg ? GE_EXPR : LE_EXPR, type,
6320                             arg0, build_real (TREE_TYPE (arg0), max));
6321
6322       temp = fold_build2_loc (loc, neg ? LT_EXPR : GT_EXPR, type,
6323                           arg0, build_real (TREE_TYPE (arg0), max));
6324       return fold_build1_loc (loc, TRUTH_NOT_EXPR, type, temp);
6325
6326     default:
6327       break;
6328     }
6329
6330   return NULL_TREE;
6331 }
6332
6333 /* Subroutine of fold() that optimizes comparisons of a division by
6334    a nonzero integer constant against an integer constant, i.e.
6335    X/C1 op C2.
6336
6337    CODE is the comparison operator: EQ_EXPR, NE_EXPR, GT_EXPR, LT_EXPR,
6338    GE_EXPR or LE_EXPR.  TYPE is the type of the result and ARG0 and ARG1
6339    are the operands of the comparison.  ARG1 must be a TREE_REAL_CST.
6340
6341    The function returns the constant folded tree if a simplification
6342    can be made, and NULL_TREE otherwise.  */
6343
6344 static tree
6345 fold_div_compare (location_t loc,
6346                   enum tree_code code, tree type, tree arg0, tree arg1)
6347 {
6348   tree prod, tmp, hi, lo;
6349   tree arg00 = TREE_OPERAND (arg0, 0);
6350   tree arg01 = TREE_OPERAND (arg0, 1);
6351   signop sign = TYPE_SIGN (TREE_TYPE (arg0));
6352   bool neg_overflow = false;
6353   bool overflow;
6354
6355   /* We have to do this the hard way to detect unsigned overflow.
6356      prod = int_const_binop (MULT_EXPR, arg01, arg1);  */
6357   wide_int val = wi::mul (arg01, arg1, sign, &overflow);
6358   prod = force_fit_type (TREE_TYPE (arg00), val, -1, overflow);
6359   neg_overflow = false;
6360
6361   if (sign == UNSIGNED)
6362     {
6363       tmp = int_const_binop (MINUS_EXPR, arg01,
6364                              build_int_cst (TREE_TYPE (arg01), 1));
6365       lo = prod;
6366
6367       /* Likewise hi = int_const_binop (PLUS_EXPR, prod, tmp).  */
6368       val = wi::add (prod, tmp, sign, &overflow);
6369       hi = force_fit_type (TREE_TYPE (arg00), val,
6370                            -1, overflow | TREE_OVERFLOW (prod));
6371     }
6372   else if (tree_int_cst_sgn (arg01) >= 0)
6373     {
6374       tmp = int_const_binop (MINUS_EXPR, arg01,
6375                              build_int_cst (TREE_TYPE (arg01), 1));
6376       switch (tree_int_cst_sgn (arg1))
6377         {
6378         case -1:
6379           neg_overflow = true;
6380           lo = int_const_binop (MINUS_EXPR, prod, tmp);
6381           hi = prod;
6382           break;
6383
6384         case  0:
6385           lo = fold_negate_const (tmp, TREE_TYPE (arg0));
6386           hi = tmp;
6387           break;
6388
6389         case  1:
6390           hi = int_const_binop (PLUS_EXPR, prod, tmp);
6391           lo = prod;
6392           break;
6393
6394         default:
6395           gcc_unreachable ();
6396         }
6397     }
6398   else
6399     {
6400       /* A negative divisor reverses the relational operators.  */
6401       code = swap_tree_comparison (code);
6402
6403       tmp = int_const_binop (PLUS_EXPR, arg01,
6404                              build_int_cst (TREE_TYPE (arg01), 1));
6405       switch (tree_int_cst_sgn (arg1))
6406         {
6407         case -1:
6408           hi = int_const_binop (MINUS_EXPR, prod, tmp);
6409           lo = prod;
6410           break;
6411
6412         case  0:
6413           hi = fold_negate_const (tmp, TREE_TYPE (arg0));
6414           lo = tmp;
6415           break;
6416
6417         case  1:
6418           neg_overflow = true;
6419           lo = int_const_binop (PLUS_EXPR, prod, tmp);
6420           hi = prod;
6421           break;
6422
6423         default:
6424           gcc_unreachable ();
6425         }
6426     }
6427
6428   switch (code)
6429     {
6430     case EQ_EXPR:
6431       if (TREE_OVERFLOW (lo) && TREE_OVERFLOW (hi))
6432         return omit_one_operand_loc (loc, type, integer_zero_node, arg00);
6433       if (TREE_OVERFLOW (hi))
6434         return fold_build2_loc (loc, GE_EXPR, type, arg00, lo);
6435       if (TREE_OVERFLOW (lo))
6436         return fold_build2_loc (loc, LE_EXPR, type, arg00, hi);
6437       return build_range_check (loc, type, arg00, 1, lo, hi);
6438
6439     case NE_EXPR:
6440       if (TREE_OVERFLOW (lo) && TREE_OVERFLOW (hi))
6441         return omit_one_operand_loc (loc, type, integer_one_node, arg00);
6442       if (TREE_OVERFLOW (hi))
6443         return fold_build2_loc (loc, LT_EXPR, type, arg00, lo);
6444       if (TREE_OVERFLOW (lo))
6445         return fold_build2_loc (loc, GT_EXPR, type, arg00, hi);
6446       return build_range_check (loc, type, arg00, 0, lo, hi);
6447
6448     case LT_EXPR:
6449       if (TREE_OVERFLOW (lo))
6450         {
6451           tmp = neg_overflow ? integer_zero_node : integer_one_node;
6452           return omit_one_operand_loc (loc, type, tmp, arg00);
6453         }
6454       return fold_build2_loc (loc, LT_EXPR, type, arg00, lo);
6455
6456     case LE_EXPR:
6457       if (TREE_OVERFLOW (hi))
6458         {
6459           tmp = neg_overflow ? integer_zero_node : integer_one_node;
6460           return omit_one_operand_loc (loc, type, tmp, arg00);
6461         }
6462       return fold_build2_loc (loc, LE_EXPR, type, arg00, hi);
6463
6464     case GT_EXPR:
6465       if (TREE_OVERFLOW (hi))
6466         {
6467           tmp = neg_overflow ? integer_one_node : integer_zero_node;
6468           return omit_one_operand_loc (loc, type, tmp, arg00);
6469         }
6470       return fold_build2_loc (loc, GT_EXPR, type, arg00, hi);
6471
6472     case GE_EXPR:
6473       if (TREE_OVERFLOW (lo))
6474         {
6475           tmp = neg_overflow ? integer_one_node : integer_zero_node;
6476           return omit_one_operand_loc (loc, type, tmp, arg00);
6477         }
6478       return fold_build2_loc (loc, GE_EXPR, type, arg00, lo);
6479
6480     default:
6481       break;
6482     }
6483
6484   return NULL_TREE;
6485 }
6486
6487
6488 /* If CODE with arguments ARG0 and ARG1 represents a single bit
6489    equality/inequality test, then return a simplified form of the test
6490    using a sign testing.  Otherwise return NULL.  TYPE is the desired
6491    result type.  */
6492
6493 static tree
6494 fold_single_bit_test_into_sign_test (location_t loc,
6495                                      enum tree_code code, tree arg0, tree arg1,
6496                                      tree result_type)
6497 {
6498   /* If this is testing a single bit, we can optimize the test.  */
6499   if ((code == NE_EXPR || code == EQ_EXPR)
6500       && TREE_CODE (arg0) == BIT_AND_EXPR && integer_zerop (arg1)
6501       && integer_pow2p (TREE_OPERAND (arg0, 1)))
6502     {
6503       /* If we have (A & C) != 0 where C is the sign bit of A, convert
6504          this into A < 0.  Similarly for (A & C) == 0 into A >= 0.  */
6505       tree arg00 = sign_bit_p (TREE_OPERAND (arg0, 0), TREE_OPERAND (arg0, 1));
6506
6507       if (arg00 != NULL_TREE
6508           /* This is only a win if casting to a signed type is cheap,
6509              i.e. when arg00's type is not a partial mode.  */
6510           && TYPE_PRECISION (TREE_TYPE (arg00))
6511              == GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (arg00))))
6512         {
6513           tree stype = signed_type_for (TREE_TYPE (arg00));
6514           return fold_build2_loc (loc, code == EQ_EXPR ? GE_EXPR : LT_EXPR,
6515                               result_type,
6516                               fold_convert_loc (loc, stype, arg00),
6517                               build_int_cst (stype, 0));
6518         }
6519     }
6520
6521   return NULL_TREE;
6522 }
6523
6524 /* If CODE with arguments ARG0 and ARG1 represents a single bit
6525    equality/inequality test, then return a simplified form of
6526    the test using shifts and logical operations.  Otherwise return
6527    NULL.  TYPE is the desired result type.  */
6528
6529 tree
6530 fold_single_bit_test (location_t loc, enum tree_code code,
6531                       tree arg0, tree arg1, tree result_type)
6532 {
6533   /* If this is testing a single bit, we can optimize the test.  */
6534   if ((code == NE_EXPR || code == EQ_EXPR)
6535       && TREE_CODE (arg0) == BIT_AND_EXPR && integer_zerop (arg1)
6536       && integer_pow2p (TREE_OPERAND (arg0, 1)))
6537     {
6538       tree inner = TREE_OPERAND (arg0, 0);
6539       tree type = TREE_TYPE (arg0);
6540       int bitnum = tree_log2 (TREE_OPERAND (arg0, 1));
6541       machine_mode operand_mode = TYPE_MODE (type);
6542       int ops_unsigned;
6543       tree signed_type, unsigned_type, intermediate_type;
6544       tree tem, one;
6545
6546       /* First, see if we can fold the single bit test into a sign-bit
6547          test.  */
6548       tem = fold_single_bit_test_into_sign_test (loc, code, arg0, arg1,
6549                                                  result_type);
6550       if (tem)
6551         return tem;
6552
6553       /* Otherwise we have (A & C) != 0 where C is a single bit,
6554          convert that into ((A >> C2) & 1).  Where C2 = log2(C).
6555          Similarly for (A & C) == 0.  */
6556
6557       /* If INNER is a right shift of a constant and it plus BITNUM does
6558          not overflow, adjust BITNUM and INNER.  */
6559       if (TREE_CODE (inner) == RSHIFT_EXPR
6560           && TREE_CODE (TREE_OPERAND (inner, 1)) == INTEGER_CST
6561           && bitnum < TYPE_PRECISION (type)
6562           && wi::ltu_p (TREE_OPERAND (inner, 1),
6563                         TYPE_PRECISION (type) - bitnum))
6564         {
6565           bitnum += tree_to_uhwi (TREE_OPERAND (inner, 1));
6566           inner = TREE_OPERAND (inner, 0);
6567         }
6568
6569       /* If we are going to be able to omit the AND below, we must do our
6570          operations as unsigned.  If we must use the AND, we have a choice.
6571          Normally unsigned is faster, but for some machines signed is.  */
6572 #ifdef LOAD_EXTEND_OP
6573       ops_unsigned = (LOAD_EXTEND_OP (operand_mode) == SIGN_EXTEND
6574                       && !flag_syntax_only) ? 0 : 1;
6575 #else
6576       ops_unsigned = 1;
6577 #endif
6578
6579       signed_type = lang_hooks.types.type_for_mode (operand_mode, 0);
6580       unsigned_type = lang_hooks.types.type_for_mode (operand_mode, 1);
6581       intermediate_type = ops_unsigned ? unsigned_type : signed_type;
6582       inner = fold_convert_loc (loc, intermediate_type, inner);
6583
6584       if (bitnum != 0)
6585         inner = build2 (RSHIFT_EXPR, intermediate_type,
6586                         inner, size_int (bitnum));
6587
6588       one = build_int_cst (intermediate_type, 1);
6589
6590       if (code == EQ_EXPR)
6591         inner = fold_build2_loc (loc, BIT_XOR_EXPR, intermediate_type, inner, one);
6592
6593       /* Put the AND last so it can combine with more things.  */
6594       inner = build2 (BIT_AND_EXPR, intermediate_type, inner, one);
6595
6596       /* Make sure to return the proper type.  */
6597       inner = fold_convert_loc (loc, result_type, inner);
6598
6599       return inner;
6600     }
6601   return NULL_TREE;
6602 }
6603
6604 /* Check whether we are allowed to reorder operands arg0 and arg1,
6605    such that the evaluation of arg1 occurs before arg0.  */
6606
6607 static bool
6608 reorder_operands_p (const_tree arg0, const_tree arg1)
6609 {
6610   if (! flag_evaluation_order)
6611       return true;
6612   if (TREE_CONSTANT (arg0) || TREE_CONSTANT (arg1))
6613     return true;
6614   return ! TREE_SIDE_EFFECTS (arg0)
6615          && ! TREE_SIDE_EFFECTS (arg1);
6616 }
6617
6618 /* Test whether it is preferable two swap two operands, ARG0 and
6619    ARG1, for example because ARG0 is an integer constant and ARG1
6620    isn't.  If REORDER is true, only recommend swapping if we can
6621    evaluate the operands in reverse order.  */
6622
6623 bool
6624 tree_swap_operands_p (const_tree arg0, const_tree arg1, bool reorder)
6625 {
6626   if (CONSTANT_CLASS_P (arg1))
6627     return 0;
6628   if (CONSTANT_CLASS_P (arg0))
6629     return 1;
6630
6631   STRIP_SIGN_NOPS (arg0);
6632   STRIP_SIGN_NOPS (arg1);
6633
6634   if (TREE_CONSTANT (arg1))
6635     return 0;
6636   if (TREE_CONSTANT (arg0))
6637     return 1;
6638
6639   if (reorder && flag_evaluation_order
6640       && (TREE_SIDE_EFFECTS (arg0) || TREE_SIDE_EFFECTS (arg1)))
6641     return 0;
6642
6643   /* It is preferable to swap two SSA_NAME to ensure a canonical form
6644      for commutative and comparison operators.  Ensuring a canonical
6645      form allows the optimizers to find additional redundancies without
6646      having to explicitly check for both orderings.  */
6647   if (TREE_CODE (arg0) == SSA_NAME
6648       && TREE_CODE (arg1) == SSA_NAME
6649       && SSA_NAME_VERSION (arg0) > SSA_NAME_VERSION (arg1))
6650     return 1;
6651
6652   /* Put SSA_NAMEs last.  */
6653   if (TREE_CODE (arg1) == SSA_NAME)
6654     return 0;
6655   if (TREE_CODE (arg0) == SSA_NAME)
6656     return 1;
6657
6658   /* Put variables last.  */
6659   if (DECL_P (arg1))
6660     return 0;
6661   if (DECL_P (arg0))
6662     return 1;
6663
6664   return 0;
6665 }
6666
6667 /* Fold comparison ARG0 CODE ARG1 (with result in TYPE), where
6668    ARG0 is extended to a wider type.  */
6669
6670 static tree
6671 fold_widened_comparison (location_t loc, enum tree_code code,
6672                          tree type, tree arg0, tree arg1)
6673 {
6674   tree arg0_unw = get_unwidened (arg0, NULL_TREE);
6675   tree arg1_unw;
6676   tree shorter_type, outer_type;
6677   tree min, max;
6678   bool above, below;
6679
6680   if (arg0_unw == arg0)
6681     return NULL_TREE;
6682   shorter_type = TREE_TYPE (arg0_unw);
6683
6684 #ifdef HAVE_canonicalize_funcptr_for_compare
6685   /* Disable this optimization if we're casting a function pointer
6686      type on targets that require function pointer canonicalization.  */
6687   if (HAVE_canonicalize_funcptr_for_compare
6688       && TREE_CODE (shorter_type) == POINTER_TYPE
6689       && TREE_CODE (TREE_TYPE (shorter_type)) == FUNCTION_TYPE)
6690     return NULL_TREE;
6691 #endif
6692
6693   if (TYPE_PRECISION (TREE_TYPE (arg0)) <= TYPE_PRECISION (shorter_type))
6694     return NULL_TREE;
6695
6696   arg1_unw = get_unwidened (arg1, NULL_TREE);
6697
6698   /* If possible, express the comparison in the shorter mode.  */
6699   if ((code == EQ_EXPR || code == NE_EXPR
6700        || TYPE_UNSIGNED (TREE_TYPE (arg0)) == TYPE_UNSIGNED (shorter_type))
6701       && (TREE_TYPE (arg1_unw) == shorter_type
6702           || ((TYPE_PRECISION (shorter_type)
6703                >= TYPE_PRECISION (TREE_TYPE (arg1_unw)))
6704               && (TYPE_UNSIGNED (shorter_type)
6705                   == TYPE_UNSIGNED (TREE_TYPE (arg1_unw))))
6706           || (TREE_CODE (arg1_unw) == INTEGER_CST
6707               && (TREE_CODE (shorter_type) == INTEGER_TYPE
6708                   || TREE_CODE (shorter_type) == BOOLEAN_TYPE)
6709               && int_fits_type_p (arg1_unw, shorter_type))))
6710     return fold_build2_loc (loc, code, type, arg0_unw,
6711                         fold_convert_loc (loc, shorter_type, arg1_unw));
6712
6713   if (TREE_CODE (arg1_unw) != INTEGER_CST
6714       || TREE_CODE (shorter_type) != INTEGER_TYPE
6715       || !int_fits_type_p (arg1_unw, shorter_type))
6716     return NULL_TREE;
6717
6718   /* If we are comparing with the integer that does not fit into the range
6719      of the shorter type, the result is known.  */
6720   outer_type = TREE_TYPE (arg1_unw);
6721   min = lower_bound_in_type (outer_type, shorter_type);
6722   max = upper_bound_in_type (outer_type, shorter_type);
6723
6724   above = integer_nonzerop (fold_relational_const (LT_EXPR, type,
6725                                                    max, arg1_unw));
6726   below = integer_nonzerop (fold_relational_const (LT_EXPR, type,
6727                                                    arg1_unw, min));
6728
6729   switch (code)
6730     {
6731     case EQ_EXPR:
6732       if (above || below)
6733         return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
6734       break;
6735
6736     case NE_EXPR:
6737       if (above || below)
6738         return omit_one_operand_loc (loc, type, integer_one_node, arg0);
6739       break;
6740
6741     case LT_EXPR:
6742     case LE_EXPR:
6743       if (above)
6744         return omit_one_operand_loc (loc, type, integer_one_node, arg0);
6745       else if (below)
6746         return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
6747
6748     case GT_EXPR:
6749     case GE_EXPR:
6750       if (above)
6751         return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
6752       else if (below)
6753         return omit_one_operand_loc (loc, type, integer_one_node, arg0);
6754
6755     default:
6756       break;
6757     }
6758
6759   return NULL_TREE;
6760 }
6761
6762 /* Fold comparison ARG0 CODE ARG1 (with result in TYPE), where for
6763    ARG0 just the signedness is changed.  */
6764
6765 static tree
6766 fold_sign_changed_comparison (location_t loc, enum tree_code code, tree type,
6767                               tree arg0, tree arg1)
6768 {
6769   tree arg0_inner;
6770   tree inner_type, outer_type;
6771
6772   if (!CONVERT_EXPR_P (arg0))
6773     return NULL_TREE;
6774
6775   outer_type = TREE_TYPE (arg0);
6776   arg0_inner = TREE_OPERAND (arg0, 0);
6777   inner_type = TREE_TYPE (arg0_inner);
6778
6779 #ifdef HAVE_canonicalize_funcptr_for_compare
6780   /* Disable this optimization if we're casting a function pointer
6781      type on targets that require function pointer canonicalization.  */
6782   if (HAVE_canonicalize_funcptr_for_compare
6783       && TREE_CODE (inner_type) == POINTER_TYPE
6784       && TREE_CODE (TREE_TYPE (inner_type)) == FUNCTION_TYPE)
6785     return NULL_TREE;
6786 #endif
6787
6788   if (TYPE_PRECISION (inner_type) != TYPE_PRECISION (outer_type))
6789     return NULL_TREE;
6790
6791   if (TREE_CODE (arg1) != INTEGER_CST
6792       && !(CONVERT_EXPR_P (arg1)
6793            && TREE_TYPE (TREE_OPERAND (arg1, 0)) == inner_type))
6794     return NULL_TREE;
6795
6796   if (TYPE_UNSIGNED (inner_type) != TYPE_UNSIGNED (outer_type)
6797       && code != NE_EXPR
6798       && code != EQ_EXPR)
6799     return NULL_TREE;
6800
6801   if (POINTER_TYPE_P (inner_type) != POINTER_TYPE_P (outer_type))
6802     return NULL_TREE;
6803
6804   if (TREE_CODE (arg1) == INTEGER_CST)
6805     arg1 = force_fit_type (inner_type, wi::to_widest (arg1), 0,
6806                            TREE_OVERFLOW (arg1));
6807   else
6808     arg1 = fold_convert_loc (loc, inner_type, arg1);
6809
6810   return fold_build2_loc (loc, code, type, arg0_inner, arg1);
6811 }
6812
6813
6814 /* Fold A < X && A + 1 > Y to A < X && A >= Y.  Normally A + 1 > Y
6815    means A >= Y && A != MAX, but in this case we know that
6816    A < X <= MAX.  INEQ is A + 1 > Y, BOUND is A < X.  */
6817
6818 static tree
6819 fold_to_nonsharp_ineq_using_bound (location_t loc, tree ineq, tree bound)
6820 {
6821   tree a, typea, type = TREE_TYPE (ineq), a1, diff, y;
6822
6823   if (TREE_CODE (bound) == LT_EXPR)
6824     a = TREE_OPERAND (bound, 0);
6825   else if (TREE_CODE (bound) == GT_EXPR)
6826     a = TREE_OPERAND (bound, 1);
6827   else
6828     return NULL_TREE;
6829
6830   typea = TREE_TYPE (a);
6831   if (!INTEGRAL_TYPE_P (typea)
6832       && !POINTER_TYPE_P (typea))
6833     return NULL_TREE;
6834
6835   if (TREE_CODE (ineq) == LT_EXPR)
6836     {
6837       a1 = TREE_OPERAND (ineq, 1);
6838       y = TREE_OPERAND (ineq, 0);
6839     }
6840   else if (TREE_CODE (ineq) == GT_EXPR)
6841     {
6842       a1 = TREE_OPERAND (ineq, 0);
6843       y = TREE_OPERAND (ineq, 1);
6844     }
6845   else
6846     return NULL_TREE;
6847
6848   if (TREE_TYPE (a1) != typea)
6849     return NULL_TREE;
6850
6851   if (POINTER_TYPE_P (typea))
6852     {
6853       /* Convert the pointer types into integer before taking the difference.  */
6854       tree ta = fold_convert_loc (loc, ssizetype, a);
6855       tree ta1 = fold_convert_loc (loc, ssizetype, a1);
6856       diff = fold_binary_loc (loc, MINUS_EXPR, ssizetype, ta1, ta);
6857     }
6858   else
6859     diff = fold_binary_loc (loc, MINUS_EXPR, typea, a1, a);
6860
6861   if (!diff || !integer_onep (diff))
6862    return NULL_TREE;
6863
6864   return fold_build2_loc (loc, GE_EXPR, type, a, y);
6865 }
6866
6867 /* Fold a sum or difference of at least one multiplication.
6868    Returns the folded tree or NULL if no simplification could be made.  */
6869
6870 static tree
6871 fold_plusminus_mult_expr (location_t loc, enum tree_code code, tree type,
6872                           tree arg0, tree arg1)
6873 {
6874   tree arg00, arg01, arg10, arg11;
6875   tree alt0 = NULL_TREE, alt1 = NULL_TREE, same;
6876
6877   /* (A * C) +- (B * C) -> (A+-B) * C.
6878      (A * C) +- A -> A * (C+-1).
6879      We are most concerned about the case where C is a constant,
6880      but other combinations show up during loop reduction.  Since
6881      it is not difficult, try all four possibilities.  */
6882
6883   if (TREE_CODE (arg0) == MULT_EXPR)
6884     {
6885       arg00 = TREE_OPERAND (arg0, 0);
6886       arg01 = TREE_OPERAND (arg0, 1);
6887     }
6888   else if (TREE_CODE (arg0) == INTEGER_CST)
6889     {
6890       arg00 = build_one_cst (type);
6891       arg01 = arg0;
6892     }
6893   else
6894     {
6895       /* We cannot generate constant 1 for fract.  */
6896       if (ALL_FRACT_MODE_P (TYPE_MODE (type)))
6897         return NULL_TREE;
6898       arg00 = arg0;
6899       arg01 = build_one_cst (type);
6900     }
6901   if (TREE_CODE (arg1) == MULT_EXPR)
6902     {
6903       arg10 = TREE_OPERAND (arg1, 0);
6904       arg11 = TREE_OPERAND (arg1, 1);
6905     }
6906   else if (TREE_CODE (arg1) == INTEGER_CST)
6907     {
6908       arg10 = build_one_cst (type);
6909       /* As we canonicalize A - 2 to A + -2 get rid of that sign for
6910          the purpose of this canonicalization.  */
6911       if (wi::neg_p (arg1, TYPE_SIGN (TREE_TYPE (arg1)))
6912           && negate_expr_p (arg1)
6913           && code == PLUS_EXPR)
6914         {
6915           arg11 = negate_expr (arg1);
6916           code = MINUS_EXPR;
6917         }
6918       else
6919         arg11 = arg1;
6920     }
6921   else
6922     {
6923       /* We cannot generate constant 1 for fract.  */
6924       if (ALL_FRACT_MODE_P (TYPE_MODE (type)))
6925         return NULL_TREE;
6926       arg10 = arg1;
6927       arg11 = build_one_cst (type);
6928     }
6929   same = NULL_TREE;
6930
6931   if (operand_equal_p (arg01, arg11, 0))
6932     same = arg01, alt0 = arg00, alt1 = arg10;
6933   else if (operand_equal_p (arg00, arg10, 0))
6934     same = arg00, alt0 = arg01, alt1 = arg11;
6935   else if (operand_equal_p (arg00, arg11, 0))
6936     same = arg00, alt0 = arg01, alt1 = arg10;
6937   else if (operand_equal_p (arg01, arg10, 0))
6938     same = arg01, alt0 = arg00, alt1 = arg11;
6939
6940   /* No identical multiplicands; see if we can find a common
6941      power-of-two factor in non-power-of-two multiplies.  This
6942      can help in multi-dimensional array access.  */
6943   else if (tree_fits_shwi_p (arg01)
6944            && tree_fits_shwi_p (arg11))
6945     {
6946       HOST_WIDE_INT int01, int11, tmp;
6947       bool swap = false;
6948       tree maybe_same;
6949       int01 = tree_to_shwi (arg01);
6950       int11 = tree_to_shwi (arg11);
6951
6952       /* Move min of absolute values to int11.  */
6953       if (absu_hwi (int01) < absu_hwi (int11))
6954         {
6955           tmp = int01, int01 = int11, int11 = tmp;
6956           alt0 = arg00, arg00 = arg10, arg10 = alt0;
6957           maybe_same = arg01;
6958           swap = true;
6959         }
6960       else
6961         maybe_same = arg11;
6962
6963       if (exact_log2 (absu_hwi (int11)) > 0 && int01 % int11 == 0
6964           /* The remainder should not be a constant, otherwise we
6965              end up folding i * 4 + 2 to (i * 2 + 1) * 2 which has
6966              increased the number of multiplications necessary.  */
6967           && TREE_CODE (arg10) != INTEGER_CST)
6968         {
6969           alt0 = fold_build2_loc (loc, MULT_EXPR, TREE_TYPE (arg00), arg00,
6970                               build_int_cst (TREE_TYPE (arg00),
6971                                              int01 / int11));
6972           alt1 = arg10;
6973           same = maybe_same;
6974           if (swap)
6975             maybe_same = alt0, alt0 = alt1, alt1 = maybe_same;
6976         }
6977     }
6978
6979   if (same)
6980     return fold_build2_loc (loc, MULT_EXPR, type,
6981                         fold_build2_loc (loc, code, type,
6982                                      fold_convert_loc (loc, type, alt0),
6983                                      fold_convert_loc (loc, type, alt1)),
6984                         fold_convert_loc (loc, type, same));
6985
6986   return NULL_TREE;
6987 }
6988
6989 /* Subroutine of native_encode_expr.  Encode the INTEGER_CST
6990    specified by EXPR into the buffer PTR of length LEN bytes.
6991    Return the number of bytes placed in the buffer, or zero
6992    upon failure.  */
6993
6994 static int
6995 native_encode_int (const_tree expr, unsigned char *ptr, int len, int off)
6996 {
6997   tree type = TREE_TYPE (expr);
6998   int total_bytes = GET_MODE_SIZE (TYPE_MODE (type));
6999   int byte, offset, word, words;
7000   unsigned char value;
7001
7002   if ((off == -1 && total_bytes > len)
7003       || off >= total_bytes)
7004     return 0;
7005   if (off == -1)
7006     off = 0;
7007   words = total_bytes / UNITS_PER_WORD;
7008
7009   for (byte = 0; byte < total_bytes; byte++)
7010     {
7011       int bitpos = byte * BITS_PER_UNIT;
7012       /* Extend EXPR according to TYPE_SIGN if the precision isn't a whole
7013          number of bytes.  */
7014       value = wi::extract_uhwi (wi::to_widest (expr), bitpos, BITS_PER_UNIT);
7015
7016       if (total_bytes > UNITS_PER_WORD)
7017         {
7018           word = byte / UNITS_PER_WORD;
7019           if (WORDS_BIG_ENDIAN)
7020             word = (words - 1) - word;
7021           offset = word * UNITS_PER_WORD;
7022           if (BYTES_BIG_ENDIAN)
7023             offset += (UNITS_PER_WORD - 1) - (byte % UNITS_PER_WORD);
7024           else
7025             offset += byte % UNITS_PER_WORD;
7026         }
7027       else
7028         offset = BYTES_BIG_ENDIAN ? (total_bytes - 1) - byte : byte;
7029       if (offset >= off
7030           && offset - off < len)
7031         ptr[offset - off] = value;
7032     }
7033   return MIN (len, total_bytes - off);
7034 }
7035
7036
7037 /* Subroutine of native_encode_expr.  Encode the FIXED_CST
7038    specified by EXPR into the buffer PTR of length LEN bytes.
7039    Return the number of bytes placed in the buffer, or zero
7040    upon failure.  */
7041
7042 static int
7043 native_encode_fixed (const_tree expr, unsigned char *ptr, int len, int off)
7044 {
7045   tree type = TREE_TYPE (expr);
7046   machine_mode mode = TYPE_MODE (type);
7047   int total_bytes = GET_MODE_SIZE (mode);
7048   FIXED_VALUE_TYPE value;
7049   tree i_value, i_type;
7050
7051   if (total_bytes * BITS_PER_UNIT > HOST_BITS_PER_DOUBLE_INT)
7052     return 0;
7053
7054   i_type = lang_hooks.types.type_for_size (GET_MODE_BITSIZE (mode), 1);
7055
7056   if (NULL_TREE == i_type
7057       || TYPE_PRECISION (i_type) != total_bytes)
7058     return 0;
7059   
7060   value = TREE_FIXED_CST (expr);
7061   i_value = double_int_to_tree (i_type, value.data);
7062
7063   return native_encode_int (i_value, ptr, len, off);
7064 }
7065
7066
7067 /* Subroutine of native_encode_expr.  Encode the REAL_CST
7068    specified by EXPR into the buffer PTR of length LEN bytes.
7069    Return the number of bytes placed in the buffer, or zero
7070    upon failure.  */
7071
7072 static int
7073 native_encode_real (const_tree expr, unsigned char *ptr, int len, int off)
7074 {
7075   tree type = TREE_TYPE (expr);
7076   int total_bytes = GET_MODE_SIZE (TYPE_MODE (type));
7077   int byte, offset, word, words, bitpos;
7078   unsigned char value;
7079
7080   /* There are always 32 bits in each long, no matter the size of
7081      the hosts long.  We handle floating point representations with
7082      up to 192 bits.  */
7083   long tmp[6];
7084
7085   if ((off == -1 && total_bytes > len)
7086       || off >= total_bytes)
7087     return 0;
7088   if (off == -1)
7089     off = 0;
7090   words = (32 / BITS_PER_UNIT) / UNITS_PER_WORD;
7091
7092   real_to_target (tmp, TREE_REAL_CST_PTR (expr), TYPE_MODE (type));
7093
7094   for (bitpos = 0; bitpos < total_bytes * BITS_PER_UNIT;
7095        bitpos += BITS_PER_UNIT)
7096     {
7097       byte = (bitpos / BITS_PER_UNIT) & 3;
7098       value = (unsigned char) (tmp[bitpos / 32] >> (bitpos & 31));
7099
7100       if (UNITS_PER_WORD < 4)
7101         {
7102           word = byte / UNITS_PER_WORD;
7103           if (WORDS_BIG_ENDIAN)
7104             word = (words - 1) - word;
7105           offset = word * UNITS_PER_WORD;
7106           if (BYTES_BIG_ENDIAN)
7107             offset += (UNITS_PER_WORD - 1) - (byte % UNITS_PER_WORD);
7108           else
7109             offset += byte % UNITS_PER_WORD;
7110         }
7111       else
7112         offset = BYTES_BIG_ENDIAN ? 3 - byte : byte;
7113       offset = offset + ((bitpos / BITS_PER_UNIT) & ~3);
7114       if (offset >= off
7115           && offset - off < len)
7116         ptr[offset - off] = value;
7117     }
7118   return MIN (len, total_bytes - off);
7119 }
7120
7121 /* Subroutine of native_encode_expr.  Encode the COMPLEX_CST
7122    specified by EXPR into the buffer PTR of length LEN bytes.
7123    Return the number of bytes placed in the buffer, or zero
7124    upon failure.  */
7125
7126 static int
7127 native_encode_complex (const_tree expr, unsigned char *ptr, int len, int off)
7128 {
7129   int rsize, isize;
7130   tree part;
7131
7132   part = TREE_REALPART (expr);
7133   rsize = native_encode_expr (part, ptr, len, off);
7134   if (off == -1
7135       && rsize == 0)
7136     return 0;
7137   part = TREE_IMAGPART (expr);
7138   if (off != -1)
7139     off = MAX (0, off - GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (part))));
7140   isize = native_encode_expr (part, ptr+rsize, len-rsize, off);
7141   if (off == -1
7142       && isize != rsize)
7143     return 0;
7144   return rsize + isize;
7145 }
7146
7147
7148 /* Subroutine of native_encode_expr.  Encode the VECTOR_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_vector (const_tree expr, unsigned char *ptr, int len, int off)
7155 {
7156   unsigned i, count;
7157   int size, offset;
7158   tree itype, elem;
7159
7160   offset = 0;
7161   count = VECTOR_CST_NELTS (expr);
7162   itype = TREE_TYPE (TREE_TYPE (expr));
7163   size = GET_MODE_SIZE (TYPE_MODE (itype));
7164   for (i = 0; i < count; i++)
7165     {
7166       if (off >= size)
7167         {
7168           off -= size;
7169           continue;
7170         }
7171       elem = VECTOR_CST_ELT (expr, i);
7172       int res = native_encode_expr (elem, ptr+offset, len-offset, off);
7173       if ((off == -1 && res != size)
7174           || res == 0)
7175         return 0;
7176       offset += res;
7177       if (offset >= len)
7178         return offset;
7179       if (off != -1)
7180         off = 0;
7181     }
7182   return offset;
7183 }
7184
7185
7186 /* Subroutine of native_encode_expr.  Encode the STRING_CST
7187    specified by EXPR into the buffer PTR of length LEN bytes.
7188    Return the number of bytes placed in the buffer, or zero
7189    upon failure.  */
7190
7191 static int
7192 native_encode_string (const_tree expr, unsigned char *ptr, int len, int off)
7193 {
7194   tree type = TREE_TYPE (expr);
7195   HOST_WIDE_INT total_bytes;
7196
7197   if (TREE_CODE (type) != ARRAY_TYPE
7198       || TREE_CODE (TREE_TYPE (type)) != INTEGER_TYPE
7199       || GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE (type))) != BITS_PER_UNIT
7200       || !tree_fits_shwi_p (TYPE_SIZE_UNIT (type)))
7201     return 0;
7202   total_bytes = tree_to_shwi (TYPE_SIZE_UNIT (type));
7203   if ((off == -1 && total_bytes > len)
7204       || off >= total_bytes)
7205     return 0;
7206   if (off == -1)
7207     off = 0;
7208   if (TREE_STRING_LENGTH (expr) - off < MIN (total_bytes, len))
7209     {
7210       int written = 0;
7211       if (off < TREE_STRING_LENGTH (expr))
7212         {
7213           written = MIN (len, TREE_STRING_LENGTH (expr) - off);
7214           memcpy (ptr, TREE_STRING_POINTER (expr) + off, written);
7215         }
7216       memset (ptr + written, 0,
7217               MIN (total_bytes - written, len - written));
7218     }
7219   else
7220     memcpy (ptr, TREE_STRING_POINTER (expr) + off, MIN (total_bytes, len));
7221   return MIN (total_bytes - off, len);
7222 }
7223
7224
7225 /* Subroutine of fold_view_convert_expr.  Encode the INTEGER_CST,
7226    REAL_CST, COMPLEX_CST or VECTOR_CST specified by EXPR into the
7227    buffer PTR of length LEN bytes.  If OFF is not -1 then start
7228    the encoding at byte offset OFF and encode at most LEN bytes.
7229    Return the number of bytes placed in the buffer, or zero upon failure.  */
7230
7231 int
7232 native_encode_expr (const_tree expr, unsigned char *ptr, int len, int off)
7233 {
7234   switch (TREE_CODE (expr))
7235     {
7236     case INTEGER_CST:
7237       return native_encode_int (expr, ptr, len, off);
7238
7239     case REAL_CST:
7240       return native_encode_real (expr, ptr, len, off);
7241
7242     case FIXED_CST:
7243       return native_encode_fixed (expr, ptr, len, off);
7244
7245     case COMPLEX_CST:
7246       return native_encode_complex (expr, ptr, len, off);
7247
7248     case VECTOR_CST:
7249       return native_encode_vector (expr, ptr, len, off);
7250
7251     case STRING_CST:
7252       return native_encode_string (expr, ptr, len, off);
7253
7254     default:
7255       return 0;
7256     }
7257 }
7258
7259
7260 /* Subroutine of native_interpret_expr.  Interpret the contents of
7261    the buffer PTR of length LEN as an INTEGER_CST of type TYPE.
7262    If the buffer cannot be interpreted, return NULL_TREE.  */
7263
7264 static tree
7265 native_interpret_int (tree type, const unsigned char *ptr, int len)
7266 {
7267   int total_bytes = GET_MODE_SIZE (TYPE_MODE (type));
7268
7269   if (total_bytes > len
7270       || total_bytes * BITS_PER_UNIT > HOST_BITS_PER_DOUBLE_INT)
7271     return NULL_TREE;
7272
7273   wide_int result = wi::from_buffer (ptr, total_bytes);
7274
7275   return wide_int_to_tree (type, result);
7276 }
7277
7278
7279 /* Subroutine of native_interpret_expr.  Interpret the contents of
7280    the buffer PTR of length LEN as a FIXED_CST of type TYPE.
7281    If the buffer cannot be interpreted, return NULL_TREE.  */
7282
7283 static tree
7284 native_interpret_fixed (tree type, const unsigned char *ptr, int len)
7285 {
7286   int total_bytes = GET_MODE_SIZE (TYPE_MODE (type));
7287   double_int result;
7288   FIXED_VALUE_TYPE fixed_value;
7289
7290   if (total_bytes > len
7291       || total_bytes * BITS_PER_UNIT > HOST_BITS_PER_DOUBLE_INT)
7292     return NULL_TREE;
7293
7294   result = double_int::from_buffer (ptr, total_bytes);
7295   fixed_value = fixed_from_double_int (result, TYPE_MODE (type));
7296
7297   return build_fixed (type, fixed_value);
7298 }
7299
7300
7301 /* Subroutine of native_interpret_expr.  Interpret the contents of
7302    the buffer PTR of length LEN as a REAL_CST of type TYPE.
7303    If the buffer cannot be interpreted, return NULL_TREE.  */
7304
7305 static tree
7306 native_interpret_real (tree type, const unsigned char *ptr, int len)
7307 {
7308   machine_mode mode = TYPE_MODE (type);
7309   int total_bytes = GET_MODE_SIZE (mode);
7310   int byte, offset, word, words, bitpos;
7311   unsigned char value;
7312   /* There are always 32 bits in each long, no matter the size of
7313      the hosts long.  We handle floating point representations with
7314      up to 192 bits.  */
7315   REAL_VALUE_TYPE r;
7316   long tmp[6];
7317
7318   total_bytes = GET_MODE_SIZE (TYPE_MODE (type));
7319   if (total_bytes > len || total_bytes > 24)
7320     return NULL_TREE;
7321   words = (32 / BITS_PER_UNIT) / UNITS_PER_WORD;
7322
7323   memset (tmp, 0, sizeof (tmp));
7324   for (bitpos = 0; bitpos < total_bytes * BITS_PER_UNIT;
7325        bitpos += BITS_PER_UNIT)
7326     {
7327       byte = (bitpos / BITS_PER_UNIT) & 3;
7328       if (UNITS_PER_WORD < 4)
7329         {
7330           word = byte / UNITS_PER_WORD;
7331           if (WORDS_BIG_ENDIAN)
7332             word = (words - 1) - word;
7333           offset = word * UNITS_PER_WORD;
7334           if (BYTES_BIG_ENDIAN)
7335             offset += (UNITS_PER_WORD - 1) - (byte % UNITS_PER_WORD);
7336           else
7337             offset += byte % UNITS_PER_WORD;
7338         }
7339       else
7340         offset = BYTES_BIG_ENDIAN ? 3 - byte : byte;
7341       value = ptr[offset + ((bitpos / BITS_PER_UNIT) & ~3)];
7342
7343       tmp[bitpos / 32] |= (unsigned long)value << (bitpos & 31);
7344     }
7345
7346   real_from_target (&r, tmp, mode);
7347   return build_real (type, r);
7348 }
7349
7350
7351 /* Subroutine of native_interpret_expr.  Interpret the contents of
7352    the buffer PTR of length LEN as a COMPLEX_CST of type TYPE.
7353    If the buffer cannot be interpreted, return NULL_TREE.  */
7354
7355 static tree
7356 native_interpret_complex (tree type, const unsigned char *ptr, int len)
7357 {
7358   tree etype, rpart, ipart;
7359   int size;
7360
7361   etype = TREE_TYPE (type);
7362   size = GET_MODE_SIZE (TYPE_MODE (etype));
7363   if (size * 2 > len)
7364     return NULL_TREE;
7365   rpart = native_interpret_expr (etype, ptr, size);
7366   if (!rpart)
7367     return NULL_TREE;
7368   ipart = native_interpret_expr (etype, ptr+size, size);
7369   if (!ipart)
7370     return NULL_TREE;
7371   return build_complex (type, rpart, ipart);
7372 }
7373
7374
7375 /* Subroutine of native_interpret_expr.  Interpret the contents of
7376    the buffer PTR of length LEN as a VECTOR_CST of type TYPE.
7377    If the buffer cannot be interpreted, return NULL_TREE.  */
7378
7379 static tree
7380 native_interpret_vector (tree type, const unsigned char *ptr, int len)
7381 {
7382   tree etype, elem;
7383   int i, size, count;
7384   tree *elements;
7385
7386   etype = TREE_TYPE (type);
7387   size = GET_MODE_SIZE (TYPE_MODE (etype));
7388   count = TYPE_VECTOR_SUBPARTS (type);
7389   if (size * count > len)
7390     return NULL_TREE;
7391
7392   elements = XALLOCAVEC (tree, count);
7393   for (i = count - 1; i >= 0; i--)
7394     {
7395       elem = native_interpret_expr (etype, ptr+(i*size), size);
7396       if (!elem)
7397         return NULL_TREE;
7398       elements[i] = elem;
7399     }
7400   return build_vector (type, elements);
7401 }
7402
7403
7404 /* Subroutine of fold_view_convert_expr.  Interpret the contents of
7405    the buffer PTR of length LEN as a constant of type TYPE.  For
7406    INTEGRAL_TYPE_P we return an INTEGER_CST, for SCALAR_FLOAT_TYPE_P
7407    we return a REAL_CST, etc...  If the buffer cannot be interpreted,
7408    return NULL_TREE.  */
7409
7410 tree
7411 native_interpret_expr (tree type, const unsigned char *ptr, int len)
7412 {
7413   switch (TREE_CODE (type))
7414     {
7415     case INTEGER_TYPE:
7416     case ENUMERAL_TYPE:
7417     case BOOLEAN_TYPE:
7418     case POINTER_TYPE:
7419     case REFERENCE_TYPE:
7420       return native_interpret_int (type, ptr, len);
7421
7422     case REAL_TYPE:
7423       return native_interpret_real (type, ptr, len);
7424
7425     case FIXED_POINT_TYPE:
7426       return native_interpret_fixed (type, ptr, len);
7427
7428     case COMPLEX_TYPE:
7429       return native_interpret_complex (type, ptr, len);
7430
7431     case VECTOR_TYPE:
7432       return native_interpret_vector (type, ptr, len);
7433
7434     default:
7435       return NULL_TREE;
7436     }
7437 }
7438
7439 /* Returns true if we can interpret the contents of a native encoding
7440    as TYPE.  */
7441
7442 static bool
7443 can_native_interpret_type_p (tree type)
7444 {
7445   switch (TREE_CODE (type))
7446     {
7447     case INTEGER_TYPE:
7448     case ENUMERAL_TYPE:
7449     case BOOLEAN_TYPE:
7450     case POINTER_TYPE:
7451     case REFERENCE_TYPE:
7452     case FIXED_POINT_TYPE:
7453     case REAL_TYPE:
7454     case COMPLEX_TYPE:
7455     case VECTOR_TYPE:
7456       return true;
7457     default:
7458       return false;
7459     }
7460 }
7461
7462 /* Fold a VIEW_CONVERT_EXPR of a constant expression EXPR to type
7463    TYPE at compile-time.  If we're unable to perform the conversion
7464    return NULL_TREE.  */
7465
7466 static tree
7467 fold_view_convert_expr (tree type, tree expr)
7468 {
7469   /* We support up to 512-bit values (for V8DFmode).  */
7470   unsigned char buffer[64];
7471   int len;
7472
7473   /* Check that the host and target are sane.  */
7474   if (CHAR_BIT != 8 || BITS_PER_UNIT != 8)
7475     return NULL_TREE;
7476
7477   len = native_encode_expr (expr, buffer, sizeof (buffer));
7478   if (len == 0)
7479     return NULL_TREE;
7480
7481   return native_interpret_expr (type, buffer, len);
7482 }
7483
7484 /* Build an expression for the address of T.  Folds away INDIRECT_REF
7485    to avoid confusing the gimplify process.  */
7486
7487 tree
7488 build_fold_addr_expr_with_type_loc (location_t loc, tree t, tree ptrtype)
7489 {
7490   /* The size of the object is not relevant when talking about its address.  */
7491   if (TREE_CODE (t) == WITH_SIZE_EXPR)
7492     t = TREE_OPERAND (t, 0);
7493
7494   if (TREE_CODE (t) == INDIRECT_REF)
7495     {
7496       t = TREE_OPERAND (t, 0);
7497
7498       if (TREE_TYPE (t) != ptrtype)
7499         t = build1_loc (loc, NOP_EXPR, ptrtype, t);
7500     }
7501   else if (TREE_CODE (t) == MEM_REF
7502            && integer_zerop (TREE_OPERAND (t, 1)))
7503     return TREE_OPERAND (t, 0);
7504   else if (TREE_CODE (t) == MEM_REF
7505            && TREE_CODE (TREE_OPERAND (t, 0)) == INTEGER_CST)
7506     return fold_binary (POINTER_PLUS_EXPR, ptrtype,
7507                         TREE_OPERAND (t, 0),
7508                         convert_to_ptrofftype (TREE_OPERAND (t, 1)));
7509   else if (TREE_CODE (t) == VIEW_CONVERT_EXPR)
7510     {
7511       t = build_fold_addr_expr_loc (loc, TREE_OPERAND (t, 0));
7512
7513       if (TREE_TYPE (t) != ptrtype)
7514         t = fold_convert_loc (loc, ptrtype, t);
7515     }
7516   else
7517     t = build1_loc (loc, ADDR_EXPR, ptrtype, t);
7518
7519   return t;
7520 }
7521
7522 /* Build an expression for the address of T.  */
7523
7524 tree
7525 build_fold_addr_expr_loc (location_t loc, tree t)
7526 {
7527   tree ptrtype = build_pointer_type (TREE_TYPE (t));
7528
7529   return build_fold_addr_expr_with_type_loc (loc, t, ptrtype);
7530 }
7531
7532 static bool vec_cst_ctor_to_array (tree, tree *);
7533
7534 /* Fold a unary expression of code CODE and type TYPE with operand
7535    OP0.  Return the folded expression if folding is successful.
7536    Otherwise, return NULL_TREE.  */
7537
7538 tree
7539 fold_unary_loc (location_t loc, enum tree_code code, tree type, tree op0)
7540 {
7541   tree tem;
7542   tree arg0;
7543   enum tree_code_class kind = TREE_CODE_CLASS (code);
7544
7545   gcc_assert (IS_EXPR_CODE_CLASS (kind)
7546               && TREE_CODE_LENGTH (code) == 1);
7547
7548   tem = generic_simplify (loc, code, type, op0);
7549   if (tem)
7550     return tem;
7551
7552   arg0 = op0;
7553   if (arg0)
7554     {
7555       if (CONVERT_EXPR_CODE_P (code)
7556           || code == FLOAT_EXPR || code == ABS_EXPR || code == NEGATE_EXPR)
7557         {
7558           /* Don't use STRIP_NOPS, because signedness of argument type
7559              matters.  */
7560           STRIP_SIGN_NOPS (arg0);
7561         }
7562       else
7563         {
7564           /* Strip any conversions that don't change the mode.  This
7565              is safe for every expression, except for a comparison
7566              expression because its signedness is derived from its
7567              operands.
7568
7569              Note that this is done as an internal manipulation within
7570              the constant folder, in order to find the simplest
7571              representation of the arguments so that their form can be
7572              studied.  In any cases, the appropriate type conversions
7573              should be put back in the tree that will get out of the
7574              constant folder.  */
7575           STRIP_NOPS (arg0);
7576         }
7577     }
7578
7579   if (TREE_CODE_CLASS (code) == tcc_unary)
7580     {
7581       if (TREE_CODE (arg0) == COMPOUND_EXPR)
7582         return build2 (COMPOUND_EXPR, type, TREE_OPERAND (arg0, 0),
7583                        fold_build1_loc (loc, code, type,
7584                                     fold_convert_loc (loc, TREE_TYPE (op0),
7585                                                       TREE_OPERAND (arg0, 1))));
7586       else if (TREE_CODE (arg0) == COND_EXPR)
7587         {
7588           tree arg01 = TREE_OPERAND (arg0, 1);
7589           tree arg02 = TREE_OPERAND (arg0, 2);
7590           if (! VOID_TYPE_P (TREE_TYPE (arg01)))
7591             arg01 = fold_build1_loc (loc, code, type,
7592                                  fold_convert_loc (loc,
7593                                                    TREE_TYPE (op0), arg01));
7594           if (! VOID_TYPE_P (TREE_TYPE (arg02)))
7595             arg02 = fold_build1_loc (loc, code, type,
7596                                  fold_convert_loc (loc,
7597                                                    TREE_TYPE (op0), arg02));
7598           tem = fold_build3_loc (loc, COND_EXPR, type, TREE_OPERAND (arg0, 0),
7599                              arg01, arg02);
7600
7601           /* If this was a conversion, and all we did was to move into
7602              inside the COND_EXPR, bring it back out.  But leave it if
7603              it is a conversion from integer to integer and the
7604              result precision is no wider than a word since such a
7605              conversion is cheap and may be optimized away by combine,
7606              while it couldn't if it were outside the COND_EXPR.  Then return
7607              so we don't get into an infinite recursion loop taking the
7608              conversion out and then back in.  */
7609
7610           if ((CONVERT_EXPR_CODE_P (code)
7611                || code == NON_LVALUE_EXPR)
7612               && TREE_CODE (tem) == COND_EXPR
7613               && TREE_CODE (TREE_OPERAND (tem, 1)) == code
7614               && TREE_CODE (TREE_OPERAND (tem, 2)) == code
7615               && ! VOID_TYPE_P (TREE_OPERAND (tem, 1))
7616               && ! VOID_TYPE_P (TREE_OPERAND (tem, 2))
7617               && (TREE_TYPE (TREE_OPERAND (TREE_OPERAND (tem, 1), 0))
7618                   == TREE_TYPE (TREE_OPERAND (TREE_OPERAND (tem, 2), 0)))
7619               && (! (INTEGRAL_TYPE_P (TREE_TYPE (tem))
7620                      && (INTEGRAL_TYPE_P
7621                          (TREE_TYPE (TREE_OPERAND (TREE_OPERAND (tem, 1), 0))))
7622                      && TYPE_PRECISION (TREE_TYPE (tem)) <= BITS_PER_WORD)
7623                   || flag_syntax_only))
7624             tem = build1_loc (loc, code, type,
7625                               build3 (COND_EXPR,
7626                                       TREE_TYPE (TREE_OPERAND
7627                                                  (TREE_OPERAND (tem, 1), 0)),
7628                                       TREE_OPERAND (tem, 0),
7629                                       TREE_OPERAND (TREE_OPERAND (tem, 1), 0),
7630                                       TREE_OPERAND (TREE_OPERAND (tem, 2),
7631                                                     0)));
7632           return tem;
7633         }
7634    }
7635
7636   switch (code)
7637     {
7638     case NON_LVALUE_EXPR:
7639       if (!maybe_lvalue_p (op0))
7640         return fold_convert_loc (loc, type, op0);
7641       return NULL_TREE;
7642
7643     CASE_CONVERT:
7644     case FLOAT_EXPR:
7645     case FIX_TRUNC_EXPR:
7646       if (COMPARISON_CLASS_P (op0))
7647         {
7648           /* If we have (type) (a CMP b) and type is an integral type, return
7649              new expression involving the new type.  Canonicalize
7650              (type) (a CMP b) to (a CMP b) ? (type) true : (type) false for
7651              non-integral type.
7652              Do not fold the result as that would not simplify further, also
7653              folding again results in recursions.  */
7654           if (TREE_CODE (type) == BOOLEAN_TYPE)
7655             return build2_loc (loc, TREE_CODE (op0), type,
7656                                TREE_OPERAND (op0, 0),
7657                                TREE_OPERAND (op0, 1));
7658           else if (!INTEGRAL_TYPE_P (type) && !VOID_TYPE_P (type)
7659                    && TREE_CODE (type) != VECTOR_TYPE)
7660             return build3_loc (loc, COND_EXPR, type, op0,
7661                                constant_boolean_node (true, type),
7662                                constant_boolean_node (false, type));
7663         }
7664
7665       /* Handle (T *)&A.B.C for A being of type T and B and C
7666          living at offset zero.  This occurs frequently in
7667          C++ upcasting and then accessing the base.  */
7668       if (TREE_CODE (op0) == ADDR_EXPR
7669           && POINTER_TYPE_P (type)
7670           && handled_component_p (TREE_OPERAND (op0, 0)))
7671         {
7672           HOST_WIDE_INT bitsize, bitpos;
7673           tree offset;
7674           machine_mode mode;
7675           int unsignedp, volatilep;
7676           tree base = TREE_OPERAND (op0, 0);
7677           base = get_inner_reference (base, &bitsize, &bitpos, &offset,
7678                                       &mode, &unsignedp, &volatilep, false);
7679           /* If the reference was to a (constant) zero offset, we can use
7680              the address of the base if it has the same base type
7681              as the result type and the pointer type is unqualified.  */
7682           if (! offset && bitpos == 0
7683               && (TYPE_MAIN_VARIANT (TREE_TYPE (type))
7684                   == TYPE_MAIN_VARIANT (TREE_TYPE (base)))
7685               && TYPE_QUALS (type) == TYPE_UNQUALIFIED)
7686             return fold_convert_loc (loc, type,
7687                                      build_fold_addr_expr_loc (loc, base));
7688         }
7689
7690       if (TREE_CODE (op0) == MODIFY_EXPR
7691           && TREE_CONSTANT (TREE_OPERAND (op0, 1))
7692           /* Detect assigning a bitfield.  */
7693           && !(TREE_CODE (TREE_OPERAND (op0, 0)) == COMPONENT_REF
7694                && DECL_BIT_FIELD
7695                (TREE_OPERAND (TREE_OPERAND (op0, 0), 1))))
7696         {
7697           /* Don't leave an assignment inside a conversion
7698              unless assigning a bitfield.  */
7699           tem = fold_build1_loc (loc, code, type, TREE_OPERAND (op0, 1));
7700           /* First do the assignment, then return converted constant.  */
7701           tem = build2_loc (loc, COMPOUND_EXPR, TREE_TYPE (tem), op0, tem);
7702           TREE_NO_WARNING (tem) = 1;
7703           TREE_USED (tem) = 1;
7704           return tem;
7705         }
7706
7707       /* Convert (T)(x & c) into (T)x & (T)c, if c is an integer
7708          constants (if x has signed type, the sign bit cannot be set
7709          in c).  This folds extension into the BIT_AND_EXPR.
7710          ??? We don't do it for BOOLEAN_TYPE or ENUMERAL_TYPE because they
7711          very likely don't have maximal range for their precision and this
7712          transformation effectively doesn't preserve non-maximal ranges.  */
7713       if (TREE_CODE (type) == INTEGER_TYPE
7714           && TREE_CODE (op0) == BIT_AND_EXPR
7715           && TREE_CODE (TREE_OPERAND (op0, 1)) == INTEGER_CST)
7716         {
7717           tree and_expr = op0;
7718           tree and0 = TREE_OPERAND (and_expr, 0);
7719           tree and1 = TREE_OPERAND (and_expr, 1);
7720           int change = 0;
7721
7722           if (TYPE_UNSIGNED (TREE_TYPE (and_expr))
7723               || (TYPE_PRECISION (type)
7724                   <= TYPE_PRECISION (TREE_TYPE (and_expr))))
7725             change = 1;
7726           else if (TYPE_PRECISION (TREE_TYPE (and1))
7727                    <= HOST_BITS_PER_WIDE_INT
7728                    && tree_fits_uhwi_p (and1))
7729             {
7730               unsigned HOST_WIDE_INT cst;
7731
7732               cst = tree_to_uhwi (and1);
7733               cst &= HOST_WIDE_INT_M1U
7734                      << (TYPE_PRECISION (TREE_TYPE (and1)) - 1);
7735               change = (cst == 0);
7736 #ifdef LOAD_EXTEND_OP
7737               if (change
7738                   && !flag_syntax_only
7739                   && (LOAD_EXTEND_OP (TYPE_MODE (TREE_TYPE (and0)))
7740                       == ZERO_EXTEND))
7741                 {
7742                   tree uns = unsigned_type_for (TREE_TYPE (and0));
7743                   and0 = fold_convert_loc (loc, uns, and0);
7744                   and1 = fold_convert_loc (loc, uns, and1);
7745                 }
7746 #endif
7747             }
7748           if (change)
7749             {
7750               tem = force_fit_type (type, wi::to_widest (and1), 0,
7751                                     TREE_OVERFLOW (and1));
7752               return fold_build2_loc (loc, BIT_AND_EXPR, type,
7753                                       fold_convert_loc (loc, type, and0), tem);
7754             }
7755         }
7756
7757       /* Convert (T1)(X p+ Y) into ((T1)X p+ Y), for pointer type,
7758          when one of the new casts will fold away. Conservatively we assume
7759          that this happens when X or Y is NOP_EXPR or Y is INTEGER_CST. */
7760       if (POINTER_TYPE_P (type)
7761           && TREE_CODE (arg0) == POINTER_PLUS_EXPR
7762           && (!TYPE_RESTRICT (type) || TYPE_RESTRICT (TREE_TYPE (arg0)))
7763           && (TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
7764               || TREE_CODE (TREE_OPERAND (arg0, 0)) == NOP_EXPR
7765               || TREE_CODE (TREE_OPERAND (arg0, 1)) == NOP_EXPR))
7766         {
7767           tree arg00 = TREE_OPERAND (arg0, 0);
7768           tree arg01 = TREE_OPERAND (arg0, 1);
7769
7770           return fold_build_pointer_plus_loc
7771                    (loc, fold_convert_loc (loc, type, arg00), arg01);
7772         }
7773
7774       /* Convert (T1)(~(T2)X) into ~(T1)X if T1 and T2 are integral types
7775          of the same precision, and X is an integer type not narrower than
7776          types T1 or T2, i.e. the cast (T2)X isn't an extension.  */
7777       if (INTEGRAL_TYPE_P (type)
7778           && TREE_CODE (op0) == BIT_NOT_EXPR
7779           && INTEGRAL_TYPE_P (TREE_TYPE (op0))
7780           && CONVERT_EXPR_P (TREE_OPERAND (op0, 0))
7781           && TYPE_PRECISION (type) == TYPE_PRECISION (TREE_TYPE (op0)))
7782         {
7783           tem = TREE_OPERAND (TREE_OPERAND (op0, 0), 0);
7784           if (INTEGRAL_TYPE_P (TREE_TYPE (tem))
7785               && TYPE_PRECISION (type) <= TYPE_PRECISION (TREE_TYPE (tem)))
7786             return fold_build1_loc (loc, BIT_NOT_EXPR, type,
7787                                 fold_convert_loc (loc, type, tem));
7788         }
7789
7790       /* Convert (T1)(X * Y) into (T1)X * (T1)Y if T1 is narrower than the
7791          type of X and Y (integer types only).  */
7792       if (INTEGRAL_TYPE_P (type)
7793           && TREE_CODE (op0) == MULT_EXPR
7794           && INTEGRAL_TYPE_P (TREE_TYPE (op0))
7795           && TYPE_PRECISION (type) < TYPE_PRECISION (TREE_TYPE (op0)))
7796         {
7797           /* Be careful not to introduce new overflows.  */
7798           tree mult_type;
7799           if (TYPE_OVERFLOW_WRAPS (type))
7800             mult_type = type;
7801           else
7802             mult_type = unsigned_type_for (type);
7803
7804           if (TYPE_PRECISION (mult_type) < TYPE_PRECISION (TREE_TYPE (op0)))
7805             {
7806               tem = fold_build2_loc (loc, MULT_EXPR, mult_type,
7807                                  fold_convert_loc (loc, mult_type,
7808                                                    TREE_OPERAND (op0, 0)),
7809                                  fold_convert_loc (loc, mult_type,
7810                                                    TREE_OPERAND (op0, 1)));
7811               return fold_convert_loc (loc, type, tem);
7812             }
7813         }
7814
7815       tem = fold_convert_const (code, type, arg0);
7816       return tem ? tem : NULL_TREE;
7817
7818     case ADDR_SPACE_CONVERT_EXPR:
7819       if (integer_zerop (arg0))
7820         return fold_convert_const (code, type, arg0);
7821       return NULL_TREE;
7822
7823     case FIXED_CONVERT_EXPR:
7824       tem = fold_convert_const (code, type, arg0);
7825       return tem ? tem : NULL_TREE;
7826
7827     case VIEW_CONVERT_EXPR:
7828       if (TREE_CODE (op0) == MEM_REF)
7829         return fold_build2_loc (loc, MEM_REF, type,
7830                                 TREE_OPERAND (op0, 0), TREE_OPERAND (op0, 1));
7831
7832       return fold_view_convert_expr (type, op0);
7833
7834     case NEGATE_EXPR:
7835       tem = fold_negate_expr (loc, arg0);
7836       if (tem)
7837         return fold_convert_loc (loc, type, tem);
7838       return NULL_TREE;
7839
7840     case ABS_EXPR:
7841       if (TREE_CODE (arg0) == INTEGER_CST || TREE_CODE (arg0) == REAL_CST)
7842         return fold_abs_const (arg0, type);
7843       /* Convert fabs((double)float) into (double)fabsf(float).  */
7844       else if (TREE_CODE (arg0) == NOP_EXPR
7845                && TREE_CODE (type) == REAL_TYPE)
7846         {
7847           tree targ0 = strip_float_extensions (arg0);
7848           if (targ0 != arg0)
7849             return fold_convert_loc (loc, type,
7850                                      fold_build1_loc (loc, ABS_EXPR,
7851                                                   TREE_TYPE (targ0),
7852                                                   targ0));
7853         }
7854       /* ABS_EXPR<ABS_EXPR<x>> = ABS_EXPR<x> even if flag_wrapv is on.  */
7855       else if (TREE_CODE (arg0) == ABS_EXPR)
7856         return arg0;
7857
7858       /* Strip sign ops from argument.  */
7859       if (TREE_CODE (type) == REAL_TYPE)
7860         {
7861           tem = fold_strip_sign_ops (arg0);
7862           if (tem)
7863             return fold_build1_loc (loc, ABS_EXPR, type,
7864                                 fold_convert_loc (loc, type, tem));
7865         }
7866       return NULL_TREE;
7867
7868     case CONJ_EXPR:
7869       if (TREE_CODE (TREE_TYPE (arg0)) != COMPLEX_TYPE)
7870         return fold_convert_loc (loc, type, arg0);
7871       if (TREE_CODE (arg0) == COMPLEX_EXPR)
7872         {
7873           tree itype = TREE_TYPE (type);
7874           tree rpart = fold_convert_loc (loc, itype, TREE_OPERAND (arg0, 0));
7875           tree ipart = fold_convert_loc (loc, itype, TREE_OPERAND (arg0, 1));
7876           return fold_build2_loc (loc, COMPLEX_EXPR, type, rpart,
7877                               negate_expr (ipart));
7878         }
7879       if (TREE_CODE (arg0) == COMPLEX_CST)
7880         {
7881           tree itype = TREE_TYPE (type);
7882           tree rpart = fold_convert_loc (loc, itype, TREE_REALPART (arg0));
7883           tree ipart = fold_convert_loc (loc, itype, TREE_IMAGPART (arg0));
7884           return build_complex (type, rpart, negate_expr (ipart));
7885         }
7886       if (TREE_CODE (arg0) == CONJ_EXPR)
7887         return fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
7888       return NULL_TREE;
7889
7890     case BIT_NOT_EXPR:
7891       if (TREE_CODE (arg0) == INTEGER_CST)
7892         return fold_not_const (arg0, type);
7893       /* Convert ~ (-A) to A - 1.  */
7894       else if (INTEGRAL_TYPE_P (type) && TREE_CODE (arg0) == NEGATE_EXPR)
7895         return fold_build2_loc (loc, MINUS_EXPR, type,
7896                             fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0)),
7897                             build_int_cst (type, 1));
7898       /* Convert ~ (A - 1) or ~ (A + -1) to -A.  */
7899       else if (INTEGRAL_TYPE_P (type)
7900                && ((TREE_CODE (arg0) == MINUS_EXPR
7901                     && integer_onep (TREE_OPERAND (arg0, 1)))
7902                    || (TREE_CODE (arg0) == PLUS_EXPR
7903                        && integer_all_onesp (TREE_OPERAND (arg0, 1)))))
7904         return fold_build1_loc (loc, NEGATE_EXPR, type,
7905                             fold_convert_loc (loc, type,
7906                                               TREE_OPERAND (arg0, 0)));
7907       /* Convert ~(X ^ Y) to ~X ^ Y or X ^ ~Y if ~X or ~Y simplify.  */
7908       else if (TREE_CODE (arg0) == BIT_XOR_EXPR
7909                && (tem = fold_unary_loc (loc, BIT_NOT_EXPR, type,
7910                                      fold_convert_loc (loc, type,
7911                                                        TREE_OPERAND (arg0, 0)))))
7912         return fold_build2_loc (loc, BIT_XOR_EXPR, type, tem,
7913                             fold_convert_loc (loc, type,
7914                                               TREE_OPERAND (arg0, 1)));
7915       else if (TREE_CODE (arg0) == BIT_XOR_EXPR
7916                && (tem = fold_unary_loc (loc, BIT_NOT_EXPR, type,
7917                                      fold_convert_loc (loc, type,
7918                                                        TREE_OPERAND (arg0, 1)))))
7919         return fold_build2_loc (loc, BIT_XOR_EXPR, type,
7920                             fold_convert_loc (loc, type,
7921                                               TREE_OPERAND (arg0, 0)), tem);
7922       /* Perform BIT_NOT_EXPR on each element individually.  */
7923       else if (TREE_CODE (arg0) == VECTOR_CST)
7924         {
7925           tree *elements;
7926           tree elem;
7927           unsigned count = VECTOR_CST_NELTS (arg0), i;
7928
7929           elements = XALLOCAVEC (tree, count);
7930           for (i = 0; i < count; i++)
7931             {
7932               elem = VECTOR_CST_ELT (arg0, i);
7933               elem = fold_unary_loc (loc, BIT_NOT_EXPR, TREE_TYPE (type), elem);
7934               if (elem == NULL_TREE)
7935                 break;
7936               elements[i] = elem;
7937             }
7938           if (i == count)
7939             return build_vector (type, elements);
7940         }
7941
7942       return NULL_TREE;
7943
7944     case TRUTH_NOT_EXPR:
7945       /* Note that the operand of this must be an int
7946          and its values must be 0 or 1.
7947          ("true" is a fixed value perhaps depending on the language,
7948          but we don't handle values other than 1 correctly yet.)  */
7949       tem = fold_truth_not_expr (loc, arg0);
7950       if (!tem)
7951         return NULL_TREE;
7952       return fold_convert_loc (loc, type, tem);
7953
7954     case REALPART_EXPR:
7955       if (TREE_CODE (TREE_TYPE (arg0)) != COMPLEX_TYPE)
7956         return fold_convert_loc (loc, type, arg0);
7957       if (TREE_CODE (arg0) == COMPLEX_CST)
7958         return fold_convert_loc (loc, type, TREE_REALPART (arg0));
7959       if (TREE_CODE (arg0) == PLUS_EXPR || TREE_CODE (arg0) == MINUS_EXPR)
7960         {
7961           tree itype = TREE_TYPE (TREE_TYPE (arg0));
7962           tem = fold_build2_loc (loc, TREE_CODE (arg0), itype,
7963                              fold_build1_loc (loc, REALPART_EXPR, itype,
7964                                           TREE_OPERAND (arg0, 0)),
7965                              fold_build1_loc (loc, REALPART_EXPR, itype,
7966                                           TREE_OPERAND (arg0, 1)));
7967           return fold_convert_loc (loc, type, tem);
7968         }
7969       if (TREE_CODE (arg0) == CONJ_EXPR)
7970         {
7971           tree itype = TREE_TYPE (TREE_TYPE (arg0));
7972           tem = fold_build1_loc (loc, REALPART_EXPR, itype,
7973                              TREE_OPERAND (arg0, 0));
7974           return fold_convert_loc (loc, type, tem);
7975         }
7976       if (TREE_CODE (arg0) == CALL_EXPR)
7977         {
7978           tree fn = get_callee_fndecl (arg0);
7979           if (fn && DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
7980             switch (DECL_FUNCTION_CODE (fn))
7981               {
7982               CASE_FLT_FN (BUILT_IN_CEXPI):
7983                 fn = mathfn_built_in (type, BUILT_IN_COS);
7984                 if (fn)
7985                   return build_call_expr_loc (loc, fn, 1, CALL_EXPR_ARG (arg0, 0));
7986                 break;
7987
7988               default:
7989                 break;
7990               }
7991         }
7992       return NULL_TREE;
7993
7994     case IMAGPART_EXPR:
7995       if (TREE_CODE (TREE_TYPE (arg0)) != COMPLEX_TYPE)
7996         return build_zero_cst (type);
7997       if (TREE_CODE (arg0) == COMPLEX_CST)
7998         return fold_convert_loc (loc, type, TREE_IMAGPART (arg0));
7999       if (TREE_CODE (arg0) == PLUS_EXPR || TREE_CODE (arg0) == MINUS_EXPR)
8000         {
8001           tree itype = TREE_TYPE (TREE_TYPE (arg0));
8002           tem = fold_build2_loc (loc, TREE_CODE (arg0), itype,
8003                              fold_build1_loc (loc, IMAGPART_EXPR, itype,
8004                                           TREE_OPERAND (arg0, 0)),
8005                              fold_build1_loc (loc, IMAGPART_EXPR, itype,
8006                                           TREE_OPERAND (arg0, 1)));
8007           return fold_convert_loc (loc, type, tem);
8008         }
8009       if (TREE_CODE (arg0) == CONJ_EXPR)
8010         {
8011           tree itype = TREE_TYPE (TREE_TYPE (arg0));
8012           tem = fold_build1_loc (loc, IMAGPART_EXPR, itype, TREE_OPERAND (arg0, 0));
8013           return fold_convert_loc (loc, type, negate_expr (tem));
8014         }
8015       if (TREE_CODE (arg0) == CALL_EXPR)
8016         {
8017           tree fn = get_callee_fndecl (arg0);
8018           if (fn && DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
8019             switch (DECL_FUNCTION_CODE (fn))
8020               {
8021               CASE_FLT_FN (BUILT_IN_CEXPI):
8022                 fn = mathfn_built_in (type, BUILT_IN_SIN);
8023                 if (fn)
8024                   return build_call_expr_loc (loc, fn, 1, CALL_EXPR_ARG (arg0, 0));
8025                 break;
8026
8027               default:
8028                 break;
8029               }
8030         }
8031       return NULL_TREE;
8032
8033     case INDIRECT_REF:
8034       /* Fold *&X to X if X is an lvalue.  */
8035       if (TREE_CODE (op0) == ADDR_EXPR)
8036         {
8037           tree op00 = TREE_OPERAND (op0, 0);
8038           if ((TREE_CODE (op00) == VAR_DECL
8039                || TREE_CODE (op00) == PARM_DECL
8040                || TREE_CODE (op00) == RESULT_DECL)
8041               && !TREE_READONLY (op00))
8042             return op00;
8043         }
8044       return NULL_TREE;
8045
8046     case VEC_UNPACK_LO_EXPR:
8047     case VEC_UNPACK_HI_EXPR:
8048     case VEC_UNPACK_FLOAT_LO_EXPR:
8049     case VEC_UNPACK_FLOAT_HI_EXPR:
8050       {
8051         unsigned int nelts = TYPE_VECTOR_SUBPARTS (type), i;
8052         tree *elts;
8053         enum tree_code subcode;
8054
8055         gcc_assert (TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0)) == nelts * 2);
8056         if (TREE_CODE (arg0) != VECTOR_CST)
8057           return NULL_TREE;
8058
8059         elts = XALLOCAVEC (tree, nelts * 2);
8060         if (!vec_cst_ctor_to_array (arg0, elts))
8061           return NULL_TREE;
8062
8063         if ((!BYTES_BIG_ENDIAN) ^ (code == VEC_UNPACK_LO_EXPR
8064                                    || code == VEC_UNPACK_FLOAT_LO_EXPR))
8065           elts += nelts;
8066
8067         if (code == VEC_UNPACK_LO_EXPR || code == VEC_UNPACK_HI_EXPR)
8068           subcode = NOP_EXPR;
8069         else
8070           subcode = FLOAT_EXPR;
8071
8072         for (i = 0; i < nelts; i++)
8073           {
8074             elts[i] = fold_convert_const (subcode, TREE_TYPE (type), elts[i]);
8075             if (elts[i] == NULL_TREE || !CONSTANT_CLASS_P (elts[i]))
8076               return NULL_TREE;
8077           }
8078
8079         return build_vector (type, elts);
8080       }
8081
8082     case REDUC_MIN_EXPR:
8083     case REDUC_MAX_EXPR:
8084     case REDUC_PLUS_EXPR:
8085       {
8086         unsigned int nelts, i;
8087         tree *elts;
8088         enum tree_code subcode;
8089
8090         if (TREE_CODE (op0) != VECTOR_CST)
8091           return NULL_TREE;
8092         nelts = TYPE_VECTOR_SUBPARTS (TREE_TYPE (op0));
8093
8094         elts = XALLOCAVEC (tree, nelts);
8095         if (!vec_cst_ctor_to_array (op0, elts))
8096           return NULL_TREE;
8097
8098         switch (code)
8099           {
8100           case REDUC_MIN_EXPR: subcode = MIN_EXPR; break;
8101           case REDUC_MAX_EXPR: subcode = MAX_EXPR; break;
8102           case REDUC_PLUS_EXPR: subcode = PLUS_EXPR; break;
8103           default: gcc_unreachable ();
8104           }
8105
8106         for (i = 1; i < nelts; i++)
8107           {
8108             elts[0] = const_binop (subcode, elts[0], elts[i]);
8109             if (elts[0] == NULL_TREE || !CONSTANT_CLASS_P (elts[0]))
8110               return NULL_TREE;
8111           }
8112
8113         return elts[0];
8114       }
8115
8116     default:
8117       return NULL_TREE;
8118     } /* switch (code) */
8119 }
8120
8121
8122 /* If the operation was a conversion do _not_ mark a resulting constant
8123    with TREE_OVERFLOW if the original constant was not.  These conversions
8124    have implementation defined behavior and retaining the TREE_OVERFLOW
8125    flag here would confuse later passes such as VRP.  */
8126 tree
8127 fold_unary_ignore_overflow_loc (location_t loc, enum tree_code code,
8128                                 tree type, tree op0)
8129 {
8130   tree res = fold_unary_loc (loc, code, type, op0);
8131   if (res
8132       && TREE_CODE (res) == INTEGER_CST
8133       && TREE_CODE (op0) == INTEGER_CST
8134       && CONVERT_EXPR_CODE_P (code))
8135     TREE_OVERFLOW (res) = TREE_OVERFLOW (op0);
8136
8137   return res;
8138 }
8139
8140 /* Fold a binary bitwise/truth expression of code CODE and type TYPE with
8141    operands OP0 and OP1.  LOC is the location of the resulting expression.
8142    ARG0 and ARG1 are the NOP_STRIPed results of OP0 and OP1.
8143    Return the folded expression if folding is successful.  Otherwise,
8144    return NULL_TREE.  */
8145 static tree
8146 fold_truth_andor (location_t loc, enum tree_code code, tree type,
8147                   tree arg0, tree arg1, tree op0, tree op1)
8148 {
8149   tree tem;
8150
8151   /* We only do these simplifications if we are optimizing.  */
8152   if (!optimize)
8153     return NULL_TREE;
8154
8155   /* Check for things like (A || B) && (A || C).  We can convert this
8156      to A || (B && C).  Note that either operator can be any of the four
8157      truth and/or operations and the transformation will still be
8158      valid.   Also note that we only care about order for the
8159      ANDIF and ORIF operators.  If B contains side effects, this
8160      might change the truth-value of A.  */
8161   if (TREE_CODE (arg0) == TREE_CODE (arg1)
8162       && (TREE_CODE (arg0) == TRUTH_ANDIF_EXPR
8163           || TREE_CODE (arg0) == TRUTH_ORIF_EXPR
8164           || TREE_CODE (arg0) == TRUTH_AND_EXPR
8165           || TREE_CODE (arg0) == TRUTH_OR_EXPR)
8166       && ! TREE_SIDE_EFFECTS (TREE_OPERAND (arg0, 1)))
8167     {
8168       tree a00 = TREE_OPERAND (arg0, 0);
8169       tree a01 = TREE_OPERAND (arg0, 1);
8170       tree a10 = TREE_OPERAND (arg1, 0);
8171       tree a11 = TREE_OPERAND (arg1, 1);
8172       int commutative = ((TREE_CODE (arg0) == TRUTH_OR_EXPR
8173                           || TREE_CODE (arg0) == TRUTH_AND_EXPR)
8174                          && (code == TRUTH_AND_EXPR
8175                              || code == TRUTH_OR_EXPR));
8176
8177       if (operand_equal_p (a00, a10, 0))
8178         return fold_build2_loc (loc, TREE_CODE (arg0), type, a00,
8179                             fold_build2_loc (loc, code, type, a01, a11));
8180       else if (commutative && operand_equal_p (a00, a11, 0))
8181         return fold_build2_loc (loc, TREE_CODE (arg0), type, a00,
8182                             fold_build2_loc (loc, code, type, a01, a10));
8183       else if (commutative && operand_equal_p (a01, a10, 0))
8184         return fold_build2_loc (loc, TREE_CODE (arg0), type, a01,
8185                             fold_build2_loc (loc, code, type, a00, a11));
8186
8187       /* This case if tricky because we must either have commutative
8188          operators or else A10 must not have side-effects.  */
8189
8190       else if ((commutative || ! TREE_SIDE_EFFECTS (a10))
8191                && operand_equal_p (a01, a11, 0))
8192         return fold_build2_loc (loc, TREE_CODE (arg0), type,
8193                             fold_build2_loc (loc, code, type, a00, a10),
8194                             a01);
8195     }
8196
8197   /* See if we can build a range comparison.  */
8198   if (0 != (tem = fold_range_test (loc, code, type, op0, op1)))
8199     return tem;
8200
8201   if ((code == TRUTH_ANDIF_EXPR && TREE_CODE (arg0) == TRUTH_ORIF_EXPR)
8202       || (code == TRUTH_ORIF_EXPR && TREE_CODE (arg0) == TRUTH_ANDIF_EXPR))
8203     {
8204       tem = merge_truthop_with_opposite_arm (loc, arg0, arg1, true);
8205       if (tem)
8206         return fold_build2_loc (loc, code, type, tem, arg1);
8207     }
8208
8209   if ((code == TRUTH_ANDIF_EXPR && TREE_CODE (arg1) == TRUTH_ORIF_EXPR)
8210       || (code == TRUTH_ORIF_EXPR && TREE_CODE (arg1) == TRUTH_ANDIF_EXPR))
8211     {
8212       tem = merge_truthop_with_opposite_arm (loc, arg1, arg0, false);
8213       if (tem)
8214         return fold_build2_loc (loc, code, type, arg0, tem);
8215     }
8216
8217   /* Check for the possibility of merging component references.  If our
8218      lhs is another similar operation, try to merge its rhs with our
8219      rhs.  Then try to merge our lhs and rhs.  */
8220   if (TREE_CODE (arg0) == code
8221       && 0 != (tem = fold_truth_andor_1 (loc, code, type,
8222                                          TREE_OPERAND (arg0, 1), arg1)))
8223     return fold_build2_loc (loc, code, type, TREE_OPERAND (arg0, 0), tem);
8224
8225   if ((tem = fold_truth_andor_1 (loc, code, type, arg0, arg1)) != 0)
8226     return tem;
8227
8228   if (LOGICAL_OP_NON_SHORT_CIRCUIT
8229       && (code == TRUTH_AND_EXPR
8230           || code == TRUTH_ANDIF_EXPR
8231           || code == TRUTH_OR_EXPR
8232           || code == TRUTH_ORIF_EXPR))
8233     {
8234       enum tree_code ncode, icode;
8235
8236       ncode = (code == TRUTH_ANDIF_EXPR || code == TRUTH_AND_EXPR)
8237               ? TRUTH_AND_EXPR : TRUTH_OR_EXPR;
8238       icode = ncode == TRUTH_AND_EXPR ? TRUTH_ANDIF_EXPR : TRUTH_ORIF_EXPR;
8239
8240       /* Transform ((A AND-IF B) AND[-IF] C) into (A AND-IF (B AND C)),
8241          or ((A OR-IF B) OR[-IF] C) into (A OR-IF (B OR C))
8242          We don't want to pack more than two leafs to a non-IF AND/OR
8243          expression.
8244          If tree-code of left-hand operand isn't an AND/OR-IF code and not
8245          equal to IF-CODE, then we don't want to add right-hand operand.
8246          If the inner right-hand side of left-hand operand has
8247          side-effects, or isn't simple, then we can't add to it,
8248          as otherwise we might destroy if-sequence.  */
8249       if (TREE_CODE (arg0) == icode
8250           && simple_operand_p_2 (arg1)
8251           /* Needed for sequence points to handle trappings, and
8252              side-effects.  */
8253           && simple_operand_p_2 (TREE_OPERAND (arg0, 1)))
8254         {
8255           tem = fold_build2_loc (loc, ncode, type, TREE_OPERAND (arg0, 1),
8256                                  arg1);
8257           return fold_build2_loc (loc, icode, type, TREE_OPERAND (arg0, 0),
8258                                   tem);
8259         }
8260         /* Same as abouve but for (A AND[-IF] (B AND-IF C)) -> ((A AND B) AND-IF C),
8261            or (A OR[-IF] (B OR-IF C) -> ((A OR B) OR-IF C).  */
8262       else if (TREE_CODE (arg1) == icode
8263           && simple_operand_p_2 (arg0)
8264           /* Needed for sequence points to handle trappings, and
8265              side-effects.  */
8266           && simple_operand_p_2 (TREE_OPERAND (arg1, 0)))
8267         {
8268           tem = fold_build2_loc (loc, ncode, type, 
8269                                  arg0, TREE_OPERAND (arg1, 0));
8270           return fold_build2_loc (loc, icode, type, tem,
8271                                   TREE_OPERAND (arg1, 1));
8272         }
8273       /* Transform (A AND-IF B) into (A AND B), or (A OR-IF B)
8274          into (A OR B).
8275          For sequence point consistancy, we need to check for trapping,
8276          and side-effects.  */
8277       else if (code == icode && simple_operand_p_2 (arg0)
8278                && simple_operand_p_2 (arg1))
8279         return fold_build2_loc (loc, ncode, type, arg0, arg1);
8280     }
8281
8282   return NULL_TREE;
8283 }
8284
8285 /* Fold a binary expression of code CODE and type TYPE with operands
8286    OP0 and OP1, containing either a MIN-MAX or a MAX-MIN combination.
8287    Return the folded expression if folding is successful.  Otherwise,
8288    return NULL_TREE.  */
8289
8290 static tree
8291 fold_minmax (location_t loc, enum tree_code code, tree type, tree op0, tree op1)
8292 {
8293   enum tree_code compl_code;
8294
8295   if (code == MIN_EXPR)
8296     compl_code = MAX_EXPR;
8297   else if (code == MAX_EXPR)
8298     compl_code = MIN_EXPR;
8299   else
8300     gcc_unreachable ();
8301
8302   /* MIN (MAX (a, b), b) == b.  */
8303   if (TREE_CODE (op0) == compl_code
8304       && operand_equal_p (TREE_OPERAND (op0, 1), op1, 0))
8305     return omit_one_operand_loc (loc, type, op1, TREE_OPERAND (op0, 0));
8306
8307   /* MIN (MAX (b, a), b) == b.  */
8308   if (TREE_CODE (op0) == compl_code
8309       && operand_equal_p (TREE_OPERAND (op0, 0), op1, 0)
8310       && reorder_operands_p (TREE_OPERAND (op0, 1), op1))
8311     return omit_one_operand_loc (loc, type, op1, TREE_OPERAND (op0, 1));
8312
8313   /* MIN (a, MAX (a, b)) == a.  */
8314   if (TREE_CODE (op1) == compl_code
8315       && operand_equal_p (op0, TREE_OPERAND (op1, 0), 0)
8316       && reorder_operands_p (op0, TREE_OPERAND (op1, 1)))
8317     return omit_one_operand_loc (loc, type, op0, TREE_OPERAND (op1, 1));
8318
8319   /* MIN (a, MAX (b, a)) == a.  */
8320   if (TREE_CODE (op1) == compl_code
8321       && operand_equal_p (op0, TREE_OPERAND (op1, 1), 0)
8322       && reorder_operands_p (op0, TREE_OPERAND (op1, 0)))
8323     return omit_one_operand_loc (loc, type, op0, TREE_OPERAND (op1, 0));
8324
8325   return NULL_TREE;
8326 }
8327
8328 /* Helper that tries to canonicalize the comparison ARG0 CODE ARG1
8329    by changing CODE to reduce the magnitude of constants involved in
8330    ARG0 of the comparison.
8331    Returns a canonicalized comparison tree if a simplification was
8332    possible, otherwise returns NULL_TREE.
8333    Set *STRICT_OVERFLOW_P to true if the canonicalization is only
8334    valid if signed overflow is undefined.  */
8335
8336 static tree
8337 maybe_canonicalize_comparison_1 (location_t loc, enum tree_code code, tree type,
8338                                  tree arg0, tree arg1,
8339                                  bool *strict_overflow_p)
8340 {
8341   enum tree_code code0 = TREE_CODE (arg0);
8342   tree t, cst0 = NULL_TREE;
8343   int sgn0;
8344   bool swap = false;
8345
8346   /* Match A +- CST code arg1 and CST code arg1.  We can change the
8347      first form only if overflow is undefined.  */
8348   if (!((TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg0))
8349          /* In principle pointers also have undefined overflow behavior,
8350             but that causes problems elsewhere.  */
8351          && !POINTER_TYPE_P (TREE_TYPE (arg0))
8352          && (code0 == MINUS_EXPR
8353              || code0 == PLUS_EXPR)
8354          && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
8355         || code0 == INTEGER_CST))
8356     return NULL_TREE;
8357
8358   /* Identify the constant in arg0 and its sign.  */
8359   if (code0 == INTEGER_CST)
8360     cst0 = arg0;
8361   else
8362     cst0 = TREE_OPERAND (arg0, 1);
8363   sgn0 = tree_int_cst_sgn (cst0);
8364
8365   /* Overflowed constants and zero will cause problems.  */
8366   if (integer_zerop (cst0)
8367       || TREE_OVERFLOW (cst0))
8368     return NULL_TREE;
8369
8370   /* See if we can reduce the magnitude of the constant in
8371      arg0 by changing the comparison code.  */
8372   if (code0 == INTEGER_CST)
8373     {
8374       /* CST <= arg1  ->  CST-1 < arg1.  */
8375       if (code == LE_EXPR && sgn0 == 1)
8376         code = LT_EXPR;
8377       /* -CST < arg1  ->  -CST-1 <= arg1.  */
8378       else if (code == LT_EXPR && sgn0 == -1)
8379         code = LE_EXPR;
8380       /* CST > arg1  ->  CST-1 >= arg1.  */
8381       else if (code == GT_EXPR && sgn0 == 1)
8382         code = GE_EXPR;
8383       /* -CST >= arg1  ->  -CST-1 > arg1.  */
8384       else if (code == GE_EXPR && sgn0 == -1)
8385         code = GT_EXPR;
8386       else
8387         return NULL_TREE;
8388       /* arg1 code' CST' might be more canonical.  */
8389       swap = true;
8390     }
8391   else
8392     {
8393       /* A - CST < arg1  ->  A - CST-1 <= arg1.  */
8394       if (code == LT_EXPR
8395           && code0 == ((sgn0 == -1) ? PLUS_EXPR : MINUS_EXPR))
8396         code = LE_EXPR;
8397       /* A + CST > arg1  ->  A + CST-1 >= arg1.  */
8398       else if (code == GT_EXPR
8399                && code0 == ((sgn0 == -1) ? MINUS_EXPR : PLUS_EXPR))
8400         code = GE_EXPR;
8401       /* A + CST <= arg1  ->  A + CST-1 < arg1.  */
8402       else if (code == LE_EXPR
8403                && code0 == ((sgn0 == -1) ? MINUS_EXPR : PLUS_EXPR))
8404         code = LT_EXPR;
8405       /* A - CST >= arg1  ->  A - CST-1 > arg1.  */
8406       else if (code == GE_EXPR
8407                && code0 == ((sgn0 == -1) ? PLUS_EXPR : MINUS_EXPR))
8408         code = GT_EXPR;
8409       else
8410         return NULL_TREE;
8411       *strict_overflow_p = true;
8412     }
8413
8414   /* Now build the constant reduced in magnitude.  But not if that
8415      would produce one outside of its types range.  */
8416   if (INTEGRAL_TYPE_P (TREE_TYPE (cst0))
8417       && ((sgn0 == 1
8418            && TYPE_MIN_VALUE (TREE_TYPE (cst0))
8419            && tree_int_cst_equal (cst0, TYPE_MIN_VALUE (TREE_TYPE (cst0))))
8420           || (sgn0 == -1
8421               && TYPE_MAX_VALUE (TREE_TYPE (cst0))
8422               && tree_int_cst_equal (cst0, TYPE_MAX_VALUE (TREE_TYPE (cst0))))))
8423     /* We cannot swap the comparison here as that would cause us to
8424        endlessly recurse.  */
8425     return NULL_TREE;
8426
8427   t = int_const_binop (sgn0 == -1 ? PLUS_EXPR : MINUS_EXPR,
8428                        cst0, build_int_cst (TREE_TYPE (cst0), 1));
8429   if (code0 != INTEGER_CST)
8430     t = fold_build2_loc (loc, code0, TREE_TYPE (arg0), TREE_OPERAND (arg0, 0), t);
8431   t = fold_convert (TREE_TYPE (arg1), t);
8432
8433   /* If swapping might yield to a more canonical form, do so.  */
8434   if (swap)
8435     return fold_build2_loc (loc, swap_tree_comparison (code), type, arg1, t);
8436   else
8437     return fold_build2_loc (loc, code, type, t, arg1);
8438 }
8439
8440 /* Canonicalize the comparison ARG0 CODE ARG1 with type TYPE with undefined
8441    overflow further.  Try to decrease the magnitude of constants involved
8442    by changing LE_EXPR and GE_EXPR to LT_EXPR and GT_EXPR or vice versa
8443    and put sole constants at the second argument position.
8444    Returns the canonicalized tree if changed, otherwise NULL_TREE.  */
8445
8446 static tree
8447 maybe_canonicalize_comparison (location_t loc, enum tree_code code, tree type,
8448                                tree arg0, tree arg1)
8449 {
8450   tree t;
8451   bool strict_overflow_p;
8452   const char * const warnmsg = G_("assuming signed overflow does not occur "
8453                                   "when reducing constant in comparison");
8454
8455   /* Try canonicalization by simplifying arg0.  */
8456   strict_overflow_p = false;
8457   t = maybe_canonicalize_comparison_1 (loc, code, type, arg0, arg1,
8458                                        &strict_overflow_p);
8459   if (t)
8460     {
8461       if (strict_overflow_p)
8462         fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_MAGNITUDE);
8463       return t;
8464     }
8465
8466   /* Try canonicalization by simplifying arg1 using the swapped
8467      comparison.  */
8468   code = swap_tree_comparison (code);
8469   strict_overflow_p = false;
8470   t = maybe_canonicalize_comparison_1 (loc, code, type, arg1, arg0,
8471                                        &strict_overflow_p);
8472   if (t && strict_overflow_p)
8473     fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_MAGNITUDE);
8474   return t;
8475 }
8476
8477 /* Return whether BASE + OFFSET + BITPOS may wrap around the address
8478    space.  This is used to avoid issuing overflow warnings for
8479    expressions like &p->x which can not wrap.  */
8480
8481 static bool
8482 pointer_may_wrap_p (tree base, tree offset, HOST_WIDE_INT bitpos)
8483 {
8484   if (!POINTER_TYPE_P (TREE_TYPE (base)))
8485     return true;
8486
8487   if (bitpos < 0)
8488     return true;
8489
8490   wide_int wi_offset;
8491   int precision = TYPE_PRECISION (TREE_TYPE (base));
8492   if (offset == NULL_TREE)
8493     wi_offset = wi::zero (precision);
8494   else if (TREE_CODE (offset) != INTEGER_CST || TREE_OVERFLOW (offset))
8495     return true;
8496   else
8497     wi_offset = offset;
8498
8499   bool overflow;
8500   wide_int units = wi::shwi (bitpos / BITS_PER_UNIT, precision);
8501   wide_int total = wi::add (wi_offset, units, UNSIGNED, &overflow);
8502   if (overflow)
8503     return true;
8504
8505   if (!wi::fits_uhwi_p (total))
8506     return true;
8507
8508   HOST_WIDE_INT size = int_size_in_bytes (TREE_TYPE (TREE_TYPE (base)));
8509   if (size <= 0)
8510     return true;
8511
8512   /* We can do slightly better for SIZE if we have an ADDR_EXPR of an
8513      array.  */
8514   if (TREE_CODE (base) == ADDR_EXPR)
8515     {
8516       HOST_WIDE_INT base_size;
8517
8518       base_size = int_size_in_bytes (TREE_TYPE (TREE_OPERAND (base, 0)));
8519       if (base_size > 0 && size < base_size)
8520         size = base_size;
8521     }
8522
8523   return total.to_uhwi () > (unsigned HOST_WIDE_INT) size;
8524 }
8525
8526 /* Return the HOST_WIDE_INT least significant bits of T, a sizetype
8527    kind INTEGER_CST.  This makes sure to properly sign-extend the
8528    constant.  */
8529
8530 static HOST_WIDE_INT
8531 size_low_cst (const_tree t)
8532 {
8533   HOST_WIDE_INT w = TREE_INT_CST_ELT (t, 0);
8534   int prec = TYPE_PRECISION (TREE_TYPE (t));
8535   if (prec < HOST_BITS_PER_WIDE_INT)
8536     return sext_hwi (w, prec);
8537   return w;
8538 }
8539
8540 /* Subroutine of fold_binary.  This routine performs all of the
8541    transformations that are common to the equality/inequality
8542    operators (EQ_EXPR and NE_EXPR) and the ordering operators
8543    (LT_EXPR, LE_EXPR, GE_EXPR and GT_EXPR).  Callers other than
8544    fold_binary should call fold_binary.  Fold a comparison with
8545    tree code CODE and type TYPE with operands OP0 and OP1.  Return
8546    the folded comparison or NULL_TREE.  */
8547
8548 static tree
8549 fold_comparison (location_t loc, enum tree_code code, tree type,
8550                  tree op0, tree op1)
8551 {
8552   const bool equality_code = (code == EQ_EXPR || code == NE_EXPR);
8553   tree arg0, arg1, tem;
8554
8555   arg0 = op0;
8556   arg1 = op1;
8557
8558   STRIP_SIGN_NOPS (arg0);
8559   STRIP_SIGN_NOPS (arg1);
8560
8561   /* Transform comparisons of the form X +- C1 CMP C2 to X CMP C2 -+ C1.  */
8562   if ((TREE_CODE (arg0) == PLUS_EXPR || TREE_CODE (arg0) == MINUS_EXPR)
8563       && (equality_code || TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg0)))
8564       && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
8565       && !TREE_OVERFLOW (TREE_OPERAND (arg0, 1))
8566       && TREE_CODE (arg1) == INTEGER_CST
8567       && !TREE_OVERFLOW (arg1))
8568     {
8569       const enum tree_code
8570         reverse_op = TREE_CODE (arg0) == PLUS_EXPR ? MINUS_EXPR : PLUS_EXPR;
8571       tree const1 = TREE_OPERAND (arg0, 1);
8572       tree const2 = fold_convert_loc (loc, TREE_TYPE (const1), arg1);
8573       tree variable = TREE_OPERAND (arg0, 0);
8574       tree new_const = int_const_binop (reverse_op, const2, const1);
8575
8576       /* If the constant operation overflowed this can be
8577          simplified as a comparison against INT_MAX/INT_MIN.  */
8578       if (TREE_OVERFLOW (new_const)
8579           && !TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg0)))
8580         {
8581           int const1_sgn = tree_int_cst_sgn (const1);
8582           enum tree_code code2 = code;
8583
8584           /* Get the sign of the constant on the lhs if the
8585              operation were VARIABLE + CONST1.  */
8586           if (TREE_CODE (arg0) == MINUS_EXPR)
8587             const1_sgn = -const1_sgn;
8588
8589           /* The sign of the constant determines if we overflowed
8590              INT_MAX (const1_sgn == -1) or INT_MIN (const1_sgn == 1).
8591              Canonicalize to the INT_MIN overflow by swapping the comparison
8592              if necessary.  */
8593           if (const1_sgn == -1)
8594             code2 = swap_tree_comparison (code);
8595
8596           /* We now can look at the canonicalized case
8597                VARIABLE + 1  CODE2  INT_MIN
8598              and decide on the result.  */
8599           switch (code2)
8600             {
8601             case EQ_EXPR:
8602             case LT_EXPR:
8603             case LE_EXPR:
8604               return
8605                 omit_one_operand_loc (loc, type, boolean_false_node, variable);
8606
8607             case NE_EXPR:
8608             case GE_EXPR:
8609             case GT_EXPR:
8610               return
8611                 omit_one_operand_loc (loc, type, boolean_true_node, variable);
8612
8613             default:
8614               gcc_unreachable ();
8615             }
8616         }
8617       else
8618         {
8619           if (!equality_code)
8620             fold_overflow_warning ("assuming signed overflow does not occur "
8621                                    "when changing X +- C1 cmp C2 to "
8622                                    "X cmp C2 -+ C1",
8623                                    WARN_STRICT_OVERFLOW_COMPARISON);
8624           return fold_build2_loc (loc, code, type, variable, new_const);
8625         }
8626     }
8627
8628   /* Transform comparisons of the form X - Y CMP 0 to X CMP Y.  */
8629   if (TREE_CODE (arg0) == MINUS_EXPR
8630       && equality_code
8631       && integer_zerop (arg1))
8632     {
8633       /* ??? The transformation is valid for the other operators if overflow
8634          is undefined for the type, but performing it here badly interacts
8635          with the transformation in fold_cond_expr_with_comparison which
8636          attempts to synthetize ABS_EXPR.  */
8637       if (!equality_code)
8638         fold_overflow_warning ("assuming signed overflow does not occur "
8639                                "when changing X - Y cmp 0 to X cmp Y",
8640                                WARN_STRICT_OVERFLOW_COMPARISON);
8641       return fold_build2_loc (loc, code, type, TREE_OPERAND (arg0, 0),
8642                               TREE_OPERAND (arg0, 1));
8643     }
8644
8645   /* For comparisons of pointers we can decompose it to a compile time
8646      comparison of the base objects and the offsets into the object.
8647      This requires at least one operand being an ADDR_EXPR or a
8648      POINTER_PLUS_EXPR to do more than the operand_equal_p test below.  */
8649   if (POINTER_TYPE_P (TREE_TYPE (arg0))
8650       && (TREE_CODE (arg0) == ADDR_EXPR
8651           || TREE_CODE (arg1) == ADDR_EXPR
8652           || TREE_CODE (arg0) == POINTER_PLUS_EXPR
8653           || TREE_CODE (arg1) == POINTER_PLUS_EXPR))
8654     {
8655       tree base0, base1, offset0 = NULL_TREE, offset1 = NULL_TREE;
8656       HOST_WIDE_INT bitsize, bitpos0 = 0, bitpos1 = 0;
8657       machine_mode mode;
8658       int volatilep, unsignedp;
8659       bool indirect_base0 = false, indirect_base1 = false;
8660
8661       /* Get base and offset for the access.  Strip ADDR_EXPR for
8662          get_inner_reference, but put it back by stripping INDIRECT_REF
8663          off the base object if possible.  indirect_baseN will be true
8664          if baseN is not an address but refers to the object itself.  */
8665       base0 = arg0;
8666       if (TREE_CODE (arg0) == ADDR_EXPR)
8667         {
8668           base0 = get_inner_reference (TREE_OPERAND (arg0, 0),
8669                                        &bitsize, &bitpos0, &offset0, &mode,
8670                                        &unsignedp, &volatilep, false);
8671           if (TREE_CODE (base0) == INDIRECT_REF)
8672             base0 = TREE_OPERAND (base0, 0);
8673           else
8674             indirect_base0 = true;
8675         }
8676       else if (TREE_CODE (arg0) == POINTER_PLUS_EXPR)
8677         {
8678           base0 = TREE_OPERAND (arg0, 0);
8679           STRIP_SIGN_NOPS (base0);
8680           if (TREE_CODE (base0) == ADDR_EXPR)
8681             {
8682               base0 = TREE_OPERAND (base0, 0);
8683               indirect_base0 = true;
8684             }
8685           offset0 = TREE_OPERAND (arg0, 1);
8686           if (tree_fits_shwi_p (offset0))
8687             {
8688               HOST_WIDE_INT off = size_low_cst (offset0);
8689               if ((HOST_WIDE_INT) (((unsigned HOST_WIDE_INT) off)
8690                                    * BITS_PER_UNIT)
8691                   / BITS_PER_UNIT == (HOST_WIDE_INT) off)
8692                 {
8693                   bitpos0 = off * BITS_PER_UNIT;
8694                   offset0 = NULL_TREE;
8695                 }
8696             }
8697         }
8698
8699       base1 = arg1;
8700       if (TREE_CODE (arg1) == ADDR_EXPR)
8701         {
8702           base1 = get_inner_reference (TREE_OPERAND (arg1, 0),
8703                                        &bitsize, &bitpos1, &offset1, &mode,
8704                                        &unsignedp, &volatilep, false);
8705           if (TREE_CODE (base1) == INDIRECT_REF)
8706             base1 = TREE_OPERAND (base1, 0);
8707           else
8708             indirect_base1 = true;
8709         }
8710       else if (TREE_CODE (arg1) == POINTER_PLUS_EXPR)
8711         {
8712           base1 = TREE_OPERAND (arg1, 0);
8713           STRIP_SIGN_NOPS (base1);
8714           if (TREE_CODE (base1) == ADDR_EXPR)
8715             {
8716               base1 = TREE_OPERAND (base1, 0);
8717               indirect_base1 = true;
8718             }
8719           offset1 = TREE_OPERAND (arg1, 1);
8720           if (tree_fits_shwi_p (offset1))
8721             {
8722               HOST_WIDE_INT off = size_low_cst (offset1);
8723               if ((HOST_WIDE_INT) (((unsigned HOST_WIDE_INT) off)
8724                                    * BITS_PER_UNIT)
8725                   / BITS_PER_UNIT == (HOST_WIDE_INT) off)
8726                 {
8727                   bitpos1 = off * BITS_PER_UNIT;
8728                   offset1 = NULL_TREE;
8729                 }
8730             }
8731         }
8732
8733       /* A local variable can never be pointed to by
8734          the default SSA name of an incoming parameter.  */
8735       if ((TREE_CODE (arg0) == ADDR_EXPR
8736            && indirect_base0
8737            && TREE_CODE (base0) == VAR_DECL
8738            && auto_var_in_fn_p (base0, current_function_decl)
8739            && !indirect_base1
8740            && TREE_CODE (base1) == SSA_NAME
8741            && SSA_NAME_IS_DEFAULT_DEF (base1)
8742            && TREE_CODE (SSA_NAME_VAR (base1)) == PARM_DECL)
8743           || (TREE_CODE (arg1) == ADDR_EXPR
8744               && indirect_base1
8745               && TREE_CODE (base1) == VAR_DECL
8746               && auto_var_in_fn_p (base1, current_function_decl)
8747               && !indirect_base0
8748               && TREE_CODE (base0) == SSA_NAME
8749               && SSA_NAME_IS_DEFAULT_DEF (base0)
8750               && TREE_CODE (SSA_NAME_VAR (base0)) == PARM_DECL))
8751         {
8752           if (code == NE_EXPR)
8753             return constant_boolean_node (1, type);
8754           else if (code == EQ_EXPR)
8755             return constant_boolean_node (0, type);
8756         }
8757       /* If we have equivalent bases we might be able to simplify.  */
8758       else if (indirect_base0 == indirect_base1
8759                && operand_equal_p (base0, base1, 0))
8760         {
8761           /* We can fold this expression to a constant if the non-constant
8762              offset parts are equal.  */
8763           if ((offset0 == offset1
8764                || (offset0 && offset1
8765                    && operand_equal_p (offset0, offset1, 0)))
8766               && (code == EQ_EXPR
8767                   || code == NE_EXPR
8768                   || (indirect_base0 && DECL_P (base0))
8769                   || POINTER_TYPE_OVERFLOW_UNDEFINED))
8770
8771             {
8772               if (!equality_code
8773                   && bitpos0 != bitpos1
8774                   && (pointer_may_wrap_p (base0, offset0, bitpos0)
8775                       || pointer_may_wrap_p (base1, offset1, bitpos1)))
8776                 fold_overflow_warning (("assuming pointer wraparound does not "
8777                                         "occur when comparing P +- C1 with "
8778                                         "P +- C2"),
8779                                        WARN_STRICT_OVERFLOW_CONDITIONAL);
8780
8781               switch (code)
8782                 {
8783                 case EQ_EXPR:
8784                   return constant_boolean_node (bitpos0 == bitpos1, type);
8785                 case NE_EXPR:
8786                   return constant_boolean_node (bitpos0 != bitpos1, type);
8787                 case LT_EXPR:
8788                   return constant_boolean_node (bitpos0 < bitpos1, type);
8789                 case LE_EXPR:
8790                   return constant_boolean_node (bitpos0 <= bitpos1, type);
8791                 case GE_EXPR:
8792                   return constant_boolean_node (bitpos0 >= bitpos1, type);
8793                 case GT_EXPR:
8794                   return constant_boolean_node (bitpos0 > bitpos1, type);
8795                 default:;
8796                 }
8797             }
8798           /* We can simplify the comparison to a comparison of the variable
8799              offset parts if the constant offset parts are equal.
8800              Be careful to use signed sizetype here because otherwise we
8801              mess with array offsets in the wrong way.  This is possible
8802              because pointer arithmetic is restricted to retain within an
8803              object and overflow on pointer differences is undefined as of
8804              6.5.6/8 and /9 with respect to the signed ptrdiff_t.  */
8805           else if (bitpos0 == bitpos1
8806                    && (equality_code
8807                        || (indirect_base0 && DECL_P (base0))
8808                        || POINTER_TYPE_OVERFLOW_UNDEFINED))
8809             {
8810               /* By converting to signed sizetype we cover middle-end pointer
8811                  arithmetic which operates on unsigned pointer types of size
8812                  type size and ARRAY_REF offsets which are properly sign or
8813                  zero extended from their type in case it is narrower than
8814                  sizetype.  */
8815               if (offset0 == NULL_TREE)
8816                 offset0 = build_int_cst (ssizetype, 0);
8817               else
8818                 offset0 = fold_convert_loc (loc, ssizetype, offset0);
8819               if (offset1 == NULL_TREE)
8820                 offset1 = build_int_cst (ssizetype, 0);
8821               else
8822                 offset1 = fold_convert_loc (loc, ssizetype, offset1);
8823
8824               if (!equality_code
8825                   && (pointer_may_wrap_p (base0, offset0, bitpos0)
8826                       || pointer_may_wrap_p (base1, offset1, bitpos1)))
8827                 fold_overflow_warning (("assuming pointer wraparound does not "
8828                                         "occur when comparing P +- C1 with "
8829                                         "P +- C2"),
8830                                        WARN_STRICT_OVERFLOW_COMPARISON);
8831
8832               return fold_build2_loc (loc, code, type, offset0, offset1);
8833             }
8834         }
8835       /* For non-equal bases we can simplify if they are addresses
8836          of local binding decls or constants.  */
8837       else if (indirect_base0 && indirect_base1
8838                /* We know that !operand_equal_p (base0, base1, 0)
8839                   because the if condition was false.  But make
8840                   sure two decls are not the same.  */
8841                && base0 != base1
8842                && TREE_CODE (arg0) == ADDR_EXPR
8843                && TREE_CODE (arg1) == ADDR_EXPR
8844                && (((TREE_CODE (base0) == VAR_DECL
8845                      || TREE_CODE (base0) == PARM_DECL)
8846                     && (targetm.binds_local_p (base0)
8847                         || CONSTANT_CLASS_P (base1)))
8848                    || CONSTANT_CLASS_P (base0))
8849                && (((TREE_CODE (base1) == VAR_DECL
8850                      || TREE_CODE (base1) == PARM_DECL)
8851                     && (targetm.binds_local_p (base1)
8852                         || CONSTANT_CLASS_P (base0)))
8853                    || CONSTANT_CLASS_P (base1)))
8854         {
8855           if (code == EQ_EXPR)
8856             return omit_two_operands_loc (loc, type, boolean_false_node,
8857                                       arg0, arg1);
8858           else if (code == NE_EXPR)
8859             return omit_two_operands_loc (loc, type, boolean_true_node,
8860                                       arg0, arg1);
8861         }
8862       /* For equal offsets we can simplify to a comparison of the
8863          base addresses.  */
8864       else if (bitpos0 == bitpos1
8865                && (indirect_base0
8866                    ? base0 != TREE_OPERAND (arg0, 0) : base0 != arg0)
8867                && (indirect_base1
8868                    ? base1 != TREE_OPERAND (arg1, 0) : base1 != arg1)
8869                && ((offset0 == offset1)
8870                    || (offset0 && offset1
8871                        && operand_equal_p (offset0, offset1, 0))))
8872         {
8873           if (indirect_base0)
8874             base0 = build_fold_addr_expr_loc (loc, base0);
8875           if (indirect_base1)
8876             base1 = build_fold_addr_expr_loc (loc, base1);
8877           return fold_build2_loc (loc, code, type, base0, base1);
8878         }
8879     }
8880
8881   /* Transform comparisons of the form X +- C1 CMP Y +- C2 to
8882      X CMP Y +- C2 +- C1 for signed X, Y.  This is valid if
8883      the resulting offset is smaller in absolute value than the
8884      original one and has the same sign.  */
8885   if (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg0))
8886       && (TREE_CODE (arg0) == PLUS_EXPR || TREE_CODE (arg0) == MINUS_EXPR)
8887       && (TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
8888           && !TREE_OVERFLOW (TREE_OPERAND (arg0, 1)))
8889       && (TREE_CODE (arg1) == PLUS_EXPR || TREE_CODE (arg1) == MINUS_EXPR)
8890       && (TREE_CODE (TREE_OPERAND (arg1, 1)) == INTEGER_CST
8891           && !TREE_OVERFLOW (TREE_OPERAND (arg1, 1))))
8892     {
8893       tree const1 = TREE_OPERAND (arg0, 1);
8894       tree const2 = TREE_OPERAND (arg1, 1);
8895       tree variable1 = TREE_OPERAND (arg0, 0);
8896       tree variable2 = TREE_OPERAND (arg1, 0);
8897       tree cst;
8898       const char * const warnmsg = G_("assuming signed overflow does not "
8899                                       "occur when combining constants around "
8900                                       "a comparison");
8901
8902       /* Put the constant on the side where it doesn't overflow and is
8903          of lower absolute value and of same sign than before.  */
8904       cst = int_const_binop (TREE_CODE (arg0) == TREE_CODE (arg1)
8905                              ? MINUS_EXPR : PLUS_EXPR,
8906                              const2, const1);
8907       if (!TREE_OVERFLOW (cst)
8908           && tree_int_cst_compare (const2, cst) == tree_int_cst_sgn (const2)
8909           && tree_int_cst_sgn (cst) == tree_int_cst_sgn (const2))
8910         {
8911           fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_COMPARISON);
8912           return fold_build2_loc (loc, code, type,
8913                                   variable1,
8914                                   fold_build2_loc (loc, TREE_CODE (arg1),
8915                                                    TREE_TYPE (arg1),
8916                                                    variable2, cst));
8917         }
8918
8919       cst = int_const_binop (TREE_CODE (arg0) == TREE_CODE (arg1)
8920                              ? MINUS_EXPR : PLUS_EXPR,
8921                              const1, const2);
8922       if (!TREE_OVERFLOW (cst)
8923           && tree_int_cst_compare (const1, cst) == tree_int_cst_sgn (const1)
8924           && tree_int_cst_sgn (cst) == tree_int_cst_sgn (const1))
8925         {
8926           fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_COMPARISON);
8927           return fold_build2_loc (loc, code, type,
8928                                   fold_build2_loc (loc, TREE_CODE (arg0),
8929                                                    TREE_TYPE (arg0),
8930                                                    variable1, cst),
8931                                   variable2);
8932         }
8933     }
8934
8935   /* Transform comparisons of the form X * C1 CMP 0 to X CMP 0 in the
8936      signed arithmetic case.  That form is created by the compiler
8937      often enough for folding it to be of value.  One example is in
8938      computing loop trip counts after Operator Strength Reduction.  */
8939   if (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg0))
8940       && TREE_CODE (arg0) == MULT_EXPR
8941       && (TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
8942           && !TREE_OVERFLOW (TREE_OPERAND (arg0, 1)))
8943       && integer_zerop (arg1))
8944     {
8945       tree const1 = TREE_OPERAND (arg0, 1);
8946       tree const2 = arg1;                       /* zero */
8947       tree variable1 = TREE_OPERAND (arg0, 0);
8948       enum tree_code cmp_code = code;
8949
8950       /* Handle unfolded multiplication by zero.  */
8951       if (integer_zerop (const1))
8952         return fold_build2_loc (loc, cmp_code, type, const1, const2);
8953
8954       fold_overflow_warning (("assuming signed overflow does not occur when "
8955                               "eliminating multiplication in comparison "
8956                               "with zero"),
8957                              WARN_STRICT_OVERFLOW_COMPARISON);
8958
8959       /* If const1 is negative we swap the sense of the comparison.  */
8960       if (tree_int_cst_sgn (const1) < 0)
8961         cmp_code = swap_tree_comparison (cmp_code);
8962
8963       return fold_build2_loc (loc, cmp_code, type, variable1, const2);
8964     }
8965
8966   tem = maybe_canonicalize_comparison (loc, code, type, arg0, arg1);
8967   if (tem)
8968     return tem;
8969
8970   if (FLOAT_TYPE_P (TREE_TYPE (arg0)))
8971     {
8972       tree targ0 = strip_float_extensions (arg0);
8973       tree targ1 = strip_float_extensions (arg1);
8974       tree newtype = TREE_TYPE (targ0);
8975
8976       if (TYPE_PRECISION (TREE_TYPE (targ1)) > TYPE_PRECISION (newtype))
8977         newtype = TREE_TYPE (targ1);
8978
8979       /* Fold (double)float1 CMP (double)float2 into float1 CMP float2.  */
8980       if (TYPE_PRECISION (newtype) < TYPE_PRECISION (TREE_TYPE (arg0)))
8981         return fold_build2_loc (loc, code, type,
8982                             fold_convert_loc (loc, newtype, targ0),
8983                             fold_convert_loc (loc, newtype, targ1));
8984
8985       /* (-a) CMP (-b) -> b CMP a  */
8986       if (TREE_CODE (arg0) == NEGATE_EXPR
8987           && TREE_CODE (arg1) == NEGATE_EXPR)
8988         return fold_build2_loc (loc, code, type, TREE_OPERAND (arg1, 0),
8989                             TREE_OPERAND (arg0, 0));
8990
8991       if (TREE_CODE (arg1) == REAL_CST)
8992         {
8993           REAL_VALUE_TYPE cst;
8994           cst = TREE_REAL_CST (arg1);
8995
8996           /* (-a) CMP CST -> a swap(CMP) (-CST)  */
8997           if (TREE_CODE (arg0) == NEGATE_EXPR)
8998             return fold_build2_loc (loc, swap_tree_comparison (code), type,
8999                                 TREE_OPERAND (arg0, 0),
9000                                 build_real (TREE_TYPE (arg1),
9001                                             real_value_negate (&cst)));
9002
9003           /* IEEE doesn't distinguish +0 and -0 in comparisons.  */
9004           /* a CMP (-0) -> a CMP 0  */
9005           if (REAL_VALUE_MINUS_ZERO (cst))
9006             return fold_build2_loc (loc, code, type, arg0,
9007                                 build_real (TREE_TYPE (arg1), dconst0));
9008
9009           /* x != NaN is always true, other ops are always false.  */
9010           if (REAL_VALUE_ISNAN (cst)
9011               && ! HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg1))))
9012             {
9013               tem = (code == NE_EXPR) ? integer_one_node : integer_zero_node;
9014               return omit_one_operand_loc (loc, type, tem, arg0);
9015             }
9016
9017           /* Fold comparisons against infinity.  */
9018           if (REAL_VALUE_ISINF (cst)
9019               && MODE_HAS_INFINITIES (TYPE_MODE (TREE_TYPE (arg1))))
9020             {
9021               tem = fold_inf_compare (loc, code, type, arg0, arg1);
9022               if (tem != NULL_TREE)
9023                 return tem;
9024             }
9025         }
9026
9027       /* If this is a comparison of a real constant with a PLUS_EXPR
9028          or a MINUS_EXPR of a real constant, we can convert it into a
9029          comparison with a revised real constant as long as no overflow
9030          occurs when unsafe_math_optimizations are enabled.  */
9031       if (flag_unsafe_math_optimizations
9032           && TREE_CODE (arg1) == REAL_CST
9033           && (TREE_CODE (arg0) == PLUS_EXPR
9034               || TREE_CODE (arg0) == MINUS_EXPR)
9035           && TREE_CODE (TREE_OPERAND (arg0, 1)) == REAL_CST
9036           && 0 != (tem = const_binop (TREE_CODE (arg0) == PLUS_EXPR
9037                                       ? MINUS_EXPR : PLUS_EXPR,
9038                                       arg1, TREE_OPERAND (arg0, 1)))
9039           && !TREE_OVERFLOW (tem))
9040         return fold_build2_loc (loc, code, type, TREE_OPERAND (arg0, 0), tem);
9041
9042       /* Likewise, we can simplify a comparison of a real constant with
9043          a MINUS_EXPR whose first operand is also a real constant, i.e.
9044          (c1 - x) < c2 becomes x > c1-c2.  Reordering is allowed on
9045          floating-point types only if -fassociative-math is set.  */
9046       if (flag_associative_math
9047           && TREE_CODE (arg1) == REAL_CST
9048           && TREE_CODE (arg0) == MINUS_EXPR
9049           && TREE_CODE (TREE_OPERAND (arg0, 0)) == REAL_CST
9050           && 0 != (tem = const_binop (MINUS_EXPR, TREE_OPERAND (arg0, 0),
9051                                       arg1))
9052           && !TREE_OVERFLOW (tem))
9053         return fold_build2_loc (loc, swap_tree_comparison (code), type,
9054                             TREE_OPERAND (arg0, 1), tem);
9055
9056       /* Fold comparisons against built-in math functions.  */
9057       if (TREE_CODE (arg1) == REAL_CST
9058           && flag_unsafe_math_optimizations
9059           && ! flag_errno_math)
9060         {
9061           enum built_in_function fcode = builtin_mathfn_code (arg0);
9062
9063           if (fcode != END_BUILTINS)
9064             {
9065               tem = fold_mathfn_compare (loc, fcode, code, type, arg0, arg1);
9066               if (tem != NULL_TREE)
9067                 return tem;
9068             }
9069         }
9070     }
9071
9072   if (TREE_CODE (TREE_TYPE (arg0)) == INTEGER_TYPE
9073       && CONVERT_EXPR_P (arg0))
9074     {
9075       /* If we are widening one operand of an integer comparison,
9076          see if the other operand is similarly being widened.  Perhaps we
9077          can do the comparison in the narrower type.  */
9078       tem = fold_widened_comparison (loc, code, type, arg0, arg1);
9079       if (tem)
9080         return tem;
9081
9082       /* Or if we are changing signedness.  */
9083       tem = fold_sign_changed_comparison (loc, code, type, arg0, arg1);
9084       if (tem)
9085         return tem;
9086     }
9087
9088   /* If this is comparing a constant with a MIN_EXPR or a MAX_EXPR of a
9089      constant, we can simplify it.  */
9090   if (TREE_CODE (arg1) == INTEGER_CST
9091       && (TREE_CODE (arg0) == MIN_EXPR
9092           || TREE_CODE (arg0) == MAX_EXPR)
9093       && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
9094     {
9095       tem = optimize_minmax_comparison (loc, code, type, op0, op1);
9096       if (tem)
9097         return tem;
9098     }
9099
9100   /* Simplify comparison of something with itself.  (For IEEE
9101      floating-point, we can only do some of these simplifications.)  */
9102   if (operand_equal_p (arg0, arg1, 0))
9103     {
9104       switch (code)
9105         {
9106         case EQ_EXPR:
9107           if (! FLOAT_TYPE_P (TREE_TYPE (arg0))
9108               || ! HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0))))
9109             return constant_boolean_node (1, type);
9110           break;
9111
9112         case GE_EXPR:
9113         case LE_EXPR:
9114           if (! FLOAT_TYPE_P (TREE_TYPE (arg0))
9115               || ! HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0))))
9116             return constant_boolean_node (1, type);
9117           return fold_build2_loc (loc, EQ_EXPR, type, arg0, arg1);
9118
9119         case NE_EXPR:
9120           /* For NE, we can only do this simplification if integer
9121              or we don't honor IEEE floating point NaNs.  */
9122           if (FLOAT_TYPE_P (TREE_TYPE (arg0))
9123               && HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0))))
9124             break;
9125           /* ... fall through ...  */
9126         case GT_EXPR:
9127         case LT_EXPR:
9128           return constant_boolean_node (0, type);
9129         default:
9130           gcc_unreachable ();
9131         }
9132     }
9133
9134   /* If we are comparing an expression that just has comparisons
9135      of two integer values, arithmetic expressions of those comparisons,
9136      and constants, we can simplify it.  There are only three cases
9137      to check: the two values can either be equal, the first can be
9138      greater, or the second can be greater.  Fold the expression for
9139      those three values.  Since each value must be 0 or 1, we have
9140      eight possibilities, each of which corresponds to the constant 0
9141      or 1 or one of the six possible comparisons.
9142
9143      This handles common cases like (a > b) == 0 but also handles
9144      expressions like  ((x > y) - (y > x)) > 0, which supposedly
9145      occur in macroized code.  */
9146
9147   if (TREE_CODE (arg1) == INTEGER_CST && TREE_CODE (arg0) != INTEGER_CST)
9148     {
9149       tree cval1 = 0, cval2 = 0;
9150       int save_p = 0;
9151
9152       if (twoval_comparison_p (arg0, &cval1, &cval2, &save_p)
9153           /* Don't handle degenerate cases here; they should already
9154              have been handled anyway.  */
9155           && cval1 != 0 && cval2 != 0
9156           && ! (TREE_CONSTANT (cval1) && TREE_CONSTANT (cval2))
9157           && TREE_TYPE (cval1) == TREE_TYPE (cval2)
9158           && INTEGRAL_TYPE_P (TREE_TYPE (cval1))
9159           && TYPE_MAX_VALUE (TREE_TYPE (cval1))
9160           && TYPE_MAX_VALUE (TREE_TYPE (cval2))
9161           && ! operand_equal_p (TYPE_MIN_VALUE (TREE_TYPE (cval1)),
9162                                 TYPE_MAX_VALUE (TREE_TYPE (cval2)), 0))
9163         {
9164           tree maxval = TYPE_MAX_VALUE (TREE_TYPE (cval1));
9165           tree minval = TYPE_MIN_VALUE (TREE_TYPE (cval1));
9166
9167           /* We can't just pass T to eval_subst in case cval1 or cval2
9168              was the same as ARG1.  */
9169
9170           tree high_result
9171                 = fold_build2_loc (loc, code, type,
9172                                eval_subst (loc, arg0, cval1, maxval,
9173                                            cval2, minval),
9174                                arg1);
9175           tree equal_result
9176                 = fold_build2_loc (loc, code, type,
9177                                eval_subst (loc, arg0, cval1, maxval,
9178                                            cval2, maxval),
9179                                arg1);
9180           tree low_result
9181                 = fold_build2_loc (loc, code, type,
9182                                eval_subst (loc, arg0, cval1, minval,
9183                                            cval2, maxval),
9184                                arg1);
9185
9186           /* All three of these results should be 0 or 1.  Confirm they are.
9187              Then use those values to select the proper code to use.  */
9188
9189           if (TREE_CODE (high_result) == INTEGER_CST
9190               && TREE_CODE (equal_result) == INTEGER_CST
9191               && TREE_CODE (low_result) == INTEGER_CST)
9192             {
9193               /* Make a 3-bit mask with the high-order bit being the
9194                  value for `>', the next for '=', and the low for '<'.  */
9195               switch ((integer_onep (high_result) * 4)
9196                       + (integer_onep (equal_result) * 2)
9197                       + integer_onep (low_result))
9198                 {
9199                 case 0:
9200                   /* Always false.  */
9201                   return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
9202                 case 1:
9203                   code = LT_EXPR;
9204                   break;
9205                 case 2:
9206                   code = EQ_EXPR;
9207                   break;
9208                 case 3:
9209                   code = LE_EXPR;
9210                   break;
9211                 case 4:
9212                   code = GT_EXPR;
9213                   break;
9214                 case 5:
9215                   code = NE_EXPR;
9216                   break;
9217                 case 6:
9218                   code = GE_EXPR;
9219                   break;
9220                 case 7:
9221                   /* Always true.  */
9222                   return omit_one_operand_loc (loc, type, integer_one_node, arg0);
9223                 }
9224
9225               if (save_p)
9226                 {
9227                   tem = save_expr (build2 (code, type, cval1, cval2));
9228                   SET_EXPR_LOCATION (tem, loc);
9229                   return tem;
9230                 }
9231               return fold_build2_loc (loc, code, type, cval1, cval2);
9232             }
9233         }
9234     }
9235
9236   /* We can fold X/C1 op C2 where C1 and C2 are integer constants
9237      into a single range test.  */
9238   if ((TREE_CODE (arg0) == TRUNC_DIV_EXPR
9239        || TREE_CODE (arg0) == EXACT_DIV_EXPR)
9240       && TREE_CODE (arg1) == INTEGER_CST
9241       && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
9242       && !integer_zerop (TREE_OPERAND (arg0, 1))
9243       && !TREE_OVERFLOW (TREE_OPERAND (arg0, 1))
9244       && !TREE_OVERFLOW (arg1))
9245     {
9246       tem = fold_div_compare (loc, code, type, arg0, arg1);
9247       if (tem != NULL_TREE)
9248         return tem;
9249     }
9250
9251   /* Fold ~X op ~Y as Y op X.  */
9252   if (TREE_CODE (arg0) == BIT_NOT_EXPR
9253       && TREE_CODE (arg1) == BIT_NOT_EXPR)
9254     {
9255       tree cmp_type = TREE_TYPE (TREE_OPERAND (arg0, 0));
9256       return fold_build2_loc (loc, code, type,
9257                           fold_convert_loc (loc, cmp_type,
9258                                             TREE_OPERAND (arg1, 0)),
9259                           TREE_OPERAND (arg0, 0));
9260     }
9261
9262   /* Fold ~X op C as X op' ~C, where op' is the swapped comparison.  */
9263   if (TREE_CODE (arg0) == BIT_NOT_EXPR
9264       && (TREE_CODE (arg1) == INTEGER_CST || TREE_CODE (arg1) == VECTOR_CST))
9265     {
9266       tree cmp_type = TREE_TYPE (TREE_OPERAND (arg0, 0));
9267       return fold_build2_loc (loc, swap_tree_comparison (code), type,
9268                           TREE_OPERAND (arg0, 0),
9269                           fold_build1_loc (loc, BIT_NOT_EXPR, cmp_type,
9270                                        fold_convert_loc (loc, cmp_type, arg1)));
9271     }
9272
9273   return NULL_TREE;
9274 }
9275
9276
9277 /* Subroutine of fold_binary.  Optimize complex multiplications of the
9278    form z * conj(z), as pow(realpart(z),2) + pow(imagpart(z),2).  The
9279    argument EXPR represents the expression "z" of type TYPE.  */
9280
9281 static tree
9282 fold_mult_zconjz (location_t loc, tree type, tree expr)
9283 {
9284   tree itype = TREE_TYPE (type);
9285   tree rpart, ipart, tem;
9286
9287   if (TREE_CODE (expr) == COMPLEX_EXPR)
9288     {
9289       rpart = TREE_OPERAND (expr, 0);
9290       ipart = TREE_OPERAND (expr, 1);
9291     }
9292   else if (TREE_CODE (expr) == COMPLEX_CST)
9293     {
9294       rpart = TREE_REALPART (expr);
9295       ipart = TREE_IMAGPART (expr);
9296     }
9297   else
9298     {
9299       expr = save_expr (expr);
9300       rpart = fold_build1_loc (loc, REALPART_EXPR, itype, expr);
9301       ipart = fold_build1_loc (loc, IMAGPART_EXPR, itype, expr);
9302     }
9303
9304   rpart = save_expr (rpart);
9305   ipart = save_expr (ipart);
9306   tem = fold_build2_loc (loc, PLUS_EXPR, itype,
9307                      fold_build2_loc (loc, MULT_EXPR, itype, rpart, rpart),
9308                      fold_build2_loc (loc, MULT_EXPR, itype, ipart, ipart));
9309   return fold_build2_loc (loc, COMPLEX_EXPR, type, tem,
9310                           build_zero_cst (itype));
9311 }
9312
9313
9314 /* Subroutine of fold_binary.  If P is the value of EXPR, computes
9315    power-of-two M and (arbitrary) N such that M divides (P-N).  This condition
9316    guarantees that P and N have the same least significant log2(M) bits.
9317    N is not otherwise constrained.  In particular, N is not normalized to
9318    0 <= N < M as is common.  In general, the precise value of P is unknown.
9319    M is chosen as large as possible such that constant N can be determined.
9320
9321    Returns M and sets *RESIDUE to N.
9322
9323    If ALLOW_FUNC_ALIGN is true, do take functions' DECL_ALIGN_UNIT into
9324    account.  This is not always possible due to PR 35705.
9325  */
9326
9327 static unsigned HOST_WIDE_INT
9328 get_pointer_modulus_and_residue (tree expr, unsigned HOST_WIDE_INT *residue,
9329                                  bool allow_func_align)
9330 {
9331   enum tree_code code;
9332
9333   *residue = 0;
9334
9335   code = TREE_CODE (expr);
9336   if (code == ADDR_EXPR)
9337     {
9338       unsigned int bitalign;
9339       get_object_alignment_1 (TREE_OPERAND (expr, 0), &bitalign, residue);
9340       *residue /= BITS_PER_UNIT;
9341       return bitalign / BITS_PER_UNIT;
9342     }
9343   else if (code == POINTER_PLUS_EXPR)
9344     {
9345       tree op0, op1;
9346       unsigned HOST_WIDE_INT modulus;
9347       enum tree_code inner_code;
9348
9349       op0 = TREE_OPERAND (expr, 0);
9350       STRIP_NOPS (op0);
9351       modulus = get_pointer_modulus_and_residue (op0, residue,
9352                                                  allow_func_align);
9353
9354       op1 = TREE_OPERAND (expr, 1);
9355       STRIP_NOPS (op1);
9356       inner_code = TREE_CODE (op1);
9357       if (inner_code == INTEGER_CST)
9358         {
9359           *residue += TREE_INT_CST_LOW (op1);
9360           return modulus;
9361         }
9362       else if (inner_code == MULT_EXPR)
9363         {
9364           op1 = TREE_OPERAND (op1, 1);
9365           if (TREE_CODE (op1) == INTEGER_CST)
9366             {
9367               unsigned HOST_WIDE_INT align;
9368
9369               /* Compute the greatest power-of-2 divisor of op1.  */
9370               align = TREE_INT_CST_LOW (op1);
9371               align &= -align;
9372
9373               /* If align is non-zero and less than *modulus, replace
9374                  *modulus with align., If align is 0, then either op1 is 0
9375                  or the greatest power-of-2 divisor of op1 doesn't fit in an
9376                  unsigned HOST_WIDE_INT.  In either case, no additional
9377                  constraint is imposed.  */
9378               if (align)
9379                 modulus = MIN (modulus, align);
9380
9381               return modulus;
9382             }
9383         }
9384     }
9385
9386   /* If we get here, we were unable to determine anything useful about the
9387      expression.  */
9388   return 1;
9389 }
9390
9391 /* Helper function for fold_vec_perm.  Store elements of VECTOR_CST or
9392    CONSTRUCTOR ARG into array ELTS and return true if successful.  */
9393
9394 static bool
9395 vec_cst_ctor_to_array (tree arg, tree *elts)
9396 {
9397   unsigned int nelts = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg)), i;
9398
9399   if (TREE_CODE (arg) == VECTOR_CST)
9400     {
9401       for (i = 0; i < VECTOR_CST_NELTS (arg); ++i)
9402         elts[i] = VECTOR_CST_ELT (arg, i);
9403     }
9404   else if (TREE_CODE (arg) == CONSTRUCTOR)
9405     {
9406       constructor_elt *elt;
9407
9408       FOR_EACH_VEC_SAFE_ELT (CONSTRUCTOR_ELTS (arg), i, elt)
9409         if (i >= nelts || TREE_CODE (TREE_TYPE (elt->value)) == VECTOR_TYPE)
9410           return false;
9411         else
9412           elts[i] = elt->value;
9413     }
9414   else
9415     return false;
9416   for (; i < nelts; i++)
9417     elts[i]
9418       = fold_convert (TREE_TYPE (TREE_TYPE (arg)), integer_zero_node);
9419   return true;
9420 }
9421
9422 /* Attempt to fold vector permutation of ARG0 and ARG1 vectors using SEL
9423    selector.  Return the folded VECTOR_CST or CONSTRUCTOR if successful,
9424    NULL_TREE otherwise.  */
9425
9426 static tree
9427 fold_vec_perm (tree type, tree arg0, tree arg1, const unsigned char *sel)
9428 {
9429   unsigned int nelts = TYPE_VECTOR_SUBPARTS (type), i;
9430   tree *elts;
9431   bool need_ctor = false;
9432
9433   gcc_assert (TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0)) == nelts
9434               && TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg1)) == nelts);
9435   if (TREE_TYPE (TREE_TYPE (arg0)) != TREE_TYPE (type)
9436       || TREE_TYPE (TREE_TYPE (arg1)) != TREE_TYPE (type))
9437     return NULL_TREE;
9438
9439   elts = XALLOCAVEC (tree, nelts * 3);
9440   if (!vec_cst_ctor_to_array (arg0, elts)
9441       || !vec_cst_ctor_to_array (arg1, elts + nelts))
9442     return NULL_TREE;
9443
9444   for (i = 0; i < nelts; i++)
9445     {
9446       if (!CONSTANT_CLASS_P (elts[sel[i]]))
9447         need_ctor = true;
9448       elts[i + 2 * nelts] = unshare_expr (elts[sel[i]]);
9449     }
9450
9451   if (need_ctor)
9452     {
9453       vec<constructor_elt, va_gc> *v;
9454       vec_alloc (v, nelts);
9455       for (i = 0; i < nelts; i++)
9456         CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, elts[2 * nelts + i]);
9457       return build_constructor (type, v);
9458     }
9459   else
9460     return build_vector (type, &elts[2 * nelts]);
9461 }
9462
9463 /* Try to fold a pointer difference of type TYPE two address expressions of
9464    array references AREF0 and AREF1 using location LOC.  Return a
9465    simplified expression for the difference or NULL_TREE.  */
9466
9467 static tree
9468 fold_addr_of_array_ref_difference (location_t loc, tree type,
9469                                    tree aref0, tree aref1)
9470 {
9471   tree base0 = TREE_OPERAND (aref0, 0);
9472   tree base1 = TREE_OPERAND (aref1, 0);
9473   tree base_offset = build_int_cst (type, 0);
9474
9475   /* If the bases are array references as well, recurse.  If the bases
9476      are pointer indirections compute the difference of the pointers.
9477      If the bases are equal, we are set.  */
9478   if ((TREE_CODE (base0) == ARRAY_REF
9479        && TREE_CODE (base1) == ARRAY_REF
9480        && (base_offset
9481            = fold_addr_of_array_ref_difference (loc, type, base0, base1)))
9482       || (INDIRECT_REF_P (base0)
9483           && INDIRECT_REF_P (base1)
9484           && (base_offset = fold_binary_loc (loc, MINUS_EXPR, type,
9485                                              TREE_OPERAND (base0, 0),
9486                                              TREE_OPERAND (base1, 0))))
9487       || operand_equal_p (base0, base1, 0))
9488     {
9489       tree op0 = fold_convert_loc (loc, type, TREE_OPERAND (aref0, 1));
9490       tree op1 = fold_convert_loc (loc, type, TREE_OPERAND (aref1, 1));
9491       tree esz = fold_convert_loc (loc, type, array_ref_element_size (aref0));
9492       tree diff = build2 (MINUS_EXPR, type, op0, op1);
9493       return fold_build2_loc (loc, PLUS_EXPR, type,
9494                               base_offset,
9495                               fold_build2_loc (loc, MULT_EXPR, type,
9496                                                diff, esz));
9497     }
9498   return NULL_TREE;
9499 }
9500
9501 /* If the real or vector real constant CST of type TYPE has an exact
9502    inverse, return it, else return NULL.  */
9503
9504 static tree
9505 exact_inverse (tree type, tree cst)
9506 {
9507   REAL_VALUE_TYPE r;
9508   tree unit_type, *elts;
9509   machine_mode mode;
9510   unsigned vec_nelts, i;
9511
9512   switch (TREE_CODE (cst))
9513     {
9514     case REAL_CST:
9515       r = TREE_REAL_CST (cst);
9516
9517       if (exact_real_inverse (TYPE_MODE (type), &r))
9518         return build_real (type, r);
9519
9520       return NULL_TREE;
9521
9522     case VECTOR_CST:
9523       vec_nelts = VECTOR_CST_NELTS (cst);
9524       elts = XALLOCAVEC (tree, vec_nelts);
9525       unit_type = TREE_TYPE (type);
9526       mode = TYPE_MODE (unit_type);
9527
9528       for (i = 0; i < vec_nelts; i++)
9529         {
9530           r = TREE_REAL_CST (VECTOR_CST_ELT (cst, i));
9531           if (!exact_real_inverse (mode, &r))
9532             return NULL_TREE;
9533           elts[i] = build_real (unit_type, r);
9534         }
9535
9536       return build_vector (type, elts);
9537
9538     default:
9539       return NULL_TREE;
9540     }
9541 }
9542
9543 /*  Mask out the tz least significant bits of X of type TYPE where
9544     tz is the number of trailing zeroes in Y.  */
9545 static wide_int
9546 mask_with_tz (tree type, const wide_int &x, const wide_int &y)
9547 {
9548   int tz = wi::ctz (y);
9549   if (tz > 0)
9550     return wi::mask (tz, true, TYPE_PRECISION (type)) & x;
9551   return x;
9552 }
9553
9554 /* Return true when T is an address and is known to be nonzero.
9555    For floating point we further ensure that T is not denormal.
9556    Similar logic is present in nonzero_address in rtlanal.h.
9557
9558    If the return value is based on the assumption that signed overflow
9559    is undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't
9560    change *STRICT_OVERFLOW_P.  */
9561
9562 static bool
9563 tree_expr_nonzero_warnv_p (tree t, bool *strict_overflow_p)
9564 {
9565   tree type = TREE_TYPE (t);
9566   enum tree_code code;
9567
9568   /* Doing something useful for floating point would need more work.  */
9569   if (!INTEGRAL_TYPE_P (type) && !POINTER_TYPE_P (type))
9570     return false;
9571
9572   code = TREE_CODE (t);
9573   switch (TREE_CODE_CLASS (code))
9574     {
9575     case tcc_unary:
9576       return tree_unary_nonzero_warnv_p (code, type, TREE_OPERAND (t, 0),
9577                                               strict_overflow_p);
9578     case tcc_binary:
9579     case tcc_comparison:
9580       return tree_binary_nonzero_warnv_p (code, type,
9581                                                TREE_OPERAND (t, 0),
9582                                                TREE_OPERAND (t, 1),
9583                                                strict_overflow_p);
9584     case tcc_constant:
9585     case tcc_declaration:
9586     case tcc_reference:
9587       return tree_single_nonzero_warnv_p (t, strict_overflow_p);
9588
9589     default:
9590       break;
9591     }
9592
9593   switch (code)
9594     {
9595     case TRUTH_NOT_EXPR:
9596       return tree_unary_nonzero_warnv_p (code, type, TREE_OPERAND (t, 0),
9597                                               strict_overflow_p);
9598
9599     case TRUTH_AND_EXPR:
9600     case TRUTH_OR_EXPR:
9601     case TRUTH_XOR_EXPR:
9602       return tree_binary_nonzero_warnv_p (code, type,
9603                                                TREE_OPERAND (t, 0),
9604                                                TREE_OPERAND (t, 1),
9605                                                strict_overflow_p);
9606
9607     case COND_EXPR:
9608     case CONSTRUCTOR:
9609     case OBJ_TYPE_REF:
9610     case ASSERT_EXPR:
9611     case ADDR_EXPR:
9612     case WITH_SIZE_EXPR:
9613     case SSA_NAME:
9614       return tree_single_nonzero_warnv_p (t, strict_overflow_p);
9615
9616     case COMPOUND_EXPR:
9617     case MODIFY_EXPR:
9618     case BIND_EXPR:
9619       return tree_expr_nonzero_warnv_p (TREE_OPERAND (t, 1),
9620                                         strict_overflow_p);
9621
9622     case SAVE_EXPR:
9623       return tree_expr_nonzero_warnv_p (TREE_OPERAND (t, 0),
9624                                         strict_overflow_p);
9625
9626     case CALL_EXPR:
9627       {
9628         tree fndecl = get_callee_fndecl (t);
9629         if (!fndecl) return false;
9630         if (flag_delete_null_pointer_checks && !flag_check_new
9631             && DECL_IS_OPERATOR_NEW (fndecl)
9632             && !TREE_NOTHROW (fndecl))
9633           return true;
9634         if (flag_delete_null_pointer_checks
9635             && lookup_attribute ("returns_nonnull",
9636                  TYPE_ATTRIBUTES (TREE_TYPE (fndecl))))
9637           return true;
9638         return alloca_call_p (t);
9639       }
9640
9641     default:
9642       break;
9643     }
9644   return false;
9645 }
9646
9647 /* Return true when T is an address and is known to be nonzero.
9648    Handle warnings about undefined signed overflow.  */
9649
9650 static bool
9651 tree_expr_nonzero_p (tree t)
9652 {
9653   bool ret, strict_overflow_p;
9654
9655   strict_overflow_p = false;
9656   ret = tree_expr_nonzero_warnv_p (t, &strict_overflow_p);
9657   if (strict_overflow_p)
9658     fold_overflow_warning (("assuming signed overflow does not occur when "
9659                             "determining that expression is always "
9660                             "non-zero"),
9661                            WARN_STRICT_OVERFLOW_MISC);
9662   return ret;
9663 }
9664
9665 /* Fold a binary expression of code CODE and type TYPE with operands
9666    OP0 and OP1.  LOC is the location of the resulting expression.
9667    Return the folded expression if folding is successful.  Otherwise,
9668    return NULL_TREE.  */
9669
9670 tree
9671 fold_binary_loc (location_t loc,
9672              enum tree_code code, tree type, tree op0, tree op1)
9673 {
9674   enum tree_code_class kind = TREE_CODE_CLASS (code);
9675   tree arg0, arg1, tem;
9676   tree t1 = NULL_TREE;
9677   bool strict_overflow_p;
9678   unsigned int prec;
9679
9680   gcc_assert (IS_EXPR_CODE_CLASS (kind)
9681               && TREE_CODE_LENGTH (code) == 2
9682               && op0 != NULL_TREE
9683               && op1 != NULL_TREE);
9684
9685   arg0 = op0;
9686   arg1 = op1;
9687
9688   /* Strip any conversions that don't change the mode.  This is
9689      safe for every expression, except for a comparison expression
9690      because its signedness is derived from its operands.  So, in
9691      the latter case, only strip conversions that don't change the
9692      signedness.  MIN_EXPR/MAX_EXPR also need signedness of arguments
9693      preserved.
9694
9695      Note that this is done as an internal manipulation within the
9696      constant folder, in order to find the simplest representation
9697      of the arguments so that their form can be studied.  In any
9698      cases, the appropriate type conversions should be put back in
9699      the tree that will get out of the constant folder.  */
9700
9701   if (kind == tcc_comparison || code == MIN_EXPR || code == MAX_EXPR)
9702     {
9703       STRIP_SIGN_NOPS (arg0);
9704       STRIP_SIGN_NOPS (arg1);
9705     }
9706   else
9707     {
9708       STRIP_NOPS (arg0);
9709       STRIP_NOPS (arg1);
9710     }
9711
9712   /* Note that TREE_CONSTANT isn't enough: static var addresses are
9713      constant but we can't do arithmetic on them.  */
9714   if ((TREE_CODE (arg0) == INTEGER_CST && TREE_CODE (arg1) == INTEGER_CST)
9715       || (TREE_CODE (arg0) == REAL_CST && TREE_CODE (arg1) == REAL_CST)
9716       || (TREE_CODE (arg0) == FIXED_CST && TREE_CODE (arg1) == FIXED_CST)
9717       || (TREE_CODE (arg0) == FIXED_CST && TREE_CODE (arg1) == INTEGER_CST)
9718       || (TREE_CODE (arg0) == COMPLEX_CST && TREE_CODE (arg1) == COMPLEX_CST)
9719       || (TREE_CODE (arg0) == VECTOR_CST && TREE_CODE (arg1) == VECTOR_CST)
9720       || (TREE_CODE (arg0) == VECTOR_CST && TREE_CODE (arg1) == INTEGER_CST))
9721     {
9722       if (kind == tcc_binary)
9723         {
9724           /* Make sure type and arg0 have the same saturating flag.  */
9725           gcc_assert (TYPE_SATURATING (type)
9726                       == TYPE_SATURATING (TREE_TYPE (arg0)));
9727           tem = const_binop (code, arg0, arg1);
9728         }
9729       else if (kind == tcc_comparison)
9730         tem = fold_relational_const (code, type, arg0, arg1);
9731       else
9732         tem = NULL_TREE;
9733
9734       if (tem != NULL_TREE)
9735         {
9736           if (TREE_TYPE (tem) != type)
9737             tem = fold_convert_loc (loc, type, tem);
9738           return tem;
9739         }
9740     }
9741
9742   /* If this is a commutative operation, and ARG0 is a constant, move it
9743      to ARG1 to reduce the number of tests below.  */
9744   if (commutative_tree_code (code)
9745       && tree_swap_operands_p (arg0, arg1, true))
9746     return fold_build2_loc (loc, code, type, op1, op0);
9747
9748   /* Likewise if this is a comparison, and ARG0 is a constant, move it
9749      to ARG1 to reduce the number of tests below.  */
9750   if (kind == tcc_comparison
9751       && tree_swap_operands_p (arg0, arg1, true))
9752     return fold_build2_loc (loc, swap_tree_comparison (code), type, op1, op0);
9753
9754   tem = generic_simplify (loc, code, type, op0, op1);
9755   if (tem)
9756     return tem;
9757
9758   /* ARG0 is the first operand of EXPR, and ARG1 is the second operand.
9759
9760      First check for cases where an arithmetic operation is applied to a
9761      compound, conditional, or comparison operation.  Push the arithmetic
9762      operation inside the compound or conditional to see if any folding
9763      can then be done.  Convert comparison to conditional for this purpose.
9764      The also optimizes non-constant cases that used to be done in
9765      expand_expr.
9766
9767      Before we do that, see if this is a BIT_AND_EXPR or a BIT_IOR_EXPR,
9768      one of the operands is a comparison and the other is a comparison, a
9769      BIT_AND_EXPR with the constant 1, or a truth value.  In that case, the
9770      code below would make the expression more complex.  Change it to a
9771      TRUTH_{AND,OR}_EXPR.  Likewise, convert a similar NE_EXPR to
9772      TRUTH_XOR_EXPR and an EQ_EXPR to the inversion of a TRUTH_XOR_EXPR.  */
9773
9774   if ((code == BIT_AND_EXPR || code == BIT_IOR_EXPR
9775        || code == EQ_EXPR || code == NE_EXPR)
9776       && TREE_CODE (type) != VECTOR_TYPE
9777       && ((truth_value_p (TREE_CODE (arg0))
9778            && (truth_value_p (TREE_CODE (arg1))
9779                || (TREE_CODE (arg1) == BIT_AND_EXPR
9780                    && integer_onep (TREE_OPERAND (arg1, 1)))))
9781           || (truth_value_p (TREE_CODE (arg1))
9782               && (truth_value_p (TREE_CODE (arg0))
9783                   || (TREE_CODE (arg0) == BIT_AND_EXPR
9784                       && integer_onep (TREE_OPERAND (arg0, 1)))))))
9785     {
9786       tem = fold_build2_loc (loc, code == BIT_AND_EXPR ? TRUTH_AND_EXPR
9787                          : code == BIT_IOR_EXPR ? TRUTH_OR_EXPR
9788                          : TRUTH_XOR_EXPR,
9789                          boolean_type_node,
9790                          fold_convert_loc (loc, boolean_type_node, arg0),
9791                          fold_convert_loc (loc, boolean_type_node, arg1));
9792
9793       if (code == EQ_EXPR)
9794         tem = invert_truthvalue_loc (loc, tem);
9795
9796       return fold_convert_loc (loc, type, tem);
9797     }
9798
9799   if (TREE_CODE_CLASS (code) == tcc_binary
9800       || TREE_CODE_CLASS (code) == tcc_comparison)
9801     {
9802       if (TREE_CODE (arg0) == COMPOUND_EXPR)
9803         {
9804           tem = fold_build2_loc (loc, code, type,
9805                              fold_convert_loc (loc, TREE_TYPE (op0),
9806                                                TREE_OPERAND (arg0, 1)), op1);
9807           return build2_loc (loc, COMPOUND_EXPR, type, TREE_OPERAND (arg0, 0),
9808                              tem);
9809         }
9810       if (TREE_CODE (arg1) == COMPOUND_EXPR
9811           && reorder_operands_p (arg0, TREE_OPERAND (arg1, 0)))
9812         {
9813           tem = fold_build2_loc (loc, code, type, op0,
9814                              fold_convert_loc (loc, TREE_TYPE (op1),
9815                                                TREE_OPERAND (arg1, 1)));
9816           return build2_loc (loc, COMPOUND_EXPR, type, TREE_OPERAND (arg1, 0),
9817                              tem);
9818         }
9819
9820       if (TREE_CODE (arg0) == COND_EXPR
9821           || TREE_CODE (arg0) == VEC_COND_EXPR
9822           || COMPARISON_CLASS_P (arg0))
9823         {
9824           tem = fold_binary_op_with_conditional_arg (loc, code, type, op0, op1,
9825                                                      arg0, arg1,
9826                                                      /*cond_first_p=*/1);
9827           if (tem != NULL_TREE)
9828             return tem;
9829         }
9830
9831       if (TREE_CODE (arg1) == COND_EXPR
9832           || TREE_CODE (arg1) == VEC_COND_EXPR
9833           || COMPARISON_CLASS_P (arg1))
9834         {
9835           tem = fold_binary_op_with_conditional_arg (loc, code, type, op0, op1,
9836                                                      arg1, arg0,
9837                                                      /*cond_first_p=*/0);
9838           if (tem != NULL_TREE)
9839             return tem;
9840         }
9841     }
9842
9843   switch (code)
9844     {
9845     case MEM_REF:
9846       /* MEM[&MEM[p, CST1], CST2] -> MEM[p, CST1 + CST2].  */
9847       if (TREE_CODE (arg0) == ADDR_EXPR
9848           && TREE_CODE (TREE_OPERAND (arg0, 0)) == MEM_REF)
9849         {
9850           tree iref = TREE_OPERAND (arg0, 0);
9851           return fold_build2 (MEM_REF, type,
9852                               TREE_OPERAND (iref, 0),
9853                               int_const_binop (PLUS_EXPR, arg1,
9854                                                TREE_OPERAND (iref, 1)));
9855         }
9856
9857       /* MEM[&a.b, CST2] -> MEM[&a, offsetof (a, b) + CST2].  */
9858       if (TREE_CODE (arg0) == ADDR_EXPR
9859           && handled_component_p (TREE_OPERAND (arg0, 0)))
9860         {
9861           tree base;
9862           HOST_WIDE_INT coffset;
9863           base = get_addr_base_and_unit_offset (TREE_OPERAND (arg0, 0),
9864                                                 &coffset);
9865           if (!base)
9866             return NULL_TREE;
9867           return fold_build2 (MEM_REF, type,
9868                               build_fold_addr_expr (base),
9869                               int_const_binop (PLUS_EXPR, arg1,
9870                                                size_int (coffset)));
9871         }
9872
9873       return NULL_TREE;
9874
9875     case POINTER_PLUS_EXPR:
9876       /* INT +p INT -> (PTR)(INT + INT).  Stripping types allows for this. */
9877       if (INTEGRAL_TYPE_P (TREE_TYPE (arg1))
9878            && INTEGRAL_TYPE_P (TREE_TYPE (arg0)))
9879         return fold_convert_loc (loc, type,
9880                                  fold_build2_loc (loc, PLUS_EXPR, sizetype,
9881                                               fold_convert_loc (loc, sizetype,
9882                                                                 arg1),
9883                                               fold_convert_loc (loc, sizetype,
9884                                                                 arg0)));
9885
9886       /* PTR_CST +p CST -> CST1 */
9887       if (TREE_CODE (arg0) == INTEGER_CST && TREE_CODE (arg1) == INTEGER_CST)
9888         return fold_build2_loc (loc, PLUS_EXPR, type, arg0,
9889                             fold_convert_loc (loc, type, arg1));
9890
9891       return NULL_TREE;
9892
9893     case PLUS_EXPR:
9894       if (INTEGRAL_TYPE_P (type) || VECTOR_INTEGER_TYPE_P (type))
9895         {
9896           /* X + (X / CST) * -CST is X % CST.  */
9897           if (TREE_CODE (arg1) == MULT_EXPR
9898               && TREE_CODE (TREE_OPERAND (arg1, 0)) == TRUNC_DIV_EXPR
9899               && operand_equal_p (arg0,
9900                                   TREE_OPERAND (TREE_OPERAND (arg1, 0), 0), 0))
9901             {
9902               tree cst0 = TREE_OPERAND (TREE_OPERAND (arg1, 0), 1);
9903               tree cst1 = TREE_OPERAND (arg1, 1);
9904               tree sum = fold_binary_loc (loc, PLUS_EXPR, TREE_TYPE (cst1),
9905                                       cst1, cst0);
9906               if (sum && integer_zerop (sum))
9907                 return fold_convert_loc (loc, type,
9908                                          fold_build2_loc (loc, TRUNC_MOD_EXPR,
9909                                                       TREE_TYPE (arg0), arg0,
9910                                                       cst0));
9911             }
9912         }
9913
9914       /* Handle (A1 * C1) + (A2 * C2) with A1, A2 or C1, C2 being the same or
9915          one.  Make sure the type is not saturating and has the signedness of
9916          the stripped operands, as fold_plusminus_mult_expr will re-associate.
9917          ??? The latter condition should use TYPE_OVERFLOW_* flags instead.  */
9918       if ((TREE_CODE (arg0) == MULT_EXPR
9919            || TREE_CODE (arg1) == MULT_EXPR)
9920           && !TYPE_SATURATING (type)
9921           && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (TREE_TYPE (arg0))
9922           && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (TREE_TYPE (arg1))
9923           && (!FLOAT_TYPE_P (type) || flag_associative_math))
9924         {
9925           tree tem = fold_plusminus_mult_expr (loc, code, type, arg0, arg1);
9926           if (tem)
9927             return tem;
9928         }
9929
9930       if (! FLOAT_TYPE_P (type))
9931         {
9932           /* If we are adding two BIT_AND_EXPR's, both of which are and'ing
9933              with a constant, and the two constants have no bits in common,
9934              we should treat this as a BIT_IOR_EXPR since this may produce more
9935              simplifications.  */
9936           if (TREE_CODE (arg0) == BIT_AND_EXPR
9937               && TREE_CODE (arg1) == BIT_AND_EXPR
9938               && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
9939               && TREE_CODE (TREE_OPERAND (arg1, 1)) == INTEGER_CST
9940               && wi::bit_and (TREE_OPERAND (arg0, 1),
9941                               TREE_OPERAND (arg1, 1)) == 0)
9942             {
9943               code = BIT_IOR_EXPR;
9944               goto bit_ior;
9945             }
9946
9947           /* Reassociate (plus (plus (mult) (foo)) (mult)) as
9948              (plus (plus (mult) (mult)) (foo)) so that we can
9949              take advantage of the factoring cases below.  */
9950           if (TYPE_OVERFLOW_WRAPS (type)
9951               && (((TREE_CODE (arg0) == PLUS_EXPR
9952                     || TREE_CODE (arg0) == MINUS_EXPR)
9953                    && TREE_CODE (arg1) == MULT_EXPR)
9954                   || ((TREE_CODE (arg1) == PLUS_EXPR
9955                        || TREE_CODE (arg1) == MINUS_EXPR)
9956                       && TREE_CODE (arg0) == MULT_EXPR)))
9957             {
9958               tree parg0, parg1, parg, marg;
9959               enum tree_code pcode;
9960
9961               if (TREE_CODE (arg1) == MULT_EXPR)
9962                 parg = arg0, marg = arg1;
9963               else
9964                 parg = arg1, marg = arg0;
9965               pcode = TREE_CODE (parg);
9966               parg0 = TREE_OPERAND (parg, 0);
9967               parg1 = TREE_OPERAND (parg, 1);
9968               STRIP_NOPS (parg0);
9969               STRIP_NOPS (parg1);
9970
9971               if (TREE_CODE (parg0) == MULT_EXPR
9972                   && TREE_CODE (parg1) != MULT_EXPR)
9973                 return fold_build2_loc (loc, pcode, type,
9974                                     fold_build2_loc (loc, PLUS_EXPR, type,
9975                                                  fold_convert_loc (loc, type,
9976                                                                    parg0),
9977                                                  fold_convert_loc (loc, type,
9978                                                                    marg)),
9979                                     fold_convert_loc (loc, type, parg1));
9980               if (TREE_CODE (parg0) != MULT_EXPR
9981                   && TREE_CODE (parg1) == MULT_EXPR)
9982                 return
9983                   fold_build2_loc (loc, PLUS_EXPR, type,
9984                                fold_convert_loc (loc, type, parg0),
9985                                fold_build2_loc (loc, pcode, type,
9986                                             fold_convert_loc (loc, type, marg),
9987                                             fold_convert_loc (loc, type,
9988                                                               parg1)));
9989             }
9990         }
9991       else
9992         {
9993           /* See if ARG1 is zero and X + ARG1 reduces to X.  */
9994           if (fold_real_zero_addition_p (TREE_TYPE (arg0), arg1, 0))
9995             return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
9996
9997           /* Likewise if the operands are reversed.  */
9998           if (fold_real_zero_addition_p (TREE_TYPE (arg1), arg0, 0))
9999             return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg1));
10000
10001           /* Convert X + -C into X - C.  */
10002           if (TREE_CODE (arg1) == REAL_CST
10003               && REAL_VALUE_NEGATIVE (TREE_REAL_CST (arg1)))
10004             {
10005               tem = fold_negate_const (arg1, type);
10006               if (!TREE_OVERFLOW (arg1) || !flag_trapping_math)
10007                 return fold_build2_loc (loc, MINUS_EXPR, type,
10008                                     fold_convert_loc (loc, type, arg0),
10009                                     fold_convert_loc (loc, type, tem));
10010             }
10011
10012           /* Fold __complex__ ( x, 0 ) + __complex__ ( 0, y )
10013              to __complex__ ( x, y ).  This is not the same for SNaNs or
10014              if signed zeros are involved.  */
10015           if (!HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg0)))
10016               && !HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (arg0)))
10017               && COMPLEX_FLOAT_TYPE_P (TREE_TYPE (arg0)))
10018             {
10019               tree rtype = TREE_TYPE (TREE_TYPE (arg0));
10020               tree arg0r = fold_unary_loc (loc, REALPART_EXPR, rtype, arg0);
10021               tree arg0i = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg0);
10022               bool arg0rz = false, arg0iz = false;
10023               if ((arg0r && (arg0rz = real_zerop (arg0r)))
10024                   || (arg0i && (arg0iz = real_zerop (arg0i))))
10025                 {
10026                   tree arg1r = fold_unary_loc (loc, REALPART_EXPR, rtype, arg1);
10027                   tree arg1i = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg1);
10028                   if (arg0rz && arg1i && real_zerop (arg1i))
10029                     {
10030                       tree rp = arg1r ? arg1r
10031                                   : build1 (REALPART_EXPR, rtype, arg1);
10032                       tree ip = arg0i ? arg0i
10033                                   : build1 (IMAGPART_EXPR, rtype, arg0);
10034                       return fold_build2_loc (loc, COMPLEX_EXPR, type, rp, ip);
10035                     }
10036                   else if (arg0iz && arg1r && real_zerop (arg1r))
10037                     {
10038                       tree rp = arg0r ? arg0r
10039                                   : build1 (REALPART_EXPR, rtype, arg0);
10040                       tree ip = arg1i ? arg1i
10041                                   : build1 (IMAGPART_EXPR, rtype, arg1);
10042                       return fold_build2_loc (loc, COMPLEX_EXPR, type, rp, ip);
10043                     }
10044                 }
10045             }
10046
10047           if (flag_unsafe_math_optimizations
10048               && (TREE_CODE (arg0) == RDIV_EXPR || TREE_CODE (arg0) == MULT_EXPR)
10049               && (TREE_CODE (arg1) == RDIV_EXPR || TREE_CODE (arg1) == MULT_EXPR)
10050               && (tem = distribute_real_division (loc, code, type, arg0, arg1)))
10051             return tem;
10052
10053           /* Convert x+x into x*2.0.  */
10054           if (operand_equal_p (arg0, arg1, 0)
10055               && SCALAR_FLOAT_TYPE_P (type))
10056             return fold_build2_loc (loc, MULT_EXPR, type, arg0,
10057                                 build_real (type, dconst2));
10058
10059           /* Convert a + (b*c + d*e) into (a + b*c) + d*e.
10060              We associate floats only if the user has specified
10061              -fassociative-math.  */
10062           if (flag_associative_math
10063               && TREE_CODE (arg1) == PLUS_EXPR
10064               && TREE_CODE (arg0) != MULT_EXPR)
10065             {
10066               tree tree10 = TREE_OPERAND (arg1, 0);
10067               tree tree11 = TREE_OPERAND (arg1, 1);
10068               if (TREE_CODE (tree11) == MULT_EXPR
10069                   && TREE_CODE (tree10) == MULT_EXPR)
10070                 {
10071                   tree tree0;
10072                   tree0 = fold_build2_loc (loc, PLUS_EXPR, type, arg0, tree10);
10073                   return fold_build2_loc (loc, PLUS_EXPR, type, tree0, tree11);
10074                 }
10075             }
10076           /* Convert (b*c + d*e) + a into b*c + (d*e +a).
10077              We associate floats only if the user has specified
10078              -fassociative-math.  */
10079           if (flag_associative_math
10080               && TREE_CODE (arg0) == PLUS_EXPR
10081               && TREE_CODE (arg1) != MULT_EXPR)
10082             {
10083               tree tree00 = TREE_OPERAND (arg0, 0);
10084               tree tree01 = TREE_OPERAND (arg0, 1);
10085               if (TREE_CODE (tree01) == MULT_EXPR
10086                   && TREE_CODE (tree00) == MULT_EXPR)
10087                 {
10088                   tree tree0;
10089                   tree0 = fold_build2_loc (loc, PLUS_EXPR, type, tree01, arg1);
10090                   return fold_build2_loc (loc, PLUS_EXPR, type, tree00, tree0);
10091                 }
10092             }
10093         }
10094
10095      bit_rotate:
10096       /* (A << C1) + (A >> C2) if A is unsigned and C1+C2 is the size of A
10097          is a rotate of A by C1 bits.  */
10098       /* (A << B) + (A >> (Z - B)) if A is unsigned and Z is the size of A
10099          is a rotate of A by B bits.  */
10100       {
10101         enum tree_code code0, code1;
10102         tree rtype;
10103         code0 = TREE_CODE (arg0);
10104         code1 = TREE_CODE (arg1);
10105         if (((code0 == RSHIFT_EXPR && code1 == LSHIFT_EXPR)
10106              || (code1 == RSHIFT_EXPR && code0 == LSHIFT_EXPR))
10107             && operand_equal_p (TREE_OPERAND (arg0, 0),
10108                                 TREE_OPERAND (arg1, 0), 0)
10109             && (rtype = TREE_TYPE (TREE_OPERAND (arg0, 0)),
10110                 TYPE_UNSIGNED (rtype))
10111             /* Only create rotates in complete modes.  Other cases are not
10112                expanded properly.  */
10113             && (element_precision (rtype)
10114                 == element_precision (TYPE_MODE (rtype))))
10115           {
10116             tree tree01, tree11;
10117             enum tree_code code01, code11;
10118
10119             tree01 = TREE_OPERAND (arg0, 1);
10120             tree11 = TREE_OPERAND (arg1, 1);
10121             STRIP_NOPS (tree01);
10122             STRIP_NOPS (tree11);
10123             code01 = TREE_CODE (tree01);
10124             code11 = TREE_CODE (tree11);
10125             if (code01 == INTEGER_CST
10126                 && code11 == INTEGER_CST
10127                 && (wi::to_widest (tree01) + wi::to_widest (tree11)
10128                     == element_precision (TREE_TYPE (TREE_OPERAND (arg0, 0)))))
10129               {
10130                 tem = build2_loc (loc, LROTATE_EXPR,
10131                                   TREE_TYPE (TREE_OPERAND (arg0, 0)),
10132                                   TREE_OPERAND (arg0, 0),
10133                                   code0 == LSHIFT_EXPR ? tree01 : tree11);
10134                 return fold_convert_loc (loc, type, tem);
10135               }
10136             else if (code11 == MINUS_EXPR)
10137               {
10138                 tree tree110, tree111;
10139                 tree110 = TREE_OPERAND (tree11, 0);
10140                 tree111 = TREE_OPERAND (tree11, 1);
10141                 STRIP_NOPS (tree110);
10142                 STRIP_NOPS (tree111);
10143                 if (TREE_CODE (tree110) == INTEGER_CST
10144                     && 0 == compare_tree_int (tree110,
10145                                               element_precision
10146                                               (TREE_TYPE (TREE_OPERAND
10147                                                           (arg0, 0))))
10148                     && operand_equal_p (tree01, tree111, 0))
10149                   return
10150                     fold_convert_loc (loc, type,
10151                                       build2 ((code0 == LSHIFT_EXPR
10152                                                ? LROTATE_EXPR
10153                                                : RROTATE_EXPR),
10154                                               TREE_TYPE (TREE_OPERAND (arg0, 0)),
10155                                               TREE_OPERAND (arg0, 0), tree01));
10156               }
10157             else if (code01 == MINUS_EXPR)
10158               {
10159                 tree tree010, tree011;
10160                 tree010 = TREE_OPERAND (tree01, 0);
10161                 tree011 = TREE_OPERAND (tree01, 1);
10162                 STRIP_NOPS (tree010);
10163                 STRIP_NOPS (tree011);
10164                 if (TREE_CODE (tree010) == INTEGER_CST
10165                     && 0 == compare_tree_int (tree010,
10166                                               element_precision
10167                                               (TREE_TYPE (TREE_OPERAND
10168                                                           (arg0, 0))))
10169                     && operand_equal_p (tree11, tree011, 0))
10170                     return fold_convert_loc
10171                       (loc, type,
10172                        build2 ((code0 != LSHIFT_EXPR
10173                                 ? LROTATE_EXPR
10174                                 : RROTATE_EXPR),
10175                                TREE_TYPE (TREE_OPERAND (arg0, 0)),
10176                                TREE_OPERAND (arg0, 0), tree11));
10177               }
10178           }
10179       }
10180
10181     associate:
10182       /* In most languages, can't associate operations on floats through
10183          parentheses.  Rather than remember where the parentheses were, we
10184          don't associate floats at all, unless the user has specified
10185          -fassociative-math.
10186          And, we need to make sure type is not saturating.  */
10187
10188       if ((! FLOAT_TYPE_P (type) || flag_associative_math)
10189           && !TYPE_SATURATING (type))
10190         {
10191           tree var0, con0, lit0, minus_lit0;
10192           tree var1, con1, lit1, minus_lit1;
10193           tree atype = type;
10194           bool ok = true;
10195
10196           /* Split both trees into variables, constants, and literals.  Then
10197              associate each group together, the constants with literals,
10198              then the result with variables.  This increases the chances of
10199              literals being recombined later and of generating relocatable
10200              expressions for the sum of a constant and literal.  */
10201           var0 = split_tree (arg0, code, &con0, &lit0, &minus_lit0, 0);
10202           var1 = split_tree (arg1, code, &con1, &lit1, &minus_lit1,
10203                              code == MINUS_EXPR);
10204
10205           /* Recombine MINUS_EXPR operands by using PLUS_EXPR.  */
10206           if (code == MINUS_EXPR)
10207             code = PLUS_EXPR;
10208
10209           /* With undefined overflow prefer doing association in a type
10210              which wraps on overflow, if that is one of the operand types.  */
10211           if ((POINTER_TYPE_P (type) && POINTER_TYPE_OVERFLOW_UNDEFINED)
10212               || (INTEGRAL_TYPE_P (type) && !TYPE_OVERFLOW_WRAPS (type)))
10213             {
10214               if (INTEGRAL_TYPE_P (TREE_TYPE (arg0))
10215                   && TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg0)))
10216                 atype = TREE_TYPE (arg0);
10217               else if (INTEGRAL_TYPE_P (TREE_TYPE (arg1))
10218                        && TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg1)))
10219                 atype = TREE_TYPE (arg1);
10220               gcc_assert (TYPE_PRECISION (atype) == TYPE_PRECISION (type));
10221             }
10222
10223           /* With undefined overflow we can only associate constants with one
10224              variable, and constants whose association doesn't overflow.  */
10225           if ((POINTER_TYPE_P (atype) && POINTER_TYPE_OVERFLOW_UNDEFINED)
10226               || (INTEGRAL_TYPE_P (atype) && !TYPE_OVERFLOW_WRAPS (atype)))
10227             {
10228               if (var0 && var1)
10229                 {
10230                   tree tmp0 = var0;
10231                   tree tmp1 = var1;
10232
10233                   if (TREE_CODE (tmp0) == NEGATE_EXPR)
10234                     tmp0 = TREE_OPERAND (tmp0, 0);
10235                   if (CONVERT_EXPR_P (tmp0)
10236                       && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (tmp0, 0)))
10237                       && (TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (tmp0, 0)))
10238                           <= TYPE_PRECISION (atype)))
10239                     tmp0 = TREE_OPERAND (tmp0, 0);
10240                   if (TREE_CODE (tmp1) == NEGATE_EXPR)
10241                     tmp1 = TREE_OPERAND (tmp1, 0);
10242                   if (CONVERT_EXPR_P (tmp1)
10243                       && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (tmp1, 0)))
10244                       && (TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (tmp1, 0)))
10245                           <= TYPE_PRECISION (atype)))
10246                     tmp1 = TREE_OPERAND (tmp1, 0);
10247                   /* The only case we can still associate with two variables
10248                      is if they are the same, modulo negation and bit-pattern
10249                      preserving conversions.  */
10250                   if (!operand_equal_p (tmp0, tmp1, 0))
10251                     ok = false;
10252                 }
10253             }
10254
10255           /* Only do something if we found more than two objects.  Otherwise,
10256              nothing has changed and we risk infinite recursion.  */
10257           if (ok
10258               && (2 < ((var0 != 0) + (var1 != 0)
10259                        + (con0 != 0) + (con1 != 0)
10260                        + (lit0 != 0) + (lit1 != 0)
10261                        + (minus_lit0 != 0) + (minus_lit1 != 0))))
10262             {
10263               bool any_overflows = false;
10264               if (lit0) any_overflows |= TREE_OVERFLOW (lit0);
10265               if (lit1) any_overflows |= TREE_OVERFLOW (lit1);
10266               if (minus_lit0) any_overflows |= TREE_OVERFLOW (minus_lit0);
10267               if (minus_lit1) any_overflows |= TREE_OVERFLOW (minus_lit1);
10268               var0 = associate_trees (loc, var0, var1, code, atype);
10269               con0 = associate_trees (loc, con0, con1, code, atype);
10270               lit0 = associate_trees (loc, lit0, lit1, code, atype);
10271               minus_lit0 = associate_trees (loc, minus_lit0, minus_lit1,
10272                                             code, atype);
10273
10274               /* Preserve the MINUS_EXPR if the negative part of the literal is
10275                  greater than the positive part.  Otherwise, the multiplicative
10276                  folding code (i.e extract_muldiv) may be fooled in case
10277                  unsigned constants are subtracted, like in the following
10278                  example: ((X*2 + 4) - 8U)/2.  */
10279               if (minus_lit0 && lit0)
10280                 {
10281                   if (TREE_CODE (lit0) == INTEGER_CST
10282                       && TREE_CODE (minus_lit0) == INTEGER_CST
10283                       && tree_int_cst_lt (lit0, minus_lit0))
10284                     {
10285                       minus_lit0 = associate_trees (loc, minus_lit0, lit0,
10286                                                     MINUS_EXPR, atype);
10287                       lit0 = 0;
10288                     }
10289                   else
10290                     {
10291                       lit0 = associate_trees (loc, lit0, minus_lit0,
10292                                               MINUS_EXPR, atype);
10293                       minus_lit0 = 0;
10294                     }
10295                 }
10296
10297               /* Don't introduce overflows through reassociation.  */
10298               if (!any_overflows
10299                   && ((lit0 && TREE_OVERFLOW (lit0))
10300                       || (minus_lit0 && TREE_OVERFLOW (minus_lit0))))
10301                 return NULL_TREE;
10302
10303               if (minus_lit0)
10304                 {
10305                   if (con0 == 0)
10306                     return
10307                       fold_convert_loc (loc, type,
10308                                         associate_trees (loc, var0, minus_lit0,
10309                                                          MINUS_EXPR, atype));
10310                   else
10311                     {
10312                       con0 = associate_trees (loc, con0, minus_lit0,
10313                                               MINUS_EXPR, atype);
10314                       return
10315                         fold_convert_loc (loc, type,
10316                                           associate_trees (loc, var0, con0,
10317                                                            PLUS_EXPR, atype));
10318                     }
10319                 }
10320
10321               con0 = associate_trees (loc, con0, lit0, code, atype);
10322               return
10323                 fold_convert_loc (loc, type, associate_trees (loc, var0, con0,
10324                                                               code, atype));
10325             }
10326         }
10327
10328       return NULL_TREE;
10329
10330     case MINUS_EXPR:
10331       /* Pointer simplifications for subtraction, simple reassociations. */
10332       if (POINTER_TYPE_P (TREE_TYPE (arg1)) && POINTER_TYPE_P (TREE_TYPE (arg0)))
10333         {
10334           /* (PTR0 p+ A) - (PTR1 p+ B) -> (PTR0 - PTR1) + (A - B) */
10335           if (TREE_CODE (arg0) == POINTER_PLUS_EXPR
10336               && TREE_CODE (arg1) == POINTER_PLUS_EXPR)
10337             {
10338               tree arg00 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
10339               tree arg01 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 1));
10340               tree arg10 = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 0));
10341               tree arg11 = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 1));
10342               return fold_build2_loc (loc, PLUS_EXPR, type,
10343                                   fold_build2_loc (loc, MINUS_EXPR, type,
10344                                                arg00, arg10),
10345                                   fold_build2_loc (loc, MINUS_EXPR, type,
10346                                                arg01, arg11));
10347             }
10348           /* (PTR0 p+ A) - PTR1 -> (PTR0 - PTR1) + A, assuming PTR0 - PTR1 simplifies. */
10349           else if (TREE_CODE (arg0) == POINTER_PLUS_EXPR)
10350             {
10351               tree arg00 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
10352               tree arg01 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 1));
10353               tree tmp = fold_binary_loc (loc, MINUS_EXPR, type, arg00,
10354                                       fold_convert_loc (loc, type, arg1));
10355               if (tmp)
10356                 return fold_build2_loc (loc, PLUS_EXPR, type, tmp, arg01);
10357             }
10358           /* PTR0 - (PTR1 p+ A) -> (PTR0 - PTR1) - A, assuming PTR0 - PTR1
10359              simplifies. */
10360           else if (TREE_CODE (arg1) == POINTER_PLUS_EXPR)
10361             {
10362               tree arg10 = fold_convert_loc (loc, type,
10363                                              TREE_OPERAND (arg1, 0));
10364               tree arg11 = fold_convert_loc (loc, type,
10365                                              TREE_OPERAND (arg1, 1));
10366               tree tmp = fold_binary_loc (loc, MINUS_EXPR, type,
10367                                           fold_convert_loc (loc, type, arg0),
10368                                           arg10);
10369               if (tmp)
10370                 return fold_build2_loc (loc, MINUS_EXPR, type, tmp, arg11);
10371             }
10372         }
10373       /* (-A) - B -> (-B) - A  where B is easily negated and we can swap.  */
10374       if (TREE_CODE (arg0) == NEGATE_EXPR
10375           && negate_expr_p (arg1)
10376           && reorder_operands_p (arg0, arg1))
10377         return fold_build2_loc (loc, MINUS_EXPR, type,
10378                             fold_convert_loc (loc, type,
10379                                               negate_expr (arg1)),
10380                             fold_convert_loc (loc, type,
10381                                               TREE_OPERAND (arg0, 0)));
10382       /* Convert -A - 1 to ~A.  */
10383       if (TREE_CODE (arg0) == NEGATE_EXPR
10384           && integer_each_onep (arg1)
10385           && !TYPE_OVERFLOW_TRAPS (type))
10386         return fold_build1_loc (loc, BIT_NOT_EXPR, type,
10387                             fold_convert_loc (loc, type,
10388                                               TREE_OPERAND (arg0, 0)));
10389
10390       /* Convert -1 - A to ~A.  */
10391       if (TREE_CODE (type) != COMPLEX_TYPE
10392           && integer_all_onesp (arg0))
10393         return fold_build1_loc (loc, BIT_NOT_EXPR, type, op1);
10394
10395
10396       /* X - (X / Y) * Y is X % Y.  */
10397       if ((INTEGRAL_TYPE_P (type) || VECTOR_INTEGER_TYPE_P (type))
10398           && TREE_CODE (arg1) == MULT_EXPR
10399           && TREE_CODE (TREE_OPERAND (arg1, 0)) == TRUNC_DIV_EXPR
10400           && operand_equal_p (arg0,
10401                               TREE_OPERAND (TREE_OPERAND (arg1, 0), 0), 0)
10402           && operand_equal_p (TREE_OPERAND (TREE_OPERAND (arg1, 0), 1),
10403                               TREE_OPERAND (arg1, 1), 0))
10404         return
10405           fold_convert_loc (loc, type,
10406                             fold_build2_loc (loc, TRUNC_MOD_EXPR, TREE_TYPE (arg0),
10407                                          arg0, TREE_OPERAND (arg1, 1)));
10408
10409       if (! FLOAT_TYPE_P (type))
10410         {
10411           if (integer_zerop (arg0))
10412             return negate_expr (fold_convert_loc (loc, type, arg1));
10413
10414           /* Fold A - (A & B) into ~B & A.  */
10415           if (!TREE_SIDE_EFFECTS (arg0)
10416               && TREE_CODE (arg1) == BIT_AND_EXPR)
10417             {
10418               if (operand_equal_p (arg0, TREE_OPERAND (arg1, 1), 0))
10419                 {
10420                   tree arg10 = fold_convert_loc (loc, type,
10421                                                  TREE_OPERAND (arg1, 0));
10422                   return fold_build2_loc (loc, BIT_AND_EXPR, type,
10423                                       fold_build1_loc (loc, BIT_NOT_EXPR,
10424                                                    type, arg10),
10425                                       fold_convert_loc (loc, type, arg0));
10426                 }
10427               if (operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
10428                 {
10429                   tree arg11 = fold_convert_loc (loc,
10430                                                  type, TREE_OPERAND (arg1, 1));
10431                   return fold_build2_loc (loc, BIT_AND_EXPR, type,
10432                                       fold_build1_loc (loc, BIT_NOT_EXPR,
10433                                                    type, arg11),
10434                                       fold_convert_loc (loc, type, arg0));
10435                 }
10436             }
10437
10438           /* Fold (A & ~B) - (A & B) into (A ^ B) - B, where B is
10439              any power of 2 minus 1.  */
10440           if (TREE_CODE (arg0) == BIT_AND_EXPR
10441               && TREE_CODE (arg1) == BIT_AND_EXPR
10442               && operand_equal_p (TREE_OPERAND (arg0, 0),
10443                                   TREE_OPERAND (arg1, 0), 0))
10444             {
10445               tree mask0 = TREE_OPERAND (arg0, 1);
10446               tree mask1 = TREE_OPERAND (arg1, 1);
10447               tree tem = fold_build1_loc (loc, BIT_NOT_EXPR, type, mask0);
10448
10449               if (operand_equal_p (tem, mask1, 0))
10450                 {
10451                   tem = fold_build2_loc (loc, BIT_XOR_EXPR, type,
10452                                      TREE_OPERAND (arg0, 0), mask1);
10453                   return fold_build2_loc (loc, MINUS_EXPR, type, tem, mask1);
10454                 }
10455             }
10456         }
10457
10458       /* See if ARG1 is zero and X - ARG1 reduces to X.  */
10459       else if (fold_real_zero_addition_p (TREE_TYPE (arg0), arg1, 1))
10460         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
10461
10462       /* (ARG0 - ARG1) is the same as (-ARG1 + ARG0).  So check whether
10463          ARG0 is zero and X + ARG0 reduces to X, since that would mean
10464          (-ARG1 + ARG0) reduces to -ARG1.  */
10465       else if (fold_real_zero_addition_p (TREE_TYPE (arg1), arg0, 0))
10466         return negate_expr (fold_convert_loc (loc, type, arg1));
10467
10468       /* Fold __complex__ ( x, 0 ) - __complex__ ( 0, y ) to
10469          __complex__ ( x, -y ).  This is not the same for SNaNs or if
10470          signed zeros are involved.  */
10471       if (!HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg0)))
10472           && !HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (arg0)))
10473           && COMPLEX_FLOAT_TYPE_P (TREE_TYPE (arg0)))
10474         {
10475           tree rtype = TREE_TYPE (TREE_TYPE (arg0));
10476           tree arg0r = fold_unary_loc (loc, REALPART_EXPR, rtype, arg0);
10477           tree arg0i = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg0);
10478           bool arg0rz = false, arg0iz = false;
10479           if ((arg0r && (arg0rz = real_zerop (arg0r)))
10480               || (arg0i && (arg0iz = real_zerop (arg0i))))
10481             {
10482               tree arg1r = fold_unary_loc (loc, REALPART_EXPR, rtype, arg1);
10483               tree arg1i = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg1);
10484               if (arg0rz && arg1i && real_zerop (arg1i))
10485                 {
10486                   tree rp = fold_build1_loc (loc, NEGATE_EXPR, rtype,
10487                                          arg1r ? arg1r
10488                                          : build1 (REALPART_EXPR, rtype, arg1));
10489                   tree ip = arg0i ? arg0i
10490                     : build1 (IMAGPART_EXPR, rtype, arg0);
10491                   return fold_build2_loc (loc, COMPLEX_EXPR, type, rp, ip);
10492                 }
10493               else if (arg0iz && arg1r && real_zerop (arg1r))
10494                 {
10495                   tree rp = arg0r ? arg0r
10496                     : build1 (REALPART_EXPR, rtype, arg0);
10497                   tree ip = fold_build1_loc (loc, NEGATE_EXPR, rtype,
10498                                          arg1i ? arg1i
10499                                          : build1 (IMAGPART_EXPR, rtype, arg1));
10500                   return fold_build2_loc (loc, COMPLEX_EXPR, type, rp, ip);
10501                 }
10502             }
10503         }
10504
10505       /* A - B -> A + (-B) if B is easily negatable.  */
10506       if (negate_expr_p (arg1)
10507           && !TYPE_OVERFLOW_SANITIZED (type)
10508           && ((FLOAT_TYPE_P (type)
10509                /* Avoid this transformation if B is a positive REAL_CST.  */
10510                && (TREE_CODE (arg1) != REAL_CST
10511                    ||  REAL_VALUE_NEGATIVE (TREE_REAL_CST (arg1))))
10512               || INTEGRAL_TYPE_P (type)))
10513         return fold_build2_loc (loc, PLUS_EXPR, type,
10514                             fold_convert_loc (loc, type, arg0),
10515                             fold_convert_loc (loc, type,
10516                                               negate_expr (arg1)));
10517
10518       /* Try folding difference of addresses.  */
10519       {
10520         HOST_WIDE_INT diff;
10521
10522         if ((TREE_CODE (arg0) == ADDR_EXPR
10523              || TREE_CODE (arg1) == ADDR_EXPR)
10524             && ptr_difference_const (arg0, arg1, &diff))
10525           return build_int_cst_type (type, diff);
10526       }
10527
10528       /* Fold &a[i] - &a[j] to i-j.  */
10529       if (TREE_CODE (arg0) == ADDR_EXPR
10530           && TREE_CODE (TREE_OPERAND (arg0, 0)) == ARRAY_REF
10531           && TREE_CODE (arg1) == ADDR_EXPR
10532           && TREE_CODE (TREE_OPERAND (arg1, 0)) == ARRAY_REF)
10533         {
10534           tree tem = fold_addr_of_array_ref_difference (loc, type,
10535                                                         TREE_OPERAND (arg0, 0),
10536                                                         TREE_OPERAND (arg1, 0));
10537           if (tem)
10538             return tem;
10539         }
10540
10541       if (FLOAT_TYPE_P (type)
10542           && flag_unsafe_math_optimizations
10543           && (TREE_CODE (arg0) == RDIV_EXPR || TREE_CODE (arg0) == MULT_EXPR)
10544           && (TREE_CODE (arg1) == RDIV_EXPR || TREE_CODE (arg1) == MULT_EXPR)
10545           && (tem = distribute_real_division (loc, code, type, arg0, arg1)))
10546         return tem;
10547
10548       /* Handle (A1 * C1) - (A2 * C2) with A1, A2 or C1, C2 being the same or
10549          one.  Make sure the type is not saturating and has the signedness of
10550          the stripped operands, as fold_plusminus_mult_expr will re-associate.
10551          ??? The latter condition should use TYPE_OVERFLOW_* flags instead.  */
10552       if ((TREE_CODE (arg0) == MULT_EXPR
10553            || TREE_CODE (arg1) == MULT_EXPR)
10554           && !TYPE_SATURATING (type)
10555           && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (TREE_TYPE (arg0))
10556           && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (TREE_TYPE (arg1))
10557           && (!FLOAT_TYPE_P (type) || flag_associative_math))
10558         {
10559           tree tem = fold_plusminus_mult_expr (loc, code, type, arg0, arg1);
10560           if (tem)
10561             return tem;
10562         }
10563
10564       goto associate;
10565
10566     case MULT_EXPR:
10567       /* (-A) * (-B) -> A * B  */
10568       if (TREE_CODE (arg0) == NEGATE_EXPR && negate_expr_p (arg1))
10569         return fold_build2_loc (loc, MULT_EXPR, type,
10570                             fold_convert_loc (loc, type,
10571                                               TREE_OPERAND (arg0, 0)),
10572                             fold_convert_loc (loc, type,
10573                                               negate_expr (arg1)));
10574       if (TREE_CODE (arg1) == NEGATE_EXPR && negate_expr_p (arg0))
10575         return fold_build2_loc (loc, MULT_EXPR, type,
10576                             fold_convert_loc (loc, type,
10577                                               negate_expr (arg0)),
10578                             fold_convert_loc (loc, type,
10579                                               TREE_OPERAND (arg1, 0)));
10580
10581       if (! FLOAT_TYPE_P (type))
10582         {
10583           /* Transform x * -1 into -x.  Make sure to do the negation
10584              on the original operand with conversions not stripped
10585              because we can only strip non-sign-changing conversions.  */
10586           if (integer_minus_onep (arg1))
10587             return fold_convert_loc (loc, type, negate_expr (op0));
10588           /* Transform x * -C into -x * C if x is easily negatable.  */
10589           if (TREE_CODE (arg1) == INTEGER_CST
10590               && tree_int_cst_sgn (arg1) == -1
10591               && negate_expr_p (arg0)
10592               && (tem = negate_expr (arg1)) != arg1
10593               && !TREE_OVERFLOW (tem))
10594             return fold_build2_loc (loc, MULT_EXPR, type,
10595                                 fold_convert_loc (loc, type,
10596                                                   negate_expr (arg0)),
10597                                 tem);
10598
10599           /* (a * (1 << b)) is (a << b)  */
10600           if (TREE_CODE (arg1) == LSHIFT_EXPR
10601               && integer_onep (TREE_OPERAND (arg1, 0)))
10602             return fold_build2_loc (loc, LSHIFT_EXPR, type, op0,
10603                                 TREE_OPERAND (arg1, 1));
10604           if (TREE_CODE (arg0) == LSHIFT_EXPR
10605               && integer_onep (TREE_OPERAND (arg0, 0)))
10606             return fold_build2_loc (loc, LSHIFT_EXPR, type, op1,
10607                                 TREE_OPERAND (arg0, 1));
10608
10609           /* (A + A) * C -> A * 2 * C  */
10610           if (TREE_CODE (arg0) == PLUS_EXPR
10611               && TREE_CODE (arg1) == INTEGER_CST
10612               && operand_equal_p (TREE_OPERAND (arg0, 0),
10613                                   TREE_OPERAND (arg0, 1), 0))
10614             return fold_build2_loc (loc, MULT_EXPR, type,
10615                                 omit_one_operand_loc (loc, type,
10616                                                   TREE_OPERAND (arg0, 0),
10617                                                   TREE_OPERAND (arg0, 1)),
10618                                 fold_build2_loc (loc, MULT_EXPR, type,
10619                                              build_int_cst (type, 2) , arg1));
10620
10621           /* ((T) (X /[ex] C)) * C cancels out if the conversion is
10622              sign-changing only.  */
10623           if (TREE_CODE (arg1) == INTEGER_CST
10624               && TREE_CODE (arg0) == EXACT_DIV_EXPR
10625               && operand_equal_p (arg1, TREE_OPERAND (arg0, 1), 0))
10626             return fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
10627
10628           strict_overflow_p = false;
10629           if (TREE_CODE (arg1) == INTEGER_CST
10630               && 0 != (tem = extract_muldiv (op0, arg1, code, NULL_TREE,
10631                                              &strict_overflow_p)))
10632             {
10633               if (strict_overflow_p)
10634                 fold_overflow_warning (("assuming signed overflow does not "
10635                                         "occur when simplifying "
10636                                         "multiplication"),
10637                                        WARN_STRICT_OVERFLOW_MISC);
10638               return fold_convert_loc (loc, type, tem);
10639             }
10640
10641           /* Optimize z * conj(z) for integer complex numbers.  */
10642           if (TREE_CODE (arg0) == CONJ_EXPR
10643               && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
10644             return fold_mult_zconjz (loc, type, arg1);
10645           if (TREE_CODE (arg1) == CONJ_EXPR
10646               && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
10647             return fold_mult_zconjz (loc, type, arg0);
10648         }
10649       else
10650         {
10651           /* Maybe fold x * 0 to 0.  The expressions aren't the same
10652              when x is NaN, since x * 0 is also NaN.  Nor are they the
10653              same in modes with signed zeros, since multiplying a
10654              negative value by 0 gives -0, not +0.  */
10655           if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0)))
10656               && !HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (arg0)))
10657               && real_zerop (arg1))
10658             return omit_one_operand_loc (loc, type, arg1, arg0);
10659           /* In IEEE floating point, x*1 is not equivalent to x for snans.
10660              Likewise for complex arithmetic with signed zeros.  */
10661           if (!HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg0)))
10662               && (!HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (arg0)))
10663                   || !COMPLEX_FLOAT_TYPE_P (TREE_TYPE (arg0)))
10664               && real_onep (arg1))
10665             return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
10666
10667           /* Transform x * -1.0 into -x.  */
10668           if (!HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg0)))
10669               && (!HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (arg0)))
10670                   || !COMPLEX_FLOAT_TYPE_P (TREE_TYPE (arg0)))
10671               && real_minus_onep (arg1))
10672             return fold_convert_loc (loc, type, negate_expr (arg0));
10673
10674           /* Convert (C1/X)*C2 into (C1*C2)/X.  This transformation may change
10675              the result for floating point types due to rounding so it is applied
10676              only if -fassociative-math was specify.  */
10677           if (flag_associative_math
10678               && TREE_CODE (arg0) == RDIV_EXPR
10679               && TREE_CODE (arg1) == REAL_CST
10680               && TREE_CODE (TREE_OPERAND (arg0, 0)) == REAL_CST)
10681             {
10682               tree tem = const_binop (MULT_EXPR, TREE_OPERAND (arg0, 0),
10683                                       arg1);
10684               if (tem)
10685                 return fold_build2_loc (loc, RDIV_EXPR, type, tem,
10686                                     TREE_OPERAND (arg0, 1));
10687             }
10688
10689           /* Strip sign operations from X in X*X, i.e. -Y*-Y -> Y*Y.  */
10690           if (operand_equal_p (arg0, arg1, 0))
10691             {
10692               tree tem = fold_strip_sign_ops (arg0);
10693               if (tem != NULL_TREE)
10694                 {
10695                   tem = fold_convert_loc (loc, type, tem);
10696                   return fold_build2_loc (loc, MULT_EXPR, type, tem, tem);
10697                 }
10698             }
10699
10700           /* Fold z * +-I to __complex__ (-+__imag z, +-__real z).
10701              This is not the same for NaNs or if signed zeros are
10702              involved.  */
10703           if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0)))
10704               && !HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (arg0)))
10705               && COMPLEX_FLOAT_TYPE_P (TREE_TYPE (arg0))
10706               && TREE_CODE (arg1) == COMPLEX_CST
10707               && real_zerop (TREE_REALPART (arg1)))
10708             {
10709               tree rtype = TREE_TYPE (TREE_TYPE (arg0));
10710               if (real_onep (TREE_IMAGPART (arg1)))
10711                 return
10712                   fold_build2_loc (loc, COMPLEX_EXPR, type,
10713                                negate_expr (fold_build1_loc (loc, IMAGPART_EXPR,
10714                                                              rtype, arg0)),
10715                                fold_build1_loc (loc, REALPART_EXPR, rtype, arg0));
10716               else if (real_minus_onep (TREE_IMAGPART (arg1)))
10717                 return
10718                   fold_build2_loc (loc, COMPLEX_EXPR, type,
10719                                fold_build1_loc (loc, IMAGPART_EXPR, rtype, arg0),
10720                                negate_expr (fold_build1_loc (loc, REALPART_EXPR,
10721                                                              rtype, arg0)));
10722             }
10723
10724           /* Optimize z * conj(z) for floating point complex numbers.
10725              Guarded by flag_unsafe_math_optimizations as non-finite
10726              imaginary components don't produce scalar results.  */
10727           if (flag_unsafe_math_optimizations
10728               && TREE_CODE (arg0) == CONJ_EXPR
10729               && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
10730             return fold_mult_zconjz (loc, type, arg1);
10731           if (flag_unsafe_math_optimizations
10732               && TREE_CODE (arg1) == CONJ_EXPR
10733               && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
10734             return fold_mult_zconjz (loc, type, arg0);
10735
10736           if (flag_unsafe_math_optimizations)
10737             {
10738               enum built_in_function fcode0 = builtin_mathfn_code (arg0);
10739               enum built_in_function fcode1 = builtin_mathfn_code (arg1);
10740
10741               /* Optimizations of root(...)*root(...).  */
10742               if (fcode0 == fcode1 && BUILTIN_ROOT_P (fcode0))
10743                 {
10744                   tree rootfn, arg;
10745                   tree arg00 = CALL_EXPR_ARG (arg0, 0);
10746                   tree arg10 = CALL_EXPR_ARG (arg1, 0);
10747
10748                   /* Optimize sqrt(x)*sqrt(x) as x.  */
10749                   if (BUILTIN_SQRT_P (fcode0)
10750                       && operand_equal_p (arg00, arg10, 0)
10751                       && ! HONOR_SNANS (TYPE_MODE (type)))
10752                     return arg00;
10753
10754                   /* Optimize root(x)*root(y) as root(x*y).  */
10755                   rootfn = TREE_OPERAND (CALL_EXPR_FN (arg0), 0);
10756                   arg = fold_build2_loc (loc, MULT_EXPR, type, arg00, arg10);
10757                   return build_call_expr_loc (loc, rootfn, 1, arg);
10758                 }
10759
10760               /* Optimize expN(x)*expN(y) as expN(x+y).  */
10761               if (fcode0 == fcode1 && BUILTIN_EXPONENT_P (fcode0))
10762                 {
10763                   tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg0), 0);
10764                   tree arg = fold_build2_loc (loc, PLUS_EXPR, type,
10765                                           CALL_EXPR_ARG (arg0, 0),
10766                                           CALL_EXPR_ARG (arg1, 0));
10767                   return build_call_expr_loc (loc, expfn, 1, arg);
10768                 }
10769
10770               /* Optimizations of pow(...)*pow(...).  */
10771               if ((fcode0 == BUILT_IN_POW && fcode1 == BUILT_IN_POW)
10772                   || (fcode0 == BUILT_IN_POWF && fcode1 == BUILT_IN_POWF)
10773                   || (fcode0 == BUILT_IN_POWL && fcode1 == BUILT_IN_POWL))
10774                 {
10775                   tree arg00 = CALL_EXPR_ARG (arg0, 0);
10776                   tree arg01 = CALL_EXPR_ARG (arg0, 1);
10777                   tree arg10 = CALL_EXPR_ARG (arg1, 0);
10778                   tree arg11 = CALL_EXPR_ARG (arg1, 1);
10779
10780                   /* Optimize pow(x,y)*pow(z,y) as pow(x*z,y).  */
10781                   if (operand_equal_p (arg01, arg11, 0))
10782                     {
10783                       tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg0), 0);
10784                       tree arg = fold_build2_loc (loc, MULT_EXPR, type,
10785                                               arg00, arg10);
10786                       return build_call_expr_loc (loc, powfn, 2, arg, arg01);
10787                     }
10788
10789                   /* Optimize pow(x,y)*pow(x,z) as pow(x,y+z).  */
10790                   if (operand_equal_p (arg00, arg10, 0))
10791                     {
10792                       tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg0), 0);
10793                       tree arg = fold_build2_loc (loc, PLUS_EXPR, type,
10794                                               arg01, arg11);
10795                       return build_call_expr_loc (loc, powfn, 2, arg00, arg);
10796                     }
10797                 }
10798
10799               /* Optimize tan(x)*cos(x) as sin(x).  */
10800               if (((fcode0 == BUILT_IN_TAN && fcode1 == BUILT_IN_COS)
10801                    || (fcode0 == BUILT_IN_TANF && fcode1 == BUILT_IN_COSF)
10802                    || (fcode0 == BUILT_IN_TANL && fcode1 == BUILT_IN_COSL)
10803                    || (fcode0 == BUILT_IN_COS && fcode1 == BUILT_IN_TAN)
10804                    || (fcode0 == BUILT_IN_COSF && fcode1 == BUILT_IN_TANF)
10805                    || (fcode0 == BUILT_IN_COSL && fcode1 == BUILT_IN_TANL))
10806                   && operand_equal_p (CALL_EXPR_ARG (arg0, 0),
10807                                       CALL_EXPR_ARG (arg1, 0), 0))
10808                 {
10809                   tree sinfn = mathfn_built_in (type, BUILT_IN_SIN);
10810
10811                   if (sinfn != NULL_TREE)
10812                     return build_call_expr_loc (loc, sinfn, 1,
10813                                             CALL_EXPR_ARG (arg0, 0));
10814                 }
10815
10816               /* Optimize x*pow(x,c) as pow(x,c+1).  */
10817               if (fcode1 == BUILT_IN_POW
10818                   || fcode1 == BUILT_IN_POWF
10819                   || fcode1 == BUILT_IN_POWL)
10820                 {
10821                   tree arg10 = CALL_EXPR_ARG (arg1, 0);
10822                   tree arg11 = CALL_EXPR_ARG (arg1, 1);
10823                   if (TREE_CODE (arg11) == REAL_CST
10824                       && !TREE_OVERFLOW (arg11)
10825                       && operand_equal_p (arg0, arg10, 0))
10826                     {
10827                       tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg1), 0);
10828                       REAL_VALUE_TYPE c;
10829                       tree arg;
10830
10831                       c = TREE_REAL_CST (arg11);
10832                       real_arithmetic (&c, PLUS_EXPR, &c, &dconst1);
10833                       arg = build_real (type, c);
10834                       return build_call_expr_loc (loc, powfn, 2, arg0, arg);
10835                     }
10836                 }
10837
10838               /* Optimize pow(x,c)*x as pow(x,c+1).  */
10839               if (fcode0 == BUILT_IN_POW
10840                   || fcode0 == BUILT_IN_POWF
10841                   || fcode0 == BUILT_IN_POWL)
10842                 {
10843                   tree arg00 = CALL_EXPR_ARG (arg0, 0);
10844                   tree arg01 = CALL_EXPR_ARG (arg0, 1);
10845                   if (TREE_CODE (arg01) == REAL_CST
10846                       && !TREE_OVERFLOW (arg01)
10847                       && operand_equal_p (arg1, arg00, 0))
10848                     {
10849                       tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg0), 0);
10850                       REAL_VALUE_TYPE c;
10851                       tree arg;
10852
10853                       c = TREE_REAL_CST (arg01);
10854                       real_arithmetic (&c, PLUS_EXPR, &c, &dconst1);
10855                       arg = build_real (type, c);
10856                       return build_call_expr_loc (loc, powfn, 2, arg1, arg);
10857                     }
10858                 }
10859
10860               /* Canonicalize x*x as pow(x,2.0), which is expanded as x*x.  */
10861               if (!in_gimple_form
10862                   && optimize
10863                   && operand_equal_p (arg0, arg1, 0))
10864                 {
10865                   tree powfn = mathfn_built_in (type, BUILT_IN_POW);
10866
10867                   if (powfn)
10868                     {
10869                       tree arg = build_real (type, dconst2);
10870                       return build_call_expr_loc (loc, powfn, 2, arg0, arg);
10871                     }
10872                 }
10873             }
10874         }
10875       goto associate;
10876
10877     case BIT_IOR_EXPR:
10878     bit_ior:
10879       /* ~X | X is -1.  */
10880       if (TREE_CODE (arg0) == BIT_NOT_EXPR
10881           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
10882         {
10883           t1 = build_zero_cst (type);
10884           t1 = fold_unary_loc (loc, BIT_NOT_EXPR, type, t1);
10885           return omit_one_operand_loc (loc, type, t1, arg1);
10886         }
10887
10888       /* X | ~X is -1.  */
10889       if (TREE_CODE (arg1) == BIT_NOT_EXPR
10890           && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
10891         {
10892           t1 = build_zero_cst (type);
10893           t1 = fold_unary_loc (loc, BIT_NOT_EXPR, type, t1);
10894           return omit_one_operand_loc (loc, type, t1, arg0);
10895         }
10896
10897       /* Canonicalize (X & C1) | C2.  */
10898       if (TREE_CODE (arg0) == BIT_AND_EXPR
10899           && TREE_CODE (arg1) == INTEGER_CST
10900           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
10901         {
10902           int width = TYPE_PRECISION (type), w;
10903           wide_int c1 = TREE_OPERAND (arg0, 1);
10904           wide_int c2 = arg1;
10905
10906           /* If (C1&C2) == C1, then (X&C1)|C2 becomes (X,C2).  */
10907           if ((c1 & c2) == c1)
10908             return omit_one_operand_loc (loc, type, arg1,
10909                                          TREE_OPERAND (arg0, 0));
10910
10911           wide_int msk = wi::mask (width, false,
10912                                    TYPE_PRECISION (TREE_TYPE (arg1)));
10913
10914           /* If (C1|C2) == ~0 then (X&C1)|C2 becomes X|C2.  */
10915           if (msk.and_not (c1 | c2) == 0)
10916             return fold_build2_loc (loc, BIT_IOR_EXPR, type,
10917                                     TREE_OPERAND (arg0, 0), arg1);
10918
10919           /* Minimize the number of bits set in C1, i.e. C1 := C1 & ~C2,
10920              unless (C1 & ~C2) | (C2 & C3) for some C3 is a mask of some
10921              mode which allows further optimizations.  */
10922           c1 &= msk;
10923           c2 &= msk;
10924           wide_int c3 = c1.and_not (c2);
10925           for (w = BITS_PER_UNIT; w <= width; w <<= 1)
10926             {
10927               wide_int mask = wi::mask (w, false,
10928                                         TYPE_PRECISION (type));
10929               if (((c1 | c2) & mask) == mask && c1.and_not (mask) == 0)
10930                 {
10931                   c3 = mask;
10932                   break;
10933                 }
10934             }
10935
10936           if (c3 != c1)
10937             return fold_build2_loc (loc, BIT_IOR_EXPR, type,
10938                                     fold_build2_loc (loc, BIT_AND_EXPR, type,
10939                                                      TREE_OPERAND (arg0, 0),
10940                                                      wide_int_to_tree (type,
10941                                                                        c3)),
10942                                     arg1);
10943         }
10944
10945       /* (X & ~Y) | (~X & Y) is X ^ Y */
10946       if (TREE_CODE (arg0) == BIT_AND_EXPR
10947           && TREE_CODE (arg1) == BIT_AND_EXPR)
10948         {
10949           tree a0, a1, l0, l1, n0, n1;
10950
10951           a0 = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 0));
10952           a1 = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 1));
10953
10954           l0 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
10955           l1 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 1));
10956           
10957           n0 = fold_build1_loc (loc, BIT_NOT_EXPR, type, l0);
10958           n1 = fold_build1_loc (loc, BIT_NOT_EXPR, type, l1);
10959           
10960           if ((operand_equal_p (n0, a0, 0)
10961                && operand_equal_p (n1, a1, 0))
10962               || (operand_equal_p (n0, a1, 0)
10963                   && operand_equal_p (n1, a0, 0)))
10964             return fold_build2_loc (loc, BIT_XOR_EXPR, type, l0, n1);
10965         }
10966
10967       t1 = distribute_bit_expr (loc, code, type, arg0, arg1);
10968       if (t1 != NULL_TREE)
10969         return t1;
10970
10971       /* Convert (or (not arg0) (not arg1)) to (not (and (arg0) (arg1))).
10972
10973          This results in more efficient code for machines without a NAND
10974          instruction.  Combine will canonicalize to the first form
10975          which will allow use of NAND instructions provided by the
10976          backend if they exist.  */
10977       if (TREE_CODE (arg0) == BIT_NOT_EXPR
10978           && TREE_CODE (arg1) == BIT_NOT_EXPR)
10979         {
10980           return
10981             fold_build1_loc (loc, BIT_NOT_EXPR, type,
10982                          build2 (BIT_AND_EXPR, type,
10983                                  fold_convert_loc (loc, type,
10984                                                    TREE_OPERAND (arg0, 0)),
10985                                  fold_convert_loc (loc, type,
10986                                                    TREE_OPERAND (arg1, 0))));
10987         }
10988
10989       /* See if this can be simplified into a rotate first.  If that
10990          is unsuccessful continue in the association code.  */
10991       goto bit_rotate;
10992
10993     case BIT_XOR_EXPR:
10994       /* ~X ^ X is -1.  */
10995       if (TREE_CODE (arg0) == BIT_NOT_EXPR
10996           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
10997         {
10998           t1 = build_zero_cst (type);
10999           t1 = fold_unary_loc (loc, BIT_NOT_EXPR, type, t1);
11000           return omit_one_operand_loc (loc, type, t1, arg1);
11001         }
11002
11003       /* X ^ ~X is -1.  */
11004       if (TREE_CODE (arg1) == BIT_NOT_EXPR
11005           && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
11006         {
11007           t1 = build_zero_cst (type);
11008           t1 = fold_unary_loc (loc, BIT_NOT_EXPR, type, t1);
11009           return omit_one_operand_loc (loc, type, t1, arg0);
11010         }
11011
11012       /* If we are XORing two BIT_AND_EXPR's, both of which are and'ing
11013          with a constant, and the two constants have no bits in common,
11014          we should treat this as a BIT_IOR_EXPR since this may produce more
11015          simplifications.  */
11016       if (TREE_CODE (arg0) == BIT_AND_EXPR
11017           && TREE_CODE (arg1) == BIT_AND_EXPR
11018           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
11019           && TREE_CODE (TREE_OPERAND (arg1, 1)) == INTEGER_CST
11020           && wi::bit_and (TREE_OPERAND (arg0, 1),
11021                           TREE_OPERAND (arg1, 1)) == 0)
11022         {
11023           code = BIT_IOR_EXPR;
11024           goto bit_ior;
11025         }
11026
11027       /* (X | Y) ^ X -> Y & ~ X*/
11028       if (TREE_CODE (arg0) == BIT_IOR_EXPR
11029           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
11030         {
11031           tree t2 = TREE_OPERAND (arg0, 1);
11032           t1 = fold_build1_loc (loc, BIT_NOT_EXPR, TREE_TYPE (arg1),
11033                             arg1);
11034           t1 = fold_build2_loc (loc, BIT_AND_EXPR, type,
11035                             fold_convert_loc (loc, type, t2),
11036                             fold_convert_loc (loc, type, t1));
11037           return t1;
11038         }
11039
11040       /* (Y | X) ^ X -> Y & ~ X*/
11041       if (TREE_CODE (arg0) == BIT_IOR_EXPR
11042           && operand_equal_p (TREE_OPERAND (arg0, 1), arg1, 0))
11043         {
11044           tree t2 = TREE_OPERAND (arg0, 0);
11045           t1 = fold_build1_loc (loc, BIT_NOT_EXPR, TREE_TYPE (arg1),
11046                             arg1);
11047           t1 = fold_build2_loc (loc, BIT_AND_EXPR, type,
11048                             fold_convert_loc (loc, type, t2),
11049                             fold_convert_loc (loc, type, t1));
11050           return t1;
11051         }
11052
11053       /* X ^ (X | Y) -> Y & ~ X*/
11054       if (TREE_CODE (arg1) == BIT_IOR_EXPR
11055           && operand_equal_p (TREE_OPERAND (arg1, 0), arg0, 0))
11056         {
11057           tree t2 = TREE_OPERAND (arg1, 1);
11058           t1 = fold_build1_loc (loc, BIT_NOT_EXPR, TREE_TYPE (arg0),
11059                             arg0);
11060           t1 = fold_build2_loc (loc, BIT_AND_EXPR, type,
11061                             fold_convert_loc (loc, type, t2),
11062                             fold_convert_loc (loc, type, t1));
11063           return t1;
11064         }
11065
11066       /* X ^ (Y | X) -> Y & ~ X*/
11067       if (TREE_CODE (arg1) == BIT_IOR_EXPR
11068           && operand_equal_p (TREE_OPERAND (arg1, 1), arg0, 0))
11069         {
11070           tree t2 = TREE_OPERAND (arg1, 0);
11071           t1 = fold_build1_loc (loc, BIT_NOT_EXPR, TREE_TYPE (arg0),
11072                             arg0);
11073           t1 = fold_build2_loc (loc, BIT_AND_EXPR, type,
11074                             fold_convert_loc (loc, type, t2),
11075                             fold_convert_loc (loc, type, t1));
11076           return t1;
11077         }
11078
11079       /* Convert ~X ^ ~Y to X ^ Y.  */
11080       if (TREE_CODE (arg0) == BIT_NOT_EXPR
11081           && TREE_CODE (arg1) == BIT_NOT_EXPR)
11082         return fold_build2_loc (loc, code, type,
11083                             fold_convert_loc (loc, type,
11084                                               TREE_OPERAND (arg0, 0)),
11085                             fold_convert_loc (loc, type,
11086                                               TREE_OPERAND (arg1, 0)));
11087
11088       /* Convert ~X ^ C to X ^ ~C.  */
11089       if (TREE_CODE (arg0) == BIT_NOT_EXPR
11090           && TREE_CODE (arg1) == INTEGER_CST)
11091         return fold_build2_loc (loc, code, type,
11092                             fold_convert_loc (loc, type,
11093                                               TREE_OPERAND (arg0, 0)),
11094                             fold_build1_loc (loc, BIT_NOT_EXPR, type, arg1));
11095
11096       /* Fold (X & 1) ^ 1 as (X & 1) == 0.  */
11097       if (TREE_CODE (arg0) == BIT_AND_EXPR
11098           && INTEGRAL_TYPE_P (type)
11099           && integer_onep (TREE_OPERAND (arg0, 1))
11100           && integer_onep (arg1))
11101         return fold_build2_loc (loc, EQ_EXPR, type, arg0,
11102                                 build_zero_cst (TREE_TYPE (arg0)));
11103
11104       /* Fold (X & Y) ^ Y as ~X & Y.  */
11105       if (TREE_CODE (arg0) == BIT_AND_EXPR
11106           && operand_equal_p (TREE_OPERAND (arg0, 1), arg1, 0))
11107         {
11108           tem = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
11109           return fold_build2_loc (loc, BIT_AND_EXPR, type,
11110                               fold_build1_loc (loc, BIT_NOT_EXPR, type, tem),
11111                               fold_convert_loc (loc, type, arg1));
11112         }
11113       /* Fold (X & Y) ^ X as ~Y & X.  */
11114       if (TREE_CODE (arg0) == BIT_AND_EXPR
11115           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0)
11116           && reorder_operands_p (TREE_OPERAND (arg0, 1), arg1))
11117         {
11118           tem = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 1));
11119           return fold_build2_loc (loc, BIT_AND_EXPR, type,
11120                               fold_build1_loc (loc, BIT_NOT_EXPR, type, tem),
11121                               fold_convert_loc (loc, type, arg1));
11122         }
11123       /* Fold X ^ (X & Y) as X & ~Y.  */
11124       if (TREE_CODE (arg1) == BIT_AND_EXPR
11125           && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
11126         {
11127           tem = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 1));
11128           return fold_build2_loc (loc, BIT_AND_EXPR, type,
11129                               fold_convert_loc (loc, type, arg0),
11130                               fold_build1_loc (loc, BIT_NOT_EXPR, type, tem));
11131         }
11132       /* Fold X ^ (Y & X) as ~Y & X.  */
11133       if (TREE_CODE (arg1) == BIT_AND_EXPR
11134           && operand_equal_p (arg0, TREE_OPERAND (arg1, 1), 0)
11135           && reorder_operands_p (arg0, TREE_OPERAND (arg1, 0)))
11136         {
11137           tem = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 0));
11138           return fold_build2_loc (loc, BIT_AND_EXPR, type,
11139                               fold_build1_loc (loc, BIT_NOT_EXPR, type, tem),
11140                               fold_convert_loc (loc, type, arg0));
11141         }
11142
11143       /* See if this can be simplified into a rotate first.  If that
11144          is unsuccessful continue in the association code.  */
11145       goto bit_rotate;
11146
11147     case BIT_AND_EXPR:
11148       /* ~X & X, (X == 0) & X, and !X & X are always zero.  */
11149       if ((TREE_CODE (arg0) == BIT_NOT_EXPR
11150            || TREE_CODE (arg0) == TRUTH_NOT_EXPR
11151            || (TREE_CODE (arg0) == EQ_EXPR
11152                && integer_zerop (TREE_OPERAND (arg0, 1))))
11153           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
11154         return omit_one_operand_loc (loc, type, integer_zero_node, arg1);
11155
11156       /* X & ~X , X & (X == 0), and X & !X are always zero.  */
11157       if ((TREE_CODE (arg1) == BIT_NOT_EXPR
11158            || TREE_CODE (arg1) == TRUTH_NOT_EXPR
11159            || (TREE_CODE (arg1) == EQ_EXPR
11160                && integer_zerop (TREE_OPERAND (arg1, 1))))
11161           && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
11162         return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
11163
11164       /* Fold (X ^ 1) & 1 as (X & 1) == 0.  */
11165       if (TREE_CODE (arg0) == BIT_XOR_EXPR
11166           && INTEGRAL_TYPE_P (type)
11167           && integer_onep (TREE_OPERAND (arg0, 1))
11168           && integer_onep (arg1))
11169         {
11170           tree tem2;
11171           tem = TREE_OPERAND (arg0, 0);
11172           tem2 = fold_convert_loc (loc, TREE_TYPE (tem), arg1);
11173           tem2 = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (tem),
11174                                   tem, tem2);
11175           return fold_build2_loc (loc, EQ_EXPR, type, tem2,
11176                                   build_zero_cst (TREE_TYPE (tem)));
11177         }
11178       /* Fold ~X & 1 as (X & 1) == 0.  */
11179       if (TREE_CODE (arg0) == BIT_NOT_EXPR
11180           && INTEGRAL_TYPE_P (type)
11181           && integer_onep (arg1))
11182         {
11183           tree tem2;
11184           tem = TREE_OPERAND (arg0, 0);
11185           tem2 = fold_convert_loc (loc, TREE_TYPE (tem), arg1);
11186           tem2 = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (tem),
11187                                   tem, tem2);
11188           return fold_build2_loc (loc, EQ_EXPR, type, tem2,
11189                                   build_zero_cst (TREE_TYPE (tem)));
11190         }
11191       /* Fold !X & 1 as X == 0.  */
11192       if (TREE_CODE (arg0) == TRUTH_NOT_EXPR
11193           && integer_onep (arg1))
11194         {
11195           tem = TREE_OPERAND (arg0, 0);
11196           return fold_build2_loc (loc, EQ_EXPR, type, tem,
11197                                   build_zero_cst (TREE_TYPE (tem)));
11198         }
11199
11200       /* Fold (X ^ Y) & Y as ~X & Y.  */
11201       if (TREE_CODE (arg0) == BIT_XOR_EXPR
11202           && operand_equal_p (TREE_OPERAND (arg0, 1), arg1, 0))
11203         {
11204           tem = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
11205           return fold_build2_loc (loc, BIT_AND_EXPR, type,
11206                               fold_build1_loc (loc, BIT_NOT_EXPR, type, tem),
11207                               fold_convert_loc (loc, type, arg1));
11208         }
11209       /* Fold (X ^ Y) & X as ~Y & X.  */
11210       if (TREE_CODE (arg0) == BIT_XOR_EXPR
11211           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0)
11212           && reorder_operands_p (TREE_OPERAND (arg0, 1), arg1))
11213         {
11214           tem = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 1));
11215           return fold_build2_loc (loc, BIT_AND_EXPR, type,
11216                               fold_build1_loc (loc, BIT_NOT_EXPR, type, tem),
11217                               fold_convert_loc (loc, type, arg1));
11218         }
11219       /* Fold X & (X ^ Y) as X & ~Y.  */
11220       if (TREE_CODE (arg1) == BIT_XOR_EXPR
11221           && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
11222         {
11223           tem = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 1));
11224           return fold_build2_loc (loc, BIT_AND_EXPR, type,
11225                               fold_convert_loc (loc, type, arg0),
11226                               fold_build1_loc (loc, BIT_NOT_EXPR, type, tem));
11227         }
11228       /* Fold X & (Y ^ X) as ~Y & X.  */
11229       if (TREE_CODE (arg1) == BIT_XOR_EXPR
11230           && operand_equal_p (arg0, TREE_OPERAND (arg1, 1), 0)
11231           && reorder_operands_p (arg0, TREE_OPERAND (arg1, 0)))
11232         {
11233           tem = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 0));
11234           return fold_build2_loc (loc, BIT_AND_EXPR, type,
11235                               fold_build1_loc (loc, BIT_NOT_EXPR, type, tem),
11236                               fold_convert_loc (loc, type, arg0));
11237         }
11238
11239       /* Fold (X * Y) & -(1 << CST) to X * Y if Y is a constant
11240          multiple of 1 << CST.  */
11241       if (TREE_CODE (arg1) == INTEGER_CST)
11242         {
11243           wide_int cst1 = arg1;
11244           wide_int ncst1 = -cst1;
11245           if ((cst1 & ncst1) == ncst1
11246               && multiple_of_p (type, arg0,
11247                                 wide_int_to_tree (TREE_TYPE (arg1), ncst1)))
11248             return fold_convert_loc (loc, type, arg0);
11249         }
11250
11251       /* Fold (X * CST1) & CST2 to zero if we can, or drop known zero
11252          bits from CST2.  */
11253       if (TREE_CODE (arg1) == INTEGER_CST
11254           && TREE_CODE (arg0) == MULT_EXPR
11255           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
11256         {
11257           wide_int warg1 = arg1;
11258           wide_int masked = mask_with_tz (type, warg1, TREE_OPERAND (arg0, 1));
11259
11260           if (masked == 0)
11261             return omit_two_operands_loc (loc, type, build_zero_cst (type),
11262                                           arg0, arg1);
11263           else if (masked != warg1)
11264             {
11265               /* Avoid the transform if arg1 is a mask of some
11266                  mode which allows further optimizations.  */
11267               int pop = wi::popcount (warg1);
11268               if (!(pop >= BITS_PER_UNIT
11269                     && exact_log2 (pop) != -1
11270                     && wi::mask (pop, false, warg1.get_precision ()) == warg1))
11271                 return fold_build2_loc (loc, code, type, op0,
11272                                         wide_int_to_tree (type, masked));
11273             }
11274         }
11275
11276       /* For constants M and N, if M == (1LL << cst) - 1 && (N & M) == M,
11277          ((A & N) + B) & M -> (A + B) & M
11278          Similarly if (N & M) == 0,
11279          ((A | N) + B) & M -> (A + B) & M
11280          and for - instead of + (or unary - instead of +)
11281          and/or ^ instead of |.
11282          If B is constant and (B & M) == 0, fold into A & M.  */
11283       if (TREE_CODE (arg1) == INTEGER_CST)
11284         {
11285           wide_int cst1 = arg1;
11286           if ((~cst1 != 0) && (cst1 & (cst1 + 1)) == 0
11287               && INTEGRAL_TYPE_P (TREE_TYPE (arg0))
11288               && (TREE_CODE (arg0) == PLUS_EXPR
11289                   || TREE_CODE (arg0) == MINUS_EXPR
11290                   || TREE_CODE (arg0) == NEGATE_EXPR)
11291               && (TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg0))
11292                   || TREE_CODE (TREE_TYPE (arg0)) == INTEGER_TYPE))
11293             {
11294               tree pmop[2];
11295               int which = 0;
11296               wide_int cst0;
11297
11298               /* Now we know that arg0 is (C + D) or (C - D) or
11299                  -C and arg1 (M) is == (1LL << cst) - 1.
11300                  Store C into PMOP[0] and D into PMOP[1].  */
11301               pmop[0] = TREE_OPERAND (arg0, 0);
11302               pmop[1] = NULL;
11303               if (TREE_CODE (arg0) != NEGATE_EXPR)
11304                 {
11305                   pmop[1] = TREE_OPERAND (arg0, 1);
11306                   which = 1;
11307                 }
11308
11309               if ((wi::max_value (TREE_TYPE (arg0)) & cst1) != cst1)
11310                 which = -1;
11311
11312               for (; which >= 0; which--)
11313                 switch (TREE_CODE (pmop[which]))
11314                   {
11315                   case BIT_AND_EXPR:
11316                   case BIT_IOR_EXPR:
11317                   case BIT_XOR_EXPR:
11318                     if (TREE_CODE (TREE_OPERAND (pmop[which], 1))
11319                         != INTEGER_CST)
11320                       break;
11321                     cst0 = TREE_OPERAND (pmop[which], 1);
11322                     cst0 &= cst1;
11323                     if (TREE_CODE (pmop[which]) == BIT_AND_EXPR)
11324                       {
11325                         if (cst0 != cst1)
11326                           break;
11327                       }
11328                     else if (cst0 != 0)
11329                       break;
11330                     /* If C or D is of the form (A & N) where
11331                        (N & M) == M, or of the form (A | N) or
11332                        (A ^ N) where (N & M) == 0, replace it with A.  */
11333                     pmop[which] = TREE_OPERAND (pmop[which], 0);
11334                     break;
11335                   case INTEGER_CST:
11336                     /* If C or D is a N where (N & M) == 0, it can be
11337                        omitted (assumed 0).  */
11338                     if ((TREE_CODE (arg0) == PLUS_EXPR
11339                          || (TREE_CODE (arg0) == MINUS_EXPR && which == 0))
11340                         && (cst1 & pmop[which]) == 0)
11341                       pmop[which] = NULL;
11342                     break;
11343                   default:
11344                     break;
11345                   }
11346
11347               /* Only build anything new if we optimized one or both arguments
11348                  above.  */
11349               if (pmop[0] != TREE_OPERAND (arg0, 0)
11350                   || (TREE_CODE (arg0) != NEGATE_EXPR
11351                       && pmop[1] != TREE_OPERAND (arg0, 1)))
11352                 {
11353                   tree utype = TREE_TYPE (arg0);
11354                   if (! TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg0)))
11355                     {
11356                       /* Perform the operations in a type that has defined
11357                          overflow behavior.  */
11358                       utype = unsigned_type_for (TREE_TYPE (arg0));
11359                       if (pmop[0] != NULL)
11360                         pmop[0] = fold_convert_loc (loc, utype, pmop[0]);
11361                       if (pmop[1] != NULL)
11362                         pmop[1] = fold_convert_loc (loc, utype, pmop[1]);
11363                     }
11364
11365                   if (TREE_CODE (arg0) == NEGATE_EXPR)
11366                     tem = fold_build1_loc (loc, NEGATE_EXPR, utype, pmop[0]);
11367                   else if (TREE_CODE (arg0) == PLUS_EXPR)
11368                     {
11369                       if (pmop[0] != NULL && pmop[1] != NULL)
11370                         tem = fold_build2_loc (loc, PLUS_EXPR, utype,
11371                                                pmop[0], pmop[1]);
11372                       else if (pmop[0] != NULL)
11373                         tem = pmop[0];
11374                       else if (pmop[1] != NULL)
11375                         tem = pmop[1];
11376                       else
11377                         return build_int_cst (type, 0);
11378                     }
11379                   else if (pmop[0] == NULL)
11380                     tem = fold_build1_loc (loc, NEGATE_EXPR, utype, pmop[1]);
11381                   else
11382                     tem = fold_build2_loc (loc, MINUS_EXPR, utype,
11383                                            pmop[0], pmop[1]);
11384                   /* TEM is now the new binary +, - or unary - replacement.  */
11385                   tem = fold_build2_loc (loc, BIT_AND_EXPR, utype, tem,
11386                                          fold_convert_loc (loc, utype, arg1));
11387                   return fold_convert_loc (loc, type, tem);
11388                 }
11389             }
11390         }
11391
11392       t1 = distribute_bit_expr (loc, code, type, arg0, arg1);
11393       if (t1 != NULL_TREE)
11394         return t1;
11395       /* Simplify ((int)c & 0377) into (int)c, if c is unsigned char.  */
11396       if (TREE_CODE (arg1) == INTEGER_CST && TREE_CODE (arg0) == NOP_EXPR
11397           && TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (arg0, 0))))
11398         {
11399           prec = TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (arg0, 0)));
11400
11401           wide_int mask = wide_int::from (arg1, prec, UNSIGNED);
11402           if (mask == -1)
11403             return
11404               fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
11405         }
11406
11407       /* Convert (and (not arg0) (not arg1)) to (not (or (arg0) (arg1))).
11408
11409          This results in more efficient code for machines without a NOR
11410          instruction.  Combine will canonicalize to the first form
11411          which will allow use of NOR instructions provided by the
11412          backend if they exist.  */
11413       if (TREE_CODE (arg0) == BIT_NOT_EXPR
11414           && TREE_CODE (arg1) == BIT_NOT_EXPR)
11415         {
11416           return fold_build1_loc (loc, BIT_NOT_EXPR, type,
11417                               build2 (BIT_IOR_EXPR, type,
11418                                       fold_convert_loc (loc, type,
11419                                                         TREE_OPERAND (arg0, 0)),
11420                                       fold_convert_loc (loc, type,
11421                                                         TREE_OPERAND (arg1, 0))));
11422         }
11423
11424       /* If arg0 is derived from the address of an object or function, we may
11425          be able to fold this expression using the object or function's
11426          alignment.  */
11427       if (POINTER_TYPE_P (TREE_TYPE (arg0)) && tree_fits_uhwi_p (arg1))
11428         {
11429           unsigned HOST_WIDE_INT modulus, residue;
11430           unsigned HOST_WIDE_INT low = tree_to_uhwi (arg1);
11431
11432           modulus = get_pointer_modulus_and_residue (arg0, &residue,
11433                                                      integer_onep (arg1));
11434
11435           /* This works because modulus is a power of 2.  If this weren't the
11436              case, we'd have to replace it by its greatest power-of-2
11437              divisor: modulus & -modulus.  */
11438           if (low < modulus)
11439             return build_int_cst (type, residue & low);
11440         }
11441
11442       /* Fold (X << C1) & C2 into (X << C1) & (C2 | ((1 << C1) - 1))
11443               (X >> C1) & C2 into (X >> C1) & (C2 | ~((type) -1 >> C1))
11444          if the new mask might be further optimized.  */
11445       if ((TREE_CODE (arg0) == LSHIFT_EXPR
11446            || TREE_CODE (arg0) == RSHIFT_EXPR)
11447           && TYPE_PRECISION (TREE_TYPE (arg0)) <= HOST_BITS_PER_WIDE_INT
11448           && TREE_CODE (arg1) == INTEGER_CST
11449           && tree_fits_uhwi_p (TREE_OPERAND (arg0, 1))
11450           && tree_to_uhwi (TREE_OPERAND (arg0, 1)) > 0
11451           && (tree_to_uhwi (TREE_OPERAND (arg0, 1))
11452               < TYPE_PRECISION (TREE_TYPE (arg0))))
11453         {
11454           unsigned int shiftc = tree_to_uhwi (TREE_OPERAND (arg0, 1));
11455           unsigned HOST_WIDE_INT mask = TREE_INT_CST_LOW (arg1);
11456           unsigned HOST_WIDE_INT newmask, zerobits = 0;
11457           tree shift_type = TREE_TYPE (arg0);
11458
11459           if (TREE_CODE (arg0) == LSHIFT_EXPR)
11460             zerobits = ((((unsigned HOST_WIDE_INT) 1) << shiftc) - 1);
11461           else if (TREE_CODE (arg0) == RSHIFT_EXPR
11462                    && TYPE_PRECISION (TREE_TYPE (arg0))
11463                       == GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (arg0))))
11464             {
11465               prec = TYPE_PRECISION (TREE_TYPE (arg0));
11466               tree arg00 = TREE_OPERAND (arg0, 0);
11467               /* See if more bits can be proven as zero because of
11468                  zero extension.  */
11469               if (TREE_CODE (arg00) == NOP_EXPR
11470                   && TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (arg00, 0))))
11471                 {
11472                   tree inner_type = TREE_TYPE (TREE_OPERAND (arg00, 0));
11473                   if (TYPE_PRECISION (inner_type)
11474                       == GET_MODE_PRECISION (TYPE_MODE (inner_type))
11475                       && TYPE_PRECISION (inner_type) < prec)
11476                     {
11477                       prec = TYPE_PRECISION (inner_type);
11478                       /* See if we can shorten the right shift.  */
11479                       if (shiftc < prec)
11480                         shift_type = inner_type;
11481                       /* Otherwise X >> C1 is all zeros, so we'll optimize
11482                          it into (X, 0) later on by making sure zerobits
11483                          is all ones.  */
11484                     }
11485                 }
11486               zerobits = ~(unsigned HOST_WIDE_INT) 0;
11487               if (shiftc < prec)
11488                 {
11489                   zerobits >>= HOST_BITS_PER_WIDE_INT - shiftc;
11490                   zerobits <<= prec - shiftc;
11491                 }
11492               /* For arithmetic shift if sign bit could be set, zerobits
11493                  can contain actually sign bits, so no transformation is
11494                  possible, unless MASK masks them all away.  In that
11495                  case the shift needs to be converted into logical shift.  */
11496               if (!TYPE_UNSIGNED (TREE_TYPE (arg0))
11497                   && prec == TYPE_PRECISION (TREE_TYPE (arg0)))
11498                 {
11499                   if ((mask & zerobits) == 0)
11500                     shift_type = unsigned_type_for (TREE_TYPE (arg0));
11501                   else
11502                     zerobits = 0;
11503                 }
11504             }
11505
11506           /* ((X << 16) & 0xff00) is (X, 0).  */
11507           if ((mask & zerobits) == mask)
11508             return omit_one_operand_loc (loc, type,
11509                                          build_int_cst (type, 0), arg0);
11510
11511           newmask = mask | zerobits;
11512           if (newmask != mask && (newmask & (newmask + 1)) == 0)
11513             {
11514               /* Only do the transformation if NEWMASK is some integer
11515                  mode's mask.  */
11516               for (prec = BITS_PER_UNIT;
11517                    prec < HOST_BITS_PER_WIDE_INT; prec <<= 1)
11518                 if (newmask == (((unsigned HOST_WIDE_INT) 1) << prec) - 1)
11519                   break;
11520               if (prec < HOST_BITS_PER_WIDE_INT
11521                   || newmask == ~(unsigned HOST_WIDE_INT) 0)
11522                 {
11523                   tree newmaskt;
11524
11525                   if (shift_type != TREE_TYPE (arg0))
11526                     {
11527                       tem = fold_build2_loc (loc, TREE_CODE (arg0), shift_type,
11528                                          fold_convert_loc (loc, shift_type,
11529                                                            TREE_OPERAND (arg0, 0)),
11530                                          TREE_OPERAND (arg0, 1));
11531                       tem = fold_convert_loc (loc, type, tem);
11532                     }
11533                   else
11534                     tem = op0;
11535                   newmaskt = build_int_cst_type (TREE_TYPE (op1), newmask);
11536                   if (!tree_int_cst_equal (newmaskt, arg1))
11537                     return fold_build2_loc (loc, BIT_AND_EXPR, type, tem, newmaskt);
11538                 }
11539             }
11540         }
11541
11542       goto associate;
11543
11544     case RDIV_EXPR:
11545       /* Don't touch a floating-point divide by zero unless the mode
11546          of the constant can represent infinity.  */
11547       if (TREE_CODE (arg1) == REAL_CST
11548           && !MODE_HAS_INFINITIES (TYPE_MODE (TREE_TYPE (arg1)))
11549           && real_zerop (arg1))
11550         return NULL_TREE;
11551
11552       /* Optimize A / A to 1.0 if we don't care about
11553          NaNs or Infinities.  Skip the transformation
11554          for non-real operands.  */
11555       if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (arg0))
11556           && ! HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0)))
11557           && ! HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (arg0)))
11558           && operand_equal_p (arg0, arg1, 0))
11559         {
11560           tree r = build_real (TREE_TYPE (arg0), dconst1);
11561
11562           return omit_two_operands_loc (loc, type, r, arg0, arg1);
11563         }
11564
11565       /* The complex version of the above A / A optimization.  */
11566       if (COMPLEX_FLOAT_TYPE_P (TREE_TYPE (arg0))
11567           && operand_equal_p (arg0, arg1, 0))
11568         {
11569           tree elem_type = TREE_TYPE (TREE_TYPE (arg0));
11570           if (! HONOR_NANS (TYPE_MODE (elem_type))
11571               && ! HONOR_INFINITIES (TYPE_MODE (elem_type)))
11572             {
11573               tree r = build_real (elem_type, dconst1);
11574               /* omit_two_operands will call fold_convert for us.  */
11575               return omit_two_operands_loc (loc, type, r, arg0, arg1);
11576             }
11577         }
11578
11579       /* (-A) / (-B) -> A / B  */
11580       if (TREE_CODE (arg0) == NEGATE_EXPR && negate_expr_p (arg1))
11581         return fold_build2_loc (loc, RDIV_EXPR, type,
11582                             TREE_OPERAND (arg0, 0),
11583                             negate_expr (arg1));
11584       if (TREE_CODE (arg1) == NEGATE_EXPR && negate_expr_p (arg0))
11585         return fold_build2_loc (loc, RDIV_EXPR, type,
11586                             negate_expr (arg0),
11587                             TREE_OPERAND (arg1, 0));
11588
11589       /* In IEEE floating point, x/1 is not equivalent to x for snans.  */
11590       if (!HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg0)))
11591           && real_onep (arg1))
11592         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
11593
11594       /* In IEEE floating point, x/-1 is not equivalent to -x for snans.  */
11595       if (!HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg0)))
11596           && real_minus_onep (arg1))
11597         return non_lvalue_loc (loc, fold_convert_loc (loc, type,
11598                                                   negate_expr (arg0)));
11599
11600       /* If ARG1 is a constant, we can convert this to a multiply by the
11601          reciprocal.  This does not have the same rounding properties,
11602          so only do this if -freciprocal-math.  We can actually
11603          always safely do it if ARG1 is a power of two, but it's hard to
11604          tell if it is or not in a portable manner.  */
11605       if (optimize
11606           && (TREE_CODE (arg1) == REAL_CST
11607               || (TREE_CODE (arg1) == COMPLEX_CST
11608                   && COMPLEX_FLOAT_TYPE_P (TREE_TYPE (arg1)))
11609               || (TREE_CODE (arg1) == VECTOR_CST
11610                   && VECTOR_FLOAT_TYPE_P (TREE_TYPE (arg1)))))
11611         {
11612           if (flag_reciprocal_math
11613               && 0 != (tem = const_binop (code, build_one_cst (type), arg1)))
11614             return fold_build2_loc (loc, MULT_EXPR, type, arg0, tem);
11615           /* Find the reciprocal if optimizing and the result is exact.
11616              TODO: Complex reciprocal not implemented.  */
11617           if (TREE_CODE (arg1) != COMPLEX_CST)
11618             {
11619               tree inverse = exact_inverse (TREE_TYPE (arg0), arg1);
11620
11621               if (inverse)
11622                 return fold_build2_loc (loc, MULT_EXPR, type, arg0, inverse);
11623             }
11624         }
11625       /* Convert A/B/C to A/(B*C).  */
11626       if (flag_reciprocal_math
11627           && TREE_CODE (arg0) == RDIV_EXPR)
11628         return fold_build2_loc (loc, RDIV_EXPR, type, TREE_OPERAND (arg0, 0),
11629                             fold_build2_loc (loc, MULT_EXPR, type,
11630                                          TREE_OPERAND (arg0, 1), arg1));
11631
11632       /* Convert A/(B/C) to (A/B)*C.  */
11633       if (flag_reciprocal_math
11634           && TREE_CODE (arg1) == RDIV_EXPR)
11635         return fold_build2_loc (loc, MULT_EXPR, type,
11636                             fold_build2_loc (loc, RDIV_EXPR, type, arg0,
11637                                          TREE_OPERAND (arg1, 0)),
11638                             TREE_OPERAND (arg1, 1));
11639
11640       /* Convert C1/(X*C2) into (C1/C2)/X.  */
11641       if (flag_reciprocal_math
11642           && TREE_CODE (arg1) == MULT_EXPR
11643           && TREE_CODE (arg0) == REAL_CST
11644           && TREE_CODE (TREE_OPERAND (arg1, 1)) == REAL_CST)
11645         {
11646           tree tem = const_binop (RDIV_EXPR, arg0,
11647                                   TREE_OPERAND (arg1, 1));
11648           if (tem)
11649             return fold_build2_loc (loc, RDIV_EXPR, type, tem,
11650                                 TREE_OPERAND (arg1, 0));
11651         }
11652
11653       if (flag_unsafe_math_optimizations)
11654         {
11655           enum built_in_function fcode0 = builtin_mathfn_code (arg0);
11656           enum built_in_function fcode1 = builtin_mathfn_code (arg1);
11657
11658           /* Optimize sin(x)/cos(x) as tan(x).  */
11659           if (((fcode0 == BUILT_IN_SIN && fcode1 == BUILT_IN_COS)
11660                || (fcode0 == BUILT_IN_SINF && fcode1 == BUILT_IN_COSF)
11661                || (fcode0 == BUILT_IN_SINL && fcode1 == BUILT_IN_COSL))
11662               && operand_equal_p (CALL_EXPR_ARG (arg0, 0),
11663                                   CALL_EXPR_ARG (arg1, 0), 0))
11664             {
11665               tree tanfn = mathfn_built_in (type, BUILT_IN_TAN);
11666
11667               if (tanfn != NULL_TREE)
11668                 return build_call_expr_loc (loc, tanfn, 1, CALL_EXPR_ARG (arg0, 0));
11669             }
11670
11671           /* Optimize cos(x)/sin(x) as 1.0/tan(x).  */
11672           if (((fcode0 == BUILT_IN_COS && fcode1 == BUILT_IN_SIN)
11673                || (fcode0 == BUILT_IN_COSF && fcode1 == BUILT_IN_SINF)
11674                || (fcode0 == BUILT_IN_COSL && fcode1 == BUILT_IN_SINL))
11675               && operand_equal_p (CALL_EXPR_ARG (arg0, 0),
11676                                   CALL_EXPR_ARG (arg1, 0), 0))
11677             {
11678               tree tanfn = mathfn_built_in (type, BUILT_IN_TAN);
11679
11680               if (tanfn != NULL_TREE)
11681                 {
11682                   tree tmp = build_call_expr_loc (loc, tanfn, 1,
11683                                               CALL_EXPR_ARG (arg0, 0));
11684                   return fold_build2_loc (loc, RDIV_EXPR, type,
11685                                       build_real (type, dconst1), tmp);
11686                 }
11687             }
11688
11689           /* Optimize sin(x)/tan(x) as cos(x) if we don't care about
11690              NaNs or Infinities.  */
11691           if (((fcode0 == BUILT_IN_SIN && fcode1 == BUILT_IN_TAN)
11692                || (fcode0 == BUILT_IN_SINF && fcode1 == BUILT_IN_TANF)
11693                || (fcode0 == BUILT_IN_SINL && fcode1 == BUILT_IN_TANL)))
11694             {
11695               tree arg00 = CALL_EXPR_ARG (arg0, 0);
11696               tree arg01 = CALL_EXPR_ARG (arg1, 0);
11697
11698               if (! HONOR_NANS (TYPE_MODE (TREE_TYPE (arg00)))
11699                   && ! HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (arg00)))
11700                   && operand_equal_p (arg00, arg01, 0))
11701                 {
11702                   tree cosfn = mathfn_built_in (type, BUILT_IN_COS);
11703
11704                   if (cosfn != NULL_TREE)
11705                     return build_call_expr_loc (loc, cosfn, 1, arg00);
11706                 }
11707             }
11708
11709           /* Optimize tan(x)/sin(x) as 1.0/cos(x) if we don't care about
11710              NaNs or Infinities.  */
11711           if (((fcode0 == BUILT_IN_TAN && fcode1 == BUILT_IN_SIN)
11712                || (fcode0 == BUILT_IN_TANF && fcode1 == BUILT_IN_SINF)
11713                || (fcode0 == BUILT_IN_TANL && fcode1 == BUILT_IN_SINL)))
11714             {
11715               tree arg00 = CALL_EXPR_ARG (arg0, 0);
11716               tree arg01 = CALL_EXPR_ARG (arg1, 0);
11717
11718               if (! HONOR_NANS (TYPE_MODE (TREE_TYPE (arg00)))
11719                   && ! HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (arg00)))
11720                   && operand_equal_p (arg00, arg01, 0))
11721                 {
11722                   tree cosfn = mathfn_built_in (type, BUILT_IN_COS);
11723
11724                   if (cosfn != NULL_TREE)
11725                     {
11726                       tree tmp = build_call_expr_loc (loc, cosfn, 1, arg00);
11727                       return fold_build2_loc (loc, RDIV_EXPR, type,
11728                                           build_real (type, dconst1),
11729                                           tmp);
11730                     }
11731                 }
11732             }
11733
11734           /* Optimize pow(x,c)/x as pow(x,c-1).  */
11735           if (fcode0 == BUILT_IN_POW
11736               || fcode0 == BUILT_IN_POWF
11737               || fcode0 == BUILT_IN_POWL)
11738             {
11739               tree arg00 = CALL_EXPR_ARG (arg0, 0);
11740               tree arg01 = CALL_EXPR_ARG (arg0, 1);
11741               if (TREE_CODE (arg01) == REAL_CST
11742                   && !TREE_OVERFLOW (arg01)
11743                   && operand_equal_p (arg1, arg00, 0))
11744                 {
11745                   tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg0), 0);
11746                   REAL_VALUE_TYPE c;
11747                   tree arg;
11748
11749                   c = TREE_REAL_CST (arg01);
11750                   real_arithmetic (&c, MINUS_EXPR, &c, &dconst1);
11751                   arg = build_real (type, c);
11752                   return build_call_expr_loc (loc, powfn, 2, arg1, arg);
11753                 }
11754             }
11755
11756           /* Optimize a/root(b/c) into a*root(c/b).  */
11757           if (BUILTIN_ROOT_P (fcode1))
11758             {
11759               tree rootarg = CALL_EXPR_ARG (arg1, 0);
11760
11761               if (TREE_CODE (rootarg) == RDIV_EXPR)
11762                 {
11763                   tree rootfn = TREE_OPERAND (CALL_EXPR_FN (arg1), 0);
11764                   tree b = TREE_OPERAND (rootarg, 0);
11765                   tree c = TREE_OPERAND (rootarg, 1);
11766
11767                   tree tmp = fold_build2_loc (loc, RDIV_EXPR, type, c, b);
11768
11769                   tmp = build_call_expr_loc (loc, rootfn, 1, tmp);
11770                   return fold_build2_loc (loc, MULT_EXPR, type, arg0, tmp);
11771                 }
11772             }
11773
11774           /* Optimize x/expN(y) into x*expN(-y).  */
11775           if (BUILTIN_EXPONENT_P (fcode1))
11776             {
11777               tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg1), 0);
11778               tree arg = negate_expr (CALL_EXPR_ARG (arg1, 0));
11779               arg1 = build_call_expr_loc (loc,
11780                                       expfn, 1,
11781                                       fold_convert_loc (loc, type, arg));
11782               return fold_build2_loc (loc, MULT_EXPR, type, arg0, arg1);
11783             }
11784
11785           /* Optimize x/pow(y,z) into x*pow(y,-z).  */
11786           if (fcode1 == BUILT_IN_POW
11787               || fcode1 == BUILT_IN_POWF
11788               || fcode1 == BUILT_IN_POWL)
11789             {
11790               tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg1), 0);
11791               tree arg10 = CALL_EXPR_ARG (arg1, 0);
11792               tree arg11 = CALL_EXPR_ARG (arg1, 1);
11793               tree neg11 = fold_convert_loc (loc, type,
11794                                              negate_expr (arg11));
11795               arg1 = build_call_expr_loc (loc, powfn, 2, arg10, neg11);
11796               return fold_build2_loc (loc, MULT_EXPR, type, arg0, arg1);
11797             }
11798         }
11799       return NULL_TREE;
11800
11801     case TRUNC_DIV_EXPR:
11802       /* Optimize (X & (-A)) / A where A is a power of 2,
11803          to X >> log2(A) */
11804       if (TREE_CODE (arg0) == BIT_AND_EXPR
11805           && !TYPE_UNSIGNED (type) && TREE_CODE (arg1) == INTEGER_CST
11806           && integer_pow2p (arg1) && tree_int_cst_sgn (arg1) > 0)
11807         {
11808           tree sum = fold_binary_loc (loc, PLUS_EXPR, TREE_TYPE (arg1),
11809                                       arg1, TREE_OPERAND (arg0, 1));
11810           if (sum && integer_zerop (sum)) {
11811             tree pow2 = build_int_cst (integer_type_node,
11812                                        wi::exact_log2 (arg1));
11813             return fold_build2_loc (loc, RSHIFT_EXPR, type,
11814                                     TREE_OPERAND (arg0, 0), pow2);
11815           }
11816         }
11817
11818       /* Fall through */
11819       
11820     case FLOOR_DIV_EXPR:
11821       /* Simplify A / (B << N) where A and B are positive and B is
11822          a power of 2, to A >> (N + log2(B)).  */
11823       strict_overflow_p = false;
11824       if (TREE_CODE (arg1) == LSHIFT_EXPR
11825           && (TYPE_UNSIGNED (type)
11826               || tree_expr_nonnegative_warnv_p (op0, &strict_overflow_p)))
11827         {
11828           tree sval = TREE_OPERAND (arg1, 0);
11829           if (integer_pow2p (sval) && tree_int_cst_sgn (sval) > 0)
11830             {
11831               tree sh_cnt = TREE_OPERAND (arg1, 1);
11832               tree pow2 = build_int_cst (TREE_TYPE (sh_cnt),
11833                                          wi::exact_log2 (sval));
11834
11835               if (strict_overflow_p)
11836                 fold_overflow_warning (("assuming signed overflow does not "
11837                                         "occur when simplifying A / (B << N)"),
11838                                        WARN_STRICT_OVERFLOW_MISC);
11839
11840               sh_cnt = fold_build2_loc (loc, PLUS_EXPR, TREE_TYPE (sh_cnt),
11841                                         sh_cnt, pow2);
11842               return fold_build2_loc (loc, RSHIFT_EXPR, type,
11843                                       fold_convert_loc (loc, type, arg0), sh_cnt);
11844             }
11845         }
11846
11847       /* For unsigned integral types, FLOOR_DIV_EXPR is the same as
11848          TRUNC_DIV_EXPR.  Rewrite into the latter in this case.  */
11849       if (INTEGRAL_TYPE_P (type)
11850           && TYPE_UNSIGNED (type)
11851           && code == FLOOR_DIV_EXPR)
11852         return fold_build2_loc (loc, TRUNC_DIV_EXPR, type, op0, op1);
11853
11854       /* Fall through */
11855
11856     case ROUND_DIV_EXPR:
11857     case CEIL_DIV_EXPR:
11858     case EXACT_DIV_EXPR:
11859       if (integer_zerop (arg1))
11860         return NULL_TREE;
11861       /* X / -1 is -X.  */
11862       if (!TYPE_UNSIGNED (type)
11863           && TREE_CODE (arg1) == INTEGER_CST
11864           && wi::eq_p (arg1, -1))
11865         return fold_convert_loc (loc, type, negate_expr (arg0));
11866
11867       /* Convert -A / -B to A / B when the type is signed and overflow is
11868          undefined.  */
11869       if ((!INTEGRAL_TYPE_P (type) || TYPE_OVERFLOW_UNDEFINED (type))
11870           && TREE_CODE (arg0) == NEGATE_EXPR
11871           && negate_expr_p (arg1))
11872         {
11873           if (INTEGRAL_TYPE_P (type))
11874             fold_overflow_warning (("assuming signed overflow does not occur "
11875                                     "when distributing negation across "
11876                                     "division"),
11877                                    WARN_STRICT_OVERFLOW_MISC);
11878           return fold_build2_loc (loc, code, type,
11879                               fold_convert_loc (loc, type,
11880                                                 TREE_OPERAND (arg0, 0)),
11881                               fold_convert_loc (loc, type,
11882                                                 negate_expr (arg1)));
11883         }
11884       if ((!INTEGRAL_TYPE_P (type) || TYPE_OVERFLOW_UNDEFINED (type))
11885           && TREE_CODE (arg1) == NEGATE_EXPR
11886           && negate_expr_p (arg0))
11887         {
11888           if (INTEGRAL_TYPE_P (type))
11889             fold_overflow_warning (("assuming signed overflow does not occur "
11890                                     "when distributing negation across "
11891                                     "division"),
11892                                    WARN_STRICT_OVERFLOW_MISC);
11893           return fold_build2_loc (loc, code, type,
11894                               fold_convert_loc (loc, type,
11895                                                 negate_expr (arg0)),
11896                               fold_convert_loc (loc, type,
11897                                                 TREE_OPERAND (arg1, 0)));
11898         }
11899
11900       /* If arg0 is a multiple of arg1, then rewrite to the fastest div
11901          operation, EXACT_DIV_EXPR.
11902
11903          Note that only CEIL_DIV_EXPR and FLOOR_DIV_EXPR are rewritten now.
11904          At one time others generated faster code, it's not clear if they do
11905          after the last round to changes to the DIV code in expmed.c.  */
11906       if ((code == CEIL_DIV_EXPR || code == FLOOR_DIV_EXPR)
11907           && multiple_of_p (type, arg0, arg1))
11908         return fold_build2_loc (loc, EXACT_DIV_EXPR, type, arg0, arg1);
11909
11910       strict_overflow_p = false;
11911       if (TREE_CODE (arg1) == INTEGER_CST
11912           && 0 != (tem = extract_muldiv (op0, arg1, code, NULL_TREE,
11913                                          &strict_overflow_p)))
11914         {
11915           if (strict_overflow_p)
11916             fold_overflow_warning (("assuming signed overflow does not occur "
11917                                     "when simplifying division"),
11918                                    WARN_STRICT_OVERFLOW_MISC);
11919           return fold_convert_loc (loc, type, tem);
11920         }
11921
11922       return NULL_TREE;
11923
11924     case CEIL_MOD_EXPR:
11925     case FLOOR_MOD_EXPR:
11926     case ROUND_MOD_EXPR:
11927     case TRUNC_MOD_EXPR:
11928       /* X % -1 is zero.  */
11929       if (!TYPE_UNSIGNED (type)
11930           && TREE_CODE (arg1) == INTEGER_CST
11931           && wi::eq_p (arg1, -1))
11932         return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
11933
11934       /* X % -C is the same as X % C.  */
11935       if (code == TRUNC_MOD_EXPR
11936           && TYPE_SIGN (type) == SIGNED
11937           && TREE_CODE (arg1) == INTEGER_CST
11938           && !TREE_OVERFLOW (arg1)
11939           && wi::neg_p (arg1)
11940           && !TYPE_OVERFLOW_TRAPS (type)
11941           /* Avoid this transformation if C is INT_MIN, i.e. C == -C.  */
11942           && !sign_bit_p (arg1, arg1))
11943         return fold_build2_loc (loc, code, type,
11944                             fold_convert_loc (loc, type, arg0),
11945                             fold_convert_loc (loc, type,
11946                                               negate_expr (arg1)));
11947
11948       /* X % -Y is the same as X % Y.  */
11949       if (code == TRUNC_MOD_EXPR
11950           && !TYPE_UNSIGNED (type)
11951           && TREE_CODE (arg1) == NEGATE_EXPR
11952           && !TYPE_OVERFLOW_TRAPS (type))
11953         return fold_build2_loc (loc, code, type, fold_convert_loc (loc, type, arg0),
11954                             fold_convert_loc (loc, type,
11955                                               TREE_OPERAND (arg1, 0)));
11956
11957       strict_overflow_p = false;
11958       if (TREE_CODE (arg1) == INTEGER_CST
11959           && 0 != (tem = extract_muldiv (op0, arg1, code, NULL_TREE,
11960                                          &strict_overflow_p)))
11961         {
11962           if (strict_overflow_p)
11963             fold_overflow_warning (("assuming signed overflow does not occur "
11964                                     "when simplifying modulus"),
11965                                    WARN_STRICT_OVERFLOW_MISC);
11966           return fold_convert_loc (loc, type, tem);
11967         }
11968
11969       /* Optimize TRUNC_MOD_EXPR by a power of two into a BIT_AND_EXPR,
11970          i.e. "X % C" into "X & (C - 1)", if X and C are positive.  */
11971       if ((code == TRUNC_MOD_EXPR || code == FLOOR_MOD_EXPR)
11972           && (TYPE_UNSIGNED (type)
11973               || tree_expr_nonnegative_warnv_p (op0, &strict_overflow_p)))
11974         {
11975           tree c = arg1;
11976           /* Also optimize A % (C << N)  where C is a power of 2,
11977              to A & ((C << N) - 1).  */
11978           if (TREE_CODE (arg1) == LSHIFT_EXPR)
11979             c = TREE_OPERAND (arg1, 0);
11980
11981           if (integer_pow2p (c) && tree_int_cst_sgn (c) > 0)
11982             {
11983               tree mask
11984                 = fold_build2_loc (loc, MINUS_EXPR, TREE_TYPE (arg1), arg1,
11985                                    build_int_cst (TREE_TYPE (arg1), 1));
11986               if (strict_overflow_p)
11987                 fold_overflow_warning (("assuming signed overflow does not "
11988                                         "occur when simplifying "
11989                                         "X % (power of two)"),
11990                                        WARN_STRICT_OVERFLOW_MISC);
11991               return fold_build2_loc (loc, BIT_AND_EXPR, type,
11992                                       fold_convert_loc (loc, type, arg0),
11993                                       fold_convert_loc (loc, type, mask));
11994             }
11995         }
11996
11997       return NULL_TREE;
11998
11999     case LROTATE_EXPR:
12000     case RROTATE_EXPR:
12001       if (integer_all_onesp (arg0))
12002         return omit_one_operand_loc (loc, type, arg0, arg1);
12003       goto shift;
12004
12005     case RSHIFT_EXPR:
12006       /* Optimize -1 >> x for arithmetic right shifts.  */
12007       if (integer_all_onesp (arg0) && !TYPE_UNSIGNED (type)
12008           && tree_expr_nonnegative_p (arg1))
12009         return omit_one_operand_loc (loc, type, arg0, arg1);
12010       /* ... fall through ...  */
12011
12012     case LSHIFT_EXPR:
12013     shift:
12014       if (integer_zerop (arg1))
12015         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
12016       if (integer_zerop (arg0))
12017         return omit_one_operand_loc (loc, type, arg0, arg1);
12018
12019       /* Prefer vector1 << scalar to vector1 << vector2
12020          if vector2 is uniform.  */
12021       if (VECTOR_TYPE_P (TREE_TYPE (arg1))
12022           && (tem = uniform_vector_p (arg1)) != NULL_TREE)
12023         return fold_build2_loc (loc, code, type, op0, tem);
12024
12025       /* Since negative shift count is not well-defined,
12026          don't try to compute it in the compiler.  */
12027       if (TREE_CODE (arg1) == INTEGER_CST && tree_int_cst_sgn (arg1) < 0)
12028         return NULL_TREE;
12029
12030       prec = element_precision (type);
12031
12032       /* Turn (a OP c1) OP c2 into a OP (c1+c2).  */
12033       if (TREE_CODE (op0) == code && tree_fits_uhwi_p (arg1)
12034           && tree_to_uhwi (arg1) < prec
12035           && tree_fits_uhwi_p (TREE_OPERAND (arg0, 1))
12036           && tree_to_uhwi (TREE_OPERAND (arg0, 1)) < prec)
12037         {
12038           unsigned int low = (tree_to_uhwi (TREE_OPERAND (arg0, 1))
12039                               + tree_to_uhwi (arg1));
12040
12041           /* Deal with a OP (c1 + c2) being undefined but (a OP c1) OP c2
12042              being well defined.  */
12043           if (low >= prec)
12044             {
12045               if (code == LROTATE_EXPR || code == RROTATE_EXPR)
12046                 low = low % prec;
12047               else if (TYPE_UNSIGNED (type) || code == LSHIFT_EXPR)
12048                 return omit_one_operand_loc (loc, type, build_zero_cst (type),
12049                                          TREE_OPERAND (arg0, 0));
12050               else
12051                 low = prec - 1;
12052             }
12053
12054           return fold_build2_loc (loc, code, type, TREE_OPERAND (arg0, 0),
12055                                   build_int_cst (TREE_TYPE (arg1), low));
12056         }
12057
12058       /* Transform (x >> c) << c into x & (-1<<c), or transform (x << c) >> c
12059          into x & ((unsigned)-1 >> c) for unsigned types.  */
12060       if (((code == LSHIFT_EXPR && TREE_CODE (arg0) == RSHIFT_EXPR)
12061            || (TYPE_UNSIGNED (type)
12062                && code == RSHIFT_EXPR && TREE_CODE (arg0) == LSHIFT_EXPR))
12063           && tree_fits_uhwi_p (arg1)
12064           && tree_to_uhwi (arg1) < prec
12065           && tree_fits_uhwi_p (TREE_OPERAND (arg0, 1))
12066           && tree_to_uhwi (TREE_OPERAND (arg0, 1)) < prec)
12067         {
12068           HOST_WIDE_INT low0 = tree_to_uhwi (TREE_OPERAND (arg0, 1));
12069           HOST_WIDE_INT low1 = tree_to_uhwi (arg1);
12070           tree lshift;
12071           tree arg00;
12072
12073           if (low0 == low1)
12074             {
12075               arg00 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
12076
12077               lshift = build_minus_one_cst (type);
12078               lshift = const_binop (code, lshift, arg1);
12079
12080               return fold_build2_loc (loc, BIT_AND_EXPR, type, arg00, lshift);
12081             }
12082         }
12083
12084       /* Rewrite an LROTATE_EXPR by a constant into an
12085          RROTATE_EXPR by a new constant.  */
12086       if (code == LROTATE_EXPR && TREE_CODE (arg1) == INTEGER_CST)
12087         {
12088           tree tem = build_int_cst (TREE_TYPE (arg1), prec);
12089           tem = const_binop (MINUS_EXPR, tem, arg1);
12090           return fold_build2_loc (loc, RROTATE_EXPR, type, op0, tem);
12091         }
12092
12093       /* If we have a rotate of a bit operation with the rotate count and
12094          the second operand of the bit operation both constant,
12095          permute the two operations.  */
12096       if (code == RROTATE_EXPR && TREE_CODE (arg1) == INTEGER_CST
12097           && (TREE_CODE (arg0) == BIT_AND_EXPR
12098               || TREE_CODE (arg0) == BIT_IOR_EXPR
12099               || TREE_CODE (arg0) == BIT_XOR_EXPR)
12100           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
12101         return fold_build2_loc (loc, TREE_CODE (arg0), type,
12102                             fold_build2_loc (loc, code, type,
12103                                          TREE_OPERAND (arg0, 0), arg1),
12104                             fold_build2_loc (loc, code, type,
12105                                          TREE_OPERAND (arg0, 1), arg1));
12106
12107       /* Two consecutive rotates adding up to the some integer
12108          multiple of the precision of the type can be ignored.  */
12109       if (code == RROTATE_EXPR && TREE_CODE (arg1) == INTEGER_CST
12110           && TREE_CODE (arg0) == RROTATE_EXPR
12111           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
12112           && wi::umod_trunc (wi::add (arg1, TREE_OPERAND (arg0, 1)),
12113                              prec) == 0)
12114         return TREE_OPERAND (arg0, 0);
12115
12116       /* Fold (X & C2) << C1 into (X << C1) & (C2 << C1)
12117               (X & C2) >> C1 into (X >> C1) & (C2 >> C1)
12118          if the latter can be further optimized.  */
12119       if ((code == LSHIFT_EXPR || code == RSHIFT_EXPR)
12120           && TREE_CODE (arg0) == BIT_AND_EXPR
12121           && TREE_CODE (arg1) == INTEGER_CST
12122           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
12123         {
12124           tree mask = fold_build2_loc (loc, code, type,
12125                                    fold_convert_loc (loc, type,
12126                                                      TREE_OPERAND (arg0, 1)),
12127                                    arg1);
12128           tree shift = fold_build2_loc (loc, code, type,
12129                                     fold_convert_loc (loc, type,
12130                                                       TREE_OPERAND (arg0, 0)),
12131                                     arg1);
12132           tem = fold_binary_loc (loc, BIT_AND_EXPR, type, shift, mask);
12133           if (tem)
12134             return tem;
12135         }
12136
12137       return NULL_TREE;
12138
12139     case MIN_EXPR:
12140       if (operand_equal_p (arg0, arg1, 0))
12141         return omit_one_operand_loc (loc, type, arg0, arg1);
12142       if (INTEGRAL_TYPE_P (type)
12143           && operand_equal_p (arg1, TYPE_MIN_VALUE (type), OEP_ONLY_CONST))
12144         return omit_one_operand_loc (loc, type, arg1, arg0);
12145       tem = fold_minmax (loc, MIN_EXPR, type, arg0, arg1);
12146       if (tem)
12147         return tem;
12148       goto associate;
12149
12150     case MAX_EXPR:
12151       if (operand_equal_p (arg0, arg1, 0))
12152         return omit_one_operand_loc (loc, type, arg0, arg1);
12153       if (INTEGRAL_TYPE_P (type)
12154           && TYPE_MAX_VALUE (type)
12155           && operand_equal_p (arg1, TYPE_MAX_VALUE (type), OEP_ONLY_CONST))
12156         return omit_one_operand_loc (loc, type, arg1, arg0);
12157       tem = fold_minmax (loc, MAX_EXPR, type, arg0, arg1);
12158       if (tem)
12159         return tem;
12160       goto associate;
12161
12162     case TRUTH_ANDIF_EXPR:
12163       /* Note that the operands of this must be ints
12164          and their values must be 0 or 1.
12165          ("true" is a fixed value perhaps depending on the language.)  */
12166       /* If first arg is constant zero, return it.  */
12167       if (integer_zerop (arg0))
12168         return fold_convert_loc (loc, type, arg0);
12169     case TRUTH_AND_EXPR:
12170       /* If either arg is constant true, drop it.  */
12171       if (TREE_CODE (arg0) == INTEGER_CST && ! integer_zerop (arg0))
12172         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg1));
12173       if (TREE_CODE (arg1) == INTEGER_CST && ! integer_zerop (arg1)
12174           /* Preserve sequence points.  */
12175           && (code != TRUTH_ANDIF_EXPR || ! TREE_SIDE_EFFECTS (arg0)))
12176         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
12177       /* If second arg is constant zero, result is zero, but first arg
12178          must be evaluated.  */
12179       if (integer_zerop (arg1))
12180         return omit_one_operand_loc (loc, type, arg1, arg0);
12181       /* Likewise for first arg, but note that only the TRUTH_AND_EXPR
12182          case will be handled here.  */
12183       if (integer_zerop (arg0))
12184         return omit_one_operand_loc (loc, type, arg0, arg1);
12185
12186       /* !X && X is always false.  */
12187       if (TREE_CODE (arg0) == TRUTH_NOT_EXPR
12188           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
12189         return omit_one_operand_loc (loc, type, integer_zero_node, arg1);
12190       /* X && !X is always false.  */
12191       if (TREE_CODE (arg1) == TRUTH_NOT_EXPR
12192           && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
12193         return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
12194
12195       /* A < X && A + 1 > Y ==> A < X && A >= Y.  Normally A + 1 > Y
12196          means A >= Y && A != MAX, but in this case we know that
12197          A < X <= MAX.  */
12198
12199       if (!TREE_SIDE_EFFECTS (arg0)
12200           && !TREE_SIDE_EFFECTS (arg1))
12201         {
12202           tem = fold_to_nonsharp_ineq_using_bound (loc, arg0, arg1);
12203           if (tem && !operand_equal_p (tem, arg0, 0))
12204             return fold_build2_loc (loc, code, type, tem, arg1);
12205
12206           tem = fold_to_nonsharp_ineq_using_bound (loc, arg1, arg0);
12207           if (tem && !operand_equal_p (tem, arg1, 0))
12208             return fold_build2_loc (loc, code, type, arg0, tem);
12209         }
12210
12211       if ((tem = fold_truth_andor (loc, code, type, arg0, arg1, op0, op1))
12212           != NULL_TREE)
12213         return tem;
12214
12215       return NULL_TREE;
12216
12217     case TRUTH_ORIF_EXPR:
12218       /* Note that the operands of this must be ints
12219          and their values must be 0 or true.
12220          ("true" is a fixed value perhaps depending on the language.)  */
12221       /* If first arg is constant true, return it.  */
12222       if (TREE_CODE (arg0) == INTEGER_CST && ! integer_zerop (arg0))
12223         return fold_convert_loc (loc, type, arg0);
12224     case TRUTH_OR_EXPR:
12225       /* If either arg is constant zero, drop it.  */
12226       if (TREE_CODE (arg0) == INTEGER_CST && integer_zerop (arg0))
12227         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg1));
12228       if (TREE_CODE (arg1) == INTEGER_CST && integer_zerop (arg1)
12229           /* Preserve sequence points.  */
12230           && (code != TRUTH_ORIF_EXPR || ! TREE_SIDE_EFFECTS (arg0)))
12231         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
12232       /* If second arg is constant true, result is true, but we must
12233          evaluate first arg.  */
12234       if (TREE_CODE (arg1) == INTEGER_CST && ! integer_zerop (arg1))
12235         return omit_one_operand_loc (loc, type, arg1, arg0);
12236       /* Likewise for first arg, but note this only occurs here for
12237          TRUTH_OR_EXPR.  */
12238       if (TREE_CODE (arg0) == INTEGER_CST && ! integer_zerop (arg0))
12239         return omit_one_operand_loc (loc, type, arg0, arg1);
12240
12241       /* !X || X is always true.  */
12242       if (TREE_CODE (arg0) == TRUTH_NOT_EXPR
12243           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
12244         return omit_one_operand_loc (loc, type, integer_one_node, arg1);
12245       /* X || !X is always true.  */
12246       if (TREE_CODE (arg1) == TRUTH_NOT_EXPR
12247           && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
12248         return omit_one_operand_loc (loc, type, integer_one_node, arg0);
12249
12250       /* (X && !Y) || (!X && Y) is X ^ Y */
12251       if (TREE_CODE (arg0) == TRUTH_AND_EXPR
12252           && TREE_CODE (arg1) == TRUTH_AND_EXPR)
12253         {
12254           tree a0, a1, l0, l1, n0, n1;
12255
12256           a0 = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 0));
12257           a1 = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 1));
12258
12259           l0 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
12260           l1 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 1));
12261           
12262           n0 = fold_build1_loc (loc, TRUTH_NOT_EXPR, type, l0);
12263           n1 = fold_build1_loc (loc, TRUTH_NOT_EXPR, type, l1);
12264           
12265           if ((operand_equal_p (n0, a0, 0)
12266                && operand_equal_p (n1, a1, 0))
12267               || (operand_equal_p (n0, a1, 0)
12268                   && operand_equal_p (n1, a0, 0)))
12269             return fold_build2_loc (loc, TRUTH_XOR_EXPR, type, l0, n1);
12270         }
12271
12272       if ((tem = fold_truth_andor (loc, code, type, arg0, arg1, op0, op1))
12273           != NULL_TREE)
12274         return tem;
12275
12276       return NULL_TREE;
12277
12278     case TRUTH_XOR_EXPR:
12279       /* If the second arg is constant zero, drop it.  */
12280       if (integer_zerop (arg1))
12281         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
12282       /* If the second arg is constant true, this is a logical inversion.  */
12283       if (integer_onep (arg1))
12284         {
12285           tem = invert_truthvalue_loc (loc, arg0);
12286           return non_lvalue_loc (loc, fold_convert_loc (loc, type, tem));
12287         }
12288       /* Identical arguments cancel to zero.  */
12289       if (operand_equal_p (arg0, arg1, 0))
12290         return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
12291
12292       /* !X ^ X is always true.  */
12293       if (TREE_CODE (arg0) == TRUTH_NOT_EXPR
12294           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
12295         return omit_one_operand_loc (loc, type, integer_one_node, arg1);
12296
12297       /* X ^ !X is always true.  */
12298       if (TREE_CODE (arg1) == TRUTH_NOT_EXPR
12299           && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
12300         return omit_one_operand_loc (loc, type, integer_one_node, arg0);
12301
12302       return NULL_TREE;
12303
12304     case EQ_EXPR:
12305     case NE_EXPR:
12306       STRIP_NOPS (arg0);
12307       STRIP_NOPS (arg1);
12308
12309       tem = fold_comparison (loc, code, type, op0, op1);
12310       if (tem != NULL_TREE)
12311         return tem;
12312
12313       /* bool_var != 0 becomes bool_var. */
12314       if (TREE_CODE (TREE_TYPE (arg0)) == BOOLEAN_TYPE && integer_zerop (arg1)
12315           && code == NE_EXPR)
12316         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
12317
12318       /* bool_var == 1 becomes bool_var. */
12319       if (TREE_CODE (TREE_TYPE (arg0)) == BOOLEAN_TYPE && integer_onep (arg1)
12320           && code == EQ_EXPR)
12321         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
12322
12323       /* bool_var != 1 becomes !bool_var. */
12324       if (TREE_CODE (TREE_TYPE (arg0)) == BOOLEAN_TYPE && integer_onep (arg1)
12325           && code == NE_EXPR)
12326         return fold_convert_loc (loc, type,
12327                                  fold_build1_loc (loc, TRUTH_NOT_EXPR,
12328                                                   TREE_TYPE (arg0), arg0));
12329
12330       /* bool_var == 0 becomes !bool_var. */
12331       if (TREE_CODE (TREE_TYPE (arg0)) == BOOLEAN_TYPE && integer_zerop (arg1)
12332           && code == EQ_EXPR)
12333         return fold_convert_loc (loc, type,
12334                                  fold_build1_loc (loc, TRUTH_NOT_EXPR,
12335                                                   TREE_TYPE (arg0), arg0));
12336
12337       /* !exp != 0 becomes !exp */
12338       if (TREE_CODE (arg0) == TRUTH_NOT_EXPR && integer_zerop (arg1)
12339           && code == NE_EXPR)
12340         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
12341
12342       /* If this is an equality comparison of the address of two non-weak,
12343          unaliased symbols neither of which are extern (since we do not
12344          have access to attributes for externs), then we know the result.  */
12345       if (TREE_CODE (arg0) == ADDR_EXPR
12346           && VAR_OR_FUNCTION_DECL_P (TREE_OPERAND (arg0, 0))
12347           && ! DECL_WEAK (TREE_OPERAND (arg0, 0))
12348           && ! lookup_attribute ("alias",
12349                                  DECL_ATTRIBUTES (TREE_OPERAND (arg0, 0)))
12350           && ! DECL_EXTERNAL (TREE_OPERAND (arg0, 0))
12351           && TREE_CODE (arg1) == ADDR_EXPR
12352           && VAR_OR_FUNCTION_DECL_P (TREE_OPERAND (arg1, 0))
12353           && ! DECL_WEAK (TREE_OPERAND (arg1, 0))
12354           && ! lookup_attribute ("alias",
12355                                  DECL_ATTRIBUTES (TREE_OPERAND (arg1, 0)))
12356           && ! DECL_EXTERNAL (TREE_OPERAND (arg1, 0)))
12357         {
12358           /* We know that we're looking at the address of two
12359              non-weak, unaliased, static _DECL nodes.
12360
12361              It is both wasteful and incorrect to call operand_equal_p
12362              to compare the two ADDR_EXPR nodes.  It is wasteful in that
12363              all we need to do is test pointer equality for the arguments
12364              to the two ADDR_EXPR nodes.  It is incorrect to use
12365              operand_equal_p as that function is NOT equivalent to a
12366              C equality test.  It can in fact return false for two
12367              objects which would test as equal using the C equality
12368              operator.  */
12369           bool equal = TREE_OPERAND (arg0, 0) == TREE_OPERAND (arg1, 0);
12370           return constant_boolean_node (equal
12371                                         ? code == EQ_EXPR : code != EQ_EXPR,
12372                                         type);
12373         }
12374
12375       /* Similarly for a NEGATE_EXPR.  */
12376       if (TREE_CODE (arg0) == NEGATE_EXPR
12377           && TREE_CODE (arg1) == INTEGER_CST
12378           && 0 != (tem = negate_expr (fold_convert_loc (loc, TREE_TYPE (arg0),
12379                                                         arg1)))
12380           && TREE_CODE (tem) == INTEGER_CST
12381           && !TREE_OVERFLOW (tem))
12382         return fold_build2_loc (loc, code, type, TREE_OPERAND (arg0, 0), tem);
12383
12384       /* Similarly for a BIT_XOR_EXPR;  X ^ C1 == C2 is X == (C1 ^ C2).  */
12385       if (TREE_CODE (arg0) == BIT_XOR_EXPR
12386           && TREE_CODE (arg1) == INTEGER_CST
12387           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
12388         return fold_build2_loc (loc, code, type, TREE_OPERAND (arg0, 0),
12389                             fold_build2_loc (loc, BIT_XOR_EXPR, TREE_TYPE (arg0),
12390                                          fold_convert_loc (loc,
12391                                                            TREE_TYPE (arg0),
12392                                                            arg1),
12393                                          TREE_OPERAND (arg0, 1)));
12394
12395       /* Transform comparisons of the form X +- Y CMP X to Y CMP 0.  */
12396       if ((TREE_CODE (arg0) == PLUS_EXPR
12397            || TREE_CODE (arg0) == POINTER_PLUS_EXPR
12398            || TREE_CODE (arg0) == MINUS_EXPR)
12399           && operand_equal_p (tree_strip_nop_conversions (TREE_OPERAND (arg0,
12400                                                                         0)),
12401                               arg1, 0)
12402           && (INTEGRAL_TYPE_P (TREE_TYPE (arg0))
12403               || POINTER_TYPE_P (TREE_TYPE (arg0))))
12404         {
12405           tree val = TREE_OPERAND (arg0, 1);
12406           return omit_two_operands_loc (loc, type,
12407                                     fold_build2_loc (loc, code, type,
12408                                                  val,
12409                                                  build_int_cst (TREE_TYPE (val),
12410                                                                 0)),
12411                                     TREE_OPERAND (arg0, 0), arg1);
12412         }
12413
12414       /* Transform comparisons of the form C - X CMP X if C % 2 == 1.  */
12415       if (TREE_CODE (arg0) == MINUS_EXPR
12416           && TREE_CODE (TREE_OPERAND (arg0, 0)) == INTEGER_CST
12417           && operand_equal_p (tree_strip_nop_conversions (TREE_OPERAND (arg0,
12418                                                                         1)),
12419                               arg1, 0)
12420           && wi::extract_uhwi (TREE_OPERAND (arg0, 0), 0, 1) == 1)
12421         {
12422           return omit_two_operands_loc (loc, type,
12423                                     code == NE_EXPR
12424                                     ? boolean_true_node : boolean_false_node,
12425                                     TREE_OPERAND (arg0, 1), arg1);
12426         }
12427
12428       /* Convert ABS_EXPR<x> == 0 or ABS_EXPR<x> != 0 to x == 0 or x != 0.  */
12429       if (TREE_CODE (arg0) == ABS_EXPR
12430           && (integer_zerop (arg1) || real_zerop (arg1)))
12431         return fold_build2_loc (loc, code, type, TREE_OPERAND (arg0, 0), arg1);
12432
12433       /* If this is an EQ or NE comparison with zero and ARG0 is
12434          (1 << foo) & bar, convert it to (bar >> foo) & 1.  Both require
12435          two operations, but the latter can be done in one less insn
12436          on machines that have only two-operand insns or on which a
12437          constant cannot be the first operand.  */
12438       if (TREE_CODE (arg0) == BIT_AND_EXPR
12439           && integer_zerop (arg1))
12440         {
12441           tree arg00 = TREE_OPERAND (arg0, 0);
12442           tree arg01 = TREE_OPERAND (arg0, 1);
12443           if (TREE_CODE (arg00) == LSHIFT_EXPR
12444               && integer_onep (TREE_OPERAND (arg00, 0)))
12445             {
12446               tree tem = fold_build2_loc (loc, RSHIFT_EXPR, TREE_TYPE (arg00),
12447                                       arg01, TREE_OPERAND (arg00, 1));
12448               tem = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg0), tem,
12449                                  build_int_cst (TREE_TYPE (arg0), 1));
12450               return fold_build2_loc (loc, code, type,
12451                                   fold_convert_loc (loc, TREE_TYPE (arg1), tem),
12452                                   arg1);
12453             }
12454           else if (TREE_CODE (arg01) == LSHIFT_EXPR
12455                    && integer_onep (TREE_OPERAND (arg01, 0)))
12456             {
12457               tree tem = fold_build2_loc (loc, RSHIFT_EXPR, TREE_TYPE (arg01),
12458                                       arg00, TREE_OPERAND (arg01, 1));
12459               tem = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg0), tem,
12460                                  build_int_cst (TREE_TYPE (arg0), 1));
12461               return fold_build2_loc (loc, code, type,
12462                                   fold_convert_loc (loc, TREE_TYPE (arg1), tem),
12463                                   arg1);
12464             }
12465         }
12466
12467       /* If this is an NE or EQ comparison of zero against the result of a
12468          signed MOD operation whose second operand is a power of 2, make
12469          the MOD operation unsigned since it is simpler and equivalent.  */
12470       if (integer_zerop (arg1)
12471           && !TYPE_UNSIGNED (TREE_TYPE (arg0))
12472           && (TREE_CODE (arg0) == TRUNC_MOD_EXPR
12473               || TREE_CODE (arg0) == CEIL_MOD_EXPR
12474               || TREE_CODE (arg0) == FLOOR_MOD_EXPR
12475               || TREE_CODE (arg0) == ROUND_MOD_EXPR)
12476           && integer_pow2p (TREE_OPERAND (arg0, 1)))
12477         {
12478           tree newtype = unsigned_type_for (TREE_TYPE (arg0));
12479           tree newmod = fold_build2_loc (loc, TREE_CODE (arg0), newtype,
12480                                      fold_convert_loc (loc, newtype,
12481                                                        TREE_OPERAND (arg0, 0)),
12482                                      fold_convert_loc (loc, newtype,
12483                                                        TREE_OPERAND (arg0, 1)));
12484
12485           return fold_build2_loc (loc, code, type, newmod,
12486                               fold_convert_loc (loc, newtype, arg1));
12487         }
12488
12489       /* Fold ((X >> C1) & C2) == 0 and ((X >> C1) & C2) != 0 where
12490          C1 is a valid shift constant, and C2 is a power of two, i.e.
12491          a single bit.  */
12492       if (TREE_CODE (arg0) == BIT_AND_EXPR
12493           && TREE_CODE (TREE_OPERAND (arg0, 0)) == RSHIFT_EXPR
12494           && TREE_CODE (TREE_OPERAND (TREE_OPERAND (arg0, 0), 1))
12495              == INTEGER_CST
12496           && integer_pow2p (TREE_OPERAND (arg0, 1))
12497           && integer_zerop (arg1))
12498         {
12499           tree itype = TREE_TYPE (arg0);
12500           tree arg001 = TREE_OPERAND (TREE_OPERAND (arg0, 0), 1);
12501           prec = TYPE_PRECISION (itype);
12502
12503           /* Check for a valid shift count.  */
12504           if (wi::ltu_p (arg001, prec))
12505             {
12506               tree arg01 = TREE_OPERAND (arg0, 1);
12507               tree arg000 = TREE_OPERAND (TREE_OPERAND (arg0, 0), 0);
12508               unsigned HOST_WIDE_INT log2 = tree_log2 (arg01);
12509               /* If (C2 << C1) doesn't overflow, then ((X >> C1) & C2) != 0
12510                  can be rewritten as (X & (C2 << C1)) != 0.  */
12511               if ((log2 + TREE_INT_CST_LOW (arg001)) < prec)
12512                 {
12513                   tem = fold_build2_loc (loc, LSHIFT_EXPR, itype, arg01, arg001);
12514                   tem = fold_build2_loc (loc, BIT_AND_EXPR, itype, arg000, tem);
12515                   return fold_build2_loc (loc, code, type, tem,
12516                                           fold_convert_loc (loc, itype, arg1));
12517                 }
12518               /* Otherwise, for signed (arithmetic) shifts,
12519                  ((X >> C1) & C2) != 0 is rewritten as X < 0, and
12520                  ((X >> C1) & C2) == 0 is rewritten as X >= 0.  */
12521               else if (!TYPE_UNSIGNED (itype))
12522                 return fold_build2_loc (loc, code == EQ_EXPR ? GE_EXPR : LT_EXPR, type,
12523                                     arg000, build_int_cst (itype, 0));
12524               /* Otherwise, of unsigned (logical) shifts,
12525                  ((X >> C1) & C2) != 0 is rewritten as (X,false), and
12526                  ((X >> C1) & C2) == 0 is rewritten as (X,true).  */
12527               else
12528                 return omit_one_operand_loc (loc, type,
12529                                          code == EQ_EXPR ? integer_one_node
12530                                                          : integer_zero_node,
12531                                          arg000);
12532             }
12533         }
12534
12535       /* If we have (A & C) == C where C is a power of 2, convert this into
12536          (A & C) != 0.  Similarly for NE_EXPR.  */
12537       if (TREE_CODE (arg0) == BIT_AND_EXPR
12538           && integer_pow2p (TREE_OPERAND (arg0, 1))
12539           && operand_equal_p (TREE_OPERAND (arg0, 1), arg1, 0))
12540         return fold_build2_loc (loc, code == EQ_EXPR ? NE_EXPR : EQ_EXPR, type,
12541                             arg0, fold_convert_loc (loc, TREE_TYPE (arg0),
12542                                                     integer_zero_node));
12543
12544       /* If we have (A & C) != 0 or (A & C) == 0 and C is the sign
12545          bit, then fold the expression into A < 0 or A >= 0.  */
12546       tem = fold_single_bit_test_into_sign_test (loc, code, arg0, arg1, type);
12547       if (tem)
12548         return tem;
12549
12550       /* If we have (A & C) == D where D & ~C != 0, convert this into 0.
12551          Similarly for NE_EXPR.  */
12552       if (TREE_CODE (arg0) == BIT_AND_EXPR
12553           && TREE_CODE (arg1) == INTEGER_CST
12554           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
12555         {
12556           tree notc = fold_build1_loc (loc, BIT_NOT_EXPR,
12557                                    TREE_TYPE (TREE_OPERAND (arg0, 1)),
12558                                    TREE_OPERAND (arg0, 1));
12559           tree dandnotc
12560             = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg0),
12561                                fold_convert_loc (loc, TREE_TYPE (arg0), arg1),
12562                                notc);
12563           tree rslt = code == EQ_EXPR ? integer_zero_node : integer_one_node;
12564           if (integer_nonzerop (dandnotc))
12565             return omit_one_operand_loc (loc, type, rslt, arg0);
12566         }
12567
12568       /* If we have (A | C) == D where C & ~D != 0, convert this into 0.
12569          Similarly for NE_EXPR.  */
12570       if (TREE_CODE (arg0) == BIT_IOR_EXPR
12571           && TREE_CODE (arg1) == INTEGER_CST
12572           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
12573         {
12574           tree notd = fold_build1_loc (loc, BIT_NOT_EXPR, TREE_TYPE (arg1), arg1);
12575           tree candnotd
12576             = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg0),
12577                                TREE_OPERAND (arg0, 1),
12578                                fold_convert_loc (loc, TREE_TYPE (arg0), notd));
12579           tree rslt = code == EQ_EXPR ? integer_zero_node : integer_one_node;
12580           if (integer_nonzerop (candnotd))
12581             return omit_one_operand_loc (loc, type, rslt, arg0);
12582         }
12583
12584       /* If this is a comparison of a field, we may be able to simplify it.  */
12585       if ((TREE_CODE (arg0) == COMPONENT_REF
12586            || TREE_CODE (arg0) == BIT_FIELD_REF)
12587           /* Handle the constant case even without -O
12588              to make sure the warnings are given.  */
12589           && (optimize || TREE_CODE (arg1) == INTEGER_CST))
12590         {
12591           t1 = optimize_bit_field_compare (loc, code, type, arg0, arg1);
12592           if (t1)
12593             return t1;
12594         }
12595
12596       /* Optimize comparisons of strlen vs zero to a compare of the
12597          first character of the string vs zero.  To wit,
12598                 strlen(ptr) == 0   =>  *ptr == 0
12599                 strlen(ptr) != 0   =>  *ptr != 0
12600          Other cases should reduce to one of these two (or a constant)
12601          due to the return value of strlen being unsigned.  */
12602       if (TREE_CODE (arg0) == CALL_EXPR
12603           && integer_zerop (arg1))
12604         {
12605           tree fndecl = get_callee_fndecl (arg0);
12606
12607           if (fndecl
12608               && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
12609               && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STRLEN
12610               && call_expr_nargs (arg0) == 1
12611               && TREE_CODE (TREE_TYPE (CALL_EXPR_ARG (arg0, 0))) == POINTER_TYPE)
12612             {
12613               tree iref = build_fold_indirect_ref_loc (loc,
12614                                                    CALL_EXPR_ARG (arg0, 0));
12615               return fold_build2_loc (loc, code, type, iref,
12616                                   build_int_cst (TREE_TYPE (iref), 0));
12617             }
12618         }
12619
12620       /* Fold (X >> C) != 0 into X < 0 if C is one less than the width
12621          of X.  Similarly fold (X >> C) == 0 into X >= 0.  */
12622       if (TREE_CODE (arg0) == RSHIFT_EXPR
12623           && integer_zerop (arg1)
12624           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
12625         {
12626           tree arg00 = TREE_OPERAND (arg0, 0);
12627           tree arg01 = TREE_OPERAND (arg0, 1);
12628           tree itype = TREE_TYPE (arg00);
12629           if (wi::eq_p (arg01, element_precision (itype) - 1))
12630             {
12631               if (TYPE_UNSIGNED (itype))
12632                 {
12633                   itype = signed_type_for (itype);
12634                   arg00 = fold_convert_loc (loc, itype, arg00);
12635                 }
12636               return fold_build2_loc (loc, code == EQ_EXPR ? GE_EXPR : LT_EXPR,
12637                                   type, arg00, build_zero_cst (itype));
12638             }
12639         }
12640
12641       /* (X ^ Y) == 0 becomes X == Y, and (X ^ Y) != 0 becomes X != Y.  */
12642       if (integer_zerop (arg1)
12643           && TREE_CODE (arg0) == BIT_XOR_EXPR)
12644         return fold_build2_loc (loc, code, type, TREE_OPERAND (arg0, 0),
12645                             TREE_OPERAND (arg0, 1));
12646
12647       /* (X ^ Y) == Y becomes X == 0.  We know that Y has no side-effects.  */
12648       if (TREE_CODE (arg0) == BIT_XOR_EXPR
12649           && operand_equal_p (TREE_OPERAND (arg0, 1), arg1, 0))
12650         return fold_build2_loc (loc, code, type, TREE_OPERAND (arg0, 0),
12651                                 build_zero_cst (TREE_TYPE (arg0)));
12652       /* Likewise (X ^ Y) == X becomes Y == 0.  X has no side-effects.  */
12653       if (TREE_CODE (arg0) == BIT_XOR_EXPR
12654           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0)
12655           && reorder_operands_p (TREE_OPERAND (arg0, 1), arg1))
12656         return fold_build2_loc (loc, code, type, TREE_OPERAND (arg0, 1),
12657                                 build_zero_cst (TREE_TYPE (arg0)));
12658
12659       /* (X ^ C1) op C2 can be rewritten as X op (C1 ^ C2).  */
12660       if (TREE_CODE (arg0) == BIT_XOR_EXPR
12661           && TREE_CODE (arg1) == INTEGER_CST
12662           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
12663         return fold_build2_loc (loc, code, type, TREE_OPERAND (arg0, 0),
12664                             fold_build2_loc (loc, BIT_XOR_EXPR, TREE_TYPE (arg1),
12665                                          TREE_OPERAND (arg0, 1), arg1));
12666
12667       /* Fold (~X & C) == 0 into (X & C) != 0 and (~X & C) != 0 into
12668          (X & C) == 0 when C is a single bit.  */
12669       if (TREE_CODE (arg0) == BIT_AND_EXPR
12670           && TREE_CODE (TREE_OPERAND (arg0, 0)) == BIT_NOT_EXPR
12671           && integer_zerop (arg1)
12672           && integer_pow2p (TREE_OPERAND (arg0, 1)))
12673         {
12674           tem = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg0),
12675                                  TREE_OPERAND (TREE_OPERAND (arg0, 0), 0),
12676                                  TREE_OPERAND (arg0, 1));
12677           return fold_build2_loc (loc, code == EQ_EXPR ? NE_EXPR : EQ_EXPR,
12678                                   type, tem,
12679                                   fold_convert_loc (loc, TREE_TYPE (arg0),
12680                                                     arg1));
12681         }
12682
12683       /* Fold ((X & C) ^ C) eq/ne 0 into (X & C) ne/eq 0, when the
12684          constant C is a power of two, i.e. a single bit.  */
12685       if (TREE_CODE (arg0) == BIT_XOR_EXPR
12686           && TREE_CODE (TREE_OPERAND (arg0, 0)) == BIT_AND_EXPR
12687           && integer_zerop (arg1)
12688           && integer_pow2p (TREE_OPERAND (arg0, 1))
12689           && operand_equal_p (TREE_OPERAND (TREE_OPERAND (arg0, 0), 1),
12690                               TREE_OPERAND (arg0, 1), OEP_ONLY_CONST))
12691         {
12692           tree arg00 = TREE_OPERAND (arg0, 0);
12693           return fold_build2_loc (loc, code == EQ_EXPR ? NE_EXPR : EQ_EXPR, type,
12694                               arg00, build_int_cst (TREE_TYPE (arg00), 0));
12695         }
12696
12697       /* Likewise, fold ((X ^ C) & C) eq/ne 0 into (X & C) ne/eq 0,
12698          when is C is a power of two, i.e. a single bit.  */
12699       if (TREE_CODE (arg0) == BIT_AND_EXPR
12700           && TREE_CODE (TREE_OPERAND (arg0, 0)) == BIT_XOR_EXPR
12701           && integer_zerop (arg1)
12702           && integer_pow2p (TREE_OPERAND (arg0, 1))
12703           && operand_equal_p (TREE_OPERAND (TREE_OPERAND (arg0, 0), 1),
12704                               TREE_OPERAND (arg0, 1), OEP_ONLY_CONST))
12705         {
12706           tree arg000 = TREE_OPERAND (TREE_OPERAND (arg0, 0), 0);
12707           tem = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg000),
12708                              arg000, TREE_OPERAND (arg0, 1));
12709           return fold_build2_loc (loc, code == EQ_EXPR ? NE_EXPR : EQ_EXPR, type,
12710                               tem, build_int_cst (TREE_TYPE (tem), 0));
12711         }
12712
12713       if (integer_zerop (arg1)
12714           && tree_expr_nonzero_p (arg0))
12715         {
12716           tree res = constant_boolean_node (code==NE_EXPR, type);
12717           return omit_one_operand_loc (loc, type, res, arg0);
12718         }
12719
12720       /* Fold -X op -Y as X op Y, where op is eq/ne.  */
12721       if (TREE_CODE (arg0) == NEGATE_EXPR
12722           && TREE_CODE (arg1) == NEGATE_EXPR)
12723         return fold_build2_loc (loc, code, type,
12724                                 TREE_OPERAND (arg0, 0),
12725                                 fold_convert_loc (loc, TREE_TYPE (arg0),
12726                                                   TREE_OPERAND (arg1, 0)));
12727
12728       /* Fold (X & C) op (Y & C) as (X ^ Y) & C op 0", and symmetries.  */
12729       if (TREE_CODE (arg0) == BIT_AND_EXPR
12730           && TREE_CODE (arg1) == BIT_AND_EXPR)
12731         {
12732           tree arg00 = TREE_OPERAND (arg0, 0);
12733           tree arg01 = TREE_OPERAND (arg0, 1);
12734           tree arg10 = TREE_OPERAND (arg1, 0);
12735           tree arg11 = TREE_OPERAND (arg1, 1);
12736           tree itype = TREE_TYPE (arg0);
12737
12738           if (operand_equal_p (arg01, arg11, 0))
12739             return fold_build2_loc (loc, code, type,
12740                                 fold_build2_loc (loc, BIT_AND_EXPR, itype,
12741                                              fold_build2_loc (loc,
12742                                                           BIT_XOR_EXPR, itype,
12743                                                           arg00, arg10),
12744                                              arg01),
12745                                 build_zero_cst (itype));
12746
12747           if (operand_equal_p (arg01, arg10, 0))
12748             return fold_build2_loc (loc, code, type,
12749                                 fold_build2_loc (loc, BIT_AND_EXPR, itype,
12750                                              fold_build2_loc (loc,
12751                                                           BIT_XOR_EXPR, itype,
12752                                                           arg00, arg11),
12753                                              arg01),
12754                                 build_zero_cst (itype));
12755
12756           if (operand_equal_p (arg00, arg11, 0))
12757             return fold_build2_loc (loc, code, type,
12758                                 fold_build2_loc (loc, BIT_AND_EXPR, itype,
12759                                              fold_build2_loc (loc,
12760                                                           BIT_XOR_EXPR, itype,
12761                                                           arg01, arg10),
12762                                              arg00),
12763                                 build_zero_cst (itype));
12764
12765           if (operand_equal_p (arg00, arg10, 0))
12766             return fold_build2_loc (loc, code, type,
12767                                 fold_build2_loc (loc, BIT_AND_EXPR, itype,
12768                                              fold_build2_loc (loc,
12769                                                           BIT_XOR_EXPR, itype,
12770                                                           arg01, arg11),
12771                                              arg00),
12772                                 build_zero_cst (itype));
12773         }
12774
12775       if (TREE_CODE (arg0) == BIT_XOR_EXPR
12776           && TREE_CODE (arg1) == BIT_XOR_EXPR)
12777         {
12778           tree arg00 = TREE_OPERAND (arg0, 0);
12779           tree arg01 = TREE_OPERAND (arg0, 1);
12780           tree arg10 = TREE_OPERAND (arg1, 0);
12781           tree arg11 = TREE_OPERAND (arg1, 1);
12782           tree itype = TREE_TYPE (arg0);
12783
12784           /* Optimize (X ^ Z) op (Y ^ Z) as X op Y, and symmetries.
12785              operand_equal_p guarantees no side-effects so we don't need
12786              to use omit_one_operand on Z.  */
12787           if (operand_equal_p (arg01, arg11, 0))
12788             return fold_build2_loc (loc, code, type, arg00,
12789                                     fold_convert_loc (loc, TREE_TYPE (arg00),
12790                                                       arg10));
12791           if (operand_equal_p (arg01, arg10, 0))
12792             return fold_build2_loc (loc, code, type, arg00,
12793                                     fold_convert_loc (loc, TREE_TYPE (arg00),
12794                                                       arg11));
12795           if (operand_equal_p (arg00, arg11, 0))
12796             return fold_build2_loc (loc, code, type, arg01,
12797                                     fold_convert_loc (loc, TREE_TYPE (arg01),
12798                                                       arg10));
12799           if (operand_equal_p (arg00, arg10, 0))
12800             return fold_build2_loc (loc, code, type, arg01,
12801                                     fold_convert_loc (loc, TREE_TYPE (arg01),
12802                                                       arg11));
12803
12804           /* Optimize (X ^ C1) op (Y ^ C2) as (X ^ (C1 ^ C2)) op Y.  */
12805           if (TREE_CODE (arg01) == INTEGER_CST
12806               && TREE_CODE (arg11) == INTEGER_CST)
12807             {
12808               tem = fold_build2_loc (loc, BIT_XOR_EXPR, itype, arg01,
12809                                      fold_convert_loc (loc, itype, arg11));
12810               tem = fold_build2_loc (loc, BIT_XOR_EXPR, itype, arg00, tem);
12811               return fold_build2_loc (loc, code, type, tem,
12812                                       fold_convert_loc (loc, itype, arg10));
12813             }
12814         }
12815
12816       /* Attempt to simplify equality/inequality comparisons of complex
12817          values.  Only lower the comparison if the result is known or
12818          can be simplified to a single scalar comparison.  */
12819       if ((TREE_CODE (arg0) == COMPLEX_EXPR
12820            || TREE_CODE (arg0) == COMPLEX_CST)
12821           && (TREE_CODE (arg1) == COMPLEX_EXPR
12822               || TREE_CODE (arg1) == COMPLEX_CST))
12823         {
12824           tree real0, imag0, real1, imag1;
12825           tree rcond, icond;
12826
12827           if (TREE_CODE (arg0) == COMPLEX_EXPR)
12828             {
12829               real0 = TREE_OPERAND (arg0, 0);
12830               imag0 = TREE_OPERAND (arg0, 1);
12831             }
12832           else
12833             {
12834               real0 = TREE_REALPART (arg0);
12835               imag0 = TREE_IMAGPART (arg0);
12836             }
12837
12838           if (TREE_CODE (arg1) == COMPLEX_EXPR)
12839             {
12840               real1 = TREE_OPERAND (arg1, 0);
12841               imag1 = TREE_OPERAND (arg1, 1);
12842             }
12843           else
12844             {
12845               real1 = TREE_REALPART (arg1);
12846               imag1 = TREE_IMAGPART (arg1);
12847             }
12848
12849           rcond = fold_binary_loc (loc, code, type, real0, real1);
12850           if (rcond && TREE_CODE (rcond) == INTEGER_CST)
12851             {
12852               if (integer_zerop (rcond))
12853                 {
12854                   if (code == EQ_EXPR)
12855                     return omit_two_operands_loc (loc, type, boolean_false_node,
12856                                               imag0, imag1);
12857                   return fold_build2_loc (loc, NE_EXPR, type, imag0, imag1);
12858                 }
12859               else
12860                 {
12861                   if (code == NE_EXPR)
12862                     return omit_two_operands_loc (loc, type, boolean_true_node,
12863                                               imag0, imag1);
12864                   return fold_build2_loc (loc, EQ_EXPR, type, imag0, imag1);
12865                 }
12866             }
12867
12868           icond = fold_binary_loc (loc, code, type, imag0, imag1);
12869           if (icond && TREE_CODE (icond) == INTEGER_CST)
12870             {
12871               if (integer_zerop (icond))
12872                 {
12873                   if (code == EQ_EXPR)
12874                     return omit_two_operands_loc (loc, type, boolean_false_node,
12875                                               real0, real1);
12876                   return fold_build2_loc (loc, NE_EXPR, type, real0, real1);
12877                 }
12878               else
12879                 {
12880                   if (code == NE_EXPR)
12881                     return omit_two_operands_loc (loc, type, boolean_true_node,
12882                                               real0, real1);
12883                   return fold_build2_loc (loc, EQ_EXPR, type, real0, real1);
12884                 }
12885             }
12886         }
12887
12888       return NULL_TREE;
12889
12890     case LT_EXPR:
12891     case GT_EXPR:
12892     case LE_EXPR:
12893     case GE_EXPR:
12894       tem = fold_comparison (loc, code, type, op0, op1);
12895       if (tem != NULL_TREE)
12896         return tem;
12897
12898       /* Transform comparisons of the form X +- C CMP X.  */
12899       if ((TREE_CODE (arg0) == PLUS_EXPR || TREE_CODE (arg0) == MINUS_EXPR)
12900           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0)
12901           && ((TREE_CODE (TREE_OPERAND (arg0, 1)) == REAL_CST
12902                && !HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg0))))
12903               || (TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
12904                   && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))))
12905         {
12906           tree arg01 = TREE_OPERAND (arg0, 1);
12907           enum tree_code code0 = TREE_CODE (arg0);
12908           int is_positive;
12909
12910           if (TREE_CODE (arg01) == REAL_CST)
12911             is_positive = REAL_VALUE_NEGATIVE (TREE_REAL_CST (arg01)) ? -1 : 1;
12912           else
12913             is_positive = tree_int_cst_sgn (arg01);
12914
12915           /* (X - c) > X becomes false.  */
12916           if (code == GT_EXPR
12917               && ((code0 == MINUS_EXPR && is_positive >= 0)
12918                   || (code0 == PLUS_EXPR && is_positive <= 0)))
12919             {
12920               if (TREE_CODE (arg01) == INTEGER_CST
12921                   && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
12922                 fold_overflow_warning (("assuming signed overflow does not "
12923                                         "occur when assuming that (X - c) > X "
12924                                         "is always false"),
12925                                        WARN_STRICT_OVERFLOW_ALL);
12926               return constant_boolean_node (0, type);
12927             }
12928
12929           /* Likewise (X + c) < X becomes false.  */
12930           if (code == LT_EXPR
12931               && ((code0 == PLUS_EXPR && is_positive >= 0)
12932                   || (code0 == MINUS_EXPR && is_positive <= 0)))
12933             {
12934               if (TREE_CODE (arg01) == INTEGER_CST
12935                   && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
12936                 fold_overflow_warning (("assuming signed overflow does not "
12937                                         "occur when assuming that "
12938                                         "(X + c) < X is always false"),
12939                                        WARN_STRICT_OVERFLOW_ALL);
12940               return constant_boolean_node (0, type);
12941             }
12942
12943           /* Convert (X - c) <= X to true.  */
12944           if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg1)))
12945               && code == LE_EXPR
12946               && ((code0 == MINUS_EXPR && is_positive >= 0)
12947                   || (code0 == PLUS_EXPR && is_positive <= 0)))
12948             {
12949               if (TREE_CODE (arg01) == INTEGER_CST
12950                   && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
12951                 fold_overflow_warning (("assuming signed overflow does not "
12952                                         "occur when assuming that "
12953                                         "(X - c) <= X is always true"),
12954                                        WARN_STRICT_OVERFLOW_ALL);
12955               return constant_boolean_node (1, type);
12956             }
12957
12958           /* Convert (X + c) >= X to true.  */
12959           if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg1)))
12960               && code == GE_EXPR
12961               && ((code0 == PLUS_EXPR && is_positive >= 0)
12962                   || (code0 == MINUS_EXPR && is_positive <= 0)))
12963             {
12964               if (TREE_CODE (arg01) == INTEGER_CST
12965                   && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
12966                 fold_overflow_warning (("assuming signed overflow does not "
12967                                         "occur when assuming that "
12968                                         "(X + c) >= X is always true"),
12969                                        WARN_STRICT_OVERFLOW_ALL);
12970               return constant_boolean_node (1, type);
12971             }
12972
12973           if (TREE_CODE (arg01) == INTEGER_CST)
12974             {
12975               /* Convert X + c > X and X - c < X to true for integers.  */
12976               if (code == GT_EXPR
12977                   && ((code0 == PLUS_EXPR && is_positive > 0)
12978                       || (code0 == MINUS_EXPR && is_positive < 0)))
12979                 {
12980                   if (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
12981                     fold_overflow_warning (("assuming signed overflow does "
12982                                             "not occur when assuming that "
12983                                             "(X + c) > X is always true"),
12984                                            WARN_STRICT_OVERFLOW_ALL);
12985                   return constant_boolean_node (1, type);
12986                 }
12987
12988               if (code == LT_EXPR
12989                   && ((code0 == MINUS_EXPR && is_positive > 0)
12990                       || (code0 == PLUS_EXPR && is_positive < 0)))
12991                 {
12992                   if (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
12993                     fold_overflow_warning (("assuming signed overflow does "
12994                                             "not occur when assuming that "
12995                                             "(X - c) < X is always true"),
12996                                            WARN_STRICT_OVERFLOW_ALL);
12997                   return constant_boolean_node (1, type);
12998                 }
12999
13000               /* Convert X + c <= X and X - c >= X to false for integers.  */
13001               if (code == LE_EXPR
13002                   && ((code0 == PLUS_EXPR && is_positive > 0)
13003                       || (code0 == MINUS_EXPR && is_positive < 0)))
13004                 {
13005                   if (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
13006                     fold_overflow_warning (("assuming signed overflow does "
13007                                             "not occur when assuming that "
13008                                             "(X + c) <= X is always false"),
13009                                            WARN_STRICT_OVERFLOW_ALL);
13010                   return constant_boolean_node (0, type);
13011                 }
13012
13013               if (code == GE_EXPR
13014                   && ((code0 == MINUS_EXPR && is_positive > 0)
13015                       || (code0 == PLUS_EXPR && is_positive < 0)))
13016                 {
13017                   if (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
13018                     fold_overflow_warning (("assuming signed overflow does "
13019                                             "not occur when assuming that "
13020                                             "(X - c) >= X is always false"),
13021                                            WARN_STRICT_OVERFLOW_ALL);
13022                   return constant_boolean_node (0, type);
13023                 }
13024             }
13025         }
13026
13027       /* Comparisons with the highest or lowest possible integer of
13028          the specified precision will have known values.  */
13029       {
13030         tree arg1_type = TREE_TYPE (arg1);
13031         unsigned int prec = TYPE_PRECISION (arg1_type);
13032
13033         if (TREE_CODE (arg1) == INTEGER_CST
13034             && (INTEGRAL_TYPE_P (arg1_type) || POINTER_TYPE_P (arg1_type)))
13035           {
13036             wide_int max = wi::max_value (arg1_type);
13037             wide_int signed_max = wi::max_value (prec, SIGNED);
13038             wide_int min = wi::min_value (arg1_type);
13039
13040             if (wi::eq_p (arg1, max))
13041               switch (code)
13042                 {
13043                 case GT_EXPR:
13044                   return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
13045
13046                 case GE_EXPR:
13047                   return fold_build2_loc (loc, EQ_EXPR, type, op0, op1);
13048
13049                 case LE_EXPR:
13050                   return omit_one_operand_loc (loc, type, integer_one_node, arg0);
13051
13052                 case LT_EXPR:
13053                   return fold_build2_loc (loc, NE_EXPR, type, op0, op1);
13054
13055                 /* The GE_EXPR and LT_EXPR cases above are not normally
13056                    reached because of previous transformations.  */
13057
13058                 default:
13059                   break;
13060                 }
13061             else if (wi::eq_p (arg1, max - 1))
13062               switch (code)
13063                 {
13064                 case GT_EXPR:
13065                   arg1 = const_binop (PLUS_EXPR, arg1,
13066                                       build_int_cst (TREE_TYPE (arg1), 1));
13067                   return fold_build2_loc (loc, EQ_EXPR, type,
13068                                       fold_convert_loc (loc,
13069                                                         TREE_TYPE (arg1), arg0),
13070                                       arg1);
13071                 case LE_EXPR:
13072                   arg1 = const_binop (PLUS_EXPR, arg1,
13073                                       build_int_cst (TREE_TYPE (arg1), 1));
13074                   return fold_build2_loc (loc, NE_EXPR, type,
13075                                       fold_convert_loc (loc, TREE_TYPE (arg1),
13076                                                         arg0),
13077                                       arg1);
13078                 default:
13079                   break;
13080                 }
13081             else if (wi::eq_p (arg1, min))
13082               switch (code)
13083                 {
13084                 case LT_EXPR:
13085                   return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
13086
13087                 case LE_EXPR:
13088                   return fold_build2_loc (loc, EQ_EXPR, type, op0, op1);
13089
13090                 case GE_EXPR:
13091                   return omit_one_operand_loc (loc, type, integer_one_node, arg0);
13092
13093                 case GT_EXPR:
13094                   return fold_build2_loc (loc, NE_EXPR, type, op0, op1);
13095
13096                 default:
13097                   break;
13098                 }
13099             else if (wi::eq_p (arg1, min + 1))
13100               switch (code)
13101                 {
13102                 case GE_EXPR:
13103                   arg1 = const_binop (MINUS_EXPR, arg1,
13104                                       build_int_cst (TREE_TYPE (arg1), 1));
13105                   return fold_build2_loc (loc, NE_EXPR, type,
13106                                       fold_convert_loc (loc,
13107                                                         TREE_TYPE (arg1), arg0),
13108                                       arg1);
13109                 case LT_EXPR:
13110                   arg1 = const_binop (MINUS_EXPR, arg1,
13111                                       build_int_cst (TREE_TYPE (arg1), 1));
13112                   return fold_build2_loc (loc, EQ_EXPR, type,
13113                                       fold_convert_loc (loc, TREE_TYPE (arg1),
13114                                                         arg0),
13115                                       arg1);
13116                 default:
13117                   break;
13118                 }
13119
13120             else if (wi::eq_p (arg1, signed_max)
13121                      && TYPE_UNSIGNED (arg1_type)
13122                      /* We will flip the signedness of the comparison operator
13123                         associated with the mode of arg1, so the sign bit is
13124                         specified by this mode.  Check that arg1 is the signed
13125                         max associated with this sign bit.  */
13126                      && prec == GET_MODE_PRECISION (TYPE_MODE (arg1_type))
13127                      /* signed_type does not work on pointer types.  */
13128                      && INTEGRAL_TYPE_P (arg1_type))
13129               {
13130                 /* The following case also applies to X < signed_max+1
13131                    and X >= signed_max+1 because previous transformations.  */
13132                 if (code == LE_EXPR || code == GT_EXPR)
13133                   {
13134                     tree st = signed_type_for (arg1_type);
13135                     return fold_build2_loc (loc,
13136                                         code == LE_EXPR ? GE_EXPR : LT_EXPR,
13137                                         type, fold_convert_loc (loc, st, arg0),
13138                                         build_int_cst (st, 0));
13139                   }
13140               }
13141           }
13142       }
13143
13144       /* If we are comparing an ABS_EXPR with a constant, we can
13145          convert all the cases into explicit comparisons, but they may
13146          well not be faster than doing the ABS and one comparison.
13147          But ABS (X) <= C is a range comparison, which becomes a subtraction
13148          and a comparison, and is probably faster.  */
13149       if (code == LE_EXPR
13150           && TREE_CODE (arg1) == INTEGER_CST
13151           && TREE_CODE (arg0) == ABS_EXPR
13152           && ! TREE_SIDE_EFFECTS (arg0)
13153           && (0 != (tem = negate_expr (arg1)))
13154           && TREE_CODE (tem) == INTEGER_CST
13155           && !TREE_OVERFLOW (tem))
13156         return fold_build2_loc (loc, TRUTH_ANDIF_EXPR, type,
13157                             build2 (GE_EXPR, type,
13158                                     TREE_OPERAND (arg0, 0), tem),
13159                             build2 (LE_EXPR, type,
13160                                     TREE_OPERAND (arg0, 0), arg1));
13161
13162       /* Convert ABS_EXPR<x> >= 0 to true.  */
13163       strict_overflow_p = false;
13164       if (code == GE_EXPR
13165           && (integer_zerop (arg1)
13166               || (! HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0)))
13167                   && real_zerop (arg1)))
13168           && tree_expr_nonnegative_warnv_p (arg0, &strict_overflow_p))
13169         {
13170           if (strict_overflow_p)
13171             fold_overflow_warning (("assuming signed overflow does not occur "
13172                                     "when simplifying comparison of "
13173                                     "absolute value and zero"),
13174                                    WARN_STRICT_OVERFLOW_CONDITIONAL);
13175           return omit_one_operand_loc (loc, type,
13176                                        constant_boolean_node (true, type),
13177                                        arg0);
13178         }
13179
13180       /* Convert ABS_EXPR<x> < 0 to false.  */
13181       strict_overflow_p = false;
13182       if (code == LT_EXPR
13183           && (integer_zerop (arg1) || real_zerop (arg1))
13184           && tree_expr_nonnegative_warnv_p (arg0, &strict_overflow_p))
13185         {
13186           if (strict_overflow_p)
13187             fold_overflow_warning (("assuming signed overflow does not occur "
13188                                     "when simplifying comparison of "
13189                                     "absolute value and zero"),
13190                                    WARN_STRICT_OVERFLOW_CONDITIONAL);
13191           return omit_one_operand_loc (loc, type,
13192                                        constant_boolean_node (false, type),
13193                                        arg0);
13194         }
13195
13196       /* If X is unsigned, convert X < (1 << Y) into X >> Y == 0
13197          and similarly for >= into !=.  */
13198       if ((code == LT_EXPR || code == GE_EXPR)
13199           && TYPE_UNSIGNED (TREE_TYPE (arg0))
13200           && TREE_CODE (arg1) == LSHIFT_EXPR
13201           && integer_onep (TREE_OPERAND (arg1, 0)))
13202         return build2_loc (loc, code == LT_EXPR ? EQ_EXPR : NE_EXPR, type,
13203                            build2 (RSHIFT_EXPR, TREE_TYPE (arg0), arg0,
13204                                    TREE_OPERAND (arg1, 1)),
13205                            build_zero_cst (TREE_TYPE (arg0)));
13206
13207       /* Similarly for X < (cast) (1 << Y).  But cast can't be narrowing,
13208          otherwise Y might be >= # of bits in X's type and thus e.g.
13209          (unsigned char) (1 << Y) for Y 15 might be 0.
13210          If the cast is widening, then 1 << Y should have unsigned type,
13211          otherwise if Y is number of bits in the signed shift type minus 1,
13212          we can't optimize this.  E.g. (unsigned long long) (1 << Y) for Y
13213          31 might be 0xffffffff80000000.  */
13214       if ((code == LT_EXPR || code == GE_EXPR)
13215           && TYPE_UNSIGNED (TREE_TYPE (arg0))
13216           && CONVERT_EXPR_P (arg1)
13217           && TREE_CODE (TREE_OPERAND (arg1, 0)) == LSHIFT_EXPR
13218           && (TYPE_PRECISION (TREE_TYPE (arg1))
13219               >= TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (arg1, 0))))
13220           && (TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (arg1, 0)))
13221               || (TYPE_PRECISION (TREE_TYPE (arg1))
13222                   == TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (arg1, 0)))))
13223           && integer_onep (TREE_OPERAND (TREE_OPERAND (arg1, 0), 0)))
13224         {
13225           tem = build2 (RSHIFT_EXPR, TREE_TYPE (arg0), arg0,
13226                         TREE_OPERAND (TREE_OPERAND (arg1, 0), 1));
13227           return build2_loc (loc, code == LT_EXPR ? EQ_EXPR : NE_EXPR, type,
13228                              fold_convert_loc (loc, TREE_TYPE (arg0), tem),
13229                              build_zero_cst (TREE_TYPE (arg0)));
13230         }
13231
13232       return NULL_TREE;
13233
13234     case UNORDERED_EXPR:
13235     case ORDERED_EXPR:
13236     case UNLT_EXPR:
13237     case UNLE_EXPR:
13238     case UNGT_EXPR:
13239     case UNGE_EXPR:
13240     case UNEQ_EXPR:
13241     case LTGT_EXPR:
13242       if (TREE_CODE (arg0) == REAL_CST && TREE_CODE (arg1) == REAL_CST)
13243         {
13244           t1 = fold_relational_const (code, type, arg0, arg1);
13245           if (t1 != NULL_TREE)
13246             return t1;
13247         }
13248
13249       /* If the first operand is NaN, the result is constant.  */
13250       if (TREE_CODE (arg0) == REAL_CST
13251           && REAL_VALUE_ISNAN (TREE_REAL_CST (arg0))
13252           && (code != LTGT_EXPR || ! flag_trapping_math))
13253         {
13254           t1 = (code == ORDERED_EXPR || code == LTGT_EXPR)
13255                ? integer_zero_node
13256                : integer_one_node;
13257           return omit_one_operand_loc (loc, type, t1, arg1);
13258         }
13259
13260       /* If the second operand is NaN, the result is constant.  */
13261       if (TREE_CODE (arg1) == REAL_CST
13262           && REAL_VALUE_ISNAN (TREE_REAL_CST (arg1))
13263           && (code != LTGT_EXPR || ! flag_trapping_math))
13264         {
13265           t1 = (code == ORDERED_EXPR || code == LTGT_EXPR)
13266                ? integer_zero_node
13267                : integer_one_node;
13268           return omit_one_operand_loc (loc, type, t1, arg0);
13269         }
13270
13271       /* Simplify unordered comparison of something with itself.  */
13272       if ((code == UNLE_EXPR || code == UNGE_EXPR || code == UNEQ_EXPR)
13273           && operand_equal_p (arg0, arg1, 0))
13274         return constant_boolean_node (1, type);
13275
13276       if (code == LTGT_EXPR
13277           && !flag_trapping_math
13278           && operand_equal_p (arg0, arg1, 0))
13279         return constant_boolean_node (0, type);
13280
13281       /* Fold (double)float1 CMP (double)float2 into float1 CMP float2.  */
13282       {
13283         tree targ0 = strip_float_extensions (arg0);
13284         tree targ1 = strip_float_extensions (arg1);
13285         tree newtype = TREE_TYPE (targ0);
13286
13287         if (TYPE_PRECISION (TREE_TYPE (targ1)) > TYPE_PRECISION (newtype))
13288           newtype = TREE_TYPE (targ1);
13289
13290         if (TYPE_PRECISION (newtype) < TYPE_PRECISION (TREE_TYPE (arg0)))
13291           return fold_build2_loc (loc, code, type,
13292                               fold_convert_loc (loc, newtype, targ0),
13293                               fold_convert_loc (loc, newtype, targ1));
13294       }
13295
13296       return NULL_TREE;
13297
13298     case COMPOUND_EXPR:
13299       /* When pedantic, a compound expression can be neither an lvalue
13300          nor an integer constant expression.  */
13301       if (TREE_SIDE_EFFECTS (arg0) || TREE_CONSTANT (arg1))
13302         return NULL_TREE;
13303       /* Don't let (0, 0) be null pointer constant.  */
13304       tem = integer_zerop (arg1) ? build1 (NOP_EXPR, type, arg1)
13305                                  : fold_convert_loc (loc, type, arg1);
13306       return pedantic_non_lvalue_loc (loc, tem);
13307
13308     case COMPLEX_EXPR:
13309       if ((TREE_CODE (arg0) == REAL_CST
13310            && TREE_CODE (arg1) == REAL_CST)
13311           || (TREE_CODE (arg0) == INTEGER_CST
13312               && TREE_CODE (arg1) == INTEGER_CST))
13313         return build_complex (type, arg0, arg1);
13314       return NULL_TREE;
13315
13316     case ASSERT_EXPR:
13317       /* An ASSERT_EXPR should never be passed to fold_binary.  */
13318       gcc_unreachable ();
13319
13320     case VEC_PACK_TRUNC_EXPR:
13321     case VEC_PACK_FIX_TRUNC_EXPR:
13322       {
13323         unsigned int nelts = TYPE_VECTOR_SUBPARTS (type), i;
13324         tree *elts;
13325
13326         gcc_assert (TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0)) == nelts / 2
13327                     && TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg1)) == nelts / 2);
13328         if (TREE_CODE (arg0) != VECTOR_CST || TREE_CODE (arg1) != VECTOR_CST)
13329           return NULL_TREE;
13330
13331         elts = XALLOCAVEC (tree, nelts);
13332         if (!vec_cst_ctor_to_array (arg0, elts)
13333             || !vec_cst_ctor_to_array (arg1, elts + nelts / 2))
13334           return NULL_TREE;
13335
13336         for (i = 0; i < nelts; i++)
13337           {
13338             elts[i] = fold_convert_const (code == VEC_PACK_TRUNC_EXPR
13339                                           ? NOP_EXPR : FIX_TRUNC_EXPR,
13340                                           TREE_TYPE (type), elts[i]);
13341             if (elts[i] == NULL_TREE || !CONSTANT_CLASS_P (elts[i]))
13342               return NULL_TREE;
13343           }
13344
13345         return build_vector (type, elts);
13346       }
13347
13348     case VEC_WIDEN_MULT_LO_EXPR:
13349     case VEC_WIDEN_MULT_HI_EXPR:
13350     case VEC_WIDEN_MULT_EVEN_EXPR:
13351     case VEC_WIDEN_MULT_ODD_EXPR:
13352       {
13353         unsigned int nelts = TYPE_VECTOR_SUBPARTS (type);
13354         unsigned int out, ofs, scale;
13355         tree *elts;
13356
13357         gcc_assert (TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0)) == nelts * 2
13358                     && TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg1)) == nelts * 2);
13359         if (TREE_CODE (arg0) != VECTOR_CST || TREE_CODE (arg1) != VECTOR_CST)
13360           return NULL_TREE;
13361
13362         elts = XALLOCAVEC (tree, nelts * 4);
13363         if (!vec_cst_ctor_to_array (arg0, elts)
13364             || !vec_cst_ctor_to_array (arg1, elts + nelts * 2))
13365           return NULL_TREE;
13366
13367         if (code == VEC_WIDEN_MULT_LO_EXPR)
13368           scale = 0, ofs = BYTES_BIG_ENDIAN ? nelts : 0;
13369         else if (code == VEC_WIDEN_MULT_HI_EXPR)
13370           scale = 0, ofs = BYTES_BIG_ENDIAN ? 0 : nelts;
13371         else if (code == VEC_WIDEN_MULT_EVEN_EXPR)
13372           scale = 1, ofs = 0;
13373         else /* if (code == VEC_WIDEN_MULT_ODD_EXPR) */
13374           scale = 1, ofs = 1;
13375         
13376         for (out = 0; out < nelts; out++)
13377           {
13378             unsigned int in1 = (out << scale) + ofs;
13379             unsigned int in2 = in1 + nelts * 2;
13380             tree t1, t2;
13381
13382             t1 = fold_convert_const (NOP_EXPR, TREE_TYPE (type), elts[in1]);
13383             t2 = fold_convert_const (NOP_EXPR, TREE_TYPE (type), elts[in2]);
13384
13385             if (t1 == NULL_TREE || t2 == NULL_TREE)
13386               return NULL_TREE;
13387             elts[out] = const_binop (MULT_EXPR, t1, t2);
13388             if (elts[out] == NULL_TREE || !CONSTANT_CLASS_P (elts[out]))
13389               return NULL_TREE;
13390           }
13391
13392         return build_vector (type, elts);
13393       }
13394
13395     default:
13396       return NULL_TREE;
13397     } /* switch (code) */
13398 }
13399
13400 /* Callback for walk_tree, looking for LABEL_EXPR.  Return *TP if it is
13401    a LABEL_EXPR; otherwise return NULL_TREE.  Do not check the subtrees
13402    of GOTO_EXPR.  */
13403
13404 static tree
13405 contains_label_1 (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED)
13406 {
13407   switch (TREE_CODE (*tp))
13408     {
13409     case LABEL_EXPR:
13410       return *tp;
13411
13412     case GOTO_EXPR:
13413       *walk_subtrees = 0;
13414
13415       /* ... fall through ...  */
13416
13417     default:
13418       return NULL_TREE;
13419     }
13420 }
13421
13422 /* Return whether the sub-tree ST contains a label which is accessible from
13423    outside the sub-tree.  */
13424
13425 static bool
13426 contains_label_p (tree st)
13427 {
13428   return
13429    (walk_tree_without_duplicates (&st, contains_label_1 , NULL) != NULL_TREE);
13430 }
13431
13432 /* Fold a ternary expression of code CODE and type TYPE with operands
13433    OP0, OP1, and OP2.  Return the folded expression if folding is
13434    successful.  Otherwise, return NULL_TREE.  */
13435
13436 tree
13437 fold_ternary_loc (location_t loc, enum tree_code code, tree type,
13438                   tree op0, tree op1, tree op2)
13439 {
13440   tree tem;
13441   tree arg0 = NULL_TREE, arg1 = NULL_TREE, arg2 = NULL_TREE;
13442   enum tree_code_class kind = TREE_CODE_CLASS (code);
13443
13444   gcc_assert (IS_EXPR_CODE_CLASS (kind)
13445               && TREE_CODE_LENGTH (code) == 3);
13446
13447   /* If this is a commutative operation, and OP0 is a constant, move it
13448      to OP1 to reduce the number of tests below.  */
13449   if (commutative_ternary_tree_code (code)
13450       && tree_swap_operands_p (op0, op1, true))
13451     return fold_build3_loc (loc, code, type, op1, op0, op2);
13452
13453   tem = generic_simplify (loc, code, type, op0, op1, op2);
13454   if (tem)
13455     return tem;
13456
13457   /* Strip any conversions that don't change the mode.  This is safe
13458      for every expression, except for a comparison expression because
13459      its signedness is derived from its operands.  So, in the latter
13460      case, only strip conversions that don't change the signedness.
13461
13462      Note that this is done as an internal manipulation within the
13463      constant folder, in order to find the simplest representation of
13464      the arguments so that their form can be studied.  In any cases,
13465      the appropriate type conversions should be put back in the tree
13466      that will get out of the constant folder.  */
13467   if (op0)
13468     {
13469       arg0 = op0;
13470       STRIP_NOPS (arg0);
13471     }
13472
13473   if (op1)
13474     {
13475       arg1 = op1;
13476       STRIP_NOPS (arg1);
13477     }
13478
13479   if (op2)
13480     {
13481       arg2 = op2;
13482       STRIP_NOPS (arg2);
13483     }
13484
13485   switch (code)
13486     {
13487     case COMPONENT_REF:
13488       if (TREE_CODE (arg0) == CONSTRUCTOR
13489           && ! type_contains_placeholder_p (TREE_TYPE (arg0)))
13490         {
13491           unsigned HOST_WIDE_INT idx;
13492           tree field, value;
13493           FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg0), idx, field, value)
13494             if (field == arg1)
13495               return value;
13496         }
13497       return NULL_TREE;
13498
13499     case COND_EXPR:
13500     case VEC_COND_EXPR:
13501       /* Pedantic ANSI C says that a conditional expression is never an lvalue,
13502          so all simple results must be passed through pedantic_non_lvalue.  */
13503       if (TREE_CODE (arg0) == INTEGER_CST)
13504         {
13505           tree unused_op = integer_zerop (arg0) ? op1 : op2;
13506           tem = integer_zerop (arg0) ? op2 : op1;
13507           /* Only optimize constant conditions when the selected branch
13508              has the same type as the COND_EXPR.  This avoids optimizing
13509              away "c ? x : throw", where the throw has a void type.
13510              Avoid throwing away that operand which contains label.  */
13511           if ((!TREE_SIDE_EFFECTS (unused_op)
13512                || !contains_label_p (unused_op))
13513               && (! VOID_TYPE_P (TREE_TYPE (tem))
13514                   || VOID_TYPE_P (type)))
13515             return pedantic_non_lvalue_loc (loc, tem);
13516           return NULL_TREE;
13517         }
13518       else if (TREE_CODE (arg0) == VECTOR_CST)
13519         {
13520           if ((TREE_CODE (arg1) == VECTOR_CST
13521                || TREE_CODE (arg1) == CONSTRUCTOR)
13522               && (TREE_CODE (arg2) == VECTOR_CST
13523                   || TREE_CODE (arg2) == CONSTRUCTOR))
13524             {
13525               unsigned int nelts = TYPE_VECTOR_SUBPARTS (type), i;
13526               unsigned char *sel = XALLOCAVEC (unsigned char, nelts);
13527               gcc_assert (nelts == VECTOR_CST_NELTS (arg0));
13528               for (i = 0; i < nelts; i++)
13529                 {
13530                   tree val = VECTOR_CST_ELT (arg0, i);
13531                   if (integer_all_onesp (val))
13532                     sel[i] = i;
13533                   else if (integer_zerop (val))
13534                     sel[i] = nelts + i;
13535                   else /* Currently unreachable.  */
13536                     return NULL_TREE;
13537                 }
13538               tree t = fold_vec_perm (type, arg1, arg2, sel);
13539               if (t != NULL_TREE)
13540                 return t;
13541             }
13542         }
13543
13544       /* If we have A op B ? A : C, we may be able to convert this to a
13545          simpler expression, depending on the operation and the values
13546          of B and C.  Signed zeros prevent all of these transformations,
13547          for reasons given above each one.
13548
13549          Also try swapping the arguments and inverting the conditional.  */
13550       if (COMPARISON_CLASS_P (arg0)
13551           && operand_equal_for_comparison_p (TREE_OPERAND (arg0, 0),
13552                                              arg1, TREE_OPERAND (arg0, 1))
13553           && !HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (arg1))))
13554         {
13555           tem = fold_cond_expr_with_comparison (loc, type, arg0, op1, op2);
13556           if (tem)
13557             return tem;
13558         }
13559
13560       if (COMPARISON_CLASS_P (arg0)
13561           && operand_equal_for_comparison_p (TREE_OPERAND (arg0, 0),
13562                                              op2,
13563                                              TREE_OPERAND (arg0, 1))
13564           && !HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (op2))))
13565         {
13566           location_t loc0 = expr_location_or (arg0, loc);
13567           tem = fold_invert_truthvalue (loc0, arg0);
13568           if (tem && COMPARISON_CLASS_P (tem))
13569             {
13570               tem = fold_cond_expr_with_comparison (loc, type, tem, op2, op1);
13571               if (tem)
13572                 return tem;
13573             }
13574         }
13575
13576       /* If the second operand is simpler than the third, swap them
13577          since that produces better jump optimization results.  */
13578       if (truth_value_p (TREE_CODE (arg0))
13579           && tree_swap_operands_p (op1, op2, false))
13580         {
13581           location_t loc0 = expr_location_or (arg0, loc);
13582           /* See if this can be inverted.  If it can't, possibly because
13583              it was a floating-point inequality comparison, don't do
13584              anything.  */
13585           tem = fold_invert_truthvalue (loc0, arg0);
13586           if (tem)
13587             return fold_build3_loc (loc, code, type, tem, op2, op1);
13588         }
13589
13590       /* Convert A ? 1 : 0 to simply A.  */
13591       if ((code == VEC_COND_EXPR ? integer_all_onesp (op1)
13592                                  : (integer_onep (op1)
13593                                     && !VECTOR_TYPE_P (type)))
13594           && integer_zerop (op2)
13595           /* If we try to convert OP0 to our type, the
13596              call to fold will try to move the conversion inside
13597              a COND, which will recurse.  In that case, the COND_EXPR
13598              is probably the best choice, so leave it alone.  */
13599           && type == TREE_TYPE (arg0))
13600         return pedantic_non_lvalue_loc (loc, arg0);
13601
13602       /* Convert A ? 0 : 1 to !A.  This prefers the use of NOT_EXPR
13603          over COND_EXPR in cases such as floating point comparisons.  */
13604       if (integer_zerop (op1)
13605           && (code == VEC_COND_EXPR ? integer_all_onesp (op2)
13606                                     : (integer_onep (op2)
13607                                        && !VECTOR_TYPE_P (type)))
13608           && truth_value_p (TREE_CODE (arg0)))
13609         return pedantic_non_lvalue_loc (loc,
13610                                     fold_convert_loc (loc, type,
13611                                               invert_truthvalue_loc (loc,
13612                                                                      arg0)));
13613
13614       /* A < 0 ? <sign bit of A> : 0 is simply (A & <sign bit of A>).  */
13615       if (TREE_CODE (arg0) == LT_EXPR
13616           && integer_zerop (TREE_OPERAND (arg0, 1))
13617           && integer_zerop (op2)
13618           && (tem = sign_bit_p (TREE_OPERAND (arg0, 0), arg1)))
13619         {
13620           /* sign_bit_p looks through both zero and sign extensions,
13621              but for this optimization only sign extensions are
13622              usable.  */
13623           tree tem2 = TREE_OPERAND (arg0, 0);
13624           while (tem != tem2)
13625             {
13626               if (TREE_CODE (tem2) != NOP_EXPR
13627                   || TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (tem2, 0))))
13628                 {
13629                   tem = NULL_TREE;
13630                   break;
13631                 }
13632               tem2 = TREE_OPERAND (tem2, 0);
13633             }
13634           /* sign_bit_p only checks ARG1 bits within A's precision.
13635              If <sign bit of A> has wider type than A, bits outside
13636              of A's precision in <sign bit of A> need to be checked.
13637              If they are all 0, this optimization needs to be done
13638              in unsigned A's type, if they are all 1 in signed A's type,
13639              otherwise this can't be done.  */
13640           if (tem
13641               && TYPE_PRECISION (TREE_TYPE (tem))
13642                  < TYPE_PRECISION (TREE_TYPE (arg1))
13643               && TYPE_PRECISION (TREE_TYPE (tem))
13644                  < TYPE_PRECISION (type))
13645             {
13646               int inner_width, outer_width;
13647               tree tem_type;
13648
13649               inner_width = TYPE_PRECISION (TREE_TYPE (tem));
13650               outer_width = TYPE_PRECISION (TREE_TYPE (arg1));
13651               if (outer_width > TYPE_PRECISION (type))
13652                 outer_width = TYPE_PRECISION (type);
13653
13654               wide_int mask = wi::shifted_mask
13655                 (inner_width, outer_width - inner_width, false,
13656                  TYPE_PRECISION (TREE_TYPE (arg1)));
13657
13658               wide_int common = mask & arg1;
13659               if (common == mask)
13660                 {
13661                   tem_type = signed_type_for (TREE_TYPE (tem));
13662                   tem = fold_convert_loc (loc, tem_type, tem);
13663                 }
13664               else if (common == 0)
13665                 {
13666                   tem_type = unsigned_type_for (TREE_TYPE (tem));
13667                   tem = fold_convert_loc (loc, tem_type, tem);
13668                 }
13669               else
13670                 tem = NULL;
13671             }
13672
13673           if (tem)
13674             return
13675               fold_convert_loc (loc, type,
13676                                 fold_build2_loc (loc, BIT_AND_EXPR,
13677                                              TREE_TYPE (tem), tem,
13678                                              fold_convert_loc (loc,
13679                                                                TREE_TYPE (tem),
13680                                                                arg1)));
13681         }
13682
13683       /* (A >> N) & 1 ? (1 << N) : 0 is simply A & (1 << N).  A & 1 was
13684          already handled above.  */
13685       if (TREE_CODE (arg0) == BIT_AND_EXPR
13686           && integer_onep (TREE_OPERAND (arg0, 1))
13687           && integer_zerop (op2)
13688           && integer_pow2p (arg1))
13689         {
13690           tree tem = TREE_OPERAND (arg0, 0);
13691           STRIP_NOPS (tem);
13692           if (TREE_CODE (tem) == RSHIFT_EXPR
13693               && tree_fits_uhwi_p (TREE_OPERAND (tem, 1))
13694               && (unsigned HOST_WIDE_INT) tree_log2 (arg1) ==
13695                  tree_to_uhwi (TREE_OPERAND (tem, 1)))
13696             return fold_build2_loc (loc, BIT_AND_EXPR, type,
13697                                 TREE_OPERAND (tem, 0), arg1);
13698         }
13699
13700       /* A & N ? N : 0 is simply A & N if N is a power of two.  This
13701          is probably obsolete because the first operand should be a
13702          truth value (that's why we have the two cases above), but let's
13703          leave it in until we can confirm this for all front-ends.  */
13704       if (integer_zerop (op2)
13705           && TREE_CODE (arg0) == NE_EXPR
13706           && integer_zerop (TREE_OPERAND (arg0, 1))
13707           && integer_pow2p (arg1)
13708           && TREE_CODE (TREE_OPERAND (arg0, 0)) == BIT_AND_EXPR
13709           && operand_equal_p (TREE_OPERAND (TREE_OPERAND (arg0, 0), 1),
13710                               arg1, OEP_ONLY_CONST))
13711         return pedantic_non_lvalue_loc (loc,
13712                                     fold_convert_loc (loc, type,
13713                                                       TREE_OPERAND (arg0, 0)));
13714
13715       /* Disable the transformations below for vectors, since
13716          fold_binary_op_with_conditional_arg may undo them immediately,
13717          yielding an infinite loop.  */
13718       if (code == VEC_COND_EXPR)
13719         return NULL_TREE;
13720
13721       /* Convert A ? B : 0 into A && B if A and B are truth values.  */
13722       if (integer_zerop (op2)
13723           && truth_value_p (TREE_CODE (arg0))
13724           && truth_value_p (TREE_CODE (arg1))
13725           && (code == VEC_COND_EXPR || !VECTOR_TYPE_P (type)))
13726         return fold_build2_loc (loc, code == VEC_COND_EXPR ? BIT_AND_EXPR
13727                                                            : TRUTH_ANDIF_EXPR,
13728                                 type, fold_convert_loc (loc, type, arg0), arg1);
13729
13730       /* Convert A ? B : 1 into !A || B if A and B are truth values.  */
13731       if (code == VEC_COND_EXPR ? integer_all_onesp (op2) : integer_onep (op2)
13732           && truth_value_p (TREE_CODE (arg0))
13733           && truth_value_p (TREE_CODE (arg1))
13734           && (code == VEC_COND_EXPR || !VECTOR_TYPE_P (type)))
13735         {
13736           location_t loc0 = expr_location_or (arg0, loc);
13737           /* Only perform transformation if ARG0 is easily inverted.  */
13738           tem = fold_invert_truthvalue (loc0, arg0);
13739           if (tem)
13740             return fold_build2_loc (loc, code == VEC_COND_EXPR
13741                                          ? BIT_IOR_EXPR
13742                                          : TRUTH_ORIF_EXPR,
13743                                     type, fold_convert_loc (loc, type, tem),
13744                                     arg1);
13745         }
13746
13747       /* Convert A ? 0 : B into !A && B if A and B are truth values.  */
13748       if (integer_zerop (arg1)
13749           && truth_value_p (TREE_CODE (arg0))
13750           && truth_value_p (TREE_CODE (op2))
13751           && (code == VEC_COND_EXPR || !VECTOR_TYPE_P (type)))
13752         {
13753           location_t loc0 = expr_location_or (arg0, loc);
13754           /* Only perform transformation if ARG0 is easily inverted.  */
13755           tem = fold_invert_truthvalue (loc0, arg0);
13756           if (tem)
13757             return fold_build2_loc (loc, code == VEC_COND_EXPR
13758                                          ? BIT_AND_EXPR : TRUTH_ANDIF_EXPR,
13759                                     type, fold_convert_loc (loc, type, tem),
13760                                     op2);
13761         }
13762
13763       /* Convert A ? 1 : B into A || B if A and B are truth values.  */
13764       if (code == VEC_COND_EXPR ? integer_all_onesp (arg1) : integer_onep (arg1)
13765           && truth_value_p (TREE_CODE (arg0))
13766           && truth_value_p (TREE_CODE (op2))
13767           && (code == VEC_COND_EXPR || !VECTOR_TYPE_P (type)))
13768         return fold_build2_loc (loc, code == VEC_COND_EXPR
13769                                      ? BIT_IOR_EXPR : TRUTH_ORIF_EXPR,
13770                                 type, fold_convert_loc (loc, type, arg0), op2);
13771
13772       return NULL_TREE;
13773
13774     case CALL_EXPR:
13775       /* CALL_EXPRs used to be ternary exprs.  Catch any mistaken uses
13776          of fold_ternary on them.  */
13777       gcc_unreachable ();
13778
13779     case BIT_FIELD_REF:
13780       if ((TREE_CODE (arg0) == VECTOR_CST
13781            || (TREE_CODE (arg0) == CONSTRUCTOR
13782                && TREE_CODE (TREE_TYPE (arg0)) == VECTOR_TYPE))
13783           && (type == TREE_TYPE (TREE_TYPE (arg0))
13784               || (TREE_CODE (type) == VECTOR_TYPE
13785                   && TREE_TYPE (type) == TREE_TYPE (TREE_TYPE (arg0)))))
13786         {
13787           tree eltype = TREE_TYPE (TREE_TYPE (arg0));
13788           unsigned HOST_WIDE_INT width = tree_to_uhwi (TYPE_SIZE (eltype));
13789           unsigned HOST_WIDE_INT n = tree_to_uhwi (arg1);
13790           unsigned HOST_WIDE_INT idx = tree_to_uhwi (op2);
13791
13792           if (n != 0
13793               && (idx % width) == 0
13794               && (n % width) == 0
13795               && ((idx + n) / width) <= TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0)))
13796             {
13797               idx = idx / width;
13798               n = n / width;
13799
13800               if (TREE_CODE (arg0) == VECTOR_CST)
13801                 {
13802                   if (n == 1)
13803                     return VECTOR_CST_ELT (arg0, idx);
13804
13805                   tree *vals = XALLOCAVEC (tree, n);
13806                   for (unsigned i = 0; i < n; ++i)
13807                     vals[i] = VECTOR_CST_ELT (arg0, idx + i);
13808                   return build_vector (type, vals);
13809                 }
13810
13811               /* Constructor elements can be subvectors.  */
13812               unsigned HOST_WIDE_INT k = 1;
13813               if (CONSTRUCTOR_NELTS (arg0) != 0)
13814                 {
13815                   tree cons_elem = TREE_TYPE (CONSTRUCTOR_ELT (arg0, 0)->value);
13816                   if (TREE_CODE (cons_elem) == VECTOR_TYPE)
13817                     k = TYPE_VECTOR_SUBPARTS (cons_elem);
13818                 }
13819
13820               /* We keep an exact subset of the constructor elements.  */
13821               if ((idx % k) == 0 && (n % k) == 0)
13822                 {
13823                   if (CONSTRUCTOR_NELTS (arg0) == 0)
13824                     return build_constructor (type, NULL);
13825                   idx /= k;
13826                   n /= k;
13827                   if (n == 1)
13828                     {
13829                       if (idx < CONSTRUCTOR_NELTS (arg0))
13830                         return CONSTRUCTOR_ELT (arg0, idx)->value;
13831                       return build_zero_cst (type);
13832                     }
13833
13834                   vec<constructor_elt, va_gc> *vals;
13835                   vec_alloc (vals, n);
13836                   for (unsigned i = 0;
13837                        i < n && idx + i < CONSTRUCTOR_NELTS (arg0);
13838                        ++i)
13839                     CONSTRUCTOR_APPEND_ELT (vals, NULL_TREE,
13840                                             CONSTRUCTOR_ELT
13841                                               (arg0, idx + i)->value);
13842                   return build_constructor (type, vals);
13843                 }
13844               /* The bitfield references a single constructor element.  */
13845               else if (idx + n <= (idx / k + 1) * k)
13846                 {
13847                   if (CONSTRUCTOR_NELTS (arg0) <= idx / k)
13848                     return build_zero_cst (type);
13849                   else if (n == k)
13850                     return CONSTRUCTOR_ELT (arg0, idx / k)->value;
13851                   else
13852                     return fold_build3_loc (loc, code, type,
13853                       CONSTRUCTOR_ELT (arg0, idx / k)->value, op1,
13854                       build_int_cst (TREE_TYPE (op2), (idx % k) * width));
13855                 }
13856             }
13857         }
13858
13859       /* A bit-field-ref that referenced the full argument can be stripped.  */
13860       if (INTEGRAL_TYPE_P (TREE_TYPE (arg0))
13861           && TYPE_PRECISION (TREE_TYPE (arg0)) == tree_to_uhwi (arg1)
13862           && integer_zerop (op2))
13863         return fold_convert_loc (loc, type, arg0);
13864
13865       /* On constants we can use native encode/interpret to constant
13866          fold (nearly) all BIT_FIELD_REFs.  */
13867       if (CONSTANT_CLASS_P (arg0)
13868           && can_native_interpret_type_p (type)
13869           && tree_fits_uhwi_p (TYPE_SIZE_UNIT (TREE_TYPE (arg0)))
13870           /* This limitation should not be necessary, we just need to
13871              round this up to mode size.  */
13872           && tree_to_uhwi (op1) % BITS_PER_UNIT == 0
13873           /* Need bit-shifting of the buffer to relax the following.  */
13874           && tree_to_uhwi (op2) % BITS_PER_UNIT == 0)
13875         {
13876           unsigned HOST_WIDE_INT bitpos = tree_to_uhwi (op2);
13877           unsigned HOST_WIDE_INT bitsize = tree_to_uhwi (op1);
13878           unsigned HOST_WIDE_INT clen;
13879           clen = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (arg0)));
13880           /* ???  We cannot tell native_encode_expr to start at
13881              some random byte only.  So limit us to a reasonable amount
13882              of work.  */
13883           if (clen <= 4096)
13884             {
13885               unsigned char *b = XALLOCAVEC (unsigned char, clen);
13886               unsigned HOST_WIDE_INT len = native_encode_expr (arg0, b, clen);
13887               if (len > 0
13888                   && len * BITS_PER_UNIT >= bitpos + bitsize)
13889                 {
13890                   tree v = native_interpret_expr (type,
13891                                                   b + bitpos / BITS_PER_UNIT,
13892                                                   bitsize / BITS_PER_UNIT);
13893                   if (v)
13894                     return v;
13895                 }
13896             }
13897         }
13898
13899       return NULL_TREE;
13900
13901     case FMA_EXPR:
13902       /* For integers we can decompose the FMA if possible.  */
13903       if (TREE_CODE (arg0) == INTEGER_CST
13904           && TREE_CODE (arg1) == INTEGER_CST)
13905         return fold_build2_loc (loc, PLUS_EXPR, type,
13906                                 const_binop (MULT_EXPR, arg0, arg1), arg2);
13907       if (integer_zerop (arg2))
13908         return fold_build2_loc (loc, MULT_EXPR, type, arg0, arg1);
13909
13910       return fold_fma (loc, type, arg0, arg1, arg2);
13911
13912     case VEC_PERM_EXPR:
13913       if (TREE_CODE (arg2) == VECTOR_CST)
13914         {
13915           unsigned int nelts = TYPE_VECTOR_SUBPARTS (type), i, mask, mask2;
13916           unsigned char *sel = XALLOCAVEC (unsigned char, 2 * nelts);
13917           unsigned char *sel2 = sel + nelts;
13918           bool need_mask_canon = false;
13919           bool need_mask_canon2 = false;
13920           bool all_in_vec0 = true;
13921           bool all_in_vec1 = true;
13922           bool maybe_identity = true;
13923           bool single_arg = (op0 == op1);
13924           bool changed = false;
13925
13926           mask2 = 2 * nelts - 1;
13927           mask = single_arg ? (nelts - 1) : mask2;
13928           gcc_assert (nelts == VECTOR_CST_NELTS (arg2));
13929           for (i = 0; i < nelts; i++)
13930             {
13931               tree val = VECTOR_CST_ELT (arg2, i);
13932               if (TREE_CODE (val) != INTEGER_CST)
13933                 return NULL_TREE;
13934
13935               /* Make sure that the perm value is in an acceptable
13936                  range.  */
13937               wide_int t = val;
13938               need_mask_canon |= wi::gtu_p (t, mask);
13939               need_mask_canon2 |= wi::gtu_p (t, mask2);
13940               sel[i] = t.to_uhwi () & mask;
13941               sel2[i] = t.to_uhwi () & mask2;
13942
13943               if (sel[i] < nelts)
13944                 all_in_vec1 = false;
13945               else
13946                 all_in_vec0 = false;
13947
13948               if ((sel[i] & (nelts-1)) != i)
13949                 maybe_identity = false;
13950             }
13951
13952           if (maybe_identity)
13953             {
13954               if (all_in_vec0)
13955                 return op0;
13956               if (all_in_vec1)
13957                 return op1;
13958             }
13959
13960           if (all_in_vec0)
13961             op1 = op0;
13962           else if (all_in_vec1)
13963             {
13964               op0 = op1;
13965               for (i = 0; i < nelts; i++)
13966                 sel[i] -= nelts;
13967               need_mask_canon = true;
13968             }
13969
13970           if ((TREE_CODE (op0) == VECTOR_CST
13971                || TREE_CODE (op0) == CONSTRUCTOR)
13972               && (TREE_CODE (op1) == VECTOR_CST
13973                   || TREE_CODE (op1) == CONSTRUCTOR))
13974             {
13975               tree t = fold_vec_perm (type, op0, op1, sel);
13976               if (t != NULL_TREE)
13977                 return t;
13978             }
13979
13980           if (op0 == op1 && !single_arg)
13981             changed = true;
13982
13983           /* Some targets are deficient and fail to expand a single
13984              argument permutation while still allowing an equivalent
13985              2-argument version.  */
13986           if (need_mask_canon && arg2 == op2
13987               && !can_vec_perm_p (TYPE_MODE (type), false, sel)
13988               && can_vec_perm_p (TYPE_MODE (type), false, sel2))
13989             {
13990               need_mask_canon = need_mask_canon2;
13991               sel = sel2;
13992             }
13993
13994           if (need_mask_canon && arg2 == op2)
13995             {
13996               tree *tsel = XALLOCAVEC (tree, nelts);
13997               tree eltype = TREE_TYPE (TREE_TYPE (arg2));
13998               for (i = 0; i < nelts; i++)
13999                 tsel[i] = build_int_cst (eltype, sel[i]);
14000               op2 = build_vector (TREE_TYPE (arg2), tsel);
14001               changed = true;
14002             }
14003
14004           if (changed)
14005             return build3_loc (loc, VEC_PERM_EXPR, type, op0, op1, op2);
14006         }
14007       return NULL_TREE;
14008
14009     default:
14010       return NULL_TREE;
14011     } /* switch (code) */
14012 }
14013
14014 /* Perform constant folding and related simplification of EXPR.
14015    The related simplifications include x*1 => x, x*0 => 0, etc.,
14016    and application of the associative law.
14017    NOP_EXPR conversions may be removed freely (as long as we
14018    are careful not to change the type of the overall expression).
14019    We cannot simplify through a CONVERT_EXPR, FIX_EXPR or FLOAT_EXPR,
14020    but we can constant-fold them if they have constant operands.  */
14021
14022 #ifdef ENABLE_FOLD_CHECKING
14023 # define fold(x) fold_1 (x)
14024 static tree fold_1 (tree);
14025 static
14026 #endif
14027 tree
14028 fold (tree expr)
14029 {
14030   const tree t = expr;
14031   enum tree_code code = TREE_CODE (t);
14032   enum tree_code_class kind = TREE_CODE_CLASS (code);
14033   tree tem;
14034   location_t loc = EXPR_LOCATION (expr);
14035
14036   /* Return right away if a constant.  */
14037   if (kind == tcc_constant)
14038     return t;
14039
14040   /* CALL_EXPR-like objects with variable numbers of operands are
14041      treated specially.  */
14042   if (kind == tcc_vl_exp)
14043     {
14044       if (code == CALL_EXPR)
14045         {
14046           tem = fold_call_expr (loc, expr, false);
14047           return tem ? tem : expr;
14048         }
14049       return expr;
14050     }
14051
14052   if (IS_EXPR_CODE_CLASS (kind))
14053     {
14054       tree type = TREE_TYPE (t);
14055       tree op0, op1, op2;
14056
14057       switch (TREE_CODE_LENGTH (code))
14058         {
14059         case 1:
14060           op0 = TREE_OPERAND (t, 0);
14061           tem = fold_unary_loc (loc, code, type, op0);
14062           return tem ? tem : expr;
14063         case 2:
14064           op0 = TREE_OPERAND (t, 0);
14065           op1 = TREE_OPERAND (t, 1);
14066           tem = fold_binary_loc (loc, code, type, op0, op1);
14067           return tem ? tem : expr;
14068         case 3:
14069           op0 = TREE_OPERAND (t, 0);
14070           op1 = TREE_OPERAND (t, 1);
14071           op2 = TREE_OPERAND (t, 2);
14072           tem = fold_ternary_loc (loc, code, type, op0, op1, op2);
14073           return tem ? tem : expr;
14074         default:
14075           break;
14076         }
14077     }
14078
14079   switch (code)
14080     {
14081     case ARRAY_REF:
14082       {
14083         tree op0 = TREE_OPERAND (t, 0);
14084         tree op1 = TREE_OPERAND (t, 1);
14085
14086         if (TREE_CODE (op1) == INTEGER_CST
14087             && TREE_CODE (op0) == CONSTRUCTOR
14088             && ! type_contains_placeholder_p (TREE_TYPE (op0)))
14089           {
14090             vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (op0);
14091             unsigned HOST_WIDE_INT end = vec_safe_length (elts);
14092             unsigned HOST_WIDE_INT begin = 0;
14093
14094             /* Find a matching index by means of a binary search.  */
14095             while (begin != end)
14096               {
14097                 unsigned HOST_WIDE_INT middle = (begin + end) / 2;
14098                 tree index = (*elts)[middle].index;
14099
14100                 if (TREE_CODE (index) == INTEGER_CST
14101                     && tree_int_cst_lt (index, op1))
14102                   begin = middle + 1;
14103                 else if (TREE_CODE (index) == INTEGER_CST
14104                          && tree_int_cst_lt (op1, index))
14105                   end = middle;
14106                 else if (TREE_CODE (index) == RANGE_EXPR
14107                          && tree_int_cst_lt (TREE_OPERAND (index, 1), op1))
14108                   begin = middle + 1;
14109                 else if (TREE_CODE (index) == RANGE_EXPR
14110                          && tree_int_cst_lt (op1, TREE_OPERAND (index, 0)))
14111                   end = middle;
14112                 else
14113                   return (*elts)[middle].value;
14114               }
14115           }
14116
14117         return t;
14118       }
14119
14120       /* Return a VECTOR_CST if possible.  */
14121     case CONSTRUCTOR:
14122       {
14123         tree type = TREE_TYPE (t);
14124         if (TREE_CODE (type) != VECTOR_TYPE)
14125           return t;
14126
14127         tree *vec = XALLOCAVEC (tree, TYPE_VECTOR_SUBPARTS (type));
14128         unsigned HOST_WIDE_INT idx, pos = 0;
14129         tree value;
14130
14131         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (t), idx, value)
14132           {
14133             if (!CONSTANT_CLASS_P (value))
14134               return t;
14135             if (TREE_CODE (value) == VECTOR_CST)
14136               {
14137                 for (unsigned i = 0; i < VECTOR_CST_NELTS (value); ++i)
14138                   vec[pos++] = VECTOR_CST_ELT (value, i);
14139               }
14140             else
14141               vec[pos++] = value;
14142           }
14143         for (; pos < TYPE_VECTOR_SUBPARTS (type); ++pos)
14144           vec[pos] = build_zero_cst (TREE_TYPE (type));
14145
14146         return build_vector (type, vec);
14147       }
14148
14149     case CONST_DECL:
14150       return fold (DECL_INITIAL (t));
14151
14152     default:
14153       return t;
14154     } /* switch (code) */
14155 }
14156
14157 #ifdef ENABLE_FOLD_CHECKING
14158 #undef fold
14159
14160 static void fold_checksum_tree (const_tree, struct md5_ctx *,
14161                                 hash_table<pointer_hash<const tree_node> > *);
14162 static void fold_check_failed (const_tree, const_tree);
14163 void print_fold_checksum (const_tree);
14164
14165 /* When --enable-checking=fold, compute a digest of expr before
14166    and after actual fold call to see if fold did not accidentally
14167    change original expr.  */
14168
14169 tree
14170 fold (tree expr)
14171 {
14172   tree ret;
14173   struct md5_ctx ctx;
14174   unsigned char checksum_before[16], checksum_after[16];
14175   hash_table<pointer_hash<const tree_node> > ht (32);
14176
14177   md5_init_ctx (&ctx);
14178   fold_checksum_tree (expr, &ctx, &ht);
14179   md5_finish_ctx (&ctx, checksum_before);
14180   ht.empty ();
14181
14182   ret = fold_1 (expr);
14183
14184   md5_init_ctx (&ctx);
14185   fold_checksum_tree (expr, &ctx, &ht);
14186   md5_finish_ctx (&ctx, checksum_after);
14187
14188   if (memcmp (checksum_before, checksum_after, 16))
14189     fold_check_failed (expr, ret);
14190
14191   return ret;
14192 }
14193
14194 void
14195 print_fold_checksum (const_tree expr)
14196 {
14197   struct md5_ctx ctx;
14198   unsigned char checksum[16], cnt;
14199   hash_table<pointer_hash<const tree_node> > ht (32);
14200
14201   md5_init_ctx (&ctx);
14202   fold_checksum_tree (expr, &ctx, &ht);
14203   md5_finish_ctx (&ctx, checksum);
14204   for (cnt = 0; cnt < 16; ++cnt)
14205     fprintf (stderr, "%02x", checksum[cnt]);
14206   putc ('\n', stderr);
14207 }
14208
14209 static void
14210 fold_check_failed (const_tree expr ATTRIBUTE_UNUSED, const_tree ret ATTRIBUTE_UNUSED)
14211 {
14212   internal_error ("fold check: original tree changed by fold");
14213 }
14214
14215 static void
14216 fold_checksum_tree (const_tree expr, struct md5_ctx *ctx,
14217                     hash_table<pointer_hash <const tree_node> > *ht)
14218 {
14219   const tree_node **slot;
14220   enum tree_code code;
14221   union tree_node buf;
14222   int i, len;
14223
14224  recursive_label:
14225   if (expr == NULL)
14226     return;
14227   slot = ht->find_slot (expr, INSERT);
14228   if (*slot != NULL)
14229     return;
14230   *slot = expr;
14231   code = TREE_CODE (expr);
14232   if (TREE_CODE_CLASS (code) == tcc_declaration
14233       && DECL_ASSEMBLER_NAME_SET_P (expr))
14234     {
14235       /* Allow DECL_ASSEMBLER_NAME to be modified.  */
14236       memcpy ((char *) &buf, expr, tree_size (expr));
14237       SET_DECL_ASSEMBLER_NAME ((tree)&buf, NULL);
14238       expr = (tree) &buf;
14239     }
14240   else if (TREE_CODE_CLASS (code) == tcc_type
14241            && (TYPE_POINTER_TO (expr)
14242                || TYPE_REFERENCE_TO (expr)
14243                || TYPE_CACHED_VALUES_P (expr)
14244                || TYPE_CONTAINS_PLACEHOLDER_INTERNAL (expr)
14245                || TYPE_NEXT_VARIANT (expr)))
14246     {
14247       /* Allow these fields to be modified.  */
14248       tree tmp;
14249       memcpy ((char *) &buf, expr, tree_size (expr));
14250       expr = tmp = (tree) &buf;
14251       TYPE_CONTAINS_PLACEHOLDER_INTERNAL (tmp) = 0;
14252       TYPE_POINTER_TO (tmp) = NULL;
14253       TYPE_REFERENCE_TO (tmp) = NULL;
14254       TYPE_NEXT_VARIANT (tmp) = NULL;
14255       if (TYPE_CACHED_VALUES_P (tmp))
14256         {
14257           TYPE_CACHED_VALUES_P (tmp) = 0;
14258           TYPE_CACHED_VALUES (tmp) = NULL;
14259         }
14260     }
14261   md5_process_bytes (expr, tree_size (expr), ctx);
14262   if (CODE_CONTAINS_STRUCT (code, TS_TYPED))
14263     fold_checksum_tree (TREE_TYPE (expr), ctx, ht);
14264   if (TREE_CODE_CLASS (code) != tcc_type
14265       && TREE_CODE_CLASS (code) != tcc_declaration
14266       && code != TREE_LIST
14267       && code != SSA_NAME
14268       && CODE_CONTAINS_STRUCT (code, TS_COMMON))
14269     fold_checksum_tree (TREE_CHAIN (expr), ctx, ht);
14270   switch (TREE_CODE_CLASS (code))
14271     {
14272     case tcc_constant:
14273       switch (code)
14274         {
14275         case STRING_CST:
14276           md5_process_bytes (TREE_STRING_POINTER (expr),
14277                              TREE_STRING_LENGTH (expr), ctx);
14278           break;
14279         case COMPLEX_CST:
14280           fold_checksum_tree (TREE_REALPART (expr), ctx, ht);
14281           fold_checksum_tree (TREE_IMAGPART (expr), ctx, ht);
14282           break;
14283         case VECTOR_CST:
14284           for (i = 0; i < (int) VECTOR_CST_NELTS (expr); ++i)
14285             fold_checksum_tree (VECTOR_CST_ELT (expr, i), ctx, ht);
14286           break;
14287         default:
14288           break;
14289         }
14290       break;
14291     case tcc_exceptional:
14292       switch (code)
14293         {
14294         case TREE_LIST:
14295           fold_checksum_tree (TREE_PURPOSE (expr), ctx, ht);
14296           fold_checksum_tree (TREE_VALUE (expr), ctx, ht);
14297           expr = TREE_CHAIN (expr);
14298           goto recursive_label;
14299           break;
14300         case TREE_VEC:
14301           for (i = 0; i < TREE_VEC_LENGTH (expr); ++i)
14302             fold_checksum_tree (TREE_VEC_ELT (expr, i), ctx, ht);
14303           break;
14304         default:
14305           break;
14306         }
14307       break;
14308     case tcc_expression:
14309     case tcc_reference:
14310     case tcc_comparison:
14311     case tcc_unary:
14312     case tcc_binary:
14313     case tcc_statement:
14314     case tcc_vl_exp:
14315       len = TREE_OPERAND_LENGTH (expr);
14316       for (i = 0; i < len; ++i)
14317         fold_checksum_tree (TREE_OPERAND (expr, i), ctx, ht);
14318       break;
14319     case tcc_declaration:
14320       fold_checksum_tree (DECL_NAME (expr), ctx, ht);
14321       fold_checksum_tree (DECL_CONTEXT (expr), ctx, ht);
14322       if (CODE_CONTAINS_STRUCT (TREE_CODE (expr), TS_DECL_COMMON))
14323         {
14324           fold_checksum_tree (DECL_SIZE (expr), ctx, ht);
14325           fold_checksum_tree (DECL_SIZE_UNIT (expr), ctx, ht);
14326           fold_checksum_tree (DECL_INITIAL (expr), ctx, ht);
14327           fold_checksum_tree (DECL_ABSTRACT_ORIGIN (expr), ctx, ht);
14328           fold_checksum_tree (DECL_ATTRIBUTES (expr), ctx, ht);
14329         }
14330
14331       if (CODE_CONTAINS_STRUCT (TREE_CODE (expr), TS_DECL_NON_COMMON))
14332         {
14333           if (TREE_CODE (expr) == FUNCTION_DECL)
14334             {
14335               fold_checksum_tree (DECL_VINDEX (expr), ctx, ht);
14336               fold_checksum_tree (DECL_ARGUMENTS (expr), ctx, ht);
14337             }
14338           fold_checksum_tree (DECL_RESULT_FLD (expr), ctx, ht);
14339         }
14340       break;
14341     case tcc_type:
14342       if (TREE_CODE (expr) == ENUMERAL_TYPE)
14343         fold_checksum_tree (TYPE_VALUES (expr), ctx, ht);
14344       fold_checksum_tree (TYPE_SIZE (expr), ctx, ht);
14345       fold_checksum_tree (TYPE_SIZE_UNIT (expr), ctx, ht);
14346       fold_checksum_tree (TYPE_ATTRIBUTES (expr), ctx, ht);
14347       fold_checksum_tree (TYPE_NAME (expr), ctx, ht);
14348       if (INTEGRAL_TYPE_P (expr)
14349           || SCALAR_FLOAT_TYPE_P (expr))
14350         {
14351           fold_checksum_tree (TYPE_MIN_VALUE (expr), ctx, ht);
14352           fold_checksum_tree (TYPE_MAX_VALUE (expr), ctx, ht);
14353         }
14354       fold_checksum_tree (TYPE_MAIN_VARIANT (expr), ctx, ht);
14355       if (TREE_CODE (expr) == RECORD_TYPE
14356           || TREE_CODE (expr) == UNION_TYPE
14357           || TREE_CODE (expr) == QUAL_UNION_TYPE)
14358         fold_checksum_tree (TYPE_BINFO (expr), ctx, ht);
14359       fold_checksum_tree (TYPE_CONTEXT (expr), ctx, ht);
14360       break;
14361     default:
14362       break;
14363     }
14364 }
14365
14366 /* Helper function for outputting the checksum of a tree T.  When
14367    debugging with gdb, you can "define mynext" to be "next" followed
14368    by "call debug_fold_checksum (op0)", then just trace down till the
14369    outputs differ.  */
14370
14371 DEBUG_FUNCTION void
14372 debug_fold_checksum (const_tree t)
14373 {
14374   int i;
14375   unsigned char checksum[16];
14376   struct md5_ctx ctx;
14377   hash_table<pointer_hash<const tree_node> > ht (32);
14378
14379   md5_init_ctx (&ctx);
14380   fold_checksum_tree (t, &ctx, &ht);
14381   md5_finish_ctx (&ctx, checksum);
14382   ht.empty ();
14383
14384   for (i = 0; i < 16; i++)
14385     fprintf (stderr, "%d ", checksum[i]);
14386
14387   fprintf (stderr, "\n");
14388 }
14389
14390 #endif
14391
14392 /* Fold a unary tree expression with code CODE of type TYPE with an
14393    operand OP0.  LOC is the location of the resulting expression.
14394    Return a folded expression if successful.  Otherwise, return a tree
14395    expression with code CODE of type TYPE with an operand OP0.  */
14396
14397 tree
14398 fold_build1_stat_loc (location_t loc,
14399                       enum tree_code code, tree type, tree op0 MEM_STAT_DECL)
14400 {
14401   tree tem;
14402 #ifdef ENABLE_FOLD_CHECKING
14403   unsigned char checksum_before[16], checksum_after[16];
14404   struct md5_ctx ctx;
14405   hash_table<pointer_hash<const tree_node> > ht (32);
14406
14407   md5_init_ctx (&ctx);
14408   fold_checksum_tree (op0, &ctx, &ht);
14409   md5_finish_ctx (&ctx, checksum_before);
14410   ht.empty ();
14411 #endif
14412
14413   tem = fold_unary_loc (loc, code, type, op0);
14414   if (!tem)
14415     tem = build1_stat_loc (loc, code, type, op0 PASS_MEM_STAT);
14416
14417 #ifdef ENABLE_FOLD_CHECKING
14418   md5_init_ctx (&ctx);
14419   fold_checksum_tree (op0, &ctx, &ht);
14420   md5_finish_ctx (&ctx, checksum_after);
14421
14422   if (memcmp (checksum_before, checksum_after, 16))
14423     fold_check_failed (op0, tem);
14424 #endif
14425   return tem;
14426 }
14427
14428 /* Fold a binary tree expression with code CODE of type TYPE with
14429    operands OP0 and OP1.  LOC is the location of the resulting
14430    expression.  Return a folded expression if successful.  Otherwise,
14431    return a tree expression with code CODE of type TYPE with operands
14432    OP0 and OP1.  */
14433
14434 tree
14435 fold_build2_stat_loc (location_t loc,
14436                       enum tree_code code, tree type, tree op0, tree op1
14437                       MEM_STAT_DECL)
14438 {
14439   tree tem;
14440 #ifdef ENABLE_FOLD_CHECKING
14441   unsigned char checksum_before_op0[16],
14442                 checksum_before_op1[16],
14443                 checksum_after_op0[16],
14444                 checksum_after_op1[16];
14445   struct md5_ctx ctx;
14446   hash_table<pointer_hash<const tree_node> > ht (32);
14447
14448   md5_init_ctx (&ctx);
14449   fold_checksum_tree (op0, &ctx, &ht);
14450   md5_finish_ctx (&ctx, checksum_before_op0);
14451   ht.empty ();
14452
14453   md5_init_ctx (&ctx);
14454   fold_checksum_tree (op1, &ctx, &ht);
14455   md5_finish_ctx (&ctx, checksum_before_op1);
14456   ht.empty ();
14457 #endif
14458
14459   tem = fold_binary_loc (loc, code, type, op0, op1);
14460   if (!tem)
14461     tem = build2_stat_loc (loc, code, type, op0, op1 PASS_MEM_STAT);
14462
14463 #ifdef ENABLE_FOLD_CHECKING
14464   md5_init_ctx (&ctx);
14465   fold_checksum_tree (op0, &ctx, &ht);
14466   md5_finish_ctx (&ctx, checksum_after_op0);
14467   ht.empty ();
14468
14469   if (memcmp (checksum_before_op0, checksum_after_op0, 16))
14470     fold_check_failed (op0, tem);
14471
14472   md5_init_ctx (&ctx);
14473   fold_checksum_tree (op1, &ctx, &ht);
14474   md5_finish_ctx (&ctx, checksum_after_op1);
14475
14476   if (memcmp (checksum_before_op1, checksum_after_op1, 16))
14477     fold_check_failed (op1, tem);
14478 #endif
14479   return tem;
14480 }
14481
14482 /* Fold a ternary tree expression with code CODE of type TYPE with
14483    operands OP0, OP1, and OP2.  Return a folded expression if
14484    successful.  Otherwise, return a tree expression with code CODE of
14485    type TYPE with operands OP0, OP1, and OP2.  */
14486
14487 tree
14488 fold_build3_stat_loc (location_t loc, enum tree_code code, tree type,
14489                       tree op0, tree op1, tree op2 MEM_STAT_DECL)
14490 {
14491   tree tem;
14492 #ifdef ENABLE_FOLD_CHECKING
14493   unsigned char checksum_before_op0[16],
14494                 checksum_before_op1[16],
14495                 checksum_before_op2[16],
14496                 checksum_after_op0[16],
14497                 checksum_after_op1[16],
14498                 checksum_after_op2[16];
14499   struct md5_ctx ctx;
14500   hash_table<pointer_hash<const tree_node> > ht (32);
14501
14502   md5_init_ctx (&ctx);
14503   fold_checksum_tree (op0, &ctx, &ht);
14504   md5_finish_ctx (&ctx, checksum_before_op0);
14505   ht.empty ();
14506
14507   md5_init_ctx (&ctx);
14508   fold_checksum_tree (op1, &ctx, &ht);
14509   md5_finish_ctx (&ctx, checksum_before_op1);
14510   ht.empty ();
14511
14512   md5_init_ctx (&ctx);
14513   fold_checksum_tree (op2, &ctx, &ht);
14514   md5_finish_ctx (&ctx, checksum_before_op2);
14515   ht.empty ();
14516 #endif
14517
14518   gcc_assert (TREE_CODE_CLASS (code) != tcc_vl_exp);
14519   tem = fold_ternary_loc (loc, code, type, op0, op1, op2);
14520   if (!tem)
14521     tem = build3_stat_loc (loc, code, type, op0, op1, op2 PASS_MEM_STAT);
14522
14523 #ifdef ENABLE_FOLD_CHECKING
14524   md5_init_ctx (&ctx);
14525   fold_checksum_tree (op0, &ctx, &ht);
14526   md5_finish_ctx (&ctx, checksum_after_op0);
14527   ht.empty ();
14528
14529   if (memcmp (checksum_before_op0, checksum_after_op0, 16))
14530     fold_check_failed (op0, tem);
14531
14532   md5_init_ctx (&ctx);
14533   fold_checksum_tree (op1, &ctx, &ht);
14534   md5_finish_ctx (&ctx, checksum_after_op1);
14535   ht.empty ();
14536
14537   if (memcmp (checksum_before_op1, checksum_after_op1, 16))
14538     fold_check_failed (op1, tem);
14539
14540   md5_init_ctx (&ctx);
14541   fold_checksum_tree (op2, &ctx, &ht);
14542   md5_finish_ctx (&ctx, checksum_after_op2);
14543
14544   if (memcmp (checksum_before_op2, checksum_after_op2, 16))
14545     fold_check_failed (op2, tem);
14546 #endif
14547   return tem;
14548 }
14549
14550 /* Fold a CALL_EXPR expression of type TYPE with operands FN and NARGS
14551    arguments in ARGARRAY, and a null static chain.
14552    Return a folded expression if successful.  Otherwise, return a CALL_EXPR
14553    of type TYPE from the given operands as constructed by build_call_array.  */
14554
14555 tree
14556 fold_build_call_array_loc (location_t loc, tree type, tree fn,
14557                            int nargs, tree *argarray)
14558 {
14559   tree tem;
14560 #ifdef ENABLE_FOLD_CHECKING
14561   unsigned char checksum_before_fn[16],
14562                 checksum_before_arglist[16],
14563                 checksum_after_fn[16],
14564                 checksum_after_arglist[16];
14565   struct md5_ctx ctx;
14566   hash_table<pointer_hash<const tree_node> > ht (32);
14567   int i;
14568
14569   md5_init_ctx (&ctx);
14570   fold_checksum_tree (fn, &ctx, &ht);
14571   md5_finish_ctx (&ctx, checksum_before_fn);
14572   ht.empty ();
14573
14574   md5_init_ctx (&ctx);
14575   for (i = 0; i < nargs; i++)
14576     fold_checksum_tree (argarray[i], &ctx, &ht);
14577   md5_finish_ctx (&ctx, checksum_before_arglist);
14578   ht.empty ();
14579 #endif
14580
14581   tem = fold_builtin_call_array (loc, type, fn, nargs, argarray);
14582
14583 #ifdef ENABLE_FOLD_CHECKING
14584   md5_init_ctx (&ctx);
14585   fold_checksum_tree (fn, &ctx, &ht);
14586   md5_finish_ctx (&ctx, checksum_after_fn);
14587   ht.empty ();
14588
14589   if (memcmp (checksum_before_fn, checksum_after_fn, 16))
14590     fold_check_failed (fn, tem);
14591
14592   md5_init_ctx (&ctx);
14593   for (i = 0; i < nargs; i++)
14594     fold_checksum_tree (argarray[i], &ctx, &ht);
14595   md5_finish_ctx (&ctx, checksum_after_arglist);
14596
14597   if (memcmp (checksum_before_arglist, checksum_after_arglist, 16))
14598     fold_check_failed (NULL_TREE, tem);
14599 #endif
14600   return tem;
14601 }
14602
14603 /* Perform constant folding and related simplification of initializer
14604    expression EXPR.  These behave identically to "fold_buildN" but ignore
14605    potential run-time traps and exceptions that fold must preserve.  */
14606
14607 #define START_FOLD_INIT \
14608   int saved_signaling_nans = flag_signaling_nans;\
14609   int saved_trapping_math = flag_trapping_math;\
14610   int saved_rounding_math = flag_rounding_math;\
14611   int saved_trapv = flag_trapv;\
14612   int saved_folding_initializer = folding_initializer;\
14613   flag_signaling_nans = 0;\
14614   flag_trapping_math = 0;\
14615   flag_rounding_math = 0;\
14616   flag_trapv = 0;\
14617   folding_initializer = 1;
14618
14619 #define END_FOLD_INIT \
14620   flag_signaling_nans = saved_signaling_nans;\
14621   flag_trapping_math = saved_trapping_math;\
14622   flag_rounding_math = saved_rounding_math;\
14623   flag_trapv = saved_trapv;\
14624   folding_initializer = saved_folding_initializer;
14625
14626 tree
14627 fold_build1_initializer_loc (location_t loc, enum tree_code code,
14628                              tree type, tree op)
14629 {
14630   tree result;
14631   START_FOLD_INIT;
14632
14633   result = fold_build1_loc (loc, code, type, op);
14634
14635   END_FOLD_INIT;
14636   return result;
14637 }
14638
14639 tree
14640 fold_build2_initializer_loc (location_t loc, enum tree_code code,
14641                              tree type, tree op0, tree op1)
14642 {
14643   tree result;
14644   START_FOLD_INIT;
14645
14646   result = fold_build2_loc (loc, code, type, op0, op1);
14647
14648   END_FOLD_INIT;
14649   return result;
14650 }
14651
14652 tree
14653 fold_build_call_array_initializer_loc (location_t loc, tree type, tree fn,
14654                                        int nargs, tree *argarray)
14655 {
14656   tree result;
14657   START_FOLD_INIT;
14658
14659   result = fold_build_call_array_loc (loc, type, fn, nargs, argarray);
14660
14661   END_FOLD_INIT;
14662   return result;
14663 }
14664
14665 #undef START_FOLD_INIT
14666 #undef END_FOLD_INIT
14667
14668 /* Determine if first argument is a multiple of second argument.  Return 0 if
14669    it is not, or we cannot easily determined it to be.
14670
14671    An example of the sort of thing we care about (at this point; this routine
14672    could surely be made more general, and expanded to do what the *_DIV_EXPR's
14673    fold cases do now) is discovering that
14674
14675      SAVE_EXPR (I) * SAVE_EXPR (J * 8)
14676
14677    is a multiple of
14678
14679      SAVE_EXPR (J * 8)
14680
14681    when we know that the two SAVE_EXPR (J * 8) nodes are the same node.
14682
14683    This code also handles discovering that
14684
14685      SAVE_EXPR (I) * SAVE_EXPR (J * 8)
14686
14687    is a multiple of 8 so we don't have to worry about dealing with a
14688    possible remainder.
14689
14690    Note that we *look* inside a SAVE_EXPR only to determine how it was
14691    calculated; it is not safe for fold to do much of anything else with the
14692    internals of a SAVE_EXPR, since it cannot know when it will be evaluated
14693    at run time.  For example, the latter example above *cannot* be implemented
14694    as SAVE_EXPR (I) * J or any variant thereof, since the value of J at
14695    evaluation time of the original SAVE_EXPR is not necessarily the same at
14696    the time the new expression is evaluated.  The only optimization of this
14697    sort that would be valid is changing
14698
14699      SAVE_EXPR (I) * SAVE_EXPR (SAVE_EXPR (J) * 8)
14700
14701    divided by 8 to
14702
14703      SAVE_EXPR (I) * SAVE_EXPR (J)
14704
14705    (where the same SAVE_EXPR (J) is used in the original and the
14706    transformed version).  */
14707
14708 int
14709 multiple_of_p (tree type, const_tree top, const_tree bottom)
14710 {
14711   if (operand_equal_p (top, bottom, 0))
14712     return 1;
14713
14714   if (TREE_CODE (type) != INTEGER_TYPE)
14715     return 0;
14716
14717   switch (TREE_CODE (top))
14718     {
14719     case BIT_AND_EXPR:
14720       /* Bitwise and provides a power of two multiple.  If the mask is
14721          a multiple of BOTTOM then TOP is a multiple of BOTTOM.  */
14722       if (!integer_pow2p (bottom))
14723         return 0;
14724       /* FALLTHRU */
14725
14726     case MULT_EXPR:
14727       return (multiple_of_p (type, TREE_OPERAND (top, 0), bottom)
14728               || multiple_of_p (type, TREE_OPERAND (top, 1), bottom));
14729
14730     case PLUS_EXPR:
14731     case MINUS_EXPR:
14732       return (multiple_of_p (type, TREE_OPERAND (top, 0), bottom)
14733               && multiple_of_p (type, TREE_OPERAND (top, 1), bottom));
14734
14735     case LSHIFT_EXPR:
14736       if (TREE_CODE (TREE_OPERAND (top, 1)) == INTEGER_CST)
14737         {
14738           tree op1, t1;
14739
14740           op1 = TREE_OPERAND (top, 1);
14741           /* const_binop may not detect overflow correctly,
14742              so check for it explicitly here.  */
14743           if (wi::gtu_p (TYPE_PRECISION (TREE_TYPE (size_one_node)), op1)
14744               && 0 != (t1 = fold_convert (type,
14745                                           const_binop (LSHIFT_EXPR,
14746                                                        size_one_node,
14747                                                        op1)))
14748               && !TREE_OVERFLOW (t1))
14749             return multiple_of_p (type, t1, bottom);
14750         }
14751       return 0;
14752
14753     case NOP_EXPR:
14754       /* Can't handle conversions from non-integral or wider integral type.  */
14755       if ((TREE_CODE (TREE_TYPE (TREE_OPERAND (top, 0))) != INTEGER_TYPE)
14756           || (TYPE_PRECISION (type)
14757               < TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (top, 0)))))
14758         return 0;
14759
14760       /* .. fall through ...  */
14761
14762     case SAVE_EXPR:
14763       return multiple_of_p (type, TREE_OPERAND (top, 0), bottom);
14764
14765     case COND_EXPR:
14766       return (multiple_of_p (type, TREE_OPERAND (top, 1), bottom)
14767               && multiple_of_p (type, TREE_OPERAND (top, 2), bottom));
14768
14769     case INTEGER_CST:
14770       if (TREE_CODE (bottom) != INTEGER_CST
14771           || integer_zerop (bottom)
14772           || (TYPE_UNSIGNED (type)
14773               && (tree_int_cst_sgn (top) < 0
14774                   || tree_int_cst_sgn (bottom) < 0)))
14775         return 0;
14776       return wi::multiple_of_p (wi::to_widest (top), wi::to_widest (bottom),
14777                                 SIGNED);
14778
14779     default:
14780       return 0;
14781     }
14782 }
14783
14784 /* Return true if CODE or TYPE is known to be non-negative. */
14785
14786 static bool
14787 tree_simple_nonnegative_warnv_p (enum tree_code code, tree type)
14788 {
14789   if ((TYPE_PRECISION (type) != 1 || TYPE_UNSIGNED (type))
14790       && truth_value_p (code))
14791     /* Truth values evaluate to 0 or 1, which is nonnegative unless we
14792        have a signed:1 type (where the value is -1 and 0).  */
14793     return true;
14794   return false;
14795 }
14796
14797 /* Return true if (CODE OP0) is known to be non-negative.  If the return
14798    value is based on the assumption that signed overflow is undefined,
14799    set *STRICT_OVERFLOW_P to true; otherwise, don't change
14800    *STRICT_OVERFLOW_P.  */
14801
14802 bool
14803 tree_unary_nonnegative_warnv_p (enum tree_code code, tree type, tree op0,
14804                                 bool *strict_overflow_p)
14805 {
14806   if (TYPE_UNSIGNED (type))
14807     return true;
14808
14809   switch (code)
14810     {
14811     case ABS_EXPR:
14812       /* We can't return 1 if flag_wrapv is set because
14813          ABS_EXPR<INT_MIN> = INT_MIN.  */
14814       if (!INTEGRAL_TYPE_P (type))
14815         return true;
14816       if (TYPE_OVERFLOW_UNDEFINED (type))
14817         {
14818           *strict_overflow_p = true;
14819           return true;
14820         }
14821       break;
14822
14823     case NON_LVALUE_EXPR:
14824     case FLOAT_EXPR:
14825     case FIX_TRUNC_EXPR:
14826       return tree_expr_nonnegative_warnv_p (op0,
14827                                             strict_overflow_p);
14828
14829     case NOP_EXPR:
14830       {
14831         tree inner_type = TREE_TYPE (op0);
14832         tree outer_type = type;
14833
14834         if (TREE_CODE (outer_type) == REAL_TYPE)
14835           {
14836             if (TREE_CODE (inner_type) == REAL_TYPE)
14837               return tree_expr_nonnegative_warnv_p (op0,
14838                                                     strict_overflow_p);
14839             if (INTEGRAL_TYPE_P (inner_type))
14840               {
14841                 if (TYPE_UNSIGNED (inner_type))
14842                   return true;
14843                 return tree_expr_nonnegative_warnv_p (op0,
14844                                                       strict_overflow_p);
14845               }
14846           }
14847         else if (INTEGRAL_TYPE_P (outer_type))
14848           {
14849             if (TREE_CODE (inner_type) == REAL_TYPE)
14850               return tree_expr_nonnegative_warnv_p (op0,
14851                                                     strict_overflow_p);
14852             if (INTEGRAL_TYPE_P (inner_type))
14853               return TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type)
14854                       && TYPE_UNSIGNED (inner_type);
14855           }
14856       }
14857       break;
14858
14859     default:
14860       return tree_simple_nonnegative_warnv_p (code, type);
14861     }
14862
14863   /* We don't know sign of `t', so be conservative and return false.  */
14864   return false;
14865 }
14866
14867 /* Return true if (CODE OP0 OP1) is known to be non-negative.  If the return
14868    value is based on the assumption that signed overflow is undefined,
14869    set *STRICT_OVERFLOW_P to true; otherwise, don't change
14870    *STRICT_OVERFLOW_P.  */
14871
14872 bool
14873 tree_binary_nonnegative_warnv_p (enum tree_code code, tree type, tree op0,
14874                                       tree op1, bool *strict_overflow_p)
14875 {
14876   if (TYPE_UNSIGNED (type))
14877     return true;
14878
14879   switch (code)
14880     {
14881     case POINTER_PLUS_EXPR:
14882     case PLUS_EXPR:
14883       if (FLOAT_TYPE_P (type))
14884         return (tree_expr_nonnegative_warnv_p (op0,
14885                                                strict_overflow_p)
14886                 && tree_expr_nonnegative_warnv_p (op1,
14887                                                   strict_overflow_p));
14888
14889       /* zero_extend(x) + zero_extend(y) is non-negative if x and y are
14890          both unsigned and at least 2 bits shorter than the result.  */
14891       if (TREE_CODE (type) == INTEGER_TYPE
14892           && TREE_CODE (op0) == NOP_EXPR
14893           && TREE_CODE (op1) == NOP_EXPR)
14894         {
14895           tree inner1 = TREE_TYPE (TREE_OPERAND (op0, 0));
14896           tree inner2 = TREE_TYPE (TREE_OPERAND (op1, 0));
14897           if (TREE_CODE (inner1) == INTEGER_TYPE && TYPE_UNSIGNED (inner1)
14898               && TREE_CODE (inner2) == INTEGER_TYPE && TYPE_UNSIGNED (inner2))
14899             {
14900               unsigned int prec = MAX (TYPE_PRECISION (inner1),
14901                                        TYPE_PRECISION (inner2)) + 1;
14902               return prec < TYPE_PRECISION (type);
14903             }
14904         }
14905       break;
14906
14907     case MULT_EXPR:
14908       if (FLOAT_TYPE_P (type) || TYPE_OVERFLOW_UNDEFINED (type))
14909         {
14910           /* x * x is always non-negative for floating point x
14911              or without overflow.  */
14912           if (operand_equal_p (op0, op1, 0)
14913               || (tree_expr_nonnegative_warnv_p (op0, strict_overflow_p)
14914                   && tree_expr_nonnegative_warnv_p (op1, strict_overflow_p)))
14915             {
14916               if (TYPE_OVERFLOW_UNDEFINED (type))
14917                 *strict_overflow_p = true;
14918               return true;
14919             }
14920         }
14921
14922       /* zero_extend(x) * zero_extend(y) is non-negative if x and y are
14923          both unsigned and their total bits is shorter than the result.  */
14924       if (TREE_CODE (type) == INTEGER_TYPE
14925           && (TREE_CODE (op0) == NOP_EXPR || TREE_CODE (op0) == INTEGER_CST)
14926           && (TREE_CODE (op1) == NOP_EXPR || TREE_CODE (op1) == INTEGER_CST))
14927         {
14928           tree inner0 = (TREE_CODE (op0) == NOP_EXPR)
14929             ? TREE_TYPE (TREE_OPERAND (op0, 0))
14930             : TREE_TYPE (op0);
14931           tree inner1 = (TREE_CODE (op1) == NOP_EXPR)
14932             ? TREE_TYPE (TREE_OPERAND (op1, 0))
14933             : TREE_TYPE (op1);
14934
14935           bool unsigned0 = TYPE_UNSIGNED (inner0);
14936           bool unsigned1 = TYPE_UNSIGNED (inner1);
14937
14938           if (TREE_CODE (op0) == INTEGER_CST)
14939             unsigned0 = unsigned0 || tree_int_cst_sgn (op0) >= 0;
14940
14941           if (TREE_CODE (op1) == INTEGER_CST)
14942             unsigned1 = unsigned1 || tree_int_cst_sgn (op1) >= 0;
14943
14944           if (TREE_CODE (inner0) == INTEGER_TYPE && unsigned0
14945               && TREE_CODE (inner1) == INTEGER_TYPE && unsigned1)
14946             {
14947               unsigned int precision0 = (TREE_CODE (op0) == INTEGER_CST)
14948                 ? tree_int_cst_min_precision (op0, UNSIGNED)
14949                 : TYPE_PRECISION (inner0);
14950
14951               unsigned int precision1 = (TREE_CODE (op1) == INTEGER_CST)
14952                 ? tree_int_cst_min_precision (op1, UNSIGNED)
14953                 : TYPE_PRECISION (inner1);
14954
14955               return precision0 + precision1 < TYPE_PRECISION (type);
14956             }
14957         }
14958       return false;
14959
14960     case BIT_AND_EXPR:
14961     case MAX_EXPR:
14962       return (tree_expr_nonnegative_warnv_p (op0,
14963                                              strict_overflow_p)
14964               || tree_expr_nonnegative_warnv_p (op1,
14965                                                 strict_overflow_p));
14966
14967     case BIT_IOR_EXPR:
14968     case BIT_XOR_EXPR:
14969     case MIN_EXPR:
14970     case RDIV_EXPR:
14971     case TRUNC_DIV_EXPR:
14972     case CEIL_DIV_EXPR:
14973     case FLOOR_DIV_EXPR:
14974     case ROUND_DIV_EXPR:
14975       return (tree_expr_nonnegative_warnv_p (op0,
14976                                              strict_overflow_p)
14977               && tree_expr_nonnegative_warnv_p (op1,
14978                                                 strict_overflow_p));
14979
14980     case TRUNC_MOD_EXPR:
14981     case CEIL_MOD_EXPR:
14982     case FLOOR_MOD_EXPR:
14983     case ROUND_MOD_EXPR:
14984       return tree_expr_nonnegative_warnv_p (op0,
14985                                             strict_overflow_p);
14986     default:
14987       return tree_simple_nonnegative_warnv_p (code, type);
14988     }
14989
14990   /* We don't know sign of `t', so be conservative and return false.  */
14991   return false;
14992 }
14993
14994 /* Return true if T is known to be non-negative.  If the return
14995    value is based on the assumption that signed overflow is undefined,
14996    set *STRICT_OVERFLOW_P to true; otherwise, don't change
14997    *STRICT_OVERFLOW_P.  */
14998
14999 bool
15000 tree_single_nonnegative_warnv_p (tree t, bool *strict_overflow_p)
15001 {
15002   if (TYPE_UNSIGNED (TREE_TYPE (t)))
15003     return true;
15004
15005   switch (TREE_CODE (t))
15006     {
15007     case INTEGER_CST:
15008       return tree_int_cst_sgn (t) >= 0;
15009
15010     case REAL_CST:
15011       return ! REAL_VALUE_NEGATIVE (TREE_REAL_CST (t));
15012
15013     case FIXED_CST:
15014       return ! FIXED_VALUE_NEGATIVE (TREE_FIXED_CST (t));
15015
15016     case COND_EXPR:
15017       return (tree_expr_nonnegative_warnv_p (TREE_OPERAND (t, 1),
15018                                              strict_overflow_p)
15019               && tree_expr_nonnegative_warnv_p (TREE_OPERAND (t, 2),
15020                                                 strict_overflow_p));
15021     default:
15022       return tree_simple_nonnegative_warnv_p (TREE_CODE (t),
15023                                                    TREE_TYPE (t));
15024     }
15025   /* We don't know sign of `t', so be conservative and return false.  */
15026   return false;
15027 }
15028
15029 /* Return true if T is known to be non-negative.  If the return
15030    value is based on the assumption that signed overflow is undefined,
15031    set *STRICT_OVERFLOW_P to true; otherwise, don't change
15032    *STRICT_OVERFLOW_P.  */
15033
15034 bool
15035 tree_call_nonnegative_warnv_p (tree type, tree fndecl,
15036                                tree arg0, tree arg1, bool *strict_overflow_p)
15037 {
15038   if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
15039     switch (DECL_FUNCTION_CODE (fndecl))
15040       {
15041         CASE_FLT_FN (BUILT_IN_ACOS):
15042         CASE_FLT_FN (BUILT_IN_ACOSH):
15043         CASE_FLT_FN (BUILT_IN_CABS):
15044         CASE_FLT_FN (BUILT_IN_COSH):
15045         CASE_FLT_FN (BUILT_IN_ERFC):
15046         CASE_FLT_FN (BUILT_IN_EXP):
15047         CASE_FLT_FN (BUILT_IN_EXP10):
15048         CASE_FLT_FN (BUILT_IN_EXP2):
15049         CASE_FLT_FN (BUILT_IN_FABS):
15050         CASE_FLT_FN (BUILT_IN_FDIM):
15051         CASE_FLT_FN (BUILT_IN_HYPOT):
15052         CASE_FLT_FN (BUILT_IN_POW10):
15053         CASE_INT_FN (BUILT_IN_FFS):
15054         CASE_INT_FN (BUILT_IN_PARITY):
15055         CASE_INT_FN (BUILT_IN_POPCOUNT):
15056         CASE_INT_FN (BUILT_IN_CLZ):
15057         CASE_INT_FN (BUILT_IN_CLRSB):
15058       case BUILT_IN_BSWAP32:
15059       case BUILT_IN_BSWAP64:
15060         /* Always true.  */
15061         return true;
15062
15063         CASE_FLT_FN (BUILT_IN_SQRT):
15064         /* sqrt(-0.0) is -0.0.  */
15065         if (!HONOR_SIGNED_ZEROS (TYPE_MODE (type)))
15066           return true;
15067         return tree_expr_nonnegative_warnv_p (arg0,
15068                                               strict_overflow_p);
15069
15070         CASE_FLT_FN (BUILT_IN_ASINH):
15071         CASE_FLT_FN (BUILT_IN_ATAN):
15072         CASE_FLT_FN (BUILT_IN_ATANH):
15073         CASE_FLT_FN (BUILT_IN_CBRT):
15074         CASE_FLT_FN (BUILT_IN_CEIL):
15075         CASE_FLT_FN (BUILT_IN_ERF):
15076         CASE_FLT_FN (BUILT_IN_EXPM1):
15077         CASE_FLT_FN (BUILT_IN_FLOOR):
15078         CASE_FLT_FN (BUILT_IN_FMOD):
15079         CASE_FLT_FN (BUILT_IN_FREXP):
15080         CASE_FLT_FN (BUILT_IN_ICEIL):
15081         CASE_FLT_FN (BUILT_IN_IFLOOR):
15082         CASE_FLT_FN (BUILT_IN_IRINT):
15083         CASE_FLT_FN (BUILT_IN_IROUND):
15084         CASE_FLT_FN (BUILT_IN_LCEIL):
15085         CASE_FLT_FN (BUILT_IN_LDEXP):
15086         CASE_FLT_FN (BUILT_IN_LFLOOR):
15087         CASE_FLT_FN (BUILT_IN_LLCEIL):
15088         CASE_FLT_FN (BUILT_IN_LLFLOOR):
15089         CASE_FLT_FN (BUILT_IN_LLRINT):
15090         CASE_FLT_FN (BUILT_IN_LLROUND):
15091         CASE_FLT_FN (BUILT_IN_LRINT):
15092         CASE_FLT_FN (BUILT_IN_LROUND):
15093         CASE_FLT_FN (BUILT_IN_MODF):
15094         CASE_FLT_FN (BUILT_IN_NEARBYINT):
15095         CASE_FLT_FN (BUILT_IN_RINT):
15096         CASE_FLT_FN (BUILT_IN_ROUND):
15097         CASE_FLT_FN (BUILT_IN_SCALB):
15098         CASE_FLT_FN (BUILT_IN_SCALBLN):
15099         CASE_FLT_FN (BUILT_IN_SCALBN):
15100         CASE_FLT_FN (BUILT_IN_SIGNBIT):
15101         CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
15102         CASE_FLT_FN (BUILT_IN_SINH):
15103         CASE_FLT_FN (BUILT_IN_TANH):
15104         CASE_FLT_FN (BUILT_IN_TRUNC):
15105         /* True if the 1st argument is nonnegative.  */
15106         return tree_expr_nonnegative_warnv_p (arg0,
15107                                               strict_overflow_p);
15108
15109         CASE_FLT_FN (BUILT_IN_FMAX):
15110         /* True if the 1st OR 2nd arguments are nonnegative.  */
15111         return (tree_expr_nonnegative_warnv_p (arg0,
15112                                                strict_overflow_p)
15113                 || (tree_expr_nonnegative_warnv_p (arg1,
15114                                                    strict_overflow_p)));
15115
15116         CASE_FLT_FN (BUILT_IN_FMIN):
15117         /* True if the 1st AND 2nd arguments are nonnegative.  */
15118         return (tree_expr_nonnegative_warnv_p (arg0,
15119                                                strict_overflow_p)
15120                 && (tree_expr_nonnegative_warnv_p (arg1,
15121                                                    strict_overflow_p)));
15122
15123         CASE_FLT_FN (BUILT_IN_COPYSIGN):
15124         /* True if the 2nd argument is nonnegative.  */
15125         return tree_expr_nonnegative_warnv_p (arg1,
15126                                               strict_overflow_p);
15127
15128         CASE_FLT_FN (BUILT_IN_POWI):
15129         /* True if the 1st argument is nonnegative or the second
15130            argument is an even integer.  */
15131         if (TREE_CODE (arg1) == INTEGER_CST
15132             && (TREE_INT_CST_LOW (arg1) & 1) == 0)
15133           return true;
15134         return tree_expr_nonnegative_warnv_p (arg0,
15135                                               strict_overflow_p);
15136
15137         CASE_FLT_FN (BUILT_IN_POW):
15138         /* True if the 1st argument is nonnegative or the second
15139            argument is an even integer valued real.  */
15140         if (TREE_CODE (arg1) == REAL_CST)
15141           {
15142             REAL_VALUE_TYPE c;
15143             HOST_WIDE_INT n;
15144
15145             c = TREE_REAL_CST (arg1);
15146             n = real_to_integer (&c);
15147             if ((n & 1) == 0)
15148               {
15149                 REAL_VALUE_TYPE cint;
15150                 real_from_integer (&cint, VOIDmode, n, SIGNED);
15151                 if (real_identical (&c, &cint))
15152                   return true;
15153               }
15154           }
15155         return tree_expr_nonnegative_warnv_p (arg0,
15156                                               strict_overflow_p);
15157
15158       default:
15159         break;
15160       }
15161   return tree_simple_nonnegative_warnv_p (CALL_EXPR,
15162                                           type);
15163 }
15164
15165 /* Return true if T is known to be non-negative.  If the return
15166    value is based on the assumption that signed overflow is undefined,
15167    set *STRICT_OVERFLOW_P to true; otherwise, don't change
15168    *STRICT_OVERFLOW_P.  */
15169
15170 static bool
15171 tree_invalid_nonnegative_warnv_p (tree t, bool *strict_overflow_p)
15172 {
15173   enum tree_code code = TREE_CODE (t);
15174   if (TYPE_UNSIGNED (TREE_TYPE (t)))
15175     return true;
15176
15177   switch (code)
15178     {
15179     case TARGET_EXPR:
15180       {
15181         tree temp = TARGET_EXPR_SLOT (t);
15182         t = TARGET_EXPR_INITIAL (t);
15183
15184         /* If the initializer is non-void, then it's a normal expression
15185            that will be assigned to the slot.  */
15186         if (!VOID_TYPE_P (t))
15187           return tree_expr_nonnegative_warnv_p (t, strict_overflow_p);
15188
15189         /* Otherwise, the initializer sets the slot in some way.  One common
15190            way is an assignment statement at the end of the initializer.  */
15191         while (1)
15192           {
15193             if (TREE_CODE (t) == BIND_EXPR)
15194               t = expr_last (BIND_EXPR_BODY (t));
15195             else if (TREE_CODE (t) == TRY_FINALLY_EXPR
15196                      || TREE_CODE (t) == TRY_CATCH_EXPR)
15197               t = expr_last (TREE_OPERAND (t, 0));
15198             else if (TREE_CODE (t) == STATEMENT_LIST)
15199               t = expr_last (t);
15200             else
15201               break;
15202           }
15203         if (TREE_CODE (t) == MODIFY_EXPR
15204             && TREE_OPERAND (t, 0) == temp)
15205           return tree_expr_nonnegative_warnv_p (TREE_OPERAND (t, 1),
15206                                                 strict_overflow_p);
15207
15208         return false;
15209       }
15210
15211     case CALL_EXPR:
15212       {
15213         tree arg0 = call_expr_nargs (t) > 0 ?  CALL_EXPR_ARG (t, 0) : NULL_TREE;
15214         tree arg1 = call_expr_nargs (t) > 1 ?  CALL_EXPR_ARG (t, 1) : NULL_TREE;
15215
15216         return tree_call_nonnegative_warnv_p (TREE_TYPE (t),
15217                                               get_callee_fndecl (t),
15218                                               arg0,
15219                                               arg1,
15220                                               strict_overflow_p);
15221       }
15222     case COMPOUND_EXPR:
15223     case MODIFY_EXPR:
15224       return tree_expr_nonnegative_warnv_p (TREE_OPERAND (t, 1),
15225                                             strict_overflow_p);
15226     case BIND_EXPR:
15227       return tree_expr_nonnegative_warnv_p (expr_last (TREE_OPERAND (t, 1)),
15228                                             strict_overflow_p);
15229     case SAVE_EXPR:
15230       return tree_expr_nonnegative_warnv_p (TREE_OPERAND (t, 0),
15231                                             strict_overflow_p);
15232
15233     default:
15234       return tree_simple_nonnegative_warnv_p (TREE_CODE (t),
15235                                                    TREE_TYPE (t));
15236     }
15237
15238   /* We don't know sign of `t', so be conservative and return false.  */
15239   return false;
15240 }
15241
15242 /* Return true if T is known to be non-negative.  If the return
15243    value is based on the assumption that signed overflow is undefined,
15244    set *STRICT_OVERFLOW_P to true; otherwise, don't change
15245    *STRICT_OVERFLOW_P.  */
15246
15247 bool
15248 tree_expr_nonnegative_warnv_p (tree t, bool *strict_overflow_p)
15249 {
15250   enum tree_code code;
15251   if (t == error_mark_node)
15252     return false;
15253
15254   code = TREE_CODE (t);
15255   switch (TREE_CODE_CLASS (code))
15256     {
15257     case tcc_binary:
15258     case tcc_comparison:
15259       return tree_binary_nonnegative_warnv_p (TREE_CODE (t),
15260                                               TREE_TYPE (t),
15261                                               TREE_OPERAND (t, 0),
15262                                               TREE_OPERAND (t, 1),
15263                                               strict_overflow_p);
15264
15265     case tcc_unary:
15266       return tree_unary_nonnegative_warnv_p (TREE_CODE (t),
15267                                              TREE_TYPE (t),
15268                                              TREE_OPERAND (t, 0),
15269                                              strict_overflow_p);
15270
15271     case tcc_constant:
15272     case tcc_declaration:
15273     case tcc_reference:
15274       return tree_single_nonnegative_warnv_p (t, strict_overflow_p);
15275
15276     default:
15277       break;
15278     }
15279
15280   switch (code)
15281     {
15282     case TRUTH_AND_EXPR:
15283     case TRUTH_OR_EXPR:
15284     case TRUTH_XOR_EXPR:
15285       return tree_binary_nonnegative_warnv_p (TREE_CODE (t),
15286                                               TREE_TYPE (t),
15287                                               TREE_OPERAND (t, 0),
15288                                               TREE_OPERAND (t, 1),
15289                                               strict_overflow_p);
15290     case TRUTH_NOT_EXPR:
15291       return tree_unary_nonnegative_warnv_p (TREE_CODE (t),
15292                                              TREE_TYPE (t),
15293                                              TREE_OPERAND (t, 0),
15294                                              strict_overflow_p);
15295
15296     case COND_EXPR:
15297     case CONSTRUCTOR:
15298     case OBJ_TYPE_REF:
15299     case ASSERT_EXPR:
15300     case ADDR_EXPR:
15301     case WITH_SIZE_EXPR:
15302     case SSA_NAME:
15303       return tree_single_nonnegative_warnv_p (t, strict_overflow_p);
15304
15305     default:
15306       return tree_invalid_nonnegative_warnv_p (t, strict_overflow_p);
15307     }
15308 }
15309
15310 /* Return true if `t' is known to be non-negative.  Handle warnings
15311    about undefined signed overflow.  */
15312
15313 bool
15314 tree_expr_nonnegative_p (tree t)
15315 {
15316   bool ret, strict_overflow_p;
15317
15318   strict_overflow_p = false;
15319   ret = tree_expr_nonnegative_warnv_p (t, &strict_overflow_p);
15320   if (strict_overflow_p)
15321     fold_overflow_warning (("assuming signed overflow does not occur when "
15322                             "determining that expression is always "
15323                             "non-negative"),
15324                            WARN_STRICT_OVERFLOW_MISC);
15325   return ret;
15326 }
15327
15328
15329 /* Return true when (CODE OP0) is an address and is known to be nonzero.
15330    For floating point we further ensure that T is not denormal.
15331    Similar logic is present in nonzero_address in rtlanal.h.
15332
15333    If the return value is based on the assumption that signed overflow
15334    is undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't
15335    change *STRICT_OVERFLOW_P.  */
15336
15337 bool
15338 tree_unary_nonzero_warnv_p (enum tree_code code, tree type, tree op0,
15339                                  bool *strict_overflow_p)
15340 {
15341   switch (code)
15342     {
15343     case ABS_EXPR:
15344       return tree_expr_nonzero_warnv_p (op0,
15345                                         strict_overflow_p);
15346
15347     case NOP_EXPR:
15348       {
15349         tree inner_type = TREE_TYPE (op0);
15350         tree outer_type = type;
15351
15352         return (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
15353                 && tree_expr_nonzero_warnv_p (op0,
15354                                               strict_overflow_p));
15355       }
15356       break;
15357
15358     case NON_LVALUE_EXPR:
15359       return tree_expr_nonzero_warnv_p (op0,
15360                                         strict_overflow_p);
15361
15362     default:
15363       break;
15364   }
15365
15366   return false;
15367 }
15368
15369 /* Return true when (CODE OP0 OP1) is an address and is known to be nonzero.
15370    For floating point we further ensure that T is not denormal.
15371    Similar logic is present in nonzero_address in rtlanal.h.
15372
15373    If the return value is based on the assumption that signed overflow
15374    is undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't
15375    change *STRICT_OVERFLOW_P.  */
15376
15377 bool
15378 tree_binary_nonzero_warnv_p (enum tree_code code,
15379                              tree type,
15380                              tree op0,
15381                              tree op1, bool *strict_overflow_p)
15382 {
15383   bool sub_strict_overflow_p;
15384   switch (code)
15385     {
15386     case POINTER_PLUS_EXPR:
15387     case PLUS_EXPR:
15388       if (TYPE_OVERFLOW_UNDEFINED (type))
15389         {
15390           /* With the presence of negative values it is hard
15391              to say something.  */
15392           sub_strict_overflow_p = false;
15393           if (!tree_expr_nonnegative_warnv_p (op0,
15394                                               &sub_strict_overflow_p)
15395               || !tree_expr_nonnegative_warnv_p (op1,
15396                                                  &sub_strict_overflow_p))
15397             return false;
15398           /* One of operands must be positive and the other non-negative.  */
15399           /* We don't set *STRICT_OVERFLOW_P here: even if this value
15400              overflows, on a twos-complement machine the sum of two
15401              nonnegative numbers can never be zero.  */
15402           return (tree_expr_nonzero_warnv_p (op0,
15403                                              strict_overflow_p)
15404                   || tree_expr_nonzero_warnv_p (op1,
15405                                                 strict_overflow_p));
15406         }
15407       break;
15408
15409     case MULT_EXPR:
15410       if (TYPE_OVERFLOW_UNDEFINED (type))
15411         {
15412           if (tree_expr_nonzero_warnv_p (op0,
15413                                          strict_overflow_p)
15414               && tree_expr_nonzero_warnv_p (op1,
15415                                             strict_overflow_p))
15416             {
15417               *strict_overflow_p = true;
15418               return true;
15419             }
15420         }
15421       break;
15422
15423     case MIN_EXPR:
15424       sub_strict_overflow_p = false;
15425       if (tree_expr_nonzero_warnv_p (op0,
15426                                      &sub_strict_overflow_p)
15427           && tree_expr_nonzero_warnv_p (op1,
15428                                         &sub_strict_overflow_p))
15429         {
15430           if (sub_strict_overflow_p)
15431             *strict_overflow_p = true;
15432         }
15433       break;
15434
15435     case MAX_EXPR:
15436       sub_strict_overflow_p = false;
15437       if (tree_expr_nonzero_warnv_p (op0,
15438                                      &sub_strict_overflow_p))
15439         {
15440           if (sub_strict_overflow_p)
15441             *strict_overflow_p = true;
15442
15443           /* When both operands are nonzero, then MAX must be too.  */
15444           if (tree_expr_nonzero_warnv_p (op1,
15445                                          strict_overflow_p))
15446             return true;
15447
15448           /* MAX where operand 0 is positive is positive.  */
15449           return tree_expr_nonnegative_warnv_p (op0,
15450                                                strict_overflow_p);
15451         }
15452       /* MAX where operand 1 is positive is positive.  */
15453       else if (tree_expr_nonzero_warnv_p (op1,
15454                                           &sub_strict_overflow_p)
15455                && tree_expr_nonnegative_warnv_p (op1,
15456                                                  &sub_strict_overflow_p))
15457         {
15458           if (sub_strict_overflow_p)
15459             *strict_overflow_p = true;
15460           return true;
15461         }
15462       break;
15463
15464     case BIT_IOR_EXPR:
15465       return (tree_expr_nonzero_warnv_p (op1,
15466                                          strict_overflow_p)
15467               || tree_expr_nonzero_warnv_p (op0,
15468                                             strict_overflow_p));
15469
15470     default:
15471       break;
15472   }
15473
15474   return false;
15475 }
15476
15477 /* Return true when T is an address and is known to be nonzero.
15478    For floating point we further ensure that T is not denormal.
15479    Similar logic is present in nonzero_address in rtlanal.h.
15480
15481    If the return value is based on the assumption that signed overflow
15482    is undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't
15483    change *STRICT_OVERFLOW_P.  */
15484
15485 bool
15486 tree_single_nonzero_warnv_p (tree t, bool *strict_overflow_p)
15487 {
15488   bool sub_strict_overflow_p;
15489   switch (TREE_CODE (t))
15490     {
15491     case INTEGER_CST:
15492       return !integer_zerop (t);
15493
15494     case ADDR_EXPR:
15495       {
15496         tree base = TREE_OPERAND (t, 0);
15497
15498         if (!DECL_P (base))
15499           base = get_base_address (base);
15500
15501         if (!base)
15502           return false;
15503
15504         /* For objects in symbol table check if we know they are non-zero.
15505            Don't do anything for variables and functions before symtab is built;
15506            it is quite possible that they will be declared weak later.  */
15507         if (DECL_P (base) && decl_in_symtab_p (base))
15508           {
15509             struct symtab_node *symbol;
15510
15511             symbol = symtab_node::get_create (base);
15512             if (symbol)
15513               return symbol->nonzero_address ();
15514             else
15515               return false;
15516           }
15517
15518         /* Function local objects are never NULL.  */
15519         if (DECL_P (base)
15520             && (DECL_CONTEXT (base)
15521                 && TREE_CODE (DECL_CONTEXT (base)) == FUNCTION_DECL
15522                 && auto_var_in_fn_p (base, DECL_CONTEXT (base))))
15523           return true;
15524
15525         /* Constants are never weak.  */
15526         if (CONSTANT_CLASS_P (base))
15527           return true;
15528
15529         return false;
15530       }
15531
15532     case COND_EXPR:
15533       sub_strict_overflow_p = false;
15534       if (tree_expr_nonzero_warnv_p (TREE_OPERAND (t, 1),
15535                                      &sub_strict_overflow_p)
15536           && tree_expr_nonzero_warnv_p (TREE_OPERAND (t, 2),
15537                                         &sub_strict_overflow_p))
15538         {
15539           if (sub_strict_overflow_p)
15540             *strict_overflow_p = true;
15541           return true;
15542         }
15543       break;
15544
15545     default:
15546       break;
15547     }
15548   return false;
15549 }
15550
15551 /* Given the components of a binary expression CODE, TYPE, OP0 and OP1,
15552    attempt to fold the expression to a constant without modifying TYPE,
15553    OP0 or OP1.
15554
15555    If the expression could be simplified to a constant, then return
15556    the constant.  If the expression would not be simplified to a
15557    constant, then return NULL_TREE.  */
15558
15559 tree
15560 fold_binary_to_constant (enum tree_code code, tree type, tree op0, tree op1)
15561 {
15562   tree tem = fold_binary (code, type, op0, op1);
15563   return (tem && TREE_CONSTANT (tem)) ? tem : NULL_TREE;
15564 }
15565
15566 /* Given the components of a unary expression CODE, TYPE and OP0,
15567    attempt to fold the expression to a constant without modifying
15568    TYPE or OP0.
15569
15570    If the expression could be simplified to a constant, then return
15571    the constant.  If the expression would not be simplified to a
15572    constant, then return NULL_TREE.  */
15573
15574 tree
15575 fold_unary_to_constant (enum tree_code code, tree type, tree op0)
15576 {
15577   tree tem = fold_unary (code, type, op0);
15578   return (tem && TREE_CONSTANT (tem)) ? tem : NULL_TREE;
15579 }
15580
15581 /* If EXP represents referencing an element in a constant string
15582    (either via pointer arithmetic or array indexing), return the
15583    tree representing the value accessed, otherwise return NULL.  */
15584
15585 tree
15586 fold_read_from_constant_string (tree exp)
15587 {
15588   if ((TREE_CODE (exp) == INDIRECT_REF
15589        || TREE_CODE (exp) == ARRAY_REF)
15590       && TREE_CODE (TREE_TYPE (exp)) == INTEGER_TYPE)
15591     {
15592       tree exp1 = TREE_OPERAND (exp, 0);
15593       tree index;
15594       tree string;
15595       location_t loc = EXPR_LOCATION (exp);
15596
15597       if (TREE_CODE (exp) == INDIRECT_REF)
15598         string = string_constant (exp1, &index);
15599       else
15600         {
15601           tree low_bound = array_ref_low_bound (exp);
15602           index = fold_convert_loc (loc, sizetype, TREE_OPERAND (exp, 1));
15603
15604           /* Optimize the special-case of a zero lower bound.
15605
15606              We convert the low_bound to sizetype to avoid some problems
15607              with constant folding.  (E.g. suppose the lower bound is 1,
15608              and its mode is QI.  Without the conversion,l (ARRAY
15609              +(INDEX-(unsigned char)1)) becomes ((ARRAY+(-(unsigned char)1))
15610              +INDEX), which becomes (ARRAY+255+INDEX).  Oops!)  */
15611           if (! integer_zerop (low_bound))
15612             index = size_diffop_loc (loc, index,
15613                                  fold_convert_loc (loc, sizetype, low_bound));
15614
15615           string = exp1;
15616         }
15617
15618       if (string
15619           && TYPE_MODE (TREE_TYPE (exp)) == TYPE_MODE (TREE_TYPE (TREE_TYPE (string)))
15620           && TREE_CODE (string) == STRING_CST
15621           && TREE_CODE (index) == INTEGER_CST
15622           && compare_tree_int (index, TREE_STRING_LENGTH (string)) < 0
15623           && (GET_MODE_CLASS (TYPE_MODE (TREE_TYPE (TREE_TYPE (string))))
15624               == MODE_INT)
15625           && (GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (TREE_TYPE (string)))) == 1))
15626         return build_int_cst_type (TREE_TYPE (exp),
15627                                    (TREE_STRING_POINTER (string)
15628                                     [TREE_INT_CST_LOW (index)]));
15629     }
15630   return NULL;
15631 }
15632
15633 /* Return the tree for neg (ARG0) when ARG0 is known to be either
15634    an integer constant, real, or fixed-point constant.
15635
15636    TYPE is the type of the result.  */
15637
15638 static tree
15639 fold_negate_const (tree arg0, tree type)
15640 {
15641   tree t = NULL_TREE;
15642
15643   switch (TREE_CODE (arg0))
15644     {
15645     case INTEGER_CST:
15646       {
15647         bool overflow;
15648         wide_int val = wi::neg (arg0, &overflow);
15649         t = force_fit_type (type, val, 1,
15650                             (overflow | TREE_OVERFLOW (arg0))
15651                             && !TYPE_UNSIGNED (type));
15652         break;
15653       }
15654
15655     case REAL_CST:
15656       t = build_real (type, real_value_negate (&TREE_REAL_CST (arg0)));
15657       break;
15658
15659     case FIXED_CST:
15660       {
15661         FIXED_VALUE_TYPE f;
15662         bool overflow_p = fixed_arithmetic (&f, NEGATE_EXPR,
15663                                             &(TREE_FIXED_CST (arg0)), NULL,
15664                                             TYPE_SATURATING (type));
15665         t = build_fixed (type, f);
15666         /* Propagate overflow flags.  */
15667         if (overflow_p | TREE_OVERFLOW (arg0))
15668           TREE_OVERFLOW (t) = 1;
15669         break;
15670       }
15671
15672     default:
15673       gcc_unreachable ();
15674     }
15675
15676   return t;
15677 }
15678
15679 /* Return the tree for abs (ARG0) when ARG0 is known to be either
15680    an integer constant or real constant.
15681
15682    TYPE is the type of the result.  */
15683
15684 tree
15685 fold_abs_const (tree arg0, tree type)
15686 {
15687   tree t = NULL_TREE;
15688
15689   switch (TREE_CODE (arg0))
15690     {
15691     case INTEGER_CST:
15692       {
15693         /* If the value is unsigned or non-negative, then the absolute value
15694            is the same as the ordinary value.  */
15695         if (!wi::neg_p (arg0, TYPE_SIGN (type)))
15696           t = arg0;
15697
15698         /* If the value is negative, then the absolute value is
15699            its negation.  */
15700         else
15701           {
15702             bool overflow;
15703             wide_int val = wi::neg (arg0, &overflow);
15704             t = force_fit_type (type, val, -1,
15705                                 overflow | TREE_OVERFLOW (arg0));
15706           }
15707       }
15708       break;
15709
15710     case REAL_CST:
15711       if (REAL_VALUE_NEGATIVE (TREE_REAL_CST (arg0)))
15712         t = build_real (type, real_value_negate (&TREE_REAL_CST (arg0)));
15713       else
15714         t =  arg0;
15715       break;
15716
15717     default:
15718       gcc_unreachable ();
15719     }
15720
15721   return t;
15722 }
15723
15724 /* Return the tree for not (ARG0) when ARG0 is known to be an integer
15725    constant.  TYPE is the type of the result.  */
15726
15727 static tree
15728 fold_not_const (const_tree arg0, tree type)
15729 {
15730   gcc_assert (TREE_CODE (arg0) == INTEGER_CST);
15731
15732   return force_fit_type (type, wi::bit_not (arg0), 0, TREE_OVERFLOW (arg0));
15733 }
15734
15735 /* Given CODE, a relational operator, the target type, TYPE and two
15736    constant operands OP0 and OP1, return the result of the
15737    relational operation.  If the result is not a compile time
15738    constant, then return NULL_TREE.  */
15739
15740 static tree
15741 fold_relational_const (enum tree_code code, tree type, tree op0, tree op1)
15742 {
15743   int result, invert;
15744
15745   /* From here on, the only cases we handle are when the result is
15746      known to be a constant.  */
15747
15748   if (TREE_CODE (op0) == REAL_CST && TREE_CODE (op1) == REAL_CST)
15749     {
15750       const REAL_VALUE_TYPE *c0 = TREE_REAL_CST_PTR (op0);
15751       const REAL_VALUE_TYPE *c1 = TREE_REAL_CST_PTR (op1);
15752
15753       /* Handle the cases where either operand is a NaN.  */
15754       if (real_isnan (c0) || real_isnan (c1))
15755         {
15756           switch (code)
15757             {
15758             case EQ_EXPR:
15759             case ORDERED_EXPR:
15760               result = 0;
15761               break;
15762
15763             case NE_EXPR:
15764             case UNORDERED_EXPR:
15765             case UNLT_EXPR:
15766             case UNLE_EXPR:
15767             case UNGT_EXPR:
15768             case UNGE_EXPR:
15769             case UNEQ_EXPR:
15770               result = 1;
15771               break;
15772
15773             case LT_EXPR:
15774             case LE_EXPR:
15775             case GT_EXPR:
15776             case GE_EXPR:
15777             case LTGT_EXPR:
15778               if (flag_trapping_math)
15779                 return NULL_TREE;
15780               result = 0;
15781               break;
15782
15783             default:
15784               gcc_unreachable ();
15785             }
15786
15787           return constant_boolean_node (result, type);
15788         }
15789
15790       return constant_boolean_node (real_compare (code, c0, c1), type);
15791     }
15792
15793   if (TREE_CODE (op0) == FIXED_CST && TREE_CODE (op1) == FIXED_CST)
15794     {
15795       const FIXED_VALUE_TYPE *c0 = TREE_FIXED_CST_PTR (op0);
15796       const FIXED_VALUE_TYPE *c1 = TREE_FIXED_CST_PTR (op1);
15797       return constant_boolean_node (fixed_compare (code, c0, c1), type);
15798     }
15799
15800   /* Handle equality/inequality of complex constants.  */
15801   if (TREE_CODE (op0) == COMPLEX_CST && TREE_CODE (op1) == COMPLEX_CST)
15802     {
15803       tree rcond = fold_relational_const (code, type,
15804                                           TREE_REALPART (op0),
15805                                           TREE_REALPART (op1));
15806       tree icond = fold_relational_const (code, type,
15807                                           TREE_IMAGPART (op0),
15808                                           TREE_IMAGPART (op1));
15809       if (code == EQ_EXPR)
15810         return fold_build2 (TRUTH_ANDIF_EXPR, type, rcond, icond);
15811       else if (code == NE_EXPR)
15812         return fold_build2 (TRUTH_ORIF_EXPR, type, rcond, icond);
15813       else
15814         return NULL_TREE;
15815     }
15816
15817   if (TREE_CODE (op0) == VECTOR_CST && TREE_CODE (op1) == VECTOR_CST)
15818     {
15819       unsigned count = VECTOR_CST_NELTS (op0);
15820       tree *elts =  XALLOCAVEC (tree, count);
15821       gcc_assert (VECTOR_CST_NELTS (op1) == count
15822                   && TYPE_VECTOR_SUBPARTS (type) == count);
15823
15824       for (unsigned i = 0; i < count; i++)
15825         {
15826           tree elem_type = TREE_TYPE (type);
15827           tree elem0 = VECTOR_CST_ELT (op0, i);
15828           tree elem1 = VECTOR_CST_ELT (op1, i);
15829
15830           tree tem = fold_relational_const (code, elem_type,
15831                                             elem0, elem1);
15832
15833           if (tem == NULL_TREE)
15834             return NULL_TREE;
15835
15836           elts[i] = build_int_cst (elem_type, integer_zerop (tem) ? 0 : -1);
15837         }
15838
15839       return build_vector (type, elts);
15840     }
15841
15842   /* From here on we only handle LT, LE, GT, GE, EQ and NE.
15843
15844      To compute GT, swap the arguments and do LT.
15845      To compute GE, do LT and invert the result.
15846      To compute LE, swap the arguments, do LT and invert the result.
15847      To compute NE, do EQ and invert the result.
15848
15849      Therefore, the code below must handle only EQ and LT.  */
15850
15851   if (code == LE_EXPR || code == GT_EXPR)
15852     {
15853       tree tem = op0;
15854       op0 = op1;
15855       op1 = tem;
15856       code = swap_tree_comparison (code);
15857     }
15858
15859   /* Note that it is safe to invert for real values here because we
15860      have already handled the one case that it matters.  */
15861
15862   invert = 0;
15863   if (code == NE_EXPR || code == GE_EXPR)
15864     {
15865       invert = 1;
15866       code = invert_tree_comparison (code, false);
15867     }
15868
15869   /* Compute a result for LT or EQ if args permit;
15870      Otherwise return T.  */
15871   if (TREE_CODE (op0) == INTEGER_CST && TREE_CODE (op1) == INTEGER_CST)
15872     {
15873       if (code == EQ_EXPR)
15874         result = tree_int_cst_equal (op0, op1);
15875       else
15876         result = tree_int_cst_lt (op0, op1);
15877     }
15878   else
15879     return NULL_TREE;
15880
15881   if (invert)
15882     result ^= 1;
15883   return constant_boolean_node (result, type);
15884 }
15885
15886 /* If necessary, return a CLEANUP_POINT_EXPR for EXPR with the
15887    indicated TYPE.  If no CLEANUP_POINT_EXPR is necessary, return EXPR
15888    itself.  */
15889
15890 tree
15891 fold_build_cleanup_point_expr (tree type, tree expr)
15892 {
15893   /* If the expression does not have side effects then we don't have to wrap
15894      it with a cleanup point expression.  */
15895   if (!TREE_SIDE_EFFECTS (expr))
15896     return expr;
15897
15898   /* If the expression is a return, check to see if the expression inside the
15899      return has no side effects or the right hand side of the modify expression
15900      inside the return. If either don't have side effects set we don't need to
15901      wrap the expression in a cleanup point expression.  Note we don't check the
15902      left hand side of the modify because it should always be a return decl.  */
15903   if (TREE_CODE (expr) == RETURN_EXPR)
15904     {
15905       tree op = TREE_OPERAND (expr, 0);
15906       if (!op || !TREE_SIDE_EFFECTS (op))
15907         return expr;
15908       op = TREE_OPERAND (op, 1);
15909       if (!TREE_SIDE_EFFECTS (op))
15910         return expr;
15911     }
15912
15913   return build1 (CLEANUP_POINT_EXPR, type, expr);
15914 }
15915
15916 /* Given a pointer value OP0 and a type TYPE, return a simplified version
15917    of an indirection through OP0, or NULL_TREE if no simplification is
15918    possible.  */
15919
15920 tree
15921 fold_indirect_ref_1 (location_t loc, tree type, tree op0)
15922 {
15923   tree sub = op0;
15924   tree subtype;
15925
15926   STRIP_NOPS (sub);
15927   subtype = TREE_TYPE (sub);
15928   if (!POINTER_TYPE_P (subtype))
15929     return NULL_TREE;
15930
15931   if (TREE_CODE (sub) == ADDR_EXPR)
15932     {
15933       tree op = TREE_OPERAND (sub, 0);
15934       tree optype = TREE_TYPE (op);
15935       /* *&CONST_DECL -> to the value of the const decl.  */
15936       if (TREE_CODE (op) == CONST_DECL)
15937         return DECL_INITIAL (op);
15938       /* *&p => p;  make sure to handle *&"str"[cst] here.  */
15939       if (type == optype)
15940         {
15941           tree fop = fold_read_from_constant_string (op);
15942           if (fop)
15943             return fop;
15944           else
15945             return op;
15946         }
15947       /* *(foo *)&fooarray => fooarray[0] */
15948       else if (TREE_CODE (optype) == ARRAY_TYPE
15949                && type == TREE_TYPE (optype)
15950                && (!in_gimple_form
15951                    || TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST))
15952         {
15953           tree type_domain = TYPE_DOMAIN (optype);
15954           tree min_val = size_zero_node;
15955           if (type_domain && TYPE_MIN_VALUE (type_domain))
15956             min_val = TYPE_MIN_VALUE (type_domain);
15957           if (in_gimple_form
15958               && TREE_CODE (min_val) != INTEGER_CST)
15959             return NULL_TREE;
15960           return build4_loc (loc, ARRAY_REF, type, op, min_val,
15961                              NULL_TREE, NULL_TREE);
15962         }
15963       /* *(foo *)&complexfoo => __real__ complexfoo */
15964       else if (TREE_CODE (optype) == COMPLEX_TYPE
15965                && type == TREE_TYPE (optype))
15966         return fold_build1_loc (loc, REALPART_EXPR, type, op);
15967       /* *(foo *)&vectorfoo => BIT_FIELD_REF<vectorfoo,...> */
15968       else if (TREE_CODE (optype) == VECTOR_TYPE
15969                && type == TREE_TYPE (optype))
15970         {
15971           tree part_width = TYPE_SIZE (type);
15972           tree index = bitsize_int (0);
15973           return fold_build3_loc (loc, BIT_FIELD_REF, type, op, part_width, index);
15974         }
15975     }
15976
15977   if (TREE_CODE (sub) == POINTER_PLUS_EXPR
15978       && TREE_CODE (TREE_OPERAND (sub, 1)) == INTEGER_CST)
15979     {
15980       tree op00 = TREE_OPERAND (sub, 0);
15981       tree op01 = TREE_OPERAND (sub, 1);
15982
15983       STRIP_NOPS (op00);
15984       if (TREE_CODE (op00) == ADDR_EXPR)
15985         {
15986           tree op00type;
15987           op00 = TREE_OPERAND (op00, 0);
15988           op00type = TREE_TYPE (op00);
15989
15990           /* ((foo*)&vectorfoo)[1] => BIT_FIELD_REF<vectorfoo,...> */
15991           if (TREE_CODE (op00type) == VECTOR_TYPE
15992               && type == TREE_TYPE (op00type))
15993             {
15994               HOST_WIDE_INT offset = tree_to_shwi (op01);
15995               tree part_width = TYPE_SIZE (type);
15996               unsigned HOST_WIDE_INT part_widthi = tree_to_shwi (part_width)/BITS_PER_UNIT;
15997               unsigned HOST_WIDE_INT indexi = offset * BITS_PER_UNIT;
15998               tree index = bitsize_int (indexi);
15999
16000               if (offset / part_widthi < TYPE_VECTOR_SUBPARTS (op00type))
16001                 return fold_build3_loc (loc,
16002                                         BIT_FIELD_REF, type, op00,
16003                                         part_width, index);
16004
16005             }
16006           /* ((foo*)&complexfoo)[1] => __imag__ complexfoo */
16007           else if (TREE_CODE (op00type) == COMPLEX_TYPE
16008                    && type == TREE_TYPE (op00type))
16009             {
16010               tree size = TYPE_SIZE_UNIT (type);
16011               if (tree_int_cst_equal (size, op01))
16012                 return fold_build1_loc (loc, IMAGPART_EXPR, type, op00);
16013             }
16014           /* ((foo *)&fooarray)[1] => fooarray[1] */
16015           else if (TREE_CODE (op00type) == ARRAY_TYPE
16016                    && type == TREE_TYPE (op00type))
16017             {
16018               tree type_domain = TYPE_DOMAIN (op00type);
16019               tree min_val = size_zero_node;
16020               if (type_domain && TYPE_MIN_VALUE (type_domain))
16021                 min_val = TYPE_MIN_VALUE (type_domain);
16022               op01 = size_binop_loc (loc, EXACT_DIV_EXPR, op01,
16023                                      TYPE_SIZE_UNIT (type));
16024               op01 = size_binop_loc (loc, PLUS_EXPR, op01, min_val);
16025               return build4_loc (loc, ARRAY_REF, type, op00, op01,
16026                                  NULL_TREE, NULL_TREE);
16027             }
16028         }
16029     }
16030
16031   /* *(foo *)fooarrptr => (*fooarrptr)[0] */
16032   if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
16033       && type == TREE_TYPE (TREE_TYPE (subtype))
16034       && (!in_gimple_form
16035           || TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST))
16036     {
16037       tree type_domain;
16038       tree min_val = size_zero_node;
16039       sub = build_fold_indirect_ref_loc (loc, sub);
16040       type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
16041       if (type_domain && TYPE_MIN_VALUE (type_domain))
16042         min_val = TYPE_MIN_VALUE (type_domain);
16043       if (in_gimple_form
16044           && TREE_CODE (min_val) != INTEGER_CST)
16045         return NULL_TREE;
16046       return build4_loc (loc, ARRAY_REF, type, sub, min_val, NULL_TREE,
16047                          NULL_TREE);
16048     }
16049
16050   return NULL_TREE;
16051 }
16052
16053 /* Builds an expression for an indirection through T, simplifying some
16054    cases.  */
16055
16056 tree
16057 build_fold_indirect_ref_loc (location_t loc, tree t)
16058 {
16059   tree type = TREE_TYPE (TREE_TYPE (t));
16060   tree sub = fold_indirect_ref_1 (loc, type, t);
16061
16062   if (sub)
16063     return sub;
16064
16065   return build1_loc (loc, INDIRECT_REF, type, t);
16066 }
16067
16068 /* Given an INDIRECT_REF T, return either T or a simplified version.  */
16069
16070 tree
16071 fold_indirect_ref_loc (location_t loc, tree t)
16072 {
16073   tree sub = fold_indirect_ref_1 (loc, TREE_TYPE (t), TREE_OPERAND (t, 0));
16074
16075   if (sub)
16076     return sub;
16077   else
16078     return t;
16079 }
16080
16081 /* Strip non-trapping, non-side-effecting tree nodes from an expression
16082    whose result is ignored.  The type of the returned tree need not be
16083    the same as the original expression.  */
16084
16085 tree
16086 fold_ignored_result (tree t)
16087 {
16088   if (!TREE_SIDE_EFFECTS (t))
16089     return integer_zero_node;
16090
16091   for (;;)
16092     switch (TREE_CODE_CLASS (TREE_CODE (t)))
16093       {
16094       case tcc_unary:
16095         t = TREE_OPERAND (t, 0);
16096         break;
16097
16098       case tcc_binary:
16099       case tcc_comparison:
16100         if (!TREE_SIDE_EFFECTS (TREE_OPERAND (t, 1)))
16101           t = TREE_OPERAND (t, 0);
16102         else if (!TREE_SIDE_EFFECTS (TREE_OPERAND (t, 0)))
16103           t = TREE_OPERAND (t, 1);
16104         else
16105           return t;
16106         break;
16107
16108       case tcc_expression:
16109         switch (TREE_CODE (t))
16110           {
16111           case COMPOUND_EXPR:
16112             if (TREE_SIDE_EFFECTS (TREE_OPERAND (t, 1)))
16113               return t;
16114             t = TREE_OPERAND (t, 0);
16115             break;
16116
16117           case COND_EXPR:
16118             if (TREE_SIDE_EFFECTS (TREE_OPERAND (t, 1))
16119                 || TREE_SIDE_EFFECTS (TREE_OPERAND (t, 2)))
16120               return t;
16121             t = TREE_OPERAND (t, 0);
16122             break;
16123
16124           default:
16125             return t;
16126           }
16127         break;
16128
16129       default:
16130         return t;
16131       }
16132 }
16133
16134 /* Return the value of VALUE, rounded up to a multiple of DIVISOR. */
16135
16136 tree
16137 round_up_loc (location_t loc, tree value, unsigned int divisor)
16138 {
16139   tree div = NULL_TREE;
16140
16141   if (divisor == 1)
16142     return value;
16143
16144   /* See if VALUE is already a multiple of DIVISOR.  If so, we don't
16145      have to do anything.  Only do this when we are not given a const,
16146      because in that case, this check is more expensive than just
16147      doing it.  */
16148   if (TREE_CODE (value) != INTEGER_CST)
16149     {
16150       div = build_int_cst (TREE_TYPE (value), divisor);
16151
16152       if (multiple_of_p (TREE_TYPE (value), value, div))
16153         return value;
16154     }
16155
16156   /* If divisor is a power of two, simplify this to bit manipulation.  */
16157   if (divisor == (divisor & -divisor))
16158     {
16159       if (TREE_CODE (value) == INTEGER_CST)
16160         {
16161           wide_int val = value;
16162           bool overflow_p;
16163
16164           if ((val & (divisor - 1)) == 0)
16165             return value;
16166
16167           overflow_p = TREE_OVERFLOW (value);
16168           val &= ~(divisor - 1);
16169           val += divisor;
16170           if (val == 0)
16171             overflow_p = true;
16172
16173           return force_fit_type (TREE_TYPE (value), val, -1, overflow_p);
16174         }
16175       else
16176         {
16177           tree t;
16178
16179           t = build_int_cst (TREE_TYPE (value), divisor - 1);
16180           value = size_binop_loc (loc, PLUS_EXPR, value, t);
16181           t = build_int_cst (TREE_TYPE (value), -divisor);
16182           value = size_binop_loc (loc, BIT_AND_EXPR, value, t);
16183         }
16184     }
16185   else
16186     {
16187       if (!div)
16188         div = build_int_cst (TREE_TYPE (value), divisor);
16189       value = size_binop_loc (loc, CEIL_DIV_EXPR, value, div);
16190       value = size_binop_loc (loc, MULT_EXPR, value, div);
16191     }
16192
16193   return value;
16194 }
16195
16196 /* Likewise, but round down.  */
16197
16198 tree
16199 round_down_loc (location_t loc, tree value, int divisor)
16200 {
16201   tree div = NULL_TREE;
16202
16203   gcc_assert (divisor > 0);
16204   if (divisor == 1)
16205     return value;
16206
16207   /* See if VALUE is already a multiple of DIVISOR.  If so, we don't
16208      have to do anything.  Only do this when we are not given a const,
16209      because in that case, this check is more expensive than just
16210      doing it.  */
16211   if (TREE_CODE (value) != INTEGER_CST)
16212     {
16213       div = build_int_cst (TREE_TYPE (value), divisor);
16214
16215       if (multiple_of_p (TREE_TYPE (value), value, div))
16216         return value;
16217     }
16218
16219   /* If divisor is a power of two, simplify this to bit manipulation.  */
16220   if (divisor == (divisor & -divisor))
16221     {
16222       tree t;
16223
16224       t = build_int_cst (TREE_TYPE (value), -divisor);
16225       value = size_binop_loc (loc, BIT_AND_EXPR, value, t);
16226     }
16227   else
16228     {
16229       if (!div)
16230         div = build_int_cst (TREE_TYPE (value), divisor);
16231       value = size_binop_loc (loc, FLOOR_DIV_EXPR, value, div);
16232       value = size_binop_loc (loc, MULT_EXPR, value, div);
16233     }
16234
16235   return value;
16236 }
16237
16238 /* Returns the pointer to the base of the object addressed by EXP and
16239    extracts the information about the offset of the access, storing it
16240    to PBITPOS and POFFSET.  */
16241
16242 static tree
16243 split_address_to_core_and_offset (tree exp,
16244                                   HOST_WIDE_INT *pbitpos, tree *poffset)
16245 {
16246   tree core;
16247   machine_mode mode;
16248   int unsignedp, volatilep;
16249   HOST_WIDE_INT bitsize;
16250   location_t loc = EXPR_LOCATION (exp);
16251
16252   if (TREE_CODE (exp) == ADDR_EXPR)
16253     {
16254       core = get_inner_reference (TREE_OPERAND (exp, 0), &bitsize, pbitpos,
16255                                   poffset, &mode, &unsignedp, &volatilep,
16256                                   false);
16257       core = build_fold_addr_expr_loc (loc, core);
16258     }
16259   else
16260     {
16261       core = exp;
16262       *pbitpos = 0;
16263       *poffset = NULL_TREE;
16264     }
16265
16266   return core;
16267 }
16268
16269 /* Returns true if addresses of E1 and E2 differ by a constant, false
16270    otherwise.  If they do, E1 - E2 is stored in *DIFF.  */
16271
16272 bool
16273 ptr_difference_const (tree e1, tree e2, HOST_WIDE_INT *diff)
16274 {
16275   tree core1, core2;
16276   HOST_WIDE_INT bitpos1, bitpos2;
16277   tree toffset1, toffset2, tdiff, type;
16278
16279   core1 = split_address_to_core_and_offset (e1, &bitpos1, &toffset1);
16280   core2 = split_address_to_core_and_offset (e2, &bitpos2, &toffset2);
16281
16282   if (bitpos1 % BITS_PER_UNIT != 0
16283       || bitpos2 % BITS_PER_UNIT != 0
16284       || !operand_equal_p (core1, core2, 0))
16285     return false;
16286
16287   if (toffset1 && toffset2)
16288     {
16289       type = TREE_TYPE (toffset1);
16290       if (type != TREE_TYPE (toffset2))
16291         toffset2 = fold_convert (type, toffset2);
16292
16293       tdiff = fold_build2 (MINUS_EXPR, type, toffset1, toffset2);
16294       if (!cst_and_fits_in_hwi (tdiff))
16295         return false;
16296
16297       *diff = int_cst_value (tdiff);
16298     }
16299   else if (toffset1 || toffset2)
16300     {
16301       /* If only one of the offsets is non-constant, the difference cannot
16302          be a constant.  */
16303       return false;
16304     }
16305   else
16306     *diff = 0;
16307
16308   *diff += (bitpos1 - bitpos2) / BITS_PER_UNIT;
16309   return true;
16310 }
16311
16312 /* Simplify the floating point expression EXP when the sign of the
16313    result is not significant.  Return NULL_TREE if no simplification
16314    is possible.  */
16315
16316 tree
16317 fold_strip_sign_ops (tree exp)
16318 {
16319   tree arg0, arg1;
16320   location_t loc = EXPR_LOCATION (exp);
16321
16322   switch (TREE_CODE (exp))
16323     {
16324     case ABS_EXPR:
16325     case NEGATE_EXPR:
16326       arg0 = fold_strip_sign_ops (TREE_OPERAND (exp, 0));
16327       return arg0 ? arg0 : TREE_OPERAND (exp, 0);
16328
16329     case MULT_EXPR:
16330     case RDIV_EXPR:
16331       if (HONOR_SIGN_DEPENDENT_ROUNDING (TYPE_MODE (TREE_TYPE (exp))))
16332         return NULL_TREE;
16333       arg0 = fold_strip_sign_ops (TREE_OPERAND (exp, 0));
16334       arg1 = fold_strip_sign_ops (TREE_OPERAND (exp, 1));
16335       if (arg0 != NULL_TREE || arg1 != NULL_TREE)
16336         return fold_build2_loc (loc, TREE_CODE (exp), TREE_TYPE (exp),
16337                             arg0 ? arg0 : TREE_OPERAND (exp, 0),
16338                             arg1 ? arg1 : TREE_OPERAND (exp, 1));
16339       break;
16340
16341     case COMPOUND_EXPR:
16342       arg0 = TREE_OPERAND (exp, 0);
16343       arg1 = fold_strip_sign_ops (TREE_OPERAND (exp, 1));
16344       if (arg1)
16345         return fold_build2_loc (loc, COMPOUND_EXPR, TREE_TYPE (exp), arg0, arg1);
16346       break;
16347
16348     case COND_EXPR:
16349       arg0 = fold_strip_sign_ops (TREE_OPERAND (exp, 1));
16350       arg1 = fold_strip_sign_ops (TREE_OPERAND (exp, 2));
16351       if (arg0 || arg1)
16352         return fold_build3_loc (loc,
16353                             COND_EXPR, TREE_TYPE (exp), TREE_OPERAND (exp, 0),
16354                             arg0 ? arg0 : TREE_OPERAND (exp, 1),
16355                             arg1 ? arg1 : TREE_OPERAND (exp, 2));
16356       break;
16357
16358     case CALL_EXPR:
16359       {
16360         const enum built_in_function fcode = builtin_mathfn_code (exp);
16361         switch (fcode)
16362         {
16363         CASE_FLT_FN (BUILT_IN_COPYSIGN):
16364           /* Strip copysign function call, return the 1st argument. */
16365           arg0 = CALL_EXPR_ARG (exp, 0);
16366           arg1 = CALL_EXPR_ARG (exp, 1);
16367           return omit_one_operand_loc (loc, TREE_TYPE (exp), arg0, arg1);
16368
16369         default:
16370           /* Strip sign ops from the argument of "odd" math functions.  */
16371           if (negate_mathfn_p (fcode))
16372             {
16373               arg0 = fold_strip_sign_ops (CALL_EXPR_ARG (exp, 0));
16374               if (arg0)
16375                 return build_call_expr_loc (loc, get_callee_fndecl (exp), 1, arg0);
16376             }
16377           break;
16378         }
16379       }
16380       break;
16381
16382     default:
16383       break;
16384     }
16385   return NULL_TREE;
16386 }