2012-07-09 Tom de Vries <tom@codesourcery.com>
[official-gcc.git] / gcc / tree-ssa-phiopt.c
blob46d8a2c4e603bad441d96faebceedb539ba068b4
1 /* Optimization of PHI nodes by converting them into straightline code.
2 Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012
3 Free Software Foundation, Inc.
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 3, or (at your option) any
10 later version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "ggc.h"
26 #include "tree.h"
27 #include "flags.h"
28 #include "tm_p.h"
29 #include "basic-block.h"
30 #include "timevar.h"
31 #include "tree-flow.h"
32 #include "tree-pass.h"
33 #include "tree-dump.h"
34 #include "langhooks.h"
35 #include "pointer-set.h"
36 #include "domwalk.h"
37 #include "cfgloop.h"
38 #include "tree-data-ref.h"
39 #include "tree-pretty-print.h"
40 #include "gimple-pretty-print.h"
41 #include "insn-config.h"
42 #include "expr.h"
43 #include "optabs.h"
45 #ifndef HAVE_conditional_move
46 #define HAVE_conditional_move (0)
47 #endif
49 static unsigned int tree_ssa_phiopt (void);
50 static unsigned int tree_ssa_phiopt_worker (bool, bool);
51 static bool conditional_replacement (basic_block, basic_block,
52 edge, edge, gimple, tree, tree);
53 static int value_replacement (basic_block, basic_block,
54 edge, edge, gimple, tree, tree);
55 static bool minmax_replacement (basic_block, basic_block,
56 edge, edge, gimple, tree, tree);
57 static bool abs_replacement (basic_block, basic_block,
58 edge, edge, gimple, tree, tree);
59 static bool cond_store_replacement (basic_block, basic_block, edge, edge,
60 struct pointer_set_t *);
61 static bool cond_if_else_store_replacement (basic_block, basic_block, basic_block);
62 static struct pointer_set_t * get_non_trapping (void);
63 static void replace_phi_edge_with_variable (basic_block, edge, gimple, tree);
64 static void hoist_adjacent_loads (basic_block, basic_block,
65 basic_block, basic_block);
66 static bool gate_hoist_loads (void);
68 /* This pass tries to replaces an if-then-else block with an
69 assignment. We have four kinds of transformations. Some of these
70 transformations are also performed by the ifcvt RTL optimizer.
72 Conditional Replacement
73 -----------------------
75 This transformation, implemented in conditional_replacement,
76 replaces
78 bb0:
79 if (cond) goto bb2; else goto bb1;
80 bb1:
81 bb2:
82 x = PHI <0 (bb1), 1 (bb0), ...>;
84 with
86 bb0:
87 x' = cond;
88 goto bb2;
89 bb2:
90 x = PHI <x' (bb0), ...>;
92 We remove bb1 as it becomes unreachable. This occurs often due to
93 gimplification of conditionals.
95 Value Replacement
96 -----------------
98 This transformation, implemented in value_replacement, replaces
100 bb0:
101 if (a != b) goto bb2; else goto bb1;
102 bb1:
103 bb2:
104 x = PHI <a (bb1), b (bb0), ...>;
106 with
108 bb0:
109 bb2:
110 x = PHI <b (bb0), ...>;
112 This opportunity can sometimes occur as a result of other
113 optimizations.
115 ABS Replacement
116 ---------------
118 This transformation, implemented in abs_replacement, replaces
120 bb0:
121 if (a >= 0) goto bb2; else goto bb1;
122 bb1:
123 x = -a;
124 bb2:
125 x = PHI <x (bb1), a (bb0), ...>;
127 with
129 bb0:
130 x' = ABS_EXPR< a >;
131 bb2:
132 x = PHI <x' (bb0), ...>;
134 MIN/MAX Replacement
135 -------------------
137 This transformation, minmax_replacement replaces
139 bb0:
140 if (a <= b) goto bb2; else goto bb1;
141 bb1:
142 bb2:
143 x = PHI <b (bb1), a (bb0), ...>;
145 with
147 bb0:
148 x' = MIN_EXPR (a, b)
149 bb2:
150 x = PHI <x' (bb0), ...>;
152 A similar transformation is done for MAX_EXPR.
155 This pass also performs a fifth transformation of a slightly different
156 flavor.
158 Adjacent Load Hoisting
159 ----------------------
161 This transformation replaces
163 bb0:
164 if (...) goto bb2; else goto bb1;
165 bb1:
166 x1 = (<expr>).field1;
167 goto bb3;
168 bb2:
169 x2 = (<expr>).field2;
170 bb3:
171 # x = PHI <x1, x2>;
173 with
175 bb0:
176 x1 = (<expr>).field1;
177 x2 = (<expr>).field2;
178 if (...) goto bb2; else goto bb1;
179 bb1:
180 goto bb3;
181 bb2:
182 bb3:
183 # x = PHI <x1, x2>;
185 The purpose of this transformation is to enable generation of conditional
186 move instructions such as Intel CMOVE or PowerPC ISEL. Because one of
187 the loads is speculative, the transformation is restricted to very
188 specific cases to avoid introducing a page fault. We are looking for
189 the common idiom:
191 if (...)
192 x = y->left;
193 else
194 x = y->right;
196 where left and right are typically adjacent pointers in a tree structure. */
198 static unsigned int
199 tree_ssa_phiopt (void)
201 return tree_ssa_phiopt_worker (false, gate_hoist_loads ());
204 /* This pass tries to transform conditional stores into unconditional
205 ones, enabling further simplifications with the simpler then and else
206 blocks. In particular it replaces this:
208 bb0:
209 if (cond) goto bb2; else goto bb1;
210 bb1:
211 *p = RHS;
212 bb2:
214 with
216 bb0:
217 if (cond) goto bb1; else goto bb2;
218 bb1:
219 condtmp' = *p;
220 bb2:
221 condtmp = PHI <RHS, condtmp'>
222 *p = condtmp;
224 This transformation can only be done under several constraints,
225 documented below. It also replaces:
227 bb0:
228 if (cond) goto bb2; else goto bb1;
229 bb1:
230 *p = RHS1;
231 goto bb3;
232 bb2:
233 *p = RHS2;
234 bb3:
236 with
238 bb0:
239 if (cond) goto bb3; else goto bb1;
240 bb1:
241 bb3:
242 condtmp = PHI <RHS1, RHS2>
243 *p = condtmp; */
245 static unsigned int
246 tree_ssa_cs_elim (void)
248 return tree_ssa_phiopt_worker (true, false);
251 /* Return the singleton PHI in the SEQ of PHIs for edges E0 and E1. */
253 static gimple
254 single_non_singleton_phi_for_edges (gimple_seq seq, edge e0, edge e1)
256 gimple_stmt_iterator i;
257 gimple phi = NULL;
258 if (gimple_seq_singleton_p (seq))
259 return gsi_stmt (gsi_start (seq));
260 for (i = gsi_start (seq); !gsi_end_p (i); gsi_next (&i))
262 gimple p = gsi_stmt (i);
263 /* If the PHI arguments are equal then we can skip this PHI. */
264 if (operand_equal_for_phi_arg_p (gimple_phi_arg_def (p, e0->dest_idx),
265 gimple_phi_arg_def (p, e1->dest_idx)))
266 continue;
268 /* If we already have a PHI that has the two edge arguments are
269 different, then return it is not a singleton for these PHIs. */
270 if (phi)
271 return NULL;
273 phi = p;
275 return phi;
278 /* For conditional store replacement we need a temporary to
279 put the old contents of the memory in. */
280 static tree condstoretemp;
282 /* The core routine of conditional store replacement and normal
283 phi optimizations. Both share much of the infrastructure in how
284 to match applicable basic block patterns. DO_STORE_ELIM is true
285 when we want to do conditional store replacement, false otherwise.
286 DO_HOIST_LOADS is true when we want to hoist adjacent loads out
287 of diamond control flow patterns, false otherwise. */
288 static unsigned int
289 tree_ssa_phiopt_worker (bool do_store_elim, bool do_hoist_loads)
291 basic_block bb;
292 basic_block *bb_order;
293 unsigned n, i;
294 bool cfgchanged = false;
295 struct pointer_set_t *nontrap = 0;
297 if (do_store_elim)
299 condstoretemp = NULL_TREE;
300 /* Calculate the set of non-trapping memory accesses. */
301 nontrap = get_non_trapping ();
304 /* Search every basic block for COND_EXPR we may be able to optimize.
306 We walk the blocks in order that guarantees that a block with
307 a single predecessor is processed before the predecessor.
308 This ensures that we collapse inner ifs before visiting the
309 outer ones, and also that we do not try to visit a removed
310 block. */
311 bb_order = blocks_in_phiopt_order ();
312 n = n_basic_blocks - NUM_FIXED_BLOCKS;
314 for (i = 0; i < n; i++)
316 gimple cond_stmt, phi;
317 basic_block bb1, bb2;
318 edge e1, e2;
319 tree arg0, arg1;
321 bb = bb_order[i];
323 cond_stmt = last_stmt (bb);
324 /* Check to see if the last statement is a GIMPLE_COND. */
325 if (!cond_stmt
326 || gimple_code (cond_stmt) != GIMPLE_COND)
327 continue;
329 e1 = EDGE_SUCC (bb, 0);
330 bb1 = e1->dest;
331 e2 = EDGE_SUCC (bb, 1);
332 bb2 = e2->dest;
334 /* We cannot do the optimization on abnormal edges. */
335 if ((e1->flags & EDGE_ABNORMAL) != 0
336 || (e2->flags & EDGE_ABNORMAL) != 0)
337 continue;
339 /* If either bb1's succ or bb2 or bb2's succ is non NULL. */
340 if (EDGE_COUNT (bb1->succs) == 0
341 || bb2 == NULL
342 || EDGE_COUNT (bb2->succs) == 0)
343 continue;
345 /* Find the bb which is the fall through to the other. */
346 if (EDGE_SUCC (bb1, 0)->dest == bb2)
348 else if (EDGE_SUCC (bb2, 0)->dest == bb1)
350 basic_block bb_tmp = bb1;
351 edge e_tmp = e1;
352 bb1 = bb2;
353 bb2 = bb_tmp;
354 e1 = e2;
355 e2 = e_tmp;
357 else if (do_store_elim
358 && EDGE_SUCC (bb1, 0)->dest == EDGE_SUCC (bb2, 0)->dest)
360 basic_block bb3 = EDGE_SUCC (bb1, 0)->dest;
362 if (!single_succ_p (bb1)
363 || (EDGE_SUCC (bb1, 0)->flags & EDGE_FALLTHRU) == 0
364 || !single_succ_p (bb2)
365 || (EDGE_SUCC (bb2, 0)->flags & EDGE_FALLTHRU) == 0
366 || EDGE_COUNT (bb3->preds) != 2)
367 continue;
368 if (cond_if_else_store_replacement (bb1, bb2, bb3))
369 cfgchanged = true;
370 continue;
372 else if (do_hoist_loads
373 && EDGE_SUCC (bb1, 0)->dest == EDGE_SUCC (bb2, 0)->dest)
375 basic_block bb3 = EDGE_SUCC (bb1, 0)->dest;
377 if (!FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (cond_stmt)))
378 && single_succ_p (bb1)
379 && single_succ_p (bb2)
380 && single_pred_p (bb1)
381 && single_pred_p (bb2)
382 && EDGE_COUNT (bb->succs) == 2
383 && EDGE_COUNT (bb3->preds) == 2
384 /* If one edge or the other is dominant, a conditional move
385 is likely to perform worse than the well-predicted branch. */
386 && !predictable_edge_p (EDGE_SUCC (bb, 0))
387 && !predictable_edge_p (EDGE_SUCC (bb, 1)))
388 hoist_adjacent_loads (bb, bb1, bb2, bb3);
389 continue;
391 else
392 continue;
394 e1 = EDGE_SUCC (bb1, 0);
396 /* Make sure that bb1 is just a fall through. */
397 if (!single_succ_p (bb1)
398 || (e1->flags & EDGE_FALLTHRU) == 0)
399 continue;
401 /* Also make sure that bb1 only have one predecessor and that it
402 is bb. */
403 if (!single_pred_p (bb1)
404 || single_pred (bb1) != bb)
405 continue;
407 if (do_store_elim)
409 /* bb1 is the middle block, bb2 the join block, bb the split block,
410 e1 the fallthrough edge from bb1 to bb2. We can't do the
411 optimization if the join block has more than two predecessors. */
412 if (EDGE_COUNT (bb2->preds) > 2)
413 continue;
414 if (cond_store_replacement (bb1, bb2, e1, e2, nontrap))
415 cfgchanged = true;
417 else
419 gimple_seq phis = phi_nodes (bb2);
420 gimple_stmt_iterator gsi;
421 bool candorest = true;
423 /* Value replacement can work with more than one PHI
424 so try that first. */
425 for (gsi = gsi_start (phis); !gsi_end_p (gsi); gsi_next (&gsi))
427 phi = gsi_stmt (gsi);
428 arg0 = gimple_phi_arg_def (phi, e1->dest_idx);
429 arg1 = gimple_phi_arg_def (phi, e2->dest_idx);
430 if (value_replacement (bb, bb1, e1, e2, phi, arg0, arg1) == 2)
432 candorest = false;
433 cfgchanged = true;
434 break;
438 if (!candorest)
439 continue;
441 phi = single_non_singleton_phi_for_edges (phis, e1, e2);
442 if (!phi)
443 continue;
445 arg0 = gimple_phi_arg_def (phi, e1->dest_idx);
446 arg1 = gimple_phi_arg_def (phi, e2->dest_idx);
448 /* Something is wrong if we cannot find the arguments in the PHI
449 node. */
450 gcc_assert (arg0 != NULL && arg1 != NULL);
452 /* Do the replacement of conditional if it can be done. */
453 if (conditional_replacement (bb, bb1, e1, e2, phi, arg0, arg1))
454 cfgchanged = true;
455 else if (abs_replacement (bb, bb1, e1, e2, phi, arg0, arg1))
456 cfgchanged = true;
457 else if (minmax_replacement (bb, bb1, e1, e2, phi, arg0, arg1))
458 cfgchanged = true;
462 free (bb_order);
464 if (do_store_elim)
465 pointer_set_destroy (nontrap);
466 /* If the CFG has changed, we should cleanup the CFG. */
467 if (cfgchanged && do_store_elim)
469 /* In cond-store replacement we have added some loads on edges
470 and new VOPS (as we moved the store, and created a load). */
471 gsi_commit_edge_inserts ();
472 return TODO_cleanup_cfg | TODO_update_ssa_only_virtuals;
474 else if (cfgchanged)
475 return TODO_cleanup_cfg;
476 return 0;
479 /* Returns the list of basic blocks in the function in an order that guarantees
480 that if a block X has just a single predecessor Y, then Y is after X in the
481 ordering. */
483 basic_block *
484 blocks_in_phiopt_order (void)
486 basic_block x, y;
487 basic_block *order = XNEWVEC (basic_block, n_basic_blocks);
488 unsigned n = n_basic_blocks - NUM_FIXED_BLOCKS;
489 unsigned np, i;
490 sbitmap visited = sbitmap_alloc (last_basic_block);
492 #define MARK_VISITED(BB) (SET_BIT (visited, (BB)->index))
493 #define VISITED_P(BB) (TEST_BIT (visited, (BB)->index))
495 sbitmap_zero (visited);
497 MARK_VISITED (ENTRY_BLOCK_PTR);
498 FOR_EACH_BB (x)
500 if (VISITED_P (x))
501 continue;
503 /* Walk the predecessors of x as long as they have precisely one
504 predecessor and add them to the list, so that they get stored
505 after x. */
506 for (y = x, np = 1;
507 single_pred_p (y) && !VISITED_P (single_pred (y));
508 y = single_pred (y))
509 np++;
510 for (y = x, i = n - np;
511 single_pred_p (y) && !VISITED_P (single_pred (y));
512 y = single_pred (y), i++)
514 order[i] = y;
515 MARK_VISITED (y);
517 order[i] = y;
518 MARK_VISITED (y);
520 gcc_assert (i == n - 1);
521 n -= np;
524 sbitmap_free (visited);
525 gcc_assert (n == 0);
526 return order;
528 #undef MARK_VISITED
529 #undef VISITED_P
533 /* Return TRUE if block BB has no executable statements, otherwise return
534 FALSE. */
536 bool
537 empty_block_p (basic_block bb)
539 /* BB must have no executable statements. */
540 gimple_stmt_iterator gsi = gsi_after_labels (bb);
541 if (phi_nodes (bb))
542 return false;
543 if (gsi_end_p (gsi))
544 return true;
545 if (is_gimple_debug (gsi_stmt (gsi)))
546 gsi_next_nondebug (&gsi);
547 return gsi_end_p (gsi);
550 /* Replace PHI node element whose edge is E in block BB with variable NEW.
551 Remove the edge from COND_BLOCK which does not lead to BB (COND_BLOCK
552 is known to have two edges, one of which must reach BB). */
554 static void
555 replace_phi_edge_with_variable (basic_block cond_block,
556 edge e, gimple phi, tree new_tree)
558 basic_block bb = gimple_bb (phi);
559 basic_block block_to_remove;
560 gimple_stmt_iterator gsi;
562 /* Change the PHI argument to new. */
563 SET_USE (PHI_ARG_DEF_PTR (phi, e->dest_idx), new_tree);
565 /* Remove the empty basic block. */
566 if (EDGE_SUCC (cond_block, 0)->dest == bb)
568 EDGE_SUCC (cond_block, 0)->flags |= EDGE_FALLTHRU;
569 EDGE_SUCC (cond_block, 0)->flags &= ~(EDGE_TRUE_VALUE | EDGE_FALSE_VALUE);
570 EDGE_SUCC (cond_block, 0)->probability = REG_BR_PROB_BASE;
571 EDGE_SUCC (cond_block, 0)->count += EDGE_SUCC (cond_block, 1)->count;
573 block_to_remove = EDGE_SUCC (cond_block, 1)->dest;
575 else
577 EDGE_SUCC (cond_block, 1)->flags |= EDGE_FALLTHRU;
578 EDGE_SUCC (cond_block, 1)->flags
579 &= ~(EDGE_TRUE_VALUE | EDGE_FALSE_VALUE);
580 EDGE_SUCC (cond_block, 1)->probability = REG_BR_PROB_BASE;
581 EDGE_SUCC (cond_block, 1)->count += EDGE_SUCC (cond_block, 0)->count;
583 block_to_remove = EDGE_SUCC (cond_block, 0)->dest;
585 delete_basic_block (block_to_remove);
587 /* Eliminate the COND_EXPR at the end of COND_BLOCK. */
588 gsi = gsi_last_bb (cond_block);
589 gsi_remove (&gsi, true);
591 if (dump_file && (dump_flags & TDF_DETAILS))
592 fprintf (dump_file,
593 "COND_EXPR in block %d and PHI in block %d converted to straightline code.\n",
594 cond_block->index,
595 bb->index);
598 /* The function conditional_replacement does the main work of doing the
599 conditional replacement. Return true if the replacement is done.
600 Otherwise return false.
601 BB is the basic block where the replacement is going to be done on. ARG0
602 is argument 0 from PHI. Likewise for ARG1. */
604 static bool
605 conditional_replacement (basic_block cond_bb, basic_block middle_bb,
606 edge e0, edge e1, gimple phi,
607 tree arg0, tree arg1)
609 tree result;
610 gimple stmt, new_stmt;
611 tree cond;
612 gimple_stmt_iterator gsi;
613 edge true_edge, false_edge;
614 tree new_var, new_var2;
615 bool neg;
617 /* FIXME: Gimplification of complex type is too hard for now. */
618 /* We aren't prepared to handle vectors either (and it is a question
619 if it would be worthwhile anyway). */
620 if (!(INTEGRAL_TYPE_P (TREE_TYPE (arg0))
621 || POINTER_TYPE_P (TREE_TYPE (arg0)))
622 || !(INTEGRAL_TYPE_P (TREE_TYPE (arg1))
623 || POINTER_TYPE_P (TREE_TYPE (arg1))))
624 return false;
626 /* The PHI arguments have the constants 0 and 1, or 0 and -1, then
627 convert it to the conditional. */
628 if ((integer_zerop (arg0) && integer_onep (arg1))
629 || (integer_zerop (arg1) && integer_onep (arg0)))
630 neg = false;
631 else if ((integer_zerop (arg0) && integer_all_onesp (arg1))
632 || (integer_zerop (arg1) && integer_all_onesp (arg0)))
633 neg = true;
634 else
635 return false;
637 if (!empty_block_p (middle_bb))
638 return false;
640 /* At this point we know we have a GIMPLE_COND with two successors.
641 One successor is BB, the other successor is an empty block which
642 falls through into BB.
644 There is a single PHI node at the join point (BB) and its arguments
645 are constants (0, 1) or (0, -1).
647 So, given the condition COND, and the two PHI arguments, we can
648 rewrite this PHI into non-branching code:
650 dest = (COND) or dest = COND'
652 We use the condition as-is if the argument associated with the
653 true edge has the value one or the argument associated with the
654 false edge as the value zero. Note that those conditions are not
655 the same since only one of the outgoing edges from the GIMPLE_COND
656 will directly reach BB and thus be associated with an argument. */
658 stmt = last_stmt (cond_bb);
659 result = PHI_RESULT (phi);
661 /* To handle special cases like floating point comparison, it is easier and
662 less error-prone to build a tree and gimplify it on the fly though it is
663 less efficient. */
664 cond = fold_build2_loc (gimple_location (stmt),
665 gimple_cond_code (stmt), boolean_type_node,
666 gimple_cond_lhs (stmt), gimple_cond_rhs (stmt));
668 /* We need to know which is the true edge and which is the false
669 edge so that we know when to invert the condition below. */
670 extract_true_false_edges_from_block (cond_bb, &true_edge, &false_edge);
671 if ((e0 == true_edge && integer_zerop (arg0))
672 || (e0 == false_edge && !integer_zerop (arg0))
673 || (e1 == true_edge && integer_zerop (arg1))
674 || (e1 == false_edge && !integer_zerop (arg1)))
675 cond = fold_build1_loc (gimple_location (stmt),
676 TRUTH_NOT_EXPR, TREE_TYPE (cond), cond);
678 if (neg)
680 cond = fold_convert_loc (gimple_location (stmt),
681 TREE_TYPE (result), cond);
682 cond = fold_build1_loc (gimple_location (stmt),
683 NEGATE_EXPR, TREE_TYPE (cond), cond);
686 /* Insert our new statements at the end of conditional block before the
687 COND_STMT. */
688 gsi = gsi_for_stmt (stmt);
689 new_var = force_gimple_operand_gsi (&gsi, cond, true, NULL, true,
690 GSI_SAME_STMT);
692 if (!useless_type_conversion_p (TREE_TYPE (result), TREE_TYPE (new_var)))
694 source_location locus_0, locus_1;
696 new_var2 = create_tmp_var (TREE_TYPE (result), NULL);
697 add_referenced_var (new_var2);
698 new_stmt = gimple_build_assign_with_ops (CONVERT_EXPR, new_var2,
699 new_var, NULL);
700 new_var2 = make_ssa_name (new_var2, new_stmt);
701 gimple_assign_set_lhs (new_stmt, new_var2);
702 gsi_insert_before (&gsi, new_stmt, GSI_SAME_STMT);
703 new_var = new_var2;
705 /* Set the locus to the first argument, unless is doesn't have one. */
706 locus_0 = gimple_phi_arg_location (phi, 0);
707 locus_1 = gimple_phi_arg_location (phi, 1);
708 if (locus_0 == UNKNOWN_LOCATION)
709 locus_0 = locus_1;
710 gimple_set_location (new_stmt, locus_0);
713 replace_phi_edge_with_variable (cond_bb, e1, phi, new_var);
715 /* Note that we optimized this PHI. */
716 return true;
719 /* Update *ARG which is defined in STMT so that it contains the
720 computed value if that seems profitable. Return true if the
721 statement is made dead by that rewriting. */
723 static bool
724 jump_function_from_stmt (tree *arg, gimple stmt)
726 enum tree_code code = gimple_assign_rhs_code (stmt);
727 if (code == ADDR_EXPR)
729 /* For arg = &p->i transform it to p, if possible. */
730 tree rhs1 = gimple_assign_rhs1 (stmt);
731 HOST_WIDE_INT offset;
732 tree tem = get_addr_base_and_unit_offset (TREE_OPERAND (rhs1, 0),
733 &offset);
734 if (tem
735 && TREE_CODE (tem) == MEM_REF
736 && double_int_zero_p
737 (double_int_add (mem_ref_offset (tem),
738 shwi_to_double_int (offset))))
740 *arg = TREE_OPERAND (tem, 0);
741 return true;
744 /* TODO: Much like IPA-CP jump-functions we want to handle constant
745 additions symbolically here, and we'd need to update the comparison
746 code that compares the arg + cst tuples in our caller. For now the
747 code above exactly handles the VEC_BASE pattern from vec.h. */
748 return false;
751 /* The function value_replacement does the main work of doing the value
752 replacement. Return non-zero if the replacement is done. Otherwise return
753 0. If we remove the middle basic block, return 2.
754 BB is the basic block where the replacement is going to be done on. ARG0
755 is argument 0 from the PHI. Likewise for ARG1. */
757 static int
758 value_replacement (basic_block cond_bb, basic_block middle_bb,
759 edge e0, edge e1, gimple phi,
760 tree arg0, tree arg1)
762 gimple_stmt_iterator gsi;
763 gimple cond;
764 edge true_edge, false_edge;
765 enum tree_code code;
766 bool emtpy_or_with_defined_p = true;
768 /* If the type says honor signed zeros we cannot do this
769 optimization. */
770 if (HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (arg1))))
771 return 0;
773 /* If there is a statement in MIDDLE_BB that defines one of the PHI
774 arguments, then adjust arg0 or arg1. */
775 gsi = gsi_after_labels (middle_bb);
776 if (!gsi_end_p (gsi) && is_gimple_debug (gsi_stmt (gsi)))
777 gsi_next_nondebug (&gsi);
778 while (!gsi_end_p (gsi))
780 gimple stmt = gsi_stmt (gsi);
781 tree lhs;
782 gsi_next_nondebug (&gsi);
783 if (!is_gimple_assign (stmt))
785 emtpy_or_with_defined_p = false;
786 continue;
788 /* Now try to adjust arg0 or arg1 according to the computation
789 in the statement. */
790 lhs = gimple_assign_lhs (stmt);
791 if (!(lhs == arg0
792 && jump_function_from_stmt (&arg0, stmt))
793 || (lhs == arg1
794 && jump_function_from_stmt (&arg1, stmt)))
795 emtpy_or_with_defined_p = false;
798 cond = last_stmt (cond_bb);
799 code = gimple_cond_code (cond);
801 /* This transformation is only valid for equality comparisons. */
802 if (code != NE_EXPR && code != EQ_EXPR)
803 return 0;
805 /* We need to know which is the true edge and which is the false
806 edge so that we know if have abs or negative abs. */
807 extract_true_false_edges_from_block (cond_bb, &true_edge, &false_edge);
809 /* At this point we know we have a COND_EXPR with two successors.
810 One successor is BB, the other successor is an empty block which
811 falls through into BB.
813 The condition for the COND_EXPR is known to be NE_EXPR or EQ_EXPR.
815 There is a single PHI node at the join point (BB) with two arguments.
817 We now need to verify that the two arguments in the PHI node match
818 the two arguments to the equality comparison. */
820 if ((operand_equal_for_phi_arg_p (arg0, gimple_cond_lhs (cond))
821 && operand_equal_for_phi_arg_p (arg1, gimple_cond_rhs (cond)))
822 || (operand_equal_for_phi_arg_p (arg1, gimple_cond_lhs (cond))
823 && operand_equal_for_phi_arg_p (arg0, gimple_cond_rhs (cond))))
825 edge e;
826 tree arg;
828 /* For NE_EXPR, we want to build an assignment result = arg where
829 arg is the PHI argument associated with the true edge. For
830 EQ_EXPR we want the PHI argument associated with the false edge. */
831 e = (code == NE_EXPR ? true_edge : false_edge);
833 /* Unfortunately, E may not reach BB (it may instead have gone to
834 OTHER_BLOCK). If that is the case, then we want the single outgoing
835 edge from OTHER_BLOCK which reaches BB and represents the desired
836 path from COND_BLOCK. */
837 if (e->dest == middle_bb)
838 e = single_succ_edge (e->dest);
840 /* Now we know the incoming edge to BB that has the argument for the
841 RHS of our new assignment statement. */
842 if (e0 == e)
843 arg = arg0;
844 else
845 arg = arg1;
847 /* If the middle basic block was empty or is defining the
848 PHI arguments and this is a single phi where the args are different
849 for the edges e0 and e1 then we can remove the middle basic block. */
850 if (emtpy_or_with_defined_p
851 && single_non_singleton_phi_for_edges (phi_nodes (gimple_bb (phi)),
852 e0, e1))
854 replace_phi_edge_with_variable (cond_bb, e1, phi, arg);
855 /* Note that we optimized this PHI. */
856 return 2;
858 else
860 /* Replace the PHI arguments with arg. */
861 SET_PHI_ARG_DEF (phi, e0->dest_idx, arg);
862 SET_PHI_ARG_DEF (phi, e1->dest_idx, arg);
863 if (dump_file && (dump_flags & TDF_DETAILS))
865 fprintf (dump_file, "PHI ");
866 print_generic_expr (dump_file, gimple_phi_result (phi), 0);
867 fprintf (dump_file, " reduced for COND_EXPR in block %d to ",
868 cond_bb->index);
869 print_generic_expr (dump_file, arg, 0);
870 fprintf (dump_file, ".\n");
872 return 1;
876 return 0;
879 /* The function minmax_replacement does the main work of doing the minmax
880 replacement. Return true if the replacement is done. Otherwise return
881 false.
882 BB is the basic block where the replacement is going to be done on. ARG0
883 is argument 0 from the PHI. Likewise for ARG1. */
885 static bool
886 minmax_replacement (basic_block cond_bb, basic_block middle_bb,
887 edge e0, edge e1, gimple phi,
888 tree arg0, tree arg1)
890 tree result, type;
891 gimple cond, new_stmt;
892 edge true_edge, false_edge;
893 enum tree_code cmp, minmax, ass_code;
894 tree smaller, larger, arg_true, arg_false;
895 gimple_stmt_iterator gsi, gsi_from;
897 type = TREE_TYPE (PHI_RESULT (phi));
899 /* The optimization may be unsafe due to NaNs. */
900 if (HONOR_NANS (TYPE_MODE (type)))
901 return false;
903 cond = last_stmt (cond_bb);
904 cmp = gimple_cond_code (cond);
906 /* This transformation is only valid for order comparisons. Record which
907 operand is smaller/larger if the result of the comparison is true. */
908 if (cmp == LT_EXPR || cmp == LE_EXPR)
910 smaller = gimple_cond_lhs (cond);
911 larger = gimple_cond_rhs (cond);
913 else if (cmp == GT_EXPR || cmp == GE_EXPR)
915 smaller = gimple_cond_rhs (cond);
916 larger = gimple_cond_lhs (cond);
918 else
919 return false;
921 /* We need to know which is the true edge and which is the false
922 edge so that we know if have abs or negative abs. */
923 extract_true_false_edges_from_block (cond_bb, &true_edge, &false_edge);
925 /* Forward the edges over the middle basic block. */
926 if (true_edge->dest == middle_bb)
927 true_edge = EDGE_SUCC (true_edge->dest, 0);
928 if (false_edge->dest == middle_bb)
929 false_edge = EDGE_SUCC (false_edge->dest, 0);
931 if (true_edge == e0)
933 gcc_assert (false_edge == e1);
934 arg_true = arg0;
935 arg_false = arg1;
937 else
939 gcc_assert (false_edge == e0);
940 gcc_assert (true_edge == e1);
941 arg_true = arg1;
942 arg_false = arg0;
945 if (empty_block_p (middle_bb))
947 if (operand_equal_for_phi_arg_p (arg_true, smaller)
948 && operand_equal_for_phi_arg_p (arg_false, larger))
950 /* Case
952 if (smaller < larger)
953 rslt = smaller;
954 else
955 rslt = larger; */
956 minmax = MIN_EXPR;
958 else if (operand_equal_for_phi_arg_p (arg_false, smaller)
959 && operand_equal_for_phi_arg_p (arg_true, larger))
960 minmax = MAX_EXPR;
961 else
962 return false;
964 else
966 /* Recognize the following case, assuming d <= u:
968 if (a <= u)
969 b = MAX (a, d);
970 x = PHI <b, u>
972 This is equivalent to
974 b = MAX (a, d);
975 x = MIN (b, u); */
977 gimple assign = last_and_only_stmt (middle_bb);
978 tree lhs, op0, op1, bound;
980 if (!assign
981 || gimple_code (assign) != GIMPLE_ASSIGN)
982 return false;
984 lhs = gimple_assign_lhs (assign);
985 ass_code = gimple_assign_rhs_code (assign);
986 if (ass_code != MAX_EXPR && ass_code != MIN_EXPR)
987 return false;
988 op0 = gimple_assign_rhs1 (assign);
989 op1 = gimple_assign_rhs2 (assign);
991 if (true_edge->src == middle_bb)
993 /* We got here if the condition is true, i.e., SMALLER < LARGER. */
994 if (!operand_equal_for_phi_arg_p (lhs, arg_true))
995 return false;
997 if (operand_equal_for_phi_arg_p (arg_false, larger))
999 /* Case
1001 if (smaller < larger)
1003 r' = MAX_EXPR (smaller, bound)
1005 r = PHI <r', larger> --> to be turned to MIN_EXPR. */
1006 if (ass_code != MAX_EXPR)
1007 return false;
1009 minmax = MIN_EXPR;
1010 if (operand_equal_for_phi_arg_p (op0, smaller))
1011 bound = op1;
1012 else if (operand_equal_for_phi_arg_p (op1, smaller))
1013 bound = op0;
1014 else
1015 return false;
1017 /* We need BOUND <= LARGER. */
1018 if (!integer_nonzerop (fold_build2 (LE_EXPR, boolean_type_node,
1019 bound, larger)))
1020 return false;
1022 else if (operand_equal_for_phi_arg_p (arg_false, smaller))
1024 /* Case
1026 if (smaller < larger)
1028 r' = MIN_EXPR (larger, bound)
1030 r = PHI <r', smaller> --> to be turned to MAX_EXPR. */
1031 if (ass_code != MIN_EXPR)
1032 return false;
1034 minmax = MAX_EXPR;
1035 if (operand_equal_for_phi_arg_p (op0, larger))
1036 bound = op1;
1037 else if (operand_equal_for_phi_arg_p (op1, larger))
1038 bound = op0;
1039 else
1040 return false;
1042 /* We need BOUND >= SMALLER. */
1043 if (!integer_nonzerop (fold_build2 (GE_EXPR, boolean_type_node,
1044 bound, smaller)))
1045 return false;
1047 else
1048 return false;
1050 else
1052 /* We got here if the condition is false, i.e., SMALLER > LARGER. */
1053 if (!operand_equal_for_phi_arg_p (lhs, arg_false))
1054 return false;
1056 if (operand_equal_for_phi_arg_p (arg_true, larger))
1058 /* Case
1060 if (smaller > larger)
1062 r' = MIN_EXPR (smaller, bound)
1064 r = PHI <r', larger> --> to be turned to MAX_EXPR. */
1065 if (ass_code != MIN_EXPR)
1066 return false;
1068 minmax = MAX_EXPR;
1069 if (operand_equal_for_phi_arg_p (op0, smaller))
1070 bound = op1;
1071 else if (operand_equal_for_phi_arg_p (op1, smaller))
1072 bound = op0;
1073 else
1074 return false;
1076 /* We need BOUND >= LARGER. */
1077 if (!integer_nonzerop (fold_build2 (GE_EXPR, boolean_type_node,
1078 bound, larger)))
1079 return false;
1081 else if (operand_equal_for_phi_arg_p (arg_true, smaller))
1083 /* Case
1085 if (smaller > larger)
1087 r' = MAX_EXPR (larger, bound)
1089 r = PHI <r', smaller> --> to be turned to MIN_EXPR. */
1090 if (ass_code != MAX_EXPR)
1091 return false;
1093 minmax = MIN_EXPR;
1094 if (operand_equal_for_phi_arg_p (op0, larger))
1095 bound = op1;
1096 else if (operand_equal_for_phi_arg_p (op1, larger))
1097 bound = op0;
1098 else
1099 return false;
1101 /* We need BOUND <= SMALLER. */
1102 if (!integer_nonzerop (fold_build2 (LE_EXPR, boolean_type_node,
1103 bound, smaller)))
1104 return false;
1106 else
1107 return false;
1110 /* Move the statement from the middle block. */
1111 gsi = gsi_last_bb (cond_bb);
1112 gsi_from = gsi_last_nondebug_bb (middle_bb);
1113 gsi_move_before (&gsi_from, &gsi);
1116 /* Emit the statement to compute min/max. */
1117 result = duplicate_ssa_name (PHI_RESULT (phi), NULL);
1118 new_stmt = gimple_build_assign_with_ops (minmax, result, arg0, arg1);
1119 gsi = gsi_last_bb (cond_bb);
1120 gsi_insert_before (&gsi, new_stmt, GSI_NEW_STMT);
1122 replace_phi_edge_with_variable (cond_bb, e1, phi, result);
1123 return true;
1126 /* The function absolute_replacement does the main work of doing the absolute
1127 replacement. Return true if the replacement is done. Otherwise return
1128 false.
1129 bb is the basic block where the replacement is going to be done on. arg0
1130 is argument 0 from the phi. Likewise for arg1. */
1132 static bool
1133 abs_replacement (basic_block cond_bb, basic_block middle_bb,
1134 edge e0 ATTRIBUTE_UNUSED, edge e1,
1135 gimple phi, tree arg0, tree arg1)
1137 tree result;
1138 gimple new_stmt, cond;
1139 gimple_stmt_iterator gsi;
1140 edge true_edge, false_edge;
1141 gimple assign;
1142 edge e;
1143 tree rhs, lhs;
1144 bool negate;
1145 enum tree_code cond_code;
1147 /* If the type says honor signed zeros we cannot do this
1148 optimization. */
1149 if (HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (arg1))))
1150 return false;
1152 /* OTHER_BLOCK must have only one executable statement which must have the
1153 form arg0 = -arg1 or arg1 = -arg0. */
1155 assign = last_and_only_stmt (middle_bb);
1156 /* If we did not find the proper negation assignment, then we can not
1157 optimize. */
1158 if (assign == NULL)
1159 return false;
1161 /* If we got here, then we have found the only executable statement
1162 in OTHER_BLOCK. If it is anything other than arg = -arg1 or
1163 arg1 = -arg0, then we can not optimize. */
1164 if (gimple_code (assign) != GIMPLE_ASSIGN)
1165 return false;
1167 lhs = gimple_assign_lhs (assign);
1169 if (gimple_assign_rhs_code (assign) != NEGATE_EXPR)
1170 return false;
1172 rhs = gimple_assign_rhs1 (assign);
1174 /* The assignment has to be arg0 = -arg1 or arg1 = -arg0. */
1175 if (!(lhs == arg0 && rhs == arg1)
1176 && !(lhs == arg1 && rhs == arg0))
1177 return false;
1179 cond = last_stmt (cond_bb);
1180 result = PHI_RESULT (phi);
1182 /* Only relationals comparing arg[01] against zero are interesting. */
1183 cond_code = gimple_cond_code (cond);
1184 if (cond_code != GT_EXPR && cond_code != GE_EXPR
1185 && cond_code != LT_EXPR && cond_code != LE_EXPR)
1186 return false;
1188 /* Make sure the conditional is arg[01] OP y. */
1189 if (gimple_cond_lhs (cond) != rhs)
1190 return false;
1192 if (FLOAT_TYPE_P (TREE_TYPE (gimple_cond_rhs (cond)))
1193 ? real_zerop (gimple_cond_rhs (cond))
1194 : integer_zerop (gimple_cond_rhs (cond)))
1196 else
1197 return false;
1199 /* We need to know which is the true edge and which is the false
1200 edge so that we know if have abs or negative abs. */
1201 extract_true_false_edges_from_block (cond_bb, &true_edge, &false_edge);
1203 /* For GT_EXPR/GE_EXPR, if the true edge goes to OTHER_BLOCK, then we
1204 will need to negate the result. Similarly for LT_EXPR/LE_EXPR if
1205 the false edge goes to OTHER_BLOCK. */
1206 if (cond_code == GT_EXPR || cond_code == GE_EXPR)
1207 e = true_edge;
1208 else
1209 e = false_edge;
1211 if (e->dest == middle_bb)
1212 negate = true;
1213 else
1214 negate = false;
1216 result = duplicate_ssa_name (result, NULL);
1218 if (negate)
1220 tree tmp = create_tmp_var (TREE_TYPE (result), NULL);
1221 add_referenced_var (tmp);
1222 lhs = make_ssa_name (tmp, NULL);
1224 else
1225 lhs = result;
1227 /* Build the modify expression with abs expression. */
1228 new_stmt = gimple_build_assign_with_ops (ABS_EXPR, lhs, rhs, NULL);
1230 gsi = gsi_last_bb (cond_bb);
1231 gsi_insert_before (&gsi, new_stmt, GSI_NEW_STMT);
1233 if (negate)
1235 /* Get the right GSI. We want to insert after the recently
1236 added ABS_EXPR statement (which we know is the first statement
1237 in the block. */
1238 new_stmt = gimple_build_assign_with_ops (NEGATE_EXPR, result, lhs, NULL);
1240 gsi_insert_after (&gsi, new_stmt, GSI_NEW_STMT);
1243 replace_phi_edge_with_variable (cond_bb, e1, phi, result);
1245 /* Note that we optimized this PHI. */
1246 return true;
1249 /* Auxiliary functions to determine the set of memory accesses which
1250 can't trap because they are preceded by accesses to the same memory
1251 portion. We do that for MEM_REFs, so we only need to track
1252 the SSA_NAME of the pointer indirectly referenced. The algorithm
1253 simply is a walk over all instructions in dominator order. When
1254 we see an MEM_REF we determine if we've already seen a same
1255 ref anywhere up to the root of the dominator tree. If we do the
1256 current access can't trap. If we don't see any dominating access
1257 the current access might trap, but might also make later accesses
1258 non-trapping, so we remember it. We need to be careful with loads
1259 or stores, for instance a load might not trap, while a store would,
1260 so if we see a dominating read access this doesn't mean that a later
1261 write access would not trap. Hence we also need to differentiate the
1262 type of access(es) seen.
1264 ??? We currently are very conservative and assume that a load might
1265 trap even if a store doesn't (write-only memory). This probably is
1266 overly conservative. */
1268 /* A hash-table of SSA_NAMEs, and in which basic block an MEM_REF
1269 through it was seen, which would constitute a no-trap region for
1270 same accesses. */
1271 struct name_to_bb
1273 unsigned int ssa_name_ver;
1274 bool store;
1275 HOST_WIDE_INT offset, size;
1276 basic_block bb;
1279 /* The hash table for remembering what we've seen. */
1280 static htab_t seen_ssa_names;
1282 /* The set of MEM_REFs which can't trap. */
1283 static struct pointer_set_t *nontrap_set;
1285 /* The hash function. */
1286 static hashval_t
1287 name_to_bb_hash (const void *p)
1289 const struct name_to_bb *n = (const struct name_to_bb *) p;
1290 return n->ssa_name_ver ^ (((hashval_t) n->store) << 31)
1291 ^ (n->offset << 6) ^ (n->size << 3);
1294 /* The equality function of *P1 and *P2. */
1295 static int
1296 name_to_bb_eq (const void *p1, const void *p2)
1298 const struct name_to_bb *n1 = (const struct name_to_bb *)p1;
1299 const struct name_to_bb *n2 = (const struct name_to_bb *)p2;
1301 return n1->ssa_name_ver == n2->ssa_name_ver
1302 && n1->store == n2->store
1303 && n1->offset == n2->offset
1304 && n1->size == n2->size;
1307 /* We see the expression EXP in basic block BB. If it's an interesting
1308 expression (an MEM_REF through an SSA_NAME) possibly insert the
1309 expression into the set NONTRAP or the hash table of seen expressions.
1310 STORE is true if this expression is on the LHS, otherwise it's on
1311 the RHS. */
1312 static void
1313 add_or_mark_expr (basic_block bb, tree exp,
1314 struct pointer_set_t *nontrap, bool store)
1316 HOST_WIDE_INT size;
1318 if (TREE_CODE (exp) == MEM_REF
1319 && TREE_CODE (TREE_OPERAND (exp, 0)) == SSA_NAME
1320 && host_integerp (TREE_OPERAND (exp, 1), 0)
1321 && (size = int_size_in_bytes (TREE_TYPE (exp))) > 0)
1323 tree name = TREE_OPERAND (exp, 0);
1324 struct name_to_bb map;
1325 void **slot;
1326 struct name_to_bb *n2bb;
1327 basic_block found_bb = 0;
1329 /* Try to find the last seen MEM_REF through the same
1330 SSA_NAME, which can trap. */
1331 map.ssa_name_ver = SSA_NAME_VERSION (name);
1332 map.bb = 0;
1333 map.store = store;
1334 map.offset = tree_low_cst (TREE_OPERAND (exp, 1), 0);
1335 map.size = size;
1337 slot = htab_find_slot (seen_ssa_names, &map, INSERT);
1338 n2bb = (struct name_to_bb *) *slot;
1339 if (n2bb)
1340 found_bb = n2bb->bb;
1342 /* If we've found a trapping MEM_REF, _and_ it dominates EXP
1343 (it's in a basic block on the path from us to the dominator root)
1344 then we can't trap. */
1345 if (found_bb && found_bb->aux == (void *)1)
1347 pointer_set_insert (nontrap, exp);
1349 else
1351 /* EXP might trap, so insert it into the hash table. */
1352 if (n2bb)
1354 n2bb->bb = bb;
1356 else
1358 n2bb = XNEW (struct name_to_bb);
1359 n2bb->ssa_name_ver = SSA_NAME_VERSION (name);
1360 n2bb->bb = bb;
1361 n2bb->store = store;
1362 n2bb->offset = map.offset;
1363 n2bb->size = size;
1364 *slot = n2bb;
1370 /* Called by walk_dominator_tree, when entering the block BB. */
1371 static void
1372 nt_init_block (struct dom_walk_data *data ATTRIBUTE_UNUSED, basic_block bb)
1374 gimple_stmt_iterator gsi;
1375 /* Mark this BB as being on the path to dominator root. */
1376 bb->aux = (void*)1;
1378 /* And walk the statements in order. */
1379 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1381 gimple stmt = gsi_stmt (gsi);
1383 if (gimple_assign_single_p (stmt))
1385 add_or_mark_expr (bb, gimple_assign_lhs (stmt), nontrap_set, true);
1386 add_or_mark_expr (bb, gimple_assign_rhs1 (stmt), nontrap_set, false);
1391 /* Called by walk_dominator_tree, when basic block BB is exited. */
1392 static void
1393 nt_fini_block (struct dom_walk_data *data ATTRIBUTE_UNUSED, basic_block bb)
1395 /* This BB isn't on the path to dominator root anymore. */
1396 bb->aux = NULL;
1399 /* This is the entry point of gathering non trapping memory accesses.
1400 It will do a dominator walk over the whole function, and it will
1401 make use of the bb->aux pointers. It returns a set of trees
1402 (the MEM_REFs itself) which can't trap. */
1403 static struct pointer_set_t *
1404 get_non_trapping (void)
1406 struct pointer_set_t *nontrap;
1407 struct dom_walk_data walk_data;
1409 nontrap = pointer_set_create ();
1410 seen_ssa_names = htab_create (128, name_to_bb_hash, name_to_bb_eq,
1411 free);
1412 /* We're going to do a dominator walk, so ensure that we have
1413 dominance information. */
1414 calculate_dominance_info (CDI_DOMINATORS);
1416 /* Setup callbacks for the generic dominator tree walker. */
1417 nontrap_set = nontrap;
1418 walk_data.dom_direction = CDI_DOMINATORS;
1419 walk_data.initialize_block_local_data = NULL;
1420 walk_data.before_dom_children = nt_init_block;
1421 walk_data.after_dom_children = nt_fini_block;
1422 walk_data.global_data = NULL;
1423 walk_data.block_local_data_size = 0;
1425 init_walk_dominator_tree (&walk_data);
1426 walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
1427 fini_walk_dominator_tree (&walk_data);
1428 htab_delete (seen_ssa_names);
1430 return nontrap;
1433 /* Do the main work of conditional store replacement. We already know
1434 that the recognized pattern looks like so:
1436 split:
1437 if (cond) goto MIDDLE_BB; else goto JOIN_BB (edge E1)
1438 MIDDLE_BB:
1439 something
1440 fallthrough (edge E0)
1441 JOIN_BB:
1442 some more
1444 We check that MIDDLE_BB contains only one store, that that store
1445 doesn't trap (not via NOTRAP, but via checking if an access to the same
1446 memory location dominates us) and that the store has a "simple" RHS. */
1448 static bool
1449 cond_store_replacement (basic_block middle_bb, basic_block join_bb,
1450 edge e0, edge e1, struct pointer_set_t *nontrap)
1452 gimple assign = last_and_only_stmt (middle_bb);
1453 tree lhs, rhs, name;
1454 gimple newphi, new_stmt;
1455 gimple_stmt_iterator gsi;
1456 source_location locus;
1458 /* Check if middle_bb contains of only one store. */
1459 if (!assign
1460 || !gimple_assign_single_p (assign))
1461 return false;
1463 locus = gimple_location (assign);
1464 lhs = gimple_assign_lhs (assign);
1465 rhs = gimple_assign_rhs1 (assign);
1466 if (TREE_CODE (lhs) != MEM_REF
1467 || TREE_CODE (TREE_OPERAND (lhs, 0)) != SSA_NAME
1468 || !is_gimple_reg_type (TREE_TYPE (lhs)))
1469 return false;
1471 /* Prove that we can move the store down. We could also check
1472 TREE_THIS_NOTRAP here, but in that case we also could move stores,
1473 whose value is not available readily, which we want to avoid. */
1474 if (!pointer_set_contains (nontrap, lhs))
1475 return false;
1477 /* Now we've checked the constraints, so do the transformation:
1478 1) Remove the single store. */
1479 gsi = gsi_for_stmt (assign);
1480 unlink_stmt_vdef (assign);
1481 gsi_remove (&gsi, true);
1482 release_defs (assign);
1484 /* 2) Create a temporary where we can store the old content
1485 of the memory touched by the store, if we need to. */
1486 if (!condstoretemp || TREE_TYPE (lhs) != TREE_TYPE (condstoretemp))
1487 condstoretemp = create_tmp_reg (TREE_TYPE (lhs), "cstore");
1488 add_referenced_var (condstoretemp);
1490 /* 3) Insert a load from the memory of the store to the temporary
1491 on the edge which did not contain the store. */
1492 lhs = unshare_expr (lhs);
1493 new_stmt = gimple_build_assign (condstoretemp, lhs);
1494 name = make_ssa_name (condstoretemp, new_stmt);
1495 gimple_assign_set_lhs (new_stmt, name);
1496 gimple_set_location (new_stmt, locus);
1497 gsi_insert_on_edge (e1, new_stmt);
1499 /* 4) Create a PHI node at the join block, with one argument
1500 holding the old RHS, and the other holding the temporary
1501 where we stored the old memory contents. */
1502 newphi = create_phi_node (condstoretemp, join_bb);
1503 add_phi_arg (newphi, rhs, e0, locus);
1504 add_phi_arg (newphi, name, e1, locus);
1506 lhs = unshare_expr (lhs);
1507 new_stmt = gimple_build_assign (lhs, PHI_RESULT (newphi));
1509 /* 5) Insert that PHI node. */
1510 gsi = gsi_after_labels (join_bb);
1511 if (gsi_end_p (gsi))
1513 gsi = gsi_last_bb (join_bb);
1514 gsi_insert_after (&gsi, new_stmt, GSI_NEW_STMT);
1516 else
1517 gsi_insert_before (&gsi, new_stmt, GSI_NEW_STMT);
1519 return true;
1522 /* Do the main work of conditional store replacement. */
1524 static bool
1525 cond_if_else_store_replacement_1 (basic_block then_bb, basic_block else_bb,
1526 basic_block join_bb, gimple then_assign,
1527 gimple else_assign)
1529 tree lhs_base, lhs, then_rhs, else_rhs;
1530 source_location then_locus, else_locus;
1531 gimple_stmt_iterator gsi;
1532 gimple newphi, new_stmt;
1534 if (then_assign == NULL
1535 || !gimple_assign_single_p (then_assign)
1536 || gimple_clobber_p (then_assign)
1537 || else_assign == NULL
1538 || !gimple_assign_single_p (else_assign)
1539 || gimple_clobber_p (else_assign))
1540 return false;
1542 lhs = gimple_assign_lhs (then_assign);
1543 if (!is_gimple_reg_type (TREE_TYPE (lhs))
1544 || !operand_equal_p (lhs, gimple_assign_lhs (else_assign), 0))
1545 return false;
1547 lhs_base = get_base_address (lhs);
1548 if (lhs_base == NULL_TREE
1549 || (!DECL_P (lhs_base) && TREE_CODE (lhs_base) != MEM_REF))
1550 return false;
1552 then_rhs = gimple_assign_rhs1 (then_assign);
1553 else_rhs = gimple_assign_rhs1 (else_assign);
1554 then_locus = gimple_location (then_assign);
1555 else_locus = gimple_location (else_assign);
1557 /* Now we've checked the constraints, so do the transformation:
1558 1) Remove the stores. */
1559 gsi = gsi_for_stmt (then_assign);
1560 unlink_stmt_vdef (then_assign);
1561 gsi_remove (&gsi, true);
1562 release_defs (then_assign);
1564 gsi = gsi_for_stmt (else_assign);
1565 unlink_stmt_vdef (else_assign);
1566 gsi_remove (&gsi, true);
1567 release_defs (else_assign);
1569 /* 2) Create a temporary where we can store the old content
1570 of the memory touched by the store, if we need to. */
1571 if (!condstoretemp || TREE_TYPE (lhs) != TREE_TYPE (condstoretemp))
1572 condstoretemp = create_tmp_reg (TREE_TYPE (lhs), "cstore");
1573 add_referenced_var (condstoretemp);
1575 /* 3) Create a PHI node at the join block, with one argument
1576 holding the old RHS, and the other holding the temporary
1577 where we stored the old memory contents. */
1578 newphi = create_phi_node (condstoretemp, join_bb);
1579 add_phi_arg (newphi, then_rhs, EDGE_SUCC (then_bb, 0), then_locus);
1580 add_phi_arg (newphi, else_rhs, EDGE_SUCC (else_bb, 0), else_locus);
1582 new_stmt = gimple_build_assign (lhs, PHI_RESULT (newphi));
1584 /* 4) Insert that PHI node. */
1585 gsi = gsi_after_labels (join_bb);
1586 if (gsi_end_p (gsi))
1588 gsi = gsi_last_bb (join_bb);
1589 gsi_insert_after (&gsi, new_stmt, GSI_NEW_STMT);
1591 else
1592 gsi_insert_before (&gsi, new_stmt, GSI_NEW_STMT);
1594 return true;
1597 /* Conditional store replacement. We already know
1598 that the recognized pattern looks like so:
1600 split:
1601 if (cond) goto THEN_BB; else goto ELSE_BB (edge E1)
1602 THEN_BB:
1604 X = Y;
1606 goto JOIN_BB;
1607 ELSE_BB:
1609 X = Z;
1611 fallthrough (edge E0)
1612 JOIN_BB:
1613 some more
1615 We check that it is safe to sink the store to JOIN_BB by verifying that
1616 there are no read-after-write or write-after-write dependencies in
1617 THEN_BB and ELSE_BB. */
1619 static bool
1620 cond_if_else_store_replacement (basic_block then_bb, basic_block else_bb,
1621 basic_block join_bb)
1623 gimple then_assign = last_and_only_stmt (then_bb);
1624 gimple else_assign = last_and_only_stmt (else_bb);
1625 VEC (data_reference_p, heap) *then_datarefs, *else_datarefs;
1626 VEC (ddr_p, heap) *then_ddrs, *else_ddrs;
1627 gimple then_store, else_store;
1628 bool found, ok = false, res;
1629 struct data_dependence_relation *ddr;
1630 data_reference_p then_dr, else_dr;
1631 int i, j;
1632 tree then_lhs, else_lhs;
1633 VEC (gimple, heap) *then_stores, *else_stores;
1634 basic_block blocks[3];
1636 if (MAX_STORES_TO_SINK == 0)
1637 return false;
1639 /* Handle the case with single statement in THEN_BB and ELSE_BB. */
1640 if (then_assign && else_assign)
1641 return cond_if_else_store_replacement_1 (then_bb, else_bb, join_bb,
1642 then_assign, else_assign);
1644 /* Find data references. */
1645 then_datarefs = VEC_alloc (data_reference_p, heap, 1);
1646 else_datarefs = VEC_alloc (data_reference_p, heap, 1);
1647 if ((find_data_references_in_bb (NULL, then_bb, &then_datarefs)
1648 == chrec_dont_know)
1649 || !VEC_length (data_reference_p, then_datarefs)
1650 || (find_data_references_in_bb (NULL, else_bb, &else_datarefs)
1651 == chrec_dont_know)
1652 || !VEC_length (data_reference_p, else_datarefs))
1654 free_data_refs (then_datarefs);
1655 free_data_refs (else_datarefs);
1656 return false;
1659 /* Find pairs of stores with equal LHS. */
1660 then_stores = VEC_alloc (gimple, heap, 1);
1661 else_stores = VEC_alloc (gimple, heap, 1);
1662 FOR_EACH_VEC_ELT (data_reference_p, then_datarefs, i, then_dr)
1664 if (DR_IS_READ (then_dr))
1665 continue;
1667 then_store = DR_STMT (then_dr);
1668 then_lhs = gimple_get_lhs (then_store);
1669 found = false;
1671 FOR_EACH_VEC_ELT (data_reference_p, else_datarefs, j, else_dr)
1673 if (DR_IS_READ (else_dr))
1674 continue;
1676 else_store = DR_STMT (else_dr);
1677 else_lhs = gimple_get_lhs (else_store);
1679 if (operand_equal_p (then_lhs, else_lhs, 0))
1681 found = true;
1682 break;
1686 if (!found)
1687 continue;
1689 VEC_safe_push (gimple, heap, then_stores, then_store);
1690 VEC_safe_push (gimple, heap, else_stores, else_store);
1693 /* No pairs of stores found. */
1694 if (!VEC_length (gimple, then_stores)
1695 || VEC_length (gimple, then_stores) > (unsigned) MAX_STORES_TO_SINK)
1697 free_data_refs (then_datarefs);
1698 free_data_refs (else_datarefs);
1699 VEC_free (gimple, heap, then_stores);
1700 VEC_free (gimple, heap, else_stores);
1701 return false;
1704 /* Compute and check data dependencies in both basic blocks. */
1705 then_ddrs = VEC_alloc (ddr_p, heap, 1);
1706 else_ddrs = VEC_alloc (ddr_p, heap, 1);
1707 if (!compute_all_dependences (then_datarefs, &then_ddrs, NULL, false)
1708 || !compute_all_dependences (else_datarefs, &else_ddrs, NULL, false))
1710 free_dependence_relations (then_ddrs);
1711 free_dependence_relations (else_ddrs);
1712 free_data_refs (then_datarefs);
1713 free_data_refs (else_datarefs);
1714 VEC_free (gimple, heap, then_stores);
1715 VEC_free (gimple, heap, else_stores);
1716 return false;
1718 blocks[0] = then_bb;
1719 blocks[1] = else_bb;
1720 blocks[2] = join_bb;
1721 renumber_gimple_stmt_uids_in_blocks (blocks, 3);
1723 /* Check that there are no read-after-write or write-after-write dependencies
1724 in THEN_BB. */
1725 FOR_EACH_VEC_ELT (ddr_p, then_ddrs, i, ddr)
1727 struct data_reference *dra = DDR_A (ddr);
1728 struct data_reference *drb = DDR_B (ddr);
1730 if (DDR_ARE_DEPENDENT (ddr) != chrec_known
1731 && ((DR_IS_READ (dra) && DR_IS_WRITE (drb)
1732 && gimple_uid (DR_STMT (dra)) > gimple_uid (DR_STMT (drb)))
1733 || (DR_IS_READ (drb) && DR_IS_WRITE (dra)
1734 && gimple_uid (DR_STMT (drb)) > gimple_uid (DR_STMT (dra)))
1735 || (DR_IS_WRITE (dra) && DR_IS_WRITE (drb))))
1737 free_dependence_relations (then_ddrs);
1738 free_dependence_relations (else_ddrs);
1739 free_data_refs (then_datarefs);
1740 free_data_refs (else_datarefs);
1741 VEC_free (gimple, heap, then_stores);
1742 VEC_free (gimple, heap, else_stores);
1743 return false;
1747 /* Check that there are no read-after-write or write-after-write dependencies
1748 in ELSE_BB. */
1749 FOR_EACH_VEC_ELT (ddr_p, else_ddrs, i, ddr)
1751 struct data_reference *dra = DDR_A (ddr);
1752 struct data_reference *drb = DDR_B (ddr);
1754 if (DDR_ARE_DEPENDENT (ddr) != chrec_known
1755 && ((DR_IS_READ (dra) && DR_IS_WRITE (drb)
1756 && gimple_uid (DR_STMT (dra)) > gimple_uid (DR_STMT (drb)))
1757 || (DR_IS_READ (drb) && DR_IS_WRITE (dra)
1758 && gimple_uid (DR_STMT (drb)) > gimple_uid (DR_STMT (dra)))
1759 || (DR_IS_WRITE (dra) && DR_IS_WRITE (drb))))
1761 free_dependence_relations (then_ddrs);
1762 free_dependence_relations (else_ddrs);
1763 free_data_refs (then_datarefs);
1764 free_data_refs (else_datarefs);
1765 VEC_free (gimple, heap, then_stores);
1766 VEC_free (gimple, heap, else_stores);
1767 return false;
1771 /* Sink stores with same LHS. */
1772 FOR_EACH_VEC_ELT (gimple, then_stores, i, then_store)
1774 else_store = VEC_index (gimple, else_stores, i);
1775 res = cond_if_else_store_replacement_1 (then_bb, else_bb, join_bb,
1776 then_store, else_store);
1777 ok = ok || res;
1780 free_dependence_relations (then_ddrs);
1781 free_dependence_relations (else_ddrs);
1782 free_data_refs (then_datarefs);
1783 free_data_refs (else_datarefs);
1784 VEC_free (gimple, heap, then_stores);
1785 VEC_free (gimple, heap, else_stores);
1787 return ok;
1790 /* Return TRUE if STMT has a VUSE whose corresponding VDEF is in BB. */
1792 static bool
1793 local_mem_dependence (gimple stmt, basic_block bb)
1795 tree vuse = gimple_vuse (stmt);
1796 gimple def;
1798 if (!vuse)
1799 return false;
1801 def = SSA_NAME_DEF_STMT (vuse);
1802 return (def && gimple_bb (def) == bb);
1805 /* Given a "diamond" control-flow pattern where BB0 tests a condition,
1806 BB1 and BB2 are "then" and "else" blocks dependent on this test,
1807 and BB3 rejoins control flow following BB1 and BB2, look for
1808 opportunities to hoist loads as follows. If BB3 contains a PHI of
1809 two loads, one each occurring in BB1 and BB2, and the loads are
1810 provably of adjacent fields in the same structure, then move both
1811 loads into BB0. Of course this can only be done if there are no
1812 dependencies preventing such motion.
1814 One of the hoisted loads will always be speculative, so the
1815 transformation is currently conservative:
1817 - The fields must be strictly adjacent.
1818 - The two fields must occupy a single memory block that is
1819 guaranteed to not cross a page boundary.
1821 The last is difficult to prove, as such memory blocks should be
1822 aligned on the minimum of the stack alignment boundary and the
1823 alignment guaranteed by heap allocation interfaces. Thus we rely
1824 on a parameter for the alignment value.
1826 Provided a good value is used for the last case, the first
1827 restriction could possibly be relaxed. */
1829 static void
1830 hoist_adjacent_loads (basic_block bb0, basic_block bb1,
1831 basic_block bb2, basic_block bb3)
1833 int param_align = PARAM_VALUE (PARAM_L1_CACHE_LINE_SIZE);
1834 unsigned param_align_bits = (unsigned) (param_align * BITS_PER_UNIT);
1835 gimple_stmt_iterator gsi;
1837 /* Walk the phis in bb3 looking for an opportunity. We are looking
1838 for phis of two SSA names, one each of which is defined in bb1 and
1839 bb2. */
1840 for (gsi = gsi_start_phis (bb3); !gsi_end_p (gsi); gsi_next (&gsi))
1842 gimple phi_stmt = gsi_stmt (gsi);
1843 gimple def1, def2, defswap;
1844 tree arg1, arg2, ref1, ref2, field1, field2, fieldswap;
1845 tree tree_offset1, tree_offset2, tree_size2, next;
1846 int offset1, offset2, size2;
1847 unsigned align1;
1848 gimple_stmt_iterator gsi2;
1849 basic_block bb_for_def1, bb_for_def2;
1851 if (gimple_phi_num_args (phi_stmt) != 2)
1852 continue;
1854 arg1 = gimple_phi_arg_def (phi_stmt, 0);
1855 arg2 = gimple_phi_arg_def (phi_stmt, 1);
1857 if (TREE_CODE (arg1) != SSA_NAME
1858 || TREE_CODE (arg2) != SSA_NAME
1859 || SSA_NAME_IS_DEFAULT_DEF (arg1)
1860 || SSA_NAME_IS_DEFAULT_DEF (arg2)
1861 || !is_gimple_reg (arg1)
1862 || !is_gimple_reg (arg2))
1863 continue;
1865 def1 = SSA_NAME_DEF_STMT (arg1);
1866 def2 = SSA_NAME_DEF_STMT (arg2);
1868 if ((gimple_bb (def1) != bb1 || gimple_bb (def2) != bb2)
1869 && (gimple_bb (def2) != bb1 || gimple_bb (def1) != bb2))
1870 continue;
1872 /* Check the mode of the arguments to be sure a conditional move
1873 can be generated for it. */
1874 if (!optab_handler (cmov_optab, TYPE_MODE (TREE_TYPE (arg1))))
1875 continue;
1877 /* Both statements must be assignments whose RHS is a COMPONENT_REF. */
1878 if (!gimple_assign_single_p (def1)
1879 || !gimple_assign_single_p (def2))
1880 continue;
1882 ref1 = gimple_assign_rhs1 (def1);
1883 ref2 = gimple_assign_rhs1 (def2);
1885 if (TREE_CODE (ref1) != COMPONENT_REF
1886 || TREE_CODE (ref2) != COMPONENT_REF)
1887 continue;
1889 /* The zeroth operand of the two component references must be
1890 identical. It is not sufficient to compare get_base_address of
1891 the two references, because this could allow for different
1892 elements of the same array in the two trees. It is not safe to
1893 assume that the existence of one array element implies the
1894 existence of a different one. */
1895 if (!operand_equal_p (TREE_OPERAND (ref1, 0), TREE_OPERAND (ref2, 0), 0))
1896 continue;
1898 field1 = TREE_OPERAND (ref1, 1);
1899 field2 = TREE_OPERAND (ref2, 1);
1901 /* Check for field adjacency, and ensure field1 comes first. */
1902 for (next = DECL_CHAIN (field1);
1903 next && TREE_CODE (next) != FIELD_DECL;
1904 next = DECL_CHAIN (next))
1907 if (next != field2)
1909 for (next = DECL_CHAIN (field2);
1910 next && TREE_CODE (next) != FIELD_DECL;
1911 next = DECL_CHAIN (next))
1914 if (next != field1)
1915 continue;
1917 fieldswap = field1;
1918 field1 = field2;
1919 field2 = fieldswap;
1920 defswap = def1;
1921 def1 = def2;
1922 def2 = defswap;
1925 bb_for_def1 = gimple_bb (def1);
1926 bb_for_def2 = gimple_bb (def2);
1928 /* Check for proper alignment of the first field. */
1929 tree_offset1 = bit_position (field1);
1930 tree_offset2 = bit_position (field2);
1931 tree_size2 = DECL_SIZE (field2);
1933 if (!host_integerp (tree_offset1, 1)
1934 || !host_integerp (tree_offset2, 1)
1935 || !host_integerp (tree_size2, 1))
1936 continue;
1938 offset1 = TREE_INT_CST_LOW (tree_offset1);
1939 offset2 = TREE_INT_CST_LOW (tree_offset2);
1940 size2 = TREE_INT_CST_LOW (tree_size2);
1941 align1 = DECL_ALIGN (field1) % param_align_bits;
1943 if (offset1 % BITS_PER_UNIT != 0)
1944 continue;
1946 /* For profitability, the two field references should fit within
1947 a single cache line. */
1948 if (align1 + offset2 - offset1 + size2 > param_align_bits)
1949 continue;
1951 /* The two expressions cannot be dependent upon vdefs defined
1952 in bb1/bb2. */
1953 if (local_mem_dependence (def1, bb_for_def1)
1954 || local_mem_dependence (def2, bb_for_def2))
1955 continue;
1957 /* The conditions are satisfied; hoist the loads from bb1 and bb2 into
1958 bb0. We hoist the first one first so that a cache miss is handled
1959 efficiently regardless of hardware cache-fill policy. */
1960 gsi2 = gsi_for_stmt (def1);
1961 gsi_move_to_bb_end (&gsi2, bb0);
1962 gsi2 = gsi_for_stmt (def2);
1963 gsi_move_to_bb_end (&gsi2, bb0);
1965 if (dump_file && (dump_flags & TDF_DETAILS))
1967 fprintf (dump_file,
1968 "\nHoisting adjacent loads from %d and %d into %d: \n",
1969 bb_for_def1->index, bb_for_def2->index, bb0->index);
1970 print_gimple_stmt (dump_file, def1, 0, TDF_VOPS|TDF_MEMSYMS);
1971 print_gimple_stmt (dump_file, def2, 0, TDF_VOPS|TDF_MEMSYMS);
1976 /* Determine whether we should attempt to hoist adjacent loads out of
1977 diamond patterns in pass_phiopt. Always hoist loads if
1978 -fhoist-adjacent-loads is specified and the target machine has
1979 both a conditional move instruction and a defined cache line size. */
1981 static bool
1982 gate_hoist_loads (void)
1984 return (flag_hoist_adjacent_loads == 1
1985 && PARAM_VALUE (PARAM_L1_CACHE_LINE_SIZE)
1986 && HAVE_conditional_move);
1989 /* Always do these optimizations if we have SSA
1990 trees to work on. */
1991 static bool
1992 gate_phiopt (void)
1994 return 1;
1997 struct gimple_opt_pass pass_phiopt =
2000 GIMPLE_PASS,
2001 "phiopt", /* name */
2002 gate_phiopt, /* gate */
2003 tree_ssa_phiopt, /* execute */
2004 NULL, /* sub */
2005 NULL, /* next */
2006 0, /* static_pass_number */
2007 TV_TREE_PHIOPT, /* tv_id */
2008 PROP_cfg | PROP_ssa, /* properties_required */
2009 0, /* properties_provided */
2010 0, /* properties_destroyed */
2011 0, /* todo_flags_start */
2012 TODO_ggc_collect
2013 | TODO_verify_ssa
2014 | TODO_verify_flow
2015 | TODO_verify_stmts /* todo_flags_finish */
2019 static bool
2020 gate_cselim (void)
2022 return flag_tree_cselim;
2025 struct gimple_opt_pass pass_cselim =
2028 GIMPLE_PASS,
2029 "cselim", /* name */
2030 gate_cselim, /* gate */
2031 tree_ssa_cs_elim, /* execute */
2032 NULL, /* sub */
2033 NULL, /* next */
2034 0, /* static_pass_number */
2035 TV_TREE_PHIOPT, /* tv_id */
2036 PROP_cfg | PROP_ssa, /* properties_required */
2037 0, /* properties_provided */
2038 0, /* properties_destroyed */
2039 0, /* todo_flags_start */
2040 TODO_ggc_collect
2041 | TODO_verify_ssa
2042 | TODO_verify_flow
2043 | TODO_verify_stmts /* todo_flags_finish */