re PR middle-end/58742 (pointer arithmetic simplification)
[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 "basic-block.h"
28 #include "gimple-pretty-print.h"
29 #include "tree-ssa-alias.h"
30 #include "internal-fn.h"
31 #include "gimple-fold.h"
32 #include "tree-eh.h"
33 #include "gimple-expr.h"
34 #include "is-a.h"
35 #include "gimple.h"
36 #include "gimplify.h"
37 #include "gimple-iterator.h"
38 #include "gimplify-me.h"
39 #include "gimple-ssa.h"
40 #include "tree-cfg.h"
41 #include "tree-phinodes.h"
42 #include "ssa-iterators.h"
43 #include "stringpool.h"
44 #include "tree-ssanames.h"
45 #include "expr.h"
46 #include "tree-dfa.h"
47 #include "tree-pass.h"
48 #include "langhooks.h"
49 #include "flags.h"
50 #include "expr.h"
51 #include "cfgloop.h"
52 #include "optabs.h"
53 #include "tree-ssa-propagate.h"
54 #include "tree-ssa-dom.h"
55
56 /* This pass propagates the RHS of assignment statements into use
57    sites of the LHS of the assignment.  It's basically a specialized
58    form of tree combination.   It is hoped all of this can disappear
59    when we have a generalized tree combiner.
60
61    One class of common cases we handle is forward propagating a single use
62    variable into a COND_EXPR.
63
64      bb0:
65        x = a COND b;
66        if (x) goto ... else goto ...
67
68    Will be transformed into:
69
70      bb0:
71        if (a COND b) goto ... else goto ...
72
73    Similarly for the tests (x == 0), (x != 0), (x == 1) and (x != 1).
74
75    Or (assuming c1 and c2 are constants):
76
77      bb0:
78        x = a + c1;
79        if (x EQ/NEQ c2) goto ... else goto ...
80
81    Will be transformed into:
82
83      bb0:
84         if (a EQ/NEQ (c2 - c1)) goto ... else goto ...
85
86    Similarly for x = a - c1.
87
88    Or
89
90      bb0:
91        x = !a
92        if (x) goto ... else goto ...
93
94    Will be transformed into:
95
96      bb0:
97         if (a == 0) goto ... else goto ...
98
99    Similarly for the tests (x == 0), (x != 0), (x == 1) and (x != 1).
100    For these cases, we propagate A into all, possibly more than one,
101    COND_EXPRs that use X.
102
103    Or
104
105      bb0:
106        x = (typecast) a
107        if (x) goto ... else goto ...
108
109    Will be transformed into:
110
111      bb0:
112         if (a != 0) goto ... else goto ...
113
114    (Assuming a is an integral type and x is a boolean or x is an
115     integral and a is a boolean.)
116
117    Similarly for the tests (x == 0), (x != 0), (x == 1) and (x != 1).
118    For these cases, we propagate A into all, possibly more than one,
119    COND_EXPRs that use X.
120
121    In addition to eliminating the variable and the statement which assigns
122    a value to the variable, we may be able to later thread the jump without
123    adding insane complexity in the dominator optimizer.
124
125    Also note these transformations can cascade.  We handle this by having
126    a worklist of COND_EXPR statements to examine.  As we make a change to
127    a statement, we put it back on the worklist to examine on the next
128    iteration of the main loop.
129
130    A second class of propagation opportunities arises for ADDR_EXPR
131    nodes.
132
133      ptr = &x->y->z;
134      res = *ptr;
135
136    Will get turned into
137
138      res = x->y->z;
139
140    Or
141      ptr = (type1*)&type2var;
142      res = *ptr
143
144    Will get turned into (if type1 and type2 are the same size
145    and neither have volatile on them):
146      res = VIEW_CONVERT_EXPR<type1>(type2var)
147
148    Or
149
150      ptr = &x[0];
151      ptr2 = ptr + <constant>;
152
153    Will get turned into
154
155      ptr2 = &x[constant/elementsize];
156
157   Or
158
159      ptr = &x[0];
160      offset = index * element_size;
161      offset_p = (pointer) offset;
162      ptr2 = ptr + offset_p
163
164   Will get turned into:
165
166      ptr2 = &x[index];
167
168   Or
169     ssa = (int) decl
170     res = ssa & 1
171
172   Provided that decl has known alignment >= 2, will get turned into
173
174     res = 0
175
176   We also propagate casts into SWITCH_EXPR and COND_EXPR conditions to
177   allow us to remove the cast and {NOT_EXPR,NEG_EXPR} into a subsequent
178   {NOT_EXPR,NEG_EXPR}.
179
180    This will (of course) be extended as other needs arise.  */
181
182 static bool forward_propagate_addr_expr (tree, tree, bool);
183
184 /* Set to true if we delete dead edges during the optimization.  */
185 static bool cfg_changed;
186
187 static tree rhs_to_tree (tree type, gimple stmt);
188
189 /* Get the next statement we can propagate NAME's value into skipping
190    trivial copies.  Returns the statement that is suitable as a
191    propagation destination or NULL_TREE if there is no such one.
192    This only returns destinations in a single-use chain.  FINAL_NAME_P
193    if non-NULL is written to the ssa name that represents the use.  */
194
195 static gimple
196 get_prop_dest_stmt (tree name, tree *final_name_p)
197 {
198   use_operand_p use;
199   gimple use_stmt;
200
201   do {
202     /* If name has multiple uses, bail out.  */
203     if (!single_imm_use (name, &use, &use_stmt))
204       return NULL;
205
206     /* If this is not a trivial copy, we found it.  */
207     if (!gimple_assign_ssa_name_copy_p (use_stmt)
208         || gimple_assign_rhs1 (use_stmt) != name)
209       break;
210
211     /* Continue searching uses of the copy destination.  */
212     name = gimple_assign_lhs (use_stmt);
213   } while (1);
214
215   if (final_name_p)
216     *final_name_p = name;
217
218   return use_stmt;
219 }
220
221 /* Get the statement we can propagate from into NAME skipping
222    trivial copies.  Returns the statement which defines the
223    propagation source or NULL_TREE if there is no such one.
224    If SINGLE_USE_ONLY is set considers only sources which have
225    a single use chain up to NAME.  If SINGLE_USE_P is non-null,
226    it is set to whether the chain to NAME is a single use chain
227    or not.  SINGLE_USE_P is not written to if SINGLE_USE_ONLY is set.  */
228
229 static gimple
230 get_prop_source_stmt (tree name, bool single_use_only, bool *single_use_p)
231 {
232   bool single_use = true;
233
234   do {
235     gimple def_stmt = SSA_NAME_DEF_STMT (name);
236
237     if (!has_single_use (name))
238       {
239         single_use = false;
240         if (single_use_only)
241           return NULL;
242       }
243
244     /* If name is defined by a PHI node or is the default def, bail out.  */
245     if (!is_gimple_assign (def_stmt))
246       return NULL;
247
248     /* If def_stmt is a simple copy, continue looking.  */
249     if (gimple_assign_rhs_code (def_stmt) == SSA_NAME)
250       name = gimple_assign_rhs1 (def_stmt);
251     else
252       {
253         if (!single_use_only && single_use_p)
254           *single_use_p = single_use;
255
256         return def_stmt;
257       }
258   } while (1);
259 }
260
261 /* Checks if the destination ssa name in DEF_STMT can be used as
262    propagation source.  Returns true if so, otherwise false.  */
263
264 static bool
265 can_propagate_from (gimple def_stmt)
266 {
267   gcc_assert (is_gimple_assign (def_stmt));
268
269   /* If the rhs has side-effects we cannot propagate from it.  */
270   if (gimple_has_volatile_ops (def_stmt))
271     return false;
272
273   /* If the rhs is a load we cannot propagate from it.  */
274   if (TREE_CODE_CLASS (gimple_assign_rhs_code (def_stmt)) == tcc_reference
275       || TREE_CODE_CLASS (gimple_assign_rhs_code (def_stmt)) == tcc_declaration)
276     return false;
277
278   /* Constants can be always propagated.  */
279   if (gimple_assign_single_p (def_stmt)
280       && is_gimple_min_invariant (gimple_assign_rhs1 (def_stmt)))
281     return true;
282
283   /* We cannot propagate ssa names that occur in abnormal phi nodes.  */
284   if (stmt_references_abnormal_ssa_name (def_stmt))
285     return false;
286
287   /* If the definition is a conversion of a pointer to a function type,
288      then we can not apply optimizations as some targets require
289      function pointers to be canonicalized and in this case this
290      optimization could eliminate a necessary canonicalization.  */
291   if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
292     {
293       tree rhs = gimple_assign_rhs1 (def_stmt);
294       if (POINTER_TYPE_P (TREE_TYPE (rhs))
295           && TREE_CODE (TREE_TYPE (TREE_TYPE (rhs))) == FUNCTION_TYPE)
296         return false;
297     }
298
299   return true;
300 }
301
302 /* Remove a chain of dead statements starting at the definition of
303    NAME.  The chain is linked via the first operand of the defining statements.
304    If NAME was replaced in its only use then this function can be used
305    to clean up dead stmts.  The function handles already released SSA
306    names gracefully.
307    Returns true if cleanup-cfg has to run.  */
308
309 static bool
310 remove_prop_source_from_use (tree name)
311 {
312   gimple_stmt_iterator gsi;
313   gimple stmt;
314   bool cfg_changed = false;
315
316   do {
317     basic_block bb;
318
319     if (SSA_NAME_IN_FREE_LIST (name)
320         || SSA_NAME_IS_DEFAULT_DEF (name)
321         || !has_zero_uses (name))
322       return cfg_changed;
323
324     stmt = SSA_NAME_DEF_STMT (name);
325     if (gimple_code (stmt) == GIMPLE_PHI
326         || gimple_has_side_effects (stmt))
327       return cfg_changed;
328
329     bb = gimple_bb (stmt);
330     gsi = gsi_for_stmt (stmt);
331     unlink_stmt_vdef (stmt);
332     if (gsi_remove (&gsi, true))
333       cfg_changed |= gimple_purge_dead_eh_edges (bb);
334     release_defs (stmt);
335
336     name = is_gimple_assign (stmt) ? gimple_assign_rhs1 (stmt) : NULL_TREE;
337   } while (name && TREE_CODE (name) == SSA_NAME);
338
339   return cfg_changed;
340 }
341
342 /* Return the rhs of a gimple_assign STMT in a form of a single tree,
343    converted to type TYPE.
344
345    This should disappear, but is needed so we can combine expressions and use
346    the fold() interfaces. Long term, we need to develop folding and combine
347    routines that deal with gimple exclusively . */
348
349 static tree
350 rhs_to_tree (tree type, gimple stmt)
351 {
352   location_t loc = gimple_location (stmt);
353   enum tree_code code = gimple_assign_rhs_code (stmt);
354   if (get_gimple_rhs_class (code) == GIMPLE_TERNARY_RHS)
355     return fold_build3_loc (loc, code, type, gimple_assign_rhs1 (stmt),
356                             gimple_assign_rhs2 (stmt),
357                             gimple_assign_rhs3 (stmt));
358   else if (get_gimple_rhs_class (code) == GIMPLE_BINARY_RHS)
359     return fold_build2_loc (loc, code, type, gimple_assign_rhs1 (stmt),
360                         gimple_assign_rhs2 (stmt));
361   else if (get_gimple_rhs_class (code) == GIMPLE_UNARY_RHS)
362     return build1 (code, type, gimple_assign_rhs1 (stmt));
363   else if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
364     return gimple_assign_rhs1 (stmt);
365   else
366     gcc_unreachable ();
367 }
368
369 /* Combine OP0 CODE OP1 in the context of a COND_EXPR.  Returns
370    the folded result in a form suitable for COND_EXPR_COND or
371    NULL_TREE, if there is no suitable simplified form.  If
372    INVARIANT_ONLY is true only gimple_min_invariant results are
373    considered simplified.  */
374
375 static tree
376 combine_cond_expr_cond (gimple stmt, enum tree_code code, tree type,
377                         tree op0, tree op1, bool invariant_only)
378 {
379   tree t;
380
381   gcc_assert (TREE_CODE_CLASS (code) == tcc_comparison);
382
383   fold_defer_overflow_warnings ();
384   t = fold_binary_loc (gimple_location (stmt), code, type, op0, op1);
385   if (!t)
386     {
387       fold_undefer_overflow_warnings (false, NULL, 0);
388       return NULL_TREE;
389     }
390
391   /* Require that we got a boolean type out if we put one in.  */
392   gcc_assert (TREE_CODE (TREE_TYPE (t)) == TREE_CODE (type));
393
394   /* Canonicalize the combined condition for use in a COND_EXPR.  */
395   t = canonicalize_cond_expr_cond (t);
396
397   /* Bail out if we required an invariant but didn't get one.  */
398   if (!t || (invariant_only && !is_gimple_min_invariant (t)))
399     {
400       fold_undefer_overflow_warnings (false, NULL, 0);
401       return NULL_TREE;
402     }
403
404   fold_undefer_overflow_warnings (!gimple_no_warning_p (stmt), stmt, 0);
405
406   return t;
407 }
408
409 /* Combine the comparison OP0 CODE OP1 at LOC with the defining statements
410    of its operand.  Return a new comparison tree or NULL_TREE if there
411    were no simplifying combines.  */
412
413 static tree
414 forward_propagate_into_comparison_1 (gimple stmt,
415                                      enum tree_code code, tree type,
416                                      tree op0, tree op1)
417 {
418   tree tmp = NULL_TREE;
419   tree rhs0 = NULL_TREE, rhs1 = NULL_TREE;
420   bool single_use0_p = false, single_use1_p = false;
421
422   /* For comparisons use the first operand, that is likely to
423      simplify comparisons against constants.  */
424   if (TREE_CODE (op0) == SSA_NAME)
425     {
426       gimple def_stmt = get_prop_source_stmt (op0, false, &single_use0_p);
427       if (def_stmt && can_propagate_from (def_stmt))
428         {
429           rhs0 = rhs_to_tree (TREE_TYPE (op1), def_stmt);
430           tmp = combine_cond_expr_cond (stmt, code, type,
431                                         rhs0, op1, !single_use0_p);
432           if (tmp)
433             return tmp;
434         }
435     }
436
437   /* If that wasn't successful, try the second operand.  */
438   if (TREE_CODE (op1) == SSA_NAME)
439     {
440       gimple def_stmt = get_prop_source_stmt (op1, false, &single_use1_p);
441       if (def_stmt && can_propagate_from (def_stmt))
442         {
443           rhs1 = rhs_to_tree (TREE_TYPE (op0), def_stmt);
444           tmp = combine_cond_expr_cond (stmt, code, type,
445                                         op0, rhs1, !single_use1_p);
446           if (tmp)
447             return tmp;
448         }
449     }
450
451   /* If that wasn't successful either, try both operands.  */
452   if (rhs0 != NULL_TREE
453       && rhs1 != NULL_TREE)
454     tmp = combine_cond_expr_cond (stmt, code, type,
455                                   rhs0, rhs1,
456                                   !(single_use0_p && single_use1_p));
457
458   return tmp;
459 }
460
461 /* Propagate from the ssa name definition statements of the assignment
462    from a comparison at *GSI into the conditional if that simplifies it.
463    Returns 1 if the stmt was modified and 2 if the CFG needs cleanup,
464    otherwise returns 0.  */
465
466 static int 
467 forward_propagate_into_comparison (gimple_stmt_iterator *gsi)
468 {
469   gimple stmt = gsi_stmt (*gsi);
470   tree tmp;
471   bool cfg_changed = false;
472   tree type = TREE_TYPE (gimple_assign_lhs (stmt));
473   tree rhs1 = gimple_assign_rhs1 (stmt);
474   tree rhs2 = gimple_assign_rhs2 (stmt);
475
476   /* Combine the comparison with defining statements.  */
477   tmp = forward_propagate_into_comparison_1 (stmt,
478                                              gimple_assign_rhs_code (stmt),
479                                              type, rhs1, rhs2);
480   if (tmp && useless_type_conversion_p (type, TREE_TYPE (tmp)))
481     {
482       gimple_assign_set_rhs_from_tree (gsi, tmp);
483       fold_stmt (gsi);
484       update_stmt (gsi_stmt (*gsi));
485
486       if (TREE_CODE (rhs1) == SSA_NAME)
487         cfg_changed |= remove_prop_source_from_use (rhs1);
488       if (TREE_CODE (rhs2) == SSA_NAME)
489         cfg_changed |= remove_prop_source_from_use (rhs2);
490       return cfg_changed ? 2 : 1;
491     }
492
493   return 0;
494 }
495
496 /* Propagate from the ssa name definition statements of COND_EXPR
497    in GIMPLE_COND statement STMT into the conditional if that simplifies it.
498    Returns zero if no statement was changed, one if there were
499    changes and two if cfg_cleanup needs to run.
500
501    This must be kept in sync with forward_propagate_into_cond.  */
502
503 static int
504 forward_propagate_into_gimple_cond (gimple stmt)
505 {
506   tree tmp;
507   enum tree_code code = gimple_cond_code (stmt);
508   bool cfg_changed = false;
509   tree rhs1 = gimple_cond_lhs (stmt);
510   tree rhs2 = gimple_cond_rhs (stmt);
511
512   /* We can do tree combining on SSA_NAME and comparison expressions.  */
513   if (TREE_CODE_CLASS (gimple_cond_code (stmt)) != tcc_comparison)
514     return 0;
515
516   tmp = forward_propagate_into_comparison_1 (stmt, code,
517                                              boolean_type_node,
518                                              rhs1, rhs2);
519   if (tmp)
520     {
521       if (dump_file && tmp)
522         {
523           fprintf (dump_file, "  Replaced '");
524           print_gimple_expr (dump_file, stmt, 0, 0);
525           fprintf (dump_file, "' with '");
526           print_generic_expr (dump_file, tmp, 0);
527           fprintf (dump_file, "'\n");
528         }
529
530       gimple_cond_set_condition_from_tree (stmt, unshare_expr (tmp));
531       update_stmt (stmt);
532
533       if (TREE_CODE (rhs1) == SSA_NAME)
534         cfg_changed |= remove_prop_source_from_use (rhs1);
535       if (TREE_CODE (rhs2) == SSA_NAME)
536         cfg_changed |= remove_prop_source_from_use (rhs2);
537       return (cfg_changed || is_gimple_min_invariant (tmp)) ? 2 : 1;
538     }
539
540   /* Canonicalize _Bool == 0 and _Bool != 1 to _Bool != 0 by swapping edges.  */
541   if ((TREE_CODE (TREE_TYPE (rhs1)) == BOOLEAN_TYPE
542        || (INTEGRAL_TYPE_P (TREE_TYPE (rhs1))
543            && TYPE_PRECISION (TREE_TYPE (rhs1)) == 1))
544       && ((code == EQ_EXPR
545            && integer_zerop (rhs2))
546           || (code == NE_EXPR
547               && integer_onep (rhs2))))
548     {
549       basic_block bb = gimple_bb (stmt);
550       gimple_cond_set_code (stmt, NE_EXPR);
551       gimple_cond_set_rhs (stmt, build_zero_cst (TREE_TYPE (rhs1)));
552       EDGE_SUCC (bb, 0)->flags ^= (EDGE_TRUE_VALUE|EDGE_FALSE_VALUE);
553       EDGE_SUCC (bb, 1)->flags ^= (EDGE_TRUE_VALUE|EDGE_FALSE_VALUE);
554       return 1;
555     }
556
557   return 0;
558 }
559
560
561 /* Propagate from the ssa name definition statements of COND_EXPR
562    in the rhs of statement STMT into the conditional if that simplifies it.
563    Returns true zero if the stmt was changed.  */
564
565 static bool
566 forward_propagate_into_cond (gimple_stmt_iterator *gsi_p)
567 {
568   gimple stmt = gsi_stmt (*gsi_p);
569   tree tmp = NULL_TREE;
570   tree cond = gimple_assign_rhs1 (stmt);
571   enum tree_code code = gimple_assign_rhs_code (stmt);
572   bool swap = false;
573
574   /* We can do tree combining on SSA_NAME and comparison expressions.  */
575   if (COMPARISON_CLASS_P (cond))
576     tmp = forward_propagate_into_comparison_1 (stmt, TREE_CODE (cond),
577                                                TREE_TYPE (cond),
578                                                TREE_OPERAND (cond, 0),
579                                                TREE_OPERAND (cond, 1));
580   else if (TREE_CODE (cond) == SSA_NAME)
581     {
582       enum tree_code def_code;
583       tree name = cond;
584       gimple def_stmt = get_prop_source_stmt (name, true, NULL);
585       if (!def_stmt || !can_propagate_from (def_stmt))
586         return 0;
587
588       def_code = gimple_assign_rhs_code (def_stmt);
589       if (TREE_CODE_CLASS (def_code) == tcc_comparison)
590         tmp = fold_build2_loc (gimple_location (def_stmt),
591                                def_code,
592                                TREE_TYPE (cond),
593                                gimple_assign_rhs1 (def_stmt),
594                                gimple_assign_rhs2 (def_stmt));
595       else if (code == COND_EXPR
596                && ((def_code == BIT_NOT_EXPR
597                     && TYPE_PRECISION (TREE_TYPE (cond)) == 1)
598                    || (def_code == BIT_XOR_EXPR
599                        && integer_onep (gimple_assign_rhs2 (def_stmt)))))
600         {
601           tmp = gimple_assign_rhs1 (def_stmt);
602           swap = true;
603         }
604     }
605
606   if (tmp
607       && is_gimple_condexpr (tmp))
608     {
609       if (dump_file && tmp)
610         {
611           fprintf (dump_file, "  Replaced '");
612           print_generic_expr (dump_file, cond, 0);
613           fprintf (dump_file, "' with '");
614           print_generic_expr (dump_file, tmp, 0);
615           fprintf (dump_file, "'\n");
616         }
617
618       if ((code == VEC_COND_EXPR) ? integer_all_onesp (tmp)
619                                   : integer_onep (tmp))
620         gimple_assign_set_rhs_from_tree (gsi_p, gimple_assign_rhs2 (stmt));
621       else if (integer_zerop (tmp))
622         gimple_assign_set_rhs_from_tree (gsi_p, gimple_assign_rhs3 (stmt));
623       else
624         {
625           gimple_assign_set_rhs1 (stmt, unshare_expr (tmp));
626           if (swap)
627             {
628               tree t = gimple_assign_rhs2 (stmt);
629               gimple_assign_set_rhs2 (stmt, gimple_assign_rhs3 (stmt));
630               gimple_assign_set_rhs3 (stmt, t);
631             }
632         }
633       stmt = gsi_stmt (*gsi_p);
634       update_stmt (stmt);
635
636       return true;
637     }
638
639   return 0;
640 }
641
642 /* Propagate from the ssa name definition statements of COND_EXPR
643    values in the rhs of statement STMT into the conditional arms
644    if that simplifies it.
645    Returns true if the stmt was changed.  */
646
647 static bool
648 combine_cond_exprs (gimple_stmt_iterator *gsi_p)
649 {
650   gimple stmt = gsi_stmt (*gsi_p);
651   tree cond, val1, val2;
652   bool changed = false;
653
654   cond = gimple_assign_rhs1 (stmt);
655   val1 = gimple_assign_rhs2 (stmt);
656   if (TREE_CODE (val1) == SSA_NAME)
657     {
658       gimple def_stmt = SSA_NAME_DEF_STMT (val1);
659       if (is_gimple_assign (def_stmt)
660           && gimple_assign_rhs_code (def_stmt) == gimple_assign_rhs_code (stmt)
661           && operand_equal_p (gimple_assign_rhs1 (def_stmt), cond, 0))
662         {
663           val1 = unshare_expr (gimple_assign_rhs2 (def_stmt));
664           gimple_assign_set_rhs2 (stmt, val1);
665           changed = true;
666         }
667     }
668   val2 = gimple_assign_rhs3 (stmt);
669   if (TREE_CODE (val2) == SSA_NAME)
670     {
671       gimple def_stmt = SSA_NAME_DEF_STMT (val2);
672       if (is_gimple_assign (def_stmt)
673           && gimple_assign_rhs_code (def_stmt) == gimple_assign_rhs_code (stmt)
674           && operand_equal_p (gimple_assign_rhs1 (def_stmt), cond, 0))
675         {
676           val2 = unshare_expr (gimple_assign_rhs3 (def_stmt));
677           gimple_assign_set_rhs3 (stmt, val2);
678           changed = true;
679         }
680     }
681   if (operand_equal_p (val1, val2, 0))
682     {
683       gimple_assign_set_rhs_from_tree (gsi_p, val1);
684       stmt = gsi_stmt (*gsi_p);
685       changed = true;
686     }
687
688   if (changed)
689     update_stmt (stmt);
690
691   return changed;
692 }
693
694 /* We've just substituted an ADDR_EXPR into stmt.  Update all the
695    relevant data structures to match.  */
696
697 static void
698 tidy_after_forward_propagate_addr (gimple stmt)
699 {
700   /* We may have turned a trapping insn into a non-trapping insn.  */
701   if (maybe_clean_or_replace_eh_stmt (stmt, stmt)
702       && gimple_purge_dead_eh_edges (gimple_bb (stmt)))
703     cfg_changed = true;
704
705   if (TREE_CODE (gimple_assign_rhs1 (stmt)) == ADDR_EXPR)
706      recompute_tree_invariant_for_addr_expr (gimple_assign_rhs1 (stmt));
707 }
708
709 /* NAME is a SSA_NAME representing DEF_RHS which is of the form
710    ADDR_EXPR <whatever>.
711
712    Try to forward propagate the ADDR_EXPR into the use USE_STMT.
713    Often this will allow for removal of an ADDR_EXPR and INDIRECT_REF
714    node or for recovery of array indexing from pointer arithmetic.
715
716    Return true if the propagation was successful (the propagation can
717    be not totally successful, yet things may have been changed).  */
718
719 static bool
720 forward_propagate_addr_expr_1 (tree name, tree def_rhs,
721                                gimple_stmt_iterator *use_stmt_gsi,
722                                bool single_use_p)
723 {
724   tree lhs, rhs, rhs2, array_ref;
725   gimple use_stmt = gsi_stmt (*use_stmt_gsi);
726   enum tree_code rhs_code;
727   bool res = true;
728
729   gcc_assert (TREE_CODE (def_rhs) == ADDR_EXPR);
730
731   lhs = gimple_assign_lhs (use_stmt);
732   rhs_code = gimple_assign_rhs_code (use_stmt);
733   rhs = gimple_assign_rhs1 (use_stmt);
734
735   /* Do not perform copy-propagation but recurse through copy chains.  */
736   if (TREE_CODE (lhs) == SSA_NAME
737       && rhs_code == SSA_NAME)
738     return forward_propagate_addr_expr (lhs, def_rhs, single_use_p);
739
740   /* The use statement could be a conversion.  Recurse to the uses of the
741      lhs as copyprop does not copy through pointer to integer to pointer
742      conversions and FRE does not catch all cases either.
743      Treat the case of a single-use name and
744      a conversion to def_rhs type separate, though.  */
745   if (TREE_CODE (lhs) == SSA_NAME
746       && CONVERT_EXPR_CODE_P (rhs_code))
747     {
748       /* If there is a point in a conversion chain where the types match
749          so we can remove a conversion re-materialize the address here
750          and stop.  */
751       if (single_use_p
752           && useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (def_rhs)))
753         {
754           gimple_assign_set_rhs1 (use_stmt, unshare_expr (def_rhs));
755           gimple_assign_set_rhs_code (use_stmt, TREE_CODE (def_rhs));
756           return true;
757         }
758
759       /* Else recurse if the conversion preserves the address value.  */
760       if ((INTEGRAL_TYPE_P (TREE_TYPE (lhs))
761            || POINTER_TYPE_P (TREE_TYPE (lhs)))
762           && (TYPE_PRECISION (TREE_TYPE (lhs))
763               >= TYPE_PRECISION (TREE_TYPE (def_rhs))))
764         return forward_propagate_addr_expr (lhs, def_rhs, single_use_p);
765
766       return false;
767     }
768
769   /* If this isn't a conversion chain from this on we only can propagate
770      into compatible pointer contexts.  */
771   if (!types_compatible_p (TREE_TYPE (name), TREE_TYPE (def_rhs)))
772     return false;
773
774   /* Propagate through constant pointer adjustments.  */
775   if (TREE_CODE (lhs) == SSA_NAME
776       && rhs_code == POINTER_PLUS_EXPR
777       && rhs == name
778       && TREE_CODE (gimple_assign_rhs2 (use_stmt)) == INTEGER_CST)
779     {
780       tree new_def_rhs;
781       /* As we come here with non-invariant addresses in def_rhs we need
782          to make sure we can build a valid constant offsetted address
783          for further propagation.  Simply rely on fold building that
784          and check after the fact.  */
785       new_def_rhs = fold_build2 (MEM_REF, TREE_TYPE (TREE_TYPE (rhs)),
786                                  def_rhs,
787                                  fold_convert (ptr_type_node,
788                                                gimple_assign_rhs2 (use_stmt)));
789       if (TREE_CODE (new_def_rhs) == MEM_REF
790           && !is_gimple_mem_ref_addr (TREE_OPERAND (new_def_rhs, 0)))
791         return false;
792       new_def_rhs = build_fold_addr_expr_with_type (new_def_rhs,
793                                                     TREE_TYPE (rhs));
794
795       /* Recurse.  If we could propagate into all uses of lhs do not
796          bother to replace into the current use but just pretend we did.  */
797       if (TREE_CODE (new_def_rhs) == ADDR_EXPR
798           && forward_propagate_addr_expr (lhs, new_def_rhs, single_use_p))
799         return true;
800
801       if (useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (new_def_rhs)))
802         gimple_assign_set_rhs_with_ops (use_stmt_gsi, TREE_CODE (new_def_rhs),
803                                         new_def_rhs, NULL_TREE);
804       else if (is_gimple_min_invariant (new_def_rhs))
805         gimple_assign_set_rhs_with_ops (use_stmt_gsi, NOP_EXPR,
806                                         new_def_rhs, NULL_TREE);
807       else
808         return false;
809       gcc_assert (gsi_stmt (*use_stmt_gsi) == use_stmt);
810       update_stmt (use_stmt);
811       return true;
812     }
813
814   /* Now strip away any outer COMPONENT_REF/ARRAY_REF nodes from the LHS.
815      ADDR_EXPR will not appear on the LHS.  */
816   tree *lhsp = gimple_assign_lhs_ptr (use_stmt);
817   while (handled_component_p (*lhsp))
818     lhsp = &TREE_OPERAND (*lhsp, 0);
819   lhs = *lhsp;
820
821   /* Now see if the LHS node is a MEM_REF using NAME.  If so,
822      propagate the ADDR_EXPR into the use of NAME and fold the result.  */
823   if (TREE_CODE (lhs) == MEM_REF
824       && TREE_OPERAND (lhs, 0) == name)
825     {
826       tree def_rhs_base;
827       HOST_WIDE_INT def_rhs_offset;
828       /* If the address is invariant we can always fold it.  */
829       if ((def_rhs_base = get_addr_base_and_unit_offset (TREE_OPERAND (def_rhs, 0),
830                                                          &def_rhs_offset)))
831         {
832           double_int off = mem_ref_offset (lhs);
833           tree new_ptr;
834           off += double_int::from_shwi (def_rhs_offset);
835           if (TREE_CODE (def_rhs_base) == MEM_REF)
836             {
837               off += mem_ref_offset (def_rhs_base);
838               new_ptr = TREE_OPERAND (def_rhs_base, 0);
839             }
840           else
841             new_ptr = build_fold_addr_expr (def_rhs_base);
842           TREE_OPERAND (lhs, 0) = new_ptr;
843           TREE_OPERAND (lhs, 1)
844             = double_int_to_tree (TREE_TYPE (TREE_OPERAND (lhs, 1)), off);
845           tidy_after_forward_propagate_addr (use_stmt);
846           /* Continue propagating into the RHS if this was not the only use.  */
847           if (single_use_p)
848             return true;
849         }
850       /* If the LHS is a plain dereference and the value type is the same as
851          that of the pointed-to type of the address we can put the
852          dereferenced address on the LHS preserving the original alias-type.  */
853       else if (integer_zerop (TREE_OPERAND (lhs, 1))
854                && ((gimple_assign_lhs (use_stmt) == lhs
855                     && useless_type_conversion_p
856                          (TREE_TYPE (TREE_OPERAND (def_rhs, 0)),
857                           TREE_TYPE (gimple_assign_rhs1 (use_stmt))))
858                    || types_compatible_p (TREE_TYPE (lhs),
859                                           TREE_TYPE (TREE_OPERAND (def_rhs, 0))))
860                /* Don't forward anything into clobber stmts if it would result
861                   in the lhs no longer being a MEM_REF.  */
862                && (!gimple_clobber_p (use_stmt)
863                    || TREE_CODE (TREE_OPERAND (def_rhs, 0)) == MEM_REF))
864         {
865           tree *def_rhs_basep = &TREE_OPERAND (def_rhs, 0);
866           tree new_offset, new_base, saved, new_lhs;
867           while (handled_component_p (*def_rhs_basep))
868             def_rhs_basep = &TREE_OPERAND (*def_rhs_basep, 0);
869           saved = *def_rhs_basep;
870           if (TREE_CODE (*def_rhs_basep) == MEM_REF)
871             {
872               new_base = TREE_OPERAND (*def_rhs_basep, 0);
873               new_offset = fold_convert (TREE_TYPE (TREE_OPERAND (lhs, 1)),
874                                          TREE_OPERAND (*def_rhs_basep, 1));
875             }
876           else
877             {
878               new_base = build_fold_addr_expr (*def_rhs_basep);
879               new_offset = TREE_OPERAND (lhs, 1);
880             }
881           *def_rhs_basep = build2 (MEM_REF, TREE_TYPE (*def_rhs_basep),
882                                    new_base, new_offset);
883           TREE_THIS_VOLATILE (*def_rhs_basep) = TREE_THIS_VOLATILE (lhs);
884           TREE_SIDE_EFFECTS (*def_rhs_basep) = TREE_SIDE_EFFECTS (lhs);
885           TREE_THIS_NOTRAP (*def_rhs_basep) = TREE_THIS_NOTRAP (lhs);
886           new_lhs = unshare_expr (TREE_OPERAND (def_rhs, 0));
887           *lhsp = new_lhs;
888           TREE_THIS_VOLATILE (new_lhs) = TREE_THIS_VOLATILE (lhs);
889           TREE_SIDE_EFFECTS (new_lhs) = TREE_SIDE_EFFECTS (lhs);
890           *def_rhs_basep = saved;
891           tidy_after_forward_propagate_addr (use_stmt);
892           /* Continue propagating into the RHS if this was not the
893              only use.  */
894           if (single_use_p)
895             return true;
896         }
897       else
898         /* We can have a struct assignment dereferencing our name twice.
899            Note that we didn't propagate into the lhs to not falsely
900            claim we did when propagating into the rhs.  */
901         res = false;
902     }
903
904   /* Strip away any outer COMPONENT_REF, ARRAY_REF or ADDR_EXPR
905      nodes from the RHS.  */
906   tree *rhsp = gimple_assign_rhs1_ptr (use_stmt);
907   if (TREE_CODE (*rhsp) == ADDR_EXPR)
908     rhsp = &TREE_OPERAND (*rhsp, 0);
909   while (handled_component_p (*rhsp))
910     rhsp = &TREE_OPERAND (*rhsp, 0);
911   rhs = *rhsp;
912
913   /* Now see if the RHS node is a MEM_REF using NAME.  If so,
914      propagate the ADDR_EXPR into the use of NAME and fold the result.  */
915   if (TREE_CODE (rhs) == MEM_REF
916       && TREE_OPERAND (rhs, 0) == name)
917     {
918       tree def_rhs_base;
919       HOST_WIDE_INT def_rhs_offset;
920       if ((def_rhs_base = get_addr_base_and_unit_offset (TREE_OPERAND (def_rhs, 0),
921                                                          &def_rhs_offset)))
922         {
923           double_int off = mem_ref_offset (rhs);
924           tree new_ptr;
925           off += double_int::from_shwi (def_rhs_offset);
926           if (TREE_CODE (def_rhs_base) == MEM_REF)
927             {
928               off += mem_ref_offset (def_rhs_base);
929               new_ptr = TREE_OPERAND (def_rhs_base, 0);
930             }
931           else
932             new_ptr = build_fold_addr_expr (def_rhs_base);
933           TREE_OPERAND (rhs, 0) = new_ptr;
934           TREE_OPERAND (rhs, 1)
935             = double_int_to_tree (TREE_TYPE (TREE_OPERAND (rhs, 1)), off);
936           fold_stmt_inplace (use_stmt_gsi);
937           tidy_after_forward_propagate_addr (use_stmt);
938           return res;
939         }
940       /* If the RHS is a plain dereference and the value type is the same as
941          that of the pointed-to type of the address we can put the
942          dereferenced address on the RHS preserving the original alias-type.  */
943       else if (integer_zerop (TREE_OPERAND (rhs, 1))
944                && ((gimple_assign_rhs1 (use_stmt) == rhs
945                     && useless_type_conversion_p
946                          (TREE_TYPE (gimple_assign_lhs (use_stmt)),
947                           TREE_TYPE (TREE_OPERAND (def_rhs, 0))))
948                    || types_compatible_p (TREE_TYPE (rhs),
949                                           TREE_TYPE (TREE_OPERAND (def_rhs, 0)))))
950         {
951           tree *def_rhs_basep = &TREE_OPERAND (def_rhs, 0);
952           tree new_offset, new_base, saved, new_rhs;
953           while (handled_component_p (*def_rhs_basep))
954             def_rhs_basep = &TREE_OPERAND (*def_rhs_basep, 0);
955           saved = *def_rhs_basep;
956           if (TREE_CODE (*def_rhs_basep) == MEM_REF)
957             {
958               new_base = TREE_OPERAND (*def_rhs_basep, 0);
959               new_offset = fold_convert (TREE_TYPE (TREE_OPERAND (rhs, 1)),
960                                          TREE_OPERAND (*def_rhs_basep, 1));
961             }
962           else
963             {
964               new_base = build_fold_addr_expr (*def_rhs_basep);
965               new_offset = TREE_OPERAND (rhs, 1);
966             }
967           *def_rhs_basep = build2 (MEM_REF, TREE_TYPE (*def_rhs_basep),
968                                    new_base, new_offset);
969           TREE_THIS_VOLATILE (*def_rhs_basep) = TREE_THIS_VOLATILE (rhs);
970           TREE_SIDE_EFFECTS (*def_rhs_basep) = TREE_SIDE_EFFECTS (rhs);
971           TREE_THIS_NOTRAP (*def_rhs_basep) = TREE_THIS_NOTRAP (rhs);
972           new_rhs = unshare_expr (TREE_OPERAND (def_rhs, 0));
973           *rhsp = new_rhs;
974           TREE_THIS_VOLATILE (new_rhs) = TREE_THIS_VOLATILE (rhs);
975           TREE_SIDE_EFFECTS (new_rhs) = TREE_SIDE_EFFECTS (rhs);
976           *def_rhs_basep = saved;
977           fold_stmt_inplace (use_stmt_gsi);
978           tidy_after_forward_propagate_addr (use_stmt);
979           return res;
980         }
981     }
982
983   /* If the use of the ADDR_EXPR is not a POINTER_PLUS_EXPR, there
984      is nothing to do. */
985   if (gimple_assign_rhs_code (use_stmt) != POINTER_PLUS_EXPR
986       || gimple_assign_rhs1 (use_stmt) != name)
987     return false;
988
989   /* The remaining cases are all for turning pointer arithmetic into
990      array indexing.  They only apply when we have the address of
991      element zero in an array.  If that is not the case then there
992      is nothing to do.  */
993   array_ref = TREE_OPERAND (def_rhs, 0);
994   if ((TREE_CODE (array_ref) != ARRAY_REF
995        || TREE_CODE (TREE_TYPE (TREE_OPERAND (array_ref, 0))) != ARRAY_TYPE
996        || TREE_CODE (TREE_OPERAND (array_ref, 1)) != INTEGER_CST)
997       && TREE_CODE (TREE_TYPE (array_ref)) != ARRAY_TYPE)
998     return false;
999
1000   rhs2 = gimple_assign_rhs2 (use_stmt);
1001   /* Optimize &x[C1] p+ C2 to  &x p+ C3 with C3 = C1 * element_size + C2.  */
1002   if (TREE_CODE (rhs2) == INTEGER_CST)
1003     {
1004       tree new_rhs = build1_loc (gimple_location (use_stmt),
1005                                  ADDR_EXPR, TREE_TYPE (def_rhs),
1006                                  fold_build2 (MEM_REF,
1007                                               TREE_TYPE (TREE_TYPE (def_rhs)),
1008                                               unshare_expr (def_rhs),
1009                                               fold_convert (ptr_type_node,
1010                                                             rhs2)));
1011       gimple_assign_set_rhs_from_tree (use_stmt_gsi, new_rhs);
1012       use_stmt = gsi_stmt (*use_stmt_gsi);
1013       update_stmt (use_stmt);
1014       tidy_after_forward_propagate_addr (use_stmt);
1015       return true;
1016     }
1017
1018   return false;
1019 }
1020
1021 /* STMT is a statement of the form SSA_NAME = ADDR_EXPR <whatever>.
1022
1023    Try to forward propagate the ADDR_EXPR into all uses of the SSA_NAME.
1024    Often this will allow for removal of an ADDR_EXPR and INDIRECT_REF
1025    node or for recovery of array indexing from pointer arithmetic.
1026
1027    PARENT_SINGLE_USE_P tells if, when in a recursive invocation, NAME was
1028    the single use in the previous invocation.  Pass true when calling
1029    this as toplevel.
1030
1031    Returns true, if all uses have been propagated into.  */
1032
1033 static bool
1034 forward_propagate_addr_expr (tree name, tree rhs, bool parent_single_use_p)
1035 {
1036   imm_use_iterator iter;
1037   gimple use_stmt;
1038   bool all = true;
1039   bool single_use_p = parent_single_use_p && has_single_use (name);
1040
1041   FOR_EACH_IMM_USE_STMT (use_stmt, iter, name)
1042     {
1043       bool result;
1044       tree use_rhs;
1045
1046       /* If the use is not in a simple assignment statement, then
1047          there is nothing we can do.  */
1048       if (!is_gimple_assign (use_stmt))
1049         {
1050           if (!is_gimple_debug (use_stmt))
1051             all = false;
1052           continue;
1053         }
1054
1055       gimple_stmt_iterator gsi = gsi_for_stmt (use_stmt);
1056       result = forward_propagate_addr_expr_1 (name, rhs, &gsi,
1057                                               single_use_p);
1058       /* If the use has moved to a different statement adjust
1059          the update machinery for the old statement too.  */
1060       if (use_stmt != gsi_stmt (gsi))
1061         {
1062           update_stmt (use_stmt);
1063           use_stmt = gsi_stmt (gsi);
1064         }
1065       update_stmt (use_stmt);
1066       all &= result;
1067
1068       /* Remove intermediate now unused copy and conversion chains.  */
1069       use_rhs = gimple_assign_rhs1 (use_stmt);
1070       if (result
1071           && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
1072           && TREE_CODE (use_rhs) == SSA_NAME
1073           && has_zero_uses (gimple_assign_lhs (use_stmt)))
1074         {
1075           gimple_stmt_iterator gsi = gsi_for_stmt (use_stmt);
1076           release_defs (use_stmt);
1077           gsi_remove (&gsi, true);
1078         }
1079     }
1080
1081   return all && has_zero_uses (name);
1082 }
1083
1084
1085 /* Forward propagate the comparison defined in *DEFGSI like
1086    cond_1 = x CMP y to uses of the form
1087      a_1 = (T')cond_1
1088      a_1 = !cond_1
1089      a_1 = cond_1 != 0
1090    Returns true if stmt is now unused.  Advance DEFGSI to the next
1091    statement.  */
1092
1093 static bool
1094 forward_propagate_comparison (gimple_stmt_iterator *defgsi)
1095 {
1096   gimple stmt = gsi_stmt (*defgsi);
1097   tree name = gimple_assign_lhs (stmt);
1098   gimple use_stmt;
1099   tree tmp = NULL_TREE;
1100   gimple_stmt_iterator gsi;
1101   enum tree_code code;
1102   tree lhs;
1103
1104   /* Don't propagate ssa names that occur in abnormal phis.  */
1105   if ((TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME
1106        && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (gimple_assign_rhs1 (stmt)))
1107       || (TREE_CODE (gimple_assign_rhs2 (stmt)) == SSA_NAME
1108         && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (gimple_assign_rhs2 (stmt))))
1109     goto bailout;
1110
1111   /* Do not un-cse comparisons.  But propagate through copies.  */
1112   use_stmt = get_prop_dest_stmt (name, &name);
1113   if (!use_stmt
1114       || !is_gimple_assign (use_stmt))
1115     goto bailout;
1116
1117   code = gimple_assign_rhs_code (use_stmt);
1118   lhs = gimple_assign_lhs (use_stmt);
1119   if (!INTEGRAL_TYPE_P (TREE_TYPE (lhs)))
1120     goto bailout;
1121
1122   /* We can propagate the condition into a statement that
1123      computes the logical negation of the comparison result.  */
1124   if ((code == BIT_NOT_EXPR
1125        && TYPE_PRECISION (TREE_TYPE (lhs)) == 1)
1126       || (code == BIT_XOR_EXPR
1127           && integer_onep (gimple_assign_rhs2 (use_stmt))))
1128     {
1129       tree type = TREE_TYPE (gimple_assign_rhs1 (stmt));
1130       bool nans = HONOR_NANS (TYPE_MODE (type));
1131       enum tree_code inv_code;
1132       inv_code = invert_tree_comparison (gimple_assign_rhs_code (stmt), nans);
1133       if (inv_code == ERROR_MARK)
1134         goto bailout;
1135
1136       tmp = build2 (inv_code, TREE_TYPE (lhs), gimple_assign_rhs1 (stmt),
1137                     gimple_assign_rhs2 (stmt));
1138     }
1139   else
1140     goto bailout;
1141
1142   gsi = gsi_for_stmt (use_stmt);
1143   gimple_assign_set_rhs_from_tree (&gsi, unshare_expr (tmp));
1144   use_stmt = gsi_stmt (gsi);
1145   update_stmt (use_stmt);
1146
1147   if (dump_file && (dump_flags & TDF_DETAILS))
1148     {
1149       fprintf (dump_file, "  Replaced '");
1150       print_gimple_expr (dump_file, stmt, 0, dump_flags);
1151       fprintf (dump_file, "' with '");
1152       print_gimple_expr (dump_file, use_stmt, 0, dump_flags);
1153       fprintf (dump_file, "'\n");
1154     }
1155
1156   /* When we remove stmt now the iterator defgsi goes off it's current
1157      sequence, hence advance it now.  */
1158   gsi_next (defgsi);
1159
1160   /* Remove defining statements.  */
1161   return remove_prop_source_from_use (name);
1162
1163 bailout:
1164   gsi_next (defgsi);
1165   return false;
1166 }
1167
1168
1169 /* GSI_P points to a statement which performs a narrowing integral
1170    conversion.
1171
1172    Look for cases like:
1173
1174      t = x & c;
1175      y = (T) t;
1176
1177    Turn them into:
1178
1179      t = x & c;
1180      y = (T) x;
1181
1182    If T is narrower than X's type and C merely masks off bits outside
1183    of (T) and nothing else.
1184
1185    Normally we'd let DCE remove the dead statement.  But no DCE runs
1186    after the last forwprop/combine pass, so we remove the obviously
1187    dead code ourselves.
1188
1189    Return TRUE if a change was made, FALSE otherwise.  */
1190
1191 static bool 
1192 simplify_conversion_from_bitmask (gimple_stmt_iterator *gsi_p)
1193 {
1194   gimple stmt = gsi_stmt (*gsi_p);
1195   gimple rhs_def_stmt = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
1196
1197   /* See if the input for the conversion was set via a BIT_AND_EXPR and
1198      the only use of the BIT_AND_EXPR result is the conversion.  */
1199   if (is_gimple_assign (rhs_def_stmt)
1200       && gimple_assign_rhs_code (rhs_def_stmt) == BIT_AND_EXPR
1201       && has_single_use (gimple_assign_lhs (rhs_def_stmt)))
1202     {
1203       tree rhs_def_operand1 = gimple_assign_rhs1 (rhs_def_stmt);
1204       tree rhs_def_operand2 = gimple_assign_rhs2 (rhs_def_stmt);
1205       tree lhs_type = TREE_TYPE (gimple_assign_lhs (stmt));
1206
1207       /* Now verify suitability of the BIT_AND_EXPR's operands.
1208          The first must be an SSA_NAME that we can propagate and the
1209          second must be an integer constant that masks out all the
1210          bits outside the final result's type, but nothing else.  */
1211       if (TREE_CODE (rhs_def_operand1) == SSA_NAME
1212           && ! SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs_def_operand1)
1213           && TREE_CODE (rhs_def_operand2) == INTEGER_CST
1214           && operand_equal_p (rhs_def_operand2,
1215                               build_low_bits_mask (TREE_TYPE (rhs_def_operand2),
1216                                                    TYPE_PRECISION (lhs_type)),
1217                                                    0))
1218         {
1219           /* This is an optimizable case.  Replace the source operand
1220              in the conversion with the first source operand of the
1221              BIT_AND_EXPR.  */
1222           gimple_assign_set_rhs1 (stmt, rhs_def_operand1);
1223           stmt = gsi_stmt (*gsi_p);
1224           update_stmt (stmt);
1225
1226           /* There is no DCE after the last forwprop pass.  It's
1227              easy to clean up the first order effects here.  */
1228           gimple_stmt_iterator si;
1229           si = gsi_for_stmt (rhs_def_stmt);
1230           gsi_remove (&si, true);
1231           release_defs (rhs_def_stmt);
1232           return true;
1233         }
1234     }
1235
1236   return false;
1237 }
1238
1239
1240 /* If we have lhs = ~x (STMT), look and see if earlier we had x = ~y.
1241    If so, we can change STMT into lhs = y which can later be copy
1242    propagated.  Similarly for negation.
1243
1244    This could trivially be formulated as a forward propagation
1245    to immediate uses.  However, we already had an implementation
1246    from DOM which used backward propagation via the use-def links.
1247
1248    It turns out that backward propagation is actually faster as
1249    there's less work to do for each NOT/NEG expression we find.
1250    Backwards propagation needs to look at the statement in a single
1251    backlink.  Forward propagation needs to look at potentially more
1252    than one forward link.
1253
1254    Returns true when the statement was changed.  */
1255
1256 static bool 
1257 simplify_not_neg_expr (gimple_stmt_iterator *gsi_p)
1258 {
1259   gimple stmt = gsi_stmt (*gsi_p);
1260   tree rhs = gimple_assign_rhs1 (stmt);
1261   gimple rhs_def_stmt = SSA_NAME_DEF_STMT (rhs);
1262
1263   /* See if the RHS_DEF_STMT has the same form as our statement.  */
1264   if (is_gimple_assign (rhs_def_stmt)
1265       && gimple_assign_rhs_code (rhs_def_stmt) == gimple_assign_rhs_code (stmt))
1266     {
1267       tree rhs_def_operand = gimple_assign_rhs1 (rhs_def_stmt);
1268
1269       /* Verify that RHS_DEF_OPERAND is a suitable SSA_NAME.  */
1270       if (TREE_CODE (rhs_def_operand) == SSA_NAME
1271           && ! SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs_def_operand))
1272         {
1273           gimple_assign_set_rhs_from_tree (gsi_p, rhs_def_operand);
1274           stmt = gsi_stmt (*gsi_p);
1275           update_stmt (stmt);
1276           return true;
1277         }
1278     }
1279
1280   return false;
1281 }
1282
1283 /* Helper function for simplify_gimple_switch.  Remove case labels that
1284    have values outside the range of the new type.  */
1285
1286 static void
1287 simplify_gimple_switch_label_vec (gimple stmt, tree index_type)
1288 {
1289   unsigned int branch_num = gimple_switch_num_labels (stmt);
1290   auto_vec<tree> labels (branch_num);
1291   unsigned int i, len;
1292
1293   /* Collect the existing case labels in a VEC, and preprocess it as if
1294      we are gimplifying a GENERIC SWITCH_EXPR.  */
1295   for (i = 1; i < branch_num; i++)
1296     labels.quick_push (gimple_switch_label (stmt, i));
1297   preprocess_case_label_vec_for_gimple (labels, index_type, NULL);
1298
1299   /* If any labels were removed, replace the existing case labels
1300      in the GIMPLE_SWITCH statement with the correct ones.
1301      Note that the type updates were done in-place on the case labels,
1302      so we only have to replace the case labels in the GIMPLE_SWITCH
1303      if the number of labels changed.  */
1304   len = labels.length ();
1305   if (len < branch_num - 1)
1306     {
1307       bitmap target_blocks;
1308       edge_iterator ei;
1309       edge e;
1310
1311       /* Corner case: *all* case labels have been removed as being
1312          out-of-range for INDEX_TYPE.  Push one label and let the
1313          CFG cleanups deal with this further.  */
1314       if (len == 0)
1315         {
1316           tree label, elt;
1317
1318           label = CASE_LABEL (gimple_switch_default_label (stmt));
1319           elt = build_case_label (build_int_cst (index_type, 0), NULL, label);
1320           labels.quick_push (elt);
1321           len = 1;
1322         }
1323
1324       for (i = 0; i < labels.length (); i++)
1325         gimple_switch_set_label (stmt, i + 1, labels[i]);
1326       for (i++ ; i < branch_num; i++)
1327         gimple_switch_set_label (stmt, i, NULL_TREE);
1328       gimple_switch_set_num_labels (stmt, len + 1);
1329
1330       /* Cleanup any edges that are now dead.  */
1331       target_blocks = BITMAP_ALLOC (NULL);
1332       for (i = 0; i < gimple_switch_num_labels (stmt); i++)
1333         {
1334           tree elt = gimple_switch_label (stmt, i);
1335           basic_block target = label_to_block (CASE_LABEL (elt));
1336           bitmap_set_bit (target_blocks, target->index);
1337         }
1338       for (ei = ei_start (gimple_bb (stmt)->succs); (e = ei_safe_edge (ei)); )
1339         {
1340           if (! bitmap_bit_p (target_blocks, e->dest->index))
1341             {
1342               remove_edge (e);
1343               cfg_changed = true;
1344               free_dominance_info (CDI_DOMINATORS);
1345             }
1346           else
1347             ei_next (&ei);
1348         } 
1349       BITMAP_FREE (target_blocks);
1350     }
1351 }
1352
1353 /* STMT is a SWITCH_EXPR for which we attempt to find equivalent forms of
1354    the condition which we may be able to optimize better.  */
1355
1356 static bool
1357 simplify_gimple_switch (gimple stmt)
1358 {
1359   tree cond = gimple_switch_index (stmt);
1360   tree def, to, ti;
1361   gimple def_stmt;
1362
1363   /* The optimization that we really care about is removing unnecessary
1364      casts.  That will let us do much better in propagating the inferred
1365      constant at the switch target.  */
1366   if (TREE_CODE (cond) == SSA_NAME)
1367     {
1368       def_stmt = SSA_NAME_DEF_STMT (cond);
1369       if (is_gimple_assign (def_stmt))
1370         {
1371           if (gimple_assign_rhs_code (def_stmt) == NOP_EXPR)
1372             {
1373               int need_precision;
1374               bool fail;
1375
1376               def = gimple_assign_rhs1 (def_stmt);
1377
1378               to = TREE_TYPE (cond);
1379               ti = TREE_TYPE (def);
1380
1381               /* If we have an extension that preserves value, then we
1382                  can copy the source value into the switch.  */
1383
1384               need_precision = TYPE_PRECISION (ti);
1385               fail = false;
1386               if (! INTEGRAL_TYPE_P (ti))
1387                 fail = true;
1388               else if (TYPE_UNSIGNED (to) && !TYPE_UNSIGNED (ti))
1389                 fail = true;
1390               else if (!TYPE_UNSIGNED (to) && TYPE_UNSIGNED (ti))
1391                 need_precision += 1;
1392               if (TYPE_PRECISION (to) < need_precision)
1393                 fail = true;
1394
1395               if (!fail)
1396                 {
1397                   gimple_switch_set_index (stmt, def);
1398                   simplify_gimple_switch_label_vec (stmt, ti);
1399                   update_stmt (stmt);
1400                   return true;
1401                 }
1402             }
1403         }
1404     }
1405
1406   return false;
1407 }
1408
1409 /* For pointers p2 and p1 return p2 - p1 if the
1410    difference is known and constant, otherwise return NULL.  */
1411
1412 static tree
1413 constant_pointer_difference (tree p1, tree p2)
1414 {
1415   int i, j;
1416 #define CPD_ITERATIONS 5
1417   tree exps[2][CPD_ITERATIONS];
1418   tree offs[2][CPD_ITERATIONS];
1419   int cnt[2];
1420
1421   for (i = 0; i < 2; i++)
1422     {
1423       tree p = i ? p1 : p2;
1424       tree off = size_zero_node;
1425       gimple stmt;
1426       enum tree_code code;
1427
1428       /* For each of p1 and p2 we need to iterate at least
1429          twice, to handle ADDR_EXPR directly in p1/p2,
1430          SSA_NAME with ADDR_EXPR or POINTER_PLUS_EXPR etc.
1431          on definition's stmt RHS.  Iterate a few extra times.  */
1432       j = 0;
1433       do
1434         {
1435           if (!POINTER_TYPE_P (TREE_TYPE (p)))
1436             break;
1437           if (TREE_CODE (p) == ADDR_EXPR)
1438             {
1439               tree q = TREE_OPERAND (p, 0);
1440               HOST_WIDE_INT offset;
1441               tree base = get_addr_base_and_unit_offset (q, &offset);
1442               if (base)
1443                 {
1444                   q = base;
1445                   if (offset)
1446                     off = size_binop (PLUS_EXPR, off, size_int (offset));
1447                 }
1448               if (TREE_CODE (q) == MEM_REF
1449                   && TREE_CODE (TREE_OPERAND (q, 0)) == SSA_NAME)
1450                 {
1451                   p = TREE_OPERAND (q, 0);
1452                   off = size_binop (PLUS_EXPR, off,
1453                                     double_int_to_tree (sizetype,
1454                                                         mem_ref_offset (q)));
1455                 }
1456               else
1457                 {
1458                   exps[i][j] = q;
1459                   offs[i][j++] = off;
1460                   break;
1461                 }
1462             }
1463           if (TREE_CODE (p) != SSA_NAME)
1464             break;
1465           exps[i][j] = p;
1466           offs[i][j++] = off;
1467           if (j == CPD_ITERATIONS)
1468             break;
1469           stmt = SSA_NAME_DEF_STMT (p);
1470           if (!is_gimple_assign (stmt) || gimple_assign_lhs (stmt) != p)
1471             break;
1472           code = gimple_assign_rhs_code (stmt);
1473           if (code == POINTER_PLUS_EXPR)
1474             {
1475               if (TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
1476                 break;
1477               off = size_binop (PLUS_EXPR, off, gimple_assign_rhs2 (stmt));
1478               p = gimple_assign_rhs1 (stmt);
1479             }
1480           else if (code == ADDR_EXPR || code == NOP_EXPR)
1481             p = gimple_assign_rhs1 (stmt);
1482           else
1483             break;
1484         }
1485       while (1);
1486       cnt[i] = j;
1487     }
1488
1489   for (i = 0; i < cnt[0]; i++)
1490     for (j = 0; j < cnt[1]; j++)
1491       if (exps[0][i] == exps[1][j])
1492         return size_binop (MINUS_EXPR, offs[0][i], offs[1][j]);
1493
1494   return NULL_TREE;
1495 }
1496
1497 /* *GSI_P is a GIMPLE_CALL to a builtin function.
1498    Optimize
1499    memcpy (p, "abcd", 4);
1500    memset (p + 4, ' ', 3);
1501    into
1502    memcpy (p, "abcd   ", 7);
1503    call if the latter can be stored by pieces during expansion.  */
1504
1505 static bool
1506 simplify_builtin_call (gimple_stmt_iterator *gsi_p, tree callee2)
1507 {
1508   gimple stmt1, stmt2 = gsi_stmt (*gsi_p);
1509   tree vuse = gimple_vuse (stmt2);
1510   if (vuse == NULL)
1511     return false;
1512   stmt1 = SSA_NAME_DEF_STMT (vuse);
1513
1514   switch (DECL_FUNCTION_CODE (callee2))
1515     {
1516     case BUILT_IN_MEMSET:
1517       if (gimple_call_num_args (stmt2) != 3
1518           || gimple_call_lhs (stmt2)
1519           || CHAR_BIT != 8
1520           || BITS_PER_UNIT != 8)
1521         break;
1522       else
1523         {
1524           tree callee1;
1525           tree ptr1, src1, str1, off1, len1, lhs1;
1526           tree ptr2 = gimple_call_arg (stmt2, 0);
1527           tree val2 = gimple_call_arg (stmt2, 1);
1528           tree len2 = gimple_call_arg (stmt2, 2);
1529           tree diff, vdef, new_str_cst;
1530           gimple use_stmt;
1531           unsigned int ptr1_align;
1532           unsigned HOST_WIDE_INT src_len;
1533           char *src_buf;
1534           use_operand_p use_p;
1535
1536           if (!tree_fits_shwi_p (val2)
1537               || !tree_fits_uhwi_p (len2))
1538             break;
1539           if (is_gimple_call (stmt1))
1540             {
1541               /* If first stmt is a call, it needs to be memcpy
1542                  or mempcpy, with string literal as second argument and
1543                  constant length.  */
1544               callee1 = gimple_call_fndecl (stmt1);
1545               if (callee1 == NULL_TREE
1546                   || DECL_BUILT_IN_CLASS (callee1) != BUILT_IN_NORMAL
1547                   || gimple_call_num_args (stmt1) != 3)
1548                 break;
1549               if (DECL_FUNCTION_CODE (callee1) != BUILT_IN_MEMCPY
1550                   && DECL_FUNCTION_CODE (callee1) != BUILT_IN_MEMPCPY)
1551                 break;
1552               ptr1 = gimple_call_arg (stmt1, 0);
1553               src1 = gimple_call_arg (stmt1, 1);
1554               len1 = gimple_call_arg (stmt1, 2);
1555               lhs1 = gimple_call_lhs (stmt1);
1556               if (!tree_fits_uhwi_p (len1))
1557                 break;
1558               str1 = string_constant (src1, &off1);
1559               if (str1 == NULL_TREE)
1560                 break;
1561               if (!tree_fits_uhwi_p (off1)
1562                   || compare_tree_int (off1, TREE_STRING_LENGTH (str1) - 1) > 0
1563                   || compare_tree_int (len1, TREE_STRING_LENGTH (str1)
1564                                              - tree_to_uhwi (off1)) > 0
1565                   || TREE_CODE (TREE_TYPE (str1)) != ARRAY_TYPE
1566                   || TYPE_MODE (TREE_TYPE (TREE_TYPE (str1)))
1567                      != TYPE_MODE (char_type_node))
1568                 break;
1569             }
1570           else if (gimple_assign_single_p (stmt1))
1571             {
1572               /* Otherwise look for length 1 memcpy optimized into
1573                  assignment.  */
1574               ptr1 = gimple_assign_lhs (stmt1);
1575               src1 = gimple_assign_rhs1 (stmt1);
1576               if (TREE_CODE (ptr1) != MEM_REF
1577                   || TYPE_MODE (TREE_TYPE (ptr1)) != TYPE_MODE (char_type_node)
1578                   || !tree_fits_shwi_p (src1))
1579                 break;
1580               ptr1 = build_fold_addr_expr (ptr1);
1581               callee1 = NULL_TREE;
1582               len1 = size_one_node;
1583               lhs1 = NULL_TREE;
1584               off1 = size_zero_node;
1585               str1 = NULL_TREE;
1586             }
1587           else
1588             break;
1589
1590           diff = constant_pointer_difference (ptr1, ptr2);
1591           if (diff == NULL && lhs1 != NULL)
1592             {
1593               diff = constant_pointer_difference (lhs1, ptr2);
1594               if (DECL_FUNCTION_CODE (callee1) == BUILT_IN_MEMPCPY
1595                   && diff != NULL)
1596                 diff = size_binop (PLUS_EXPR, diff,
1597                                    fold_convert (sizetype, len1));
1598             }
1599           /* If the difference between the second and first destination pointer
1600              is not constant, or is bigger than memcpy length, bail out.  */
1601           if (diff == NULL
1602               || !tree_fits_uhwi_p (diff)
1603               || tree_int_cst_lt (len1, diff))
1604             break;
1605
1606           /* Use maximum of difference plus memset length and memcpy length
1607              as the new memcpy length, if it is too big, bail out.  */
1608           src_len = tree_to_uhwi (diff);
1609           src_len += tree_to_uhwi (len2);
1610           if (src_len < tree_to_uhwi (len1))
1611             src_len = tree_to_uhwi (len1);
1612           if (src_len > 1024)
1613             break;
1614
1615           /* If mempcpy value is used elsewhere, bail out, as mempcpy
1616              with bigger length will return different result.  */
1617           if (lhs1 != NULL_TREE
1618               && DECL_FUNCTION_CODE (callee1) == BUILT_IN_MEMPCPY
1619               && (TREE_CODE (lhs1) != SSA_NAME
1620                   || !single_imm_use (lhs1, &use_p, &use_stmt)
1621                   || use_stmt != stmt2))
1622             break;
1623
1624           /* If anything reads memory in between memcpy and memset
1625              call, the modified memcpy call might change it.  */
1626           vdef = gimple_vdef (stmt1);
1627           if (vdef != NULL
1628               && (!single_imm_use (vdef, &use_p, &use_stmt)
1629                   || use_stmt != stmt2))
1630             break;
1631
1632           ptr1_align = get_pointer_alignment (ptr1);
1633           /* Construct the new source string literal.  */
1634           src_buf = XALLOCAVEC (char, src_len + 1);
1635           if (callee1)
1636             memcpy (src_buf,
1637                     TREE_STRING_POINTER (str1) + tree_to_uhwi (off1),
1638                     tree_to_uhwi (len1));
1639           else
1640             src_buf[0] = tree_to_shwi (src1);
1641           memset (src_buf + tree_to_uhwi (diff),
1642                   tree_to_shwi (val2), tree_to_uhwi (len2));
1643           src_buf[src_len] = '\0';
1644           /* Neither builtin_strncpy_read_str nor builtin_memcpy_read_str
1645              handle embedded '\0's.  */
1646           if (strlen (src_buf) != src_len)
1647             break;
1648           rtl_profile_for_bb (gimple_bb (stmt2));
1649           /* If the new memcpy wouldn't be emitted by storing the literal
1650              by pieces, this optimization might enlarge .rodata too much,
1651              as commonly used string literals couldn't be shared any
1652              longer.  */
1653           if (!can_store_by_pieces (src_len,
1654                                     builtin_strncpy_read_str,
1655                                     src_buf, ptr1_align, false))
1656             break;
1657
1658           new_str_cst = build_string_literal (src_len, src_buf);
1659           if (callee1)
1660             {
1661               /* If STMT1 is a mem{,p}cpy call, adjust it and remove
1662                  memset call.  */
1663               if (lhs1 && DECL_FUNCTION_CODE (callee1) == BUILT_IN_MEMPCPY)
1664                 gimple_call_set_lhs (stmt1, NULL_TREE);
1665               gimple_call_set_arg (stmt1, 1, new_str_cst);
1666               gimple_call_set_arg (stmt1, 2,
1667                                    build_int_cst (TREE_TYPE (len1), src_len));
1668               update_stmt (stmt1);
1669               unlink_stmt_vdef (stmt2);
1670               gsi_remove (gsi_p, true);
1671               release_defs (stmt2);
1672               if (lhs1 && DECL_FUNCTION_CODE (callee1) == BUILT_IN_MEMPCPY)
1673                 release_ssa_name (lhs1);
1674               return true;
1675             }
1676           else
1677             {
1678               /* Otherwise, if STMT1 is length 1 memcpy optimized into
1679                  assignment, remove STMT1 and change memset call into
1680                  memcpy call.  */
1681               gimple_stmt_iterator gsi = gsi_for_stmt (stmt1);
1682
1683               if (!is_gimple_val (ptr1))
1684                 ptr1 = force_gimple_operand_gsi (gsi_p, ptr1, true, NULL_TREE,
1685                                                  true, GSI_SAME_STMT);
1686               gimple_call_set_fndecl (stmt2,
1687                                       builtin_decl_explicit (BUILT_IN_MEMCPY));
1688               gimple_call_set_arg (stmt2, 0, ptr1);
1689               gimple_call_set_arg (stmt2, 1, new_str_cst);
1690               gimple_call_set_arg (stmt2, 2,
1691                                    build_int_cst (TREE_TYPE (len2), src_len));
1692               unlink_stmt_vdef (stmt1);
1693               gsi_remove (&gsi, true);
1694               release_defs (stmt1);
1695               update_stmt (stmt2);
1696               return false;
1697             }
1698         }
1699       break;
1700     default:
1701       break;
1702     }
1703   return false;
1704 }
1705
1706 /* Checks if expression has type of one-bit precision, or is a known
1707    truth-valued expression.  */
1708 static bool
1709 truth_valued_ssa_name (tree name)
1710 {
1711   gimple def;
1712   tree type = TREE_TYPE (name);
1713
1714   if (!INTEGRAL_TYPE_P (type))
1715     return false;
1716   /* Don't check here for BOOLEAN_TYPE as the precision isn't
1717      necessarily one and so ~X is not equal to !X.  */
1718   if (TYPE_PRECISION (type) == 1)
1719     return true;
1720   def = SSA_NAME_DEF_STMT (name);
1721   if (is_gimple_assign (def))
1722     return truth_value_p (gimple_assign_rhs_code (def));
1723   return false;
1724 }
1725
1726 /* Helper routine for simplify_bitwise_binary_1 function.
1727    Return for the SSA name NAME the expression X if it mets condition
1728    NAME = !X. Otherwise return NULL_TREE.
1729    Detected patterns for NAME = !X are:
1730      !X and X == 0 for X with integral type.
1731      X ^ 1, X != 1,or ~X for X with integral type with precision of one.  */
1732 static tree
1733 lookup_logical_inverted_value (tree name)
1734 {
1735   tree op1, op2;
1736   enum tree_code code;
1737   gimple def;
1738
1739   /* If name has none-intergal type, or isn't a SSA_NAME, then
1740      return.  */
1741   if (TREE_CODE (name) != SSA_NAME
1742       || !INTEGRAL_TYPE_P (TREE_TYPE (name)))
1743     return NULL_TREE;
1744   def = SSA_NAME_DEF_STMT (name);
1745   if (!is_gimple_assign (def))
1746     return NULL_TREE;
1747
1748   code = gimple_assign_rhs_code (def);
1749   op1 = gimple_assign_rhs1 (def);
1750   op2 = NULL_TREE;
1751
1752   /* Get for EQ_EXPR or BIT_XOR_EXPR operation the second operand.
1753      If CODE isn't an EQ_EXPR, BIT_XOR_EXPR, or BIT_NOT_EXPR, then return.  */
1754   if (code == EQ_EXPR || code == NE_EXPR
1755       || code == BIT_XOR_EXPR)
1756     op2 = gimple_assign_rhs2 (def);
1757
1758   switch (code)
1759     {
1760     case BIT_NOT_EXPR:
1761       if (truth_valued_ssa_name (name))
1762         return op1;
1763       break;
1764     case EQ_EXPR:
1765       /* Check if we have X == 0 and X has an integral type.  */
1766       if (!INTEGRAL_TYPE_P (TREE_TYPE (op1)))
1767         break;
1768       if (integer_zerop (op2))
1769         return op1;
1770       break;
1771     case NE_EXPR:
1772       /* Check if we have X != 1 and X is a truth-valued.  */
1773       if (!INTEGRAL_TYPE_P (TREE_TYPE (op1)))
1774         break;
1775       if (integer_onep (op2) && truth_valued_ssa_name (op1))
1776         return op1;
1777       break;
1778     case BIT_XOR_EXPR:
1779       /* Check if we have X ^ 1 and X is truth valued.  */
1780       if (integer_onep (op2) && truth_valued_ssa_name (op1))
1781         return op1;
1782       break;
1783     default:
1784       break;
1785     }
1786
1787   return NULL_TREE;
1788 }
1789
1790 /* Optimize ARG1 CODE ARG2 to a constant for bitwise binary
1791    operations CODE, if one operand has the logically inverted
1792    value of the other.  */
1793 static tree
1794 simplify_bitwise_binary_1 (enum tree_code code, tree type,
1795                            tree arg1, tree arg2)
1796 {
1797   tree anot;
1798
1799   /* If CODE isn't a bitwise binary operation, return NULL_TREE.  */
1800   if (code != BIT_AND_EXPR && code != BIT_IOR_EXPR
1801       && code != BIT_XOR_EXPR)
1802     return NULL_TREE;
1803
1804   /* First check if operands ARG1 and ARG2 are equal.  If so
1805      return NULL_TREE as this optimization is handled fold_stmt.  */
1806   if (arg1 == arg2)
1807     return NULL_TREE;
1808   /* See if we have in arguments logical-not patterns.  */
1809   if (((anot = lookup_logical_inverted_value (arg1)) == NULL_TREE
1810        || anot != arg2)
1811       && ((anot = lookup_logical_inverted_value (arg2)) == NULL_TREE
1812           || anot != arg1))
1813     return NULL_TREE;
1814
1815   /* X & !X -> 0.  */
1816   if (code == BIT_AND_EXPR)
1817     return fold_convert (type, integer_zero_node);
1818   /* X | !X -> 1 and X ^ !X -> 1, if X is truth-valued.  */
1819   if (truth_valued_ssa_name (anot))
1820     return fold_convert (type, integer_one_node);
1821
1822   /* ??? Otherwise result is (X != 0 ? X : 1).  not handled.  */
1823   return NULL_TREE;
1824 }
1825
1826 /* Given a ssa_name in NAME see if it was defined by an assignment and
1827    set CODE to be the code and ARG1 to the first operand on the rhs and ARG2
1828    to the second operand on the rhs. */
1829
1830 static inline void
1831 defcodefor_name (tree name, enum tree_code *code, tree *arg1, tree *arg2)
1832 {
1833   gimple def;
1834   enum tree_code code1;
1835   tree arg11;
1836   tree arg21;
1837   tree arg31;
1838   enum gimple_rhs_class grhs_class;
1839
1840   code1 = TREE_CODE (name);
1841   arg11 = name;
1842   arg21 = NULL_TREE;
1843   grhs_class = get_gimple_rhs_class (code1);
1844
1845   if (code1 == SSA_NAME)
1846     {
1847       def = SSA_NAME_DEF_STMT (name);
1848       
1849       if (def && is_gimple_assign (def)
1850           && can_propagate_from (def))
1851         {
1852           code1 = gimple_assign_rhs_code (def);
1853           arg11 = gimple_assign_rhs1 (def);
1854           arg21 = gimple_assign_rhs2 (def);
1855           arg31 = gimple_assign_rhs2 (def);
1856         }
1857     }
1858   else if (grhs_class == GIMPLE_TERNARY_RHS
1859            || GIMPLE_BINARY_RHS
1860            || GIMPLE_UNARY_RHS
1861            || GIMPLE_SINGLE_RHS)
1862     extract_ops_from_tree_1 (name, &code1, &arg11, &arg21, &arg31);
1863
1864   *code = code1;
1865   *arg1 = arg11;
1866   if (arg2)
1867     *arg2 = arg21;
1868   /* Ignore arg3 currently. */
1869 }
1870
1871 /* Return true if a conversion of an operand from type FROM to type TO
1872    should be applied after performing the operation instead.  */
1873
1874 static bool
1875 hoist_conversion_for_bitop_p (tree to, tree from)
1876 {
1877   /* That's a good idea if the conversion widens the operand, thus
1878      after hoisting the conversion the operation will be narrower.  */
1879   if (TYPE_PRECISION (from) < TYPE_PRECISION (to))
1880     return true;
1881
1882   /* It's also a good idea if the conversion is to a non-integer mode.  */
1883   if (GET_MODE_CLASS (TYPE_MODE (to)) != MODE_INT)
1884     return true;
1885
1886   /* Or if the precision of TO is not the same as the precision
1887      of its mode.  */
1888   if (TYPE_PRECISION (to) != GET_MODE_PRECISION (TYPE_MODE (to)))
1889     return true;
1890
1891   return false;
1892 }
1893
1894 /* GSI points to a statement of the form
1895
1896    result = OP0 CODE OP1
1897
1898    Where OP0 and OP1 are single bit SSA_NAMEs and CODE is either
1899    BIT_AND_EXPR or BIT_IOR_EXPR.
1900
1901    If OP0 is fed by a bitwise negation of another single bit SSA_NAME,
1902    then we can simplify the two statements into a single LT_EXPR or LE_EXPR
1903    when code is BIT_AND_EXPR and BIT_IOR_EXPR respectively.
1904
1905    If a simplification is made, return TRUE, else return FALSE.  */
1906 static bool
1907 simplify_bitwise_binary_boolean (gimple_stmt_iterator *gsi,
1908                                  enum tree_code code,
1909                                  tree op0, tree op1)
1910 {
1911   gimple op0_def_stmt = SSA_NAME_DEF_STMT (op0);
1912
1913   if (!is_gimple_assign (op0_def_stmt)
1914       || (gimple_assign_rhs_code (op0_def_stmt) != BIT_NOT_EXPR))
1915     return false;
1916
1917   tree x = gimple_assign_rhs1 (op0_def_stmt);
1918   if (TREE_CODE (x) == SSA_NAME
1919       && INTEGRAL_TYPE_P (TREE_TYPE (x))
1920       && TYPE_PRECISION (TREE_TYPE (x)) == 1
1921       && TYPE_UNSIGNED (TREE_TYPE (x)) == TYPE_UNSIGNED (TREE_TYPE (op1)))
1922     {
1923       enum tree_code newcode;
1924
1925       gimple stmt = gsi_stmt (*gsi);
1926       gimple_assign_set_rhs1 (stmt, x);
1927       gimple_assign_set_rhs2 (stmt, op1);
1928       if (code == BIT_AND_EXPR)
1929         newcode = TYPE_UNSIGNED (TREE_TYPE (x)) ? LT_EXPR : GT_EXPR;
1930       else
1931         newcode = TYPE_UNSIGNED (TREE_TYPE (x)) ? LE_EXPR : GE_EXPR;
1932       gimple_assign_set_rhs_code (stmt, newcode); 
1933       update_stmt (stmt);
1934       return true;
1935     }
1936   return false;
1937
1938 }
1939
1940 /* Simplify bitwise binary operations.
1941    Return true if a transformation applied, otherwise return false.  */
1942
1943 static bool
1944 simplify_bitwise_binary (gimple_stmt_iterator *gsi)
1945 {
1946   gimple stmt = gsi_stmt (*gsi);
1947   tree arg1 = gimple_assign_rhs1 (stmt);
1948   tree arg2 = gimple_assign_rhs2 (stmt);
1949   enum tree_code code = gimple_assign_rhs_code (stmt);
1950   tree res;
1951   tree def1_arg1, def1_arg2, def2_arg1, def2_arg2;
1952   enum tree_code def1_code, def2_code;
1953
1954   defcodefor_name (arg1, &def1_code, &def1_arg1, &def1_arg2);
1955   defcodefor_name (arg2, &def2_code, &def2_arg1, &def2_arg2);
1956
1957   /* Try to fold (type) X op CST -> (type) (X op ((type-x) CST))
1958      when profitable.  */
1959   if (TREE_CODE (arg2) == INTEGER_CST
1960       && CONVERT_EXPR_CODE_P (def1_code)
1961       && hoist_conversion_for_bitop_p (TREE_TYPE (arg1), TREE_TYPE (def1_arg1))
1962       && INTEGRAL_TYPE_P (TREE_TYPE (def1_arg1))
1963       && int_fits_type_p (arg2, TREE_TYPE (def1_arg1)))
1964     {
1965       gimple newop;
1966       tree tem = make_ssa_name (TREE_TYPE (def1_arg1), NULL);
1967       newop =
1968         gimple_build_assign_with_ops (code, tem, def1_arg1,
1969                                       fold_convert_loc (gimple_location (stmt),
1970                                                         TREE_TYPE (def1_arg1),
1971                                                         arg2));
1972       gimple_set_location (newop, gimple_location (stmt));
1973       gsi_insert_before (gsi, newop, GSI_SAME_STMT);
1974       gimple_assign_set_rhs_with_ops_1 (gsi, NOP_EXPR,
1975                                         tem, NULL_TREE, NULL_TREE);
1976       update_stmt (gsi_stmt (*gsi));
1977       return true;
1978     }
1979
1980   /* For bitwise binary operations apply operand conversions to the
1981      binary operation result instead of to the operands.  This allows
1982      to combine successive conversions and bitwise binary operations.  */
1983   if (CONVERT_EXPR_CODE_P (def1_code)
1984       && CONVERT_EXPR_CODE_P (def2_code)
1985       && types_compatible_p (TREE_TYPE (def1_arg1), TREE_TYPE (def2_arg1))
1986       && hoist_conversion_for_bitop_p (TREE_TYPE (arg1), TREE_TYPE (def1_arg1)))
1987     {
1988       gimple newop;
1989       tree tem = make_ssa_name (TREE_TYPE (def1_arg1), NULL);
1990       newop = gimple_build_assign_with_ops (code, tem, def1_arg1, def2_arg1);
1991       gimple_set_location (newop, gimple_location (stmt));
1992       gsi_insert_before (gsi, newop, GSI_SAME_STMT);
1993       gimple_assign_set_rhs_with_ops_1 (gsi, NOP_EXPR,
1994                                         tem, NULL_TREE, NULL_TREE);
1995       update_stmt (gsi_stmt (*gsi));
1996       return true;
1997     }
1998
1999
2000    /* Simplify (A & B) OP0 (C & B) to (A OP0 C) & B. */
2001    if (def1_code == def2_code
2002        && def1_code == BIT_AND_EXPR
2003        && operand_equal_for_phi_arg_p (def1_arg2,
2004                                        def2_arg2))
2005     {
2006       tree b = def1_arg2;
2007       tree a = def1_arg1;
2008       tree c = def2_arg1;
2009       tree inner = fold_build2 (code, TREE_TYPE (arg2), a, c);
2010       /* If A OP0 C (this usually means C is the same as A) is 0
2011          then fold it down correctly. */
2012       if (integer_zerop (inner))
2013         {
2014           gimple_assign_set_rhs_from_tree (gsi, inner);
2015           update_stmt (stmt);
2016           return true;
2017         }
2018       /* If A OP0 C (this usually means C is the same as A) is a ssa_name
2019          then fold it down correctly. */
2020       else if (TREE_CODE (inner) == SSA_NAME)
2021         {
2022           tree outer = fold_build2 (def1_code, TREE_TYPE (inner),
2023                                     inner, b);
2024           gimple_assign_set_rhs_from_tree (gsi, outer);
2025           update_stmt (stmt);
2026           return true;
2027         }
2028       else
2029         {
2030           gimple newop;
2031           tree tem;
2032           tem = make_ssa_name (TREE_TYPE (arg2), NULL);
2033           newop = gimple_build_assign_with_ops (code, tem, a, c);
2034           gimple_set_location (newop, gimple_location (stmt));
2035           /* Make sure to re-process the new stmt as it's walking upwards.  */
2036           gsi_insert_before (gsi, newop, GSI_NEW_STMT);
2037           gimple_assign_set_rhs1 (stmt, tem);
2038           gimple_assign_set_rhs2 (stmt, b);
2039           gimple_assign_set_rhs_code (stmt, def1_code);
2040           update_stmt (stmt);
2041           return true;
2042         }
2043     }
2044
2045   /* (a | CST1) & CST2  ->  (a & CST2) | (CST1 & CST2).  */
2046   if (code == BIT_AND_EXPR
2047       && def1_code == BIT_IOR_EXPR
2048       && CONSTANT_CLASS_P (arg2)
2049       && CONSTANT_CLASS_P (def1_arg2))
2050     {
2051       tree cst = fold_build2 (BIT_AND_EXPR, TREE_TYPE (arg2),
2052                               arg2, def1_arg2);
2053       tree tem;
2054       gimple newop;
2055       if (integer_zerop (cst))
2056         {
2057           gimple_assign_set_rhs1 (stmt, def1_arg1);
2058           update_stmt (stmt);
2059           return true;
2060         }
2061       tem = make_ssa_name (TREE_TYPE (arg2), NULL);
2062       newop = gimple_build_assign_with_ops (BIT_AND_EXPR,
2063                                             tem, def1_arg1, arg2);
2064       gimple_set_location (newop, gimple_location (stmt));
2065       /* Make sure to re-process the new stmt as it's walking upwards.  */
2066       gsi_insert_before (gsi, newop, GSI_NEW_STMT);
2067       gimple_assign_set_rhs1 (stmt, tem);
2068       gimple_assign_set_rhs2 (stmt, cst);
2069       gimple_assign_set_rhs_code (stmt, BIT_IOR_EXPR);
2070       update_stmt (stmt);
2071       return true;
2072     }
2073
2074   /* Combine successive equal operations with constants.  */
2075   if ((code == BIT_AND_EXPR
2076        || code == BIT_IOR_EXPR
2077        || code == BIT_XOR_EXPR)
2078       && def1_code == code 
2079       && CONSTANT_CLASS_P (arg2)
2080       && CONSTANT_CLASS_P (def1_arg2))
2081     {
2082       tree cst = fold_build2 (code, TREE_TYPE (arg2),
2083                               arg2, def1_arg2);
2084       gimple_assign_set_rhs1 (stmt, def1_arg1);
2085       gimple_assign_set_rhs2 (stmt, cst);
2086       update_stmt (stmt);
2087       return true;
2088     }
2089
2090   /* Canonicalize X ^ ~0 to ~X.  */
2091   if (code == BIT_XOR_EXPR
2092       && integer_all_onesp (arg2))
2093     {
2094       gimple_assign_set_rhs_with_ops (gsi, BIT_NOT_EXPR, arg1, NULL_TREE);
2095       gcc_assert (gsi_stmt (*gsi) == stmt);
2096       update_stmt (stmt);
2097       return true;
2098     }
2099
2100   /* Try simple folding for X op !X, and X op X.  */
2101   res = simplify_bitwise_binary_1 (code, TREE_TYPE (arg1), arg1, arg2);
2102   if (res != NULL_TREE)
2103     {
2104       gimple_assign_set_rhs_from_tree (gsi, res);
2105       update_stmt (gsi_stmt (*gsi));
2106       return true;
2107     }
2108
2109   if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR)
2110     {
2111       enum tree_code ocode = code == BIT_AND_EXPR ? BIT_IOR_EXPR : BIT_AND_EXPR;
2112       if (def1_code == ocode)
2113         {
2114           tree x = arg2;
2115           enum tree_code coden;
2116           tree a1, a2;
2117           /* ( X | Y) & X -> X */
2118           /* ( X & Y) | X -> X */
2119           if (x == def1_arg1
2120               || x == def1_arg2)
2121             {
2122               gimple_assign_set_rhs_from_tree (gsi, x);
2123               update_stmt (gsi_stmt (*gsi));
2124               return true;
2125             }
2126
2127           defcodefor_name (def1_arg1, &coden, &a1, &a2);
2128           /* (~X | Y) & X -> X & Y */
2129           /* (~X & Y) | X -> X | Y */
2130           if (coden == BIT_NOT_EXPR && a1 == x)
2131             {
2132               gimple_assign_set_rhs_with_ops (gsi, code,
2133                                               x, def1_arg2);
2134               gcc_assert (gsi_stmt (*gsi) == stmt);
2135               update_stmt (stmt);
2136               return true;
2137             }
2138           defcodefor_name (def1_arg2, &coden, &a1, &a2);
2139           /* (Y | ~X) & X -> X & Y */
2140           /* (Y & ~X) | X -> X | Y */
2141           if (coden == BIT_NOT_EXPR && a1 == x)
2142             {
2143               gimple_assign_set_rhs_with_ops (gsi, code,
2144                                               x, def1_arg1);
2145               gcc_assert (gsi_stmt (*gsi) == stmt);
2146               update_stmt (stmt);
2147               return true;
2148             }
2149         }
2150       if (def2_code == ocode)
2151         {
2152           enum tree_code coden;
2153           tree a1;
2154           tree x = arg1;
2155           /* X & ( X | Y) -> X */
2156           /* X | ( X & Y) -> X */
2157           if (x == def2_arg1
2158               || x == def2_arg2)
2159             {
2160               gimple_assign_set_rhs_from_tree (gsi, x);
2161               update_stmt (gsi_stmt (*gsi));
2162               return true;
2163             }
2164           defcodefor_name (def2_arg1, &coden, &a1, NULL);
2165           /* (~X | Y) & X -> X & Y */
2166           /* (~X & Y) | X -> X | Y */
2167           if (coden == BIT_NOT_EXPR && a1 == x)
2168             {
2169               gimple_assign_set_rhs_with_ops (gsi, code,
2170                                               x, def2_arg2);
2171               gcc_assert (gsi_stmt (*gsi) == stmt);
2172               update_stmt (stmt);
2173               return true;
2174             }
2175           defcodefor_name (def2_arg2, &coden, &a1, NULL);
2176           /* (Y | ~X) & X -> X & Y */
2177           /* (Y & ~X) | X -> X | Y */
2178           if (coden == BIT_NOT_EXPR && a1 == x)
2179             {
2180               gimple_assign_set_rhs_with_ops (gsi, code,
2181                                               x, def2_arg1);
2182               gcc_assert (gsi_stmt (*gsi) == stmt);
2183               update_stmt (stmt);
2184               return true;
2185             }
2186         }
2187
2188       /* If arg1 and arg2 are booleans (or any single bit type)
2189          then try to simplify:
2190
2191            (~X & Y) -> X < Y
2192            (X & ~Y) -> Y < X
2193            (~X | Y) -> X <= Y
2194            (X | ~Y) -> Y <= X 
2195
2196           But only do this if our result feeds into a comparison as
2197           this transformation is not always a win, particularly on
2198           targets with and-not instructions.  */
2199       if (TREE_CODE (arg1) == SSA_NAME
2200           && TREE_CODE (arg2) == SSA_NAME
2201           && INTEGRAL_TYPE_P (TREE_TYPE (arg1))
2202           && TYPE_PRECISION (TREE_TYPE (arg1)) == 1
2203           && TYPE_PRECISION (TREE_TYPE (arg2)) == 1
2204           && (TYPE_UNSIGNED (TREE_TYPE (arg1))
2205               == TYPE_UNSIGNED (TREE_TYPE (arg2))))
2206         {
2207           use_operand_p use_p;
2208           gimple use_stmt;
2209
2210           if (single_imm_use (gimple_assign_lhs (stmt), &use_p, &use_stmt))
2211             {
2212               if (gimple_code (use_stmt) == GIMPLE_COND
2213                   && gimple_cond_lhs (use_stmt) == gimple_assign_lhs (stmt)
2214                   && integer_zerop (gimple_cond_rhs (use_stmt))
2215                   && gimple_cond_code (use_stmt) == NE_EXPR)
2216                 {
2217                   if (simplify_bitwise_binary_boolean (gsi, code, arg1, arg2))
2218                     return true;
2219                   if (simplify_bitwise_binary_boolean (gsi, code, arg2, arg1))
2220                     return true;
2221                 }
2222             }
2223         }
2224     }
2225   return false;
2226 }
2227
2228
2229 /* Recognize rotation patterns.  Return true if a transformation
2230    applied, otherwise return false.
2231
2232    We are looking for X with unsigned type T with bitsize B, OP being
2233    +, | or ^, some type T2 wider than T and
2234    (X << CNT1) OP (X >> CNT2)                           iff CNT1 + CNT2 == B
2235    ((T) ((T2) X << CNT1)) OP ((T) ((T2) X >> CNT2))     iff CNT1 + CNT2 == B
2236    (X << Y) OP (X >> (B - Y))
2237    (X << (int) Y) OP (X >> (int) (B - Y))
2238    ((T) ((T2) X << Y)) OP ((T) ((T2) X >> (B - Y)))
2239    ((T) ((T2) X << (int) Y)) OP ((T) ((T2) X >> (int) (B - Y)))
2240    (X << Y) | (X >> ((-Y) & (B - 1)))
2241    (X << (int) Y) | (X >> (int) ((-Y) & (B - 1)))
2242    ((T) ((T2) X << Y)) | ((T) ((T2) X >> ((-Y) & (B - 1))))
2243    ((T) ((T2) X << (int) Y)) | ((T) ((T2) X >> (int) ((-Y) & (B - 1))))
2244
2245    and transform these into:
2246    X r<< CNT1
2247    X r<< Y
2248
2249    Note, in the patterns with T2 type, the type of OP operands
2250    might be even a signed type, but should have precision B.  */
2251
2252 static bool
2253 simplify_rotate (gimple_stmt_iterator *gsi)
2254 {
2255   gimple stmt = gsi_stmt (*gsi);
2256   tree arg[2], rtype, rotcnt = NULL_TREE;
2257   tree def_arg1[2], def_arg2[2];
2258   enum tree_code def_code[2];
2259   tree lhs;
2260   int i;
2261   bool swapped_p = false;
2262   gimple g;
2263
2264   arg[0] = gimple_assign_rhs1 (stmt);
2265   arg[1] = gimple_assign_rhs2 (stmt);
2266   rtype = TREE_TYPE (arg[0]);
2267
2268   /* Only create rotates in complete modes.  Other cases are not
2269      expanded properly.  */
2270   if (!INTEGRAL_TYPE_P (rtype)
2271       || TYPE_PRECISION (rtype) != GET_MODE_PRECISION (TYPE_MODE (rtype)))
2272     return false;
2273
2274   for (i = 0; i < 2; i++)
2275     defcodefor_name (arg[i], &def_code[i], &def_arg1[i], &def_arg2[i]);
2276
2277   /* Look through narrowing conversions.  */
2278   if (CONVERT_EXPR_CODE_P (def_code[0])
2279       && CONVERT_EXPR_CODE_P (def_code[1])
2280       && INTEGRAL_TYPE_P (TREE_TYPE (def_arg1[0]))
2281       && INTEGRAL_TYPE_P (TREE_TYPE (def_arg1[1]))
2282       && TYPE_PRECISION (TREE_TYPE (def_arg1[0]))
2283          == TYPE_PRECISION (TREE_TYPE (def_arg1[1]))
2284       && TYPE_PRECISION (TREE_TYPE (def_arg1[0])) > TYPE_PRECISION (rtype)
2285       && has_single_use (arg[0])
2286       && has_single_use (arg[1]))
2287     {
2288       for (i = 0; i < 2; i++)
2289         {
2290           arg[i] = def_arg1[i];
2291           defcodefor_name (arg[i], &def_code[i], &def_arg1[i], &def_arg2[i]);
2292         }
2293     }
2294
2295   /* One operand has to be LSHIFT_EXPR and one RSHIFT_EXPR.  */
2296   for (i = 0; i < 2; i++)
2297     if (def_code[i] != LSHIFT_EXPR && def_code[i] != RSHIFT_EXPR)
2298       return false;
2299     else if (!has_single_use (arg[i]))
2300       return false;
2301   if (def_code[0] == def_code[1])
2302     return false;
2303
2304   /* If we've looked through narrowing conversions before, look through
2305      widening conversions from unsigned type with the same precision
2306      as rtype here.  */
2307   if (TYPE_PRECISION (TREE_TYPE (def_arg1[0])) != TYPE_PRECISION (rtype))
2308     for (i = 0; i < 2; i++)
2309       {
2310         tree tem;
2311         enum tree_code code;
2312         defcodefor_name (def_arg1[i], &code, &tem, NULL);
2313         if (!CONVERT_EXPR_CODE_P (code)
2314             || !INTEGRAL_TYPE_P (TREE_TYPE (tem))
2315             || TYPE_PRECISION (TREE_TYPE (tem)) != TYPE_PRECISION (rtype))
2316           return false;
2317         def_arg1[i] = tem;
2318       }
2319   /* Both shifts have to use the same first operand.  */
2320   if (TREE_CODE (def_arg1[0]) != SSA_NAME || def_arg1[0] != def_arg1[1])
2321     return false;
2322   if (!TYPE_UNSIGNED (TREE_TYPE (def_arg1[0])))
2323     return false;
2324
2325   /* CNT1 + CNT2 == B case above.  */
2326   if (tree_fits_uhwi_p (def_arg2[0])
2327       && tree_fits_uhwi_p (def_arg2[1])
2328       && tree_to_uhwi (def_arg2[0])
2329          + tree_to_uhwi (def_arg2[1]) == TYPE_PRECISION (rtype))
2330     rotcnt = def_arg2[0];
2331   else if (TREE_CODE (def_arg2[0]) != SSA_NAME
2332            || TREE_CODE (def_arg2[1]) != SSA_NAME)
2333     return false;
2334   else
2335     {
2336       tree cdef_arg1[2], cdef_arg2[2], def_arg2_alt[2];
2337       enum tree_code cdef_code[2];
2338       /* Look through conversion of the shift count argument.
2339          The C/C++ FE cast any shift count argument to integer_type_node.
2340          The only problem might be if the shift count type maximum value
2341          is equal or smaller than number of bits in rtype.  */
2342       for (i = 0; i < 2; i++)
2343         {
2344           def_arg2_alt[i] = def_arg2[i];
2345           defcodefor_name (def_arg2[i], &cdef_code[i],
2346                            &cdef_arg1[i], &cdef_arg2[i]);
2347           if (CONVERT_EXPR_CODE_P (cdef_code[i])
2348               && INTEGRAL_TYPE_P (TREE_TYPE (cdef_arg1[i]))
2349               && TYPE_PRECISION (TREE_TYPE (cdef_arg1[i]))
2350                  > floor_log2 (TYPE_PRECISION (rtype))
2351               && TYPE_PRECISION (TREE_TYPE (cdef_arg1[i]))
2352                  == GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (cdef_arg1[i]))))
2353             {
2354               def_arg2_alt[i] = cdef_arg1[i];
2355               defcodefor_name (def_arg2_alt[i], &cdef_code[i],
2356                                &cdef_arg1[i], &cdef_arg2[i]);
2357             }
2358         }
2359       for (i = 0; i < 2; i++)
2360         /* Check for one shift count being Y and the other B - Y,
2361            with optional casts.  */
2362         if (cdef_code[i] == MINUS_EXPR
2363             && tree_fits_shwi_p (cdef_arg1[i])
2364             && tree_to_shwi (cdef_arg1[i]) == TYPE_PRECISION (rtype)
2365             && TREE_CODE (cdef_arg2[i]) == SSA_NAME)
2366           {
2367             tree tem;
2368             enum tree_code code;
2369
2370             if (cdef_arg2[i] == def_arg2[1 - i]
2371                 || cdef_arg2[i] == def_arg2_alt[1 - i])
2372               {
2373                 rotcnt = cdef_arg2[i];
2374                 break;
2375               }
2376             defcodefor_name (cdef_arg2[i], &code, &tem, NULL);
2377             if (CONVERT_EXPR_CODE_P (code)
2378                 && INTEGRAL_TYPE_P (TREE_TYPE (tem))
2379                 && TYPE_PRECISION (TREE_TYPE (tem))
2380                  > floor_log2 (TYPE_PRECISION (rtype))
2381                 && TYPE_PRECISION (TREE_TYPE (tem))
2382                  == GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (tem)))
2383                 && (tem == def_arg2[1 - i]
2384                     || tem == def_arg2_alt[1 - i]))
2385               {
2386                 rotcnt = tem;
2387                 break;
2388               }
2389           }
2390         /* The above sequence isn't safe for Y being 0,
2391            because then one of the shifts triggers undefined behavior.
2392            This alternative is safe even for rotation count of 0.
2393            One shift count is Y and the other (-Y) & (B - 1).  */
2394         else if (cdef_code[i] == BIT_AND_EXPR
2395                  && tree_fits_shwi_p (cdef_arg2[i])
2396                  && tree_to_shwi (cdef_arg2[i])
2397                     == TYPE_PRECISION (rtype) - 1
2398                  && TREE_CODE (cdef_arg1[i]) == SSA_NAME
2399                  && gimple_assign_rhs_code (stmt) == BIT_IOR_EXPR)
2400           {
2401             tree tem;
2402             enum tree_code code;
2403
2404             defcodefor_name (cdef_arg1[i], &code, &tem, NULL);
2405             if (CONVERT_EXPR_CODE_P (code)
2406                 && INTEGRAL_TYPE_P (TREE_TYPE (tem))
2407                 && TYPE_PRECISION (TREE_TYPE (tem))
2408                  > floor_log2 (TYPE_PRECISION (rtype))
2409                 && TYPE_PRECISION (TREE_TYPE (tem))
2410                  == GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (tem))))
2411               defcodefor_name (tem, &code, &tem, NULL);
2412
2413             if (code == NEGATE_EXPR)
2414               {
2415                 if (tem == def_arg2[1 - i] || tem == def_arg2_alt[1 - i])
2416                   {
2417                     rotcnt = tem;
2418                     break;
2419                   }
2420                 defcodefor_name (tem, &code, &tem, NULL);
2421                 if (CONVERT_EXPR_CODE_P (code)
2422                     && INTEGRAL_TYPE_P (TREE_TYPE (tem))
2423                     && TYPE_PRECISION (TREE_TYPE (tem))
2424                        > floor_log2 (TYPE_PRECISION (rtype))
2425                     && TYPE_PRECISION (TREE_TYPE (tem))
2426                        == GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (tem)))
2427                     && (tem == def_arg2[1 - i]
2428                         || tem == def_arg2_alt[1 - i]))
2429                   {
2430                     rotcnt = tem;
2431                     break;
2432                   }
2433               }
2434           }
2435       if (rotcnt == NULL_TREE)
2436         return false;
2437       swapped_p = i != 1;
2438     }
2439
2440   if (!useless_type_conversion_p (TREE_TYPE (def_arg2[0]),
2441                                   TREE_TYPE (rotcnt)))
2442     {
2443       g = gimple_build_assign_with_ops (NOP_EXPR,
2444                                         make_ssa_name (TREE_TYPE (def_arg2[0]),
2445                                                        NULL),
2446                                         rotcnt, NULL_TREE);
2447       gsi_insert_before (gsi, g, GSI_SAME_STMT);
2448       rotcnt = gimple_assign_lhs (g);
2449     }
2450   lhs = gimple_assign_lhs (stmt);
2451   if (!useless_type_conversion_p (rtype, TREE_TYPE (def_arg1[0])))
2452     lhs = make_ssa_name (TREE_TYPE (def_arg1[0]), NULL);
2453   g = gimple_build_assign_with_ops (((def_code[0] == LSHIFT_EXPR) ^ swapped_p)
2454                                     ? LROTATE_EXPR : RROTATE_EXPR,
2455                                     lhs, def_arg1[0], rotcnt);
2456   if (!useless_type_conversion_p (rtype, TREE_TYPE (def_arg1[0])))
2457     {
2458       gsi_insert_before (gsi, g, GSI_SAME_STMT);
2459       g = gimple_build_assign_with_ops (NOP_EXPR, gimple_assign_lhs (stmt),
2460                                         lhs, NULL_TREE);
2461     }
2462   gsi_replace (gsi, g, false);
2463   return true;
2464 }
2465
2466 /* Perform re-associations of the plus or minus statement STMT that are
2467    always permitted.  Returns true if the CFG was changed.  */
2468
2469 static bool
2470 associate_plusminus (gimple_stmt_iterator *gsi)
2471 {
2472   gimple stmt = gsi_stmt (*gsi);
2473   tree rhs1 = gimple_assign_rhs1 (stmt);
2474   tree rhs2 = gimple_assign_rhs2 (stmt);
2475   enum tree_code code = gimple_assign_rhs_code (stmt);
2476   bool changed;
2477
2478   /* We can't reassociate at all for saturating types.  */
2479   if (TYPE_SATURATING (TREE_TYPE (rhs1)))
2480     return false;
2481
2482   /* First contract negates.  */
2483   do
2484     {
2485       changed = false;
2486
2487       /* A +- (-B) -> A -+ B.  */
2488       if (TREE_CODE (rhs2) == SSA_NAME)
2489         {
2490           gimple def_stmt = SSA_NAME_DEF_STMT (rhs2);
2491           if (is_gimple_assign (def_stmt)
2492               && gimple_assign_rhs_code (def_stmt) == NEGATE_EXPR
2493               && can_propagate_from (def_stmt))
2494             {
2495               code = (code == MINUS_EXPR) ? PLUS_EXPR : MINUS_EXPR;
2496               gimple_assign_set_rhs_code (stmt, code);
2497               rhs2 = gimple_assign_rhs1 (def_stmt);
2498               gimple_assign_set_rhs2 (stmt, rhs2);
2499               gimple_set_modified (stmt, true);
2500               changed = true;
2501             }
2502         }
2503
2504       /* (-A) + B -> B - A.  */
2505       if (TREE_CODE (rhs1) == SSA_NAME
2506           && code == PLUS_EXPR)
2507         {
2508           gimple def_stmt = SSA_NAME_DEF_STMT (rhs1);
2509           if (is_gimple_assign (def_stmt)
2510               && gimple_assign_rhs_code (def_stmt) == NEGATE_EXPR
2511               && can_propagate_from (def_stmt))
2512             {
2513               code = MINUS_EXPR;
2514               gimple_assign_set_rhs_code (stmt, code);
2515               rhs1 = rhs2;
2516               gimple_assign_set_rhs1 (stmt, rhs1);
2517               rhs2 = gimple_assign_rhs1 (def_stmt);
2518               gimple_assign_set_rhs2 (stmt, rhs2);
2519               gimple_set_modified (stmt, true);
2520               changed = true;
2521             }
2522         }
2523     }
2524   while (changed);
2525
2526   /* We can't reassociate floating-point or fixed-point plus or minus
2527      because of saturation to +-Inf.  */
2528   if (FLOAT_TYPE_P (TREE_TYPE (rhs1))
2529       || FIXED_POINT_TYPE_P (TREE_TYPE (rhs1)))
2530     goto out;
2531
2532   /* Second match patterns that allow contracting a plus-minus pair
2533      irrespective of overflow issues.
2534
2535         (A +- B) - A       ->  +- B
2536         (A +- B) -+ B      ->  A
2537         (CST +- A) +- CST  ->  CST +- A
2538         (A +- CST) +- CST  ->  A +- CST
2539         ~A + A             ->  -1
2540         ~A + 1             ->  -A 
2541         A - (A +- B)       ->  -+ B
2542         A +- (B +- A)      ->  +- B
2543         CST +- (CST +- A)  ->  CST +- A
2544         CST +- (A +- CST)  ->  CST +- A
2545         A + ~A             ->  -1
2546         (T)(P + A) - (T)P  -> (T)A
2547
2548      via commutating the addition and contracting operations to zero
2549      by reassociation.  */
2550
2551   if (TREE_CODE (rhs1) == SSA_NAME)
2552     {
2553       gimple def_stmt = SSA_NAME_DEF_STMT (rhs1);
2554       if (is_gimple_assign (def_stmt) && can_propagate_from (def_stmt))
2555         {
2556           enum tree_code def_code = gimple_assign_rhs_code (def_stmt);
2557           if (def_code == PLUS_EXPR
2558               || def_code == MINUS_EXPR)
2559             {
2560               tree def_rhs1 = gimple_assign_rhs1 (def_stmt);
2561               tree def_rhs2 = gimple_assign_rhs2 (def_stmt);
2562               if (operand_equal_p (def_rhs1, rhs2, 0)
2563                   && code == MINUS_EXPR)
2564                 {
2565                   /* (A +- B) - A -> +- B.  */
2566                   code = ((def_code == PLUS_EXPR)
2567                           ? TREE_CODE (def_rhs2) : NEGATE_EXPR);
2568                   rhs1 = def_rhs2;
2569                   rhs2 = NULL_TREE;
2570                   gimple_assign_set_rhs_with_ops (gsi, code, rhs1, NULL_TREE);
2571                   gcc_assert (gsi_stmt (*gsi) == stmt);
2572                   gimple_set_modified (stmt, true);
2573                 }
2574               else if (operand_equal_p (def_rhs2, rhs2, 0)
2575                        && code != def_code)
2576                 {
2577                   /* (A +- B) -+ B -> A.  */
2578                   code = TREE_CODE (def_rhs1);
2579                   rhs1 = def_rhs1;
2580                   rhs2 = NULL_TREE;
2581                   gimple_assign_set_rhs_with_ops (gsi, code, rhs1, NULL_TREE);
2582                   gcc_assert (gsi_stmt (*gsi) == stmt);
2583                   gimple_set_modified (stmt, true);
2584                 }
2585               else if (CONSTANT_CLASS_P (rhs2)
2586                        && CONSTANT_CLASS_P (def_rhs1))
2587                 {
2588                   /* (CST +- A) +- CST -> CST +- A.  */
2589                   tree cst = fold_binary (code, TREE_TYPE (rhs1),
2590                                           def_rhs1, rhs2);
2591                   if (cst && !TREE_OVERFLOW (cst))
2592                     {
2593                       code = def_code;
2594                       gimple_assign_set_rhs_code (stmt, code);
2595                       rhs1 = cst;
2596                       gimple_assign_set_rhs1 (stmt, rhs1);
2597                       rhs2 = def_rhs2;
2598                       gimple_assign_set_rhs2 (stmt, rhs2);
2599                       gimple_set_modified (stmt, true);
2600                     }
2601                 }
2602               else if (CONSTANT_CLASS_P (rhs2)
2603                        && CONSTANT_CLASS_P (def_rhs2))
2604                 {
2605                   /* (A +- CST) +- CST -> A +- CST.  */
2606                   enum tree_code mix = (code == def_code)
2607                                        ? PLUS_EXPR : MINUS_EXPR;
2608                   tree cst = fold_binary (mix, TREE_TYPE (rhs1),
2609                                           def_rhs2, rhs2);
2610                   if (cst && !TREE_OVERFLOW (cst))
2611                     {
2612                       code = def_code;
2613                       gimple_assign_set_rhs_code (stmt, code);
2614                       rhs1 = def_rhs1;
2615                       gimple_assign_set_rhs1 (stmt, rhs1);
2616                       rhs2 = cst;
2617                       gimple_assign_set_rhs2 (stmt, rhs2);
2618                       gimple_set_modified (stmt, true);
2619                     }
2620                 }
2621             }
2622           else if (def_code == BIT_NOT_EXPR && code == PLUS_EXPR)
2623             {
2624               tree def_rhs1 = gimple_assign_rhs1 (def_stmt);
2625               if (operand_equal_p (def_rhs1, rhs2, 0))
2626                 {
2627                   /* ~A + A -> -1.  */
2628                   rhs1 = build_all_ones_cst (TREE_TYPE (rhs2));
2629                   rhs2 = NULL_TREE;
2630                   code = TREE_CODE (rhs1);
2631                   gimple_assign_set_rhs_with_ops (gsi, code, rhs1, NULL_TREE);
2632                   gcc_assert (gsi_stmt (*gsi) == stmt);
2633                   gimple_set_modified (stmt, true);
2634                 }
2635               else if ((TREE_CODE (TREE_TYPE (rhs2)) != COMPLEX_TYPE
2636                         && integer_onep (rhs2))
2637                        || (TREE_CODE (rhs2) == COMPLEX_CST
2638                            && integer_onep (TREE_REALPART (rhs2))
2639                            && integer_onep (TREE_IMAGPART (rhs2))))
2640                 {
2641                   /* ~A + 1 -> -A.  */
2642                   code = NEGATE_EXPR;
2643                   rhs1 = def_rhs1;
2644                   rhs2 = NULL_TREE;
2645                   gimple_assign_set_rhs_with_ops (gsi, code, rhs1, NULL_TREE);
2646                   gcc_assert (gsi_stmt (*gsi) == stmt);
2647                   gimple_set_modified (stmt, true);
2648                 }
2649             }
2650           else if (CONVERT_EXPR_CODE_P (def_code) && code == MINUS_EXPR
2651                    && TREE_CODE (rhs2) == SSA_NAME)
2652             {
2653               /* (T)(ptr + adj) - (T)ptr -> (T)adj.  */
2654               gimple def_stmt2 = SSA_NAME_DEF_STMT (rhs2);
2655               if (TREE_CODE (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
2656                   && is_gimple_assign (def_stmt2)
2657                   && can_propagate_from (def_stmt2)
2658                   && CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
2659                   && TREE_CODE (gimple_assign_rhs1 (def_stmt2)) == SSA_NAME)
2660                 {
2661                   /* Now we have (T)A - (T)ptr.  */
2662                   tree ptr = gimple_assign_rhs1 (def_stmt2);
2663                   def_stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (def_stmt));
2664                   if (is_gimple_assign (def_stmt2)
2665                       && gimple_assign_rhs_code (def_stmt2) == POINTER_PLUS_EXPR
2666                       && gimple_assign_rhs1 (def_stmt2) == ptr)
2667                     {
2668                       /* And finally (T)(ptr + X) - (T)ptr.  */
2669                       tree adj = gimple_assign_rhs2 (def_stmt2);
2670                       /* If the conversion of the pointer adjustment to the
2671                          final type requires a sign- or zero-extension we
2672                          have to punt - it is not defined which one is
2673                          correct.  */
2674                       if (TYPE_PRECISION (TREE_TYPE (rhs1))
2675                           <= TYPE_PRECISION (TREE_TYPE (adj))
2676                           || (TREE_CODE (adj) == INTEGER_CST
2677                               && tree_int_cst_sign_bit (adj) == 0))
2678                         {
2679                           if (useless_type_conversion_p (TREE_TYPE (rhs1),
2680                                                          TREE_TYPE (adj)))
2681                             {
2682                               code = TREE_CODE (adj);
2683                               rhs1 = adj;
2684                             }
2685                           else
2686                             {
2687                               code = NOP_EXPR;
2688                               rhs1 = adj;
2689                             }
2690                           rhs2 = NULL_TREE;
2691                           gimple_assign_set_rhs_with_ops (gsi, code, rhs1,
2692                                                           NULL_TREE);
2693                           gcc_assert (gsi_stmt (*gsi) == stmt);
2694                           gimple_set_modified (stmt, true);
2695                         }
2696                     }
2697                 }
2698             }
2699         }
2700     }
2701
2702   if (rhs2 && TREE_CODE (rhs2) == SSA_NAME)
2703     {
2704       gimple def_stmt = SSA_NAME_DEF_STMT (rhs2);
2705       if (is_gimple_assign (def_stmt) && can_propagate_from (def_stmt))
2706         {
2707           enum tree_code def_code = gimple_assign_rhs_code (def_stmt);
2708           if (def_code == PLUS_EXPR
2709               || def_code == MINUS_EXPR)
2710             {
2711               tree def_rhs1 = gimple_assign_rhs1 (def_stmt);
2712               tree def_rhs2 = gimple_assign_rhs2 (def_stmt);
2713               if (operand_equal_p (def_rhs1, rhs1, 0)
2714                   && code == MINUS_EXPR)
2715                 {
2716                   /* A - (A +- B) -> -+ B.  */
2717                   code = ((def_code == PLUS_EXPR)
2718                           ? NEGATE_EXPR : TREE_CODE (def_rhs2));
2719                   rhs1 = def_rhs2;
2720                   rhs2 = NULL_TREE;
2721                   gimple_assign_set_rhs_with_ops (gsi, code, rhs1, NULL_TREE);
2722                   gcc_assert (gsi_stmt (*gsi) == stmt);
2723                   gimple_set_modified (stmt, true);
2724                 }
2725               else if (operand_equal_p (def_rhs2, rhs1, 0)
2726                        && code != def_code)
2727                 {
2728                   /* A +- (B +- A) -> +- B.  */
2729                   code = ((code == PLUS_EXPR)
2730                           ? TREE_CODE (def_rhs1) : NEGATE_EXPR);
2731                   rhs1 = def_rhs1;
2732                   rhs2 = NULL_TREE;
2733                   gimple_assign_set_rhs_with_ops (gsi, code, rhs1, NULL_TREE);
2734                   gcc_assert (gsi_stmt (*gsi) == stmt);
2735                   gimple_set_modified (stmt, true);
2736                 }
2737               else if (CONSTANT_CLASS_P (rhs1)
2738                        && CONSTANT_CLASS_P (def_rhs1))
2739                 {
2740                   /* CST +- (CST +- A) -> CST +- A.  */
2741                   tree cst = fold_binary (code, TREE_TYPE (rhs2),
2742                                           rhs1, def_rhs1);
2743                   if (cst && !TREE_OVERFLOW (cst))
2744                     {
2745                       code = (code == def_code ? PLUS_EXPR : MINUS_EXPR);
2746                       gimple_assign_set_rhs_code (stmt, code);
2747                       rhs1 = cst;
2748                       gimple_assign_set_rhs1 (stmt, rhs1);
2749                       rhs2 = def_rhs2;
2750                       gimple_assign_set_rhs2 (stmt, rhs2);
2751                       gimple_set_modified (stmt, true);
2752                     }
2753                 }
2754               else if (CONSTANT_CLASS_P (rhs1)
2755                        && CONSTANT_CLASS_P (def_rhs2))
2756                 {
2757                   /* CST +- (A +- CST) -> CST +- A.  */
2758                   tree cst = fold_binary (def_code == code
2759                                           ? PLUS_EXPR : MINUS_EXPR,
2760                                           TREE_TYPE (rhs2),
2761                                           rhs1, def_rhs2);
2762                   if (cst && !TREE_OVERFLOW (cst))
2763                     {
2764                       rhs1 = cst;
2765                       gimple_assign_set_rhs1 (stmt, rhs1);
2766                       rhs2 = def_rhs1;
2767                       gimple_assign_set_rhs2 (stmt, rhs2);
2768                       gimple_set_modified (stmt, true);
2769                     }
2770                 }
2771             }
2772           else if (def_code == BIT_NOT_EXPR)
2773             {
2774               tree def_rhs1 = gimple_assign_rhs1 (def_stmt);
2775               if (code == PLUS_EXPR
2776                   && operand_equal_p (def_rhs1, rhs1, 0))
2777                 {
2778                   /* A + ~A -> -1.  */
2779                   rhs1 = build_all_ones_cst (TREE_TYPE (rhs1));
2780                   rhs2 = NULL_TREE;
2781                   code = TREE_CODE (rhs1);
2782                   gimple_assign_set_rhs_with_ops (gsi, code, rhs1, NULL_TREE);
2783                   gcc_assert (gsi_stmt (*gsi) == stmt);
2784                   gimple_set_modified (stmt, true);
2785                 }
2786             }
2787         }
2788     }
2789
2790 out:
2791   if (gimple_modified_p (stmt))
2792     {
2793       fold_stmt_inplace (gsi);
2794       update_stmt (stmt);
2795       if (maybe_clean_or_replace_eh_stmt (stmt, stmt)
2796           && gimple_purge_dead_eh_edges (gimple_bb (stmt)))
2797         return true;
2798     }
2799
2800   return false;
2801 }
2802
2803 /* Associate operands of a POINTER_PLUS_EXPR assignmen at *GSI.  Returns
2804    true if anything changed, false otherwise.  */
2805
2806 static bool
2807 associate_pointerplus (gimple_stmt_iterator *gsi)
2808 {
2809   gimple stmt = gsi_stmt (*gsi);
2810   gimple def_stmt;
2811   tree ptr, rhs, algn;
2812
2813   /* Pattern match
2814        tem = (sizetype) ptr;
2815        tem = tem & algn;
2816        tem = -tem;
2817        ... = ptr p+ tem;
2818      and produce the simpler and easier to analyze with respect to alignment
2819        ... = ptr & ~algn;  */
2820   ptr = gimple_assign_rhs1 (stmt);
2821   rhs = gimple_assign_rhs2 (stmt);
2822   if (TREE_CODE (rhs) != SSA_NAME)
2823     return false;
2824   def_stmt = SSA_NAME_DEF_STMT (rhs);
2825   if (!is_gimple_assign (def_stmt)
2826       || gimple_assign_rhs_code (def_stmt) != NEGATE_EXPR)
2827     return false;
2828   rhs = gimple_assign_rhs1 (def_stmt);
2829   if (TREE_CODE (rhs) != SSA_NAME)
2830     return false;
2831   def_stmt = SSA_NAME_DEF_STMT (rhs);
2832   if (!is_gimple_assign (def_stmt)
2833       || gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
2834     return false;
2835   rhs = gimple_assign_rhs1 (def_stmt);
2836   algn = gimple_assign_rhs2 (def_stmt);
2837   if (TREE_CODE (rhs) != SSA_NAME
2838       || TREE_CODE (algn) != INTEGER_CST)
2839     return false;
2840   def_stmt = SSA_NAME_DEF_STMT (rhs);
2841   if (!is_gimple_assign (def_stmt)
2842       || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
2843     return false;
2844   if (gimple_assign_rhs1 (def_stmt) != ptr)
2845     return false;
2846
2847   algn = double_int_to_tree (TREE_TYPE (ptr), ~tree_to_double_int (algn));
2848   gimple_assign_set_rhs_with_ops (gsi, BIT_AND_EXPR, ptr, algn);
2849   fold_stmt_inplace (gsi);
2850   update_stmt (stmt);
2851
2852   return true;
2853 }
2854
2855 /* Combine two conversions in a row for the second conversion at *GSI.
2856    Returns 1 if there were any changes made, 2 if cfg-cleanup needs to
2857    run.  Else it returns 0.  */
2858  
2859 static int
2860 combine_conversions (gimple_stmt_iterator *gsi)
2861 {
2862   gimple stmt = gsi_stmt (*gsi);
2863   gimple def_stmt;
2864   tree op0, lhs;
2865   enum tree_code code = gimple_assign_rhs_code (stmt);
2866   enum tree_code code2;
2867
2868   gcc_checking_assert (CONVERT_EXPR_CODE_P (code)
2869                        || code == FLOAT_EXPR
2870                        || code == FIX_TRUNC_EXPR);
2871
2872   lhs = gimple_assign_lhs (stmt);
2873   op0 = gimple_assign_rhs1 (stmt);
2874   if (useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (op0)))
2875     {
2876       gimple_assign_set_rhs_code (stmt, TREE_CODE (op0));
2877       return 1;
2878     }
2879
2880   if (TREE_CODE (op0) != SSA_NAME)
2881     return 0;
2882
2883   def_stmt = SSA_NAME_DEF_STMT (op0);
2884   if (!is_gimple_assign (def_stmt))
2885     return 0;
2886
2887   code2 = gimple_assign_rhs_code (def_stmt);
2888
2889   if (CONVERT_EXPR_CODE_P (code2) || code2 == FLOAT_EXPR)
2890     {
2891       tree defop0 = gimple_assign_rhs1 (def_stmt);
2892       tree type = TREE_TYPE (lhs);
2893       tree inside_type = TREE_TYPE (defop0);
2894       tree inter_type = TREE_TYPE (op0);
2895       int inside_int = INTEGRAL_TYPE_P (inside_type);
2896       int inside_ptr = POINTER_TYPE_P (inside_type);
2897       int inside_float = FLOAT_TYPE_P (inside_type);
2898       int inside_vec = TREE_CODE (inside_type) == VECTOR_TYPE;
2899       unsigned int inside_prec = TYPE_PRECISION (inside_type);
2900       int inside_unsignedp = TYPE_UNSIGNED (inside_type);
2901       int inter_int = INTEGRAL_TYPE_P (inter_type);
2902       int inter_ptr = POINTER_TYPE_P (inter_type);
2903       int inter_float = FLOAT_TYPE_P (inter_type);
2904       int inter_vec = TREE_CODE (inter_type) == VECTOR_TYPE;
2905       unsigned int inter_prec = TYPE_PRECISION (inter_type);
2906       int inter_unsignedp = TYPE_UNSIGNED (inter_type);
2907       int final_int = INTEGRAL_TYPE_P (type);
2908       int final_ptr = POINTER_TYPE_P (type);
2909       int final_float = FLOAT_TYPE_P (type);
2910       int final_vec = TREE_CODE (type) == VECTOR_TYPE;
2911       unsigned int final_prec = TYPE_PRECISION (type);
2912       int final_unsignedp = TYPE_UNSIGNED (type);
2913
2914       /* Don't propagate ssa names that occur in abnormal phis.  */
2915       if (TREE_CODE (defop0) == SSA_NAME
2916           && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (defop0))
2917         return 0;
2918
2919       /* In addition to the cases of two conversions in a row
2920          handled below, if we are converting something to its own
2921          type via an object of identical or wider precision, neither
2922          conversion is needed.  */
2923       if (useless_type_conversion_p (type, inside_type)
2924           && (((inter_int || inter_ptr) && final_int)
2925               || (inter_float && final_float))
2926           && inter_prec >= final_prec)
2927         {
2928           gimple_assign_set_rhs1 (stmt, unshare_expr (defop0));
2929           gimple_assign_set_rhs_code (stmt, TREE_CODE (defop0));
2930           update_stmt (stmt);
2931           return remove_prop_source_from_use (op0) ? 2 : 1;
2932         }
2933
2934       /* Likewise, if the intermediate and initial types are either both
2935          float or both integer, we don't need the middle conversion if the
2936          former is wider than the latter and doesn't change the signedness
2937          (for integers).  Avoid this if the final type is a pointer since
2938          then we sometimes need the middle conversion.  Likewise if the
2939          final type has a precision not equal to the size of its mode.  */
2940       if (((inter_int && inside_int)
2941            || (inter_float && inside_float)
2942            || (inter_vec && inside_vec))
2943           && inter_prec >= inside_prec
2944           && (inter_float || inter_vec
2945               || inter_unsignedp == inside_unsignedp)
2946           && ! (final_prec != GET_MODE_PRECISION (TYPE_MODE (type))
2947                 && TYPE_MODE (type) == TYPE_MODE (inter_type))
2948           && ! final_ptr
2949           && (! final_vec || inter_prec == inside_prec))
2950         {
2951           gimple_assign_set_rhs1 (stmt, defop0);
2952           update_stmt (stmt);
2953           return remove_prop_source_from_use (op0) ? 2 : 1;
2954         }
2955
2956       /* If we have a sign-extension of a zero-extended value, we can
2957          replace that by a single zero-extension.  Likewise if the
2958          final conversion does not change precision we can drop the
2959          intermediate conversion.  */
2960       if (inside_int && inter_int && final_int
2961           && ((inside_prec < inter_prec && inter_prec < final_prec
2962                && inside_unsignedp && !inter_unsignedp)
2963               || final_prec == inter_prec))
2964         {
2965           gimple_assign_set_rhs1 (stmt, defop0);
2966           update_stmt (stmt);
2967           return remove_prop_source_from_use (op0) ? 2 : 1;
2968         }
2969
2970       /* Two conversions in a row are not needed unless:
2971          - some conversion is floating-point (overstrict for now), or
2972          - some conversion is a vector (overstrict for now), or
2973          - the intermediate type is narrower than both initial and
2974          final, or
2975          - the intermediate type and innermost type differ in signedness,
2976          and the outermost type is wider than the intermediate, or
2977          - the initial type is a pointer type and the precisions of the
2978          intermediate and final types differ, or
2979          - the final type is a pointer type and the precisions of the
2980          initial and intermediate types differ.  */
2981       if (! inside_float && ! inter_float && ! final_float
2982           && ! inside_vec && ! inter_vec && ! final_vec
2983           && (inter_prec >= inside_prec || inter_prec >= final_prec)
2984           && ! (inside_int && inter_int
2985                 && inter_unsignedp != inside_unsignedp
2986                 && inter_prec < final_prec)
2987           && ((inter_unsignedp && inter_prec > inside_prec)
2988               == (final_unsignedp && final_prec > inter_prec))
2989           && ! (inside_ptr && inter_prec != final_prec)
2990           && ! (final_ptr && inside_prec != inter_prec)
2991           && ! (final_prec != GET_MODE_PRECISION (TYPE_MODE (type))
2992                 && TYPE_MODE (type) == TYPE_MODE (inter_type)))
2993         {
2994           gimple_assign_set_rhs1 (stmt, defop0);
2995           update_stmt (stmt);
2996           return remove_prop_source_from_use (op0) ? 2 : 1;
2997         }
2998
2999       /* A truncation to an unsigned type should be canonicalized as
3000          bitwise and of a mask.  */
3001       if (final_int && inter_int && inside_int
3002           && final_prec == inside_prec
3003           && final_prec > inter_prec
3004           && inter_unsignedp)
3005         {
3006           tree tem;
3007           tem = fold_build2 (BIT_AND_EXPR, inside_type,
3008                              defop0,
3009                              double_int_to_tree
3010                                (inside_type, double_int::mask (inter_prec)));
3011           if (!useless_type_conversion_p (type, inside_type))
3012             {
3013               tem = force_gimple_operand_gsi (gsi, tem, true, NULL_TREE, true,
3014                                               GSI_SAME_STMT);
3015               gimple_assign_set_rhs1 (stmt, tem);
3016             }
3017           else
3018             gimple_assign_set_rhs_from_tree (gsi, tem);
3019           update_stmt (gsi_stmt (*gsi));
3020           return 1;
3021         }
3022
3023       /* If we are converting an integer to a floating-point that can
3024          represent it exactly and back to an integer, we can skip the
3025          floating-point conversion.  */
3026       if (inside_int && inter_float && final_int &&
3027           (unsigned) significand_size (TYPE_MODE (inter_type))
3028           >= inside_prec - !inside_unsignedp)
3029         {
3030           if (useless_type_conversion_p (type, inside_type))
3031             {
3032               gimple_assign_set_rhs1 (stmt, unshare_expr (defop0));
3033               gimple_assign_set_rhs_code (stmt, TREE_CODE (defop0));
3034               update_stmt (stmt);
3035               return remove_prop_source_from_use (op0) ? 2 : 1;
3036             }
3037           else
3038             {
3039               gimple_assign_set_rhs1 (stmt, defop0);
3040               gimple_assign_set_rhs_code (stmt, CONVERT_EXPR);
3041               update_stmt (stmt);
3042               return remove_prop_source_from_use (op0) ? 2 : 1;
3043             }
3044         }
3045     }
3046
3047   return 0;
3048 }
3049
3050 /* Combine VIEW_CONVERT_EXPRs with their defining statement.  */
3051
3052 static bool
3053 simplify_vce (gimple_stmt_iterator *gsi)
3054 {
3055   gimple stmt = gsi_stmt (*gsi);
3056   tree type = TREE_TYPE (gimple_assign_lhs (stmt));
3057
3058   /* Drop useless VIEW_CONVERT_EXPRs.  */
3059   tree op = TREE_OPERAND (gimple_assign_rhs1 (stmt), 0);
3060   if (useless_type_conversion_p (type, TREE_TYPE (op)))
3061     {
3062       gimple_assign_set_rhs1 (stmt, op);
3063       update_stmt (stmt);
3064       return true;
3065     }
3066
3067   if (TREE_CODE (op) != SSA_NAME)
3068     return false;
3069
3070   gimple def_stmt = SSA_NAME_DEF_STMT (op);
3071   if (!is_gimple_assign (def_stmt))
3072     return false;
3073
3074   tree def_op = gimple_assign_rhs1 (def_stmt);
3075   switch (gimple_assign_rhs_code (def_stmt))
3076     {
3077     CASE_CONVERT:
3078       /* Strip integral conversions that do not change the precision.  */
3079       if ((INTEGRAL_TYPE_P (TREE_TYPE (op))
3080            || POINTER_TYPE_P (TREE_TYPE (op)))
3081           && (INTEGRAL_TYPE_P (TREE_TYPE (def_op))
3082               || POINTER_TYPE_P (TREE_TYPE (def_op)))
3083           && (TYPE_PRECISION (TREE_TYPE (op))
3084               == TYPE_PRECISION (TREE_TYPE (def_op))))
3085         {
3086           TREE_OPERAND (gimple_assign_rhs1 (stmt), 0) = def_op;
3087           update_stmt (stmt);
3088           return true;
3089         }
3090       break;
3091
3092     case VIEW_CONVERT_EXPR:
3093       /* Series of VIEW_CONVERT_EXPRs on register operands can
3094          be contracted.  */
3095       if (TREE_CODE (TREE_OPERAND (def_op, 0)) == SSA_NAME)
3096         {
3097           if (useless_type_conversion_p (type,
3098                                          TREE_TYPE (TREE_OPERAND (def_op, 0))))
3099             gimple_assign_set_rhs1 (stmt, TREE_OPERAND (def_op, 0));
3100           else
3101             TREE_OPERAND (gimple_assign_rhs1 (stmt), 0)
3102                 = TREE_OPERAND (def_op, 0);
3103           update_stmt (stmt);
3104           return true;
3105         }
3106
3107     default:;
3108     }
3109
3110   return false;
3111 }
3112
3113 /* Combine an element access with a shuffle.  Returns true if there were
3114    any changes made, else it returns false.  */
3115  
3116 static bool
3117 simplify_bitfield_ref (gimple_stmt_iterator *gsi)
3118 {
3119   gimple stmt = gsi_stmt (*gsi);
3120   gimple def_stmt;
3121   tree op, op0, op1, op2;
3122   tree elem_type;
3123   unsigned idx, n, size;
3124   enum tree_code code;
3125
3126   op = gimple_assign_rhs1 (stmt);
3127   gcc_checking_assert (TREE_CODE (op) == BIT_FIELD_REF);
3128
3129   op0 = TREE_OPERAND (op, 0);
3130   if (TREE_CODE (op0) != SSA_NAME
3131       || TREE_CODE (TREE_TYPE (op0)) != VECTOR_TYPE)
3132     return false;
3133
3134   def_stmt = get_prop_source_stmt (op0, false, NULL);
3135   if (!def_stmt || !can_propagate_from (def_stmt))
3136     return false;
3137
3138   op1 = TREE_OPERAND (op, 1);
3139   op2 = TREE_OPERAND (op, 2);
3140   code = gimple_assign_rhs_code (def_stmt);
3141
3142   if (code == CONSTRUCTOR)
3143     {
3144       tree tem = fold_ternary (BIT_FIELD_REF, TREE_TYPE (op),
3145                                gimple_assign_rhs1 (def_stmt), op1, op2);
3146       if (!tem || !valid_gimple_rhs_p (tem))
3147         return false;
3148       gimple_assign_set_rhs_from_tree (gsi, tem);
3149       update_stmt (gsi_stmt (*gsi));
3150       return true;
3151     }
3152
3153   elem_type = TREE_TYPE (TREE_TYPE (op0));
3154   if (TREE_TYPE (op) != elem_type)
3155     return false;
3156
3157   size = TREE_INT_CST_LOW (TYPE_SIZE (elem_type));
3158   n = TREE_INT_CST_LOW (op1) / size;
3159   if (n != 1)
3160     return false;
3161   idx = TREE_INT_CST_LOW (op2) / size;
3162
3163   if (code == VEC_PERM_EXPR)
3164     {
3165       tree p, m, index, tem;
3166       unsigned nelts;
3167       m = gimple_assign_rhs3 (def_stmt);
3168       if (TREE_CODE (m) != VECTOR_CST)
3169         return false;
3170       nelts = VECTOR_CST_NELTS (m);
3171       idx = TREE_INT_CST_LOW (VECTOR_CST_ELT (m, idx));
3172       idx %= 2 * nelts;
3173       if (idx < nelts)
3174         {
3175           p = gimple_assign_rhs1 (def_stmt);
3176         }
3177       else
3178         {
3179           p = gimple_assign_rhs2 (def_stmt);
3180           idx -= nelts;
3181         }
3182       index = build_int_cst (TREE_TYPE (TREE_TYPE (m)), idx * size);
3183       tem = build3 (BIT_FIELD_REF, TREE_TYPE (op),
3184                     unshare_expr (p), op1, index);
3185       gimple_assign_set_rhs1 (stmt, tem);
3186       fold_stmt (gsi);
3187       update_stmt (gsi_stmt (*gsi));
3188       return true;
3189     }
3190
3191   return false;
3192 }
3193
3194 /* Determine whether applying the 2 permutations (mask1 then mask2)
3195    gives back one of the input.  */
3196
3197 static int
3198 is_combined_permutation_identity (tree mask1, tree mask2)
3199 {
3200   tree mask;
3201   unsigned int nelts, i, j;
3202   bool maybe_identity1 = true;
3203   bool maybe_identity2 = true;
3204
3205   gcc_checking_assert (TREE_CODE (mask1) == VECTOR_CST
3206                        && TREE_CODE (mask2) == VECTOR_CST);
3207   mask = fold_ternary (VEC_PERM_EXPR, TREE_TYPE (mask1), mask1, mask1, mask2);
3208   gcc_assert (TREE_CODE (mask) == VECTOR_CST);
3209
3210   nelts = VECTOR_CST_NELTS (mask);
3211   for (i = 0; i < nelts; i++)
3212     {
3213       tree val = VECTOR_CST_ELT (mask, i);
3214       gcc_assert (TREE_CODE (val) == INTEGER_CST);
3215       j = TREE_INT_CST_LOW (val) & (2 * nelts - 1);
3216       if (j == i)
3217         maybe_identity2 = false;
3218       else if (j == i + nelts)
3219         maybe_identity1 = false;
3220       else
3221         return 0;
3222     }
3223   return maybe_identity1 ? 1 : maybe_identity2 ? 2 : 0;
3224 }
3225
3226 /* Combine a shuffle with its arguments.  Returns 1 if there were any
3227    changes made, 2 if cfg-cleanup needs to run.  Else it returns 0.  */
3228  
3229 static int
3230 simplify_permutation (gimple_stmt_iterator *gsi)
3231 {
3232   gimple stmt = gsi_stmt (*gsi);
3233   gimple def_stmt;
3234   tree op0, op1, op2, op3, arg0, arg1;
3235   enum tree_code code;
3236   bool single_use_op0 = false;
3237
3238   gcc_checking_assert (gimple_assign_rhs_code (stmt) == VEC_PERM_EXPR);
3239
3240   op0 = gimple_assign_rhs1 (stmt);
3241   op1 = gimple_assign_rhs2 (stmt);
3242   op2 = gimple_assign_rhs3 (stmt);
3243
3244   if (TREE_CODE (op2) != VECTOR_CST)
3245     return 0;
3246
3247   if (TREE_CODE (op0) == VECTOR_CST)
3248     {
3249       code = VECTOR_CST;
3250       arg0 = op0;
3251     }
3252   else if (TREE_CODE (op0) == SSA_NAME)
3253     {
3254       def_stmt = get_prop_source_stmt (op0, false, &single_use_op0);
3255       if (!def_stmt || !can_propagate_from (def_stmt))
3256         return 0;
3257
3258       code = gimple_assign_rhs_code (def_stmt);
3259       arg0 = gimple_assign_rhs1 (def_stmt);
3260     }
3261   else
3262     return 0;
3263
3264   /* Two consecutive shuffles.  */
3265   if (code == VEC_PERM_EXPR)
3266     {
3267       tree orig;
3268       int ident;
3269
3270       if (op0 != op1)
3271         return 0;
3272       op3 = gimple_assign_rhs3 (def_stmt);
3273       if (TREE_CODE (op3) != VECTOR_CST)
3274         return 0;
3275       ident = is_combined_permutation_identity (op3, op2);
3276       if (!ident)
3277         return 0;
3278       orig = (ident == 1) ? gimple_assign_rhs1 (def_stmt)
3279                           : gimple_assign_rhs2 (def_stmt);
3280       gimple_assign_set_rhs1 (stmt, unshare_expr (orig));
3281       gimple_assign_set_rhs_code (stmt, TREE_CODE (orig));
3282       gimple_set_num_ops (stmt, 2);
3283       update_stmt (stmt);
3284       return remove_prop_source_from_use (op0) ? 2 : 1;
3285     }
3286
3287   /* Shuffle of a constructor.  */
3288   else if (code == CONSTRUCTOR || code == VECTOR_CST)
3289     {
3290       tree opt;
3291       bool ret = false;
3292       if (op0 != op1)
3293         {
3294           if (TREE_CODE (op0) == SSA_NAME && !single_use_op0)
3295             return 0;
3296
3297           if (TREE_CODE (op1) == VECTOR_CST)
3298             arg1 = op1;
3299           else if (TREE_CODE (op1) == SSA_NAME)
3300             {
3301               enum tree_code code2;
3302
3303               gimple def_stmt2 = get_prop_source_stmt (op1, true, NULL);
3304               if (!def_stmt2 || !can_propagate_from (def_stmt2))
3305                 return 0;
3306
3307               code2 = gimple_assign_rhs_code (def_stmt2);
3308               if (code2 != CONSTRUCTOR && code2 != VECTOR_CST)
3309                 return 0;
3310               arg1 = gimple_assign_rhs1 (def_stmt2);
3311             }
3312           else
3313             return 0;
3314         }
3315       else
3316         {
3317           /* Already used twice in this statement.  */
3318           if (TREE_CODE (op0) == SSA_NAME && num_imm_uses (op0) > 2)
3319             return 0;
3320           arg1 = arg0;
3321         }
3322       opt = fold_ternary (VEC_PERM_EXPR, TREE_TYPE (op0), arg0, arg1, op2);
3323       if (!opt
3324           || (TREE_CODE (opt) != CONSTRUCTOR && TREE_CODE (opt) != VECTOR_CST))
3325         return 0;
3326       gimple_assign_set_rhs_from_tree (gsi, opt);
3327       update_stmt (gsi_stmt (*gsi));
3328       if (TREE_CODE (op0) == SSA_NAME)
3329         ret = remove_prop_source_from_use (op0);
3330       if (op0 != op1 && TREE_CODE (op1) == SSA_NAME)
3331         ret |= remove_prop_source_from_use (op1);
3332       return ret ? 2 : 1;
3333     }
3334
3335   return 0;
3336 }
3337
3338 /* Recognize a VEC_PERM_EXPR.  Returns true if there were any changes.  */
3339
3340 static bool
3341 simplify_vector_constructor (gimple_stmt_iterator *gsi)
3342 {
3343   gimple stmt = gsi_stmt (*gsi);
3344   gimple def_stmt;
3345   tree op, op2, orig, type, elem_type;
3346   unsigned elem_size, nelts, i;
3347   enum tree_code code;
3348   constructor_elt *elt;
3349   unsigned char *sel;
3350   bool maybe_ident;
3351
3352   gcc_checking_assert (gimple_assign_rhs_code (stmt) == CONSTRUCTOR);
3353
3354   op = gimple_assign_rhs1 (stmt);
3355   type = TREE_TYPE (op);
3356   gcc_checking_assert (TREE_CODE (type) == VECTOR_TYPE);
3357
3358   nelts = TYPE_VECTOR_SUBPARTS (type);
3359   elem_type = TREE_TYPE (type);
3360   elem_size = TREE_INT_CST_LOW (TYPE_SIZE (elem_type));
3361
3362   sel = XALLOCAVEC (unsigned char, nelts);
3363   orig = NULL;
3364   maybe_ident = true;
3365   FOR_EACH_VEC_SAFE_ELT (CONSTRUCTOR_ELTS (op), i, elt)
3366     {
3367       tree ref, op1;
3368
3369       if (i >= nelts)
3370         return false;
3371
3372       if (TREE_CODE (elt->value) != SSA_NAME)
3373         return false;
3374       def_stmt = get_prop_source_stmt (elt->value, false, NULL);
3375       if (!def_stmt)
3376         return false;
3377       code = gimple_assign_rhs_code (def_stmt);
3378       if (code != BIT_FIELD_REF)
3379         return false;
3380       op1 = gimple_assign_rhs1 (def_stmt);
3381       ref = TREE_OPERAND (op1, 0);
3382       if (orig)
3383         {
3384           if (ref != orig)
3385             return false;
3386         }
3387       else
3388         {
3389           if (TREE_CODE (ref) != SSA_NAME)
3390             return false;
3391           if (!useless_type_conversion_p (type, TREE_TYPE (ref)))
3392             return false;
3393           orig = ref;
3394         }
3395       if (TREE_INT_CST_LOW (TREE_OPERAND (op1, 1)) != elem_size)
3396         return false;
3397       sel[i] = TREE_INT_CST_LOW (TREE_OPERAND (op1, 2)) / elem_size;
3398       if (sel[i] != i) maybe_ident = false;
3399     }
3400   if (i < nelts)
3401     return false;
3402
3403   if (maybe_ident)
3404     gimple_assign_set_rhs_from_tree (gsi, orig);
3405   else
3406     {
3407       tree mask_type, *mask_elts;
3408
3409       if (!can_vec_perm_p (TYPE_MODE (type), false, sel))
3410         return false;
3411       mask_type
3412         = build_vector_type (build_nonstandard_integer_type (elem_size, 1),
3413                              nelts);
3414       if (GET_MODE_CLASS (TYPE_MODE (mask_type)) != MODE_VECTOR_INT
3415           || GET_MODE_SIZE (TYPE_MODE (mask_type))
3416              != GET_MODE_SIZE (TYPE_MODE (type)))
3417         return false;
3418       mask_elts = XALLOCAVEC (tree, nelts);
3419       for (i = 0; i < nelts; i++)
3420         mask_elts[i] = build_int_cst (TREE_TYPE (mask_type), sel[i]);
3421       op2 = build_vector (mask_type, mask_elts);
3422       gimple_assign_set_rhs_with_ops_1 (gsi, VEC_PERM_EXPR, orig, orig, op2);
3423     }
3424   update_stmt (gsi_stmt (*gsi));
3425   return true;
3426 }
3427
3428 /* Main entry point for the forward propagation and statement combine
3429    optimizer.  */
3430
3431 static unsigned int
3432 ssa_forward_propagate_and_combine (void)
3433 {
3434   basic_block bb;
3435   unsigned int todoflags = 0;
3436
3437   cfg_changed = false;
3438
3439   FOR_EACH_BB_FN (bb, cfun)
3440     {
3441       gimple_stmt_iterator gsi;
3442
3443       /* Apply forward propagation to all stmts in the basic-block.
3444          Note we update GSI within the loop as necessary.  */
3445       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
3446         {
3447           gimple stmt = gsi_stmt (gsi);
3448           tree lhs, rhs;
3449           enum tree_code code;
3450
3451           if (!is_gimple_assign (stmt))
3452             {
3453               gsi_next (&gsi);
3454               continue;
3455             }
3456
3457           lhs = gimple_assign_lhs (stmt);
3458           rhs = gimple_assign_rhs1 (stmt);
3459           code = gimple_assign_rhs_code (stmt);
3460           if (TREE_CODE (lhs) != SSA_NAME
3461               || has_zero_uses (lhs))
3462             {
3463               gsi_next (&gsi);
3464               continue;
3465             }
3466
3467           /* If this statement sets an SSA_NAME to an address,
3468              try to propagate the address into the uses of the SSA_NAME.  */
3469           if (code == ADDR_EXPR
3470               /* Handle pointer conversions on invariant addresses
3471                  as well, as this is valid gimple.  */
3472               || (CONVERT_EXPR_CODE_P (code)
3473                   && TREE_CODE (rhs) == ADDR_EXPR
3474                   && POINTER_TYPE_P (TREE_TYPE (lhs))))
3475             {
3476               tree base = get_base_address (TREE_OPERAND (rhs, 0));
3477               if ((!base
3478                    || !DECL_P (base)
3479                    || decl_address_invariant_p (base))
3480                   && !stmt_references_abnormal_ssa_name (stmt)
3481                   && forward_propagate_addr_expr (lhs, rhs, true))
3482                 {
3483                   release_defs (stmt);
3484                   gsi_remove (&gsi, true);
3485                 }
3486               else
3487                 gsi_next (&gsi);
3488             }
3489           else if (code == POINTER_PLUS_EXPR)
3490             {
3491               tree off = gimple_assign_rhs2 (stmt);
3492               if (TREE_CODE (off) == INTEGER_CST
3493                   && can_propagate_from (stmt)
3494                   && !simple_iv_increment_p (stmt)
3495                   /* ???  Better adjust the interface to that function
3496                      instead of building new trees here.  */
3497                   && forward_propagate_addr_expr
3498                        (lhs,
3499                         build1_loc (gimple_location (stmt),
3500                                     ADDR_EXPR, TREE_TYPE (rhs),
3501                                     fold_build2 (MEM_REF,
3502                                                  TREE_TYPE (TREE_TYPE (rhs)),
3503                                                  rhs,
3504                                                  fold_convert (ptr_type_node,
3505                                                                off))), true))
3506                 {
3507                   release_defs (stmt);
3508                   gsi_remove (&gsi, true);
3509                 }
3510               else if (is_gimple_min_invariant (rhs))
3511                 {
3512                   /* Make sure to fold &a[0] + off_1 here.  */
3513                   fold_stmt_inplace (&gsi);
3514                   update_stmt (stmt);
3515                   if (gimple_assign_rhs_code (stmt) == POINTER_PLUS_EXPR)
3516                     gsi_next (&gsi);
3517                 }
3518               else
3519                 gsi_next (&gsi);
3520             }
3521           else if (TREE_CODE_CLASS (code) == tcc_comparison)
3522             {
3523               if (forward_propagate_comparison (&gsi))
3524                 cfg_changed = true;
3525             }
3526           else
3527             gsi_next (&gsi);
3528         }
3529
3530       /* Combine stmts with the stmts defining their operands.
3531          Note we update GSI within the loop as necessary.  */
3532       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi);)
3533         {
3534           gimple stmt = gsi_stmt (gsi);
3535           bool changed = false;
3536
3537           /* Mark stmt as potentially needing revisiting.  */
3538           gimple_set_plf (stmt, GF_PLF_1, false);
3539
3540           switch (gimple_code (stmt))
3541             {
3542             case GIMPLE_ASSIGN:
3543               {
3544                 tree rhs1 = gimple_assign_rhs1 (stmt);
3545                 enum tree_code code = gimple_assign_rhs_code (stmt);
3546
3547                 if ((code == BIT_NOT_EXPR
3548                      || code == NEGATE_EXPR)
3549                     && TREE_CODE (rhs1) == SSA_NAME)
3550                   changed = simplify_not_neg_expr (&gsi);
3551                 else if (code == COND_EXPR
3552                          || code == VEC_COND_EXPR)
3553                   {
3554                     /* In this case the entire COND_EXPR is in rhs1. */
3555                     if (forward_propagate_into_cond (&gsi)
3556                         || combine_cond_exprs (&gsi))
3557                       {
3558                         changed = true;
3559                         stmt = gsi_stmt (gsi);
3560                       }
3561                   }
3562                 else if (TREE_CODE_CLASS (code) == tcc_comparison)
3563                   {
3564                     int did_something;
3565                     did_something = forward_propagate_into_comparison (&gsi);
3566                     if (did_something == 2)
3567                       cfg_changed = true;
3568                     changed = did_something != 0;
3569                   }
3570                 else if ((code == PLUS_EXPR
3571                           || code == BIT_IOR_EXPR
3572                           || code == BIT_XOR_EXPR)
3573                          && simplify_rotate (&gsi))
3574                   changed = true;
3575                 else if (code == BIT_AND_EXPR
3576                          || code == BIT_IOR_EXPR
3577                          || code == BIT_XOR_EXPR)
3578                   changed = simplify_bitwise_binary (&gsi);
3579                 else if (code == PLUS_EXPR
3580                          || code == MINUS_EXPR)
3581                   changed = associate_plusminus (&gsi);
3582                 else if (code == POINTER_PLUS_EXPR)
3583                   changed = associate_pointerplus (&gsi);
3584                 else if (CONVERT_EXPR_CODE_P (code)
3585                          || code == FLOAT_EXPR
3586                          || code == FIX_TRUNC_EXPR)
3587                   {
3588                     int did_something = combine_conversions (&gsi);
3589                     if (did_something == 2)
3590                       cfg_changed = true;
3591
3592                     /* If we have a narrowing conversion to an integral
3593                        type that is fed by a BIT_AND_EXPR, we might be
3594                        able to remove the BIT_AND_EXPR if it merely
3595                        masks off bits outside the final type (and nothing
3596                        else.  */
3597                     if (! did_something)
3598                       {
3599                         tree outer_type = TREE_TYPE (gimple_assign_lhs (stmt));
3600                         tree inner_type = TREE_TYPE (gimple_assign_rhs1 (stmt));
3601                         if (TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME
3602                             && INTEGRAL_TYPE_P (outer_type)
3603                             && INTEGRAL_TYPE_P (inner_type)
3604                             && (TYPE_PRECISION (outer_type)
3605                                 <= TYPE_PRECISION (inner_type)))
3606                           did_something = simplify_conversion_from_bitmask (&gsi);
3607                       }
3608                       
3609                     changed = did_something != 0;
3610                   }
3611                 else if (code == VIEW_CONVERT_EXPR)
3612                   changed = simplify_vce (&gsi);
3613                 else if (code == VEC_PERM_EXPR)
3614                   {
3615                     int did_something = simplify_permutation (&gsi);
3616                     if (did_something == 2)
3617                       cfg_changed = true;
3618                     changed = did_something != 0;
3619                   }
3620                 else if (code == BIT_FIELD_REF)
3621                   changed = simplify_bitfield_ref (&gsi);
3622                 else if (code == CONSTRUCTOR
3623                          && TREE_CODE (TREE_TYPE (rhs1)) == VECTOR_TYPE)
3624                   changed = simplify_vector_constructor (&gsi);
3625                 break;
3626               }
3627
3628             case GIMPLE_SWITCH:
3629               changed = simplify_gimple_switch (stmt);
3630               break;
3631
3632             case GIMPLE_COND:
3633               {
3634                 int did_something;
3635                 did_something = forward_propagate_into_gimple_cond (stmt);
3636                 if (did_something == 2)
3637                   cfg_changed = true;
3638                 changed = did_something != 0;
3639                 break;
3640               }
3641
3642             case GIMPLE_CALL:
3643               {
3644                 tree callee = gimple_call_fndecl (stmt);
3645                 if (callee != NULL_TREE
3646                     && DECL_BUILT_IN_CLASS (callee) == BUILT_IN_NORMAL)
3647                   changed = simplify_builtin_call (&gsi, callee);
3648                 break;
3649               }
3650
3651             default:;
3652             }
3653
3654           if (changed)
3655             {
3656               /* If the stmt changed then re-visit it and the statements
3657                  inserted before it.  */
3658               for (; !gsi_end_p (gsi); gsi_prev (&gsi))
3659                 if (gimple_plf (gsi_stmt (gsi), GF_PLF_1))
3660                   break;
3661               if (gsi_end_p (gsi))
3662                 gsi = gsi_start_bb (bb);
3663               else
3664                 gsi_next (&gsi);
3665             }
3666           else
3667             {
3668               /* Stmt no longer needs to be revisited.  */
3669               gimple_set_plf (stmt, GF_PLF_1, true);
3670               gsi_next (&gsi);
3671             }
3672         }
3673     }
3674
3675   if (cfg_changed)
3676     todoflags |= TODO_cleanup_cfg;
3677
3678   return todoflags;
3679 }
3680
3681
3682 static bool
3683 gate_forwprop (void)
3684 {
3685   return flag_tree_forwprop;
3686 }
3687
3688 namespace {
3689
3690 const pass_data pass_data_forwprop =
3691 {
3692   GIMPLE_PASS, /* type */
3693   "forwprop", /* name */
3694   OPTGROUP_NONE, /* optinfo_flags */
3695   true, /* has_gate */
3696   true, /* has_execute */
3697   TV_TREE_FORWPROP, /* tv_id */
3698   ( PROP_cfg | PROP_ssa ), /* properties_required */
3699   0, /* properties_provided */
3700   0, /* properties_destroyed */
3701   0, /* todo_flags_start */
3702   ( TODO_update_ssa | TODO_verify_ssa ), /* todo_flags_finish */
3703 };
3704
3705 class pass_forwprop : public gimple_opt_pass
3706 {
3707 public:
3708   pass_forwprop (gcc::context *ctxt)
3709     : gimple_opt_pass (pass_data_forwprop, ctxt)
3710   {}
3711
3712   /* opt_pass methods: */
3713   opt_pass * clone () { return new pass_forwprop (m_ctxt); }
3714   bool gate () { return gate_forwprop (); }
3715   unsigned int execute () { return ssa_forward_propagate_and_combine (); }
3716
3717 }; // class pass_forwprop
3718
3719 } // anon namespace
3720
3721 gimple_opt_pass *
3722 make_pass_forwprop (gcc::context *ctxt)
3723 {
3724   return new pass_forwprop (ctxt);
3725 }