Implement TARGET_IRA_CHANGE_PSEUDO_ALLOCNO_CLASS hook.
[official-gcc.git] / gcc / cfgcleanup.c
blob59071ca134563940ddbff77805cef32d1ed6387d
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 "tm.h"
36 #include "rtl.h"
37 #include "input.h"
38 #include "alias.h"
39 #include "symtab.h"
40 #include "tree.h"
41 #include "hard-reg-set.h"
42 #include "regs.h"
43 #include "insn-config.h"
44 #include "flags.h"
45 #include "recog.h"
46 #include "diagnostic-core.h"
47 #include "alloc-pool.h"
48 #include "cselib.h"
49 #include "params.h"
50 #include "tm_p.h"
51 #include "target.h"
52 #include "function.h" /* For inline functions in emit-rtl.h they need crtl. */
53 #include "emit-rtl.h"
54 #include "tree-pass.h"
55 #include "cfgloop.h"
56 #include "function.h"
57 #include "expmed.h"
58 #include "dojump.h"
59 #include "explow.h"
60 #include "calls.h"
61 #include "varasm.h"
62 #include "stmt.h"
63 #include "expr.h"
64 #include "dominance.h"
65 #include "cfg.h"
66 #include "cfgrtl.h"
67 #include "cfganal.h"
68 #include "cfgbuild.h"
69 #include "cfgcleanup.h"
70 #include "predict.h"
71 #include "basic-block.h"
72 #include "df.h"
73 #include "dce.h"
74 #include "dbgcnt.h"
75 #include "rtl-iter.h"
77 #define FORWARDER_BLOCK_P(BB) ((BB)->flags & BB_FORWARDER_BLOCK)
79 /* Set to true when we are running first pass of try_optimize_cfg loop. */
80 static bool first_pass;
82 /* Set to true if crossjumps occurred in the latest run of try_optimize_cfg. */
83 static bool crossjumps_occured;
85 /* Set to true if we couldn't run an optimization due to stale liveness
86 information; we should run df_analyze to enable more opportunities. */
87 static bool block_was_dirty;
89 static bool try_crossjump_to_edge (int, edge, edge, enum replace_direction);
90 static bool try_crossjump_bb (int, basic_block);
91 static bool outgoing_edges_match (int, basic_block, basic_block);
92 static enum replace_direction old_insns_match_p (int, rtx_insn *, rtx_insn *);
94 static void merge_blocks_move_predecessor_nojumps (basic_block, basic_block);
95 static void merge_blocks_move_successor_nojumps (basic_block, basic_block);
96 static bool try_optimize_cfg (int);
97 static bool try_simplify_condjump (basic_block);
98 static bool try_forward_edges (int, basic_block);
99 static edge thread_jump (edge, basic_block);
100 static bool mark_effect (rtx, bitmap);
101 static void notice_new_block (basic_block);
102 static void update_forwarder_flag (basic_block);
103 static void merge_memattrs (rtx, rtx);
105 /* Set flags for newly created block. */
107 static void
108 notice_new_block (basic_block bb)
110 if (!bb)
111 return;
113 if (forwarder_block_p (bb))
114 bb->flags |= BB_FORWARDER_BLOCK;
117 /* Recompute forwarder flag after block has been modified. */
119 static void
120 update_forwarder_flag (basic_block bb)
122 if (forwarder_block_p (bb))
123 bb->flags |= BB_FORWARDER_BLOCK;
124 else
125 bb->flags &= ~BB_FORWARDER_BLOCK;
128 /* Simplify a conditional jump around an unconditional jump.
129 Return true if something changed. */
131 static bool
132 try_simplify_condjump (basic_block cbranch_block)
134 basic_block jump_block, jump_dest_block, cbranch_dest_block;
135 edge cbranch_jump_edge, cbranch_fallthru_edge;
136 rtx_insn *cbranch_insn;
138 /* Verify that there are exactly two successors. */
139 if (EDGE_COUNT (cbranch_block->succs) != 2)
140 return false;
142 /* Verify that we've got a normal conditional branch at the end
143 of the block. */
144 cbranch_insn = BB_END (cbranch_block);
145 if (!any_condjump_p (cbranch_insn))
146 return false;
148 cbranch_fallthru_edge = FALLTHRU_EDGE (cbranch_block);
149 cbranch_jump_edge = BRANCH_EDGE (cbranch_block);
151 /* The next block must not have multiple predecessors, must not
152 be the last block in the function, and must contain just the
153 unconditional jump. */
154 jump_block = cbranch_fallthru_edge->dest;
155 if (!single_pred_p (jump_block)
156 || jump_block->next_bb == EXIT_BLOCK_PTR_FOR_FN (cfun)
157 || !FORWARDER_BLOCK_P (jump_block))
158 return false;
159 jump_dest_block = single_succ (jump_block);
161 /* If we are partitioning hot/cold basic blocks, we don't want to
162 mess up unconditional or indirect jumps that cross between hot
163 and cold sections.
165 Basic block partitioning may result in some jumps that appear to
166 be optimizable (or blocks that appear to be mergeable), but which really
167 must be left untouched (they are required to make it safely across
168 partition boundaries). See the comments at the top of
169 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
171 if (BB_PARTITION (jump_block) != BB_PARTITION (jump_dest_block)
172 || (cbranch_jump_edge->flags & EDGE_CROSSING))
173 return false;
175 /* The conditional branch must target the block after the
176 unconditional branch. */
177 cbranch_dest_block = cbranch_jump_edge->dest;
179 if (cbranch_dest_block == EXIT_BLOCK_PTR_FOR_FN (cfun)
180 || !can_fallthru (jump_block, cbranch_dest_block))
181 return false;
183 /* Invert the conditional branch. */
184 if (!invert_jump (as_a <rtx_jump_insn *> (cbranch_insn),
185 block_label (jump_dest_block), 0))
186 return false;
188 if (dump_file)
189 fprintf (dump_file, "Simplifying condjump %i around jump %i\n",
190 INSN_UID (cbranch_insn), INSN_UID (BB_END (jump_block)));
192 /* Success. Update the CFG to match. Note that after this point
193 the edge variable names appear backwards; the redirection is done
194 this way to preserve edge profile data. */
195 cbranch_jump_edge = redirect_edge_succ_nodup (cbranch_jump_edge,
196 cbranch_dest_block);
197 cbranch_fallthru_edge = redirect_edge_succ_nodup (cbranch_fallthru_edge,
198 jump_dest_block);
199 cbranch_jump_edge->flags |= EDGE_FALLTHRU;
200 cbranch_fallthru_edge->flags &= ~EDGE_FALLTHRU;
201 update_br_prob_note (cbranch_block);
203 /* Delete the block with the unconditional jump, and clean up the mess. */
204 delete_basic_block (jump_block);
205 tidy_fallthru_edge (cbranch_jump_edge);
206 update_forwarder_flag (cbranch_block);
208 return true;
211 /* Attempt to prove that operation is NOOP using CSElib or mark the effect
212 on register. Used by jump threading. */
214 static bool
215 mark_effect (rtx exp, regset nonequal)
217 rtx dest;
218 switch (GET_CODE (exp))
220 /* In case we do clobber the register, mark it as equal, as we know the
221 value is dead so it don't have to match. */
222 case CLOBBER:
223 dest = XEXP (exp, 0);
224 if (REG_P (dest))
225 bitmap_clear_range (nonequal, REGNO (dest), REG_NREGS (dest));
226 return false;
228 case SET:
229 if (rtx_equal_for_cselib_p (SET_DEST (exp), SET_SRC (exp)))
230 return false;
231 dest = SET_DEST (exp);
232 if (dest == pc_rtx)
233 return false;
234 if (!REG_P (dest))
235 return true;
236 bitmap_set_range (nonequal, REGNO (dest), REG_NREGS (dest));
237 return false;
239 default:
240 return false;
244 /* Return true if X contains a register in NONEQUAL. */
245 static bool
246 mentions_nonequal_regs (const_rtx x, regset nonequal)
248 subrtx_iterator::array_type array;
249 FOR_EACH_SUBRTX (iter, array, x, NONCONST)
251 const_rtx x = *iter;
252 if (REG_P (x))
254 unsigned int end_regno = END_REGNO (x);
255 for (unsigned int regno = REGNO (x); regno < end_regno; ++regno)
256 if (REGNO_REG_SET_P (nonequal, regno))
257 return true;
260 return false;
263 /* Attempt to prove that the basic block B will have no side effects and
264 always continues in the same edge if reached via E. Return the edge
265 if exist, NULL otherwise. */
267 static edge
268 thread_jump (edge e, basic_block b)
270 rtx set1, set2, cond1, cond2;
271 rtx_insn *insn;
272 enum rtx_code code1, code2, reversed_code2;
273 bool reverse1 = false;
274 unsigned i;
275 regset nonequal;
276 bool failed = false;
277 reg_set_iterator rsi;
279 if (b->flags & BB_NONTHREADABLE_BLOCK)
280 return NULL;
282 /* At the moment, we do handle only conditional jumps, but later we may
283 want to extend this code to tablejumps and others. */
284 if (EDGE_COUNT (e->src->succs) != 2)
285 return NULL;
286 if (EDGE_COUNT (b->succs) != 2)
288 b->flags |= BB_NONTHREADABLE_BLOCK;
289 return NULL;
292 /* Second branch must end with onlyjump, as we will eliminate the jump. */
293 if (!any_condjump_p (BB_END (e->src)))
294 return NULL;
296 if (!any_condjump_p (BB_END (b)) || !onlyjump_p (BB_END (b)))
298 b->flags |= BB_NONTHREADABLE_BLOCK;
299 return NULL;
302 set1 = pc_set (BB_END (e->src));
303 set2 = pc_set (BB_END (b));
304 if (((e->flags & EDGE_FALLTHRU) != 0)
305 != (XEXP (SET_SRC (set1), 1) == pc_rtx))
306 reverse1 = true;
308 cond1 = XEXP (SET_SRC (set1), 0);
309 cond2 = XEXP (SET_SRC (set2), 0);
310 if (reverse1)
311 code1 = reversed_comparison_code (cond1, BB_END (e->src));
312 else
313 code1 = GET_CODE (cond1);
315 code2 = GET_CODE (cond2);
316 reversed_code2 = reversed_comparison_code (cond2, BB_END (b));
318 if (!comparison_dominates_p (code1, code2)
319 && !comparison_dominates_p (code1, reversed_code2))
320 return NULL;
322 /* Ensure that the comparison operators are equivalent.
323 ??? This is far too pessimistic. We should allow swapped operands,
324 different CCmodes, or for example comparisons for interval, that
325 dominate even when operands are not equivalent. */
326 if (!rtx_equal_p (XEXP (cond1, 0), XEXP (cond2, 0))
327 || !rtx_equal_p (XEXP (cond1, 1), XEXP (cond2, 1)))
328 return NULL;
330 /* Short circuit cases where block B contains some side effects, as we can't
331 safely bypass it. */
332 for (insn = NEXT_INSN (BB_HEAD (b)); insn != NEXT_INSN (BB_END (b));
333 insn = NEXT_INSN (insn))
334 if (INSN_P (insn) && side_effects_p (PATTERN (insn)))
336 b->flags |= BB_NONTHREADABLE_BLOCK;
337 return NULL;
340 cselib_init (0);
342 /* First process all values computed in the source basic block. */
343 for (insn = NEXT_INSN (BB_HEAD (e->src));
344 insn != NEXT_INSN (BB_END (e->src));
345 insn = NEXT_INSN (insn))
346 if (INSN_P (insn))
347 cselib_process_insn (insn);
349 nonequal = BITMAP_ALLOC (NULL);
350 CLEAR_REG_SET (nonequal);
352 /* Now assume that we've continued by the edge E to B and continue
353 processing as if it were same basic block.
354 Our goal is to prove that whole block is an NOOP. */
356 for (insn = NEXT_INSN (BB_HEAD (b));
357 insn != NEXT_INSN (BB_END (b)) && !failed;
358 insn = NEXT_INSN (insn))
360 if (INSN_P (insn))
362 rtx pat = PATTERN (insn);
364 if (GET_CODE (pat) == PARALLEL)
366 for (i = 0; i < (unsigned)XVECLEN (pat, 0); i++)
367 failed |= mark_effect (XVECEXP (pat, 0, i), nonequal);
369 else
370 failed |= mark_effect (pat, nonequal);
373 cselib_process_insn (insn);
376 /* Later we should clear nonequal of dead registers. So far we don't
377 have life information in cfg_cleanup. */
378 if (failed)
380 b->flags |= BB_NONTHREADABLE_BLOCK;
381 goto failed_exit;
384 /* cond2 must not mention any register that is not equal to the
385 former block. */
386 if (mentions_nonequal_regs (cond2, nonequal))
387 goto failed_exit;
389 EXECUTE_IF_SET_IN_REG_SET (nonequal, 0, i, rsi)
390 goto failed_exit;
392 BITMAP_FREE (nonequal);
393 cselib_finish ();
394 if ((comparison_dominates_p (code1, code2) != 0)
395 != (XEXP (SET_SRC (set2), 1) == pc_rtx))
396 return BRANCH_EDGE (b);
397 else
398 return FALLTHRU_EDGE (b);
400 failed_exit:
401 BITMAP_FREE (nonequal);
402 cselib_finish ();
403 return NULL;
406 /* Attempt to forward edges leaving basic block B.
407 Return true if successful. */
409 static bool
410 try_forward_edges (int mode, basic_block b)
412 bool changed = false;
413 edge_iterator ei;
414 edge e, *threaded_edges = NULL;
416 /* If we are partitioning hot/cold basic blocks, we don't want to
417 mess up unconditional or indirect jumps that cross between hot
418 and cold sections.
420 Basic block partitioning may result in some jumps that appear to
421 be optimizable (or blocks that appear to be mergeable), but which really
422 must be left untouched (they are required to make it safely across
423 partition boundaries). See the comments at the top of
424 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
426 if (JUMP_P (BB_END (b)) && CROSSING_JUMP_P (BB_END (b)))
427 return false;
429 for (ei = ei_start (b->succs); (e = ei_safe_edge (ei)); )
431 basic_block target, first;
432 location_t goto_locus;
433 int counter;
434 bool threaded = false;
435 int nthreaded_edges = 0;
436 bool may_thread = first_pass || (b->flags & BB_MODIFIED) != 0;
438 /* Skip complex edges because we don't know how to update them.
440 Still handle fallthru edges, as we can succeed to forward fallthru
441 edge to the same place as the branch edge of conditional branch
442 and turn conditional branch to an unconditional branch. */
443 if (e->flags & EDGE_COMPLEX)
445 ei_next (&ei);
446 continue;
449 target = first = e->dest;
450 counter = NUM_FIXED_BLOCKS;
451 goto_locus = e->goto_locus;
453 /* If we are partitioning hot/cold basic_blocks, we don't want to mess
454 up jumps that cross between hot/cold sections.
456 Basic block partitioning may result in some jumps that appear
457 to be optimizable (or blocks that appear to be mergeable), but which
458 really must be left untouched (they are required to make it safely
459 across partition boundaries). See the comments at the top of
460 bb-reorder.c:partition_hot_cold_basic_blocks for complete
461 details. */
463 if (first != EXIT_BLOCK_PTR_FOR_FN (cfun)
464 && JUMP_P (BB_END (first))
465 && CROSSING_JUMP_P (BB_END (first)))
466 return changed;
468 while (counter < n_basic_blocks_for_fn (cfun))
470 basic_block new_target = NULL;
471 bool new_target_threaded = false;
472 may_thread |= (target->flags & BB_MODIFIED) != 0;
474 if (FORWARDER_BLOCK_P (target)
475 && !(single_succ_edge (target)->flags & EDGE_CROSSING)
476 && single_succ (target) != EXIT_BLOCK_PTR_FOR_FN (cfun))
478 /* Bypass trivial infinite loops. */
479 new_target = single_succ (target);
480 if (target == new_target)
481 counter = n_basic_blocks_for_fn (cfun);
482 else if (!optimize)
484 /* When not optimizing, ensure that edges or forwarder
485 blocks with different locus are not optimized out. */
486 location_t new_locus = single_succ_edge (target)->goto_locus;
487 location_t locus = goto_locus;
489 if (LOCATION_LOCUS (new_locus) != UNKNOWN_LOCATION
490 && LOCATION_LOCUS (locus) != UNKNOWN_LOCATION
491 && new_locus != locus)
492 new_target = NULL;
493 else
495 if (LOCATION_LOCUS (new_locus) != UNKNOWN_LOCATION)
496 locus = new_locus;
498 rtx_insn *last = BB_END (target);
499 if (DEBUG_INSN_P (last))
500 last = prev_nondebug_insn (last);
501 if (last && INSN_P (last))
502 new_locus = INSN_LOCATION (last);
503 else
504 new_locus = UNKNOWN_LOCATION;
506 if (LOCATION_LOCUS (new_locus) != UNKNOWN_LOCATION
507 && LOCATION_LOCUS (locus) != UNKNOWN_LOCATION
508 && new_locus != locus)
509 new_target = NULL;
510 else
512 if (LOCATION_LOCUS (new_locus) != UNKNOWN_LOCATION)
513 locus = new_locus;
515 goto_locus = locus;
521 /* Allow to thread only over one edge at time to simplify updating
522 of probabilities. */
523 else if ((mode & CLEANUP_THREADING) && may_thread)
525 edge t = thread_jump (e, target);
526 if (t)
528 if (!threaded_edges)
529 threaded_edges = XNEWVEC (edge,
530 n_basic_blocks_for_fn (cfun));
531 else
533 int i;
535 /* Detect an infinite loop across blocks not
536 including the start block. */
537 for (i = 0; i < nthreaded_edges; ++i)
538 if (threaded_edges[i] == t)
539 break;
540 if (i < nthreaded_edges)
542 counter = n_basic_blocks_for_fn (cfun);
543 break;
547 /* Detect an infinite loop across the start block. */
548 if (t->dest == b)
549 break;
551 gcc_assert (nthreaded_edges
552 < (n_basic_blocks_for_fn (cfun)
553 - NUM_FIXED_BLOCKS));
554 threaded_edges[nthreaded_edges++] = t;
556 new_target = t->dest;
557 new_target_threaded = true;
561 if (!new_target)
562 break;
564 counter++;
565 target = new_target;
566 threaded |= new_target_threaded;
569 if (counter >= n_basic_blocks_for_fn (cfun))
571 if (dump_file)
572 fprintf (dump_file, "Infinite loop in BB %i.\n",
573 target->index);
575 else if (target == first)
576 ; /* We didn't do anything. */
577 else
579 /* Save the values now, as the edge may get removed. */
580 gcov_type edge_count = e->count;
581 int edge_probability = e->probability;
582 int edge_frequency;
583 int n = 0;
585 e->goto_locus = goto_locus;
587 /* Don't force if target is exit block. */
588 if (threaded && target != EXIT_BLOCK_PTR_FOR_FN (cfun))
590 notice_new_block (redirect_edge_and_branch_force (e, target));
591 if (dump_file)
592 fprintf (dump_file, "Conditionals threaded.\n");
594 else if (!redirect_edge_and_branch (e, target))
596 if (dump_file)
597 fprintf (dump_file,
598 "Forwarding edge %i->%i to %i failed.\n",
599 b->index, e->dest->index, target->index);
600 ei_next (&ei);
601 continue;
604 /* We successfully forwarded the edge. Now update profile
605 data: for each edge we traversed in the chain, remove
606 the original edge's execution count. */
607 edge_frequency = apply_probability (b->frequency, edge_probability);
611 edge t;
613 if (!single_succ_p (first))
615 gcc_assert (n < nthreaded_edges);
616 t = threaded_edges [n++];
617 gcc_assert (t->src == first);
618 update_bb_profile_for_threading (first, edge_frequency,
619 edge_count, t);
620 update_br_prob_note (first);
622 else
624 first->count -= edge_count;
625 if (first->count < 0)
626 first->count = 0;
627 first->frequency -= edge_frequency;
628 if (first->frequency < 0)
629 first->frequency = 0;
630 /* It is possible that as the result of
631 threading we've removed edge as it is
632 threaded to the fallthru edge. Avoid
633 getting out of sync. */
634 if (n < nthreaded_edges
635 && first == threaded_edges [n]->src)
636 n++;
637 t = single_succ_edge (first);
640 t->count -= edge_count;
641 if (t->count < 0)
642 t->count = 0;
643 first = t->dest;
645 while (first != target);
647 changed = true;
648 continue;
650 ei_next (&ei);
653 free (threaded_edges);
654 return changed;
658 /* Blocks A and B are to be merged into a single block. A has no incoming
659 fallthru edge, so it can be moved before B without adding or modifying
660 any jumps (aside from the jump from A to B). */
662 static void
663 merge_blocks_move_predecessor_nojumps (basic_block a, basic_block b)
665 rtx_insn *barrier;
667 /* If we are partitioning hot/cold basic blocks, we don't want to
668 mess up unconditional or indirect jumps that cross between hot
669 and cold sections.
671 Basic block partitioning may result in some jumps that appear to
672 be optimizable (or blocks that appear to be mergeable), but which really
673 must be left untouched (they are required to make it safely across
674 partition boundaries). See the comments at the top of
675 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
677 if (BB_PARTITION (a) != BB_PARTITION (b))
678 return;
680 barrier = next_nonnote_insn (BB_END (a));
681 gcc_assert (BARRIER_P (barrier));
682 delete_insn (barrier);
684 /* Scramble the insn chain. */
685 if (BB_END (a) != PREV_INSN (BB_HEAD (b)))
686 reorder_insns_nobb (BB_HEAD (a), BB_END (a), PREV_INSN (BB_HEAD (b)));
687 df_set_bb_dirty (a);
689 if (dump_file)
690 fprintf (dump_file, "Moved block %d before %d and merged.\n",
691 a->index, b->index);
693 /* Swap the records for the two blocks around. */
695 unlink_block (a);
696 link_block (a, b->prev_bb);
698 /* Now blocks A and B are contiguous. Merge them. */
699 merge_blocks (a, b);
702 /* Blocks A and B are to be merged into a single block. B has no outgoing
703 fallthru edge, so it can be moved after A without adding or modifying
704 any jumps (aside from the jump from A to B). */
706 static void
707 merge_blocks_move_successor_nojumps (basic_block a, basic_block b)
709 rtx_insn *barrier, *real_b_end;
710 rtx label;
711 rtx_jump_table_data *table;
713 /* If we are partitioning hot/cold basic blocks, we don't want to
714 mess up unconditional or indirect jumps that cross between hot
715 and cold sections.
717 Basic block partitioning may result in some jumps that appear to
718 be optimizable (or blocks that appear to be mergeable), but which really
719 must be left untouched (they are required to make it safely across
720 partition boundaries). See the comments at the top of
721 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
723 if (BB_PARTITION (a) != BB_PARTITION (b))
724 return;
726 real_b_end = BB_END (b);
728 /* If there is a jump table following block B temporarily add the jump table
729 to block B so that it will also be moved to the correct location. */
730 if (tablejump_p (BB_END (b), &label, &table)
731 && prev_active_insn (label) == BB_END (b))
733 BB_END (b) = table;
736 /* There had better have been a barrier there. Delete it. */
737 barrier = NEXT_INSN (BB_END (b));
738 if (barrier && BARRIER_P (barrier))
739 delete_insn (barrier);
742 /* Scramble the insn chain. */
743 reorder_insns_nobb (BB_HEAD (b), BB_END (b), BB_END (a));
745 /* Restore the real end of b. */
746 BB_END (b) = real_b_end;
748 if (dump_file)
749 fprintf (dump_file, "Moved block %d after %d and merged.\n",
750 b->index, a->index);
752 /* Now blocks A and B are contiguous. Merge them. */
753 merge_blocks (a, b);
756 /* Attempt to merge basic blocks that are potentially non-adjacent.
757 Return NULL iff the attempt failed, otherwise return basic block
758 where cleanup_cfg should continue. Because the merging commonly
759 moves basic block away or introduces another optimization
760 possibility, return basic block just before B so cleanup_cfg don't
761 need to iterate.
763 It may be good idea to return basic block before C in the case
764 C has been moved after B and originally appeared earlier in the
765 insn sequence, but we have no information available about the
766 relative ordering of these two. Hopefully it is not too common. */
768 static basic_block
769 merge_blocks_move (edge e, basic_block b, basic_block c, int mode)
771 basic_block next;
773 /* If we are partitioning hot/cold basic blocks, we don't want to
774 mess up unconditional or indirect jumps that cross between hot
775 and cold sections.
777 Basic block partitioning may result in some jumps that appear to
778 be optimizable (or blocks that appear to be mergeable), but which really
779 must be left untouched (they are required to make it safely across
780 partition boundaries). See the comments at the top of
781 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
783 if (BB_PARTITION (b) != BB_PARTITION (c))
784 return NULL;
786 /* If B has a fallthru edge to C, no need to move anything. */
787 if (e->flags & EDGE_FALLTHRU)
789 int b_index = b->index, c_index = c->index;
791 /* Protect the loop latches. */
792 if (current_loops && c->loop_father->latch == c)
793 return NULL;
795 merge_blocks (b, c);
796 update_forwarder_flag (b);
798 if (dump_file)
799 fprintf (dump_file, "Merged %d and %d without moving.\n",
800 b_index, c_index);
802 return b->prev_bb == ENTRY_BLOCK_PTR_FOR_FN (cfun) ? b : b->prev_bb;
805 /* Otherwise we will need to move code around. Do that only if expensive
806 transformations are allowed. */
807 else if (mode & CLEANUP_EXPENSIVE)
809 edge tmp_edge, b_fallthru_edge;
810 bool c_has_outgoing_fallthru;
811 bool b_has_incoming_fallthru;
813 /* Avoid overactive code motion, as the forwarder blocks should be
814 eliminated by edge redirection instead. One exception might have
815 been if B is a forwarder block and C has no fallthru edge, but
816 that should be cleaned up by bb-reorder instead. */
817 if (FORWARDER_BLOCK_P (b) || FORWARDER_BLOCK_P (c))
818 return NULL;
820 /* We must make sure to not munge nesting of lexical blocks,
821 and loop notes. This is done by squeezing out all the notes
822 and leaving them there to lie. Not ideal, but functional. */
824 tmp_edge = find_fallthru_edge (c->succs);
825 c_has_outgoing_fallthru = (tmp_edge != NULL);
827 tmp_edge = find_fallthru_edge (b->preds);
828 b_has_incoming_fallthru = (tmp_edge != NULL);
829 b_fallthru_edge = tmp_edge;
830 next = b->prev_bb;
831 if (next == c)
832 next = next->prev_bb;
834 /* Otherwise, we're going to try to move C after B. If C does
835 not have an outgoing fallthru, then it can be moved
836 immediately after B without introducing or modifying jumps. */
837 if (! c_has_outgoing_fallthru)
839 merge_blocks_move_successor_nojumps (b, c);
840 return next == ENTRY_BLOCK_PTR_FOR_FN (cfun) ? next->next_bb : next;
843 /* If B does not have an incoming fallthru, then it can be moved
844 immediately before C without introducing or modifying jumps.
845 C cannot be the first block, so we do not have to worry about
846 accessing a non-existent block. */
848 if (b_has_incoming_fallthru)
850 basic_block bb;
852 if (b_fallthru_edge->src == ENTRY_BLOCK_PTR_FOR_FN (cfun))
853 return NULL;
854 bb = force_nonfallthru (b_fallthru_edge);
855 if (bb)
856 notice_new_block (bb);
859 merge_blocks_move_predecessor_nojumps (b, c);
860 return next == ENTRY_BLOCK_PTR_FOR_FN (cfun) ? next->next_bb : next;
863 return NULL;
867 /* Removes the memory attributes of MEM expression
868 if they are not equal. */
870 static void
871 merge_memattrs (rtx x, rtx y)
873 int i;
874 int j;
875 enum rtx_code code;
876 const char *fmt;
878 if (x == y)
879 return;
880 if (x == 0 || y == 0)
881 return;
883 code = GET_CODE (x);
885 if (code != GET_CODE (y))
886 return;
888 if (GET_MODE (x) != GET_MODE (y))
889 return;
891 if (code == MEM && !mem_attrs_eq_p (MEM_ATTRS (x), MEM_ATTRS (y)))
893 if (! MEM_ATTRS (x))
894 MEM_ATTRS (y) = 0;
895 else if (! MEM_ATTRS (y))
896 MEM_ATTRS (x) = 0;
897 else
899 HOST_WIDE_INT mem_size;
901 if (MEM_ALIAS_SET (x) != MEM_ALIAS_SET (y))
903 set_mem_alias_set (x, 0);
904 set_mem_alias_set (y, 0);
907 if (! mem_expr_equal_p (MEM_EXPR (x), MEM_EXPR (y)))
909 set_mem_expr (x, 0);
910 set_mem_expr (y, 0);
911 clear_mem_offset (x);
912 clear_mem_offset (y);
914 else if (MEM_OFFSET_KNOWN_P (x) != MEM_OFFSET_KNOWN_P (y)
915 || (MEM_OFFSET_KNOWN_P (x)
916 && MEM_OFFSET (x) != MEM_OFFSET (y)))
918 clear_mem_offset (x);
919 clear_mem_offset (y);
922 if (MEM_SIZE_KNOWN_P (x) && MEM_SIZE_KNOWN_P (y))
924 mem_size = MAX (MEM_SIZE (x), MEM_SIZE (y));
925 set_mem_size (x, mem_size);
926 set_mem_size (y, mem_size);
928 else
930 clear_mem_size (x);
931 clear_mem_size (y);
934 set_mem_align (x, MIN (MEM_ALIGN (x), MEM_ALIGN (y)));
935 set_mem_align (y, MEM_ALIGN (x));
938 if (code == MEM)
940 if (MEM_READONLY_P (x) != MEM_READONLY_P (y))
942 MEM_READONLY_P (x) = 0;
943 MEM_READONLY_P (y) = 0;
945 if (MEM_NOTRAP_P (x) != MEM_NOTRAP_P (y))
947 MEM_NOTRAP_P (x) = 0;
948 MEM_NOTRAP_P (y) = 0;
950 if (MEM_VOLATILE_P (x) != MEM_VOLATILE_P (y))
952 MEM_VOLATILE_P (x) = 1;
953 MEM_VOLATILE_P (y) = 1;
957 fmt = GET_RTX_FORMAT (code);
958 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
960 switch (fmt[i])
962 case 'E':
963 /* Two vectors must have the same length. */
964 if (XVECLEN (x, i) != XVECLEN (y, i))
965 return;
967 for (j = 0; j < XVECLEN (x, i); j++)
968 merge_memattrs (XVECEXP (x, i, j), XVECEXP (y, i, j));
970 break;
972 case 'e':
973 merge_memattrs (XEXP (x, i), XEXP (y, i));
976 return;
980 /* Checks if patterns P1 and P2 are equivalent, apart from the possibly
981 different single sets S1 and S2. */
983 static bool
984 equal_different_set_p (rtx p1, rtx s1, rtx p2, rtx s2)
986 int i;
987 rtx e1, e2;
989 if (p1 == s1 && p2 == s2)
990 return true;
992 if (GET_CODE (p1) != PARALLEL || GET_CODE (p2) != PARALLEL)
993 return false;
995 if (XVECLEN (p1, 0) != XVECLEN (p2, 0))
996 return false;
998 for (i = 0; i < XVECLEN (p1, 0); i++)
1000 e1 = XVECEXP (p1, 0, i);
1001 e2 = XVECEXP (p2, 0, i);
1002 if (e1 == s1 && e2 == s2)
1003 continue;
1004 if (reload_completed
1005 ? rtx_renumbered_equal_p (e1, e2) : rtx_equal_p (e1, e2))
1006 continue;
1008 return false;
1011 return true;
1015 /* NOTE1 is the REG_EQUAL note, if any, attached to an insn
1016 that is a single_set with a SET_SRC of SRC1. Similarly
1017 for NOTE2/SRC2.
1019 So effectively NOTE1/NOTE2 are an alternate form of
1020 SRC1/SRC2 respectively.
1022 Return nonzero if SRC1 or NOTE1 has the same constant
1023 integer value as SRC2 or NOTE2. Else return zero. */
1024 static int
1025 values_equal_p (rtx note1, rtx note2, rtx src1, rtx src2)
1027 if (note1
1028 && note2
1029 && CONST_INT_P (XEXP (note1, 0))
1030 && rtx_equal_p (XEXP (note1, 0), XEXP (note2, 0)))
1031 return 1;
1033 if (!note1
1034 && !note2
1035 && CONST_INT_P (src1)
1036 && CONST_INT_P (src2)
1037 && rtx_equal_p (src1, src2))
1038 return 1;
1040 if (note1
1041 && CONST_INT_P (src2)
1042 && rtx_equal_p (XEXP (note1, 0), src2))
1043 return 1;
1045 if (note2
1046 && CONST_INT_P (src1)
1047 && rtx_equal_p (XEXP (note2, 0), src1))
1048 return 1;
1050 return 0;
1053 /* Examine register notes on I1 and I2 and return:
1054 - dir_forward if I1 can be replaced by I2, or
1055 - dir_backward if I2 can be replaced by I1, or
1056 - dir_both if both are the case. */
1058 static enum replace_direction
1059 can_replace_by (rtx_insn *i1, rtx_insn *i2)
1061 rtx s1, s2, d1, d2, src1, src2, note1, note2;
1062 bool c1, c2;
1064 /* Check for 2 sets. */
1065 s1 = single_set (i1);
1066 s2 = single_set (i2);
1067 if (s1 == NULL_RTX || s2 == NULL_RTX)
1068 return dir_none;
1070 /* Check that the 2 sets set the same dest. */
1071 d1 = SET_DEST (s1);
1072 d2 = SET_DEST (s2);
1073 if (!(reload_completed
1074 ? rtx_renumbered_equal_p (d1, d2) : rtx_equal_p (d1, d2)))
1075 return dir_none;
1077 /* Find identical req_equiv or reg_equal note, which implies that the 2 sets
1078 set dest to the same value. */
1079 note1 = find_reg_equal_equiv_note (i1);
1080 note2 = find_reg_equal_equiv_note (i2);
1082 src1 = SET_SRC (s1);
1083 src2 = SET_SRC (s2);
1085 if (!values_equal_p (note1, note2, src1, src2))
1086 return dir_none;
1088 if (!equal_different_set_p (PATTERN (i1), s1, PATTERN (i2), s2))
1089 return dir_none;
1091 /* Although the 2 sets set dest to the same value, we cannot replace
1092 (set (dest) (const_int))
1094 (set (dest) (reg))
1095 because we don't know if the reg is live and has the same value at the
1096 location of replacement. */
1097 c1 = CONST_INT_P (src1);
1098 c2 = CONST_INT_P (src2);
1099 if (c1 && c2)
1100 return dir_both;
1101 else if (c2)
1102 return dir_forward;
1103 else if (c1)
1104 return dir_backward;
1106 return dir_none;
1109 /* Merges directions A and B. */
1111 static enum replace_direction
1112 merge_dir (enum replace_direction a, enum replace_direction b)
1114 /* Implements the following table:
1115 |bo fw bw no
1116 ---+-----------
1117 bo |bo fw bw no
1118 fw |-- fw no no
1119 bw |-- -- bw no
1120 no |-- -- -- no. */
1122 if (a == b)
1123 return a;
1125 if (a == dir_both)
1126 return b;
1127 if (b == dir_both)
1128 return a;
1130 return dir_none;
1133 /* Examine I1 and I2 and return:
1134 - dir_forward if I1 can be replaced by I2, or
1135 - dir_backward if I2 can be replaced by I1, or
1136 - dir_both if both are the case. */
1138 static enum replace_direction
1139 old_insns_match_p (int mode ATTRIBUTE_UNUSED, rtx_insn *i1, rtx_insn *i2)
1141 rtx p1, p2;
1143 /* Verify that I1 and I2 are equivalent. */
1144 if (GET_CODE (i1) != GET_CODE (i2))
1145 return dir_none;
1147 /* __builtin_unreachable() may lead to empty blocks (ending with
1148 NOTE_INSN_BASIC_BLOCK). They may be crossjumped. */
1149 if (NOTE_INSN_BASIC_BLOCK_P (i1) && NOTE_INSN_BASIC_BLOCK_P (i2))
1150 return dir_both;
1152 /* ??? Do not allow cross-jumping between different stack levels. */
1153 p1 = find_reg_note (i1, REG_ARGS_SIZE, NULL);
1154 p2 = find_reg_note (i2, REG_ARGS_SIZE, NULL);
1155 if (p1 && p2)
1157 p1 = XEXP (p1, 0);
1158 p2 = XEXP (p2, 0);
1159 if (!rtx_equal_p (p1, p2))
1160 return dir_none;
1162 /* ??? Worse, this adjustment had better be constant lest we
1163 have differing incoming stack levels. */
1164 if (!frame_pointer_needed
1165 && find_args_size_adjust (i1) == HOST_WIDE_INT_MIN)
1166 return dir_none;
1168 else if (p1 || p2)
1169 return dir_none;
1171 p1 = PATTERN (i1);
1172 p2 = PATTERN (i2);
1174 if (GET_CODE (p1) != GET_CODE (p2))
1175 return dir_none;
1177 /* If this is a CALL_INSN, compare register usage information.
1178 If we don't check this on stack register machines, the two
1179 CALL_INSNs might be merged leaving reg-stack.c with mismatching
1180 numbers of stack registers in the same basic block.
1181 If we don't check this on machines with delay slots, a delay slot may
1182 be filled that clobbers a parameter expected by the subroutine.
1184 ??? We take the simple route for now and assume that if they're
1185 equal, they were constructed identically.
1187 Also check for identical exception regions. */
1189 if (CALL_P (i1))
1191 /* Ensure the same EH region. */
1192 rtx n1 = find_reg_note (i1, REG_EH_REGION, 0);
1193 rtx n2 = find_reg_note (i2, REG_EH_REGION, 0);
1195 if (!n1 && n2)
1196 return dir_none;
1198 if (n1 && (!n2 || XEXP (n1, 0) != XEXP (n2, 0)))
1199 return dir_none;
1201 if (!rtx_equal_p (CALL_INSN_FUNCTION_USAGE (i1),
1202 CALL_INSN_FUNCTION_USAGE (i2))
1203 || SIBLING_CALL_P (i1) != SIBLING_CALL_P (i2))
1204 return dir_none;
1206 /* For address sanitizer, never crossjump __asan_report_* builtins,
1207 otherwise errors might be reported on incorrect lines. */
1208 if (flag_sanitize & SANITIZE_ADDRESS)
1210 rtx call = get_call_rtx_from (i1);
1211 if (call && GET_CODE (XEXP (XEXP (call, 0), 0)) == SYMBOL_REF)
1213 rtx symbol = XEXP (XEXP (call, 0), 0);
1214 if (SYMBOL_REF_DECL (symbol)
1215 && TREE_CODE (SYMBOL_REF_DECL (symbol)) == FUNCTION_DECL)
1217 if ((DECL_BUILT_IN_CLASS (SYMBOL_REF_DECL (symbol))
1218 == BUILT_IN_NORMAL)
1219 && DECL_FUNCTION_CODE (SYMBOL_REF_DECL (symbol))
1220 >= BUILT_IN_ASAN_REPORT_LOAD1
1221 && DECL_FUNCTION_CODE (SYMBOL_REF_DECL (symbol))
1222 <= BUILT_IN_ASAN_STOREN)
1223 return dir_none;
1229 #ifdef STACK_REGS
1230 /* If cross_jump_death_matters is not 0, the insn's mode
1231 indicates whether or not the insn contains any stack-like
1232 regs. */
1234 if ((mode & CLEANUP_POST_REGSTACK) && stack_regs_mentioned (i1))
1236 /* If register stack conversion has already been done, then
1237 death notes must also be compared before it is certain that
1238 the two instruction streams match. */
1240 rtx note;
1241 HARD_REG_SET i1_regset, i2_regset;
1243 CLEAR_HARD_REG_SET (i1_regset);
1244 CLEAR_HARD_REG_SET (i2_regset);
1246 for (note = REG_NOTES (i1); note; note = XEXP (note, 1))
1247 if (REG_NOTE_KIND (note) == REG_DEAD && STACK_REG_P (XEXP (note, 0)))
1248 SET_HARD_REG_BIT (i1_regset, REGNO (XEXP (note, 0)));
1250 for (note = REG_NOTES (i2); note; note = XEXP (note, 1))
1251 if (REG_NOTE_KIND (note) == REG_DEAD && STACK_REG_P (XEXP (note, 0)))
1252 SET_HARD_REG_BIT (i2_regset, REGNO (XEXP (note, 0)));
1254 if (!hard_reg_set_equal_p (i1_regset, i2_regset))
1255 return dir_none;
1257 #endif
1259 if (reload_completed
1260 ? rtx_renumbered_equal_p (p1, p2) : rtx_equal_p (p1, p2))
1261 return dir_both;
1263 return can_replace_by (i1, i2);
1266 /* When comparing insns I1 and I2 in flow_find_cross_jump or
1267 flow_find_head_matching_sequence, ensure the notes match. */
1269 static void
1270 merge_notes (rtx_insn *i1, rtx_insn *i2)
1272 /* If the merged insns have different REG_EQUAL notes, then
1273 remove them. */
1274 rtx equiv1 = find_reg_equal_equiv_note (i1);
1275 rtx equiv2 = find_reg_equal_equiv_note (i2);
1277 if (equiv1 && !equiv2)
1278 remove_note (i1, equiv1);
1279 else if (!equiv1 && equiv2)
1280 remove_note (i2, equiv2);
1281 else if (equiv1 && equiv2
1282 && !rtx_equal_p (XEXP (equiv1, 0), XEXP (equiv2, 0)))
1284 remove_note (i1, equiv1);
1285 remove_note (i2, equiv2);
1289 /* Walks from I1 in BB1 backward till the next non-debug insn, and returns the
1290 resulting insn in I1, and the corresponding bb in BB1. At the head of a
1291 bb, if there is a predecessor bb that reaches this bb via fallthru, and
1292 FOLLOW_FALLTHRU, walks further in the predecessor bb and registers this in
1293 DID_FALLTHRU. Otherwise, stops at the head of the bb. */
1295 static void
1296 walk_to_nondebug_insn (rtx_insn **i1, basic_block *bb1, bool follow_fallthru,
1297 bool *did_fallthru)
1299 edge fallthru;
1301 *did_fallthru = false;
1303 /* Ignore notes. */
1304 while (!NONDEBUG_INSN_P (*i1))
1306 if (*i1 != BB_HEAD (*bb1))
1308 *i1 = PREV_INSN (*i1);
1309 continue;
1312 if (!follow_fallthru)
1313 return;
1315 fallthru = find_fallthru_edge ((*bb1)->preds);
1316 if (!fallthru || fallthru->src == ENTRY_BLOCK_PTR_FOR_FN (cfun)
1317 || !single_succ_p (fallthru->src))
1318 return;
1320 *bb1 = fallthru->src;
1321 *i1 = BB_END (*bb1);
1322 *did_fallthru = true;
1326 /* Look through the insns at the end of BB1 and BB2 and find the longest
1327 sequence that are either equivalent, or allow forward or backward
1328 replacement. Store the first insns for that sequence in *F1 and *F2 and
1329 return the sequence length.
1331 DIR_P indicates the allowed replacement direction on function entry, and
1332 the actual replacement direction on function exit. If NULL, only equivalent
1333 sequences are allowed.
1335 To simplify callers of this function, if the blocks match exactly,
1336 store the head of the blocks in *F1 and *F2. */
1339 flow_find_cross_jump (basic_block bb1, basic_block bb2, rtx_insn **f1,
1340 rtx_insn **f2, enum replace_direction *dir_p)
1342 rtx_insn *i1, *i2, *last1, *last2, *afterlast1, *afterlast2;
1343 int ninsns = 0;
1344 enum replace_direction dir, last_dir, afterlast_dir;
1345 bool follow_fallthru, did_fallthru;
1347 if (dir_p)
1348 dir = *dir_p;
1349 else
1350 dir = dir_both;
1351 afterlast_dir = dir;
1352 last_dir = afterlast_dir;
1354 /* Skip simple jumps at the end of the blocks. Complex jumps still
1355 need to be compared for equivalence, which we'll do below. */
1357 i1 = BB_END (bb1);
1358 last1 = afterlast1 = last2 = afterlast2 = NULL;
1359 if (onlyjump_p (i1)
1360 || (returnjump_p (i1) && !side_effects_p (PATTERN (i1))))
1362 last1 = i1;
1363 i1 = PREV_INSN (i1);
1366 i2 = BB_END (bb2);
1367 if (onlyjump_p (i2)
1368 || (returnjump_p (i2) && !side_effects_p (PATTERN (i2))))
1370 last2 = i2;
1371 /* Count everything except for unconditional jump as insn.
1372 Don't count any jumps if dir_p is NULL. */
1373 if (!simplejump_p (i2) && !returnjump_p (i2) && last1 && dir_p)
1374 ninsns++;
1375 i2 = PREV_INSN (i2);
1378 while (true)
1380 /* In the following example, we can replace all jumps to C by jumps to A.
1382 This removes 4 duplicate insns.
1383 [bb A] insn1 [bb C] insn1
1384 insn2 insn2
1385 [bb B] insn3 insn3
1386 insn4 insn4
1387 jump_insn jump_insn
1389 We could also replace all jumps to A by jumps to C, but that leaves B
1390 alive, and removes only 2 duplicate insns. In a subsequent crossjump
1391 step, all jumps to B would be replaced with jumps to the middle of C,
1392 achieving the same result with more effort.
1393 So we allow only the first possibility, which means that we don't allow
1394 fallthru in the block that's being replaced. */
1396 follow_fallthru = dir_p && dir != dir_forward;
1397 walk_to_nondebug_insn (&i1, &bb1, follow_fallthru, &did_fallthru);
1398 if (did_fallthru)
1399 dir = dir_backward;
1401 follow_fallthru = dir_p && dir != dir_backward;
1402 walk_to_nondebug_insn (&i2, &bb2, follow_fallthru, &did_fallthru);
1403 if (did_fallthru)
1404 dir = dir_forward;
1406 if (i1 == BB_HEAD (bb1) || i2 == BB_HEAD (bb2))
1407 break;
1409 dir = merge_dir (dir, old_insns_match_p (0, i1, i2));
1410 if (dir == dir_none || (!dir_p && dir != dir_both))
1411 break;
1413 merge_memattrs (i1, i2);
1415 /* Don't begin a cross-jump with a NOTE insn. */
1416 if (INSN_P (i1))
1418 merge_notes (i1, i2);
1420 afterlast1 = last1, afterlast2 = last2;
1421 last1 = i1, last2 = i2;
1422 afterlast_dir = last_dir;
1423 last_dir = dir;
1424 if (active_insn_p (i1))
1425 ninsns++;
1428 i1 = PREV_INSN (i1);
1429 i2 = PREV_INSN (i2);
1432 /* Don't allow the insn after a compare to be shared by
1433 cross-jumping unless the compare is also shared. */
1434 if (HAVE_cc0 && ninsns && reg_mentioned_p (cc0_rtx, last1)
1435 && ! sets_cc0_p (last1))
1436 last1 = afterlast1, last2 = afterlast2, last_dir = afterlast_dir, ninsns--;
1438 /* Include preceding notes and labels in the cross-jump. One,
1439 this may bring us to the head of the blocks as requested above.
1440 Two, it keeps line number notes as matched as may be. */
1441 if (ninsns)
1443 bb1 = BLOCK_FOR_INSN (last1);
1444 while (last1 != BB_HEAD (bb1) && !NONDEBUG_INSN_P (PREV_INSN (last1)))
1445 last1 = PREV_INSN (last1);
1447 if (last1 != BB_HEAD (bb1) && LABEL_P (PREV_INSN (last1)))
1448 last1 = PREV_INSN (last1);
1450 bb2 = BLOCK_FOR_INSN (last2);
1451 while (last2 != BB_HEAD (bb2) && !NONDEBUG_INSN_P (PREV_INSN (last2)))
1452 last2 = PREV_INSN (last2);
1454 if (last2 != BB_HEAD (bb2) && LABEL_P (PREV_INSN (last2)))
1455 last2 = PREV_INSN (last2);
1457 *f1 = last1;
1458 *f2 = last2;
1461 if (dir_p)
1462 *dir_p = last_dir;
1463 return ninsns;
1466 /* Like flow_find_cross_jump, except start looking for a matching sequence from
1467 the head of the two blocks. Do not include jumps at the end.
1468 If STOP_AFTER is nonzero, stop after finding that many matching
1469 instructions. If STOP_AFTER is zero, count all INSN_P insns, if it is
1470 non-zero, only count active insns. */
1473 flow_find_head_matching_sequence (basic_block bb1, basic_block bb2, rtx_insn **f1,
1474 rtx_insn **f2, int stop_after)
1476 rtx_insn *i1, *i2, *last1, *last2, *beforelast1, *beforelast2;
1477 int ninsns = 0;
1478 edge e;
1479 edge_iterator ei;
1480 int nehedges1 = 0, nehedges2 = 0;
1482 FOR_EACH_EDGE (e, ei, bb1->succs)
1483 if (e->flags & EDGE_EH)
1484 nehedges1++;
1485 FOR_EACH_EDGE (e, ei, bb2->succs)
1486 if (e->flags & EDGE_EH)
1487 nehedges2++;
1489 i1 = BB_HEAD (bb1);
1490 i2 = BB_HEAD (bb2);
1491 last1 = beforelast1 = last2 = beforelast2 = NULL;
1493 while (true)
1495 /* Ignore notes, except NOTE_INSN_EPILOGUE_BEG. */
1496 while (!NONDEBUG_INSN_P (i1) && i1 != BB_END (bb1))
1498 if (NOTE_P (i1) && NOTE_KIND (i1) == NOTE_INSN_EPILOGUE_BEG)
1499 break;
1500 i1 = NEXT_INSN (i1);
1503 while (!NONDEBUG_INSN_P (i2) && i2 != BB_END (bb2))
1505 if (NOTE_P (i2) && NOTE_KIND (i2) == NOTE_INSN_EPILOGUE_BEG)
1506 break;
1507 i2 = NEXT_INSN (i2);
1510 if ((i1 == BB_END (bb1) && !NONDEBUG_INSN_P (i1))
1511 || (i2 == BB_END (bb2) && !NONDEBUG_INSN_P (i2)))
1512 break;
1514 if (NOTE_P (i1) || NOTE_P (i2)
1515 || JUMP_P (i1) || JUMP_P (i2))
1516 break;
1518 /* A sanity check to make sure we're not merging insns with different
1519 effects on EH. If only one of them ends a basic block, it shouldn't
1520 have an EH edge; if both end a basic block, there should be the same
1521 number of EH edges. */
1522 if ((i1 == BB_END (bb1) && i2 != BB_END (bb2)
1523 && nehedges1 > 0)
1524 || (i2 == BB_END (bb2) && i1 != BB_END (bb1)
1525 && nehedges2 > 0)
1526 || (i1 == BB_END (bb1) && i2 == BB_END (bb2)
1527 && nehedges1 != nehedges2))
1528 break;
1530 if (old_insns_match_p (0, i1, i2) != dir_both)
1531 break;
1533 merge_memattrs (i1, i2);
1535 /* Don't begin a cross-jump with a NOTE insn. */
1536 if (INSN_P (i1))
1538 merge_notes (i1, i2);
1540 beforelast1 = last1, beforelast2 = last2;
1541 last1 = i1, last2 = i2;
1542 if (!stop_after || active_insn_p (i1))
1543 ninsns++;
1546 if (i1 == BB_END (bb1) || i2 == BB_END (bb2)
1547 || (stop_after > 0 && ninsns == stop_after))
1548 break;
1550 i1 = NEXT_INSN (i1);
1551 i2 = NEXT_INSN (i2);
1554 /* Don't allow a compare to be shared by cross-jumping unless the insn
1555 after the compare is also shared. */
1556 if (HAVE_cc0 && ninsns && reg_mentioned_p (cc0_rtx, last1)
1557 && sets_cc0_p (last1))
1558 last1 = beforelast1, last2 = beforelast2, ninsns--;
1560 if (ninsns)
1562 *f1 = last1;
1563 *f2 = last2;
1566 return ninsns;
1569 /* Return true iff outgoing edges of BB1 and BB2 match, together with
1570 the branch instruction. This means that if we commonize the control
1571 flow before end of the basic block, the semantic remains unchanged.
1573 We may assume that there exists one edge with a common destination. */
1575 static bool
1576 outgoing_edges_match (int mode, basic_block bb1, basic_block bb2)
1578 int nehedges1 = 0, nehedges2 = 0;
1579 edge fallthru1 = 0, fallthru2 = 0;
1580 edge e1, e2;
1581 edge_iterator ei;
1583 /* If we performed shrink-wrapping, edges to the exit block can
1584 only be distinguished for JUMP_INSNs. The two paths may differ in
1585 whether they went through the prologue. Sibcalls are fine, we know
1586 that we either didn't need or inserted an epilogue before them. */
1587 if (crtl->shrink_wrapped
1588 && single_succ_p (bb1)
1589 && single_succ (bb1) == EXIT_BLOCK_PTR_FOR_FN (cfun)
1590 && !JUMP_P (BB_END (bb1))
1591 && !(CALL_P (BB_END (bb1)) && SIBLING_CALL_P (BB_END (bb1))))
1592 return false;
1594 /* If BB1 has only one successor, we may be looking at either an
1595 unconditional jump, or a fake edge to exit. */
1596 if (single_succ_p (bb1)
1597 && (single_succ_edge (bb1)->flags & (EDGE_COMPLEX | EDGE_FAKE)) == 0
1598 && (!JUMP_P (BB_END (bb1)) || simplejump_p (BB_END (bb1))))
1599 return (single_succ_p (bb2)
1600 && (single_succ_edge (bb2)->flags
1601 & (EDGE_COMPLEX | EDGE_FAKE)) == 0
1602 && (!JUMP_P (BB_END (bb2)) || simplejump_p (BB_END (bb2))));
1604 /* Match conditional jumps - this may get tricky when fallthru and branch
1605 edges are crossed. */
1606 if (EDGE_COUNT (bb1->succs) == 2
1607 && any_condjump_p (BB_END (bb1))
1608 && onlyjump_p (BB_END (bb1)))
1610 edge b1, f1, b2, f2;
1611 bool reverse, match;
1612 rtx set1, set2, cond1, cond2;
1613 enum rtx_code code1, code2;
1615 if (EDGE_COUNT (bb2->succs) != 2
1616 || !any_condjump_p (BB_END (bb2))
1617 || !onlyjump_p (BB_END (bb2)))
1618 return false;
1620 b1 = BRANCH_EDGE (bb1);
1621 b2 = BRANCH_EDGE (bb2);
1622 f1 = FALLTHRU_EDGE (bb1);
1623 f2 = FALLTHRU_EDGE (bb2);
1625 /* Get around possible forwarders on fallthru edges. Other cases
1626 should be optimized out already. */
1627 if (FORWARDER_BLOCK_P (f1->dest))
1628 f1 = single_succ_edge (f1->dest);
1630 if (FORWARDER_BLOCK_P (f2->dest))
1631 f2 = single_succ_edge (f2->dest);
1633 /* To simplify use of this function, return false if there are
1634 unneeded forwarder blocks. These will get eliminated later
1635 during cleanup_cfg. */
1636 if (FORWARDER_BLOCK_P (f1->dest)
1637 || FORWARDER_BLOCK_P (f2->dest)
1638 || FORWARDER_BLOCK_P (b1->dest)
1639 || FORWARDER_BLOCK_P (b2->dest))
1640 return false;
1642 if (f1->dest == f2->dest && b1->dest == b2->dest)
1643 reverse = false;
1644 else if (f1->dest == b2->dest && b1->dest == f2->dest)
1645 reverse = true;
1646 else
1647 return false;
1649 set1 = pc_set (BB_END (bb1));
1650 set2 = pc_set (BB_END (bb2));
1651 if ((XEXP (SET_SRC (set1), 1) == pc_rtx)
1652 != (XEXP (SET_SRC (set2), 1) == pc_rtx))
1653 reverse = !reverse;
1655 cond1 = XEXP (SET_SRC (set1), 0);
1656 cond2 = XEXP (SET_SRC (set2), 0);
1657 code1 = GET_CODE (cond1);
1658 if (reverse)
1659 code2 = reversed_comparison_code (cond2, BB_END (bb2));
1660 else
1661 code2 = GET_CODE (cond2);
1663 if (code2 == UNKNOWN)
1664 return false;
1666 /* Verify codes and operands match. */
1667 match = ((code1 == code2
1668 && rtx_renumbered_equal_p (XEXP (cond1, 0), XEXP (cond2, 0))
1669 && rtx_renumbered_equal_p (XEXP (cond1, 1), XEXP (cond2, 1)))
1670 || (code1 == swap_condition (code2)
1671 && rtx_renumbered_equal_p (XEXP (cond1, 1),
1672 XEXP (cond2, 0))
1673 && rtx_renumbered_equal_p (XEXP (cond1, 0),
1674 XEXP (cond2, 1))));
1676 /* If we return true, we will join the blocks. Which means that
1677 we will only have one branch prediction bit to work with. Thus
1678 we require the existing branches to have probabilities that are
1679 roughly similar. */
1680 if (match
1681 && optimize_bb_for_speed_p (bb1)
1682 && optimize_bb_for_speed_p (bb2))
1684 int prob2;
1686 if (b1->dest == b2->dest)
1687 prob2 = b2->probability;
1688 else
1689 /* Do not use f2 probability as f2 may be forwarded. */
1690 prob2 = REG_BR_PROB_BASE - b2->probability;
1692 /* Fail if the difference in probabilities is greater than 50%.
1693 This rules out two well-predicted branches with opposite
1694 outcomes. */
1695 if (abs (b1->probability - prob2) > REG_BR_PROB_BASE / 2)
1697 if (dump_file)
1698 fprintf (dump_file,
1699 "Outcomes of branch in bb %i and %i differ too much (%i %i)\n",
1700 bb1->index, bb2->index, b1->probability, prob2);
1702 return false;
1706 if (dump_file && match)
1707 fprintf (dump_file, "Conditionals in bb %i and %i match.\n",
1708 bb1->index, bb2->index);
1710 return match;
1713 /* Generic case - we are seeing a computed jump, table jump or trapping
1714 instruction. */
1716 /* Check whether there are tablejumps in the end of BB1 and BB2.
1717 Return true if they are identical. */
1719 rtx label1, label2;
1720 rtx_jump_table_data *table1, *table2;
1722 if (tablejump_p (BB_END (bb1), &label1, &table1)
1723 && tablejump_p (BB_END (bb2), &label2, &table2)
1724 && GET_CODE (PATTERN (table1)) == GET_CODE (PATTERN (table2)))
1726 /* The labels should never be the same rtx. If they really are same
1727 the jump tables are same too. So disable crossjumping of blocks BB1
1728 and BB2 because when deleting the common insns in the end of BB1
1729 by delete_basic_block () the jump table would be deleted too. */
1730 /* If LABEL2 is referenced in BB1->END do not do anything
1731 because we would loose information when replacing
1732 LABEL1 by LABEL2 and then LABEL2 by LABEL1 in BB1->END. */
1733 if (label1 != label2 && !rtx_referenced_p (label2, BB_END (bb1)))
1735 /* Set IDENTICAL to true when the tables are identical. */
1736 bool identical = false;
1737 rtx p1, p2;
1739 p1 = PATTERN (table1);
1740 p2 = PATTERN (table2);
1741 if (GET_CODE (p1) == ADDR_VEC && rtx_equal_p (p1, p2))
1743 identical = true;
1745 else if (GET_CODE (p1) == ADDR_DIFF_VEC
1746 && (XVECLEN (p1, 1) == XVECLEN (p2, 1))
1747 && rtx_equal_p (XEXP (p1, 2), XEXP (p2, 2))
1748 && rtx_equal_p (XEXP (p1, 3), XEXP (p2, 3)))
1750 int i;
1752 identical = true;
1753 for (i = XVECLEN (p1, 1) - 1; i >= 0 && identical; i--)
1754 if (!rtx_equal_p (XVECEXP (p1, 1, i), XVECEXP (p2, 1, i)))
1755 identical = false;
1758 if (identical)
1760 bool match;
1762 /* Temporarily replace references to LABEL1 with LABEL2
1763 in BB1->END so that we could compare the instructions. */
1764 replace_label_in_insn (BB_END (bb1), label1, label2, false);
1766 match = (old_insns_match_p (mode, BB_END (bb1), BB_END (bb2))
1767 == dir_both);
1768 if (dump_file && match)
1769 fprintf (dump_file,
1770 "Tablejumps in bb %i and %i match.\n",
1771 bb1->index, bb2->index);
1773 /* Set the original label in BB1->END because when deleting
1774 a block whose end is a tablejump, the tablejump referenced
1775 from the instruction is deleted too. */
1776 replace_label_in_insn (BB_END (bb1), label2, label1, false);
1778 return match;
1781 return false;
1785 /* Find the last non-debug non-note instruction in each bb, except
1786 stop when we see the NOTE_INSN_BASIC_BLOCK, as old_insns_match_p
1787 handles that case specially. old_insns_match_p does not handle
1788 other types of instruction notes. */
1789 rtx_insn *last1 = BB_END (bb1);
1790 rtx_insn *last2 = BB_END (bb2);
1791 while (!NOTE_INSN_BASIC_BLOCK_P (last1) &&
1792 (DEBUG_INSN_P (last1) || NOTE_P (last1)))
1793 last1 = PREV_INSN (last1);
1794 while (!NOTE_INSN_BASIC_BLOCK_P (last2) &&
1795 (DEBUG_INSN_P (last2) || NOTE_P (last2)))
1796 last2 = PREV_INSN (last2);
1797 gcc_assert (last1 && last2);
1799 /* First ensure that the instructions match. There may be many outgoing
1800 edges so this test is generally cheaper. */
1801 if (old_insns_match_p (mode, last1, last2) != dir_both)
1802 return false;
1804 /* Search the outgoing edges, ensure that the counts do match, find possible
1805 fallthru and exception handling edges since these needs more
1806 validation. */
1807 if (EDGE_COUNT (bb1->succs) != EDGE_COUNT (bb2->succs))
1808 return false;
1810 bool nonfakeedges = false;
1811 FOR_EACH_EDGE (e1, ei, bb1->succs)
1813 e2 = EDGE_SUCC (bb2, ei.index);
1815 if ((e1->flags & EDGE_FAKE) == 0)
1816 nonfakeedges = true;
1818 if (e1->flags & EDGE_EH)
1819 nehedges1++;
1821 if (e2->flags & EDGE_EH)
1822 nehedges2++;
1824 if (e1->flags & EDGE_FALLTHRU)
1825 fallthru1 = e1;
1826 if (e2->flags & EDGE_FALLTHRU)
1827 fallthru2 = e2;
1830 /* If number of edges of various types does not match, fail. */
1831 if (nehedges1 != nehedges2
1832 || (fallthru1 != 0) != (fallthru2 != 0))
1833 return false;
1835 /* If !ACCUMULATE_OUTGOING_ARGS, bb1 (and bb2) have no successors
1836 and the last real insn doesn't have REG_ARGS_SIZE note, don't
1837 attempt to optimize, as the two basic blocks might have different
1838 REG_ARGS_SIZE depths. For noreturn calls and unconditional
1839 traps there should be REG_ARG_SIZE notes, they could be missing
1840 for __builtin_unreachable () uses though. */
1841 if (!nonfakeedges
1842 && !ACCUMULATE_OUTGOING_ARGS
1843 && (!INSN_P (last1)
1844 || !find_reg_note (last1, REG_ARGS_SIZE, NULL)))
1845 return false;
1847 /* fallthru edges must be forwarded to the same destination. */
1848 if (fallthru1)
1850 basic_block d1 = (forwarder_block_p (fallthru1->dest)
1851 ? single_succ (fallthru1->dest): fallthru1->dest);
1852 basic_block d2 = (forwarder_block_p (fallthru2->dest)
1853 ? single_succ (fallthru2->dest): fallthru2->dest);
1855 if (d1 != d2)
1856 return false;
1859 /* Ensure the same EH region. */
1861 rtx n1 = find_reg_note (BB_END (bb1), REG_EH_REGION, 0);
1862 rtx n2 = find_reg_note (BB_END (bb2), REG_EH_REGION, 0);
1864 if (!n1 && n2)
1865 return false;
1867 if (n1 && (!n2 || XEXP (n1, 0) != XEXP (n2, 0)))
1868 return false;
1871 /* The same checks as in try_crossjump_to_edge. It is required for RTL
1872 version of sequence abstraction. */
1873 FOR_EACH_EDGE (e1, ei, bb2->succs)
1875 edge e2;
1876 edge_iterator ei;
1877 basic_block d1 = e1->dest;
1879 if (FORWARDER_BLOCK_P (d1))
1880 d1 = EDGE_SUCC (d1, 0)->dest;
1882 FOR_EACH_EDGE (e2, ei, bb1->succs)
1884 basic_block d2 = e2->dest;
1885 if (FORWARDER_BLOCK_P (d2))
1886 d2 = EDGE_SUCC (d2, 0)->dest;
1887 if (d1 == d2)
1888 break;
1891 if (!e2)
1892 return false;
1895 return true;
1898 /* Returns true if BB basic block has a preserve label. */
1900 static bool
1901 block_has_preserve_label (basic_block bb)
1903 return (bb
1904 && block_label (bb)
1905 && LABEL_PRESERVE_P (block_label (bb)));
1908 /* E1 and E2 are edges with the same destination block. Search their
1909 predecessors for common code. If found, redirect control flow from
1910 (maybe the middle of) E1->SRC to (maybe the middle of) E2->SRC (dir_forward),
1911 or the other way around (dir_backward). DIR specifies the allowed
1912 replacement direction. */
1914 static bool
1915 try_crossjump_to_edge (int mode, edge e1, edge e2,
1916 enum replace_direction dir)
1918 int nmatch;
1919 basic_block src1 = e1->src, src2 = e2->src;
1920 basic_block redirect_to, redirect_from, to_remove;
1921 basic_block osrc1, osrc2, redirect_edges_to, tmp;
1922 rtx_insn *newpos1, *newpos2;
1923 edge s;
1924 edge_iterator ei;
1926 newpos1 = newpos2 = NULL;
1928 /* If we have partitioned hot/cold basic blocks, it is a bad idea
1929 to try this optimization.
1931 Basic block partitioning may result in some jumps that appear to
1932 be optimizable (or blocks that appear to be mergeable), but which really
1933 must be left untouched (they are required to make it safely across
1934 partition boundaries). See the comments at the top of
1935 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
1937 if (crtl->has_bb_partition && reload_completed)
1938 return false;
1940 /* Search backward through forwarder blocks. We don't need to worry
1941 about multiple entry or chained forwarders, as they will be optimized
1942 away. We do this to look past the unconditional jump following a
1943 conditional jump that is required due to the current CFG shape. */
1944 if (single_pred_p (src1)
1945 && FORWARDER_BLOCK_P (src1))
1946 e1 = single_pred_edge (src1), src1 = e1->src;
1948 if (single_pred_p (src2)
1949 && FORWARDER_BLOCK_P (src2))
1950 e2 = single_pred_edge (src2), src2 = e2->src;
1952 /* Nothing to do if we reach ENTRY, or a common source block. */
1953 if (src1 == ENTRY_BLOCK_PTR_FOR_FN (cfun) || src2
1954 == ENTRY_BLOCK_PTR_FOR_FN (cfun))
1955 return false;
1956 if (src1 == src2)
1957 return false;
1959 /* Seeing more than 1 forwarder blocks would confuse us later... */
1960 if (FORWARDER_BLOCK_P (e1->dest)
1961 && FORWARDER_BLOCK_P (single_succ (e1->dest)))
1962 return false;
1964 if (FORWARDER_BLOCK_P (e2->dest)
1965 && FORWARDER_BLOCK_P (single_succ (e2->dest)))
1966 return false;
1968 /* Likewise with dead code (possibly newly created by the other optimizations
1969 of cfg_cleanup). */
1970 if (EDGE_COUNT (src1->preds) == 0 || EDGE_COUNT (src2->preds) == 0)
1971 return false;
1973 /* Look for the common insn sequence, part the first ... */
1974 if (!outgoing_edges_match (mode, src1, src2))
1975 return false;
1977 /* ... and part the second. */
1978 nmatch = flow_find_cross_jump (src1, src2, &newpos1, &newpos2, &dir);
1980 osrc1 = src1;
1981 osrc2 = src2;
1982 if (newpos1 != NULL_RTX)
1983 src1 = BLOCK_FOR_INSN (newpos1);
1984 if (newpos2 != NULL_RTX)
1985 src2 = BLOCK_FOR_INSN (newpos2);
1987 if (dir == dir_backward)
1989 #define SWAP(T, X, Y) do { T tmp = (X); (X) = (Y); (Y) = tmp; } while (0)
1990 SWAP (basic_block, osrc1, osrc2);
1991 SWAP (basic_block, src1, src2);
1992 SWAP (edge, e1, e2);
1993 SWAP (rtx_insn *, newpos1, newpos2);
1994 #undef SWAP
1997 /* Don't proceed with the crossjump unless we found a sufficient number
1998 of matching instructions or the 'from' block was totally matched
1999 (such that its predecessors will hopefully be redirected and the
2000 block removed). */
2001 if ((nmatch < PARAM_VALUE (PARAM_MIN_CROSSJUMP_INSNS))
2002 && (newpos1 != BB_HEAD (src1)))
2003 return false;
2005 /* Avoid deleting preserve label when redirecting ABNORMAL edges. */
2006 if (block_has_preserve_label (e1->dest)
2007 && (e1->flags & EDGE_ABNORMAL))
2008 return false;
2010 /* Here we know that the insns in the end of SRC1 which are common with SRC2
2011 will be deleted.
2012 If we have tablejumps in the end of SRC1 and SRC2
2013 they have been already compared for equivalence in outgoing_edges_match ()
2014 so replace the references to TABLE1 by references to TABLE2. */
2016 rtx label1, label2;
2017 rtx_jump_table_data *table1, *table2;
2019 if (tablejump_p (BB_END (osrc1), &label1, &table1)
2020 && tablejump_p (BB_END (osrc2), &label2, &table2)
2021 && label1 != label2)
2023 rtx_insn *insn;
2025 /* Replace references to LABEL1 with LABEL2. */
2026 for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
2028 /* Do not replace the label in SRC1->END because when deleting
2029 a block whose end is a tablejump, the tablejump referenced
2030 from the instruction is deleted too. */
2031 if (insn != BB_END (osrc1))
2032 replace_label_in_insn (insn, label1, label2, true);
2037 /* Avoid splitting if possible. We must always split when SRC2 has
2038 EH predecessor edges, or we may end up with basic blocks with both
2039 normal and EH predecessor edges. */
2040 if (newpos2 == BB_HEAD (src2)
2041 && !(EDGE_PRED (src2, 0)->flags & EDGE_EH))
2042 redirect_to = src2;
2043 else
2045 if (newpos2 == BB_HEAD (src2))
2047 /* Skip possible basic block header. */
2048 if (LABEL_P (newpos2))
2049 newpos2 = NEXT_INSN (newpos2);
2050 while (DEBUG_INSN_P (newpos2))
2051 newpos2 = NEXT_INSN (newpos2);
2052 if (NOTE_P (newpos2))
2053 newpos2 = NEXT_INSN (newpos2);
2054 while (DEBUG_INSN_P (newpos2))
2055 newpos2 = NEXT_INSN (newpos2);
2058 if (dump_file)
2059 fprintf (dump_file, "Splitting bb %i before %i insns\n",
2060 src2->index, nmatch);
2061 redirect_to = split_block (src2, PREV_INSN (newpos2))->dest;
2064 if (dump_file)
2065 fprintf (dump_file,
2066 "Cross jumping from bb %i to bb %i; %i common insns\n",
2067 src1->index, src2->index, nmatch);
2069 /* We may have some registers visible through the block. */
2070 df_set_bb_dirty (redirect_to);
2072 if (osrc2 == src2)
2073 redirect_edges_to = redirect_to;
2074 else
2075 redirect_edges_to = osrc2;
2077 /* Recompute the frequencies and counts of outgoing edges. */
2078 FOR_EACH_EDGE (s, ei, redirect_edges_to->succs)
2080 edge s2;
2081 edge_iterator ei;
2082 basic_block d = s->dest;
2084 if (FORWARDER_BLOCK_P (d))
2085 d = single_succ (d);
2087 FOR_EACH_EDGE (s2, ei, src1->succs)
2089 basic_block d2 = s2->dest;
2090 if (FORWARDER_BLOCK_P (d2))
2091 d2 = single_succ (d2);
2092 if (d == d2)
2093 break;
2096 s->count += s2->count;
2098 /* Take care to update possible forwarder blocks. We verified
2099 that there is no more than one in the chain, so we can't run
2100 into infinite loop. */
2101 if (FORWARDER_BLOCK_P (s->dest))
2103 single_succ_edge (s->dest)->count += s2->count;
2104 s->dest->count += s2->count;
2105 s->dest->frequency += EDGE_FREQUENCY (s);
2108 if (FORWARDER_BLOCK_P (s2->dest))
2110 single_succ_edge (s2->dest)->count -= s2->count;
2111 if (single_succ_edge (s2->dest)->count < 0)
2112 single_succ_edge (s2->dest)->count = 0;
2113 s2->dest->count -= s2->count;
2114 s2->dest->frequency -= EDGE_FREQUENCY (s);
2115 if (s2->dest->frequency < 0)
2116 s2->dest->frequency = 0;
2117 if (s2->dest->count < 0)
2118 s2->dest->count = 0;
2121 if (!redirect_edges_to->frequency && !src1->frequency)
2122 s->probability = (s->probability + s2->probability) / 2;
2123 else
2124 s->probability
2125 = ((s->probability * redirect_edges_to->frequency +
2126 s2->probability * src1->frequency)
2127 / (redirect_edges_to->frequency + src1->frequency));
2130 /* Adjust count and frequency for the block. An earlier jump
2131 threading pass may have left the profile in an inconsistent
2132 state (see update_bb_profile_for_threading) so we must be
2133 prepared for overflows. */
2134 tmp = redirect_to;
2137 tmp->count += src1->count;
2138 tmp->frequency += src1->frequency;
2139 if (tmp->frequency > BB_FREQ_MAX)
2140 tmp->frequency = BB_FREQ_MAX;
2141 if (tmp == redirect_edges_to)
2142 break;
2143 tmp = find_fallthru_edge (tmp->succs)->dest;
2145 while (true);
2146 update_br_prob_note (redirect_edges_to);
2148 /* Edit SRC1 to go to REDIRECT_TO at NEWPOS1. */
2150 /* Skip possible basic block header. */
2151 if (LABEL_P (newpos1))
2152 newpos1 = NEXT_INSN (newpos1);
2154 while (DEBUG_INSN_P (newpos1))
2155 newpos1 = NEXT_INSN (newpos1);
2157 if (NOTE_INSN_BASIC_BLOCK_P (newpos1))
2158 newpos1 = NEXT_INSN (newpos1);
2160 while (DEBUG_INSN_P (newpos1))
2161 newpos1 = NEXT_INSN (newpos1);
2163 redirect_from = split_block (src1, PREV_INSN (newpos1))->src;
2164 to_remove = single_succ (redirect_from);
2166 redirect_edge_and_branch_force (single_succ_edge (redirect_from), redirect_to);
2167 delete_basic_block (to_remove);
2169 update_forwarder_flag (redirect_from);
2170 if (redirect_to != src2)
2171 update_forwarder_flag (src2);
2173 return true;
2176 /* Search the predecessors of BB for common insn sequences. When found,
2177 share code between them by redirecting control flow. Return true if
2178 any changes made. */
2180 static bool
2181 try_crossjump_bb (int mode, basic_block bb)
2183 edge e, e2, fallthru;
2184 bool changed;
2185 unsigned max, ix, ix2;
2187 /* Nothing to do if there is not at least two incoming edges. */
2188 if (EDGE_COUNT (bb->preds) < 2)
2189 return false;
2191 /* Don't crossjump if this block ends in a computed jump,
2192 unless we are optimizing for size. */
2193 if (optimize_bb_for_size_p (bb)
2194 && bb != EXIT_BLOCK_PTR_FOR_FN (cfun)
2195 && computed_jump_p (BB_END (bb)))
2196 return false;
2198 /* If we are partitioning hot/cold basic blocks, we don't want to
2199 mess up unconditional or indirect jumps that cross between hot
2200 and cold sections.
2202 Basic block partitioning may result in some jumps that appear to
2203 be optimizable (or blocks that appear to be mergeable), but which really
2204 must be left untouched (they are required to make it safely across
2205 partition boundaries). See the comments at the top of
2206 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
2208 if (BB_PARTITION (EDGE_PRED (bb, 0)->src) !=
2209 BB_PARTITION (EDGE_PRED (bb, 1)->src)
2210 || (EDGE_PRED (bb, 0)->flags & EDGE_CROSSING))
2211 return false;
2213 /* It is always cheapest to redirect a block that ends in a branch to
2214 a block that falls through into BB, as that adds no branches to the
2215 program. We'll try that combination first. */
2216 fallthru = NULL;
2217 max = PARAM_VALUE (PARAM_MAX_CROSSJUMP_EDGES);
2219 if (EDGE_COUNT (bb->preds) > max)
2220 return false;
2222 fallthru = find_fallthru_edge (bb->preds);
2224 changed = false;
2225 for (ix = 0; ix < EDGE_COUNT (bb->preds);)
2227 e = EDGE_PRED (bb, ix);
2228 ix++;
2230 /* As noted above, first try with the fallthru predecessor (or, a
2231 fallthru predecessor if we are in cfglayout mode). */
2232 if (fallthru)
2234 /* Don't combine the fallthru edge into anything else.
2235 If there is a match, we'll do it the other way around. */
2236 if (e == fallthru)
2237 continue;
2238 /* If nothing changed since the last attempt, there is nothing
2239 we can do. */
2240 if (!first_pass
2241 && !((e->src->flags & BB_MODIFIED)
2242 || (fallthru->src->flags & BB_MODIFIED)))
2243 continue;
2245 if (try_crossjump_to_edge (mode, e, fallthru, dir_forward))
2247 changed = true;
2248 ix = 0;
2249 continue;
2253 /* Non-obvious work limiting check: Recognize that we're going
2254 to call try_crossjump_bb on every basic block. So if we have
2255 two blocks with lots of outgoing edges (a switch) and they
2256 share lots of common destinations, then we would do the
2257 cross-jump check once for each common destination.
2259 Now, if the blocks actually are cross-jump candidates, then
2260 all of their destinations will be shared. Which means that
2261 we only need check them for cross-jump candidacy once. We
2262 can eliminate redundant checks of crossjump(A,B) by arbitrarily
2263 choosing to do the check from the block for which the edge
2264 in question is the first successor of A. */
2265 if (EDGE_SUCC (e->src, 0) != e)
2266 continue;
2268 for (ix2 = 0; ix2 < EDGE_COUNT (bb->preds); ix2++)
2270 e2 = EDGE_PRED (bb, ix2);
2272 if (e2 == e)
2273 continue;
2275 /* We've already checked the fallthru edge above. */
2276 if (e2 == fallthru)
2277 continue;
2279 /* The "first successor" check above only prevents multiple
2280 checks of crossjump(A,B). In order to prevent redundant
2281 checks of crossjump(B,A), require that A be the block
2282 with the lowest index. */
2283 if (e->src->index > e2->src->index)
2284 continue;
2286 /* If nothing changed since the last attempt, there is nothing
2287 we can do. */
2288 if (!first_pass
2289 && !((e->src->flags & BB_MODIFIED)
2290 || (e2->src->flags & BB_MODIFIED)))
2291 continue;
2293 /* Both e and e2 are not fallthru edges, so we can crossjump in either
2294 direction. */
2295 if (try_crossjump_to_edge (mode, e, e2, dir_both))
2297 changed = true;
2298 ix = 0;
2299 break;
2304 if (changed)
2305 crossjumps_occured = true;
2307 return changed;
2310 /* Search the successors of BB for common insn sequences. When found,
2311 share code between them by moving it across the basic block
2312 boundary. Return true if any changes made. */
2314 static bool
2315 try_head_merge_bb (basic_block bb)
2317 basic_block final_dest_bb = NULL;
2318 int max_match = INT_MAX;
2319 edge e0;
2320 rtx_insn **headptr, **currptr, **nextptr;
2321 bool changed, moveall;
2322 unsigned ix;
2323 rtx_insn *e0_last_head;
2324 rtx cond;
2325 rtx_insn *move_before;
2326 unsigned nedges = EDGE_COUNT (bb->succs);
2327 rtx_insn *jump = BB_END (bb);
2328 regset live, live_union;
2330 /* Nothing to do if there is not at least two outgoing edges. */
2331 if (nedges < 2)
2332 return false;
2334 /* Don't crossjump if this block ends in a computed jump,
2335 unless we are optimizing for size. */
2336 if (optimize_bb_for_size_p (bb)
2337 && bb != EXIT_BLOCK_PTR_FOR_FN (cfun)
2338 && computed_jump_p (BB_END (bb)))
2339 return false;
2341 cond = get_condition (jump, &move_before, true, false);
2342 if (cond == NULL_RTX)
2344 if (HAVE_cc0 && reg_mentioned_p (cc0_rtx, jump))
2345 move_before = prev_nonnote_nondebug_insn (jump);
2346 else
2347 move_before = jump;
2350 for (ix = 0; ix < nedges; ix++)
2351 if (EDGE_SUCC (bb, ix)->dest == EXIT_BLOCK_PTR_FOR_FN (cfun))
2352 return false;
2354 for (ix = 0; ix < nedges; ix++)
2356 edge e = EDGE_SUCC (bb, ix);
2357 basic_block other_bb = e->dest;
2359 if (df_get_bb_dirty (other_bb))
2361 block_was_dirty = true;
2362 return false;
2365 if (e->flags & EDGE_ABNORMAL)
2366 return false;
2368 /* Normally, all destination blocks must only be reachable from this
2369 block, i.e. they must have one incoming edge.
2371 There is one special case we can handle, that of multiple consecutive
2372 jumps where the first jumps to one of the targets of the second jump.
2373 This happens frequently in switch statements for default labels.
2374 The structure is as follows:
2375 FINAL_DEST_BB
2376 ....
2377 if (cond) jump A;
2378 fall through
2380 jump with targets A, B, C, D...
2382 has two incoming edges, from FINAL_DEST_BB and BB
2384 In this case, we can try to move the insns through BB and into
2385 FINAL_DEST_BB. */
2386 if (EDGE_COUNT (other_bb->preds) != 1)
2388 edge incoming_edge, incoming_bb_other_edge;
2389 edge_iterator ei;
2391 if (final_dest_bb != NULL
2392 || EDGE_COUNT (other_bb->preds) != 2)
2393 return false;
2395 /* We must be able to move the insns across the whole block. */
2396 move_before = BB_HEAD (bb);
2397 while (!NONDEBUG_INSN_P (move_before))
2398 move_before = NEXT_INSN (move_before);
2400 if (EDGE_COUNT (bb->preds) != 1)
2401 return false;
2402 incoming_edge = EDGE_PRED (bb, 0);
2403 final_dest_bb = incoming_edge->src;
2404 if (EDGE_COUNT (final_dest_bb->succs) != 2)
2405 return false;
2406 FOR_EACH_EDGE (incoming_bb_other_edge, ei, final_dest_bb->succs)
2407 if (incoming_bb_other_edge != incoming_edge)
2408 break;
2409 if (incoming_bb_other_edge->dest != other_bb)
2410 return false;
2414 e0 = EDGE_SUCC (bb, 0);
2415 e0_last_head = NULL;
2416 changed = false;
2418 for (ix = 1; ix < nedges; ix++)
2420 edge e = EDGE_SUCC (bb, ix);
2421 rtx_insn *e0_last, *e_last;
2422 int nmatch;
2424 nmatch = flow_find_head_matching_sequence (e0->dest, e->dest,
2425 &e0_last, &e_last, 0);
2426 if (nmatch == 0)
2427 return false;
2429 if (nmatch < max_match)
2431 max_match = nmatch;
2432 e0_last_head = e0_last;
2436 /* If we matched an entire block, we probably have to avoid moving the
2437 last insn. */
2438 if (max_match > 0
2439 && e0_last_head == BB_END (e0->dest)
2440 && (find_reg_note (e0_last_head, REG_EH_REGION, 0)
2441 || control_flow_insn_p (e0_last_head)))
2443 max_match--;
2444 if (max_match == 0)
2445 return false;
2447 e0_last_head = prev_real_insn (e0_last_head);
2448 while (DEBUG_INSN_P (e0_last_head));
2451 if (max_match == 0)
2452 return false;
2454 /* We must find a union of the live registers at each of the end points. */
2455 live = BITMAP_ALLOC (NULL);
2456 live_union = BITMAP_ALLOC (NULL);
2458 currptr = XNEWVEC (rtx_insn *, nedges);
2459 headptr = XNEWVEC (rtx_insn *, nedges);
2460 nextptr = XNEWVEC (rtx_insn *, nedges);
2462 for (ix = 0; ix < nedges; ix++)
2464 int j;
2465 basic_block merge_bb = EDGE_SUCC (bb, ix)->dest;
2466 rtx_insn *head = BB_HEAD (merge_bb);
2468 while (!NONDEBUG_INSN_P (head))
2469 head = NEXT_INSN (head);
2470 headptr[ix] = head;
2471 currptr[ix] = head;
2473 /* Compute the end point and live information */
2474 for (j = 1; j < max_match; j++)
2476 head = NEXT_INSN (head);
2477 while (!NONDEBUG_INSN_P (head));
2478 simulate_backwards_to_point (merge_bb, live, head);
2479 IOR_REG_SET (live_union, live);
2482 /* If we're moving across two blocks, verify the validity of the
2483 first move, then adjust the target and let the loop below deal
2484 with the final move. */
2485 if (final_dest_bb != NULL)
2487 rtx_insn *move_upto;
2489 moveall = can_move_insns_across (currptr[0], e0_last_head, move_before,
2490 jump, e0->dest, live_union,
2491 NULL, &move_upto);
2492 if (!moveall)
2494 if (move_upto == NULL_RTX)
2495 goto out;
2497 while (e0_last_head != move_upto)
2499 df_simulate_one_insn_backwards (e0->dest, e0_last_head,
2500 live_union);
2501 e0_last_head = PREV_INSN (e0_last_head);
2504 if (e0_last_head == NULL_RTX)
2505 goto out;
2507 jump = BB_END (final_dest_bb);
2508 cond = get_condition (jump, &move_before, true, false);
2509 if (cond == NULL_RTX)
2511 if (HAVE_cc0 && reg_mentioned_p (cc0_rtx, jump))
2512 move_before = prev_nonnote_nondebug_insn (jump);
2513 else
2514 move_before = jump;
2520 rtx_insn *move_upto;
2521 moveall = can_move_insns_across (currptr[0], e0_last_head,
2522 move_before, jump, e0->dest, live_union,
2523 NULL, &move_upto);
2524 if (!moveall && move_upto == NULL_RTX)
2526 if (jump == move_before)
2527 break;
2529 /* Try again, using a different insertion point. */
2530 move_before = jump;
2532 /* Don't try moving before a cc0 user, as that may invalidate
2533 the cc0. */
2534 if (HAVE_cc0 && reg_mentioned_p (cc0_rtx, jump))
2535 break;
2537 continue;
2540 if (final_dest_bb && !moveall)
2541 /* We haven't checked whether a partial move would be OK for the first
2542 move, so we have to fail this case. */
2543 break;
2545 changed = true;
2546 for (;;)
2548 if (currptr[0] == move_upto)
2549 break;
2550 for (ix = 0; ix < nedges; ix++)
2552 rtx_insn *curr = currptr[ix];
2554 curr = NEXT_INSN (curr);
2555 while (!NONDEBUG_INSN_P (curr));
2556 currptr[ix] = curr;
2560 /* If we can't currently move all of the identical insns, remember
2561 each insn after the range that we'll merge. */
2562 if (!moveall)
2563 for (ix = 0; ix < nedges; ix++)
2565 rtx_insn *curr = currptr[ix];
2567 curr = NEXT_INSN (curr);
2568 while (!NONDEBUG_INSN_P (curr));
2569 nextptr[ix] = curr;
2572 reorder_insns (headptr[0], currptr[0], PREV_INSN (move_before));
2573 df_set_bb_dirty (EDGE_SUCC (bb, 0)->dest);
2574 if (final_dest_bb != NULL)
2575 df_set_bb_dirty (final_dest_bb);
2576 df_set_bb_dirty (bb);
2577 for (ix = 1; ix < nedges; ix++)
2579 df_set_bb_dirty (EDGE_SUCC (bb, ix)->dest);
2580 delete_insn_chain (headptr[ix], currptr[ix], false);
2582 if (!moveall)
2584 if (jump == move_before)
2585 break;
2587 /* For the unmerged insns, try a different insertion point. */
2588 move_before = jump;
2590 /* Don't try moving before a cc0 user, as that may invalidate
2591 the cc0. */
2592 if (HAVE_cc0 && reg_mentioned_p (cc0_rtx, jump))
2593 break;
2595 for (ix = 0; ix < nedges; ix++)
2596 currptr[ix] = headptr[ix] = nextptr[ix];
2599 while (!moveall);
2601 out:
2602 free (currptr);
2603 free (headptr);
2604 free (nextptr);
2606 crossjumps_occured |= changed;
2608 return changed;
2611 /* Return true if BB contains just bb note, or bb note followed
2612 by only DEBUG_INSNs. */
2614 static bool
2615 trivially_empty_bb_p (basic_block bb)
2617 rtx_insn *insn = BB_END (bb);
2619 while (1)
2621 if (insn == BB_HEAD (bb))
2622 return true;
2623 if (!DEBUG_INSN_P (insn))
2624 return false;
2625 insn = PREV_INSN (insn);
2629 /* Do simple CFG optimizations - basic block merging, simplifying of jump
2630 instructions etc. Return nonzero if changes were made. */
2632 static bool
2633 try_optimize_cfg (int mode)
2635 bool changed_overall = false;
2636 bool changed;
2637 int iterations = 0;
2638 basic_block bb, b, next;
2640 if (mode & (CLEANUP_CROSSJUMP | CLEANUP_THREADING))
2641 clear_bb_flags ();
2643 crossjumps_occured = false;
2645 FOR_EACH_BB_FN (bb, cfun)
2646 update_forwarder_flag (bb);
2648 if (! targetm.cannot_modify_jumps_p ())
2650 first_pass = true;
2651 /* Attempt to merge blocks as made possible by edge removal. If
2652 a block has only one successor, and the successor has only
2653 one predecessor, they may be combined. */
2656 block_was_dirty = false;
2657 changed = false;
2658 iterations++;
2660 if (dump_file)
2661 fprintf (dump_file,
2662 "\n\ntry_optimize_cfg iteration %i\n\n",
2663 iterations);
2665 for (b = ENTRY_BLOCK_PTR_FOR_FN (cfun)->next_bb; b
2666 != EXIT_BLOCK_PTR_FOR_FN (cfun);)
2668 basic_block c;
2669 edge s;
2670 bool changed_here = false;
2672 /* Delete trivially dead basic blocks. This is either
2673 blocks with no predecessors, or empty blocks with no
2674 successors. However if the empty block with no
2675 successors is the successor of the ENTRY_BLOCK, it is
2676 kept. This ensures that the ENTRY_BLOCK will have a
2677 successor which is a precondition for many RTL
2678 passes. Empty blocks may result from expanding
2679 __builtin_unreachable (). */
2680 if (EDGE_COUNT (b->preds) == 0
2681 || (EDGE_COUNT (b->succs) == 0
2682 && trivially_empty_bb_p (b)
2683 && single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun))->dest
2684 != b))
2686 c = b->prev_bb;
2687 if (EDGE_COUNT (b->preds) > 0)
2689 edge e;
2690 edge_iterator ei;
2692 if (current_ir_type () == IR_RTL_CFGLAYOUT)
2694 if (BB_FOOTER (b)
2695 && BARRIER_P (BB_FOOTER (b)))
2696 FOR_EACH_EDGE (e, ei, b->preds)
2697 if ((e->flags & EDGE_FALLTHRU)
2698 && BB_FOOTER (e->src) == NULL)
2700 if (BB_FOOTER (b))
2702 BB_FOOTER (e->src) = BB_FOOTER (b);
2703 BB_FOOTER (b) = NULL;
2705 else
2707 start_sequence ();
2708 BB_FOOTER (e->src) = emit_barrier ();
2709 end_sequence ();
2713 else
2715 rtx_insn *last = get_last_bb_insn (b);
2716 if (last && BARRIER_P (last))
2717 FOR_EACH_EDGE (e, ei, b->preds)
2718 if ((e->flags & EDGE_FALLTHRU))
2719 emit_barrier_after (BB_END (e->src));
2722 delete_basic_block (b);
2723 changed = true;
2724 /* Avoid trying to remove the exit block. */
2725 b = (c == ENTRY_BLOCK_PTR_FOR_FN (cfun) ? c->next_bb : c);
2726 continue;
2729 /* Remove code labels no longer used. */
2730 if (single_pred_p (b)
2731 && (single_pred_edge (b)->flags & EDGE_FALLTHRU)
2732 && !(single_pred_edge (b)->flags & EDGE_COMPLEX)
2733 && LABEL_P (BB_HEAD (b))
2734 && !LABEL_PRESERVE_P (BB_HEAD (b))
2735 /* If the previous block ends with a branch to this
2736 block, we can't delete the label. Normally this
2737 is a condjump that is yet to be simplified, but
2738 if CASE_DROPS_THRU, this can be a tablejump with
2739 some element going to the same place as the
2740 default (fallthru). */
2741 && (single_pred (b) == ENTRY_BLOCK_PTR_FOR_FN (cfun)
2742 || !JUMP_P (BB_END (single_pred (b)))
2743 || ! label_is_jump_target_p (BB_HEAD (b),
2744 BB_END (single_pred (b)))))
2746 delete_insn (BB_HEAD (b));
2747 if (dump_file)
2748 fprintf (dump_file, "Deleted label in block %i.\n",
2749 b->index);
2752 /* If we fall through an empty block, we can remove it. */
2753 if (!(mode & (CLEANUP_CFGLAYOUT | CLEANUP_NO_INSN_DEL))
2754 && single_pred_p (b)
2755 && (single_pred_edge (b)->flags & EDGE_FALLTHRU)
2756 && !LABEL_P (BB_HEAD (b))
2757 && FORWARDER_BLOCK_P (b)
2758 /* Note that forwarder_block_p true ensures that
2759 there is a successor for this block. */
2760 && (single_succ_edge (b)->flags & EDGE_FALLTHRU)
2761 && n_basic_blocks_for_fn (cfun) > NUM_FIXED_BLOCKS + 1)
2763 if (dump_file)
2764 fprintf (dump_file,
2765 "Deleting fallthru block %i.\n",
2766 b->index);
2768 c = ((b->prev_bb == ENTRY_BLOCK_PTR_FOR_FN (cfun))
2769 ? b->next_bb : b->prev_bb);
2770 redirect_edge_succ_nodup (single_pred_edge (b),
2771 single_succ (b));
2772 delete_basic_block (b);
2773 changed = true;
2774 b = c;
2775 continue;
2778 /* Merge B with its single successor, if any. */
2779 if (single_succ_p (b)
2780 && (s = single_succ_edge (b))
2781 && !(s->flags & EDGE_COMPLEX)
2782 && (c = s->dest) != EXIT_BLOCK_PTR_FOR_FN (cfun)
2783 && single_pred_p (c)
2784 && b != c)
2786 /* When not in cfg_layout mode use code aware of reordering
2787 INSN. This code possibly creates new basic blocks so it
2788 does not fit merge_blocks interface and is kept here in
2789 hope that it will become useless once more of compiler
2790 is transformed to use cfg_layout mode. */
2792 if ((mode & CLEANUP_CFGLAYOUT)
2793 && can_merge_blocks_p (b, c))
2795 merge_blocks (b, c);
2796 update_forwarder_flag (b);
2797 changed_here = true;
2799 else if (!(mode & CLEANUP_CFGLAYOUT)
2800 /* If the jump insn has side effects,
2801 we can't kill the edge. */
2802 && (!JUMP_P (BB_END (b))
2803 || (reload_completed
2804 ? simplejump_p (BB_END (b))
2805 : (onlyjump_p (BB_END (b))
2806 && !tablejump_p (BB_END (b),
2807 NULL, NULL))))
2808 && (next = merge_blocks_move (s, b, c, mode)))
2810 b = next;
2811 changed_here = true;
2815 /* Simplify branch over branch. */
2816 if ((mode & CLEANUP_EXPENSIVE)
2817 && !(mode & CLEANUP_CFGLAYOUT)
2818 && try_simplify_condjump (b))
2819 changed_here = true;
2821 /* If B has a single outgoing edge, but uses a
2822 non-trivial jump instruction without side-effects, we
2823 can either delete the jump entirely, or replace it
2824 with a simple unconditional jump. */
2825 if (single_succ_p (b)
2826 && single_succ (b) != EXIT_BLOCK_PTR_FOR_FN (cfun)
2827 && onlyjump_p (BB_END (b))
2828 && !CROSSING_JUMP_P (BB_END (b))
2829 && try_redirect_by_replacing_jump (single_succ_edge (b),
2830 single_succ (b),
2831 (mode & CLEANUP_CFGLAYOUT) != 0))
2833 update_forwarder_flag (b);
2834 changed_here = true;
2837 /* Simplify branch to branch. */
2838 if (try_forward_edges (mode, b))
2840 update_forwarder_flag (b);
2841 changed_here = true;
2844 /* Look for shared code between blocks. */
2845 if ((mode & CLEANUP_CROSSJUMP)
2846 && try_crossjump_bb (mode, b))
2847 changed_here = true;
2849 if ((mode & CLEANUP_CROSSJUMP)
2850 /* This can lengthen register lifetimes. Do it only after
2851 reload. */
2852 && reload_completed
2853 && try_head_merge_bb (b))
2854 changed_here = true;
2856 /* Don't get confused by the index shift caused by
2857 deleting blocks. */
2858 if (!changed_here)
2859 b = b->next_bb;
2860 else
2861 changed = true;
2864 if ((mode & CLEANUP_CROSSJUMP)
2865 && try_crossjump_bb (mode, EXIT_BLOCK_PTR_FOR_FN (cfun)))
2866 changed = true;
2868 if (block_was_dirty)
2870 /* This should only be set by head-merging. */
2871 gcc_assert (mode & CLEANUP_CROSSJUMP);
2872 df_analyze ();
2875 if (changed)
2877 /* Edge forwarding in particular can cause hot blocks previously
2878 reached by both hot and cold blocks to become dominated only
2879 by cold blocks. This will cause the verification below to fail,
2880 and lead to now cold code in the hot section. This is not easy
2881 to detect and fix during edge forwarding, and in some cases
2882 is only visible after newly unreachable blocks are deleted,
2883 which will be done in fixup_partitions. */
2884 fixup_partitions ();
2886 #ifdef ENABLE_CHECKING
2887 verify_flow_info ();
2888 #endif
2891 changed_overall |= changed;
2892 first_pass = false;
2894 while (changed);
2897 FOR_ALL_BB_FN (b, cfun)
2898 b->flags &= ~(BB_FORWARDER_BLOCK | BB_NONTHREADABLE_BLOCK);
2900 return changed_overall;
2903 /* Delete all unreachable basic blocks. */
2905 bool
2906 delete_unreachable_blocks (void)
2908 bool changed = false;
2909 basic_block b, prev_bb;
2911 find_unreachable_blocks ();
2913 /* When we're in GIMPLE mode and there may be debug insns, we should
2914 delete blocks in reverse dominator order, so as to get a chance
2915 to substitute all released DEFs into debug stmts. If we don't
2916 have dominators information, walking blocks backward gets us a
2917 better chance of retaining most debug information than
2918 otherwise. */
2919 if (MAY_HAVE_DEBUG_INSNS && current_ir_type () == IR_GIMPLE
2920 && dom_info_available_p (CDI_DOMINATORS))
2922 for (b = EXIT_BLOCK_PTR_FOR_FN (cfun)->prev_bb;
2923 b != ENTRY_BLOCK_PTR_FOR_FN (cfun); b = prev_bb)
2925 prev_bb = b->prev_bb;
2927 if (!(b->flags & BB_REACHABLE))
2929 /* Speed up the removal of blocks that don't dominate
2930 others. Walking backwards, this should be the common
2931 case. */
2932 if (!first_dom_son (CDI_DOMINATORS, b))
2933 delete_basic_block (b);
2934 else
2936 vec<basic_block> h
2937 = get_all_dominated_blocks (CDI_DOMINATORS, b);
2939 while (h.length ())
2941 b = h.pop ();
2943 prev_bb = b->prev_bb;
2945 gcc_assert (!(b->flags & BB_REACHABLE));
2947 delete_basic_block (b);
2950 h.release ();
2953 changed = true;
2957 else
2959 for (b = EXIT_BLOCK_PTR_FOR_FN (cfun)->prev_bb;
2960 b != ENTRY_BLOCK_PTR_FOR_FN (cfun); b = prev_bb)
2962 prev_bb = b->prev_bb;
2964 if (!(b->flags & BB_REACHABLE))
2966 delete_basic_block (b);
2967 changed = true;
2972 if (changed)
2973 tidy_fallthru_edges ();
2974 return changed;
2977 /* Delete any jump tables never referenced. We can't delete them at the
2978 time of removing tablejump insn as they are referenced by the preceding
2979 insns computing the destination, so we delay deleting and garbagecollect
2980 them once life information is computed. */
2981 void
2982 delete_dead_jumptables (void)
2984 basic_block bb;
2986 /* A dead jump table does not belong to any basic block. Scan insns
2987 between two adjacent basic blocks. */
2988 FOR_EACH_BB_FN (bb, cfun)
2990 rtx_insn *insn, *next;
2992 for (insn = NEXT_INSN (BB_END (bb));
2993 insn && !NOTE_INSN_BASIC_BLOCK_P (insn);
2994 insn = next)
2996 next = NEXT_INSN (insn);
2997 if (LABEL_P (insn)
2998 && LABEL_NUSES (insn) == LABEL_PRESERVE_P (insn)
2999 && JUMP_TABLE_DATA_P (next))
3001 rtx_insn *label = insn, *jump = next;
3003 if (dump_file)
3004 fprintf (dump_file, "Dead jumptable %i removed\n",
3005 INSN_UID (insn));
3007 next = NEXT_INSN (next);
3008 delete_insn (jump);
3009 delete_insn (label);
3016 /* Tidy the CFG by deleting unreachable code and whatnot. */
3018 bool
3019 cleanup_cfg (int mode)
3021 bool changed = false;
3023 /* Set the cfglayout mode flag here. We could update all the callers
3024 but that is just inconvenient, especially given that we eventually
3025 want to have cfglayout mode as the default. */
3026 if (current_ir_type () == IR_RTL_CFGLAYOUT)
3027 mode |= CLEANUP_CFGLAYOUT;
3029 timevar_push (TV_CLEANUP_CFG);
3030 if (delete_unreachable_blocks ())
3032 changed = true;
3033 /* We've possibly created trivially dead code. Cleanup it right
3034 now to introduce more opportunities for try_optimize_cfg. */
3035 if (!(mode & (CLEANUP_NO_INSN_DEL))
3036 && !reload_completed)
3037 delete_trivially_dead_insns (get_insns (), max_reg_num ());
3040 compact_blocks ();
3042 /* To tail-merge blocks ending in the same noreturn function (e.g.
3043 a call to abort) we have to insert fake edges to exit. Do this
3044 here once. The fake edges do not interfere with any other CFG
3045 cleanups. */
3046 if (mode & CLEANUP_CROSSJUMP)
3047 add_noreturn_fake_exit_edges ();
3049 if (!dbg_cnt (cfg_cleanup))
3050 return changed;
3052 while (try_optimize_cfg (mode))
3054 delete_unreachable_blocks (), changed = true;
3055 if (!(mode & CLEANUP_NO_INSN_DEL))
3057 /* Try to remove some trivially dead insns when doing an expensive
3058 cleanup. But delete_trivially_dead_insns doesn't work after
3059 reload (it only handles pseudos) and run_fast_dce is too costly
3060 to run in every iteration.
3062 For effective cross jumping, we really want to run a fast DCE to
3063 clean up any dead conditions, or they get in the way of performing
3064 useful tail merges.
3066 Other transformations in cleanup_cfg are not so sensitive to dead
3067 code, so delete_trivially_dead_insns or even doing nothing at all
3068 is good enough. */
3069 if ((mode & CLEANUP_EXPENSIVE) && !reload_completed
3070 && !delete_trivially_dead_insns (get_insns (), max_reg_num ()))
3071 break;
3072 if ((mode & CLEANUP_CROSSJUMP) && crossjumps_occured)
3073 run_fast_dce ();
3075 else
3076 break;
3079 if (mode & CLEANUP_CROSSJUMP)
3080 remove_fake_exit_edges ();
3082 /* Don't call delete_dead_jumptables in cfglayout mode, because
3083 that function assumes that jump tables are in the insns stream.
3084 But we also don't _have_ to delete dead jumptables in cfglayout
3085 mode because we shouldn't even be looking at things that are
3086 not in a basic block. Dead jumptables are cleaned up when
3087 going out of cfglayout mode. */
3088 if (!(mode & CLEANUP_CFGLAYOUT))
3089 delete_dead_jumptables ();
3091 /* ??? We probably do this way too often. */
3092 if (current_loops
3093 && (changed
3094 || (mode & CLEANUP_CFG_CHANGED)))
3096 timevar_push (TV_REPAIR_LOOPS);
3097 /* The above doesn't preserve dominance info if available. */
3098 gcc_assert (!dom_info_available_p (CDI_DOMINATORS));
3099 calculate_dominance_info (CDI_DOMINATORS);
3100 fix_loop_structure (NULL);
3101 free_dominance_info (CDI_DOMINATORS);
3102 timevar_pop (TV_REPAIR_LOOPS);
3105 timevar_pop (TV_CLEANUP_CFG);
3107 return changed;
3110 namespace {
3112 const pass_data pass_data_jump =
3114 RTL_PASS, /* type */
3115 "jump", /* name */
3116 OPTGROUP_NONE, /* optinfo_flags */
3117 TV_JUMP, /* tv_id */
3118 0, /* properties_required */
3119 0, /* properties_provided */
3120 0, /* properties_destroyed */
3121 0, /* todo_flags_start */
3122 0, /* todo_flags_finish */
3125 class pass_jump : public rtl_opt_pass
3127 public:
3128 pass_jump (gcc::context *ctxt)
3129 : rtl_opt_pass (pass_data_jump, ctxt)
3132 /* opt_pass methods: */
3133 virtual unsigned int execute (function *);
3135 }; // class pass_jump
3137 unsigned int
3138 pass_jump::execute (function *)
3140 delete_trivially_dead_insns (get_insns (), max_reg_num ());
3141 if (dump_file)
3142 dump_flow_info (dump_file, dump_flags);
3143 cleanup_cfg ((optimize ? CLEANUP_EXPENSIVE : 0)
3144 | (flag_thread_jumps ? CLEANUP_THREADING : 0));
3145 return 0;
3148 } // anon namespace
3150 rtl_opt_pass *
3151 make_pass_jump (gcc::context *ctxt)
3153 return new pass_jump (ctxt);
3156 namespace {
3158 const pass_data pass_data_jump2 =
3160 RTL_PASS, /* type */
3161 "jump2", /* name */
3162 OPTGROUP_NONE, /* optinfo_flags */
3163 TV_JUMP, /* tv_id */
3164 0, /* properties_required */
3165 0, /* properties_provided */
3166 0, /* properties_destroyed */
3167 0, /* todo_flags_start */
3168 0, /* todo_flags_finish */
3171 class pass_jump2 : public rtl_opt_pass
3173 public:
3174 pass_jump2 (gcc::context *ctxt)
3175 : rtl_opt_pass (pass_data_jump2, ctxt)
3178 /* opt_pass methods: */
3179 virtual unsigned int execute (function *)
3181 cleanup_cfg (flag_crossjumping ? CLEANUP_CROSSJUMP : 0);
3182 return 0;
3185 }; // class pass_jump2
3187 } // anon namespace
3189 rtl_opt_pass *
3190 make_pass_jump2 (gcc::context *ctxt)
3192 return new pass_jump2 (ctxt);