match.pd: Implement pattern from simplify_mult.
[platform/upstream/gcc.git] / gcc / tree-ssa-forwprop.c
1 /* Forward propagation of expressions for single use variables.
2    Copyright (C) 2004-2014 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
9 any later version.
10
11 GCC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License 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 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "tm.h"
24 #include "tree.h"
25 #include "stor-layout.h"
26 #include "tm_p.h"
27 #include "predict.h"
28 #include "vec.h"
29 #include "hashtab.h"
30 #include "hash-set.h"
31 #include "machmode.h"
32 #include "hard-reg-set.h"
33 #include "input.h"
34 #include "function.h"
35 #include "dominance.h"
36 #include "cfg.h"
37 #include "basic-block.h"
38 #include "gimple-pretty-print.h"
39 #include "tree-ssa-alias.h"
40 #include "internal-fn.h"
41 #include "gimple-fold.h"
42 #include "tree-eh.h"
43 #include "gimple-expr.h"
44 #include "is-a.h"
45 #include "gimple.h"
46 #include "gimplify.h"
47 #include "gimple-iterator.h"
48 #include "gimplify-me.h"
49 #include "gimple-ssa.h"
50 #include "tree-cfg.h"
51 #include "tree-phinodes.h"
52 #include "ssa-iterators.h"
53 #include "stringpool.h"
54 #include "tree-ssanames.h"
55 #include "expr.h"
56 #include "tree-dfa.h"
57 #include "tree-pass.h"
58 #include "langhooks.h"
59 #include "flags.h"
60 #include "diagnostic.h"
61 #include "expr.h"
62 #include "cfgloop.h"
63 #include "insn-codes.h"
64 #include "optabs.h"
65 #include "tree-ssa-propagate.h"
66 #include "tree-ssa-dom.h"
67 #include "builtins.h"
68 #include "tree-cfgcleanup.h"
69 #include "tree-into-ssa.h"
70 #include "cfganal.h"
71
72 /* This pass propagates the RHS of assignment statements into use
73    sites of the LHS of the assignment.  It's basically a specialized
74    form of tree combination.   It is hoped all of this can disappear
75    when we have a generalized tree combiner.
76
77    One class of common cases we handle is forward propagating a single use
78    variable into a COND_EXPR.
79
80      bb0:
81        x = a COND b;
82        if (x) goto ... else goto ...
83
84    Will be transformed into:
85
86      bb0:
87        if (a COND b) goto ... else goto ...
88
89    Similarly for the tests (x == 0), (x != 0), (x == 1) and (x != 1).
90
91    Or (assuming c1 and c2 are constants):
92
93      bb0:
94        x = a + c1;
95        if (x EQ/NEQ c2) goto ... else goto ...
96
97    Will be transformed into:
98
99      bb0:
100         if (a EQ/NEQ (c2 - c1)) goto ... else goto ...
101
102    Similarly for x = a - c1.
103
104    Or
105
106      bb0:
107        x = !a
108        if (x) goto ... else goto ...
109
110    Will be transformed into:
111
112      bb0:
113         if (a == 0) goto ... else goto ...
114
115    Similarly for the tests (x == 0), (x != 0), (x == 1) and (x != 1).
116    For these cases, we propagate A into all, possibly more than one,
117    COND_EXPRs that use X.
118
119    Or
120
121      bb0:
122        x = (typecast) a
123        if (x) goto ... else goto ...
124
125    Will be transformed into:
126
127      bb0:
128         if (a != 0) goto ... else goto ...
129
130    (Assuming a is an integral type and x is a boolean or x is an
131     integral and a is a boolean.)
132
133    Similarly for the tests (x == 0), (x != 0), (x == 1) and (x != 1).
134    For these cases, we propagate A into all, possibly more than one,
135    COND_EXPRs that use X.
136
137    In addition to eliminating the variable and the statement which assigns
138    a value to the variable, we may be able to later thread the jump without
139    adding insane complexity in the dominator optimizer.
140
141    Also note these transformations can cascade.  We handle this by having
142    a worklist of COND_EXPR statements to examine.  As we make a change to
143    a statement, we put it back on the worklist to examine on the next
144    iteration of the main loop.
145
146    A second class of propagation opportunities arises for ADDR_EXPR
147    nodes.
148
149      ptr = &x->y->z;
150      res = *ptr;
151
152    Will get turned into
153
154      res = x->y->z;
155
156    Or
157      ptr = (type1*)&type2var;
158      res = *ptr
159
160    Will get turned into (if type1 and type2 are the same size
161    and neither have volatile on them):
162      res = VIEW_CONVERT_EXPR<type1>(type2var)
163
164    Or
165
166      ptr = &x[0];
167      ptr2 = ptr + <constant>;
168
169    Will get turned into
170
171      ptr2 = &x[constant/elementsize];
172
173   Or
174
175      ptr = &x[0];
176      offset = index * element_size;
177      offset_p = (pointer) offset;
178      ptr2 = ptr + offset_p
179
180   Will get turned into:
181
182      ptr2 = &x[index];
183
184   Or
185     ssa = (int) decl
186     res = ssa & 1
187
188   Provided that decl has known alignment >= 2, will get turned into
189
190     res = 0
191
192   We also propagate casts into SWITCH_EXPR and COND_EXPR conditions to
193   allow us to remove the cast and {NOT_EXPR,NEG_EXPR} into a subsequent
194   {NOT_EXPR,NEG_EXPR}.
195
196    This will (of course) be extended as other needs arise.  */
197
198 static bool forward_propagate_addr_expr (tree, tree, bool);
199
200 /* Set to true if we delete dead edges during the optimization.  */
201 static bool cfg_changed;
202
203 static tree rhs_to_tree (tree type, gimple stmt);
204
205 static bitmap to_purge;
206
207 /* Const-and-copy lattice.  */
208 static vec<tree> lattice;
209
210 /* Set the lattice entry for NAME to VAL.  */
211 static void
212 fwprop_set_lattice_val (tree name, tree val)
213 {
214   if (TREE_CODE (name) == SSA_NAME)
215     {
216       if (SSA_NAME_VERSION (name) >= lattice.length ())
217         {
218           lattice.reserve (num_ssa_names - lattice.length ());
219           lattice.quick_grow_cleared (num_ssa_names);
220         }
221       lattice[SSA_NAME_VERSION (name)] = val;
222     }
223 }
224
225 /* Invalidate the lattice entry for NAME, done when releasing SSA names.  */
226 static void
227 fwprop_invalidate_lattice (tree name)
228 {
229   if (name
230       && TREE_CODE (name) == SSA_NAME
231       && SSA_NAME_VERSION (name) < lattice.length ())
232     lattice[SSA_NAME_VERSION (name)] = NULL_TREE;
233 }
234
235
236 /* Get the next statement we can propagate NAME's value into skipping
237    trivial copies.  Returns the statement that is suitable as a
238    propagation destination or NULL_TREE if there is no such one.
239    This only returns destinations in a single-use chain.  FINAL_NAME_P
240    if non-NULL is written to the ssa name that represents the use.  */
241
242 static gimple
243 get_prop_dest_stmt (tree name, tree *final_name_p)
244 {
245   use_operand_p use;
246   gimple use_stmt;
247
248   do {
249     /* If name has multiple uses, bail out.  */
250     if (!single_imm_use (name, &use, &use_stmt))
251       return NULL;
252
253     /* If this is not a trivial copy, we found it.  */
254     if (!gimple_assign_ssa_name_copy_p (use_stmt)
255         || gimple_assign_rhs1 (use_stmt) != name)
256       break;
257
258     /* Continue searching uses of the copy destination.  */
259     name = gimple_assign_lhs (use_stmt);
260   } while (1);
261
262   if (final_name_p)
263     *final_name_p = name;
264
265   return use_stmt;
266 }
267
268 /* Get the statement we can propagate from into NAME skipping
269    trivial copies.  Returns the statement which defines the
270    propagation source or NULL_TREE if there is no such one.
271    If SINGLE_USE_ONLY is set considers only sources which have
272    a single use chain up to NAME.  If SINGLE_USE_P is non-null,
273    it is set to whether the chain to NAME is a single use chain
274    or not.  SINGLE_USE_P is not written to if SINGLE_USE_ONLY is set.  */
275
276 static gimple
277 get_prop_source_stmt (tree name, bool single_use_only, bool *single_use_p)
278 {
279   bool single_use = true;
280
281   do {
282     gimple def_stmt = SSA_NAME_DEF_STMT (name);
283
284     if (!has_single_use (name))
285       {
286         single_use = false;
287         if (single_use_only)
288           return NULL;
289       }
290
291     /* If name is defined by a PHI node or is the default def, bail out.  */
292     if (!is_gimple_assign (def_stmt))
293       return NULL;
294
295     /* If def_stmt is a simple copy, continue looking.  */
296     if (gimple_assign_rhs_code (def_stmt) == SSA_NAME)
297       name = gimple_assign_rhs1 (def_stmt);
298     else
299       {
300         if (!single_use_only && single_use_p)
301           *single_use_p = single_use;
302
303         return def_stmt;
304       }
305   } while (1);
306 }
307
308 /* Checks if the destination ssa name in DEF_STMT can be used as
309    propagation source.  Returns true if so, otherwise false.  */
310
311 static bool
312 can_propagate_from (gimple def_stmt)
313 {
314   gcc_assert (is_gimple_assign (def_stmt));
315
316   /* If the rhs has side-effects we cannot propagate from it.  */
317   if (gimple_has_volatile_ops (def_stmt))
318     return false;
319
320   /* If the rhs is a load we cannot propagate from it.  */
321   if (TREE_CODE_CLASS (gimple_assign_rhs_code (def_stmt)) == tcc_reference
322       || TREE_CODE_CLASS (gimple_assign_rhs_code (def_stmt)) == tcc_declaration)
323     return false;
324
325   /* Constants can be always propagated.  */
326   if (gimple_assign_single_p (def_stmt)
327       && is_gimple_min_invariant (gimple_assign_rhs1 (def_stmt)))
328     return true;
329
330   /* We cannot propagate ssa names that occur in abnormal phi nodes.  */
331   if (stmt_references_abnormal_ssa_name (def_stmt))
332     return false;
333
334   /* If the definition is a conversion of a pointer to a function type,
335      then we can not apply optimizations as some targets require
336      function pointers to be canonicalized and in this case this
337      optimization could eliminate a necessary canonicalization.  */
338   if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
339     {
340       tree rhs = gimple_assign_rhs1 (def_stmt);
341       if (POINTER_TYPE_P (TREE_TYPE (rhs))
342           && TREE_CODE (TREE_TYPE (TREE_TYPE (rhs))) == FUNCTION_TYPE)
343         return false;
344     }
345
346   return true;
347 }
348
349 /* Remove a chain of dead statements starting at the definition of
350    NAME.  The chain is linked via the first operand of the defining statements.
351    If NAME was replaced in its only use then this function can be used
352    to clean up dead stmts.  The function handles already released SSA
353    names gracefully.
354    Returns true if cleanup-cfg has to run.  */
355
356 static bool
357 remove_prop_source_from_use (tree name)
358 {
359   gimple_stmt_iterator gsi;
360   gimple stmt;
361   bool cfg_changed = false;
362
363   do {
364     basic_block bb;
365
366     if (SSA_NAME_IN_FREE_LIST (name)
367         || SSA_NAME_IS_DEFAULT_DEF (name)
368         || !has_zero_uses (name))
369       return cfg_changed;
370
371     stmt = SSA_NAME_DEF_STMT (name);
372     if (gimple_code (stmt) == GIMPLE_PHI
373         || gimple_has_side_effects (stmt))
374       return cfg_changed;
375
376     bb = gimple_bb (stmt);
377     gsi = gsi_for_stmt (stmt);
378     unlink_stmt_vdef (stmt);
379     if (gsi_remove (&gsi, true))
380       bitmap_set_bit (to_purge, bb->index);
381     fwprop_invalidate_lattice (gimple_get_lhs (stmt));
382     release_defs (stmt);
383
384     name = is_gimple_assign (stmt) ? gimple_assign_rhs1 (stmt) : NULL_TREE;
385   } while (name && TREE_CODE (name) == SSA_NAME);
386
387   return cfg_changed;
388 }
389
390 /* Return the rhs of a gimple_assign STMT in a form of a single tree,
391    converted to type TYPE.
392
393    This should disappear, but is needed so we can combine expressions and use
394    the fold() interfaces. Long term, we need to develop folding and combine
395    routines that deal with gimple exclusively . */
396
397 static tree
398 rhs_to_tree (tree type, gimple stmt)
399 {
400   location_t loc = gimple_location (stmt);
401   enum tree_code code = gimple_assign_rhs_code (stmt);
402   if (get_gimple_rhs_class (code) == GIMPLE_TERNARY_RHS)
403     return fold_build3_loc (loc, code, type, gimple_assign_rhs1 (stmt),
404                             gimple_assign_rhs2 (stmt),
405                             gimple_assign_rhs3 (stmt));
406   else if (get_gimple_rhs_class (code) == GIMPLE_BINARY_RHS)
407     return fold_build2_loc (loc, code, type, gimple_assign_rhs1 (stmt),
408                         gimple_assign_rhs2 (stmt));
409   else if (get_gimple_rhs_class (code) == GIMPLE_UNARY_RHS)
410     return build1 (code, type, gimple_assign_rhs1 (stmt));
411   else if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
412     return gimple_assign_rhs1 (stmt);
413   else
414     gcc_unreachable ();
415 }
416
417 /* Combine OP0 CODE OP1 in the context of a COND_EXPR.  Returns
418    the folded result in a form suitable for COND_EXPR_COND or
419    NULL_TREE, if there is no suitable simplified form.  If
420    INVARIANT_ONLY is true only gimple_min_invariant results are
421    considered simplified.  */
422
423 static tree
424 combine_cond_expr_cond (gimple stmt, enum tree_code code, tree type,
425                         tree op0, tree op1, bool invariant_only)
426 {
427   tree t;
428
429   gcc_assert (TREE_CODE_CLASS (code) == tcc_comparison);
430
431   fold_defer_overflow_warnings ();
432   t = fold_binary_loc (gimple_location (stmt), code, type, op0, op1);
433   if (!t)
434     {
435       fold_undefer_overflow_warnings (false, NULL, 0);
436       return NULL_TREE;
437     }
438
439   /* Require that we got a boolean type out if we put one in.  */
440   gcc_assert (TREE_CODE (TREE_TYPE (t)) == TREE_CODE (type));
441
442   /* Canonicalize the combined condition for use in a COND_EXPR.  */
443   t = canonicalize_cond_expr_cond (t);
444
445   /* Bail out if we required an invariant but didn't get one.  */
446   if (!t || (invariant_only && !is_gimple_min_invariant (t)))
447     {
448       fold_undefer_overflow_warnings (false, NULL, 0);
449       return NULL_TREE;
450     }
451
452   fold_undefer_overflow_warnings (!gimple_no_warning_p (stmt), stmt, 0);
453
454   return t;
455 }
456
457 /* Combine the comparison OP0 CODE OP1 at LOC with the defining statements
458    of its operand.  Return a new comparison tree or NULL_TREE if there
459    were no simplifying combines.  */
460
461 static tree
462 forward_propagate_into_comparison_1 (gimple stmt,
463                                      enum tree_code code, tree type,
464                                      tree op0, tree op1)
465 {
466   tree tmp = NULL_TREE;
467   tree rhs0 = NULL_TREE, rhs1 = NULL_TREE;
468   bool single_use0_p = false, single_use1_p = false;
469
470   /* For comparisons use the first operand, that is likely to
471      simplify comparisons against constants.  */
472   if (TREE_CODE (op0) == SSA_NAME)
473     {
474       gimple def_stmt = get_prop_source_stmt (op0, false, &single_use0_p);
475       if (def_stmt && can_propagate_from (def_stmt))
476         {
477           rhs0 = rhs_to_tree (TREE_TYPE (op1), def_stmt);
478           tmp = combine_cond_expr_cond (stmt, code, type,
479                                         rhs0, op1, !single_use0_p);
480           if (tmp)
481             return tmp;
482         }
483     }
484
485   /* If that wasn't successful, try the second operand.  */
486   if (TREE_CODE (op1) == SSA_NAME)
487     {
488       gimple def_stmt = get_prop_source_stmt (op1, false, &single_use1_p);
489       if (def_stmt && can_propagate_from (def_stmt))
490         {
491           rhs1 = rhs_to_tree (TREE_TYPE (op0), def_stmt);
492           tmp = combine_cond_expr_cond (stmt, code, type,
493                                         op0, rhs1, !single_use1_p);
494           if (tmp)
495             return tmp;
496         }
497     }
498
499   /* If that wasn't successful either, try both operands.  */
500   if (rhs0 != NULL_TREE
501       && rhs1 != NULL_TREE)
502     tmp = combine_cond_expr_cond (stmt, code, type,
503                                   rhs0, rhs1,
504                                   !(single_use0_p && single_use1_p));
505
506   return tmp;
507 }
508
509 /* Propagate from the ssa name definition statements of the assignment
510    from a comparison at *GSI into the conditional if that simplifies it.
511    Returns 1 if the stmt was modified and 2 if the CFG needs cleanup,
512    otherwise returns 0.  */
513
514 static int 
515 forward_propagate_into_comparison (gimple_stmt_iterator *gsi)
516 {
517   gimple stmt = gsi_stmt (*gsi);
518   tree tmp;
519   bool cfg_changed = false;
520   tree type = TREE_TYPE (gimple_assign_lhs (stmt));
521   tree rhs1 = gimple_assign_rhs1 (stmt);
522   tree rhs2 = gimple_assign_rhs2 (stmt);
523
524   /* Combine the comparison with defining statements.  */
525   tmp = forward_propagate_into_comparison_1 (stmt,
526                                              gimple_assign_rhs_code (stmt),
527                                              type, rhs1, rhs2);
528   if (tmp && useless_type_conversion_p (type, TREE_TYPE (tmp)))
529     {
530       gimple_assign_set_rhs_from_tree (gsi, tmp);
531       fold_stmt (gsi);
532       update_stmt (gsi_stmt (*gsi));
533
534       if (TREE_CODE (rhs1) == SSA_NAME)
535         cfg_changed |= remove_prop_source_from_use (rhs1);
536       if (TREE_CODE (rhs2) == SSA_NAME)
537         cfg_changed |= remove_prop_source_from_use (rhs2);
538       return cfg_changed ? 2 : 1;
539     }
540
541   return 0;
542 }
543
544 /* Propagate from the ssa name definition statements of COND_EXPR
545    in GIMPLE_COND statement STMT into the conditional if that simplifies it.
546    Returns zero if no statement was changed, one if there were
547    changes and two if cfg_cleanup needs to run.
548
549    This must be kept in sync with forward_propagate_into_cond.  */
550
551 static int
552 forward_propagate_into_gimple_cond (gimple stmt)
553 {
554   tree tmp;
555   enum tree_code code = gimple_cond_code (stmt);
556   bool cfg_changed = false;
557   tree rhs1 = gimple_cond_lhs (stmt);
558   tree rhs2 = gimple_cond_rhs (stmt);
559
560   /* We can do tree combining on SSA_NAME and comparison expressions.  */
561   if (TREE_CODE_CLASS (gimple_cond_code (stmt)) != tcc_comparison)
562     return 0;
563
564   tmp = forward_propagate_into_comparison_1 (stmt, code,
565                                              boolean_type_node,
566                                              rhs1, rhs2);
567   if (tmp)
568     {
569       if (dump_file && tmp)
570         {
571           fprintf (dump_file, "  Replaced '");
572           print_gimple_expr (dump_file, stmt, 0, 0);
573           fprintf (dump_file, "' with '");
574           print_generic_expr (dump_file, tmp, 0);
575           fprintf (dump_file, "'\n");
576         }
577
578       gimple_cond_set_condition_from_tree (stmt, unshare_expr (tmp));
579       update_stmt (stmt);
580
581       if (TREE_CODE (rhs1) == SSA_NAME)
582         cfg_changed |= remove_prop_source_from_use (rhs1);
583       if (TREE_CODE (rhs2) == SSA_NAME)
584         cfg_changed |= remove_prop_source_from_use (rhs2);
585       return (cfg_changed || is_gimple_min_invariant (tmp)) ? 2 : 1;
586     }
587
588   /* Canonicalize _Bool == 0 and _Bool != 1 to _Bool != 0 by swapping edges.  */
589   if ((TREE_CODE (TREE_TYPE (rhs1)) == BOOLEAN_TYPE
590        || (INTEGRAL_TYPE_P (TREE_TYPE (rhs1))
591            && TYPE_PRECISION (TREE_TYPE (rhs1)) == 1))
592       && ((code == EQ_EXPR
593            && integer_zerop (rhs2))
594           || (code == NE_EXPR
595               && integer_onep (rhs2))))
596     {
597       basic_block bb = gimple_bb (stmt);
598       gimple_cond_set_code (stmt, NE_EXPR);
599       gimple_cond_set_rhs (stmt, build_zero_cst (TREE_TYPE (rhs1)));
600       EDGE_SUCC (bb, 0)->flags ^= (EDGE_TRUE_VALUE|EDGE_FALSE_VALUE);
601       EDGE_SUCC (bb, 1)->flags ^= (EDGE_TRUE_VALUE|EDGE_FALSE_VALUE);
602       return 1;
603     }
604
605   return 0;
606 }
607
608
609 /* Propagate from the ssa name definition statements of COND_EXPR
610    in the rhs of statement STMT into the conditional if that simplifies it.
611    Returns true zero if the stmt was changed.  */
612
613 static bool
614 forward_propagate_into_cond (gimple_stmt_iterator *gsi_p)
615 {
616   gimple stmt = gsi_stmt (*gsi_p);
617   tree tmp = NULL_TREE;
618   tree cond = gimple_assign_rhs1 (stmt);
619   enum tree_code code = gimple_assign_rhs_code (stmt);
620   bool swap = false;
621
622   /* We can do tree combining on SSA_NAME and comparison expressions.  */
623   if (COMPARISON_CLASS_P (cond))
624     tmp = forward_propagate_into_comparison_1 (stmt, TREE_CODE (cond),
625                                                TREE_TYPE (cond),
626                                                TREE_OPERAND (cond, 0),
627                                                TREE_OPERAND (cond, 1));
628   else if (TREE_CODE (cond) == SSA_NAME)
629     {
630       enum tree_code def_code;
631       tree name = cond;
632       gimple def_stmt = get_prop_source_stmt (name, true, NULL);
633       if (!def_stmt || !can_propagate_from (def_stmt))
634         return 0;
635
636       def_code = gimple_assign_rhs_code (def_stmt);
637       if (TREE_CODE_CLASS (def_code) == tcc_comparison)
638         tmp = fold_build2_loc (gimple_location (def_stmt),
639                                def_code,
640                                TREE_TYPE (cond),
641                                gimple_assign_rhs1 (def_stmt),
642                                gimple_assign_rhs2 (def_stmt));
643       else if (code == COND_EXPR
644                && ((def_code == BIT_NOT_EXPR
645                     && TYPE_PRECISION (TREE_TYPE (cond)) == 1)
646                    || (def_code == BIT_XOR_EXPR
647                        && integer_onep (gimple_assign_rhs2 (def_stmt)))))
648         {
649           tmp = gimple_assign_rhs1 (def_stmt);
650           swap = true;
651         }
652     }
653
654   if (tmp
655       && is_gimple_condexpr (tmp))
656     {
657       if (dump_file && tmp)
658         {
659           fprintf (dump_file, "  Replaced '");
660           print_generic_expr (dump_file, cond, 0);
661           fprintf (dump_file, "' with '");
662           print_generic_expr (dump_file, tmp, 0);
663           fprintf (dump_file, "'\n");
664         }
665
666       if ((code == VEC_COND_EXPR) ? integer_all_onesp (tmp)
667                                   : integer_onep (tmp))
668         gimple_assign_set_rhs_from_tree (gsi_p, gimple_assign_rhs2 (stmt));
669       else if (integer_zerop (tmp))
670         gimple_assign_set_rhs_from_tree (gsi_p, gimple_assign_rhs3 (stmt));
671       else
672         {
673           gimple_assign_set_rhs1 (stmt, unshare_expr (tmp));
674           if (swap)
675             {
676               tree t = gimple_assign_rhs2 (stmt);
677               gimple_assign_set_rhs2 (stmt, gimple_assign_rhs3 (stmt));
678               gimple_assign_set_rhs3 (stmt, t);
679             }
680         }
681       stmt = gsi_stmt (*gsi_p);
682       update_stmt (stmt);
683
684       return true;
685     }
686
687   return 0;
688 }
689
690 /* Propagate from the ssa name definition statements of COND_EXPR
691    values in the rhs of statement STMT into the conditional arms
692    if that simplifies it.
693    Returns true if the stmt was changed.  */
694
695 static bool
696 combine_cond_exprs (gimple_stmt_iterator *gsi_p)
697 {
698   gimple stmt = gsi_stmt (*gsi_p);
699   tree cond, val1, val2;
700   bool changed = false;
701
702   cond = gimple_assign_rhs1 (stmt);
703   val1 = gimple_assign_rhs2 (stmt);
704   if (TREE_CODE (val1) == SSA_NAME)
705     {
706       gimple def_stmt = SSA_NAME_DEF_STMT (val1);
707       if (is_gimple_assign (def_stmt)
708           && gimple_assign_rhs_code (def_stmt) == gimple_assign_rhs_code (stmt)
709           && operand_equal_p (gimple_assign_rhs1 (def_stmt), cond, 0))
710         {
711           val1 = unshare_expr (gimple_assign_rhs2 (def_stmt));
712           gimple_assign_set_rhs2 (stmt, val1);
713           changed = true;
714         }
715     }
716   val2 = gimple_assign_rhs3 (stmt);
717   if (TREE_CODE (val2) == SSA_NAME)
718     {
719       gimple def_stmt = SSA_NAME_DEF_STMT (val2);
720       if (is_gimple_assign (def_stmt)
721           && gimple_assign_rhs_code (def_stmt) == gimple_assign_rhs_code (stmt)
722           && operand_equal_p (gimple_assign_rhs1 (def_stmt), cond, 0))
723         {
724           val2 = unshare_expr (gimple_assign_rhs3 (def_stmt));
725           gimple_assign_set_rhs3 (stmt, val2);
726           changed = true;
727         }
728     }
729   if (operand_equal_p (val1, val2, 0))
730     {
731       gimple_assign_set_rhs_from_tree (gsi_p, val1);
732       stmt = gsi_stmt (*gsi_p);
733       changed = true;
734     }
735
736   if (changed)
737     update_stmt (stmt);
738
739   return changed;
740 }
741
742 /* We've just substituted an ADDR_EXPR into stmt.  Update all the
743    relevant data structures to match.  */
744
745 static void
746 tidy_after_forward_propagate_addr (gimple stmt)
747 {
748   /* We may have turned a trapping insn into a non-trapping insn.  */
749   if (maybe_clean_or_replace_eh_stmt (stmt, stmt))
750     bitmap_set_bit (to_purge, gimple_bb (stmt)->index);
751
752   if (TREE_CODE (gimple_assign_rhs1 (stmt)) == ADDR_EXPR)
753      recompute_tree_invariant_for_addr_expr (gimple_assign_rhs1 (stmt));
754 }
755
756 /* NAME is a SSA_NAME representing DEF_RHS which is of the form
757    ADDR_EXPR <whatever>.
758
759    Try to forward propagate the ADDR_EXPR into the use USE_STMT.
760    Often this will allow for removal of an ADDR_EXPR and INDIRECT_REF
761    node or for recovery of array indexing from pointer arithmetic.
762
763    Return true if the propagation was successful (the propagation can
764    be not totally successful, yet things may have been changed).  */
765
766 static bool
767 forward_propagate_addr_expr_1 (tree name, tree def_rhs,
768                                gimple_stmt_iterator *use_stmt_gsi,
769                                bool single_use_p)
770 {
771   tree lhs, rhs, rhs2, array_ref;
772   gimple use_stmt = gsi_stmt (*use_stmt_gsi);
773   enum tree_code rhs_code;
774   bool res = true;
775
776   gcc_assert (TREE_CODE (def_rhs) == ADDR_EXPR);
777
778   lhs = gimple_assign_lhs (use_stmt);
779   rhs_code = gimple_assign_rhs_code (use_stmt);
780   rhs = gimple_assign_rhs1 (use_stmt);
781
782   /* Do not perform copy-propagation but recurse through copy chains.  */
783   if (TREE_CODE (lhs) == SSA_NAME
784       && rhs_code == SSA_NAME)
785     return forward_propagate_addr_expr (lhs, def_rhs, single_use_p);
786
787   /* The use statement could be a conversion.  Recurse to the uses of the
788      lhs as copyprop does not copy through pointer to integer to pointer
789      conversions and FRE does not catch all cases either.
790      Treat the case of a single-use name and
791      a conversion to def_rhs type separate, though.  */
792   if (TREE_CODE (lhs) == SSA_NAME
793       && CONVERT_EXPR_CODE_P (rhs_code))
794     {
795       /* If there is a point in a conversion chain where the types match
796          so we can remove a conversion re-materialize the address here
797          and stop.  */
798       if (single_use_p
799           && useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (def_rhs)))
800         {
801           gimple_assign_set_rhs1 (use_stmt, unshare_expr (def_rhs));
802           gimple_assign_set_rhs_code (use_stmt, TREE_CODE (def_rhs));
803           return true;
804         }
805
806       /* Else recurse if the conversion preserves the address value.  */
807       if ((INTEGRAL_TYPE_P (TREE_TYPE (lhs))
808            || POINTER_TYPE_P (TREE_TYPE (lhs)))
809           && (TYPE_PRECISION (TREE_TYPE (lhs))
810               >= TYPE_PRECISION (TREE_TYPE (def_rhs))))
811         return forward_propagate_addr_expr (lhs, def_rhs, single_use_p);
812
813       return false;
814     }
815
816   /* If this isn't a conversion chain from this on we only can propagate
817      into compatible pointer contexts.  */
818   if (!types_compatible_p (TREE_TYPE (name), TREE_TYPE (def_rhs)))
819     return false;
820
821   /* Propagate through constant pointer adjustments.  */
822   if (TREE_CODE (lhs) == SSA_NAME
823       && rhs_code == POINTER_PLUS_EXPR
824       && rhs == name
825       && TREE_CODE (gimple_assign_rhs2 (use_stmt)) == INTEGER_CST)
826     {
827       tree new_def_rhs;
828       /* As we come here with non-invariant addresses in def_rhs we need
829          to make sure we can build a valid constant offsetted address
830          for further propagation.  Simply rely on fold building that
831          and check after the fact.  */
832       new_def_rhs = fold_build2 (MEM_REF, TREE_TYPE (TREE_TYPE (rhs)),
833                                  def_rhs,
834                                  fold_convert (ptr_type_node,
835                                                gimple_assign_rhs2 (use_stmt)));
836       if (TREE_CODE (new_def_rhs) == MEM_REF
837           && !is_gimple_mem_ref_addr (TREE_OPERAND (new_def_rhs, 0)))
838         return false;
839       new_def_rhs = build_fold_addr_expr_with_type (new_def_rhs,
840                                                     TREE_TYPE (rhs));
841
842       /* Recurse.  If we could propagate into all uses of lhs do not
843          bother to replace into the current use but just pretend we did.  */
844       if (TREE_CODE (new_def_rhs) == ADDR_EXPR
845           && forward_propagate_addr_expr (lhs, new_def_rhs, single_use_p))
846         return true;
847
848       if (useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (new_def_rhs)))
849         gimple_assign_set_rhs_with_ops (use_stmt_gsi, TREE_CODE (new_def_rhs),
850                                         new_def_rhs, NULL_TREE);
851       else if (is_gimple_min_invariant (new_def_rhs))
852         gimple_assign_set_rhs_with_ops (use_stmt_gsi, NOP_EXPR,
853                                         new_def_rhs, NULL_TREE);
854       else
855         return false;
856       gcc_assert (gsi_stmt (*use_stmt_gsi) == use_stmt);
857       update_stmt (use_stmt);
858       return true;
859     }
860
861   /* Now strip away any outer COMPONENT_REF/ARRAY_REF nodes from the LHS.
862      ADDR_EXPR will not appear on the LHS.  */
863   tree *lhsp = gimple_assign_lhs_ptr (use_stmt);
864   while (handled_component_p (*lhsp))
865     lhsp = &TREE_OPERAND (*lhsp, 0);
866   lhs = *lhsp;
867
868   /* Now see if the LHS node is a MEM_REF using NAME.  If so,
869      propagate the ADDR_EXPR into the use of NAME and fold the result.  */
870   if (TREE_CODE (lhs) == MEM_REF
871       && TREE_OPERAND (lhs, 0) == name)
872     {
873       tree def_rhs_base;
874       HOST_WIDE_INT def_rhs_offset;
875       /* If the address is invariant we can always fold it.  */
876       if ((def_rhs_base = get_addr_base_and_unit_offset (TREE_OPERAND (def_rhs, 0),
877                                                          &def_rhs_offset)))
878         {
879           offset_int off = mem_ref_offset (lhs);
880           tree new_ptr;
881           off += def_rhs_offset;
882           if (TREE_CODE (def_rhs_base) == MEM_REF)
883             {
884               off += mem_ref_offset (def_rhs_base);
885               new_ptr = TREE_OPERAND (def_rhs_base, 0);
886             }
887           else
888             new_ptr = build_fold_addr_expr (def_rhs_base);
889           TREE_OPERAND (lhs, 0) = new_ptr;
890           TREE_OPERAND (lhs, 1)
891             = wide_int_to_tree (TREE_TYPE (TREE_OPERAND (lhs, 1)), off);
892           tidy_after_forward_propagate_addr (use_stmt);
893           /* Continue propagating into the RHS if this was not the only use.  */
894           if (single_use_p)
895             return true;
896         }
897       /* If the LHS is a plain dereference and the value type is the same as
898          that of the pointed-to type of the address we can put the
899          dereferenced address on the LHS preserving the original alias-type.  */
900       else if (integer_zerop (TREE_OPERAND (lhs, 1))
901                && ((gimple_assign_lhs (use_stmt) == lhs
902                     && useless_type_conversion_p
903                          (TREE_TYPE (TREE_OPERAND (def_rhs, 0)),
904                           TREE_TYPE (gimple_assign_rhs1 (use_stmt))))
905                    || types_compatible_p (TREE_TYPE (lhs),
906                                           TREE_TYPE (TREE_OPERAND (def_rhs, 0))))
907                /* Don't forward anything into clobber stmts if it would result
908                   in the lhs no longer being a MEM_REF.  */
909                && (!gimple_clobber_p (use_stmt)
910                    || TREE_CODE (TREE_OPERAND (def_rhs, 0)) == MEM_REF))
911         {
912           tree *def_rhs_basep = &TREE_OPERAND (def_rhs, 0);
913           tree new_offset, new_base, saved, new_lhs;
914           while (handled_component_p (*def_rhs_basep))
915             def_rhs_basep = &TREE_OPERAND (*def_rhs_basep, 0);
916           saved = *def_rhs_basep;
917           if (TREE_CODE (*def_rhs_basep) == MEM_REF)
918             {
919               new_base = TREE_OPERAND (*def_rhs_basep, 0);
920               new_offset = fold_convert (TREE_TYPE (TREE_OPERAND (lhs, 1)),
921                                          TREE_OPERAND (*def_rhs_basep, 1));
922             }
923           else
924             {
925               new_base = build_fold_addr_expr (*def_rhs_basep);
926               new_offset = TREE_OPERAND (lhs, 1);
927             }
928           *def_rhs_basep = build2 (MEM_REF, TREE_TYPE (*def_rhs_basep),
929                                    new_base, new_offset);
930           TREE_THIS_VOLATILE (*def_rhs_basep) = TREE_THIS_VOLATILE (lhs);
931           TREE_SIDE_EFFECTS (*def_rhs_basep) = TREE_SIDE_EFFECTS (lhs);
932           TREE_THIS_NOTRAP (*def_rhs_basep) = TREE_THIS_NOTRAP (lhs);
933           new_lhs = unshare_expr (TREE_OPERAND (def_rhs, 0));
934           *lhsp = new_lhs;
935           TREE_THIS_VOLATILE (new_lhs) = TREE_THIS_VOLATILE (lhs);
936           TREE_SIDE_EFFECTS (new_lhs) = TREE_SIDE_EFFECTS (lhs);
937           *def_rhs_basep = saved;
938           tidy_after_forward_propagate_addr (use_stmt);
939           /* Continue propagating into the RHS if this was not the
940              only use.  */
941           if (single_use_p)
942             return true;
943         }
944       else
945         /* We can have a struct assignment dereferencing our name twice.
946            Note that we didn't propagate into the lhs to not falsely
947            claim we did when propagating into the rhs.  */
948         res = false;
949     }
950
951   /* Strip away any outer COMPONENT_REF, ARRAY_REF or ADDR_EXPR
952      nodes from the RHS.  */
953   tree *rhsp = gimple_assign_rhs1_ptr (use_stmt);
954   if (TREE_CODE (*rhsp) == ADDR_EXPR)
955     rhsp = &TREE_OPERAND (*rhsp, 0);
956   while (handled_component_p (*rhsp))
957     rhsp = &TREE_OPERAND (*rhsp, 0);
958   rhs = *rhsp;
959
960   /* Now see if the RHS node is a MEM_REF using NAME.  If so,
961      propagate the ADDR_EXPR into the use of NAME and fold the result.  */
962   if (TREE_CODE (rhs) == MEM_REF
963       && TREE_OPERAND (rhs, 0) == name)
964     {
965       tree def_rhs_base;
966       HOST_WIDE_INT def_rhs_offset;
967       if ((def_rhs_base = get_addr_base_and_unit_offset (TREE_OPERAND (def_rhs, 0),
968                                                          &def_rhs_offset)))
969         {
970           offset_int off = mem_ref_offset (rhs);
971           tree new_ptr;
972           off += def_rhs_offset;
973           if (TREE_CODE (def_rhs_base) == MEM_REF)
974             {
975               off += mem_ref_offset (def_rhs_base);
976               new_ptr = TREE_OPERAND (def_rhs_base, 0);
977             }
978           else
979             new_ptr = build_fold_addr_expr (def_rhs_base);
980           TREE_OPERAND (rhs, 0) = new_ptr;
981           TREE_OPERAND (rhs, 1)
982             = wide_int_to_tree (TREE_TYPE (TREE_OPERAND (rhs, 1)), off);
983           fold_stmt_inplace (use_stmt_gsi);
984           tidy_after_forward_propagate_addr (use_stmt);
985           return res;
986         }
987       /* If the RHS is a plain dereference and the value type is the same as
988          that of the pointed-to type of the address we can put the
989          dereferenced address on the RHS preserving the original alias-type.  */
990       else if (integer_zerop (TREE_OPERAND (rhs, 1))
991                && ((gimple_assign_rhs1 (use_stmt) == rhs
992                     && useless_type_conversion_p
993                          (TREE_TYPE (gimple_assign_lhs (use_stmt)),
994                           TREE_TYPE (TREE_OPERAND (def_rhs, 0))))
995                    || types_compatible_p (TREE_TYPE (rhs),
996                                           TREE_TYPE (TREE_OPERAND (def_rhs, 0)))))
997         {
998           tree *def_rhs_basep = &TREE_OPERAND (def_rhs, 0);
999           tree new_offset, new_base, saved, new_rhs;
1000           while (handled_component_p (*def_rhs_basep))
1001             def_rhs_basep = &TREE_OPERAND (*def_rhs_basep, 0);
1002           saved = *def_rhs_basep;
1003           if (TREE_CODE (*def_rhs_basep) == MEM_REF)
1004             {
1005               new_base = TREE_OPERAND (*def_rhs_basep, 0);
1006               new_offset = fold_convert (TREE_TYPE (TREE_OPERAND (rhs, 1)),
1007                                          TREE_OPERAND (*def_rhs_basep, 1));
1008             }
1009           else
1010             {
1011               new_base = build_fold_addr_expr (*def_rhs_basep);
1012               new_offset = TREE_OPERAND (rhs, 1);
1013             }
1014           *def_rhs_basep = build2 (MEM_REF, TREE_TYPE (*def_rhs_basep),
1015                                    new_base, new_offset);
1016           TREE_THIS_VOLATILE (*def_rhs_basep) = TREE_THIS_VOLATILE (rhs);
1017           TREE_SIDE_EFFECTS (*def_rhs_basep) = TREE_SIDE_EFFECTS (rhs);
1018           TREE_THIS_NOTRAP (*def_rhs_basep) = TREE_THIS_NOTRAP (rhs);
1019           new_rhs = unshare_expr (TREE_OPERAND (def_rhs, 0));
1020           *rhsp = new_rhs;
1021           TREE_THIS_VOLATILE (new_rhs) = TREE_THIS_VOLATILE (rhs);
1022           TREE_SIDE_EFFECTS (new_rhs) = TREE_SIDE_EFFECTS (rhs);
1023           *def_rhs_basep = saved;
1024           fold_stmt_inplace (use_stmt_gsi);
1025           tidy_after_forward_propagate_addr (use_stmt);
1026           return res;
1027         }
1028     }
1029
1030   /* If the use of the ADDR_EXPR is not a POINTER_PLUS_EXPR, there
1031      is nothing to do. */
1032   if (gimple_assign_rhs_code (use_stmt) != POINTER_PLUS_EXPR
1033       || gimple_assign_rhs1 (use_stmt) != name)
1034     return false;
1035
1036   /* The remaining cases are all for turning pointer arithmetic into
1037      array indexing.  They only apply when we have the address of
1038      element zero in an array.  If that is not the case then there
1039      is nothing to do.  */
1040   array_ref = TREE_OPERAND (def_rhs, 0);
1041   if ((TREE_CODE (array_ref) != ARRAY_REF
1042        || TREE_CODE (TREE_TYPE (TREE_OPERAND (array_ref, 0))) != ARRAY_TYPE
1043        || TREE_CODE (TREE_OPERAND (array_ref, 1)) != INTEGER_CST)
1044       && TREE_CODE (TREE_TYPE (array_ref)) != ARRAY_TYPE)
1045     return false;
1046
1047   rhs2 = gimple_assign_rhs2 (use_stmt);
1048   /* Optimize &x[C1] p+ C2 to  &x p+ C3 with C3 = C1 * element_size + C2.  */
1049   if (TREE_CODE (rhs2) == INTEGER_CST)
1050     {
1051       tree new_rhs = build1_loc (gimple_location (use_stmt),
1052                                  ADDR_EXPR, TREE_TYPE (def_rhs),
1053                                  fold_build2 (MEM_REF,
1054                                               TREE_TYPE (TREE_TYPE (def_rhs)),
1055                                               unshare_expr (def_rhs),
1056                                               fold_convert (ptr_type_node,
1057                                                             rhs2)));
1058       gimple_assign_set_rhs_from_tree (use_stmt_gsi, new_rhs);
1059       use_stmt = gsi_stmt (*use_stmt_gsi);
1060       update_stmt (use_stmt);
1061       tidy_after_forward_propagate_addr (use_stmt);
1062       return true;
1063     }
1064
1065   return false;
1066 }
1067
1068 /* STMT is a statement of the form SSA_NAME = ADDR_EXPR <whatever>.
1069
1070    Try to forward propagate the ADDR_EXPR into all uses of the SSA_NAME.
1071    Often this will allow for removal of an ADDR_EXPR and INDIRECT_REF
1072    node or for recovery of array indexing from pointer arithmetic.
1073
1074    PARENT_SINGLE_USE_P tells if, when in a recursive invocation, NAME was
1075    the single use in the previous invocation.  Pass true when calling
1076    this as toplevel.
1077
1078    Returns true, if all uses have been propagated into.  */
1079
1080 static bool
1081 forward_propagate_addr_expr (tree name, tree rhs, bool parent_single_use_p)
1082 {
1083   imm_use_iterator iter;
1084   gimple use_stmt;
1085   bool all = true;
1086   bool single_use_p = parent_single_use_p && has_single_use (name);
1087
1088   FOR_EACH_IMM_USE_STMT (use_stmt, iter, name)
1089     {
1090       bool result;
1091       tree use_rhs;
1092
1093       /* If the use is not in a simple assignment statement, then
1094          there is nothing we can do.  */
1095       if (!is_gimple_assign (use_stmt))
1096         {
1097           if (!is_gimple_debug (use_stmt))
1098             all = false;
1099           continue;
1100         }
1101
1102       gimple_stmt_iterator gsi = gsi_for_stmt (use_stmt);
1103       result = forward_propagate_addr_expr_1 (name, rhs, &gsi,
1104                                               single_use_p);
1105       /* If the use has moved to a different statement adjust
1106          the update machinery for the old statement too.  */
1107       if (use_stmt != gsi_stmt (gsi))
1108         {
1109           update_stmt (use_stmt);
1110           use_stmt = gsi_stmt (gsi);
1111         }
1112       update_stmt (use_stmt);
1113       all &= result;
1114
1115       /* Remove intermediate now unused copy and conversion chains.  */
1116       use_rhs = gimple_assign_rhs1 (use_stmt);
1117       if (result
1118           && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
1119           && TREE_CODE (use_rhs) == SSA_NAME
1120           && has_zero_uses (gimple_assign_lhs (use_stmt)))
1121         {
1122           gimple_stmt_iterator gsi = gsi_for_stmt (use_stmt);
1123           fwprop_invalidate_lattice (gimple_get_lhs (use_stmt));
1124           release_defs (use_stmt);
1125           gsi_remove (&gsi, true);
1126         }
1127     }
1128
1129   return all && has_zero_uses (name);
1130 }
1131
1132
1133 /* Forward propagate the comparison defined in *DEFGSI like
1134    cond_1 = x CMP y to uses of the form
1135      a_1 = (T')cond_1
1136      a_1 = !cond_1
1137      a_1 = cond_1 != 0
1138    Returns true if stmt is now unused.  Advance DEFGSI to the next
1139    statement.  */
1140
1141 static bool
1142 forward_propagate_comparison (gimple_stmt_iterator *defgsi)
1143 {
1144   gimple stmt = gsi_stmt (*defgsi);
1145   tree name = gimple_assign_lhs (stmt);
1146   gimple use_stmt;
1147   tree tmp = NULL_TREE;
1148   gimple_stmt_iterator gsi;
1149   enum tree_code code;
1150   tree lhs;
1151
1152   /* Don't propagate ssa names that occur in abnormal phis.  */
1153   if ((TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME
1154        && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (gimple_assign_rhs1 (stmt)))
1155       || (TREE_CODE (gimple_assign_rhs2 (stmt)) == SSA_NAME
1156         && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (gimple_assign_rhs2 (stmt))))
1157     goto bailout;
1158
1159   /* Do not un-cse comparisons.  But propagate through copies.  */
1160   use_stmt = get_prop_dest_stmt (name, &name);
1161   if (!use_stmt
1162       || !is_gimple_assign (use_stmt))
1163     goto bailout;
1164
1165   code = gimple_assign_rhs_code (use_stmt);
1166   lhs = gimple_assign_lhs (use_stmt);
1167   if (!INTEGRAL_TYPE_P (TREE_TYPE (lhs)))
1168     goto bailout;
1169
1170   /* We can propagate the condition into a statement that
1171      computes the logical negation of the comparison result.  */
1172   if ((code == BIT_NOT_EXPR
1173        && TYPE_PRECISION (TREE_TYPE (lhs)) == 1)
1174       || (code == BIT_XOR_EXPR
1175           && integer_onep (gimple_assign_rhs2 (use_stmt))))
1176     {
1177       tree type = TREE_TYPE (gimple_assign_rhs1 (stmt));
1178       bool nans = HONOR_NANS (TYPE_MODE (type));
1179       enum tree_code inv_code;
1180       inv_code = invert_tree_comparison (gimple_assign_rhs_code (stmt), nans);
1181       if (inv_code == ERROR_MARK)
1182         goto bailout;
1183
1184       tmp = build2 (inv_code, TREE_TYPE (lhs), gimple_assign_rhs1 (stmt),
1185                     gimple_assign_rhs2 (stmt));
1186     }
1187   else
1188     goto bailout;
1189
1190   gsi = gsi_for_stmt (use_stmt);
1191   gimple_assign_set_rhs_from_tree (&gsi, unshare_expr (tmp));
1192   use_stmt = gsi_stmt (gsi);
1193   update_stmt (use_stmt);
1194
1195   if (dump_file && (dump_flags & TDF_DETAILS))
1196     {
1197       fprintf (dump_file, "  Replaced '");
1198       print_gimple_expr (dump_file, stmt, 0, dump_flags);
1199       fprintf (dump_file, "' with '");
1200       print_gimple_expr (dump_file, use_stmt, 0, dump_flags);
1201       fprintf (dump_file, "'\n");
1202     }
1203
1204   /* When we remove stmt now the iterator defgsi goes off it's current
1205      sequence, hence advance it now.  */
1206   gsi_next (defgsi);
1207
1208   /* Remove defining statements.  */
1209   return remove_prop_source_from_use (name);
1210
1211 bailout:
1212   gsi_next (defgsi);
1213   return false;
1214 }
1215
1216
1217 /* Helper function for simplify_gimple_switch.  Remove case labels that
1218    have values outside the range of the new type.  */
1219
1220 static void
1221 simplify_gimple_switch_label_vec (gimple stmt, tree index_type)
1222 {
1223   unsigned int branch_num = gimple_switch_num_labels (stmt);
1224   auto_vec<tree> labels (branch_num);
1225   unsigned int i, len;
1226
1227   /* Collect the existing case labels in a VEC, and preprocess it as if
1228      we are gimplifying a GENERIC SWITCH_EXPR.  */
1229   for (i = 1; i < branch_num; i++)
1230     labels.quick_push (gimple_switch_label (stmt, i));
1231   preprocess_case_label_vec_for_gimple (labels, index_type, NULL);
1232
1233   /* If any labels were removed, replace the existing case labels
1234      in the GIMPLE_SWITCH statement with the correct ones.
1235      Note that the type updates were done in-place on the case labels,
1236      so we only have to replace the case labels in the GIMPLE_SWITCH
1237      if the number of labels changed.  */
1238   len = labels.length ();
1239   if (len < branch_num - 1)
1240     {
1241       bitmap target_blocks;
1242       edge_iterator ei;
1243       edge e;
1244
1245       /* Corner case: *all* case labels have been removed as being
1246          out-of-range for INDEX_TYPE.  Push one label and let the
1247          CFG cleanups deal with this further.  */
1248       if (len == 0)
1249         {
1250           tree label, elt;
1251
1252           label = CASE_LABEL (gimple_switch_default_label (stmt));
1253           elt = build_case_label (build_int_cst (index_type, 0), NULL, label);
1254           labels.quick_push (elt);
1255           len = 1;
1256         }
1257
1258       for (i = 0; i < labels.length (); i++)
1259         gimple_switch_set_label (stmt, i + 1, labels[i]);
1260       for (i++ ; i < branch_num; i++)
1261         gimple_switch_set_label (stmt, i, NULL_TREE);
1262       gimple_switch_set_num_labels (stmt, len + 1);
1263
1264       /* Cleanup any edges that are now dead.  */
1265       target_blocks = BITMAP_ALLOC (NULL);
1266       for (i = 0; i < gimple_switch_num_labels (stmt); i++)
1267         {
1268           tree elt = gimple_switch_label (stmt, i);
1269           basic_block target = label_to_block (CASE_LABEL (elt));
1270           bitmap_set_bit (target_blocks, target->index);
1271         }
1272       for (ei = ei_start (gimple_bb (stmt)->succs); (e = ei_safe_edge (ei)); )
1273         {
1274           if (! bitmap_bit_p (target_blocks, e->dest->index))
1275             {
1276               remove_edge (e);
1277               cfg_changed = true;
1278               free_dominance_info (CDI_DOMINATORS);
1279             }
1280           else
1281             ei_next (&ei);
1282         } 
1283       BITMAP_FREE (target_blocks);
1284     }
1285 }
1286
1287 /* STMT is a SWITCH_EXPR for which we attempt to find equivalent forms of
1288    the condition which we may be able to optimize better.  */
1289
1290 static bool
1291 simplify_gimple_switch (gimple stmt)
1292 {
1293   /* The optimization that we really care about is removing unnecessary
1294      casts.  That will let us do much better in propagating the inferred
1295      constant at the switch target.  */
1296   tree cond = gimple_switch_index (stmt);
1297   if (TREE_CODE (cond) == SSA_NAME)
1298     {
1299       gimple def_stmt = SSA_NAME_DEF_STMT (cond);
1300       if (gimple_assign_cast_p (def_stmt))
1301         {
1302           tree def = gimple_assign_rhs1 (def_stmt);
1303           if (TREE_CODE (def) != SSA_NAME)
1304             return false;
1305
1306           /* If we have an extension or sign-change that preserves the
1307              values we check against then we can copy the source value into
1308              the switch.  */
1309           tree ti = TREE_TYPE (def);
1310           if (INTEGRAL_TYPE_P (ti)
1311               && TYPE_PRECISION (ti) <= TYPE_PRECISION (TREE_TYPE (cond)))
1312             {
1313               size_t n = gimple_switch_num_labels (stmt);
1314               tree min = NULL_TREE, max = NULL_TREE;
1315               if (n > 1)
1316                 {
1317                   min = CASE_LOW (gimple_switch_label (stmt, 1));
1318                   if (CASE_HIGH (gimple_switch_label (stmt, n - 1)))
1319                     max = CASE_HIGH (gimple_switch_label (stmt, n - 1));
1320                   else
1321                     max = CASE_LOW (gimple_switch_label (stmt, n - 1));
1322                 }
1323               if ((!min || int_fits_type_p (min, ti))
1324                   && (!max || int_fits_type_p (max, ti)))
1325                 {
1326                   gimple_switch_set_index (stmt, def);
1327                   simplify_gimple_switch_label_vec (stmt, ti);
1328                   update_stmt (stmt);
1329                   return true;
1330                 }
1331             }
1332         }
1333     }
1334
1335   return false;
1336 }
1337
1338 /* For pointers p2 and p1 return p2 - p1 if the
1339    difference is known and constant, otherwise return NULL.  */
1340
1341 static tree
1342 constant_pointer_difference (tree p1, tree p2)
1343 {
1344   int i, j;
1345 #define CPD_ITERATIONS 5
1346   tree exps[2][CPD_ITERATIONS];
1347   tree offs[2][CPD_ITERATIONS];
1348   int cnt[2];
1349
1350   for (i = 0; i < 2; i++)
1351     {
1352       tree p = i ? p1 : p2;
1353       tree off = size_zero_node;
1354       gimple stmt;
1355       enum tree_code code;
1356
1357       /* For each of p1 and p2 we need to iterate at least
1358          twice, to handle ADDR_EXPR directly in p1/p2,
1359          SSA_NAME with ADDR_EXPR or POINTER_PLUS_EXPR etc.
1360          on definition's stmt RHS.  Iterate a few extra times.  */
1361       j = 0;
1362       do
1363         {
1364           if (!POINTER_TYPE_P (TREE_TYPE (p)))
1365             break;
1366           if (TREE_CODE (p) == ADDR_EXPR)
1367             {
1368               tree q = TREE_OPERAND (p, 0);
1369               HOST_WIDE_INT offset;
1370               tree base = get_addr_base_and_unit_offset (q, &offset);
1371               if (base)
1372                 {
1373                   q = base;
1374                   if (offset)
1375                     off = size_binop (PLUS_EXPR, off, size_int (offset));
1376                 }
1377               if (TREE_CODE (q) == MEM_REF
1378                   && TREE_CODE (TREE_OPERAND (q, 0)) == SSA_NAME)
1379                 {
1380                   p = TREE_OPERAND (q, 0);
1381                   off = size_binop (PLUS_EXPR, off,
1382                                     wide_int_to_tree (sizetype,
1383                                                       mem_ref_offset (q)));
1384                 }
1385               else
1386                 {
1387                   exps[i][j] = q;
1388                   offs[i][j++] = off;
1389                   break;
1390                 }
1391             }
1392           if (TREE_CODE (p) != SSA_NAME)
1393             break;
1394           exps[i][j] = p;
1395           offs[i][j++] = off;
1396           if (j == CPD_ITERATIONS)
1397             break;
1398           stmt = SSA_NAME_DEF_STMT (p);
1399           if (!is_gimple_assign (stmt) || gimple_assign_lhs (stmt) != p)
1400             break;
1401           code = gimple_assign_rhs_code (stmt);
1402           if (code == POINTER_PLUS_EXPR)
1403             {
1404               if (TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
1405                 break;
1406               off = size_binop (PLUS_EXPR, off, gimple_assign_rhs2 (stmt));
1407               p = gimple_assign_rhs1 (stmt);
1408             }
1409           else if (code == ADDR_EXPR || CONVERT_EXPR_CODE_P (code))
1410             p = gimple_assign_rhs1 (stmt);
1411           else
1412             break;
1413         }
1414       while (1);
1415       cnt[i] = j;
1416     }
1417
1418   for (i = 0; i < cnt[0]; i++)
1419     for (j = 0; j < cnt[1]; j++)
1420       if (exps[0][i] == exps[1][j])
1421         return size_binop (MINUS_EXPR, offs[0][i], offs[1][j]);
1422
1423   return NULL_TREE;
1424 }
1425
1426 /* *GSI_P is a GIMPLE_CALL to a builtin function.
1427    Optimize
1428    memcpy (p, "abcd", 4);
1429    memset (p + 4, ' ', 3);
1430    into
1431    memcpy (p, "abcd   ", 7);
1432    call if the latter can be stored by pieces during expansion.  */
1433
1434 static bool
1435 simplify_builtin_call (gimple_stmt_iterator *gsi_p, tree callee2)
1436 {
1437   gimple stmt1, stmt2 = gsi_stmt (*gsi_p);
1438   tree vuse = gimple_vuse (stmt2);
1439   if (vuse == NULL)
1440     return false;
1441   stmt1 = SSA_NAME_DEF_STMT (vuse);
1442
1443   switch (DECL_FUNCTION_CODE (callee2))
1444     {
1445     case BUILT_IN_MEMSET:
1446       if (gimple_call_num_args (stmt2) != 3
1447           || gimple_call_lhs (stmt2)
1448           || CHAR_BIT != 8
1449           || BITS_PER_UNIT != 8)
1450         break;
1451       else
1452         {
1453           tree callee1;
1454           tree ptr1, src1, str1, off1, len1, lhs1;
1455           tree ptr2 = gimple_call_arg (stmt2, 0);
1456           tree val2 = gimple_call_arg (stmt2, 1);
1457           tree len2 = gimple_call_arg (stmt2, 2);
1458           tree diff, vdef, new_str_cst;
1459           gimple use_stmt;
1460           unsigned int ptr1_align;
1461           unsigned HOST_WIDE_INT src_len;
1462           char *src_buf;
1463           use_operand_p use_p;
1464
1465           if (!tree_fits_shwi_p (val2)
1466               || !tree_fits_uhwi_p (len2))
1467             break;
1468           if (is_gimple_call (stmt1))
1469             {
1470               /* If first stmt is a call, it needs to be memcpy
1471                  or mempcpy, with string literal as second argument and
1472                  constant length.  */
1473               callee1 = gimple_call_fndecl (stmt1);
1474               if (callee1 == NULL_TREE
1475                   || DECL_BUILT_IN_CLASS (callee1) != BUILT_IN_NORMAL
1476                   || gimple_call_num_args (stmt1) != 3)
1477                 break;
1478               if (DECL_FUNCTION_CODE (callee1) != BUILT_IN_MEMCPY
1479                   && DECL_FUNCTION_CODE (callee1) != BUILT_IN_MEMPCPY)
1480                 break;
1481               ptr1 = gimple_call_arg (stmt1, 0);
1482               src1 = gimple_call_arg (stmt1, 1);
1483               len1 = gimple_call_arg (stmt1, 2);
1484               lhs1 = gimple_call_lhs (stmt1);
1485               if (!tree_fits_uhwi_p (len1))
1486                 break;
1487               str1 = string_constant (src1, &off1);
1488               if (str1 == NULL_TREE)
1489                 break;
1490               if (!tree_fits_uhwi_p (off1)
1491                   || compare_tree_int (off1, TREE_STRING_LENGTH (str1) - 1) > 0
1492                   || compare_tree_int (len1, TREE_STRING_LENGTH (str1)
1493                                              - tree_to_uhwi (off1)) > 0
1494                   || TREE_CODE (TREE_TYPE (str1)) != ARRAY_TYPE
1495                   || TYPE_MODE (TREE_TYPE (TREE_TYPE (str1)))
1496                      != TYPE_MODE (char_type_node))
1497                 break;
1498             }
1499           else if (gimple_assign_single_p (stmt1))
1500             {
1501               /* Otherwise look for length 1 memcpy optimized into
1502                  assignment.  */
1503               ptr1 = gimple_assign_lhs (stmt1);
1504               src1 = gimple_assign_rhs1 (stmt1);
1505               if (TREE_CODE (ptr1) != MEM_REF
1506                   || TYPE_MODE (TREE_TYPE (ptr1)) != TYPE_MODE (char_type_node)
1507                   || !tree_fits_shwi_p (src1))
1508                 break;
1509               ptr1 = build_fold_addr_expr (ptr1);
1510               callee1 = NULL_TREE;
1511               len1 = size_one_node;
1512               lhs1 = NULL_TREE;
1513               off1 = size_zero_node;
1514               str1 = NULL_TREE;
1515             }
1516           else
1517             break;
1518
1519           diff = constant_pointer_difference (ptr1, ptr2);
1520           if (diff == NULL && lhs1 != NULL)
1521             {
1522               diff = constant_pointer_difference (lhs1, ptr2);
1523               if (DECL_FUNCTION_CODE (callee1) == BUILT_IN_MEMPCPY
1524                   && diff != NULL)
1525                 diff = size_binop (PLUS_EXPR, diff,
1526                                    fold_convert (sizetype, len1));
1527             }
1528           /* If the difference between the second and first destination pointer
1529              is not constant, or is bigger than memcpy length, bail out.  */
1530           if (diff == NULL
1531               || !tree_fits_uhwi_p (diff)
1532               || tree_int_cst_lt (len1, diff))
1533             break;
1534
1535           /* Use maximum of difference plus memset length and memcpy length
1536              as the new memcpy length, if it is too big, bail out.  */
1537           src_len = tree_to_uhwi (diff);
1538           src_len += tree_to_uhwi (len2);
1539           if (src_len < tree_to_uhwi (len1))
1540             src_len = tree_to_uhwi (len1);
1541           if (src_len > 1024)
1542             break;
1543
1544           /* If mempcpy value is used elsewhere, bail out, as mempcpy
1545              with bigger length will return different result.  */
1546           if (lhs1 != NULL_TREE
1547               && DECL_FUNCTION_CODE (callee1) == BUILT_IN_MEMPCPY
1548               && (TREE_CODE (lhs1) != SSA_NAME
1549                   || !single_imm_use (lhs1, &use_p, &use_stmt)
1550                   || use_stmt != stmt2))
1551             break;
1552
1553           /* If anything reads memory in between memcpy and memset
1554              call, the modified memcpy call might change it.  */
1555           vdef = gimple_vdef (stmt1);
1556           if (vdef != NULL
1557               && (!single_imm_use (vdef, &use_p, &use_stmt)
1558                   || use_stmt != stmt2))
1559             break;
1560
1561           ptr1_align = get_pointer_alignment (ptr1);
1562           /* Construct the new source string literal.  */
1563           src_buf = XALLOCAVEC (char, src_len + 1);
1564           if (callee1)
1565             memcpy (src_buf,
1566                     TREE_STRING_POINTER (str1) + tree_to_uhwi (off1),
1567                     tree_to_uhwi (len1));
1568           else
1569             src_buf[0] = tree_to_shwi (src1);
1570           memset (src_buf + tree_to_uhwi (diff),
1571                   tree_to_shwi (val2), tree_to_uhwi (len2));
1572           src_buf[src_len] = '\0';
1573           /* Neither builtin_strncpy_read_str nor builtin_memcpy_read_str
1574              handle embedded '\0's.  */
1575           if (strlen (src_buf) != src_len)
1576             break;
1577           rtl_profile_for_bb (gimple_bb (stmt2));
1578           /* If the new memcpy wouldn't be emitted by storing the literal
1579              by pieces, this optimization might enlarge .rodata too much,
1580              as commonly used string literals couldn't be shared any
1581              longer.  */
1582           if (!can_store_by_pieces (src_len,
1583                                     builtin_strncpy_read_str,
1584                                     src_buf, ptr1_align, false))
1585             break;
1586
1587           new_str_cst = build_string_literal (src_len, src_buf);
1588           if (callee1)
1589             {
1590               /* If STMT1 is a mem{,p}cpy call, adjust it and remove
1591                  memset call.  */
1592               if (lhs1 && DECL_FUNCTION_CODE (callee1) == BUILT_IN_MEMPCPY)
1593                 gimple_call_set_lhs (stmt1, NULL_TREE);
1594               gimple_call_set_arg (stmt1, 1, new_str_cst);
1595               gimple_call_set_arg (stmt1, 2,
1596                                    build_int_cst (TREE_TYPE (len1), src_len));
1597               update_stmt (stmt1);
1598               unlink_stmt_vdef (stmt2);
1599               gsi_remove (gsi_p, true);
1600               fwprop_invalidate_lattice (gimple_get_lhs (stmt2));
1601               release_defs (stmt2);
1602               if (lhs1 && DECL_FUNCTION_CODE (callee1) == BUILT_IN_MEMPCPY)
1603                 {
1604                   fwprop_invalidate_lattice (lhs1);
1605                   release_ssa_name (lhs1);
1606                 }
1607               return true;
1608             }
1609           else
1610             {
1611               /* Otherwise, if STMT1 is length 1 memcpy optimized into
1612                  assignment, remove STMT1 and change memset call into
1613                  memcpy call.  */
1614               gimple_stmt_iterator gsi = gsi_for_stmt (stmt1);
1615
1616               if (!is_gimple_val (ptr1))
1617                 ptr1 = force_gimple_operand_gsi (gsi_p, ptr1, true, NULL_TREE,
1618                                                  true, GSI_SAME_STMT);
1619               gimple_call_set_fndecl (stmt2,
1620                                       builtin_decl_explicit (BUILT_IN_MEMCPY));
1621               gimple_call_set_arg (stmt2, 0, ptr1);
1622               gimple_call_set_arg (stmt2, 1, new_str_cst);
1623               gimple_call_set_arg (stmt2, 2,
1624                                    build_int_cst (TREE_TYPE (len2), src_len));
1625               unlink_stmt_vdef (stmt1);
1626               gsi_remove (&gsi, true);
1627               fwprop_invalidate_lattice (gimple_get_lhs (stmt1));
1628               release_defs (stmt1);
1629               update_stmt (stmt2);
1630               return false;
1631             }
1632         }
1633       break;
1634     default:
1635       break;
1636     }
1637   return false;
1638 }
1639
1640 /* Given a ssa_name in NAME see if it was defined by an assignment and
1641    set CODE to be the code and ARG1 to the first operand on the rhs and ARG2
1642    to the second operand on the rhs. */
1643
1644 static inline void
1645 defcodefor_name (tree name, enum tree_code *code, tree *arg1, tree *arg2)
1646 {
1647   gimple def;
1648   enum tree_code code1;
1649   tree arg11;
1650   tree arg21;
1651   tree arg31;
1652   enum gimple_rhs_class grhs_class;
1653
1654   code1 = TREE_CODE (name);
1655   arg11 = name;
1656   arg21 = NULL_TREE;
1657   grhs_class = get_gimple_rhs_class (code1);
1658
1659   if (code1 == SSA_NAME)
1660     {
1661       def = SSA_NAME_DEF_STMT (name);
1662       
1663       if (def && is_gimple_assign (def)
1664           && can_propagate_from (def))
1665         {
1666           code1 = gimple_assign_rhs_code (def);
1667           arg11 = gimple_assign_rhs1 (def);
1668           arg21 = gimple_assign_rhs2 (def);
1669           arg31 = gimple_assign_rhs2 (def);
1670         }
1671     }
1672   else if (grhs_class == GIMPLE_TERNARY_RHS
1673            || GIMPLE_BINARY_RHS
1674            || GIMPLE_UNARY_RHS
1675            || GIMPLE_SINGLE_RHS)
1676     extract_ops_from_tree_1 (name, &code1, &arg11, &arg21, &arg31);
1677
1678   *code = code1;
1679   *arg1 = arg11;
1680   if (arg2)
1681     *arg2 = arg21;
1682   /* Ignore arg3 currently. */
1683 }
1684
1685
1686 /* Recognize rotation patterns.  Return true if a transformation
1687    applied, otherwise return false.
1688
1689    We are looking for X with unsigned type T with bitsize B, OP being
1690    +, | or ^, some type T2 wider than T and
1691    (X << CNT1) OP (X >> CNT2)                           iff CNT1 + CNT2 == B
1692    ((T) ((T2) X << CNT1)) OP ((T) ((T2) X >> CNT2))     iff CNT1 + CNT2 == B
1693    (X << Y) OP (X >> (B - Y))
1694    (X << (int) Y) OP (X >> (int) (B - Y))
1695    ((T) ((T2) X << Y)) OP ((T) ((T2) X >> (B - Y)))
1696    ((T) ((T2) X << (int) Y)) OP ((T) ((T2) X >> (int) (B - Y)))
1697    (X << Y) | (X >> ((-Y) & (B - 1)))
1698    (X << (int) Y) | (X >> (int) ((-Y) & (B - 1)))
1699    ((T) ((T2) X << Y)) | ((T) ((T2) X >> ((-Y) & (B - 1))))
1700    ((T) ((T2) X << (int) Y)) | ((T) ((T2) X >> (int) ((-Y) & (B - 1))))
1701
1702    and transform these into:
1703    X r<< CNT1
1704    X r<< Y
1705
1706    Note, in the patterns with T2 type, the type of OP operands
1707    might be even a signed type, but should have precision B.  */
1708
1709 static bool
1710 simplify_rotate (gimple_stmt_iterator *gsi)
1711 {
1712   gimple stmt = gsi_stmt (*gsi);
1713   tree arg[2], rtype, rotcnt = NULL_TREE;
1714   tree def_arg1[2], def_arg2[2];
1715   enum tree_code def_code[2];
1716   tree lhs;
1717   int i;
1718   bool swapped_p = false;
1719   gimple g;
1720
1721   arg[0] = gimple_assign_rhs1 (stmt);
1722   arg[1] = gimple_assign_rhs2 (stmt);
1723   rtype = TREE_TYPE (arg[0]);
1724
1725   /* Only create rotates in complete modes.  Other cases are not
1726      expanded properly.  */
1727   if (!INTEGRAL_TYPE_P (rtype)
1728       || TYPE_PRECISION (rtype) != GET_MODE_PRECISION (TYPE_MODE (rtype)))
1729     return false;
1730
1731   for (i = 0; i < 2; i++)
1732     defcodefor_name (arg[i], &def_code[i], &def_arg1[i], &def_arg2[i]);
1733
1734   /* Look through narrowing conversions.  */
1735   if (CONVERT_EXPR_CODE_P (def_code[0])
1736       && CONVERT_EXPR_CODE_P (def_code[1])
1737       && INTEGRAL_TYPE_P (TREE_TYPE (def_arg1[0]))
1738       && INTEGRAL_TYPE_P (TREE_TYPE (def_arg1[1]))
1739       && TYPE_PRECISION (TREE_TYPE (def_arg1[0]))
1740          == TYPE_PRECISION (TREE_TYPE (def_arg1[1]))
1741       && TYPE_PRECISION (TREE_TYPE (def_arg1[0])) > TYPE_PRECISION (rtype)
1742       && has_single_use (arg[0])
1743       && has_single_use (arg[1]))
1744     {
1745       for (i = 0; i < 2; i++)
1746         {
1747           arg[i] = def_arg1[i];
1748           defcodefor_name (arg[i], &def_code[i], &def_arg1[i], &def_arg2[i]);
1749         }
1750     }
1751
1752   /* One operand has to be LSHIFT_EXPR and one RSHIFT_EXPR.  */
1753   for (i = 0; i < 2; i++)
1754     if (def_code[i] != LSHIFT_EXPR && def_code[i] != RSHIFT_EXPR)
1755       return false;
1756     else if (!has_single_use (arg[i]))
1757       return false;
1758   if (def_code[0] == def_code[1])
1759     return false;
1760
1761   /* If we've looked through narrowing conversions before, look through
1762      widening conversions from unsigned type with the same precision
1763      as rtype here.  */
1764   if (TYPE_PRECISION (TREE_TYPE (def_arg1[0])) != TYPE_PRECISION (rtype))
1765     for (i = 0; i < 2; i++)
1766       {
1767         tree tem;
1768         enum tree_code code;
1769         defcodefor_name (def_arg1[i], &code, &tem, NULL);
1770         if (!CONVERT_EXPR_CODE_P (code)
1771             || !INTEGRAL_TYPE_P (TREE_TYPE (tem))
1772             || TYPE_PRECISION (TREE_TYPE (tem)) != TYPE_PRECISION (rtype))
1773           return false;
1774         def_arg1[i] = tem;
1775       }
1776   /* Both shifts have to use the same first operand.  */
1777   if (TREE_CODE (def_arg1[0]) != SSA_NAME || def_arg1[0] != def_arg1[1])
1778     return false;
1779   if (!TYPE_UNSIGNED (TREE_TYPE (def_arg1[0])))
1780     return false;
1781
1782   /* CNT1 + CNT2 == B case above.  */
1783   if (tree_fits_uhwi_p (def_arg2[0])
1784       && tree_fits_uhwi_p (def_arg2[1])
1785       && tree_to_uhwi (def_arg2[0])
1786          + tree_to_uhwi (def_arg2[1]) == TYPE_PRECISION (rtype))
1787     rotcnt = def_arg2[0];
1788   else if (TREE_CODE (def_arg2[0]) != SSA_NAME
1789            || TREE_CODE (def_arg2[1]) != SSA_NAME)
1790     return false;
1791   else
1792     {
1793       tree cdef_arg1[2], cdef_arg2[2], def_arg2_alt[2];
1794       enum tree_code cdef_code[2];
1795       /* Look through conversion of the shift count argument.
1796          The C/C++ FE cast any shift count argument to integer_type_node.
1797          The only problem might be if the shift count type maximum value
1798          is equal or smaller than number of bits in rtype.  */
1799       for (i = 0; i < 2; i++)
1800         {
1801           def_arg2_alt[i] = def_arg2[i];
1802           defcodefor_name (def_arg2[i], &cdef_code[i],
1803                            &cdef_arg1[i], &cdef_arg2[i]);
1804           if (CONVERT_EXPR_CODE_P (cdef_code[i])
1805               && INTEGRAL_TYPE_P (TREE_TYPE (cdef_arg1[i]))
1806               && TYPE_PRECISION (TREE_TYPE (cdef_arg1[i]))
1807                  > floor_log2 (TYPE_PRECISION (rtype))
1808               && TYPE_PRECISION (TREE_TYPE (cdef_arg1[i]))
1809                  == GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (cdef_arg1[i]))))
1810             {
1811               def_arg2_alt[i] = cdef_arg1[i];
1812               defcodefor_name (def_arg2_alt[i], &cdef_code[i],
1813                                &cdef_arg1[i], &cdef_arg2[i]);
1814             }
1815         }
1816       for (i = 0; i < 2; i++)
1817         /* Check for one shift count being Y and the other B - Y,
1818            with optional casts.  */
1819         if (cdef_code[i] == MINUS_EXPR
1820             && tree_fits_shwi_p (cdef_arg1[i])
1821             && tree_to_shwi (cdef_arg1[i]) == TYPE_PRECISION (rtype)
1822             && TREE_CODE (cdef_arg2[i]) == SSA_NAME)
1823           {
1824             tree tem;
1825             enum tree_code code;
1826
1827             if (cdef_arg2[i] == def_arg2[1 - i]
1828                 || cdef_arg2[i] == def_arg2_alt[1 - i])
1829               {
1830                 rotcnt = cdef_arg2[i];
1831                 break;
1832               }
1833             defcodefor_name (cdef_arg2[i], &code, &tem, NULL);
1834             if (CONVERT_EXPR_CODE_P (code)
1835                 && INTEGRAL_TYPE_P (TREE_TYPE (tem))
1836                 && TYPE_PRECISION (TREE_TYPE (tem))
1837                  > floor_log2 (TYPE_PRECISION (rtype))
1838                 && TYPE_PRECISION (TREE_TYPE (tem))
1839                  == GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (tem)))
1840                 && (tem == def_arg2[1 - i]
1841                     || tem == def_arg2_alt[1 - i]))
1842               {
1843                 rotcnt = tem;
1844                 break;
1845               }
1846           }
1847         /* The above sequence isn't safe for Y being 0,
1848            because then one of the shifts triggers undefined behavior.
1849            This alternative is safe even for rotation count of 0.
1850            One shift count is Y and the other (-Y) & (B - 1).  */
1851         else if (cdef_code[i] == BIT_AND_EXPR
1852                  && tree_fits_shwi_p (cdef_arg2[i])
1853                  && tree_to_shwi (cdef_arg2[i])
1854                     == TYPE_PRECISION (rtype) - 1
1855                  && TREE_CODE (cdef_arg1[i]) == SSA_NAME
1856                  && gimple_assign_rhs_code (stmt) == BIT_IOR_EXPR)
1857           {
1858             tree tem;
1859             enum tree_code code;
1860
1861             defcodefor_name (cdef_arg1[i], &code, &tem, NULL);
1862             if (CONVERT_EXPR_CODE_P (code)
1863                 && INTEGRAL_TYPE_P (TREE_TYPE (tem))
1864                 && TYPE_PRECISION (TREE_TYPE (tem))
1865                  > floor_log2 (TYPE_PRECISION (rtype))
1866                 && TYPE_PRECISION (TREE_TYPE (tem))
1867                  == GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (tem))))
1868               defcodefor_name (tem, &code, &tem, NULL);
1869
1870             if (code == NEGATE_EXPR)
1871               {
1872                 if (tem == def_arg2[1 - i] || tem == def_arg2_alt[1 - i])
1873                   {
1874                     rotcnt = tem;
1875                     break;
1876                   }
1877                 defcodefor_name (tem, &code, &tem, NULL);
1878                 if (CONVERT_EXPR_CODE_P (code)
1879                     && INTEGRAL_TYPE_P (TREE_TYPE (tem))
1880                     && TYPE_PRECISION (TREE_TYPE (tem))
1881                        > floor_log2 (TYPE_PRECISION (rtype))
1882                     && TYPE_PRECISION (TREE_TYPE (tem))
1883                        == GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (tem)))
1884                     && (tem == def_arg2[1 - i]
1885                         || tem == def_arg2_alt[1 - i]))
1886                   {
1887                     rotcnt = tem;
1888                     break;
1889                   }
1890               }
1891           }
1892       if (rotcnt == NULL_TREE)
1893         return false;
1894       swapped_p = i != 1;
1895     }
1896
1897   if (!useless_type_conversion_p (TREE_TYPE (def_arg2[0]),
1898                                   TREE_TYPE (rotcnt)))
1899     {
1900       g = gimple_build_assign_with_ops (NOP_EXPR,
1901                                         make_ssa_name (TREE_TYPE (def_arg2[0]),
1902                                                        NULL),
1903                                         rotcnt, NULL_TREE);
1904       gsi_insert_before (gsi, g, GSI_SAME_STMT);
1905       rotcnt = gimple_assign_lhs (g);
1906     }
1907   lhs = gimple_assign_lhs (stmt);
1908   if (!useless_type_conversion_p (rtype, TREE_TYPE (def_arg1[0])))
1909     lhs = make_ssa_name (TREE_TYPE (def_arg1[0]), NULL);
1910   g = gimple_build_assign_with_ops (((def_code[0] == LSHIFT_EXPR) ^ swapped_p)
1911                                     ? LROTATE_EXPR : RROTATE_EXPR,
1912                                     lhs, def_arg1[0], rotcnt);
1913   if (!useless_type_conversion_p (rtype, TREE_TYPE (def_arg1[0])))
1914     {
1915       gsi_insert_before (gsi, g, GSI_SAME_STMT);
1916       g = gimple_build_assign_with_ops (NOP_EXPR, gimple_assign_lhs (stmt),
1917                                         lhs, NULL_TREE);
1918     }
1919   gsi_replace (gsi, g, false);
1920   return true;
1921 }
1922
1923 /* Perform re-associations of the plus or minus statement STMT that are
1924    always permitted.  Returns true if the CFG was changed.  */
1925
1926 static bool
1927 associate_plusminus (gimple_stmt_iterator *gsi)
1928 {
1929   gimple stmt = gsi_stmt (*gsi);
1930   tree rhs1 = gimple_assign_rhs1 (stmt);
1931   tree rhs2 = gimple_assign_rhs2 (stmt);
1932   enum tree_code code = gimple_assign_rhs_code (stmt);
1933   bool changed;
1934
1935   /* We can't reassociate at all for saturating types.  */
1936   if (TYPE_SATURATING (TREE_TYPE (rhs1)))
1937     return false;
1938
1939   /* First contract negates.  */
1940   do
1941     {
1942       changed = false;
1943
1944       /* A +- (-B) -> A -+ B.  */
1945       if (TREE_CODE (rhs2) == SSA_NAME)
1946         {
1947           gimple def_stmt = SSA_NAME_DEF_STMT (rhs2);
1948           if (is_gimple_assign (def_stmt)
1949               && gimple_assign_rhs_code (def_stmt) == NEGATE_EXPR
1950               && can_propagate_from (def_stmt))
1951             {
1952               code = (code == MINUS_EXPR) ? PLUS_EXPR : MINUS_EXPR;
1953               gimple_assign_set_rhs_code (stmt, code);
1954               rhs2 = gimple_assign_rhs1 (def_stmt);
1955               gimple_assign_set_rhs2 (stmt, rhs2);
1956               gimple_set_modified (stmt, true);
1957               changed = true;
1958             }
1959         }
1960
1961       /* (-A) + B -> B - A.  */
1962       if (TREE_CODE (rhs1) == SSA_NAME
1963           && code == PLUS_EXPR)
1964         {
1965           gimple def_stmt = SSA_NAME_DEF_STMT (rhs1);
1966           if (is_gimple_assign (def_stmt)
1967               && gimple_assign_rhs_code (def_stmt) == NEGATE_EXPR
1968               && can_propagate_from (def_stmt))
1969             {
1970               code = MINUS_EXPR;
1971               gimple_assign_set_rhs_code (stmt, code);
1972               rhs1 = rhs2;
1973               gimple_assign_set_rhs1 (stmt, rhs1);
1974               rhs2 = gimple_assign_rhs1 (def_stmt);
1975               gimple_assign_set_rhs2 (stmt, rhs2);
1976               gimple_set_modified (stmt, true);
1977               changed = true;
1978             }
1979         }
1980     }
1981   while (changed);
1982
1983   /* We can't reassociate floating-point or fixed-point plus or minus
1984      because of saturation to +-Inf.  */
1985   if (FLOAT_TYPE_P (TREE_TYPE (rhs1))
1986       || FIXED_POINT_TYPE_P (TREE_TYPE (rhs1)))
1987     goto out;
1988
1989   /* Second match patterns that allow contracting a plus-minus pair
1990      irrespective of overflow issues.
1991
1992         (A +- B) - A       ->  +- B
1993         (A +- B) -+ B      ->  A
1994         (CST +- A) +- CST  ->  CST +- A
1995         (A +- CST) +- CST  ->  A +- CST
1996         ~A + A             ->  -1
1997         ~A + 1             ->  -A 
1998         A - (A +- B)       ->  -+ B
1999         A +- (B +- A)      ->  +- B
2000         CST +- (CST +- A)  ->  CST +- A
2001         CST +- (A +- CST)  ->  CST +- A
2002         A + ~A             ->  -1
2003         (T)(P + A) - (T)P  -> (T)A
2004
2005      via commutating the addition and contracting operations to zero
2006      by reassociation.  */
2007
2008   if (TREE_CODE (rhs1) == SSA_NAME)
2009     {
2010       gimple def_stmt = SSA_NAME_DEF_STMT (rhs1);
2011       if (is_gimple_assign (def_stmt) && can_propagate_from (def_stmt))
2012         {
2013           enum tree_code def_code = gimple_assign_rhs_code (def_stmt);
2014           if (def_code == PLUS_EXPR
2015               || def_code == MINUS_EXPR)
2016             {
2017               tree def_rhs1 = gimple_assign_rhs1 (def_stmt);
2018               tree def_rhs2 = gimple_assign_rhs2 (def_stmt);
2019               if (operand_equal_p (def_rhs1, rhs2, 0)
2020                   && code == MINUS_EXPR)
2021                 {
2022                   /* (A +- B) - A -> +- B.  */
2023                   code = ((def_code == PLUS_EXPR)
2024                           ? TREE_CODE (def_rhs2) : NEGATE_EXPR);
2025                   rhs1 = def_rhs2;
2026                   rhs2 = NULL_TREE;
2027                   gimple_assign_set_rhs_with_ops (gsi, code, rhs1, NULL_TREE);
2028                   gcc_assert (gsi_stmt (*gsi) == stmt);
2029                   gimple_set_modified (stmt, true);
2030                 }
2031               else if (operand_equal_p (def_rhs2, rhs2, 0)
2032                        && code != def_code)
2033                 {
2034                   /* (A +- B) -+ B -> A.  */
2035                   code = TREE_CODE (def_rhs1);
2036                   rhs1 = def_rhs1;
2037                   rhs2 = NULL_TREE;
2038                   gimple_assign_set_rhs_with_ops (gsi, code, rhs1, NULL_TREE);
2039                   gcc_assert (gsi_stmt (*gsi) == stmt);
2040                   gimple_set_modified (stmt, true);
2041                 }
2042               else if (CONSTANT_CLASS_P (rhs2)
2043                        && CONSTANT_CLASS_P (def_rhs1))
2044                 {
2045                   /* (CST +- A) +- CST -> CST +- A.  */
2046                   tree cst = fold_binary (code, TREE_TYPE (rhs1),
2047                                           def_rhs1, rhs2);
2048                   if (cst && !TREE_OVERFLOW (cst))
2049                     {
2050                       code = def_code;
2051                       gimple_assign_set_rhs_code (stmt, code);
2052                       rhs1 = cst;
2053                       gimple_assign_set_rhs1 (stmt, rhs1);
2054                       rhs2 = def_rhs2;
2055                       gimple_assign_set_rhs2 (stmt, rhs2);
2056                       gimple_set_modified (stmt, true);
2057                     }
2058                 }
2059               else if (CONSTANT_CLASS_P (rhs2)
2060                        && CONSTANT_CLASS_P (def_rhs2))
2061                 {
2062                   /* (A +- CST) +- CST -> A +- CST.  */
2063                   enum tree_code mix = (code == def_code)
2064                                        ? PLUS_EXPR : MINUS_EXPR;
2065                   tree cst = fold_binary (mix, TREE_TYPE (rhs1),
2066                                           def_rhs2, rhs2);
2067                   if (cst && !TREE_OVERFLOW (cst))
2068                     {
2069                       code = def_code;
2070                       gimple_assign_set_rhs_code (stmt, code);
2071                       rhs1 = def_rhs1;
2072                       gimple_assign_set_rhs1 (stmt, rhs1);
2073                       rhs2 = cst;
2074                       gimple_assign_set_rhs2 (stmt, rhs2);
2075                       gimple_set_modified (stmt, true);
2076                     }
2077                 }
2078             }
2079           else if (def_code == BIT_NOT_EXPR && code == PLUS_EXPR)
2080             {
2081               tree def_rhs1 = gimple_assign_rhs1 (def_stmt);
2082               if (operand_equal_p (def_rhs1, rhs2, 0))
2083                 {
2084                   /* ~A + A -> -1.  */
2085                   rhs1 = build_all_ones_cst (TREE_TYPE (rhs2));
2086                   rhs2 = NULL_TREE;
2087                   code = TREE_CODE (rhs1);
2088                   gimple_assign_set_rhs_with_ops (gsi, code, rhs1, NULL_TREE);
2089                   gcc_assert (gsi_stmt (*gsi) == stmt);
2090                   gimple_set_modified (stmt, true);
2091                 }
2092               else if ((TREE_CODE (TREE_TYPE (rhs2)) != COMPLEX_TYPE
2093                         && integer_onep (rhs2))
2094                        || (TREE_CODE (rhs2) == COMPLEX_CST
2095                            && integer_onep (TREE_REALPART (rhs2))
2096                            && integer_onep (TREE_IMAGPART (rhs2))))
2097                 {
2098                   /* ~A + 1 -> -A.  */
2099                   code = NEGATE_EXPR;
2100                   rhs1 = def_rhs1;
2101                   rhs2 = NULL_TREE;
2102                   gimple_assign_set_rhs_with_ops (gsi, code, rhs1, NULL_TREE);
2103                   gcc_assert (gsi_stmt (*gsi) == stmt);
2104                   gimple_set_modified (stmt, true);
2105                 }
2106             }
2107           else if (code == MINUS_EXPR
2108                    && CONVERT_EXPR_CODE_P (def_code)
2109                    && TREE_CODE (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
2110                    && TREE_CODE (rhs2) == SSA_NAME)
2111             {
2112               /* (T)(P + A) - (T)P -> (T)A.  */
2113               gimple def_stmt2 = SSA_NAME_DEF_STMT (rhs2);
2114               if (is_gimple_assign (def_stmt2)
2115                   && can_propagate_from (def_stmt2)
2116                   && CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
2117                   && TREE_CODE (gimple_assign_rhs1 (def_stmt2)) == SSA_NAME)
2118                 {
2119                   /* Now we have (T)X - (T)P.  */
2120                   tree p = gimple_assign_rhs1 (def_stmt2);
2121                   def_stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (def_stmt));
2122                   if (is_gimple_assign (def_stmt2)
2123                       && can_propagate_from (def_stmt2)
2124                       && (gimple_assign_rhs_code (def_stmt2) == POINTER_PLUS_EXPR
2125                           || gimple_assign_rhs_code (def_stmt2) == PLUS_EXPR)
2126                       && gimple_assign_rhs1 (def_stmt2) == p)
2127                     {
2128                       /* And finally (T)(P + A) - (T)P.  */
2129                       tree a = gimple_assign_rhs2 (def_stmt2);
2130                       if (TYPE_PRECISION (TREE_TYPE (rhs1))
2131                           <= TYPE_PRECISION (TREE_TYPE (a))
2132                           /* For integer types, if A has a smaller type
2133                              than T the result depends on the possible
2134                              overflow in P + A.
2135                              E.g. T=size_t, A=(unsigned)429497295, P>0.
2136                              However, if an overflow in P + A would cause
2137                              undefined behavior, we can assume that there
2138                              is no overflow.  */
2139                           || (INTEGRAL_TYPE_P (TREE_TYPE (p))
2140                               && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (p)))
2141                           /* For pointer types, if the conversion of A to the
2142                              final type requires a sign- or zero-extension,
2143                              then we have to punt - it is not defined which
2144                              one is correct.  */
2145                           || (POINTER_TYPE_P (TREE_TYPE (p))
2146                               && TREE_CODE (a) == INTEGER_CST
2147                               && tree_int_cst_sign_bit (a) == 0))
2148                         {
2149                           if (issue_strict_overflow_warning
2150                               (WARN_STRICT_OVERFLOW_MISC)
2151                               && TYPE_PRECISION (TREE_TYPE (rhs1))
2152                                  > TYPE_PRECISION (TREE_TYPE (a))
2153                               && INTEGRAL_TYPE_P (TREE_TYPE (p)))
2154                             warning_at (gimple_location (stmt),
2155                                         OPT_Wstrict_overflow,
2156                                         "assuming signed overflow does not "
2157                                         "occur when assuming that "
2158                                         "(T)(P + A) - (T)P is always (T)A");
2159                           if (useless_type_conversion_p (TREE_TYPE (rhs1),
2160                                                          TREE_TYPE (a)))
2161                             code = TREE_CODE (a);
2162                           else
2163                             code = NOP_EXPR;
2164                           rhs1 = a;
2165                           rhs2 = NULL_TREE;
2166                           gimple_assign_set_rhs_with_ops (gsi, code, rhs1,
2167                                                           rhs2);
2168                           gcc_assert (gsi_stmt (*gsi) == stmt);
2169                           gimple_set_modified (stmt, true);
2170                         }
2171                     }
2172                 }
2173             }
2174         }
2175     }
2176
2177   if (rhs2 && TREE_CODE (rhs2) == SSA_NAME)
2178     {
2179       gimple def_stmt = SSA_NAME_DEF_STMT (rhs2);
2180       if (is_gimple_assign (def_stmt) && can_propagate_from (def_stmt))
2181         {
2182           enum tree_code def_code = gimple_assign_rhs_code (def_stmt);
2183           if (def_code == PLUS_EXPR
2184               || def_code == MINUS_EXPR)
2185             {
2186               tree def_rhs1 = gimple_assign_rhs1 (def_stmt);
2187               tree def_rhs2 = gimple_assign_rhs2 (def_stmt);
2188               if (operand_equal_p (def_rhs1, rhs1, 0)
2189                   && code == MINUS_EXPR)
2190                 {
2191                   /* A - (A +- B) -> -+ B.  */
2192                   code = ((def_code == PLUS_EXPR)
2193                           ? NEGATE_EXPR : TREE_CODE (def_rhs2));
2194                   rhs1 = def_rhs2;
2195                   rhs2 = NULL_TREE;
2196                   gimple_assign_set_rhs_with_ops (gsi, code, rhs1, NULL_TREE);
2197                   gcc_assert (gsi_stmt (*gsi) == stmt);
2198                   gimple_set_modified (stmt, true);
2199                 }
2200               else if (operand_equal_p (def_rhs2, rhs1, 0)
2201                        && code != def_code)
2202                 {
2203                   /* A +- (B +- A) -> +- B.  */
2204                   code = ((code == PLUS_EXPR)
2205                           ? TREE_CODE (def_rhs1) : NEGATE_EXPR);
2206                   rhs1 = def_rhs1;
2207                   rhs2 = NULL_TREE;
2208                   gimple_assign_set_rhs_with_ops (gsi, code, rhs1, NULL_TREE);
2209                   gcc_assert (gsi_stmt (*gsi) == stmt);
2210                   gimple_set_modified (stmt, true);
2211                 }
2212               else if (CONSTANT_CLASS_P (rhs1)
2213                        && CONSTANT_CLASS_P (def_rhs1))
2214                 {
2215                   /* CST +- (CST +- A) -> CST +- A.  */
2216                   tree cst = fold_binary (code, TREE_TYPE (rhs2),
2217                                           rhs1, def_rhs1);
2218                   if (cst && !TREE_OVERFLOW (cst))
2219                     {
2220                       code = (code == def_code ? PLUS_EXPR : MINUS_EXPR);
2221                       gimple_assign_set_rhs_code (stmt, code);
2222                       rhs1 = cst;
2223                       gimple_assign_set_rhs1 (stmt, rhs1);
2224                       rhs2 = def_rhs2;
2225                       gimple_assign_set_rhs2 (stmt, rhs2);
2226                       gimple_set_modified (stmt, true);
2227                     }
2228                 }
2229               else if (CONSTANT_CLASS_P (rhs1)
2230                        && CONSTANT_CLASS_P (def_rhs2))
2231                 {
2232                   /* CST +- (A +- CST) -> CST +- A.  */
2233                   tree cst = fold_binary (def_code == code
2234                                           ? PLUS_EXPR : MINUS_EXPR,
2235                                           TREE_TYPE (rhs2),
2236                                           rhs1, def_rhs2);
2237                   if (cst && !TREE_OVERFLOW (cst))
2238                     {
2239                       rhs1 = cst;
2240                       gimple_assign_set_rhs1 (stmt, rhs1);
2241                       rhs2 = def_rhs1;
2242                       gimple_assign_set_rhs2 (stmt, rhs2);
2243                       gimple_set_modified (stmt, true);
2244                     }
2245                 }
2246             }
2247           else if (def_code == BIT_NOT_EXPR)
2248             {
2249               tree def_rhs1 = gimple_assign_rhs1 (def_stmt);
2250               if (code == PLUS_EXPR
2251                   && operand_equal_p (def_rhs1, rhs1, 0))
2252                 {
2253                   /* A + ~A -> -1.  */
2254                   rhs1 = build_all_ones_cst (TREE_TYPE (rhs1));
2255                   rhs2 = NULL_TREE;
2256                   code = TREE_CODE (rhs1);
2257                   gimple_assign_set_rhs_with_ops (gsi, code, rhs1, NULL_TREE);
2258                   gcc_assert (gsi_stmt (*gsi) == stmt);
2259                   gimple_set_modified (stmt, true);
2260                 }
2261             }
2262         }
2263     }
2264
2265 out:
2266   if (gimple_modified_p (stmt))
2267     {
2268       fold_stmt_inplace (gsi);
2269       update_stmt (stmt);
2270       return true;
2271     }
2272
2273   return false;
2274 }
2275
2276 /* Combine an element access with a shuffle.  Returns true if there were
2277    any changes made, else it returns false.  */
2278  
2279 static bool
2280 simplify_bitfield_ref (gimple_stmt_iterator *gsi)
2281 {
2282   gimple stmt = gsi_stmt (*gsi);
2283   gimple def_stmt;
2284   tree op, op0, op1, op2;
2285   tree elem_type;
2286   unsigned idx, n, size;
2287   enum tree_code code;
2288
2289   op = gimple_assign_rhs1 (stmt);
2290   gcc_checking_assert (TREE_CODE (op) == BIT_FIELD_REF);
2291
2292   op0 = TREE_OPERAND (op, 0);
2293   if (TREE_CODE (op0) != SSA_NAME
2294       || TREE_CODE (TREE_TYPE (op0)) != VECTOR_TYPE)
2295     return false;
2296
2297   def_stmt = get_prop_source_stmt (op0, false, NULL);
2298   if (!def_stmt || !can_propagate_from (def_stmt))
2299     return false;
2300
2301   op1 = TREE_OPERAND (op, 1);
2302   op2 = TREE_OPERAND (op, 2);
2303   code = gimple_assign_rhs_code (def_stmt);
2304
2305   if (code == CONSTRUCTOR)
2306     {
2307       tree tem = fold_ternary (BIT_FIELD_REF, TREE_TYPE (op),
2308                                gimple_assign_rhs1 (def_stmt), op1, op2);
2309       if (!tem || !valid_gimple_rhs_p (tem))
2310         return false;
2311       gimple_assign_set_rhs_from_tree (gsi, tem);
2312       update_stmt (gsi_stmt (*gsi));
2313       return true;
2314     }
2315
2316   elem_type = TREE_TYPE (TREE_TYPE (op0));
2317   if (TREE_TYPE (op) != elem_type)
2318     return false;
2319
2320   size = TREE_INT_CST_LOW (TYPE_SIZE (elem_type));
2321   n = TREE_INT_CST_LOW (op1) / size;
2322   if (n != 1)
2323     return false;
2324   idx = TREE_INT_CST_LOW (op2) / size;
2325
2326   if (code == VEC_PERM_EXPR)
2327     {
2328       tree p, m, index, tem;
2329       unsigned nelts;
2330       m = gimple_assign_rhs3 (def_stmt);
2331       if (TREE_CODE (m) != VECTOR_CST)
2332         return false;
2333       nelts = VECTOR_CST_NELTS (m);
2334       idx = TREE_INT_CST_LOW (VECTOR_CST_ELT (m, idx));
2335       idx %= 2 * nelts;
2336       if (idx < nelts)
2337         {
2338           p = gimple_assign_rhs1 (def_stmt);
2339         }
2340       else
2341         {
2342           p = gimple_assign_rhs2 (def_stmt);
2343           idx -= nelts;
2344         }
2345       index = build_int_cst (TREE_TYPE (TREE_TYPE (m)), idx * size);
2346       tem = build3 (BIT_FIELD_REF, TREE_TYPE (op),
2347                     unshare_expr (p), op1, index);
2348       gimple_assign_set_rhs1 (stmt, tem);
2349       fold_stmt (gsi);
2350       update_stmt (gsi_stmt (*gsi));
2351       return true;
2352     }
2353
2354   return false;
2355 }
2356
2357 /* Determine whether applying the 2 permutations (mask1 then mask2)
2358    gives back one of the input.  */
2359
2360 static int
2361 is_combined_permutation_identity (tree mask1, tree mask2)
2362 {
2363   tree mask;
2364   unsigned int nelts, i, j;
2365   bool maybe_identity1 = true;
2366   bool maybe_identity2 = true;
2367
2368   gcc_checking_assert (TREE_CODE (mask1) == VECTOR_CST
2369                        && TREE_CODE (mask2) == VECTOR_CST);
2370   mask = fold_ternary (VEC_PERM_EXPR, TREE_TYPE (mask1), mask1, mask1, mask2);
2371   gcc_assert (TREE_CODE (mask) == VECTOR_CST);
2372
2373   nelts = VECTOR_CST_NELTS (mask);
2374   for (i = 0; i < nelts; i++)
2375     {
2376       tree val = VECTOR_CST_ELT (mask, i);
2377       gcc_assert (TREE_CODE (val) == INTEGER_CST);
2378       j = TREE_INT_CST_LOW (val) & (2 * nelts - 1);
2379       if (j == i)
2380         maybe_identity2 = false;
2381       else if (j == i + nelts)
2382         maybe_identity1 = false;
2383       else
2384         return 0;
2385     }
2386   return maybe_identity1 ? 1 : maybe_identity2 ? 2 : 0;
2387 }
2388
2389 /* Combine a shuffle with its arguments.  Returns 1 if there were any
2390    changes made, 2 if cfg-cleanup needs to run.  Else it returns 0.  */
2391  
2392 static int
2393 simplify_permutation (gimple_stmt_iterator *gsi)
2394 {
2395   gimple stmt = gsi_stmt (*gsi);
2396   gimple def_stmt;
2397   tree op0, op1, op2, op3, arg0, arg1;
2398   enum tree_code code;
2399   bool single_use_op0 = false;
2400
2401   gcc_checking_assert (gimple_assign_rhs_code (stmt) == VEC_PERM_EXPR);
2402
2403   op0 = gimple_assign_rhs1 (stmt);
2404   op1 = gimple_assign_rhs2 (stmt);
2405   op2 = gimple_assign_rhs3 (stmt);
2406
2407   if (TREE_CODE (op2) != VECTOR_CST)
2408     return 0;
2409
2410   if (TREE_CODE (op0) == VECTOR_CST)
2411     {
2412       code = VECTOR_CST;
2413       arg0 = op0;
2414     }
2415   else if (TREE_CODE (op0) == SSA_NAME)
2416     {
2417       def_stmt = get_prop_source_stmt (op0, false, &single_use_op0);
2418       if (!def_stmt || !can_propagate_from (def_stmt))
2419         return 0;
2420
2421       code = gimple_assign_rhs_code (def_stmt);
2422       arg0 = gimple_assign_rhs1 (def_stmt);
2423     }
2424   else
2425     return 0;
2426
2427   /* Two consecutive shuffles.  */
2428   if (code == VEC_PERM_EXPR)
2429     {
2430       tree orig;
2431       int ident;
2432
2433       if (op0 != op1)
2434         return 0;
2435       op3 = gimple_assign_rhs3 (def_stmt);
2436       if (TREE_CODE (op3) != VECTOR_CST)
2437         return 0;
2438       ident = is_combined_permutation_identity (op3, op2);
2439       if (!ident)
2440         return 0;
2441       orig = (ident == 1) ? gimple_assign_rhs1 (def_stmt)
2442                           : gimple_assign_rhs2 (def_stmt);
2443       gimple_assign_set_rhs1 (stmt, unshare_expr (orig));
2444       gimple_assign_set_rhs_code (stmt, TREE_CODE (orig));
2445       gimple_set_num_ops (stmt, 2);
2446       update_stmt (stmt);
2447       return remove_prop_source_from_use (op0) ? 2 : 1;
2448     }
2449
2450   /* Shuffle of a constructor.  */
2451   else if (code == CONSTRUCTOR || code == VECTOR_CST)
2452     {
2453       tree opt;
2454       bool ret = false;
2455       if (op0 != op1)
2456         {
2457           if (TREE_CODE (op0) == SSA_NAME && !single_use_op0)
2458             return 0;
2459
2460           if (TREE_CODE (op1) == VECTOR_CST)
2461             arg1 = op1;
2462           else if (TREE_CODE (op1) == SSA_NAME)
2463             {
2464               enum tree_code code2;
2465
2466               gimple def_stmt2 = get_prop_source_stmt (op1, true, NULL);
2467               if (!def_stmt2 || !can_propagate_from (def_stmt2))
2468                 return 0;
2469
2470               code2 = gimple_assign_rhs_code (def_stmt2);
2471               if (code2 != CONSTRUCTOR && code2 != VECTOR_CST)
2472                 return 0;
2473               arg1 = gimple_assign_rhs1 (def_stmt2);
2474             }
2475           else
2476             return 0;
2477         }
2478       else
2479         {
2480           /* Already used twice in this statement.  */
2481           if (TREE_CODE (op0) == SSA_NAME && num_imm_uses (op0) > 2)
2482             return 0;
2483           arg1 = arg0;
2484         }
2485       opt = fold_ternary (VEC_PERM_EXPR, TREE_TYPE (op0), arg0, arg1, op2);
2486       if (!opt
2487           || (TREE_CODE (opt) != CONSTRUCTOR && TREE_CODE (opt) != VECTOR_CST))
2488         return 0;
2489       gimple_assign_set_rhs_from_tree (gsi, opt);
2490       update_stmt (gsi_stmt (*gsi));
2491       if (TREE_CODE (op0) == SSA_NAME)
2492         ret = remove_prop_source_from_use (op0);
2493       if (op0 != op1 && TREE_CODE (op1) == SSA_NAME)
2494         ret |= remove_prop_source_from_use (op1);
2495       return ret ? 2 : 1;
2496     }
2497
2498   return 0;
2499 }
2500
2501 /* Recognize a VEC_PERM_EXPR.  Returns true if there were any changes.  */
2502
2503 static bool
2504 simplify_vector_constructor (gimple_stmt_iterator *gsi)
2505 {
2506   gimple stmt = gsi_stmt (*gsi);
2507   gimple def_stmt;
2508   tree op, op2, orig, type, elem_type;
2509   unsigned elem_size, nelts, i;
2510   enum tree_code code;
2511   constructor_elt *elt;
2512   unsigned char *sel;
2513   bool maybe_ident;
2514
2515   gcc_checking_assert (gimple_assign_rhs_code (stmt) == CONSTRUCTOR);
2516
2517   op = gimple_assign_rhs1 (stmt);
2518   type = TREE_TYPE (op);
2519   gcc_checking_assert (TREE_CODE (type) == VECTOR_TYPE);
2520
2521   nelts = TYPE_VECTOR_SUBPARTS (type);
2522   elem_type = TREE_TYPE (type);
2523   elem_size = TREE_INT_CST_LOW (TYPE_SIZE (elem_type));
2524
2525   sel = XALLOCAVEC (unsigned char, nelts);
2526   orig = NULL;
2527   maybe_ident = true;
2528   FOR_EACH_VEC_SAFE_ELT (CONSTRUCTOR_ELTS (op), i, elt)
2529     {
2530       tree ref, op1;
2531
2532       if (i >= nelts)
2533         return false;
2534
2535       if (TREE_CODE (elt->value) != SSA_NAME)
2536         return false;
2537       def_stmt = get_prop_source_stmt (elt->value, false, NULL);
2538       if (!def_stmt)
2539         return false;
2540       code = gimple_assign_rhs_code (def_stmt);
2541       if (code != BIT_FIELD_REF)
2542         return false;
2543       op1 = gimple_assign_rhs1 (def_stmt);
2544       ref = TREE_OPERAND (op1, 0);
2545       if (orig)
2546         {
2547           if (ref != orig)
2548             return false;
2549         }
2550       else
2551         {
2552           if (TREE_CODE (ref) != SSA_NAME)
2553             return false;
2554           if (!useless_type_conversion_p (type, TREE_TYPE (ref)))
2555             return false;
2556           orig = ref;
2557         }
2558       if (TREE_INT_CST_LOW (TREE_OPERAND (op1, 1)) != elem_size)
2559         return false;
2560       sel[i] = TREE_INT_CST_LOW (TREE_OPERAND (op1, 2)) / elem_size;
2561       if (sel[i] != i) maybe_ident = false;
2562     }
2563   if (i < nelts)
2564     return false;
2565
2566   if (maybe_ident)
2567     gimple_assign_set_rhs_from_tree (gsi, orig);
2568   else
2569     {
2570       tree mask_type, *mask_elts;
2571
2572       if (!can_vec_perm_p (TYPE_MODE (type), false, sel))
2573         return false;
2574       mask_type
2575         = build_vector_type (build_nonstandard_integer_type (elem_size, 1),
2576                              nelts);
2577       if (GET_MODE_CLASS (TYPE_MODE (mask_type)) != MODE_VECTOR_INT
2578           || GET_MODE_SIZE (TYPE_MODE (mask_type))
2579              != GET_MODE_SIZE (TYPE_MODE (type)))
2580         return false;
2581       mask_elts = XALLOCAVEC (tree, nelts);
2582       for (i = 0; i < nelts; i++)
2583         mask_elts[i] = build_int_cst (TREE_TYPE (mask_type), sel[i]);
2584       op2 = build_vector (mask_type, mask_elts);
2585       gimple_assign_set_rhs_with_ops_1 (gsi, VEC_PERM_EXPR, orig, orig, op2);
2586     }
2587   update_stmt (gsi_stmt (*gsi));
2588   return true;
2589 }
2590
2591
2592 /* Primitive "lattice" function for gimple_simplify.  */
2593
2594 static tree
2595 fwprop_ssa_val (tree name)
2596 {
2597   /* First valueize NAME.  */
2598   if (TREE_CODE (name) == SSA_NAME
2599       && SSA_NAME_VERSION (name) < lattice.length ())
2600     {
2601       tree val = lattice[SSA_NAME_VERSION (name)];
2602       if (val)
2603         name = val;
2604     }
2605   /* We continue matching along SSA use-def edges for SSA names
2606      that are not single-use.  Currently there are no patterns
2607      that would cause any issues with that.  */
2608   return name;
2609 }
2610
2611 /* Main entry point for the forward propagation and statement combine
2612    optimizer.  */
2613
2614 namespace {
2615
2616 const pass_data pass_data_forwprop =
2617 {
2618   GIMPLE_PASS, /* type */
2619   "forwprop", /* name */
2620   OPTGROUP_NONE, /* optinfo_flags */
2621   TV_TREE_FORWPROP, /* tv_id */
2622   ( PROP_cfg | PROP_ssa ), /* properties_required */
2623   0, /* properties_provided */
2624   0, /* properties_destroyed */
2625   0, /* todo_flags_start */
2626   TODO_update_ssa, /* todo_flags_finish */
2627 };
2628
2629 class pass_forwprop : public gimple_opt_pass
2630 {
2631 public:
2632   pass_forwprop (gcc::context *ctxt)
2633     : gimple_opt_pass (pass_data_forwprop, ctxt)
2634   {}
2635
2636   /* opt_pass methods: */
2637   opt_pass * clone () { return new pass_forwprop (m_ctxt); }
2638   virtual bool gate (function *) { return flag_tree_forwprop; }
2639   virtual unsigned int execute (function *);
2640
2641 }; // class pass_forwprop
2642
2643 unsigned int
2644 pass_forwprop::execute (function *fun)
2645 {
2646   unsigned int todoflags = 0;
2647
2648   cfg_changed = false;
2649
2650   /* Combine stmts with the stmts defining their operands.  Do that
2651      in an order that guarantees visiting SSA defs before SSA uses.  */
2652   lattice.create (num_ssa_names);
2653   lattice.quick_grow_cleared (num_ssa_names);
2654   int *postorder = XNEWVEC (int, n_basic_blocks_for_fn (fun));
2655   int postorder_num = inverted_post_order_compute (postorder);
2656   to_purge = BITMAP_ALLOC (NULL);
2657   for (int i = 0; i < postorder_num; ++i)
2658     {
2659       gimple_stmt_iterator gsi;
2660       basic_block bb = BASIC_BLOCK_FOR_FN (fun, postorder[i]);
2661
2662       /* Apply forward propagation to all stmts in the basic-block.
2663          Note we update GSI within the loop as necessary.  */
2664       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
2665         {
2666           gimple stmt = gsi_stmt (gsi);
2667           tree lhs, rhs;
2668           enum tree_code code;
2669
2670           if (!is_gimple_assign (stmt))
2671             {
2672               gsi_next (&gsi);
2673               continue;
2674             }
2675
2676           lhs = gimple_assign_lhs (stmt);
2677           rhs = gimple_assign_rhs1 (stmt);
2678           code = gimple_assign_rhs_code (stmt);
2679           if (TREE_CODE (lhs) != SSA_NAME
2680               || has_zero_uses (lhs))
2681             {
2682               gsi_next (&gsi);
2683               continue;
2684             }
2685
2686           /* If this statement sets an SSA_NAME to an address,
2687              try to propagate the address into the uses of the SSA_NAME.  */
2688           if (code == ADDR_EXPR
2689               /* Handle pointer conversions on invariant addresses
2690                  as well, as this is valid gimple.  */
2691               || (CONVERT_EXPR_CODE_P (code)
2692                   && TREE_CODE (rhs) == ADDR_EXPR
2693                   && POINTER_TYPE_P (TREE_TYPE (lhs))))
2694             {
2695               tree base = get_base_address (TREE_OPERAND (rhs, 0));
2696               if ((!base
2697                    || !DECL_P (base)
2698                    || decl_address_invariant_p (base))
2699                   && !stmt_references_abnormal_ssa_name (stmt)
2700                   && forward_propagate_addr_expr (lhs, rhs, true))
2701                 {
2702                   fwprop_invalidate_lattice (gimple_get_lhs (stmt));
2703                   release_defs (stmt);
2704                   gsi_remove (&gsi, true);
2705                 }
2706               else
2707                 gsi_next (&gsi);
2708             }
2709           else if (code == POINTER_PLUS_EXPR)
2710             {
2711               tree off = gimple_assign_rhs2 (stmt);
2712               if (TREE_CODE (off) == INTEGER_CST
2713                   && can_propagate_from (stmt)
2714                   && !simple_iv_increment_p (stmt)
2715                   /* ???  Better adjust the interface to that function
2716                      instead of building new trees here.  */
2717                   && forward_propagate_addr_expr
2718                        (lhs,
2719                         build1_loc (gimple_location (stmt),
2720                                     ADDR_EXPR, TREE_TYPE (rhs),
2721                                     fold_build2 (MEM_REF,
2722                                                  TREE_TYPE (TREE_TYPE (rhs)),
2723                                                  rhs,
2724                                                  fold_convert (ptr_type_node,
2725                                                                off))), true))
2726                 {
2727                   fwprop_invalidate_lattice (gimple_get_lhs (stmt));
2728                   release_defs (stmt);
2729                   gsi_remove (&gsi, true);
2730                 }
2731               else if (is_gimple_min_invariant (rhs))
2732                 {
2733                   /* Make sure to fold &a[0] + off_1 here.  */
2734                   fold_stmt_inplace (&gsi);
2735                   update_stmt (stmt);
2736                   if (gimple_assign_rhs_code (stmt) == POINTER_PLUS_EXPR)
2737                     gsi_next (&gsi);
2738                 }
2739               else
2740                 gsi_next (&gsi);
2741             }
2742           else if (TREE_CODE_CLASS (code) == tcc_comparison)
2743             {
2744               if (forward_propagate_comparison (&gsi))
2745                 cfg_changed = true;
2746             }
2747           else
2748             gsi_next (&gsi);
2749         }
2750
2751       /* Combine stmts with the stmts defining their operands.
2752          Note we update GSI within the loop as necessary.  */
2753       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi);)
2754         {
2755           gimple stmt = gsi_stmt (gsi);
2756           gimple orig_stmt = stmt;
2757           bool changed = false;
2758
2759           /* Mark stmt as potentially needing revisiting.  */
2760           gimple_set_plf (stmt, GF_PLF_1, false);
2761
2762           if (fold_stmt (&gsi, fwprop_ssa_val))
2763             {
2764               changed = true;
2765               stmt = gsi_stmt (gsi);
2766               if (maybe_clean_or_replace_eh_stmt (orig_stmt, stmt))
2767                 bitmap_set_bit (to_purge, bb->index);
2768               /* Cleanup the CFG if we simplified a condition to
2769                  true or false.  */
2770               if (gimple_code (stmt) == GIMPLE_COND
2771                   && (gimple_cond_true_p (stmt)
2772                       || gimple_cond_false_p (stmt)))
2773                 cfg_changed = true;
2774               update_stmt (stmt);
2775             }
2776
2777           switch (gimple_code (stmt))
2778             {
2779             case GIMPLE_ASSIGN:
2780               {
2781                 tree rhs1 = gimple_assign_rhs1 (stmt);
2782                 enum tree_code code = gimple_assign_rhs_code (stmt);
2783
2784                 if (code == COND_EXPR
2785                     || code == VEC_COND_EXPR)
2786                   {
2787                     /* In this case the entire COND_EXPR is in rhs1. */
2788                     if (forward_propagate_into_cond (&gsi)
2789                         || combine_cond_exprs (&gsi))
2790                       {
2791                         changed = true;
2792                         stmt = gsi_stmt (gsi);
2793                       }
2794                   }
2795                 else if (TREE_CODE_CLASS (code) == tcc_comparison)
2796                   {
2797                     int did_something;
2798                     did_something = forward_propagate_into_comparison (&gsi);
2799                     if (did_something == 2)
2800                       cfg_changed = true;
2801                     changed = did_something != 0;
2802                   }
2803                 else if ((code == PLUS_EXPR
2804                           || code == BIT_IOR_EXPR
2805                           || code == BIT_XOR_EXPR)
2806                          && simplify_rotate (&gsi))
2807                   changed = true;
2808                 else if (code == PLUS_EXPR
2809                          || code == MINUS_EXPR)
2810                   {
2811                     changed = associate_plusminus (&gsi);
2812                     if (changed
2813                         && maybe_clean_or_replace_eh_stmt (stmt, stmt))
2814                       bitmap_set_bit (to_purge, bb->index);
2815                   }
2816                 else if (code == VEC_PERM_EXPR)
2817                   {
2818                     int did_something = simplify_permutation (&gsi);
2819                     if (did_something == 2)
2820                       cfg_changed = true;
2821                     changed = did_something != 0;
2822                   }
2823                 else if (code == BIT_FIELD_REF)
2824                   changed = simplify_bitfield_ref (&gsi);
2825                 else if (code == CONSTRUCTOR
2826                          && TREE_CODE (TREE_TYPE (rhs1)) == VECTOR_TYPE)
2827                   changed = simplify_vector_constructor (&gsi);
2828                 break;
2829               }
2830
2831             case GIMPLE_SWITCH:
2832               changed = simplify_gimple_switch (stmt);
2833               break;
2834
2835             case GIMPLE_COND:
2836               {
2837                 int did_something;
2838                 did_something = forward_propagate_into_gimple_cond (stmt);
2839                 if (did_something == 2)
2840                   cfg_changed = true;
2841                 changed = did_something != 0;
2842                 break;
2843               }
2844
2845             case GIMPLE_CALL:
2846               {
2847                 tree callee = gimple_call_fndecl (stmt);
2848                 if (callee != NULL_TREE
2849                     && DECL_BUILT_IN_CLASS (callee) == BUILT_IN_NORMAL)
2850                   changed = simplify_builtin_call (&gsi, callee);
2851                 break;
2852               }
2853
2854             default:;
2855             }
2856
2857           if (changed)
2858             {
2859               /* If the stmt changed then re-visit it and the statements
2860                  inserted before it.  */
2861               for (; !gsi_end_p (gsi); gsi_prev (&gsi))
2862                 if (gimple_plf (gsi_stmt (gsi), GF_PLF_1))
2863                   break;
2864               if (gsi_end_p (gsi))
2865                 gsi = gsi_start_bb (bb);
2866               else
2867                 gsi_next (&gsi);
2868             }
2869           else
2870             {
2871               /* Stmt no longer needs to be revisited.  */
2872               gimple_set_plf (stmt, GF_PLF_1, true);
2873
2874               /* Fill up the lattice.  */
2875               if (gimple_assign_single_p (stmt))
2876                 {
2877                   tree lhs = gimple_assign_lhs (stmt);
2878                   tree rhs = gimple_assign_rhs1 (stmt);
2879                   if (TREE_CODE (lhs) == SSA_NAME)
2880                     {
2881                       tree val = lhs;
2882                       if (TREE_CODE (rhs) == SSA_NAME)
2883                         val = fwprop_ssa_val (rhs);
2884                       else if (is_gimple_min_invariant (rhs))
2885                         val = rhs;
2886                       fwprop_set_lattice_val (lhs, val);
2887                     }
2888                 }
2889
2890               gsi_next (&gsi);
2891             }
2892         }
2893     }
2894   free (postorder);
2895   lattice.release ();
2896
2897   cfg_changed |= gimple_purge_all_dead_eh_edges (to_purge);
2898   BITMAP_FREE (to_purge);
2899
2900   if (cfg_changed)
2901     todoflags |= TODO_cleanup_cfg;
2902
2903   return todoflags;
2904 }
2905
2906 } // anon namespace
2907
2908 gimple_opt_pass *
2909 make_pass_forwprop (gcc::context *ctxt)
2910 {
2911   return new pass_forwprop (ctxt);
2912 }