fold-const.c (operand_equal_p): Handle matching of vector constructors.
[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-2015 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
10
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3.  If not see
18 <http://www.gnu.org/licenses/>.  */
19
20 /*@@ This file should be rewritten to use an arbitrary precision
21   @@ representation for "struct tree_int_cst" and "struct tree_real_cst".
22   @@ Perhaps the routines could also be used for bc/dc, and made a lib.
23   @@ The routines that translate from the ap rep should
24   @@ warn if precision et. al. is lost.
25   @@ This would also make life easier when this technology is used
26   @@ for cross-compilers.  */
27
28 /* The entry points in this file are fold, size_int_wide and size_binop.
29
30    fold takes a tree as argument and returns a simplified tree.
31
32    size_binop takes a tree code for an arithmetic operation
33    and two operands that are trees, and produces a tree for the
34    result, assuming the type comes from `sizetype'.
35
36    size_int takes an integer value, and creates a tree constant
37    with type from `sizetype'.
38
39    Note: Since the folders get called on non-gimple code as well as
40    gimple code, we need to handle GIMPLE tuples as well as their
41    corresponding tree equivalents.  */
42
43 #include "config.h"
44 #include "system.h"
45 #include "coretypes.h"
46 #include "backend.h"
47 #include "predict.h"
48 #include "tree.h"
49 #include "gimple.h"
50 #include "rtl.h"
51 #include "flags.h"
52 #include "alias.h"
53 #include "fold-const.h"
54 #include "stor-layout.h"
55 #include "calls.h"
56 #include "tree-iterator.h"
57 #include "realmpfr.h"
58 #include "insn-config.h"
59 #include "expmed.h"
60 #include "dojump.h"
61 #include "explow.h"
62 #include "emit-rtl.h"
63 #include "varasm.h"
64 #include "stmt.h"
65 #include "expr.h"
66 #include "tm_p.h"
67 #include "target.h"
68 #include "diagnostic-core.h"
69 #include "intl.h"
70 #include "langhooks.h"
71 #include "md5.h"
72 #include "internal-fn.h"
73 #include "tree-eh.h"
74 #include "gimplify.h"
75 #include "tree-dfa.h"
76 #include "builtins.h"
77 #include "cgraph.h"
78 #include "generic-match.h"
79 #include "optabs-query.h"
80 #include "gimple-fold.h"
81 #include "params.h"
82 #include "tree-ssa-operands.h"
83 #include "tree-into-ssa.h"
84
85 #ifndef LOAD_EXTEND_OP
86 #define LOAD_EXTEND_OP(M) UNKNOWN
87 #endif
88
89 /* Nonzero if we are folding constants inside an initializer; zero
90    otherwise.  */
91 int folding_initializer = 0;
92
93 /* The following constants represent a bit based encoding of GCC's
94    comparison operators.  This encoding simplifies transformations
95    on relational comparison operators, such as AND and OR.  */
96 enum comparison_code {
97   COMPCODE_FALSE = 0,
98   COMPCODE_LT = 1,
99   COMPCODE_EQ = 2,
100   COMPCODE_LE = 3,
101   COMPCODE_GT = 4,
102   COMPCODE_LTGT = 5,
103   COMPCODE_GE = 6,
104   COMPCODE_ORD = 7,
105   COMPCODE_UNORD = 8,
106   COMPCODE_UNLT = 9,
107   COMPCODE_UNEQ = 10,
108   COMPCODE_UNLE = 11,
109   COMPCODE_UNGT = 12,
110   COMPCODE_NE = 13,
111   COMPCODE_UNGE = 14,
112   COMPCODE_TRUE = 15
113 };
114
115 static bool negate_expr_p (tree);
116 static tree negate_expr (tree);
117 static tree split_tree (tree, enum tree_code, tree *, tree *, tree *, int);
118 static tree associate_trees (location_t, tree, tree, enum tree_code, 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 make_bit_field_ref (location_t, tree, tree,
125                                 HOST_WIDE_INT, HOST_WIDE_INT, int);
126 static tree optimize_bit_field_compare (location_t, enum tree_code,
127                                         tree, tree, tree);
128 static tree decode_field_reference (location_t, tree, HOST_WIDE_INT *,
129                                     HOST_WIDE_INT *,
130                                     machine_mode *, int *, int *,
131                                     tree *, tree *);
132 static int simple_operand_p (const_tree);
133 static bool simple_operand_p_2 (tree);
134 static tree range_binop (enum tree_code, tree, tree, int, tree, int);
135 static tree range_predecessor (tree);
136 static tree range_successor (tree);
137 static tree fold_range_test (location_t, enum tree_code, tree, tree, tree);
138 static tree fold_cond_expr_with_comparison (location_t, tree, tree, tree, tree);
139 static tree unextend (tree, int, int, tree);
140 static tree optimize_minmax_comparison (location_t, enum tree_code,
141                                         tree, tree, tree);
142 static tree extract_muldiv (tree, tree, enum tree_code, tree, bool *);
143 static tree extract_muldiv_1 (tree, tree, enum tree_code, tree, bool *);
144 static tree fold_binary_op_with_conditional_arg (location_t,
145                                                  enum tree_code, tree,
146                                                  tree, tree,
147                                                  tree, tree, int);
148 static tree fold_div_compare (location_t, enum tree_code, tree, tree, tree);
149 static bool reorder_operands_p (const_tree, const_tree);
150 static tree fold_negate_const (tree, tree);
151 static tree fold_not_const (const_tree, tree);
152 static tree fold_relational_const (enum tree_code, tree, tree, tree);
153 static tree fold_convert_const (enum tree_code, tree, tree);
154 static tree fold_view_convert_expr (tree, tree);
155 static bool vec_cst_ctor_to_array (tree, tree *);
156
157
158 /* Return EXPR_LOCATION of T if it is not UNKNOWN_LOCATION.
159    Otherwise, return LOC.  */
160
161 static location_t
162 expr_location_or (tree t, location_t loc)
163 {
164   location_t tloc = EXPR_LOCATION (t);
165   return tloc == UNKNOWN_LOCATION ? loc : tloc;
166 }
167
168 /* Similar to protected_set_expr_location, but never modify x in place,
169    if location can and needs to be set, unshare it.  */
170
171 static inline tree
172 protected_set_expr_location_unshare (tree x, location_t loc)
173 {
174   if (CAN_HAVE_LOCATION_P (x)
175       && EXPR_LOCATION (x) != loc
176       && !(TREE_CODE (x) == SAVE_EXPR
177            || TREE_CODE (x) == TARGET_EXPR
178            || TREE_CODE (x) == BIND_EXPR))
179     {
180       x = copy_node (x);
181       SET_EXPR_LOCATION (x, loc);
182     }
183   return x;
184 }
185 \f
186 /* If ARG2 divides ARG1 with zero remainder, carries out the exact
187    division and returns the quotient.  Otherwise returns
188    NULL_TREE.  */
189
190 tree
191 div_if_zero_remainder (const_tree arg1, const_tree arg2)
192 {
193   widest_int quo;
194
195   if (wi::multiple_of_p (wi::to_widest (arg1), wi::to_widest (arg2),
196                          SIGNED, &quo))
197     return wide_int_to_tree (TREE_TYPE (arg1), quo);
198
199   return NULL_TREE; 
200 }
201 \f
202 /* This is nonzero if we should defer warnings about undefined
203    overflow.  This facility exists because these warnings are a
204    special case.  The code to estimate loop iterations does not want
205    to issue any warnings, since it works with expressions which do not
206    occur in user code.  Various bits of cleanup code call fold(), but
207    only use the result if it has certain characteristics (e.g., is a
208    constant); that code only wants to issue a warning if the result is
209    used.  */
210
211 static int fold_deferring_overflow_warnings;
212
213 /* If a warning about undefined overflow is deferred, this is the
214    warning.  Note that this may cause us to turn two warnings into
215    one, but that is fine since it is sufficient to only give one
216    warning per expression.  */
217
218 static const char* fold_deferred_overflow_warning;
219
220 /* If a warning about undefined overflow is deferred, this is the
221    level at which the warning should be emitted.  */
222
223 static enum warn_strict_overflow_code fold_deferred_overflow_code;
224
225 /* Start deferring overflow warnings.  We could use a stack here to
226    permit nested calls, but at present it is not necessary.  */
227
228 void
229 fold_defer_overflow_warnings (void)
230 {
231   ++fold_deferring_overflow_warnings;
232 }
233
234 /* Stop deferring overflow warnings.  If there is a pending warning,
235    and ISSUE is true, then issue the warning if appropriate.  STMT is
236    the statement with which the warning should be associated (used for
237    location information); STMT may be NULL.  CODE is the level of the
238    warning--a warn_strict_overflow_code value.  This function will use
239    the smaller of CODE and the deferred code when deciding whether to
240    issue the warning.  CODE may be zero to mean to always use the
241    deferred code.  */
242
243 void
244 fold_undefer_overflow_warnings (bool issue, const gimple *stmt, int code)
245 {
246   const char *warnmsg;
247   location_t locus;
248
249   gcc_assert (fold_deferring_overflow_warnings > 0);
250   --fold_deferring_overflow_warnings;
251   if (fold_deferring_overflow_warnings > 0)
252     {
253       if (fold_deferred_overflow_warning != NULL
254           && code != 0
255           && code < (int) fold_deferred_overflow_code)
256         fold_deferred_overflow_code = (enum warn_strict_overflow_code) code;
257       return;
258     }
259
260   warnmsg = fold_deferred_overflow_warning;
261   fold_deferred_overflow_warning = NULL;
262
263   if (!issue || warnmsg == NULL)
264     return;
265
266   if (gimple_no_warning_p (stmt))
267     return;
268
269   /* Use the smallest code level when deciding to issue the
270      warning.  */
271   if (code == 0 || code > (int) fold_deferred_overflow_code)
272     code = fold_deferred_overflow_code;
273
274   if (!issue_strict_overflow_warning (code))
275     return;
276
277   if (stmt == NULL)
278     locus = input_location;
279   else
280     locus = gimple_location (stmt);
281   warning_at (locus, OPT_Wstrict_overflow, "%s", warnmsg);
282 }
283
284 /* Stop deferring overflow warnings, ignoring any deferred
285    warnings.  */
286
287 void
288 fold_undefer_and_ignore_overflow_warnings (void)
289 {
290   fold_undefer_overflow_warnings (false, NULL, 0);
291 }
292
293 /* Whether we are deferring overflow warnings.  */
294
295 bool
296 fold_deferring_overflow_warnings_p (void)
297 {
298   return fold_deferring_overflow_warnings > 0;
299 }
300
301 /* This is called when we fold something based on the fact that signed
302    overflow is undefined.  */
303
304 static void
305 fold_overflow_warning (const char* gmsgid, enum warn_strict_overflow_code wc)
306 {
307   if (fold_deferring_overflow_warnings > 0)
308     {
309       if (fold_deferred_overflow_warning == NULL
310           || wc < fold_deferred_overflow_code)
311         {
312           fold_deferred_overflow_warning = gmsgid;
313           fold_deferred_overflow_code = wc;
314         }
315     }
316   else if (issue_strict_overflow_warning (wc))
317     warning (OPT_Wstrict_overflow, gmsgid);
318 }
319 \f
320 /* Return true if the built-in mathematical function specified by CODE
321    is odd, i.e. -f(x) == f(-x).  */
322
323 bool
324 negate_mathfn_p (enum built_in_function code)
325 {
326   switch (code)
327     {
328     CASE_FLT_FN (BUILT_IN_ASIN):
329     CASE_FLT_FN (BUILT_IN_ASINH):
330     CASE_FLT_FN (BUILT_IN_ATAN):
331     CASE_FLT_FN (BUILT_IN_ATANH):
332     CASE_FLT_FN (BUILT_IN_CASIN):
333     CASE_FLT_FN (BUILT_IN_CASINH):
334     CASE_FLT_FN (BUILT_IN_CATAN):
335     CASE_FLT_FN (BUILT_IN_CATANH):
336     CASE_FLT_FN (BUILT_IN_CBRT):
337     CASE_FLT_FN (BUILT_IN_CPROJ):
338     CASE_FLT_FN (BUILT_IN_CSIN):
339     CASE_FLT_FN (BUILT_IN_CSINH):
340     CASE_FLT_FN (BUILT_IN_CTAN):
341     CASE_FLT_FN (BUILT_IN_CTANH):
342     CASE_FLT_FN (BUILT_IN_ERF):
343     CASE_FLT_FN (BUILT_IN_LLROUND):
344     CASE_FLT_FN (BUILT_IN_LROUND):
345     CASE_FLT_FN (BUILT_IN_ROUND):
346     CASE_FLT_FN (BUILT_IN_SIN):
347     CASE_FLT_FN (BUILT_IN_SINH):
348     CASE_FLT_FN (BUILT_IN_TAN):
349     CASE_FLT_FN (BUILT_IN_TANH):
350     CASE_FLT_FN (BUILT_IN_TRUNC):
351       return true;
352
353     CASE_FLT_FN (BUILT_IN_LLRINT):
354     CASE_FLT_FN (BUILT_IN_LRINT):
355     CASE_FLT_FN (BUILT_IN_NEARBYINT):
356     CASE_FLT_FN (BUILT_IN_RINT):
357       return !flag_rounding_math;
358
359     default:
360       break;
361     }
362   return false;
363 }
364
365 /* Check whether we may negate an integer constant T without causing
366    overflow.  */
367
368 bool
369 may_negate_without_overflow_p (const_tree t)
370 {
371   tree type;
372
373   gcc_assert (TREE_CODE (t) == INTEGER_CST);
374
375   type = TREE_TYPE (t);
376   if (TYPE_UNSIGNED (type))
377     return false;
378
379   return !wi::only_sign_bit_p (t);
380 }
381
382 /* Determine whether an expression T can be cheaply negated using
383    the function negate_expr without introducing undefined overflow.  */
384
385 static bool
386 negate_expr_p (tree t)
387 {
388   tree type;
389
390   if (t == 0)
391     return false;
392
393   type = TREE_TYPE (t);
394
395   STRIP_SIGN_NOPS (t);
396   switch (TREE_CODE (t))
397     {
398     case INTEGER_CST:
399       if (INTEGRAL_TYPE_P (type) && TYPE_OVERFLOW_WRAPS (type))
400         return true;
401
402       /* Check that -CST will not overflow type.  */
403       return may_negate_without_overflow_p (t);
404     case BIT_NOT_EXPR:
405       return (INTEGRAL_TYPE_P (type)
406               && TYPE_OVERFLOW_WRAPS (type));
407
408     case FIXED_CST:
409       return true;
410
411     case NEGATE_EXPR:
412       return !TYPE_OVERFLOW_SANITIZED (type);
413
414     case REAL_CST:
415       /* We want to canonicalize to positive real constants.  Pretend
416          that only negative ones can be easily negated.  */
417       return REAL_VALUE_NEGATIVE (TREE_REAL_CST (t));
418
419     case COMPLEX_CST:
420       return negate_expr_p (TREE_REALPART (t))
421              && negate_expr_p (TREE_IMAGPART (t));
422
423     case VECTOR_CST:
424       {
425         if (FLOAT_TYPE_P (TREE_TYPE (type)) || TYPE_OVERFLOW_WRAPS (type))
426           return true;
427
428         int count = TYPE_VECTOR_SUBPARTS (type), i;
429
430         for (i = 0; i < count; i++)
431           if (!negate_expr_p (VECTOR_CST_ELT (t, i)))
432             return false;
433
434         return true;
435       }
436
437     case COMPLEX_EXPR:
438       return negate_expr_p (TREE_OPERAND (t, 0))
439              && negate_expr_p (TREE_OPERAND (t, 1));
440
441     case CONJ_EXPR:
442       return negate_expr_p (TREE_OPERAND (t, 0));
443
444     case PLUS_EXPR:
445       if (HONOR_SIGN_DEPENDENT_ROUNDING (element_mode (type))
446           || HONOR_SIGNED_ZEROS (element_mode (type)))
447         return false;
448       /* -(A + B) -> (-B) - A.  */
449       if (negate_expr_p (TREE_OPERAND (t, 1))
450           && reorder_operands_p (TREE_OPERAND (t, 0),
451                                  TREE_OPERAND (t, 1)))
452         return true;
453       /* -(A + B) -> (-A) - B.  */
454       return negate_expr_p (TREE_OPERAND (t, 0));
455
456     case MINUS_EXPR:
457       /* We can't turn -(A-B) into B-A when we honor signed zeros.  */
458       return !HONOR_SIGN_DEPENDENT_ROUNDING (element_mode (type))
459              && !HONOR_SIGNED_ZEROS (element_mode (type))
460              && reorder_operands_p (TREE_OPERAND (t, 0),
461                                     TREE_OPERAND (t, 1));
462
463     case MULT_EXPR:
464       if (TYPE_UNSIGNED (TREE_TYPE (t)))
465         break;
466
467       /* Fall through.  */
468
469     case RDIV_EXPR:
470       if (! HONOR_SIGN_DEPENDENT_ROUNDING (element_mode (TREE_TYPE (t))))
471         return negate_expr_p (TREE_OPERAND (t, 1))
472                || negate_expr_p (TREE_OPERAND (t, 0));
473       break;
474
475     case TRUNC_DIV_EXPR:
476     case ROUND_DIV_EXPR:
477     case EXACT_DIV_EXPR:
478       /* In general we can't negate A / B, because if A is INT_MIN and
479          B is 1, we may turn this into INT_MIN / -1 which is undefined
480          and actually traps on some architectures.  But if overflow is
481          undefined, we can negate, because - (INT_MIN / 1) is an
482          overflow.  */
483       if (INTEGRAL_TYPE_P (TREE_TYPE (t)))
484         {
485           if (!TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (t)))
486             break;
487           /* If overflow is undefined then we have to be careful because
488              we ask whether it's ok to associate the negate with the
489              division which is not ok for example for
490              -((a - b) / c) where (-(a - b)) / c may invoke undefined
491              overflow because of negating INT_MIN.  So do not use
492              negate_expr_p here but open-code the two important cases.  */
493           if (TREE_CODE (TREE_OPERAND (t, 0)) == NEGATE_EXPR
494               || (TREE_CODE (TREE_OPERAND (t, 0)) == INTEGER_CST
495                   && may_negate_without_overflow_p (TREE_OPERAND (t, 0))))
496             return true;
497         }
498       else if (negate_expr_p (TREE_OPERAND (t, 0)))
499         return true;
500       return negate_expr_p (TREE_OPERAND (t, 1));
501
502     case NOP_EXPR:
503       /* Negate -((double)float) as (double)(-float).  */
504       if (TREE_CODE (type) == REAL_TYPE)
505         {
506           tree tem = strip_float_extensions (t);
507           if (tem != t)
508             return negate_expr_p (tem);
509         }
510       break;
511
512     case CALL_EXPR:
513       /* Negate -f(x) as f(-x).  */
514       if (negate_mathfn_p (builtin_mathfn_code (t)))
515         return negate_expr_p (CALL_EXPR_ARG (t, 0));
516       break;
517
518     case RSHIFT_EXPR:
519       /* Optimize -((int)x >> 31) into (unsigned)x >> 31 for int.  */
520       if (TREE_CODE (TREE_OPERAND (t, 1)) == INTEGER_CST)
521         {
522           tree op1 = TREE_OPERAND (t, 1);
523           if (wi::eq_p (op1, TYPE_PRECISION (type) - 1))
524             return true;
525         }
526       break;
527
528     default:
529       break;
530     }
531   return false;
532 }
533
534 /* Given T, an expression, return a folded tree for -T or NULL_TREE, if no
535    simplification is possible.
536    If negate_expr_p would return true for T, NULL_TREE will never be
537    returned.  */
538
539 static tree
540 fold_negate_expr (location_t loc, tree t)
541 {
542   tree type = TREE_TYPE (t);
543   tree tem;
544
545   switch (TREE_CODE (t))
546     {
547     /* Convert - (~A) to A + 1.  */
548     case BIT_NOT_EXPR:
549       if (INTEGRAL_TYPE_P (type))
550         return fold_build2_loc (loc, PLUS_EXPR, type, TREE_OPERAND (t, 0),
551                             build_one_cst (type));
552       break;
553
554     case INTEGER_CST:
555       tem = fold_negate_const (t, type);
556       if (TREE_OVERFLOW (tem) == TREE_OVERFLOW (t)
557           || (ANY_INTEGRAL_TYPE_P (type)
558               && !TYPE_OVERFLOW_TRAPS (type)
559               && TYPE_OVERFLOW_WRAPS (type))
560           || (flag_sanitize & SANITIZE_SI_OVERFLOW) == 0)
561         return tem;
562       break;
563
564     case REAL_CST:
565       tem = fold_negate_const (t, type);
566       return tem;
567
568     case FIXED_CST:
569       tem = fold_negate_const (t, type);
570       return tem;
571
572     case COMPLEX_CST:
573       {
574         tree rpart = fold_negate_expr (loc, TREE_REALPART (t));
575         tree ipart = fold_negate_expr (loc, TREE_IMAGPART (t));
576         if (rpart && ipart)
577           return build_complex (type, rpart, ipart);
578       }
579       break;
580
581     case VECTOR_CST:
582       {
583         int count = TYPE_VECTOR_SUBPARTS (type), i;
584         tree *elts = XALLOCAVEC (tree, count);
585
586         for (i = 0; i < count; i++)
587           {
588             elts[i] = fold_negate_expr (loc, VECTOR_CST_ELT (t, i));
589             if (elts[i] == NULL_TREE)
590               return NULL_TREE;
591           }
592
593         return build_vector (type, elts);
594       }
595
596     case COMPLEX_EXPR:
597       if (negate_expr_p (t))
598         return fold_build2_loc (loc, COMPLEX_EXPR, type,
599                             fold_negate_expr (loc, TREE_OPERAND (t, 0)),
600                             fold_negate_expr (loc, TREE_OPERAND (t, 1)));
601       break;
602
603     case CONJ_EXPR:
604       if (negate_expr_p (t))
605         return fold_build1_loc (loc, CONJ_EXPR, type,
606                             fold_negate_expr (loc, TREE_OPERAND (t, 0)));
607       break;
608
609     case NEGATE_EXPR:
610       if (!TYPE_OVERFLOW_SANITIZED (type))
611         return TREE_OPERAND (t, 0);
612       break;
613
614     case PLUS_EXPR:
615       if (!HONOR_SIGN_DEPENDENT_ROUNDING (element_mode (type))
616           && !HONOR_SIGNED_ZEROS (element_mode (type)))
617         {
618           /* -(A + B) -> (-B) - A.  */
619           if (negate_expr_p (TREE_OPERAND (t, 1))
620               && reorder_operands_p (TREE_OPERAND (t, 0),
621                                      TREE_OPERAND (t, 1)))
622             {
623               tem = negate_expr (TREE_OPERAND (t, 1));
624               return fold_build2_loc (loc, MINUS_EXPR, type,
625                                   tem, TREE_OPERAND (t, 0));
626             }
627
628           /* -(A + B) -> (-A) - B.  */
629           if (negate_expr_p (TREE_OPERAND (t, 0)))
630             {
631               tem = negate_expr (TREE_OPERAND (t, 0));
632               return fold_build2_loc (loc, MINUS_EXPR, type,
633                                   tem, TREE_OPERAND (t, 1));
634             }
635         }
636       break;
637
638     case MINUS_EXPR:
639       /* - (A - B) -> B - A  */
640       if (!HONOR_SIGN_DEPENDENT_ROUNDING (element_mode (type))
641           && !HONOR_SIGNED_ZEROS (element_mode (type))
642           && reorder_operands_p (TREE_OPERAND (t, 0), TREE_OPERAND (t, 1)))
643         return fold_build2_loc (loc, MINUS_EXPR, type,
644                             TREE_OPERAND (t, 1), TREE_OPERAND (t, 0));
645       break;
646
647     case MULT_EXPR:
648       if (TYPE_UNSIGNED (type))
649         break;
650
651       /* Fall through.  */
652
653     case RDIV_EXPR:
654       if (! HONOR_SIGN_DEPENDENT_ROUNDING (element_mode (type)))
655         {
656           tem = TREE_OPERAND (t, 1);
657           if (negate_expr_p (tem))
658             return fold_build2_loc (loc, TREE_CODE (t), type,
659                                 TREE_OPERAND (t, 0), negate_expr (tem));
660           tem = TREE_OPERAND (t, 0);
661           if (negate_expr_p (tem))
662             return fold_build2_loc (loc, TREE_CODE (t), type,
663                                 negate_expr (tem), TREE_OPERAND (t, 1));
664         }
665       break;
666
667     case TRUNC_DIV_EXPR:
668     case ROUND_DIV_EXPR:
669     case EXACT_DIV_EXPR:
670       /* In general we can't negate A / B, because if A is INT_MIN and
671          B is 1, we may turn this into INT_MIN / -1 which is undefined
672          and actually traps on some architectures.  But if overflow is
673          undefined, we can negate, because - (INT_MIN / 1) is an
674          overflow.  */
675       if (!INTEGRAL_TYPE_P (type) || TYPE_OVERFLOW_UNDEFINED (type))
676         {
677           const char * const warnmsg = G_("assuming signed overflow does not "
678                                           "occur when negating a division");
679           tem = TREE_OPERAND (t, 1);
680           if (negate_expr_p (tem))
681             {
682               if (INTEGRAL_TYPE_P (type)
683                   && (TREE_CODE (tem) != INTEGER_CST
684                       || integer_onep (tem)))
685                 fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_MISC);
686               return fold_build2_loc (loc, TREE_CODE (t), type,
687                                   TREE_OPERAND (t, 0), negate_expr (tem));
688             }
689           /* If overflow is undefined then we have to be careful because
690              we ask whether it's ok to associate the negate with the
691              division which is not ok for example for
692              -((a - b) / c) where (-(a - b)) / c may invoke undefined
693              overflow because of negating INT_MIN.  So do not use
694              negate_expr_p here but open-code the two important cases.  */
695           tem = TREE_OPERAND (t, 0);
696           if ((INTEGRAL_TYPE_P (type)
697                && (TREE_CODE (tem) == NEGATE_EXPR
698                    || (TREE_CODE (tem) == INTEGER_CST
699                        && may_negate_without_overflow_p (tem))))
700               || !INTEGRAL_TYPE_P (type))
701             return fold_build2_loc (loc, TREE_CODE (t), type,
702                                     negate_expr (tem), TREE_OPERAND (t, 1));
703         }
704       break;
705
706     case NOP_EXPR:
707       /* Convert -((double)float) into (double)(-float).  */
708       if (TREE_CODE (type) == REAL_TYPE)
709         {
710           tem = strip_float_extensions (t);
711           if (tem != t && negate_expr_p (tem))
712             return fold_convert_loc (loc, type, negate_expr (tem));
713         }
714       break;
715
716     case CALL_EXPR:
717       /* Negate -f(x) as f(-x).  */
718       if (negate_mathfn_p (builtin_mathfn_code (t))
719           && negate_expr_p (CALL_EXPR_ARG (t, 0)))
720         {
721           tree fndecl, arg;
722
723           fndecl = get_callee_fndecl (t);
724           arg = negate_expr (CALL_EXPR_ARG (t, 0));
725           return build_call_expr_loc (loc, fndecl, 1, arg);
726         }
727       break;
728
729     case RSHIFT_EXPR:
730       /* Optimize -((int)x >> 31) into (unsigned)x >> 31 for int.  */
731       if (TREE_CODE (TREE_OPERAND (t, 1)) == INTEGER_CST)
732         {
733           tree op1 = TREE_OPERAND (t, 1);
734           if (wi::eq_p (op1, TYPE_PRECISION (type) - 1))
735             {
736               tree ntype = TYPE_UNSIGNED (type)
737                            ? signed_type_for (type)
738                            : unsigned_type_for (type);
739               tree temp = fold_convert_loc (loc, ntype, TREE_OPERAND (t, 0));
740               temp = fold_build2_loc (loc, RSHIFT_EXPR, ntype, temp, op1);
741               return fold_convert_loc (loc, type, temp);
742             }
743         }
744       break;
745
746     default:
747       break;
748     }
749
750   return NULL_TREE;
751 }
752
753 /* Like fold_negate_expr, but return a NEGATE_EXPR tree, if T can not be
754    negated in a simpler way.  Also allow for T to be NULL_TREE, in which case
755    return NULL_TREE. */
756
757 static tree
758 negate_expr (tree t)
759 {
760   tree type, tem;
761   location_t loc;
762
763   if (t == NULL_TREE)
764     return NULL_TREE;
765
766   loc = EXPR_LOCATION (t);
767   type = TREE_TYPE (t);
768   STRIP_SIGN_NOPS (t);
769
770   tem = fold_negate_expr (loc, t);
771   if (!tem)
772     tem = build1_loc (loc, NEGATE_EXPR, TREE_TYPE (t), t);
773   return fold_convert_loc (loc, type, tem);
774 }
775 \f
776 /* Split a tree IN into a constant, literal and variable parts that could be
777    combined with CODE to make IN.  "constant" means an expression with
778    TREE_CONSTANT but that isn't an actual constant.  CODE must be a
779    commutative arithmetic operation.  Store the constant part into *CONP,
780    the literal in *LITP and return the variable part.  If a part isn't
781    present, set it to null.  If the tree does not decompose in this way,
782    return the entire tree as the variable part and the other parts as null.
783
784    If CODE is PLUS_EXPR we also split trees that use MINUS_EXPR.  In that
785    case, we negate an operand that was subtracted.  Except if it is a
786    literal for which we use *MINUS_LITP instead.
787
788    If NEGATE_P is true, we are negating all of IN, again except a literal
789    for which we use *MINUS_LITP instead.
790
791    If IN is itself a literal or constant, return it as appropriate.
792
793    Note that we do not guarantee that any of the three values will be the
794    same type as IN, but they will have the same signedness and mode.  */
795
796 static tree
797 split_tree (tree in, enum tree_code code, tree *conp, tree *litp,
798             tree *minus_litp, int negate_p)
799 {
800   tree var = 0;
801
802   *conp = 0;
803   *litp = 0;
804   *minus_litp = 0;
805
806   /* Strip any conversions that don't change the machine mode or signedness.  */
807   STRIP_SIGN_NOPS (in);
808
809   if (TREE_CODE (in) == INTEGER_CST || TREE_CODE (in) == REAL_CST
810       || TREE_CODE (in) == FIXED_CST)
811     *litp = in;
812   else if (TREE_CODE (in) == code
813            || ((! FLOAT_TYPE_P (TREE_TYPE (in)) || flag_associative_math)
814                && ! SAT_FIXED_POINT_TYPE_P (TREE_TYPE (in))
815                /* We can associate addition and subtraction together (even
816                   though the C standard doesn't say so) for integers because
817                   the value is not affected.  For reals, the value might be
818                   affected, so we can't.  */
819                && ((code == PLUS_EXPR && TREE_CODE (in) == MINUS_EXPR)
820                    || (code == MINUS_EXPR && TREE_CODE (in) == PLUS_EXPR))))
821     {
822       tree op0 = TREE_OPERAND (in, 0);
823       tree op1 = TREE_OPERAND (in, 1);
824       int neg1_p = TREE_CODE (in) == MINUS_EXPR;
825       int neg_litp_p = 0, neg_conp_p = 0, neg_var_p = 0;
826
827       /* First see if either of the operands is a literal, then a constant.  */
828       if (TREE_CODE (op0) == INTEGER_CST || TREE_CODE (op0) == REAL_CST
829           || TREE_CODE (op0) == FIXED_CST)
830         *litp = op0, op0 = 0;
831       else if (TREE_CODE (op1) == INTEGER_CST || TREE_CODE (op1) == REAL_CST
832                || TREE_CODE (op1) == FIXED_CST)
833         *litp = op1, neg_litp_p = neg1_p, op1 = 0;
834
835       if (op0 != 0 && TREE_CONSTANT (op0))
836         *conp = op0, op0 = 0;
837       else if (op1 != 0 && TREE_CONSTANT (op1))
838         *conp = op1, neg_conp_p = neg1_p, op1 = 0;
839
840       /* If we haven't dealt with either operand, this is not a case we can
841          decompose.  Otherwise, VAR is either of the ones remaining, if any.  */
842       if (op0 != 0 && op1 != 0)
843         var = in;
844       else if (op0 != 0)
845         var = op0;
846       else
847         var = op1, neg_var_p = neg1_p;
848
849       /* Now do any needed negations.  */
850       if (neg_litp_p)
851         *minus_litp = *litp, *litp = 0;
852       if (neg_conp_p)
853         *conp = negate_expr (*conp);
854       if (neg_var_p)
855         var = negate_expr (var);
856     }
857   else if (TREE_CODE (in) == BIT_NOT_EXPR
858            && code == PLUS_EXPR)
859     {
860       /* -X - 1 is folded to ~X, undo that here.  */
861       *minus_litp = build_one_cst (TREE_TYPE (in));
862       var = negate_expr (TREE_OPERAND (in, 0));
863     }
864   else if (TREE_CONSTANT (in))
865     *conp = in;
866   else
867     var = in;
868
869   if (negate_p)
870     {
871       if (*litp)
872         *minus_litp = *litp, *litp = 0;
873       else if (*minus_litp)
874         *litp = *minus_litp, *minus_litp = 0;
875       *conp = negate_expr (*conp);
876       var = negate_expr (var);
877     }
878
879   return var;
880 }
881
882 /* Re-associate trees split by the above function.  T1 and T2 are
883    either expressions to associate or null.  Return the new
884    expression, if any.  LOC is the location of the new expression.  If
885    we build an operation, do it in TYPE and with CODE.  */
886
887 static tree
888 associate_trees (location_t loc, tree t1, tree t2, enum tree_code code, tree type)
889 {
890   if (t1 == 0)
891     return t2;
892   else if (t2 == 0)
893     return t1;
894
895   /* If either input is CODE, a PLUS_EXPR, or a MINUS_EXPR, don't
896      try to fold this since we will have infinite recursion.  But do
897      deal with any NEGATE_EXPRs.  */
898   if (TREE_CODE (t1) == code || TREE_CODE (t2) == code
899       || TREE_CODE (t1) == MINUS_EXPR || TREE_CODE (t2) == MINUS_EXPR)
900     {
901       if (code == PLUS_EXPR)
902         {
903           if (TREE_CODE (t1) == NEGATE_EXPR)
904             return build2_loc (loc, MINUS_EXPR, type,
905                                fold_convert_loc (loc, type, t2),
906                                fold_convert_loc (loc, type,
907                                                  TREE_OPERAND (t1, 0)));
908           else if (TREE_CODE (t2) == NEGATE_EXPR)
909             return build2_loc (loc, MINUS_EXPR, type,
910                                fold_convert_loc (loc, type, t1),
911                                fold_convert_loc (loc, type,
912                                                  TREE_OPERAND (t2, 0)));
913           else if (integer_zerop (t2))
914             return fold_convert_loc (loc, type, t1);
915         }
916       else if (code == MINUS_EXPR)
917         {
918           if (integer_zerop (t2))
919             return fold_convert_loc (loc, type, t1);
920         }
921
922       return build2_loc (loc, code, type, fold_convert_loc (loc, type, t1),
923                          fold_convert_loc (loc, type, t2));
924     }
925
926   return fold_build2_loc (loc, code, type, fold_convert_loc (loc, type, t1),
927                           fold_convert_loc (loc, type, t2));
928 }
929 \f
930 /* Check whether TYPE1 and TYPE2 are equivalent integer types, suitable
931    for use in int_const_binop, size_binop and size_diffop.  */
932
933 static bool
934 int_binop_types_match_p (enum tree_code code, const_tree type1, const_tree type2)
935 {
936   if (!INTEGRAL_TYPE_P (type1) && !POINTER_TYPE_P (type1))
937     return false;
938   if (!INTEGRAL_TYPE_P (type2) && !POINTER_TYPE_P (type2))
939     return false;
940
941   switch (code)
942     {
943     case LSHIFT_EXPR:
944     case RSHIFT_EXPR:
945     case LROTATE_EXPR:
946     case RROTATE_EXPR:
947       return true;
948
949     default:
950       break;
951     }
952
953   return TYPE_UNSIGNED (type1) == TYPE_UNSIGNED (type2)
954          && TYPE_PRECISION (type1) == TYPE_PRECISION (type2)
955          && TYPE_MODE (type1) == TYPE_MODE (type2);
956 }
957
958
959 /* Combine two integer constants ARG1 and ARG2 under operation CODE
960    to produce a new constant.  Return NULL_TREE if we don't know how
961    to evaluate CODE at compile-time.  */
962
963 static tree
964 int_const_binop_1 (enum tree_code code, const_tree arg1, const_tree parg2,
965                    int overflowable)
966 {
967   wide_int res;
968   tree t;
969   tree type = TREE_TYPE (arg1);
970   signop sign = TYPE_SIGN (type);
971   bool overflow = false;
972
973   wide_int arg2 = wide_int::from (parg2, TYPE_PRECISION (type),
974                                   TYPE_SIGN (TREE_TYPE (parg2)));
975
976   switch (code)
977     {
978     case BIT_IOR_EXPR:
979       res = wi::bit_or (arg1, arg2);
980       break;
981
982     case BIT_XOR_EXPR:
983       res = wi::bit_xor (arg1, arg2);
984       break;
985
986     case BIT_AND_EXPR:
987       res = wi::bit_and (arg1, arg2);
988       break;
989
990     case RSHIFT_EXPR:
991     case LSHIFT_EXPR:
992       if (wi::neg_p (arg2))
993         {
994           arg2 = -arg2;
995           if (code == RSHIFT_EXPR)
996             code = LSHIFT_EXPR;
997           else
998             code = RSHIFT_EXPR;
999         }
1000
1001       if (code == RSHIFT_EXPR)
1002         /* It's unclear from the C standard whether shifts can overflow.
1003            The following code ignores overflow; perhaps a C standard
1004            interpretation ruling is needed.  */
1005         res = wi::rshift (arg1, arg2, sign);
1006       else
1007         res = wi::lshift (arg1, arg2);
1008       break;
1009
1010     case RROTATE_EXPR:
1011     case LROTATE_EXPR:
1012       if (wi::neg_p (arg2))
1013         {
1014           arg2 = -arg2;
1015           if (code == RROTATE_EXPR)
1016             code = LROTATE_EXPR;
1017           else
1018             code = RROTATE_EXPR;
1019         }
1020
1021       if (code == RROTATE_EXPR)
1022         res = wi::rrotate (arg1, arg2);
1023       else
1024         res = wi::lrotate (arg1, arg2);
1025       break;
1026
1027     case PLUS_EXPR:
1028       res = wi::add (arg1, arg2, sign, &overflow);
1029       break;
1030
1031     case MINUS_EXPR:
1032       res = wi::sub (arg1, arg2, sign, &overflow);
1033       break;
1034
1035     case MULT_EXPR:
1036       res = wi::mul (arg1, arg2, sign, &overflow);
1037       break;
1038
1039     case MULT_HIGHPART_EXPR:
1040       res = wi::mul_high (arg1, arg2, sign);
1041       break;
1042
1043     case TRUNC_DIV_EXPR:
1044     case EXACT_DIV_EXPR:
1045       if (arg2 == 0)
1046         return NULL_TREE;
1047       res = wi::div_trunc (arg1, arg2, sign, &overflow);
1048       break;
1049
1050     case FLOOR_DIV_EXPR:
1051       if (arg2 == 0)
1052         return NULL_TREE;
1053       res = wi::div_floor (arg1, arg2, sign, &overflow);
1054       break;
1055
1056     case CEIL_DIV_EXPR:
1057       if (arg2 == 0)
1058         return NULL_TREE;
1059       res = wi::div_ceil (arg1, arg2, sign, &overflow);
1060       break;
1061
1062     case ROUND_DIV_EXPR:
1063       if (arg2 == 0)
1064         return NULL_TREE;
1065       res = wi::div_round (arg1, arg2, sign, &overflow);
1066       break;
1067
1068     case TRUNC_MOD_EXPR:
1069       if (arg2 == 0)
1070         return NULL_TREE;
1071       res = wi::mod_trunc (arg1, arg2, sign, &overflow);
1072       break;
1073
1074     case FLOOR_MOD_EXPR:
1075       if (arg2 == 0)
1076         return NULL_TREE;
1077       res = wi::mod_floor (arg1, arg2, sign, &overflow);
1078       break;
1079
1080     case CEIL_MOD_EXPR:
1081       if (arg2 == 0)
1082         return NULL_TREE;
1083       res = wi::mod_ceil (arg1, arg2, sign, &overflow);
1084       break;
1085
1086     case ROUND_MOD_EXPR:
1087       if (arg2 == 0)
1088         return NULL_TREE;
1089       res = wi::mod_round (arg1, arg2, sign, &overflow);
1090       break;
1091
1092     case MIN_EXPR:
1093       res = wi::min (arg1, arg2, sign);
1094       break;
1095
1096     case MAX_EXPR:
1097       res = wi::max (arg1, arg2, sign);
1098       break;
1099
1100     default:
1101       return NULL_TREE;
1102     }
1103
1104   t = force_fit_type (type, res, overflowable,
1105                       (((sign == SIGNED || overflowable == -1)
1106                         && overflow)
1107                        | TREE_OVERFLOW (arg1) | TREE_OVERFLOW (parg2)));
1108
1109   return t;
1110 }
1111
1112 tree
1113 int_const_binop (enum tree_code code, const_tree arg1, const_tree arg2)
1114 {
1115   return int_const_binop_1 (code, arg1, arg2, 1);
1116 }
1117
1118 /* Combine two constants ARG1 and ARG2 under operation CODE to produce a new
1119    constant.  We assume ARG1 and ARG2 have the same data type, or at least
1120    are the same kind of constant and the same machine mode.  Return zero if
1121    combining the constants is not allowed in the current operating mode.  */
1122
1123 static tree
1124 const_binop (enum tree_code code, tree arg1, tree arg2)
1125 {
1126   /* Sanity check for the recursive cases.  */
1127   if (!arg1 || !arg2)
1128     return NULL_TREE;
1129
1130   STRIP_NOPS (arg1);
1131   STRIP_NOPS (arg2);
1132
1133   if (TREE_CODE (arg1) == INTEGER_CST && TREE_CODE (arg2) == INTEGER_CST)
1134     {
1135       if (code == POINTER_PLUS_EXPR)
1136         return int_const_binop (PLUS_EXPR,
1137                                 arg1, fold_convert (TREE_TYPE (arg1), arg2));
1138
1139       return int_const_binop (code, arg1, arg2);
1140     }
1141
1142   if (TREE_CODE (arg1) == REAL_CST && TREE_CODE (arg2) == REAL_CST)
1143     {
1144       machine_mode mode;
1145       REAL_VALUE_TYPE d1;
1146       REAL_VALUE_TYPE d2;
1147       REAL_VALUE_TYPE value;
1148       REAL_VALUE_TYPE result;
1149       bool inexact;
1150       tree t, type;
1151
1152       /* The following codes are handled by real_arithmetic.  */
1153       switch (code)
1154         {
1155         case PLUS_EXPR:
1156         case MINUS_EXPR:
1157         case MULT_EXPR:
1158         case RDIV_EXPR:
1159         case MIN_EXPR:
1160         case MAX_EXPR:
1161           break;
1162
1163         default:
1164           return NULL_TREE;
1165         }
1166
1167       d1 = TREE_REAL_CST (arg1);
1168       d2 = TREE_REAL_CST (arg2);
1169
1170       type = TREE_TYPE (arg1);
1171       mode = TYPE_MODE (type);
1172
1173       /* Don't perform operation if we honor signaling NaNs and
1174          either operand is a NaN.  */
1175       if (HONOR_SNANS (mode)
1176           && (REAL_VALUE_ISNAN (d1) || REAL_VALUE_ISNAN (d2)))
1177         return NULL_TREE;
1178
1179       /* Don't perform operation if it would raise a division
1180          by zero exception.  */
1181       if (code == RDIV_EXPR
1182           && real_equal (&d2, &dconst0)
1183           && (flag_trapping_math || ! MODE_HAS_INFINITIES (mode)))
1184         return NULL_TREE;
1185
1186       /* If either operand is a NaN, just return it.  Otherwise, set up
1187          for floating-point trap; we return an overflow.  */
1188       if (REAL_VALUE_ISNAN (d1))
1189         return arg1;
1190       else if (REAL_VALUE_ISNAN (d2))
1191         return arg2;
1192
1193       inexact = real_arithmetic (&value, code, &d1, &d2);
1194       real_convert (&result, mode, &value);
1195
1196       /* Don't constant fold this floating point operation if
1197          the result has overflowed and flag_trapping_math.  */
1198       if (flag_trapping_math
1199           && MODE_HAS_INFINITIES (mode)
1200           && REAL_VALUE_ISINF (result)
1201           && !REAL_VALUE_ISINF (d1)
1202           && !REAL_VALUE_ISINF (d2))
1203         return NULL_TREE;
1204
1205       /* Don't constant fold this floating point operation if the
1206          result may dependent upon the run-time rounding mode and
1207          flag_rounding_math is set, or if GCC's software emulation
1208          is unable to accurately represent the result.  */
1209       if ((flag_rounding_math
1210            || (MODE_COMPOSITE_P (mode) && !flag_unsafe_math_optimizations))
1211           && (inexact || !real_identical (&result, &value)))
1212         return NULL_TREE;
1213
1214       t = build_real (type, result);
1215
1216       TREE_OVERFLOW (t) = TREE_OVERFLOW (arg1) | TREE_OVERFLOW (arg2);
1217       return t;
1218     }
1219
1220   if (TREE_CODE (arg1) == FIXED_CST)
1221     {
1222       FIXED_VALUE_TYPE f1;
1223       FIXED_VALUE_TYPE f2;
1224       FIXED_VALUE_TYPE result;
1225       tree t, type;
1226       int sat_p;
1227       bool overflow_p;
1228
1229       /* The following codes are handled by fixed_arithmetic.  */
1230       switch (code)
1231         {
1232         case PLUS_EXPR:
1233         case MINUS_EXPR:
1234         case MULT_EXPR:
1235         case TRUNC_DIV_EXPR:
1236           if (TREE_CODE (arg2) != FIXED_CST)
1237             return NULL_TREE;
1238           f2 = TREE_FIXED_CST (arg2);
1239           break;
1240
1241         case LSHIFT_EXPR:
1242         case RSHIFT_EXPR:
1243           {
1244             if (TREE_CODE (arg2) != INTEGER_CST)
1245               return NULL_TREE;
1246             wide_int w2 = arg2;
1247             f2.data.high = w2.elt (1);
1248             f2.data.low = w2.elt (0);
1249             f2.mode = SImode;
1250           }
1251           break;
1252
1253         default:
1254           return NULL_TREE;
1255         }
1256
1257       f1 = TREE_FIXED_CST (arg1);
1258       type = TREE_TYPE (arg1);
1259       sat_p = TYPE_SATURATING (type);
1260       overflow_p = fixed_arithmetic (&result, code, &f1, &f2, sat_p);
1261       t = build_fixed (type, result);
1262       /* Propagate overflow flags.  */
1263       if (overflow_p | TREE_OVERFLOW (arg1) | TREE_OVERFLOW (arg2))
1264         TREE_OVERFLOW (t) = 1;
1265       return t;
1266     }
1267
1268   if (TREE_CODE (arg1) == COMPLEX_CST && TREE_CODE (arg2) == COMPLEX_CST)
1269     {
1270       tree type = TREE_TYPE (arg1);
1271       tree r1 = TREE_REALPART (arg1);
1272       tree i1 = TREE_IMAGPART (arg1);
1273       tree r2 = TREE_REALPART (arg2);
1274       tree i2 = TREE_IMAGPART (arg2);
1275       tree real, imag;
1276
1277       switch (code)
1278         {
1279         case PLUS_EXPR:
1280         case MINUS_EXPR:
1281           real = const_binop (code, r1, r2);
1282           imag = const_binop (code, i1, i2);
1283           break;
1284
1285         case MULT_EXPR:
1286           if (COMPLEX_FLOAT_TYPE_P (type))
1287             return do_mpc_arg2 (arg1, arg2, type,
1288                                 /* do_nonfinite= */ folding_initializer,
1289                                 mpc_mul);
1290
1291           real = const_binop (MINUS_EXPR,
1292                               const_binop (MULT_EXPR, r1, r2),
1293                               const_binop (MULT_EXPR, i1, i2));
1294           imag = const_binop (PLUS_EXPR,
1295                               const_binop (MULT_EXPR, r1, i2),
1296                               const_binop (MULT_EXPR, i1, r2));
1297           break;
1298
1299         case RDIV_EXPR:
1300           if (COMPLEX_FLOAT_TYPE_P (type))
1301             return do_mpc_arg2 (arg1, arg2, type,
1302                                 /* do_nonfinite= */ folding_initializer,
1303                                 mpc_div);
1304           /* Fallthru ... */
1305         case TRUNC_DIV_EXPR:
1306         case CEIL_DIV_EXPR:
1307         case FLOOR_DIV_EXPR:
1308         case ROUND_DIV_EXPR:
1309           if (flag_complex_method == 0)
1310           {
1311             /* Keep this algorithm in sync with
1312                tree-complex.c:expand_complex_div_straight().
1313
1314                Expand complex division to scalars, straightforward algorithm.
1315                a / b = ((ar*br + ai*bi)/t) + i((ai*br - ar*bi)/t)
1316                t = br*br + bi*bi
1317             */
1318             tree magsquared
1319               = const_binop (PLUS_EXPR,
1320                              const_binop (MULT_EXPR, r2, r2),
1321                              const_binop (MULT_EXPR, i2, i2));
1322             tree t1
1323               = const_binop (PLUS_EXPR,
1324                              const_binop (MULT_EXPR, r1, r2),
1325                              const_binop (MULT_EXPR, i1, i2));
1326             tree t2
1327               = const_binop (MINUS_EXPR,
1328                              const_binop (MULT_EXPR, i1, r2),
1329                              const_binop (MULT_EXPR, r1, i2));
1330
1331             real = const_binop (code, t1, magsquared);
1332             imag = const_binop (code, t2, magsquared);
1333           }
1334           else
1335           {
1336             /* Keep this algorithm in sync with
1337                tree-complex.c:expand_complex_div_wide().
1338
1339                Expand complex division to scalars, modified algorithm to minimize
1340                overflow with wide input ranges.  */
1341             tree compare = fold_build2 (LT_EXPR, boolean_type_node,
1342                                         fold_abs_const (r2, TREE_TYPE (type)),
1343                                         fold_abs_const (i2, TREE_TYPE (type)));
1344
1345             if (integer_nonzerop (compare))
1346               {
1347                 /* In the TRUE branch, we compute
1348                    ratio = br/bi;
1349                    div = (br * ratio) + bi;
1350                    tr = (ar * ratio) + ai;
1351                    ti = (ai * ratio) - ar;
1352                    tr = tr / div;
1353                    ti = ti / div;  */
1354                 tree ratio = const_binop (code, r2, i2);
1355                 tree div = const_binop (PLUS_EXPR, i2,
1356                                         const_binop (MULT_EXPR, r2, ratio));
1357                 real = const_binop (MULT_EXPR, r1, ratio);
1358                 real = const_binop (PLUS_EXPR, real, i1);
1359                 real = const_binop (code, real, div);
1360
1361                 imag = const_binop (MULT_EXPR, i1, ratio);
1362                 imag = const_binop (MINUS_EXPR, imag, r1);
1363                 imag = const_binop (code, imag, div);
1364               }
1365             else
1366               {
1367                 /* In the FALSE branch, we compute
1368                    ratio = d/c;
1369                    divisor = (d * ratio) + c;
1370                    tr = (b * ratio) + a;
1371                    ti = b - (a * ratio);
1372                    tr = tr / div;
1373                    ti = ti / div;  */
1374                 tree ratio = const_binop (code, i2, r2);
1375                 tree div = const_binop (PLUS_EXPR, r2,
1376                                         const_binop (MULT_EXPR, i2, ratio));
1377
1378                 real = const_binop (MULT_EXPR, i1, ratio);
1379                 real = const_binop (PLUS_EXPR, real, r1);
1380                 real = const_binop (code, real, div);
1381
1382                 imag = const_binop (MULT_EXPR, r1, ratio);
1383                 imag = const_binop (MINUS_EXPR, i1, imag);
1384                 imag = const_binop (code, imag, div);
1385               }
1386           }
1387           break;
1388
1389         default:
1390           return NULL_TREE;
1391         }
1392
1393       if (real && imag)
1394         return build_complex (type, real, imag);
1395     }
1396
1397   if (TREE_CODE (arg1) == VECTOR_CST
1398       && TREE_CODE (arg2) == VECTOR_CST)
1399     {
1400       tree type = TREE_TYPE (arg1);
1401       int count = TYPE_VECTOR_SUBPARTS (type), i;
1402       tree *elts = XALLOCAVEC (tree, count);
1403
1404       for (i = 0; i < count; i++)
1405         {
1406           tree elem1 = VECTOR_CST_ELT (arg1, i);
1407           tree elem2 = VECTOR_CST_ELT (arg2, i);
1408
1409           elts[i] = const_binop (code, elem1, elem2);
1410
1411           /* It is possible that const_binop cannot handle the given
1412              code and return NULL_TREE */
1413           if (elts[i] == NULL_TREE)
1414             return NULL_TREE;
1415         }
1416
1417       return build_vector (type, elts);
1418     }
1419
1420   /* Shifts allow a scalar offset for a vector.  */
1421   if (TREE_CODE (arg1) == VECTOR_CST
1422       && TREE_CODE (arg2) == INTEGER_CST)
1423     {
1424       tree type = TREE_TYPE (arg1);
1425       int count = TYPE_VECTOR_SUBPARTS (type), i;
1426       tree *elts = XALLOCAVEC (tree, count);
1427
1428       for (i = 0; i < count; i++)
1429         {
1430           tree elem1 = VECTOR_CST_ELT (arg1, i);
1431
1432           elts[i] = const_binop (code, elem1, arg2);
1433
1434           /* It is possible that const_binop cannot handle the given
1435              code and return NULL_TREE.  */
1436           if (elts[i] == NULL_TREE)
1437             return NULL_TREE;
1438         }
1439
1440       return build_vector (type, elts);
1441     }
1442   return NULL_TREE;
1443 }
1444
1445 /* Overload that adds a TYPE parameter to be able to dispatch
1446    to fold_relational_const.  */
1447
1448 tree
1449 const_binop (enum tree_code code, tree type, tree arg1, tree arg2)
1450 {
1451   if (TREE_CODE_CLASS (code) == tcc_comparison)
1452     return fold_relational_const (code, type, arg1, arg2);
1453
1454   /* ???  Until we make the const_binop worker take the type of the
1455      result as argument put those cases that need it here.  */
1456   switch (code)
1457     {
1458     case COMPLEX_EXPR:
1459       if ((TREE_CODE (arg1) == REAL_CST
1460            && TREE_CODE (arg2) == REAL_CST)
1461           || (TREE_CODE (arg1) == INTEGER_CST
1462               && TREE_CODE (arg2) == INTEGER_CST))
1463         return build_complex (type, arg1, arg2);
1464       return NULL_TREE;
1465
1466     case VEC_PACK_TRUNC_EXPR:
1467     case VEC_PACK_FIX_TRUNC_EXPR:
1468       {
1469         unsigned int nelts = TYPE_VECTOR_SUBPARTS (type), i;
1470         tree *elts;
1471
1472         gcc_assert (TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg1)) == nelts / 2
1473                     && TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg2)) == nelts / 2);
1474         if (TREE_CODE (arg1) != VECTOR_CST
1475             || TREE_CODE (arg2) != VECTOR_CST)
1476           return NULL_TREE;
1477
1478         elts = XALLOCAVEC (tree, nelts);
1479         if (!vec_cst_ctor_to_array (arg1, elts)
1480             || !vec_cst_ctor_to_array (arg2, elts + nelts / 2))
1481           return NULL_TREE;
1482
1483         for (i = 0; i < nelts; i++)
1484           {
1485             elts[i] = fold_convert_const (code == VEC_PACK_TRUNC_EXPR
1486                                           ? NOP_EXPR : FIX_TRUNC_EXPR,
1487                                           TREE_TYPE (type), elts[i]);
1488             if (elts[i] == NULL_TREE || !CONSTANT_CLASS_P (elts[i]))
1489               return NULL_TREE;
1490           }
1491
1492         return build_vector (type, elts);
1493       }
1494
1495     case VEC_WIDEN_MULT_LO_EXPR:
1496     case VEC_WIDEN_MULT_HI_EXPR:
1497     case VEC_WIDEN_MULT_EVEN_EXPR:
1498     case VEC_WIDEN_MULT_ODD_EXPR:
1499       {
1500         unsigned int nelts = TYPE_VECTOR_SUBPARTS (type);
1501         unsigned int out, ofs, scale;
1502         tree *elts;
1503
1504         gcc_assert (TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg1)) == nelts * 2
1505                     && TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg2)) == nelts * 2);
1506         if (TREE_CODE (arg1) != VECTOR_CST || TREE_CODE (arg2) != VECTOR_CST)
1507           return NULL_TREE;
1508
1509         elts = XALLOCAVEC (tree, nelts * 4);
1510         if (!vec_cst_ctor_to_array (arg1, elts)
1511             || !vec_cst_ctor_to_array (arg2, elts + nelts * 2))
1512           return NULL_TREE;
1513
1514         if (code == VEC_WIDEN_MULT_LO_EXPR)
1515           scale = 0, ofs = BYTES_BIG_ENDIAN ? nelts : 0;
1516         else if (code == VEC_WIDEN_MULT_HI_EXPR)
1517           scale = 0, ofs = BYTES_BIG_ENDIAN ? 0 : nelts;
1518         else if (code == VEC_WIDEN_MULT_EVEN_EXPR)
1519           scale = 1, ofs = 0;
1520         else /* if (code == VEC_WIDEN_MULT_ODD_EXPR) */
1521           scale = 1, ofs = 1;
1522
1523         for (out = 0; out < nelts; out++)
1524           {
1525             unsigned int in1 = (out << scale) + ofs;
1526             unsigned int in2 = in1 + nelts * 2;
1527             tree t1, t2;
1528
1529             t1 = fold_convert_const (NOP_EXPR, TREE_TYPE (type), elts[in1]);
1530             t2 = fold_convert_const (NOP_EXPR, TREE_TYPE (type), elts[in2]);
1531
1532             if (t1 == NULL_TREE || t2 == NULL_TREE)
1533               return NULL_TREE;
1534             elts[out] = const_binop (MULT_EXPR, t1, t2);
1535             if (elts[out] == NULL_TREE || !CONSTANT_CLASS_P (elts[out]))
1536               return NULL_TREE;
1537           }
1538
1539         return build_vector (type, elts);
1540       }
1541
1542     default:;
1543     }
1544
1545   if (TREE_CODE_CLASS (code) != tcc_binary)
1546     return NULL_TREE;
1547
1548   /* Make sure type and arg0 have the same saturating flag.  */
1549   gcc_checking_assert (TYPE_SATURATING (type)
1550                        == TYPE_SATURATING (TREE_TYPE (arg1)));
1551
1552   return const_binop (code, arg1, arg2);
1553 }
1554
1555 /* Compute CODE ARG1 with resulting type TYPE with ARG1 being constant.
1556    Return zero if computing the constants is not possible.  */
1557
1558 tree
1559 const_unop (enum tree_code code, tree type, tree arg0)
1560 {
1561   switch (code)
1562     {
1563     CASE_CONVERT:
1564     case FLOAT_EXPR:
1565     case FIX_TRUNC_EXPR:
1566     case FIXED_CONVERT_EXPR:
1567       return fold_convert_const (code, type, arg0);
1568
1569     case ADDR_SPACE_CONVERT_EXPR:
1570       if (integer_zerop (arg0))
1571         return fold_convert_const (code, type, arg0);
1572       break;
1573
1574     case VIEW_CONVERT_EXPR:
1575       return fold_view_convert_expr (type, arg0);
1576
1577     case NEGATE_EXPR:
1578       {
1579         /* Can't call fold_negate_const directly here as that doesn't
1580            handle all cases and we might not be able to negate some
1581            constants.  */
1582         tree tem = fold_negate_expr (UNKNOWN_LOCATION, arg0);
1583         if (tem && CONSTANT_CLASS_P (tem))
1584           return tem;
1585         break;
1586       }
1587
1588     case ABS_EXPR:
1589       if (TREE_CODE (arg0) == INTEGER_CST || TREE_CODE (arg0) == REAL_CST)
1590         return fold_abs_const (arg0, type);
1591       break;
1592
1593     case CONJ_EXPR:
1594       if (TREE_CODE (arg0) == COMPLEX_CST)
1595         {
1596           tree ipart = fold_negate_const (TREE_IMAGPART (arg0),
1597                                           TREE_TYPE (type));
1598           return build_complex (type, TREE_REALPART (arg0), ipart);
1599         }
1600       break;
1601
1602     case BIT_NOT_EXPR:
1603       if (TREE_CODE (arg0) == INTEGER_CST)
1604         return fold_not_const (arg0, type);
1605       /* Perform BIT_NOT_EXPR on each element individually.  */
1606       else if (TREE_CODE (arg0) == VECTOR_CST)
1607         {
1608           tree *elements;
1609           tree elem;
1610           unsigned count = VECTOR_CST_NELTS (arg0), i;
1611
1612           elements = XALLOCAVEC (tree, count);
1613           for (i = 0; i < count; i++)
1614             {
1615               elem = VECTOR_CST_ELT (arg0, i);
1616               elem = const_unop (BIT_NOT_EXPR, TREE_TYPE (type), elem);
1617               if (elem == NULL_TREE)
1618                 break;
1619               elements[i] = elem;
1620             }
1621           if (i == count)
1622             return build_vector (type, elements);
1623         }
1624       break;
1625
1626     case TRUTH_NOT_EXPR:
1627       if (TREE_CODE (arg0) == INTEGER_CST)
1628         return constant_boolean_node (integer_zerop (arg0), type);
1629       break;
1630
1631     case REALPART_EXPR:
1632       if (TREE_CODE (arg0) == COMPLEX_CST)
1633         return fold_convert (type, TREE_REALPART (arg0));
1634       break;
1635
1636     case IMAGPART_EXPR:
1637       if (TREE_CODE (arg0) == COMPLEX_CST)
1638         return fold_convert (type, TREE_IMAGPART (arg0));
1639       break;
1640
1641     case VEC_UNPACK_LO_EXPR:
1642     case VEC_UNPACK_HI_EXPR:
1643     case VEC_UNPACK_FLOAT_LO_EXPR:
1644     case VEC_UNPACK_FLOAT_HI_EXPR:
1645       {
1646         unsigned int nelts = TYPE_VECTOR_SUBPARTS (type), i;
1647         tree *elts;
1648         enum tree_code subcode;
1649
1650         gcc_assert (TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0)) == nelts * 2);
1651         if (TREE_CODE (arg0) != VECTOR_CST)
1652           return NULL_TREE;
1653
1654         elts = XALLOCAVEC (tree, nelts * 2);
1655         if (!vec_cst_ctor_to_array (arg0, elts))
1656           return NULL_TREE;
1657
1658         if ((!BYTES_BIG_ENDIAN) ^ (code == VEC_UNPACK_LO_EXPR
1659                                    || code == VEC_UNPACK_FLOAT_LO_EXPR))
1660           elts += nelts;
1661
1662         if (code == VEC_UNPACK_LO_EXPR || code == VEC_UNPACK_HI_EXPR)
1663           subcode = NOP_EXPR;
1664         else
1665           subcode = FLOAT_EXPR;
1666
1667         for (i = 0; i < nelts; i++)
1668           {
1669             elts[i] = fold_convert_const (subcode, TREE_TYPE (type), elts[i]);
1670             if (elts[i] == NULL_TREE || !CONSTANT_CLASS_P (elts[i]))
1671               return NULL_TREE;
1672           }
1673
1674         return build_vector (type, elts);
1675       }
1676
1677     case REDUC_MIN_EXPR:
1678     case REDUC_MAX_EXPR:
1679     case REDUC_PLUS_EXPR:
1680       {
1681         unsigned int nelts, i;
1682         tree *elts;
1683         enum tree_code subcode;
1684
1685         if (TREE_CODE (arg0) != VECTOR_CST)
1686           return NULL_TREE;
1687         nelts = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
1688
1689         elts = XALLOCAVEC (tree, nelts);
1690         if (!vec_cst_ctor_to_array (arg0, elts))
1691           return NULL_TREE;
1692
1693         switch (code)
1694           {
1695           case REDUC_MIN_EXPR: subcode = MIN_EXPR; break;
1696           case REDUC_MAX_EXPR: subcode = MAX_EXPR; break;
1697           case REDUC_PLUS_EXPR: subcode = PLUS_EXPR; break;
1698           default: gcc_unreachable ();
1699           }
1700
1701         for (i = 1; i < nelts; i++)
1702           {
1703             elts[0] = const_binop (subcode, elts[0], elts[i]);
1704             if (elts[0] == NULL_TREE || !CONSTANT_CLASS_P (elts[0]))
1705               return NULL_TREE;
1706           }
1707
1708         return elts[0];
1709       }
1710
1711     default:
1712       break;
1713     }
1714
1715   return NULL_TREE;
1716 }
1717
1718 /* Create a sizetype INT_CST node with NUMBER sign extended.  KIND
1719    indicates which particular sizetype to create.  */
1720
1721 tree
1722 size_int_kind (HOST_WIDE_INT number, enum size_type_kind kind)
1723 {
1724   return build_int_cst (sizetype_tab[(int) kind], number);
1725 }
1726 \f
1727 /* Combine operands OP1 and OP2 with arithmetic operation CODE.  CODE
1728    is a tree code.  The type of the result is taken from the operands.
1729    Both must be equivalent integer types, ala int_binop_types_match_p.
1730    If the operands are constant, so is the result.  */
1731
1732 tree
1733 size_binop_loc (location_t loc, enum tree_code code, tree arg0, tree arg1)
1734 {
1735   tree type = TREE_TYPE (arg0);
1736
1737   if (arg0 == error_mark_node || arg1 == error_mark_node)
1738     return error_mark_node;
1739
1740   gcc_assert (int_binop_types_match_p (code, TREE_TYPE (arg0),
1741                                        TREE_TYPE (arg1)));
1742
1743   /* Handle the special case of two integer constants faster.  */
1744   if (TREE_CODE (arg0) == INTEGER_CST && TREE_CODE (arg1) == INTEGER_CST)
1745     {
1746       /* And some specific cases even faster than that.  */
1747       if (code == PLUS_EXPR)
1748         {
1749           if (integer_zerop (arg0) && !TREE_OVERFLOW (arg0))
1750             return arg1;
1751           if (integer_zerop (arg1) && !TREE_OVERFLOW (arg1))
1752             return arg0;
1753         }
1754       else if (code == MINUS_EXPR)
1755         {
1756           if (integer_zerop (arg1) && !TREE_OVERFLOW (arg1))
1757             return arg0;
1758         }
1759       else if (code == MULT_EXPR)
1760         {
1761           if (integer_onep (arg0) && !TREE_OVERFLOW (arg0))
1762             return arg1;
1763         }
1764
1765       /* Handle general case of two integer constants.  For sizetype
1766          constant calculations we always want to know about overflow,
1767          even in the unsigned case.  */
1768       return int_const_binop_1 (code, arg0, arg1, -1);
1769     }
1770
1771   return fold_build2_loc (loc, code, type, arg0, arg1);
1772 }
1773
1774 /* Given two values, either both of sizetype or both of bitsizetype,
1775    compute the difference between the two values.  Return the value
1776    in signed type corresponding to the type of the operands.  */
1777
1778 tree
1779 size_diffop_loc (location_t loc, tree arg0, tree arg1)
1780 {
1781   tree type = TREE_TYPE (arg0);
1782   tree ctype;
1783
1784   gcc_assert (int_binop_types_match_p (MINUS_EXPR, TREE_TYPE (arg0),
1785                                        TREE_TYPE (arg1)));
1786
1787   /* If the type is already signed, just do the simple thing.  */
1788   if (!TYPE_UNSIGNED (type))
1789     return size_binop_loc (loc, MINUS_EXPR, arg0, arg1);
1790
1791   if (type == sizetype)
1792     ctype = ssizetype;
1793   else if (type == bitsizetype)
1794     ctype = sbitsizetype;
1795   else
1796     ctype = signed_type_for (type);
1797
1798   /* If either operand is not a constant, do the conversions to the signed
1799      type and subtract.  The hardware will do the right thing with any
1800      overflow in the subtraction.  */
1801   if (TREE_CODE (arg0) != INTEGER_CST || TREE_CODE (arg1) != INTEGER_CST)
1802     return size_binop_loc (loc, MINUS_EXPR,
1803                            fold_convert_loc (loc, ctype, arg0),
1804                            fold_convert_loc (loc, ctype, arg1));
1805
1806   /* If ARG0 is larger than ARG1, subtract and return the result in CTYPE.
1807      Otherwise, subtract the other way, convert to CTYPE (we know that can't
1808      overflow) and negate (which can't either).  Special-case a result
1809      of zero while we're here.  */
1810   if (tree_int_cst_equal (arg0, arg1))
1811     return build_int_cst (ctype, 0);
1812   else if (tree_int_cst_lt (arg1, arg0))
1813     return fold_convert_loc (loc, ctype,
1814                              size_binop_loc (loc, MINUS_EXPR, arg0, arg1));
1815   else
1816     return size_binop_loc (loc, MINUS_EXPR, build_int_cst (ctype, 0),
1817                            fold_convert_loc (loc, ctype,
1818                                              size_binop_loc (loc,
1819                                                              MINUS_EXPR,
1820                                                              arg1, arg0)));
1821 }
1822 \f
1823 /* A subroutine of fold_convert_const handling conversions of an
1824    INTEGER_CST to another integer type.  */
1825
1826 static tree
1827 fold_convert_const_int_from_int (tree type, const_tree arg1)
1828 {
1829   /* Given an integer constant, make new constant with new type,
1830      appropriately sign-extended or truncated.  Use widest_int
1831      so that any extension is done according ARG1's type.  */
1832   return force_fit_type (type, wi::to_widest (arg1),
1833                          !POINTER_TYPE_P (TREE_TYPE (arg1)),
1834                          TREE_OVERFLOW (arg1));
1835 }
1836
1837 /* A subroutine of fold_convert_const handling conversions a REAL_CST
1838    to an integer type.  */
1839
1840 static tree
1841 fold_convert_const_int_from_real (enum tree_code code, tree type, const_tree arg1)
1842 {
1843   bool overflow = false;
1844   tree t;
1845
1846   /* The following code implements the floating point to integer
1847      conversion rules required by the Java Language Specification,
1848      that IEEE NaNs are mapped to zero and values that overflow
1849      the target precision saturate, i.e. values greater than
1850      INT_MAX are mapped to INT_MAX, and values less than INT_MIN
1851      are mapped to INT_MIN.  These semantics are allowed by the
1852      C and C++ standards that simply state that the behavior of
1853      FP-to-integer conversion is unspecified upon overflow.  */
1854
1855   wide_int val;
1856   REAL_VALUE_TYPE r;
1857   REAL_VALUE_TYPE x = TREE_REAL_CST (arg1);
1858
1859   switch (code)
1860     {
1861     case FIX_TRUNC_EXPR:
1862       real_trunc (&r, VOIDmode, &x);
1863       break;
1864
1865     default:
1866       gcc_unreachable ();
1867     }
1868
1869   /* If R is NaN, return zero and show we have an overflow.  */
1870   if (REAL_VALUE_ISNAN (r))
1871     {
1872       overflow = true;
1873       val = wi::zero (TYPE_PRECISION (type));
1874     }
1875
1876   /* See if R is less than the lower bound or greater than the
1877      upper bound.  */
1878
1879   if (! overflow)
1880     {
1881       tree lt = TYPE_MIN_VALUE (type);
1882       REAL_VALUE_TYPE l = real_value_from_int_cst (NULL_TREE, lt);
1883       if (real_less (&r, &l))
1884         {
1885           overflow = true;
1886           val = lt;
1887         }
1888     }
1889
1890   if (! overflow)
1891     {
1892       tree ut = TYPE_MAX_VALUE (type);
1893       if (ut)
1894         {
1895           REAL_VALUE_TYPE u = real_value_from_int_cst (NULL_TREE, ut);
1896           if (real_less (&u, &r))
1897             {
1898               overflow = true;
1899               val = ut;
1900             }
1901         }
1902     }
1903
1904   if (! overflow)
1905     val = real_to_integer (&r, &overflow, TYPE_PRECISION (type));
1906
1907   t = force_fit_type (type, val, -1, overflow | TREE_OVERFLOW (arg1));
1908   return t;
1909 }
1910
1911 /* A subroutine of fold_convert_const handling conversions of a
1912    FIXED_CST to an integer type.  */
1913
1914 static tree
1915 fold_convert_const_int_from_fixed (tree type, const_tree arg1)
1916 {
1917   tree t;
1918   double_int temp, temp_trunc;
1919   unsigned int mode;
1920
1921   /* Right shift FIXED_CST to temp by fbit.  */
1922   temp = TREE_FIXED_CST (arg1).data;
1923   mode = TREE_FIXED_CST (arg1).mode;
1924   if (GET_MODE_FBIT (mode) < HOST_BITS_PER_DOUBLE_INT)
1925     {
1926       temp = temp.rshift (GET_MODE_FBIT (mode),
1927                           HOST_BITS_PER_DOUBLE_INT,
1928                           SIGNED_FIXED_POINT_MODE_P (mode));
1929
1930       /* Left shift temp to temp_trunc by fbit.  */
1931       temp_trunc = temp.lshift (GET_MODE_FBIT (mode),
1932                                 HOST_BITS_PER_DOUBLE_INT,
1933                                 SIGNED_FIXED_POINT_MODE_P (mode));
1934     }
1935   else
1936     {
1937       temp = double_int_zero;
1938       temp_trunc = double_int_zero;
1939     }
1940
1941   /* If FIXED_CST is negative, we need to round the value toward 0.
1942      By checking if the fractional bits are not zero to add 1 to temp.  */
1943   if (SIGNED_FIXED_POINT_MODE_P (mode)
1944       && temp_trunc.is_negative ()
1945       && TREE_FIXED_CST (arg1).data != temp_trunc)
1946     temp += double_int_one;
1947
1948   /* Given a fixed-point constant, make new constant with new type,
1949      appropriately sign-extended or truncated.  */
1950   t = force_fit_type (type, temp, -1,
1951                       (temp.is_negative ()
1952                        && (TYPE_UNSIGNED (type)
1953                            < TYPE_UNSIGNED (TREE_TYPE (arg1))))
1954                       | TREE_OVERFLOW (arg1));
1955
1956   return t;
1957 }
1958
1959 /* A subroutine of fold_convert_const handling conversions a REAL_CST
1960    to another floating point type.  */
1961
1962 static tree
1963 fold_convert_const_real_from_real (tree type, const_tree arg1)
1964 {
1965   REAL_VALUE_TYPE value;
1966   tree t;
1967
1968   real_convert (&value, TYPE_MODE (type), &TREE_REAL_CST (arg1));
1969   t = build_real (type, value);
1970
1971   /* If converting an infinity or NAN to a representation that doesn't
1972      have one, set the overflow bit so that we can produce some kind of
1973      error message at the appropriate point if necessary.  It's not the
1974      most user-friendly message, but it's better than nothing.  */
1975   if (REAL_VALUE_ISINF (TREE_REAL_CST (arg1))
1976       && !MODE_HAS_INFINITIES (TYPE_MODE (type)))
1977     TREE_OVERFLOW (t) = 1;
1978   else if (REAL_VALUE_ISNAN (TREE_REAL_CST (arg1))
1979            && !MODE_HAS_NANS (TYPE_MODE (type)))
1980     TREE_OVERFLOW (t) = 1;
1981   /* Regular overflow, conversion produced an infinity in a mode that
1982      can't represent them.  */
1983   else if (!MODE_HAS_INFINITIES (TYPE_MODE (type))
1984            && REAL_VALUE_ISINF (value)
1985            && !REAL_VALUE_ISINF (TREE_REAL_CST (arg1)))
1986     TREE_OVERFLOW (t) = 1;
1987   else
1988     TREE_OVERFLOW (t) = TREE_OVERFLOW (arg1);
1989   return t;
1990 }
1991
1992 /* A subroutine of fold_convert_const handling conversions a FIXED_CST
1993    to a floating point type.  */
1994
1995 static tree
1996 fold_convert_const_real_from_fixed (tree type, const_tree arg1)
1997 {
1998   REAL_VALUE_TYPE value;
1999   tree t;
2000
2001   real_convert_from_fixed (&value, TYPE_MODE (type), &TREE_FIXED_CST (arg1));
2002   t = build_real (type, value);
2003
2004   TREE_OVERFLOW (t) = TREE_OVERFLOW (arg1);
2005   return t;
2006 }
2007
2008 /* A subroutine of fold_convert_const handling conversions a FIXED_CST
2009    to another fixed-point type.  */
2010
2011 static tree
2012 fold_convert_const_fixed_from_fixed (tree type, const_tree arg1)
2013 {
2014   FIXED_VALUE_TYPE value;
2015   tree t;
2016   bool overflow_p;
2017
2018   overflow_p = fixed_convert (&value, TYPE_MODE (type), &TREE_FIXED_CST (arg1),
2019                               TYPE_SATURATING (type));
2020   t = build_fixed (type, value);
2021
2022   /* Propagate overflow flags.  */
2023   if (overflow_p | TREE_OVERFLOW (arg1))
2024     TREE_OVERFLOW (t) = 1;
2025   return t;
2026 }
2027
2028 /* A subroutine of fold_convert_const handling conversions an INTEGER_CST
2029    to a fixed-point type.  */
2030
2031 static tree
2032 fold_convert_const_fixed_from_int (tree type, const_tree arg1)
2033 {
2034   FIXED_VALUE_TYPE value;
2035   tree t;
2036   bool overflow_p;
2037   double_int di;
2038
2039   gcc_assert (TREE_INT_CST_NUNITS (arg1) <= 2);
2040
2041   di.low = TREE_INT_CST_ELT (arg1, 0);
2042   if (TREE_INT_CST_NUNITS (arg1) == 1)
2043     di.high = (HOST_WIDE_INT) di.low < 0 ? (HOST_WIDE_INT) -1 : 0;
2044   else
2045     di.high = TREE_INT_CST_ELT (arg1, 1);
2046
2047   overflow_p = fixed_convert_from_int (&value, TYPE_MODE (type), di,
2048                                        TYPE_UNSIGNED (TREE_TYPE (arg1)),
2049                                        TYPE_SATURATING (type));
2050   t = build_fixed (type, value);
2051
2052   /* Propagate overflow flags.  */
2053   if (overflow_p | TREE_OVERFLOW (arg1))
2054     TREE_OVERFLOW (t) = 1;
2055   return t;
2056 }
2057
2058 /* A subroutine of fold_convert_const handling conversions a REAL_CST
2059    to a fixed-point type.  */
2060
2061 static tree
2062 fold_convert_const_fixed_from_real (tree type, const_tree arg1)
2063 {
2064   FIXED_VALUE_TYPE value;
2065   tree t;
2066   bool overflow_p;
2067
2068   overflow_p = fixed_convert_from_real (&value, TYPE_MODE (type),
2069                                         &TREE_REAL_CST (arg1),
2070                                         TYPE_SATURATING (type));
2071   t = build_fixed (type, value);
2072
2073   /* Propagate overflow flags.  */
2074   if (overflow_p | TREE_OVERFLOW (arg1))
2075     TREE_OVERFLOW (t) = 1;
2076   return t;
2077 }
2078
2079 /* Attempt to fold type conversion operation CODE of expression ARG1 to
2080    type TYPE.  If no simplification can be done return NULL_TREE.  */
2081
2082 static tree
2083 fold_convert_const (enum tree_code code, tree type, tree arg1)
2084 {
2085   if (TREE_TYPE (arg1) == type)
2086     return arg1;
2087
2088   if (POINTER_TYPE_P (type) || INTEGRAL_TYPE_P (type)
2089       || TREE_CODE (type) == OFFSET_TYPE)
2090     {
2091       if (TREE_CODE (arg1) == INTEGER_CST)
2092         return fold_convert_const_int_from_int (type, arg1);
2093       else if (TREE_CODE (arg1) == REAL_CST)
2094         return fold_convert_const_int_from_real (code, type, arg1);
2095       else if (TREE_CODE (arg1) == FIXED_CST)
2096         return fold_convert_const_int_from_fixed (type, arg1);
2097     }
2098   else if (TREE_CODE (type) == REAL_TYPE)
2099     {
2100       if (TREE_CODE (arg1) == INTEGER_CST)
2101         return build_real_from_int_cst (type, arg1);
2102       else if (TREE_CODE (arg1) == REAL_CST)
2103         return fold_convert_const_real_from_real (type, arg1);
2104       else if (TREE_CODE (arg1) == FIXED_CST)
2105         return fold_convert_const_real_from_fixed (type, arg1);
2106     }
2107   else if (TREE_CODE (type) == FIXED_POINT_TYPE)
2108     {
2109       if (TREE_CODE (arg1) == FIXED_CST)
2110         return fold_convert_const_fixed_from_fixed (type, arg1);
2111       else if (TREE_CODE (arg1) == INTEGER_CST)
2112         return fold_convert_const_fixed_from_int (type, arg1);
2113       else if (TREE_CODE (arg1) == REAL_CST)
2114         return fold_convert_const_fixed_from_real (type, arg1);
2115     }
2116   return NULL_TREE;
2117 }
2118
2119 /* Construct a vector of zero elements of vector type TYPE.  */
2120
2121 static tree
2122 build_zero_vector (tree type)
2123 {
2124   tree t;
2125
2126   t = fold_convert_const (NOP_EXPR, TREE_TYPE (type), integer_zero_node);
2127   return build_vector_from_val (type, t);
2128 }
2129
2130 /* Returns true, if ARG is convertible to TYPE using a NOP_EXPR.  */
2131
2132 bool
2133 fold_convertible_p (const_tree type, const_tree arg)
2134 {
2135   tree orig = TREE_TYPE (arg);
2136
2137   if (type == orig)
2138     return true;
2139
2140   if (TREE_CODE (arg) == ERROR_MARK
2141       || TREE_CODE (type) == ERROR_MARK
2142       || TREE_CODE (orig) == ERROR_MARK)
2143     return false;
2144
2145   if (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (orig))
2146     return true;
2147
2148   switch (TREE_CODE (type))
2149     {
2150     case INTEGER_TYPE: case ENUMERAL_TYPE: case BOOLEAN_TYPE:
2151     case POINTER_TYPE: case REFERENCE_TYPE:
2152     case OFFSET_TYPE:
2153       if (INTEGRAL_TYPE_P (orig) || POINTER_TYPE_P (orig)
2154           || TREE_CODE (orig) == OFFSET_TYPE)
2155         return true;
2156       return (TREE_CODE (orig) == VECTOR_TYPE
2157               && tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (orig)));
2158
2159     case REAL_TYPE:
2160     case FIXED_POINT_TYPE:
2161     case COMPLEX_TYPE:
2162     case VECTOR_TYPE:
2163     case VOID_TYPE:
2164       return TREE_CODE (type) == TREE_CODE (orig);
2165
2166     default:
2167       return false;
2168     }
2169 }
2170
2171 /* Convert expression ARG to type TYPE.  Used by the middle-end for
2172    simple conversions in preference to calling the front-end's convert.  */
2173
2174 tree
2175 fold_convert_loc (location_t loc, tree type, tree arg)
2176 {
2177   tree orig = TREE_TYPE (arg);
2178   tree tem;
2179
2180   if (type == orig)
2181     return arg;
2182
2183   if (TREE_CODE (arg) == ERROR_MARK
2184       || TREE_CODE (type) == ERROR_MARK
2185       || TREE_CODE (orig) == ERROR_MARK)
2186     return error_mark_node;
2187
2188   switch (TREE_CODE (type))
2189     {
2190     case POINTER_TYPE:
2191     case REFERENCE_TYPE:
2192       /* Handle conversions between pointers to different address spaces.  */
2193       if (POINTER_TYPE_P (orig)
2194           && (TYPE_ADDR_SPACE (TREE_TYPE (type))
2195               != TYPE_ADDR_SPACE (TREE_TYPE (orig))))
2196         return fold_build1_loc (loc, ADDR_SPACE_CONVERT_EXPR, type, arg);
2197       /* fall through */
2198
2199     case INTEGER_TYPE: case ENUMERAL_TYPE: case BOOLEAN_TYPE:
2200     case OFFSET_TYPE:
2201       if (TREE_CODE (arg) == INTEGER_CST)
2202         {
2203           tem = fold_convert_const (NOP_EXPR, type, arg);
2204           if (tem != NULL_TREE)
2205             return tem;
2206         }
2207       if (INTEGRAL_TYPE_P (orig) || POINTER_TYPE_P (orig)
2208           || TREE_CODE (orig) == OFFSET_TYPE)
2209         return fold_build1_loc (loc, NOP_EXPR, type, arg);
2210       if (TREE_CODE (orig) == COMPLEX_TYPE)
2211         return fold_convert_loc (loc, type,
2212                              fold_build1_loc (loc, REALPART_EXPR,
2213                                           TREE_TYPE (orig), arg));
2214       gcc_assert (TREE_CODE (orig) == VECTOR_TYPE
2215                   && tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (orig)));
2216       return fold_build1_loc (loc, NOP_EXPR, type, arg);
2217
2218     case REAL_TYPE:
2219       if (TREE_CODE (arg) == INTEGER_CST)
2220         {
2221           tem = fold_convert_const (FLOAT_EXPR, type, arg);
2222           if (tem != NULL_TREE)
2223             return tem;
2224         }
2225       else if (TREE_CODE (arg) == REAL_CST)
2226         {
2227           tem = fold_convert_const (NOP_EXPR, type, arg);
2228           if (tem != NULL_TREE)
2229             return tem;
2230         }
2231       else if (TREE_CODE (arg) == FIXED_CST)
2232         {
2233           tem = fold_convert_const (FIXED_CONVERT_EXPR, type, arg);
2234           if (tem != NULL_TREE)
2235             return tem;
2236         }
2237
2238       switch (TREE_CODE (orig))
2239         {
2240         case INTEGER_TYPE:
2241         case BOOLEAN_TYPE: case ENUMERAL_TYPE:
2242         case POINTER_TYPE: case REFERENCE_TYPE:
2243           return fold_build1_loc (loc, FLOAT_EXPR, type, arg);
2244
2245         case REAL_TYPE:
2246           return fold_build1_loc (loc, NOP_EXPR, type, arg);
2247
2248         case FIXED_POINT_TYPE:
2249           return fold_build1_loc (loc, FIXED_CONVERT_EXPR, type, arg);
2250
2251         case COMPLEX_TYPE:
2252           tem = fold_build1_loc (loc, REALPART_EXPR, TREE_TYPE (orig), arg);
2253           return fold_convert_loc (loc, type, tem);
2254
2255         default:
2256           gcc_unreachable ();
2257         }
2258
2259     case FIXED_POINT_TYPE:
2260       if (TREE_CODE (arg) == FIXED_CST || TREE_CODE (arg) == INTEGER_CST
2261           || TREE_CODE (arg) == REAL_CST)
2262         {
2263           tem = fold_convert_const (FIXED_CONVERT_EXPR, type, arg);
2264           if (tem != NULL_TREE)
2265             goto fold_convert_exit;
2266         }
2267
2268       switch (TREE_CODE (orig))
2269         {
2270         case FIXED_POINT_TYPE:
2271         case INTEGER_TYPE:
2272         case ENUMERAL_TYPE:
2273         case BOOLEAN_TYPE:
2274         case REAL_TYPE:
2275           return fold_build1_loc (loc, FIXED_CONVERT_EXPR, type, arg);
2276
2277         case COMPLEX_TYPE:
2278           tem = fold_build1_loc (loc, REALPART_EXPR, TREE_TYPE (orig), arg);
2279           return fold_convert_loc (loc, type, tem);
2280
2281         default:
2282           gcc_unreachable ();
2283         }
2284
2285     case COMPLEX_TYPE:
2286       switch (TREE_CODE (orig))
2287         {
2288         case INTEGER_TYPE:
2289         case BOOLEAN_TYPE: case ENUMERAL_TYPE:
2290         case POINTER_TYPE: case REFERENCE_TYPE:
2291         case REAL_TYPE:
2292         case FIXED_POINT_TYPE:
2293           return fold_build2_loc (loc, COMPLEX_EXPR, type,
2294                               fold_convert_loc (loc, TREE_TYPE (type), arg),
2295                               fold_convert_loc (loc, TREE_TYPE (type),
2296                                             integer_zero_node));
2297         case COMPLEX_TYPE:
2298           {
2299             tree rpart, ipart;
2300
2301             if (TREE_CODE (arg) == COMPLEX_EXPR)
2302               {
2303                 rpart = fold_convert_loc (loc, TREE_TYPE (type),
2304                                       TREE_OPERAND (arg, 0));
2305                 ipart = fold_convert_loc (loc, TREE_TYPE (type),
2306                                       TREE_OPERAND (arg, 1));
2307                 return fold_build2_loc (loc, COMPLEX_EXPR, type, rpart, ipart);
2308               }
2309
2310             arg = save_expr (arg);
2311             rpart = fold_build1_loc (loc, REALPART_EXPR, TREE_TYPE (orig), arg);
2312             ipart = fold_build1_loc (loc, IMAGPART_EXPR, TREE_TYPE (orig), arg);
2313             rpart = fold_convert_loc (loc, TREE_TYPE (type), rpart);
2314             ipart = fold_convert_loc (loc, TREE_TYPE (type), ipart);
2315             return fold_build2_loc (loc, COMPLEX_EXPR, type, rpart, ipart);
2316           }
2317
2318         default:
2319           gcc_unreachable ();
2320         }
2321
2322     case VECTOR_TYPE:
2323       if (integer_zerop (arg))
2324         return build_zero_vector (type);
2325       gcc_assert (tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (orig)));
2326       gcc_assert (INTEGRAL_TYPE_P (orig) || POINTER_TYPE_P (orig)
2327                   || TREE_CODE (orig) == VECTOR_TYPE);
2328       return fold_build1_loc (loc, VIEW_CONVERT_EXPR, type, arg);
2329
2330     case VOID_TYPE:
2331       tem = fold_ignored_result (arg);
2332       return fold_build1_loc (loc, NOP_EXPR, type, tem);
2333
2334     default:
2335       if (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (orig))
2336         return fold_build1_loc (loc, NOP_EXPR, type, arg);
2337       gcc_unreachable ();
2338     }
2339  fold_convert_exit:
2340   protected_set_expr_location_unshare (tem, loc);
2341   return tem;
2342 }
2343 \f
2344 /* Return false if expr can be assumed not to be an lvalue, true
2345    otherwise.  */
2346
2347 static bool
2348 maybe_lvalue_p (const_tree x)
2349 {
2350   /* We only need to wrap lvalue tree codes.  */
2351   switch (TREE_CODE (x))
2352   {
2353   case VAR_DECL:
2354   case PARM_DECL:
2355   case RESULT_DECL:
2356   case LABEL_DECL:
2357   case FUNCTION_DECL:
2358   case SSA_NAME:
2359
2360   case COMPONENT_REF:
2361   case MEM_REF:
2362   case INDIRECT_REF:
2363   case ARRAY_REF:
2364   case ARRAY_RANGE_REF:
2365   case BIT_FIELD_REF:
2366   case OBJ_TYPE_REF:
2367
2368   case REALPART_EXPR:
2369   case IMAGPART_EXPR:
2370   case PREINCREMENT_EXPR:
2371   case PREDECREMENT_EXPR:
2372   case SAVE_EXPR:
2373   case TRY_CATCH_EXPR:
2374   case WITH_CLEANUP_EXPR:
2375   case COMPOUND_EXPR:
2376   case MODIFY_EXPR:
2377   case TARGET_EXPR:
2378   case COND_EXPR:
2379   case BIND_EXPR:
2380     break;
2381
2382   default:
2383     /* Assume the worst for front-end tree codes.  */
2384     if ((int)TREE_CODE (x) >= NUM_TREE_CODES)
2385       break;
2386     return false;
2387   }
2388
2389   return true;
2390 }
2391
2392 /* Return an expr equal to X but certainly not valid as an lvalue.  */
2393
2394 tree
2395 non_lvalue_loc (location_t loc, tree x)
2396 {
2397   /* While we are in GIMPLE, NON_LVALUE_EXPR doesn't mean anything to
2398      us.  */
2399   if (in_gimple_form)
2400     return x;
2401
2402   if (! maybe_lvalue_p (x))
2403     return x;
2404   return build1_loc (loc, NON_LVALUE_EXPR, TREE_TYPE (x), x);
2405 }
2406
2407 /* When pedantic, return an expr equal to X but certainly not valid as a
2408    pedantic lvalue.  Otherwise, return X.  */
2409
2410 static tree
2411 pedantic_non_lvalue_loc (location_t loc, tree x)
2412 {
2413   return protected_set_expr_location_unshare (x, loc);
2414 }
2415 \f
2416 /* Given a tree comparison code, return the code that is the logical inverse.
2417    It is generally not safe to do this for floating-point comparisons, except
2418    for EQ_EXPR, NE_EXPR, ORDERED_EXPR and UNORDERED_EXPR, so we return
2419    ERROR_MARK in this case.  */
2420
2421 enum tree_code
2422 invert_tree_comparison (enum tree_code code, bool honor_nans)
2423 {
2424   if (honor_nans && flag_trapping_math && code != EQ_EXPR && code != NE_EXPR
2425       && code != ORDERED_EXPR && code != UNORDERED_EXPR)
2426     return ERROR_MARK;
2427
2428   switch (code)
2429     {
2430     case EQ_EXPR:
2431       return NE_EXPR;
2432     case NE_EXPR:
2433       return EQ_EXPR;
2434     case GT_EXPR:
2435       return honor_nans ? UNLE_EXPR : LE_EXPR;
2436     case GE_EXPR:
2437       return honor_nans ? UNLT_EXPR : LT_EXPR;
2438     case LT_EXPR:
2439       return honor_nans ? UNGE_EXPR : GE_EXPR;
2440     case LE_EXPR:
2441       return honor_nans ? UNGT_EXPR : GT_EXPR;
2442     case LTGT_EXPR:
2443       return UNEQ_EXPR;
2444     case UNEQ_EXPR:
2445       return LTGT_EXPR;
2446     case UNGT_EXPR:
2447       return LE_EXPR;
2448     case UNGE_EXPR:
2449       return LT_EXPR;
2450     case UNLT_EXPR:
2451       return GE_EXPR;
2452     case UNLE_EXPR:
2453       return GT_EXPR;
2454     case ORDERED_EXPR:
2455       return UNORDERED_EXPR;
2456     case UNORDERED_EXPR:
2457       return ORDERED_EXPR;
2458     default:
2459       gcc_unreachable ();
2460     }
2461 }
2462
2463 /* Similar, but return the comparison that results if the operands are
2464    swapped.  This is safe for floating-point.  */
2465
2466 enum tree_code
2467 swap_tree_comparison (enum tree_code code)
2468 {
2469   switch (code)
2470     {
2471     case EQ_EXPR:
2472     case NE_EXPR:
2473     case ORDERED_EXPR:
2474     case UNORDERED_EXPR:
2475     case LTGT_EXPR:
2476     case UNEQ_EXPR:
2477       return code;
2478     case GT_EXPR:
2479       return LT_EXPR;
2480     case GE_EXPR:
2481       return LE_EXPR;
2482     case LT_EXPR:
2483       return GT_EXPR;
2484     case LE_EXPR:
2485       return GE_EXPR;
2486     case UNGT_EXPR:
2487       return UNLT_EXPR;
2488     case UNGE_EXPR:
2489       return UNLE_EXPR;
2490     case UNLT_EXPR:
2491       return UNGT_EXPR;
2492     case UNLE_EXPR:
2493       return UNGE_EXPR;
2494     default:
2495       gcc_unreachable ();
2496     }
2497 }
2498
2499
2500 /* Convert a comparison tree code from an enum tree_code representation
2501    into a compcode bit-based encoding.  This function is the inverse of
2502    compcode_to_comparison.  */
2503
2504 static enum comparison_code
2505 comparison_to_compcode (enum tree_code code)
2506 {
2507   switch (code)
2508     {
2509     case LT_EXPR:
2510       return COMPCODE_LT;
2511     case EQ_EXPR:
2512       return COMPCODE_EQ;
2513     case LE_EXPR:
2514       return COMPCODE_LE;
2515     case GT_EXPR:
2516       return COMPCODE_GT;
2517     case NE_EXPR:
2518       return COMPCODE_NE;
2519     case GE_EXPR:
2520       return COMPCODE_GE;
2521     case ORDERED_EXPR:
2522       return COMPCODE_ORD;
2523     case UNORDERED_EXPR:
2524       return COMPCODE_UNORD;
2525     case UNLT_EXPR:
2526       return COMPCODE_UNLT;
2527     case UNEQ_EXPR:
2528       return COMPCODE_UNEQ;
2529     case UNLE_EXPR:
2530       return COMPCODE_UNLE;
2531     case UNGT_EXPR:
2532       return COMPCODE_UNGT;
2533     case LTGT_EXPR:
2534       return COMPCODE_LTGT;
2535     case UNGE_EXPR:
2536       return COMPCODE_UNGE;
2537     default:
2538       gcc_unreachable ();
2539     }
2540 }
2541
2542 /* Convert a compcode bit-based encoding of a comparison operator back
2543    to GCC's enum tree_code representation.  This function is the
2544    inverse of comparison_to_compcode.  */
2545
2546 static enum tree_code
2547 compcode_to_comparison (enum comparison_code code)
2548 {
2549   switch (code)
2550     {
2551     case COMPCODE_LT:
2552       return LT_EXPR;
2553     case COMPCODE_EQ:
2554       return EQ_EXPR;
2555     case COMPCODE_LE:
2556       return LE_EXPR;
2557     case COMPCODE_GT:
2558       return GT_EXPR;
2559     case COMPCODE_NE:
2560       return NE_EXPR;
2561     case COMPCODE_GE:
2562       return GE_EXPR;
2563     case COMPCODE_ORD:
2564       return ORDERED_EXPR;
2565     case COMPCODE_UNORD:
2566       return UNORDERED_EXPR;
2567     case COMPCODE_UNLT:
2568       return UNLT_EXPR;
2569     case COMPCODE_UNEQ:
2570       return UNEQ_EXPR;
2571     case COMPCODE_UNLE:
2572       return UNLE_EXPR;
2573     case COMPCODE_UNGT:
2574       return UNGT_EXPR;
2575     case COMPCODE_LTGT:
2576       return LTGT_EXPR;
2577     case COMPCODE_UNGE:
2578       return UNGE_EXPR;
2579     default:
2580       gcc_unreachable ();
2581     }
2582 }
2583
2584 /* Return a tree for the comparison which is the combination of
2585    doing the AND or OR (depending on CODE) of the two operations LCODE
2586    and RCODE on the identical operands LL_ARG and LR_ARG.  Take into account
2587    the possibility of trapping if the mode has NaNs, and return NULL_TREE
2588    if this makes the transformation invalid.  */
2589
2590 tree
2591 combine_comparisons (location_t loc,
2592                      enum tree_code code, enum tree_code lcode,
2593                      enum tree_code rcode, tree truth_type,
2594                      tree ll_arg, tree lr_arg)
2595 {
2596   bool honor_nans = HONOR_NANS (ll_arg);
2597   enum comparison_code lcompcode = comparison_to_compcode (lcode);
2598   enum comparison_code rcompcode = comparison_to_compcode (rcode);
2599   int compcode;
2600
2601   switch (code)
2602     {
2603     case TRUTH_AND_EXPR: case TRUTH_ANDIF_EXPR:
2604       compcode = lcompcode & rcompcode;
2605       break;
2606
2607     case TRUTH_OR_EXPR: case TRUTH_ORIF_EXPR:
2608       compcode = lcompcode | rcompcode;
2609       break;
2610
2611     default:
2612       return NULL_TREE;
2613     }
2614
2615   if (!honor_nans)
2616     {
2617       /* Eliminate unordered comparisons, as well as LTGT and ORD
2618          which are not used unless the mode has NaNs.  */
2619       compcode &= ~COMPCODE_UNORD;
2620       if (compcode == COMPCODE_LTGT)
2621         compcode = COMPCODE_NE;
2622       else if (compcode == COMPCODE_ORD)
2623         compcode = COMPCODE_TRUE;
2624     }
2625    else if (flag_trapping_math)
2626      {
2627         /* Check that the original operation and the optimized ones will trap
2628            under the same condition.  */
2629         bool ltrap = (lcompcode & COMPCODE_UNORD) == 0
2630                      && (lcompcode != COMPCODE_EQ)
2631                      && (lcompcode != COMPCODE_ORD);
2632         bool rtrap = (rcompcode & COMPCODE_UNORD) == 0
2633                      && (rcompcode != COMPCODE_EQ)
2634                      && (rcompcode != COMPCODE_ORD);
2635         bool trap = (compcode & COMPCODE_UNORD) == 0
2636                     && (compcode != COMPCODE_EQ)
2637                     && (compcode != COMPCODE_ORD);
2638
2639         /* In a short-circuited boolean expression the LHS might be
2640            such that the RHS, if evaluated, will never trap.  For
2641            example, in ORD (x, y) && (x < y), we evaluate the RHS only
2642            if neither x nor y is NaN.  (This is a mixed blessing: for
2643            example, the expression above will never trap, hence
2644            optimizing it to x < y would be invalid).  */
2645         if ((code == TRUTH_ORIF_EXPR && (lcompcode & COMPCODE_UNORD))
2646             || (code == TRUTH_ANDIF_EXPR && !(lcompcode & COMPCODE_UNORD)))
2647           rtrap = false;
2648
2649         /* If the comparison was short-circuited, and only the RHS
2650            trapped, we may now generate a spurious trap.  */
2651         if (rtrap && !ltrap
2652             && (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR))
2653           return NULL_TREE;
2654
2655         /* If we changed the conditions that cause a trap, we lose.  */
2656         if ((ltrap || rtrap) != trap)
2657           return NULL_TREE;
2658       }
2659
2660   if (compcode == COMPCODE_TRUE)
2661     return constant_boolean_node (true, truth_type);
2662   else if (compcode == COMPCODE_FALSE)
2663     return constant_boolean_node (false, truth_type);
2664   else
2665     {
2666       enum tree_code tcode;
2667
2668       tcode = compcode_to_comparison ((enum comparison_code) compcode);
2669       return fold_build2_loc (loc, tcode, truth_type, ll_arg, lr_arg);
2670     }
2671 }
2672 \f
2673 /* Return nonzero if two operands (typically of the same tree node)
2674    are necessarily equal.  If either argument has side-effects this
2675    function returns zero.  FLAGS modifies behavior as follows:
2676
2677    If OEP_ONLY_CONST is set, only return nonzero for constants.
2678    This function tests whether the operands are indistinguishable;
2679    it does not test whether they are equal using C's == operation.
2680    The distinction is important for IEEE floating point, because
2681    (1) -0.0 and 0.0 are distinguishable, but -0.0==0.0, and
2682    (2) two NaNs may be indistinguishable, but NaN!=NaN.
2683
2684    If OEP_ONLY_CONST is unset, a VAR_DECL is considered equal to itself
2685    even though it may hold multiple values during a function.
2686    This is because a GCC tree node guarantees that nothing else is
2687    executed between the evaluation of its "operands" (which may often
2688    be evaluated in arbitrary order).  Hence if the operands themselves
2689    don't side-effect, the VAR_DECLs, PARM_DECLs etc... must hold the
2690    same value in each operand/subexpression.  Hence leaving OEP_ONLY_CONST
2691    unset means assuming isochronic (or instantaneous) tree equivalence.
2692    Unless comparing arbitrary expression trees, such as from different
2693    statements, this flag can usually be left unset.
2694
2695    If OEP_PURE_SAME is set, then pure functions with identical arguments
2696    are considered the same.  It is used when the caller has other ways
2697    to ensure that global memory is unchanged in between.
2698
2699    If OEP_ADDRESS_OF is set, we are actually comparing addresses of objects,
2700    not values of expressions.  OEP_CONSTANT_ADDRESS_OF in addition to
2701    OEP_ADDRESS_OF is used for ADDR_EXPR with TREE_CONSTANT flag set and we
2702    further ignore any side effects on SAVE_EXPRs then.  */
2703
2704 int
2705 operand_equal_p (const_tree arg0, const_tree arg1, unsigned int flags)
2706 {
2707   /* If either is ERROR_MARK, they aren't equal.  */
2708   if (TREE_CODE (arg0) == ERROR_MARK || TREE_CODE (arg1) == ERROR_MARK
2709       || TREE_TYPE (arg0) == error_mark_node
2710       || TREE_TYPE (arg1) == error_mark_node)
2711     return 0;
2712
2713   /* Similar, if either does not have a type (like a released SSA name), 
2714      they aren't equal.  */
2715   if (!TREE_TYPE (arg0) || !TREE_TYPE (arg1))
2716     return 0;
2717
2718   /* Check equality of integer constants before bailing out due to
2719      precision differences.  */
2720   if (TREE_CODE (arg0) == INTEGER_CST && TREE_CODE (arg1) == INTEGER_CST)
2721     {
2722       /* Address of INTEGER_CST is not defined; check that we did not forget
2723          to drop the OEP_ADDRESS_OF/OEP_CONSTANT_ADDRESS_OF flags.  */
2724       gcc_checking_assert (!(flags
2725                              & (OEP_ADDRESS_OF | OEP_CONSTANT_ADDRESS_OF)));
2726       return tree_int_cst_equal (arg0, arg1);
2727     }
2728
2729   if (!(flags & OEP_ADDRESS_OF))
2730     {
2731       /* If both types don't have the same signedness, then we can't consider
2732          them equal.  We must check this before the STRIP_NOPS calls
2733          because they may change the signedness of the arguments.  As pointers
2734          strictly don't have a signedness, require either two pointers or
2735          two non-pointers as well.  */
2736       if (TYPE_UNSIGNED (TREE_TYPE (arg0)) != TYPE_UNSIGNED (TREE_TYPE (arg1))
2737           || POINTER_TYPE_P (TREE_TYPE (arg0))
2738                              != POINTER_TYPE_P (TREE_TYPE (arg1)))
2739         return 0;
2740
2741       /* We cannot consider pointers to different address space equal.  */
2742       if (POINTER_TYPE_P (TREE_TYPE (arg0))
2743                           && POINTER_TYPE_P (TREE_TYPE (arg1))
2744           && (TYPE_ADDR_SPACE (TREE_TYPE (TREE_TYPE (arg0)))
2745               != TYPE_ADDR_SPACE (TREE_TYPE (TREE_TYPE (arg1)))))
2746         return 0;
2747
2748       /* If both types don't have the same precision, then it is not safe
2749          to strip NOPs.  */
2750       if (element_precision (TREE_TYPE (arg0))
2751           != element_precision (TREE_TYPE (arg1)))
2752         return 0;
2753
2754       STRIP_NOPS (arg0);
2755       STRIP_NOPS (arg1);
2756     }
2757 #if 0
2758   /* FIXME: Fortran FE currently produce ADDR_EXPR of NOP_EXPR. Enable the
2759      sanity check once the issue is solved.  */
2760   else
2761     /* Addresses of conversions and SSA_NAMEs (and many other things)
2762        are not defined.  Check that we did not forget to drop the
2763        OEP_ADDRESS_OF/OEP_CONSTANT_ADDRESS_OF flags.  */
2764     gcc_checking_assert (!CONVERT_EXPR_P (arg0) && !CONVERT_EXPR_P (arg1)
2765                          && TREE_CODE (arg0) != SSA_NAME);
2766 #endif
2767
2768   /* In case both args are comparisons but with different comparison
2769      code, try to swap the comparison operands of one arg to produce
2770      a match and compare that variant.  */
2771   if (TREE_CODE (arg0) != TREE_CODE (arg1)
2772       && COMPARISON_CLASS_P (arg0)
2773       && COMPARISON_CLASS_P (arg1))
2774     {
2775       enum tree_code swap_code = swap_tree_comparison (TREE_CODE (arg1));
2776
2777       if (TREE_CODE (arg0) == swap_code)
2778         return operand_equal_p (TREE_OPERAND (arg0, 0),
2779                                 TREE_OPERAND (arg1, 1), flags)
2780                && operand_equal_p (TREE_OPERAND (arg0, 1),
2781                                    TREE_OPERAND (arg1, 0), flags);
2782     }
2783
2784   if (TREE_CODE (arg0) != TREE_CODE (arg1))
2785     {
2786       /* NOP_EXPR and CONVERT_EXPR are considered equal.  */
2787       if (CONVERT_EXPR_P (arg0) && CONVERT_EXPR_P (arg1))
2788         ;
2789       else if (flags & OEP_ADDRESS_OF)
2790         {
2791           /* If we are interested in comparing addresses ignore
2792              MEM_REF wrappings of the base that can appear just for
2793              TBAA reasons.  */
2794           if (TREE_CODE (arg0) == MEM_REF
2795               && DECL_P (arg1)
2796               && TREE_CODE (TREE_OPERAND (arg0, 0)) == ADDR_EXPR
2797               && TREE_OPERAND (TREE_OPERAND (arg0, 0), 0) == arg1
2798               && integer_zerop (TREE_OPERAND (arg0, 1)))
2799             return 1;
2800           else if (TREE_CODE (arg1) == MEM_REF
2801                    && DECL_P (arg0)
2802                    && TREE_CODE (TREE_OPERAND (arg1, 0)) == ADDR_EXPR
2803                    && TREE_OPERAND (TREE_OPERAND (arg1, 0), 0) == arg0
2804                    && integer_zerop (TREE_OPERAND (arg1, 1)))
2805             return 1;
2806           return 0;
2807         }
2808       else
2809         return 0;
2810     }
2811
2812   /* This is needed for conversions and for COMPONENT_REF.
2813      Might as well play it safe and always test this.  */
2814   if (TREE_CODE (TREE_TYPE (arg0)) == ERROR_MARK
2815       || TREE_CODE (TREE_TYPE (arg1)) == ERROR_MARK
2816       || TYPE_MODE (TREE_TYPE (arg0)) != TYPE_MODE (TREE_TYPE (arg1)))
2817     return 0;
2818
2819   /* If ARG0 and ARG1 are the same SAVE_EXPR, they are necessarily equal.
2820      We don't care about side effects in that case because the SAVE_EXPR
2821      takes care of that for us. In all other cases, two expressions are
2822      equal if they have no side effects.  If we have two identical
2823      expressions with side effects that should be treated the same due
2824      to the only side effects being identical SAVE_EXPR's, that will
2825      be detected in the recursive calls below.
2826      If we are taking an invariant address of two identical objects
2827      they are necessarily equal as well.  */
2828   if (arg0 == arg1 && ! (flags & OEP_ONLY_CONST)
2829       && (TREE_CODE (arg0) == SAVE_EXPR
2830           || (flags & OEP_CONSTANT_ADDRESS_OF)
2831           || (! TREE_SIDE_EFFECTS (arg0) && ! TREE_SIDE_EFFECTS (arg1))))
2832     return 1;
2833
2834   /* Next handle constant cases, those for which we can return 1 even
2835      if ONLY_CONST is set.  */
2836   if (TREE_CONSTANT (arg0) && TREE_CONSTANT (arg1))
2837     switch (TREE_CODE (arg0))
2838       {
2839       case INTEGER_CST:
2840         return tree_int_cst_equal (arg0, arg1);
2841
2842       case FIXED_CST:
2843         return FIXED_VALUES_IDENTICAL (TREE_FIXED_CST (arg0),
2844                                        TREE_FIXED_CST (arg1));
2845
2846       case REAL_CST:
2847         if (real_identical (&TREE_REAL_CST (arg0), &TREE_REAL_CST (arg1)))
2848           return 1;
2849
2850
2851         if (!HONOR_SIGNED_ZEROS (arg0))
2852           {
2853             /* If we do not distinguish between signed and unsigned zero,
2854                consider them equal.  */
2855             if (real_zerop (arg0) && real_zerop (arg1))
2856               return 1;
2857           }
2858         return 0;
2859
2860       case VECTOR_CST:
2861         {
2862           unsigned i;
2863
2864           if (VECTOR_CST_NELTS (arg0) != VECTOR_CST_NELTS (arg1))
2865             return 0;
2866
2867           for (i = 0; i < VECTOR_CST_NELTS (arg0); ++i)
2868             {
2869               if (!operand_equal_p (VECTOR_CST_ELT (arg0, i),
2870                                     VECTOR_CST_ELT (arg1, i), flags))
2871                 return 0;
2872             }
2873           return 1;
2874         }
2875
2876       case COMPLEX_CST:
2877         return (operand_equal_p (TREE_REALPART (arg0), TREE_REALPART (arg1),
2878                                  flags)
2879                 && operand_equal_p (TREE_IMAGPART (arg0), TREE_IMAGPART (arg1),
2880                                     flags));
2881
2882       case STRING_CST:
2883         return (TREE_STRING_LENGTH (arg0) == TREE_STRING_LENGTH (arg1)
2884                 && ! memcmp (TREE_STRING_POINTER (arg0),
2885                               TREE_STRING_POINTER (arg1),
2886                               TREE_STRING_LENGTH (arg0)));
2887
2888       case ADDR_EXPR:
2889         gcc_checking_assert (!(flags
2890                                & (OEP_ADDRESS_OF | OEP_CONSTANT_ADDRESS_OF)));
2891         return operand_equal_p (TREE_OPERAND (arg0, 0), TREE_OPERAND (arg1, 0),
2892                                 flags | OEP_ADDRESS_OF
2893                                 | OEP_CONSTANT_ADDRESS_OF);
2894       case CONSTRUCTOR:
2895         /* In GIMPLE empty constructors are allowed in initializers of
2896            aggregates.  */
2897         return (!vec_safe_length (CONSTRUCTOR_ELTS (arg0))
2898                 && !vec_safe_length (CONSTRUCTOR_ELTS (arg1)));
2899       default:
2900         break;
2901       }
2902
2903   if (flags & OEP_ONLY_CONST)
2904     return 0;
2905
2906 /* Define macros to test an operand from arg0 and arg1 for equality and a
2907    variant that allows null and views null as being different from any
2908    non-null value.  In the latter case, if either is null, the both
2909    must be; otherwise, do the normal comparison.  */
2910 #define OP_SAME(N) operand_equal_p (TREE_OPERAND (arg0, N),     \
2911                                     TREE_OPERAND (arg1, N), flags)
2912
2913 #define OP_SAME_WITH_NULL(N)                            \
2914   ((!TREE_OPERAND (arg0, N) || !TREE_OPERAND (arg1, N)) \
2915    ? TREE_OPERAND (arg0, N) == TREE_OPERAND (arg1, N) : OP_SAME (N))
2916
2917   switch (TREE_CODE_CLASS (TREE_CODE (arg0)))
2918     {
2919     case tcc_unary:
2920       /* Two conversions are equal only if signedness and modes match.  */
2921       switch (TREE_CODE (arg0))
2922         {
2923         CASE_CONVERT:
2924         case FIX_TRUNC_EXPR:
2925           if (TYPE_UNSIGNED (TREE_TYPE (arg0))
2926               != TYPE_UNSIGNED (TREE_TYPE (arg1)))
2927             return 0;
2928           break;
2929         default:
2930           break;
2931         }
2932
2933       return OP_SAME (0);
2934
2935
2936     case tcc_comparison:
2937     case tcc_binary:
2938       if (OP_SAME (0) && OP_SAME (1))
2939         return 1;
2940
2941       /* For commutative ops, allow the other order.  */
2942       return (commutative_tree_code (TREE_CODE (arg0))
2943               && operand_equal_p (TREE_OPERAND (arg0, 0),
2944                                   TREE_OPERAND (arg1, 1), flags)
2945               && operand_equal_p (TREE_OPERAND (arg0, 1),
2946                                   TREE_OPERAND (arg1, 0), flags));
2947
2948     case tcc_reference:
2949       /* If either of the pointer (or reference) expressions we are
2950          dereferencing contain a side effect, these cannot be equal,
2951          but their addresses can be.  */
2952       if ((flags & OEP_CONSTANT_ADDRESS_OF) == 0
2953           && (TREE_SIDE_EFFECTS (arg0)
2954               || TREE_SIDE_EFFECTS (arg1)))
2955         return 0;
2956
2957       switch (TREE_CODE (arg0))
2958         {
2959         case INDIRECT_REF:
2960           if (!(flags & (OEP_ADDRESS_OF | OEP_CONSTANT_ADDRESS_OF))
2961               && (TYPE_ALIGN (TREE_TYPE (arg0))
2962                   != TYPE_ALIGN (TREE_TYPE (arg1))))
2963             return 0;
2964           flags &= ~(OEP_CONSTANT_ADDRESS_OF|OEP_ADDRESS_OF);
2965           return OP_SAME (0);
2966
2967         case REALPART_EXPR:
2968         case IMAGPART_EXPR:
2969           return OP_SAME (0);
2970
2971         case TARGET_MEM_REF:
2972         case MEM_REF:
2973           if (!(flags & (OEP_ADDRESS_OF | OEP_CONSTANT_ADDRESS_OF)))
2974             {
2975               /* Require equal access sizes */
2976               if (TYPE_SIZE (TREE_TYPE (arg0)) != TYPE_SIZE (TREE_TYPE (arg1))
2977                   && (!TYPE_SIZE (TREE_TYPE (arg0))
2978                       || !TYPE_SIZE (TREE_TYPE (arg1))
2979                       || !operand_equal_p (TYPE_SIZE (TREE_TYPE (arg0)),
2980                                            TYPE_SIZE (TREE_TYPE (arg1)),
2981                                            flags)))
2982                 return 0;
2983               /* Verify that access happens in similar types.  */
2984               if (!types_compatible_p (TREE_TYPE (arg0), TREE_TYPE (arg1)))
2985                 return 0;
2986               /* Verify that accesses are TBAA compatible.  */
2987               if (flag_strict_aliasing
2988                   && (!alias_ptr_types_compatible_p
2989                         (TREE_TYPE (TREE_OPERAND (arg0, 1)),
2990                          TREE_TYPE (TREE_OPERAND (arg1, 1)))
2991                       || (MR_DEPENDENCE_CLIQUE (arg0)
2992                           != MR_DEPENDENCE_CLIQUE (arg1))
2993                       || (MR_DEPENDENCE_BASE (arg0)
2994                           != MR_DEPENDENCE_BASE (arg1))))
2995                 return 0;
2996              /* Verify that alignment is compatible.  */
2997              if (TYPE_ALIGN (TREE_TYPE (arg0))
2998                  != TYPE_ALIGN (TREE_TYPE (arg1)))
2999                 return 0;
3000             }
3001           flags &= ~(OEP_CONSTANT_ADDRESS_OF|OEP_ADDRESS_OF);
3002           return (OP_SAME (0) && OP_SAME (1)
3003                   /* TARGET_MEM_REF require equal extra operands.  */
3004                   && (TREE_CODE (arg0) != TARGET_MEM_REF
3005                       || (OP_SAME_WITH_NULL (2)
3006                           && OP_SAME_WITH_NULL (3)
3007                           && OP_SAME_WITH_NULL (4))));
3008
3009         case ARRAY_REF:
3010         case ARRAY_RANGE_REF:
3011           /* Operands 2 and 3 may be null.
3012              Compare the array index by value if it is constant first as we
3013              may have different types but same value here.  */
3014           if (!OP_SAME (0))
3015             return 0;
3016           flags &= ~(OEP_CONSTANT_ADDRESS_OF|OEP_ADDRESS_OF);
3017           return ((tree_int_cst_equal (TREE_OPERAND (arg0, 1),
3018                                        TREE_OPERAND (arg1, 1))
3019                    || OP_SAME (1))
3020                   && OP_SAME_WITH_NULL (2)
3021                   && OP_SAME_WITH_NULL (3));
3022
3023         case COMPONENT_REF:
3024           /* Handle operand 2 the same as for ARRAY_REF.  Operand 0
3025              may be NULL when we're called to compare MEM_EXPRs.  */
3026           if (!OP_SAME_WITH_NULL (0)
3027               || !OP_SAME (1))
3028             return 0;
3029           flags &= ~(OEP_CONSTANT_ADDRESS_OF|OEP_ADDRESS_OF);
3030           return OP_SAME_WITH_NULL (2);
3031
3032         case BIT_FIELD_REF:
3033           if (!OP_SAME (0))
3034             return 0;
3035           flags &= ~(OEP_CONSTANT_ADDRESS_OF|OEP_ADDRESS_OF);
3036           return OP_SAME (1) && OP_SAME (2);
3037
3038         default:
3039           return 0;
3040         }
3041
3042     case tcc_expression:
3043       switch (TREE_CODE (arg0))
3044         {
3045         case ADDR_EXPR:
3046           /* Be sure we pass right ADDRESS_OF flag.  */
3047           gcc_checking_assert (!(flags
3048                                  & (OEP_ADDRESS_OF
3049                                     | OEP_CONSTANT_ADDRESS_OF)));
3050           return operand_equal_p (TREE_OPERAND (arg0, 0),
3051                                   TREE_OPERAND (arg1, 0),
3052                                   flags | OEP_ADDRESS_OF);
3053
3054         case TRUTH_NOT_EXPR:
3055           return OP_SAME (0);
3056
3057         case TRUTH_ANDIF_EXPR:
3058         case TRUTH_ORIF_EXPR:
3059           return OP_SAME (0) && OP_SAME (1);
3060
3061         case FMA_EXPR:
3062         case WIDEN_MULT_PLUS_EXPR:
3063         case WIDEN_MULT_MINUS_EXPR:
3064           if (!OP_SAME (2))
3065             return 0;
3066           /* The multiplcation operands are commutative.  */
3067           /* FALLTHRU */
3068
3069         case TRUTH_AND_EXPR:
3070         case TRUTH_OR_EXPR:
3071         case TRUTH_XOR_EXPR:
3072           if (OP_SAME (0) && OP_SAME (1))
3073             return 1;
3074
3075           /* Otherwise take into account this is a commutative operation.  */
3076           return (operand_equal_p (TREE_OPERAND (arg0, 0),
3077                                    TREE_OPERAND (arg1, 1), flags)
3078                   && operand_equal_p (TREE_OPERAND (arg0, 1),
3079                                       TREE_OPERAND (arg1, 0), flags));
3080
3081         case COND_EXPR:
3082         case VEC_COND_EXPR:
3083         case DOT_PROD_EXPR:
3084           return OP_SAME (0) && OP_SAME (1) && OP_SAME (2);
3085
3086         default:
3087           return 0;
3088         }
3089
3090     case tcc_vl_exp:
3091       switch (TREE_CODE (arg0))
3092         {
3093         case CALL_EXPR:
3094           if ((CALL_EXPR_FN (arg0) == NULL_TREE)
3095               != (CALL_EXPR_FN (arg1) == NULL_TREE))
3096             /* If not both CALL_EXPRs are either internal or normal function
3097                functions, then they are not equal.  */
3098             return 0;
3099           else if (CALL_EXPR_FN (arg0) == NULL_TREE)
3100             {
3101               /* If the CALL_EXPRs call different internal functions, then they
3102                  are not equal.  */
3103               if (CALL_EXPR_IFN (arg0) != CALL_EXPR_IFN (arg1))
3104                 return 0;
3105             }
3106           else
3107             {
3108               /* If the CALL_EXPRs call different functions, then they are not
3109                  equal.  */
3110               if (! operand_equal_p (CALL_EXPR_FN (arg0), CALL_EXPR_FN (arg1),
3111                                      flags))
3112                 return 0;
3113             }
3114
3115           {
3116             unsigned int cef = call_expr_flags (arg0);
3117             if (flags & OEP_PURE_SAME)
3118               cef &= ECF_CONST | ECF_PURE;
3119             else
3120               cef &= ECF_CONST;
3121             if (!cef)
3122               return 0;
3123           }
3124
3125           /* Now see if all the arguments are the same.  */
3126           {
3127             const_call_expr_arg_iterator iter0, iter1;
3128             const_tree a0, a1;
3129             for (a0 = first_const_call_expr_arg (arg0, &iter0),
3130                    a1 = first_const_call_expr_arg (arg1, &iter1);
3131                  a0 && a1;
3132                  a0 = next_const_call_expr_arg (&iter0),
3133                    a1 = next_const_call_expr_arg (&iter1))
3134               if (! operand_equal_p (a0, a1, flags))
3135                 return 0;
3136
3137             /* If we get here and both argument lists are exhausted
3138                then the CALL_EXPRs are equal.  */
3139             return ! (a0 || a1);
3140           }
3141         default:
3142           return 0;
3143         }
3144
3145     case tcc_declaration:
3146       /* Consider __builtin_sqrt equal to sqrt.  */
3147       return (TREE_CODE (arg0) == FUNCTION_DECL
3148               && DECL_BUILT_IN (arg0) && DECL_BUILT_IN (arg1)
3149               && DECL_BUILT_IN_CLASS (arg0) == DECL_BUILT_IN_CLASS (arg1)
3150               && DECL_FUNCTION_CODE (arg0) == DECL_FUNCTION_CODE (arg1));
3151
3152     case tcc_exceptional:
3153       if (TREE_CODE (arg0) == CONSTRUCTOR)
3154         {
3155           /* In GIMPLE constructors are used only to build vectors from
3156              elements.  Individual elements in the constructor must be
3157              indexed in increasing order and form an initial sequence.
3158
3159              We make no effort to compare constructors in generic.
3160              (see sem_variable::equals in ipa-icf which can do so for
3161               constants).  */
3162           if (!VECTOR_TYPE_P (TREE_TYPE (arg0))
3163               || !VECTOR_TYPE_P (TREE_TYPE (arg1)))
3164             return 0;
3165
3166           /* Be sure that vectors constructed have the same representation.
3167              We only tested element precision and modes to match.
3168              Vectors may be BLKmode and thus also check that the number of
3169              parts match.  */
3170           if (TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0))
3171               != TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg1)))
3172             return 0;
3173
3174           vec<constructor_elt, va_gc> *v0 = CONSTRUCTOR_ELTS (arg0);
3175           vec<constructor_elt, va_gc> *v1 = CONSTRUCTOR_ELTS (arg1);
3176           unsigned int len = vec_safe_length (v0);
3177
3178           if (len != vec_safe_length (v1))
3179             return 0;
3180
3181           for (unsigned int i = 0; i < len; i++)
3182             {
3183               constructor_elt *c0 = &(*v0)[i];
3184               constructor_elt *c1 = &(*v1)[i];
3185
3186               if (!operand_equal_p (c0->value, c1->value, flags)
3187                   /* In GIMPLE the indexes can be either NULL or matching i.
3188                      Double check this so we won't get false
3189                      positives for GENERIC.  */
3190                   || (c0->index
3191                       && (TREE_CODE (c0->index) != INTEGER_CST 
3192                           || !compare_tree_int (c0->index, i)))
3193                   || (c1->index
3194                       && (TREE_CODE (c1->index) != INTEGER_CST 
3195                           || !compare_tree_int (c1->index, i))))
3196                 return 0;
3197             }
3198           return 1;
3199         }
3200       return 0;
3201
3202     default:
3203       return 0;
3204     }
3205
3206 #undef OP_SAME
3207 #undef OP_SAME_WITH_NULL
3208 }
3209 \f
3210 /* Similar to operand_equal_p, but see if ARG0 might have been made by
3211    shorten_compare from ARG1 when ARG1 was being compared with OTHER.
3212
3213    When in doubt, return 0.  */
3214
3215 static int
3216 operand_equal_for_comparison_p (tree arg0, tree arg1, tree other)
3217 {
3218   int unsignedp1, unsignedpo;
3219   tree primarg0, primarg1, primother;
3220   unsigned int correct_width;
3221
3222   if (operand_equal_p (arg0, arg1, 0))
3223     return 1;
3224
3225   if (! INTEGRAL_TYPE_P (TREE_TYPE (arg0))
3226       || ! INTEGRAL_TYPE_P (TREE_TYPE (arg1)))
3227     return 0;
3228
3229   /* Discard any conversions that don't change the modes of ARG0 and ARG1
3230      and see if the inner values are the same.  This removes any
3231      signedness comparison, which doesn't matter here.  */
3232   primarg0 = arg0, primarg1 = arg1;
3233   STRIP_NOPS (primarg0);
3234   STRIP_NOPS (primarg1);
3235   if (operand_equal_p (primarg0, primarg1, 0))
3236     return 1;
3237
3238   /* Duplicate what shorten_compare does to ARG1 and see if that gives the
3239      actual comparison operand, ARG0.
3240
3241      First throw away any conversions to wider types
3242      already present in the operands.  */
3243
3244   primarg1 = get_narrower (arg1, &unsignedp1);
3245   primother = get_narrower (other, &unsignedpo);
3246
3247   correct_width = TYPE_PRECISION (TREE_TYPE (arg1));
3248   if (unsignedp1 == unsignedpo
3249       && TYPE_PRECISION (TREE_TYPE (primarg1)) < correct_width
3250       && TYPE_PRECISION (TREE_TYPE (primother)) < correct_width)
3251     {
3252       tree type = TREE_TYPE (arg0);
3253
3254       /* Make sure shorter operand is extended the right way
3255          to match the longer operand.  */
3256       primarg1 = fold_convert (signed_or_unsigned_type_for
3257                                (unsignedp1, TREE_TYPE (primarg1)), primarg1);
3258
3259       if (operand_equal_p (arg0, fold_convert (type, primarg1), 0))
3260         return 1;
3261     }
3262
3263   return 0;
3264 }
3265 \f
3266 /* See if ARG is an expression that is either a comparison or is performing
3267    arithmetic on comparisons.  The comparisons must only be comparing
3268    two different values, which will be stored in *CVAL1 and *CVAL2; if
3269    they are nonzero it means that some operands have already been found.
3270    No variables may be used anywhere else in the expression except in the
3271    comparisons.  If SAVE_P is true it means we removed a SAVE_EXPR around
3272    the expression and save_expr needs to be called with CVAL1 and CVAL2.
3273
3274    If this is true, return 1.  Otherwise, return zero.  */
3275
3276 static int
3277 twoval_comparison_p (tree arg, tree *cval1, tree *cval2, int *save_p)
3278 {
3279   enum tree_code code = TREE_CODE (arg);
3280   enum tree_code_class tclass = TREE_CODE_CLASS (code);
3281
3282   /* We can handle some of the tcc_expression cases here.  */
3283   if (tclass == tcc_expression && code == TRUTH_NOT_EXPR)
3284     tclass = tcc_unary;
3285   else if (tclass == tcc_expression
3286            && (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR
3287                || code == COMPOUND_EXPR))
3288     tclass = tcc_binary;
3289
3290   else if (tclass == tcc_expression && code == SAVE_EXPR
3291            && ! TREE_SIDE_EFFECTS (TREE_OPERAND (arg, 0)))
3292     {
3293       /* If we've already found a CVAL1 or CVAL2, this expression is
3294          two complex to handle.  */
3295       if (*cval1 || *cval2)
3296         return 0;
3297
3298       tclass = tcc_unary;
3299       *save_p = 1;
3300     }
3301
3302   switch (tclass)
3303     {
3304     case tcc_unary:
3305       return twoval_comparison_p (TREE_OPERAND (arg, 0), cval1, cval2, save_p);
3306
3307     case tcc_binary:
3308       return (twoval_comparison_p (TREE_OPERAND (arg, 0), cval1, cval2, save_p)
3309               && twoval_comparison_p (TREE_OPERAND (arg, 1),
3310                                       cval1, cval2, save_p));
3311
3312     case tcc_constant:
3313       return 1;
3314
3315     case tcc_expression:
3316       if (code == COND_EXPR)
3317         return (twoval_comparison_p (TREE_OPERAND (arg, 0),
3318                                      cval1, cval2, save_p)
3319                 && twoval_comparison_p (TREE_OPERAND (arg, 1),
3320                                         cval1, cval2, save_p)
3321                 && twoval_comparison_p (TREE_OPERAND (arg, 2),
3322                                         cval1, cval2, save_p));
3323       return 0;
3324
3325     case tcc_comparison:
3326       /* First see if we can handle the first operand, then the second.  For
3327          the second operand, we know *CVAL1 can't be zero.  It must be that
3328          one side of the comparison is each of the values; test for the
3329          case where this isn't true by failing if the two operands
3330          are the same.  */
3331
3332       if (operand_equal_p (TREE_OPERAND (arg, 0),
3333                            TREE_OPERAND (arg, 1), 0))
3334         return 0;
3335
3336       if (*cval1 == 0)
3337         *cval1 = TREE_OPERAND (arg, 0);
3338       else if (operand_equal_p (*cval1, TREE_OPERAND (arg, 0), 0))
3339         ;
3340       else if (*cval2 == 0)
3341         *cval2 = TREE_OPERAND (arg, 0);
3342       else if (operand_equal_p (*cval2, TREE_OPERAND (arg, 0), 0))
3343         ;
3344       else
3345         return 0;
3346
3347       if (operand_equal_p (*cval1, TREE_OPERAND (arg, 1), 0))
3348         ;
3349       else if (*cval2 == 0)
3350         *cval2 = TREE_OPERAND (arg, 1);
3351       else if (operand_equal_p (*cval2, TREE_OPERAND (arg, 1), 0))
3352         ;
3353       else
3354         return 0;
3355
3356       return 1;
3357
3358     default:
3359       return 0;
3360     }
3361 }
3362 \f
3363 /* ARG is a tree that is known to contain just arithmetic operations and
3364    comparisons.  Evaluate the operations in the tree substituting NEW0 for
3365    any occurrence of OLD0 as an operand of a comparison and likewise for
3366    NEW1 and OLD1.  */
3367
3368 static tree
3369 eval_subst (location_t loc, tree arg, tree old0, tree new0,
3370             tree old1, tree new1)
3371 {
3372   tree type = TREE_TYPE (arg);
3373   enum tree_code code = TREE_CODE (arg);
3374   enum tree_code_class tclass = TREE_CODE_CLASS (code);
3375
3376   /* We can handle some of the tcc_expression cases here.  */
3377   if (tclass == tcc_expression && code == TRUTH_NOT_EXPR)
3378     tclass = tcc_unary;
3379   else if (tclass == tcc_expression
3380            && (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR))
3381     tclass = tcc_binary;
3382
3383   switch (tclass)
3384     {
3385     case tcc_unary:
3386       return fold_build1_loc (loc, code, type,
3387                           eval_subst (loc, TREE_OPERAND (arg, 0),
3388                                       old0, new0, old1, new1));
3389
3390     case tcc_binary:
3391       return fold_build2_loc (loc, code, type,
3392                           eval_subst (loc, TREE_OPERAND (arg, 0),
3393                                       old0, new0, old1, new1),
3394                           eval_subst (loc, TREE_OPERAND (arg, 1),
3395                                       old0, new0, old1, new1));
3396
3397     case tcc_expression:
3398       switch (code)
3399         {
3400         case SAVE_EXPR:
3401           return eval_subst (loc, TREE_OPERAND (arg, 0), old0, new0,
3402                              old1, new1);
3403
3404         case COMPOUND_EXPR:
3405           return eval_subst (loc, TREE_OPERAND (arg, 1), old0, new0,
3406                              old1, new1);
3407
3408         case COND_EXPR:
3409           return fold_build3_loc (loc, code, type,
3410                               eval_subst (loc, TREE_OPERAND (arg, 0),
3411                                           old0, new0, old1, new1),
3412                               eval_subst (loc, TREE_OPERAND (arg, 1),
3413                                           old0, new0, old1, new1),
3414                               eval_subst (loc, TREE_OPERAND (arg, 2),
3415                                           old0, new0, old1, new1));
3416         default:
3417           break;
3418         }
3419       /* Fall through - ???  */
3420
3421     case tcc_comparison:
3422       {
3423         tree arg0 = TREE_OPERAND (arg, 0);
3424         tree arg1 = TREE_OPERAND (arg, 1);
3425
3426         /* We need to check both for exact equality and tree equality.  The
3427            former will be true if the operand has a side-effect.  In that
3428            case, we know the operand occurred exactly once.  */
3429
3430         if (arg0 == old0 || operand_equal_p (arg0, old0, 0))
3431           arg0 = new0;
3432         else if (arg0 == old1 || operand_equal_p (arg0, old1, 0))
3433           arg0 = new1;
3434
3435         if (arg1 == old0 || operand_equal_p (arg1, old0, 0))
3436           arg1 = new0;
3437         else if (arg1 == old1 || operand_equal_p (arg1, old1, 0))
3438           arg1 = new1;
3439
3440         return fold_build2_loc (loc, code, type, arg0, arg1);
3441       }
3442
3443     default:
3444       return arg;
3445     }
3446 }
3447 \f
3448 /* Return a tree for the case when the result of an expression is RESULT
3449    converted to TYPE and OMITTED was previously an operand of the expression
3450    but is now not needed (e.g., we folded OMITTED * 0).
3451
3452    If OMITTED has side effects, we must evaluate it.  Otherwise, just do
3453    the conversion of RESULT to TYPE.  */
3454
3455 tree
3456 omit_one_operand_loc (location_t loc, tree type, tree result, tree omitted)
3457 {
3458   tree t = fold_convert_loc (loc, type, result);
3459
3460   /* If the resulting operand is an empty statement, just return the omitted
3461      statement casted to void. */
3462   if (IS_EMPTY_STMT (t) && TREE_SIDE_EFFECTS (omitted))
3463     return build1_loc (loc, NOP_EXPR, void_type_node,
3464                        fold_ignored_result (omitted));
3465
3466   if (TREE_SIDE_EFFECTS (omitted))
3467     return build2_loc (loc, COMPOUND_EXPR, type,
3468                        fold_ignored_result (omitted), t);
3469
3470   return non_lvalue_loc (loc, t);
3471 }
3472
3473 /* Return a tree for the case when the result of an expression is RESULT
3474    converted to TYPE and OMITTED1 and OMITTED2 were previously operands
3475    of the expression but are now not needed.
3476
3477    If OMITTED1 or OMITTED2 has side effects, they must be evaluated.
3478    If both OMITTED1 and OMITTED2 have side effects, OMITTED1 is
3479    evaluated before OMITTED2.  Otherwise, if neither has side effects,
3480    just do the conversion of RESULT to TYPE.  */
3481
3482 tree
3483 omit_two_operands_loc (location_t loc, tree type, tree result,
3484                        tree omitted1, tree omitted2)
3485 {
3486   tree t = fold_convert_loc (loc, type, result);
3487
3488   if (TREE_SIDE_EFFECTS (omitted2))
3489     t = build2_loc (loc, COMPOUND_EXPR, type, omitted2, t);
3490   if (TREE_SIDE_EFFECTS (omitted1))
3491     t = build2_loc (loc, COMPOUND_EXPR, type, omitted1, t);
3492
3493   return TREE_CODE (t) != COMPOUND_EXPR ? non_lvalue_loc (loc, t) : t;
3494 }
3495
3496 \f
3497 /* Return a simplified tree node for the truth-negation of ARG.  This
3498    never alters ARG itself.  We assume that ARG is an operation that
3499    returns a truth value (0 or 1).
3500
3501    FIXME: one would think we would fold the result, but it causes
3502    problems with the dominator optimizer.  */
3503
3504 static tree
3505 fold_truth_not_expr (location_t loc, tree arg)
3506 {
3507   tree type = TREE_TYPE (arg);
3508   enum tree_code code = TREE_CODE (arg);
3509   location_t loc1, loc2;
3510
3511   /* If this is a comparison, we can simply invert it, except for
3512      floating-point non-equality comparisons, in which case we just
3513      enclose a TRUTH_NOT_EXPR around what we have.  */
3514
3515   if (TREE_CODE_CLASS (code) == tcc_comparison)
3516     {
3517       tree op_type = TREE_TYPE (TREE_OPERAND (arg, 0));
3518       if (FLOAT_TYPE_P (op_type)
3519           && flag_trapping_math
3520           && code != ORDERED_EXPR && code != UNORDERED_EXPR
3521           && code != NE_EXPR && code != EQ_EXPR)
3522         return NULL_TREE;
3523
3524       code = invert_tree_comparison (code, HONOR_NANS (op_type));
3525       if (code == ERROR_MARK)
3526         return NULL_TREE;
3527
3528       return build2_loc (loc, code, type, TREE_OPERAND (arg, 0),
3529                          TREE_OPERAND (arg, 1));
3530     }
3531
3532   switch (code)
3533     {
3534     case INTEGER_CST:
3535       return constant_boolean_node (integer_zerop (arg), type);
3536
3537     case TRUTH_AND_EXPR:
3538       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3539       loc2 = expr_location_or (TREE_OPERAND (arg, 1), loc);
3540       return build2_loc (loc, TRUTH_OR_EXPR, type,
3541                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)),
3542                          invert_truthvalue_loc (loc2, TREE_OPERAND (arg, 1)));
3543
3544     case TRUTH_OR_EXPR:
3545       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3546       loc2 = expr_location_or (TREE_OPERAND (arg, 1), loc);
3547       return build2_loc (loc, TRUTH_AND_EXPR, type,
3548                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)),
3549                          invert_truthvalue_loc (loc2, TREE_OPERAND (arg, 1)));
3550
3551     case TRUTH_XOR_EXPR:
3552       /* Here we can invert either operand.  We invert the first operand
3553          unless the second operand is a TRUTH_NOT_EXPR in which case our
3554          result is the XOR of the first operand with the inside of the
3555          negation of the second operand.  */
3556
3557       if (TREE_CODE (TREE_OPERAND (arg, 1)) == TRUTH_NOT_EXPR)
3558         return build2_loc (loc, TRUTH_XOR_EXPR, type, TREE_OPERAND (arg, 0),
3559                            TREE_OPERAND (TREE_OPERAND (arg, 1), 0));
3560       else
3561         return build2_loc (loc, TRUTH_XOR_EXPR, type,
3562                            invert_truthvalue_loc (loc, TREE_OPERAND (arg, 0)),
3563                            TREE_OPERAND (arg, 1));
3564
3565     case TRUTH_ANDIF_EXPR:
3566       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3567       loc2 = expr_location_or (TREE_OPERAND (arg, 1), loc);
3568       return build2_loc (loc, TRUTH_ORIF_EXPR, type,
3569                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)),
3570                          invert_truthvalue_loc (loc2, TREE_OPERAND (arg, 1)));
3571
3572     case TRUTH_ORIF_EXPR:
3573       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3574       loc2 = expr_location_or (TREE_OPERAND (arg, 1), loc);
3575       return build2_loc (loc, TRUTH_ANDIF_EXPR, type,
3576                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)),
3577                          invert_truthvalue_loc (loc2, TREE_OPERAND (arg, 1)));
3578
3579     case TRUTH_NOT_EXPR:
3580       return TREE_OPERAND (arg, 0);
3581
3582     case COND_EXPR:
3583       {
3584         tree arg1 = TREE_OPERAND (arg, 1);
3585         tree arg2 = TREE_OPERAND (arg, 2);
3586
3587         loc1 = expr_location_or (TREE_OPERAND (arg, 1), loc);
3588         loc2 = expr_location_or (TREE_OPERAND (arg, 2), loc);
3589
3590         /* A COND_EXPR may have a throw as one operand, which
3591            then has void type.  Just leave void operands
3592            as they are.  */
3593         return build3_loc (loc, COND_EXPR, type, TREE_OPERAND (arg, 0),
3594                            VOID_TYPE_P (TREE_TYPE (arg1))
3595                            ? arg1 : invert_truthvalue_loc (loc1, arg1),
3596                            VOID_TYPE_P (TREE_TYPE (arg2))
3597                            ? arg2 : invert_truthvalue_loc (loc2, arg2));
3598       }
3599
3600     case COMPOUND_EXPR:
3601       loc1 = expr_location_or (TREE_OPERAND (arg, 1), loc);
3602       return build2_loc (loc, COMPOUND_EXPR, type,
3603                          TREE_OPERAND (arg, 0),
3604                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 1)));
3605
3606     case NON_LVALUE_EXPR:
3607       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3608       return invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0));
3609
3610     CASE_CONVERT:
3611       if (TREE_CODE (TREE_TYPE (arg)) == BOOLEAN_TYPE)
3612         return build1_loc (loc, TRUTH_NOT_EXPR, type, arg);
3613
3614       /* ... fall through ...  */
3615
3616     case FLOAT_EXPR:
3617       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3618       return build1_loc (loc, TREE_CODE (arg), type,
3619                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)));
3620
3621     case BIT_AND_EXPR:
3622       if (!integer_onep (TREE_OPERAND (arg, 1)))
3623         return NULL_TREE;
3624       return build2_loc (loc, EQ_EXPR, type, arg, build_int_cst (type, 0));
3625
3626     case SAVE_EXPR:
3627       return build1_loc (loc, TRUTH_NOT_EXPR, type, arg);
3628
3629     case CLEANUP_POINT_EXPR:
3630       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3631       return build1_loc (loc, CLEANUP_POINT_EXPR, type,
3632                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)));
3633
3634     default:
3635       return NULL_TREE;
3636     }
3637 }
3638
3639 /* Fold the truth-negation of ARG.  This never alters ARG itself.  We
3640    assume that ARG is an operation that returns a truth value (0 or 1
3641    for scalars, 0 or -1 for vectors).  Return the folded expression if
3642    folding is successful.  Otherwise, return NULL_TREE.  */
3643
3644 static tree
3645 fold_invert_truthvalue (location_t loc, tree arg)
3646 {
3647   tree type = TREE_TYPE (arg);
3648   return fold_unary_loc (loc, VECTOR_TYPE_P (type)
3649                               ? BIT_NOT_EXPR
3650                               : TRUTH_NOT_EXPR,
3651                          type, arg);
3652 }
3653
3654 /* Return a simplified tree node for the truth-negation of ARG.  This
3655    never alters ARG itself.  We assume that ARG is an operation that
3656    returns a truth value (0 or 1 for scalars, 0 or -1 for vectors).  */
3657
3658 tree
3659 invert_truthvalue_loc (location_t loc, tree arg)
3660 {
3661   if (TREE_CODE (arg) == ERROR_MARK)
3662     return arg;
3663
3664   tree type = TREE_TYPE (arg);
3665   return fold_build1_loc (loc, VECTOR_TYPE_P (type)
3666                                ? BIT_NOT_EXPR
3667                                : TRUTH_NOT_EXPR,
3668                           type, arg);
3669 }
3670
3671 /* Knowing that ARG0 and ARG1 are both RDIV_EXPRs, simplify a binary operation
3672    with code CODE.  This optimization is unsafe.  */
3673 static tree
3674 distribute_real_division (location_t loc, enum tree_code code, tree type,
3675                           tree arg0, tree arg1)
3676 {
3677   bool mul0 = TREE_CODE (arg0) == MULT_EXPR;
3678   bool mul1 = TREE_CODE (arg1) == MULT_EXPR;
3679
3680   /* (A / C) +- (B / C) -> (A +- B) / C.  */
3681   if (mul0 == mul1
3682       && operand_equal_p (TREE_OPERAND (arg0, 1),
3683                        TREE_OPERAND (arg1, 1), 0))
3684     return fold_build2_loc (loc, mul0 ? MULT_EXPR : RDIV_EXPR, type,
3685                         fold_build2_loc (loc, code, type,
3686                                      TREE_OPERAND (arg0, 0),
3687                                      TREE_OPERAND (arg1, 0)),
3688                         TREE_OPERAND (arg0, 1));
3689
3690   /* (A / C1) +- (A / C2) -> A * (1 / C1 +- 1 / C2).  */
3691   if (operand_equal_p (TREE_OPERAND (arg0, 0),
3692                        TREE_OPERAND (arg1, 0), 0)
3693       && TREE_CODE (TREE_OPERAND (arg0, 1)) == REAL_CST
3694       && TREE_CODE (TREE_OPERAND (arg1, 1)) == REAL_CST)
3695     {
3696       REAL_VALUE_TYPE r0, r1;
3697       r0 = TREE_REAL_CST (TREE_OPERAND (arg0, 1));
3698       r1 = TREE_REAL_CST (TREE_OPERAND (arg1, 1));
3699       if (!mul0)
3700         real_arithmetic (&r0, RDIV_EXPR, &dconst1, &r0);
3701       if (!mul1)
3702         real_arithmetic (&r1, RDIV_EXPR, &dconst1, &r1);
3703       real_arithmetic (&r0, code, &r0, &r1);
3704       return fold_build2_loc (loc, MULT_EXPR, type,
3705                           TREE_OPERAND (arg0, 0),
3706                           build_real (type, r0));
3707     }
3708
3709   return NULL_TREE;
3710 }
3711 \f
3712 /* Return a BIT_FIELD_REF of type TYPE to refer to BITSIZE bits of INNER
3713    starting at BITPOS.  The field is unsigned if UNSIGNEDP is nonzero.  */
3714
3715 static tree
3716 make_bit_field_ref (location_t loc, tree inner, tree type,
3717                     HOST_WIDE_INT bitsize, HOST_WIDE_INT bitpos, int unsignedp)
3718 {
3719   tree result, bftype;
3720
3721   if (bitpos == 0)
3722     {
3723       tree size = TYPE_SIZE (TREE_TYPE (inner));
3724       if ((INTEGRAL_TYPE_P (TREE_TYPE (inner))
3725            || POINTER_TYPE_P (TREE_TYPE (inner)))
3726           && tree_fits_shwi_p (size)
3727           && tree_to_shwi (size) == bitsize)
3728         return fold_convert_loc (loc, type, inner);
3729     }
3730
3731   bftype = type;
3732   if (TYPE_PRECISION (bftype) != bitsize
3733       || TYPE_UNSIGNED (bftype) == !unsignedp)
3734     bftype = build_nonstandard_integer_type (bitsize, 0);
3735
3736   result = build3_loc (loc, BIT_FIELD_REF, bftype, inner,
3737                        size_int (bitsize), bitsize_int (bitpos));
3738
3739   if (bftype != type)
3740     result = fold_convert_loc (loc, type, result);
3741
3742   return result;
3743 }
3744
3745 /* Optimize a bit-field compare.
3746
3747    There are two cases:  First is a compare against a constant and the
3748    second is a comparison of two items where the fields are at the same
3749    bit position relative to the start of a chunk (byte, halfword, word)
3750    large enough to contain it.  In these cases we can avoid the shift
3751    implicit in bitfield extractions.
3752
3753    For constants, we emit a compare of the shifted constant with the
3754    BIT_AND_EXPR of a mask and a byte, halfword, or word of the operand being
3755    compared.  For two fields at the same position, we do the ANDs with the
3756    similar mask and compare the result of the ANDs.
3757
3758    CODE is the comparison code, known to be either NE_EXPR or EQ_EXPR.
3759    COMPARE_TYPE is the type of the comparison, and LHS and RHS
3760    are the left and right operands of the comparison, respectively.
3761
3762    If the optimization described above can be done, we return the resulting
3763    tree.  Otherwise we return zero.  */
3764
3765 static tree
3766 optimize_bit_field_compare (location_t loc, enum tree_code code,
3767                             tree compare_type, tree lhs, tree rhs)
3768 {
3769   HOST_WIDE_INT lbitpos, lbitsize, rbitpos, rbitsize, nbitpos, nbitsize;
3770   tree type = TREE_TYPE (lhs);
3771   tree unsigned_type;
3772   int const_p = TREE_CODE (rhs) == INTEGER_CST;
3773   machine_mode lmode, rmode, nmode;
3774   int lunsignedp, runsignedp;
3775   int lvolatilep = 0, rvolatilep = 0;
3776   tree linner, rinner = NULL_TREE;
3777   tree mask;
3778   tree offset;
3779
3780   /* Get all the information about the extractions being done.  If the bit size
3781      if the same as the size of the underlying object, we aren't doing an
3782      extraction at all and so can do nothing.  We also don't want to
3783      do anything if the inner expression is a PLACEHOLDER_EXPR since we
3784      then will no longer be able to replace it.  */
3785   linner = get_inner_reference (lhs, &lbitsize, &lbitpos, &offset, &lmode,
3786                                 &lunsignedp, &lvolatilep, false);
3787   if (linner == lhs || lbitsize == GET_MODE_BITSIZE (lmode) || lbitsize < 0
3788       || offset != 0 || TREE_CODE (linner) == PLACEHOLDER_EXPR || lvolatilep)
3789     return 0;
3790
3791  if (!const_p)
3792    {
3793      /* If this is not a constant, we can only do something if bit positions,
3794         sizes, and signedness are the same.  */
3795      rinner = get_inner_reference (rhs, &rbitsize, &rbitpos, &offset, &rmode,
3796                                    &runsignedp, &rvolatilep, false);
3797
3798      if (rinner == rhs || lbitpos != rbitpos || lbitsize != rbitsize
3799          || lunsignedp != runsignedp || offset != 0
3800          || TREE_CODE (rinner) == PLACEHOLDER_EXPR || rvolatilep)
3801        return 0;
3802    }
3803
3804   /* See if we can find a mode to refer to this field.  We should be able to,
3805      but fail if we can't.  */
3806   nmode = get_best_mode (lbitsize, lbitpos, 0, 0,
3807                          const_p ? TYPE_ALIGN (TREE_TYPE (linner))
3808                          : MIN (TYPE_ALIGN (TREE_TYPE (linner)),
3809                                 TYPE_ALIGN (TREE_TYPE (rinner))),
3810                          word_mode, false);
3811   if (nmode == VOIDmode)
3812     return 0;
3813
3814   /* Set signed and unsigned types of the precision of this mode for the
3815      shifts below.  */
3816   unsigned_type = lang_hooks.types.type_for_mode (nmode, 1);
3817
3818   /* Compute the bit position and size for the new reference and our offset
3819      within it. If the new reference is the same size as the original, we
3820      won't optimize anything, so return zero.  */
3821   nbitsize = GET_MODE_BITSIZE (nmode);
3822   nbitpos = lbitpos & ~ (nbitsize - 1);
3823   lbitpos -= nbitpos;
3824   if (nbitsize == lbitsize)
3825     return 0;
3826
3827   if (BYTES_BIG_ENDIAN)
3828     lbitpos = nbitsize - lbitsize - lbitpos;
3829
3830   /* Make the mask to be used against the extracted field.  */
3831   mask = build_int_cst_type (unsigned_type, -1);
3832   mask = const_binop (LSHIFT_EXPR, mask, size_int (nbitsize - lbitsize));
3833   mask = const_binop (RSHIFT_EXPR, mask,
3834                       size_int (nbitsize - lbitsize - lbitpos));
3835
3836   if (! const_p)
3837     /* If not comparing with constant, just rework the comparison
3838        and return.  */
3839     return fold_build2_loc (loc, code, compare_type,
3840                         fold_build2_loc (loc, BIT_AND_EXPR, unsigned_type,
3841                                      make_bit_field_ref (loc, linner,
3842                                                          unsigned_type,
3843                                                          nbitsize, nbitpos,
3844                                                          1),
3845                                      mask),
3846                         fold_build2_loc (loc, BIT_AND_EXPR, unsigned_type,
3847                                      make_bit_field_ref (loc, rinner,
3848                                                          unsigned_type,
3849                                                          nbitsize, nbitpos,
3850                                                          1),
3851                                      mask));
3852
3853   /* Otherwise, we are handling the constant case. See if the constant is too
3854      big for the field.  Warn and return a tree of for 0 (false) if so.  We do
3855      this not only for its own sake, but to avoid having to test for this
3856      error case below.  If we didn't, we might generate wrong code.
3857
3858      For unsigned fields, the constant shifted right by the field length should
3859      be all zero.  For signed fields, the high-order bits should agree with
3860      the sign bit.  */
3861
3862   if (lunsignedp)
3863     {
3864       if (wi::lrshift (rhs, lbitsize) != 0)
3865         {
3866           warning (0, "comparison is always %d due to width of bit-field",
3867                    code == NE_EXPR);
3868           return constant_boolean_node (code == NE_EXPR, compare_type);
3869         }
3870     }
3871   else
3872     {
3873       wide_int tem = wi::arshift (rhs, lbitsize - 1);
3874       if (tem != 0 && tem != -1)
3875         {
3876           warning (0, "comparison is always %d due to width of bit-field",
3877                    code == NE_EXPR);
3878           return constant_boolean_node (code == NE_EXPR, compare_type);
3879         }
3880     }
3881
3882   /* Single-bit compares should always be against zero.  */
3883   if (lbitsize == 1 && ! integer_zerop (rhs))
3884     {
3885       code = code == EQ_EXPR ? NE_EXPR : EQ_EXPR;
3886       rhs = build_int_cst (type, 0);
3887     }
3888
3889   /* Make a new bitfield reference, shift the constant over the
3890      appropriate number of bits and mask it with the computed mask
3891      (in case this was a signed field).  If we changed it, make a new one.  */
3892   lhs = make_bit_field_ref (loc, linner, unsigned_type, nbitsize, nbitpos, 1);
3893
3894   rhs = const_binop (BIT_AND_EXPR,
3895                      const_binop (LSHIFT_EXPR,
3896                                   fold_convert_loc (loc, unsigned_type, rhs),
3897                                   size_int (lbitpos)),
3898                      mask);
3899
3900   lhs = build2_loc (loc, code, compare_type,
3901                     build2 (BIT_AND_EXPR, unsigned_type, lhs, mask), rhs);
3902   return lhs;
3903 }
3904 \f
3905 /* Subroutine for fold_truth_andor_1: decode a field reference.
3906
3907    If EXP is a comparison reference, we return the innermost reference.
3908
3909    *PBITSIZE is set to the number of bits in the reference, *PBITPOS is
3910    set to the starting bit number.
3911
3912    If the innermost field can be completely contained in a mode-sized
3913    unit, *PMODE is set to that mode.  Otherwise, it is set to VOIDmode.
3914
3915    *PVOLATILEP is set to 1 if the any expression encountered is volatile;
3916    otherwise it is not changed.
3917
3918    *PUNSIGNEDP is set to the signedness of the field.
3919
3920    *PMASK is set to the mask used.  This is either contained in a
3921    BIT_AND_EXPR or derived from the width of the field.
3922
3923    *PAND_MASK is set to the mask found in a BIT_AND_EXPR, if any.
3924
3925    Return 0 if this is not a component reference or is one that we can't
3926    do anything with.  */
3927
3928 static tree
3929 decode_field_reference (location_t loc, tree exp, HOST_WIDE_INT *pbitsize,
3930                         HOST_WIDE_INT *pbitpos, machine_mode *pmode,
3931                         int *punsignedp, int *pvolatilep,
3932                         tree *pmask, tree *pand_mask)
3933 {
3934   tree outer_type = 0;
3935   tree and_mask = 0;
3936   tree mask, inner, offset;
3937   tree unsigned_type;
3938   unsigned int precision;
3939
3940   /* All the optimizations using this function assume integer fields.
3941      There are problems with FP fields since the type_for_size call
3942      below can fail for, e.g., XFmode.  */
3943   if (! INTEGRAL_TYPE_P (TREE_TYPE (exp)))
3944     return 0;
3945
3946   /* We are interested in the bare arrangement of bits, so strip everything
3947      that doesn't affect the machine mode.  However, record the type of the
3948      outermost expression if it may matter below.  */
3949   if (CONVERT_EXPR_P (exp)
3950       || TREE_CODE (exp) == NON_LVALUE_EXPR)
3951     outer_type = TREE_TYPE (exp);
3952   STRIP_NOPS (exp);
3953
3954   if (TREE_CODE (exp) == BIT_AND_EXPR)
3955     {
3956       and_mask = TREE_OPERAND (exp, 1);
3957       exp = TREE_OPERAND (exp, 0);
3958       STRIP_NOPS (exp); STRIP_NOPS (and_mask);
3959       if (TREE_CODE (and_mask) != INTEGER_CST)
3960         return 0;
3961     }
3962
3963   inner = get_inner_reference (exp, pbitsize, pbitpos, &offset, pmode,
3964                                punsignedp, pvolatilep, false);
3965   if ((inner == exp && and_mask == 0)
3966       || *pbitsize < 0 || offset != 0
3967       || TREE_CODE (inner) == PLACEHOLDER_EXPR)
3968     return 0;
3969
3970   /* If the number of bits in the reference is the same as the bitsize of
3971      the outer type, then the outer type gives the signedness. Otherwise
3972      (in case of a small bitfield) the signedness is unchanged.  */
3973   if (outer_type && *pbitsize == TYPE_PRECISION (outer_type))
3974     *punsignedp = TYPE_UNSIGNED (outer_type);
3975
3976   /* Compute the mask to access the bitfield.  */
3977   unsigned_type = lang_hooks.types.type_for_size (*pbitsize, 1);
3978   precision = TYPE_PRECISION (unsigned_type);
3979
3980   mask = build_int_cst_type (unsigned_type, -1);
3981
3982   mask = const_binop (LSHIFT_EXPR, mask, size_int (precision - *pbitsize));
3983   mask = const_binop (RSHIFT_EXPR, mask, size_int (precision - *pbitsize));
3984
3985   /* Merge it with the mask we found in the BIT_AND_EXPR, if any.  */
3986   if (and_mask != 0)
3987     mask = fold_build2_loc (loc, BIT_AND_EXPR, unsigned_type,
3988                         fold_convert_loc (loc, unsigned_type, and_mask), mask);
3989
3990   *pmask = mask;
3991   *pand_mask = and_mask;
3992   return inner;
3993 }
3994
3995 /* Return nonzero if MASK represents a mask of SIZE ones in the low-order
3996    bit positions and MASK is SIGNED.  */
3997
3998 static int
3999 all_ones_mask_p (const_tree mask, unsigned int size)
4000 {
4001   tree type = TREE_TYPE (mask);
4002   unsigned int precision = TYPE_PRECISION (type);
4003
4004   /* If this function returns true when the type of the mask is
4005      UNSIGNED, then there will be errors.  In particular see
4006      gcc.c-torture/execute/990326-1.c.  There does not appear to be
4007      any documentation paper trail as to why this is so.  But the pre
4008      wide-int worked with that restriction and it has been preserved
4009      here.  */
4010   if (size > precision || TYPE_SIGN (type) == UNSIGNED)
4011     return false;
4012
4013   return wi::mask (size, false, precision) == mask;
4014 }
4015
4016 /* Subroutine for fold: determine if VAL is the INTEGER_CONST that
4017    represents the sign bit of EXP's type.  If EXP represents a sign
4018    or zero extension, also test VAL against the unextended type.
4019    The return value is the (sub)expression whose sign bit is VAL,
4020    or NULL_TREE otherwise.  */
4021
4022 tree
4023 sign_bit_p (tree exp, const_tree val)
4024 {
4025   int width;
4026   tree t;
4027
4028   /* Tree EXP must have an integral type.  */
4029   t = TREE_TYPE (exp);
4030   if (! INTEGRAL_TYPE_P (t))
4031     return NULL_TREE;
4032
4033   /* Tree VAL must be an integer constant.  */
4034   if (TREE_CODE (val) != INTEGER_CST
4035       || TREE_OVERFLOW (val))
4036     return NULL_TREE;
4037
4038   width = TYPE_PRECISION (t);
4039   if (wi::only_sign_bit_p (val, width))
4040     return exp;
4041
4042   /* Handle extension from a narrower type.  */
4043   if (TREE_CODE (exp) == NOP_EXPR
4044       && TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (exp, 0))) < width)
4045     return sign_bit_p (TREE_OPERAND (exp, 0), val);
4046
4047   return NULL_TREE;
4048 }
4049
4050 /* Subroutine for fold_truth_andor_1: determine if an operand is simple enough
4051    to be evaluated unconditionally.  */
4052
4053 static int
4054 simple_operand_p (const_tree exp)
4055 {
4056   /* Strip any conversions that don't change the machine mode.  */
4057   STRIP_NOPS (exp);
4058
4059   return (CONSTANT_CLASS_P (exp)
4060           || TREE_CODE (exp) == SSA_NAME
4061           || (DECL_P (exp)
4062               && ! TREE_ADDRESSABLE (exp)
4063               && ! TREE_THIS_VOLATILE (exp)
4064               && ! DECL_NONLOCAL (exp)
4065               /* Don't regard global variables as simple.  They may be
4066                  allocated in ways unknown to the compiler (shared memory,
4067                  #pragma weak, etc).  */
4068               && ! TREE_PUBLIC (exp)
4069               && ! DECL_EXTERNAL (exp)
4070               /* Weakrefs are not safe to be read, since they can be NULL.
4071                  They are !TREE_PUBLIC && !DECL_EXTERNAL but still
4072                  have DECL_WEAK flag set.  */
4073               && (! VAR_OR_FUNCTION_DECL_P (exp) || ! DECL_WEAK (exp))
4074               /* Loading a static variable is unduly expensive, but global
4075                  registers aren't expensive.  */
4076               && (! TREE_STATIC (exp) || DECL_REGISTER (exp))));
4077 }
4078
4079 /* Subroutine for fold_truth_andor: determine if an operand is simple enough
4080    to be evaluated unconditionally.
4081    I addition to simple_operand_p, we assume that comparisons, conversions,
4082    and logic-not operations are simple, if their operands are simple, too.  */
4083
4084 static bool
4085 simple_operand_p_2 (tree exp)
4086 {
4087   enum tree_code code;
4088
4089   if (TREE_SIDE_EFFECTS (exp)
4090       || tree_could_trap_p (exp))
4091     return false;
4092
4093   while (CONVERT_EXPR_P (exp))
4094     exp = TREE_OPERAND (exp, 0);
4095
4096   code = TREE_CODE (exp);
4097
4098   if (TREE_CODE_CLASS (code) == tcc_comparison)
4099     return (simple_operand_p (TREE_OPERAND (exp, 0))
4100             && simple_operand_p (TREE_OPERAND (exp, 1)));
4101
4102   if (code == TRUTH_NOT_EXPR)
4103       return simple_operand_p_2 (TREE_OPERAND (exp, 0));
4104
4105   return simple_operand_p (exp);
4106 }
4107
4108 \f
4109 /* The following functions are subroutines to fold_range_test and allow it to
4110    try to change a logical combination of comparisons into a range test.
4111
4112    For example, both
4113         X == 2 || X == 3 || X == 4 || X == 5
4114    and
4115         X >= 2 && X <= 5
4116    are converted to
4117         (unsigned) (X - 2) <= 3
4118
4119    We describe each set of comparisons as being either inside or outside
4120    a range, using a variable named like IN_P, and then describe the
4121    range with a lower and upper bound.  If one of the bounds is omitted,
4122    it represents either the highest or lowest value of the type.
4123
4124    In the comments below, we represent a range by two numbers in brackets
4125    preceded by a "+" to designate being inside that range, or a "-" to
4126    designate being outside that range, so the condition can be inverted by
4127    flipping the prefix.  An omitted bound is represented by a "-".  For
4128    example, "- [-, 10]" means being outside the range starting at the lowest
4129    possible value and ending at 10, in other words, being greater than 10.
4130    The range "+ [-, -]" is always true and hence the range "- [-, -]" is
4131    always false.
4132
4133    We set up things so that the missing bounds are handled in a consistent
4134    manner so neither a missing bound nor "true" and "false" need to be
4135    handled using a special case.  */
4136
4137 /* Return the result of applying CODE to ARG0 and ARG1, but handle the case
4138    of ARG0 and/or ARG1 being omitted, meaning an unlimited range. UPPER0_P
4139    and UPPER1_P are nonzero if the respective argument is an upper bound
4140    and zero for a lower.  TYPE, if nonzero, is the type of the result; it
4141    must be specified for a comparison.  ARG1 will be converted to ARG0's
4142    type if both are specified.  */
4143
4144 static tree
4145 range_binop (enum tree_code code, tree type, tree arg0, int upper0_p,
4146              tree arg1, int upper1_p)
4147 {
4148   tree tem;
4149   int result;
4150   int sgn0, sgn1;
4151
4152   /* If neither arg represents infinity, do the normal operation.
4153      Else, if not a comparison, return infinity.  Else handle the special
4154      comparison rules. Note that most of the cases below won't occur, but
4155      are handled for consistency.  */
4156
4157   if (arg0 != 0 && arg1 != 0)
4158     {
4159       tem = fold_build2 (code, type != 0 ? type : TREE_TYPE (arg0),
4160                          arg0, fold_convert (TREE_TYPE (arg0), arg1));
4161       STRIP_NOPS (tem);
4162       return TREE_CODE (tem) == INTEGER_CST ? tem : 0;
4163     }
4164
4165   if (TREE_CODE_CLASS (code) != tcc_comparison)
4166     return 0;
4167
4168   /* Set SGN[01] to -1 if ARG[01] is a lower bound, 1 for upper, and 0
4169      for neither.  In real maths, we cannot assume open ended ranges are
4170      the same. But, this is computer arithmetic, where numbers are finite.
4171      We can therefore make the transformation of any unbounded range with
4172      the value Z, Z being greater than any representable number. This permits
4173      us to treat unbounded ranges as equal.  */
4174   sgn0 = arg0 != 0 ? 0 : (upper0_p ? 1 : -1);
4175   sgn1 = arg1 != 0 ? 0 : (upper1_p ? 1 : -1);
4176   switch (code)
4177     {
4178     case EQ_EXPR:
4179       result = sgn0 == sgn1;
4180       break;
4181     case NE_EXPR:
4182       result = sgn0 != sgn1;
4183       break;
4184     case LT_EXPR:
4185       result = sgn0 < sgn1;
4186       break;
4187     case LE_EXPR:
4188       result = sgn0 <= sgn1;
4189       break;
4190     case GT_EXPR:
4191       result = sgn0 > sgn1;
4192       break;
4193     case GE_EXPR:
4194       result = sgn0 >= sgn1;
4195       break;
4196     default:
4197       gcc_unreachable ();
4198     }
4199
4200   return constant_boolean_node (result, type);
4201 }
4202 \f
4203 /* Helper routine for make_range.  Perform one step for it, return
4204    new expression if the loop should continue or NULL_TREE if it should
4205    stop.  */
4206
4207 tree
4208 make_range_step (location_t loc, enum tree_code code, tree arg0, tree arg1,
4209                  tree exp_type, tree *p_low, tree *p_high, int *p_in_p,
4210                  bool *strict_overflow_p)
4211 {
4212   tree arg0_type = TREE_TYPE (arg0);
4213   tree n_low, n_high, low = *p_low, high = *p_high;
4214   int in_p = *p_in_p, n_in_p;
4215
4216   switch (code)
4217     {
4218     case TRUTH_NOT_EXPR:
4219       /* We can only do something if the range is testing for zero.  */
4220       if (low == NULL_TREE || high == NULL_TREE
4221           || ! integer_zerop (low) || ! integer_zerop (high))
4222         return NULL_TREE;
4223       *p_in_p = ! in_p;
4224       return arg0;
4225
4226     case EQ_EXPR: case NE_EXPR:
4227     case LT_EXPR: case LE_EXPR: case GE_EXPR: case GT_EXPR:
4228       /* We can only do something if the range is testing for zero
4229          and if the second operand is an integer constant.  Note that
4230          saying something is "in" the range we make is done by
4231          complementing IN_P since it will set in the initial case of
4232          being not equal to zero; "out" is leaving it alone.  */
4233       if (low == NULL_TREE || high == NULL_TREE
4234           || ! integer_zerop (low) || ! integer_zerop (high)
4235           || TREE_CODE (arg1) != INTEGER_CST)
4236         return NULL_TREE;
4237
4238       switch (code)
4239         {
4240         case NE_EXPR:  /* - [c, c]  */
4241           low = high = arg1;
4242           break;
4243         case EQ_EXPR:  /* + [c, c]  */
4244           in_p = ! in_p, low = high = arg1;
4245           break;
4246         case GT_EXPR:  /* - [-, c] */
4247           low = 0, high = arg1;
4248           break;
4249         case GE_EXPR:  /* + [c, -] */
4250           in_p = ! in_p, low = arg1, high = 0;
4251           break;
4252         case LT_EXPR:  /* - [c, -] */
4253           low = arg1, high = 0;
4254           break;
4255         case LE_EXPR:  /* + [-, c] */
4256           in_p = ! in_p, low = 0, high = arg1;
4257           break;
4258         default:
4259           gcc_unreachable ();
4260         }
4261
4262       /* If this is an unsigned comparison, we also know that EXP is
4263          greater than or equal to zero.  We base the range tests we make
4264          on that fact, so we record it here so we can parse existing
4265          range tests.  We test arg0_type since often the return type
4266          of, e.g. EQ_EXPR, is boolean.  */
4267       if (TYPE_UNSIGNED (arg0_type) && (low == 0 || high == 0))
4268         {
4269           if (! merge_ranges (&n_in_p, &n_low, &n_high,
4270                               in_p, low, high, 1,
4271                               build_int_cst (arg0_type, 0),
4272                               NULL_TREE))
4273             return NULL_TREE;
4274
4275           in_p = n_in_p, low = n_low, high = n_high;
4276
4277           /* If the high bound is missing, but we have a nonzero low
4278              bound, reverse the range so it goes from zero to the low bound
4279              minus 1.  */
4280           if (high == 0 && low && ! integer_zerop (low))
4281             {
4282               in_p = ! in_p;
4283               high = range_binop (MINUS_EXPR, NULL_TREE, low, 0,
4284                                   build_int_cst (TREE_TYPE (low), 1), 0);
4285               low = build_int_cst (arg0_type, 0);
4286             }
4287         }
4288
4289       *p_low = low;
4290       *p_high = high;
4291       *p_in_p = in_p;
4292       return arg0;
4293
4294     case NEGATE_EXPR:
4295       /* If flag_wrapv and ARG0_TYPE is signed, make sure
4296          low and high are non-NULL, then normalize will DTRT.  */
4297       if (!TYPE_UNSIGNED (arg0_type)
4298           && !TYPE_OVERFLOW_UNDEFINED (arg0_type))
4299         {
4300           if (low == NULL_TREE)
4301             low = TYPE_MIN_VALUE (arg0_type);
4302           if (high == NULL_TREE)
4303             high = TYPE_MAX_VALUE (arg0_type);
4304         }
4305
4306       /* (-x) IN [a,b] -> x in [-b, -a]  */
4307       n_low = range_binop (MINUS_EXPR, exp_type,
4308                            build_int_cst (exp_type, 0),
4309                            0, high, 1);
4310       n_high = range_binop (MINUS_EXPR, exp_type,
4311                             build_int_cst (exp_type, 0),
4312                             0, low, 0);
4313       if (n_high != 0 && TREE_OVERFLOW (n_high))
4314         return NULL_TREE;
4315       goto normalize;
4316
4317     case BIT_NOT_EXPR:
4318       /* ~ X -> -X - 1  */
4319       return build2_loc (loc, MINUS_EXPR, exp_type, negate_expr (arg0),
4320                          build_int_cst (exp_type, 1));
4321
4322     case PLUS_EXPR:
4323     case MINUS_EXPR:
4324       if (TREE_CODE (arg1) != INTEGER_CST)
4325         return NULL_TREE;
4326
4327       /* If flag_wrapv and ARG0_TYPE is signed, then we cannot
4328          move a constant to the other side.  */
4329       if (!TYPE_UNSIGNED (arg0_type)
4330           && !TYPE_OVERFLOW_UNDEFINED (arg0_type))
4331         return NULL_TREE;
4332
4333       /* If EXP is signed, any overflow in the computation is undefined,
4334          so we don't worry about it so long as our computations on
4335          the bounds don't overflow.  For unsigned, overflow is defined
4336          and this is exactly the right thing.  */
4337       n_low = range_binop (code == MINUS_EXPR ? PLUS_EXPR : MINUS_EXPR,
4338                            arg0_type, low, 0, arg1, 0);
4339       n_high = range_binop (code == MINUS_EXPR ? PLUS_EXPR : MINUS_EXPR,
4340                             arg0_type, high, 1, arg1, 0);
4341       if ((n_low != 0 && TREE_OVERFLOW (n_low))
4342           || (n_high != 0 && TREE_OVERFLOW (n_high)))
4343         return NULL_TREE;
4344
4345       if (TYPE_OVERFLOW_UNDEFINED (arg0_type))
4346         *strict_overflow_p = true;
4347
4348       normalize:
4349         /* Check for an unsigned range which has wrapped around the maximum
4350            value thus making n_high < n_low, and normalize it.  */
4351         if (n_low && n_high && tree_int_cst_lt (n_high, n_low))
4352           {
4353             low = range_binop (PLUS_EXPR, arg0_type, n_high, 0,
4354                                build_int_cst (TREE_TYPE (n_high), 1), 0);
4355             high = range_binop (MINUS_EXPR, arg0_type, n_low, 0,
4356                                 build_int_cst (TREE_TYPE (n_low), 1), 0);
4357
4358             /* If the range is of the form +/- [ x+1, x ], we won't
4359                be able to normalize it.  But then, it represents the
4360                whole range or the empty set, so make it
4361                +/- [ -, - ].  */
4362             if (tree_int_cst_equal (n_low, low)
4363                 && tree_int_cst_equal (n_high, high))
4364               low = high = 0;
4365             else
4366               in_p = ! in_p;
4367           }
4368         else
4369           low = n_low, high = n_high;
4370
4371         *p_low = low;
4372         *p_high = high;
4373         *p_in_p = in_p;
4374         return arg0;
4375
4376     CASE_CONVERT:
4377     case NON_LVALUE_EXPR:
4378       if (TYPE_PRECISION (arg0_type) > TYPE_PRECISION (exp_type))
4379         return NULL_TREE;
4380
4381       if (! INTEGRAL_TYPE_P (arg0_type)
4382           || (low != 0 && ! int_fits_type_p (low, arg0_type))
4383           || (high != 0 && ! int_fits_type_p (high, arg0_type)))
4384         return NULL_TREE;
4385
4386       n_low = low, n_high = high;
4387
4388       if (n_low != 0)
4389         n_low = fold_convert_loc (loc, arg0_type, n_low);
4390
4391       if (n_high != 0)
4392         n_high = fold_convert_loc (loc, arg0_type, n_high);
4393
4394       /* If we're converting arg0 from an unsigned type, to exp,
4395          a signed type,  we will be doing the comparison as unsigned.
4396          The tests above have already verified that LOW and HIGH
4397          are both positive.
4398
4399          So we have to ensure that we will handle large unsigned
4400          values the same way that the current signed bounds treat
4401          negative values.  */
4402
4403       if (!TYPE_UNSIGNED (exp_type) && TYPE_UNSIGNED (arg0_type))
4404         {
4405           tree high_positive;
4406           tree equiv_type;
4407           /* For fixed-point modes, we need to pass the saturating flag
4408              as the 2nd parameter.  */
4409           if (ALL_FIXED_POINT_MODE_P (TYPE_MODE (arg0_type)))
4410             equiv_type
4411               = lang_hooks.types.type_for_mode (TYPE_MODE (arg0_type),
4412                                                 TYPE_SATURATING (arg0_type));
4413           else
4414             equiv_type
4415               = lang_hooks.types.type_for_mode (TYPE_MODE (arg0_type), 1);
4416
4417           /* A range without an upper bound is, naturally, unbounded.
4418              Since convert would have cropped a very large value, use
4419              the max value for the destination type.  */
4420           high_positive
4421             = TYPE_MAX_VALUE (equiv_type) ? TYPE_MAX_VALUE (equiv_type)
4422               : TYPE_MAX_VALUE (arg0_type);
4423
4424           if (TYPE_PRECISION (exp_type) == TYPE_PRECISION (arg0_type))
4425             high_positive = fold_build2_loc (loc, RSHIFT_EXPR, arg0_type,
4426                                              fold_convert_loc (loc, arg0_type,
4427                                                                high_positive),
4428                                              build_int_cst (arg0_type, 1));
4429
4430           /* If the low bound is specified, "and" the range with the
4431              range for which the original unsigned value will be
4432              positive.  */
4433           if (low != 0)
4434             {
4435               if (! merge_ranges (&n_in_p, &n_low, &n_high, 1, n_low, n_high,
4436                                   1, fold_convert_loc (loc, arg0_type,
4437                                                        integer_zero_node),
4438                                   high_positive))
4439                 return NULL_TREE;
4440
4441               in_p = (n_in_p == in_p);
4442             }
4443           else
4444             {
4445               /* Otherwise, "or" the range with the range of the input
4446                  that will be interpreted as negative.  */
4447               if (! merge_ranges (&n_in_p, &n_low, &n_high, 0, n_low, n_high,
4448                                   1, fold_convert_loc (loc, arg0_type,
4449                                                        integer_zero_node),
4450                                   high_positive))
4451                 return NULL_TREE;
4452
4453               in_p = (in_p != n_in_p);
4454             }
4455         }
4456
4457       *p_low = n_low;
4458       *p_high = n_high;
4459       *p_in_p = in_p;
4460       return arg0;
4461
4462     default:
4463       return NULL_TREE;
4464     }
4465 }
4466
4467 /* Given EXP, a logical expression, set the range it is testing into
4468    variables denoted by PIN_P, PLOW, and PHIGH.  Return the expression
4469    actually being tested.  *PLOW and *PHIGH will be made of the same
4470    type as the returned expression.  If EXP is not a comparison, we
4471    will most likely not be returning a useful value and range.  Set
4472    *STRICT_OVERFLOW_P to true if the return value is only valid
4473    because signed overflow is undefined; otherwise, do not change
4474    *STRICT_OVERFLOW_P.  */
4475
4476 tree
4477 make_range (tree exp, int *pin_p, tree *plow, tree *phigh,
4478             bool *strict_overflow_p)
4479 {
4480   enum tree_code code;
4481   tree arg0, arg1 = NULL_TREE;
4482   tree exp_type, nexp;
4483   int in_p;
4484   tree low, high;
4485   location_t loc = EXPR_LOCATION (exp);
4486
4487   /* Start with simply saying "EXP != 0" and then look at the code of EXP
4488      and see if we can refine the range.  Some of the cases below may not
4489      happen, but it doesn't seem worth worrying about this.  We "continue"
4490      the outer loop when we've changed something; otherwise we "break"
4491      the switch, which will "break" the while.  */
4492
4493   in_p = 0;
4494   low = high = build_int_cst (TREE_TYPE (exp), 0);
4495
4496   while (1)
4497     {
4498       code = TREE_CODE (exp);
4499       exp_type = TREE_TYPE (exp);
4500       arg0 = NULL_TREE;
4501
4502       if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (code)))
4503         {
4504           if (TREE_OPERAND_LENGTH (exp) > 0)
4505             arg0 = TREE_OPERAND (exp, 0);
4506           if (TREE_CODE_CLASS (code) == tcc_binary
4507               || TREE_CODE_CLASS (code) == tcc_comparison
4508               || (TREE_CODE_CLASS (code) == tcc_expression
4509                   && TREE_OPERAND_LENGTH (exp) > 1))
4510             arg1 = TREE_OPERAND (exp, 1);
4511         }
4512       if (arg0 == NULL_TREE)
4513         break;
4514
4515       nexp = make_range_step (loc, code, arg0, arg1, exp_type, &low,
4516                               &high, &in_p, strict_overflow_p);
4517       if (nexp == NULL_TREE)
4518         break;
4519       exp = nexp;
4520     }
4521
4522   /* If EXP is a constant, we can evaluate whether this is true or false.  */
4523   if (TREE_CODE (exp) == INTEGER_CST)
4524     {
4525       in_p = in_p == (integer_onep (range_binop (GE_EXPR, integer_type_node,
4526                                                  exp, 0, low, 0))
4527                       && integer_onep (range_binop (LE_EXPR, integer_type_node,
4528                                                     exp, 1, high, 1)));
4529       low = high = 0;
4530       exp = 0;
4531     }
4532
4533   *pin_p = in_p, *plow = low, *phigh = high;
4534   return exp;
4535 }
4536 \f
4537 /* Given a range, LOW, HIGH, and IN_P, an expression, EXP, and a result
4538    type, TYPE, return an expression to test if EXP is in (or out of, depending
4539    on IN_P) the range.  Return 0 if the test couldn't be created.  */
4540
4541 tree
4542 build_range_check (location_t loc, tree type, tree exp, int in_p,
4543                    tree low, tree high)
4544 {
4545   tree etype = TREE_TYPE (exp), value;
4546
4547   /* Disable this optimization for function pointer expressions
4548      on targets that require function pointer canonicalization.  */
4549   if (targetm.have_canonicalize_funcptr_for_compare ()
4550       && TREE_CODE (etype) == POINTER_TYPE
4551       && TREE_CODE (TREE_TYPE (etype)) == FUNCTION_TYPE)
4552     return NULL_TREE;
4553
4554   if (! in_p)
4555     {
4556       value = build_range_check (loc, type, exp, 1, low, high);
4557       if (value != 0)
4558         return invert_truthvalue_loc (loc, value);
4559
4560       return 0;
4561     }
4562
4563   if (low == 0 && high == 0)
4564     return omit_one_operand_loc (loc, type, build_int_cst (type, 1), exp);
4565
4566   if (low == 0)
4567     return fold_build2_loc (loc, LE_EXPR, type, exp,
4568                         fold_convert_loc (loc, etype, high));
4569
4570   if (high == 0)
4571     return fold_build2_loc (loc, GE_EXPR, type, exp,
4572                         fold_convert_loc (loc, etype, low));
4573
4574   if (operand_equal_p (low, high, 0))
4575     return fold_build2_loc (loc, EQ_EXPR, type, exp,
4576                         fold_convert_loc (loc, etype, low));
4577
4578   if (integer_zerop (low))
4579     {
4580       if (! TYPE_UNSIGNED (etype))
4581         {
4582           etype = unsigned_type_for (etype);
4583           high = fold_convert_loc (loc, etype, high);
4584           exp = fold_convert_loc (loc, etype, exp);
4585         }
4586       return build_range_check (loc, type, exp, 1, 0, high);
4587     }
4588
4589   /* Optimize (c>=1) && (c<=127) into (signed char)c > 0.  */
4590   if (integer_onep (low) && TREE_CODE (high) == INTEGER_CST)
4591     {
4592       int prec = TYPE_PRECISION (etype);
4593
4594       if (wi::mask (prec - 1, false, prec) == high)
4595         {
4596           if (TYPE_UNSIGNED (etype))
4597             {
4598               tree signed_etype = signed_type_for (etype);
4599               if (TYPE_PRECISION (signed_etype) != TYPE_PRECISION (etype))
4600                 etype
4601                   = build_nonstandard_integer_type (TYPE_PRECISION (etype), 0);
4602               else
4603                 etype = signed_etype;
4604               exp = fold_convert_loc (loc, etype, exp);
4605             }
4606           return fold_build2_loc (loc, GT_EXPR, type, exp,
4607                               build_int_cst (etype, 0));
4608         }
4609     }
4610
4611   /* Optimize (c>=low) && (c<=high) into (c-low>=0) && (c-low<=high-low).
4612      This requires wrap-around arithmetics for the type of the expression.
4613      First make sure that arithmetics in this type is valid, then make sure
4614      that it wraps around.  */
4615   if (TREE_CODE (etype) == ENUMERAL_TYPE || TREE_CODE (etype) == BOOLEAN_TYPE)
4616     etype = lang_hooks.types.type_for_size (TYPE_PRECISION (etype),
4617                                             TYPE_UNSIGNED (etype));
4618
4619   if (TREE_CODE (etype) == INTEGER_TYPE && !TYPE_OVERFLOW_WRAPS (etype))
4620     {
4621       tree utype, minv, maxv;
4622
4623       /* Check if (unsigned) INT_MAX + 1 == (unsigned) INT_MIN
4624          for the type in question, as we rely on this here.  */
4625       utype = unsigned_type_for (etype);
4626       maxv = fold_convert_loc (loc, utype, TYPE_MAX_VALUE (etype));
4627       maxv = range_binop (PLUS_EXPR, NULL_TREE, maxv, 1,
4628                           build_int_cst (TREE_TYPE (maxv), 1), 1);
4629       minv = fold_convert_loc (loc, utype, TYPE_MIN_VALUE (etype));
4630
4631       if (integer_zerop (range_binop (NE_EXPR, integer_type_node,
4632                                       minv, 1, maxv, 1)))
4633         etype = utype;
4634       else
4635         return 0;
4636     }
4637
4638   high = fold_convert_loc (loc, etype, high);
4639   low = fold_convert_loc (loc, etype, low);
4640   exp = fold_convert_loc (loc, etype, exp);
4641
4642   value = const_binop (MINUS_EXPR, high, low);
4643
4644
4645   if (POINTER_TYPE_P (etype))
4646     {
4647       if (value != 0 && !TREE_OVERFLOW (value))
4648         {
4649           low = fold_build1_loc (loc, NEGATE_EXPR, TREE_TYPE (low), low);
4650           return build_range_check (loc, type,
4651                                     fold_build_pointer_plus_loc (loc, exp, low),
4652                                     1, build_int_cst (etype, 0), value);
4653         }
4654       return 0;
4655     }
4656
4657   if (value != 0 && !TREE_OVERFLOW (value))
4658     return build_range_check (loc, type,
4659                               fold_build2_loc (loc, MINUS_EXPR, etype, exp, low),
4660                               1, build_int_cst (etype, 0), value);
4661
4662   return 0;
4663 }
4664 \f
4665 /* Return the predecessor of VAL in its type, handling the infinite case.  */
4666
4667 static tree
4668 range_predecessor (tree val)
4669 {
4670   tree type = TREE_TYPE (val);
4671
4672   if (INTEGRAL_TYPE_P (type)
4673       && operand_equal_p (val, TYPE_MIN_VALUE (type), 0))
4674     return 0;
4675   else
4676     return range_binop (MINUS_EXPR, NULL_TREE, val, 0,
4677                         build_int_cst (TREE_TYPE (val), 1), 0);
4678 }
4679
4680 /* Return the successor of VAL in its type, handling the infinite case.  */
4681
4682 static tree
4683 range_successor (tree val)
4684 {
4685   tree type = TREE_TYPE (val);
4686
4687   if (INTEGRAL_TYPE_P (type)
4688       && operand_equal_p (val, TYPE_MAX_VALUE (type), 0))
4689     return 0;
4690   else
4691     return range_binop (PLUS_EXPR, NULL_TREE, val, 0,
4692                         build_int_cst (TREE_TYPE (val), 1), 0);
4693 }
4694
4695 /* Given two ranges, see if we can merge them into one.  Return 1 if we
4696    can, 0 if we can't.  Set the output range into the specified parameters.  */
4697
4698 bool
4699 merge_ranges (int *pin_p, tree *plow, tree *phigh, int in0_p, tree low0,
4700               tree high0, int in1_p, tree low1, tree high1)
4701 {
4702   int no_overlap;
4703   int subset;
4704   int temp;
4705   tree tem;
4706   int in_p;
4707   tree low, high;
4708   int lowequal = ((low0 == 0 && low1 == 0)
4709                   || integer_onep (range_binop (EQ_EXPR, integer_type_node,
4710                                                 low0, 0, low1, 0)));
4711   int highequal = ((high0 == 0 && high1 == 0)
4712                    || integer_onep (range_binop (EQ_EXPR, integer_type_node,
4713                                                  high0, 1, high1, 1)));
4714
4715   /* Make range 0 be the range that starts first, or ends last if they
4716      start at the same value.  Swap them if it isn't.  */
4717   if (integer_onep (range_binop (GT_EXPR, integer_type_node,
4718                                  low0, 0, low1, 0))
4719       || (lowequal
4720           && integer_onep (range_binop (GT_EXPR, integer_type_node,
4721                                         high1, 1, high0, 1))))
4722     {
4723       temp = in0_p, in0_p = in1_p, in1_p = temp;
4724       tem = low0, low0 = low1, low1 = tem;
4725       tem = high0, high0 = high1, high1 = tem;
4726     }
4727
4728   /* Now flag two cases, whether the ranges are disjoint or whether the
4729      second range is totally subsumed in the first.  Note that the tests
4730      below are simplified by the ones above.  */
4731   no_overlap = integer_onep (range_binop (LT_EXPR, integer_type_node,
4732                                           high0, 1, low1, 0));
4733   subset = integer_onep (range_binop (LE_EXPR, integer_type_node,
4734                                       high1, 1, high0, 1));
4735
4736   /* We now have four cases, depending on whether we are including or
4737      excluding the two ranges.  */
4738   if (in0_p && in1_p)
4739     {
4740       /* If they don't overlap, the result is false.  If the second range
4741          is a subset it is the result.  Otherwise, the range is from the start
4742          of the second to the end of the first.  */
4743       if (no_overlap)
4744         in_p = 0, low = high = 0;
4745       else if (subset)
4746         in_p = 1, low = low1, high = high1;
4747       else
4748         in_p = 1, low = low1, high = high0;
4749     }
4750
4751   else if (in0_p && ! in1_p)
4752     {
4753       /* If they don't overlap, the result is the first range.  If they are
4754          equal, the result is false.  If the second range is a subset of the
4755          first, and the ranges begin at the same place, we go from just after
4756          the end of the second range to the end of the first.  If the second
4757          range is not a subset of the first, or if it is a subset and both
4758          ranges end at the same place, the range starts at the start of the
4759          first range and ends just before the second range.
4760          Otherwise, we can't describe this as a single range.  */
4761       if (no_overlap)
4762         in_p = 1, low = low0, high = high0;
4763       else if (lowequal && highequal)
4764         in_p = 0, low = high = 0;
4765       else if (subset && lowequal)
4766         {
4767           low = range_successor (high1);
4768           high = high0;
4769           in_p = 1;
4770           if (low == 0)
4771             {
4772               /* We are in the weird situation where high0 > high1 but
4773                  high1 has no successor.  Punt.  */
4774               return 0;
4775             }
4776         }
4777       else if (! subset || highequal)
4778         {
4779           low = low0;
4780           high = range_predecessor (low1);
4781           in_p = 1;
4782           if (high == 0)
4783             {
4784               /* low0 < low1 but low1 has no predecessor.  Punt.  */
4785               return 0;
4786             }
4787         }
4788       else
4789         return 0;
4790     }
4791
4792   else if (! in0_p && in1_p)
4793     {
4794       /* If they don't overlap, the result is the second range.  If the second
4795          is a subset of the first, the result is false.  Otherwise,
4796          the range starts just after the first range and ends at the
4797          end of the second.  */
4798       if (no_overlap)
4799         in_p = 1, low = low1, high = high1;
4800       else if (subset || highequal)
4801         in_p = 0, low = high = 0;
4802       else
4803         {
4804           low = range_successor (high0);
4805           high = high1;
4806           in_p = 1;
4807           if (low == 0)
4808             {
4809               /* high1 > high0 but high0 has no successor.  Punt.  */
4810               return 0;
4811             }
4812         }
4813     }
4814
4815   else
4816     {
4817       /* The case where we are excluding both ranges.  Here the complex case
4818          is if they don't overlap.  In that case, the only time we have a
4819          range is if they are adjacent.  If the second is a subset of the
4820          first, the result is the first.  Otherwise, the range to exclude
4821          starts at the beginning of the first range and ends at the end of the
4822          second.  */
4823       if (no_overlap)
4824         {
4825           if (integer_onep (range_binop (EQ_EXPR, integer_type_node,
4826                                          range_successor (high0),
4827                                          1, low1, 0)))
4828             in_p = 0, low = low0, high = high1;
4829           else
4830             {
4831               /* Canonicalize - [min, x] into - [-, x].  */
4832               if (low0 && TREE_CODE (low0) == INTEGER_CST)
4833                 switch (TREE_CODE (TREE_TYPE (low0)))
4834                   {
4835                   case ENUMERAL_TYPE:
4836                     if (TYPE_PRECISION (TREE_TYPE (low0))
4837                         != GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE (low0))))
4838                       break;
4839                     /* FALLTHROUGH */
4840                   case INTEGER_TYPE:
4841                     if (tree_int_cst_equal (low0,
4842                                             TYPE_MIN_VALUE (TREE_TYPE (low0))))
4843                       low0 = 0;
4844                     break;
4845                   case POINTER_TYPE:
4846                     if (TYPE_UNSIGNED (TREE_TYPE (low0))
4847                         && integer_zerop (low0))
4848                       low0 = 0;
4849                     break;
4850                   default:
4851                     break;
4852                   }
4853
4854               /* Canonicalize - [x, max] into - [x, -].  */
4855               if (high1 && TREE_CODE (high1) == INTEGER_CST)
4856                 switch (TREE_CODE (TREE_TYPE (high1)))
4857                   {
4858                   case ENUMERAL_TYPE:
4859                     if (TYPE_PRECISION (TREE_TYPE (high1))
4860                         != GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE (high1))))
4861                       break;
4862                     /* FALLTHROUGH */
4863                   case INTEGER_TYPE:
4864                     if (tree_int_cst_equal (high1,
4865                                             TYPE_MAX_VALUE (TREE_TYPE (high1))))
4866                       high1 = 0;
4867                     break;
4868                   case POINTER_TYPE:
4869                     if (TYPE_UNSIGNED (TREE_TYPE (high1))
4870                         && integer_zerop (range_binop (PLUS_EXPR, NULL_TREE,
4871                                                        high1, 1,
4872                                                        build_int_cst (TREE_TYPE (high1), 1),
4873                                                        1)))
4874                       high1 = 0;
4875                     break;
4876                   default:
4877                     break;
4878                   }
4879
4880               /* The ranges might be also adjacent between the maximum and
4881                  minimum values of the given type.  For
4882                  - [{min,-}, x] and - [y, {max,-}] ranges where x + 1 < y
4883                  return + [x + 1, y - 1].  */
4884               if (low0 == 0 && high1 == 0)
4885                 {
4886                   low = range_successor (high0);
4887                   high = range_predecessor (low1);
4888                   if (low == 0 || high == 0)
4889                     return 0;
4890
4891                   in_p = 1;
4892                 }
4893               else
4894                 return 0;
4895             }
4896         }
4897       else if (subset)
4898         in_p = 0, low = low0, high = high0;
4899       else
4900         in_p = 0, low = low0, high = high1;
4901     }
4902
4903   *pin_p = in_p, *plow = low, *phigh = high;
4904   return 1;
4905 }
4906 \f
4907
4908 /* Subroutine of fold, looking inside expressions of the form
4909    A op B ? A : C, where ARG0, ARG1 and ARG2 are the three operands
4910    of the COND_EXPR.  This function is being used also to optimize
4911    A op B ? C : A, by reversing the comparison first.
4912
4913    Return a folded expression whose code is not a COND_EXPR
4914    anymore, or NULL_TREE if no folding opportunity is found.  */
4915
4916 static tree
4917 fold_cond_expr_with_comparison (location_t loc, tree type,
4918                                 tree arg0, tree arg1, tree arg2)
4919 {
4920   enum tree_code comp_code = TREE_CODE (arg0);
4921   tree arg00 = TREE_OPERAND (arg0, 0);
4922   tree arg01 = TREE_OPERAND (arg0, 1);
4923   tree arg1_type = TREE_TYPE (arg1);
4924   tree tem;
4925
4926   STRIP_NOPS (arg1);
4927   STRIP_NOPS (arg2);
4928
4929   /* If we have A op 0 ? A : -A, consider applying the following
4930      transformations:
4931
4932      A == 0? A : -A    same as -A
4933      A != 0? A : -A    same as A
4934      A >= 0? A : -A    same as abs (A)
4935      A > 0?  A : -A    same as abs (A)
4936      A <= 0? A : -A    same as -abs (A)
4937      A < 0?  A : -A    same as -abs (A)
4938
4939      None of these transformations work for modes with signed
4940      zeros.  If A is +/-0, the first two transformations will
4941      change the sign of the result (from +0 to -0, or vice
4942      versa).  The last four will fix the sign of the result,
4943      even though the original expressions could be positive or
4944      negative, depending on the sign of A.
4945
4946      Note that all these transformations are correct if A is
4947      NaN, since the two alternatives (A and -A) are also NaNs.  */
4948   if (!HONOR_SIGNED_ZEROS (element_mode (type))
4949       && (FLOAT_TYPE_P (TREE_TYPE (arg01))
4950           ? real_zerop (arg01)
4951           : integer_zerop (arg01))
4952       && ((TREE_CODE (arg2) == NEGATE_EXPR
4953            && operand_equal_p (TREE_OPERAND (arg2, 0), arg1, 0))
4954              /* In the case that A is of the form X-Y, '-A' (arg2) may
4955                 have already been folded to Y-X, check for that. */
4956           || (TREE_CODE (arg1) == MINUS_EXPR
4957               && TREE_CODE (arg2) == MINUS_EXPR
4958               && operand_equal_p (TREE_OPERAND (arg1, 0),
4959                                   TREE_OPERAND (arg2, 1), 0)
4960               && operand_equal_p (TREE_OPERAND (arg1, 1),
4961                                   TREE_OPERAND (arg2, 0), 0))))
4962     switch (comp_code)
4963       {
4964       case EQ_EXPR:
4965       case UNEQ_EXPR:
4966         tem = fold_convert_loc (loc, arg1_type, arg1);
4967         return pedantic_non_lvalue_loc (loc,
4968                                     fold_convert_loc (loc, type,
4969                                                   negate_expr (tem)));
4970       case NE_EXPR:
4971       case LTGT_EXPR:
4972         return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, arg1));
4973       case UNGE_EXPR:
4974       case UNGT_EXPR:
4975         if (flag_trapping_math)
4976           break;
4977         /* Fall through.  */
4978       case GE_EXPR:
4979       case GT_EXPR:
4980         if (TYPE_UNSIGNED (TREE_TYPE (arg1)))
4981           arg1 = fold_convert_loc (loc, signed_type_for
4982                                (TREE_TYPE (arg1)), arg1);
4983         tem = fold_build1_loc (loc, ABS_EXPR, TREE_TYPE (arg1), arg1);
4984         return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, tem));
4985       case UNLE_EXPR:
4986       case UNLT_EXPR:
4987         if (flag_trapping_math)
4988           break;
4989       case LE_EXPR:
4990       case LT_EXPR:
4991         if (TYPE_UNSIGNED (TREE_TYPE (arg1)))
4992           arg1 = fold_convert_loc (loc, signed_type_for
4993                                (TREE_TYPE (arg1)), arg1);
4994         tem = fold_build1_loc (loc, ABS_EXPR, TREE_TYPE (arg1), arg1);
4995         return negate_expr (fold_convert_loc (loc, type, tem));
4996       default:
4997         gcc_assert (TREE_CODE_CLASS (comp_code) == tcc_comparison);
4998         break;
4999       }
5000
5001   /* A != 0 ? A : 0 is simply A, unless A is -0.  Likewise
5002      A == 0 ? A : 0 is always 0 unless A is -0.  Note that
5003      both transformations are correct when A is NaN: A != 0
5004      is then true, and A == 0 is false.  */
5005
5006   if (!HONOR_SIGNED_ZEROS (element_mode (type))
5007       && integer_zerop (arg01) && integer_zerop (arg2))
5008     {
5009       if (comp_code == NE_EXPR)
5010         return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, arg1));
5011       else if (comp_code == EQ_EXPR)
5012         return build_zero_cst (type);
5013     }
5014
5015   /* Try some transformations of A op B ? A : B.
5016
5017      A == B? A : B    same as B
5018      A != B? A : B    same as A
5019      A >= B? A : B    same as max (A, B)
5020      A > B?  A : B    same as max (B, A)
5021      A <= B? A : B    same as min (A, B)
5022      A < B?  A : B    same as min (B, A)
5023
5024      As above, these transformations don't work in the presence
5025      of signed zeros.  For example, if A and B are zeros of
5026      opposite sign, the first two transformations will change
5027      the sign of the result.  In the last four, the original
5028      expressions give different results for (A=+0, B=-0) and
5029      (A=-0, B=+0), but the transformed expressions do not.
5030
5031      The first two transformations are correct if either A or B
5032      is a NaN.  In the first transformation, the condition will
5033      be false, and B will indeed be chosen.  In the case of the
5034      second transformation, the condition A != B will be true,
5035      and A will be chosen.
5036
5037      The conversions to max() and min() are not correct if B is
5038      a number and A is not.  The conditions in the original
5039      expressions will be false, so all four give B.  The min()
5040      and max() versions would give a NaN instead.  */
5041   if (!HONOR_SIGNED_ZEROS (element_mode (type))
5042       && operand_equal_for_comparison_p (arg01, arg2, arg00)
5043       /* Avoid these transformations if the COND_EXPR may be used
5044          as an lvalue in the C++ front-end.  PR c++/19199.  */
5045       && (in_gimple_form
5046           || VECTOR_TYPE_P (type)
5047           || (! lang_GNU_CXX ()
5048               && strcmp (lang_hooks.name, "GNU Objective-C++") != 0)
5049           || ! maybe_lvalue_p (arg1)
5050           || ! maybe_lvalue_p (arg2)))
5051     {
5052       tree comp_op0 = arg00;
5053       tree comp_op1 = arg01;
5054       tree comp_type = TREE_TYPE (comp_op0);
5055
5056       /* Avoid adding NOP_EXPRs in case this is an lvalue.  */
5057       if (TYPE_MAIN_VARIANT (comp_type) == TYPE_MAIN_VARIANT (type))
5058         {
5059           comp_type = type;
5060           comp_op0 = arg1;
5061           comp_op1 = arg2;
5062         }
5063
5064       switch (comp_code)
5065         {
5066         case EQ_EXPR:
5067           return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, arg2));
5068         case NE_EXPR:
5069           return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, arg1));
5070         case LE_EXPR:
5071         case LT_EXPR:
5072         case UNLE_EXPR:
5073         case UNLT_EXPR:
5074           /* In C++ a ?: expression can be an lvalue, so put the
5075              operand which will be used if they are equal first
5076              so that we can convert this back to the
5077              corresponding COND_EXPR.  */
5078           if (!HONOR_NANS (arg1))
5079             {
5080               comp_op0 = fold_convert_loc (loc, comp_type, comp_op0);
5081               comp_op1 = fold_convert_loc (loc, comp_type, comp_op1);
5082               tem = (comp_code == LE_EXPR || comp_code == UNLE_EXPR)
5083                     ? fold_build2_loc (loc, MIN_EXPR, comp_type, comp_op0, comp_op1)
5084                     : fold_build2_loc (loc, MIN_EXPR, comp_type,
5085                                    comp_op1, comp_op0);
5086               return pedantic_non_lvalue_loc (loc,
5087                                           fold_convert_loc (loc, type, tem));
5088             }
5089           break;
5090         case GE_EXPR:
5091         case GT_EXPR:
5092         case UNGE_EXPR:
5093         case UNGT_EXPR:
5094           if (!HONOR_NANS (arg1))
5095             {
5096               comp_op0 = fold_convert_loc (loc, comp_type, comp_op0);
5097               comp_op1 = fold_convert_loc (loc, comp_type, comp_op1);
5098               tem = (comp_code == GE_EXPR || comp_code == UNGE_EXPR)
5099                     ? fold_build2_loc (loc, MAX_EXPR, comp_type, comp_op0, comp_op1)
5100                     : fold_build2_loc (loc, MAX_EXPR, comp_type,
5101                                    comp_op1, comp_op0);
5102               return pedantic_non_lvalue_loc (loc,
5103                                           fold_convert_loc (loc, type, tem));
5104             }
5105           break;
5106         case UNEQ_EXPR:
5107           if (!HONOR_NANS (arg1))
5108             return pedantic_non_lvalue_loc (loc,
5109                                         fold_convert_loc (loc, type, arg2));
5110           break;
5111         case LTGT_EXPR:
5112           if (!HONOR_NANS (arg1))
5113             return pedantic_non_lvalue_loc (loc,
5114                                         fold_convert_loc (loc, type, arg1));
5115           break;
5116         default:
5117           gcc_assert (TREE_CODE_CLASS (comp_code) == tcc_comparison);
5118           break;
5119         }
5120     }
5121
5122   /* If this is A op C1 ? A : C2 with C1 and C2 constant integers,
5123      we might still be able to simplify this.  For example,
5124      if C1 is one less or one more than C2, this might have started
5125      out as a MIN or MAX and been transformed by this function.
5126      Only good for INTEGER_TYPEs, because we need TYPE_MAX_VALUE.  */
5127
5128   if (INTEGRAL_TYPE_P (type)
5129       && TREE_CODE (arg01) == INTEGER_CST
5130       && TREE_CODE (arg2) == INTEGER_CST)
5131     switch (comp_code)
5132       {
5133       case EQ_EXPR:
5134         if (TREE_CODE (arg1) == INTEGER_CST)
5135           break;
5136         /* We can replace A with C1 in this case.  */
5137         arg1 = fold_convert_loc (loc, type, arg01);
5138         return fold_build3_loc (loc, COND_EXPR, type, arg0, arg1, arg2);
5139
5140       case LT_EXPR:
5141         /* If C1 is C2 + 1, this is min(A, C2), but use ARG00's type for
5142            MIN_EXPR, to preserve the signedness of the comparison.  */
5143         if (! operand_equal_p (arg2, TYPE_MAX_VALUE (type),
5144                                OEP_ONLY_CONST)
5145             && operand_equal_p (arg01,
5146                                 const_binop (PLUS_EXPR, arg2,
5147                                              build_int_cst (type, 1)),
5148                                 OEP_ONLY_CONST))
5149           {
5150             tem = fold_build2_loc (loc, MIN_EXPR, TREE_TYPE (arg00), arg00,
5151                                    fold_convert_loc (loc, TREE_TYPE (arg00),
5152                                                      arg2));
5153             return pedantic_non_lvalue_loc (loc,
5154                                             fold_convert_loc (loc, type, tem));
5155           }
5156         break;
5157
5158       case LE_EXPR:
5159         /* If C1 is C2 - 1, this is min(A, C2), with the same care
5160            as above.  */
5161         if (! operand_equal_p (arg2, TYPE_MIN_VALUE (type),
5162                                OEP_ONLY_CONST)
5163             && operand_equal_p (arg01,
5164                                 const_binop (MINUS_EXPR, arg2,
5165                                              build_int_cst (type, 1)),
5166                                 OEP_ONLY_CONST))
5167           {
5168             tem = fold_build2_loc (loc, MIN_EXPR, TREE_TYPE (arg00), arg00,
5169                                    fold_convert_loc (loc, TREE_TYPE (arg00),
5170                                                      arg2));
5171             return pedantic_non_lvalue_loc (loc,
5172                                             fold_convert_loc (loc, type, tem));
5173           }
5174         break;
5175
5176       case GT_EXPR:
5177         /* If C1 is C2 - 1, this is max(A, C2), but use ARG00's type for
5178            MAX_EXPR, to preserve the signedness of the comparison.  */
5179         if (! operand_equal_p (arg2, TYPE_MIN_VALUE (type),
5180                                OEP_ONLY_CONST)
5181             && operand_equal_p (arg01,
5182                                 const_binop (MINUS_EXPR, arg2,
5183                                              build_int_cst (type, 1)),
5184                                 OEP_ONLY_CONST))
5185           {
5186             tem = fold_build2_loc (loc, MAX_EXPR, TREE_TYPE (arg00), arg00,
5187                                    fold_convert_loc (loc, TREE_TYPE (arg00),
5188                                                      arg2));
5189             return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, tem));
5190           }
5191         break;
5192
5193       case GE_EXPR:
5194         /* If C1 is C2 + 1, this is max(A, C2), with the same care as above.  */
5195         if (! operand_equal_p (arg2, TYPE_MAX_VALUE (type),
5196                                OEP_ONLY_CONST)
5197             && operand_equal_p (arg01,
5198                                 const_binop (PLUS_EXPR, arg2,
5199                                              build_int_cst (type, 1)),
5200                                 OEP_ONLY_CONST))
5201           {
5202             tem = fold_build2_loc (loc, MAX_EXPR, TREE_TYPE (arg00), arg00,
5203                                    fold_convert_loc (loc, TREE_TYPE (arg00),
5204                                                      arg2));
5205             return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, tem));
5206           }
5207         break;
5208       case NE_EXPR:
5209         break;
5210       default:
5211         gcc_unreachable ();
5212       }
5213
5214   return NULL_TREE;
5215 }
5216
5217
5218 \f
5219 #ifndef LOGICAL_OP_NON_SHORT_CIRCUIT
5220 #define LOGICAL_OP_NON_SHORT_CIRCUIT \
5221   (BRANCH_COST (optimize_function_for_speed_p (cfun), \
5222                 false) >= 2)
5223 #endif
5224
5225 /* EXP is some logical combination of boolean tests.  See if we can
5226    merge it into some range test.  Return the new tree if so.  */
5227
5228 static tree
5229 fold_range_test (location_t loc, enum tree_code code, tree type,
5230                  tree op0, tree op1)
5231 {
5232   int or_op = (code == TRUTH_ORIF_EXPR
5233                || code == TRUTH_OR_EXPR);
5234   int in0_p, in1_p, in_p;
5235   tree low0, low1, low, high0, high1, high;
5236   bool strict_overflow_p = false;
5237   tree tem, lhs, rhs;
5238   const char * const warnmsg = G_("assuming signed overflow does not occur "
5239                                   "when simplifying range test");
5240
5241   if (!INTEGRAL_TYPE_P (type))
5242     return 0;
5243
5244   lhs = make_range (op0, &in0_p, &low0, &high0, &strict_overflow_p);
5245   rhs = make_range (op1, &in1_p, &low1, &high1, &strict_overflow_p);
5246
5247   /* If this is an OR operation, invert both sides; we will invert
5248      again at the end.  */
5249   if (or_op)
5250     in0_p = ! in0_p, in1_p = ! in1_p;
5251
5252   /* If both expressions are the same, if we can merge the ranges, and we
5253      can build the range test, return it or it inverted.  If one of the
5254      ranges is always true or always false, consider it to be the same
5255      expression as the other.  */
5256   if ((lhs == 0 || rhs == 0 || operand_equal_p (lhs, rhs, 0))
5257       && merge_ranges (&in_p, &low, &high, in0_p, low0, high0,
5258                        in1_p, low1, high1)
5259       && 0 != (tem = (build_range_check (loc, type,
5260                                          lhs != 0 ? lhs
5261                                          : rhs != 0 ? rhs : integer_zero_node,
5262                                          in_p, low, high))))
5263     {
5264       if (strict_overflow_p)
5265         fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_COMPARISON);
5266       return or_op ? invert_truthvalue_loc (loc, tem) : tem;
5267     }
5268
5269   /* On machines where the branch cost is expensive, if this is a
5270      short-circuited branch and the underlying object on both sides
5271      is the same, make a non-short-circuit operation.  */
5272   else if (LOGICAL_OP_NON_SHORT_CIRCUIT
5273            && lhs != 0 && rhs != 0
5274            && (code == TRUTH_ANDIF_EXPR
5275                || code == TRUTH_ORIF_EXPR)
5276            && operand_equal_p (lhs, rhs, 0))
5277     {
5278       /* If simple enough, just rewrite.  Otherwise, make a SAVE_EXPR
5279          unless we are at top level or LHS contains a PLACEHOLDER_EXPR, in
5280          which cases we can't do this.  */
5281       if (simple_operand_p (lhs))
5282         return build2_loc (loc, code == TRUTH_ANDIF_EXPR
5283                            ? TRUTH_AND_EXPR : TRUTH_OR_EXPR,
5284                            type, op0, op1);
5285
5286       else if (!lang_hooks.decls.global_bindings_p ()
5287                && !CONTAINS_PLACEHOLDER_P (lhs))
5288         {
5289           tree common = save_expr (lhs);
5290
5291           if (0 != (lhs = build_range_check (loc, type, common,
5292                                              or_op ? ! in0_p : in0_p,
5293                                              low0, high0))
5294               && (0 != (rhs = build_range_check (loc, type, common,
5295                                                  or_op ? ! in1_p : in1_p,
5296                                                  low1, high1))))
5297             {
5298               if (strict_overflow_p)
5299                 fold_overflow_warning (warnmsg,
5300                                        WARN_STRICT_OVERFLOW_COMPARISON);
5301               return build2_loc (loc, code == TRUTH_ANDIF_EXPR
5302                                  ? TRUTH_AND_EXPR : TRUTH_OR_EXPR,
5303                                  type, lhs, rhs);
5304             }
5305         }
5306     }
5307
5308   return 0;
5309 }
5310 \f
5311 /* Subroutine for fold_truth_andor_1: C is an INTEGER_CST interpreted as a P
5312    bit value.  Arrange things so the extra bits will be set to zero if and
5313    only if C is signed-extended to its full width.  If MASK is nonzero,
5314    it is an INTEGER_CST that should be AND'ed with the extra bits.  */
5315
5316 static tree
5317 unextend (tree c, int p, int unsignedp, tree mask)
5318 {
5319   tree type = TREE_TYPE (c);
5320   int modesize = GET_MODE_BITSIZE (TYPE_MODE (type));
5321   tree temp;
5322
5323   if (p == modesize || unsignedp)
5324     return c;
5325
5326   /* We work by getting just the sign bit into the low-order bit, then
5327      into the high-order bit, then sign-extend.  We then XOR that value
5328      with C.  */
5329   temp = build_int_cst (TREE_TYPE (c), wi::extract_uhwi (c, p - 1, 1));
5330
5331   /* We must use a signed type in order to get an arithmetic right shift.
5332      However, we must also avoid introducing accidental overflows, so that
5333      a subsequent call to integer_zerop will work.  Hence we must
5334      do the type conversion here.  At this point, the constant is either
5335      zero or one, and the conversion to a signed type can never overflow.
5336      We could get an overflow if this conversion is done anywhere else.  */
5337   if (TYPE_UNSIGNED (type))
5338     temp = fold_convert (signed_type_for (type), temp);
5339
5340   temp = const_binop (LSHIFT_EXPR, temp, size_int (modesize - 1));
5341   temp = const_binop (RSHIFT_EXPR, temp, size_int (modesize - p - 1));
5342   if (mask != 0)
5343     temp = const_binop (BIT_AND_EXPR, temp,
5344                         fold_convert (TREE_TYPE (c), mask));
5345   /* If necessary, convert the type back to match the type of C.  */
5346   if (TYPE_UNSIGNED (type))
5347     temp = fold_convert (type, temp);
5348
5349   return fold_convert (type, const_binop (BIT_XOR_EXPR, c, temp));
5350 }
5351 \f
5352 /* For an expression that has the form
5353      (A && B) || ~B
5354    or
5355      (A || B) && ~B,
5356    we can drop one of the inner expressions and simplify to
5357      A || ~B
5358    or
5359      A && ~B
5360    LOC is the location of the resulting expression.  OP is the inner 
5361    logical operation; the left-hand side in the examples above, while CMPOP
5362    is the right-hand side.  RHS_ONLY is used to prevent us from accidentally
5363    removing a condition that guards another, as in
5364      (A != NULL && A->...) || A == NULL
5365    which we must not transform.  If RHS_ONLY is true, only eliminate the
5366    right-most operand of the inner logical operation.  */
5367
5368 static tree
5369 merge_truthop_with_opposite_arm (location_t loc, tree op, tree cmpop,
5370                                  bool rhs_only)
5371 {
5372   tree type = TREE_TYPE (cmpop);
5373   enum tree_code code = TREE_CODE (cmpop);
5374   enum tree_code truthop_code = TREE_CODE (op);
5375   tree lhs = TREE_OPERAND (op, 0);
5376   tree rhs = TREE_OPERAND (op, 1);
5377   tree orig_lhs = lhs, orig_rhs = rhs;
5378   enum tree_code rhs_code = TREE_CODE (rhs);
5379   enum tree_code lhs_code = TREE_CODE (lhs);
5380   enum tree_code inv_code;
5381
5382   if (TREE_SIDE_EFFECTS (op) || TREE_SIDE_EFFECTS (cmpop))
5383     return NULL_TREE;
5384
5385   if (TREE_CODE_CLASS (code) != tcc_comparison)
5386     return NULL_TREE;
5387
5388   if (rhs_code == truthop_code)
5389     {
5390       tree newrhs = merge_truthop_with_opposite_arm (loc, rhs, cmpop, rhs_only);
5391       if (newrhs != NULL_TREE)
5392         {
5393           rhs = newrhs;
5394           rhs_code = TREE_CODE (rhs);
5395         }
5396     }
5397   if (lhs_code == truthop_code && !rhs_only)
5398     {
5399       tree newlhs = merge_truthop_with_opposite_arm (loc, lhs, cmpop, false);
5400       if (newlhs != NULL_TREE)
5401         {
5402           lhs = newlhs;
5403           lhs_code = TREE_CODE (lhs);
5404         }
5405     }
5406
5407   inv_code = invert_tree_comparison (code, HONOR_NANS (type));
5408   if (inv_code == rhs_code
5409       && operand_equal_p (TREE_OPERAND (rhs, 0), TREE_OPERAND (cmpop, 0), 0)
5410       && operand_equal_p (TREE_OPERAND (rhs, 1), TREE_OPERAND (cmpop, 1), 0))
5411     return lhs;
5412   if (!rhs_only && inv_code == lhs_code
5413       && operand_equal_p (TREE_OPERAND (lhs, 0), TREE_OPERAND (cmpop, 0), 0)
5414       && operand_equal_p (TREE_OPERAND (lhs, 1), TREE_OPERAND (cmpop, 1), 0))
5415     return rhs;
5416   if (rhs != orig_rhs || lhs != orig_lhs)
5417     return fold_build2_loc (loc, truthop_code, TREE_TYPE (cmpop),
5418                             lhs, rhs);
5419   return NULL_TREE;
5420 }
5421
5422 /* Find ways of folding logical expressions of LHS and RHS:
5423    Try to merge two comparisons to the same innermost item.
5424    Look for range tests like "ch >= '0' && ch <= '9'".
5425    Look for combinations of simple terms on machines with expensive branches
5426    and evaluate the RHS unconditionally.
5427
5428    For example, if we have p->a == 2 && p->b == 4 and we can make an
5429    object large enough to span both A and B, we can do this with a comparison
5430    against the object ANDed with the a mask.
5431
5432    If we have p->a == q->a && p->b == q->b, we may be able to use bit masking
5433    operations to do this with one comparison.
5434
5435    We check for both normal comparisons and the BIT_AND_EXPRs made this by
5436    function and the one above.
5437
5438    CODE is the logical operation being done.  It can be TRUTH_ANDIF_EXPR,
5439    TRUTH_AND_EXPR, TRUTH_ORIF_EXPR, or TRUTH_OR_EXPR.
5440
5441    TRUTH_TYPE is the type of the logical operand and LHS and RHS are its
5442    two operands.
5443
5444    We return the simplified tree or 0 if no optimization is possible.  */
5445
5446 static tree
5447 fold_truth_andor_1 (location_t loc, enum tree_code code, tree truth_type,
5448                     tree lhs, tree rhs)
5449 {
5450   /* If this is the "or" of two comparisons, we can do something if
5451      the comparisons are NE_EXPR.  If this is the "and", we can do something
5452      if the comparisons are EQ_EXPR.  I.e.,
5453         (a->b == 2 && a->c == 4) can become (a->new == NEW).
5454
5455      WANTED_CODE is this operation code.  For single bit fields, we can
5456      convert EQ_EXPR to NE_EXPR so we need not reject the "wrong"
5457      comparison for one-bit fields.  */
5458
5459   enum tree_code wanted_code;
5460   enum tree_code lcode, rcode;
5461   tree ll_arg, lr_arg, rl_arg, rr_arg;
5462   tree ll_inner, lr_inner, rl_inner, rr_inner;
5463   HOST_WIDE_INT ll_bitsize, ll_bitpos, lr_bitsize, lr_bitpos;
5464   HOST_WIDE_INT rl_bitsize, rl_bitpos, rr_bitsize, rr_bitpos;
5465   HOST_WIDE_INT xll_bitpos, xlr_bitpos, xrl_bitpos, xrr_bitpos;
5466   HOST_WIDE_INT lnbitsize, lnbitpos, rnbitsize, rnbitpos;
5467   int ll_unsignedp, lr_unsignedp, rl_unsignedp, rr_unsignedp;
5468   machine_mode ll_mode, lr_mode, rl_mode, rr_mode;
5469   machine_mode lnmode, rnmode;
5470   tree ll_mask, lr_mask, rl_mask, rr_mask;
5471   tree ll_and_mask, lr_and_mask, rl_and_mask, rr_and_mask;
5472   tree l_const, r_const;
5473   tree lntype, rntype, result;
5474   HOST_WIDE_INT first_bit, end_bit;
5475   int volatilep;
5476
5477   /* Start by getting the comparison codes.  Fail if anything is volatile.
5478      If one operand is a BIT_AND_EXPR with the constant one, treat it as if
5479      it were surrounded with a NE_EXPR.  */
5480
5481   if (TREE_SIDE_EFFECTS (lhs) || TREE_SIDE_EFFECTS (rhs))
5482     return 0;
5483
5484   lcode = TREE_CODE (lhs);
5485   rcode = TREE_CODE (rhs);
5486
5487   if (lcode == BIT_AND_EXPR && integer_onep (TREE_OPERAND (lhs, 1)))
5488     {
5489       lhs = build2 (NE_EXPR, truth_type, lhs,
5490                     build_int_cst (TREE_TYPE (lhs), 0));
5491       lcode = NE_EXPR;
5492     }
5493
5494   if (rcode == BIT_AND_EXPR && integer_onep (TREE_OPERAND (rhs, 1)))
5495     {
5496       rhs = build2 (NE_EXPR, truth_type, rhs,
5497                     build_int_cst (TREE_TYPE (rhs), 0));
5498       rcode = NE_EXPR;
5499     }
5500
5501   if (TREE_CODE_CLASS (lcode) != tcc_comparison
5502       || TREE_CODE_CLASS (rcode) != tcc_comparison)
5503     return 0;
5504
5505   ll_arg = TREE_OPERAND (lhs, 0);
5506   lr_arg = TREE_OPERAND (lhs, 1);
5507   rl_arg = TREE_OPERAND (rhs, 0);
5508   rr_arg = TREE_OPERAND (rhs, 1);
5509
5510   /* Simplify (x<y) && (x==y) into (x<=y) and related optimizations.  */
5511   if (simple_operand_p (ll_arg)
5512       && simple_operand_p (lr_arg))
5513     {
5514       if (operand_equal_p (ll_arg, rl_arg, 0)
5515           && operand_equal_p (lr_arg, rr_arg, 0))
5516         {
5517           result = combine_comparisons (loc, code, lcode, rcode,
5518                                         truth_type, ll_arg, lr_arg);
5519           if (result)
5520             return result;
5521         }
5522       else if (operand_equal_p (ll_arg, rr_arg, 0)
5523                && operand_equal_p (lr_arg, rl_arg, 0))
5524         {
5525           result = combine_comparisons (loc, code, lcode,
5526                                         swap_tree_comparison (rcode),
5527                                         truth_type, ll_arg, lr_arg);
5528           if (result)
5529             return result;
5530         }
5531     }
5532
5533   code = ((code == TRUTH_AND_EXPR || code == TRUTH_ANDIF_EXPR)
5534           ? TRUTH_AND_EXPR : TRUTH_OR_EXPR);
5535
5536   /* If the RHS can be evaluated unconditionally and its operands are
5537      simple, it wins to evaluate the RHS unconditionally on machines
5538      with expensive branches.  In this case, this isn't a comparison
5539      that can be merged.  */
5540
5541   if (BRANCH_COST (optimize_function_for_speed_p (cfun),
5542                    false) >= 2
5543       && ! FLOAT_TYPE_P (TREE_TYPE (rl_arg))
5544       && simple_operand_p (rl_arg)
5545       && simple_operand_p (rr_arg))
5546     {
5547       /* Convert (a != 0) || (b != 0) into (a | b) != 0.  */
5548       if (code == TRUTH_OR_EXPR
5549           && lcode == NE_EXPR && integer_zerop (lr_arg)
5550           && rcode == NE_EXPR && integer_zerop (rr_arg)
5551           && TREE_TYPE (ll_arg) == TREE_TYPE (rl_arg)
5552           && INTEGRAL_TYPE_P (TREE_TYPE (ll_arg)))
5553         return build2_loc (loc, NE_EXPR, truth_type,
5554                            build2 (BIT_IOR_EXPR, TREE_TYPE (ll_arg),
5555                                    ll_arg, rl_arg),
5556                            build_int_cst (TREE_TYPE (ll_arg), 0));
5557
5558       /* Convert (a == 0) && (b == 0) into (a | b) == 0.  */
5559       if (code == TRUTH_AND_EXPR
5560           && lcode == EQ_EXPR && integer_zerop (lr_arg)
5561           && rcode == EQ_EXPR && integer_zerop (rr_arg)
5562           && TREE_TYPE (ll_arg) == TREE_TYPE (rl_arg)
5563           && INTEGRAL_TYPE_P (TREE_TYPE (ll_arg)))
5564         return build2_loc (loc, EQ_EXPR, truth_type,
5565                            build2 (BIT_IOR_EXPR, TREE_TYPE (ll_arg),
5566                                    ll_arg, rl_arg),
5567                            build_int_cst (TREE_TYPE (ll_arg), 0));
5568     }
5569
5570   /* See if the comparisons can be merged.  Then get all the parameters for
5571      each side.  */
5572
5573   if ((lcode != EQ_EXPR && lcode != NE_EXPR)
5574       || (rcode != EQ_EXPR && rcode != NE_EXPR))
5575     return 0;
5576
5577   volatilep = 0;
5578   ll_inner = decode_field_reference (loc, ll_arg,
5579                                      &ll_bitsize, &ll_bitpos, &ll_mode,
5580                                      &ll_unsignedp, &volatilep, &ll_mask,
5581                                      &ll_and_mask);
5582   lr_inner = decode_field_reference (loc, lr_arg,
5583                                      &lr_bitsize, &lr_bitpos, &lr_mode,
5584                                      &lr_unsignedp, &volatilep, &lr_mask,
5585                                      &lr_and_mask);
5586   rl_inner = decode_field_reference (loc, rl_arg,
5587                                      &rl_bitsize, &rl_bitpos, &rl_mode,
5588                                      &rl_unsignedp, &volatilep, &rl_mask,
5589                                      &rl_and_mask);
5590   rr_inner = decode_field_reference (loc, rr_arg,
5591                                      &rr_bitsize, &rr_bitpos, &rr_mode,
5592                                      &rr_unsignedp, &volatilep, &rr_mask,
5593                                      &rr_and_mask);
5594
5595   /* It must be true that the inner operation on the lhs of each
5596      comparison must be the same if we are to be able to do anything.
5597      Then see if we have constants.  If not, the same must be true for
5598      the rhs's.  */
5599   if (volatilep || ll_inner == 0 || rl_inner == 0
5600       || ! operand_equal_p (ll_inner, rl_inner, 0))
5601     return 0;
5602
5603   if (TREE_CODE (lr_arg) == INTEGER_CST
5604       && TREE_CODE (rr_arg) == INTEGER_CST)
5605     l_const = lr_arg, r_const = rr_arg;
5606   else if (lr_inner == 0 || rr_inner == 0
5607            || ! operand_equal_p (lr_inner, rr_inner, 0))
5608     return 0;
5609   else
5610     l_const = r_const = 0;
5611
5612   /* If either comparison code is not correct for our logical operation,
5613      fail.  However, we can convert a one-bit comparison against zero into
5614      the opposite comparison against that bit being set in the field.  */
5615
5616   wanted_code = (code == TRUTH_AND_EXPR ? EQ_EXPR : NE_EXPR);
5617   if (lcode != wanted_code)
5618     {
5619       if (l_const && integer_zerop (l_const) && integer_pow2p (ll_mask))
5620         {
5621           /* Make the left operand unsigned, since we are only interested
5622              in the value of one bit.  Otherwise we are doing the wrong
5623              thing below.  */
5624           ll_unsignedp = 1;
5625           l_const = ll_mask;
5626         }
5627       else
5628         return 0;
5629     }
5630
5631   /* This is analogous to the code for l_const above.  */
5632   if (rcode != wanted_code)
5633     {
5634       if (r_const && integer_zerop (r_const) && integer_pow2p (rl_mask))
5635         {
5636           rl_unsignedp = 1;
5637           r_const = rl_mask;
5638         }
5639       else
5640         return 0;
5641     }
5642
5643   /* See if we can find a mode that contains both fields being compared on
5644      the left.  If we can't, fail.  Otherwise, update all constants and masks
5645      to be relative to a field of that size.  */
5646   first_bit = MIN (ll_bitpos, rl_bitpos);
5647   end_bit = MAX (ll_bitpos + ll_bitsize, rl_bitpos + rl_bitsize);
5648   lnmode = get_best_mode (end_bit - first_bit, first_bit, 0, 0,
5649                           TYPE_ALIGN (TREE_TYPE (ll_inner)), word_mode,
5650                           volatilep);
5651   if (lnmode == VOIDmode)
5652     return 0;
5653
5654   lnbitsize = GET_MODE_BITSIZE (lnmode);
5655   lnbitpos = first_bit & ~ (lnbitsize - 1);
5656   lntype = lang_hooks.types.type_for_size (lnbitsize, 1);
5657   xll_bitpos = ll_bitpos - lnbitpos, xrl_bitpos = rl_bitpos - lnbitpos;
5658
5659   if (BYTES_BIG_ENDIAN)
5660     {
5661       xll_bitpos = lnbitsize - xll_bitpos - ll_bitsize;
5662       xrl_bitpos = lnbitsize - xrl_bitpos - rl_bitsize;
5663     }
5664
5665   ll_mask = const_binop (LSHIFT_EXPR, fold_convert_loc (loc, lntype, ll_mask),
5666                          size_int (xll_bitpos));
5667   rl_mask = const_binop (LSHIFT_EXPR, fold_convert_loc (loc, lntype, rl_mask),
5668                          size_int (xrl_bitpos));
5669
5670   if (l_const)
5671     {
5672       l_const = fold_convert_loc (loc, lntype, l_const);
5673       l_const = unextend (l_const, ll_bitsize, ll_unsignedp, ll_and_mask);
5674       l_const = const_binop (LSHIFT_EXPR, l_const, size_int (xll_bitpos));
5675       if (! integer_zerop (const_binop (BIT_AND_EXPR, l_const,
5676                                         fold_build1_loc (loc, BIT_NOT_EXPR,
5677                                                      lntype, ll_mask))))
5678         {
5679           warning (0, "comparison is always %d", wanted_code == NE_EXPR);
5680
5681           return constant_boolean_node (wanted_code == NE_EXPR, truth_type);
5682         }
5683     }
5684   if (r_const)
5685     {
5686       r_const = fold_convert_loc (loc, lntype, r_const);
5687       r_const = unextend (r_const, rl_bitsize, rl_unsignedp, rl_and_mask);
5688       r_const = const_binop (LSHIFT_EXPR, r_const, size_int (xrl_bitpos));
5689       if (! integer_zerop (const_binop (BIT_AND_EXPR, r_const,
5690                                         fold_build1_loc (loc, BIT_NOT_EXPR,
5691                                                      lntype, rl_mask))))
5692         {
5693           warning (0, "comparison is always %d", wanted_code == NE_EXPR);
5694
5695           return constant_boolean_node (wanted_code == NE_EXPR, truth_type);
5696         }
5697     }
5698
5699   /* If the right sides are not constant, do the same for it.  Also,
5700      disallow this optimization if a size or signedness mismatch occurs
5701      between the left and right sides.  */
5702   if (l_const == 0)
5703     {
5704       if (ll_bitsize != lr_bitsize || rl_bitsize != rr_bitsize
5705           || ll_unsignedp != lr_unsignedp || rl_unsignedp != rr_unsignedp
5706           /* Make sure the two fields on the right
5707              correspond to the left without being swapped.  */
5708           || ll_bitpos - rl_bitpos != lr_bitpos - rr_bitpos)
5709         return 0;
5710
5711       first_bit = MIN (lr_bitpos, rr_bitpos);
5712       end_bit = MAX (lr_bitpos + lr_bitsize, rr_bitpos + rr_bitsize);
5713       rnmode = get_best_mode (end_bit - first_bit, first_bit, 0, 0,
5714                               TYPE_ALIGN (TREE_TYPE (lr_inner)), word_mode,
5715                               volatilep);
5716       if (rnmode == VOIDmode)
5717         return 0;
5718
5719       rnbitsize = GET_MODE_BITSIZE (rnmode);
5720       rnbitpos = first_bit & ~ (rnbitsize - 1);
5721       rntype = lang_hooks.types.type_for_size (rnbitsize, 1);
5722       xlr_bitpos = lr_bitpos - rnbitpos, xrr_bitpos = rr_bitpos - rnbitpos;
5723
5724       if (BYTES_BIG_ENDIAN)
5725         {
5726           xlr_bitpos = rnbitsize - xlr_bitpos - lr_bitsize;
5727           xrr_bitpos = rnbitsize - xrr_bitpos - rr_bitsize;
5728         }
5729
5730       lr_mask = const_binop (LSHIFT_EXPR, fold_convert_loc (loc,
5731                                                             rntype, lr_mask),
5732                              size_int (xlr_bitpos));
5733       rr_mask = const_binop (LSHIFT_EXPR, fold_convert_loc (loc,
5734                                                             rntype, rr_mask),
5735                              size_int (xrr_bitpos));
5736
5737       /* Make a mask that corresponds to both fields being compared.
5738          Do this for both items being compared.  If the operands are the
5739          same size and the bits being compared are in the same position
5740          then we can do this by masking both and comparing the masked
5741          results.  */
5742       ll_mask = const_binop (BIT_IOR_EXPR, ll_mask, rl_mask);
5743       lr_mask = const_binop (BIT_IOR_EXPR, lr_mask, rr_mask);
5744       if (lnbitsize == rnbitsize && xll_bitpos == xlr_bitpos)
5745         {
5746           lhs = make_bit_field_ref (loc, ll_inner, lntype, lnbitsize, lnbitpos,
5747                                     ll_unsignedp || rl_unsignedp);
5748           if (! all_ones_mask_p (ll_mask, lnbitsize))
5749             lhs = build2 (BIT_AND_EXPR, lntype, lhs, ll_mask);
5750
5751           rhs = make_bit_field_ref (loc, lr_inner, rntype, rnbitsize, rnbitpos,
5752                                     lr_unsignedp || rr_unsignedp);
5753           if (! all_ones_mask_p (lr_mask, rnbitsize))
5754             rhs = build2 (BIT_AND_EXPR, rntype, rhs, lr_mask);
5755
5756           return build2_loc (loc, wanted_code, truth_type, lhs, rhs);
5757         }
5758
5759       /* There is still another way we can do something:  If both pairs of
5760          fields being compared are adjacent, we may be able to make a wider
5761          field containing them both.
5762
5763          Note that we still must mask the lhs/rhs expressions.  Furthermore,
5764          the mask must be shifted to account for the shift done by
5765          make_bit_field_ref.  */
5766       if ((ll_bitsize + ll_bitpos == rl_bitpos
5767            && lr_bitsize + lr_bitpos == rr_bitpos)
5768           || (ll_bitpos == rl_bitpos + rl_bitsize
5769               && lr_bitpos == rr_bitpos + rr_bitsize))
5770         {
5771           tree type;
5772
5773           lhs = make_bit_field_ref (loc, ll_inner, lntype,
5774                                     ll_bitsize + rl_bitsize,
5775                                     MIN (ll_bitpos, rl_bitpos), ll_unsignedp);
5776           rhs = make_bit_field_ref (loc, lr_inner, rntype,
5777                                     lr_bitsize + rr_bitsize,
5778                                     MIN (lr_bitpos, rr_bitpos), lr_unsignedp);
5779
5780           ll_mask = const_binop (RSHIFT_EXPR, ll_mask,
5781                                  size_int (MIN (xll_bitpos, xrl_bitpos)));
5782           lr_mask = const_binop (RSHIFT_EXPR, lr_mask,
5783                                  size_int (MIN (xlr_bitpos, xrr_bitpos)));
5784
5785           /* Convert to the smaller type before masking out unwanted bits.  */
5786           type = lntype;
5787           if (lntype != rntype)
5788             {
5789               if (lnbitsize > rnbitsize)
5790                 {
5791                   lhs = fold_convert_loc (loc, rntype, lhs);
5792                   ll_mask = fold_convert_loc (loc, rntype, ll_mask);
5793                   type = rntype;
5794                 }
5795               else if (lnbitsize < rnbitsize)
5796                 {
5797                   rhs = fold_convert_loc (loc, lntype, rhs);
5798                   lr_mask = fold_convert_loc (loc, lntype, lr_mask);
5799                   type = lntype;
5800                 }
5801             }
5802
5803           if (! all_ones_mask_p (ll_mask, ll_bitsize + rl_bitsize))
5804             lhs = build2 (BIT_AND_EXPR, type, lhs, ll_mask);
5805
5806           if (! all_ones_mask_p (lr_mask, lr_bitsize + rr_bitsize))
5807             rhs = build2 (BIT_AND_EXPR, type, rhs, lr_mask);
5808
5809           return build2_loc (loc, wanted_code, truth_type, lhs, rhs);
5810         }
5811
5812       return 0;
5813     }
5814
5815   /* Handle the case of comparisons with constants.  If there is something in
5816      common between the masks, those bits of the constants must be the same.
5817      If not, the condition is always false.  Test for this to avoid generating
5818      incorrect code below.  */
5819   result = const_binop (BIT_AND_EXPR, ll_mask, rl_mask);
5820   if (! integer_zerop (result)
5821       && simple_cst_equal (const_binop (BIT_AND_EXPR, result, l_const),
5822                            const_binop (BIT_AND_EXPR, result, r_const)) != 1)
5823     {
5824       if (wanted_code == NE_EXPR)
5825         {
5826           warning (0, "%<or%> of unmatched not-equal tests is always 1");
5827           return constant_boolean_node (true, truth_type);
5828         }
5829       else
5830         {
5831           warning (0, "%<and%> of mutually exclusive equal-tests is always 0");
5832           return constant_boolean_node (false, truth_type);
5833         }
5834     }
5835
5836   /* Construct the expression we will return.  First get the component
5837      reference we will make.  Unless the mask is all ones the width of
5838      that field, perform the mask operation.  Then compare with the
5839      merged constant.  */
5840   result = make_bit_field_ref (loc, ll_inner, lntype, lnbitsize, lnbitpos,
5841                                ll_unsignedp || rl_unsignedp);
5842
5843   ll_mask = const_binop (BIT_IOR_EXPR, ll_mask, rl_mask);
5844   if (! all_ones_mask_p (ll_mask, lnbitsize))
5845     result = build2_loc (loc, BIT_AND_EXPR, lntype, result, ll_mask);
5846
5847   return build2_loc (loc, wanted_code, truth_type, result,
5848                      const_binop (BIT_IOR_EXPR, l_const, r_const));
5849 }
5850 \f
5851 /* Optimize T, which is a comparison of a MIN_EXPR or MAX_EXPR with a
5852    constant.  */
5853
5854 static tree
5855 optimize_minmax_comparison (location_t loc, enum tree_code code, tree type,
5856                             tree op0, tree op1)
5857 {
5858   tree arg0 = op0;
5859   enum tree_code op_code;
5860   tree comp_const;
5861   tree minmax_const;
5862   int consts_equal, consts_lt;
5863   tree inner;
5864
5865   STRIP_SIGN_NOPS (arg0);
5866
5867   op_code = TREE_CODE (arg0);
5868   minmax_const = TREE_OPERAND (arg0, 1);
5869   comp_const = fold_convert_loc (loc, TREE_TYPE (arg0), op1);
5870   consts_equal = tree_int_cst_equal (minmax_const, comp_const);
5871   consts_lt = tree_int_cst_lt (minmax_const, comp_const);
5872   inner = TREE_OPERAND (arg0, 0);
5873
5874   /* If something does not permit us to optimize, return the original tree.  */
5875   if ((op_code != MIN_EXPR && op_code != MAX_EXPR)
5876       || TREE_CODE (comp_const) != INTEGER_CST
5877       || TREE_OVERFLOW (comp_const)
5878       || TREE_CODE (minmax_const) != INTEGER_CST
5879       || TREE_OVERFLOW (minmax_const))
5880     return NULL_TREE;
5881
5882   /* Now handle all the various comparison codes.  We only handle EQ_EXPR
5883      and GT_EXPR, doing the rest with recursive calls using logical
5884      simplifications.  */
5885   switch (code)
5886     {
5887     case NE_EXPR:  case LT_EXPR:  case LE_EXPR:
5888       {
5889         tree tem
5890           = optimize_minmax_comparison (loc,
5891                                         invert_tree_comparison (code, false),
5892                                         type, op0, op1);
5893         if (tem)
5894           return invert_truthvalue_loc (loc, tem);
5895         return NULL_TREE;
5896       }
5897
5898     case GE_EXPR:
5899       return
5900         fold_build2_loc (loc, TRUTH_ORIF_EXPR, type,
5901                      optimize_minmax_comparison
5902                      (loc, EQ_EXPR, type, arg0, comp_const),
5903                      optimize_minmax_comparison
5904                      (loc, GT_EXPR, type, arg0, comp_const));
5905
5906     case EQ_EXPR:
5907       if (op_code == MAX_EXPR && consts_equal)
5908         /* MAX (X, 0) == 0  ->  X <= 0  */
5909         return fold_build2_loc (loc, LE_EXPR, type, inner, comp_const);
5910
5911       else if (op_code == MAX_EXPR && consts_lt)
5912         /* MAX (X, 0) == 5  ->  X == 5   */
5913         return fold_build2_loc (loc, EQ_EXPR, type, inner, comp_const);
5914
5915       else if (op_code == MAX_EXPR)
5916         /* MAX (X, 0) == -1  ->  false  */
5917         return omit_one_operand_loc (loc, type, integer_zero_node, inner);
5918
5919       else if (consts_equal)
5920         /* MIN (X, 0) == 0  ->  X >= 0  */
5921         return fold_build2_loc (loc, GE_EXPR, type, inner, comp_const);
5922
5923       else if (consts_lt)
5924         /* MIN (X, 0) == 5  ->  false  */
5925         return omit_one_operand_loc (loc, type, integer_zero_node, inner);
5926
5927       else
5928         /* MIN (X, 0) == -1  ->  X == -1  */
5929         return fold_build2_loc (loc, EQ_EXPR, type, inner, comp_const);
5930
5931     case GT_EXPR:
5932       if (op_code == MAX_EXPR && (consts_equal || consts_lt))
5933         /* MAX (X, 0) > 0  ->  X > 0
5934            MAX (X, 0) > 5  ->  X > 5  */
5935         return fold_build2_loc (loc, GT_EXPR, type, inner, comp_const);
5936
5937       else if (op_code == MAX_EXPR)
5938         /* MAX (X, 0) > -1  ->  true  */
5939         return omit_one_operand_loc (loc, type, integer_one_node, inner);
5940
5941       else if (op_code == MIN_EXPR && (consts_equal || consts_lt))
5942         /* MIN (X, 0) > 0  ->  false
5943            MIN (X, 0) > 5  ->  false  */
5944         return omit_one_operand_loc (loc, type, integer_zero_node, inner);
5945
5946       else
5947         /* MIN (X, 0) > -1  ->  X > -1  */
5948         return fold_build2_loc (loc, GT_EXPR, type, inner, comp_const);
5949
5950     default:
5951       return NULL_TREE;
5952     }
5953 }
5954 \f
5955 /* T is an integer expression that is being multiplied, divided, or taken a
5956    modulus (CODE says which and what kind of divide or modulus) by a
5957    constant C.  See if we can eliminate that operation by folding it with
5958    other operations already in T.  WIDE_TYPE, if non-null, is a type that
5959    should be used for the computation if wider than our type.
5960
5961    For example, if we are dividing (X * 8) + (Y * 16) by 4, we can return
5962    (X * 2) + (Y * 4).  We must, however, be assured that either the original
5963    expression would not overflow or that overflow is undefined for the type
5964    in the language in question.
5965
5966    If we return a non-null expression, it is an equivalent form of the
5967    original computation, but need not be in the original type.
5968
5969    We set *STRICT_OVERFLOW_P to true if the return values depends on
5970    signed overflow being undefined.  Otherwise we do not change
5971    *STRICT_OVERFLOW_P.  */
5972
5973 static tree
5974 extract_muldiv (tree t, tree c, enum tree_code code, tree wide_type,
5975                 bool *strict_overflow_p)
5976 {
5977   /* To avoid exponential search depth, refuse to allow recursion past
5978      three levels.  Beyond that (1) it's highly unlikely that we'll find
5979      something interesting and (2) we've probably processed it before
5980      when we built the inner expression.  */
5981
5982   static int depth;
5983   tree ret;
5984
5985   if (depth > 3)
5986     return NULL;
5987
5988   depth++;
5989   ret = extract_muldiv_1 (t, c, code, wide_type, strict_overflow_p);
5990   depth--;
5991
5992   return ret;
5993 }
5994
5995 static tree
5996 extract_muldiv_1 (tree t, tree c, enum tree_code code, tree wide_type,
5997                   bool *strict_overflow_p)
5998 {
5999   tree type = TREE_TYPE (t);
6000   enum tree_code tcode = TREE_CODE (t);
6001   tree ctype = (wide_type != 0 && (GET_MODE_SIZE (TYPE_MODE (wide_type))
6002                                    > GET_MODE_SIZE (TYPE_MODE (type)))
6003                 ? wide_type : type);
6004   tree t1, t2;
6005   int same_p = tcode == code;
6006   tree op0 = NULL_TREE, op1 = NULL_TREE;
6007   bool sub_strict_overflow_p;
6008
6009   /* Don't deal with constants of zero here; they confuse the code below.  */
6010   if (integer_zerop (c))
6011     return NULL_TREE;
6012
6013   if (TREE_CODE_CLASS (tcode) == tcc_unary)
6014     op0 = TREE_OPERAND (t, 0);
6015
6016   if (TREE_CODE_CLASS (tcode) == tcc_binary)
6017     op0 = TREE_OPERAND (t, 0), op1 = TREE_OPERAND (t, 1);
6018
6019   /* Note that we need not handle conditional operations here since fold
6020      already handles those cases.  So just do arithmetic here.  */
6021   switch (tcode)
6022     {
6023     case INTEGER_CST:
6024       /* For a constant, we can always simplify if we are a multiply
6025          or (for divide and modulus) if it is a multiple of our constant.  */
6026       if (code == MULT_EXPR
6027           || wi::multiple_of_p (t, c, TYPE_SIGN (type)))
6028         return const_binop (code, fold_convert (ctype, t),
6029                             fold_convert (ctype, c));
6030       break;
6031
6032     CASE_CONVERT: case NON_LVALUE_EXPR:
6033       /* If op0 is an expression ...  */
6034       if ((COMPARISON_CLASS_P (op0)
6035            || UNARY_CLASS_P (op0)
6036            || BINARY_CLASS_P (op0)
6037            || VL_EXP_CLASS_P (op0)
6038            || EXPRESSION_CLASS_P (op0))
6039           /* ... and has wrapping overflow, and its type is smaller
6040              than ctype, then we cannot pass through as widening.  */
6041           && (((ANY_INTEGRAL_TYPE_P (TREE_TYPE (op0))
6042                 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
6043                && (TYPE_PRECISION (ctype)
6044                    > TYPE_PRECISION (TREE_TYPE (op0))))
6045               /* ... or this is a truncation (t is narrower than op0),
6046                  then we cannot pass through this narrowing.  */
6047               || (TYPE_PRECISION (type)
6048                   < TYPE_PRECISION (TREE_TYPE (op0)))
6049               /* ... or signedness changes for division or modulus,
6050                  then we cannot pass through this conversion.  */
6051               || (code != MULT_EXPR
6052                   && (TYPE_UNSIGNED (ctype)
6053                       != TYPE_UNSIGNED (TREE_TYPE (op0))))
6054               /* ... or has undefined overflow while the converted to
6055                  type has not, we cannot do the operation in the inner type
6056                  as that would introduce undefined overflow.  */
6057               || ((ANY_INTEGRAL_TYPE_P (TREE_TYPE (op0))
6058                    && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (op0)))
6059                   && !TYPE_OVERFLOW_UNDEFINED (type))))
6060         break;
6061
6062       /* Pass the constant down and see if we can make a simplification.  If
6063          we can, replace this expression with the inner simplification for
6064          possible later conversion to our or some other type.  */
6065       if ((t2 = fold_convert (TREE_TYPE (op0), c)) != 0
6066           && TREE_CODE (t2) == INTEGER_CST
6067           && !TREE_OVERFLOW (t2)
6068           && (0 != (t1 = extract_muldiv (op0, t2, code,
6069                                          code == MULT_EXPR
6070                                          ? ctype : NULL_TREE,
6071                                          strict_overflow_p))))
6072         return t1;
6073       break;
6074
6075     case ABS_EXPR:
6076       /* If widening the type changes it from signed to unsigned, then we
6077          must avoid building ABS_EXPR itself as unsigned.  */
6078       if (TYPE_UNSIGNED (ctype) && !TYPE_UNSIGNED (type))
6079         {
6080           tree cstype = (*signed_type_for) (ctype);
6081           if ((t1 = extract_muldiv (op0, c, code, cstype, strict_overflow_p))
6082               != 0)
6083             {
6084               t1 = fold_build1 (tcode, cstype, fold_convert (cstype, t1));
6085               return fold_convert (ctype, t1);
6086             }
6087           break;
6088         }
6089       /* If the constant is negative, we cannot simplify this.  */
6090       if (tree_int_cst_sgn (c) == -1)
6091         break;
6092       /* FALLTHROUGH */
6093     case NEGATE_EXPR:
6094       /* For division and modulus, type can't be unsigned, as e.g.
6095          (-(x / 2U)) / 2U isn't equal to -((x / 2U) / 2U) for x >= 2.
6096          For signed types, even with wrapping overflow, this is fine.  */
6097       if (code != MULT_EXPR && TYPE_UNSIGNED (type))
6098         break;
6099       if ((t1 = extract_muldiv (op0, c, code, wide_type, strict_overflow_p))
6100           != 0)
6101         return fold_build1 (tcode, ctype, fold_convert (ctype, t1));
6102       break;
6103
6104     case MIN_EXPR:  case MAX_EXPR:
6105       /* If widening the type changes the signedness, then we can't perform
6106          this optimization as that changes the result.  */
6107       if (TYPE_UNSIGNED (ctype) != TYPE_UNSIGNED (type))
6108         break;
6109
6110       /* MIN (a, b) / 5 -> MIN (a / 5, b / 5)  */
6111       sub_strict_overflow_p = false;
6112       if ((t1 = extract_muldiv (op0, c, code, wide_type,
6113                                 &sub_strict_overflow_p)) != 0
6114           && (t2 = extract_muldiv (op1, c, code, wide_type,
6115                                    &sub_strict_overflow_p)) != 0)
6116         {
6117           if (tree_int_cst_sgn (c) < 0)
6118             tcode = (tcode == MIN_EXPR ? MAX_EXPR : MIN_EXPR);
6119           if (sub_strict_overflow_p)
6120             *strict_overflow_p = true;
6121           return fold_build2 (tcode, ctype, fold_convert (ctype, t1),
6122                               fold_convert (ctype, t2));
6123         }
6124       break;
6125
6126     case LSHIFT_EXPR:  case RSHIFT_EXPR:
6127       /* If the second operand is constant, this is a multiplication
6128          or floor division, by a power of two, so we can treat it that
6129          way unless the multiplier or divisor overflows.  Signed
6130          left-shift overflow is implementation-defined rather than
6131          undefined in C90, so do not convert signed left shift into
6132          multiplication.  */
6133       if (TREE_CODE (op1) == INTEGER_CST
6134           && (tcode == RSHIFT_EXPR || TYPE_UNSIGNED (TREE_TYPE (op0)))
6135           /* const_binop may not detect overflow correctly,
6136              so check for it explicitly here.  */
6137           && wi::gtu_p (TYPE_PRECISION (TREE_TYPE (size_one_node)), op1)
6138           && 0 != (t1 = fold_convert (ctype,
6139                                       const_binop (LSHIFT_EXPR,
6140                                                    size_one_node,
6141                                                    op1)))
6142           && !TREE_OVERFLOW (t1))
6143         return extract_muldiv (build2 (tcode == LSHIFT_EXPR
6144                                        ? MULT_EXPR : FLOOR_DIV_EXPR,
6145                                        ctype,
6146                                        fold_convert (ctype, op0),
6147                                        t1),
6148                                c, code, wide_type, strict_overflow_p);
6149       break;
6150
6151     case PLUS_EXPR:  case MINUS_EXPR:
6152       /* See if we can eliminate the operation on both sides.  If we can, we
6153          can return a new PLUS or MINUS.  If we can't, the only remaining
6154          cases where we can do anything are if the second operand is a
6155          constant.  */
6156       sub_strict_overflow_p = false;
6157       t1 = extract_muldiv (op0, c, code, wide_type, &sub_strict_overflow_p);
6158       t2 = extract_muldiv (op1, c, code, wide_type, &sub_strict_overflow_p);
6159       if (t1 != 0 && t2 != 0
6160           && (code == MULT_EXPR
6161               /* If not multiplication, we can only do this if both operands
6162                  are divisible by c.  */
6163               || (multiple_of_p (ctype, op0, c)
6164                   && multiple_of_p (ctype, op1, c))))
6165         {
6166           if (sub_strict_overflow_p)
6167             *strict_overflow_p = true;
6168           return fold_build2 (tcode, ctype, fold_convert (ctype, t1),
6169                               fold_convert (ctype, t2));
6170         }
6171
6172       /* If this was a subtraction, negate OP1 and set it to be an addition.
6173          This simplifies the logic below.  */
6174       if (tcode == MINUS_EXPR)
6175         {
6176           tcode = PLUS_EXPR, op1 = negate_expr (op1);
6177           /* If OP1 was not easily negatable, the constant may be OP0.  */
6178           if (TREE_CODE (op0) == INTEGER_CST)
6179             {
6180               std::swap (op0, op1);
6181               std::swap (t1, t2);
6182             }
6183         }
6184
6185       if (TREE_CODE (op1) != INTEGER_CST)
6186         break;
6187
6188       /* If either OP1 or C are negative, this optimization is not safe for
6189          some of the division and remainder types while for others we need
6190          to change the code.  */
6191       if (tree_int_cst_sgn (op1) < 0 || tree_int_cst_sgn (c) < 0)
6192         {
6193           if (code == CEIL_DIV_EXPR)
6194             code = FLOOR_DIV_EXPR;
6195           else if (code == FLOOR_DIV_EXPR)
6196             code = CEIL_DIV_EXPR;
6197           else if (code != MULT_EXPR
6198                    && code != CEIL_MOD_EXPR && code != FLOOR_MOD_EXPR)
6199             break;
6200         }
6201
6202       /* If it's a multiply or a division/modulus operation of a multiple
6203          of our constant, do the operation and verify it doesn't overflow.  */
6204       if (code == MULT_EXPR
6205           || wi::multiple_of_p (op1, c, TYPE_SIGN (type)))
6206         {
6207           op1 = const_binop (code, fold_convert (ctype, op1),
6208                              fold_convert (ctype, c));
6209           /* We allow the constant to overflow with wrapping semantics.  */
6210           if (op1 == 0
6211               || (TREE_OVERFLOW (op1) && !TYPE_OVERFLOW_WRAPS (ctype)))
6212             break;
6213         }
6214       else
6215         break;
6216
6217       /* If we have an unsigned type, we cannot widen the operation since it
6218          will change the result if the original computation overflowed.  */
6219       if (TYPE_UNSIGNED (ctype) && ctype != type)
6220         break;
6221
6222       /* If we were able to eliminate our operation from the first side,
6223          apply our operation to the second side and reform the PLUS.  */
6224       if (t1 != 0 && (TREE_CODE (t1) != code || code == MULT_EXPR))
6225         return fold_build2 (tcode, ctype, fold_convert (ctype, t1), op1);
6226
6227       /* The last case is if we are a multiply.  In that case, we can
6228          apply the distributive law to commute the multiply and addition
6229          if the multiplication of the constants doesn't overflow
6230          and overflow is defined.  With undefined overflow
6231          op0 * c might overflow, while (op0 + orig_op1) * c doesn't.  */
6232       if (code == MULT_EXPR && TYPE_OVERFLOW_WRAPS (ctype))
6233         return fold_build2 (tcode, ctype,
6234                             fold_build2 (code, ctype,
6235                                          fold_convert (ctype, op0),
6236                                          fold_convert (ctype, c)),
6237                             op1);
6238
6239       break;
6240
6241     case MULT_EXPR:
6242       /* We have a special case here if we are doing something like
6243          (C * 8) % 4 since we know that's zero.  */
6244       if ((code == TRUNC_MOD_EXPR || code == CEIL_MOD_EXPR
6245            || code == FLOOR_MOD_EXPR || code == ROUND_MOD_EXPR)
6246           /* If the multiplication can overflow we cannot optimize this.  */
6247           && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (t))
6248           && TREE_CODE (TREE_OPERAND (t, 1)) == INTEGER_CST
6249           && wi::multiple_of_p (op1, c, TYPE_SIGN (type)))
6250         {
6251           *strict_overflow_p = true;
6252           return omit_one_operand (type, integer_zero_node, op0);
6253         }
6254
6255       /* ... fall through ...  */
6256
6257     case TRUNC_DIV_EXPR:  case CEIL_DIV_EXPR:  case FLOOR_DIV_EXPR:
6258     case ROUND_DIV_EXPR:  case EXACT_DIV_EXPR:
6259       /* If we can extract our operation from the LHS, do so and return a
6260          new operation.  Likewise for the RHS from a MULT_EXPR.  Otherwise,
6261          do something only if the second operand is a constant.  */
6262       if (same_p
6263           && (t1 = extract_muldiv (op0, c, code, wide_type,
6264                                    strict_overflow_p)) != 0)
6265         return fold_build2 (tcode, ctype, fold_convert (ctype, t1),
6266                             fold_convert (ctype, op1));
6267       else if (tcode == MULT_EXPR && code == MULT_EXPR
6268                && (t1 = extract_muldiv (op1, c, code, wide_type,
6269                                         strict_overflow_p)) != 0)
6270         return fold_build2 (tcode, ctype, fold_convert (ctype, op0),
6271                             fold_convert (ctype, t1));
6272       else if (TREE_CODE (op1) != INTEGER_CST)
6273         return 0;
6274
6275       /* If these are the same operation types, we can associate them
6276          assuming no overflow.  */
6277       if (tcode == code)
6278         {
6279           bool overflow_p = false;
6280           bool overflow_mul_p;
6281           signop sign = TYPE_SIGN (ctype);
6282           wide_int mul = wi::mul (op1, c, sign, &overflow_mul_p);
6283           overflow_p = TREE_OVERFLOW (c) | TREE_OVERFLOW (op1);
6284           if (overflow_mul_p
6285               && ((sign == UNSIGNED && tcode != MULT_EXPR) || sign == SIGNED))
6286             overflow_p = true;
6287           if (!overflow_p)
6288             {
6289               mul = wide_int::from (mul, TYPE_PRECISION (ctype),
6290                                     TYPE_SIGN (TREE_TYPE (op1)));
6291               return fold_build2 (tcode, ctype, fold_convert (ctype, op0),
6292                                   wide_int_to_tree (ctype, mul));
6293             }
6294         }
6295
6296       /* If these operations "cancel" each other, we have the main
6297          optimizations of this pass, which occur when either constant is a
6298          multiple of the other, in which case we replace this with either an
6299          operation or CODE or TCODE.
6300
6301          If we have an unsigned type, we cannot do this since it will change
6302          the result if the original computation overflowed.  */
6303       if (TYPE_OVERFLOW_UNDEFINED (ctype)
6304           && ((code == MULT_EXPR && tcode == EXACT_DIV_EXPR)
6305               || (tcode == MULT_EXPR
6306                   && code != TRUNC_MOD_EXPR && code != CEIL_MOD_EXPR
6307                   && code != FLOOR_MOD_EXPR && code != ROUND_MOD_EXPR
6308                   && code != MULT_EXPR)))
6309         {
6310           if (wi::multiple_of_p (op1, c, TYPE_SIGN (type)))
6311             {
6312               if (TYPE_OVERFLOW_UNDEFINED (ctype))
6313                 *strict_overflow_p = true;
6314               return fold_build2 (tcode, ctype, fold_convert (ctype, op0),
6315                                   fold_convert (ctype,
6316                                                 const_binop (TRUNC_DIV_EXPR,
6317                                                              op1, c)));
6318             }
6319           else if (wi::multiple_of_p (c, op1, TYPE_SIGN (type)))
6320             {
6321               if (TYPE_OVERFLOW_UNDEFINED (ctype))
6322                 *strict_overflow_p = true;
6323               return fold_build2 (code, ctype, fold_convert (ctype, op0),
6324                                   fold_convert (ctype,
6325                                                 const_binop (TRUNC_DIV_EXPR,
6326                                                              c, op1)));
6327             }
6328         }
6329       break;
6330
6331     default:
6332       break;
6333     }
6334
6335   return 0;
6336 }
6337 \f
6338 /* Return a node which has the indicated constant VALUE (either 0 or
6339    1 for scalars or {-1,-1,..} or {0,0,...} for vectors),
6340    and is of the indicated TYPE.  */
6341
6342 tree
6343 constant_boolean_node (bool value, tree type)
6344 {
6345   if (type == integer_type_node)
6346     return value ? integer_one_node : integer_zero_node;
6347   else if (type == boolean_type_node)
6348     return value ? boolean_true_node : boolean_false_node;
6349   else if (TREE_CODE (type) == VECTOR_TYPE)
6350     return build_vector_from_val (type,
6351                                   build_int_cst (TREE_TYPE (type),
6352                                                  value ? -1 : 0));
6353   else
6354     return fold_convert (type, value ? integer_one_node : integer_zero_node);
6355 }
6356
6357
6358 /* Transform `a + (b ? x : y)' into `b ? (a + x) : (a + y)'.
6359    Transform, `a + (x < y)' into `(x < y) ? (a + 1) : (a + 0)'.  Here
6360    CODE corresponds to the `+', COND to the `(b ? x : y)' or `(x < y)'
6361    expression, and ARG to `a'.  If COND_FIRST_P is nonzero, then the
6362    COND is the first argument to CODE; otherwise (as in the example
6363    given here), it is the second argument.  TYPE is the type of the
6364    original expression.  Return NULL_TREE if no simplification is
6365    possible.  */
6366
6367 static tree
6368 fold_binary_op_with_conditional_arg (location_t loc,
6369                                      enum tree_code code,
6370                                      tree type, tree op0, tree op1,
6371                                      tree cond, tree arg, int cond_first_p)
6372 {
6373   tree cond_type = cond_first_p ? TREE_TYPE (op0) : TREE_TYPE (op1);
6374   tree arg_type = cond_first_p ? TREE_TYPE (op1) : TREE_TYPE (op0);
6375   tree test, true_value, false_value;
6376   tree lhs = NULL_TREE;
6377   tree rhs = NULL_TREE;
6378   enum tree_code cond_code = COND_EXPR;
6379
6380   if (TREE_CODE (cond) == COND_EXPR
6381       || TREE_CODE (cond) == VEC_COND_EXPR)
6382     {
6383       test = TREE_OPERAND (cond, 0);
6384       true_value = TREE_OPERAND (cond, 1);
6385       false_value = TREE_OPERAND (cond, 2);
6386       /* If this operand throws an expression, then it does not make
6387          sense to try to perform a logical or arithmetic operation
6388          involving it.  */
6389       if (VOID_TYPE_P (TREE_TYPE (true_value)))
6390         lhs = true_value;
6391       if (VOID_TYPE_P (TREE_TYPE (false_value)))
6392         rhs = false_value;
6393     }
6394   else
6395     {
6396       tree testtype = TREE_TYPE (cond);
6397       test = cond;
6398       true_value = constant_boolean_node (true, testtype);
6399       false_value = constant_boolean_node (false, testtype);
6400     }
6401
6402   if (TREE_CODE (TREE_TYPE (test)) == VECTOR_TYPE)
6403     cond_code = VEC_COND_EXPR;
6404
6405   /* This transformation is only worthwhile if we don't have to wrap ARG
6406      in a SAVE_EXPR and the operation can be simplified without recursing
6407      on at least one of the branches once its pushed inside the COND_EXPR.  */
6408   if (!TREE_CONSTANT (arg)
6409       && (TREE_SIDE_EFFECTS (arg)
6410           || TREE_CODE (arg) == COND_EXPR || TREE_CODE (arg) == VEC_COND_EXPR
6411           || TREE_CONSTANT (true_value) || TREE_CONSTANT (false_value)))
6412     return NULL_TREE;
6413
6414   arg = fold_convert_loc (loc, arg_type, arg);
6415   if (lhs == 0)
6416     {
6417       true_value = fold_convert_loc (loc, cond_type, true_value);
6418       if (cond_first_p)
6419         lhs = fold_build2_loc (loc, code, type, true_value, arg);
6420       else
6421         lhs = fold_build2_loc (loc, code, type, arg, true_value);
6422     }
6423   if (rhs == 0)
6424     {
6425       false_value = fold_convert_loc (loc, cond_type, false_value);
6426       if (cond_first_p)
6427         rhs = fold_build2_loc (loc, code, type, false_value, arg);
6428       else
6429         rhs = fold_build2_loc (loc, code, type, arg, false_value);
6430     }
6431
6432   /* Check that we have simplified at least one of the branches.  */
6433   if (!TREE_CONSTANT (arg) && !TREE_CONSTANT (lhs) && !TREE_CONSTANT (rhs))
6434     return NULL_TREE;
6435
6436   return fold_build3_loc (loc, cond_code, type, test, lhs, rhs);
6437 }
6438
6439 \f
6440 /* Subroutine of fold() that checks for the addition of +/- 0.0.
6441
6442    If !NEGATE, return true if ADDEND is +/-0.0 and, for all X of type
6443    TYPE, X + ADDEND is the same as X.  If NEGATE, return true if X -
6444    ADDEND is the same as X.
6445
6446    X + 0 and X - 0 both give X when X is NaN, infinite, or nonzero
6447    and finite.  The problematic cases are when X is zero, and its mode
6448    has signed zeros.  In the case of rounding towards -infinity,
6449    X - 0 is not the same as X because 0 - 0 is -0.  In other rounding
6450    modes, X + 0 is not the same as X because -0 + 0 is 0.  */
6451
6452 bool
6453 fold_real_zero_addition_p (const_tree type, const_tree addend, int negate)
6454 {
6455   if (!real_zerop (addend))
6456     return false;
6457
6458   /* Don't allow the fold with -fsignaling-nans.  */
6459   if (HONOR_SNANS (element_mode (type)))
6460     return false;
6461
6462   /* Allow the fold if zeros aren't signed, or their sign isn't important.  */
6463   if (!HONOR_SIGNED_ZEROS (element_mode (type)))
6464     return true;
6465
6466   /* In a vector or complex, we would need to check the sign of all zeros.  */
6467   if (TREE_CODE (addend) != REAL_CST)
6468     return false;
6469
6470   /* Treat x + -0 as x - 0 and x - -0 as x + 0.  */
6471   if (REAL_VALUE_MINUS_ZERO (TREE_REAL_CST (addend)))
6472     negate = !negate;
6473
6474   /* The mode has signed zeros, and we have to honor their sign.
6475      In this situation, there is only one case we can return true for.
6476      X - 0 is the same as X unless rounding towards -infinity is
6477      supported.  */
6478   return negate && !HONOR_SIGN_DEPENDENT_ROUNDING (element_mode (type));
6479 }
6480
6481 /* Subroutine of fold() that optimizes comparisons of a division by
6482    a nonzero integer constant against an integer constant, i.e.
6483    X/C1 op C2.
6484
6485    CODE is the comparison operator: EQ_EXPR, NE_EXPR, GT_EXPR, LT_EXPR,
6486    GE_EXPR or LE_EXPR.  TYPE is the type of the result and ARG0 and ARG1
6487    are the operands of the comparison.  ARG1 must be a TREE_REAL_CST.
6488
6489    The function returns the constant folded tree if a simplification
6490    can be made, and NULL_TREE otherwise.  */
6491
6492 static tree
6493 fold_div_compare (location_t loc,
6494                   enum tree_code code, tree type, tree arg0, tree arg1)
6495 {
6496   tree prod, tmp, hi, lo;
6497   tree arg00 = TREE_OPERAND (arg0, 0);
6498   tree arg01 = TREE_OPERAND (arg0, 1);
6499   signop sign = TYPE_SIGN (TREE_TYPE (arg0));
6500   bool neg_overflow = false;
6501   bool overflow;
6502
6503   /* We have to do this the hard way to detect unsigned overflow.
6504      prod = int_const_binop (MULT_EXPR, arg01, arg1);  */
6505   wide_int val = wi::mul (arg01, arg1, sign, &overflow);
6506   prod = force_fit_type (TREE_TYPE (arg00), val, -1, overflow);
6507   neg_overflow = false;
6508
6509   if (sign == UNSIGNED)
6510     {
6511       tmp = int_const_binop (MINUS_EXPR, arg01,
6512                              build_int_cst (TREE_TYPE (arg01), 1));
6513       lo = prod;
6514
6515       /* Likewise hi = int_const_binop (PLUS_EXPR, prod, tmp).  */
6516       val = wi::add (prod, tmp, sign, &overflow);
6517       hi = force_fit_type (TREE_TYPE (arg00), val,
6518                            -1, overflow | TREE_OVERFLOW (prod));
6519     }
6520   else if (tree_int_cst_sgn (arg01) >= 0)
6521     {
6522       tmp = int_const_binop (MINUS_EXPR, arg01,
6523                              build_int_cst (TREE_TYPE (arg01), 1));
6524       switch (tree_int_cst_sgn (arg1))
6525         {
6526         case -1:
6527           neg_overflow = true;
6528           lo = int_const_binop (MINUS_EXPR, prod, tmp);
6529           hi = prod;
6530           break;
6531
6532         case  0:
6533           lo = fold_negate_const (tmp, TREE_TYPE (arg0));
6534           hi = tmp;
6535           break;
6536
6537         case  1:
6538           hi = int_const_binop (PLUS_EXPR, prod, tmp);
6539           lo = prod;
6540           break;
6541
6542         default:
6543           gcc_unreachable ();
6544         }
6545     }
6546   else
6547     {
6548       /* A negative divisor reverses the relational operators.  */
6549       code = swap_tree_comparison (code);
6550
6551       tmp = int_const_binop (PLUS_EXPR, arg01,
6552                              build_int_cst (TREE_TYPE (arg01), 1));
6553       switch (tree_int_cst_sgn (arg1))
6554         {
6555         case -1:
6556           hi = int_const_binop (MINUS_EXPR, prod, tmp);
6557           lo = prod;
6558           break;
6559
6560         case  0:
6561           hi = fold_negate_const (tmp, TREE_TYPE (arg0));
6562           lo = tmp;
6563           break;
6564
6565         case  1:
6566           neg_overflow = true;
6567           lo = int_const_binop (PLUS_EXPR, prod, tmp);
6568           hi = prod;
6569           break;
6570
6571         default:
6572           gcc_unreachable ();
6573         }
6574     }
6575
6576   switch (code)
6577     {
6578     case EQ_EXPR:
6579       if (TREE_OVERFLOW (lo) && TREE_OVERFLOW (hi))
6580         return omit_one_operand_loc (loc, type, integer_zero_node, arg00);
6581       if (TREE_OVERFLOW (hi))
6582         return fold_build2_loc (loc, GE_EXPR, type, arg00, lo);
6583       if (TREE_OVERFLOW (lo))
6584         return fold_build2_loc (loc, LE_EXPR, type, arg00, hi);
6585       return build_range_check (loc, type, arg00, 1, lo, hi);
6586
6587     case NE_EXPR:
6588       if (TREE_OVERFLOW (lo) && TREE_OVERFLOW (hi))
6589         return omit_one_operand_loc (loc, type, integer_one_node, arg00);
6590       if (TREE_OVERFLOW (hi))
6591         return fold_build2_loc (loc, LT_EXPR, type, arg00, lo);
6592       if (TREE_OVERFLOW (lo))
6593         return fold_build2_loc (loc, GT_EXPR, type, arg00, hi);
6594       return build_range_check (loc, type, arg00, 0, lo, hi);
6595
6596     case LT_EXPR:
6597       if (TREE_OVERFLOW (lo))
6598         {
6599           tmp = neg_overflow ? integer_zero_node : integer_one_node;
6600           return omit_one_operand_loc (loc, type, tmp, arg00);
6601         }
6602       return fold_build2_loc (loc, LT_EXPR, type, arg00, lo);
6603
6604     case LE_EXPR:
6605       if (TREE_OVERFLOW (hi))
6606         {
6607           tmp = neg_overflow ? integer_zero_node : integer_one_node;
6608           return omit_one_operand_loc (loc, type, tmp, arg00);
6609         }
6610       return fold_build2_loc (loc, LE_EXPR, type, arg00, hi);
6611
6612     case GT_EXPR:
6613       if (TREE_OVERFLOW (hi))
6614         {
6615           tmp = neg_overflow ? integer_one_node : integer_zero_node;
6616           return omit_one_operand_loc (loc, type, tmp, arg00);
6617         }
6618       return fold_build2_loc (loc, GT_EXPR, type, arg00, hi);
6619
6620     case GE_EXPR:
6621       if (TREE_OVERFLOW (lo))
6622         {
6623           tmp = neg_overflow ? integer_one_node : integer_zero_node;
6624           return omit_one_operand_loc (loc, type, tmp, arg00);
6625         }
6626       return fold_build2_loc (loc, GE_EXPR, type, arg00, lo);
6627
6628     default:
6629       break;
6630     }
6631
6632   return NULL_TREE;
6633 }
6634
6635
6636 /* If CODE with arguments ARG0 and ARG1 represents a single bit
6637    equality/inequality test, then return a simplified form of the test
6638    using a sign testing.  Otherwise return NULL.  TYPE is the desired
6639    result type.  */
6640
6641 static tree
6642 fold_single_bit_test_into_sign_test (location_t loc,
6643                                      enum tree_code code, tree arg0, tree arg1,
6644                                      tree result_type)
6645 {
6646   /* If this is testing a single bit, we can optimize the test.  */
6647   if ((code == NE_EXPR || code == EQ_EXPR)
6648       && TREE_CODE (arg0) == BIT_AND_EXPR && integer_zerop (arg1)
6649       && integer_pow2p (TREE_OPERAND (arg0, 1)))
6650     {
6651       /* If we have (A & C) != 0 where C is the sign bit of A, convert
6652          this into A < 0.  Similarly for (A & C) == 0 into A >= 0.  */
6653       tree arg00 = sign_bit_p (TREE_OPERAND (arg0, 0), TREE_OPERAND (arg0, 1));
6654
6655       if (arg00 != NULL_TREE
6656           /* This is only a win if casting to a signed type is cheap,
6657              i.e. when arg00's type is not a partial mode.  */
6658           && TYPE_PRECISION (TREE_TYPE (arg00))
6659              == GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (arg00))))
6660         {
6661           tree stype = signed_type_for (TREE_TYPE (arg00));
6662           return fold_build2_loc (loc, code == EQ_EXPR ? GE_EXPR : LT_EXPR,
6663                               result_type,
6664                               fold_convert_loc (loc, stype, arg00),
6665                               build_int_cst (stype, 0));
6666         }
6667     }
6668
6669   return NULL_TREE;
6670 }
6671
6672 /* If CODE with arguments ARG0 and ARG1 represents a single bit
6673    equality/inequality test, then return a simplified form of
6674    the test using shifts and logical operations.  Otherwise return
6675    NULL.  TYPE is the desired result type.  */
6676
6677 tree
6678 fold_single_bit_test (location_t loc, enum tree_code code,
6679                       tree arg0, tree arg1, tree result_type)
6680 {
6681   /* If this is testing a single bit, we can optimize the test.  */
6682   if ((code == NE_EXPR || code == EQ_EXPR)
6683       && TREE_CODE (arg0) == BIT_AND_EXPR && integer_zerop (arg1)
6684       && integer_pow2p (TREE_OPERAND (arg0, 1)))
6685     {
6686       tree inner = TREE_OPERAND (arg0, 0);
6687       tree type = TREE_TYPE (arg0);
6688       int bitnum = tree_log2 (TREE_OPERAND (arg0, 1));
6689       machine_mode operand_mode = TYPE_MODE (type);
6690       int ops_unsigned;
6691       tree signed_type, unsigned_type, intermediate_type;
6692       tree tem, one;
6693
6694       /* First, see if we can fold the single bit test into a sign-bit
6695          test.  */
6696       tem = fold_single_bit_test_into_sign_test (loc, code, arg0, arg1,
6697                                                  result_type);
6698       if (tem)
6699         return tem;
6700
6701       /* Otherwise we have (A & C) != 0 where C is a single bit,
6702          convert that into ((A >> C2) & 1).  Where C2 = log2(C).
6703          Similarly for (A & C) == 0.  */
6704
6705       /* If INNER is a right shift of a constant and it plus BITNUM does
6706          not overflow, adjust BITNUM and INNER.  */
6707       if (TREE_CODE (inner) == RSHIFT_EXPR
6708           && TREE_CODE (TREE_OPERAND (inner, 1)) == INTEGER_CST
6709           && bitnum < TYPE_PRECISION (type)
6710           && wi::ltu_p (TREE_OPERAND (inner, 1),
6711                         TYPE_PRECISION (type) - bitnum))
6712         {
6713           bitnum += tree_to_uhwi (TREE_OPERAND (inner, 1));
6714           inner = TREE_OPERAND (inner, 0);
6715         }
6716
6717       /* If we are going to be able to omit the AND below, we must do our
6718          operations as unsigned.  If we must use the AND, we have a choice.
6719          Normally unsigned is faster, but for some machines signed is.  */
6720       ops_unsigned = (LOAD_EXTEND_OP (operand_mode) == SIGN_EXTEND
6721                       && !flag_syntax_only) ? 0 : 1;
6722
6723       signed_type = lang_hooks.types.type_for_mode (operand_mode, 0);
6724       unsigned_type = lang_hooks.types.type_for_mode (operand_mode, 1);
6725       intermediate_type = ops_unsigned ? unsigned_type : signed_type;
6726       inner = fold_convert_loc (loc, intermediate_type, inner);
6727
6728       if (bitnum != 0)
6729         inner = build2 (RSHIFT_EXPR, intermediate_type,
6730                         inner, size_int (bitnum));
6731
6732       one = build_int_cst (intermediate_type, 1);
6733
6734       if (code == EQ_EXPR)
6735         inner = fold_build2_loc (loc, BIT_XOR_EXPR, intermediate_type, inner, one);
6736
6737       /* Put the AND last so it can combine with more things.  */
6738       inner = build2 (BIT_AND_EXPR, intermediate_type, inner, one);
6739
6740       /* Make sure to return the proper type.  */
6741       inner = fold_convert_loc (loc, result_type, inner);
6742
6743       return inner;
6744     }
6745   return NULL_TREE;
6746 }
6747
6748 /* Check whether we are allowed to reorder operands arg0 and arg1,
6749    such that the evaluation of arg1 occurs before arg0.  */
6750
6751 static bool
6752 reorder_operands_p (const_tree arg0, const_tree arg1)
6753 {
6754   if (! flag_evaluation_order)
6755       return true;
6756   if (TREE_CONSTANT (arg0) || TREE_CONSTANT (arg1))
6757     return true;
6758   return ! TREE_SIDE_EFFECTS (arg0)
6759          && ! TREE_SIDE_EFFECTS (arg1);
6760 }
6761
6762 /* Test whether it is preferable two swap two operands, ARG0 and
6763    ARG1, for example because ARG0 is an integer constant and ARG1
6764    isn't.  If REORDER is true, only recommend swapping if we can
6765    evaluate the operands in reverse order.  */
6766
6767 bool
6768 tree_swap_operands_p (const_tree arg0, const_tree arg1, bool reorder)
6769 {
6770   if (CONSTANT_CLASS_P (arg1))
6771     return 0;
6772   if (CONSTANT_CLASS_P (arg0))
6773     return 1;
6774
6775   STRIP_NOPS (arg0);
6776   STRIP_NOPS (arg1);
6777
6778   if (TREE_CONSTANT (arg1))
6779     return 0;
6780   if (TREE_CONSTANT (arg0))
6781     return 1;
6782
6783   if (reorder && flag_evaluation_order
6784       && (TREE_SIDE_EFFECTS (arg0) || TREE_SIDE_EFFECTS (arg1)))
6785     return 0;
6786
6787   /* It is preferable to swap two SSA_NAME to ensure a canonical form
6788      for commutative and comparison operators.  Ensuring a canonical
6789      form allows the optimizers to find additional redundancies without
6790      having to explicitly check for both orderings.  */
6791   if (TREE_CODE (arg0) == SSA_NAME
6792       && TREE_CODE (arg1) == SSA_NAME
6793       && SSA_NAME_VERSION (arg0) > SSA_NAME_VERSION (arg1))
6794     return 1;
6795
6796   /* Put SSA_NAMEs last.  */
6797   if (TREE_CODE (arg1) == SSA_NAME)
6798     return 0;
6799   if (TREE_CODE (arg0) == SSA_NAME)
6800     return 1;
6801
6802   /* Put variables last.  */
6803   if (DECL_P (arg1))
6804     return 0;
6805   if (DECL_P (arg0))
6806     return 1;
6807
6808   return 0;
6809 }
6810
6811
6812 /* Fold A < X && A + 1 > Y to A < X && A >= Y.  Normally A + 1 > Y
6813    means A >= Y && A != MAX, but in this case we know that
6814    A < X <= MAX.  INEQ is A + 1 > Y, BOUND is A < X.  */
6815
6816 static tree
6817 fold_to_nonsharp_ineq_using_bound (location_t loc, tree ineq, tree bound)
6818 {
6819   tree a, typea, type = TREE_TYPE (ineq), a1, diff, y;
6820
6821   if (TREE_CODE (bound) == LT_EXPR)
6822     a = TREE_OPERAND (bound, 0);
6823   else if (TREE_CODE (bound) == GT_EXPR)
6824     a = TREE_OPERAND (bound, 1);
6825   else
6826     return NULL_TREE;
6827
6828   typea = TREE_TYPE (a);
6829   if (!INTEGRAL_TYPE_P (typea)
6830       && !POINTER_TYPE_P (typea))
6831     return NULL_TREE;
6832
6833   if (TREE_CODE (ineq) == LT_EXPR)
6834     {
6835       a1 = TREE_OPERAND (ineq, 1);
6836       y = TREE_OPERAND (ineq, 0);
6837     }
6838   else if (TREE_CODE (ineq) == GT_EXPR)
6839     {
6840       a1 = TREE_OPERAND (ineq, 0);
6841       y = TREE_OPERAND (ineq, 1);
6842     }
6843   else
6844     return NULL_TREE;
6845
6846   if (TREE_TYPE (a1) != typea)
6847     return NULL_TREE;
6848
6849   if (POINTER_TYPE_P (typea))
6850     {
6851       /* Convert the pointer types into integer before taking the difference.  */
6852       tree ta = fold_convert_loc (loc, ssizetype, a);
6853       tree ta1 = fold_convert_loc (loc, ssizetype, a1);
6854       diff = fold_binary_loc (loc, MINUS_EXPR, ssizetype, ta1, ta);
6855     }
6856   else
6857     diff = fold_binary_loc (loc, MINUS_EXPR, typea, a1, a);
6858
6859   if (!diff || !integer_onep (diff))
6860    return NULL_TREE;
6861
6862   return fold_build2_loc (loc, GE_EXPR, type, a, y);
6863 }
6864
6865 /* Fold a sum or difference of at least one multiplication.
6866    Returns the folded tree or NULL if no simplification could be made.  */
6867
6868 static tree
6869 fold_plusminus_mult_expr (location_t loc, enum tree_code code, tree type,
6870                           tree arg0, tree arg1)
6871 {
6872   tree arg00, arg01, arg10, arg11;
6873   tree alt0 = NULL_TREE, alt1 = NULL_TREE, same;
6874
6875   /* (A * C) +- (B * C) -> (A+-B) * C.
6876      (A * C) +- A -> A * (C+-1).
6877      We are most concerned about the case where C is a constant,
6878      but other combinations show up during loop reduction.  Since
6879      it is not difficult, try all four possibilities.  */
6880
6881   if (TREE_CODE (arg0) == MULT_EXPR)
6882     {
6883       arg00 = TREE_OPERAND (arg0, 0);
6884       arg01 = TREE_OPERAND (arg0, 1);
6885     }
6886   else if (TREE_CODE (arg0) == INTEGER_CST)
6887     {
6888       arg00 = build_one_cst (type);
6889       arg01 = arg0;
6890     }
6891   else
6892     {
6893       /* We cannot generate constant 1 for fract.  */
6894       if (ALL_FRACT_MODE_P (TYPE_MODE (type)))
6895         return NULL_TREE;
6896       arg00 = arg0;
6897       arg01 = build_one_cst (type);
6898     }
6899   if (TREE_CODE (arg1) == MULT_EXPR)
6900     {
6901       arg10 = TREE_OPERAND (arg1, 0);
6902       arg11 = TREE_OPERAND (arg1, 1);
6903     }
6904   else if (TREE_CODE (arg1) == INTEGER_CST)
6905     {
6906       arg10 = build_one_cst (type);
6907       /* As we canonicalize A - 2 to A + -2 get rid of that sign for
6908          the purpose of this canonicalization.  */
6909       if (wi::neg_p (arg1, TYPE_SIGN (TREE_TYPE (arg1)))
6910           && negate_expr_p (arg1)
6911           && code == PLUS_EXPR)
6912         {
6913           arg11 = negate_expr (arg1);
6914           code = MINUS_EXPR;
6915         }
6916       else
6917         arg11 = arg1;
6918     }
6919   else
6920     {
6921       /* We cannot generate constant 1 for fract.  */
6922       if (ALL_FRACT_MODE_P (TYPE_MODE (type)))
6923         return NULL_TREE;
6924       arg10 = arg1;
6925       arg11 = build_one_cst (type);
6926     }
6927   same = NULL_TREE;
6928
6929   if (operand_equal_p (arg01, arg11, 0))
6930     same = arg01, alt0 = arg00, alt1 = arg10;
6931   else if (operand_equal_p (arg00, arg10, 0))
6932     same = arg00, alt0 = arg01, alt1 = arg11;
6933   else if (operand_equal_p (arg00, arg11, 0))
6934     same = arg00, alt0 = arg01, alt1 = arg10;
6935   else if (operand_equal_p (arg01, arg10, 0))
6936     same = arg01, alt0 = arg00, alt1 = arg11;
6937
6938   /* No identical multiplicands; see if we can find a common
6939      power-of-two factor in non-power-of-two multiplies.  This
6940      can help in multi-dimensional array access.  */
6941   else if (tree_fits_shwi_p (arg01)
6942            && tree_fits_shwi_p (arg11))
6943     {
6944       HOST_WIDE_INT int01, int11, tmp;
6945       bool swap = false;
6946       tree maybe_same;
6947       int01 = tree_to_shwi (arg01);
6948       int11 = tree_to_shwi (arg11);
6949
6950       /* Move min of absolute values to int11.  */
6951       if (absu_hwi (int01) < absu_hwi (int11))
6952         {
6953           tmp = int01, int01 = int11, int11 = tmp;
6954           alt0 = arg00, arg00 = arg10, arg10 = alt0;
6955           maybe_same = arg01;
6956           swap = true;
6957         }
6958       else
6959         maybe_same = arg11;
6960
6961       if (exact_log2 (absu_hwi (int11)) > 0 && int01 % int11 == 0
6962           /* The remainder should not be a constant, otherwise we
6963              end up folding i * 4 + 2 to (i * 2 + 1) * 2 which has
6964              increased the number of multiplications necessary.  */
6965           && TREE_CODE (arg10) != INTEGER_CST)
6966         {
6967           alt0 = fold_build2_loc (loc, MULT_EXPR, TREE_TYPE (arg00), arg00,
6968                               build_int_cst (TREE_TYPE (arg00),
6969                                              int01 / int11));
6970           alt1 = arg10;
6971           same = maybe_same;
6972           if (swap)
6973             maybe_same = alt0, alt0 = alt1, alt1 = maybe_same;
6974         }
6975     }
6976
6977   if (same)
6978     return fold_build2_loc (loc, MULT_EXPR, type,
6979                         fold_build2_loc (loc, code, type,
6980                                      fold_convert_loc (loc, type, alt0),
6981                                      fold_convert_loc (loc, type, alt1)),
6982                         fold_convert_loc (loc, type, same));
6983
6984   return NULL_TREE;
6985 }
6986
6987 /* Subroutine of native_encode_expr.  Encode the INTEGER_CST
6988    specified by EXPR into the buffer PTR of length LEN bytes.
6989    Return the number of bytes placed in the buffer, or zero
6990    upon failure.  */
6991
6992 static int
6993 native_encode_int (const_tree expr, unsigned char *ptr, int len, int off)
6994 {
6995   tree type = TREE_TYPE (expr);
6996   int total_bytes = GET_MODE_SIZE (TYPE_MODE (type));
6997   int byte, offset, word, words;
6998   unsigned char value;
6999
7000   if ((off == -1 && total_bytes > len)
7001       || off >= total_bytes)
7002     return 0;
7003   if (off == -1)
7004     off = 0;
7005   words = total_bytes / UNITS_PER_WORD;
7006
7007   for (byte = 0; byte < total_bytes; byte++)
7008     {
7009       int bitpos = byte * BITS_PER_UNIT;
7010       /* Extend EXPR according to TYPE_SIGN if the precision isn't a whole
7011          number of bytes.  */
7012       value = wi::extract_uhwi (wi::to_widest (expr), bitpos, BITS_PER_UNIT);
7013
7014       if (total_bytes > UNITS_PER_WORD)
7015         {
7016           word = byte / UNITS_PER_WORD;
7017           if (WORDS_BIG_ENDIAN)
7018             word = (words - 1) - word;
7019           offset = word * UNITS_PER_WORD;
7020           if (BYTES_BIG_ENDIAN)
7021             offset += (UNITS_PER_WORD - 1) - (byte % UNITS_PER_WORD);
7022           else
7023             offset += byte % UNITS_PER_WORD;
7024         }
7025       else
7026         offset = BYTES_BIG_ENDIAN ? (total_bytes - 1) - byte : byte;
7027       if (offset >= off
7028           && offset - off < len)
7029         ptr[offset - off] = value;
7030     }
7031   return MIN (len, total_bytes - off);
7032 }
7033
7034
7035 /* Subroutine of native_encode_expr.  Encode the FIXED_CST
7036    specified by EXPR into the buffer PTR of length LEN bytes.
7037    Return the number of bytes placed in the buffer, or zero
7038    upon failure.  */
7039
7040 static int
7041 native_encode_fixed (const_tree expr, unsigned char *ptr, int len, int off)
7042 {
7043   tree type = TREE_TYPE (expr);
7044   machine_mode mode = TYPE_MODE (type);
7045   int total_bytes = GET_MODE_SIZE (mode);
7046   FIXED_VALUE_TYPE value;
7047   tree i_value, i_type;
7048
7049   if (total_bytes * BITS_PER_UNIT > HOST_BITS_PER_DOUBLE_INT)
7050     return 0;
7051
7052   i_type = lang_hooks.types.type_for_size (GET_MODE_BITSIZE (mode), 1);
7053
7054   if (NULL_TREE == i_type
7055       || TYPE_PRECISION (i_type) != total_bytes)
7056     return 0;
7057   
7058   value = TREE_FIXED_CST (expr);
7059   i_value = double_int_to_tree (i_type, value.data);
7060
7061   return native_encode_int (i_value, ptr, len, off);
7062 }
7063
7064
7065 /* Subroutine of native_encode_expr.  Encode the REAL_CST
7066    specified by EXPR into the buffer PTR of length LEN bytes.
7067    Return the number of bytes placed in the buffer, or zero
7068    upon failure.  */
7069
7070 static int
7071 native_encode_real (const_tree expr, unsigned char *ptr, int len, int off)
7072 {
7073   tree type = TREE_TYPE (expr);
7074   int total_bytes = GET_MODE_SIZE (TYPE_MODE (type));
7075   int byte, offset, word, words, bitpos;
7076   unsigned char value;
7077
7078   /* There are always 32 bits in each long, no matter the size of
7079      the hosts long.  We handle floating point representations with
7080      up to 192 bits.  */
7081   long tmp[6];
7082
7083   if ((off == -1 && total_bytes > len)
7084       || off >= total_bytes)
7085     return 0;
7086   if (off == -1)
7087     off = 0;
7088   words = (32 / BITS_PER_UNIT) / UNITS_PER_WORD;
7089
7090   real_to_target (tmp, TREE_REAL_CST_PTR (expr), TYPE_MODE (type));
7091
7092   for (bitpos = 0; bitpos < total_bytes * BITS_PER_UNIT;
7093        bitpos += BITS_PER_UNIT)
7094     {
7095       byte = (bitpos / BITS_PER_UNIT) & 3;
7096       value = (unsigned char) (tmp[bitpos / 32] >> (bitpos & 31));
7097
7098       if (UNITS_PER_WORD < 4)
7099         {
7100           word = byte / UNITS_PER_WORD;
7101           if (WORDS_BIG_ENDIAN)
7102             word = (words - 1) - word;
7103           offset = word * UNITS_PER_WORD;
7104           if (BYTES_BIG_ENDIAN)
7105             offset += (UNITS_PER_WORD - 1) - (byte % UNITS_PER_WORD);
7106           else
7107             offset += byte % UNITS_PER_WORD;
7108         }
7109       else
7110         offset = BYTES_BIG_ENDIAN ? 3 - byte : byte;
7111       offset = offset + ((bitpos / BITS_PER_UNIT) & ~3);
7112       if (offset >= off
7113           && offset - off < len)
7114         ptr[offset - off] = value;
7115     }
7116   return MIN (len, total_bytes - off);
7117 }
7118
7119 /* Subroutine of native_encode_expr.  Encode the COMPLEX_CST
7120    specified by EXPR into the buffer PTR of length LEN bytes.
7121    Return the number of bytes placed in the buffer, or zero
7122    upon failure.  */
7123
7124 static int
7125 native_encode_complex (const_tree expr, unsigned char *ptr, int len, int off)
7126 {
7127   int rsize, isize;
7128   tree part;
7129
7130   part = TREE_REALPART (expr);
7131   rsize = native_encode_expr (part, ptr, len, off);
7132   if (off == -1
7133       && rsize == 0)
7134     return 0;
7135   part = TREE_IMAGPART (expr);
7136   if (off != -1)
7137     off = MAX (0, off - GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (part))));
7138   isize = native_encode_expr (part, ptr+rsize, len-rsize, off);
7139   if (off == -1
7140       && isize != rsize)
7141     return 0;
7142   return rsize + isize;
7143 }
7144
7145
7146 /* Subroutine of native_encode_expr.  Encode the VECTOR_CST
7147    specified by EXPR into the buffer PTR of length LEN bytes.
7148    Return the number of bytes placed in the buffer, or zero
7149    upon failure.  */
7150
7151 static int
7152 native_encode_vector (const_tree expr, unsigned char *ptr, int len, int off)
7153 {
7154   unsigned i, count;
7155   int size, offset;
7156   tree itype, elem;
7157
7158   offset = 0;
7159   count = VECTOR_CST_NELTS (expr);
7160   itype = TREE_TYPE (TREE_TYPE (expr));
7161   size = GET_MODE_SIZE (TYPE_MODE (itype));
7162   for (i = 0; i < count; i++)
7163     {
7164       if (off >= size)
7165         {
7166           off -= size;
7167           continue;
7168         }
7169       elem = VECTOR_CST_ELT (expr, i);
7170       int res = native_encode_expr (elem, ptr+offset, len-offset, off);
7171       if ((off == -1 && res != size)
7172           || res == 0)
7173         return 0;
7174       offset += res;
7175       if (offset >= len)
7176         return offset;
7177       if (off != -1)
7178         off = 0;
7179     }
7180   return offset;
7181 }
7182
7183
7184 /* Subroutine of native_encode_expr.  Encode the STRING_CST
7185    specified by EXPR into the buffer PTR of length LEN bytes.
7186    Return the number of bytes placed in the buffer, or zero
7187    upon failure.  */
7188
7189 static int
7190 native_encode_string (const_tree expr, unsigned char *ptr, int len, int off)
7191 {
7192   tree type = TREE_TYPE (expr);
7193   HOST_WIDE_INT total_bytes;
7194
7195   if (TREE_CODE (type) != ARRAY_TYPE
7196       || TREE_CODE (TREE_TYPE (type)) != INTEGER_TYPE
7197       || GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE (type))) != BITS_PER_UNIT
7198       || !tree_fits_shwi_p (TYPE_SIZE_UNIT (type)))
7199     return 0;
7200   total_bytes = tree_to_shwi (TYPE_SIZE_UNIT (type));
7201   if ((off == -1 && total_bytes > len)
7202       || off >= total_bytes)
7203     return 0;
7204   if (off == -1)
7205     off = 0;
7206   if (TREE_STRING_LENGTH (expr) - off < MIN (total_bytes, len))
7207     {
7208       int written = 0;
7209       if (off < TREE_STRING_LENGTH (expr))
7210         {
7211           written = MIN (len, TREE_STRING_LENGTH (expr) - off);
7212           memcpy (ptr, TREE_STRING_POINTER (expr) + off, written);
7213         }
7214       memset (ptr + written, 0,
7215               MIN (total_bytes - written, len - written));
7216     }
7217   else
7218     memcpy (ptr, TREE_STRING_POINTER (expr) + off, MIN (total_bytes, len));
7219   return MIN (total_bytes - off, len);
7220 }
7221
7222
7223 /* Subroutine of fold_view_convert_expr.  Encode the INTEGER_CST,
7224    REAL_CST, COMPLEX_CST or VECTOR_CST specified by EXPR into the
7225    buffer PTR of length LEN bytes.  If OFF is not -1 then start
7226    the encoding at byte offset OFF and encode at most LEN bytes.
7227    Return the number of bytes placed in the buffer, or zero upon failure.  */
7228
7229 int
7230 native_encode_expr (const_tree expr, unsigned char *ptr, int len, int off)
7231 {
7232   /* We don't support starting at negative offset and -1 is special.  */
7233   if (off < -1)
7234     return 0;
7235
7236   switch (TREE_CODE (expr))
7237     {
7238     case INTEGER_CST:
7239       return native_encode_int (expr, ptr, len, off);
7240
7241     case REAL_CST:
7242       return native_encode_real (expr, ptr, len, off);
7243
7244     case FIXED_CST:
7245       return native_encode_fixed (expr, ptr, len, off);
7246
7247     case COMPLEX_CST:
7248       return native_encode_complex (expr, ptr, len, off);
7249
7250     case VECTOR_CST:
7251       return native_encode_vector (expr, ptr, len, off);
7252
7253     case STRING_CST:
7254       return native_encode_string (expr, ptr, len, off);
7255
7256     default:
7257       return 0;
7258     }
7259 }
7260
7261
7262 /* Subroutine of native_interpret_expr.  Interpret the contents of
7263    the buffer PTR of length LEN as an INTEGER_CST of type TYPE.
7264    If the buffer cannot be interpreted, return NULL_TREE.  */
7265
7266 static tree
7267 native_interpret_int (tree type, const unsigned char *ptr, int len)
7268 {
7269   int total_bytes = GET_MODE_SIZE (TYPE_MODE (type));
7270
7271   if (total_bytes > len
7272       || total_bytes * BITS_PER_UNIT > HOST_BITS_PER_DOUBLE_INT)
7273     return NULL_TREE;
7274
7275   wide_int result = wi::from_buffer (ptr, total_bytes);
7276
7277   return wide_int_to_tree (type, result);
7278 }
7279
7280
7281 /* Subroutine of native_interpret_expr.  Interpret the contents of
7282    the buffer PTR of length LEN as a FIXED_CST of type TYPE.
7283    If the buffer cannot be interpreted, return NULL_TREE.  */
7284
7285 static tree
7286 native_interpret_fixed (tree type, const unsigned char *ptr, int len)
7287 {
7288   int total_bytes = GET_MODE_SIZE (TYPE_MODE (type));
7289   double_int result;
7290   FIXED_VALUE_TYPE fixed_value;
7291
7292   if (total_bytes > len
7293       || total_bytes * BITS_PER_UNIT > HOST_BITS_PER_DOUBLE_INT)
7294     return NULL_TREE;
7295
7296   result = double_int::from_buffer (ptr, total_bytes);
7297   fixed_value = fixed_from_double_int (result, TYPE_MODE (type));
7298
7299   return build_fixed (type, fixed_value);
7300 }
7301
7302
7303 /* Subroutine of native_interpret_expr.  Interpret the contents of
7304    the buffer PTR of length LEN as a REAL_CST of type TYPE.
7305    If the buffer cannot be interpreted, return NULL_TREE.  */
7306
7307 static tree
7308 native_interpret_real (tree type, const unsigned char *ptr, int len)
7309 {
7310   machine_mode mode = TYPE_MODE (type);
7311   int total_bytes = GET_MODE_SIZE (mode);
7312   unsigned char value;
7313   /* There are always 32 bits in each long, no matter the size of
7314      the hosts long.  We handle floating point representations with
7315      up to 192 bits.  */
7316   REAL_VALUE_TYPE r;
7317   long tmp[6];
7318
7319   total_bytes = GET_MODE_SIZE (TYPE_MODE (type));
7320   if (total_bytes > len || total_bytes > 24)
7321     return NULL_TREE;
7322   int words = (32 / BITS_PER_UNIT) / UNITS_PER_WORD;
7323
7324   memset (tmp, 0, sizeof (tmp));
7325   for (int bitpos = 0; bitpos < total_bytes * BITS_PER_UNIT;
7326        bitpos += BITS_PER_UNIT)
7327     {
7328       /* Both OFFSET and BYTE index within a long;
7329          bitpos indexes the whole float.  */
7330       int offset, byte = (bitpos / BITS_PER_UNIT) & 3;
7331       if (UNITS_PER_WORD < 4)
7332         {
7333           int word = byte / UNITS_PER_WORD;
7334           if (WORDS_BIG_ENDIAN)
7335             word = (words - 1) - word;
7336           offset = word * UNITS_PER_WORD;
7337           if (BYTES_BIG_ENDIAN)
7338             offset += (UNITS_PER_WORD - 1) - (byte % UNITS_PER_WORD);
7339           else
7340             offset += byte % UNITS_PER_WORD;
7341         }
7342       else
7343         {
7344           offset = byte;
7345           if (BYTES_BIG_ENDIAN)
7346             {
7347               /* Reverse bytes within each long, or within the entire float
7348                  if it's smaller than a long (for HFmode).  */
7349               offset = MIN (3, total_bytes - 1) - offset;
7350               gcc_assert (offset >= 0);
7351             }
7352         }
7353       value = ptr[offset + ((bitpos / BITS_PER_UNIT) & ~3)];
7354
7355       tmp[bitpos / 32] |= (unsigned long)value << (bitpos & 31);
7356     }
7357
7358   real_from_target (&r, tmp, mode);
7359   return build_real (type, r);
7360 }
7361
7362
7363 /* Subroutine of native_interpret_expr.  Interpret the contents of
7364    the buffer PTR of length LEN as a COMPLEX_CST of type TYPE.
7365    If the buffer cannot be interpreted, return NULL_TREE.  */
7366
7367 static tree
7368 native_interpret_complex (tree type, const unsigned char *ptr, int len)
7369 {
7370   tree etype, rpart, ipart;
7371   int size;
7372
7373   etype = TREE_TYPE (type);
7374   size = GET_MODE_SIZE (TYPE_MODE (etype));
7375   if (size * 2 > len)
7376     return NULL_TREE;
7377   rpart = native_interpret_expr (etype, ptr, size);
7378   if (!rpart)
7379     return NULL_TREE;
7380   ipart = native_interpret_expr (etype, ptr+size, size);
7381   if (!ipart)
7382     return NULL_TREE;
7383   return build_complex (type, rpart, ipart);
7384 }
7385
7386
7387 /* Subroutine of native_interpret_expr.  Interpret the contents of
7388    the buffer PTR of length LEN as a VECTOR_CST of type TYPE.
7389    If the buffer cannot be interpreted, return NULL_TREE.  */
7390
7391 static tree
7392 native_interpret_vector (tree type, const unsigned char *ptr, int len)
7393 {
7394   tree etype, elem;
7395   int i, size, count;
7396   tree *elements;
7397
7398   etype = TREE_TYPE (type);
7399   size = GET_MODE_SIZE (TYPE_MODE (etype));
7400   count = TYPE_VECTOR_SUBPARTS (type);
7401   if (size * count > len)
7402     return NULL_TREE;
7403
7404   elements = XALLOCAVEC (tree, count);
7405   for (i = count - 1; i >= 0; i--)
7406     {
7407       elem = native_interpret_expr (etype, ptr+(i*size), size);
7408       if (!elem)
7409         return NULL_TREE;
7410       elements[i] = elem;
7411     }
7412   return build_vector (type, elements);
7413 }
7414
7415
7416 /* Subroutine of fold_view_convert_expr.  Interpret the contents of
7417    the buffer PTR of length LEN as a constant of type TYPE.  For
7418    INTEGRAL_TYPE_P we return an INTEGER_CST, for SCALAR_FLOAT_TYPE_P
7419    we return a REAL_CST, etc...  If the buffer cannot be interpreted,
7420    return NULL_TREE.  */
7421
7422 tree
7423 native_interpret_expr (tree type, const unsigned char *ptr, int len)
7424 {
7425   switch (TREE_CODE (type))
7426     {
7427     case INTEGER_TYPE:
7428     case ENUMERAL_TYPE:
7429     case BOOLEAN_TYPE:
7430     case POINTER_TYPE:
7431     case REFERENCE_TYPE:
7432       return native_interpret_int (type, ptr, len);
7433
7434     case REAL_TYPE:
7435       return native_interpret_real (type, ptr, len);
7436
7437     case FIXED_POINT_TYPE:
7438       return native_interpret_fixed (type, ptr, len);
7439
7440     case COMPLEX_TYPE:
7441       return native_interpret_complex (type, ptr, len);
7442
7443     case VECTOR_TYPE:
7444       return native_interpret_vector (type, ptr, len);
7445
7446     default:
7447       return NULL_TREE;
7448     }
7449 }
7450
7451 /* Returns true if we can interpret the contents of a native encoding
7452    as TYPE.  */
7453
7454 static bool
7455 can_native_interpret_type_p (tree type)
7456 {
7457   switch (TREE_CODE (type))
7458     {
7459     case INTEGER_TYPE:
7460     case ENUMERAL_TYPE:
7461     case BOOLEAN_TYPE:
7462     case POINTER_TYPE:
7463     case REFERENCE_TYPE:
7464     case FIXED_POINT_TYPE:
7465     case REAL_TYPE:
7466     case COMPLEX_TYPE:
7467     case VECTOR_TYPE:
7468       return true;
7469     default:
7470       return false;
7471     }
7472 }
7473
7474 /* Fold a VIEW_CONVERT_EXPR of a constant expression EXPR to type
7475    TYPE at compile-time.  If we're unable to perform the conversion
7476    return NULL_TREE.  */
7477
7478 static tree
7479 fold_view_convert_expr (tree type, tree expr)
7480 {
7481   /* We support up to 512-bit values (for V8DFmode).  */
7482   unsigned char buffer[64];
7483   int len;
7484
7485   /* Check that the host and target are sane.  */
7486   if (CHAR_BIT != 8 || BITS_PER_UNIT != 8)
7487     return NULL_TREE;
7488
7489   len = native_encode_expr (expr, buffer, sizeof (buffer));
7490   if (len == 0)
7491     return NULL_TREE;
7492
7493   return native_interpret_expr (type, buffer, len);
7494 }
7495
7496 /* Build an expression for the address of T.  Folds away INDIRECT_REF
7497    to avoid confusing the gimplify process.  */
7498
7499 tree
7500 build_fold_addr_expr_with_type_loc (location_t loc, tree t, tree ptrtype)
7501 {
7502   /* The size of the object is not relevant when talking about its address.  */
7503   if (TREE_CODE (t) == WITH_SIZE_EXPR)
7504     t = TREE_OPERAND (t, 0);
7505
7506   if (TREE_CODE (t) == INDIRECT_REF)
7507     {
7508       t = TREE_OPERAND (t, 0);
7509
7510       if (TREE_TYPE (t) != ptrtype)
7511         t = build1_loc (loc, NOP_EXPR, ptrtype, t);
7512     }
7513   else if (TREE_CODE (t) == MEM_REF
7514            && integer_zerop (TREE_OPERAND (t, 1)))
7515     return TREE_OPERAND (t, 0);
7516   else if (TREE_CODE (t) == MEM_REF
7517            && TREE_CODE (TREE_OPERAND (t, 0)) == INTEGER_CST)
7518     return fold_binary (POINTER_PLUS_EXPR, ptrtype,
7519                         TREE_OPERAND (t, 0),
7520                         convert_to_ptrofftype (TREE_OPERAND (t, 1)));
7521   else if (TREE_CODE (t) == VIEW_CONVERT_EXPR)
7522     {
7523       t = build_fold_addr_expr_loc (loc, TREE_OPERAND (t, 0));
7524
7525       if (TREE_TYPE (t) != ptrtype)
7526         t = fold_convert_loc (loc, ptrtype, t);
7527     }
7528   else
7529     t = build1_loc (loc, ADDR_EXPR, ptrtype, t);
7530
7531   return t;
7532 }
7533
7534 /* Build an expression for the address of T.  */
7535
7536 tree
7537 build_fold_addr_expr_loc (location_t loc, tree t)
7538 {
7539   tree ptrtype = build_pointer_type (TREE_TYPE (t));
7540
7541   return build_fold_addr_expr_with_type_loc (loc, t, ptrtype);
7542 }
7543
7544 /* Fold a unary expression of code CODE and type TYPE with operand
7545    OP0.  Return the folded expression if folding is successful.
7546    Otherwise, return NULL_TREE.  */
7547
7548 tree
7549 fold_unary_loc (location_t loc, enum tree_code code, tree type, tree op0)
7550 {
7551   tree tem;
7552   tree arg0;
7553   enum tree_code_class kind = TREE_CODE_CLASS (code);
7554
7555   gcc_assert (IS_EXPR_CODE_CLASS (kind)
7556               && TREE_CODE_LENGTH (code) == 1);
7557
7558   arg0 = op0;
7559   if (arg0)
7560     {
7561       if (CONVERT_EXPR_CODE_P (code)
7562           || code == FLOAT_EXPR || code == ABS_EXPR || code == NEGATE_EXPR)
7563         {
7564           /* Don't use STRIP_NOPS, because signedness of argument type
7565              matters.  */
7566           STRIP_SIGN_NOPS (arg0);
7567         }
7568       else
7569         {
7570           /* Strip any conversions that don't change the mode.  This
7571              is safe for every expression, except for a comparison
7572              expression because its signedness is derived from its
7573              operands.
7574
7575              Note that this is done as an internal manipulation within
7576              the constant folder, in order to find the simplest
7577              representation of the arguments so that their form can be
7578              studied.  In any cases, the appropriate type conversions
7579              should be put back in the tree that will get out of the
7580              constant folder.  */
7581           STRIP_NOPS (arg0);
7582         }
7583
7584       if (CONSTANT_CLASS_P (arg0))
7585         {
7586           tree tem = const_unop (code, type, arg0);
7587           if (tem)
7588             {
7589               if (TREE_TYPE (tem) != type)
7590                 tem = fold_convert_loc (loc, type, tem);
7591               return tem;
7592             }
7593         }
7594     }
7595
7596   tem = generic_simplify (loc, code, type, op0);
7597   if (tem)
7598     return tem;
7599
7600   if (TREE_CODE_CLASS (code) == tcc_unary)
7601     {
7602       if (TREE_CODE (arg0) == COMPOUND_EXPR)
7603         return build2 (COMPOUND_EXPR, type, TREE_OPERAND (arg0, 0),
7604                        fold_build1_loc (loc, code, type,
7605                                     fold_convert_loc (loc, TREE_TYPE (op0),
7606                                                       TREE_OPERAND (arg0, 1))));
7607       else if (TREE_CODE (arg0) == COND_EXPR)
7608         {
7609           tree arg01 = TREE_OPERAND (arg0, 1);
7610           tree arg02 = TREE_OPERAND (arg0, 2);
7611           if (! VOID_TYPE_P (TREE_TYPE (arg01)))
7612             arg01 = fold_build1_loc (loc, code, type,
7613                                  fold_convert_loc (loc,
7614                                                    TREE_TYPE (op0), arg01));
7615           if (! VOID_TYPE_P (TREE_TYPE (arg02)))
7616             arg02 = fold_build1_loc (loc, code, type,
7617                                  fold_convert_loc (loc,
7618                                                    TREE_TYPE (op0), arg02));
7619           tem = fold_build3_loc (loc, COND_EXPR, type, TREE_OPERAND (arg0, 0),
7620                              arg01, arg02);
7621
7622           /* If this was a conversion, and all we did was to move into
7623              inside the COND_EXPR, bring it back out.  But leave it if
7624              it is a conversion from integer to integer and the
7625              result precision is no wider than a word since such a
7626              conversion is cheap and may be optimized away by combine,
7627              while it couldn't if it were outside the COND_EXPR.  Then return
7628              so we don't get into an infinite recursion loop taking the
7629              conversion out and then back in.  */
7630
7631           if ((CONVERT_EXPR_CODE_P (code)
7632                || code == NON_LVALUE_EXPR)
7633               && TREE_CODE (tem) == COND_EXPR
7634               && TREE_CODE (TREE_OPERAND (tem, 1)) == code
7635               && TREE_CODE (TREE_OPERAND (tem, 2)) == code
7636               && ! VOID_TYPE_P (TREE_OPERAND (tem, 1))
7637               && ! VOID_TYPE_P (TREE_OPERAND (tem, 2))
7638               && (TREE_TYPE (TREE_OPERAND (TREE_OPERAND (tem, 1), 0))
7639                   == TREE_TYPE (TREE_OPERAND (TREE_OPERAND (tem, 2), 0)))
7640               && (! (INTEGRAL_TYPE_P (TREE_TYPE (tem))
7641                      && (INTEGRAL_TYPE_P
7642                          (TREE_TYPE (TREE_OPERAND (TREE_OPERAND (tem, 1), 0))))
7643                      && TYPE_PRECISION (TREE_TYPE (tem)) <= BITS_PER_WORD)
7644                   || flag_syntax_only))
7645             tem = build1_loc (loc, code, type,
7646                               build3 (COND_EXPR,
7647                                       TREE_TYPE (TREE_OPERAND
7648                                                  (TREE_OPERAND (tem, 1), 0)),
7649                                       TREE_OPERAND (tem, 0),
7650                                       TREE_OPERAND (TREE_OPERAND (tem, 1), 0),
7651                                       TREE_OPERAND (TREE_OPERAND (tem, 2),
7652                                                     0)));
7653           return tem;
7654         }
7655    }
7656
7657   switch (code)
7658     {
7659     case NON_LVALUE_EXPR:
7660       if (!maybe_lvalue_p (op0))
7661         return fold_convert_loc (loc, type, op0);
7662       return NULL_TREE;
7663
7664     CASE_CONVERT:
7665     case FLOAT_EXPR:
7666     case FIX_TRUNC_EXPR:
7667       if (COMPARISON_CLASS_P (op0))
7668         {
7669           /* If we have (type) (a CMP b) and type is an integral type, return
7670              new expression involving the new type.  Canonicalize
7671              (type) (a CMP b) to (a CMP b) ? (type) true : (type) false for
7672              non-integral type.
7673              Do not fold the result as that would not simplify further, also
7674              folding again results in recursions.  */
7675           if (TREE_CODE (type) == BOOLEAN_TYPE)
7676             return build2_loc (loc, TREE_CODE (op0), type,
7677                                TREE_OPERAND (op0, 0),
7678                                TREE_OPERAND (op0, 1));
7679           else if (!INTEGRAL_TYPE_P (type) && !VOID_TYPE_P (type)
7680                    && TREE_CODE (type) != VECTOR_TYPE)
7681             return build3_loc (loc, COND_EXPR, type, op0,
7682                                constant_boolean_node (true, type),
7683                                constant_boolean_node (false, type));
7684         }
7685
7686       /* Handle (T *)&A.B.C for A being of type T and B and C
7687          living at offset zero.  This occurs frequently in
7688          C++ upcasting and then accessing the base.  */
7689       if (TREE_CODE (op0) == ADDR_EXPR
7690           && POINTER_TYPE_P (type)
7691           && handled_component_p (TREE_OPERAND (op0, 0)))
7692         {
7693           HOST_WIDE_INT bitsize, bitpos;
7694           tree offset;
7695           machine_mode mode;
7696           int unsignedp, volatilep;
7697           tree base = TREE_OPERAND (op0, 0);
7698           base = get_inner_reference (base, &bitsize, &bitpos, &offset,
7699                                       &mode, &unsignedp, &volatilep, false);
7700           /* If the reference was to a (constant) zero offset, we can use
7701              the address of the base if it has the same base type
7702              as the result type and the pointer type is unqualified.  */
7703           if (! offset && bitpos == 0
7704               && (TYPE_MAIN_VARIANT (TREE_TYPE (type))
7705                   == TYPE_MAIN_VARIANT (TREE_TYPE (base)))
7706               && TYPE_QUALS (type) == TYPE_UNQUALIFIED)
7707             return fold_convert_loc (loc, type,
7708                                      build_fold_addr_expr_loc (loc, base));
7709         }
7710
7711       if (TREE_CODE (op0) == MODIFY_EXPR
7712           && TREE_CONSTANT (TREE_OPERAND (op0, 1))
7713           /* Detect assigning a bitfield.  */
7714           && !(TREE_CODE (TREE_OPERAND (op0, 0)) == COMPONENT_REF
7715                && DECL_BIT_FIELD
7716                (TREE_OPERAND (TREE_OPERAND (op0, 0), 1))))
7717         {
7718           /* Don't leave an assignment inside a conversion
7719              unless assigning a bitfield.  */
7720           tem = fold_build1_loc (loc, code, type, TREE_OPERAND (op0, 1));
7721           /* First do the assignment, then return converted constant.  */
7722           tem = build2_loc (loc, COMPOUND_EXPR, TREE_TYPE (tem), op0, tem);
7723           TREE_NO_WARNING (tem) = 1;
7724           TREE_USED (tem) = 1;
7725           return tem;
7726         }
7727
7728       /* Convert (T)(x & c) into (T)x & (T)c, if c is an integer
7729          constants (if x has signed type, the sign bit cannot be set
7730          in c).  This folds extension into the BIT_AND_EXPR.
7731          ??? We don't do it for BOOLEAN_TYPE or ENUMERAL_TYPE because they
7732          very likely don't have maximal range for their precision and this
7733          transformation effectively doesn't preserve non-maximal ranges.  */
7734       if (TREE_CODE (type) == INTEGER_TYPE
7735           && TREE_CODE (op0) == BIT_AND_EXPR
7736           && TREE_CODE (TREE_OPERAND (op0, 1)) == INTEGER_CST)
7737         {
7738           tree and_expr = op0;
7739           tree and0 = TREE_OPERAND (and_expr, 0);
7740           tree and1 = TREE_OPERAND (and_expr, 1);
7741           int change = 0;
7742
7743           if (TYPE_UNSIGNED (TREE_TYPE (and_expr))
7744               || (TYPE_PRECISION (type)
7745                   <= TYPE_PRECISION (TREE_TYPE (and_expr))))
7746             change = 1;
7747           else if (TYPE_PRECISION (TREE_TYPE (and1))
7748                    <= HOST_BITS_PER_WIDE_INT
7749                    && tree_fits_uhwi_p (and1))
7750             {
7751               unsigned HOST_WIDE_INT cst;
7752
7753               cst = tree_to_uhwi (and1);
7754               cst &= HOST_WIDE_INT_M1U
7755                      << (TYPE_PRECISION (TREE_TYPE (and1)) - 1);
7756               change = (cst == 0);
7757               if (change
7758                   && !flag_syntax_only
7759                   && (LOAD_EXTEND_OP (TYPE_MODE (TREE_TYPE (and0)))
7760                       == ZERO_EXTEND))
7761                 {
7762                   tree uns = unsigned_type_for (TREE_TYPE (and0));
7763                   and0 = fold_convert_loc (loc, uns, and0);
7764                   and1 = fold_convert_loc (loc, uns, and1);
7765                 }
7766             }
7767           if (change)
7768             {
7769               tem = force_fit_type (type, wi::to_widest (and1), 0,
7770                                     TREE_OVERFLOW (and1));
7771               return fold_build2_loc (loc, BIT_AND_EXPR, type,
7772                                       fold_convert_loc (loc, type, and0), tem);
7773             }
7774         }
7775
7776       /* Convert (T1)(X p+ Y) into ((T1)X p+ Y), for pointer type,
7777          when one of the new casts will fold away. Conservatively we assume
7778          that this happens when X or Y is NOP_EXPR or Y is INTEGER_CST. */
7779       if (POINTER_TYPE_P (type)
7780           && TREE_CODE (arg0) == POINTER_PLUS_EXPR
7781           && (!TYPE_RESTRICT (type) || TYPE_RESTRICT (TREE_TYPE (arg0)))
7782           && (TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
7783               || TREE_CODE (TREE_OPERAND (arg0, 0)) == NOP_EXPR
7784               || TREE_CODE (TREE_OPERAND (arg0, 1)) == NOP_EXPR))
7785         {
7786           tree arg00 = TREE_OPERAND (arg0, 0);
7787           tree arg01 = TREE_OPERAND (arg0, 1);
7788
7789           return fold_build_pointer_plus_loc
7790                    (loc, fold_convert_loc (loc, type, arg00), arg01);
7791         }
7792
7793       /* Convert (T1)(~(T2)X) into ~(T1)X if T1 and T2 are integral types
7794          of the same precision, and X is an integer type not narrower than
7795          types T1 or T2, i.e. the cast (T2)X isn't an extension.  */
7796       if (INTEGRAL_TYPE_P (type)
7797           && TREE_CODE (op0) == BIT_NOT_EXPR
7798           && INTEGRAL_TYPE_P (TREE_TYPE (op0))
7799           && CONVERT_EXPR_P (TREE_OPERAND (op0, 0))
7800           && TYPE_PRECISION (type) == TYPE_PRECISION (TREE_TYPE (op0)))
7801         {
7802           tem = TREE_OPERAND (TREE_OPERAND (op0, 0), 0);
7803           if (INTEGRAL_TYPE_P (TREE_TYPE (tem))
7804               && TYPE_PRECISION (type) <= TYPE_PRECISION (TREE_TYPE (tem)))
7805             return fold_build1_loc (loc, BIT_NOT_EXPR, type,
7806                                 fold_convert_loc (loc, type, tem));
7807         }
7808
7809       /* Convert (T1)(X * Y) into (T1)X * (T1)Y if T1 is narrower than the
7810          type of X and Y (integer types only).  */
7811       if (INTEGRAL_TYPE_P (type)
7812           && TREE_CODE (op0) == MULT_EXPR
7813           && INTEGRAL_TYPE_P (TREE_TYPE (op0))
7814           && TYPE_PRECISION (type) < TYPE_PRECISION (TREE_TYPE (op0)))
7815         {
7816           /* Be careful not to introduce new overflows.  */
7817           tree mult_type;
7818           if (TYPE_OVERFLOW_WRAPS (type))
7819             mult_type = type;
7820           else
7821             mult_type = unsigned_type_for (type);
7822
7823           if (TYPE_PRECISION (mult_type) < TYPE_PRECISION (TREE_TYPE (op0)))
7824             {
7825               tem = fold_build2_loc (loc, MULT_EXPR, mult_type,
7826                                  fold_convert_loc (loc, mult_type,
7827                                                    TREE_OPERAND (op0, 0)),
7828                                  fold_convert_loc (loc, mult_type,
7829                                                    TREE_OPERAND (op0, 1)));
7830               return fold_convert_loc (loc, type, tem);
7831             }
7832         }
7833
7834       return NULL_TREE;
7835
7836     case VIEW_CONVERT_EXPR:
7837       if (TREE_CODE (op0) == MEM_REF)
7838         return fold_build2_loc (loc, MEM_REF, type,
7839                                 TREE_OPERAND (op0, 0), TREE_OPERAND (op0, 1));
7840
7841       return NULL_TREE;
7842
7843     case NEGATE_EXPR:
7844       tem = fold_negate_expr (loc, arg0);
7845       if (tem)
7846         return fold_convert_loc (loc, type, tem);
7847       return NULL_TREE;
7848
7849     case ABS_EXPR:
7850       /* Convert fabs((double)float) into (double)fabsf(float).  */
7851       if (TREE_CODE (arg0) == NOP_EXPR
7852           && TREE_CODE (type) == REAL_TYPE)
7853         {
7854           tree targ0 = strip_float_extensions (arg0);
7855           if (targ0 != arg0)
7856             return fold_convert_loc (loc, type,
7857                                      fold_build1_loc (loc, ABS_EXPR,
7858                                                   TREE_TYPE (targ0),
7859                                                   targ0));
7860         }
7861       return NULL_TREE;
7862
7863     case BIT_NOT_EXPR:
7864       /* Convert ~(X ^ Y) to ~X ^ Y or X ^ ~Y if ~X or ~Y simplify.  */
7865       if (TREE_CODE (arg0) == BIT_XOR_EXPR
7866           && (tem = fold_unary_loc (loc, BIT_NOT_EXPR, type,
7867                                     fold_convert_loc (loc, type,
7868                                                       TREE_OPERAND (arg0, 0)))))
7869         return fold_build2_loc (loc, BIT_XOR_EXPR, type, tem,
7870                                 fold_convert_loc (loc, type,
7871                                                   TREE_OPERAND (arg0, 1)));
7872       else if (TREE_CODE (arg0) == BIT_XOR_EXPR
7873                && (tem = fold_unary_loc (loc, BIT_NOT_EXPR, type,
7874                                      fold_convert_loc (loc, type,
7875                                                        TREE_OPERAND (arg0, 1)))))
7876         return fold_build2_loc (loc, BIT_XOR_EXPR, type,
7877                             fold_convert_loc (loc, type,
7878                                               TREE_OPERAND (arg0, 0)), tem);
7879
7880       return NULL_TREE;
7881
7882     case TRUTH_NOT_EXPR:
7883       /* Note that the operand of this must be an int
7884          and its values must be 0 or 1.
7885          ("true" is a fixed value perhaps depending on the language,
7886          but we don't handle values other than 1 correctly yet.)  */
7887       tem = fold_truth_not_expr (loc, arg0);
7888       if (!tem)
7889         return NULL_TREE;
7890       return fold_convert_loc (loc, type, tem);
7891
7892     case INDIRECT_REF:
7893       /* Fold *&X to X if X is an lvalue.  */
7894       if (TREE_CODE (op0) == ADDR_EXPR)
7895         {
7896           tree op00 = TREE_OPERAND (op0, 0);
7897           if ((TREE_CODE (op00) == VAR_DECL
7898                || TREE_CODE (op00) == PARM_DECL
7899                || TREE_CODE (op00) == RESULT_DECL)
7900               && !TREE_READONLY (op00))
7901             return op00;
7902         }
7903       return NULL_TREE;
7904
7905     default:
7906       return NULL_TREE;
7907     } /* switch (code) */
7908 }
7909
7910
7911 /* If the operation was a conversion do _not_ mark a resulting constant
7912    with TREE_OVERFLOW if the original constant was not.  These conversions
7913    have implementation defined behavior and retaining the TREE_OVERFLOW
7914    flag here would confuse later passes such as VRP.  */
7915 tree
7916 fold_unary_ignore_overflow_loc (location_t loc, enum tree_code code,
7917                                 tree type, tree op0)
7918 {
7919   tree res = fold_unary_loc (loc, code, type, op0);
7920   if (res
7921       && TREE_CODE (res) == INTEGER_CST
7922       && TREE_CODE (op0) == INTEGER_CST
7923       && CONVERT_EXPR_CODE_P (code))
7924     TREE_OVERFLOW (res) = TREE_OVERFLOW (op0);
7925
7926   return res;
7927 }
7928
7929 /* Fold a binary bitwise/truth expression of code CODE and type TYPE with
7930    operands OP0 and OP1.  LOC is the location of the resulting expression.
7931    ARG0 and ARG1 are the NOP_STRIPed results of OP0 and OP1.
7932    Return the folded expression if folding is successful.  Otherwise,
7933    return NULL_TREE.  */
7934 static tree
7935 fold_truth_andor (location_t loc, enum tree_code code, tree type,
7936                   tree arg0, tree arg1, tree op0, tree op1)
7937 {
7938   tree tem;
7939
7940   /* We only do these simplifications if we are optimizing.  */
7941   if (!optimize)
7942     return NULL_TREE;
7943
7944   /* Check for things like (A || B) && (A || C).  We can convert this
7945      to A || (B && C).  Note that either operator can be any of the four
7946      truth and/or operations and the transformation will still be
7947      valid.   Also note that we only care about order for the
7948      ANDIF and ORIF operators.  If B contains side effects, this
7949      might change the truth-value of A.  */
7950   if (TREE_CODE (arg0) == TREE_CODE (arg1)
7951       && (TREE_CODE (arg0) == TRUTH_ANDIF_EXPR
7952           || TREE_CODE (arg0) == TRUTH_ORIF_EXPR
7953           || TREE_CODE (arg0) == TRUTH_AND_EXPR
7954           || TREE_CODE (arg0) == TRUTH_OR_EXPR)
7955       && ! TREE_SIDE_EFFECTS (TREE_OPERAND (arg0, 1)))
7956     {
7957       tree a00 = TREE_OPERAND (arg0, 0);
7958       tree a01 = TREE_OPERAND (arg0, 1);
7959       tree a10 = TREE_OPERAND (arg1, 0);
7960       tree a11 = TREE_OPERAND (arg1, 1);
7961       int commutative = ((TREE_CODE (arg0) == TRUTH_OR_EXPR
7962                           || TREE_CODE (arg0) == TRUTH_AND_EXPR)
7963                          && (code == TRUTH_AND_EXPR
7964                              || code == TRUTH_OR_EXPR));
7965
7966       if (operand_equal_p (a00, a10, 0))
7967         return fold_build2_loc (loc, TREE_CODE (arg0), type, a00,
7968                             fold_build2_loc (loc, code, type, a01, a11));
7969       else if (commutative && operand_equal_p (a00, a11, 0))
7970         return fold_build2_loc (loc, TREE_CODE (arg0), type, a00,
7971                             fold_build2_loc (loc, code, type, a01, a10));
7972       else if (commutative && operand_equal_p (a01, a10, 0))
7973         return fold_build2_loc (loc, TREE_CODE (arg0), type, a01,
7974                             fold_build2_loc (loc, code, type, a00, a11));
7975
7976       /* This case if tricky because we must either have commutative
7977          operators or else A10 must not have side-effects.  */
7978
7979       else if ((commutative || ! TREE_SIDE_EFFECTS (a10))
7980                && operand_equal_p (a01, a11, 0))
7981         return fold_build2_loc (loc, TREE_CODE (arg0), type,
7982                             fold_build2_loc (loc, code, type, a00, a10),
7983                             a01);
7984     }
7985
7986   /* See if we can build a range comparison.  */
7987   if (0 != (tem = fold_range_test (loc, code, type, op0, op1)))
7988     return tem;
7989
7990   if ((code == TRUTH_ANDIF_EXPR && TREE_CODE (arg0) == TRUTH_ORIF_EXPR)
7991       || (code == TRUTH_ORIF_EXPR && TREE_CODE (arg0) == TRUTH_ANDIF_EXPR))
7992     {
7993       tem = merge_truthop_with_opposite_arm (loc, arg0, arg1, true);
7994       if (tem)
7995         return fold_build2_loc (loc, code, type, tem, arg1);
7996     }
7997
7998   if ((code == TRUTH_ANDIF_EXPR && TREE_CODE (arg1) == TRUTH_ORIF_EXPR)
7999       || (code == TRUTH_ORIF_EXPR && TREE_CODE (arg1) == TRUTH_ANDIF_EXPR))
8000     {
8001       tem = merge_truthop_with_opposite_arm (loc, arg1, arg0, false);
8002       if (tem)
8003         return fold_build2_loc (loc, code, type, arg0, tem);
8004     }
8005
8006   /* Check for the possibility of merging component references.  If our
8007      lhs is another similar operation, try to merge its rhs with our
8008      rhs.  Then try to merge our lhs and rhs.  */
8009   if (TREE_CODE (arg0) == code
8010       && 0 != (tem = fold_truth_andor_1 (loc, code, type,
8011                                          TREE_OPERAND (arg0, 1), arg1)))
8012     return fold_build2_loc (loc, code, type, TREE_OPERAND (arg0, 0), tem);
8013
8014   if ((tem = fold_truth_andor_1 (loc, code, type, arg0, arg1)) != 0)
8015     return tem;
8016
8017   if (LOGICAL_OP_NON_SHORT_CIRCUIT
8018       && (code == TRUTH_AND_EXPR
8019           || code == TRUTH_ANDIF_EXPR
8020           || code == TRUTH_OR_EXPR
8021           || code == TRUTH_ORIF_EXPR))
8022     {
8023       enum tree_code ncode, icode;
8024
8025       ncode = (code == TRUTH_ANDIF_EXPR || code == TRUTH_AND_EXPR)
8026               ? TRUTH_AND_EXPR : TRUTH_OR_EXPR;
8027       icode = ncode == TRUTH_AND_EXPR ? TRUTH_ANDIF_EXPR : TRUTH_ORIF_EXPR;
8028
8029       /* Transform ((A AND-IF B) AND[-IF] C) into (A AND-IF (B AND C)),
8030          or ((A OR-IF B) OR[-IF] C) into (A OR-IF (B OR C))
8031          We don't want to pack more than two leafs to a non-IF AND/OR
8032          expression.
8033          If tree-code of left-hand operand isn't an AND/OR-IF code and not
8034          equal to IF-CODE, then we don't want to add right-hand operand.
8035          If the inner right-hand side of left-hand operand has
8036          side-effects, or isn't simple, then we can't add to it,
8037          as otherwise we might destroy if-sequence.  */
8038       if (TREE_CODE (arg0) == icode
8039           && simple_operand_p_2 (arg1)
8040           /* Needed for sequence points to handle trappings, and
8041              side-effects.  */
8042           && simple_operand_p_2 (TREE_OPERAND (arg0, 1)))
8043         {
8044           tem = fold_build2_loc (loc, ncode, type, TREE_OPERAND (arg0, 1),
8045                                  arg1);
8046           return fold_build2_loc (loc, icode, type, TREE_OPERAND (arg0, 0),
8047                                   tem);
8048         }
8049         /* Same as abouve but for (A AND[-IF] (B AND-IF C)) -> ((A AND B) AND-IF C),
8050            or (A OR[-IF] (B OR-IF C) -> ((A OR B) OR-IF C).  */
8051       else if (TREE_CODE (arg1) == icode
8052           && simple_operand_p_2 (arg0)
8053           /* Needed for sequence points to handle trappings, and
8054              side-effects.  */
8055           && simple_operand_p_2 (TREE_OPERAND (arg1, 0)))
8056         {
8057           tem = fold_build2_loc (loc, ncode, type, 
8058                                  arg0, TREE_OPERAND (arg1, 0));
8059           return fold_build2_loc (loc, icode, type, tem,
8060                                   TREE_OPERAND (arg1, 1));
8061         }
8062       /* Transform (A AND-IF B) into (A AND B), or (A OR-IF B)
8063          into (A OR B).
8064          For sequence point consistancy, we need to check for trapping,
8065          and side-effects.  */
8066       else if (code == icode && simple_operand_p_2 (arg0)
8067                && simple_operand_p_2 (arg1))
8068         return fold_build2_loc (loc, ncode, type, arg0, arg1);
8069     }
8070
8071   return NULL_TREE;
8072 }
8073
8074 /* Fold a binary expression of code CODE and type TYPE with operands
8075    OP0 and OP1, containing either a MIN-MAX or a MAX-MIN combination.
8076    Return the folded expression if folding is successful.  Otherwise,
8077    return NULL_TREE.  */
8078
8079 static tree
8080 fold_minmax (location_t loc, enum tree_code code, tree type, tree op0, tree op1)
8081 {
8082   enum tree_code compl_code;
8083
8084   if (code == MIN_EXPR)
8085     compl_code = MAX_EXPR;
8086   else if (code == MAX_EXPR)
8087     compl_code = MIN_EXPR;
8088   else
8089     gcc_unreachable ();
8090
8091   /* MIN (MAX (a, b), b) == b.  */
8092   if (TREE_CODE (op0) == compl_code
8093       && operand_equal_p (TREE_OPERAND (op0, 1), op1, 0))
8094     return omit_one_operand_loc (loc, type, op1, TREE_OPERAND (op0, 0));
8095
8096   /* MIN (MAX (b, a), b) == b.  */
8097   if (TREE_CODE (op0) == compl_code
8098       && operand_equal_p (TREE_OPERAND (op0, 0), op1, 0)
8099       && reorder_operands_p (TREE_OPERAND (op0, 1), op1))
8100     return omit_one_operand_loc (loc, type, op1, TREE_OPERAND (op0, 1));
8101
8102   /* MIN (a, MAX (a, b)) == a.  */
8103   if (TREE_CODE (op1) == compl_code
8104       && operand_equal_p (op0, TREE_OPERAND (op1, 0), 0)
8105       && reorder_operands_p (op0, TREE_OPERAND (op1, 1)))
8106     return omit_one_operand_loc (loc, type, op0, TREE_OPERAND (op1, 1));
8107
8108   /* MIN (a, MAX (b, a)) == a.  */
8109   if (TREE_CODE (op1) == compl_code
8110       && operand_equal_p (op0, TREE_OPERAND (op1, 1), 0)
8111       && reorder_operands_p (op0, TREE_OPERAND (op1, 0)))
8112     return omit_one_operand_loc (loc, type, op0, TREE_OPERAND (op1, 0));
8113
8114   return NULL_TREE;
8115 }
8116
8117 /* Helper that tries to canonicalize the comparison ARG0 CODE ARG1
8118    by changing CODE to reduce the magnitude of constants involved in
8119    ARG0 of the comparison.
8120    Returns a canonicalized comparison tree if a simplification was
8121    possible, otherwise returns NULL_TREE.
8122    Set *STRICT_OVERFLOW_P to true if the canonicalization is only
8123    valid if signed overflow is undefined.  */
8124
8125 static tree
8126 maybe_canonicalize_comparison_1 (location_t loc, enum tree_code code, tree type,
8127                                  tree arg0, tree arg1,
8128                                  bool *strict_overflow_p)
8129 {
8130   enum tree_code code0 = TREE_CODE (arg0);
8131   tree t, cst0 = NULL_TREE;
8132   int sgn0;
8133
8134   /* Match A +- CST code arg1.  We can change this only if overflow
8135      is undefined.  */
8136   if (!((ANY_INTEGRAL_TYPE_P (TREE_TYPE (arg0))
8137          && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg0)))
8138         /* In principle pointers also have undefined overflow behavior,
8139            but that causes problems elsewhere.  */
8140         && !POINTER_TYPE_P (TREE_TYPE (arg0))
8141         && (code0 == MINUS_EXPR
8142             || code0 == PLUS_EXPR)
8143         && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST))
8144     return NULL_TREE;
8145
8146   /* Identify the constant in arg0 and its sign.  */
8147   cst0 = TREE_OPERAND (arg0, 1);
8148   sgn0 = tree_int_cst_sgn (cst0);
8149
8150   /* Overflowed constants and zero will cause problems.  */
8151   if (integer_zerop (cst0)
8152       || TREE_OVERFLOW (cst0))
8153     return NULL_TREE;
8154
8155   /* See if we can reduce the magnitude of the constant in
8156      arg0 by changing the comparison code.  */
8157   /* A - CST < arg1  ->  A - CST-1 <= arg1.  */
8158   if (code == LT_EXPR
8159       && code0 == ((sgn0 == -1) ? PLUS_EXPR : MINUS_EXPR))
8160     code = LE_EXPR;
8161   /* A + CST > arg1  ->  A + CST-1 >= arg1.  */
8162   else if (code == GT_EXPR
8163            && code0 == ((sgn0 == -1) ? MINUS_EXPR : PLUS_EXPR))
8164     code = GE_EXPR;
8165   /* A + CST <= arg1  ->  A + CST-1 < arg1.  */
8166   else if (code == LE_EXPR
8167            && code0 == ((sgn0 == -1) ? MINUS_EXPR : PLUS_EXPR))
8168     code = LT_EXPR;
8169   /* A - CST >= arg1  ->  A - CST-1 > arg1.  */
8170   else if (code == GE_EXPR
8171            && code0 == ((sgn0 == -1) ? PLUS_EXPR : MINUS_EXPR))
8172     code = GT_EXPR;
8173   else
8174     return NULL_TREE;
8175   *strict_overflow_p = true;
8176
8177   /* Now build the constant reduced in magnitude.  But not if that
8178      would produce one outside of its types range.  */
8179   if (INTEGRAL_TYPE_P (TREE_TYPE (cst0))
8180       && ((sgn0 == 1
8181            && TYPE_MIN_VALUE (TREE_TYPE (cst0))
8182            && tree_int_cst_equal (cst0, TYPE_MIN_VALUE (TREE_TYPE (cst0))))
8183           || (sgn0 == -1
8184               && TYPE_MAX_VALUE (TREE_TYPE (cst0))
8185               && tree_int_cst_equal (cst0, TYPE_MAX_VALUE (TREE_TYPE (cst0))))))
8186     return NULL_TREE;
8187
8188   t = int_const_binop (sgn0 == -1 ? PLUS_EXPR : MINUS_EXPR,
8189                        cst0, build_int_cst (TREE_TYPE (cst0), 1));
8190   t = fold_build2_loc (loc, code0, TREE_TYPE (arg0), TREE_OPERAND (arg0, 0), t);
8191   t = fold_convert (TREE_TYPE (arg1), t);
8192
8193   return fold_build2_loc (loc, code, type, t, arg1);
8194 }
8195
8196 /* Canonicalize the comparison ARG0 CODE ARG1 with type TYPE with undefined
8197    overflow further.  Try to decrease the magnitude of constants involved
8198    by changing LE_EXPR and GE_EXPR to LT_EXPR and GT_EXPR or vice versa
8199    and put sole constants at the second argument position.
8200    Returns the canonicalized tree if changed, otherwise NULL_TREE.  */
8201
8202 static tree
8203 maybe_canonicalize_comparison (location_t loc, enum tree_code code, tree type,
8204                                tree arg0, tree arg1)
8205 {
8206   tree t;
8207   bool strict_overflow_p;
8208   const char * const warnmsg = G_("assuming signed overflow does not occur "
8209                                   "when reducing constant in comparison");
8210
8211   /* Try canonicalization by simplifying arg0.  */
8212   strict_overflow_p = false;
8213   t = maybe_canonicalize_comparison_1 (loc, code, type, arg0, arg1,
8214                                        &strict_overflow_p);
8215   if (t)
8216     {
8217       if (strict_overflow_p)
8218         fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_MAGNITUDE);
8219       return t;
8220     }
8221
8222   /* Try canonicalization by simplifying arg1 using the swapped
8223      comparison.  */
8224   code = swap_tree_comparison (code);
8225   strict_overflow_p = false;
8226   t = maybe_canonicalize_comparison_1 (loc, code, type, arg1, arg0,
8227                                        &strict_overflow_p);
8228   if (t && strict_overflow_p)
8229     fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_MAGNITUDE);
8230   return t;
8231 }
8232
8233 /* Return whether BASE + OFFSET + BITPOS may wrap around the address
8234    space.  This is used to avoid issuing overflow warnings for
8235    expressions like &p->x which can not wrap.  */
8236
8237 static bool
8238 pointer_may_wrap_p (tree base, tree offset, HOST_WIDE_INT bitpos)
8239 {
8240   if (!POINTER_TYPE_P (TREE_TYPE (base)))
8241     return true;
8242
8243   if (bitpos < 0)
8244     return true;
8245
8246   wide_int wi_offset;
8247   int precision = TYPE_PRECISION (TREE_TYPE (base));
8248   if (offset == NULL_TREE)
8249     wi_offset = wi::zero (precision);
8250   else if (TREE_CODE (offset) != INTEGER_CST || TREE_OVERFLOW (offset))
8251     return true;
8252   else
8253     wi_offset = offset;
8254
8255   bool overflow;
8256   wide_int units = wi::shwi (bitpos / BITS_PER_UNIT, precision);
8257   wide_int total = wi::add (wi_offset, units, UNSIGNED, &overflow);
8258   if (overflow)
8259     return true;
8260
8261   if (!wi::fits_uhwi_p (total))
8262     return true;
8263
8264   HOST_WIDE_INT size = int_size_in_bytes (TREE_TYPE (TREE_TYPE (base)));
8265   if (size <= 0)
8266     return true;
8267
8268   /* We can do slightly better for SIZE if we have an ADDR_EXPR of an
8269      array.  */
8270   if (TREE_CODE (base) == ADDR_EXPR)
8271     {
8272       HOST_WIDE_INT base_size;
8273
8274       base_size = int_size_in_bytes (TREE_TYPE (TREE_OPERAND (base, 0)));
8275       if (base_size > 0 && size < base_size)
8276         size = base_size;
8277     }
8278
8279   return total.to_uhwi () > (unsigned HOST_WIDE_INT) size;
8280 }
8281
8282 /* Return the HOST_WIDE_INT least significant bits of T, a sizetype
8283    kind INTEGER_CST.  This makes sure to properly sign-extend the
8284    constant.  */
8285
8286 static HOST_WIDE_INT
8287 size_low_cst (const_tree t)
8288 {
8289   HOST_WIDE_INT w = TREE_INT_CST_ELT (t, 0);
8290   int prec = TYPE_PRECISION (TREE_TYPE (t));
8291   if (prec < HOST_BITS_PER_WIDE_INT)
8292     return sext_hwi (w, prec);
8293   return w;
8294 }
8295
8296 /* Subroutine of fold_binary.  This routine performs all of the
8297    transformations that are common to the equality/inequality
8298    operators (EQ_EXPR and NE_EXPR) and the ordering operators
8299    (LT_EXPR, LE_EXPR, GE_EXPR and GT_EXPR).  Callers other than
8300    fold_binary should call fold_binary.  Fold a comparison with
8301    tree code CODE and type TYPE with operands OP0 and OP1.  Return
8302    the folded comparison or NULL_TREE.  */
8303
8304 static tree
8305 fold_comparison (location_t loc, enum tree_code code, tree type,
8306                  tree op0, tree op1)
8307 {
8308   const bool equality_code = (code == EQ_EXPR || code == NE_EXPR);
8309   tree arg0, arg1, tem;
8310
8311   arg0 = op0;
8312   arg1 = op1;
8313
8314   STRIP_SIGN_NOPS (arg0);
8315   STRIP_SIGN_NOPS (arg1);
8316
8317   /* Transform comparisons of the form X +- C1 CMP C2 to X CMP C2 -+ C1.  */
8318   if ((TREE_CODE (arg0) == PLUS_EXPR || TREE_CODE (arg0) == MINUS_EXPR)
8319       && (equality_code
8320           || (ANY_INTEGRAL_TYPE_P (TREE_TYPE (arg0))
8321               && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg0))))
8322       && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
8323       && !TREE_OVERFLOW (TREE_OPERAND (arg0, 1))
8324       && TREE_CODE (arg1) == INTEGER_CST
8325       && !TREE_OVERFLOW (arg1))
8326     {
8327       const enum tree_code
8328         reverse_op = TREE_CODE (arg0) == PLUS_EXPR ? MINUS_EXPR : PLUS_EXPR;
8329       tree const1 = TREE_OPERAND (arg0, 1);
8330       tree const2 = fold_convert_loc (loc, TREE_TYPE (const1), arg1);
8331       tree variable = TREE_OPERAND (arg0, 0);
8332       tree new_const = int_const_binop (reverse_op, const2, const1);
8333
8334       /* If the constant operation overflowed this can be
8335          simplified as a comparison against INT_MAX/INT_MIN.  */
8336       if (TREE_OVERFLOW (new_const)
8337           && !TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg0)))
8338         {
8339           int const1_sgn = tree_int_cst_sgn (const1);
8340           enum tree_code code2 = code;
8341
8342           /* Get the sign of the constant on the lhs if the
8343              operation were VARIABLE + CONST1.  */
8344           if (TREE_CODE (arg0) == MINUS_EXPR)
8345             const1_sgn = -const1_sgn;
8346
8347           /* The sign of the constant determines if we overflowed
8348              INT_MAX (const1_sgn == -1) or INT_MIN (const1_sgn == 1).
8349              Canonicalize to the INT_MIN overflow by swapping the comparison
8350              if necessary.  */
8351           if (const1_sgn == -1)
8352             code2 = swap_tree_comparison (code);
8353
8354           /* We now can look at the canonicalized case
8355                VARIABLE + 1  CODE2  INT_MIN
8356              and decide on the result.  */
8357           switch (code2)
8358             {
8359             case EQ_EXPR:
8360             case LT_EXPR:
8361             case LE_EXPR:
8362               return
8363                 omit_one_operand_loc (loc, type, boolean_false_node, variable);
8364
8365             case NE_EXPR:
8366             case GE_EXPR:
8367             case GT_EXPR:
8368               return
8369                 omit_one_operand_loc (loc, type, boolean_true_node, variable);
8370
8371             default:
8372               gcc_unreachable ();
8373             }
8374         }
8375       else
8376         {
8377           if (!equality_code)
8378             fold_overflow_warning ("assuming signed overflow does not occur "
8379                                    "when changing X +- C1 cmp C2 to "
8380                                    "X cmp C2 -+ C1",
8381                                    WARN_STRICT_OVERFLOW_COMPARISON);
8382           return fold_build2_loc (loc, code, type, variable, new_const);
8383         }
8384     }
8385
8386   /* For comparisons of pointers we can decompose it to a compile time
8387      comparison of the base objects and the offsets into the object.
8388      This requires at least one operand being an ADDR_EXPR or a
8389      POINTER_PLUS_EXPR to do more than the operand_equal_p test below.  */
8390   if (POINTER_TYPE_P (TREE_TYPE (arg0))
8391       && (TREE_CODE (arg0) == ADDR_EXPR
8392           || TREE_CODE (arg1) == ADDR_EXPR
8393           || TREE_CODE (arg0) == POINTER_PLUS_EXPR
8394           || TREE_CODE (arg1) == POINTER_PLUS_EXPR))
8395     {
8396       tree base0, base1, offset0 = NULL_TREE, offset1 = NULL_TREE;
8397       HOST_WIDE_INT bitsize, bitpos0 = 0, bitpos1 = 0;
8398       machine_mode mode;
8399       int volatilep, unsignedp;
8400       bool indirect_base0 = false, indirect_base1 = false;
8401
8402       /* Get base and offset for the access.  Strip ADDR_EXPR for
8403          get_inner_reference, but put it back by stripping INDIRECT_REF
8404          off the base object if possible.  indirect_baseN will be true
8405          if baseN is not an address but refers to the object itself.  */
8406       base0 = arg0;
8407       if (TREE_CODE (arg0) == ADDR_EXPR)
8408         {
8409           base0 = get_inner_reference (TREE_OPERAND (arg0, 0),
8410                                        &bitsize, &bitpos0, &offset0, &mode,
8411                                        &unsignedp, &volatilep, false);
8412           if (TREE_CODE (base0) == INDIRECT_REF)
8413             base0 = TREE_OPERAND (base0, 0);
8414           else
8415             indirect_base0 = true;
8416         }
8417       else if (TREE_CODE (arg0) == POINTER_PLUS_EXPR)
8418         {
8419           base0 = TREE_OPERAND (arg0, 0);
8420           STRIP_SIGN_NOPS (base0);
8421           if (TREE_CODE (base0) == ADDR_EXPR)
8422             {
8423               base0 = TREE_OPERAND (base0, 0);
8424               indirect_base0 = true;
8425             }
8426           offset0 = TREE_OPERAND (arg0, 1);
8427           if (tree_fits_shwi_p (offset0))
8428             {
8429               HOST_WIDE_INT off = size_low_cst (offset0);
8430               if ((HOST_WIDE_INT) (((unsigned HOST_WIDE_INT) off)
8431                                    * BITS_PER_UNIT)
8432                   / BITS_PER_UNIT == (HOST_WIDE_INT) off)
8433                 {
8434                   bitpos0 = off * BITS_PER_UNIT;
8435                   offset0 = NULL_TREE;
8436                 }
8437             }
8438         }
8439
8440       base1 = arg1;
8441       if (TREE_CODE (arg1) == ADDR_EXPR)
8442         {
8443           base1 = get_inner_reference (TREE_OPERAND (arg1, 0),
8444                                        &bitsize, &bitpos1, &offset1, &mode,
8445                                        &unsignedp, &volatilep, false);
8446           if (TREE_CODE (base1) == INDIRECT_REF)
8447             base1 = TREE_OPERAND (base1, 0);
8448           else
8449             indirect_base1 = true;
8450         }
8451       else if (TREE_CODE (arg1) == POINTER_PLUS_EXPR)
8452         {
8453           base1 = TREE_OPERAND (arg1, 0);
8454           STRIP_SIGN_NOPS (base1);
8455           if (TREE_CODE (base1) == ADDR_EXPR)
8456             {
8457               base1 = TREE_OPERAND (base1, 0);
8458               indirect_base1 = true;
8459             }
8460           offset1 = TREE_OPERAND (arg1, 1);
8461           if (tree_fits_shwi_p (offset1))
8462             {
8463               HOST_WIDE_INT off = size_low_cst (offset1);
8464               if ((HOST_WIDE_INT) (((unsigned HOST_WIDE_INT) off)
8465                                    * BITS_PER_UNIT)
8466                   / BITS_PER_UNIT == (HOST_WIDE_INT) off)
8467                 {
8468                   bitpos1 = off * BITS_PER_UNIT;
8469                   offset1 = NULL_TREE;
8470                 }
8471             }
8472         }
8473
8474       /* If we have equivalent bases we might be able to simplify.  */
8475       if (indirect_base0 == indirect_base1
8476           && operand_equal_p (base0, base1,
8477                               indirect_base0 ? OEP_ADDRESS_OF : 0))
8478         {
8479           /* We can fold this expression to a constant if the non-constant
8480              offset parts are equal.  */
8481           if ((offset0 == offset1
8482                || (offset0 && offset1
8483                    && operand_equal_p (offset0, offset1, 0)))
8484               && (code == EQ_EXPR
8485                   || code == NE_EXPR
8486                   || (indirect_base0 && DECL_P (base0))
8487                   || POINTER_TYPE_OVERFLOW_UNDEFINED))
8488
8489             {
8490               if (!equality_code
8491                   && bitpos0 != bitpos1
8492                   && (pointer_may_wrap_p (base0, offset0, bitpos0)
8493                       || pointer_may_wrap_p (base1, offset1, bitpos1)))
8494                 fold_overflow_warning (("assuming pointer wraparound does not "
8495                                         "occur when comparing P +- C1 with "
8496                                         "P +- C2"),
8497                                        WARN_STRICT_OVERFLOW_CONDITIONAL);
8498
8499               switch (code)
8500                 {
8501                 case EQ_EXPR:
8502                   return constant_boolean_node (bitpos0 == bitpos1, type);
8503                 case NE_EXPR:
8504                   return constant_boolean_node (bitpos0 != bitpos1, type);
8505                 case LT_EXPR:
8506                   return constant_boolean_node (bitpos0 < bitpos1, type);
8507                 case LE_EXPR:
8508                   return constant_boolean_node (bitpos0 <= bitpos1, type);
8509                 case GE_EXPR:
8510                   return constant_boolean_node (bitpos0 >= bitpos1, type);
8511                 case GT_EXPR:
8512                   return constant_boolean_node (bitpos0 > bitpos1, type);
8513                 default:;
8514                 }
8515             }
8516           /* We can simplify the comparison to a comparison of the variable
8517              offset parts if the constant offset parts are equal.
8518              Be careful to use signed sizetype here because otherwise we
8519              mess with array offsets in the wrong way.  This is possible
8520              because pointer arithmetic is restricted to retain within an
8521              object and overflow on pointer differences is undefined as of
8522              6.5.6/8 and /9 with respect to the signed ptrdiff_t.  */
8523           else if (bitpos0 == bitpos1
8524                    && (equality_code
8525                        || (indirect_base0 && DECL_P (base0))
8526                        || POINTER_TYPE_OVERFLOW_UNDEFINED))
8527             {
8528               /* By converting to signed sizetype we cover middle-end pointer
8529                  arithmetic which operates on unsigned pointer types of size
8530                  type size and ARRAY_REF offsets which are properly sign or
8531                  zero extended from their type in case it is narrower than
8532                  sizetype.  */
8533               if (offset0 == NULL_TREE)
8534                 offset0 = build_int_cst (ssizetype, 0);
8535               else
8536                 offset0 = fold_convert_loc (loc, ssizetype, offset0);
8537               if (offset1 == NULL_TREE)
8538                 offset1 = build_int_cst (ssizetype, 0);
8539               else
8540                 offset1 = fold_convert_loc (loc, ssizetype, offset1);
8541
8542               if (!equality_code
8543                   && (pointer_may_wrap_p (base0, offset0, bitpos0)
8544                       || pointer_may_wrap_p (base1, offset1, bitpos1)))
8545                 fold_overflow_warning (("assuming pointer wraparound does not "
8546                                         "occur when comparing P +- C1 with "
8547                                         "P +- C2"),
8548                                        WARN_STRICT_OVERFLOW_COMPARISON);
8549
8550               return fold_build2_loc (loc, code, type, offset0, offset1);
8551             }
8552         }
8553       /* For equal offsets we can simplify to a comparison of the
8554          base addresses.  */
8555       else if (bitpos0 == bitpos1
8556                && (indirect_base0
8557                    ? base0 != TREE_OPERAND (arg0, 0) : base0 != arg0)
8558                && (indirect_base1
8559                    ? base1 != TREE_OPERAND (arg1, 0) : base1 != arg1)
8560                && ((offset0 == offset1)
8561                    || (offset0 && offset1
8562                        && operand_equal_p (offset0, offset1, 0))))
8563         {
8564           if (indirect_base0)
8565             base0 = build_fold_addr_expr_loc (loc, base0);
8566           if (indirect_base1)
8567             base1 = build_fold_addr_expr_loc (loc, base1);
8568           return fold_build2_loc (loc, code, type, base0, base1);
8569         }
8570     }
8571
8572   /* Transform comparisons of the form X +- C1 CMP Y +- C2 to
8573      X CMP Y +- C2 +- C1 for signed X, Y.  This is valid if
8574      the resulting offset is smaller in absolute value than the
8575      original one and has the same sign.  */
8576   if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (arg0))
8577       && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg0))
8578       && (TREE_CODE (arg0) == PLUS_EXPR || TREE_CODE (arg0) == MINUS_EXPR)
8579       && (TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
8580           && !TREE_OVERFLOW (TREE_OPERAND (arg0, 1)))
8581       && (TREE_CODE (arg1) == PLUS_EXPR || TREE_CODE (arg1) == MINUS_EXPR)
8582       && (TREE_CODE (TREE_OPERAND (arg1, 1)) == INTEGER_CST
8583           && !TREE_OVERFLOW (TREE_OPERAND (arg1, 1))))
8584     {
8585       tree const1 = TREE_OPERAND (arg0, 1);
8586       tree const2 = TREE_OPERAND (arg1, 1);
8587       tree variable1 = TREE_OPERAND (arg0, 0);
8588       tree variable2 = TREE_OPERAND (arg1, 0);
8589       tree cst;
8590       const char * const warnmsg = G_("assuming signed overflow does not "
8591                                       "occur when combining constants around "
8592                                       "a comparison");
8593
8594       /* Put the constant on the side where it doesn't overflow and is
8595          of lower absolute value and of same sign than before.  */
8596       cst = int_const_binop (TREE_CODE (arg0) == TREE_CODE (arg1)
8597                              ? MINUS_EXPR : PLUS_EXPR,
8598                              const2, const1);
8599       if (!TREE_OVERFLOW (cst)
8600           && tree_int_cst_compare (const2, cst) == tree_int_cst_sgn (const2)
8601           && tree_int_cst_sgn (cst) == tree_int_cst_sgn (const2))
8602         {
8603           fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_COMPARISON);
8604           return fold_build2_loc (loc, code, type,
8605                                   variable1,
8606                                   fold_build2_loc (loc, TREE_CODE (arg1),
8607                                                    TREE_TYPE (arg1),
8608                                                    variable2, cst));
8609         }
8610
8611       cst = int_const_binop (TREE_CODE (arg0) == TREE_CODE (arg1)
8612                              ? MINUS_EXPR : PLUS_EXPR,
8613                              const1, const2);
8614       if (!TREE_OVERFLOW (cst)
8615           && tree_int_cst_compare (const1, cst) == tree_int_cst_sgn (const1)
8616           && tree_int_cst_sgn (cst) == tree_int_cst_sgn (const1))
8617         {
8618           fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_COMPARISON);
8619           return fold_build2_loc (loc, code, type,
8620                                   fold_build2_loc (loc, TREE_CODE (arg0),
8621                                                    TREE_TYPE (arg0),
8622                                                    variable1, cst),
8623                                   variable2);
8624         }
8625     }
8626
8627   tem = maybe_canonicalize_comparison (loc, code, type, arg0, arg1);
8628   if (tem)
8629     return tem;
8630
8631   /* If this is comparing a constant with a MIN_EXPR or a MAX_EXPR of a
8632      constant, we can simplify it.  */
8633   if (TREE_CODE (arg1) == INTEGER_CST
8634       && (TREE_CODE (arg0) == MIN_EXPR
8635           || TREE_CODE (arg0) == MAX_EXPR)
8636       && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
8637     {
8638       tem = optimize_minmax_comparison (loc, code, type, op0, op1);
8639       if (tem)
8640         return tem;
8641     }
8642
8643   /* If we are comparing an expression that just has comparisons
8644      of two integer values, arithmetic expressions of those comparisons,
8645      and constants, we can simplify it.  There are only three cases
8646      to check: the two values can either be equal, the first can be
8647      greater, or the second can be greater.  Fold the expression for
8648      those three values.  Since each value must be 0 or 1, we have
8649      eight possibilities, each of which corresponds to the constant 0
8650      or 1 or one of the six possible comparisons.
8651
8652      This handles common cases like (a > b) == 0 but also handles
8653      expressions like  ((x > y) - (y > x)) > 0, which supposedly
8654      occur in macroized code.  */
8655
8656   if (TREE_CODE (arg1) == INTEGER_CST && TREE_CODE (arg0) != INTEGER_CST)
8657     {
8658       tree cval1 = 0, cval2 = 0;
8659       int save_p = 0;
8660
8661       if (twoval_comparison_p (arg0, &cval1, &cval2, &save_p)
8662           /* Don't handle degenerate cases here; they should already
8663              have been handled anyway.  */
8664           && cval1 != 0 && cval2 != 0
8665           && ! (TREE_CONSTANT (cval1) && TREE_CONSTANT (cval2))
8666           && TREE_TYPE (cval1) == TREE_TYPE (cval2)
8667           && INTEGRAL_TYPE_P (TREE_TYPE (cval1))
8668           && TYPE_MAX_VALUE (TREE_TYPE (cval1))
8669           && TYPE_MAX_VALUE (TREE_TYPE (cval2))
8670           && ! operand_equal_p (TYPE_MIN_VALUE (TREE_TYPE (cval1)),
8671                                 TYPE_MAX_VALUE (TREE_TYPE (cval2)), 0))
8672         {
8673           tree maxval = TYPE_MAX_VALUE (TREE_TYPE (cval1));
8674           tree minval = TYPE_MIN_VALUE (TREE_TYPE (cval1));
8675
8676           /* We can't just pass T to eval_subst in case cval1 or cval2
8677              was the same as ARG1.  */
8678
8679           tree high_result
8680                 = fold_build2_loc (loc, code, type,
8681                                eval_subst (loc, arg0, cval1, maxval,
8682                                            cval2, minval),
8683                                arg1);
8684           tree equal_result
8685                 = fold_build2_loc (loc, code, type,
8686                                eval_subst (loc, arg0, cval1, maxval,
8687                                            cval2, maxval),
8688                                arg1);
8689           tree low_result
8690                 = fold_build2_loc (loc, code, type,
8691                                eval_subst (loc, arg0, cval1, minval,
8692                                            cval2, maxval),
8693                                arg1);
8694
8695           /* All three of these results should be 0 or 1.  Confirm they are.
8696              Then use those values to select the proper code to use.  */
8697
8698           if (TREE_CODE (high_result) == INTEGER_CST
8699               && TREE_CODE (equal_result) == INTEGER_CST
8700               && TREE_CODE (low_result) == INTEGER_CST)
8701             {
8702               /* Make a 3-bit mask with the high-order bit being the
8703                  value for `>', the next for '=', and the low for '<'.  */
8704               switch ((integer_onep (high_result) * 4)
8705                       + (integer_onep (equal_result) * 2)
8706                       + integer_onep (low_result))
8707                 {
8708                 case 0:
8709                   /* Always false.  */
8710                   return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
8711                 case 1:
8712                   code = LT_EXPR;
8713                   break;
8714                 case 2:
8715                   code = EQ_EXPR;
8716                   break;
8717                 case 3:
8718                   code = LE_EXPR;
8719                   break;
8720                 case 4:
8721                   code = GT_EXPR;
8722                   break;
8723                 case 5:
8724                   code = NE_EXPR;
8725                   break;
8726                 case 6:
8727                   code = GE_EXPR;
8728                   break;
8729                 case 7:
8730                   /* Always true.  */
8731                   return omit_one_operand_loc (loc, type, integer_one_node, arg0);
8732                 }
8733
8734               if (save_p)
8735                 {
8736                   tem = save_expr (build2 (code, type, cval1, cval2));
8737                   SET_EXPR_LOCATION (tem, loc);
8738                   return tem;
8739                 }
8740               return fold_build2_loc (loc, code, type, cval1, cval2);
8741             }
8742         }
8743     }
8744
8745   /* We can fold X/C1 op C2 where C1 and C2 are integer constants
8746      into a single range test.  */
8747   if ((TREE_CODE (arg0) == TRUNC_DIV_EXPR
8748        || TREE_CODE (arg0) == EXACT_DIV_EXPR)
8749       && TREE_CODE (arg1) == INTEGER_CST
8750       && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
8751       && !integer_zerop (TREE_OPERAND (arg0, 1))
8752       && !TREE_OVERFLOW (TREE_OPERAND (arg0, 1))
8753       && !TREE_OVERFLOW (arg1))
8754     {
8755       tem = fold_div_compare (loc, code, type, arg0, arg1);
8756       if (tem != NULL_TREE)
8757         return tem;
8758     }
8759
8760   return NULL_TREE;
8761 }
8762
8763
8764 /* Subroutine of fold_binary.  Optimize complex multiplications of the
8765    form z * conj(z), as pow(realpart(z),2) + pow(imagpart(z),2).  The
8766    argument EXPR represents the expression "z" of type TYPE.  */
8767
8768 static tree
8769 fold_mult_zconjz (location_t loc, tree type, tree expr)
8770 {
8771   tree itype = TREE_TYPE (type);
8772   tree rpart, ipart, tem;
8773
8774   if (TREE_CODE (expr) == COMPLEX_EXPR)
8775     {
8776       rpart = TREE_OPERAND (expr, 0);
8777       ipart = TREE_OPERAND (expr, 1);
8778     }
8779   else if (TREE_CODE (expr) == COMPLEX_CST)
8780     {
8781       rpart = TREE_REALPART (expr);
8782       ipart = TREE_IMAGPART (expr);
8783     }
8784   else
8785     {
8786       expr = save_expr (expr);
8787       rpart = fold_build1_loc (loc, REALPART_EXPR, itype, expr);
8788       ipart = fold_build1_loc (loc, IMAGPART_EXPR, itype, expr);
8789     }
8790
8791   rpart = save_expr (rpart);
8792   ipart = save_expr (ipart);
8793   tem = fold_build2_loc (loc, PLUS_EXPR, itype,
8794                      fold_build2_loc (loc, MULT_EXPR, itype, rpart, rpart),
8795                      fold_build2_loc (loc, MULT_EXPR, itype, ipart, ipart));
8796   return fold_build2_loc (loc, COMPLEX_EXPR, type, tem,
8797                           build_zero_cst (itype));
8798 }
8799
8800
8801 /* Helper function for fold_vec_perm.  Store elements of VECTOR_CST or
8802    CONSTRUCTOR ARG into array ELTS and return true if successful.  */
8803
8804 static bool
8805 vec_cst_ctor_to_array (tree arg, tree *elts)
8806 {
8807   unsigned int nelts = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg)), i;
8808
8809   if (TREE_CODE (arg) == VECTOR_CST)
8810     {
8811       for (i = 0; i < VECTOR_CST_NELTS (arg); ++i)
8812         elts[i] = VECTOR_CST_ELT (arg, i);
8813     }
8814   else if (TREE_CODE (arg) == CONSTRUCTOR)
8815     {
8816       constructor_elt *elt;
8817
8818       FOR_EACH_VEC_SAFE_ELT (CONSTRUCTOR_ELTS (arg), i, elt)
8819         if (i >= nelts || TREE_CODE (TREE_TYPE (elt->value)) == VECTOR_TYPE)
8820           return false;
8821         else
8822           elts[i] = elt->value;
8823     }
8824   else
8825     return false;
8826   for (; i < nelts; i++)
8827     elts[i]
8828       = fold_convert (TREE_TYPE (TREE_TYPE (arg)), integer_zero_node);
8829   return true;
8830 }
8831
8832 /* Attempt to fold vector permutation of ARG0 and ARG1 vectors using SEL
8833    selector.  Return the folded VECTOR_CST or CONSTRUCTOR if successful,
8834    NULL_TREE otherwise.  */
8835
8836 static tree
8837 fold_vec_perm (tree type, tree arg0, tree arg1, const unsigned char *sel)
8838 {
8839   unsigned int nelts = TYPE_VECTOR_SUBPARTS (type), i;
8840   tree *elts;
8841   bool need_ctor = false;
8842
8843   gcc_assert (TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0)) == nelts
8844               && TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg1)) == nelts);
8845   if (TREE_TYPE (TREE_TYPE (arg0)) != TREE_TYPE (type)
8846       || TREE_TYPE (TREE_TYPE (arg1)) != TREE_TYPE (type))
8847     return NULL_TREE;
8848
8849   elts = XALLOCAVEC (tree, nelts * 3);
8850   if (!vec_cst_ctor_to_array (arg0, elts)
8851       || !vec_cst_ctor_to_array (arg1, elts + nelts))
8852     return NULL_TREE;
8853
8854   for (i = 0; i < nelts; i++)
8855     {
8856       if (!CONSTANT_CLASS_P (elts[sel[i]]))
8857         need_ctor = true;
8858       elts[i + 2 * nelts] = unshare_expr (elts[sel[i]]);
8859     }
8860
8861   if (need_ctor)
8862     {
8863       vec<constructor_elt, va_gc> *v;
8864       vec_alloc (v, nelts);
8865       for (i = 0; i < nelts; i++)
8866         CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, elts[2 * nelts + i]);
8867       return build_constructor (type, v);
8868     }
8869   else
8870     return build_vector (type, &elts[2 * nelts]);
8871 }
8872
8873 /* Try to fold a pointer difference of type TYPE two address expressions of
8874    array references AREF0 and AREF1 using location LOC.  Return a
8875    simplified expression for the difference or NULL_TREE.  */
8876
8877 static tree
8878 fold_addr_of_array_ref_difference (location_t loc, tree type,
8879                                    tree aref0, tree aref1)
8880 {
8881   tree base0 = TREE_OPERAND (aref0, 0);
8882   tree base1 = TREE_OPERAND (aref1, 0);
8883   tree base_offset = build_int_cst (type, 0);
8884
8885   /* If the bases are array references as well, recurse.  If the bases
8886      are pointer indirections compute the difference of the pointers.
8887      If the bases are equal, we are set.  */
8888   if ((TREE_CODE (base0) == ARRAY_REF
8889        && TREE_CODE (base1) == ARRAY_REF
8890        && (base_offset
8891            = fold_addr_of_array_ref_difference (loc, type, base0, base1)))
8892       || (INDIRECT_REF_P (base0)
8893           && INDIRECT_REF_P (base1)
8894           && (base_offset
8895                 = fold_binary_loc (loc, MINUS_EXPR, type,
8896                                    fold_convert (type, TREE_OPERAND (base0, 0)),
8897                                    fold_convert (type,
8898                                                  TREE_OPERAND (base1, 0)))))
8899       || operand_equal_p (base0, base1, OEP_ADDRESS_OF))
8900     {
8901       tree op0 = fold_convert_loc (loc, type, TREE_OPERAND (aref0, 1));
8902       tree op1 = fold_convert_loc (loc, type, TREE_OPERAND (aref1, 1));
8903       tree esz = fold_convert_loc (loc, type, array_ref_element_size (aref0));
8904       tree diff = build2 (MINUS_EXPR, type, op0, op1);
8905       return fold_build2_loc (loc, PLUS_EXPR, type,
8906                               base_offset,
8907                               fold_build2_loc (loc, MULT_EXPR, type,
8908                                                diff, esz));
8909     }
8910   return NULL_TREE;
8911 }
8912
8913 /* If the real or vector real constant CST of type TYPE has an exact
8914    inverse, return it, else return NULL.  */
8915
8916 tree
8917 exact_inverse (tree type, tree cst)
8918 {
8919   REAL_VALUE_TYPE r;
8920   tree unit_type, *elts;
8921   machine_mode mode;
8922   unsigned vec_nelts, i;
8923
8924   switch (TREE_CODE (cst))
8925     {
8926     case REAL_CST:
8927       r = TREE_REAL_CST (cst);
8928
8929       if (exact_real_inverse (TYPE_MODE (type), &r))
8930         return build_real (type, r);
8931
8932       return NULL_TREE;
8933
8934     case VECTOR_CST:
8935       vec_nelts = VECTOR_CST_NELTS (cst);
8936       elts = XALLOCAVEC (tree, vec_nelts);
8937       unit_type = TREE_TYPE (type);
8938       mode = TYPE_MODE (unit_type);
8939
8940       for (i = 0; i < vec_nelts; i++)
8941         {
8942           r = TREE_REAL_CST (VECTOR_CST_ELT (cst, i));
8943           if (!exact_real_inverse (mode, &r))
8944             return NULL_TREE;
8945           elts[i] = build_real (unit_type, r);
8946         }
8947
8948       return build_vector (type, elts);
8949
8950     default:
8951       return NULL_TREE;
8952     }
8953 }
8954
8955 /*  Mask out the tz least significant bits of X of type TYPE where
8956     tz is the number of trailing zeroes in Y.  */
8957 static wide_int
8958 mask_with_tz (tree type, const wide_int &x, const wide_int &y)
8959 {
8960   int tz = wi::ctz (y);
8961   if (tz > 0)
8962     return wi::mask (tz, true, TYPE_PRECISION (type)) & x;
8963   return x;
8964 }
8965
8966 /* Return true when T is an address and is known to be nonzero.
8967    For floating point we further ensure that T is not denormal.
8968    Similar logic is present in nonzero_address in rtlanal.h.
8969
8970    If the return value is based on the assumption that signed overflow
8971    is undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't
8972    change *STRICT_OVERFLOW_P.  */
8973
8974 static bool
8975 tree_expr_nonzero_warnv_p (tree t, bool *strict_overflow_p)
8976 {
8977   tree type = TREE_TYPE (t);
8978   enum tree_code code;
8979
8980   /* Doing something useful for floating point would need more work.  */
8981   if (!INTEGRAL_TYPE_P (type) && !POINTER_TYPE_P (type))
8982     return false;
8983
8984   code = TREE_CODE (t);
8985   switch (TREE_CODE_CLASS (code))
8986     {
8987     case tcc_unary:
8988       return tree_unary_nonzero_warnv_p (code, type, TREE_OPERAND (t, 0),
8989                                               strict_overflow_p);
8990     case tcc_binary:
8991     case tcc_comparison:
8992       return tree_binary_nonzero_warnv_p (code, type,
8993                                                TREE_OPERAND (t, 0),
8994                                                TREE_OPERAND (t, 1),
8995                                                strict_overflow_p);
8996     case tcc_constant:
8997     case tcc_declaration:
8998     case tcc_reference:
8999       return tree_single_nonzero_warnv_p (t, strict_overflow_p);
9000
9001     default:
9002       break;
9003     }
9004
9005   switch (code)
9006     {
9007     case TRUTH_NOT_EXPR:
9008       return tree_unary_nonzero_warnv_p (code, type, TREE_OPERAND (t, 0),
9009                                               strict_overflow_p);
9010
9011     case TRUTH_AND_EXPR:
9012     case TRUTH_OR_EXPR:
9013     case TRUTH_XOR_EXPR:
9014       return tree_binary_nonzero_warnv_p (code, type,
9015                                                TREE_OPERAND (t, 0),
9016                                                TREE_OPERAND (t, 1),
9017                                                strict_overflow_p);
9018
9019     case COND_EXPR:
9020     case CONSTRUCTOR:
9021     case OBJ_TYPE_REF:
9022     case ASSERT_EXPR:
9023     case ADDR_EXPR:
9024     case WITH_SIZE_EXPR:
9025     case SSA_NAME:
9026       return tree_single_nonzero_warnv_p (t, strict_overflow_p);
9027
9028     case COMPOUND_EXPR:
9029     case MODIFY_EXPR:
9030     case BIND_EXPR:
9031       return tree_expr_nonzero_warnv_p (TREE_OPERAND (t, 1),
9032                                         strict_overflow_p);
9033
9034     case SAVE_EXPR:
9035       return tree_expr_nonzero_warnv_p (TREE_OPERAND (t, 0),
9036                                         strict_overflow_p);
9037
9038     case CALL_EXPR:
9039       {
9040         tree fndecl = get_callee_fndecl (t);
9041         if (!fndecl) return false;
9042         if (flag_delete_null_pointer_checks && !flag_check_new
9043             && DECL_IS_OPERATOR_NEW (fndecl)
9044             && !TREE_NOTHROW (fndecl))
9045           return true;
9046         if (flag_delete_null_pointer_checks
9047             && lookup_attribute ("returns_nonnull",
9048                  TYPE_ATTRIBUTES (TREE_TYPE (fndecl))))
9049           return true;
9050         return alloca_call_p (t);
9051       }
9052
9053     default:
9054       break;
9055     }
9056   return false;
9057 }
9058
9059 /* Return true when T is an address and is known to be nonzero.
9060    Handle warnings about undefined signed overflow.  */
9061
9062 static bool
9063 tree_expr_nonzero_p (tree t)
9064 {
9065   bool ret, strict_overflow_p;
9066
9067   strict_overflow_p = false;
9068   ret = tree_expr_nonzero_warnv_p (t, &strict_overflow_p);
9069   if (strict_overflow_p)
9070     fold_overflow_warning (("assuming signed overflow does not occur when "
9071                             "determining that expression is always "
9072                             "non-zero"),
9073                            WARN_STRICT_OVERFLOW_MISC);
9074   return ret;
9075 }
9076
9077 /* Fold a binary expression of code CODE and type TYPE with operands
9078    OP0 and OP1.  LOC is the location of the resulting expression.
9079    Return the folded expression if folding is successful.  Otherwise,
9080    return NULL_TREE.  */
9081
9082 tree
9083 fold_binary_loc (location_t loc,
9084              enum tree_code code, tree type, tree op0, tree op1)
9085 {
9086   enum tree_code_class kind = TREE_CODE_CLASS (code);
9087   tree arg0, arg1, tem;
9088   tree t1 = NULL_TREE;
9089   bool strict_overflow_p;
9090   unsigned int prec;
9091
9092   gcc_assert (IS_EXPR_CODE_CLASS (kind)
9093               && TREE_CODE_LENGTH (code) == 2
9094               && op0 != NULL_TREE
9095               && op1 != NULL_TREE);
9096
9097   arg0 = op0;
9098   arg1 = op1;
9099
9100   /* Strip any conversions that don't change the mode.  This is
9101      safe for every expression, except for a comparison expression
9102      because its signedness is derived from its operands.  So, in
9103      the latter case, only strip conversions that don't change the
9104      signedness.  MIN_EXPR/MAX_EXPR also need signedness of arguments
9105      preserved.
9106
9107      Note that this is done as an internal manipulation within the
9108      constant folder, in order to find the simplest representation
9109      of the arguments so that their form can be studied.  In any
9110      cases, the appropriate type conversions should be put back in
9111      the tree that will get out of the constant folder.  */
9112
9113   if (kind == tcc_comparison || code == MIN_EXPR || code == MAX_EXPR)
9114     {
9115       STRIP_SIGN_NOPS (arg0);
9116       STRIP_SIGN_NOPS (arg1);
9117     }
9118   else
9119     {
9120       STRIP_NOPS (arg0);
9121       STRIP_NOPS (arg1);
9122     }
9123
9124   /* Note that TREE_CONSTANT isn't enough: static var addresses are
9125      constant but we can't do arithmetic on them.  */
9126   if (CONSTANT_CLASS_P (arg0) && CONSTANT_CLASS_P (arg1))
9127     {
9128       tem = const_binop (code, type, arg0, arg1);
9129       if (tem != NULL_TREE)
9130         {
9131           if (TREE_TYPE (tem) != type)
9132             tem = fold_convert_loc (loc, type, tem);
9133           return tem;
9134         }
9135     }
9136
9137   /* If this is a commutative operation, and ARG0 is a constant, move it
9138      to ARG1 to reduce the number of tests below.  */
9139   if (commutative_tree_code (code)
9140       && tree_swap_operands_p (arg0, arg1, true))
9141     return fold_build2_loc (loc, code, type, op1, op0);
9142
9143   /* Likewise if this is a comparison, and ARG0 is a constant, move it
9144      to ARG1 to reduce the number of tests below.  */
9145   if (kind == tcc_comparison
9146       && tree_swap_operands_p (arg0, arg1, true))
9147     return fold_build2_loc (loc, swap_tree_comparison (code), type, op1, op0);
9148
9149   tem = generic_simplify (loc, code, type, op0, op1);
9150   if (tem)
9151     return tem;
9152
9153   /* ARG0 is the first operand of EXPR, and ARG1 is the second operand.
9154
9155      First check for cases where an arithmetic operation is applied to a
9156      compound, conditional, or comparison operation.  Push the arithmetic
9157      operation inside the compound or conditional to see if any folding
9158      can then be done.  Convert comparison to conditional for this purpose.
9159      The also optimizes non-constant cases that used to be done in
9160      expand_expr.
9161
9162      Before we do that, see if this is a BIT_AND_EXPR or a BIT_IOR_EXPR,
9163      one of the operands is a comparison and the other is a comparison, a
9164      BIT_AND_EXPR with the constant 1, or a truth value.  In that case, the
9165      code below would make the expression more complex.  Change it to a
9166      TRUTH_{AND,OR}_EXPR.  Likewise, convert a similar NE_EXPR to
9167      TRUTH_XOR_EXPR and an EQ_EXPR to the inversion of a TRUTH_XOR_EXPR.  */
9168
9169   if ((code == BIT_AND_EXPR || code == BIT_IOR_EXPR
9170        || code == EQ_EXPR || code == NE_EXPR)
9171       && TREE_CODE (type) != VECTOR_TYPE
9172       && ((truth_value_p (TREE_CODE (arg0))
9173            && (truth_value_p (TREE_CODE (arg1))
9174                || (TREE_CODE (arg1) == BIT_AND_EXPR
9175                    && integer_onep (TREE_OPERAND (arg1, 1)))))
9176           || (truth_value_p (TREE_CODE (arg1))
9177               && (truth_value_p (TREE_CODE (arg0))
9178                   || (TREE_CODE (arg0) == BIT_AND_EXPR
9179                       && integer_onep (TREE_OPERAND (arg0, 1)))))))
9180     {
9181       tem = fold_build2_loc (loc, code == BIT_AND_EXPR ? TRUTH_AND_EXPR
9182                          : code == BIT_IOR_EXPR ? TRUTH_OR_EXPR
9183                          : TRUTH_XOR_EXPR,
9184                          boolean_type_node,
9185                          fold_convert_loc (loc, boolean_type_node, arg0),
9186                          fold_convert_loc (loc, boolean_type_node, arg1));
9187
9188       if (code == EQ_EXPR)
9189         tem = invert_truthvalue_loc (loc, tem);
9190
9191       return fold_convert_loc (loc, type, tem);
9192     }
9193
9194   if (TREE_CODE_CLASS (code) == tcc_binary
9195       || TREE_CODE_CLASS (code) == tcc_comparison)
9196     {
9197       if (TREE_CODE (arg0) == COMPOUND_EXPR)
9198         {
9199           tem = fold_build2_loc (loc, code, type,
9200                              fold_convert_loc (loc, TREE_TYPE (op0),
9201                                                TREE_OPERAND (arg0, 1)), op1);
9202           return build2_loc (loc, COMPOUND_EXPR, type, TREE_OPERAND (arg0, 0),
9203                              tem);
9204         }
9205       if (TREE_CODE (arg1) == COMPOUND_EXPR
9206           && reorder_operands_p (arg0, TREE_OPERAND (arg1, 0)))
9207         {
9208           tem = fold_build2_loc (loc, code, type, op0,
9209                              fold_convert_loc (loc, TREE_TYPE (op1),
9210                                                TREE_OPERAND (arg1, 1)));
9211           return build2_loc (loc, COMPOUND_EXPR, type, TREE_OPERAND (arg1, 0),
9212                              tem);
9213         }
9214
9215       if (TREE_CODE (arg0) == COND_EXPR
9216           || TREE_CODE (arg0) == VEC_COND_EXPR
9217           || COMPARISON_CLASS_P (arg0))
9218         {
9219           tem = fold_binary_op_with_conditional_arg (loc, code, type, op0, op1,
9220                                                      arg0, arg1,
9221                                                      /*cond_first_p=*/1);
9222           if (tem != NULL_TREE)
9223             return tem;
9224         }
9225
9226       if (TREE_CODE (arg1) == COND_EXPR
9227           || TREE_CODE (arg1) == VEC_COND_EXPR
9228           || COMPARISON_CLASS_P (arg1))
9229         {
9230           tem = fold_binary_op_with_conditional_arg (loc, code, type, op0, op1,
9231                                                      arg1, arg0,
9232                                                      /*cond_first_p=*/0);
9233           if (tem != NULL_TREE)
9234             return tem;
9235         }
9236     }
9237
9238   switch (code)
9239     {
9240     case MEM_REF:
9241       /* MEM[&MEM[p, CST1], CST2] -> MEM[p, CST1 + CST2].  */
9242       if (TREE_CODE (arg0) == ADDR_EXPR
9243           && TREE_CODE (TREE_OPERAND (arg0, 0)) == MEM_REF)
9244         {
9245           tree iref = TREE_OPERAND (arg0, 0);
9246           return fold_build2 (MEM_REF, type,
9247                               TREE_OPERAND (iref, 0),
9248                               int_const_binop (PLUS_EXPR, arg1,
9249                                                TREE_OPERAND (iref, 1)));
9250         }
9251
9252       /* MEM[&a.b, CST2] -> MEM[&a, offsetof (a, b) + CST2].  */
9253       if (TREE_CODE (arg0) == ADDR_EXPR
9254           && handled_component_p (TREE_OPERAND (arg0, 0)))
9255         {
9256           tree base;
9257           HOST_WIDE_INT coffset;
9258           base = get_addr_base_and_unit_offset (TREE_OPERAND (arg0, 0),
9259                                                 &coffset);
9260           if (!base)
9261             return NULL_TREE;
9262           return fold_build2 (MEM_REF, type,
9263                               build_fold_addr_expr (base),
9264                               int_const_binop (PLUS_EXPR, arg1,
9265                                                size_int (coffset)));
9266         }
9267
9268       return NULL_TREE;
9269
9270     case POINTER_PLUS_EXPR:
9271       /* INT +p INT -> (PTR)(INT + INT).  Stripping types allows for this. */
9272       if (INTEGRAL_TYPE_P (TREE_TYPE (arg1))
9273            && INTEGRAL_TYPE_P (TREE_TYPE (arg0)))
9274         return fold_convert_loc (loc, type,
9275                                  fold_build2_loc (loc, PLUS_EXPR, sizetype,
9276                                               fold_convert_loc (loc, sizetype,
9277                                                                 arg1),
9278                                               fold_convert_loc (loc, sizetype,
9279                                                                 arg0)));
9280
9281       return NULL_TREE;
9282
9283     case PLUS_EXPR:
9284       if (INTEGRAL_TYPE_P (type) || VECTOR_INTEGER_TYPE_P (type))
9285         {
9286           /* X + (X / CST) * -CST is X % CST.  */
9287           if (TREE_CODE (arg1) == MULT_EXPR
9288               && TREE_CODE (TREE_OPERAND (arg1, 0)) == TRUNC_DIV_EXPR
9289               && operand_equal_p (arg0,
9290                                   TREE_OPERAND (TREE_OPERAND (arg1, 0), 0), 0))
9291             {
9292               tree cst0 = TREE_OPERAND (TREE_OPERAND (arg1, 0), 1);
9293               tree cst1 = TREE_OPERAND (arg1, 1);
9294               tree sum = fold_binary_loc (loc, PLUS_EXPR, TREE_TYPE (cst1),
9295                                       cst1, cst0);
9296               if (sum && integer_zerop (sum))
9297                 return fold_convert_loc (loc, type,
9298                                          fold_build2_loc (loc, TRUNC_MOD_EXPR,
9299                                                       TREE_TYPE (arg0), arg0,
9300                                                       cst0));
9301             }
9302         }
9303
9304       /* Handle (A1 * C1) + (A2 * C2) with A1, A2 or C1, C2 being the same or
9305          one.  Make sure the type is not saturating and has the signedness of
9306          the stripped operands, as fold_plusminus_mult_expr will re-associate.
9307          ??? The latter condition should use TYPE_OVERFLOW_* flags instead.  */
9308       if ((TREE_CODE (arg0) == MULT_EXPR
9309            || TREE_CODE (arg1) == MULT_EXPR)
9310           && !TYPE_SATURATING (type)
9311           && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (TREE_TYPE (arg0))
9312           && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (TREE_TYPE (arg1))
9313           && (!FLOAT_TYPE_P (type) || flag_associative_math))
9314         {
9315           tree tem = fold_plusminus_mult_expr (loc, code, type, arg0, arg1);
9316           if (tem)
9317             return tem;
9318         }
9319
9320       if (! FLOAT_TYPE_P (type))
9321         {
9322           /* Reassociate (plus (plus (mult) (foo)) (mult)) as
9323              (plus (plus (mult) (mult)) (foo)) so that we can
9324              take advantage of the factoring cases below.  */
9325           if (ANY_INTEGRAL_TYPE_P (type)
9326               && TYPE_OVERFLOW_WRAPS (type)
9327               && (((TREE_CODE (arg0) == PLUS_EXPR
9328                     || TREE_CODE (arg0) == MINUS_EXPR)
9329                    && TREE_CODE (arg1) == MULT_EXPR)
9330                   || ((TREE_CODE (arg1) == PLUS_EXPR
9331                        || TREE_CODE (arg1) == MINUS_EXPR)
9332                       && TREE_CODE (arg0) == MULT_EXPR)))
9333             {
9334               tree parg0, parg1, parg, marg;
9335               enum tree_code pcode;
9336
9337               if (TREE_CODE (arg1) == MULT_EXPR)
9338                 parg = arg0, marg = arg1;
9339               else
9340                 parg = arg1, marg = arg0;
9341               pcode = TREE_CODE (parg);
9342               parg0 = TREE_OPERAND (parg, 0);
9343               parg1 = TREE_OPERAND (parg, 1);
9344               STRIP_NOPS (parg0);
9345               STRIP_NOPS (parg1);
9346
9347               if (TREE_CODE (parg0) == MULT_EXPR
9348                   && TREE_CODE (parg1) != MULT_EXPR)
9349                 return fold_build2_loc (loc, pcode, type,
9350                                     fold_build2_loc (loc, PLUS_EXPR, type,
9351                                                  fold_convert_loc (loc, type,
9352                                                                    parg0),
9353                                                  fold_convert_loc (loc, type,
9354                                                                    marg)),
9355                                     fold_convert_loc (loc, type, parg1));
9356               if (TREE_CODE (parg0) != MULT_EXPR
9357                   && TREE_CODE (parg1) == MULT_EXPR)
9358                 return
9359                   fold_build2_loc (loc, PLUS_EXPR, type,
9360                                fold_convert_loc (loc, type, parg0),
9361                                fold_build2_loc (loc, pcode, type,
9362                                             fold_convert_loc (loc, type, marg),
9363                                             fold_convert_loc (loc, type,
9364                                                               parg1)));
9365             }
9366         }
9367       else
9368         {
9369           /* Fold __complex__ ( x, 0 ) + __complex__ ( 0, y )
9370              to __complex__ ( x, y ).  This is not the same for SNaNs or
9371              if signed zeros are involved.  */
9372           if (!HONOR_SNANS (element_mode (arg0))
9373               && !HONOR_SIGNED_ZEROS (element_mode (arg0))
9374               && COMPLEX_FLOAT_TYPE_P (TREE_TYPE (arg0)))
9375             {
9376               tree rtype = TREE_TYPE (TREE_TYPE (arg0));
9377               tree arg0r = fold_unary_loc (loc, REALPART_EXPR, rtype, arg0);
9378               tree arg0i = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg0);
9379               bool arg0rz = false, arg0iz = false;
9380               if ((arg0r && (arg0rz = real_zerop (arg0r)))
9381                   || (arg0i && (arg0iz = real_zerop (arg0i))))
9382                 {
9383                   tree arg1r = fold_unary_loc (loc, REALPART_EXPR, rtype, arg1);
9384                   tree arg1i = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg1);
9385                   if (arg0rz && arg1i && real_zerop (arg1i))
9386                     {
9387                       tree rp = arg1r ? arg1r
9388                                   : build1 (REALPART_EXPR, rtype, arg1);
9389                       tree ip = arg0i ? arg0i
9390                                   : build1 (IMAGPART_EXPR, rtype, arg0);
9391                       return fold_build2_loc (loc, COMPLEX_EXPR, type, rp, ip);
9392                     }
9393                   else if (arg0iz && arg1r && real_zerop (arg1r))
9394                     {
9395                       tree rp = arg0r ? arg0r
9396                                   : build1 (REALPART_EXPR, rtype, arg0);
9397                       tree ip = arg1i ? arg1i
9398                                   : build1 (IMAGPART_EXPR, rtype, arg1);
9399                       return fold_build2_loc (loc, COMPLEX_EXPR, type, rp, ip);
9400                     }
9401                 }
9402             }
9403
9404           if (flag_unsafe_math_optimizations
9405               && (TREE_CODE (arg0) == RDIV_EXPR || TREE_CODE (arg0) == MULT_EXPR)
9406               && (TREE_CODE (arg1) == RDIV_EXPR || TREE_CODE (arg1) == MULT_EXPR)
9407               && (tem = distribute_real_division (loc, code, type, arg0, arg1)))
9408             return tem;
9409
9410           /* Convert a + (b*c + d*e) into (a + b*c) + d*e.
9411              We associate floats only if the user has specified
9412              -fassociative-math.  */
9413           if (flag_associative_math
9414               && TREE_CODE (arg1) == PLUS_EXPR
9415               && TREE_CODE (arg0) != MULT_EXPR)
9416             {
9417               tree tree10 = TREE_OPERAND (arg1, 0);
9418               tree tree11 = TREE_OPERAND (arg1, 1);
9419               if (TREE_CODE (tree11) == MULT_EXPR
9420                   && TREE_CODE (tree10) == MULT_EXPR)
9421                 {
9422                   tree tree0;
9423                   tree0 = fold_build2_loc (loc, PLUS_EXPR, type, arg0, tree10);
9424                   return fold_build2_loc (loc, PLUS_EXPR, type, tree0, tree11);
9425                 }
9426             }
9427           /* Convert (b*c + d*e) + a into b*c + (d*e +a).
9428              We associate floats only if the user has specified
9429              -fassociative-math.  */
9430           if (flag_associative_math
9431               && TREE_CODE (arg0) == PLUS_EXPR
9432               && TREE_CODE (arg1) != MULT_EXPR)
9433             {
9434               tree tree00 = TREE_OPERAND (arg0, 0);
9435               tree tree01 = TREE_OPERAND (arg0, 1);
9436               if (TREE_CODE (tree01) == MULT_EXPR
9437                   && TREE_CODE (tree00) == MULT_EXPR)
9438                 {
9439                   tree tree0;
9440                   tree0 = fold_build2_loc (loc, PLUS_EXPR, type, tree01, arg1);
9441                   return fold_build2_loc (loc, PLUS_EXPR, type, tree00, tree0);
9442                 }
9443             }
9444         }
9445
9446      bit_rotate:
9447       /* (A << C1) + (A >> C2) if A is unsigned and C1+C2 is the size of A
9448          is a rotate of A by C1 bits.  */
9449       /* (A << B) + (A >> (Z - B)) if A is unsigned and Z is the size of A
9450          is a rotate of A by B bits.  */
9451       {
9452         enum tree_code code0, code1;
9453         tree rtype;
9454         code0 = TREE_CODE (arg0);
9455         code1 = TREE_CODE (arg1);
9456         if (((code0 == RSHIFT_EXPR && code1 == LSHIFT_EXPR)
9457              || (code1 == RSHIFT_EXPR && code0 == LSHIFT_EXPR))
9458             && operand_equal_p (TREE_OPERAND (arg0, 0),
9459                                 TREE_OPERAND (arg1, 0), 0)
9460             && (rtype = TREE_TYPE (TREE_OPERAND (arg0, 0)),
9461                 TYPE_UNSIGNED (rtype))
9462             /* Only create rotates in complete modes.  Other cases are not
9463                expanded properly.  */
9464             && (element_precision (rtype)
9465                 == GET_MODE_UNIT_PRECISION (TYPE_MODE (rtype))))
9466           {
9467             tree tree01, tree11;
9468             enum tree_code code01, code11;
9469
9470             tree01 = TREE_OPERAND (arg0, 1);
9471             tree11 = TREE_OPERAND (arg1, 1);
9472             STRIP_NOPS (tree01);
9473             STRIP_NOPS (tree11);
9474             code01 = TREE_CODE (tree01);
9475             code11 = TREE_CODE (tree11);
9476             if (code01 == INTEGER_CST
9477                 && code11 == INTEGER_CST
9478                 && (wi::to_widest (tree01) + wi::to_widest (tree11)
9479                     == element_precision (TREE_TYPE (TREE_OPERAND (arg0, 0)))))
9480               {
9481                 tem = build2_loc (loc, LROTATE_EXPR,
9482                                   TREE_TYPE (TREE_OPERAND (arg0, 0)),
9483                                   TREE_OPERAND (arg0, 0),
9484                                   code0 == LSHIFT_EXPR
9485                                   ? TREE_OPERAND (arg0, 1)
9486                                   : TREE_OPERAND (arg1, 1));
9487                 return fold_convert_loc (loc, type, tem);
9488               }
9489             else if (code11 == MINUS_EXPR)
9490               {
9491                 tree tree110, tree111;
9492                 tree110 = TREE_OPERAND (tree11, 0);
9493                 tree111 = TREE_OPERAND (tree11, 1);
9494                 STRIP_NOPS (tree110);
9495                 STRIP_NOPS (tree111);
9496                 if (TREE_CODE (tree110) == INTEGER_CST
9497                     && 0 == compare_tree_int (tree110,
9498                                               element_precision
9499                                               (TREE_TYPE (TREE_OPERAND
9500                                                           (arg0, 0))))
9501                     && operand_equal_p (tree01, tree111, 0))
9502                   return
9503                     fold_convert_loc (loc, type,
9504                                       build2 ((code0 == LSHIFT_EXPR
9505                                                ? LROTATE_EXPR
9506                                                : RROTATE_EXPR),
9507                                               TREE_TYPE (TREE_OPERAND (arg0, 0)),
9508                                               TREE_OPERAND (arg0, 0),
9509                                               TREE_OPERAND (arg0, 1)));
9510               }
9511             else if (code01 == MINUS_EXPR)
9512               {
9513                 tree tree010, tree011;
9514                 tree010 = TREE_OPERAND (tree01, 0);
9515                 tree011 = TREE_OPERAND (tree01, 1);
9516                 STRIP_NOPS (tree010);
9517                 STRIP_NOPS (tree011);
9518                 if (TREE_CODE (tree010) == INTEGER_CST
9519                     && 0 == compare_tree_int (tree010,
9520                                               element_precision
9521                                               (TREE_TYPE (TREE_OPERAND
9522                                                           (arg0, 0))))
9523                     && operand_equal_p (tree11, tree011, 0))
9524                     return fold_convert_loc
9525                       (loc, type,
9526                        build2 ((code0 != LSHIFT_EXPR
9527                                 ? LROTATE_EXPR
9528                                 : RROTATE_EXPR),
9529                                TREE_TYPE (TREE_OPERAND (arg0, 0)),
9530                                TREE_OPERAND (arg0, 0), TREE_OPERAND (arg1, 1)));
9531               }
9532           }
9533       }
9534
9535     associate:
9536       /* In most languages, can't associate operations on floats through
9537          parentheses.  Rather than remember where the parentheses were, we
9538          don't associate floats at all, unless the user has specified
9539          -fassociative-math.
9540          And, we need to make sure type is not saturating.  */
9541
9542       if ((! FLOAT_TYPE_P (type) || flag_associative_math)
9543           && !TYPE_SATURATING (type))
9544         {
9545           tree var0, con0, lit0, minus_lit0;
9546           tree var1, con1, lit1, minus_lit1;
9547           tree atype = type;
9548           bool ok = true;
9549
9550           /* Split both trees into variables, constants, and literals.  Then
9551              associate each group together, the constants with literals,
9552              then the result with variables.  This increases the chances of
9553              literals being recombined later and of generating relocatable
9554              expressions for the sum of a constant and literal.  */
9555           var0 = split_tree (arg0, code, &con0, &lit0, &minus_lit0, 0);
9556           var1 = split_tree (arg1, code, &con1, &lit1, &minus_lit1,
9557                              code == MINUS_EXPR);
9558
9559           /* Recombine MINUS_EXPR operands by using PLUS_EXPR.  */
9560           if (code == MINUS_EXPR)
9561             code = PLUS_EXPR;
9562
9563           /* With undefined overflow prefer doing association in a type
9564              which wraps on overflow, if that is one of the operand types.  */
9565           if ((POINTER_TYPE_P (type) && POINTER_TYPE_OVERFLOW_UNDEFINED)
9566               || (INTEGRAL_TYPE_P (type) && !TYPE_OVERFLOW_WRAPS (type)))
9567             {
9568               if (INTEGRAL_TYPE_P (TREE_TYPE (arg0))
9569                   && TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg0)))
9570                 atype = TREE_TYPE (arg0);
9571               else if (INTEGRAL_TYPE_P (TREE_TYPE (arg1))
9572                        && TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg1)))
9573                 atype = TREE_TYPE (arg1);
9574               gcc_assert (TYPE_PRECISION (atype) == TYPE_PRECISION (type));
9575             }
9576
9577           /* With undefined overflow we can only associate constants with one
9578              variable, and constants whose association doesn't overflow.  */
9579           if ((POINTER_TYPE_P (atype) && POINTER_TYPE_OVERFLOW_UNDEFINED)
9580               || (INTEGRAL_TYPE_P (atype) && !TYPE_OVERFLOW_WRAPS (atype)))
9581             {
9582               if (var0 && var1)
9583                 {
9584                   tree tmp0 = var0;
9585                   tree tmp1 = var1;
9586                   bool one_neg = false;
9587
9588                   if (TREE_CODE (tmp0) == NEGATE_EXPR)
9589                     {
9590                       tmp0 = TREE_OPERAND (tmp0, 0);
9591                       one_neg = !one_neg;
9592                     }
9593                   if (CONVERT_EXPR_P (tmp0)
9594                       && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (tmp0, 0)))
9595                       && (TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (tmp0, 0)))
9596                           <= TYPE_PRECISION (atype)))
9597                     tmp0 = TREE_OPERAND (tmp0, 0);
9598                   if (TREE_CODE (tmp1) == NEGATE_EXPR)
9599                     {
9600                       tmp1 = TREE_OPERAND (tmp1, 0);
9601                       one_neg = !one_neg;
9602                     }
9603                   if (CONVERT_EXPR_P (tmp1)
9604                       && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (tmp1, 0)))
9605                       && (TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (tmp1, 0)))
9606                           <= TYPE_PRECISION (atype)))
9607                     tmp1 = TREE_OPERAND (tmp1, 0);
9608                   /* The only case we can still associate with two variables
9609                      is if they cancel out.  */
9610                   if (!one_neg
9611                       || !operand_equal_p (tmp0, tmp1, 0))
9612                     ok = false;
9613                 }
9614             }
9615
9616           /* Only do something if we found more than two objects.  Otherwise,
9617              nothing has changed and we risk infinite recursion.  */
9618           if (ok
9619               && (2 < ((var0 != 0) + (var1 != 0)
9620                        + (con0 != 0) + (con1 != 0)
9621                        + (lit0 != 0) + (lit1 != 0)
9622                        + (minus_lit0 != 0) + (minus_lit1 != 0))))
9623             {
9624               bool any_overflows = false;
9625               if (lit0) any_overflows |= TREE_OVERFLOW (lit0);
9626               if (lit1) any_overflows |= TREE_OVERFLOW (lit1);
9627               if (minus_lit0) any_overflows |= TREE_OVERFLOW (minus_lit0);
9628               if (minus_lit1) any_overflows |= TREE_OVERFLOW (minus_lit1);
9629               var0 = associate_trees (loc, var0, var1, code, atype);
9630               con0 = associate_trees (loc, con0, con1, code, atype);
9631               lit0 = associate_trees (loc, lit0, lit1, code, atype);
9632               minus_lit0 = associate_trees (loc, minus_lit0, minus_lit1,
9633                                             code, atype);
9634
9635               /* Preserve the MINUS_EXPR if the negative part of the literal is
9636                  greater than the positive part.  Otherwise, the multiplicative
9637                  folding code (i.e extract_muldiv) may be fooled in case
9638                  unsigned constants are subtracted, like in the following
9639                  example: ((X*2 + 4) - 8U)/2.  */
9640               if (minus_lit0 && lit0)
9641                 {
9642                   if (TREE_CODE (lit0) == INTEGER_CST
9643                       && TREE_CODE (minus_lit0) == INTEGER_CST
9644                       && tree_int_cst_lt (lit0, minus_lit0))
9645                     {
9646                       minus_lit0 = associate_trees (loc, minus_lit0, lit0,
9647                                                     MINUS_EXPR, atype);
9648                       lit0 = 0;
9649                     }
9650                   else
9651                     {
9652                       lit0 = associate_trees (loc, lit0, minus_lit0,
9653                                               MINUS_EXPR, atype);
9654                       minus_lit0 = 0;
9655                     }
9656                 }
9657
9658               /* Don't introduce overflows through reassociation.  */
9659               if (!any_overflows
9660                   && ((lit0 && TREE_OVERFLOW_P (lit0))
9661                       || (minus_lit0 && TREE_OVERFLOW_P (minus_lit0))))
9662                 return NULL_TREE;
9663
9664               if (minus_lit0)
9665                 {
9666                   if (con0 == 0)
9667                     return
9668                       fold_convert_loc (loc, type,
9669                                         associate_trees (loc, var0, minus_lit0,
9670                                                          MINUS_EXPR, atype));
9671                   else
9672                     {
9673                       con0 = associate_trees (loc, con0, minus_lit0,
9674                                               MINUS_EXPR, atype);
9675                       return
9676                         fold_convert_loc (loc, type,
9677                                           associate_trees (loc, var0, con0,
9678                                                            PLUS_EXPR, atype));
9679                     }
9680                 }
9681
9682               con0 = associate_trees (loc, con0, lit0, code, atype);
9683               return
9684                 fold_convert_loc (loc, type, associate_trees (loc, var0, con0,
9685                                                               code, atype));
9686             }
9687         }
9688
9689       return NULL_TREE;
9690
9691     case MINUS_EXPR:
9692       /* (-A) - B -> (-B) - A  where B is easily negated and we can swap.  */
9693       if (TREE_CODE (arg0) == NEGATE_EXPR
9694           && negate_expr_p (arg1)
9695           && reorder_operands_p (arg0, arg1))
9696         return fold_build2_loc (loc, MINUS_EXPR, type,
9697                             fold_convert_loc (loc, type,
9698                                               negate_expr (arg1)),
9699                             fold_convert_loc (loc, type,
9700                                               TREE_OPERAND (arg0, 0)));
9701
9702       /* Fold __complex__ ( x, 0 ) - __complex__ ( 0, y ) to
9703          __complex__ ( x, -y ).  This is not the same for SNaNs or if
9704          signed zeros are involved.  */
9705       if (!HONOR_SNANS (element_mode (arg0))
9706           && !HONOR_SIGNED_ZEROS (element_mode (arg0))
9707           && COMPLEX_FLOAT_TYPE_P (TREE_TYPE (arg0)))
9708         {
9709           tree rtype = TREE_TYPE (TREE_TYPE (arg0));
9710           tree arg0r = fold_unary_loc (loc, REALPART_EXPR, rtype, arg0);
9711           tree arg0i = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg0);
9712           bool arg0rz = false, arg0iz = false;
9713           if ((arg0r && (arg0rz = real_zerop (arg0r)))
9714               || (arg0i && (arg0iz = real_zerop (arg0i))))
9715             {
9716               tree arg1r = fold_unary_loc (loc, REALPART_EXPR, rtype, arg1);
9717               tree arg1i = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg1);
9718               if (arg0rz && arg1i && real_zerop (arg1i))
9719                 {
9720                   tree rp = fold_build1_loc (loc, NEGATE_EXPR, rtype,
9721                                          arg1r ? arg1r
9722                                          : build1 (REALPART_EXPR, rtype, arg1));
9723                   tree ip = arg0i ? arg0i
9724                     : build1 (IMAGPART_EXPR, rtype, arg0);
9725                   return fold_build2_loc (loc, COMPLEX_EXPR, type, rp, ip);
9726                 }
9727               else if (arg0iz && arg1r && real_zerop (arg1r))
9728                 {
9729                   tree rp = arg0r ? arg0r
9730                     : build1 (REALPART_EXPR, rtype, arg0);
9731                   tree ip = fold_build1_loc (loc, NEGATE_EXPR, rtype,
9732                                          arg1i ? arg1i
9733                                          : build1 (IMAGPART_EXPR, rtype, arg1));
9734                   return fold_build2_loc (loc, COMPLEX_EXPR, type, rp, ip);
9735                 }
9736             }
9737         }
9738
9739       /* A - B -> A + (-B) if B is easily negatable.  */
9740       if (negate_expr_p (arg1)
9741           && !TYPE_OVERFLOW_SANITIZED (type)
9742           && ((FLOAT_TYPE_P (type)
9743                /* Avoid this transformation if B is a positive REAL_CST.  */
9744                && (TREE_CODE (arg1) != REAL_CST
9745                    ||  REAL_VALUE_NEGATIVE (TREE_REAL_CST (arg1))))
9746               || INTEGRAL_TYPE_P (type)))
9747         return fold_build2_loc (loc, PLUS_EXPR, type,
9748                             fold_convert_loc (loc, type, arg0),
9749                             fold_convert_loc (loc, type,
9750                                               negate_expr (arg1)));
9751
9752       /* Fold &a[i] - &a[j] to i-j.  */
9753       if (TREE_CODE (arg0) == ADDR_EXPR
9754           && TREE_CODE (TREE_OPERAND (arg0, 0)) == ARRAY_REF
9755           && TREE_CODE (arg1) == ADDR_EXPR
9756           && TREE_CODE (TREE_OPERAND (arg1, 0)) == ARRAY_REF)
9757         {
9758           tree tem = fold_addr_of_array_ref_difference (loc, type,
9759                                                         TREE_OPERAND (arg0, 0),
9760                                                         TREE_OPERAND (arg1, 0));
9761           if (tem)
9762             return tem;
9763         }
9764
9765       if (FLOAT_TYPE_P (type)
9766           && flag_unsafe_math_optimizations
9767           && (TREE_CODE (arg0) == RDIV_EXPR || TREE_CODE (arg0) == MULT_EXPR)
9768           && (TREE_CODE (arg1) == RDIV_EXPR || TREE_CODE (arg1) == MULT_EXPR)
9769           && (tem = distribute_real_division (loc, code, type, arg0, arg1)))
9770         return tem;
9771
9772       /* Handle (A1 * C1) - (A2 * C2) with A1, A2 or C1, C2 being the same or
9773          one.  Make sure the type is not saturating and has the signedness of
9774          the stripped operands, as fold_plusminus_mult_expr will re-associate.
9775          ??? The latter condition should use TYPE_OVERFLOW_* flags instead.  */
9776       if ((TREE_CODE (arg0) == MULT_EXPR
9777            || TREE_CODE (arg1) == MULT_EXPR)
9778           && !TYPE_SATURATING (type)
9779           && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (TREE_TYPE (arg0))
9780           && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (TREE_TYPE (arg1))
9781           && (!FLOAT_TYPE_P (type) || flag_associative_math))
9782         {
9783           tree tem = fold_plusminus_mult_expr (loc, code, type, arg0, arg1);
9784           if (tem)
9785             return tem;
9786         }
9787
9788       goto associate;
9789
9790     case MULT_EXPR:
9791       if (! FLOAT_TYPE_P (type))
9792         {
9793           /* Transform x * -C into -x * C if x is easily negatable.  */
9794           if (TREE_CODE (arg1) == INTEGER_CST
9795               && tree_int_cst_sgn (arg1) == -1
9796               && negate_expr_p (arg0)
9797               && (tem = negate_expr (arg1)) != arg1
9798               && !TREE_OVERFLOW (tem))
9799             return fold_build2_loc (loc, MULT_EXPR, type,
9800                                 fold_convert_loc (loc, type,
9801                                                   negate_expr (arg0)),
9802                                 tem);
9803
9804           /* (A + A) * C -> A * 2 * C  */
9805           if (TREE_CODE (arg0) == PLUS_EXPR
9806               && TREE_CODE (arg1) == INTEGER_CST
9807               && operand_equal_p (TREE_OPERAND (arg0, 0),
9808                                   TREE_OPERAND (arg0, 1), 0))
9809             return fold_build2_loc (loc, MULT_EXPR, type,
9810                                 omit_one_operand_loc (loc, type,
9811                                                   TREE_OPERAND (arg0, 0),
9812                                                   TREE_OPERAND (arg0, 1)),
9813                                 fold_build2_loc (loc, MULT_EXPR, type,
9814                                              build_int_cst (type, 2) , arg1));
9815
9816           /* ((T) (X /[ex] C)) * C cancels out if the conversion is
9817              sign-changing only.  */
9818           if (TREE_CODE (arg1) == INTEGER_CST
9819               && TREE_CODE (arg0) == EXACT_DIV_EXPR
9820               && operand_equal_p (arg1, TREE_OPERAND (arg0, 1), 0))
9821             return fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
9822
9823           strict_overflow_p = false;
9824           if (TREE_CODE (arg1) == INTEGER_CST
9825               && 0 != (tem = extract_muldiv (op0, arg1, code, NULL_TREE,
9826                                              &strict_overflow_p)))
9827             {
9828               if (strict_overflow_p)
9829                 fold_overflow_warning (("assuming signed overflow does not "
9830                                         "occur when simplifying "
9831                                         "multiplication"),
9832                                        WARN_STRICT_OVERFLOW_MISC);
9833               return fold_convert_loc (loc, type, tem);
9834             }
9835
9836           /* Optimize z * conj(z) for integer complex numbers.  */
9837           if (TREE_CODE (arg0) == CONJ_EXPR
9838               && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
9839             return fold_mult_zconjz (loc, type, arg1);
9840           if (TREE_CODE (arg1) == CONJ_EXPR
9841               && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
9842             return fold_mult_zconjz (loc, type, arg0);
9843         }
9844       else
9845         {
9846           /* Fold z * +-I to __complex__ (-+__imag z, +-__real z).
9847              This is not the same for NaNs or if signed zeros are
9848              involved.  */
9849           if (!HONOR_NANS (arg0)
9850               && !HONOR_SIGNED_ZEROS (element_mode (arg0))
9851               && COMPLEX_FLOAT_TYPE_P (TREE_TYPE (arg0))
9852               && TREE_CODE (arg1) == COMPLEX_CST
9853               && real_zerop (TREE_REALPART (arg1)))
9854             {
9855               tree rtype = TREE_TYPE (TREE_TYPE (arg0));
9856               if (real_onep (TREE_IMAGPART (arg1)))
9857                 return
9858                   fold_build2_loc (loc, COMPLEX_EXPR, type,
9859                                negate_expr (fold_build1_loc (loc, IMAGPART_EXPR,
9860                                                              rtype, arg0)),
9861                                fold_build1_loc (loc, REALPART_EXPR, rtype, arg0));
9862               else if (real_minus_onep (TREE_IMAGPART (arg1)))
9863                 return
9864                   fold_build2_loc (loc, COMPLEX_EXPR, type,
9865                                fold_build1_loc (loc, IMAGPART_EXPR, rtype, arg0),
9866                                negate_expr (fold_build1_loc (loc, REALPART_EXPR,
9867                                                              rtype, arg0)));
9868             }
9869
9870           /* Optimize z * conj(z) for floating point complex numbers.
9871              Guarded by flag_unsafe_math_optimizations as non-finite
9872              imaginary components don't produce scalar results.  */
9873           if (flag_unsafe_math_optimizations
9874               && TREE_CODE (arg0) == CONJ_EXPR
9875               && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
9876             return fold_mult_zconjz (loc, type, arg1);
9877           if (flag_unsafe_math_optimizations
9878               && TREE_CODE (arg1) == CONJ_EXPR
9879               && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
9880             return fold_mult_zconjz (loc, type, arg0);
9881
9882           if (flag_unsafe_math_optimizations)
9883             {
9884
9885               /* Canonicalize x*x as pow(x,2.0), which is expanded as x*x.  */
9886               if (!in_gimple_form
9887                   && optimize
9888                   && operand_equal_p (arg0, arg1, 0))
9889                 {
9890                   tree powfn = mathfn_built_in (type, BUILT_IN_POW);
9891
9892                   if (powfn)
9893                     {
9894                       tree arg = build_real (type, dconst2);
9895                       return build_call_expr_loc (loc, powfn, 2, arg0, arg);
9896                     }
9897                 }
9898             }
9899         }
9900       goto associate;
9901
9902     case BIT_IOR_EXPR:
9903       /* Canonicalize (X & C1) | C2.  */
9904       if (TREE_CODE (arg0) == BIT_AND_EXPR
9905           && TREE_CODE (arg1) == INTEGER_CST
9906           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
9907         {
9908           int width = TYPE_PRECISION (type), w;
9909           wide_int c1 = TREE_OPERAND (arg0, 1);
9910           wide_int c2 = arg1;
9911
9912           /* If (C1&C2) == C1, then (X&C1)|C2 becomes (X,C2).  */
9913           if ((c1 & c2) == c1)
9914             return omit_one_operand_loc (loc, type, arg1,
9915                                          TREE_OPERAND (arg0, 0));
9916
9917           wide_int msk = wi::mask (width, false,
9918                                    TYPE_PRECISION (TREE_TYPE (arg1)));
9919
9920           /* If (C1|C2) == ~0 then (X&C1)|C2 becomes X|C2.  */
9921           if (msk.and_not (c1 | c2) == 0)
9922             return fold_build2_loc (loc, BIT_IOR_EXPR, type,
9923                                     TREE_OPERAND (arg0, 0), arg1);
9924
9925           /* Minimize the number of bits set in C1, i.e. C1 := C1 & ~C2,
9926              unless (C1 & ~C2) | (C2 & C3) for some C3 is a mask of some
9927              mode which allows further optimizations.  */
9928           c1 &= msk;
9929           c2 &= msk;
9930           wide_int c3 = c1.and_not (c2);
9931           for (w = BITS_PER_UNIT; w <= width; w <<= 1)
9932             {
9933               wide_int mask = wi::mask (w, false,
9934                                         TYPE_PRECISION (type));
9935               if (((c1 | c2) & mask) == mask && c1.and_not (mask) == 0)
9936                 {
9937                   c3 = mask;
9938                   break;
9939                 }
9940             }
9941
9942           if (c3 != c1)
9943             return fold_build2_loc (loc, BIT_IOR_EXPR, type,
9944                                     fold_build2_loc (loc, BIT_AND_EXPR, type,
9945                                                      TREE_OPERAND (arg0, 0),
9946                                                      wide_int_to_tree (type,
9947                                                                        c3)),
9948                                     arg1);
9949         }
9950
9951       /* See if this can be simplified into a rotate first.  If that
9952          is unsuccessful continue in the association code.  */
9953       goto bit_rotate;
9954
9955     case BIT_XOR_EXPR:
9956       /* Fold (X & 1) ^ 1 as (X & 1) == 0.  */
9957       if (TREE_CODE (arg0) == BIT_AND_EXPR
9958           && INTEGRAL_TYPE_P (type)
9959           && integer_onep (TREE_OPERAND (arg0, 1))
9960           && integer_onep (arg1))
9961         return fold_build2_loc (loc, EQ_EXPR, type, arg0,
9962                                 build_zero_cst (TREE_TYPE (arg0)));
9963
9964       /* See if this can be simplified into a rotate first.  If that
9965          is unsuccessful continue in the association code.  */
9966       goto bit_rotate;
9967
9968     case BIT_AND_EXPR:
9969       /* Fold (X ^ 1) & 1 as (X & 1) == 0.  */
9970       if (TREE_CODE (arg0) == BIT_XOR_EXPR
9971           && INTEGRAL_TYPE_P (type)
9972           && integer_onep (TREE_OPERAND (arg0, 1))
9973           && integer_onep (arg1))
9974         {
9975           tree tem2;
9976           tem = TREE_OPERAND (arg0, 0);
9977           tem2 = fold_convert_loc (loc, TREE_TYPE (tem), arg1);
9978           tem2 = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (tem),
9979                                   tem, tem2);
9980           return fold_build2_loc (loc, EQ_EXPR, type, tem2,
9981                                   build_zero_cst (TREE_TYPE (tem)));
9982         }
9983       /* Fold ~X & 1 as (X & 1) == 0.  */
9984       if (TREE_CODE (arg0) == BIT_NOT_EXPR
9985           && INTEGRAL_TYPE_P (type)
9986           && integer_onep (arg1))
9987         {
9988           tree tem2;
9989           tem = TREE_OPERAND (arg0, 0);
9990           tem2 = fold_convert_loc (loc, TREE_TYPE (tem), arg1);
9991           tem2 = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (tem),
9992                                   tem, tem2);
9993           return fold_build2_loc (loc, EQ_EXPR, type, tem2,
9994                                   build_zero_cst (TREE_TYPE (tem)));
9995         }
9996       /* Fold !X & 1 as X == 0.  */
9997       if (TREE_CODE (arg0) == TRUTH_NOT_EXPR
9998           && integer_onep (arg1))
9999         {
10000           tem = TREE_OPERAND (arg0, 0);
10001           return fold_build2_loc (loc, EQ_EXPR, type, tem,
10002                                   build_zero_cst (TREE_TYPE (tem)));
10003         }
10004
10005       /* Fold (X ^ Y) & Y as ~X & Y.  */
10006       if (TREE_CODE (arg0) == BIT_XOR_EXPR
10007           && operand_equal_p (TREE_OPERAND (arg0, 1), arg1, 0))
10008         {
10009           tem = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
10010           return fold_build2_loc (loc, BIT_AND_EXPR, type,
10011                               fold_build1_loc (loc, BIT_NOT_EXPR, type, tem),
10012                               fold_convert_loc (loc, type, arg1));
10013         }
10014       /* Fold (X ^ Y) & X as ~Y & X.  */
10015       if (TREE_CODE (arg0) == BIT_XOR_EXPR
10016           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0)
10017           && reorder_operands_p (TREE_OPERAND (arg0, 1), arg1))
10018         {
10019           tem = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 1));
10020           return fold_build2_loc (loc, BIT_AND_EXPR, type,
10021                               fold_build1_loc (loc, BIT_NOT_EXPR, type, tem),
10022                               fold_convert_loc (loc, type, arg1));
10023         }
10024       /* Fold X & (X ^ Y) as X & ~Y.  */
10025       if (TREE_CODE (arg1) == BIT_XOR_EXPR
10026           && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
10027         {
10028           tem = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 1));
10029           return fold_build2_loc (loc, BIT_AND_EXPR, type,
10030                               fold_convert_loc (loc, type, arg0),
10031                               fold_build1_loc (loc, BIT_NOT_EXPR, type, tem));
10032         }
10033       /* Fold X & (Y ^ X) as ~Y & X.  */
10034       if (TREE_CODE (arg1) == BIT_XOR_EXPR
10035           && operand_equal_p (arg0, TREE_OPERAND (arg1, 1), 0)
10036           && reorder_operands_p (arg0, TREE_OPERAND (arg1, 0)))
10037         {
10038           tem = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 0));
10039           return fold_build2_loc (loc, BIT_AND_EXPR, type,
10040                               fold_build1_loc (loc, BIT_NOT_EXPR, type, tem),
10041                               fold_convert_loc (loc, type, arg0));
10042         }
10043
10044       /* Fold (X * Y) & -(1 << CST) to X * Y if Y is a constant
10045          multiple of 1 << CST.  */
10046       if (TREE_CODE (arg1) == INTEGER_CST)
10047         {
10048           wide_int cst1 = arg1;
10049           wide_int ncst1 = -cst1;
10050           if ((cst1 & ncst1) == ncst1
10051               && multiple_of_p (type, arg0,
10052                                 wide_int_to_tree (TREE_TYPE (arg1), ncst1)))
10053             return fold_convert_loc (loc, type, arg0);
10054         }
10055
10056       /* Fold (X * CST1) & CST2 to zero if we can, or drop known zero
10057          bits from CST2.  */
10058       if (TREE_CODE (arg1) == INTEGER_CST
10059           && TREE_CODE (arg0) == MULT_EXPR
10060           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
10061         {
10062           wide_int warg1 = arg1;
10063           wide_int masked = mask_with_tz (type, warg1, TREE_OPERAND (arg0, 1));
10064
10065           if (masked == 0)
10066             return omit_two_operands_loc (loc, type, build_zero_cst (type),
10067                                           arg0, arg1);
10068           else if (masked != warg1)
10069             {
10070               /* Avoid the transform if arg1 is a mask of some
10071                  mode which allows further optimizations.  */
10072               int pop = wi::popcount (warg1);
10073               if (!(pop >= BITS_PER_UNIT
10074                     && exact_log2 (pop) != -1
10075                     && wi::mask (pop, false, warg1.get_precision ()) == warg1))
10076                 return fold_build2_loc (loc, code, type, op0,
10077                                         wide_int_to_tree (type, masked));
10078             }
10079         }
10080
10081       /* For constants M and N, if M == (1LL << cst) - 1 && (N & M) == M,
10082          ((A & N) + B) & M -> (A + B) & M
10083          Similarly if (N & M) == 0,
10084          ((A | N) + B) & M -> (A + B) & M
10085          and for - instead of + (or unary - instead of +)
10086          and/or ^ instead of |.
10087          If B is constant and (B & M) == 0, fold into A & M.  */
10088       if (TREE_CODE (arg1) == INTEGER_CST)
10089         {
10090           wide_int cst1 = arg1;
10091           if ((~cst1 != 0) && (cst1 & (cst1 + 1)) == 0
10092               && INTEGRAL_TYPE_P (TREE_TYPE (arg0))
10093               && (TREE_CODE (arg0) == PLUS_EXPR
10094                   || TREE_CODE (arg0) == MINUS_EXPR
10095                   || TREE_CODE (arg0) == NEGATE_EXPR)
10096               && (TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg0))
10097                   || TREE_CODE (TREE_TYPE (arg0)) == INTEGER_TYPE))
10098             {
10099               tree pmop[2];
10100               int which = 0;
10101               wide_int cst0;
10102
10103               /* Now we know that arg0 is (C + D) or (C - D) or
10104                  -C and arg1 (M) is == (1LL << cst) - 1.
10105                  Store C into PMOP[0] and D into PMOP[1].  */
10106               pmop[0] = TREE_OPERAND (arg0, 0);
10107               pmop[1] = NULL;
10108               if (TREE_CODE (arg0) != NEGATE_EXPR)
10109                 {
10110                   pmop[1] = TREE_OPERAND (arg0, 1);
10111                   which = 1;
10112                 }
10113
10114               if ((wi::max_value (TREE_TYPE (arg0)) & cst1) != cst1)
10115                 which = -1;
10116
10117               for (; which >= 0; which--)
10118                 switch (TREE_CODE (pmop[which]))
10119                   {
10120                   case BIT_AND_EXPR:
10121                   case BIT_IOR_EXPR:
10122                   case BIT_XOR_EXPR:
10123                     if (TREE_CODE (TREE_OPERAND (pmop[which], 1))
10124                         != INTEGER_CST)
10125                       break;
10126                     cst0 = TREE_OPERAND (pmop[which], 1);
10127                     cst0 &= cst1;
10128                     if (TREE_CODE (pmop[which]) == BIT_AND_EXPR)
10129                       {
10130                         if (cst0 != cst1)
10131                           break;
10132                       }
10133                     else if (cst0 != 0)
10134                       break;
10135                     /* If C or D is of the form (A & N) where
10136                        (N & M) == M, or of the form (A | N) or
10137                        (A ^ N) where (N & M) == 0, replace it with A.  */
10138                     pmop[which] = TREE_OPERAND (pmop[which], 0);
10139                     break;
10140                   case INTEGER_CST:
10141                     /* If C or D is a N where (N & M) == 0, it can be
10142                        omitted (assumed 0).  */
10143                     if ((TREE_CODE (arg0) == PLUS_EXPR
10144                          || (TREE_CODE (arg0) == MINUS_EXPR && which == 0))
10145                         && (cst1 & pmop[which]) == 0)
10146                       pmop[which] = NULL;
10147                     break;
10148                   default:
10149                     break;
10150                   }
10151
10152               /* Only build anything new if we optimized one or both arguments
10153                  above.  */
10154               if (pmop[0] != TREE_OPERAND (arg0, 0)
10155                   || (TREE_CODE (arg0) != NEGATE_EXPR
10156                       && pmop[1] != TREE_OPERAND (arg0, 1)))
10157                 {
10158                   tree utype = TREE_TYPE (arg0);
10159                   if (! TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg0)))
10160                     {
10161                       /* Perform the operations in a type that has defined
10162                          overflow behavior.  */
10163                       utype = unsigned_type_for (TREE_TYPE (arg0));
10164                       if (pmop[0] != NULL)
10165                         pmop[0] = fold_convert_loc (loc, utype, pmop[0]);
10166                       if (pmop[1] != NULL)
10167                         pmop[1] = fold_convert_loc (loc, utype, pmop[1]);
10168                     }
10169
10170                   if (TREE_CODE (arg0) == NEGATE_EXPR)
10171                     tem = fold_build1_loc (loc, NEGATE_EXPR, utype, pmop[0]);
10172                   else if (TREE_CODE (arg0) == PLUS_EXPR)
10173                     {
10174                       if (pmop[0] != NULL && pmop[1] != NULL)
10175                         tem = fold_build2_loc (loc, PLUS_EXPR, utype,
10176                                                pmop[0], pmop[1]);
10177                       else if (pmop[0] != NULL)
10178                         tem = pmop[0];
10179                       else if (pmop[1] != NULL)
10180                         tem = pmop[1];
10181                       else
10182                         return build_int_cst (type, 0);
10183                     }
10184                   else if (pmop[0] == NULL)
10185                     tem = fold_build1_loc (loc, NEGATE_EXPR, utype, pmop[1]);
10186                   else
10187                     tem = fold_build2_loc (loc, MINUS_EXPR, utype,
10188                                            pmop[0], pmop[1]);
10189                   /* TEM is now the new binary +, - or unary - replacement.  */
10190                   tem = fold_build2_loc (loc, BIT_AND_EXPR, utype, tem,
10191                                          fold_convert_loc (loc, utype, arg1));
10192                   return fold_convert_loc (loc, type, tem);
10193                 }
10194             }
10195         }
10196
10197       /* Simplify ((int)c & 0377) into (int)c, if c is unsigned char.  */
10198       if (TREE_CODE (arg1) == INTEGER_CST && TREE_CODE (arg0) == NOP_EXPR
10199           && TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (arg0, 0))))
10200         {
10201           prec = element_precision (TREE_TYPE (TREE_OPERAND (arg0, 0)));
10202
10203           wide_int mask = wide_int::from (arg1, prec, UNSIGNED);
10204           if (mask == -1)
10205             return
10206               fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
10207         }
10208
10209       goto associate;
10210
10211     case RDIV_EXPR:
10212       /* Don't touch a floating-point divide by zero unless the mode
10213          of the constant can represent infinity.  */
10214       if (TREE_CODE (arg1) == REAL_CST
10215           && !MODE_HAS_INFINITIES (TYPE_MODE (TREE_TYPE (arg1)))
10216           && real_zerop (arg1))
10217         return NULL_TREE;
10218
10219       /* (-A) / (-B) -> A / B  */
10220       if (TREE_CODE (arg0) == NEGATE_EXPR && negate_expr_p (arg1))
10221         return fold_build2_loc (loc, RDIV_EXPR, type,
10222                             TREE_OPERAND (arg0, 0),
10223                             negate_expr (arg1));
10224       if (TREE_CODE (arg1) == NEGATE_EXPR && negate_expr_p (arg0))
10225         return fold_build2_loc (loc, RDIV_EXPR, type,
10226                             negate_expr (arg0),
10227                             TREE_OPERAND (arg1, 0));
10228
10229       /* Convert A/B/C to A/(B*C).  */
10230       if (flag_reciprocal_math
10231           && TREE_CODE (arg0) == RDIV_EXPR)
10232         return fold_build2_loc (loc, RDIV_EXPR, type, TREE_OPERAND (arg0, 0),
10233                             fold_build2_loc (loc, MULT_EXPR, type,
10234                                          TREE_OPERAND (arg0, 1), arg1));
10235
10236       /* Convert A/(B/C) to (A/B)*C.  */
10237       if (flag_reciprocal_math
10238           && TREE_CODE (arg1) == RDIV_EXPR)
10239         return fold_build2_loc (loc, MULT_EXPR, type,
10240                             fold_build2_loc (loc, RDIV_EXPR, type, arg0,
10241                                          TREE_OPERAND (arg1, 0)),
10242                             TREE_OPERAND (arg1, 1));
10243
10244       /* Convert C1/(X*C2) into (C1/C2)/X.  */
10245       if (flag_reciprocal_math
10246           && TREE_CODE (arg1) == MULT_EXPR
10247           && TREE_CODE (arg0) == REAL_CST
10248           && TREE_CODE (TREE_OPERAND (arg1, 1)) == REAL_CST)
10249         {
10250           tree tem = const_binop (RDIV_EXPR, arg0,
10251                                   TREE_OPERAND (arg1, 1));
10252           if (tem)
10253             return fold_build2_loc (loc, RDIV_EXPR, type, tem,
10254                                 TREE_OPERAND (arg1, 0));
10255         }
10256
10257       return NULL_TREE;
10258
10259     case TRUNC_DIV_EXPR:
10260       /* Optimize (X & (-A)) / A where A is a power of 2,
10261          to X >> log2(A) */
10262       if (TREE_CODE (arg0) == BIT_AND_EXPR
10263           && !TYPE_UNSIGNED (type) && TREE_CODE (arg1) == INTEGER_CST
10264           && integer_pow2p (arg1) && tree_int_cst_sgn (arg1) > 0)
10265         {
10266           tree sum = fold_binary_loc (loc, PLUS_EXPR, TREE_TYPE (arg1),
10267                                       arg1, TREE_OPERAND (arg0, 1));
10268           if (sum && integer_zerop (sum)) {
10269             tree pow2 = build_int_cst (integer_type_node,
10270                                        wi::exact_log2 (arg1));
10271             return fold_build2_loc (loc, RSHIFT_EXPR, type,
10272                                     TREE_OPERAND (arg0, 0), pow2);
10273           }
10274         }
10275
10276       /* Fall through */
10277       
10278     case FLOOR_DIV_EXPR:
10279       /* Simplify A / (B << N) where A and B are positive and B is
10280          a power of 2, to A >> (N + log2(B)).  */
10281       strict_overflow_p = false;
10282       if (TREE_CODE (arg1) == LSHIFT_EXPR
10283           && (TYPE_UNSIGNED (type)
10284               || tree_expr_nonnegative_warnv_p (op0, &strict_overflow_p)))
10285         {
10286           tree sval = TREE_OPERAND (arg1, 0);
10287           if (integer_pow2p (sval) && tree_int_cst_sgn (sval) > 0)
10288             {
10289               tree sh_cnt = TREE_OPERAND (arg1, 1);
10290               tree pow2 = build_int_cst (TREE_TYPE (sh_cnt),
10291                                          wi::exact_log2 (sval));
10292
10293               if (strict_overflow_p)
10294                 fold_overflow_warning (("assuming signed overflow does not "
10295                                         "occur when simplifying A / (B << N)"),
10296                                        WARN_STRICT_OVERFLOW_MISC);
10297
10298               sh_cnt = fold_build2_loc (loc, PLUS_EXPR, TREE_TYPE (sh_cnt),
10299                                         sh_cnt, pow2);
10300               return fold_build2_loc (loc, RSHIFT_EXPR, type,
10301                                       fold_convert_loc (loc, type, arg0), sh_cnt);
10302             }
10303         }
10304
10305       /* Fall through */
10306
10307     case ROUND_DIV_EXPR:
10308     case CEIL_DIV_EXPR:
10309     case EXACT_DIV_EXPR:
10310       if (integer_zerop (arg1))
10311         return NULL_TREE;
10312
10313       /* Convert -A / -B to A / B when the type is signed and overflow is
10314          undefined.  */
10315       if ((!INTEGRAL_TYPE_P (type) || TYPE_OVERFLOW_UNDEFINED (type))
10316           && TREE_CODE (arg0) == NEGATE_EXPR
10317           && negate_expr_p (arg1))
10318         {
10319           if (INTEGRAL_TYPE_P (type))
10320             fold_overflow_warning (("assuming signed overflow does not occur "
10321                                     "when distributing negation across "
10322                                     "division"),
10323                                    WARN_STRICT_OVERFLOW_MISC);
10324           return fold_build2_loc (loc, code, type,
10325                               fold_convert_loc (loc, type,
10326                                                 TREE_OPERAND (arg0, 0)),
10327                               fold_convert_loc (loc, type,
10328                                                 negate_expr (arg1)));
10329         }
10330       if ((!INTEGRAL_TYPE_P (type) || TYPE_OVERFLOW_UNDEFINED (type))
10331           && TREE_CODE (arg1) == NEGATE_EXPR
10332           && negate_expr_p (arg0))
10333         {
10334           if (INTEGRAL_TYPE_P (type))
10335             fold_overflow_warning (("assuming signed overflow does not occur "
10336                                     "when distributing negation across "
10337                                     "division"),
10338                                    WARN_STRICT_OVERFLOW_MISC);
10339           return fold_build2_loc (loc, code, type,
10340                               fold_convert_loc (loc, type,
10341                                                 negate_expr (arg0)),
10342                               fold_convert_loc (loc, type,
10343                                                 TREE_OPERAND (arg1, 0)));
10344         }
10345
10346       /* If arg0 is a multiple of arg1, then rewrite to the fastest div
10347          operation, EXACT_DIV_EXPR.
10348
10349          Note that only CEIL_DIV_EXPR and FLOOR_DIV_EXPR are rewritten now.
10350          At one time others generated faster code, it's not clear if they do
10351          after the last round to changes to the DIV code in expmed.c.  */
10352       if ((code == CEIL_DIV_EXPR || code == FLOOR_DIV_EXPR)
10353           && multiple_of_p (type, arg0, arg1))
10354         return fold_build2_loc (loc, EXACT_DIV_EXPR, type,
10355                                 fold_convert (type, arg0),
10356                                 fold_convert (type, arg1));
10357
10358       strict_overflow_p = false;
10359       if (TREE_CODE (arg1) == INTEGER_CST
10360           && 0 != (tem = extract_muldiv (op0, arg1, code, NULL_TREE,
10361                                          &strict_overflow_p)))
10362         {
10363           if (strict_overflow_p)
10364             fold_overflow_warning (("assuming signed overflow does not occur "
10365                                     "when simplifying division"),
10366                                    WARN_STRICT_OVERFLOW_MISC);
10367           return fold_convert_loc (loc, type, tem);
10368         }
10369
10370       return NULL_TREE;
10371
10372     case CEIL_MOD_EXPR:
10373     case FLOOR_MOD_EXPR:
10374     case ROUND_MOD_EXPR:
10375     case TRUNC_MOD_EXPR:
10376       strict_overflow_p = false;
10377       if (TREE_CODE (arg1) == INTEGER_CST
10378           && 0 != (tem = extract_muldiv (op0, arg1, code, NULL_TREE,
10379                                          &strict_overflow_p)))
10380         {
10381           if (strict_overflow_p)
10382             fold_overflow_warning (("assuming signed overflow does not occur "
10383                                     "when simplifying modulus"),
10384                                    WARN_STRICT_OVERFLOW_MISC);
10385           return fold_convert_loc (loc, type, tem);
10386         }
10387
10388       return NULL_TREE;
10389
10390     case LROTATE_EXPR:
10391     case RROTATE_EXPR:
10392     case RSHIFT_EXPR:
10393     case LSHIFT_EXPR:
10394       /* Since negative shift count is not well-defined,
10395          don't try to compute it in the compiler.  */
10396       if (TREE_CODE (arg1) == INTEGER_CST && tree_int_cst_sgn (arg1) < 0)
10397         return NULL_TREE;
10398
10399       prec = element_precision (type);
10400
10401       /* If we have a rotate of a bit operation with the rotate count and
10402          the second operand of the bit operation both constant,
10403          permute the two operations.  */
10404       if (code == RROTATE_EXPR && TREE_CODE (arg1) == INTEGER_CST
10405           && (TREE_CODE (arg0) == BIT_AND_EXPR
10406               || TREE_CODE (arg0) == BIT_IOR_EXPR
10407               || TREE_CODE (arg0) == BIT_XOR_EXPR)
10408           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
10409         return fold_build2_loc (loc, TREE_CODE (arg0), type,
10410                             fold_build2_loc (loc, code, type,
10411                                          TREE_OPERAND (arg0, 0), arg1),
10412                             fold_build2_loc (loc, code, type,
10413                                          TREE_OPERAND (arg0, 1), arg1));
10414
10415       /* Two consecutive rotates adding up to the some integer
10416          multiple of the precision of the type can be ignored.  */
10417       if (code == RROTATE_EXPR && TREE_CODE (arg1) == INTEGER_CST
10418           && TREE_CODE (arg0) == RROTATE_EXPR
10419           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
10420           && wi::umod_trunc (wi::add (arg1, TREE_OPERAND (arg0, 1)),
10421                              prec) == 0)
10422         return TREE_OPERAND (arg0, 0);
10423
10424       return NULL_TREE;
10425
10426     case MIN_EXPR:
10427       tem = fold_minmax (loc, MIN_EXPR, type, arg0, arg1);
10428       if (tem)
10429         return tem;
10430       goto associate;
10431
10432     case MAX_EXPR:
10433       tem = fold_minmax (loc, MAX_EXPR, type, arg0, arg1);
10434       if (tem)
10435         return tem;
10436       goto associate;
10437
10438     case TRUTH_ANDIF_EXPR:
10439       /* Note that the operands of this must be ints
10440          and their values must be 0 or 1.
10441          ("true" is a fixed value perhaps depending on the language.)  */
10442       /* If first arg is constant zero, return it.  */
10443       if (integer_zerop (arg0))
10444         return fold_convert_loc (loc, type, arg0);
10445     case TRUTH_AND_EXPR:
10446       /* If either arg is constant true, drop it.  */
10447       if (TREE_CODE (arg0) == INTEGER_CST && ! integer_zerop (arg0))
10448         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg1));
10449       if (TREE_CODE (arg1) == INTEGER_CST && ! integer_zerop (arg1)
10450           /* Preserve sequence points.  */
10451           && (code != TRUTH_ANDIF_EXPR || ! TREE_SIDE_EFFECTS (arg0)))
10452         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
10453       /* If second arg is constant zero, result is zero, but first arg
10454          must be evaluated.  */
10455       if (integer_zerop (arg1))
10456         return omit_one_operand_loc (loc, type, arg1, arg0);
10457       /* Likewise for first arg, but note that only the TRUTH_AND_EXPR
10458          case will be handled here.  */
10459       if (integer_zerop (arg0))
10460         return omit_one_operand_loc (loc, type, arg0, arg1);
10461
10462       /* !X && X is always false.  */
10463       if (TREE_CODE (arg0) == TRUTH_NOT_EXPR
10464           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
10465         return omit_one_operand_loc (loc, type, integer_zero_node, arg1);
10466       /* X && !X is always false.  */
10467       if (TREE_CODE (arg1) == TRUTH_NOT_EXPR
10468           && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
10469         return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
10470
10471       /* A < X && A + 1 > Y ==> A < X && A >= Y.  Normally A + 1 > Y
10472          means A >= Y && A != MAX, but in this case we know that
10473          A < X <= MAX.  */
10474
10475       if (!TREE_SIDE_EFFECTS (arg0)
10476           && !TREE_SIDE_EFFECTS (arg1))
10477         {
10478           tem = fold_to_nonsharp_ineq_using_bound (loc, arg0, arg1);
10479           if (tem && !operand_equal_p (tem, arg0, 0))
10480             return fold_build2_loc (loc, code, type, tem, arg1);
10481
10482           tem = fold_to_nonsharp_ineq_using_bound (loc, arg1, arg0);
10483           if (tem && !operand_equal_p (tem, arg1, 0))
10484             return fold_build2_loc (loc, code, type, arg0, tem);
10485         }
10486
10487       if ((tem = fold_truth_andor (loc, code, type, arg0, arg1, op0, op1))
10488           != NULL_TREE)
10489         return tem;
10490
10491       return NULL_TREE;
10492
10493     case TRUTH_ORIF_EXPR:
10494       /* Note that the operands of this must be ints
10495          and their values must be 0 or true.
10496          ("true" is a fixed value perhaps depending on the language.)  */
10497       /* If first arg is constant true, return it.  */
10498       if (TREE_CODE (arg0) == INTEGER_CST && ! integer_zerop (arg0))
10499         return fold_convert_loc (loc, type, arg0);
10500     case TRUTH_OR_EXPR:
10501       /* If either arg is constant zero, drop it.  */
10502       if (TREE_CODE (arg0) == INTEGER_CST && integer_zerop (arg0))
10503         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg1));
10504       if (TREE_CODE (arg1) == INTEGER_CST && integer_zerop (arg1)
10505           /* Preserve sequence points.  */
10506           && (code != TRUTH_ORIF_EXPR || ! TREE_SIDE_EFFECTS (arg0)))
10507         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
10508       /* If second arg is constant true, result is true, but we must
10509          evaluate first arg.  */
10510       if (TREE_CODE (arg1) == INTEGER_CST && ! integer_zerop (arg1))
10511         return omit_one_operand_loc (loc, type, arg1, arg0);
10512       /* Likewise for first arg, but note this only occurs here for
10513          TRUTH_OR_EXPR.  */
10514       if (TREE_CODE (arg0) == INTEGER_CST && ! integer_zerop (arg0))
10515         return omit_one_operand_loc (loc, type, arg0, arg1);
10516
10517       /* !X || X is always true.  */
10518       if (TREE_CODE (arg0) == TRUTH_NOT_EXPR
10519           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
10520         return omit_one_operand_loc (loc, type, integer_one_node, arg1);
10521       /* X || !X is always true.  */
10522       if (TREE_CODE (arg1) == TRUTH_NOT_EXPR
10523           && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
10524         return omit_one_operand_loc (loc, type, integer_one_node, arg0);
10525
10526       /* (X && !Y) || (!X && Y) is X ^ Y */
10527       if (TREE_CODE (arg0) == TRUTH_AND_EXPR
10528           && TREE_CODE (arg1) == TRUTH_AND_EXPR)
10529         {
10530           tree a0, a1, l0, l1, n0, n1;
10531
10532           a0 = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 0));
10533           a1 = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 1));
10534
10535           l0 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
10536           l1 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 1));
10537           
10538           n0 = fold_build1_loc (loc, TRUTH_NOT_EXPR, type, l0);
10539           n1 = fold_build1_loc (loc, TRUTH_NOT_EXPR, type, l1);
10540           
10541           if ((operand_equal_p (n0, a0, 0)
10542                && operand_equal_p (n1, a1, 0))
10543               || (operand_equal_p (n0, a1, 0)
10544                   && operand_equal_p (n1, a0, 0)))
10545             return fold_build2_loc (loc, TRUTH_XOR_EXPR, type, l0, n1);
10546         }
10547
10548       if ((tem = fold_truth_andor (loc, code, type, arg0, arg1, op0, op1))
10549           != NULL_TREE)
10550         return tem;
10551
10552       return NULL_TREE;
10553
10554     case TRUTH_XOR_EXPR:
10555       /* If the second arg is constant zero, drop it.  */
10556       if (integer_zerop (arg1))
10557         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
10558       /* If the second arg is constant true, this is a logical inversion.  */
10559       if (integer_onep (arg1))
10560         {
10561           tem = invert_truthvalue_loc (loc, arg0);
10562           return non_lvalue_loc (loc, fold_convert_loc (loc, type, tem));
10563         }
10564       /* Identical arguments cancel to zero.  */
10565       if (operand_equal_p (arg0, arg1, 0))
10566         return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
10567
10568       /* !X ^ X is always true.  */
10569       if (TREE_CODE (arg0) == TRUTH_NOT_EXPR
10570           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
10571         return omit_one_operand_loc (loc, type, integer_one_node, arg1);
10572
10573       /* X ^ !X is always true.  */
10574       if (TREE_CODE (arg1) == TRUTH_NOT_EXPR
10575           && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
10576         return omit_one_operand_loc (loc, type, integer_one_node, arg0);
10577
10578       return NULL_TREE;
10579
10580     case EQ_EXPR:
10581     case NE_EXPR:
10582       STRIP_NOPS (arg0);
10583       STRIP_NOPS (arg1);
10584
10585       tem = fold_comparison (loc, code, type, op0, op1);
10586       if (tem != NULL_TREE)
10587         return tem;
10588
10589       /* bool_var != 1 becomes !bool_var. */
10590       if (TREE_CODE (TREE_TYPE (arg0)) == BOOLEAN_TYPE && integer_onep (arg1)
10591           && code == NE_EXPR)
10592         return fold_convert_loc (loc, type,
10593                                  fold_build1_loc (loc, TRUTH_NOT_EXPR,
10594                                                   TREE_TYPE (arg0), arg0));
10595
10596       /* bool_var == 0 becomes !bool_var. */
10597       if (TREE_CODE (TREE_TYPE (arg0)) == BOOLEAN_TYPE && integer_zerop (arg1)
10598           && code == EQ_EXPR)
10599         return fold_convert_loc (loc, type,
10600                                  fold_build1_loc (loc, TRUTH_NOT_EXPR,
10601                                                   TREE_TYPE (arg0), arg0));
10602
10603       /* !exp != 0 becomes !exp */
10604       if (TREE_CODE (arg0) == TRUTH_NOT_EXPR && integer_zerop (arg1)
10605           && code == NE_EXPR)
10606         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
10607
10608       /* Transform comparisons of the form X +- Y CMP X to Y CMP 0.  */
10609       if ((TREE_CODE (arg0) == PLUS_EXPR
10610            || TREE_CODE (arg0) == POINTER_PLUS_EXPR
10611            || TREE_CODE (arg0) == MINUS_EXPR)
10612           && operand_equal_p (tree_strip_nop_conversions (TREE_OPERAND (arg0,
10613                                                                         0)),
10614                               arg1, 0)
10615           && (INTEGRAL_TYPE_P (TREE_TYPE (arg0))
10616               || POINTER_TYPE_P (TREE_TYPE (arg0))))
10617         {
10618           tree val = TREE_OPERAND (arg0, 1);
10619           return omit_two_operands_loc (loc, type,
10620                                     fold_build2_loc (loc, code, type,
10621                                                  val,
10622                                                  build_int_cst (TREE_TYPE (val),
10623                                                                 0)),
10624                                     TREE_OPERAND (arg0, 0), arg1);
10625         }
10626
10627       /* Transform comparisons of the form C - X CMP X if C % 2 == 1.  */
10628       if (TREE_CODE (arg0) == MINUS_EXPR
10629           && TREE_CODE (TREE_OPERAND (arg0, 0)) == INTEGER_CST
10630           && operand_equal_p (tree_strip_nop_conversions (TREE_OPERAND (arg0,
10631                                                                         1)),
10632                               arg1, 0)
10633           && wi::extract_uhwi (TREE_OPERAND (arg0, 0), 0, 1) == 1)
10634         {
10635           return omit_two_operands_loc (loc, type,
10636                                     code == NE_EXPR
10637                                     ? boolean_true_node : boolean_false_node,
10638                                     TREE_OPERAND (arg0, 1), arg1);
10639         }
10640
10641       /* If this is an EQ or NE comparison with zero and ARG0 is
10642          (1 << foo) & bar, convert it to (bar >> foo) & 1.  Both require
10643          two operations, but the latter can be done in one less insn
10644          on machines that have only two-operand insns or on which a
10645          constant cannot be the first operand.  */
10646       if (TREE_CODE (arg0) == BIT_AND_EXPR
10647           && integer_zerop (arg1))
10648         {
10649           tree arg00 = TREE_OPERAND (arg0, 0);
10650           tree arg01 = TREE_OPERAND (arg0, 1);
10651           if (TREE_CODE (arg00) == LSHIFT_EXPR
10652               && integer_onep (TREE_OPERAND (arg00, 0)))
10653             {
10654               tree tem = fold_build2_loc (loc, RSHIFT_EXPR, TREE_TYPE (arg00),
10655                                       arg01, TREE_OPERAND (arg00, 1));
10656               tem = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg0), tem,
10657                                  build_int_cst (TREE_TYPE (arg0), 1));
10658               return fold_build2_loc (loc, code, type,
10659                                   fold_convert_loc (loc, TREE_TYPE (arg1), tem),
10660                                   arg1);
10661             }
10662           else if (TREE_CODE (arg01) == LSHIFT_EXPR
10663                    && integer_onep (TREE_OPERAND (arg01, 0)))
10664             {
10665               tree tem = fold_build2_loc (loc, RSHIFT_EXPR, TREE_TYPE (arg01),
10666                                       arg00, TREE_OPERAND (arg01, 1));
10667               tem = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg0), tem,
10668                                  build_int_cst (TREE_TYPE (arg0), 1));
10669               return fold_build2_loc (loc, code, type,
10670                                   fold_convert_loc (loc, TREE_TYPE (arg1), tem),
10671                                   arg1);
10672             }
10673         }
10674
10675       /* If this is an NE or EQ comparison of zero against the result of a
10676          signed MOD operation whose second operand is a power of 2, make
10677          the MOD operation unsigned since it is simpler and equivalent.  */
10678       if (integer_zerop (arg1)
10679           && !TYPE_UNSIGNED (TREE_TYPE (arg0))
10680           && (TREE_CODE (arg0) == TRUNC_MOD_EXPR
10681               || TREE_CODE (arg0) == CEIL_MOD_EXPR
10682               || TREE_CODE (arg0) == FLOOR_MOD_EXPR
10683               || TREE_CODE (arg0) == ROUND_MOD_EXPR)
10684           && integer_pow2p (TREE_OPERAND (arg0, 1)))
10685         {
10686           tree newtype = unsigned_type_for (TREE_TYPE (arg0));
10687           tree newmod = fold_build2_loc (loc, TREE_CODE (arg0), newtype,
10688                                      fold_convert_loc (loc, newtype,
10689                                                        TREE_OPERAND (arg0, 0)),
10690                                      fold_convert_loc (loc, newtype,
10691                                                        TREE_OPERAND (arg0, 1)));
10692
10693           return fold_build2_loc (loc, code, type, newmod,
10694                               fold_convert_loc (loc, newtype, arg1));
10695         }
10696
10697       /* Fold ((X >> C1) & C2) == 0 and ((X >> C1) & C2) != 0 where
10698          C1 is a valid shift constant, and C2 is a power of two, i.e.
10699          a single bit.  */
10700       if (TREE_CODE (arg0) == BIT_AND_EXPR
10701           && TREE_CODE (TREE_OPERAND (arg0, 0)) == RSHIFT_EXPR
10702           && TREE_CODE (TREE_OPERAND (TREE_OPERAND (arg0, 0), 1))
10703              == INTEGER_CST
10704           && integer_pow2p (TREE_OPERAND (arg0, 1))
10705           && integer_zerop (arg1))
10706         {
10707           tree itype = TREE_TYPE (arg0);
10708           tree arg001 = TREE_OPERAND (TREE_OPERAND (arg0, 0), 1);
10709           prec = TYPE_PRECISION (itype);
10710
10711           /* Check for a valid shift count.  */
10712           if (wi::ltu_p (arg001, prec))
10713             {
10714               tree arg01 = TREE_OPERAND (arg0, 1);
10715               tree arg000 = TREE_OPERAND (TREE_OPERAND (arg0, 0), 0);
10716               unsigned HOST_WIDE_INT log2 = tree_log2 (arg01);
10717               /* If (C2 << C1) doesn't overflow, then ((X >> C1) & C2) != 0
10718                  can be rewritten as (X & (C2 << C1)) != 0.  */
10719               if ((log2 + TREE_INT_CST_LOW (arg001)) < prec)
10720                 {
10721                   tem = fold_build2_loc (loc, LSHIFT_EXPR, itype, arg01, arg001);
10722                   tem = fold_build2_loc (loc, BIT_AND_EXPR, itype, arg000, tem);
10723                   return fold_build2_loc (loc, code, type, tem,
10724                                           fold_convert_loc (loc, itype, arg1));
10725                 }
10726               /* Otherwise, for signed (arithmetic) shifts,
10727                  ((X >> C1) & C2) != 0 is rewritten as X < 0, and
10728                  ((X >> C1) & C2) == 0 is rewritten as X >= 0.  */
10729               else if (!TYPE_UNSIGNED (itype))
10730                 return fold_build2_loc (loc, code == EQ_EXPR ? GE_EXPR : LT_EXPR, type,
10731                                     arg000, build_int_cst (itype, 0));
10732               /* Otherwise, of unsigned (logical) shifts,
10733                  ((X >> C1) & C2) != 0 is rewritten as (X,false), and
10734                  ((X >> C1) & C2) == 0 is rewritten as (X,true).  */
10735               else
10736                 return omit_one_operand_loc (loc, type,
10737                                          code == EQ_EXPR ? integer_one_node
10738                                                          : integer_zero_node,
10739                                          arg000);
10740             }
10741         }
10742
10743       /* If we have (A & C) == D where D & ~C != 0, convert this into 0.
10744          Similarly for NE_EXPR.  */
10745       if (TREE_CODE (arg0) == BIT_AND_EXPR
10746           && TREE_CODE (arg1) == INTEGER_CST
10747           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
10748         {
10749           tree notc = fold_build1_loc (loc, BIT_NOT_EXPR,
10750                                    TREE_TYPE (TREE_OPERAND (arg0, 1)),
10751                                    TREE_OPERAND (arg0, 1));
10752           tree dandnotc
10753             = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg0),
10754                                fold_convert_loc (loc, TREE_TYPE (arg0), arg1),
10755                                notc);
10756           tree rslt = code == EQ_EXPR ? integer_zero_node : integer_one_node;
10757           if (integer_nonzerop (dandnotc))
10758             return omit_one_operand_loc (loc, type, rslt, arg0);
10759         }
10760
10761       /* If this is a comparison of a field, we may be able to simplify it.  */
10762       if ((TREE_CODE (arg0) == COMPONENT_REF
10763            || TREE_CODE (arg0) == BIT_FIELD_REF)
10764           /* Handle the constant case even without -O
10765              to make sure the warnings are given.  */
10766           && (optimize || TREE_CODE (arg1) == INTEGER_CST))
10767         {
10768           t1 = optimize_bit_field_compare (loc, code, type, arg0, arg1);
10769           if (t1)
10770             return t1;
10771         }
10772
10773       /* Optimize comparisons of strlen vs zero to a compare of the
10774          first character of the string vs zero.  To wit,
10775                 strlen(ptr) == 0   =>  *ptr == 0
10776                 strlen(ptr) != 0   =>  *ptr != 0
10777          Other cases should reduce to one of these two (or a constant)
10778          due to the return value of strlen being unsigned.  */
10779       if (TREE_CODE (arg0) == CALL_EXPR
10780           && integer_zerop (arg1))
10781         {
10782           tree fndecl = get_callee_fndecl (arg0);
10783
10784           if (fndecl
10785               && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
10786               && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STRLEN
10787               && call_expr_nargs (arg0) == 1
10788               && TREE_CODE (TREE_TYPE (CALL_EXPR_ARG (arg0, 0))) == POINTER_TYPE)
10789             {
10790               tree iref = build_fold_indirect_ref_loc (loc,
10791                                                    CALL_EXPR_ARG (arg0, 0));
10792               return fold_build2_loc (loc, code, type, iref,
10793                                   build_int_cst (TREE_TYPE (iref), 0));
10794             }
10795         }
10796
10797       /* Fold (X >> C) != 0 into X < 0 if C is one less than the width
10798          of X.  Similarly fold (X >> C) == 0 into X >= 0.  */
10799       if (TREE_CODE (arg0) == RSHIFT_EXPR
10800           && integer_zerop (arg1)
10801           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
10802         {
10803           tree arg00 = TREE_OPERAND (arg0, 0);
10804           tree arg01 = TREE_OPERAND (arg0, 1);
10805           tree itype = TREE_TYPE (arg00);
10806           if (wi::eq_p (arg01, element_precision (itype) - 1))
10807             {
10808               if (TYPE_UNSIGNED (itype))
10809                 {
10810                   itype = signed_type_for (itype);
10811                   arg00 = fold_convert_loc (loc, itype, arg00);
10812                 }
10813               return fold_build2_loc (loc, code == EQ_EXPR ? GE_EXPR : LT_EXPR,
10814                                   type, arg00, build_zero_cst (itype));
10815             }
10816         }
10817
10818       /* Fold (~X & C) == 0 into (X & C) != 0 and (~X & C) != 0 into
10819          (X & C) == 0 when C is a single bit.  */
10820       if (TREE_CODE (arg0) == BIT_AND_EXPR
10821           && TREE_CODE (TREE_OPERAND (arg0, 0)) == BIT_NOT_EXPR
10822           && integer_zerop (arg1)
10823           && integer_pow2p (TREE_OPERAND (arg0, 1)))
10824         {
10825           tem = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg0),
10826                                  TREE_OPERAND (TREE_OPERAND (arg0, 0), 0),
10827                                  TREE_OPERAND (arg0, 1));
10828           return fold_build2_loc (loc, code == EQ_EXPR ? NE_EXPR : EQ_EXPR,
10829                                   type, tem,
10830                                   fold_convert_loc (loc, TREE_TYPE (arg0),
10831                                                     arg1));
10832         }
10833
10834       /* Fold ((X & C) ^ C) eq/ne 0 into (X & C) ne/eq 0, when the
10835          constant C is a power of two, i.e. a single bit.  */
10836       if (TREE_CODE (arg0) == BIT_XOR_EXPR
10837           && TREE_CODE (TREE_OPERAND (arg0, 0)) == BIT_AND_EXPR
10838           && integer_zerop (arg1)
10839           && integer_pow2p (TREE_OPERAND (arg0, 1))
10840           && operand_equal_p (TREE_OPERAND (TREE_OPERAND (arg0, 0), 1),
10841                               TREE_OPERAND (arg0, 1), OEP_ONLY_CONST))
10842         {
10843           tree arg00 = TREE_OPERAND (arg0, 0);
10844           return fold_build2_loc (loc, code == EQ_EXPR ? NE_EXPR : EQ_EXPR, type,
10845                               arg00, build_int_cst (TREE_TYPE (arg00), 0));
10846         }
10847
10848       /* Likewise, fold ((X ^ C) & C) eq/ne 0 into (X & C) ne/eq 0,
10849          when is C is a power of two, i.e. a single bit.  */
10850       if (TREE_CODE (arg0) == BIT_AND_EXPR
10851           && TREE_CODE (TREE_OPERAND (arg0, 0)) == BIT_XOR_EXPR
10852           && integer_zerop (arg1)
10853           && integer_pow2p (TREE_OPERAND (arg0, 1))
10854           && operand_equal_p (TREE_OPERAND (TREE_OPERAND (arg0, 0), 1),
10855                               TREE_OPERAND (arg0, 1), OEP_ONLY_CONST))
10856         {
10857           tree arg000 = TREE_OPERAND (TREE_OPERAND (arg0, 0), 0);
10858           tem = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg000),
10859                              arg000, TREE_OPERAND (arg0, 1));
10860           return fold_build2_loc (loc, code == EQ_EXPR ? NE_EXPR : EQ_EXPR, type,
10861                               tem, build_int_cst (TREE_TYPE (tem), 0));
10862         }
10863
10864       if (integer_zerop (arg1)
10865           && tree_expr_nonzero_p (arg0))
10866         {
10867           tree res = constant_boolean_node (code==NE_EXPR, type);
10868           return omit_one_operand_loc (loc, type, res, arg0);
10869         }
10870
10871       /* Fold (X & C) op (Y & C) as (X ^ Y) & C op 0", and symmetries.  */
10872       if (TREE_CODE (arg0) == BIT_AND_EXPR
10873           && TREE_CODE (arg1) == BIT_AND_EXPR)
10874         {
10875           tree arg00 = TREE_OPERAND (arg0, 0);
10876           tree arg01 = TREE_OPERAND (arg0, 1);
10877           tree arg10 = TREE_OPERAND (arg1, 0);
10878           tree arg11 = TREE_OPERAND (arg1, 1);
10879           tree itype = TREE_TYPE (arg0);
10880
10881           if (operand_equal_p (arg01, arg11, 0))
10882             return fold_build2_loc (loc, code, type,
10883                                 fold_build2_loc (loc, BIT_AND_EXPR, itype,
10884                                              fold_build2_loc (loc,
10885                                                           BIT_XOR_EXPR, itype,
10886                                                           arg00, arg10),
10887                                              arg01),
10888                                 build_zero_cst (itype));
10889
10890           if (operand_equal_p (arg01, arg10, 0))
10891             return fold_build2_loc (loc, code, type,
10892                                 fold_build2_loc (loc, BIT_AND_EXPR, itype,
10893                                              fold_build2_loc (loc,
10894                                                           BIT_XOR_EXPR, itype,
10895                                                           arg00, arg11),
10896                                              arg01),
10897                                 build_zero_cst (itype));
10898
10899           if (operand_equal_p (arg00, arg11, 0))
10900             return fold_build2_loc (loc, code, type,
10901                                 fold_build2_loc (loc, BIT_AND_EXPR, itype,
10902                                              fold_build2_loc (loc,
10903                                                           BIT_XOR_EXPR, itype,
10904                                                           arg01, arg10),
10905                                              arg00),
10906                                 build_zero_cst (itype));
10907
10908           if (operand_equal_p (arg00, arg10, 0))
10909             return fold_build2_loc (loc, code, type,
10910                                 fold_build2_loc (loc, BIT_AND_EXPR, itype,
10911                                              fold_build2_loc (loc,
10912                                                           BIT_XOR_EXPR, itype,
10913                                                           arg01, arg11),
10914                                              arg00),
10915                                 build_zero_cst (itype));
10916         }
10917
10918       if (TREE_CODE (arg0) == BIT_XOR_EXPR
10919           && TREE_CODE (arg1) == BIT_XOR_EXPR)
10920         {
10921           tree arg00 = TREE_OPERAND (arg0, 0);
10922           tree arg01 = TREE_OPERAND (arg0, 1);
10923           tree arg10 = TREE_OPERAND (arg1, 0);
10924           tree arg11 = TREE_OPERAND (arg1, 1);
10925           tree itype = TREE_TYPE (arg0);
10926
10927           /* Optimize (X ^ Z) op (Y ^ Z) as X op Y, and symmetries.
10928              operand_equal_p guarantees no side-effects so we don't need
10929              to use omit_one_operand on Z.  */
10930           if (operand_equal_p (arg01, arg11, 0))
10931             return fold_build2_loc (loc, code, type, arg00,
10932                                     fold_convert_loc (loc, TREE_TYPE (arg00),
10933                                                       arg10));
10934           if (operand_equal_p (arg01, arg10, 0))
10935             return fold_build2_loc (loc, code, type, arg00,
10936                                     fold_convert_loc (loc, TREE_TYPE (arg00),
10937                                                       arg11));
10938           if (operand_equal_p (arg00, arg11, 0))
10939             return fold_build2_loc (loc, code, type, arg01,
10940                                     fold_convert_loc (loc, TREE_TYPE (arg01),
10941                                                       arg10));
10942           if (operand_equal_p (arg00, arg10, 0))
10943             return fold_build2_loc (loc, code, type, arg01,
10944                                     fold_convert_loc (loc, TREE_TYPE (arg01),
10945                                                       arg11));
10946
10947           /* Optimize (X ^ C1) op (Y ^ C2) as (X ^ (C1 ^ C2)) op Y.  */
10948           if (TREE_CODE (arg01) == INTEGER_CST
10949               && TREE_CODE (arg11) == INTEGER_CST)
10950             {
10951               tem = fold_build2_loc (loc, BIT_XOR_EXPR, itype, arg01,
10952                                      fold_convert_loc (loc, itype, arg11));
10953               tem = fold_build2_loc (loc, BIT_XOR_EXPR, itype, arg00, tem);
10954               return fold_build2_loc (loc, code, type, tem,
10955                                       fold_convert_loc (loc, itype, arg10));
10956             }
10957         }
10958
10959       /* Attempt to simplify equality/inequality comparisons of complex
10960          values.  Only lower the comparison if the result is known or
10961          can be simplified to a single scalar comparison.  */
10962       if ((TREE_CODE (arg0) == COMPLEX_EXPR
10963            || TREE_CODE (arg0) == COMPLEX_CST)
10964           && (TREE_CODE (arg1) == COMPLEX_EXPR
10965               || TREE_CODE (arg1) == COMPLEX_CST))
10966         {
10967           tree real0, imag0, real1, imag1;
10968           tree rcond, icond;
10969
10970           if (TREE_CODE (arg0) == COMPLEX_EXPR)
10971             {
10972               real0 = TREE_OPERAND (arg0, 0);
10973               imag0 = TREE_OPERAND (arg0, 1);
10974             }
10975           else
10976             {
10977               real0 = TREE_REALPART (arg0);
10978               imag0 = TREE_IMAGPART (arg0);
10979             }
10980
10981           if (TREE_CODE (arg1) == COMPLEX_EXPR)
10982             {
10983               real1 = TREE_OPERAND (arg1, 0);
10984               imag1 = TREE_OPERAND (arg1, 1);
10985             }
10986           else
10987             {
10988               real1 = TREE_REALPART (arg1);
10989               imag1 = TREE_IMAGPART (arg1);
10990             }
10991
10992           rcond = fold_binary_loc (loc, code, type, real0, real1);
10993           if (rcond && TREE_CODE (rcond) == INTEGER_CST)
10994             {
10995               if (integer_zerop (rcond))
10996                 {
10997                   if (code == EQ_EXPR)
10998                     return omit_two_operands_loc (loc, type, boolean_false_node,
10999                                               imag0, imag1);
11000                   return fold_build2_loc (loc, NE_EXPR, type, imag0, imag1);
11001                 }
11002               else
11003                 {
11004                   if (code == NE_EXPR)
11005                     return omit_two_operands_loc (loc, type, boolean_true_node,
11006                                               imag0, imag1);
11007                   return fold_build2_loc (loc, EQ_EXPR, type, imag0, imag1);
11008                 }
11009             }
11010
11011           icond = fold_binary_loc (loc, code, type, imag0, imag1);
11012           if (icond && TREE_CODE (icond) == INTEGER_CST)
11013             {
11014               if (integer_zerop (icond))
11015                 {
11016                   if (code == EQ_EXPR)
11017                     return omit_two_operands_loc (loc, type, boolean_false_node,
11018                                               real0, real1);
11019                   return fold_build2_loc (loc, NE_EXPR, type, real0, real1);
11020                 }
11021               else
11022                 {
11023                   if (code == NE_EXPR)
11024                     return omit_two_operands_loc (loc, type, boolean_true_node,
11025                                               real0, real1);
11026                   return fold_build2_loc (loc, EQ_EXPR, type, real0, real1);
11027                 }
11028             }
11029         }
11030
11031       return NULL_TREE;
11032
11033     case LT_EXPR:
11034     case GT_EXPR:
11035     case LE_EXPR:
11036     case GE_EXPR:
11037       tem = fold_comparison (loc, code, type, op0, op1);
11038       if (tem != NULL_TREE)
11039         return tem;
11040
11041       /* Transform comparisons of the form X +- C CMP X.  */
11042       if ((TREE_CODE (arg0) == PLUS_EXPR || TREE_CODE (arg0) == MINUS_EXPR)
11043           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0)
11044           && ((TREE_CODE (TREE_OPERAND (arg0, 1)) == REAL_CST
11045                && !HONOR_SNANS (arg0))
11046               || (TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
11047                   && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))))
11048         {
11049           tree arg01 = TREE_OPERAND (arg0, 1);
11050           enum tree_code code0 = TREE_CODE (arg0);
11051           int is_positive;
11052
11053           if (TREE_CODE (arg01) == REAL_CST)
11054             is_positive = REAL_VALUE_NEGATIVE (TREE_REAL_CST (arg01)) ? -1 : 1;
11055           else
11056             is_positive = tree_int_cst_sgn (arg01);
11057
11058           /* (X - c) > X becomes false.  */
11059           if (code == GT_EXPR
11060               && ((code0 == MINUS_EXPR && is_positive >= 0)
11061                   || (code0 == PLUS_EXPR && is_positive <= 0)))
11062             {
11063               if (TREE_CODE (arg01) == INTEGER_CST
11064                   && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
11065                 fold_overflow_warning (("assuming signed overflow does not "
11066                                         "occur when assuming that (X - c) > X "
11067                                         "is always false"),
11068                                        WARN_STRICT_OVERFLOW_ALL);
11069               return constant_boolean_node (0, type);
11070             }
11071
11072           /* Likewise (X + c) < X becomes false.  */
11073           if (code == LT_EXPR
11074               && ((code0 == PLUS_EXPR && is_positive >= 0)
11075                   || (code0 == MINUS_EXPR && is_positive <= 0)))
11076             {
11077               if (TREE_CODE (arg01) == INTEGER_CST
11078                   && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
11079                 fold_overflow_warning (("assuming signed overflow does not "
11080                                         "occur when assuming that "
11081                                         "(X + c) < X is always false"),
11082                                        WARN_STRICT_OVERFLOW_ALL);
11083               return constant_boolean_node (0, type);
11084             }
11085
11086           /* Convert (X - c) <= X to true.  */
11087           if (!HONOR_NANS (arg1)
11088               && code == LE_EXPR
11089               && ((code0 == MINUS_EXPR && is_positive >= 0)
11090                   || (code0 == PLUS_EXPR && is_positive <= 0)))
11091             {
11092               if (TREE_CODE (arg01) == INTEGER_CST
11093                   && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
11094                 fold_overflow_warning (("assuming signed overflow does not "
11095                                         "occur when assuming that "
11096                                         "(X - c) <= X is always true"),
11097                                        WARN_STRICT_OVERFLOW_ALL);
11098               return constant_boolean_node (1, type);
11099             }
11100
11101           /* Convert (X + c) >= X to true.  */
11102           if (!HONOR_NANS (arg1)
11103               && code == GE_EXPR
11104               && ((code0 == PLUS_EXPR && is_positive >= 0)
11105                   || (code0 == MINUS_EXPR && is_positive <= 0)))
11106             {
11107               if (TREE_CODE (arg01) == INTEGER_CST
11108                   && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
11109                 fold_overflow_warning (("assuming signed overflow does not "
11110                                         "occur when assuming that "
11111                                         "(X + c) >= X is always true"),
11112                                        WARN_STRICT_OVERFLOW_ALL);
11113               return constant_boolean_node (1, type);
11114             }
11115
11116           if (TREE_CODE (arg01) == INTEGER_CST)
11117             {
11118               /* Convert X + c > X and X - c < X to true for integers.  */
11119               if (code == GT_EXPR
11120                   && ((code0 == PLUS_EXPR && is_positive > 0)
11121                       || (code0 == MINUS_EXPR && is_positive < 0)))
11122                 {
11123                   if (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
11124                     fold_overflow_warning (("assuming signed overflow does "
11125                                             "not occur when assuming that "
11126                                             "(X + c) > X is always true"),
11127                                            WARN_STRICT_OVERFLOW_ALL);
11128                   return constant_boolean_node (1, type);
11129                 }
11130
11131               if (code == LT_EXPR
11132                   && ((code0 == MINUS_EXPR && is_positive > 0)
11133                       || (code0 == PLUS_EXPR && is_positive < 0)))
11134                 {
11135                   if (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
11136                     fold_overflow_warning (("assuming signed overflow does "
11137                                             "not occur when assuming that "
11138                                             "(X - c) < X is always true"),
11139                                            WARN_STRICT_OVERFLOW_ALL);
11140                   return constant_boolean_node (1, type);
11141                 }
11142
11143               /* Convert X + c <= X and X - c >= X to false for integers.  */
11144               if (code == LE_EXPR
11145                   && ((code0 == PLUS_EXPR && is_positive > 0)
11146                       || (code0 == MINUS_EXPR && is_positive < 0)))
11147                 {
11148                   if (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
11149                     fold_overflow_warning (("assuming signed overflow does "
11150                                             "not occur when assuming that "
11151                                             "(X + c) <= X is always false"),
11152                                            WARN_STRICT_OVERFLOW_ALL);
11153                   return constant_boolean_node (0, type);
11154                 }
11155
11156               if (code == GE_EXPR
11157                   && ((code0 == MINUS_EXPR && is_positive > 0)
11158                       || (code0 == PLUS_EXPR && is_positive < 0)))
11159                 {
11160                   if (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
11161                     fold_overflow_warning (("assuming signed overflow does "
11162                                             "not occur when assuming that "
11163                                             "(X - c) >= X is always false"),
11164                                            WARN_STRICT_OVERFLOW_ALL);
11165                   return constant_boolean_node (0, type);
11166                 }
11167             }
11168         }
11169
11170       /* If we are comparing an ABS_EXPR with a constant, we can
11171          convert all the cases into explicit comparisons, but they may
11172          well not be faster than doing the ABS and one comparison.
11173          But ABS (X) <= C is a range comparison, which becomes a subtraction
11174          and a comparison, and is probably faster.  */
11175       if (code == LE_EXPR
11176           && TREE_CODE (arg1) == INTEGER_CST
11177           && TREE_CODE (arg0) == ABS_EXPR
11178           && ! TREE_SIDE_EFFECTS (arg0)
11179           && (0 != (tem = negate_expr (arg1)))
11180           && TREE_CODE (tem) == INTEGER_CST
11181           && !TREE_OVERFLOW (tem))
11182         return fold_build2_loc (loc, TRUTH_ANDIF_EXPR, type,
11183                             build2 (GE_EXPR, type,
11184                                     TREE_OPERAND (arg0, 0), tem),
11185                             build2 (LE_EXPR, type,
11186                                     TREE_OPERAND (arg0, 0), arg1));
11187
11188       /* Convert ABS_EXPR<x> >= 0 to true.  */
11189       strict_overflow_p = false;
11190       if (code == GE_EXPR
11191           && (integer_zerop (arg1)
11192               || (! HONOR_NANS (arg0)
11193                   && real_zerop (arg1)))
11194           && tree_expr_nonnegative_warnv_p (arg0, &strict_overflow_p))
11195         {
11196           if (strict_overflow_p)
11197             fold_overflow_warning (("assuming signed overflow does not occur "
11198                                     "when simplifying comparison of "
11199                                     "absolute value and zero"),
11200                                    WARN_STRICT_OVERFLOW_CONDITIONAL);
11201           return omit_one_operand_loc (loc, type,
11202                                        constant_boolean_node (true, type),
11203                                        arg0);
11204         }
11205
11206       /* Convert ABS_EXPR<x> < 0 to false.  */
11207       strict_overflow_p = false;
11208       if (code == LT_EXPR
11209           && (integer_zerop (arg1) || real_zerop (arg1))
11210           && tree_expr_nonnegative_warnv_p (arg0, &strict_overflow_p))
11211         {
11212           if (strict_overflow_p)
11213             fold_overflow_warning (("assuming signed overflow does not occur "
11214                                     "when simplifying comparison of "
11215                                     "absolute value and zero"),
11216                                    WARN_STRICT_OVERFLOW_CONDITIONAL);
11217           return omit_one_operand_loc (loc, type,
11218                                        constant_boolean_node (false, type),
11219                                        arg0);
11220         }
11221
11222       /* If X is unsigned, convert X < (1 << Y) into X >> Y == 0
11223          and similarly for >= into !=.  */
11224       if ((code == LT_EXPR || code == GE_EXPR)
11225           && TYPE_UNSIGNED (TREE_TYPE (arg0))
11226           && TREE_CODE (arg1) == LSHIFT_EXPR
11227           && integer_onep (TREE_OPERAND (arg1, 0)))
11228         return build2_loc (loc, code == LT_EXPR ? EQ_EXPR : NE_EXPR, type,
11229                            build2 (RSHIFT_EXPR, TREE_TYPE (arg0), arg0,
11230                                    TREE_OPERAND (arg1, 1)),
11231                            build_zero_cst (TREE_TYPE (arg0)));
11232
11233       /* Similarly for X < (cast) (1 << Y).  But cast can't be narrowing,
11234          otherwise Y might be >= # of bits in X's type and thus e.g.
11235          (unsigned char) (1 << Y) for Y 15 might be 0.
11236          If the cast is widening, then 1 << Y should have unsigned type,
11237          otherwise if Y is number of bits in the signed shift type minus 1,
11238          we can't optimize this.  E.g. (unsigned long long) (1 << Y) for Y
11239          31 might be 0xffffffff80000000.  */
11240       if ((code == LT_EXPR || code == GE_EXPR)
11241           && TYPE_UNSIGNED (TREE_TYPE (arg0))
11242           && CONVERT_EXPR_P (arg1)
11243           && TREE_CODE (TREE_OPERAND (arg1, 0)) == LSHIFT_EXPR
11244           && (element_precision (TREE_TYPE (arg1))
11245               >= element_precision (TREE_TYPE (TREE_OPERAND (arg1, 0))))
11246           && (TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (arg1, 0)))
11247               || (element_precision (TREE_TYPE (arg1))
11248                   == element_precision (TREE_TYPE (TREE_OPERAND (arg1, 0)))))
11249           && integer_onep (TREE_OPERAND (TREE_OPERAND (arg1, 0), 0)))
11250         {
11251           tem = build2 (RSHIFT_EXPR, TREE_TYPE (arg0), arg0,
11252                         TREE_OPERAND (TREE_OPERAND (arg1, 0), 1));
11253           return build2_loc (loc, code == LT_EXPR ? EQ_EXPR : NE_EXPR, type,
11254                              fold_convert_loc (loc, TREE_TYPE (arg0), tem),
11255                              build_zero_cst (TREE_TYPE (arg0)));
11256         }
11257
11258       return NULL_TREE;
11259
11260     case UNORDERED_EXPR:
11261     case ORDERED_EXPR:
11262     case UNLT_EXPR:
11263     case UNLE_EXPR:
11264     case UNGT_EXPR:
11265     case UNGE_EXPR:
11266     case UNEQ_EXPR:
11267     case LTGT_EXPR:
11268       /* Fold (double)float1 CMP (double)float2 into float1 CMP float2.  */
11269       {
11270         tree targ0 = strip_float_extensions (arg0);
11271         tree targ1 = strip_float_extensions (arg1);
11272         tree newtype = TREE_TYPE (targ0);
11273
11274         if (TYPE_PRECISION (TREE_TYPE (targ1)) > TYPE_PRECISION (newtype))
11275           newtype = TREE_TYPE (targ1);
11276
11277         if (TYPE_PRECISION (newtype) < TYPE_PRECISION (TREE_TYPE (arg0)))
11278           return fold_build2_loc (loc, code, type,
11279                               fold_convert_loc (loc, newtype, targ0),
11280                               fold_convert_loc (loc, newtype, targ1));
11281       }
11282
11283       return NULL_TREE;
11284
11285     case COMPOUND_EXPR:
11286       /* When pedantic, a compound expression can be neither an lvalue
11287          nor an integer constant expression.  */
11288       if (TREE_SIDE_EFFECTS (arg0) || TREE_CONSTANT (arg1))
11289         return NULL_TREE;
11290       /* Don't let (0, 0) be null pointer constant.  */
11291       tem = integer_zerop (arg1) ? build1 (NOP_EXPR, type, arg1)
11292                                  : fold_convert_loc (loc, type, arg1);
11293       return pedantic_non_lvalue_loc (loc, tem);
11294
11295     case ASSERT_EXPR:
11296       /* An ASSERT_EXPR should never be passed to fold_binary.  */
11297       gcc_unreachable ();
11298
11299     default:
11300       return NULL_TREE;
11301     } /* switch (code) */
11302 }
11303
11304 /* Callback for walk_tree, looking for LABEL_EXPR.  Return *TP if it is
11305    a LABEL_EXPR; otherwise return NULL_TREE.  Do not check the subtrees
11306    of GOTO_EXPR.  */
11307
11308 static tree
11309 contains_label_1 (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED)
11310 {
11311   switch (TREE_CODE (*tp))
11312     {
11313     case LABEL_EXPR:
11314       return *tp;
11315
11316     case GOTO_EXPR:
11317       *walk_subtrees = 0;
11318
11319       /* ... fall through ...  */
11320
11321     default:
11322       return NULL_TREE;
11323     }
11324 }
11325
11326 /* Return whether the sub-tree ST contains a label which is accessible from
11327    outside the sub-tree.  */
11328
11329 static bool
11330 contains_label_p (tree st)
11331 {
11332   return
11333    (walk_tree_without_duplicates (&st, contains_label_1 , NULL) != NULL_TREE);
11334 }
11335
11336 /* Fold a ternary expression of code CODE and type TYPE with operands
11337    OP0, OP1, and OP2.  Return the folded expression if folding is
11338    successful.  Otherwise, return NULL_TREE.  */
11339
11340 tree
11341 fold_ternary_loc (location_t loc, enum tree_code code, tree type,
11342                   tree op0, tree op1, tree op2)
11343 {
11344   tree tem;
11345   tree arg0 = NULL_TREE, arg1 = NULL_TREE, arg2 = NULL_TREE;
11346   enum tree_code_class kind = TREE_CODE_CLASS (code);
11347
11348   gcc_assert (IS_EXPR_CODE_CLASS (kind)
11349               && TREE_CODE_LENGTH (code) == 3);
11350
11351   /* If this is a commutative operation, and OP0 is a constant, move it
11352      to OP1 to reduce the number of tests below.  */
11353   if (commutative_ternary_tree_code (code)
11354       && tree_swap_operands_p (op0, op1, true))
11355     return fold_build3_loc (loc, code, type, op1, op0, op2);
11356
11357   tem = generic_simplify (loc, code, type, op0, op1, op2);
11358   if (tem)
11359     return tem;
11360
11361   /* Strip any conversions that don't change the mode.  This is safe
11362      for every expression, except for a comparison expression because
11363      its signedness is derived from its operands.  So, in the latter
11364      case, only strip conversions that don't change the signedness.
11365
11366      Note that this is done as an internal manipulation within the
11367      constant folder, in order to find the simplest representation of
11368      the arguments so that their form can be studied.  In any cases,
11369      the appropriate type conversions should be put back in the tree
11370      that will get out of the constant folder.  */
11371   if (op0)
11372     {
11373       arg0 = op0;
11374       STRIP_NOPS (arg0);
11375     }
11376
11377   if (op1)
11378     {
11379       arg1 = op1;
11380       STRIP_NOPS (arg1);
11381     }
11382
11383   if (op2)
11384     {
11385       arg2 = op2;
11386       STRIP_NOPS (arg2);
11387     }
11388
11389   switch (code)
11390     {
11391     case COMPONENT_REF:
11392       if (TREE_CODE (arg0) == CONSTRUCTOR
11393           && ! type_contains_placeholder_p (TREE_TYPE (arg0)))
11394         {
11395           unsigned HOST_WIDE_INT idx;
11396           tree field, value;
11397           FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg0), idx, field, value)
11398             if (field == arg1)
11399               return value;
11400         }
11401       return NULL_TREE;
11402
11403     case COND_EXPR:
11404     case VEC_COND_EXPR:
11405       /* Pedantic ANSI C says that a conditional expression is never an lvalue,
11406          so all simple results must be passed through pedantic_non_lvalue.  */
11407       if (TREE_CODE (arg0) == INTEGER_CST)
11408         {
11409           tree unused_op = integer_zerop (arg0) ? op1 : op2;
11410           tem = integer_zerop (arg0) ? op2 : op1;
11411           /* Only optimize constant conditions when the selected branch
11412              has the same type as the COND_EXPR.  This avoids optimizing
11413              away "c ? x : throw", where the throw has a void type.
11414              Avoid throwing away that operand which contains label.  */
11415           if ((!TREE_SIDE_EFFECTS (unused_op)
11416                || !contains_label_p (unused_op))
11417               && (! VOID_TYPE_P (TREE_TYPE (tem))
11418                   || VOID_TYPE_P (type)))
11419             return pedantic_non_lvalue_loc (loc, tem);
11420           return NULL_TREE;
11421         }
11422       else if (TREE_CODE (arg0) == VECTOR_CST)
11423         {
11424           if ((TREE_CODE (arg1) == VECTOR_CST
11425                || TREE_CODE (arg1) == CONSTRUCTOR)
11426               && (TREE_CODE (arg2) == VECTOR_CST
11427                   || TREE_CODE (arg2) == CONSTRUCTOR))
11428             {
11429               unsigned int nelts = TYPE_VECTOR_SUBPARTS (type), i;
11430               unsigned char *sel = XALLOCAVEC (unsigned char, nelts);
11431               gcc_assert (nelts == VECTOR_CST_NELTS (arg0));
11432               for (i = 0; i < nelts; i++)
11433                 {
11434                   tree val = VECTOR_CST_ELT (arg0, i);
11435                   if (integer_all_onesp (val))
11436                     sel[i] = i;
11437                   else if (integer_zerop (val))
11438                     sel[i] = nelts + i;
11439                   else /* Currently unreachable.  */
11440                     return NULL_TREE;
11441                 }
11442               tree t = fold_vec_perm (type, arg1, arg2, sel);
11443               if (t != NULL_TREE)
11444                 return t;
11445             }
11446         }
11447
11448       /* If we have A op B ? A : C, we may be able to convert this to a
11449          simpler expression, depending on the operation and the values
11450          of B and C.  Signed zeros prevent all of these transformations,
11451          for reasons given above each one.
11452
11453          Also try swapping the arguments and inverting the conditional.  */
11454       if (COMPARISON_CLASS_P (arg0)
11455           && operand_equal_for_comparison_p (TREE_OPERAND (arg0, 0),
11456                                              arg1, TREE_OPERAND (arg0, 1))
11457           && !HONOR_SIGNED_ZEROS (element_mode (arg1)))
11458         {
11459           tem = fold_cond_expr_with_comparison (loc, type, arg0, op1, op2);
11460           if (tem)
11461             return tem;
11462         }
11463
11464       if (COMPARISON_CLASS_P (arg0)
11465           && operand_equal_for_comparison_p (TREE_OPERAND (arg0, 0),
11466                                              op2,
11467                                              TREE_OPERAND (arg0, 1))
11468           && !HONOR_SIGNED_ZEROS (element_mode (op2)))
11469         {
11470           location_t loc0 = expr_location_or (arg0, loc);
11471           tem = fold_invert_truthvalue (loc0, arg0);
11472           if (tem && COMPARISON_CLASS_P (tem))
11473             {
11474               tem = fold_cond_expr_with_comparison (loc, type, tem, op2, op1);
11475               if (tem)
11476                 return tem;
11477             }
11478         }
11479
11480       /* If the second operand is simpler than the third, swap them
11481          since that produces better jump optimization results.  */
11482       if (truth_value_p (TREE_CODE (arg0))
11483           && tree_swap_operands_p (op1, op2, false))
11484         {
11485           location_t loc0 = expr_location_or (arg0, loc);
11486           /* See if this can be inverted.  If it can't, possibly because
11487              it was a floating-point inequality comparison, don't do
11488              anything.  */
11489           tem = fold_invert_truthvalue (loc0, arg0);
11490           if (tem)
11491             return fold_build3_loc (loc, code, type, tem, op2, op1);
11492         }
11493
11494       /* Convert A ? 1 : 0 to simply A.  */
11495       if ((code == VEC_COND_EXPR ? integer_all_onesp (op1)
11496                                  : (integer_onep (op1)
11497                                     && !VECTOR_TYPE_P (type)))
11498           && integer_zerop (op2)
11499           /* If we try to convert OP0 to our type, the
11500              call to fold will try to move the conversion inside
11501              a COND, which will recurse.  In that case, the COND_EXPR
11502              is probably the best choice, so leave it alone.  */
11503           && type == TREE_TYPE (arg0))
11504         return pedantic_non_lvalue_loc (loc, arg0);
11505
11506       /* Convert A ? 0 : 1 to !A.  This prefers the use of NOT_EXPR
11507          over COND_EXPR in cases such as floating point comparisons.  */
11508       if (integer_zerop (op1)
11509           && (code == VEC_COND_EXPR ? integer_all_onesp (op2)
11510                                     : (integer_onep (op2)
11511                                        && !VECTOR_TYPE_P (type)))
11512           && truth_value_p (TREE_CODE (arg0)))
11513         return pedantic_non_lvalue_loc (loc,
11514                                     fold_convert_loc (loc, type,
11515                                               invert_truthvalue_loc (loc,
11516                                                                      arg0)));
11517
11518       /* A < 0 ? <sign bit of A> : 0 is simply (A & <sign bit of A>).  */
11519       if (TREE_CODE (arg0) == LT_EXPR
11520           && integer_zerop (TREE_OPERAND (arg0, 1))
11521           && integer_zerop (op2)
11522           && (tem = sign_bit_p (TREE_OPERAND (arg0, 0), arg1)))
11523         {
11524           /* sign_bit_p looks through both zero and sign extensions,
11525              but for this optimization only sign extensions are
11526              usable.  */
11527           tree tem2 = TREE_OPERAND (arg0, 0);
11528           while (tem != tem2)
11529             {
11530               if (TREE_CODE (tem2) != NOP_EXPR
11531                   || TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (tem2, 0))))
11532                 {
11533                   tem = NULL_TREE;
11534                   break;
11535                 }
11536               tem2 = TREE_OPERAND (tem2, 0);
11537             }
11538           /* sign_bit_p only checks ARG1 bits within A's precision.
11539              If <sign bit of A> has wider type than A, bits outside
11540              of A's precision in <sign bit of A> need to be checked.
11541              If they are all 0, this optimization needs to be done
11542              in unsigned A's type, if they are all 1 in signed A's type,
11543              otherwise this can't be done.  */
11544           if (tem
11545               && TYPE_PRECISION (TREE_TYPE (tem))
11546                  < TYPE_PRECISION (TREE_TYPE (arg1))
11547               && TYPE_PRECISION (TREE_TYPE (tem))
11548                  < TYPE_PRECISION (type))
11549             {
11550               int inner_width, outer_width;
11551               tree tem_type;
11552
11553               inner_width = TYPE_PRECISION (TREE_TYPE (tem));
11554               outer_width = TYPE_PRECISION (TREE_TYPE (arg1));
11555               if (outer_width > TYPE_PRECISION (type))
11556                 outer_width = TYPE_PRECISION (type);
11557
11558               wide_int mask = wi::shifted_mask
11559                 (inner_width, outer_width - inner_width, false,
11560                  TYPE_PRECISION (TREE_TYPE (arg1)));
11561
11562               wide_int common = mask & arg1;
11563               if (common == mask)
11564                 {
11565                   tem_type = signed_type_for (TREE_TYPE (tem));
11566                   tem = fold_convert_loc (loc, tem_type, tem);
11567                 }
11568               else if (common == 0)
11569                 {
11570                   tem_type = unsigned_type_for (TREE_TYPE (tem));
11571                   tem = fold_convert_loc (loc, tem_type, tem);
11572                 }
11573               else
11574                 tem = NULL;
11575             }
11576
11577           if (tem)
11578             return
11579               fold_convert_loc (loc, type,
11580                                 fold_build2_loc (loc, BIT_AND_EXPR,
11581                                              TREE_TYPE (tem), tem,
11582                                              fold_convert_loc (loc,
11583                                                                TREE_TYPE (tem),
11584                                                                arg1)));
11585         }
11586
11587       /* (A >> N) & 1 ? (1 << N) : 0 is simply A & (1 << N).  A & 1 was
11588          already handled above.  */
11589       if (TREE_CODE (arg0) == BIT_AND_EXPR
11590           && integer_onep (TREE_OPERAND (arg0, 1))
11591           && integer_zerop (op2)
11592           && integer_pow2p (arg1))
11593         {
11594           tree tem = TREE_OPERAND (arg0, 0);
11595           STRIP_NOPS (tem);
11596           if (TREE_CODE (tem) == RSHIFT_EXPR
11597               && tree_fits_uhwi_p (TREE_OPERAND (tem, 1))
11598               && (unsigned HOST_WIDE_INT) tree_log2 (arg1) ==
11599                  tree_to_uhwi (TREE_OPERAND (tem, 1)))
11600             return fold_build2_loc (loc, BIT_AND_EXPR, type,
11601                                 TREE_OPERAND (tem, 0), arg1);
11602         }
11603
11604       /* A & N ? N : 0 is simply A & N if N is a power of two.  This
11605          is probably obsolete because the first operand should be a
11606          truth value (that's why we have the two cases above), but let's
11607          leave it in until we can confirm this for all front-ends.  */
11608       if (integer_zerop (op2)
11609           && TREE_CODE (arg0) == NE_EXPR
11610           && integer_zerop (TREE_OPERAND (arg0, 1))
11611           && integer_pow2p (arg1)
11612           && TREE_CODE (TREE_OPERAND (arg0, 0)) == BIT_AND_EXPR
11613           && operand_equal_p (TREE_OPERAND (TREE_OPERAND (arg0, 0), 1),
11614                               arg1, OEP_ONLY_CONST))
11615         return pedantic_non_lvalue_loc (loc,
11616                                     fold_convert_loc (loc, type,
11617                                                       TREE_OPERAND (arg0, 0)));
11618
11619       /* Disable the transformations below for vectors, since
11620          fold_binary_op_with_conditional_arg may undo them immediately,
11621          yielding an infinite loop.  */
11622       if (code == VEC_COND_EXPR)
11623         return NULL_TREE;
11624
11625       /* Convert A ? B : 0 into A && B if A and B are truth values.  */
11626       if (integer_zerop (op2)
11627           && truth_value_p (TREE_CODE (arg0))
11628           && truth_value_p (TREE_CODE (arg1))
11629           && (code == VEC_COND_EXPR || !VECTOR_TYPE_P (type)))
11630         return fold_build2_loc (loc, code == VEC_COND_EXPR ? BIT_AND_EXPR
11631                                                            : TRUTH_ANDIF_EXPR,
11632                                 type, fold_convert_loc (loc, type, arg0), arg1);
11633
11634       /* Convert A ? B : 1 into !A || B if A and B are truth values.  */
11635       if (code == VEC_COND_EXPR ? integer_all_onesp (op2) : integer_onep (op2)
11636           && truth_value_p (TREE_CODE (arg0))
11637           && truth_value_p (TREE_CODE (arg1))
11638           && (code == VEC_COND_EXPR || !VECTOR_TYPE_P (type)))
11639         {
11640           location_t loc0 = expr_location_or (arg0, loc);
11641           /* Only perform transformation if ARG0 is easily inverted.  */
11642           tem = fold_invert_truthvalue (loc0, arg0);
11643           if (tem)
11644             return fold_build2_loc (loc, code == VEC_COND_EXPR
11645                                          ? BIT_IOR_EXPR
11646                                          : TRUTH_ORIF_EXPR,
11647                                     type, fold_convert_loc (loc, type, tem),
11648                                     arg1);
11649         }
11650
11651       /* Convert A ? 0 : B into !A && B if A and B are truth values.  */
11652       if (integer_zerop (arg1)
11653           && truth_value_p (TREE_CODE (arg0))
11654           && truth_value_p (TREE_CODE (op2))
11655           && (code == VEC_COND_EXPR || !VECTOR_TYPE_P (type)))
11656         {
11657           location_t loc0 = expr_location_or (arg0, loc);
11658           /* Only perform transformation if ARG0 is easily inverted.  */
11659           tem = fold_invert_truthvalue (loc0, arg0);
11660           if (tem)
11661             return fold_build2_loc (loc, code == VEC_COND_EXPR
11662                                          ? BIT_AND_EXPR : TRUTH_ANDIF_EXPR,
11663                                     type, fold_convert_loc (loc, type, tem),
11664                                     op2);
11665         }
11666
11667       /* Convert A ? 1 : B into A || B if A and B are truth values.  */
11668       if (code == VEC_COND_EXPR ? integer_all_onesp (arg1) : integer_onep (arg1)
11669           && truth_value_p (TREE_CODE (arg0))
11670           && truth_value_p (TREE_CODE (op2))
11671           && (code == VEC_COND_EXPR || !VECTOR_TYPE_P (type)))
11672         return fold_build2_loc (loc, code == VEC_COND_EXPR
11673                                      ? BIT_IOR_EXPR : TRUTH_ORIF_EXPR,
11674                                 type, fold_convert_loc (loc, type, arg0), op2);
11675
11676       return NULL_TREE;
11677
11678     case CALL_EXPR:
11679       /* CALL_EXPRs used to be ternary exprs.  Catch any mistaken uses
11680          of fold_ternary on them.  */
11681       gcc_unreachable ();
11682
11683     case BIT_FIELD_REF:
11684       if ((TREE_CODE (arg0) == VECTOR_CST
11685            || (TREE_CODE (arg0) == CONSTRUCTOR
11686                && TREE_CODE (TREE_TYPE (arg0)) == VECTOR_TYPE))
11687           && (type == TREE_TYPE (TREE_TYPE (arg0))
11688               || (TREE_CODE (type) == VECTOR_TYPE
11689                   && TREE_TYPE (type) == TREE_TYPE (TREE_TYPE (arg0)))))
11690         {
11691           tree eltype = TREE_TYPE (TREE_TYPE (arg0));
11692           unsigned HOST_WIDE_INT width = tree_to_uhwi (TYPE_SIZE (eltype));
11693           unsigned HOST_WIDE_INT n = tree_to_uhwi (arg1);
11694           unsigned HOST_WIDE_INT idx = tree_to_uhwi (op2);
11695
11696           if (n != 0
11697               && (idx % width) == 0
11698               && (n % width) == 0
11699               && ((idx + n) / width) <= TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0)))
11700             {
11701               idx = idx / width;
11702               n = n / width;
11703
11704               if (TREE_CODE (arg0) == VECTOR_CST)
11705                 {
11706                   if (n == 1)
11707                     return VECTOR_CST_ELT (arg0, idx);
11708
11709                   tree *vals = XALLOCAVEC (tree, n);
11710                   for (unsigned i = 0; i < n; ++i)
11711                     vals[i] = VECTOR_CST_ELT (arg0, idx + i);
11712                   return build_vector (type, vals);
11713                 }
11714
11715               /* Constructor elements can be subvectors.  */
11716               unsigned HOST_WIDE_INT k = 1;
11717               if (CONSTRUCTOR_NELTS (arg0) != 0)
11718                 {
11719                   tree cons_elem = TREE_TYPE (CONSTRUCTOR_ELT (arg0, 0)->value);
11720                   if (TREE_CODE (cons_elem) == VECTOR_TYPE)
11721                     k = TYPE_VECTOR_SUBPARTS (cons_elem);
11722                 }
11723
11724               /* We keep an exact subset of the constructor elements.  */
11725               if ((idx % k) == 0 && (n % k) == 0)
11726                 {
11727                   if (CONSTRUCTOR_NELTS (arg0) == 0)
11728                     return build_constructor (type, NULL);
11729                   idx /= k;
11730                   n /= k;
11731                   if (n == 1)
11732                     {
11733                       if (idx < CONSTRUCTOR_NELTS (arg0))
11734                         return CONSTRUCTOR_ELT (arg0, idx)->value;
11735                       return build_zero_cst (type);
11736                     }
11737
11738                   vec<constructor_elt, va_gc> *vals;
11739                   vec_alloc (vals, n);
11740                   for (unsigned i = 0;
11741                        i < n && idx + i < CONSTRUCTOR_NELTS (arg0);
11742                        ++i)
11743                     CONSTRUCTOR_APPEND_ELT (vals, NULL_TREE,
11744                                             CONSTRUCTOR_ELT
11745                                               (arg0, idx + i)->value);
11746                   return build_constructor (type, vals);
11747                 }
11748               /* The bitfield references a single constructor element.  */
11749               else if (idx + n <= (idx / k + 1) * k)
11750                 {
11751                   if (CONSTRUCTOR_NELTS (arg0) <= idx / k)
11752                     return build_zero_cst (type);
11753                   else if (n == k)
11754                     return CONSTRUCTOR_ELT (arg0, idx / k)->value;
11755                   else
11756                     return fold_build3_loc (loc, code, type,
11757                       CONSTRUCTOR_ELT (arg0, idx / k)->value, op1,
11758                       build_int_cst (TREE_TYPE (op2), (idx % k) * width));
11759                 }
11760             }
11761         }
11762
11763       /* A bit-field-ref that referenced the full argument can be stripped.  */
11764       if (INTEGRAL_TYPE_P (TREE_TYPE (arg0))
11765           && TYPE_PRECISION (TREE_TYPE (arg0)) == tree_to_uhwi (arg1)
11766           && integer_zerop (op2))
11767         return fold_convert_loc (loc, type, arg0);
11768
11769       /* On constants we can use native encode/interpret to constant
11770          fold (nearly) all BIT_FIELD_REFs.  */
11771       if (CONSTANT_CLASS_P (arg0)
11772           && can_native_interpret_type_p (type)
11773           && tree_fits_uhwi_p (TYPE_SIZE_UNIT (TREE_TYPE (arg0)))
11774           /* This limitation should not be necessary, we just need to
11775              round this up to mode size.  */
11776           && tree_to_uhwi (op1) % BITS_PER_UNIT == 0
11777           /* Need bit-shifting of the buffer to relax the following.  */
11778           && tree_to_uhwi (op2) % BITS_PER_UNIT == 0)
11779         {
11780           unsigned HOST_WIDE_INT bitpos = tree_to_uhwi (op2);
11781           unsigned HOST_WIDE_INT bitsize = tree_to_uhwi (op1);
11782           unsigned HOST_WIDE_INT clen;
11783           clen = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (arg0)));
11784           /* ???  We cannot tell native_encode_expr to start at
11785              some random byte only.  So limit us to a reasonable amount
11786              of work.  */
11787           if (clen <= 4096)
11788             {
11789               unsigned char *b = XALLOCAVEC (unsigned char, clen);
11790               unsigned HOST_WIDE_INT len = native_encode_expr (arg0, b, clen);
11791               if (len > 0
11792                   && len * BITS_PER_UNIT >= bitpos + bitsize)
11793                 {
11794                   tree v = native_interpret_expr (type,
11795                                                   b + bitpos / BITS_PER_UNIT,
11796                                                   bitsize / BITS_PER_UNIT);
11797                   if (v)
11798                     return v;
11799                 }
11800             }
11801         }
11802
11803       return NULL_TREE;
11804
11805     case FMA_EXPR:
11806       /* For integers we can decompose the FMA if possible.  */
11807       if (TREE_CODE (arg0) == INTEGER_CST
11808           && TREE_CODE (arg1) == INTEGER_CST)
11809         return fold_build2_loc (loc, PLUS_EXPR, type,
11810                                 const_binop (MULT_EXPR, arg0, arg1), arg2);
11811       if (integer_zerop (arg2))
11812         return fold_build2_loc (loc, MULT_EXPR, type, arg0, arg1);
11813
11814       return fold_fma (loc, type, arg0, arg1, arg2);
11815
11816     case VEC_PERM_EXPR:
11817       if (TREE_CODE (arg2) == VECTOR_CST)
11818         {
11819           unsigned int nelts = TYPE_VECTOR_SUBPARTS (type), i, mask, mask2;
11820           unsigned char *sel = XALLOCAVEC (unsigned char, 2 * nelts);
11821           unsigned char *sel2 = sel + nelts;
11822           bool need_mask_canon = false;
11823           bool need_mask_canon2 = false;
11824           bool all_in_vec0 = true;
11825           bool all_in_vec1 = true;
11826           bool maybe_identity = true;
11827           bool single_arg = (op0 == op1);
11828           bool changed = false;
11829
11830           mask2 = 2 * nelts - 1;
11831           mask = single_arg ? (nelts - 1) : mask2;
11832           gcc_assert (nelts == VECTOR_CST_NELTS (arg2));
11833           for (i = 0; i < nelts; i++)
11834             {
11835               tree val = VECTOR_CST_ELT (arg2, i);
11836               if (TREE_CODE (val) != INTEGER_CST)
11837                 return NULL_TREE;
11838
11839               /* Make sure that the perm value is in an acceptable
11840                  range.  */
11841               wide_int t = val;
11842               need_mask_canon |= wi::gtu_p (t, mask);
11843               need_mask_canon2 |= wi::gtu_p (t, mask2);
11844               sel[i] = t.to_uhwi () & mask;
11845               sel2[i] = t.to_uhwi () & mask2;
11846
11847               if (sel[i] < nelts)
11848                 all_in_vec1 = false;
11849               else
11850                 all_in_vec0 = false;
11851
11852               if ((sel[i] & (nelts-1)) != i)
11853                 maybe_identity = false;
11854             }
11855
11856           if (maybe_identity)
11857             {
11858               if (all_in_vec0)
11859                 return op0;
11860               if (all_in_vec1)
11861                 return op1;
11862             }
11863
11864           if (all_in_vec0)
11865             op1 = op0;
11866           else if (all_in_vec1)
11867             {
11868               op0 = op1;
11869               for (i = 0; i < nelts; i++)
11870                 sel[i] -= nelts;
11871               need_mask_canon = true;
11872             }
11873
11874           if ((TREE_CODE (op0) == VECTOR_CST
11875                || TREE_CODE (op0) == CONSTRUCTOR)
11876               && (TREE_CODE (op1) == VECTOR_CST
11877                   || TREE_CODE (op1) == CONSTRUCTOR))
11878             {
11879               tree t = fold_vec_perm (type, op0, op1, sel);
11880               if (t != NULL_TREE)
11881                 return t;
11882             }
11883
11884           if (op0 == op1 && !single_arg)
11885             changed = true;
11886
11887           /* Some targets are deficient and fail to expand a single
11888              argument permutation while still allowing an equivalent
11889              2-argument version.  */
11890           if (need_mask_canon && arg2 == op2
11891               && !can_vec_perm_p (TYPE_MODE (type), false, sel)
11892               && can_vec_perm_p (TYPE_MODE (type), false, sel2))
11893             {
11894               need_mask_canon = need_mask_canon2;
11895               sel = sel2;
11896             }
11897
11898           if (need_mask_canon && arg2 == op2)
11899             {
11900               tree *tsel = XALLOCAVEC (tree, nelts);
11901               tree eltype = TREE_TYPE (TREE_TYPE (arg2));
11902               for (i = 0; i < nelts; i++)
11903                 tsel[i] = build_int_cst (eltype, sel[i]);
11904               op2 = build_vector (TREE_TYPE (arg2), tsel);
11905               changed = true;
11906             }
11907
11908           if (changed)
11909             return build3_loc (loc, VEC_PERM_EXPR, type, op0, op1, op2);
11910         }
11911       return NULL_TREE;
11912
11913     default:
11914       return NULL_TREE;
11915     } /* switch (code) */
11916 }
11917
11918 /* Perform constant folding and related simplification of EXPR.
11919    The related simplifications include x*1 => x, x*0 => 0, etc.,
11920    and application of the associative law.
11921    NOP_EXPR conversions may be removed freely (as long as we
11922    are careful not to change the type of the overall expression).
11923    We cannot simplify through a CONVERT_EXPR, FIX_EXPR or FLOAT_EXPR,
11924    but we can constant-fold them if they have constant operands.  */
11925
11926 #ifdef ENABLE_FOLD_CHECKING
11927 # define fold(x) fold_1 (x)
11928 static tree fold_1 (tree);
11929 static
11930 #endif
11931 tree
11932 fold (tree expr)
11933 {
11934   const tree t = expr;
11935   enum tree_code code = TREE_CODE (t);
11936   enum tree_code_class kind = TREE_CODE_CLASS (code);
11937   tree tem;
11938   location_t loc = EXPR_LOCATION (expr);
11939
11940   /* Return right away if a constant.  */
11941   if (kind == tcc_constant)
11942     return t;
11943
11944   /* CALL_EXPR-like objects with variable numbers of operands are
11945      treated specially.  */
11946   if (kind == tcc_vl_exp)
11947     {
11948       if (code == CALL_EXPR)
11949         {
11950           tem = fold_call_expr (loc, expr, false);
11951           return tem ? tem : expr;
11952         }
11953       return expr;
11954     }
11955
11956   if (IS_EXPR_CODE_CLASS (kind))
11957     {
11958       tree type = TREE_TYPE (t);
11959       tree op0, op1, op2;
11960
11961       switch (TREE_CODE_LENGTH (code))
11962         {
11963         case 1:
11964           op0 = TREE_OPERAND (t, 0);
11965           tem = fold_unary_loc (loc, code, type, op0);
11966           return tem ? tem : expr;
11967         case 2:
11968           op0 = TREE_OPERAND (t, 0);
11969           op1 = TREE_OPERAND (t, 1);
11970           tem = fold_binary_loc (loc, code, type, op0, op1);
11971           return tem ? tem : expr;
11972         case 3:
11973           op0 = TREE_OPERAND (t, 0);
11974           op1 = TREE_OPERAND (t, 1);
11975           op2 = TREE_OPERAND (t, 2);
11976           tem = fold_ternary_loc (loc, code, type, op0, op1, op2);
11977           return tem ? tem : expr;
11978         default:
11979           break;
11980         }
11981     }
11982
11983   switch (code)
11984     {
11985     case ARRAY_REF:
11986       {
11987         tree op0 = TREE_OPERAND (t, 0);
11988         tree op1 = TREE_OPERAND (t, 1);
11989
11990         if (TREE_CODE (op1) == INTEGER_CST
11991             && TREE_CODE (op0) == CONSTRUCTOR
11992             && ! type_contains_placeholder_p (TREE_TYPE (op0)))
11993           {
11994             vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (op0);
11995             unsigned HOST_WIDE_INT end = vec_safe_length (elts);
11996             unsigned HOST_WIDE_INT begin = 0;
11997
11998             /* Find a matching index by means of a binary search.  */
11999             while (begin != end)
12000               {
12001                 unsigned HOST_WIDE_INT middle = (begin + end) / 2;
12002                 tree index = (*elts)[middle].index;
12003
12004                 if (TREE_CODE (index) == INTEGER_CST
12005                     && tree_int_cst_lt (index, op1))
12006                   begin = middle + 1;
12007                 else if (TREE_CODE (index) == INTEGER_CST
12008                          && tree_int_cst_lt (op1, index))
12009                   end = middle;
12010                 else if (TREE_CODE (index) == RANGE_EXPR
12011                          && tree_int_cst_lt (TREE_OPERAND (index, 1), op1))
12012                   begin = middle + 1;
12013                 else if (TREE_CODE (index) == RANGE_EXPR
12014                          && tree_int_cst_lt (op1, TREE_OPERAND (index, 0)))
12015                   end = middle;
12016                 else
12017                   return (*elts)[middle].value;
12018               }
12019           }
12020
12021         return t;
12022       }
12023
12024       /* Return a VECTOR_CST if possible.  */
12025     case CONSTRUCTOR:
12026       {
12027         tree type = TREE_TYPE (t);
12028         if (TREE_CODE (type) != VECTOR_TYPE)
12029           return t;
12030
12031         tree *vec = XALLOCAVEC (tree, TYPE_VECTOR_SUBPARTS (type));
12032         unsigned HOST_WIDE_INT idx, pos = 0;
12033         tree value;
12034
12035         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (t), idx, value)
12036           {
12037             if (!CONSTANT_CLASS_P (value))
12038               return t;
12039             if (TREE_CODE (value) == VECTOR_CST)
12040               {
12041                 for (unsigned i = 0; i < VECTOR_CST_NELTS (value); ++i)
12042                   vec[pos++] = VECTOR_CST_ELT (value, i);
12043               }
12044             else
12045               vec[pos++] = value;
12046           }
12047         for (; pos < TYPE_VECTOR_SUBPARTS (type); ++pos)
12048           vec[pos] = build_zero_cst (TREE_TYPE (type));
12049
12050         return build_vector (type, vec);
12051       }
12052
12053     case CONST_DECL:
12054       return fold (DECL_INITIAL (t));
12055
12056     default:
12057       return t;
12058     } /* switch (code) */
12059 }
12060
12061 #ifdef ENABLE_FOLD_CHECKING
12062 #undef fold
12063
12064 static void fold_checksum_tree (const_tree, struct md5_ctx *,
12065                                 hash_table<nofree_ptr_hash<const tree_node> > *);
12066 static void fold_check_failed (const_tree, const_tree);
12067 void print_fold_checksum (const_tree);
12068
12069 /* When --enable-checking=fold, compute a digest of expr before
12070    and after actual fold call to see if fold did not accidentally
12071    change original expr.  */
12072
12073 tree
12074 fold (tree expr)
12075 {
12076   tree ret;
12077   struct md5_ctx ctx;
12078   unsigned char checksum_before[16], checksum_after[16];
12079   hash_table<nofree_ptr_hash<const tree_node> > ht (32);
12080
12081   md5_init_ctx (&ctx);
12082   fold_checksum_tree (expr, &ctx, &ht);
12083   md5_finish_ctx (&ctx, checksum_before);
12084   ht.empty ();
12085
12086   ret = fold_1 (expr);
12087
12088   md5_init_ctx (&ctx);
12089   fold_checksum_tree (expr, &ctx, &ht);
12090   md5_finish_ctx (&ctx, checksum_after);
12091
12092   if (memcmp (checksum_before, checksum_after, 16))
12093     fold_check_failed (expr, ret);
12094
12095   return ret;
12096 }
12097
12098 void
12099 print_fold_checksum (const_tree expr)
12100 {
12101   struct md5_ctx ctx;
12102   unsigned char checksum[16], cnt;
12103   hash_table<nofree_ptr_hash<const tree_node> > ht (32);
12104
12105   md5_init_ctx (&ctx);
12106   fold_checksum_tree (expr, &ctx, &ht);
12107   md5_finish_ctx (&ctx, checksum);
12108   for (cnt = 0; cnt < 16; ++cnt)
12109     fprintf (stderr, "%02x", checksum[cnt]);
12110   putc ('\n', stderr);
12111 }
12112
12113 static void
12114 fold_check_failed (const_tree expr ATTRIBUTE_UNUSED, const_tree ret ATTRIBUTE_UNUSED)
12115 {
12116   internal_error ("fold check: original tree changed by fold");
12117 }
12118
12119 static void
12120 fold_checksum_tree (const_tree expr, struct md5_ctx *ctx,
12121                     hash_table<nofree_ptr_hash <const tree_node> > *ht)
12122 {
12123   const tree_node **slot;
12124   enum tree_code code;
12125   union tree_node buf;
12126   int i, len;
12127
12128  recursive_label:
12129   if (expr == NULL)
12130     return;
12131   slot = ht->find_slot (expr, INSERT);
12132   if (*slot != NULL)
12133     return;
12134   *slot = expr;
12135   code = TREE_CODE (expr);
12136   if (TREE_CODE_CLASS (code) == tcc_declaration
12137       && HAS_DECL_ASSEMBLER_NAME_P (expr))
12138     {
12139       /* Allow DECL_ASSEMBLER_NAME and symtab_node to be modified.  */
12140       memcpy ((char *) &buf, expr, tree_size (expr));
12141       SET_DECL_ASSEMBLER_NAME ((tree)&buf, NULL);
12142       buf.decl_with_vis.symtab_node = NULL;
12143       expr = (tree) &buf;
12144     }
12145   else if (TREE_CODE_CLASS (code) == tcc_type
12146            && (TYPE_POINTER_TO (expr)
12147                || TYPE_REFERENCE_TO (expr)
12148                || TYPE_CACHED_VALUES_P (expr)
12149                || TYPE_CONTAINS_PLACEHOLDER_INTERNAL (expr)
12150                || TYPE_NEXT_VARIANT (expr)))
12151     {
12152       /* Allow these fields to be modified.  */
12153       tree tmp;
12154       memcpy ((char *) &buf, expr, tree_size (expr));
12155       expr = tmp = (tree) &buf;
12156       TYPE_CONTAINS_PLACEHOLDER_INTERNAL (tmp) = 0;
12157       TYPE_POINTER_TO (tmp) = NULL;
12158       TYPE_REFERENCE_TO (tmp) = NULL;
12159       TYPE_NEXT_VARIANT (tmp) = NULL;
12160       if (TYPE_CACHED_VALUES_P (tmp))
12161         {
12162           TYPE_CACHED_VALUES_P (tmp) = 0;
12163           TYPE_CACHED_VALUES (tmp) = NULL;
12164         }
12165     }
12166   md5_process_bytes (expr, tree_size (expr), ctx);
12167   if (CODE_CONTAINS_STRUCT (code, TS_TYPED))
12168     fold_checksum_tree (TREE_TYPE (expr), ctx, ht);
12169   if (TREE_CODE_CLASS (code) != tcc_type
12170       && TREE_CODE_CLASS (code) != tcc_declaration
12171       && code != TREE_LIST
12172       && code != SSA_NAME
12173       && CODE_CONTAINS_STRUCT (code, TS_COMMON))
12174     fold_checksum_tree (TREE_CHAIN (expr), ctx, ht);
12175   switch (TREE_CODE_CLASS (code))
12176     {
12177     case tcc_constant:
12178       switch (code)
12179         {
12180         case STRING_CST:
12181           md5_process_bytes (TREE_STRING_POINTER (expr),
12182                              TREE_STRING_LENGTH (expr), ctx);
12183           break;
12184         case COMPLEX_CST:
12185           fold_checksum_tree (TREE_REALPART (expr), ctx, ht);
12186           fold_checksum_tree (TREE_IMAGPART (expr), ctx, ht);
12187           break;
12188         case VECTOR_CST:
12189           for (i = 0; i < (int) VECTOR_CST_NELTS (expr); ++i)
12190             fold_checksum_tree (VECTOR_CST_ELT (expr, i), ctx, ht);
12191           break;
12192         default:
12193           break;
12194         }
12195       break;
12196     case tcc_exceptional:
12197       switch (code)
12198         {
12199         case TREE_LIST:
12200           fold_checksum_tree (TREE_PURPOSE (expr), ctx, ht);
12201           fold_checksum_tree (TREE_VALUE (expr), ctx, ht);
12202           expr = TREE_CHAIN (expr);
12203           goto recursive_label;
12204           break;
12205         case TREE_VEC:
12206           for (i = 0; i < TREE_VEC_LENGTH (expr); ++i)
12207             fold_checksum_tree (TREE_VEC_ELT (expr, i), ctx, ht);
12208           break;
12209         default:
12210           break;
12211         }
12212       break;
12213     case tcc_expression:
12214     case tcc_reference:
12215     case tcc_comparison:
12216     case tcc_unary:
12217     case tcc_binary:
12218     case tcc_statement:
12219     case tcc_vl_exp:
12220       len = TREE_OPERAND_LENGTH (expr);
12221       for (i = 0; i < len; ++i)
12222         fold_checksum_tree (TREE_OPERAND (expr, i), ctx, ht);
12223       break;
12224     case tcc_declaration:
12225       fold_checksum_tree (DECL_NAME (expr), ctx, ht);
12226       fold_checksum_tree (DECL_CONTEXT (expr), ctx, ht);
12227       if (CODE_CONTAINS_STRUCT (TREE_CODE (expr), TS_DECL_COMMON))
12228         {
12229           fold_checksum_tree (DECL_SIZE (expr), ctx, ht);
12230           fold_checksum_tree (DECL_SIZE_UNIT (expr), ctx, ht);
12231           fold_checksum_tree (DECL_INITIAL (expr), ctx, ht);
12232           fold_checksum_tree (DECL_ABSTRACT_ORIGIN (expr), ctx, ht);
12233           fold_checksum_tree (DECL_ATTRIBUTES (expr), ctx, ht);
12234         }
12235
12236       if (CODE_CONTAINS_STRUCT (TREE_CODE (expr), TS_DECL_NON_COMMON))
12237         {
12238           if (TREE_CODE (expr) == FUNCTION_DECL)
12239             {
12240               fold_checksum_tree (DECL_VINDEX (expr), ctx, ht);
12241               fold_checksum_tree (DECL_ARGUMENTS (expr), ctx, ht);
12242             }
12243           fold_checksum_tree (DECL_RESULT_FLD (expr), ctx, ht);
12244         }
12245       break;
12246     case tcc_type:
12247       if (TREE_CODE (expr) == ENUMERAL_TYPE)
12248         fold_checksum_tree (TYPE_VALUES (expr), ctx, ht);
12249       fold_checksum_tree (TYPE_SIZE (expr), ctx, ht);
12250       fold_checksum_tree (TYPE_SIZE_UNIT (expr), ctx, ht);
12251       fold_checksum_tree (TYPE_ATTRIBUTES (expr), ctx, ht);
12252       fold_checksum_tree (TYPE_NAME (expr), ctx, ht);
12253       if (INTEGRAL_TYPE_P (expr)
12254           || SCALAR_FLOAT_TYPE_P (expr))
12255         {
12256           fold_checksum_tree (TYPE_MIN_VALUE (expr), ctx, ht);
12257           fold_checksum_tree (TYPE_MAX_VALUE (expr), ctx, ht);
12258         }
12259       fold_checksum_tree (TYPE_MAIN_VARIANT (expr), ctx, ht);
12260       if (TREE_CODE (expr) == RECORD_TYPE
12261           || TREE_CODE (expr) == UNION_TYPE
12262           || TREE_CODE (expr) == QUAL_UNION_TYPE)
12263         fold_checksum_tree (TYPE_BINFO (expr), ctx, ht);
12264       fold_checksum_tree (TYPE_CONTEXT (expr), ctx, ht);
12265       break;
12266     default:
12267       break;
12268     }
12269 }
12270
12271 /* Helper function for outputting the checksum of a tree T.  When
12272    debugging with gdb, you can "define mynext" to be "next" followed
12273    by "call debug_fold_checksum (op0)", then just trace down till the
12274    outputs differ.  */
12275
12276 DEBUG_FUNCTION void
12277 debug_fold_checksum (const_tree t)
12278 {
12279   int i;
12280   unsigned char checksum[16];
12281   struct md5_ctx ctx;
12282   hash_table<nofree_ptr_hash<const tree_node> > ht (32);
12283
12284   md5_init_ctx (&ctx);
12285   fold_checksum_tree (t, &ctx, &ht);
12286   md5_finish_ctx (&ctx, checksum);
12287   ht.empty ();
12288
12289   for (i = 0; i < 16; i++)
12290     fprintf (stderr, "%d ", checksum[i]);
12291
12292   fprintf (stderr, "\n");
12293 }
12294
12295 #endif
12296
12297 /* Fold a unary tree expression with code CODE of type TYPE with an
12298    operand OP0.  LOC is the location of the resulting expression.
12299    Return a folded expression if successful.  Otherwise, return a tree
12300    expression with code CODE of type TYPE with an operand OP0.  */
12301
12302 tree
12303 fold_build1_stat_loc (location_t loc,
12304                       enum tree_code code, tree type, tree op0 MEM_STAT_DECL)
12305 {
12306   tree tem;
12307 #ifdef ENABLE_FOLD_CHECKING
12308   unsigned char checksum_before[16], checksum_after[16];
12309   struct md5_ctx ctx;
12310   hash_table<nofree_ptr_hash<const tree_node> > ht (32);
12311
12312   md5_init_ctx (&ctx);
12313   fold_checksum_tree (op0, &ctx, &ht);
12314   md5_finish_ctx (&ctx, checksum_before);
12315   ht.empty ();
12316 #endif
12317
12318   tem = fold_unary_loc (loc, code, type, op0);
12319   if (!tem)
12320     tem = build1_stat_loc (loc, code, type, op0 PASS_MEM_STAT);
12321
12322 #ifdef ENABLE_FOLD_CHECKING
12323   md5_init_ctx (&ctx);
12324   fold_checksum_tree (op0, &ctx, &ht);
12325   md5_finish_ctx (&ctx, checksum_after);
12326
12327   if (memcmp (checksum_before, checksum_after, 16))
12328     fold_check_failed (op0, tem);
12329 #endif
12330   return tem;
12331 }
12332
12333 /* Fold a binary tree expression with code CODE of type TYPE with
12334    operands OP0 and OP1.  LOC is the location of the resulting
12335    expression.  Return a folded expression if successful.  Otherwise,
12336    return a tree expression with code CODE of type TYPE with operands
12337    OP0 and OP1.  */
12338
12339 tree
12340 fold_build2_stat_loc (location_t loc,
12341                       enum tree_code code, tree type, tree op0, tree op1
12342                       MEM_STAT_DECL)
12343 {
12344   tree tem;
12345 #ifdef ENABLE_FOLD_CHECKING
12346   unsigned char checksum_before_op0[16],
12347                 checksum_before_op1[16],
12348                 checksum_after_op0[16],
12349                 checksum_after_op1[16];
12350   struct md5_ctx ctx;
12351   hash_table<nofree_ptr_hash<const tree_node> > ht (32);
12352
12353   md5_init_ctx (&ctx);
12354   fold_checksum_tree (op0, &ctx, &ht);
12355   md5_finish_ctx (&ctx, checksum_before_op0);
12356   ht.empty ();
12357
12358   md5_init_ctx (&ctx);
12359   fold_checksum_tree (op1, &ctx, &ht);
12360   md5_finish_ctx (&ctx, checksum_before_op1);
12361   ht.empty ();
12362 #endif
12363
12364   tem = fold_binary_loc (loc, code, type, op0, op1);
12365   if (!tem)
12366     tem = build2_stat_loc (loc, code, type, op0, op1 PASS_MEM_STAT);
12367
12368 #ifdef ENABLE_FOLD_CHECKING
12369   md5_init_ctx (&ctx);
12370   fold_checksum_tree (op0, &ctx, &ht);
12371   md5_finish_ctx (&ctx, checksum_after_op0);
12372   ht.empty ();
12373
12374   if (memcmp (checksum_before_op0, checksum_after_op0, 16))
12375     fold_check_failed (op0, tem);
12376
12377   md5_init_ctx (&ctx);
12378   fold_checksum_tree (op1, &ctx, &ht);
12379   md5_finish_ctx (&ctx, checksum_after_op1);
12380
12381   if (memcmp (checksum_before_op1, checksum_after_op1, 16))
12382     fold_check_failed (op1, tem);
12383 #endif
12384   return tem;
12385 }
12386
12387 /* Fold a ternary tree expression with code CODE of type TYPE with
12388    operands OP0, OP1, and OP2.  Return a folded expression if
12389    successful.  Otherwise, return a tree expression with code CODE of
12390    type TYPE with operands OP0, OP1, and OP2.  */
12391
12392 tree
12393 fold_build3_stat_loc (location_t loc, enum tree_code code, tree type,
12394                       tree op0, tree op1, tree op2 MEM_STAT_DECL)
12395 {
12396   tree tem;
12397 #ifdef ENABLE_FOLD_CHECKING
12398   unsigned char checksum_before_op0[16],
12399                 checksum_before_op1[16],
12400                 checksum_before_op2[16],
12401                 checksum_after_op0[16],
12402                 checksum_after_op1[16],
12403                 checksum_after_op2[16];
12404   struct md5_ctx ctx;
12405   hash_table<nofree_ptr_hash<const tree_node> > ht (32);
12406
12407   md5_init_ctx (&ctx);
12408   fold_checksum_tree (op0, &ctx, &ht);
12409   md5_finish_ctx (&ctx, checksum_before_op0);
12410   ht.empty ();
12411
12412   md5_init_ctx (&ctx);
12413   fold_checksum_tree (op1, &ctx, &ht);
12414   md5_finish_ctx (&ctx, checksum_before_op1);
12415   ht.empty ();
12416
12417   md5_init_ctx (&ctx);
12418   fold_checksum_tree (op2, &ctx, &ht);
12419   md5_finish_ctx (&ctx, checksum_before_op2);
12420   ht.empty ();
12421 #endif
12422
12423   gcc_assert (TREE_CODE_CLASS (code) != tcc_vl_exp);
12424   tem = fold_ternary_loc (loc, code, type, op0, op1, op2);
12425   if (!tem)
12426     tem = build3_stat_loc (loc, code, type, op0, op1, op2 PASS_MEM_STAT);
12427
12428 #ifdef ENABLE_FOLD_CHECKING
12429   md5_init_ctx (&ctx);
12430   fold_checksum_tree (op0, &ctx, &ht);
12431   md5_finish_ctx (&ctx, checksum_after_op0);
12432   ht.empty ();
12433
12434   if (memcmp (checksum_before_op0, checksum_after_op0, 16))
12435     fold_check_failed (op0, tem);
12436
12437   md5_init_ctx (&ctx);
12438   fold_checksum_tree (op1, &ctx, &ht);
12439   md5_finish_ctx (&ctx, checksum_after_op1);
12440   ht.empty ();
12441
12442   if (memcmp (checksum_before_op1, checksum_after_op1, 16))
12443     fold_check_failed (op1, tem);
12444
12445   md5_init_ctx (&ctx);
12446   fold_checksum_tree (op2, &ctx, &ht);
12447   md5_finish_ctx (&ctx, checksum_after_op2);
12448
12449   if (memcmp (checksum_before_op2, checksum_after_op2, 16))
12450     fold_check_failed (op2, tem);
12451 #endif
12452   return tem;
12453 }
12454
12455 /* Fold a CALL_EXPR expression of type TYPE with operands FN and NARGS
12456    arguments in ARGARRAY, and a null static chain.
12457    Return a folded expression if successful.  Otherwise, return a CALL_EXPR
12458    of type TYPE from the given operands as constructed by build_call_array.  */
12459
12460 tree
12461 fold_build_call_array_loc (location_t loc, tree type, tree fn,
12462                            int nargs, tree *argarray)
12463 {
12464   tree tem;
12465 #ifdef ENABLE_FOLD_CHECKING
12466   unsigned char checksum_before_fn[16],
12467                 checksum_before_arglist[16],
12468                 checksum_after_fn[16],
12469                 checksum_after_arglist[16];
12470   struct md5_ctx ctx;
12471   hash_table<nofree_ptr_hash<const tree_node> > ht (32);
12472   int i;
12473
12474   md5_init_ctx (&ctx);
12475   fold_checksum_tree (fn, &ctx, &ht);
12476   md5_finish_ctx (&ctx, checksum_before_fn);
12477   ht.empty ();
12478
12479   md5_init_ctx (&ctx);
12480   for (i = 0; i < nargs; i++)
12481     fold_checksum_tree (argarray[i], &ctx, &ht);
12482   md5_finish_ctx (&ctx, checksum_before_arglist);
12483   ht.empty ();
12484 #endif
12485
12486   tem = fold_builtin_call_array (loc, type, fn, nargs, argarray);
12487   if (!tem)
12488     tem = build_call_array_loc (loc, type, fn, nargs, argarray);
12489
12490 #ifdef ENABLE_FOLD_CHECKING
12491   md5_init_ctx (&ctx);
12492   fold_checksum_tree (fn, &ctx, &ht);
12493   md5_finish_ctx (&ctx, checksum_after_fn);
12494   ht.empty ();
12495
12496   if (memcmp (checksum_before_fn, checksum_after_fn, 16))
12497     fold_check_failed (fn, tem);
12498
12499   md5_init_ctx (&ctx);
12500   for (i = 0; i < nargs; i++)
12501     fold_checksum_tree (argarray[i], &ctx, &ht);
12502   md5_finish_ctx (&ctx, checksum_after_arglist);
12503
12504   if (memcmp (checksum_before_arglist, checksum_after_arglist, 16))
12505     fold_check_failed (NULL_TREE, tem);
12506 #endif
12507   return tem;
12508 }
12509
12510 /* Perform constant folding and related simplification of initializer
12511    expression EXPR.  These behave identically to "fold_buildN" but ignore
12512    potential run-time traps and exceptions that fold must preserve.  */
12513
12514 #define START_FOLD_INIT \
12515   int saved_signaling_nans = flag_signaling_nans;\
12516   int saved_trapping_math = flag_trapping_math;\
12517   int saved_rounding_math = flag_rounding_math;\
12518   int saved_trapv = flag_trapv;\
12519   int saved_folding_initializer = folding_initializer;\
12520   flag_signaling_nans = 0;\
12521   flag_trapping_math = 0;\
12522   flag_rounding_math = 0;\
12523   flag_trapv = 0;\
12524   folding_initializer = 1;
12525
12526 #define END_FOLD_INIT \
12527   flag_signaling_nans = saved_signaling_nans;\
12528   flag_trapping_math = saved_trapping_math;\
12529   flag_rounding_math = saved_rounding_math;\
12530   flag_trapv = saved_trapv;\
12531   folding_initializer = saved_folding_initializer;
12532
12533 tree
12534 fold_build1_initializer_loc (location_t loc, enum tree_code code,
12535                              tree type, tree op)
12536 {
12537   tree result;
12538   START_FOLD_INIT;
12539
12540   result = fold_build1_loc (loc, code, type, op);
12541
12542   END_FOLD_INIT;
12543   return result;
12544 }
12545
12546 tree
12547 fold_build2_initializer_loc (location_t loc, enum tree_code code,
12548                              tree type, tree op0, tree op1)
12549 {
12550   tree result;
12551   START_FOLD_INIT;
12552
12553   result = fold_build2_loc (loc, code, type, op0, op1);
12554
12555   END_FOLD_INIT;
12556   return result;
12557 }
12558
12559 tree
12560 fold_build_call_array_initializer_loc (location_t loc, tree type, tree fn,
12561                                        int nargs, tree *argarray)
12562 {
12563   tree result;
12564   START_FOLD_INIT;
12565
12566   result = fold_build_call_array_loc (loc, type, fn, nargs, argarray);
12567
12568   END_FOLD_INIT;
12569   return result;
12570 }
12571
12572 #undef START_FOLD_INIT
12573 #undef END_FOLD_INIT
12574
12575 /* Determine if first argument is a multiple of second argument.  Return 0 if
12576    it is not, or we cannot easily determined it to be.
12577
12578    An example of the sort of thing we care about (at this point; this routine
12579    could surely be made more general, and expanded to do what the *_DIV_EXPR's
12580    fold cases do now) is discovering that
12581
12582      SAVE_EXPR (I) * SAVE_EXPR (J * 8)
12583
12584    is a multiple of
12585
12586      SAVE_EXPR (J * 8)
12587
12588    when we know that the two SAVE_EXPR (J * 8) nodes are the same node.
12589
12590    This code also handles discovering that
12591
12592      SAVE_EXPR (I) * SAVE_EXPR (J * 8)
12593
12594    is a multiple of 8 so we don't have to worry about dealing with a
12595    possible remainder.
12596
12597    Note that we *look* inside a SAVE_EXPR only to determine how it was
12598    calculated; it is not safe for fold to do much of anything else with the
12599    internals of a SAVE_EXPR, since it cannot know when it will be evaluated
12600    at run time.  For example, the latter example above *cannot* be implemented
12601    as SAVE_EXPR (I) * J or any variant thereof, since the value of J at
12602    evaluation time of the original SAVE_EXPR is not necessarily the same at
12603    the time the new expression is evaluated.  The only optimization of this
12604    sort that would be valid is changing
12605
12606      SAVE_EXPR (I) * SAVE_EXPR (SAVE_EXPR (J) * 8)
12607
12608    divided by 8 to
12609
12610      SAVE_EXPR (I) * SAVE_EXPR (J)
12611
12612    (where the same SAVE_EXPR (J) is used in the original and the
12613    transformed version).  */
12614
12615 int
12616 multiple_of_p (tree type, const_tree top, const_tree bottom)
12617 {
12618   if (operand_equal_p (top, bottom, 0))
12619     return 1;
12620
12621   if (TREE_CODE (type) != INTEGER_TYPE)
12622     return 0;
12623
12624   switch (TREE_CODE (top))
12625     {
12626     case BIT_AND_EXPR:
12627       /* Bitwise and provides a power of two multiple.  If the mask is
12628          a multiple of BOTTOM then TOP is a multiple of BOTTOM.  */
12629       if (!integer_pow2p (bottom))
12630         return 0;
12631       /* FALLTHRU */
12632
12633     case MULT_EXPR:
12634       return (multiple_of_p (type, TREE_OPERAND (top, 0), bottom)
12635               || multiple_of_p (type, TREE_OPERAND (top, 1), bottom));
12636
12637     case PLUS_EXPR:
12638     case MINUS_EXPR:
12639       return (multiple_of_p (type, TREE_OPERAND (top, 0), bottom)
12640               && multiple_of_p (type, TREE_OPERAND (top, 1), bottom));
12641
12642     case LSHIFT_EXPR:
12643       if (TREE_CODE (TREE_OPERAND (top, 1)) == INTEGER_CST)
12644         {
12645           tree op1, t1;
12646
12647           op1 = TREE_OPERAND (top, 1);
12648           /* const_binop may not detect overflow correctly,
12649              so check for it explicitly here.  */
12650           if (wi::gtu_p (TYPE_PRECISION (TREE_TYPE (size_one_node)), op1)
12651               && 0 != (t1 = fold_convert (type,
12652                                           const_binop (LSHIFT_EXPR,
12653                                                        size_one_node,
12654                                                        op1)))
12655               && !TREE_OVERFLOW (t1))
12656             return multiple_of_p (type, t1, bottom);
12657         }
12658       return 0;
12659
12660     case NOP_EXPR:
12661       /* Can't handle conversions from non-integral or wider integral type.  */
12662       if ((TREE_CODE (TREE_TYPE (TREE_OPERAND (top, 0))) != INTEGER_TYPE)
12663           || (TYPE_PRECISION (type)
12664               < TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (top, 0)))))
12665         return 0;
12666
12667       /* .. fall through ...  */
12668
12669     case SAVE_EXPR:
12670       return multiple_of_p (type, TREE_OPERAND (top, 0), bottom);
12671
12672     case COND_EXPR:
12673       return (multiple_of_p (type, TREE_OPERAND (top, 1), bottom)
12674               && multiple_of_p (type, TREE_OPERAND (top, 2), bottom));
12675
12676     case INTEGER_CST:
12677       if (TREE_CODE (bottom) != INTEGER_CST
12678           || integer_zerop (bottom)
12679           || (TYPE_UNSIGNED (type)
12680               && (tree_int_cst_sgn (top) < 0
12681                   || tree_int_cst_sgn (bottom) < 0)))
12682         return 0;
12683       return wi::multiple_of_p (wi::to_widest (top), wi::to_widest (bottom),
12684                                 SIGNED);
12685
12686     default:
12687       return 0;
12688     }
12689 }
12690
12691 #define tree_expr_nonnegative_warnv_p(X, Y) \
12692   _Pragma ("GCC error \"Use RECURSE for recursive calls\"") 0
12693
12694 #define RECURSE(X) \
12695   ((tree_expr_nonnegative_warnv_p) (X, strict_overflow_p, depth + 1))
12696
12697 /* Return true if CODE or TYPE is known to be non-negative. */
12698
12699 static bool
12700 tree_simple_nonnegative_warnv_p (enum tree_code code, tree type)
12701 {
12702   if ((TYPE_PRECISION (type) != 1 || TYPE_UNSIGNED (type))
12703       && truth_value_p (code))
12704     /* Truth values evaluate to 0 or 1, which is nonnegative unless we
12705        have a signed:1 type (where the value is -1 and 0).  */
12706     return true;
12707   return false;
12708 }
12709
12710 /* Return true if (CODE OP0) is known to be non-negative.  If the return
12711    value is based on the assumption that signed overflow is undefined,
12712    set *STRICT_OVERFLOW_P to true; otherwise, don't change
12713    *STRICT_OVERFLOW_P.  DEPTH is the current nesting depth of the query.  */
12714
12715 bool
12716 tree_unary_nonnegative_warnv_p (enum tree_code code, tree type, tree op0,
12717                                 bool *strict_overflow_p, int depth)
12718 {
12719   if (TYPE_UNSIGNED (type))
12720     return true;
12721
12722   switch (code)
12723     {
12724     case ABS_EXPR:
12725       /* We can't return 1 if flag_wrapv is set because
12726          ABS_EXPR<INT_MIN> = INT_MIN.  */
12727       if (!ANY_INTEGRAL_TYPE_P (type))
12728         return true;
12729       if (TYPE_OVERFLOW_UNDEFINED (type))
12730         {
12731           *strict_overflow_p = true;
12732           return true;
12733         }
12734       break;
12735
12736     case NON_LVALUE_EXPR:
12737     case FLOAT_EXPR:
12738     case FIX_TRUNC_EXPR:
12739       return RECURSE (op0);
12740
12741     CASE_CONVERT:
12742       {
12743         tree inner_type = TREE_TYPE (op0);
12744         tree outer_type = type;
12745
12746         if (TREE_CODE (outer_type) == REAL_TYPE)
12747           {
12748             if (TREE_CODE (inner_type) == REAL_TYPE)
12749               return RECURSE (op0);
12750             if (INTEGRAL_TYPE_P (inner_type))
12751               {
12752                 if (TYPE_UNSIGNED (inner_type))
12753                   return true;
12754                 return RECURSE (op0);
12755               }
12756           }
12757         else if (INTEGRAL_TYPE_P (outer_type))
12758           {
12759             if (TREE_CODE (inner_type) == REAL_TYPE)
12760               return RECURSE (op0);
12761             if (INTEGRAL_TYPE_P (inner_type))
12762               return TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type)
12763                       && TYPE_UNSIGNED (inner_type);
12764           }
12765       }
12766       break;
12767
12768     default:
12769       return tree_simple_nonnegative_warnv_p (code, type);
12770     }
12771
12772   /* We don't know sign of `t', so be conservative and return false.  */
12773   return false;
12774 }
12775
12776 /* Return true if (CODE OP0 OP1) is known to be non-negative.  If the return
12777    value is based on the assumption that signed overflow is undefined,
12778    set *STRICT_OVERFLOW_P to true; otherwise, don't change
12779    *STRICT_OVERFLOW_P.  DEPTH is the current nesting depth of the query.  */
12780
12781 bool
12782 tree_binary_nonnegative_warnv_p (enum tree_code code, tree type, tree op0,
12783                                  tree op1, bool *strict_overflow_p,
12784                                  int depth)
12785 {
12786   if (TYPE_UNSIGNED (type))
12787     return true;
12788
12789   switch (code)
12790     {
12791     case POINTER_PLUS_EXPR:
12792     case PLUS_EXPR:
12793       if (FLOAT_TYPE_P (type))
12794         return RECURSE (op0) && RECURSE (op1);
12795
12796       /* zero_extend(x) + zero_extend(y) is non-negative if x and y are
12797          both unsigned and at least 2 bits shorter than the result.  */
12798       if (TREE_CODE (type) == INTEGER_TYPE
12799           && TREE_CODE (op0) == NOP_EXPR
12800           && TREE_CODE (op1) == NOP_EXPR)
12801         {
12802           tree inner1 = TREE_TYPE (TREE_OPERAND (op0, 0));
12803           tree inner2 = TREE_TYPE (TREE_OPERAND (op1, 0));
12804           if (TREE_CODE (inner1) == INTEGER_TYPE && TYPE_UNSIGNED (inner1)
12805               && TREE_CODE (inner2) == INTEGER_TYPE && TYPE_UNSIGNED (inner2))
12806             {
12807               unsigned int prec = MAX (TYPE_PRECISION (inner1),
12808                                        TYPE_PRECISION (inner2)) + 1;
12809               return prec < TYPE_PRECISION (type);
12810             }
12811         }
12812       break;
12813
12814     case MULT_EXPR:
12815       if (FLOAT_TYPE_P (type) || TYPE_OVERFLOW_UNDEFINED (type))
12816         {
12817           /* x * x is always non-negative for floating point x
12818              or without overflow.  */
12819           if (operand_equal_p (op0, op1, 0)
12820               || (RECURSE (op0) && RECURSE (op1)))
12821             {
12822               if (ANY_INTEGRAL_TYPE_P (type)
12823                   && TYPE_OVERFLOW_UNDEFINED (type))
12824                 *strict_overflow_p = true;
12825               return true;
12826             }
12827         }
12828
12829       /* zero_extend(x) * zero_extend(y) is non-negative if x and y are
12830          both unsigned and their total bits is shorter than the result.  */
12831       if (TREE_CODE (type) == INTEGER_TYPE
12832           && (TREE_CODE (op0) == NOP_EXPR || TREE_CODE (op0) == INTEGER_CST)
12833           && (TREE_CODE (op1) == NOP_EXPR || TREE_CODE (op1) == INTEGER_CST))
12834         {
12835           tree inner0 = (TREE_CODE (op0) == NOP_EXPR)
12836             ? TREE_TYPE (TREE_OPERAND (op0, 0))
12837             : TREE_TYPE (op0);
12838           tree inner1 = (TREE_CODE (op1) == NOP_EXPR)
12839             ? TREE_TYPE (TREE_OPERAND (op1, 0))
12840             : TREE_TYPE (op1);
12841
12842           bool unsigned0 = TYPE_UNSIGNED (inner0);
12843           bool unsigned1 = TYPE_UNSIGNED (inner1);
12844
12845           if (TREE_CODE (op0) == INTEGER_CST)
12846             unsigned0 = unsigned0 || tree_int_cst_sgn (op0) >= 0;
12847
12848           if (TREE_CODE (op1) == INTEGER_CST)
12849             unsigned1 = unsigned1 || tree_int_cst_sgn (op1) >= 0;
12850
12851           if (TREE_CODE (inner0) == INTEGER_TYPE && unsigned0
12852               && TREE_CODE (inner1) == INTEGER_TYPE && unsigned1)
12853             {
12854               unsigned int precision0 = (TREE_CODE (op0) == INTEGER_CST)
12855                 ? tree_int_cst_min_precision (op0, UNSIGNED)
12856                 : TYPE_PRECISION (inner0);
12857
12858               unsigned int precision1 = (TREE_CODE (op1) == INTEGER_CST)
12859                 ? tree_int_cst_min_precision (op1, UNSIGNED)
12860                 : TYPE_PRECISION (inner1);
12861
12862               return precision0 + precision1 < TYPE_PRECISION (type);
12863             }
12864         }
12865       return false;
12866
12867     case BIT_AND_EXPR:
12868     case MAX_EXPR:
12869       return RECURSE (op0) || RECURSE (op1);
12870
12871     case BIT_IOR_EXPR:
12872     case BIT_XOR_EXPR:
12873     case MIN_EXPR:
12874     case RDIV_EXPR:
12875     case TRUNC_DIV_EXPR:
12876     case CEIL_DIV_EXPR:
12877     case FLOOR_DIV_EXPR:
12878     case ROUND_DIV_EXPR:
12879       return RECURSE (op0) && RECURSE (op1);
12880
12881     case TRUNC_MOD_EXPR:
12882       return RECURSE (op0);
12883
12884     case FLOOR_MOD_EXPR:
12885       return RECURSE (op1);
12886
12887     case CEIL_MOD_EXPR:
12888     case ROUND_MOD_EXPR:
12889     default:
12890       return tree_simple_nonnegative_warnv_p (code, type);
12891     }
12892
12893   /* We don't know sign of `t', so be conservative and return false.  */
12894   return false;
12895 }
12896
12897 /* Return true if T is known to be non-negative.  If the return
12898    value is based on the assumption that signed overflow is undefined,
12899    set *STRICT_OVERFLOW_P to true; otherwise, don't change
12900    *STRICT_OVERFLOW_P.  DEPTH is the current nesting depth of the query.  */
12901
12902 bool
12903 tree_single_nonnegative_warnv_p (tree t, bool *strict_overflow_p, int depth)
12904 {
12905   if (TYPE_UNSIGNED (TREE_TYPE (t)))
12906     return true;
12907
12908   switch (TREE_CODE (t))
12909     {
12910     case INTEGER_CST:
12911       return tree_int_cst_sgn (t) >= 0;
12912
12913     case REAL_CST:
12914       return ! REAL_VALUE_NEGATIVE (TREE_REAL_CST (t));
12915
12916     case FIXED_CST:
12917       return ! FIXED_VALUE_NEGATIVE (TREE_FIXED_CST (t));
12918
12919     case COND_EXPR:
12920       return RECURSE (TREE_OPERAND (t, 1)) && RECURSE (TREE_OPERAND (t, 2));
12921
12922     case SSA_NAME:
12923       /* Limit the depth of recursion to avoid quadratic behavior.
12924          This is expected to catch almost all occurrences in practice.
12925          If this code misses important cases that unbounded recursion
12926          would not, passes that need this information could be revised
12927          to provide it through dataflow propagation.  */
12928       return (!name_registered_for_update_p (t)
12929               && depth < PARAM_VALUE (PARAM_MAX_SSA_NAME_QUERY_DEPTH)
12930               && gimple_stmt_nonnegative_warnv_p (SSA_NAME_DEF_STMT (t),
12931                                                   strict_overflow_p, depth));
12932
12933     default:
12934       return tree_simple_nonnegative_warnv_p (TREE_CODE (t), TREE_TYPE (t));
12935     }
12936 }
12937
12938 /* Return true if T is known to be non-negative.  If the return
12939    value is based on the assumption that signed overflow is undefined,
12940    set *STRICT_OVERFLOW_P to true; otherwise, don't change
12941    *STRICT_OVERFLOW_P.  DEPTH is the current nesting depth of the query.  */
12942
12943 bool
12944 tree_call_nonnegative_warnv_p (tree type, tree fndecl, tree arg0, tree arg1,
12945                                bool *strict_overflow_p, int depth)
12946 {
12947   if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
12948     switch (DECL_FUNCTION_CODE (fndecl))
12949       {
12950         CASE_FLT_FN (BUILT_IN_ACOS):
12951         CASE_FLT_FN (BUILT_IN_ACOSH):
12952         CASE_FLT_FN (BUILT_IN_CABS):
12953         CASE_FLT_FN (BUILT_IN_COSH):
12954         CASE_FLT_FN (BUILT_IN_ERFC):
12955         CASE_FLT_FN (BUILT_IN_EXP):
12956         CASE_FLT_FN (BUILT_IN_EXP10):
12957         CASE_FLT_FN (BUILT_IN_EXP2):
12958         CASE_FLT_FN (BUILT_IN_FABS):
12959         CASE_FLT_FN (BUILT_IN_FDIM):
12960         CASE_FLT_FN (BUILT_IN_HYPOT):
12961         CASE_FLT_FN (BUILT_IN_POW10):
12962         CASE_INT_FN (BUILT_IN_FFS):
12963         CASE_INT_FN (BUILT_IN_PARITY):
12964         CASE_INT_FN (BUILT_IN_POPCOUNT):
12965         CASE_INT_FN (BUILT_IN_CLZ):
12966         CASE_INT_FN (BUILT_IN_CLRSB):
12967       case BUILT_IN_BSWAP32:
12968       case BUILT_IN_BSWAP64:
12969         /* Always true.  */
12970         return true;
12971
12972         CASE_FLT_FN (BUILT_IN_SQRT):
12973         /* sqrt(-0.0) is -0.0.  */
12974         if (!HONOR_SIGNED_ZEROS (element_mode (type)))
12975           return true;
12976         return RECURSE (arg0);
12977
12978         CASE_FLT_FN (BUILT_IN_ASINH):
12979         CASE_FLT_FN (BUILT_IN_ATAN):
12980         CASE_FLT_FN (BUILT_IN_ATANH):
12981         CASE_FLT_FN (BUILT_IN_CBRT):
12982         CASE_FLT_FN (BUILT_IN_CEIL):
12983         CASE_FLT_FN (BUILT_IN_ERF):
12984         CASE_FLT_FN (BUILT_IN_EXPM1):
12985         CASE_FLT_FN (BUILT_IN_FLOOR):
12986         CASE_FLT_FN (BUILT_IN_FMOD):
12987         CASE_FLT_FN (BUILT_IN_FREXP):
12988         CASE_FLT_FN (BUILT_IN_ICEIL):
12989         CASE_FLT_FN (BUILT_IN_IFLOOR):
12990         CASE_FLT_FN (BUILT_IN_IRINT):
12991         CASE_FLT_FN (BUILT_IN_IROUND):
12992         CASE_FLT_FN (BUILT_IN_LCEIL):
12993         CASE_FLT_FN (BUILT_IN_LDEXP):
12994         CASE_FLT_FN (BUILT_IN_LFLOOR):
12995         CASE_FLT_FN (BUILT_IN_LLCEIL):
12996         CASE_FLT_FN (BUILT_IN_LLFLOOR):
12997         CASE_FLT_FN (BUILT_IN_LLRINT):
12998         CASE_FLT_FN (BUILT_IN_LLROUND):
12999         CASE_FLT_FN (BUILT_IN_LRINT):
13000         CASE_FLT_FN (BUILT_IN_LROUND):
13001         CASE_FLT_FN (BUILT_IN_MODF):
13002         CASE_FLT_FN (BUILT_IN_NEARBYINT):
13003         CASE_FLT_FN (BUILT_IN_RINT):
13004         CASE_FLT_FN (BUILT_IN_ROUND):
13005         CASE_FLT_FN (BUILT_IN_SCALB):
13006         CASE_FLT_FN (BUILT_IN_SCALBLN):
13007         CASE_FLT_FN (BUILT_IN_SCALBN):
13008         CASE_FLT_FN (BUILT_IN_SIGNBIT):
13009         CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
13010         CASE_FLT_FN (BUILT_IN_SINH):
13011         CASE_FLT_FN (BUILT_IN_TANH):
13012         CASE_FLT_FN (BUILT_IN_TRUNC):
13013         /* True if the 1st argument is nonnegative.  */
13014         return RECURSE (arg0);
13015
13016         CASE_FLT_FN (BUILT_IN_FMAX):
13017         /* True if the 1st OR 2nd arguments are nonnegative.  */
13018         return RECURSE (arg0) || RECURSE (arg1);
13019
13020         CASE_FLT_FN (BUILT_IN_FMIN):
13021         /* True if the 1st AND 2nd arguments are nonnegative.  */
13022         return RECURSE (arg0) && RECURSE (arg1);
13023
13024         CASE_FLT_FN (BUILT_IN_COPYSIGN):
13025         /* True if the 2nd argument is nonnegative.  */
13026         return RECURSE (arg1);
13027
13028         CASE_FLT_FN (BUILT_IN_POWI):
13029         /* True if the 1st argument is nonnegative or the second
13030            argument is an even integer.  */
13031         if (TREE_CODE (arg1) == INTEGER_CST
13032             && (TREE_INT_CST_LOW (arg1) & 1) == 0)
13033           return true;
13034         return RECURSE (arg0);
13035
13036         CASE_FLT_FN (BUILT_IN_POW):
13037         /* True if the 1st argument is nonnegative or the second
13038            argument is an even integer valued real.  */
13039         if (TREE_CODE (arg1) == REAL_CST)
13040           {
13041             REAL_VALUE_TYPE c;
13042             HOST_WIDE_INT n;
13043
13044             c = TREE_REAL_CST (arg1);
13045             n = real_to_integer (&c);
13046             if ((n & 1) == 0)
13047               {
13048                 REAL_VALUE_TYPE cint;
13049                 real_from_integer (&cint, VOIDmode, n, SIGNED);
13050                 if (real_identical (&c, &cint))
13051                   return true;
13052               }
13053           }
13054         return RECURSE (arg0);
13055
13056       default:
13057         break;
13058       }
13059   return tree_simple_nonnegative_warnv_p (CALL_EXPR, type);
13060 }
13061
13062 /* Return true if T is known to be non-negative.  If the return
13063    value is based on the assumption that signed overflow is undefined,
13064    set *STRICT_OVERFLOW_P to true; otherwise, don't change
13065    *STRICT_OVERFLOW_P.  DEPTH is the current nesting depth of the query.  */
13066
13067 static bool
13068 tree_invalid_nonnegative_warnv_p (tree t, bool *strict_overflow_p, int depth)
13069 {
13070   enum tree_code code = TREE_CODE (t);
13071   if (TYPE_UNSIGNED (TREE_TYPE (t)))
13072     return true;
13073
13074   switch (code)
13075     {
13076     case TARGET_EXPR:
13077       {
13078         tree temp = TARGET_EXPR_SLOT (t);
13079         t = TARGET_EXPR_INITIAL (t);
13080
13081         /* If the initializer is non-void, then it's a normal expression
13082            that will be assigned to the slot.  */
13083         if (!VOID_TYPE_P (t))
13084           return RECURSE (t);
13085
13086         /* Otherwise, the initializer sets the slot in some way.  One common
13087            way is an assignment statement at the end of the initializer.  */
13088         while (1)
13089           {
13090             if (TREE_CODE (t) == BIND_EXPR)
13091               t = expr_last (BIND_EXPR_BODY (t));
13092             else if (TREE_CODE (t) == TRY_FINALLY_EXPR
13093                      || TREE_CODE (t) == TRY_CATCH_EXPR)
13094               t = expr_last (TREE_OPERAND (t, 0));
13095             else if (TREE_CODE (t) == STATEMENT_LIST)
13096               t = expr_last (t);
13097             else
13098               break;
13099           }
13100         if (TREE_CODE (t) == MODIFY_EXPR
13101             && TREE_OPERAND (t, 0) == temp)
13102           return RECURSE (TREE_OPERAND (t, 1));
13103
13104         return false;
13105       }
13106
13107     case CALL_EXPR:
13108       {
13109         tree arg0 = call_expr_nargs (t) > 0 ?  CALL_EXPR_ARG (t, 0) : NULL_TREE;
13110         tree arg1 = call_expr_nargs (t) > 1 ?  CALL_EXPR_ARG (t, 1) : NULL_TREE;
13111
13112         return tree_call_nonnegative_warnv_p (TREE_TYPE (t),
13113                                               get_callee_fndecl (t),
13114                                               arg0,
13115                                               arg1,
13116                                               strict_overflow_p, depth);
13117       }
13118     case COMPOUND_EXPR:
13119     case MODIFY_EXPR:
13120       return RECURSE (TREE_OPERAND (t, 1));
13121
13122     case BIND_EXPR:
13123       return RECURSE (expr_last (TREE_OPERAND (t, 1)));
13124
13125     case SAVE_EXPR:
13126       return RECURSE (TREE_OPERAND (t, 0));
13127
13128     default:
13129       return tree_simple_nonnegative_warnv_p (TREE_CODE (t), TREE_TYPE (t));
13130     }
13131 }
13132
13133 #undef RECURSE
13134 #undef tree_expr_nonnegative_warnv_p
13135
13136 /* Return true if T is known to be non-negative.  If the return
13137    value is based on the assumption that signed overflow is undefined,
13138    set *STRICT_OVERFLOW_P to true; otherwise, don't change
13139    *STRICT_OVERFLOW_P.  DEPTH is the current nesting depth of the query.  */
13140
13141 bool
13142 tree_expr_nonnegative_warnv_p (tree t, bool *strict_overflow_p, int depth)
13143 {
13144   enum tree_code code;
13145   if (t == error_mark_node)
13146     return false;
13147
13148   code = TREE_CODE (t);
13149   switch (TREE_CODE_CLASS (code))
13150     {
13151     case tcc_binary:
13152     case tcc_comparison:
13153       return tree_binary_nonnegative_warnv_p (TREE_CODE (t),
13154                                               TREE_TYPE (t),
13155                                               TREE_OPERAND (t, 0),
13156                                               TREE_OPERAND (t, 1),
13157                                               strict_overflow_p, depth);
13158
13159     case tcc_unary:
13160       return tree_unary_nonnegative_warnv_p (TREE_CODE (t),
13161                                              TREE_TYPE (t),
13162                                              TREE_OPERAND (t, 0),
13163                                              strict_overflow_p, depth);
13164
13165     case tcc_constant:
13166     case tcc_declaration:
13167     case tcc_reference:
13168       return tree_single_nonnegative_warnv_p (t, strict_overflow_p, depth);
13169
13170     default:
13171       break;
13172     }
13173
13174   switch (code)
13175     {
13176     case TRUTH_AND_EXPR:
13177     case TRUTH_OR_EXPR:
13178     case TRUTH_XOR_EXPR:
13179       return tree_binary_nonnegative_warnv_p (TREE_CODE (t),
13180                                               TREE_TYPE (t),
13181                                               TREE_OPERAND (t, 0),
13182                                               TREE_OPERAND (t, 1),
13183                                               strict_overflow_p, depth);
13184     case TRUTH_NOT_EXPR:
13185       return tree_unary_nonnegative_warnv_p (TREE_CODE (t),
13186                                              TREE_TYPE (t),
13187                                              TREE_OPERAND (t, 0),
13188                                              strict_overflow_p, depth);
13189
13190     case COND_EXPR:
13191     case CONSTRUCTOR:
13192     case OBJ_TYPE_REF:
13193     case ASSERT_EXPR:
13194     case ADDR_EXPR:
13195     case WITH_SIZE_EXPR:
13196     case SSA_NAME:
13197       return tree_single_nonnegative_warnv_p (t, strict_overflow_p, depth);
13198
13199     default:
13200       return tree_invalid_nonnegative_warnv_p (t, strict_overflow_p, depth);
13201     }
13202 }
13203
13204 /* Return true if `t' is known to be non-negative.  Handle warnings
13205    about undefined signed overflow.  */
13206
13207 bool
13208 tree_expr_nonnegative_p (tree t)
13209 {
13210   bool ret, strict_overflow_p;
13211
13212   strict_overflow_p = false;
13213   ret = tree_expr_nonnegative_warnv_p (t, &strict_overflow_p);
13214   if (strict_overflow_p)
13215     fold_overflow_warning (("assuming signed overflow does not occur when "
13216                             "determining that expression is always "
13217                             "non-negative"),
13218                            WARN_STRICT_OVERFLOW_MISC);
13219   return ret;
13220 }
13221
13222
13223 /* Return true when (CODE OP0) is an address and is known to be nonzero.
13224    For floating point we further ensure that T is not denormal.
13225    Similar logic is present in nonzero_address in rtlanal.h.
13226
13227    If the return value is based on the assumption that signed overflow
13228    is undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't
13229    change *STRICT_OVERFLOW_P.  */
13230
13231 bool
13232 tree_unary_nonzero_warnv_p (enum tree_code code, tree type, tree op0,
13233                                  bool *strict_overflow_p)
13234 {
13235   switch (code)
13236     {
13237     case ABS_EXPR:
13238       return tree_expr_nonzero_warnv_p (op0,
13239                                         strict_overflow_p);
13240
13241     case NOP_EXPR:
13242       {
13243         tree inner_type = TREE_TYPE (op0);
13244         tree outer_type = type;
13245
13246         return (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
13247                 && tree_expr_nonzero_warnv_p (op0,
13248                                               strict_overflow_p));
13249       }
13250       break;
13251
13252     case NON_LVALUE_EXPR:
13253       return tree_expr_nonzero_warnv_p (op0,
13254                                         strict_overflow_p);
13255
13256     default:
13257       break;
13258   }
13259
13260   return false;
13261 }
13262
13263 /* Return true when (CODE OP0 OP1) is an address and is known to be nonzero.
13264    For floating point we further ensure that T is not denormal.
13265    Similar logic is present in nonzero_address in rtlanal.h.
13266
13267    If the return value is based on the assumption that signed overflow
13268    is undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't
13269    change *STRICT_OVERFLOW_P.  */
13270
13271 bool
13272 tree_binary_nonzero_warnv_p (enum tree_code code,
13273                              tree type,
13274                              tree op0,
13275                              tree op1, bool *strict_overflow_p)
13276 {
13277   bool sub_strict_overflow_p;
13278   switch (code)
13279     {
13280     case POINTER_PLUS_EXPR:
13281     case PLUS_EXPR:
13282       if (ANY_INTEGRAL_TYPE_P (type) && TYPE_OVERFLOW_UNDEFINED (type))
13283         {
13284           /* With the presence of negative values it is hard
13285              to say something.  */
13286           sub_strict_overflow_p = false;
13287           if (!tree_expr_nonnegative_warnv_p (op0,
13288                                               &sub_strict_overflow_p)
13289               || !tree_expr_nonnegative_warnv_p (op1,
13290                                                  &sub_strict_overflow_p))
13291             return false;
13292           /* One of operands must be positive and the other non-negative.  */
13293           /* We don't set *STRICT_OVERFLOW_P here: even if this value
13294              overflows, on a twos-complement machine the sum of two
13295              nonnegative numbers can never be zero.  */
13296           return (tree_expr_nonzero_warnv_p (op0,
13297                                              strict_overflow_p)
13298                   || tree_expr_nonzero_warnv_p (op1,
13299                                                 strict_overflow_p));
13300         }
13301       break;
13302
13303     case MULT_EXPR:
13304       if (TYPE_OVERFLOW_UNDEFINED (type))
13305         {
13306           if (tree_expr_nonzero_warnv_p (op0,
13307                                          strict_overflow_p)
13308               && tree_expr_nonzero_warnv_p (op1,
13309                                             strict_overflow_p))
13310             {
13311               *strict_overflow_p = true;
13312               return true;
13313             }
13314         }
13315       break;
13316
13317     case MIN_EXPR:
13318       sub_strict_overflow_p = false;
13319       if (tree_expr_nonzero_warnv_p (op0,
13320                                      &sub_strict_overflow_p)
13321           && tree_expr_nonzero_warnv_p (op1,
13322                                         &sub_strict_overflow_p))
13323         {
13324           if (sub_strict_overflow_p)
13325             *strict_overflow_p = true;
13326         }
13327       break;
13328
13329     case MAX_EXPR:
13330       sub_strict_overflow_p = false;
13331       if (tree_expr_nonzero_warnv_p (op0,
13332                                      &sub_strict_overflow_p))
13333         {
13334           if (sub_strict_overflow_p)
13335             *strict_overflow_p = true;
13336
13337           /* When both operands are nonzero, then MAX must be too.  */
13338           if (tree_expr_nonzero_warnv_p (op1,
13339                                          strict_overflow_p))
13340             return true;
13341
13342           /* MAX where operand 0 is positive is positive.  */
13343           return tree_expr_nonnegative_warnv_p (op0,
13344                                                strict_overflow_p);
13345         }
13346       /* MAX where operand 1 is positive is positive.  */
13347       else if (tree_expr_nonzero_warnv_p (op1,
13348                                           &sub_strict_overflow_p)
13349                && tree_expr_nonnegative_warnv_p (op1,
13350                                                  &sub_strict_overflow_p))
13351         {
13352           if (sub_strict_overflow_p)
13353             *strict_overflow_p = true;
13354           return true;
13355         }
13356       break;
13357
13358     case BIT_IOR_EXPR:
13359       return (tree_expr_nonzero_warnv_p (op1,
13360                                          strict_overflow_p)
13361               || tree_expr_nonzero_warnv_p (op0,
13362                                             strict_overflow_p));
13363
13364     default:
13365       break;
13366   }
13367
13368   return false;
13369 }
13370
13371 /* Return true when T is an address and is known to be nonzero.
13372    For floating point we further ensure that T is not denormal.
13373    Similar logic is present in nonzero_address in rtlanal.h.
13374
13375    If the return value is based on the assumption that signed overflow
13376    is undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't
13377    change *STRICT_OVERFLOW_P.  */
13378
13379 bool
13380 tree_single_nonzero_warnv_p (tree t, bool *strict_overflow_p)
13381 {
13382   bool sub_strict_overflow_p;
13383   switch (TREE_CODE (t))
13384     {
13385     case INTEGER_CST:
13386       return !integer_zerop (t);
13387
13388     case ADDR_EXPR:
13389       {
13390         tree base = TREE_OPERAND (t, 0);
13391
13392         if (!DECL_P (base))
13393           base = get_base_address (base);
13394
13395         if (!base)
13396           return false;
13397
13398         /* For objects in symbol table check if we know they are non-zero.
13399            Don't do anything for variables and functions before symtab is built;
13400            it is quite possible that they will be declared weak later.  */
13401         if (DECL_P (base) && decl_in_symtab_p (base))
13402           {
13403             struct symtab_node *symbol;
13404
13405             symbol = symtab_node::get_create (base);
13406             if (symbol)
13407               return symbol->nonzero_address ();
13408             else
13409               return false;
13410           }
13411
13412         /* Function local objects are never NULL.  */
13413         if (DECL_P (base)
13414             && (DECL_CONTEXT (base)
13415                 && TREE_CODE (DECL_CONTEXT (base)) == FUNCTION_DECL
13416                 && auto_var_in_fn_p (base, DECL_CONTEXT (base))))
13417           return true;
13418
13419         /* Constants are never weak.  */
13420         if (CONSTANT_CLASS_P (base))
13421           return true;
13422
13423         return false;
13424       }
13425
13426     case COND_EXPR:
13427       sub_strict_overflow_p = false;
13428       if (tree_expr_nonzero_warnv_p (TREE_OPERAND (t, 1),
13429                                      &sub_strict_overflow_p)
13430           && tree_expr_nonzero_warnv_p (TREE_OPERAND (t, 2),
13431                                         &sub_strict_overflow_p))
13432         {
13433           if (sub_strict_overflow_p)
13434             *strict_overflow_p = true;
13435           return true;
13436         }
13437       break;
13438
13439     default:
13440       break;
13441     }
13442   return false;
13443 }
13444
13445 #define integer_valued_real_p(X) \
13446   _Pragma ("GCC error \"Use RECURSE for recursive calls\"") 0
13447
13448 #define RECURSE(X) \
13449   ((integer_valued_real_p) (X, depth + 1))
13450
13451 /* Return true if the floating point result of (CODE OP0) has an
13452    integer value.  We also allow +Inf, -Inf and NaN to be considered
13453    integer values.
13454
13455    DEPTH is the current nesting depth of the query.  */
13456
13457 bool
13458 integer_valued_real_unary_p (tree_code code, tree op0, int depth)
13459 {
13460   switch (code)
13461     {
13462     case FLOAT_EXPR:
13463       return true;
13464
13465     case ABS_EXPR:
13466       return RECURSE (op0);
13467
13468     CASE_CONVERT:
13469       {
13470         tree type = TREE_TYPE (op0);
13471         if (TREE_CODE (type) == INTEGER_TYPE)
13472           return true;
13473         if (TREE_CODE (type) == REAL_TYPE)
13474           return RECURSE (op0);
13475         break;
13476       }
13477
13478     default:
13479       break;
13480     }
13481   return false;
13482 }
13483
13484 /* Return true if the floating point result of (CODE OP0 OP1) has an
13485    integer value.  We also allow +Inf, -Inf and NaN to be considered
13486    integer values.
13487
13488    DEPTH is the current nesting depth of the query.  */
13489
13490 bool
13491 integer_valued_real_binary_p (tree_code code, tree op0, tree op1, int depth)
13492 {
13493   switch (code)
13494     {
13495     case PLUS_EXPR:
13496     case MINUS_EXPR:
13497     case MULT_EXPR:
13498     case MIN_EXPR:
13499     case MAX_EXPR:
13500       return RECURSE (op0) && RECURSE (op1);
13501
13502     default:
13503       break;
13504     }
13505   return false;
13506 }
13507
13508 /* Return true if the floating point result of calling FNDECL with arguments
13509    ARG0 and ARG1 has an integer value.  We also allow +Inf, -Inf and NaN to be
13510    considered integer values.  If FNDECL takes fewer than 2 arguments,
13511    the remaining ARGn are null.
13512
13513    DEPTH is the current nesting depth of the query.  */
13514
13515 bool
13516 integer_valued_real_call_p (tree fndecl, tree arg0, tree arg1, int depth)
13517 {
13518   if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
13519     switch (DECL_FUNCTION_CODE (fndecl))
13520       {
13521       CASE_FLT_FN (BUILT_IN_CEIL):
13522       CASE_FLT_FN (BUILT_IN_FLOOR):
13523       CASE_FLT_FN (BUILT_IN_NEARBYINT):
13524       CASE_FLT_FN (BUILT_IN_RINT):
13525       CASE_FLT_FN (BUILT_IN_ROUND):
13526       CASE_FLT_FN (BUILT_IN_TRUNC):
13527         return true;
13528
13529       CASE_FLT_FN (BUILT_IN_FMIN):
13530       CASE_FLT_FN (BUILT_IN_FMAX):
13531         return RECURSE (arg0) && RECURSE (arg1);
13532
13533       default:
13534         break;
13535       }
13536   return false;
13537 }
13538
13539 /* Return true if the floating point expression T (a GIMPLE_SINGLE_RHS)
13540    has an integer value.  We also allow +Inf, -Inf and NaN to be
13541    considered integer values.
13542
13543    DEPTH is the current nesting depth of the query.  */
13544
13545 bool
13546 integer_valued_real_single_p (tree t, int depth)
13547 {
13548   switch (TREE_CODE (t))
13549     {
13550     case REAL_CST:
13551       return real_isinteger (TREE_REAL_CST_PTR (t), TYPE_MODE (TREE_TYPE (t)));
13552
13553     case COND_EXPR:
13554       return RECURSE (TREE_OPERAND (t, 1)) && RECURSE (TREE_OPERAND (t, 2));
13555
13556     case SSA_NAME:
13557       /* Limit the depth of recursion to avoid quadratic behavior.
13558          This is expected to catch almost all occurrences in practice.
13559          If this code misses important cases that unbounded recursion
13560          would not, passes that need this information could be revised
13561          to provide it through dataflow propagation.  */
13562       return (!name_registered_for_update_p (t)
13563               && depth < PARAM_VALUE (PARAM_MAX_SSA_NAME_QUERY_DEPTH)
13564               && gimple_stmt_integer_valued_real_p (SSA_NAME_DEF_STMT (t),
13565                                                     depth));
13566
13567     default:
13568       break;
13569     }
13570   return false;
13571 }
13572
13573 /* Return true if the floating point expression T (a GIMPLE_INVALID_RHS)
13574    has an integer value.  We also allow +Inf, -Inf and NaN to be
13575    considered integer values.
13576
13577    DEPTH is the current nesting depth of the query.  */
13578
13579 static bool
13580 integer_valued_real_invalid_p (tree t, int depth)
13581 {
13582   switch (TREE_CODE (t))
13583     {
13584     case COMPOUND_EXPR:
13585     case MODIFY_EXPR:
13586     case BIND_EXPR:
13587       return RECURSE (TREE_OPERAND (t, 1));
13588
13589     case SAVE_EXPR:
13590       return RECURSE (TREE_OPERAND (t, 0));
13591
13592     default:
13593       break;
13594     }
13595   return false;
13596 }
13597
13598 #undef RECURSE
13599 #undef integer_valued_real_p
13600
13601 /* Return true if the floating point expression T has an integer value.
13602    We also allow +Inf, -Inf and NaN to be considered integer values.
13603
13604    DEPTH is the current nesting depth of the query.  */
13605
13606 bool
13607 integer_valued_real_p (tree t, int depth)
13608 {
13609   if (t == error_mark_node)
13610     return false;
13611
13612   tree_code code = TREE_CODE (t);
13613   switch (TREE_CODE_CLASS (code))
13614     {
13615     case tcc_binary:
13616     case tcc_comparison:
13617       return integer_valued_real_binary_p (code, TREE_OPERAND (t, 0),
13618                                            TREE_OPERAND (t, 1), depth);
13619
13620     case tcc_unary:
13621       return integer_valued_real_unary_p (code, TREE_OPERAND (t, 0), depth);
13622
13623     case tcc_constant:
13624     case tcc_declaration:
13625     case tcc_reference:
13626       return integer_valued_real_single_p (t, depth);
13627
13628     default:
13629       break;
13630     }
13631
13632   switch (code)
13633     {
13634     case COND_EXPR:
13635     case SSA_NAME:
13636       return integer_valued_real_single_p (t, depth);
13637
13638     case CALL_EXPR:
13639       {
13640         tree arg0 = (call_expr_nargs (t) > 0
13641                      ? CALL_EXPR_ARG (t, 0)
13642                      : NULL_TREE);
13643         tree arg1 = (call_expr_nargs (t) > 1
13644                      ? CALL_EXPR_ARG (t, 1)
13645                      : NULL_TREE);
13646         return integer_valued_real_call_p (get_callee_fndecl (t),
13647                                            arg0, arg1, depth);
13648       }
13649
13650     default:
13651       return integer_valued_real_invalid_p (t, depth);
13652     }
13653 }
13654
13655 /* Given the components of a binary expression CODE, TYPE, OP0 and OP1,
13656    attempt to fold the expression to a constant without modifying TYPE,
13657    OP0 or OP1.
13658
13659    If the expression could be simplified to a constant, then return
13660    the constant.  If the expression would not be simplified to a
13661    constant, then return NULL_TREE.  */
13662
13663 tree
13664 fold_binary_to_constant (enum tree_code code, tree type, tree op0, tree op1)
13665 {
13666   tree tem = fold_binary (code, type, op0, op1);
13667   return (tem && TREE_CONSTANT (tem)) ? tem : NULL_TREE;
13668 }
13669
13670 /* Given the components of a unary expression CODE, TYPE and OP0,
13671    attempt to fold the expression to a constant without modifying
13672    TYPE or OP0.
13673
13674    If the expression could be simplified to a constant, then return
13675    the constant.  If the expression would not be simplified to a
13676    constant, then return NULL_TREE.  */
13677
13678 tree
13679 fold_unary_to_constant (enum tree_code code, tree type, tree op0)
13680 {
13681   tree tem = fold_unary (code, type, op0);
13682   return (tem && TREE_CONSTANT (tem)) ? tem : NULL_TREE;
13683 }
13684
13685 /* If EXP represents referencing an element in a constant string
13686    (either via pointer arithmetic or array indexing), return the
13687    tree representing the value accessed, otherwise return NULL.  */
13688
13689 tree
13690 fold_read_from_constant_string (tree exp)
13691 {
13692   if ((TREE_CODE (exp) == INDIRECT_REF
13693        || TREE_CODE (exp) == ARRAY_REF)
13694       && TREE_CODE (TREE_TYPE (exp)) == INTEGER_TYPE)
13695     {
13696       tree exp1 = TREE_OPERAND (exp, 0);
13697       tree index;
13698       tree string;
13699       location_t loc = EXPR_LOCATION (exp);
13700
13701       if (TREE_CODE (exp) == INDIRECT_REF)
13702         string = string_constant (exp1, &index);
13703       else
13704         {
13705           tree low_bound = array_ref_low_bound (exp);
13706           index = fold_convert_loc (loc, sizetype, TREE_OPERAND (exp, 1));
13707
13708           /* Optimize the special-case of a zero lower bound.
13709
13710              We convert the low_bound to sizetype to avoid some problems
13711              with constant folding.  (E.g. suppose the lower bound is 1,
13712              and its mode is QI.  Without the conversion,l (ARRAY
13713              +(INDEX-(unsigned char)1)) becomes ((ARRAY+(-(unsigned char)1))
13714              +INDEX), which becomes (ARRAY+255+INDEX).  Oops!)  */
13715           if (! integer_zerop (low_bound))
13716             index = size_diffop_loc (loc, index,
13717                                  fold_convert_loc (loc, sizetype, low_bound));
13718
13719           string = exp1;
13720         }
13721
13722       if (string
13723           && TYPE_MODE (TREE_TYPE (exp)) == TYPE_MODE (TREE_TYPE (TREE_TYPE (string)))
13724           && TREE_CODE (string) == STRING_CST
13725           && TREE_CODE (index) == INTEGER_CST
13726           && compare_tree_int (index, TREE_STRING_LENGTH (string)) < 0
13727           && (GET_MODE_CLASS (TYPE_MODE (TREE_TYPE (TREE_TYPE (string))))
13728               == MODE_INT)
13729           && (GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (TREE_TYPE (string)))) == 1))
13730         return build_int_cst_type (TREE_TYPE (exp),
13731                                    (TREE_STRING_POINTER (string)
13732                                     [TREE_INT_CST_LOW (index)]));
13733     }
13734   return NULL;
13735 }
13736
13737 /* Return the tree for neg (ARG0) when ARG0 is known to be either
13738    an integer constant, real, or fixed-point constant.
13739
13740    TYPE is the type of the result.  */
13741
13742 static tree
13743 fold_negate_const (tree arg0, tree type)
13744 {
13745   tree t = NULL_TREE;
13746
13747   switch (TREE_CODE (arg0))
13748     {
13749     case INTEGER_CST:
13750       {
13751         bool overflow;
13752         wide_int val = wi::neg (arg0, &overflow);
13753         t = force_fit_type (type, val, 1,
13754                             (overflow | TREE_OVERFLOW (arg0))
13755                             && !TYPE_UNSIGNED (type));
13756         break;
13757       }
13758
13759     case REAL_CST:
13760       t = build_real (type, real_value_negate (&TREE_REAL_CST (arg0)));
13761       break;
13762
13763     case FIXED_CST:
13764       {
13765         FIXED_VALUE_TYPE f;
13766         bool overflow_p = fixed_arithmetic (&f, NEGATE_EXPR,
13767                                             &(TREE_FIXED_CST (arg0)), NULL,
13768                                             TYPE_SATURATING (type));
13769         t = build_fixed (type, f);
13770         /* Propagate overflow flags.  */
13771         if (overflow_p | TREE_OVERFLOW (arg0))
13772           TREE_OVERFLOW (t) = 1;
13773         break;
13774       }
13775
13776     default:
13777       gcc_unreachable ();
13778     }
13779
13780   return t;
13781 }
13782
13783 /* Return the tree for abs (ARG0) when ARG0 is known to be either
13784    an integer constant or real constant.
13785
13786    TYPE is the type of the result.  */
13787
13788 tree
13789 fold_abs_const (tree arg0, tree type)
13790 {
13791   tree t = NULL_TREE;
13792
13793   switch (TREE_CODE (arg0))
13794     {
13795     case INTEGER_CST:
13796       {
13797         /* If the value is unsigned or non-negative, then the absolute value
13798            is the same as the ordinary value.  */
13799         if (!wi::neg_p (arg0, TYPE_SIGN (type)))
13800           t = arg0;
13801
13802         /* If the value is negative, then the absolute value is
13803            its negation.  */
13804         else
13805           {
13806             bool overflow;
13807             wide_int val = wi::neg (arg0, &overflow);
13808             t = force_fit_type (type, val, -1,
13809                                 overflow | TREE_OVERFLOW (arg0));
13810           }
13811       }
13812       break;
13813
13814     case REAL_CST:
13815       if (REAL_VALUE_NEGATIVE (TREE_REAL_CST (arg0)))
13816         t = build_real (type, real_value_negate (&TREE_REAL_CST (arg0)));
13817       else
13818         t =  arg0;
13819       break;
13820
13821     default:
13822       gcc_unreachable ();
13823     }
13824
13825   return t;
13826 }
13827
13828 /* Return the tree for not (ARG0) when ARG0 is known to be an integer
13829    constant.  TYPE is the type of the result.  */
13830
13831 static tree
13832 fold_not_const (const_tree arg0, tree type)
13833 {
13834   gcc_assert (TREE_CODE (arg0) == INTEGER_CST);
13835
13836   return force_fit_type (type, wi::bit_not (arg0), 0, TREE_OVERFLOW (arg0));
13837 }
13838
13839 /* Given CODE, a relational operator, the target type, TYPE and two
13840    constant operands OP0 and OP1, return the result of the
13841    relational operation.  If the result is not a compile time
13842    constant, then return NULL_TREE.  */
13843
13844 static tree
13845 fold_relational_const (enum tree_code code, tree type, tree op0, tree op1)
13846 {
13847   int result, invert;
13848
13849   /* From here on, the only cases we handle are when the result is
13850      known to be a constant.  */
13851
13852   if (TREE_CODE (op0) == REAL_CST && TREE_CODE (op1) == REAL_CST)
13853     {
13854       const REAL_VALUE_TYPE *c0 = TREE_REAL_CST_PTR (op0);
13855       const REAL_VALUE_TYPE *c1 = TREE_REAL_CST_PTR (op1);
13856
13857       /* Handle the cases where either operand is a NaN.  */
13858       if (real_isnan (c0) || real_isnan (c1))
13859         {
13860           switch (code)
13861             {
13862             case EQ_EXPR:
13863             case ORDERED_EXPR:
13864               result = 0;
13865               break;
13866
13867             case NE_EXPR:
13868             case UNORDERED_EXPR:
13869             case UNLT_EXPR:
13870             case UNLE_EXPR:
13871             case UNGT_EXPR:
13872             case UNGE_EXPR:
13873             case UNEQ_EXPR:
13874               result = 1;
13875               break;
13876
13877             case LT_EXPR:
13878             case LE_EXPR:
13879             case GT_EXPR:
13880             case GE_EXPR:
13881             case LTGT_EXPR:
13882               if (flag_trapping_math)
13883                 return NULL_TREE;
13884               result = 0;
13885               break;
13886
13887             default:
13888               gcc_unreachable ();
13889             }
13890
13891           return constant_boolean_node (result, type);
13892         }
13893
13894       return constant_boolean_node (real_compare (code, c0, c1), type);
13895     }
13896
13897   if (TREE_CODE (op0) == FIXED_CST && TREE_CODE (op1) == FIXED_CST)
13898     {
13899       const FIXED_VALUE_TYPE *c0 = TREE_FIXED_CST_PTR (op0);
13900       const FIXED_VALUE_TYPE *c1 = TREE_FIXED_CST_PTR (op1);
13901       return constant_boolean_node (fixed_compare (code, c0, c1), type);
13902     }
13903
13904   /* Handle equality/inequality of complex constants.  */
13905   if (TREE_CODE (op0) == COMPLEX_CST && TREE_CODE (op1) == COMPLEX_CST)
13906     {
13907       tree rcond = fold_relational_const (code, type,
13908                                           TREE_REALPART (op0),
13909                                           TREE_REALPART (op1));
13910       tree icond = fold_relational_const (code, type,
13911                                           TREE_IMAGPART (op0),
13912                                           TREE_IMAGPART (op1));
13913       if (code == EQ_EXPR)
13914         return fold_build2 (TRUTH_ANDIF_EXPR, type, rcond, icond);
13915       else if (code == NE_EXPR)
13916         return fold_build2 (TRUTH_ORIF_EXPR, type, rcond, icond);
13917       else
13918         return NULL_TREE;
13919     }
13920
13921   if (TREE_CODE (op0) == VECTOR_CST && TREE_CODE (op1) == VECTOR_CST)
13922     {
13923       unsigned count = VECTOR_CST_NELTS (op0);
13924       tree *elts =  XALLOCAVEC (tree, count);
13925       gcc_assert (VECTOR_CST_NELTS (op1) == count
13926                   && TYPE_VECTOR_SUBPARTS (type) == count);
13927
13928       for (unsigned i = 0; i < count; i++)
13929         {
13930           tree elem_type = TREE_TYPE (type);
13931           tree elem0 = VECTOR_CST_ELT (op0, i);
13932           tree elem1 = VECTOR_CST_ELT (op1, i);
13933
13934           tree tem = fold_relational_const (code, elem_type,
13935                                             elem0, elem1);
13936
13937           if (tem == NULL_TREE)
13938             return NULL_TREE;
13939
13940           elts[i] = build_int_cst (elem_type, integer_zerop (tem) ? 0 : -1);
13941         }
13942
13943       return build_vector (type, elts);
13944     }
13945
13946   /* From here on we only handle LT, LE, GT, GE, EQ and NE.
13947
13948      To compute GT, swap the arguments and do LT.
13949      To compute GE, do LT and invert the result.
13950      To compute LE, swap the arguments, do LT and invert the result.
13951      To compute NE, do EQ and invert the result.
13952
13953      Therefore, the code below must handle only EQ and LT.  */
13954
13955   if (code == LE_EXPR || code == GT_EXPR)
13956     {
13957       std::swap (op0, op1);
13958       code = swap_tree_comparison (code);
13959     }
13960
13961   /* Note that it is safe to invert for real values here because we
13962      have already handled the one case that it matters.  */
13963
13964   invert = 0;
13965   if (code == NE_EXPR || code == GE_EXPR)
13966     {
13967       invert = 1;
13968       code = invert_tree_comparison (code, false);
13969     }
13970
13971   /* Compute a result for LT or EQ if args permit;
13972      Otherwise return T.  */
13973   if (TREE_CODE (op0) == INTEGER_CST && TREE_CODE (op1) == INTEGER_CST)
13974     {
13975       if (code == EQ_EXPR)
13976         result = tree_int_cst_equal (op0, op1);
13977       else
13978         result = tree_int_cst_lt (op0, op1);
13979     }
13980   else
13981     return NULL_TREE;
13982
13983   if (invert)
13984     result ^= 1;
13985   return constant_boolean_node (result, type);
13986 }
13987
13988 /* If necessary, return a CLEANUP_POINT_EXPR for EXPR with the
13989    indicated TYPE.  If no CLEANUP_POINT_EXPR is necessary, return EXPR
13990    itself.  */
13991
13992 tree
13993 fold_build_cleanup_point_expr (tree type, tree expr)
13994 {
13995   /* If the expression does not have side effects then we don't have to wrap
13996      it with a cleanup point expression.  */
13997   if (!TREE_SIDE_EFFECTS (expr))
13998     return expr;
13999
14000   /* If the expression is a return, check to see if the expression inside the
14001      return has no side effects or the right hand side of the modify expression
14002      inside the return. If either don't have side effects set we don't need to
14003      wrap the expression in a cleanup point expression.  Note we don't check the
14004      left hand side of the modify because it should always be a return decl.  */
14005   if (TREE_CODE (expr) == RETURN_EXPR)
14006     {
14007       tree op = TREE_OPERAND (expr, 0);
14008       if (!op || !TREE_SIDE_EFFECTS (op))
14009         return expr;
14010       op = TREE_OPERAND (op, 1);
14011       if (!TREE_SIDE_EFFECTS (op))
14012         return expr;
14013     }
14014
14015   return build1 (CLEANUP_POINT_EXPR, type, expr);
14016 }
14017
14018 /* Given a pointer value OP0 and a type TYPE, return a simplified version
14019    of an indirection through OP0, or NULL_TREE if no simplification is
14020    possible.  */
14021
14022 tree
14023 fold_indirect_ref_1 (location_t loc, tree type, tree op0)
14024 {
14025   tree sub = op0;
14026   tree subtype;
14027
14028   STRIP_NOPS (sub);
14029   subtype = TREE_TYPE (sub);
14030   if (!POINTER_TYPE_P (subtype))
14031     return NULL_TREE;
14032
14033   if (TREE_CODE (sub) == ADDR_EXPR)
14034     {
14035       tree op = TREE_OPERAND (sub, 0);
14036       tree optype = TREE_TYPE (op);
14037       /* *&CONST_DECL -> to the value of the const decl.  */
14038       if (TREE_CODE (op) == CONST_DECL)
14039         return DECL_INITIAL (op);
14040       /* *&p => p;  make sure to handle *&"str"[cst] here.  */
14041       if (type == optype)
14042         {
14043           tree fop = fold_read_from_constant_string (op);
14044           if (fop)
14045             return fop;
14046           else
14047             return op;
14048         }
14049       /* *(foo *)&fooarray => fooarray[0] */
14050       else if (TREE_CODE (optype) == ARRAY_TYPE
14051                && type == TREE_TYPE (optype)
14052                && (!in_gimple_form
14053                    || TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST))
14054         {
14055           tree type_domain = TYPE_DOMAIN (optype);
14056           tree min_val = size_zero_node;
14057           if (type_domain && TYPE_MIN_VALUE (type_domain))
14058             min_val = TYPE_MIN_VALUE (type_domain);
14059           if (in_gimple_form
14060               && TREE_CODE (min_val) != INTEGER_CST)
14061             return NULL_TREE;
14062           return build4_loc (loc, ARRAY_REF, type, op, min_val,
14063                              NULL_TREE, NULL_TREE);
14064         }
14065       /* *(foo *)&complexfoo => __real__ complexfoo */
14066       else if (TREE_CODE (optype) == COMPLEX_TYPE
14067                && type == TREE_TYPE (optype))
14068         return fold_build1_loc (loc, REALPART_EXPR, type, op);
14069       /* *(foo *)&vectorfoo => BIT_FIELD_REF<vectorfoo,...> */
14070       else if (TREE_CODE (optype) == VECTOR_TYPE
14071                && type == TREE_TYPE (optype))
14072         {
14073           tree part_width = TYPE_SIZE (type);
14074           tree index = bitsize_int (0);
14075           return fold_build3_loc (loc, BIT_FIELD_REF, type, op, part_width, index);
14076         }
14077     }
14078
14079   if (TREE_CODE (sub) == POINTER_PLUS_EXPR
14080       && TREE_CODE (TREE_OPERAND (sub, 1)) == INTEGER_CST)
14081     {
14082       tree op00 = TREE_OPERAND (sub, 0);
14083       tree op01 = TREE_OPERAND (sub, 1);
14084
14085       STRIP_NOPS (op00);
14086       if (TREE_CODE (op00) == ADDR_EXPR)
14087         {
14088           tree op00type;
14089           op00 = TREE_OPERAND (op00, 0);
14090           op00type = TREE_TYPE (op00);
14091
14092           /* ((foo*)&vectorfoo)[1] => BIT_FIELD_REF<vectorfoo,...> */
14093           if (TREE_CODE (op00type) == VECTOR_TYPE
14094               && type == TREE_TYPE (op00type))
14095             {
14096               HOST_WIDE_INT offset = tree_to_shwi (op01);
14097               tree part_width = TYPE_SIZE (type);
14098               unsigned HOST_WIDE_INT part_widthi = tree_to_shwi (part_width)/BITS_PER_UNIT;
14099               unsigned HOST_WIDE_INT indexi = offset * BITS_PER_UNIT;
14100               tree index = bitsize_int (indexi);
14101
14102               if (offset / part_widthi < TYPE_VECTOR_SUBPARTS (op00type))
14103                 return fold_build3_loc (loc,
14104                                         BIT_FIELD_REF, type, op00,
14105                                         part_width, index);
14106
14107             }
14108           /* ((foo*)&complexfoo)[1] => __imag__ complexfoo */
14109           else if (TREE_CODE (op00type) == COMPLEX_TYPE
14110                    && type == TREE_TYPE (op00type))
14111             {
14112               tree size = TYPE_SIZE_UNIT (type);
14113               if (tree_int_cst_equal (size, op01))
14114                 return fold_build1_loc (loc, IMAGPART_EXPR, type, op00);
14115             }
14116           /* ((foo *)&fooarray)[1] => fooarray[1] */
14117           else if (TREE_CODE (op00type) == ARRAY_TYPE
14118                    && type == TREE_TYPE (op00type))
14119             {
14120               tree type_domain = TYPE_DOMAIN (op00type);
14121               tree min_val = size_zero_node;
14122               if (type_domain && TYPE_MIN_VALUE (type_domain))
14123                 min_val = TYPE_MIN_VALUE (type_domain);
14124               op01 = size_binop_loc (loc, EXACT_DIV_EXPR, op01,
14125                                      TYPE_SIZE_UNIT (type));
14126               op01 = size_binop_loc (loc, PLUS_EXPR, op01, min_val);
14127               return build4_loc (loc, ARRAY_REF, type, op00, op01,
14128                                  NULL_TREE, NULL_TREE);
14129             }
14130         }
14131     }
14132
14133   /* *(foo *)fooarrptr => (*fooarrptr)[0] */
14134   if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
14135       && type == TREE_TYPE (TREE_TYPE (subtype))
14136       && (!in_gimple_form
14137           || TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST))
14138     {
14139       tree type_domain;
14140       tree min_val = size_zero_node;
14141       sub = build_fold_indirect_ref_loc (loc, sub);
14142       type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
14143       if (type_domain && TYPE_MIN_VALUE (type_domain))
14144         min_val = TYPE_MIN_VALUE (type_domain);
14145       if (in_gimple_form
14146           && TREE_CODE (min_val) != INTEGER_CST)
14147         return NULL_TREE;
14148       return build4_loc (loc, ARRAY_REF, type, sub, min_val, NULL_TREE,
14149                          NULL_TREE);
14150     }
14151
14152   return NULL_TREE;
14153 }
14154
14155 /* Builds an expression for an indirection through T, simplifying some
14156    cases.  */
14157
14158 tree
14159 build_fold_indirect_ref_loc (location_t loc, tree t)
14160 {
14161   tree type = TREE_TYPE (TREE_TYPE (t));
14162   tree sub = fold_indirect_ref_1 (loc, type, t);
14163
14164   if (sub)
14165     return sub;
14166
14167   return build1_loc (loc, INDIRECT_REF, type, t);
14168 }
14169
14170 /* Given an INDIRECT_REF T, return either T or a simplified version.  */
14171
14172 tree
14173 fold_indirect_ref_loc (location_t loc, tree t)
14174 {
14175   tree sub = fold_indirect_ref_1 (loc, TREE_TYPE (t), TREE_OPERAND (t, 0));
14176
14177   if (sub)
14178     return sub;
14179   else
14180     return t;
14181 }
14182
14183 /* Strip non-trapping, non-side-effecting tree nodes from an expression
14184    whose result is ignored.  The type of the returned tree need not be
14185    the same as the original expression.  */
14186
14187 tree
14188 fold_ignored_result (tree t)
14189 {
14190   if (!TREE_SIDE_EFFECTS (t))
14191     return integer_zero_node;
14192
14193   for (;;)
14194     switch (TREE_CODE_CLASS (TREE_CODE (t)))
14195       {
14196       case tcc_unary:
14197         t = TREE_OPERAND (t, 0);
14198         break;
14199
14200       case tcc_binary:
14201       case tcc_comparison:
14202         if (!TREE_SIDE_EFFECTS (TREE_OPERAND (t, 1)))
14203           t = TREE_OPERAND (t, 0);
14204         else if (!TREE_SIDE_EFFECTS (TREE_OPERAND (t, 0)))
14205           t = TREE_OPERAND (t, 1);
14206         else
14207           return t;
14208         break;
14209
14210       case tcc_expression:
14211         switch (TREE_CODE (t))
14212           {
14213           case COMPOUND_EXPR:
14214             if (TREE_SIDE_EFFECTS (TREE_OPERAND (t, 1)))
14215               return t;
14216             t = TREE_OPERAND (t, 0);
14217             break;
14218
14219           case COND_EXPR:
14220             if (TREE_SIDE_EFFECTS (TREE_OPERAND (t, 1))
14221                 || TREE_SIDE_EFFECTS (TREE_OPERAND (t, 2)))
14222               return t;
14223             t = TREE_OPERAND (t, 0);
14224             break;
14225
14226           default:
14227             return t;
14228           }
14229         break;
14230
14231       default:
14232         return t;
14233       }
14234 }
14235
14236 /* Return the value of VALUE, rounded up to a multiple of DIVISOR. */
14237
14238 tree
14239 round_up_loc (location_t loc, tree value, unsigned int divisor)
14240 {
14241   tree div = NULL_TREE;
14242
14243   if (divisor == 1)
14244     return value;
14245
14246   /* See if VALUE is already a multiple of DIVISOR.  If so, we don't
14247      have to do anything.  Only do this when we are not given a const,
14248      because in that case, this check is more expensive than just
14249      doing it.  */
14250   if (TREE_CODE (value) != INTEGER_CST)
14251     {
14252       div = build_int_cst (TREE_TYPE (value), divisor);
14253
14254       if (multiple_of_p (TREE_TYPE (value), value, div))
14255         return value;
14256     }
14257
14258   /* If divisor is a power of two, simplify this to bit manipulation.  */
14259   if (divisor == (divisor & -divisor))
14260     {
14261       if (TREE_CODE (value) == INTEGER_CST)
14262         {
14263           wide_int val = value;
14264           bool overflow_p;
14265
14266           if ((val & (divisor - 1)) == 0)
14267             return value;
14268
14269           overflow_p = TREE_OVERFLOW (value);
14270           val += divisor - 1;
14271           val &= - (int) divisor;
14272           if (val == 0)
14273             overflow_p = true;
14274
14275           return force_fit_type (TREE_TYPE (value), val, -1, overflow_p);
14276         }
14277       else
14278         {
14279           tree t;
14280
14281           t = build_int_cst (TREE_TYPE (value), divisor - 1);
14282           value = size_binop_loc (loc, PLUS_EXPR, value, t);
14283           t = build_int_cst (TREE_TYPE (value), - (int) divisor);
14284           value = size_binop_loc (loc, BIT_AND_EXPR, value, t);
14285         }
14286     }
14287   else
14288     {
14289       if (!div)
14290         div = build_int_cst (TREE_TYPE (value), divisor);
14291       value = size_binop_loc (loc, CEIL_DIV_EXPR, value, div);
14292       value = size_binop_loc (loc, MULT_EXPR, value, div);
14293     }
14294
14295   return value;
14296 }
14297
14298 /* Likewise, but round down.  */
14299
14300 tree
14301 round_down_loc (location_t loc, tree value, int divisor)
14302 {
14303   tree div = NULL_TREE;
14304
14305   gcc_assert (divisor > 0);
14306   if (divisor == 1)
14307     return value;
14308
14309   /* See if VALUE is already a multiple of DIVISOR.  If so, we don't
14310      have to do anything.  Only do this when we are not given a const,
14311      because in that case, this check is more expensive than just
14312      doing it.  */
14313   if (TREE_CODE (value) != INTEGER_CST)
14314     {
14315       div = build_int_cst (TREE_TYPE (value), divisor);
14316
14317       if (multiple_of_p (TREE_TYPE (value), value, div))
14318         return value;
14319     }
14320
14321   /* If divisor is a power of two, simplify this to bit manipulation.  */
14322   if (divisor == (divisor & -divisor))
14323     {
14324       tree t;
14325
14326       t = build_int_cst (TREE_TYPE (value), -divisor);
14327       value = size_binop_loc (loc, BIT_AND_EXPR, value, t);
14328     }
14329   else
14330     {
14331       if (!div)
14332         div = build_int_cst (TREE_TYPE (value), divisor);
14333       value = size_binop_loc (loc, FLOOR_DIV_EXPR, value, div);
14334       value = size_binop_loc (loc, MULT_EXPR, value, div);
14335     }
14336
14337   return value;
14338 }
14339
14340 /* Returns the pointer to the base of the object addressed by EXP and
14341    extracts the information about the offset of the access, storing it
14342    to PBITPOS and POFFSET.  */
14343
14344 static tree
14345 split_address_to_core_and_offset (tree exp,
14346                                   HOST_WIDE_INT *pbitpos, tree *poffset)
14347 {
14348   tree core;
14349   machine_mode mode;
14350   int unsignedp, volatilep;
14351   HOST_WIDE_INT bitsize;
14352   location_t loc = EXPR_LOCATION (exp);
14353
14354   if (TREE_CODE (exp) == ADDR_EXPR)
14355     {
14356       core = get_inner_reference (TREE_OPERAND (exp, 0), &bitsize, pbitpos,
14357                                   poffset, &mode, &unsignedp, &volatilep,
14358                                   false);
14359       core = build_fold_addr_expr_loc (loc, core);
14360     }
14361   else
14362     {
14363       core = exp;
14364       *pbitpos = 0;
14365       *poffset = NULL_TREE;
14366     }
14367
14368   return core;
14369 }
14370
14371 /* Returns true if addresses of E1 and E2 differ by a constant, false
14372    otherwise.  If they do, E1 - E2 is stored in *DIFF.  */
14373
14374 bool
14375 ptr_difference_const (tree e1, tree e2, HOST_WIDE_INT *diff)
14376 {
14377   tree core1, core2;
14378   HOST_WIDE_INT bitpos1, bitpos2;
14379   tree toffset1, toffset2, tdiff, type;
14380
14381   core1 = split_address_to_core_and_offset (e1, &bitpos1, &toffset1);
14382   core2 = split_address_to_core_and_offset (e2, &bitpos2, &toffset2);
14383
14384   if (bitpos1 % BITS_PER_UNIT != 0
14385       || bitpos2 % BITS_PER_UNIT != 0
14386       || !operand_equal_p (core1, core2, 0))
14387     return false;
14388
14389   if (toffset1 && toffset2)
14390     {
14391       type = TREE_TYPE (toffset1);
14392       if (type != TREE_TYPE (toffset2))
14393         toffset2 = fold_convert (type, toffset2);
14394
14395       tdiff = fold_build2 (MINUS_EXPR, type, toffset1, toffset2);
14396       if (!cst_and_fits_in_hwi (tdiff))
14397         return false;
14398
14399       *diff = int_cst_value (tdiff);
14400     }
14401   else if (toffset1 || toffset2)
14402     {
14403       /* If only one of the offsets is non-constant, the difference cannot
14404          be a constant.  */
14405       return false;
14406     }
14407   else
14408     *diff = 0;
14409
14410   *diff += (bitpos1 - bitpos2) / BITS_PER_UNIT;
14411   return true;
14412 }
14413
14414 /* Return OFF converted to a pointer offset type suitable as offset for
14415    POINTER_PLUS_EXPR.  Use location LOC for this conversion.  */
14416 tree
14417 convert_to_ptrofftype_loc (location_t loc, tree off)
14418 {
14419   return fold_convert_loc (loc, sizetype, off);
14420 }
14421
14422 /* Build and fold a POINTER_PLUS_EXPR at LOC offsetting PTR by OFF.  */
14423 tree
14424 fold_build_pointer_plus_loc (location_t loc, tree ptr, tree off)
14425 {
14426   return fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (ptr),
14427                           ptr, convert_to_ptrofftype_loc (loc, off));
14428 }
14429
14430 /* Build and fold a POINTER_PLUS_EXPR at LOC offsetting PTR by OFF.  */
14431 tree
14432 fold_build_pointer_plus_hwi_loc (location_t loc, tree ptr, HOST_WIDE_INT off)
14433 {
14434   return fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (ptr),
14435                           ptr, size_int (off));
14436 }