2015-09-25 Vladimir Makarov <vmakarov@redhat.com>
[official-gcc.git] / gcc / cfgcleanup.c
blob7e576bce39b9e27f2c2ff20fe19b6ee03ca83b20
1 /* Control flow optimization code for GNU compiler.
2 Copyright (C) 1987-2015 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
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/>. */
20 /* This file contains optimizer of the control flow. The main entry point is
21 cleanup_cfg. Following optimizations are performed:
23 - Unreachable blocks removal
24 - Edge forwarding (edge to the forwarder block is forwarded to its
25 successor. Simplification of the branch instruction is performed by
26 underlying infrastructure so branch can be converted to simplejump or
27 eliminated).
28 - Cross jumping (tail merging)
29 - Conditional jump-around-simplejump simplification
30 - Basic block merging. */
32 #include "config.h"
33 #include "system.h"
34 #include "coretypes.h"
35 #include "backend.h"
36 #include "cfghooks.h"
37 #include "tree.h"
38 #include "rtl.h"
39 #include "df.h"
40 #include "alias.h"
41 #include "regs.h"
42 #include "insn-config.h"
43 #include "flags.h"
44 #include "recog.h"
45 #include "diagnostic-core.h"
46 #include "alloc-pool.h"
47 #include "cselib.h"
48 #include "params.h"
49 #include "tm_p.h"
50 #include "target.h"
51 #include "emit-rtl.h"
52 #include "tree-pass.h"
53 #include "cfgloop.h"
54 #include "expmed.h"
55 #include "dojump.h"
56 #include "explow.h"
57 #include "calls.h"
58 #include "varasm.h"
59 #include "stmt.h"
60 #include "expr.h"
61 #include "cfgrtl.h"
62 #include "cfganal.h"
63 #include "cfgbuild.h"
64 #include "cfgcleanup.h"
65 #include "dce.h"
66 #include "dbgcnt.h"
67 #include "rtl-iter.h"
69 #define FORWARDER_BLOCK_P(BB) ((BB)->flags & BB_FORWARDER_BLOCK)
71 /* Set to true when we are running first pass of try_optimize_cfg loop. */
72 static bool first_pass;
74 /* Set to true if crossjumps occurred in the latest run of try_optimize_cfg. */
75 static bool crossjumps_occured;
77 /* Set to true if we couldn't run an optimization due to stale liveness
78 information; we should run df_analyze to enable more opportunities. */
79 static bool block_was_dirty;
81 static bool try_crossjump_to_edge (int, edge, edge, enum replace_direction);
82 static bool try_crossjump_bb (int, basic_block);
83 static bool outgoing_edges_match (int, basic_block, basic_block);
84 static enum replace_direction old_insns_match_p (int, rtx_insn *, rtx_insn *);
86 static void merge_blocks_move_predecessor_nojumps (basic_block, basic_block);
87 static void merge_blocks_move_successor_nojumps (basic_block, basic_block);
88 static bool try_optimize_cfg (int);
89 static bool try_simplify_condjump (basic_block);
90 static bool try_forward_edges (int, basic_block);
91 static edge thread_jump (edge, basic_block);
92 static bool mark_effect (rtx, bitmap);
93 static void notice_new_block (basic_block);
94 static void update_forwarder_flag (basic_block);
95 static void merge_memattrs (rtx, rtx);
97 /* Set flags for newly created block. */
99 static void
100 notice_new_block (basic_block bb)
102 if (!bb)
103 return;
105 if (forwarder_block_p (bb))
106 bb->flags |= BB_FORWARDER_BLOCK;
109 /* Recompute forwarder flag after block has been modified. */
111 static void
112 update_forwarder_flag (basic_block bb)
114 if (forwarder_block_p (bb))
115 bb->flags |= BB_FORWARDER_BLOCK;
116 else
117 bb->flags &= ~BB_FORWARDER_BLOCK;
120 /* Simplify a conditional jump around an unconditional jump.
121 Return true if something changed. */
123 static bool
124 try_simplify_condjump (basic_block cbranch_block)
126 basic_block jump_block, jump_dest_block, cbranch_dest_block;
127 edge cbranch_jump_edge, cbranch_fallthru_edge;
128 rtx_insn *cbranch_insn;
130 /* Verify that there are exactly two successors. */
131 if (EDGE_COUNT (cbranch_block->succs) != 2)
132 return false;
134 /* Verify that we've got a normal conditional branch at the end
135 of the block. */
136 cbranch_insn = BB_END (cbranch_block);
137 if (!any_condjump_p (cbranch_insn))
138 return false;
140 cbranch_fallthru_edge = FALLTHRU_EDGE (cbranch_block);
141 cbranch_jump_edge = BRANCH_EDGE (cbranch_block);
143 /* The next block must not have multiple predecessors, must not
144 be the last block in the function, and must contain just the
145 unconditional jump. */
146 jump_block = cbranch_fallthru_edge->dest;
147 if (!single_pred_p (jump_block)
148 || jump_block->next_bb == EXIT_BLOCK_PTR_FOR_FN (cfun)
149 || !FORWARDER_BLOCK_P (jump_block))
150 return false;
151 jump_dest_block = single_succ (jump_block);
153 /* If we are partitioning hot/cold basic blocks, we don't want to
154 mess up unconditional or indirect jumps that cross between hot
155 and cold sections.
157 Basic block partitioning may result in some jumps that appear to
158 be optimizable (or blocks that appear to be mergeable), but which really
159 must be left untouched (they are required to make it safely across
160 partition boundaries). See the comments at the top of
161 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
163 if (BB_PARTITION (jump_block) != BB_PARTITION (jump_dest_block)
164 || (cbranch_jump_edge->flags & EDGE_CROSSING))
165 return false;
167 /* The conditional branch must target the block after the
168 unconditional branch. */
169 cbranch_dest_block = cbranch_jump_edge->dest;
171 if (cbranch_dest_block == EXIT_BLOCK_PTR_FOR_FN (cfun)
172 || !can_fallthru (jump_block, cbranch_dest_block))
173 return false;
175 /* Invert the conditional branch. */
176 if (!invert_jump (as_a <rtx_jump_insn *> (cbranch_insn),
177 block_label (jump_dest_block), 0))
178 return false;
180 if (dump_file)
181 fprintf (dump_file, "Simplifying condjump %i around jump %i\n",
182 INSN_UID (cbranch_insn), INSN_UID (BB_END (jump_block)));
184 /* Success. Update the CFG to match. Note that after this point
185 the edge variable names appear backwards; the redirection is done
186 this way to preserve edge profile data. */
187 cbranch_jump_edge = redirect_edge_succ_nodup (cbranch_jump_edge,
188 cbranch_dest_block);
189 cbranch_fallthru_edge = redirect_edge_succ_nodup (cbranch_fallthru_edge,
190 jump_dest_block);
191 cbranch_jump_edge->flags |= EDGE_FALLTHRU;
192 cbranch_fallthru_edge->flags &= ~EDGE_FALLTHRU;
193 update_br_prob_note (cbranch_block);
195 /* Delete the block with the unconditional jump, and clean up the mess. */
196 delete_basic_block (jump_block);
197 tidy_fallthru_edge (cbranch_jump_edge);
198 update_forwarder_flag (cbranch_block);
200 return true;
203 /* Attempt to prove that operation is NOOP using CSElib or mark the effect
204 on register. Used by jump threading. */
206 static bool
207 mark_effect (rtx exp, regset nonequal)
209 rtx dest;
210 switch (GET_CODE (exp))
212 /* In case we do clobber the register, mark it as equal, as we know the
213 value is dead so it don't have to match. */
214 case CLOBBER:
215 dest = XEXP (exp, 0);
216 if (REG_P (dest))
217 bitmap_clear_range (nonequal, REGNO (dest), REG_NREGS (dest));
218 return false;
220 case SET:
221 if (rtx_equal_for_cselib_p (SET_DEST (exp), SET_SRC (exp)))
222 return false;
223 dest = SET_DEST (exp);
224 if (dest == pc_rtx)
225 return false;
226 if (!REG_P (dest))
227 return true;
228 bitmap_set_range (nonequal, REGNO (dest), REG_NREGS (dest));
229 return false;
231 default:
232 return false;
236 /* Return true if X contains a register in NONEQUAL. */
237 static bool
238 mentions_nonequal_regs (const_rtx x, regset nonequal)
240 subrtx_iterator::array_type array;
241 FOR_EACH_SUBRTX (iter, array, x, NONCONST)
243 const_rtx x = *iter;
244 if (REG_P (x))
246 unsigned int end_regno = END_REGNO (x);
247 for (unsigned int regno = REGNO (x); regno < end_regno; ++regno)
248 if (REGNO_REG_SET_P (nonequal, regno))
249 return true;
252 return false;
255 /* Attempt to prove that the basic block B will have no side effects and
256 always continues in the same edge if reached via E. Return the edge
257 if exist, NULL otherwise. */
259 static edge
260 thread_jump (edge e, basic_block b)
262 rtx set1, set2, cond1, cond2;
263 rtx_insn *insn;
264 enum rtx_code code1, code2, reversed_code2;
265 bool reverse1 = false;
266 unsigned i;
267 regset nonequal;
268 bool failed = false;
269 reg_set_iterator rsi;
271 if (b->flags & BB_NONTHREADABLE_BLOCK)
272 return NULL;
274 /* At the moment, we do handle only conditional jumps, but later we may
275 want to extend this code to tablejumps and others. */
276 if (EDGE_COUNT (e->src->succs) != 2)
277 return NULL;
278 if (EDGE_COUNT (b->succs) != 2)
280 b->flags |= BB_NONTHREADABLE_BLOCK;
281 return NULL;
284 /* Second branch must end with onlyjump, as we will eliminate the jump. */
285 if (!any_condjump_p (BB_END (e->src)))
286 return NULL;
288 if (!any_condjump_p (BB_END (b)) || !onlyjump_p (BB_END (b)))
290 b->flags |= BB_NONTHREADABLE_BLOCK;
291 return NULL;
294 set1 = pc_set (BB_END (e->src));
295 set2 = pc_set (BB_END (b));
296 if (((e->flags & EDGE_FALLTHRU) != 0)
297 != (XEXP (SET_SRC (set1), 1) == pc_rtx))
298 reverse1 = true;
300 cond1 = XEXP (SET_SRC (set1), 0);
301 cond2 = XEXP (SET_SRC (set2), 0);
302 if (reverse1)
303 code1 = reversed_comparison_code (cond1, BB_END (e->src));
304 else
305 code1 = GET_CODE (cond1);
307 code2 = GET_CODE (cond2);
308 reversed_code2 = reversed_comparison_code (cond2, BB_END (b));
310 if (!comparison_dominates_p (code1, code2)
311 && !comparison_dominates_p (code1, reversed_code2))
312 return NULL;
314 /* Ensure that the comparison operators are equivalent.
315 ??? This is far too pessimistic. We should allow swapped operands,
316 different CCmodes, or for example comparisons for interval, that
317 dominate even when operands are not equivalent. */
318 if (!rtx_equal_p (XEXP (cond1, 0), XEXP (cond2, 0))
319 || !rtx_equal_p (XEXP (cond1, 1), XEXP (cond2, 1)))
320 return NULL;
322 /* Short circuit cases where block B contains some side effects, as we can't
323 safely bypass it. */
324 for (insn = NEXT_INSN (BB_HEAD (b)); insn != NEXT_INSN (BB_END (b));
325 insn = NEXT_INSN (insn))
326 if (INSN_P (insn) && side_effects_p (PATTERN (insn)))
328 b->flags |= BB_NONTHREADABLE_BLOCK;
329 return NULL;
332 cselib_init (0);
334 /* First process all values computed in the source basic block. */
335 for (insn = NEXT_INSN (BB_HEAD (e->src));
336 insn != NEXT_INSN (BB_END (e->src));
337 insn = NEXT_INSN (insn))
338 if (INSN_P (insn))
339 cselib_process_insn (insn);
341 nonequal = BITMAP_ALLOC (NULL);
342 CLEAR_REG_SET (nonequal);
344 /* Now assume that we've continued by the edge E to B and continue
345 processing as if it were same basic block.
346 Our goal is to prove that whole block is an NOOP. */
348 for (insn = NEXT_INSN (BB_HEAD (b));
349 insn != NEXT_INSN (BB_END (b)) && !failed;
350 insn = NEXT_INSN (insn))
352 if (INSN_P (insn))
354 rtx pat = PATTERN (insn);
356 if (GET_CODE (pat) == PARALLEL)
358 for (i = 0; i < (unsigned)XVECLEN (pat, 0); i++)
359 failed |= mark_effect (XVECEXP (pat, 0, i), nonequal);
361 else
362 failed |= mark_effect (pat, nonequal);
365 cselib_process_insn (insn);
368 /* Later we should clear nonequal of dead registers. So far we don't
369 have life information in cfg_cleanup. */
370 if (failed)
372 b->flags |= BB_NONTHREADABLE_BLOCK;
373 goto failed_exit;
376 /* cond2 must not mention any register that is not equal to the
377 former block. */
378 if (mentions_nonequal_regs (cond2, nonequal))
379 goto failed_exit;
381 EXECUTE_IF_SET_IN_REG_SET (nonequal, 0, i, rsi)
382 goto failed_exit;
384 BITMAP_FREE (nonequal);
385 cselib_finish ();
386 if ((comparison_dominates_p (code1, code2) != 0)
387 != (XEXP (SET_SRC (set2), 1) == pc_rtx))
388 return BRANCH_EDGE (b);
389 else
390 return FALLTHRU_EDGE (b);
392 failed_exit:
393 BITMAP_FREE (nonequal);
394 cselib_finish ();
395 return NULL;
398 /* Attempt to forward edges leaving basic block B.
399 Return true if successful. */
401 static bool
402 try_forward_edges (int mode, basic_block b)
404 bool changed = false;
405 edge_iterator ei;
406 edge e, *threaded_edges = NULL;
408 /* If we are partitioning hot/cold basic blocks, we don't want to
409 mess up unconditional or indirect jumps that cross between hot
410 and cold sections.
412 Basic block partitioning may result in some jumps that appear to
413 be optimizable (or blocks that appear to be mergeable), but which really
414 must be left untouched (they are required to make it safely across
415 partition boundaries). See the comments at the top of
416 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
418 if (JUMP_P (BB_END (b)) && CROSSING_JUMP_P (BB_END (b)))
419 return false;
421 for (ei = ei_start (b->succs); (e = ei_safe_edge (ei)); )
423 basic_block target, first;
424 location_t goto_locus;
425 int counter;
426 bool threaded = false;
427 int nthreaded_edges = 0;
428 bool may_thread = first_pass || (b->flags & BB_MODIFIED) != 0;
430 /* Skip complex edges because we don't know how to update them.
432 Still handle fallthru edges, as we can succeed to forward fallthru
433 edge to the same place as the branch edge of conditional branch
434 and turn conditional branch to an unconditional branch. */
435 if (e->flags & EDGE_COMPLEX)
437 ei_next (&ei);
438 continue;
441 target = first = e->dest;
442 counter = NUM_FIXED_BLOCKS;
443 goto_locus = e->goto_locus;
445 /* If we are partitioning hot/cold basic_blocks, we don't want to mess
446 up jumps that cross between hot/cold sections.
448 Basic block partitioning may result in some jumps that appear
449 to be optimizable (or blocks that appear to be mergeable), but which
450 really must be left untouched (they are required to make it safely
451 across partition boundaries). See the comments at the top of
452 bb-reorder.c:partition_hot_cold_basic_blocks for complete
453 details. */
455 if (first != EXIT_BLOCK_PTR_FOR_FN (cfun)
456 && JUMP_P (BB_END (first))
457 && CROSSING_JUMP_P (BB_END (first)))
458 return changed;
460 while (counter < n_basic_blocks_for_fn (cfun))
462 basic_block new_target = NULL;
463 bool new_target_threaded = false;
464 may_thread |= (target->flags & BB_MODIFIED) != 0;
466 if (FORWARDER_BLOCK_P (target)
467 && !(single_succ_edge (target)->flags & EDGE_CROSSING)
468 && single_succ (target) != EXIT_BLOCK_PTR_FOR_FN (cfun))
470 /* Bypass trivial infinite loops. */
471 new_target = single_succ (target);
472 if (target == new_target)
473 counter = n_basic_blocks_for_fn (cfun);
474 else if (!optimize)
476 /* When not optimizing, ensure that edges or forwarder
477 blocks with different locus are not optimized out. */
478 location_t new_locus = single_succ_edge (target)->goto_locus;
479 location_t locus = goto_locus;
481 if (LOCATION_LOCUS (new_locus) != UNKNOWN_LOCATION
482 && LOCATION_LOCUS (locus) != UNKNOWN_LOCATION
483 && new_locus != locus)
484 new_target = NULL;
485 else
487 if (LOCATION_LOCUS (new_locus) != UNKNOWN_LOCATION)
488 locus = new_locus;
490 rtx_insn *last = BB_END (target);
491 if (DEBUG_INSN_P (last))
492 last = prev_nondebug_insn (last);
493 if (last && INSN_P (last))
494 new_locus = INSN_LOCATION (last);
495 else
496 new_locus = UNKNOWN_LOCATION;
498 if (LOCATION_LOCUS (new_locus) != UNKNOWN_LOCATION
499 && LOCATION_LOCUS (locus) != UNKNOWN_LOCATION
500 && new_locus != locus)
501 new_target = NULL;
502 else
504 if (LOCATION_LOCUS (new_locus) != UNKNOWN_LOCATION)
505 locus = new_locus;
507 goto_locus = locus;
513 /* Allow to thread only over one edge at time to simplify updating
514 of probabilities. */
515 else if ((mode & CLEANUP_THREADING) && may_thread)
517 edge t = thread_jump (e, target);
518 if (t)
520 if (!threaded_edges)
521 threaded_edges = XNEWVEC (edge,
522 n_basic_blocks_for_fn (cfun));
523 else
525 int i;
527 /* Detect an infinite loop across blocks not
528 including the start block. */
529 for (i = 0; i < nthreaded_edges; ++i)
530 if (threaded_edges[i] == t)
531 break;
532 if (i < nthreaded_edges)
534 counter = n_basic_blocks_for_fn (cfun);
535 break;
539 /* Detect an infinite loop across the start block. */
540 if (t->dest == b)
541 break;
543 gcc_assert (nthreaded_edges
544 < (n_basic_blocks_for_fn (cfun)
545 - NUM_FIXED_BLOCKS));
546 threaded_edges[nthreaded_edges++] = t;
548 new_target = t->dest;
549 new_target_threaded = true;
553 if (!new_target)
554 break;
556 counter++;
557 target = new_target;
558 threaded |= new_target_threaded;
561 if (counter >= n_basic_blocks_for_fn (cfun))
563 if (dump_file)
564 fprintf (dump_file, "Infinite loop in BB %i.\n",
565 target->index);
567 else if (target == first)
568 ; /* We didn't do anything. */
569 else
571 /* Save the values now, as the edge may get removed. */
572 gcov_type edge_count = e->count;
573 int edge_probability = e->probability;
574 int edge_frequency;
575 int n = 0;
577 e->goto_locus = goto_locus;
579 /* Don't force if target is exit block. */
580 if (threaded && target != EXIT_BLOCK_PTR_FOR_FN (cfun))
582 notice_new_block (redirect_edge_and_branch_force (e, target));
583 if (dump_file)
584 fprintf (dump_file, "Conditionals threaded.\n");
586 else if (!redirect_edge_and_branch (e, target))
588 if (dump_file)
589 fprintf (dump_file,
590 "Forwarding edge %i->%i to %i failed.\n",
591 b->index, e->dest->index, target->index);
592 ei_next (&ei);
593 continue;
596 /* We successfully forwarded the edge. Now update profile
597 data: for each edge we traversed in the chain, remove
598 the original edge's execution count. */
599 edge_frequency = apply_probability (b->frequency, edge_probability);
603 edge t;
605 if (!single_succ_p (first))
607 gcc_assert (n < nthreaded_edges);
608 t = threaded_edges [n++];
609 gcc_assert (t->src == first);
610 update_bb_profile_for_threading (first, edge_frequency,
611 edge_count, t);
612 update_br_prob_note (first);
614 else
616 first->count -= edge_count;
617 if (first->count < 0)
618 first->count = 0;
619 first->frequency -= edge_frequency;
620 if (first->frequency < 0)
621 first->frequency = 0;
622 /* It is possible that as the result of
623 threading we've removed edge as it is
624 threaded to the fallthru edge. Avoid
625 getting out of sync. */
626 if (n < nthreaded_edges
627 && first == threaded_edges [n]->src)
628 n++;
629 t = single_succ_edge (first);
632 t->count -= edge_count;
633 if (t->count < 0)
634 t->count = 0;
635 first = t->dest;
637 while (first != target);
639 changed = true;
640 continue;
642 ei_next (&ei);
645 free (threaded_edges);
646 return changed;
650 /* Blocks A and B are to be merged into a single block. A has no incoming
651 fallthru edge, so it can be moved before B without adding or modifying
652 any jumps (aside from the jump from A to B). */
654 static void
655 merge_blocks_move_predecessor_nojumps (basic_block a, basic_block b)
657 rtx_insn *barrier;
659 /* If we are partitioning hot/cold basic blocks, we don't want to
660 mess up unconditional or indirect jumps that cross between hot
661 and cold sections.
663 Basic block partitioning may result in some jumps that appear to
664 be optimizable (or blocks that appear to be mergeable), but which really
665 must be left untouched (they are required to make it safely across
666 partition boundaries). See the comments at the top of
667 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
669 if (BB_PARTITION (a) != BB_PARTITION (b))
670 return;
672 barrier = next_nonnote_insn (BB_END (a));
673 gcc_assert (BARRIER_P (barrier));
674 delete_insn (barrier);
676 /* Scramble the insn chain. */
677 if (BB_END (a) != PREV_INSN (BB_HEAD (b)))
678 reorder_insns_nobb (BB_HEAD (a), BB_END (a), PREV_INSN (BB_HEAD (b)));
679 df_set_bb_dirty (a);
681 if (dump_file)
682 fprintf (dump_file, "Moved block %d before %d and merged.\n",
683 a->index, b->index);
685 /* Swap the records for the two blocks around. */
687 unlink_block (a);
688 link_block (a, b->prev_bb);
690 /* Now blocks A and B are contiguous. Merge them. */
691 merge_blocks (a, b);
694 /* Blocks A and B are to be merged into a single block. B has no outgoing
695 fallthru edge, so it can be moved after A without adding or modifying
696 any jumps (aside from the jump from A to B). */
698 static void
699 merge_blocks_move_successor_nojumps (basic_block a, basic_block b)
701 rtx_insn *barrier, *real_b_end;
702 rtx label;
703 rtx_jump_table_data *table;
705 /* If we are partitioning hot/cold basic blocks, we don't want to
706 mess up unconditional or indirect jumps that cross between hot
707 and cold sections.
709 Basic block partitioning may result in some jumps that appear to
710 be optimizable (or blocks that appear to be mergeable), but which really
711 must be left untouched (they are required to make it safely across
712 partition boundaries). See the comments at the top of
713 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
715 if (BB_PARTITION (a) != BB_PARTITION (b))
716 return;
718 real_b_end = BB_END (b);
720 /* If there is a jump table following block B temporarily add the jump table
721 to block B so that it will also be moved to the correct location. */
722 if (tablejump_p (BB_END (b), &label, &table)
723 && prev_active_insn (label) == BB_END (b))
725 BB_END (b) = table;
728 /* There had better have been a barrier there. Delete it. */
729 barrier = NEXT_INSN (BB_END (b));
730 if (barrier && BARRIER_P (barrier))
731 delete_insn (barrier);
734 /* Scramble the insn chain. */
735 reorder_insns_nobb (BB_HEAD (b), BB_END (b), BB_END (a));
737 /* Restore the real end of b. */
738 BB_END (b) = real_b_end;
740 if (dump_file)
741 fprintf (dump_file, "Moved block %d after %d and merged.\n",
742 b->index, a->index);
744 /* Now blocks A and B are contiguous. Merge them. */
745 merge_blocks (a, b);
748 /* Attempt to merge basic blocks that are potentially non-adjacent.
749 Return NULL iff the attempt failed, otherwise return basic block
750 where cleanup_cfg should continue. Because the merging commonly
751 moves basic block away or introduces another optimization
752 possibility, return basic block just before B so cleanup_cfg don't
753 need to iterate.
755 It may be good idea to return basic block before C in the case
756 C has been moved after B and originally appeared earlier in the
757 insn sequence, but we have no information available about the
758 relative ordering of these two. Hopefully it is not too common. */
760 static basic_block
761 merge_blocks_move (edge e, basic_block b, basic_block c, int mode)
763 basic_block next;
765 /* If we are partitioning hot/cold basic blocks, we don't want to
766 mess up unconditional or indirect jumps that cross between hot
767 and cold sections.
769 Basic block partitioning may result in some jumps that appear to
770 be optimizable (or blocks that appear to be mergeable), but which really
771 must be left untouched (they are required to make it safely across
772 partition boundaries). See the comments at the top of
773 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
775 if (BB_PARTITION (b) != BB_PARTITION (c))
776 return NULL;
778 /* If B has a fallthru edge to C, no need to move anything. */
779 if (e->flags & EDGE_FALLTHRU)
781 int b_index = b->index, c_index = c->index;
783 /* Protect the loop latches. */
784 if (current_loops && c->loop_father->latch == c)
785 return NULL;
787 merge_blocks (b, c);
788 update_forwarder_flag (b);
790 if (dump_file)
791 fprintf (dump_file, "Merged %d and %d without moving.\n",
792 b_index, c_index);
794 return b->prev_bb == ENTRY_BLOCK_PTR_FOR_FN (cfun) ? b : b->prev_bb;
797 /* Otherwise we will need to move code around. Do that only if expensive
798 transformations are allowed. */
799 else if (mode & CLEANUP_EXPENSIVE)
801 edge tmp_edge, b_fallthru_edge;
802 bool c_has_outgoing_fallthru;
803 bool b_has_incoming_fallthru;
805 /* Avoid overactive code motion, as the forwarder blocks should be
806 eliminated by edge redirection instead. One exception might have
807 been if B is a forwarder block and C has no fallthru edge, but
808 that should be cleaned up by bb-reorder instead. */
809 if (FORWARDER_BLOCK_P (b) || FORWARDER_BLOCK_P (c))
810 return NULL;
812 /* We must make sure to not munge nesting of lexical blocks,
813 and loop notes. This is done by squeezing out all the notes
814 and leaving them there to lie. Not ideal, but functional. */
816 tmp_edge = find_fallthru_edge (c->succs);
817 c_has_outgoing_fallthru = (tmp_edge != NULL);
819 tmp_edge = find_fallthru_edge (b->preds);
820 b_has_incoming_fallthru = (tmp_edge != NULL);
821 b_fallthru_edge = tmp_edge;
822 next = b->prev_bb;
823 if (next == c)
824 next = next->prev_bb;
826 /* Otherwise, we're going to try to move C after B. If C does
827 not have an outgoing fallthru, then it can be moved
828 immediately after B without introducing or modifying jumps. */
829 if (! c_has_outgoing_fallthru)
831 merge_blocks_move_successor_nojumps (b, c);
832 return next == ENTRY_BLOCK_PTR_FOR_FN (cfun) ? next->next_bb : next;
835 /* If B does not have an incoming fallthru, then it can be moved
836 immediately before C without introducing or modifying jumps.
837 C cannot be the first block, so we do not have to worry about
838 accessing a non-existent block. */
840 if (b_has_incoming_fallthru)
842 basic_block bb;
844 if (b_fallthru_edge->src == ENTRY_BLOCK_PTR_FOR_FN (cfun))
845 return NULL;
846 bb = force_nonfallthru (b_fallthru_edge);
847 if (bb)
848 notice_new_block (bb);
851 merge_blocks_move_predecessor_nojumps (b, c);
852 return next == ENTRY_BLOCK_PTR_FOR_FN (cfun) ? next->next_bb : next;
855 return NULL;
859 /* Removes the memory attributes of MEM expression
860 if they are not equal. */
862 static void
863 merge_memattrs (rtx x, rtx y)
865 int i;
866 int j;
867 enum rtx_code code;
868 const char *fmt;
870 if (x == y)
871 return;
872 if (x == 0 || y == 0)
873 return;
875 code = GET_CODE (x);
877 if (code != GET_CODE (y))
878 return;
880 if (GET_MODE (x) != GET_MODE (y))
881 return;
883 if (code == MEM && !mem_attrs_eq_p (MEM_ATTRS (x), MEM_ATTRS (y)))
885 if (! MEM_ATTRS (x))
886 MEM_ATTRS (y) = 0;
887 else if (! MEM_ATTRS (y))
888 MEM_ATTRS (x) = 0;
889 else
891 HOST_WIDE_INT mem_size;
893 if (MEM_ALIAS_SET (x) != MEM_ALIAS_SET (y))
895 set_mem_alias_set (x, 0);
896 set_mem_alias_set (y, 0);
899 if (! mem_expr_equal_p (MEM_EXPR (x), MEM_EXPR (y)))
901 set_mem_expr (x, 0);
902 set_mem_expr (y, 0);
903 clear_mem_offset (x);
904 clear_mem_offset (y);
906 else if (MEM_OFFSET_KNOWN_P (x) != MEM_OFFSET_KNOWN_P (y)
907 || (MEM_OFFSET_KNOWN_P (x)
908 && MEM_OFFSET (x) != MEM_OFFSET (y)))
910 clear_mem_offset (x);
911 clear_mem_offset (y);
914 if (MEM_SIZE_KNOWN_P (x) && MEM_SIZE_KNOWN_P (y))
916 mem_size = MAX (MEM_SIZE (x), MEM_SIZE (y));
917 set_mem_size (x, mem_size);
918 set_mem_size (y, mem_size);
920 else
922 clear_mem_size (x);
923 clear_mem_size (y);
926 set_mem_align (x, MIN (MEM_ALIGN (x), MEM_ALIGN (y)));
927 set_mem_align (y, MEM_ALIGN (x));
930 if (code == MEM)
932 if (MEM_READONLY_P (x) != MEM_READONLY_P (y))
934 MEM_READONLY_P (x) = 0;
935 MEM_READONLY_P (y) = 0;
937 if (MEM_NOTRAP_P (x) != MEM_NOTRAP_P (y))
939 MEM_NOTRAP_P (x) = 0;
940 MEM_NOTRAP_P (y) = 0;
942 if (MEM_VOLATILE_P (x) != MEM_VOLATILE_P (y))
944 MEM_VOLATILE_P (x) = 1;
945 MEM_VOLATILE_P (y) = 1;
949 fmt = GET_RTX_FORMAT (code);
950 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
952 switch (fmt[i])
954 case 'E':
955 /* Two vectors must have the same length. */
956 if (XVECLEN (x, i) != XVECLEN (y, i))
957 return;
959 for (j = 0; j < XVECLEN (x, i); j++)
960 merge_memattrs (XVECEXP (x, i, j), XVECEXP (y, i, j));
962 break;
964 case 'e':
965 merge_memattrs (XEXP (x, i), XEXP (y, i));
968 return;
972 /* Checks if patterns P1 and P2 are equivalent, apart from the possibly
973 different single sets S1 and S2. */
975 static bool
976 equal_different_set_p (rtx p1, rtx s1, rtx p2, rtx s2)
978 int i;
979 rtx e1, e2;
981 if (p1 == s1 && p2 == s2)
982 return true;
984 if (GET_CODE (p1) != PARALLEL || GET_CODE (p2) != PARALLEL)
985 return false;
987 if (XVECLEN (p1, 0) != XVECLEN (p2, 0))
988 return false;
990 for (i = 0; i < XVECLEN (p1, 0); i++)
992 e1 = XVECEXP (p1, 0, i);
993 e2 = XVECEXP (p2, 0, i);
994 if (e1 == s1 && e2 == s2)
995 continue;
996 if (reload_completed
997 ? rtx_renumbered_equal_p (e1, e2) : rtx_equal_p (e1, e2))
998 continue;
1000 return false;
1003 return true;
1007 /* NOTE1 is the REG_EQUAL note, if any, attached to an insn
1008 that is a single_set with a SET_SRC of SRC1. Similarly
1009 for NOTE2/SRC2.
1011 So effectively NOTE1/NOTE2 are an alternate form of
1012 SRC1/SRC2 respectively.
1014 Return nonzero if SRC1 or NOTE1 has the same constant
1015 integer value as SRC2 or NOTE2. Else return zero. */
1016 static int
1017 values_equal_p (rtx note1, rtx note2, rtx src1, rtx src2)
1019 if (note1
1020 && note2
1021 && CONST_INT_P (XEXP (note1, 0))
1022 && rtx_equal_p (XEXP (note1, 0), XEXP (note2, 0)))
1023 return 1;
1025 if (!note1
1026 && !note2
1027 && CONST_INT_P (src1)
1028 && CONST_INT_P (src2)
1029 && rtx_equal_p (src1, src2))
1030 return 1;
1032 if (note1
1033 && CONST_INT_P (src2)
1034 && rtx_equal_p (XEXP (note1, 0), src2))
1035 return 1;
1037 if (note2
1038 && CONST_INT_P (src1)
1039 && rtx_equal_p (XEXP (note2, 0), src1))
1040 return 1;
1042 return 0;
1045 /* Examine register notes on I1 and I2 and return:
1046 - dir_forward if I1 can be replaced by I2, or
1047 - dir_backward if I2 can be replaced by I1, or
1048 - dir_both if both are the case. */
1050 static enum replace_direction
1051 can_replace_by (rtx_insn *i1, rtx_insn *i2)
1053 rtx s1, s2, d1, d2, src1, src2, note1, note2;
1054 bool c1, c2;
1056 /* Check for 2 sets. */
1057 s1 = single_set (i1);
1058 s2 = single_set (i2);
1059 if (s1 == NULL_RTX || s2 == NULL_RTX)
1060 return dir_none;
1062 /* Check that the 2 sets set the same dest. */
1063 d1 = SET_DEST (s1);
1064 d2 = SET_DEST (s2);
1065 if (!(reload_completed
1066 ? rtx_renumbered_equal_p (d1, d2) : rtx_equal_p (d1, d2)))
1067 return dir_none;
1069 /* Find identical req_equiv or reg_equal note, which implies that the 2 sets
1070 set dest to the same value. */
1071 note1 = find_reg_equal_equiv_note (i1);
1072 note2 = find_reg_equal_equiv_note (i2);
1074 src1 = SET_SRC (s1);
1075 src2 = SET_SRC (s2);
1077 if (!values_equal_p (note1, note2, src1, src2))
1078 return dir_none;
1080 if (!equal_different_set_p (PATTERN (i1), s1, PATTERN (i2), s2))
1081 return dir_none;
1083 /* Although the 2 sets set dest to the same value, we cannot replace
1084 (set (dest) (const_int))
1086 (set (dest) (reg))
1087 because we don't know if the reg is live and has the same value at the
1088 location of replacement. */
1089 c1 = CONST_INT_P (src1);
1090 c2 = CONST_INT_P (src2);
1091 if (c1 && c2)
1092 return dir_both;
1093 else if (c2)
1094 return dir_forward;
1095 else if (c1)
1096 return dir_backward;
1098 return dir_none;
1101 /* Merges directions A and B. */
1103 static enum replace_direction
1104 merge_dir (enum replace_direction a, enum replace_direction b)
1106 /* Implements the following table:
1107 |bo fw bw no
1108 ---+-----------
1109 bo |bo fw bw no
1110 fw |-- fw no no
1111 bw |-- -- bw no
1112 no |-- -- -- no. */
1114 if (a == b)
1115 return a;
1117 if (a == dir_both)
1118 return b;
1119 if (b == dir_both)
1120 return a;
1122 return dir_none;
1125 /* Examine I1 and I2 and return:
1126 - dir_forward if I1 can be replaced by I2, or
1127 - dir_backward if I2 can be replaced by I1, or
1128 - dir_both if both are the case. */
1130 static enum replace_direction
1131 old_insns_match_p (int mode ATTRIBUTE_UNUSED, rtx_insn *i1, rtx_insn *i2)
1133 rtx p1, p2;
1135 /* Verify that I1 and I2 are equivalent. */
1136 if (GET_CODE (i1) != GET_CODE (i2))
1137 return dir_none;
1139 /* __builtin_unreachable() may lead to empty blocks (ending with
1140 NOTE_INSN_BASIC_BLOCK). They may be crossjumped. */
1141 if (NOTE_INSN_BASIC_BLOCK_P (i1) && NOTE_INSN_BASIC_BLOCK_P (i2))
1142 return dir_both;
1144 /* ??? Do not allow cross-jumping between different stack levels. */
1145 p1 = find_reg_note (i1, REG_ARGS_SIZE, NULL);
1146 p2 = find_reg_note (i2, REG_ARGS_SIZE, NULL);
1147 if (p1 && p2)
1149 p1 = XEXP (p1, 0);
1150 p2 = XEXP (p2, 0);
1151 if (!rtx_equal_p (p1, p2))
1152 return dir_none;
1154 /* ??? Worse, this adjustment had better be constant lest we
1155 have differing incoming stack levels. */
1156 if (!frame_pointer_needed
1157 && find_args_size_adjust (i1) == HOST_WIDE_INT_MIN)
1158 return dir_none;
1160 else if (p1 || p2)
1161 return dir_none;
1163 p1 = PATTERN (i1);
1164 p2 = PATTERN (i2);
1166 if (GET_CODE (p1) != GET_CODE (p2))
1167 return dir_none;
1169 /* If this is a CALL_INSN, compare register usage information.
1170 If we don't check this on stack register machines, the two
1171 CALL_INSNs might be merged leaving reg-stack.c with mismatching
1172 numbers of stack registers in the same basic block.
1173 If we don't check this on machines with delay slots, a delay slot may
1174 be filled that clobbers a parameter expected by the subroutine.
1176 ??? We take the simple route for now and assume that if they're
1177 equal, they were constructed identically.
1179 Also check for identical exception regions. */
1181 if (CALL_P (i1))
1183 /* Ensure the same EH region. */
1184 rtx n1 = find_reg_note (i1, REG_EH_REGION, 0);
1185 rtx n2 = find_reg_note (i2, REG_EH_REGION, 0);
1187 if (!n1 && n2)
1188 return dir_none;
1190 if (n1 && (!n2 || XEXP (n1, 0) != XEXP (n2, 0)))
1191 return dir_none;
1193 if (!rtx_equal_p (CALL_INSN_FUNCTION_USAGE (i1),
1194 CALL_INSN_FUNCTION_USAGE (i2))
1195 || SIBLING_CALL_P (i1) != SIBLING_CALL_P (i2))
1196 return dir_none;
1198 /* For address sanitizer, never crossjump __asan_report_* builtins,
1199 otherwise errors might be reported on incorrect lines. */
1200 if (flag_sanitize & SANITIZE_ADDRESS)
1202 rtx call = get_call_rtx_from (i1);
1203 if (call && GET_CODE (XEXP (XEXP (call, 0), 0)) == SYMBOL_REF)
1205 rtx symbol = XEXP (XEXP (call, 0), 0);
1206 if (SYMBOL_REF_DECL (symbol)
1207 && TREE_CODE (SYMBOL_REF_DECL (symbol)) == FUNCTION_DECL)
1209 if ((DECL_BUILT_IN_CLASS (SYMBOL_REF_DECL (symbol))
1210 == BUILT_IN_NORMAL)
1211 && DECL_FUNCTION_CODE (SYMBOL_REF_DECL (symbol))
1212 >= BUILT_IN_ASAN_REPORT_LOAD1
1213 && DECL_FUNCTION_CODE (SYMBOL_REF_DECL (symbol))
1214 <= BUILT_IN_ASAN_STOREN)
1215 return dir_none;
1221 #ifdef STACK_REGS
1222 /* If cross_jump_death_matters is not 0, the insn's mode
1223 indicates whether or not the insn contains any stack-like
1224 regs. */
1226 if ((mode & CLEANUP_POST_REGSTACK) && stack_regs_mentioned (i1))
1228 /* If register stack conversion has already been done, then
1229 death notes must also be compared before it is certain that
1230 the two instruction streams match. */
1232 rtx note;
1233 HARD_REG_SET i1_regset, i2_regset;
1235 CLEAR_HARD_REG_SET (i1_regset);
1236 CLEAR_HARD_REG_SET (i2_regset);
1238 for (note = REG_NOTES (i1); note; note = XEXP (note, 1))
1239 if (REG_NOTE_KIND (note) == REG_DEAD && STACK_REG_P (XEXP (note, 0)))
1240 SET_HARD_REG_BIT (i1_regset, REGNO (XEXP (note, 0)));
1242 for (note = REG_NOTES (i2); note; note = XEXP (note, 1))
1243 if (REG_NOTE_KIND (note) == REG_DEAD && STACK_REG_P (XEXP (note, 0)))
1244 SET_HARD_REG_BIT (i2_regset, REGNO (XEXP (note, 0)));
1246 if (!hard_reg_set_equal_p (i1_regset, i2_regset))
1247 return dir_none;
1249 #endif
1251 if (reload_completed
1252 ? rtx_renumbered_equal_p (p1, p2) : rtx_equal_p (p1, p2))
1253 return dir_both;
1255 return can_replace_by (i1, i2);
1258 /* When comparing insns I1 and I2 in flow_find_cross_jump or
1259 flow_find_head_matching_sequence, ensure the notes match. */
1261 static void
1262 merge_notes (rtx_insn *i1, rtx_insn *i2)
1264 /* If the merged insns have different REG_EQUAL notes, then
1265 remove them. */
1266 rtx equiv1 = find_reg_equal_equiv_note (i1);
1267 rtx equiv2 = find_reg_equal_equiv_note (i2);
1269 if (equiv1 && !equiv2)
1270 remove_note (i1, equiv1);
1271 else if (!equiv1 && equiv2)
1272 remove_note (i2, equiv2);
1273 else if (equiv1 && equiv2
1274 && !rtx_equal_p (XEXP (equiv1, 0), XEXP (equiv2, 0)))
1276 remove_note (i1, equiv1);
1277 remove_note (i2, equiv2);
1281 /* Walks from I1 in BB1 backward till the next non-debug insn, and returns the
1282 resulting insn in I1, and the corresponding bb in BB1. At the head of a
1283 bb, if there is a predecessor bb that reaches this bb via fallthru, and
1284 FOLLOW_FALLTHRU, walks further in the predecessor bb and registers this in
1285 DID_FALLTHRU. Otherwise, stops at the head of the bb. */
1287 static void
1288 walk_to_nondebug_insn (rtx_insn **i1, basic_block *bb1, bool follow_fallthru,
1289 bool *did_fallthru)
1291 edge fallthru;
1293 *did_fallthru = false;
1295 /* Ignore notes. */
1296 while (!NONDEBUG_INSN_P (*i1))
1298 if (*i1 != BB_HEAD (*bb1))
1300 *i1 = PREV_INSN (*i1);
1301 continue;
1304 if (!follow_fallthru)
1305 return;
1307 fallthru = find_fallthru_edge ((*bb1)->preds);
1308 if (!fallthru || fallthru->src == ENTRY_BLOCK_PTR_FOR_FN (cfun)
1309 || !single_succ_p (fallthru->src))
1310 return;
1312 *bb1 = fallthru->src;
1313 *i1 = BB_END (*bb1);
1314 *did_fallthru = true;
1318 /* Look through the insns at the end of BB1 and BB2 and find the longest
1319 sequence that are either equivalent, or allow forward or backward
1320 replacement. Store the first insns for that sequence in *F1 and *F2 and
1321 return the sequence length.
1323 DIR_P indicates the allowed replacement direction on function entry, and
1324 the actual replacement direction on function exit. If NULL, only equivalent
1325 sequences are allowed.
1327 To simplify callers of this function, if the blocks match exactly,
1328 store the head of the blocks in *F1 and *F2. */
1331 flow_find_cross_jump (basic_block bb1, basic_block bb2, rtx_insn **f1,
1332 rtx_insn **f2, enum replace_direction *dir_p)
1334 rtx_insn *i1, *i2, *last1, *last2, *afterlast1, *afterlast2;
1335 int ninsns = 0;
1336 enum replace_direction dir, last_dir, afterlast_dir;
1337 bool follow_fallthru, did_fallthru;
1339 if (dir_p)
1340 dir = *dir_p;
1341 else
1342 dir = dir_both;
1343 afterlast_dir = dir;
1344 last_dir = afterlast_dir;
1346 /* Skip simple jumps at the end of the blocks. Complex jumps still
1347 need to be compared for equivalence, which we'll do below. */
1349 i1 = BB_END (bb1);
1350 last1 = afterlast1 = last2 = afterlast2 = NULL;
1351 if (onlyjump_p (i1)
1352 || (returnjump_p (i1) && !side_effects_p (PATTERN (i1))))
1354 last1 = i1;
1355 i1 = PREV_INSN (i1);
1358 i2 = BB_END (bb2);
1359 if (onlyjump_p (i2)
1360 || (returnjump_p (i2) && !side_effects_p (PATTERN (i2))))
1362 last2 = i2;
1363 /* Count everything except for unconditional jump as insn.
1364 Don't count any jumps if dir_p is NULL. */
1365 if (!simplejump_p (i2) && !returnjump_p (i2) && last1 && dir_p)
1366 ninsns++;
1367 i2 = PREV_INSN (i2);
1370 while (true)
1372 /* In the following example, we can replace all jumps to C by jumps to A.
1374 This removes 4 duplicate insns.
1375 [bb A] insn1 [bb C] insn1
1376 insn2 insn2
1377 [bb B] insn3 insn3
1378 insn4 insn4
1379 jump_insn jump_insn
1381 We could also replace all jumps to A by jumps to C, but that leaves B
1382 alive, and removes only 2 duplicate insns. In a subsequent crossjump
1383 step, all jumps to B would be replaced with jumps to the middle of C,
1384 achieving the same result with more effort.
1385 So we allow only the first possibility, which means that we don't allow
1386 fallthru in the block that's being replaced. */
1388 follow_fallthru = dir_p && dir != dir_forward;
1389 walk_to_nondebug_insn (&i1, &bb1, follow_fallthru, &did_fallthru);
1390 if (did_fallthru)
1391 dir = dir_backward;
1393 follow_fallthru = dir_p && dir != dir_backward;
1394 walk_to_nondebug_insn (&i2, &bb2, follow_fallthru, &did_fallthru);
1395 if (did_fallthru)
1396 dir = dir_forward;
1398 if (i1 == BB_HEAD (bb1) || i2 == BB_HEAD (bb2))
1399 break;
1401 dir = merge_dir (dir, old_insns_match_p (0, i1, i2));
1402 if (dir == dir_none || (!dir_p && dir != dir_both))
1403 break;
1405 merge_memattrs (i1, i2);
1407 /* Don't begin a cross-jump with a NOTE insn. */
1408 if (INSN_P (i1))
1410 merge_notes (i1, i2);
1412 afterlast1 = last1, afterlast2 = last2;
1413 last1 = i1, last2 = i2;
1414 afterlast_dir = last_dir;
1415 last_dir = dir;
1416 if (active_insn_p (i1))
1417 ninsns++;
1420 i1 = PREV_INSN (i1);
1421 i2 = PREV_INSN (i2);
1424 /* Don't allow the insn after a compare to be shared by
1425 cross-jumping unless the compare is also shared. */
1426 if (HAVE_cc0 && ninsns && reg_mentioned_p (cc0_rtx, last1)
1427 && ! sets_cc0_p (last1))
1428 last1 = afterlast1, last2 = afterlast2, last_dir = afterlast_dir, ninsns--;
1430 /* Include preceding notes and labels in the cross-jump. One,
1431 this may bring us to the head of the blocks as requested above.
1432 Two, it keeps line number notes as matched as may be. */
1433 if (ninsns)
1435 bb1 = BLOCK_FOR_INSN (last1);
1436 while (last1 != BB_HEAD (bb1) && !NONDEBUG_INSN_P (PREV_INSN (last1)))
1437 last1 = PREV_INSN (last1);
1439 if (last1 != BB_HEAD (bb1) && LABEL_P (PREV_INSN (last1)))
1440 last1 = PREV_INSN (last1);
1442 bb2 = BLOCK_FOR_INSN (last2);
1443 while (last2 != BB_HEAD (bb2) && !NONDEBUG_INSN_P (PREV_INSN (last2)))
1444 last2 = PREV_INSN (last2);
1446 if (last2 != BB_HEAD (bb2) && LABEL_P (PREV_INSN (last2)))
1447 last2 = PREV_INSN (last2);
1449 *f1 = last1;
1450 *f2 = last2;
1453 if (dir_p)
1454 *dir_p = last_dir;
1455 return ninsns;
1458 /* Like flow_find_cross_jump, except start looking for a matching sequence from
1459 the head of the two blocks. Do not include jumps at the end.
1460 If STOP_AFTER is nonzero, stop after finding that many matching
1461 instructions. If STOP_AFTER is zero, count all INSN_P insns, if it is
1462 non-zero, only count active insns. */
1465 flow_find_head_matching_sequence (basic_block bb1, basic_block bb2, rtx_insn **f1,
1466 rtx_insn **f2, int stop_after)
1468 rtx_insn *i1, *i2, *last1, *last2, *beforelast1, *beforelast2;
1469 int ninsns = 0;
1470 edge e;
1471 edge_iterator ei;
1472 int nehedges1 = 0, nehedges2 = 0;
1474 FOR_EACH_EDGE (e, ei, bb1->succs)
1475 if (e->flags & EDGE_EH)
1476 nehedges1++;
1477 FOR_EACH_EDGE (e, ei, bb2->succs)
1478 if (e->flags & EDGE_EH)
1479 nehedges2++;
1481 i1 = BB_HEAD (bb1);
1482 i2 = BB_HEAD (bb2);
1483 last1 = beforelast1 = last2 = beforelast2 = NULL;
1485 while (true)
1487 /* Ignore notes, except NOTE_INSN_EPILOGUE_BEG. */
1488 while (!NONDEBUG_INSN_P (i1) && i1 != BB_END (bb1))
1490 if (NOTE_P (i1) && NOTE_KIND (i1) == NOTE_INSN_EPILOGUE_BEG)
1491 break;
1492 i1 = NEXT_INSN (i1);
1495 while (!NONDEBUG_INSN_P (i2) && i2 != BB_END (bb2))
1497 if (NOTE_P (i2) && NOTE_KIND (i2) == NOTE_INSN_EPILOGUE_BEG)
1498 break;
1499 i2 = NEXT_INSN (i2);
1502 if ((i1 == BB_END (bb1) && !NONDEBUG_INSN_P (i1))
1503 || (i2 == BB_END (bb2) && !NONDEBUG_INSN_P (i2)))
1504 break;
1506 if (NOTE_P (i1) || NOTE_P (i2)
1507 || JUMP_P (i1) || JUMP_P (i2))
1508 break;
1510 /* A sanity check to make sure we're not merging insns with different
1511 effects on EH. If only one of them ends a basic block, it shouldn't
1512 have an EH edge; if both end a basic block, there should be the same
1513 number of EH edges. */
1514 if ((i1 == BB_END (bb1) && i2 != BB_END (bb2)
1515 && nehedges1 > 0)
1516 || (i2 == BB_END (bb2) && i1 != BB_END (bb1)
1517 && nehedges2 > 0)
1518 || (i1 == BB_END (bb1) && i2 == BB_END (bb2)
1519 && nehedges1 != nehedges2))
1520 break;
1522 if (old_insns_match_p (0, i1, i2) != dir_both)
1523 break;
1525 merge_memattrs (i1, i2);
1527 /* Don't begin a cross-jump with a NOTE insn. */
1528 if (INSN_P (i1))
1530 merge_notes (i1, i2);
1532 beforelast1 = last1, beforelast2 = last2;
1533 last1 = i1, last2 = i2;
1534 if (!stop_after || active_insn_p (i1))
1535 ninsns++;
1538 if (i1 == BB_END (bb1) || i2 == BB_END (bb2)
1539 || (stop_after > 0 && ninsns == stop_after))
1540 break;
1542 i1 = NEXT_INSN (i1);
1543 i2 = NEXT_INSN (i2);
1546 /* Don't allow a compare to be shared by cross-jumping unless the insn
1547 after the compare is also shared. */
1548 if (HAVE_cc0 && ninsns && reg_mentioned_p (cc0_rtx, last1)
1549 && sets_cc0_p (last1))
1550 last1 = beforelast1, last2 = beforelast2, ninsns--;
1552 if (ninsns)
1554 *f1 = last1;
1555 *f2 = last2;
1558 return ninsns;
1561 /* Return true iff outgoing edges of BB1 and BB2 match, together with
1562 the branch instruction. This means that if we commonize the control
1563 flow before end of the basic block, the semantic remains unchanged.
1565 We may assume that there exists one edge with a common destination. */
1567 static bool
1568 outgoing_edges_match (int mode, basic_block bb1, basic_block bb2)
1570 int nehedges1 = 0, nehedges2 = 0;
1571 edge fallthru1 = 0, fallthru2 = 0;
1572 edge e1, e2;
1573 edge_iterator ei;
1575 /* If we performed shrink-wrapping, edges to the exit block can
1576 only be distinguished for JUMP_INSNs. The two paths may differ in
1577 whether they went through the prologue. Sibcalls are fine, we know
1578 that we either didn't need or inserted an epilogue before them. */
1579 if (crtl->shrink_wrapped
1580 && single_succ_p (bb1)
1581 && single_succ (bb1) == EXIT_BLOCK_PTR_FOR_FN (cfun)
1582 && !JUMP_P (BB_END (bb1))
1583 && !(CALL_P (BB_END (bb1)) && SIBLING_CALL_P (BB_END (bb1))))
1584 return false;
1586 /* If BB1 has only one successor, we may be looking at either an
1587 unconditional jump, or a fake edge to exit. */
1588 if (single_succ_p (bb1)
1589 && (single_succ_edge (bb1)->flags & (EDGE_COMPLEX | EDGE_FAKE)) == 0
1590 && (!JUMP_P (BB_END (bb1)) || simplejump_p (BB_END (bb1))))
1591 return (single_succ_p (bb2)
1592 && (single_succ_edge (bb2)->flags
1593 & (EDGE_COMPLEX | EDGE_FAKE)) == 0
1594 && (!JUMP_P (BB_END (bb2)) || simplejump_p (BB_END (bb2))));
1596 /* Match conditional jumps - this may get tricky when fallthru and branch
1597 edges are crossed. */
1598 if (EDGE_COUNT (bb1->succs) == 2
1599 && any_condjump_p (BB_END (bb1))
1600 && onlyjump_p (BB_END (bb1)))
1602 edge b1, f1, b2, f2;
1603 bool reverse, match;
1604 rtx set1, set2, cond1, cond2;
1605 enum rtx_code code1, code2;
1607 if (EDGE_COUNT (bb2->succs) != 2
1608 || !any_condjump_p (BB_END (bb2))
1609 || !onlyjump_p (BB_END (bb2)))
1610 return false;
1612 b1 = BRANCH_EDGE (bb1);
1613 b2 = BRANCH_EDGE (bb2);
1614 f1 = FALLTHRU_EDGE (bb1);
1615 f2 = FALLTHRU_EDGE (bb2);
1617 /* Get around possible forwarders on fallthru edges. Other cases
1618 should be optimized out already. */
1619 if (FORWARDER_BLOCK_P (f1->dest))
1620 f1 = single_succ_edge (f1->dest);
1622 if (FORWARDER_BLOCK_P (f2->dest))
1623 f2 = single_succ_edge (f2->dest);
1625 /* To simplify use of this function, return false if there are
1626 unneeded forwarder blocks. These will get eliminated later
1627 during cleanup_cfg. */
1628 if (FORWARDER_BLOCK_P (f1->dest)
1629 || FORWARDER_BLOCK_P (f2->dest)
1630 || FORWARDER_BLOCK_P (b1->dest)
1631 || FORWARDER_BLOCK_P (b2->dest))
1632 return false;
1634 if (f1->dest == f2->dest && b1->dest == b2->dest)
1635 reverse = false;
1636 else if (f1->dest == b2->dest && b1->dest == f2->dest)
1637 reverse = true;
1638 else
1639 return false;
1641 set1 = pc_set (BB_END (bb1));
1642 set2 = pc_set (BB_END (bb2));
1643 if ((XEXP (SET_SRC (set1), 1) == pc_rtx)
1644 != (XEXP (SET_SRC (set2), 1) == pc_rtx))
1645 reverse = !reverse;
1647 cond1 = XEXP (SET_SRC (set1), 0);
1648 cond2 = XEXP (SET_SRC (set2), 0);
1649 code1 = GET_CODE (cond1);
1650 if (reverse)
1651 code2 = reversed_comparison_code (cond2, BB_END (bb2));
1652 else
1653 code2 = GET_CODE (cond2);
1655 if (code2 == UNKNOWN)
1656 return false;
1658 /* Verify codes and operands match. */
1659 match = ((code1 == code2
1660 && rtx_renumbered_equal_p (XEXP (cond1, 0), XEXP (cond2, 0))
1661 && rtx_renumbered_equal_p (XEXP (cond1, 1), XEXP (cond2, 1)))
1662 || (code1 == swap_condition (code2)
1663 && rtx_renumbered_equal_p (XEXP (cond1, 1),
1664 XEXP (cond2, 0))
1665 && rtx_renumbered_equal_p (XEXP (cond1, 0),
1666 XEXP (cond2, 1))));
1668 /* If we return true, we will join the blocks. Which means that
1669 we will only have one branch prediction bit to work with. Thus
1670 we require the existing branches to have probabilities that are
1671 roughly similar. */
1672 if (match
1673 && optimize_bb_for_speed_p (bb1)
1674 && optimize_bb_for_speed_p (bb2))
1676 int prob2;
1678 if (b1->dest == b2->dest)
1679 prob2 = b2->probability;
1680 else
1681 /* Do not use f2 probability as f2 may be forwarded. */
1682 prob2 = REG_BR_PROB_BASE - b2->probability;
1684 /* Fail if the difference in probabilities is greater than 50%.
1685 This rules out two well-predicted branches with opposite
1686 outcomes. */
1687 if (abs (b1->probability - prob2) > REG_BR_PROB_BASE / 2)
1689 if (dump_file)
1690 fprintf (dump_file,
1691 "Outcomes of branch in bb %i and %i differ too much (%i %i)\n",
1692 bb1->index, bb2->index, b1->probability, prob2);
1694 return false;
1698 if (dump_file && match)
1699 fprintf (dump_file, "Conditionals in bb %i and %i match.\n",
1700 bb1->index, bb2->index);
1702 return match;
1705 /* Generic case - we are seeing a computed jump, table jump or trapping
1706 instruction. */
1708 /* Check whether there are tablejumps in the end of BB1 and BB2.
1709 Return true if they are identical. */
1711 rtx label1, label2;
1712 rtx_jump_table_data *table1, *table2;
1714 if (tablejump_p (BB_END (bb1), &label1, &table1)
1715 && tablejump_p (BB_END (bb2), &label2, &table2)
1716 && GET_CODE (PATTERN (table1)) == GET_CODE (PATTERN (table2)))
1718 /* The labels should never be the same rtx. If they really are same
1719 the jump tables are same too. So disable crossjumping of blocks BB1
1720 and BB2 because when deleting the common insns in the end of BB1
1721 by delete_basic_block () the jump table would be deleted too. */
1722 /* If LABEL2 is referenced in BB1->END do not do anything
1723 because we would loose information when replacing
1724 LABEL1 by LABEL2 and then LABEL2 by LABEL1 in BB1->END. */
1725 if (label1 != label2 && !rtx_referenced_p (label2, BB_END (bb1)))
1727 /* Set IDENTICAL to true when the tables are identical. */
1728 bool identical = false;
1729 rtx p1, p2;
1731 p1 = PATTERN (table1);
1732 p2 = PATTERN (table2);
1733 if (GET_CODE (p1) == ADDR_VEC && rtx_equal_p (p1, p2))
1735 identical = true;
1737 else if (GET_CODE (p1) == ADDR_DIFF_VEC
1738 && (XVECLEN (p1, 1) == XVECLEN (p2, 1))
1739 && rtx_equal_p (XEXP (p1, 2), XEXP (p2, 2))
1740 && rtx_equal_p (XEXP (p1, 3), XEXP (p2, 3)))
1742 int i;
1744 identical = true;
1745 for (i = XVECLEN (p1, 1) - 1; i >= 0 && identical; i--)
1746 if (!rtx_equal_p (XVECEXP (p1, 1, i), XVECEXP (p2, 1, i)))
1747 identical = false;
1750 if (identical)
1752 bool match;
1754 /* Temporarily replace references to LABEL1 with LABEL2
1755 in BB1->END so that we could compare the instructions. */
1756 replace_label_in_insn (BB_END (bb1), label1, label2, false);
1758 match = (old_insns_match_p (mode, BB_END (bb1), BB_END (bb2))
1759 == dir_both);
1760 if (dump_file && match)
1761 fprintf (dump_file,
1762 "Tablejumps in bb %i and %i match.\n",
1763 bb1->index, bb2->index);
1765 /* Set the original label in BB1->END because when deleting
1766 a block whose end is a tablejump, the tablejump referenced
1767 from the instruction is deleted too. */
1768 replace_label_in_insn (BB_END (bb1), label2, label1, false);
1770 return match;
1773 return false;
1777 /* Find the last non-debug non-note instruction in each bb, except
1778 stop when we see the NOTE_INSN_BASIC_BLOCK, as old_insns_match_p
1779 handles that case specially. old_insns_match_p does not handle
1780 other types of instruction notes. */
1781 rtx_insn *last1 = BB_END (bb1);
1782 rtx_insn *last2 = BB_END (bb2);
1783 while (!NOTE_INSN_BASIC_BLOCK_P (last1) &&
1784 (DEBUG_INSN_P (last1) || NOTE_P (last1)))
1785 last1 = PREV_INSN (last1);
1786 while (!NOTE_INSN_BASIC_BLOCK_P (last2) &&
1787 (DEBUG_INSN_P (last2) || NOTE_P (last2)))
1788 last2 = PREV_INSN (last2);
1789 gcc_assert (last1 && last2);
1791 /* First ensure that the instructions match. There may be many outgoing
1792 edges so this test is generally cheaper. */
1793 if (old_insns_match_p (mode, last1, last2) != dir_both)
1794 return false;
1796 /* Search the outgoing edges, ensure that the counts do match, find possible
1797 fallthru and exception handling edges since these needs more
1798 validation. */
1799 if (EDGE_COUNT (bb1->succs) != EDGE_COUNT (bb2->succs))
1800 return false;
1802 bool nonfakeedges = false;
1803 FOR_EACH_EDGE (e1, ei, bb1->succs)
1805 e2 = EDGE_SUCC (bb2, ei.index);
1807 if ((e1->flags & EDGE_FAKE) == 0)
1808 nonfakeedges = true;
1810 if (e1->flags & EDGE_EH)
1811 nehedges1++;
1813 if (e2->flags & EDGE_EH)
1814 nehedges2++;
1816 if (e1->flags & EDGE_FALLTHRU)
1817 fallthru1 = e1;
1818 if (e2->flags & EDGE_FALLTHRU)
1819 fallthru2 = e2;
1822 /* If number of edges of various types does not match, fail. */
1823 if (nehedges1 != nehedges2
1824 || (fallthru1 != 0) != (fallthru2 != 0))
1825 return false;
1827 /* If !ACCUMULATE_OUTGOING_ARGS, bb1 (and bb2) have no successors
1828 and the last real insn doesn't have REG_ARGS_SIZE note, don't
1829 attempt to optimize, as the two basic blocks might have different
1830 REG_ARGS_SIZE depths. For noreturn calls and unconditional
1831 traps there should be REG_ARG_SIZE notes, they could be missing
1832 for __builtin_unreachable () uses though. */
1833 if (!nonfakeedges
1834 && !ACCUMULATE_OUTGOING_ARGS
1835 && (!INSN_P (last1)
1836 || !find_reg_note (last1, REG_ARGS_SIZE, NULL)))
1837 return false;
1839 /* fallthru edges must be forwarded to the same destination. */
1840 if (fallthru1)
1842 basic_block d1 = (forwarder_block_p (fallthru1->dest)
1843 ? single_succ (fallthru1->dest): fallthru1->dest);
1844 basic_block d2 = (forwarder_block_p (fallthru2->dest)
1845 ? single_succ (fallthru2->dest): fallthru2->dest);
1847 if (d1 != d2)
1848 return false;
1851 /* Ensure the same EH region. */
1853 rtx n1 = find_reg_note (BB_END (bb1), REG_EH_REGION, 0);
1854 rtx n2 = find_reg_note (BB_END (bb2), REG_EH_REGION, 0);
1856 if (!n1 && n2)
1857 return false;
1859 if (n1 && (!n2 || XEXP (n1, 0) != XEXP (n2, 0)))
1860 return false;
1863 /* The same checks as in try_crossjump_to_edge. It is required for RTL
1864 version of sequence abstraction. */
1865 FOR_EACH_EDGE (e1, ei, bb2->succs)
1867 edge e2;
1868 edge_iterator ei;
1869 basic_block d1 = e1->dest;
1871 if (FORWARDER_BLOCK_P (d1))
1872 d1 = EDGE_SUCC (d1, 0)->dest;
1874 FOR_EACH_EDGE (e2, ei, bb1->succs)
1876 basic_block d2 = e2->dest;
1877 if (FORWARDER_BLOCK_P (d2))
1878 d2 = EDGE_SUCC (d2, 0)->dest;
1879 if (d1 == d2)
1880 break;
1883 if (!e2)
1884 return false;
1887 return true;
1890 /* Returns true if BB basic block has a preserve label. */
1892 static bool
1893 block_has_preserve_label (basic_block bb)
1895 return (bb
1896 && block_label (bb)
1897 && LABEL_PRESERVE_P (block_label (bb)));
1900 /* E1 and E2 are edges with the same destination block. Search their
1901 predecessors for common code. If found, redirect control flow from
1902 (maybe the middle of) E1->SRC to (maybe the middle of) E2->SRC (dir_forward),
1903 or the other way around (dir_backward). DIR specifies the allowed
1904 replacement direction. */
1906 static bool
1907 try_crossjump_to_edge (int mode, edge e1, edge e2,
1908 enum replace_direction dir)
1910 int nmatch;
1911 basic_block src1 = e1->src, src2 = e2->src;
1912 basic_block redirect_to, redirect_from, to_remove;
1913 basic_block osrc1, osrc2, redirect_edges_to, tmp;
1914 rtx_insn *newpos1, *newpos2;
1915 edge s;
1916 edge_iterator ei;
1918 newpos1 = newpos2 = NULL;
1920 /* If we have partitioned hot/cold basic blocks, it is a bad idea
1921 to try this optimization.
1923 Basic block partitioning may result in some jumps that appear to
1924 be optimizable (or blocks that appear to be mergeable), but which really
1925 must be left untouched (they are required to make it safely across
1926 partition boundaries). See the comments at the top of
1927 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
1929 if (crtl->has_bb_partition && reload_completed)
1930 return false;
1932 /* Search backward through forwarder blocks. We don't need to worry
1933 about multiple entry or chained forwarders, as they will be optimized
1934 away. We do this to look past the unconditional jump following a
1935 conditional jump that is required due to the current CFG shape. */
1936 if (single_pred_p (src1)
1937 && FORWARDER_BLOCK_P (src1))
1938 e1 = single_pred_edge (src1), src1 = e1->src;
1940 if (single_pred_p (src2)
1941 && FORWARDER_BLOCK_P (src2))
1942 e2 = single_pred_edge (src2), src2 = e2->src;
1944 /* Nothing to do if we reach ENTRY, or a common source block. */
1945 if (src1 == ENTRY_BLOCK_PTR_FOR_FN (cfun) || src2
1946 == ENTRY_BLOCK_PTR_FOR_FN (cfun))
1947 return false;
1948 if (src1 == src2)
1949 return false;
1951 /* Seeing more than 1 forwarder blocks would confuse us later... */
1952 if (FORWARDER_BLOCK_P (e1->dest)
1953 && FORWARDER_BLOCK_P (single_succ (e1->dest)))
1954 return false;
1956 if (FORWARDER_BLOCK_P (e2->dest)
1957 && FORWARDER_BLOCK_P (single_succ (e2->dest)))
1958 return false;
1960 /* Likewise with dead code (possibly newly created by the other optimizations
1961 of cfg_cleanup). */
1962 if (EDGE_COUNT (src1->preds) == 0 || EDGE_COUNT (src2->preds) == 0)
1963 return false;
1965 /* Look for the common insn sequence, part the first ... */
1966 if (!outgoing_edges_match (mode, src1, src2))
1967 return false;
1969 /* ... and part the second. */
1970 nmatch = flow_find_cross_jump (src1, src2, &newpos1, &newpos2, &dir);
1972 osrc1 = src1;
1973 osrc2 = src2;
1974 if (newpos1 != NULL_RTX)
1975 src1 = BLOCK_FOR_INSN (newpos1);
1976 if (newpos2 != NULL_RTX)
1977 src2 = BLOCK_FOR_INSN (newpos2);
1979 if (dir == dir_backward)
1981 #define SWAP(T, X, Y) do { T tmp = (X); (X) = (Y); (Y) = tmp; } while (0)
1982 SWAP (basic_block, osrc1, osrc2);
1983 SWAP (basic_block, src1, src2);
1984 SWAP (edge, e1, e2);
1985 SWAP (rtx_insn *, newpos1, newpos2);
1986 #undef SWAP
1989 /* Don't proceed with the crossjump unless we found a sufficient number
1990 of matching instructions or the 'from' block was totally matched
1991 (such that its predecessors will hopefully be redirected and the
1992 block removed). */
1993 if ((nmatch < PARAM_VALUE (PARAM_MIN_CROSSJUMP_INSNS))
1994 && (newpos1 != BB_HEAD (src1)))
1995 return false;
1997 /* Avoid deleting preserve label when redirecting ABNORMAL edges. */
1998 if (block_has_preserve_label (e1->dest)
1999 && (e1->flags & EDGE_ABNORMAL))
2000 return false;
2002 /* Here we know that the insns in the end of SRC1 which are common with SRC2
2003 will be deleted.
2004 If we have tablejumps in the end of SRC1 and SRC2
2005 they have been already compared for equivalence in outgoing_edges_match ()
2006 so replace the references to TABLE1 by references to TABLE2. */
2008 rtx label1, label2;
2009 rtx_jump_table_data *table1, *table2;
2011 if (tablejump_p (BB_END (osrc1), &label1, &table1)
2012 && tablejump_p (BB_END (osrc2), &label2, &table2)
2013 && label1 != label2)
2015 rtx_insn *insn;
2017 /* Replace references to LABEL1 with LABEL2. */
2018 for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
2020 /* Do not replace the label in SRC1->END because when deleting
2021 a block whose end is a tablejump, the tablejump referenced
2022 from the instruction is deleted too. */
2023 if (insn != BB_END (osrc1))
2024 replace_label_in_insn (insn, label1, label2, true);
2029 /* Avoid splitting if possible. We must always split when SRC2 has
2030 EH predecessor edges, or we may end up with basic blocks with both
2031 normal and EH predecessor edges. */
2032 if (newpos2 == BB_HEAD (src2)
2033 && !(EDGE_PRED (src2, 0)->flags & EDGE_EH))
2034 redirect_to = src2;
2035 else
2037 if (newpos2 == BB_HEAD (src2))
2039 /* Skip possible basic block header. */
2040 if (LABEL_P (newpos2))
2041 newpos2 = NEXT_INSN (newpos2);
2042 while (DEBUG_INSN_P (newpos2))
2043 newpos2 = NEXT_INSN (newpos2);
2044 if (NOTE_P (newpos2))
2045 newpos2 = NEXT_INSN (newpos2);
2046 while (DEBUG_INSN_P (newpos2))
2047 newpos2 = NEXT_INSN (newpos2);
2050 if (dump_file)
2051 fprintf (dump_file, "Splitting bb %i before %i insns\n",
2052 src2->index, nmatch);
2053 redirect_to = split_block (src2, PREV_INSN (newpos2))->dest;
2056 if (dump_file)
2057 fprintf (dump_file,
2058 "Cross jumping from bb %i to bb %i; %i common insns\n",
2059 src1->index, src2->index, nmatch);
2061 /* We may have some registers visible through the block. */
2062 df_set_bb_dirty (redirect_to);
2064 if (osrc2 == src2)
2065 redirect_edges_to = redirect_to;
2066 else
2067 redirect_edges_to = osrc2;
2069 /* Recompute the frequencies and counts of outgoing edges. */
2070 FOR_EACH_EDGE (s, ei, redirect_edges_to->succs)
2072 edge s2;
2073 edge_iterator ei;
2074 basic_block d = s->dest;
2076 if (FORWARDER_BLOCK_P (d))
2077 d = single_succ (d);
2079 FOR_EACH_EDGE (s2, ei, src1->succs)
2081 basic_block d2 = s2->dest;
2082 if (FORWARDER_BLOCK_P (d2))
2083 d2 = single_succ (d2);
2084 if (d == d2)
2085 break;
2088 s->count += s2->count;
2090 /* Take care to update possible forwarder blocks. We verified
2091 that there is no more than one in the chain, so we can't run
2092 into infinite loop. */
2093 if (FORWARDER_BLOCK_P (s->dest))
2095 single_succ_edge (s->dest)->count += s2->count;
2096 s->dest->count += s2->count;
2097 s->dest->frequency += EDGE_FREQUENCY (s);
2100 if (FORWARDER_BLOCK_P (s2->dest))
2102 single_succ_edge (s2->dest)->count -= s2->count;
2103 if (single_succ_edge (s2->dest)->count < 0)
2104 single_succ_edge (s2->dest)->count = 0;
2105 s2->dest->count -= s2->count;
2106 s2->dest->frequency -= EDGE_FREQUENCY (s);
2107 if (s2->dest->frequency < 0)
2108 s2->dest->frequency = 0;
2109 if (s2->dest->count < 0)
2110 s2->dest->count = 0;
2113 if (!redirect_edges_to->frequency && !src1->frequency)
2114 s->probability = (s->probability + s2->probability) / 2;
2115 else
2116 s->probability
2117 = ((s->probability * redirect_edges_to->frequency +
2118 s2->probability * src1->frequency)
2119 / (redirect_edges_to->frequency + src1->frequency));
2122 /* Adjust count and frequency for the block. An earlier jump
2123 threading pass may have left the profile in an inconsistent
2124 state (see update_bb_profile_for_threading) so we must be
2125 prepared for overflows. */
2126 tmp = redirect_to;
2129 tmp->count += src1->count;
2130 tmp->frequency += src1->frequency;
2131 if (tmp->frequency > BB_FREQ_MAX)
2132 tmp->frequency = BB_FREQ_MAX;
2133 if (tmp == redirect_edges_to)
2134 break;
2135 tmp = find_fallthru_edge (tmp->succs)->dest;
2137 while (true);
2138 update_br_prob_note (redirect_edges_to);
2140 /* Edit SRC1 to go to REDIRECT_TO at NEWPOS1. */
2142 /* Skip possible basic block header. */
2143 if (LABEL_P (newpos1))
2144 newpos1 = NEXT_INSN (newpos1);
2146 while (DEBUG_INSN_P (newpos1))
2147 newpos1 = NEXT_INSN (newpos1);
2149 if (NOTE_INSN_BASIC_BLOCK_P (newpos1))
2150 newpos1 = NEXT_INSN (newpos1);
2152 while (DEBUG_INSN_P (newpos1))
2153 newpos1 = NEXT_INSN (newpos1);
2155 redirect_from = split_block (src1, PREV_INSN (newpos1))->src;
2156 to_remove = single_succ (redirect_from);
2158 redirect_edge_and_branch_force (single_succ_edge (redirect_from), redirect_to);
2159 delete_basic_block (to_remove);
2161 update_forwarder_flag (redirect_from);
2162 if (redirect_to != src2)
2163 update_forwarder_flag (src2);
2165 return true;
2168 /* Search the predecessors of BB for common insn sequences. When found,
2169 share code between them by redirecting control flow. Return true if
2170 any changes made. */
2172 static bool
2173 try_crossjump_bb (int mode, basic_block bb)
2175 edge e, e2, fallthru;
2176 bool changed;
2177 unsigned max, ix, ix2;
2179 /* Nothing to do if there is not at least two incoming edges. */
2180 if (EDGE_COUNT (bb->preds) < 2)
2181 return false;
2183 /* Don't crossjump if this block ends in a computed jump,
2184 unless we are optimizing for size. */
2185 if (optimize_bb_for_size_p (bb)
2186 && bb != EXIT_BLOCK_PTR_FOR_FN (cfun)
2187 && computed_jump_p (BB_END (bb)))
2188 return false;
2190 /* If we are partitioning hot/cold basic blocks, we don't want to
2191 mess up unconditional or indirect jumps that cross between hot
2192 and cold sections.
2194 Basic block partitioning may result in some jumps that appear to
2195 be optimizable (or blocks that appear to be mergeable), but which really
2196 must be left untouched (they are required to make it safely across
2197 partition boundaries). See the comments at the top of
2198 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
2200 if (BB_PARTITION (EDGE_PRED (bb, 0)->src) !=
2201 BB_PARTITION (EDGE_PRED (bb, 1)->src)
2202 || (EDGE_PRED (bb, 0)->flags & EDGE_CROSSING))
2203 return false;
2205 /* It is always cheapest to redirect a block that ends in a branch to
2206 a block that falls through into BB, as that adds no branches to the
2207 program. We'll try that combination first. */
2208 fallthru = NULL;
2209 max = PARAM_VALUE (PARAM_MAX_CROSSJUMP_EDGES);
2211 if (EDGE_COUNT (bb->preds) > max)
2212 return false;
2214 fallthru = find_fallthru_edge (bb->preds);
2216 changed = false;
2217 for (ix = 0; ix < EDGE_COUNT (bb->preds);)
2219 e = EDGE_PRED (bb, ix);
2220 ix++;
2222 /* As noted above, first try with the fallthru predecessor (or, a
2223 fallthru predecessor if we are in cfglayout mode). */
2224 if (fallthru)
2226 /* Don't combine the fallthru edge into anything else.
2227 If there is a match, we'll do it the other way around. */
2228 if (e == fallthru)
2229 continue;
2230 /* If nothing changed since the last attempt, there is nothing
2231 we can do. */
2232 if (!first_pass
2233 && !((e->src->flags & BB_MODIFIED)
2234 || (fallthru->src->flags & BB_MODIFIED)))
2235 continue;
2237 if (try_crossjump_to_edge (mode, e, fallthru, dir_forward))
2239 changed = true;
2240 ix = 0;
2241 continue;
2245 /* Non-obvious work limiting check: Recognize that we're going
2246 to call try_crossjump_bb on every basic block. So if we have
2247 two blocks with lots of outgoing edges (a switch) and they
2248 share lots of common destinations, then we would do the
2249 cross-jump check once for each common destination.
2251 Now, if the blocks actually are cross-jump candidates, then
2252 all of their destinations will be shared. Which means that
2253 we only need check them for cross-jump candidacy once. We
2254 can eliminate redundant checks of crossjump(A,B) by arbitrarily
2255 choosing to do the check from the block for which the edge
2256 in question is the first successor of A. */
2257 if (EDGE_SUCC (e->src, 0) != e)
2258 continue;
2260 for (ix2 = 0; ix2 < EDGE_COUNT (bb->preds); ix2++)
2262 e2 = EDGE_PRED (bb, ix2);
2264 if (e2 == e)
2265 continue;
2267 /* We've already checked the fallthru edge above. */
2268 if (e2 == fallthru)
2269 continue;
2271 /* The "first successor" check above only prevents multiple
2272 checks of crossjump(A,B). In order to prevent redundant
2273 checks of crossjump(B,A), require that A be the block
2274 with the lowest index. */
2275 if (e->src->index > e2->src->index)
2276 continue;
2278 /* If nothing changed since the last attempt, there is nothing
2279 we can do. */
2280 if (!first_pass
2281 && !((e->src->flags & BB_MODIFIED)
2282 || (e2->src->flags & BB_MODIFIED)))
2283 continue;
2285 /* Both e and e2 are not fallthru edges, so we can crossjump in either
2286 direction. */
2287 if (try_crossjump_to_edge (mode, e, e2, dir_both))
2289 changed = true;
2290 ix = 0;
2291 break;
2296 if (changed)
2297 crossjumps_occured = true;
2299 return changed;
2302 /* Search the successors of BB for common insn sequences. When found,
2303 share code between them by moving it across the basic block
2304 boundary. Return true if any changes made. */
2306 static bool
2307 try_head_merge_bb (basic_block bb)
2309 basic_block final_dest_bb = NULL;
2310 int max_match = INT_MAX;
2311 edge e0;
2312 rtx_insn **headptr, **currptr, **nextptr;
2313 bool changed, moveall;
2314 unsigned ix;
2315 rtx_insn *e0_last_head;
2316 rtx cond;
2317 rtx_insn *move_before;
2318 unsigned nedges = EDGE_COUNT (bb->succs);
2319 rtx_insn *jump = BB_END (bb);
2320 regset live, live_union;
2322 /* Nothing to do if there is not at least two outgoing edges. */
2323 if (nedges < 2)
2324 return false;
2326 /* Don't crossjump if this block ends in a computed jump,
2327 unless we are optimizing for size. */
2328 if (optimize_bb_for_size_p (bb)
2329 && bb != EXIT_BLOCK_PTR_FOR_FN (cfun)
2330 && computed_jump_p (BB_END (bb)))
2331 return false;
2333 cond = get_condition (jump, &move_before, true, false);
2334 if (cond == NULL_RTX)
2336 if (HAVE_cc0 && reg_mentioned_p (cc0_rtx, jump))
2337 move_before = prev_nonnote_nondebug_insn (jump);
2338 else
2339 move_before = jump;
2342 for (ix = 0; ix < nedges; ix++)
2343 if (EDGE_SUCC (bb, ix)->dest == EXIT_BLOCK_PTR_FOR_FN (cfun))
2344 return false;
2346 for (ix = 0; ix < nedges; ix++)
2348 edge e = EDGE_SUCC (bb, ix);
2349 basic_block other_bb = e->dest;
2351 if (df_get_bb_dirty (other_bb))
2353 block_was_dirty = true;
2354 return false;
2357 if (e->flags & EDGE_ABNORMAL)
2358 return false;
2360 /* Normally, all destination blocks must only be reachable from this
2361 block, i.e. they must have one incoming edge.
2363 There is one special case we can handle, that of multiple consecutive
2364 jumps where the first jumps to one of the targets of the second jump.
2365 This happens frequently in switch statements for default labels.
2366 The structure is as follows:
2367 FINAL_DEST_BB
2368 ....
2369 if (cond) jump A;
2370 fall through
2372 jump with targets A, B, C, D...
2374 has two incoming edges, from FINAL_DEST_BB and BB
2376 In this case, we can try to move the insns through BB and into
2377 FINAL_DEST_BB. */
2378 if (EDGE_COUNT (other_bb->preds) != 1)
2380 edge incoming_edge, incoming_bb_other_edge;
2381 edge_iterator ei;
2383 if (final_dest_bb != NULL
2384 || EDGE_COUNT (other_bb->preds) != 2)
2385 return false;
2387 /* We must be able to move the insns across the whole block. */
2388 move_before = BB_HEAD (bb);
2389 while (!NONDEBUG_INSN_P (move_before))
2390 move_before = NEXT_INSN (move_before);
2392 if (EDGE_COUNT (bb->preds) != 1)
2393 return false;
2394 incoming_edge = EDGE_PRED (bb, 0);
2395 final_dest_bb = incoming_edge->src;
2396 if (EDGE_COUNT (final_dest_bb->succs) != 2)
2397 return false;
2398 FOR_EACH_EDGE (incoming_bb_other_edge, ei, final_dest_bb->succs)
2399 if (incoming_bb_other_edge != incoming_edge)
2400 break;
2401 if (incoming_bb_other_edge->dest != other_bb)
2402 return false;
2406 e0 = EDGE_SUCC (bb, 0);
2407 e0_last_head = NULL;
2408 changed = false;
2410 for (ix = 1; ix < nedges; ix++)
2412 edge e = EDGE_SUCC (bb, ix);
2413 rtx_insn *e0_last, *e_last;
2414 int nmatch;
2416 nmatch = flow_find_head_matching_sequence (e0->dest, e->dest,
2417 &e0_last, &e_last, 0);
2418 if (nmatch == 0)
2419 return false;
2421 if (nmatch < max_match)
2423 max_match = nmatch;
2424 e0_last_head = e0_last;
2428 /* If we matched an entire block, we probably have to avoid moving the
2429 last insn. */
2430 if (max_match > 0
2431 && e0_last_head == BB_END (e0->dest)
2432 && (find_reg_note (e0_last_head, REG_EH_REGION, 0)
2433 || control_flow_insn_p (e0_last_head)))
2435 max_match--;
2436 if (max_match == 0)
2437 return false;
2439 e0_last_head = prev_real_insn (e0_last_head);
2440 while (DEBUG_INSN_P (e0_last_head));
2443 if (max_match == 0)
2444 return false;
2446 /* We must find a union of the live registers at each of the end points. */
2447 live = BITMAP_ALLOC (NULL);
2448 live_union = BITMAP_ALLOC (NULL);
2450 currptr = XNEWVEC (rtx_insn *, nedges);
2451 headptr = XNEWVEC (rtx_insn *, nedges);
2452 nextptr = XNEWVEC (rtx_insn *, nedges);
2454 for (ix = 0; ix < nedges; ix++)
2456 int j;
2457 basic_block merge_bb = EDGE_SUCC (bb, ix)->dest;
2458 rtx_insn *head = BB_HEAD (merge_bb);
2460 while (!NONDEBUG_INSN_P (head))
2461 head = NEXT_INSN (head);
2462 headptr[ix] = head;
2463 currptr[ix] = head;
2465 /* Compute the end point and live information */
2466 for (j = 1; j < max_match; j++)
2468 head = NEXT_INSN (head);
2469 while (!NONDEBUG_INSN_P (head));
2470 simulate_backwards_to_point (merge_bb, live, head);
2471 IOR_REG_SET (live_union, live);
2474 /* If we're moving across two blocks, verify the validity of the
2475 first move, then adjust the target and let the loop below deal
2476 with the final move. */
2477 if (final_dest_bb != NULL)
2479 rtx_insn *move_upto;
2481 moveall = can_move_insns_across (currptr[0], e0_last_head, move_before,
2482 jump, e0->dest, live_union,
2483 NULL, &move_upto);
2484 if (!moveall)
2486 if (move_upto == NULL_RTX)
2487 goto out;
2489 while (e0_last_head != move_upto)
2491 df_simulate_one_insn_backwards (e0->dest, e0_last_head,
2492 live_union);
2493 e0_last_head = PREV_INSN (e0_last_head);
2496 if (e0_last_head == NULL_RTX)
2497 goto out;
2499 jump = BB_END (final_dest_bb);
2500 cond = get_condition (jump, &move_before, true, false);
2501 if (cond == NULL_RTX)
2503 if (HAVE_cc0 && reg_mentioned_p (cc0_rtx, jump))
2504 move_before = prev_nonnote_nondebug_insn (jump);
2505 else
2506 move_before = jump;
2512 rtx_insn *move_upto;
2513 moveall = can_move_insns_across (currptr[0], e0_last_head,
2514 move_before, jump, e0->dest, live_union,
2515 NULL, &move_upto);
2516 if (!moveall && move_upto == NULL_RTX)
2518 if (jump == move_before)
2519 break;
2521 /* Try again, using a different insertion point. */
2522 move_before = jump;
2524 /* Don't try moving before a cc0 user, as that may invalidate
2525 the cc0. */
2526 if (HAVE_cc0 && reg_mentioned_p (cc0_rtx, jump))
2527 break;
2529 continue;
2532 if (final_dest_bb && !moveall)
2533 /* We haven't checked whether a partial move would be OK for the first
2534 move, so we have to fail this case. */
2535 break;
2537 changed = true;
2538 for (;;)
2540 if (currptr[0] == move_upto)
2541 break;
2542 for (ix = 0; ix < nedges; ix++)
2544 rtx_insn *curr = currptr[ix];
2546 curr = NEXT_INSN (curr);
2547 while (!NONDEBUG_INSN_P (curr));
2548 currptr[ix] = curr;
2552 /* If we can't currently move all of the identical insns, remember
2553 each insn after the range that we'll merge. */
2554 if (!moveall)
2555 for (ix = 0; ix < nedges; ix++)
2557 rtx_insn *curr = currptr[ix];
2559 curr = NEXT_INSN (curr);
2560 while (!NONDEBUG_INSN_P (curr));
2561 nextptr[ix] = curr;
2564 reorder_insns (headptr[0], currptr[0], PREV_INSN (move_before));
2565 df_set_bb_dirty (EDGE_SUCC (bb, 0)->dest);
2566 if (final_dest_bb != NULL)
2567 df_set_bb_dirty (final_dest_bb);
2568 df_set_bb_dirty (bb);
2569 for (ix = 1; ix < nedges; ix++)
2571 df_set_bb_dirty (EDGE_SUCC (bb, ix)->dest);
2572 delete_insn_chain (headptr[ix], currptr[ix], false);
2574 if (!moveall)
2576 if (jump == move_before)
2577 break;
2579 /* For the unmerged insns, try a different insertion point. */
2580 move_before = jump;
2582 /* Don't try moving before a cc0 user, as that may invalidate
2583 the cc0. */
2584 if (HAVE_cc0 && reg_mentioned_p (cc0_rtx, jump))
2585 break;
2587 for (ix = 0; ix < nedges; ix++)
2588 currptr[ix] = headptr[ix] = nextptr[ix];
2591 while (!moveall);
2593 out:
2594 free (currptr);
2595 free (headptr);
2596 free (nextptr);
2598 crossjumps_occured |= changed;
2600 return changed;
2603 /* Return true if BB contains just bb note, or bb note followed
2604 by only DEBUG_INSNs. */
2606 static bool
2607 trivially_empty_bb_p (basic_block bb)
2609 rtx_insn *insn = BB_END (bb);
2611 while (1)
2613 if (insn == BB_HEAD (bb))
2614 return true;
2615 if (!DEBUG_INSN_P (insn))
2616 return false;
2617 insn = PREV_INSN (insn);
2621 /* Do simple CFG optimizations - basic block merging, simplifying of jump
2622 instructions etc. Return nonzero if changes were made. */
2624 static bool
2625 try_optimize_cfg (int mode)
2627 bool changed_overall = false;
2628 bool changed;
2629 int iterations = 0;
2630 basic_block bb, b, next;
2632 if (mode & (CLEANUP_CROSSJUMP | CLEANUP_THREADING))
2633 clear_bb_flags ();
2635 crossjumps_occured = false;
2637 FOR_EACH_BB_FN (bb, cfun)
2638 update_forwarder_flag (bb);
2640 if (! targetm.cannot_modify_jumps_p ())
2642 first_pass = true;
2643 /* Attempt to merge blocks as made possible by edge removal. If
2644 a block has only one successor, and the successor has only
2645 one predecessor, they may be combined. */
2648 block_was_dirty = false;
2649 changed = false;
2650 iterations++;
2652 if (dump_file)
2653 fprintf (dump_file,
2654 "\n\ntry_optimize_cfg iteration %i\n\n",
2655 iterations);
2657 for (b = ENTRY_BLOCK_PTR_FOR_FN (cfun)->next_bb; b
2658 != EXIT_BLOCK_PTR_FOR_FN (cfun);)
2660 basic_block c;
2661 edge s;
2662 bool changed_here = false;
2664 /* Delete trivially dead basic blocks. This is either
2665 blocks with no predecessors, or empty blocks with no
2666 successors. However if the empty block with no
2667 successors is the successor of the ENTRY_BLOCK, it is
2668 kept. This ensures that the ENTRY_BLOCK will have a
2669 successor which is a precondition for many RTL
2670 passes. Empty blocks may result from expanding
2671 __builtin_unreachable (). */
2672 if (EDGE_COUNT (b->preds) == 0
2673 || (EDGE_COUNT (b->succs) == 0
2674 && trivially_empty_bb_p (b)
2675 && single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun))->dest
2676 != b))
2678 c = b->prev_bb;
2679 if (EDGE_COUNT (b->preds) > 0)
2681 edge e;
2682 edge_iterator ei;
2684 if (current_ir_type () == IR_RTL_CFGLAYOUT)
2686 if (BB_FOOTER (b)
2687 && BARRIER_P (BB_FOOTER (b)))
2688 FOR_EACH_EDGE (e, ei, b->preds)
2689 if ((e->flags & EDGE_FALLTHRU)
2690 && BB_FOOTER (e->src) == NULL)
2692 if (BB_FOOTER (b))
2694 BB_FOOTER (e->src) = BB_FOOTER (b);
2695 BB_FOOTER (b) = NULL;
2697 else
2699 start_sequence ();
2700 BB_FOOTER (e->src) = emit_barrier ();
2701 end_sequence ();
2705 else
2707 rtx_insn *last = get_last_bb_insn (b);
2708 if (last && BARRIER_P (last))
2709 FOR_EACH_EDGE (e, ei, b->preds)
2710 if ((e->flags & EDGE_FALLTHRU))
2711 emit_barrier_after (BB_END (e->src));
2714 delete_basic_block (b);
2715 changed = true;
2716 /* Avoid trying to remove the exit block. */
2717 b = (c == ENTRY_BLOCK_PTR_FOR_FN (cfun) ? c->next_bb : c);
2718 continue;
2721 /* Remove code labels no longer used. */
2722 if (single_pred_p (b)
2723 && (single_pred_edge (b)->flags & EDGE_FALLTHRU)
2724 && !(single_pred_edge (b)->flags & EDGE_COMPLEX)
2725 && LABEL_P (BB_HEAD (b))
2726 && !LABEL_PRESERVE_P (BB_HEAD (b))
2727 /* If the previous block ends with a branch to this
2728 block, we can't delete the label. Normally this
2729 is a condjump that is yet to be simplified, but
2730 if CASE_DROPS_THRU, this can be a tablejump with
2731 some element going to the same place as the
2732 default (fallthru). */
2733 && (single_pred (b) == ENTRY_BLOCK_PTR_FOR_FN (cfun)
2734 || !JUMP_P (BB_END (single_pred (b)))
2735 || ! label_is_jump_target_p (BB_HEAD (b),
2736 BB_END (single_pred (b)))))
2738 delete_insn (BB_HEAD (b));
2739 if (dump_file)
2740 fprintf (dump_file, "Deleted label in block %i.\n",
2741 b->index);
2744 /* If we fall through an empty block, we can remove it. */
2745 if (!(mode & (CLEANUP_CFGLAYOUT | CLEANUP_NO_INSN_DEL))
2746 && single_pred_p (b)
2747 && (single_pred_edge (b)->flags & EDGE_FALLTHRU)
2748 && !LABEL_P (BB_HEAD (b))
2749 && FORWARDER_BLOCK_P (b)
2750 /* Note that forwarder_block_p true ensures that
2751 there is a successor for this block. */
2752 && (single_succ_edge (b)->flags & EDGE_FALLTHRU)
2753 && n_basic_blocks_for_fn (cfun) > NUM_FIXED_BLOCKS + 1)
2755 if (dump_file)
2756 fprintf (dump_file,
2757 "Deleting fallthru block %i.\n",
2758 b->index);
2760 c = ((b->prev_bb == ENTRY_BLOCK_PTR_FOR_FN (cfun))
2761 ? b->next_bb : b->prev_bb);
2762 redirect_edge_succ_nodup (single_pred_edge (b),
2763 single_succ (b));
2764 delete_basic_block (b);
2765 changed = true;
2766 b = c;
2767 continue;
2770 /* Merge B with its single successor, if any. */
2771 if (single_succ_p (b)
2772 && (s = single_succ_edge (b))
2773 && !(s->flags & EDGE_COMPLEX)
2774 && (c = s->dest) != EXIT_BLOCK_PTR_FOR_FN (cfun)
2775 && single_pred_p (c)
2776 && b != c)
2778 /* When not in cfg_layout mode use code aware of reordering
2779 INSN. This code possibly creates new basic blocks so it
2780 does not fit merge_blocks interface and is kept here in
2781 hope that it will become useless once more of compiler
2782 is transformed to use cfg_layout mode. */
2784 if ((mode & CLEANUP_CFGLAYOUT)
2785 && can_merge_blocks_p (b, c))
2787 merge_blocks (b, c);
2788 update_forwarder_flag (b);
2789 changed_here = true;
2791 else if (!(mode & CLEANUP_CFGLAYOUT)
2792 /* If the jump insn has side effects,
2793 we can't kill the edge. */
2794 && (!JUMP_P (BB_END (b))
2795 || (reload_completed
2796 ? simplejump_p (BB_END (b))
2797 : (onlyjump_p (BB_END (b))
2798 && !tablejump_p (BB_END (b),
2799 NULL, NULL))))
2800 && (next = merge_blocks_move (s, b, c, mode)))
2802 b = next;
2803 changed_here = true;
2807 /* Simplify branch over branch. */
2808 if ((mode & CLEANUP_EXPENSIVE)
2809 && !(mode & CLEANUP_CFGLAYOUT)
2810 && try_simplify_condjump (b))
2811 changed_here = true;
2813 /* If B has a single outgoing edge, but uses a
2814 non-trivial jump instruction without side-effects, we
2815 can either delete the jump entirely, or replace it
2816 with a simple unconditional jump. */
2817 if (single_succ_p (b)
2818 && single_succ (b) != EXIT_BLOCK_PTR_FOR_FN (cfun)
2819 && onlyjump_p (BB_END (b))
2820 && !CROSSING_JUMP_P (BB_END (b))
2821 && try_redirect_by_replacing_jump (single_succ_edge (b),
2822 single_succ (b),
2823 (mode & CLEANUP_CFGLAYOUT) != 0))
2825 update_forwarder_flag (b);
2826 changed_here = true;
2829 /* Simplify branch to branch. */
2830 if (try_forward_edges (mode, b))
2832 update_forwarder_flag (b);
2833 changed_here = true;
2836 /* Look for shared code between blocks. */
2837 if ((mode & CLEANUP_CROSSJUMP)
2838 && try_crossjump_bb (mode, b))
2839 changed_here = true;
2841 if ((mode & CLEANUP_CROSSJUMP)
2842 /* This can lengthen register lifetimes. Do it only after
2843 reload. */
2844 && reload_completed
2845 && try_head_merge_bb (b))
2846 changed_here = true;
2848 /* Don't get confused by the index shift caused by
2849 deleting blocks. */
2850 if (!changed_here)
2851 b = b->next_bb;
2852 else
2853 changed = true;
2856 if ((mode & CLEANUP_CROSSJUMP)
2857 && try_crossjump_bb (mode, EXIT_BLOCK_PTR_FOR_FN (cfun)))
2858 changed = true;
2860 if (block_was_dirty)
2862 /* This should only be set by head-merging. */
2863 gcc_assert (mode & CLEANUP_CROSSJUMP);
2864 df_analyze ();
2867 if (changed)
2869 /* Edge forwarding in particular can cause hot blocks previously
2870 reached by both hot and cold blocks to become dominated only
2871 by cold blocks. This will cause the verification below to fail,
2872 and lead to now cold code in the hot section. This is not easy
2873 to detect and fix during edge forwarding, and in some cases
2874 is only visible after newly unreachable blocks are deleted,
2875 which will be done in fixup_partitions. */
2876 fixup_partitions ();
2878 #ifdef ENABLE_CHECKING
2879 verify_flow_info ();
2880 #endif
2883 changed_overall |= changed;
2884 first_pass = false;
2886 while (changed);
2889 FOR_ALL_BB_FN (b, cfun)
2890 b->flags &= ~(BB_FORWARDER_BLOCK | BB_NONTHREADABLE_BLOCK);
2892 return changed_overall;
2895 /* Delete all unreachable basic blocks. */
2897 bool
2898 delete_unreachable_blocks (void)
2900 bool changed = false;
2901 basic_block b, prev_bb;
2903 find_unreachable_blocks ();
2905 /* When we're in GIMPLE mode and there may be debug insns, we should
2906 delete blocks in reverse dominator order, so as to get a chance
2907 to substitute all released DEFs into debug stmts. If we don't
2908 have dominators information, walking blocks backward gets us a
2909 better chance of retaining most debug information than
2910 otherwise. */
2911 if (MAY_HAVE_DEBUG_INSNS && current_ir_type () == IR_GIMPLE
2912 && dom_info_available_p (CDI_DOMINATORS))
2914 for (b = EXIT_BLOCK_PTR_FOR_FN (cfun)->prev_bb;
2915 b != ENTRY_BLOCK_PTR_FOR_FN (cfun); b = prev_bb)
2917 prev_bb = b->prev_bb;
2919 if (!(b->flags & BB_REACHABLE))
2921 /* Speed up the removal of blocks that don't dominate
2922 others. Walking backwards, this should be the common
2923 case. */
2924 if (!first_dom_son (CDI_DOMINATORS, b))
2925 delete_basic_block (b);
2926 else
2928 vec<basic_block> h
2929 = get_all_dominated_blocks (CDI_DOMINATORS, b);
2931 while (h.length ())
2933 b = h.pop ();
2935 prev_bb = b->prev_bb;
2937 gcc_assert (!(b->flags & BB_REACHABLE));
2939 delete_basic_block (b);
2942 h.release ();
2945 changed = true;
2949 else
2951 for (b = EXIT_BLOCK_PTR_FOR_FN (cfun)->prev_bb;
2952 b != ENTRY_BLOCK_PTR_FOR_FN (cfun); b = prev_bb)
2954 prev_bb = b->prev_bb;
2956 if (!(b->flags & BB_REACHABLE))
2958 delete_basic_block (b);
2959 changed = true;
2964 if (changed)
2965 tidy_fallthru_edges ();
2966 return changed;
2969 /* Delete any jump tables never referenced. We can't delete them at the
2970 time of removing tablejump insn as they are referenced by the preceding
2971 insns computing the destination, so we delay deleting and garbagecollect
2972 them once life information is computed. */
2973 void
2974 delete_dead_jumptables (void)
2976 basic_block bb;
2978 /* A dead jump table does not belong to any basic block. Scan insns
2979 between two adjacent basic blocks. */
2980 FOR_EACH_BB_FN (bb, cfun)
2982 rtx_insn *insn, *next;
2984 for (insn = NEXT_INSN (BB_END (bb));
2985 insn && !NOTE_INSN_BASIC_BLOCK_P (insn);
2986 insn = next)
2988 next = NEXT_INSN (insn);
2989 if (LABEL_P (insn)
2990 && LABEL_NUSES (insn) == LABEL_PRESERVE_P (insn)
2991 && JUMP_TABLE_DATA_P (next))
2993 rtx_insn *label = insn, *jump = next;
2995 if (dump_file)
2996 fprintf (dump_file, "Dead jumptable %i removed\n",
2997 INSN_UID (insn));
2999 next = NEXT_INSN (next);
3000 delete_insn (jump);
3001 delete_insn (label);
3008 /* Tidy the CFG by deleting unreachable code and whatnot. */
3010 bool
3011 cleanup_cfg (int mode)
3013 bool changed = false;
3015 /* Set the cfglayout mode flag here. We could update all the callers
3016 but that is just inconvenient, especially given that we eventually
3017 want to have cfglayout mode as the default. */
3018 if (current_ir_type () == IR_RTL_CFGLAYOUT)
3019 mode |= CLEANUP_CFGLAYOUT;
3021 timevar_push (TV_CLEANUP_CFG);
3022 if (delete_unreachable_blocks ())
3024 changed = true;
3025 /* We've possibly created trivially dead code. Cleanup it right
3026 now to introduce more opportunities for try_optimize_cfg. */
3027 if (!(mode & (CLEANUP_NO_INSN_DEL))
3028 && !reload_completed)
3029 delete_trivially_dead_insns (get_insns (), max_reg_num ());
3032 compact_blocks ();
3034 /* To tail-merge blocks ending in the same noreturn function (e.g.
3035 a call to abort) we have to insert fake edges to exit. Do this
3036 here once. The fake edges do not interfere with any other CFG
3037 cleanups. */
3038 if (mode & CLEANUP_CROSSJUMP)
3039 add_noreturn_fake_exit_edges ();
3041 if (!dbg_cnt (cfg_cleanup))
3042 return changed;
3044 while (try_optimize_cfg (mode))
3046 delete_unreachable_blocks (), changed = true;
3047 if (!(mode & CLEANUP_NO_INSN_DEL))
3049 /* Try to remove some trivially dead insns when doing an expensive
3050 cleanup. But delete_trivially_dead_insns doesn't work after
3051 reload (it only handles pseudos) and run_fast_dce is too costly
3052 to run in every iteration.
3054 For effective cross jumping, we really want to run a fast DCE to
3055 clean up any dead conditions, or they get in the way of performing
3056 useful tail merges.
3058 Other transformations in cleanup_cfg are not so sensitive to dead
3059 code, so delete_trivially_dead_insns or even doing nothing at all
3060 is good enough. */
3061 if ((mode & CLEANUP_EXPENSIVE) && !reload_completed
3062 && !delete_trivially_dead_insns (get_insns (), max_reg_num ()))
3063 break;
3064 if ((mode & CLEANUP_CROSSJUMP) && crossjumps_occured)
3065 run_fast_dce ();
3067 else
3068 break;
3071 if (mode & CLEANUP_CROSSJUMP)
3072 remove_fake_exit_edges ();
3074 /* Don't call delete_dead_jumptables in cfglayout mode, because
3075 that function assumes that jump tables are in the insns stream.
3076 But we also don't _have_ to delete dead jumptables in cfglayout
3077 mode because we shouldn't even be looking at things that are
3078 not in a basic block. Dead jumptables are cleaned up when
3079 going out of cfglayout mode. */
3080 if (!(mode & CLEANUP_CFGLAYOUT))
3081 delete_dead_jumptables ();
3083 /* ??? We probably do this way too often. */
3084 if (current_loops
3085 && (changed
3086 || (mode & CLEANUP_CFG_CHANGED)))
3088 timevar_push (TV_REPAIR_LOOPS);
3089 /* The above doesn't preserve dominance info if available. */
3090 gcc_assert (!dom_info_available_p (CDI_DOMINATORS));
3091 calculate_dominance_info (CDI_DOMINATORS);
3092 fix_loop_structure (NULL);
3093 free_dominance_info (CDI_DOMINATORS);
3094 timevar_pop (TV_REPAIR_LOOPS);
3097 timevar_pop (TV_CLEANUP_CFG);
3099 return changed;
3102 namespace {
3104 const pass_data pass_data_jump =
3106 RTL_PASS, /* type */
3107 "jump", /* name */
3108 OPTGROUP_NONE, /* optinfo_flags */
3109 TV_JUMP, /* tv_id */
3110 0, /* properties_required */
3111 0, /* properties_provided */
3112 0, /* properties_destroyed */
3113 0, /* todo_flags_start */
3114 0, /* todo_flags_finish */
3117 class pass_jump : public rtl_opt_pass
3119 public:
3120 pass_jump (gcc::context *ctxt)
3121 : rtl_opt_pass (pass_data_jump, ctxt)
3124 /* opt_pass methods: */
3125 virtual unsigned int execute (function *);
3127 }; // class pass_jump
3129 unsigned int
3130 pass_jump::execute (function *)
3132 delete_trivially_dead_insns (get_insns (), max_reg_num ());
3133 if (dump_file)
3134 dump_flow_info (dump_file, dump_flags);
3135 cleanup_cfg ((optimize ? CLEANUP_EXPENSIVE : 0)
3136 | (flag_thread_jumps ? CLEANUP_THREADING : 0));
3137 return 0;
3140 } // anon namespace
3142 rtl_opt_pass *
3143 make_pass_jump (gcc::context *ctxt)
3145 return new pass_jump (ctxt);
3148 namespace {
3150 const pass_data pass_data_jump2 =
3152 RTL_PASS, /* type */
3153 "jump2", /* name */
3154 OPTGROUP_NONE, /* optinfo_flags */
3155 TV_JUMP, /* tv_id */
3156 0, /* properties_required */
3157 0, /* properties_provided */
3158 0, /* properties_destroyed */
3159 0, /* todo_flags_start */
3160 0, /* todo_flags_finish */
3163 class pass_jump2 : public rtl_opt_pass
3165 public:
3166 pass_jump2 (gcc::context *ctxt)
3167 : rtl_opt_pass (pass_data_jump2, ctxt)
3170 /* opt_pass methods: */
3171 virtual unsigned int execute (function *)
3173 cleanup_cfg (flag_crossjumping ? CLEANUP_CROSSJUMP : 0);
3174 return 0;
3177 }; // class pass_jump2
3179 } // anon namespace
3181 rtl_opt_pass *
3182 make_pass_jump2 (gcc::context *ctxt)
3184 return new pass_jump2 (ctxt);