Convert PATTERN from a macro to a pair of inline functions
[official-gcc.git] / gcc / cfgcleanup.c
blob2264b4bfe54acdd90688381691a2063e88efd6a4
1 /* Control flow optimization code for GNU compiler.
2 Copyright (C) 1987-2014 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 "tree.h"
38 #include "hard-reg-set.h"
39 #include "regs.h"
40 #include "insn-config.h"
41 #include "flags.h"
42 #include "recog.h"
43 #include "diagnostic-core.h"
44 #include "cselib.h"
45 #include "params.h"
46 #include "tm_p.h"
47 #include "target.h"
48 #include "function.h" /* For inline functions in emit-rtl.h they need crtl. */
49 #include "emit-rtl.h"
50 #include "tree-pass.h"
51 #include "cfgloop.h"
52 #include "expr.h"
53 #include "df.h"
54 #include "dce.h"
55 #include "dbgcnt.h"
56 #include "emit-rtl.h"
58 #define FORWARDER_BLOCK_P(BB) ((BB)->flags & BB_FORWARDER_BLOCK)
60 /* Set to true when we are running first pass of try_optimize_cfg loop. */
61 static bool first_pass;
63 /* Set to true if crossjumps occurred in the latest run of try_optimize_cfg. */
64 static bool crossjumps_occured;
66 /* Set to true if we couldn't run an optimization due to stale liveness
67 information; we should run df_analyze to enable more opportunities. */
68 static bool block_was_dirty;
70 static bool try_crossjump_to_edge (int, edge, edge, enum replace_direction);
71 static bool try_crossjump_bb (int, basic_block);
72 static bool outgoing_edges_match (int, basic_block, basic_block);
73 static enum replace_direction old_insns_match_p (int, rtx_insn *, rtx_insn *);
75 static void merge_blocks_move_predecessor_nojumps (basic_block, basic_block);
76 static void merge_blocks_move_successor_nojumps (basic_block, basic_block);
77 static bool try_optimize_cfg (int);
78 static bool try_simplify_condjump (basic_block);
79 static bool try_forward_edges (int, basic_block);
80 static edge thread_jump (edge, basic_block);
81 static bool mark_effect (rtx, bitmap);
82 static void notice_new_block (basic_block);
83 static void update_forwarder_flag (basic_block);
84 static int mentions_nonequal_regs (rtx *, void *);
85 static void merge_memattrs (rtx, rtx);
87 /* Set flags for newly created block. */
89 static void
90 notice_new_block (basic_block bb)
92 if (!bb)
93 return;
95 if (forwarder_block_p (bb))
96 bb->flags |= BB_FORWARDER_BLOCK;
99 /* Recompute forwarder flag after block has been modified. */
101 static void
102 update_forwarder_flag (basic_block bb)
104 if (forwarder_block_p (bb))
105 bb->flags |= BB_FORWARDER_BLOCK;
106 else
107 bb->flags &= ~BB_FORWARDER_BLOCK;
110 /* Simplify a conditional jump around an unconditional jump.
111 Return true if something changed. */
113 static bool
114 try_simplify_condjump (basic_block cbranch_block)
116 basic_block jump_block, jump_dest_block, cbranch_dest_block;
117 edge cbranch_jump_edge, cbranch_fallthru_edge;
118 rtx_insn *cbranch_insn;
120 /* Verify that there are exactly two successors. */
121 if (EDGE_COUNT (cbranch_block->succs) != 2)
122 return false;
124 /* Verify that we've got a normal conditional branch at the end
125 of the block. */
126 cbranch_insn = BB_END (cbranch_block);
127 if (!any_condjump_p (cbranch_insn))
128 return false;
130 cbranch_fallthru_edge = FALLTHRU_EDGE (cbranch_block);
131 cbranch_jump_edge = BRANCH_EDGE (cbranch_block);
133 /* The next block must not have multiple predecessors, must not
134 be the last block in the function, and must contain just the
135 unconditional jump. */
136 jump_block = cbranch_fallthru_edge->dest;
137 if (!single_pred_p (jump_block)
138 || jump_block->next_bb == EXIT_BLOCK_PTR_FOR_FN (cfun)
139 || !FORWARDER_BLOCK_P (jump_block))
140 return false;
141 jump_dest_block = single_succ (jump_block);
143 /* If we are partitioning hot/cold basic blocks, we don't want to
144 mess up unconditional or indirect jumps that cross between hot
145 and cold sections.
147 Basic block partitioning may result in some jumps that appear to
148 be optimizable (or blocks that appear to be mergeable), but which really
149 must be left untouched (they are required to make it safely across
150 partition boundaries). See the comments at the top of
151 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
153 if (BB_PARTITION (jump_block) != BB_PARTITION (jump_dest_block)
154 || (cbranch_jump_edge->flags & EDGE_CROSSING))
155 return false;
157 /* The conditional branch must target the block after the
158 unconditional branch. */
159 cbranch_dest_block = cbranch_jump_edge->dest;
161 if (cbranch_dest_block == EXIT_BLOCK_PTR_FOR_FN (cfun)
162 || !can_fallthru (jump_block, cbranch_dest_block))
163 return false;
165 /* Invert the conditional branch. */
166 if (!invert_jump (cbranch_insn, block_label (jump_dest_block), 0))
167 return false;
169 if (dump_file)
170 fprintf (dump_file, "Simplifying condjump %i around jump %i\n",
171 INSN_UID (cbranch_insn), INSN_UID (BB_END (jump_block)));
173 /* Success. Update the CFG to match. Note that after this point
174 the edge variable names appear backwards; the redirection is done
175 this way to preserve edge profile data. */
176 cbranch_jump_edge = redirect_edge_succ_nodup (cbranch_jump_edge,
177 cbranch_dest_block);
178 cbranch_fallthru_edge = redirect_edge_succ_nodup (cbranch_fallthru_edge,
179 jump_dest_block);
180 cbranch_jump_edge->flags |= EDGE_FALLTHRU;
181 cbranch_fallthru_edge->flags &= ~EDGE_FALLTHRU;
182 update_br_prob_note (cbranch_block);
184 /* Delete the block with the unconditional jump, and clean up the mess. */
185 delete_basic_block (jump_block);
186 tidy_fallthru_edge (cbranch_jump_edge);
187 update_forwarder_flag (cbranch_block);
189 return true;
192 /* Attempt to prove that operation is NOOP using CSElib or mark the effect
193 on register. Used by jump threading. */
195 static bool
196 mark_effect (rtx exp, regset nonequal)
198 int regno;
199 rtx dest;
200 switch (GET_CODE (exp))
202 /* In case we do clobber the register, mark it as equal, as we know the
203 value is dead so it don't have to match. */
204 case CLOBBER:
205 if (REG_P (XEXP (exp, 0)))
207 dest = XEXP (exp, 0);
208 regno = REGNO (dest);
209 if (HARD_REGISTER_NUM_P (regno))
210 bitmap_clear_range (nonequal, regno,
211 hard_regno_nregs[regno][GET_MODE (dest)]);
212 else
213 bitmap_clear_bit (nonequal, regno);
215 return false;
217 case SET:
218 if (rtx_equal_for_cselib_p (SET_DEST (exp), SET_SRC (exp)))
219 return false;
220 dest = SET_DEST (exp);
221 if (dest == pc_rtx)
222 return false;
223 if (!REG_P (dest))
224 return true;
225 regno = REGNO (dest);
226 if (HARD_REGISTER_NUM_P (regno))
227 bitmap_set_range (nonequal, regno,
228 hard_regno_nregs[regno][GET_MODE (dest)]);
229 else
230 bitmap_set_bit (nonequal, regno);
231 return false;
233 default:
234 return false;
238 /* Return nonzero if X is a register set in regset DATA.
239 Called via for_each_rtx. */
240 static int
241 mentions_nonequal_regs (rtx *x, void *data)
243 regset nonequal = (regset) data;
244 if (REG_P (*x))
246 int regno;
248 regno = REGNO (*x);
249 if (REGNO_REG_SET_P (nonequal, regno))
250 return 1;
251 if (regno < FIRST_PSEUDO_REGISTER)
253 int n = hard_regno_nregs[regno][GET_MODE (*x)];
254 while (--n > 0)
255 if (REGNO_REG_SET_P (nonequal, regno + n))
256 return 1;
259 return 0;
261 /* Attempt to prove that the basic block B will have no side effects and
262 always continues in the same edge if reached via E. Return the edge
263 if exist, NULL otherwise. */
265 static edge
266 thread_jump (edge e, basic_block b)
268 rtx set1, set2, cond1, cond2;
269 rtx_insn *insn;
270 enum rtx_code code1, code2, reversed_code2;
271 bool reverse1 = false;
272 unsigned i;
273 regset nonequal;
274 bool failed = false;
275 reg_set_iterator rsi;
277 if (b->flags & BB_NONTHREADABLE_BLOCK)
278 return NULL;
280 /* At the moment, we do handle only conditional jumps, but later we may
281 want to extend this code to tablejumps and others. */
282 if (EDGE_COUNT (e->src->succs) != 2)
283 return NULL;
284 if (EDGE_COUNT (b->succs) != 2)
286 b->flags |= BB_NONTHREADABLE_BLOCK;
287 return NULL;
290 /* Second branch must end with onlyjump, as we will eliminate the jump. */
291 if (!any_condjump_p (BB_END (e->src)))
292 return NULL;
294 if (!any_condjump_p (BB_END (b)) || !onlyjump_p (BB_END (b)))
296 b->flags |= BB_NONTHREADABLE_BLOCK;
297 return NULL;
300 set1 = pc_set (BB_END (e->src));
301 set2 = pc_set (BB_END (b));
302 if (((e->flags & EDGE_FALLTHRU) != 0)
303 != (XEXP (SET_SRC (set1), 1) == pc_rtx))
304 reverse1 = true;
306 cond1 = XEXP (SET_SRC (set1), 0);
307 cond2 = XEXP (SET_SRC (set2), 0);
308 if (reverse1)
309 code1 = reversed_comparison_code (cond1, BB_END (e->src));
310 else
311 code1 = GET_CODE (cond1);
313 code2 = GET_CODE (cond2);
314 reversed_code2 = reversed_comparison_code (cond2, BB_END (b));
316 if (!comparison_dominates_p (code1, code2)
317 && !comparison_dominates_p (code1, reversed_code2))
318 return NULL;
320 /* Ensure that the comparison operators are equivalent.
321 ??? This is far too pessimistic. We should allow swapped operands,
322 different CCmodes, or for example comparisons for interval, that
323 dominate even when operands are not equivalent. */
324 if (!rtx_equal_p (XEXP (cond1, 0), XEXP (cond2, 0))
325 || !rtx_equal_p (XEXP (cond1, 1), XEXP (cond2, 1)))
326 return NULL;
328 /* Short circuit cases where block B contains some side effects, as we can't
329 safely bypass it. */
330 for (insn = NEXT_INSN (BB_HEAD (b)); insn != NEXT_INSN (BB_END (b));
331 insn = NEXT_INSN (insn))
332 if (INSN_P (insn) && side_effects_p (PATTERN (insn)))
334 b->flags |= BB_NONTHREADABLE_BLOCK;
335 return NULL;
338 cselib_init (0);
340 /* First process all values computed in the source basic block. */
341 for (insn = NEXT_INSN (BB_HEAD (e->src));
342 insn != NEXT_INSN (BB_END (e->src));
343 insn = NEXT_INSN (insn))
344 if (INSN_P (insn))
345 cselib_process_insn (insn);
347 nonequal = BITMAP_ALLOC (NULL);
348 CLEAR_REG_SET (nonequal);
350 /* Now assume that we've continued by the edge E to B and continue
351 processing as if it were same basic block.
352 Our goal is to prove that whole block is an NOOP. */
354 for (insn = NEXT_INSN (BB_HEAD (b));
355 insn != NEXT_INSN (BB_END (b)) && !failed;
356 insn = NEXT_INSN (insn))
358 if (INSN_P (insn))
360 rtx pat = PATTERN (insn);
362 if (GET_CODE (pat) == PARALLEL)
364 for (i = 0; i < (unsigned)XVECLEN (pat, 0); i++)
365 failed |= mark_effect (XVECEXP (pat, 0, i), nonequal);
367 else
368 failed |= mark_effect (pat, nonequal);
371 cselib_process_insn (insn);
374 /* Later we should clear nonequal of dead registers. So far we don't
375 have life information in cfg_cleanup. */
376 if (failed)
378 b->flags |= BB_NONTHREADABLE_BLOCK;
379 goto failed_exit;
382 /* cond2 must not mention any register that is not equal to the
383 former block. */
384 if (for_each_rtx (&cond2, mentions_nonequal_regs, nonequal))
385 goto failed_exit;
387 EXECUTE_IF_SET_IN_REG_SET (nonequal, 0, i, rsi)
388 goto failed_exit;
390 BITMAP_FREE (nonequal);
391 cselib_finish ();
392 if ((comparison_dominates_p (code1, code2) != 0)
393 != (XEXP (SET_SRC (set2), 1) == pc_rtx))
394 return BRANCH_EDGE (b);
395 else
396 return FALLTHRU_EDGE (b);
398 failed_exit:
399 BITMAP_FREE (nonequal);
400 cselib_finish ();
401 return NULL;
404 /* Attempt to forward edges leaving basic block B.
405 Return true if successful. */
407 static bool
408 try_forward_edges (int mode, basic_block b)
410 bool changed = false;
411 edge_iterator ei;
412 edge e, *threaded_edges = NULL;
414 /* If we are partitioning hot/cold basic blocks, we don't want to
415 mess up unconditional or indirect jumps that cross between hot
416 and cold sections.
418 Basic block partitioning may result in some jumps that appear to
419 be optimizable (or blocks that appear to be mergeable), but which really
420 must be left untouched (they are required to make it safely across
421 partition boundaries). See the comments at the top of
422 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
424 if (JUMP_P (BB_END (b)) && CROSSING_JUMP_P (BB_END (b)))
425 return false;
427 for (ei = ei_start (b->succs); (e = ei_safe_edge (ei)); )
429 basic_block target, first;
430 location_t goto_locus;
431 int counter;
432 bool threaded = false;
433 int nthreaded_edges = 0;
434 bool may_thread = first_pass || (b->flags & BB_MODIFIED) != 0;
436 /* Skip complex edges because we don't know how to update them.
438 Still handle fallthru edges, as we can succeed to forward fallthru
439 edge to the same place as the branch edge of conditional branch
440 and turn conditional branch to an unconditional branch. */
441 if (e->flags & EDGE_COMPLEX)
443 ei_next (&ei);
444 continue;
447 target = first = e->dest;
448 counter = NUM_FIXED_BLOCKS;
449 goto_locus = e->goto_locus;
451 /* If we are partitioning hot/cold basic_blocks, we don't want to mess
452 up jumps that cross between hot/cold sections.
454 Basic block partitioning may result in some jumps that appear
455 to be optimizable (or blocks that appear to be mergeable), but which
456 really must be left untouched (they are required to make it safely
457 across partition boundaries). See the comments at the top of
458 bb-reorder.c:partition_hot_cold_basic_blocks for complete
459 details. */
461 if (first != EXIT_BLOCK_PTR_FOR_FN (cfun)
462 && JUMP_P (BB_END (first))
463 && CROSSING_JUMP_P (BB_END (first)))
464 return changed;
466 while (counter < n_basic_blocks_for_fn (cfun))
468 basic_block new_target = NULL;
469 bool new_target_threaded = false;
470 may_thread |= (target->flags & BB_MODIFIED) != 0;
472 if (FORWARDER_BLOCK_P (target)
473 && !(single_succ_edge (target)->flags & EDGE_CROSSING)
474 && single_succ (target) != EXIT_BLOCK_PTR_FOR_FN (cfun))
476 /* Bypass trivial infinite loops. */
477 new_target = single_succ (target);
478 if (target == new_target)
479 counter = n_basic_blocks_for_fn (cfun);
480 else if (!optimize)
482 /* When not optimizing, ensure that edges or forwarder
483 blocks with different locus are not optimized out. */
484 location_t new_locus = single_succ_edge (target)->goto_locus;
485 location_t locus = goto_locus;
487 if (LOCATION_LOCUS (new_locus) != UNKNOWN_LOCATION
488 && LOCATION_LOCUS (locus) != UNKNOWN_LOCATION
489 && new_locus != locus)
490 new_target = NULL;
491 else
493 if (LOCATION_LOCUS (new_locus) != UNKNOWN_LOCATION)
494 locus = new_locus;
496 rtx_insn *last = BB_END (target);
497 if (DEBUG_INSN_P (last))
498 last = prev_nondebug_insn (last);
499 if (last && INSN_P (last))
500 new_locus = INSN_LOCATION (last);
501 else
502 new_locus = UNKNOWN_LOCATION;
504 if (LOCATION_LOCUS (new_locus) != UNKNOWN_LOCATION
505 && LOCATION_LOCUS (locus) != UNKNOWN_LOCATION
506 && new_locus != locus)
507 new_target = NULL;
508 else
510 if (LOCATION_LOCUS (new_locus) != UNKNOWN_LOCATION)
511 locus = new_locus;
513 goto_locus = locus;
519 /* Allow to thread only over one edge at time to simplify updating
520 of probabilities. */
521 else if ((mode & CLEANUP_THREADING) && may_thread)
523 edge t = thread_jump (e, target);
524 if (t)
526 if (!threaded_edges)
527 threaded_edges = XNEWVEC (edge,
528 n_basic_blocks_for_fn (cfun));
529 else
531 int i;
533 /* Detect an infinite loop across blocks not
534 including the start block. */
535 for (i = 0; i < nthreaded_edges; ++i)
536 if (threaded_edges[i] == t)
537 break;
538 if (i < nthreaded_edges)
540 counter = n_basic_blocks_for_fn (cfun);
541 break;
545 /* Detect an infinite loop across the start block. */
546 if (t->dest == b)
547 break;
549 gcc_assert (nthreaded_edges
550 < (n_basic_blocks_for_fn (cfun)
551 - NUM_FIXED_BLOCKS));
552 threaded_edges[nthreaded_edges++] = t;
554 new_target = t->dest;
555 new_target_threaded = true;
559 if (!new_target)
560 break;
562 counter++;
563 target = new_target;
564 threaded |= new_target_threaded;
567 if (counter >= n_basic_blocks_for_fn (cfun))
569 if (dump_file)
570 fprintf (dump_file, "Infinite loop in BB %i.\n",
571 target->index);
573 else if (target == first)
574 ; /* We didn't do anything. */
575 else
577 /* Save the values now, as the edge may get removed. */
578 gcov_type edge_count = e->count;
579 int edge_probability = e->probability;
580 int edge_frequency;
581 int n = 0;
583 e->goto_locus = goto_locus;
585 /* Don't force if target is exit block. */
586 if (threaded && target != EXIT_BLOCK_PTR_FOR_FN (cfun))
588 notice_new_block (redirect_edge_and_branch_force (e, target));
589 if (dump_file)
590 fprintf (dump_file, "Conditionals threaded.\n");
592 else if (!redirect_edge_and_branch (e, target))
594 if (dump_file)
595 fprintf (dump_file,
596 "Forwarding edge %i->%i to %i failed.\n",
597 b->index, e->dest->index, target->index);
598 ei_next (&ei);
599 continue;
602 /* We successfully forwarded the edge. Now update profile
603 data: for each edge we traversed in the chain, remove
604 the original edge's execution count. */
605 edge_frequency = apply_probability (b->frequency, edge_probability);
609 edge t;
611 if (!single_succ_p (first))
613 gcc_assert (n < nthreaded_edges);
614 t = threaded_edges [n++];
615 gcc_assert (t->src == first);
616 update_bb_profile_for_threading (first, edge_frequency,
617 edge_count, t);
618 update_br_prob_note (first);
620 else
622 first->count -= edge_count;
623 if (first->count < 0)
624 first->count = 0;
625 first->frequency -= edge_frequency;
626 if (first->frequency < 0)
627 first->frequency = 0;
628 /* It is possible that as the result of
629 threading we've removed edge as it is
630 threaded to the fallthru edge. Avoid
631 getting out of sync. */
632 if (n < nthreaded_edges
633 && first == threaded_edges [n]->src)
634 n++;
635 t = single_succ_edge (first);
638 t->count -= edge_count;
639 if (t->count < 0)
640 t->count = 0;
641 first = t->dest;
643 while (first != target);
645 changed = true;
646 continue;
648 ei_next (&ei);
651 free (threaded_edges);
652 return changed;
656 /* Blocks A and B are to be merged into a single block. A has no incoming
657 fallthru edge, so it can be moved before B without adding or modifying
658 any jumps (aside from the jump from A to B). */
660 static void
661 merge_blocks_move_predecessor_nojumps (basic_block a, basic_block b)
663 rtx_insn *barrier;
665 /* If we are partitioning hot/cold basic blocks, we don't want to
666 mess up unconditional or indirect jumps that cross between hot
667 and cold sections.
669 Basic block partitioning may result in some jumps that appear to
670 be optimizable (or blocks that appear to be mergeable), but which really
671 must be left untouched (they are required to make it safely across
672 partition boundaries). See the comments at the top of
673 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
675 if (BB_PARTITION (a) != BB_PARTITION (b))
676 return;
678 barrier = next_nonnote_insn (BB_END (a));
679 gcc_assert (BARRIER_P (barrier));
680 delete_insn (barrier);
682 /* Scramble the insn chain. */
683 if (BB_END (a) != PREV_INSN (BB_HEAD (b)))
684 reorder_insns_nobb (BB_HEAD (a), BB_END (a), PREV_INSN (BB_HEAD (b)));
685 df_set_bb_dirty (a);
687 if (dump_file)
688 fprintf (dump_file, "Moved block %d before %d and merged.\n",
689 a->index, b->index);
691 /* Swap the records for the two blocks around. */
693 unlink_block (a);
694 link_block (a, b->prev_bb);
696 /* Now blocks A and B are contiguous. Merge them. */
697 merge_blocks (a, b);
700 /* Blocks A and B are to be merged into a single block. B has no outgoing
701 fallthru edge, so it can be moved after A without adding or modifying
702 any jumps (aside from the jump from A to B). */
704 static void
705 merge_blocks_move_successor_nojumps (basic_block a, basic_block b)
707 rtx_insn *barrier, *real_b_end;
708 rtx label;
709 rtx_jump_table_data *table;
711 /* If we are partitioning hot/cold basic blocks, we don't want to
712 mess up unconditional or indirect jumps that cross between hot
713 and cold sections.
715 Basic block partitioning may result in some jumps that appear to
716 be optimizable (or blocks that appear to be mergeable), but which really
717 must be left untouched (they are required to make it safely across
718 partition boundaries). See the comments at the top of
719 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
721 if (BB_PARTITION (a) != BB_PARTITION (b))
722 return;
724 real_b_end = BB_END (b);
726 /* If there is a jump table following block B temporarily add the jump table
727 to block B so that it will also be moved to the correct location. */
728 if (tablejump_p (BB_END (b), &label, &table)
729 && prev_active_insn (label) == BB_END (b))
731 BB_END (b) = table;
734 /* There had better have been a barrier there. Delete it. */
735 barrier = NEXT_INSN (BB_END (b));
736 if (barrier && BARRIER_P (barrier))
737 delete_insn (barrier);
740 /* Scramble the insn chain. */
741 reorder_insns_nobb (BB_HEAD (b), BB_END (b), BB_END (a));
743 /* Restore the real end of b. */
744 BB_END (b) = real_b_end;
746 if (dump_file)
747 fprintf (dump_file, "Moved block %d after %d and merged.\n",
748 b->index, a->index);
750 /* Now blocks A and B are contiguous. Merge them. */
751 merge_blocks (a, b);
754 /* Attempt to merge basic blocks that are potentially non-adjacent.
755 Return NULL iff the attempt failed, otherwise return basic block
756 where cleanup_cfg should continue. Because the merging commonly
757 moves basic block away or introduces another optimization
758 possibility, return basic block just before B so cleanup_cfg don't
759 need to iterate.
761 It may be good idea to return basic block before C in the case
762 C has been moved after B and originally appeared earlier in the
763 insn sequence, but we have no information available about the
764 relative ordering of these two. Hopefully it is not too common. */
766 static basic_block
767 merge_blocks_move (edge e, basic_block b, basic_block c, int mode)
769 basic_block next;
771 /* If we are partitioning hot/cold basic blocks, we don't want to
772 mess up unconditional or indirect jumps that cross between hot
773 and cold sections.
775 Basic block partitioning may result in some jumps that appear to
776 be optimizable (or blocks that appear to be mergeable), but which really
777 must be left untouched (they are required to make it safely across
778 partition boundaries). See the comments at the top of
779 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
781 if (BB_PARTITION (b) != BB_PARTITION (c))
782 return NULL;
784 /* If B has a fallthru edge to C, no need to move anything. */
785 if (e->flags & EDGE_FALLTHRU)
787 int b_index = b->index, c_index = c->index;
789 /* Protect the loop latches. */
790 if (current_loops && c->loop_father->latch == c)
791 return NULL;
793 merge_blocks (b, c);
794 update_forwarder_flag (b);
796 if (dump_file)
797 fprintf (dump_file, "Merged %d and %d without moving.\n",
798 b_index, c_index);
800 return b->prev_bb == ENTRY_BLOCK_PTR_FOR_FN (cfun) ? b : b->prev_bb;
803 /* Otherwise we will need to move code around. Do that only if expensive
804 transformations are allowed. */
805 else if (mode & CLEANUP_EXPENSIVE)
807 edge tmp_edge, b_fallthru_edge;
808 bool c_has_outgoing_fallthru;
809 bool b_has_incoming_fallthru;
811 /* Avoid overactive code motion, as the forwarder blocks should be
812 eliminated by edge redirection instead. One exception might have
813 been if B is a forwarder block and C has no fallthru edge, but
814 that should be cleaned up by bb-reorder instead. */
815 if (FORWARDER_BLOCK_P (b) || FORWARDER_BLOCK_P (c))
816 return NULL;
818 /* We must make sure to not munge nesting of lexical blocks,
819 and loop notes. This is done by squeezing out all the notes
820 and leaving them there to lie. Not ideal, but functional. */
822 tmp_edge = find_fallthru_edge (c->succs);
823 c_has_outgoing_fallthru = (tmp_edge != NULL);
825 tmp_edge = find_fallthru_edge (b->preds);
826 b_has_incoming_fallthru = (tmp_edge != NULL);
827 b_fallthru_edge = tmp_edge;
828 next = b->prev_bb;
829 if (next == c)
830 next = next->prev_bb;
832 /* Otherwise, we're going to try to move C after B. If C does
833 not have an outgoing fallthru, then it can be moved
834 immediately after B without introducing or modifying jumps. */
835 if (! c_has_outgoing_fallthru)
837 merge_blocks_move_successor_nojumps (b, c);
838 return next == ENTRY_BLOCK_PTR_FOR_FN (cfun) ? next->next_bb : next;
841 /* If B does not have an incoming fallthru, then it can be moved
842 immediately before C without introducing or modifying jumps.
843 C cannot be the first block, so we do not have to worry about
844 accessing a non-existent block. */
846 if (b_has_incoming_fallthru)
848 basic_block bb;
850 if (b_fallthru_edge->src == ENTRY_BLOCK_PTR_FOR_FN (cfun))
851 return NULL;
852 bb = force_nonfallthru (b_fallthru_edge);
853 if (bb)
854 notice_new_block (bb);
857 merge_blocks_move_predecessor_nojumps (b, c);
858 return next == ENTRY_BLOCK_PTR_FOR_FN (cfun) ? next->next_bb : next;
861 return NULL;
865 /* Removes the memory attributes of MEM expression
866 if they are not equal. */
868 void
869 merge_memattrs (rtx x, rtx y)
871 int i;
872 int j;
873 enum rtx_code code;
874 const char *fmt;
876 if (x == y)
877 return;
878 if (x == 0 || y == 0)
879 return;
881 code = GET_CODE (x);
883 if (code != GET_CODE (y))
884 return;
886 if (GET_MODE (x) != GET_MODE (y))
887 return;
889 if (code == MEM && !mem_attrs_eq_p (MEM_ATTRS (x), MEM_ATTRS (y)))
891 if (! MEM_ATTRS (x))
892 MEM_ATTRS (y) = 0;
893 else if (! MEM_ATTRS (y))
894 MEM_ATTRS (x) = 0;
895 else
897 HOST_WIDE_INT mem_size;
899 if (MEM_ALIAS_SET (x) != MEM_ALIAS_SET (y))
901 set_mem_alias_set (x, 0);
902 set_mem_alias_set (y, 0);
905 if (! mem_expr_equal_p (MEM_EXPR (x), MEM_EXPR (y)))
907 set_mem_expr (x, 0);
908 set_mem_expr (y, 0);
909 clear_mem_offset (x);
910 clear_mem_offset (y);
912 else if (MEM_OFFSET_KNOWN_P (x) != MEM_OFFSET_KNOWN_P (y)
913 || (MEM_OFFSET_KNOWN_P (x)
914 && MEM_OFFSET (x) != MEM_OFFSET (y)))
916 clear_mem_offset (x);
917 clear_mem_offset (y);
920 if (MEM_SIZE_KNOWN_P (x) && MEM_SIZE_KNOWN_P (y))
922 mem_size = MAX (MEM_SIZE (x), MEM_SIZE (y));
923 set_mem_size (x, mem_size);
924 set_mem_size (y, mem_size);
926 else
928 clear_mem_size (x);
929 clear_mem_size (y);
932 set_mem_align (x, MIN (MEM_ALIGN (x), MEM_ALIGN (y)));
933 set_mem_align (y, MEM_ALIGN (x));
936 if (code == MEM)
938 if (MEM_READONLY_P (x) != MEM_READONLY_P (y))
940 MEM_READONLY_P (x) = 0;
941 MEM_READONLY_P (y) = 0;
943 if (MEM_NOTRAP_P (x) != MEM_NOTRAP_P (y))
945 MEM_NOTRAP_P (x) = 0;
946 MEM_NOTRAP_P (y) = 0;
948 if (MEM_VOLATILE_P (x) != MEM_VOLATILE_P (y))
950 MEM_VOLATILE_P (x) = 1;
951 MEM_VOLATILE_P (y) = 1;
955 fmt = GET_RTX_FORMAT (code);
956 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
958 switch (fmt[i])
960 case 'E':
961 /* Two vectors must have the same length. */
962 if (XVECLEN (x, i) != XVECLEN (y, i))
963 return;
965 for (j = 0; j < XVECLEN (x, i); j++)
966 merge_memattrs (XVECEXP (x, i, j), XVECEXP (y, i, j));
968 break;
970 case 'e':
971 merge_memattrs (XEXP (x, i), XEXP (y, i));
974 return;
978 /* Checks if patterns P1 and P2 are equivalent, apart from the possibly
979 different single sets S1 and S2. */
981 static bool
982 equal_different_set_p (rtx p1, rtx s1, rtx p2, rtx s2)
984 int i;
985 rtx e1, e2;
987 if (p1 == s1 && p2 == s2)
988 return true;
990 if (GET_CODE (p1) != PARALLEL || GET_CODE (p2) != PARALLEL)
991 return false;
993 if (XVECLEN (p1, 0) != XVECLEN (p2, 0))
994 return false;
996 for (i = 0; i < XVECLEN (p1, 0); i++)
998 e1 = XVECEXP (p1, 0, i);
999 e2 = XVECEXP (p2, 0, i);
1000 if (e1 == s1 && e2 == s2)
1001 continue;
1002 if (reload_completed
1003 ? rtx_renumbered_equal_p (e1, e2) : rtx_equal_p (e1, e2))
1004 continue;
1006 return false;
1009 return true;
1012 /* Examine register notes on I1 and I2 and return:
1013 - dir_forward if I1 can be replaced by I2, or
1014 - dir_backward if I2 can be replaced by I1, or
1015 - dir_both if both are the case. */
1017 static enum replace_direction
1018 can_replace_by (rtx_insn *i1, rtx_insn *i2)
1020 rtx s1, s2, d1, d2, src1, src2, note1, note2;
1021 bool c1, c2;
1023 /* Check for 2 sets. */
1024 s1 = single_set (i1);
1025 s2 = single_set (i2);
1026 if (s1 == NULL_RTX || s2 == NULL_RTX)
1027 return dir_none;
1029 /* Check that the 2 sets set the same dest. */
1030 d1 = SET_DEST (s1);
1031 d2 = SET_DEST (s2);
1032 if (!(reload_completed
1033 ? rtx_renumbered_equal_p (d1, d2) : rtx_equal_p (d1, d2)))
1034 return dir_none;
1036 /* Find identical req_equiv or reg_equal note, which implies that the 2 sets
1037 set dest to the same value. */
1038 note1 = find_reg_equal_equiv_note (i1);
1039 note2 = find_reg_equal_equiv_note (i2);
1040 if (!note1 || !note2 || !rtx_equal_p (XEXP (note1, 0), XEXP (note2, 0))
1041 || !CONST_INT_P (XEXP (note1, 0)))
1042 return dir_none;
1044 if (!equal_different_set_p (PATTERN (i1), s1, PATTERN (i2), s2))
1045 return dir_none;
1047 /* Although the 2 sets set dest to the same value, we cannot replace
1048 (set (dest) (const_int))
1050 (set (dest) (reg))
1051 because we don't know if the reg is live and has the same value at the
1052 location of replacement. */
1053 src1 = SET_SRC (s1);
1054 src2 = SET_SRC (s2);
1055 c1 = CONST_INT_P (src1);
1056 c2 = CONST_INT_P (src2);
1057 if (c1 && c2)
1058 return dir_both;
1059 else if (c2)
1060 return dir_forward;
1061 else if (c1)
1062 return dir_backward;
1064 return dir_none;
1067 /* Merges directions A and B. */
1069 static enum replace_direction
1070 merge_dir (enum replace_direction a, enum replace_direction b)
1072 /* Implements the following table:
1073 |bo fw bw no
1074 ---+-----------
1075 bo |bo fw bw no
1076 fw |-- fw no no
1077 bw |-- -- bw no
1078 no |-- -- -- no. */
1080 if (a == b)
1081 return a;
1083 if (a == dir_both)
1084 return b;
1085 if (b == dir_both)
1086 return a;
1088 return dir_none;
1091 /* Examine I1 and I2 and return:
1092 - dir_forward if I1 can be replaced by I2, or
1093 - dir_backward if I2 can be replaced by I1, or
1094 - dir_both if both are the case. */
1096 static enum replace_direction
1097 old_insns_match_p (int mode ATTRIBUTE_UNUSED, rtx_insn *i1, rtx_insn *i2)
1099 rtx p1, p2;
1101 /* Verify that I1 and I2 are equivalent. */
1102 if (GET_CODE (i1) != GET_CODE (i2))
1103 return dir_none;
1105 /* __builtin_unreachable() may lead to empty blocks (ending with
1106 NOTE_INSN_BASIC_BLOCK). They may be crossjumped. */
1107 if (NOTE_INSN_BASIC_BLOCK_P (i1) && NOTE_INSN_BASIC_BLOCK_P (i2))
1108 return dir_both;
1110 /* ??? Do not allow cross-jumping between different stack levels. */
1111 p1 = find_reg_note (i1, REG_ARGS_SIZE, NULL);
1112 p2 = find_reg_note (i2, REG_ARGS_SIZE, NULL);
1113 if (p1 && p2)
1115 p1 = XEXP (p1, 0);
1116 p2 = XEXP (p2, 0);
1117 if (!rtx_equal_p (p1, p2))
1118 return dir_none;
1120 /* ??? Worse, this adjustment had better be constant lest we
1121 have differing incoming stack levels. */
1122 if (!frame_pointer_needed
1123 && find_args_size_adjust (i1) == HOST_WIDE_INT_MIN)
1124 return dir_none;
1126 else if (p1 || p2)
1127 return dir_none;
1129 p1 = PATTERN (i1);
1130 p2 = PATTERN (i2);
1132 if (GET_CODE (p1) != GET_CODE (p2))
1133 return dir_none;
1135 /* If this is a CALL_INSN, compare register usage information.
1136 If we don't check this on stack register machines, the two
1137 CALL_INSNs might be merged leaving reg-stack.c with mismatching
1138 numbers of stack registers in the same basic block.
1139 If we don't check this on machines with delay slots, a delay slot may
1140 be filled that clobbers a parameter expected by the subroutine.
1142 ??? We take the simple route for now and assume that if they're
1143 equal, they were constructed identically.
1145 Also check for identical exception regions. */
1147 if (CALL_P (i1))
1149 /* Ensure the same EH region. */
1150 rtx n1 = find_reg_note (i1, REG_EH_REGION, 0);
1151 rtx n2 = find_reg_note (i2, REG_EH_REGION, 0);
1153 if (!n1 && n2)
1154 return dir_none;
1156 if (n1 && (!n2 || XEXP (n1, 0) != XEXP (n2, 0)))
1157 return dir_none;
1159 if (!rtx_equal_p (CALL_INSN_FUNCTION_USAGE (i1),
1160 CALL_INSN_FUNCTION_USAGE (i2))
1161 || SIBLING_CALL_P (i1) != SIBLING_CALL_P (i2))
1162 return dir_none;
1164 /* For address sanitizer, never crossjump __asan_report_* builtins,
1165 otherwise errors might be reported on incorrect lines. */
1166 if (flag_sanitize & SANITIZE_ADDRESS)
1168 rtx call = get_call_rtx_from (i1);
1169 if (call && GET_CODE (XEXP (XEXP (call, 0), 0)) == SYMBOL_REF)
1171 rtx symbol = XEXP (XEXP (call, 0), 0);
1172 if (SYMBOL_REF_DECL (symbol)
1173 && TREE_CODE (SYMBOL_REF_DECL (symbol)) == FUNCTION_DECL)
1175 if ((DECL_BUILT_IN_CLASS (SYMBOL_REF_DECL (symbol))
1176 == BUILT_IN_NORMAL)
1177 && DECL_FUNCTION_CODE (SYMBOL_REF_DECL (symbol))
1178 >= BUILT_IN_ASAN_REPORT_LOAD1
1179 && DECL_FUNCTION_CODE (SYMBOL_REF_DECL (symbol))
1180 <= BUILT_IN_ASAN_STOREN)
1181 return dir_none;
1187 #ifdef STACK_REGS
1188 /* If cross_jump_death_matters is not 0, the insn's mode
1189 indicates whether or not the insn contains any stack-like
1190 regs. */
1192 if ((mode & CLEANUP_POST_REGSTACK) && stack_regs_mentioned (i1))
1194 /* If register stack conversion has already been done, then
1195 death notes must also be compared before it is certain that
1196 the two instruction streams match. */
1198 rtx note;
1199 HARD_REG_SET i1_regset, i2_regset;
1201 CLEAR_HARD_REG_SET (i1_regset);
1202 CLEAR_HARD_REG_SET (i2_regset);
1204 for (note = REG_NOTES (i1); note; note = XEXP (note, 1))
1205 if (REG_NOTE_KIND (note) == REG_DEAD && STACK_REG_P (XEXP (note, 0)))
1206 SET_HARD_REG_BIT (i1_regset, REGNO (XEXP (note, 0)));
1208 for (note = REG_NOTES (i2); note; note = XEXP (note, 1))
1209 if (REG_NOTE_KIND (note) == REG_DEAD && STACK_REG_P (XEXP (note, 0)))
1210 SET_HARD_REG_BIT (i2_regset, REGNO (XEXP (note, 0)));
1212 if (!hard_reg_set_equal_p (i1_regset, i2_regset))
1213 return dir_none;
1215 #endif
1217 if (reload_completed
1218 ? rtx_renumbered_equal_p (p1, p2) : rtx_equal_p (p1, p2))
1219 return dir_both;
1221 return can_replace_by (i1, i2);
1224 /* When comparing insns I1 and I2 in flow_find_cross_jump or
1225 flow_find_head_matching_sequence, ensure the notes match. */
1227 static void
1228 merge_notes (rtx_insn *i1, rtx_insn *i2)
1230 /* If the merged insns have different REG_EQUAL notes, then
1231 remove them. */
1232 rtx equiv1 = find_reg_equal_equiv_note (i1);
1233 rtx equiv2 = find_reg_equal_equiv_note (i2);
1235 if (equiv1 && !equiv2)
1236 remove_note (i1, equiv1);
1237 else if (!equiv1 && equiv2)
1238 remove_note (i2, equiv2);
1239 else if (equiv1 && equiv2
1240 && !rtx_equal_p (XEXP (equiv1, 0), XEXP (equiv2, 0)))
1242 remove_note (i1, equiv1);
1243 remove_note (i2, equiv2);
1247 /* Walks from I1 in BB1 backward till the next non-debug insn, and returns the
1248 resulting insn in I1, and the corresponding bb in BB1. At the head of a
1249 bb, if there is a predecessor bb that reaches this bb via fallthru, and
1250 FOLLOW_FALLTHRU, walks further in the predecessor bb and registers this in
1251 DID_FALLTHRU. Otherwise, stops at the head of the bb. */
1253 static void
1254 walk_to_nondebug_insn (rtx_insn **i1, basic_block *bb1, bool follow_fallthru,
1255 bool *did_fallthru)
1257 edge fallthru;
1259 *did_fallthru = false;
1261 /* Ignore notes. */
1262 while (!NONDEBUG_INSN_P (*i1))
1264 if (*i1 != BB_HEAD (*bb1))
1266 *i1 = PREV_INSN (*i1);
1267 continue;
1270 if (!follow_fallthru)
1271 return;
1273 fallthru = find_fallthru_edge ((*bb1)->preds);
1274 if (!fallthru || fallthru->src == ENTRY_BLOCK_PTR_FOR_FN (cfun)
1275 || !single_succ_p (fallthru->src))
1276 return;
1278 *bb1 = fallthru->src;
1279 *i1 = BB_END (*bb1);
1280 *did_fallthru = true;
1284 /* Look through the insns at the end of BB1 and BB2 and find the longest
1285 sequence that are either equivalent, or allow forward or backward
1286 replacement. Store the first insns for that sequence in *F1 and *F2 and
1287 return the sequence length.
1289 DIR_P indicates the allowed replacement direction on function entry, and
1290 the actual replacement direction on function exit. If NULL, only equivalent
1291 sequences are allowed.
1293 To simplify callers of this function, if the blocks match exactly,
1294 store the head of the blocks in *F1 and *F2. */
1297 flow_find_cross_jump (basic_block bb1, basic_block bb2, rtx_insn **f1,
1298 rtx_insn **f2, enum replace_direction *dir_p)
1300 rtx_insn *i1, *i2, *last1, *last2, *afterlast1, *afterlast2;
1301 int ninsns = 0;
1302 enum replace_direction dir, last_dir, afterlast_dir;
1303 bool follow_fallthru, did_fallthru;
1305 if (dir_p)
1306 dir = *dir_p;
1307 else
1308 dir = dir_both;
1309 afterlast_dir = dir;
1310 last_dir = afterlast_dir;
1312 /* Skip simple jumps at the end of the blocks. Complex jumps still
1313 need to be compared for equivalence, which we'll do below. */
1315 i1 = BB_END (bb1);
1316 last1 = afterlast1 = last2 = afterlast2 = NULL;
1317 if (onlyjump_p (i1)
1318 || (returnjump_p (i1) && !side_effects_p (PATTERN (i1))))
1320 last1 = i1;
1321 i1 = PREV_INSN (i1);
1324 i2 = BB_END (bb2);
1325 if (onlyjump_p (i2)
1326 || (returnjump_p (i2) && !side_effects_p (PATTERN (i2))))
1328 last2 = i2;
1329 /* Count everything except for unconditional jump as insn.
1330 Don't count any jumps if dir_p is NULL. */
1331 if (!simplejump_p (i2) && !returnjump_p (i2) && last1 && dir_p)
1332 ninsns++;
1333 i2 = PREV_INSN (i2);
1336 while (true)
1338 /* In the following example, we can replace all jumps to C by jumps to A.
1340 This removes 4 duplicate insns.
1341 [bb A] insn1 [bb C] insn1
1342 insn2 insn2
1343 [bb B] insn3 insn3
1344 insn4 insn4
1345 jump_insn jump_insn
1347 We could also replace all jumps to A by jumps to C, but that leaves B
1348 alive, and removes only 2 duplicate insns. In a subsequent crossjump
1349 step, all jumps to B would be replaced with jumps to the middle of C,
1350 achieving the same result with more effort.
1351 So we allow only the first possibility, which means that we don't allow
1352 fallthru in the block that's being replaced. */
1354 follow_fallthru = dir_p && dir != dir_forward;
1355 walk_to_nondebug_insn (&i1, &bb1, follow_fallthru, &did_fallthru);
1356 if (did_fallthru)
1357 dir = dir_backward;
1359 follow_fallthru = dir_p && dir != dir_backward;
1360 walk_to_nondebug_insn (&i2, &bb2, follow_fallthru, &did_fallthru);
1361 if (did_fallthru)
1362 dir = dir_forward;
1364 if (i1 == BB_HEAD (bb1) || i2 == BB_HEAD (bb2))
1365 break;
1367 dir = merge_dir (dir, old_insns_match_p (0, i1, i2));
1368 if (dir == dir_none || (!dir_p && dir != dir_both))
1369 break;
1371 merge_memattrs (i1, i2);
1373 /* Don't begin a cross-jump with a NOTE insn. */
1374 if (INSN_P (i1))
1376 merge_notes (i1, i2);
1378 afterlast1 = last1, afterlast2 = last2;
1379 last1 = i1, last2 = i2;
1380 afterlast_dir = last_dir;
1381 last_dir = dir;
1382 if (active_insn_p (i1))
1383 ninsns++;
1386 i1 = PREV_INSN (i1);
1387 i2 = PREV_INSN (i2);
1390 #ifdef HAVE_cc0
1391 /* Don't allow the insn after a compare to be shared by
1392 cross-jumping unless the compare is also shared. */
1393 if (ninsns && reg_mentioned_p (cc0_rtx, last1) && ! sets_cc0_p (last1))
1394 last1 = afterlast1, last2 = afterlast2, last_dir = afterlast_dir, ninsns--;
1395 #endif
1397 /* Include preceding notes and labels in the cross-jump. One,
1398 this may bring us to the head of the blocks as requested above.
1399 Two, it keeps line number notes as matched as may be. */
1400 if (ninsns)
1402 bb1 = BLOCK_FOR_INSN (last1);
1403 while (last1 != BB_HEAD (bb1) && !NONDEBUG_INSN_P (PREV_INSN (last1)))
1404 last1 = PREV_INSN (last1);
1406 if (last1 != BB_HEAD (bb1) && LABEL_P (PREV_INSN (last1)))
1407 last1 = PREV_INSN (last1);
1409 bb2 = BLOCK_FOR_INSN (last2);
1410 while (last2 != BB_HEAD (bb2) && !NONDEBUG_INSN_P (PREV_INSN (last2)))
1411 last2 = PREV_INSN (last2);
1413 if (last2 != BB_HEAD (bb2) && LABEL_P (PREV_INSN (last2)))
1414 last2 = PREV_INSN (last2);
1416 *f1 = last1;
1417 *f2 = last2;
1420 if (dir_p)
1421 *dir_p = last_dir;
1422 return ninsns;
1425 /* Like flow_find_cross_jump, except start looking for a matching sequence from
1426 the head of the two blocks. Do not include jumps at the end.
1427 If STOP_AFTER is nonzero, stop after finding that many matching
1428 instructions. If STOP_AFTER is zero, count all INSN_P insns, if it is
1429 non-zero, only count active insns. */
1432 flow_find_head_matching_sequence (basic_block bb1, basic_block bb2, rtx_insn **f1,
1433 rtx_insn **f2, int stop_after)
1435 rtx_insn *i1, *i2, *last1, *last2, *beforelast1, *beforelast2;
1436 int ninsns = 0;
1437 edge e;
1438 edge_iterator ei;
1439 int nehedges1 = 0, nehedges2 = 0;
1441 FOR_EACH_EDGE (e, ei, bb1->succs)
1442 if (e->flags & EDGE_EH)
1443 nehedges1++;
1444 FOR_EACH_EDGE (e, ei, bb2->succs)
1445 if (e->flags & EDGE_EH)
1446 nehedges2++;
1448 i1 = BB_HEAD (bb1);
1449 i2 = BB_HEAD (bb2);
1450 last1 = beforelast1 = last2 = beforelast2 = NULL;
1452 while (true)
1454 /* Ignore notes, except NOTE_INSN_EPILOGUE_BEG. */
1455 while (!NONDEBUG_INSN_P (i1) && i1 != BB_END (bb1))
1457 if (NOTE_P (i1) && NOTE_KIND (i1) == NOTE_INSN_EPILOGUE_BEG)
1458 break;
1459 i1 = NEXT_INSN (i1);
1462 while (!NONDEBUG_INSN_P (i2) && i2 != BB_END (bb2))
1464 if (NOTE_P (i2) && NOTE_KIND (i2) == NOTE_INSN_EPILOGUE_BEG)
1465 break;
1466 i2 = NEXT_INSN (i2);
1469 if ((i1 == BB_END (bb1) && !NONDEBUG_INSN_P (i1))
1470 || (i2 == BB_END (bb2) && !NONDEBUG_INSN_P (i2)))
1471 break;
1473 if (NOTE_P (i1) || NOTE_P (i2)
1474 || JUMP_P (i1) || JUMP_P (i2))
1475 break;
1477 /* A sanity check to make sure we're not merging insns with different
1478 effects on EH. If only one of them ends a basic block, it shouldn't
1479 have an EH edge; if both end a basic block, there should be the same
1480 number of EH edges. */
1481 if ((i1 == BB_END (bb1) && i2 != BB_END (bb2)
1482 && nehedges1 > 0)
1483 || (i2 == BB_END (bb2) && i1 != BB_END (bb1)
1484 && nehedges2 > 0)
1485 || (i1 == BB_END (bb1) && i2 == BB_END (bb2)
1486 && nehedges1 != nehedges2))
1487 break;
1489 if (old_insns_match_p (0, i1, i2) != dir_both)
1490 break;
1492 merge_memattrs (i1, i2);
1494 /* Don't begin a cross-jump with a NOTE insn. */
1495 if (INSN_P (i1))
1497 merge_notes (i1, i2);
1499 beforelast1 = last1, beforelast2 = last2;
1500 last1 = i1, last2 = i2;
1501 if (!stop_after || active_insn_p (i1))
1502 ninsns++;
1505 if (i1 == BB_END (bb1) || i2 == BB_END (bb2)
1506 || (stop_after > 0 && ninsns == stop_after))
1507 break;
1509 i1 = NEXT_INSN (i1);
1510 i2 = NEXT_INSN (i2);
1513 #ifdef HAVE_cc0
1514 /* Don't allow a compare to be shared by cross-jumping unless the insn
1515 after the compare is also shared. */
1516 if (ninsns && reg_mentioned_p (cc0_rtx, last1) && sets_cc0_p (last1))
1517 last1 = beforelast1, last2 = beforelast2, ninsns--;
1518 #endif
1520 if (ninsns)
1522 *f1 = last1;
1523 *f2 = last2;
1526 return ninsns;
1529 /* Return true iff outgoing edges of BB1 and BB2 match, together with
1530 the branch instruction. This means that if we commonize the control
1531 flow before end of the basic block, the semantic remains unchanged.
1533 We may assume that there exists one edge with a common destination. */
1535 static bool
1536 outgoing_edges_match (int mode, basic_block bb1, basic_block bb2)
1538 int nehedges1 = 0, nehedges2 = 0;
1539 edge fallthru1 = 0, fallthru2 = 0;
1540 edge e1, e2;
1541 edge_iterator ei;
1543 /* If we performed shrink-wrapping, edges to the exit block can
1544 only be distinguished for JUMP_INSNs. The two paths may differ in
1545 whether they went through the prologue. Sibcalls are fine, we know
1546 that we either didn't need or inserted an epilogue before them. */
1547 if (crtl->shrink_wrapped
1548 && single_succ_p (bb1)
1549 && single_succ (bb1) == EXIT_BLOCK_PTR_FOR_FN (cfun)
1550 && !JUMP_P (BB_END (bb1))
1551 && !(CALL_P (BB_END (bb1)) && SIBLING_CALL_P (BB_END (bb1))))
1552 return false;
1554 /* If BB1 has only one successor, we may be looking at either an
1555 unconditional jump, or a fake edge to exit. */
1556 if (single_succ_p (bb1)
1557 && (single_succ_edge (bb1)->flags & (EDGE_COMPLEX | EDGE_FAKE)) == 0
1558 && (!JUMP_P (BB_END (bb1)) || simplejump_p (BB_END (bb1))))
1559 return (single_succ_p (bb2)
1560 && (single_succ_edge (bb2)->flags
1561 & (EDGE_COMPLEX | EDGE_FAKE)) == 0
1562 && (!JUMP_P (BB_END (bb2)) || simplejump_p (BB_END (bb2))));
1564 /* Match conditional jumps - this may get tricky when fallthru and branch
1565 edges are crossed. */
1566 if (EDGE_COUNT (bb1->succs) == 2
1567 && any_condjump_p (BB_END (bb1))
1568 && onlyjump_p (BB_END (bb1)))
1570 edge b1, f1, b2, f2;
1571 bool reverse, match;
1572 rtx set1, set2, cond1, cond2;
1573 enum rtx_code code1, code2;
1575 if (EDGE_COUNT (bb2->succs) != 2
1576 || !any_condjump_p (BB_END (bb2))
1577 || !onlyjump_p (BB_END (bb2)))
1578 return false;
1580 b1 = BRANCH_EDGE (bb1);
1581 b2 = BRANCH_EDGE (bb2);
1582 f1 = FALLTHRU_EDGE (bb1);
1583 f2 = FALLTHRU_EDGE (bb2);
1585 /* Get around possible forwarders on fallthru edges. Other cases
1586 should be optimized out already. */
1587 if (FORWARDER_BLOCK_P (f1->dest))
1588 f1 = single_succ_edge (f1->dest);
1590 if (FORWARDER_BLOCK_P (f2->dest))
1591 f2 = single_succ_edge (f2->dest);
1593 /* To simplify use of this function, return false if there are
1594 unneeded forwarder blocks. These will get eliminated later
1595 during cleanup_cfg. */
1596 if (FORWARDER_BLOCK_P (f1->dest)
1597 || FORWARDER_BLOCK_P (f2->dest)
1598 || FORWARDER_BLOCK_P (b1->dest)
1599 || FORWARDER_BLOCK_P (b2->dest))
1600 return false;
1602 if (f1->dest == f2->dest && b1->dest == b2->dest)
1603 reverse = false;
1604 else if (f1->dest == b2->dest && b1->dest == f2->dest)
1605 reverse = true;
1606 else
1607 return false;
1609 set1 = pc_set (BB_END (bb1));
1610 set2 = pc_set (BB_END (bb2));
1611 if ((XEXP (SET_SRC (set1), 1) == pc_rtx)
1612 != (XEXP (SET_SRC (set2), 1) == pc_rtx))
1613 reverse = !reverse;
1615 cond1 = XEXP (SET_SRC (set1), 0);
1616 cond2 = XEXP (SET_SRC (set2), 0);
1617 code1 = GET_CODE (cond1);
1618 if (reverse)
1619 code2 = reversed_comparison_code (cond2, BB_END (bb2));
1620 else
1621 code2 = GET_CODE (cond2);
1623 if (code2 == UNKNOWN)
1624 return false;
1626 /* Verify codes and operands match. */
1627 match = ((code1 == code2
1628 && rtx_renumbered_equal_p (XEXP (cond1, 0), XEXP (cond2, 0))
1629 && rtx_renumbered_equal_p (XEXP (cond1, 1), XEXP (cond2, 1)))
1630 || (code1 == swap_condition (code2)
1631 && rtx_renumbered_equal_p (XEXP (cond1, 1),
1632 XEXP (cond2, 0))
1633 && rtx_renumbered_equal_p (XEXP (cond1, 0),
1634 XEXP (cond2, 1))));
1636 /* If we return true, we will join the blocks. Which means that
1637 we will only have one branch prediction bit to work with. Thus
1638 we require the existing branches to have probabilities that are
1639 roughly similar. */
1640 if (match
1641 && optimize_bb_for_speed_p (bb1)
1642 && optimize_bb_for_speed_p (bb2))
1644 int prob2;
1646 if (b1->dest == b2->dest)
1647 prob2 = b2->probability;
1648 else
1649 /* Do not use f2 probability as f2 may be forwarded. */
1650 prob2 = REG_BR_PROB_BASE - b2->probability;
1652 /* Fail if the difference in probabilities is greater than 50%.
1653 This rules out two well-predicted branches with opposite
1654 outcomes. */
1655 if (abs (b1->probability - prob2) > REG_BR_PROB_BASE / 2)
1657 if (dump_file)
1658 fprintf (dump_file,
1659 "Outcomes of branch in bb %i and %i differ too much (%i %i)\n",
1660 bb1->index, bb2->index, b1->probability, prob2);
1662 return false;
1666 if (dump_file && match)
1667 fprintf (dump_file, "Conditionals in bb %i and %i match.\n",
1668 bb1->index, bb2->index);
1670 return match;
1673 /* Generic case - we are seeing a computed jump, table jump or trapping
1674 instruction. */
1676 /* Check whether there are tablejumps in the end of BB1 and BB2.
1677 Return true if they are identical. */
1679 rtx label1, label2;
1680 rtx_jump_table_data *table1, *table2;
1682 if (tablejump_p (BB_END (bb1), &label1, &table1)
1683 && tablejump_p (BB_END (bb2), &label2, &table2)
1684 && GET_CODE (PATTERN (table1)) == GET_CODE (PATTERN (table2)))
1686 /* The labels should never be the same rtx. If they really are same
1687 the jump tables are same too. So disable crossjumping of blocks BB1
1688 and BB2 because when deleting the common insns in the end of BB1
1689 by delete_basic_block () the jump table would be deleted too. */
1690 /* If LABEL2 is referenced in BB1->END do not do anything
1691 because we would loose information when replacing
1692 LABEL1 by LABEL2 and then LABEL2 by LABEL1 in BB1->END. */
1693 if (label1 != label2 && !rtx_referenced_p (label2, BB_END (bb1)))
1695 /* Set IDENTICAL to true when the tables are identical. */
1696 bool identical = false;
1697 rtx p1, p2;
1699 p1 = PATTERN (table1);
1700 p2 = PATTERN (table2);
1701 if (GET_CODE (p1) == ADDR_VEC && rtx_equal_p (p1, p2))
1703 identical = true;
1705 else if (GET_CODE (p1) == ADDR_DIFF_VEC
1706 && (XVECLEN (p1, 1) == XVECLEN (p2, 1))
1707 && rtx_equal_p (XEXP (p1, 2), XEXP (p2, 2))
1708 && rtx_equal_p (XEXP (p1, 3), XEXP (p2, 3)))
1710 int i;
1712 identical = true;
1713 for (i = XVECLEN (p1, 1) - 1; i >= 0 && identical; i--)
1714 if (!rtx_equal_p (XVECEXP (p1, 1, i), XVECEXP (p2, 1, i)))
1715 identical = false;
1718 if (identical)
1720 replace_label_data rr;
1721 bool match;
1723 /* Temporarily replace references to LABEL1 with LABEL2
1724 in BB1->END so that we could compare the instructions. */
1725 rr.r1 = label1;
1726 rr.r2 = label2;
1727 rr.update_label_nuses = false;
1728 for_each_rtx_in_insn (&BB_END (bb1), replace_label, &rr);
1730 match = (old_insns_match_p (mode, BB_END (bb1), BB_END (bb2))
1731 == dir_both);
1732 if (dump_file && match)
1733 fprintf (dump_file,
1734 "Tablejumps in bb %i and %i match.\n",
1735 bb1->index, bb2->index);
1737 /* Set the original label in BB1->END because when deleting
1738 a block whose end is a tablejump, the tablejump referenced
1739 from the instruction is deleted too. */
1740 rr.r1 = label2;
1741 rr.r2 = label1;
1742 for_each_rtx_in_insn (&BB_END (bb1), replace_label, &rr);
1744 return match;
1747 return false;
1751 /* Find the last non-debug non-note instruction in each bb, except
1752 stop when we see the NOTE_INSN_BASIC_BLOCK, as old_insns_match_p
1753 handles that case specially. old_insns_match_p does not handle
1754 other types of instruction notes. */
1755 rtx_insn *last1 = BB_END (bb1);
1756 rtx_insn *last2 = BB_END (bb2);
1757 while (!NOTE_INSN_BASIC_BLOCK_P (last1) &&
1758 (DEBUG_INSN_P (last1) || NOTE_P (last1)))
1759 last1 = PREV_INSN (last1);
1760 while (!NOTE_INSN_BASIC_BLOCK_P (last2) &&
1761 (DEBUG_INSN_P (last2) || NOTE_P (last2)))
1762 last2 = PREV_INSN (last2);
1763 gcc_assert (last1 && last2);
1765 /* First ensure that the instructions match. There may be many outgoing
1766 edges so this test is generally cheaper. */
1767 if (old_insns_match_p (mode, last1, last2) != dir_both)
1768 return false;
1770 /* Search the outgoing edges, ensure that the counts do match, find possible
1771 fallthru and exception handling edges since these needs more
1772 validation. */
1773 if (EDGE_COUNT (bb1->succs) != EDGE_COUNT (bb2->succs))
1774 return false;
1776 bool nonfakeedges = false;
1777 FOR_EACH_EDGE (e1, ei, bb1->succs)
1779 e2 = EDGE_SUCC (bb2, ei.index);
1781 if ((e1->flags & EDGE_FAKE) == 0)
1782 nonfakeedges = true;
1784 if (e1->flags & EDGE_EH)
1785 nehedges1++;
1787 if (e2->flags & EDGE_EH)
1788 nehedges2++;
1790 if (e1->flags & EDGE_FALLTHRU)
1791 fallthru1 = e1;
1792 if (e2->flags & EDGE_FALLTHRU)
1793 fallthru2 = e2;
1796 /* If number of edges of various types does not match, fail. */
1797 if (nehedges1 != nehedges2
1798 || (fallthru1 != 0) != (fallthru2 != 0))
1799 return false;
1801 /* If !ACCUMULATE_OUTGOING_ARGS, bb1 (and bb2) have no successors
1802 and the last real insn doesn't have REG_ARGS_SIZE note, don't
1803 attempt to optimize, as the two basic blocks might have different
1804 REG_ARGS_SIZE depths. For noreturn calls and unconditional
1805 traps there should be REG_ARG_SIZE notes, they could be missing
1806 for __builtin_unreachable () uses though. */
1807 if (!nonfakeedges
1808 && !ACCUMULATE_OUTGOING_ARGS
1809 && (!INSN_P (last1)
1810 || !find_reg_note (last1, REG_ARGS_SIZE, NULL)))
1811 return false;
1813 /* fallthru edges must be forwarded to the same destination. */
1814 if (fallthru1)
1816 basic_block d1 = (forwarder_block_p (fallthru1->dest)
1817 ? single_succ (fallthru1->dest): fallthru1->dest);
1818 basic_block d2 = (forwarder_block_p (fallthru2->dest)
1819 ? single_succ (fallthru2->dest): fallthru2->dest);
1821 if (d1 != d2)
1822 return false;
1825 /* Ensure the same EH region. */
1827 rtx n1 = find_reg_note (BB_END (bb1), REG_EH_REGION, 0);
1828 rtx n2 = find_reg_note (BB_END (bb2), REG_EH_REGION, 0);
1830 if (!n1 && n2)
1831 return false;
1833 if (n1 && (!n2 || XEXP (n1, 0) != XEXP (n2, 0)))
1834 return false;
1837 /* The same checks as in try_crossjump_to_edge. It is required for RTL
1838 version of sequence abstraction. */
1839 FOR_EACH_EDGE (e1, ei, bb2->succs)
1841 edge e2;
1842 edge_iterator ei;
1843 basic_block d1 = e1->dest;
1845 if (FORWARDER_BLOCK_P (d1))
1846 d1 = EDGE_SUCC (d1, 0)->dest;
1848 FOR_EACH_EDGE (e2, ei, bb1->succs)
1850 basic_block d2 = e2->dest;
1851 if (FORWARDER_BLOCK_P (d2))
1852 d2 = EDGE_SUCC (d2, 0)->dest;
1853 if (d1 == d2)
1854 break;
1857 if (!e2)
1858 return false;
1861 return true;
1864 /* Returns true if BB basic block has a preserve label. */
1866 static bool
1867 block_has_preserve_label (basic_block bb)
1869 return (bb
1870 && block_label (bb)
1871 && LABEL_PRESERVE_P (block_label (bb)));
1874 /* E1 and E2 are edges with the same destination block. Search their
1875 predecessors for common code. If found, redirect control flow from
1876 (maybe the middle of) E1->SRC to (maybe the middle of) E2->SRC (dir_forward),
1877 or the other way around (dir_backward). DIR specifies the allowed
1878 replacement direction. */
1880 static bool
1881 try_crossjump_to_edge (int mode, edge e1, edge e2,
1882 enum replace_direction dir)
1884 int nmatch;
1885 basic_block src1 = e1->src, src2 = e2->src;
1886 basic_block redirect_to, redirect_from, to_remove;
1887 basic_block osrc1, osrc2, redirect_edges_to, tmp;
1888 rtx_insn *newpos1, *newpos2;
1889 edge s;
1890 edge_iterator ei;
1892 newpos1 = newpos2 = NULL;
1894 /* If we have partitioned hot/cold basic blocks, it is a bad idea
1895 to try this optimization.
1897 Basic block partitioning may result in some jumps that appear to
1898 be optimizable (or blocks that appear to be mergeable), but which really
1899 must be left untouched (they are required to make it safely across
1900 partition boundaries). See the comments at the top of
1901 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
1903 if (crtl->has_bb_partition && reload_completed)
1904 return false;
1906 /* Search backward through forwarder blocks. We don't need to worry
1907 about multiple entry or chained forwarders, as they will be optimized
1908 away. We do this to look past the unconditional jump following a
1909 conditional jump that is required due to the current CFG shape. */
1910 if (single_pred_p (src1)
1911 && FORWARDER_BLOCK_P (src1))
1912 e1 = single_pred_edge (src1), src1 = e1->src;
1914 if (single_pred_p (src2)
1915 && FORWARDER_BLOCK_P (src2))
1916 e2 = single_pred_edge (src2), src2 = e2->src;
1918 /* Nothing to do if we reach ENTRY, or a common source block. */
1919 if (src1 == ENTRY_BLOCK_PTR_FOR_FN (cfun) || src2
1920 == ENTRY_BLOCK_PTR_FOR_FN (cfun))
1921 return false;
1922 if (src1 == src2)
1923 return false;
1925 /* Seeing more than 1 forwarder blocks would confuse us later... */
1926 if (FORWARDER_BLOCK_P (e1->dest)
1927 && FORWARDER_BLOCK_P (single_succ (e1->dest)))
1928 return false;
1930 if (FORWARDER_BLOCK_P (e2->dest)
1931 && FORWARDER_BLOCK_P (single_succ (e2->dest)))
1932 return false;
1934 /* Likewise with dead code (possibly newly created by the other optimizations
1935 of cfg_cleanup). */
1936 if (EDGE_COUNT (src1->preds) == 0 || EDGE_COUNT (src2->preds) == 0)
1937 return false;
1939 /* Look for the common insn sequence, part the first ... */
1940 if (!outgoing_edges_match (mode, src1, src2))
1941 return false;
1943 /* ... and part the second. */
1944 nmatch = flow_find_cross_jump (src1, src2, &newpos1, &newpos2, &dir);
1946 osrc1 = src1;
1947 osrc2 = src2;
1948 if (newpos1 != NULL_RTX)
1949 src1 = BLOCK_FOR_INSN (newpos1);
1950 if (newpos2 != NULL_RTX)
1951 src2 = BLOCK_FOR_INSN (newpos2);
1953 if (dir == dir_backward)
1955 #define SWAP(T, X, Y) do { T tmp = (X); (X) = (Y); (Y) = tmp; } while (0)
1956 SWAP (basic_block, osrc1, osrc2);
1957 SWAP (basic_block, src1, src2);
1958 SWAP (edge, e1, e2);
1959 SWAP (rtx_insn *, newpos1, newpos2);
1960 #undef SWAP
1963 /* Don't proceed with the crossjump unless we found a sufficient number
1964 of matching instructions or the 'from' block was totally matched
1965 (such that its predecessors will hopefully be redirected and the
1966 block removed). */
1967 if ((nmatch < PARAM_VALUE (PARAM_MIN_CROSSJUMP_INSNS))
1968 && (newpos1 != BB_HEAD (src1)))
1969 return false;
1971 /* Avoid deleting preserve label when redirecting ABNORMAL edges. */
1972 if (block_has_preserve_label (e1->dest)
1973 && (e1->flags & EDGE_ABNORMAL))
1974 return false;
1976 /* Here we know that the insns in the end of SRC1 which are common with SRC2
1977 will be deleted.
1978 If we have tablejumps in the end of SRC1 and SRC2
1979 they have been already compared for equivalence in outgoing_edges_match ()
1980 so replace the references to TABLE1 by references to TABLE2. */
1982 rtx label1, label2;
1983 rtx_jump_table_data *table1, *table2;
1985 if (tablejump_p (BB_END (osrc1), &label1, &table1)
1986 && tablejump_p (BB_END (osrc2), &label2, &table2)
1987 && label1 != label2)
1989 replace_label_data rr;
1990 rtx_insn *insn;
1992 /* Replace references to LABEL1 with LABEL2. */
1993 rr.r1 = label1;
1994 rr.r2 = label2;
1995 rr.update_label_nuses = true;
1996 for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
1998 /* Do not replace the label in SRC1->END because when deleting
1999 a block whose end is a tablejump, the tablejump referenced
2000 from the instruction is deleted too. */
2001 if (insn != BB_END (osrc1))
2002 for_each_rtx_in_insn (&insn, replace_label, &rr);
2007 /* Avoid splitting if possible. We must always split when SRC2 has
2008 EH predecessor edges, or we may end up with basic blocks with both
2009 normal and EH predecessor edges. */
2010 if (newpos2 == BB_HEAD (src2)
2011 && !(EDGE_PRED (src2, 0)->flags & EDGE_EH))
2012 redirect_to = src2;
2013 else
2015 if (newpos2 == BB_HEAD (src2))
2017 /* Skip possible basic block header. */
2018 if (LABEL_P (newpos2))
2019 newpos2 = NEXT_INSN (newpos2);
2020 while (DEBUG_INSN_P (newpos2))
2021 newpos2 = NEXT_INSN (newpos2);
2022 if (NOTE_P (newpos2))
2023 newpos2 = NEXT_INSN (newpos2);
2024 while (DEBUG_INSN_P (newpos2))
2025 newpos2 = NEXT_INSN (newpos2);
2028 if (dump_file)
2029 fprintf (dump_file, "Splitting bb %i before %i insns\n",
2030 src2->index, nmatch);
2031 redirect_to = split_block (src2, PREV_INSN (newpos2))->dest;
2034 if (dump_file)
2035 fprintf (dump_file,
2036 "Cross jumping from bb %i to bb %i; %i common insns\n",
2037 src1->index, src2->index, nmatch);
2039 /* We may have some registers visible through the block. */
2040 df_set_bb_dirty (redirect_to);
2042 if (osrc2 == src2)
2043 redirect_edges_to = redirect_to;
2044 else
2045 redirect_edges_to = osrc2;
2047 /* Recompute the frequencies and counts of outgoing edges. */
2048 FOR_EACH_EDGE (s, ei, redirect_edges_to->succs)
2050 edge s2;
2051 edge_iterator ei;
2052 basic_block d = s->dest;
2054 if (FORWARDER_BLOCK_P (d))
2055 d = single_succ (d);
2057 FOR_EACH_EDGE (s2, ei, src1->succs)
2059 basic_block d2 = s2->dest;
2060 if (FORWARDER_BLOCK_P (d2))
2061 d2 = single_succ (d2);
2062 if (d == d2)
2063 break;
2066 s->count += s2->count;
2068 /* Take care to update possible forwarder blocks. We verified
2069 that there is no more than one in the chain, so we can't run
2070 into infinite loop. */
2071 if (FORWARDER_BLOCK_P (s->dest))
2073 single_succ_edge (s->dest)->count += s2->count;
2074 s->dest->count += s2->count;
2075 s->dest->frequency += EDGE_FREQUENCY (s);
2078 if (FORWARDER_BLOCK_P (s2->dest))
2080 single_succ_edge (s2->dest)->count -= s2->count;
2081 if (single_succ_edge (s2->dest)->count < 0)
2082 single_succ_edge (s2->dest)->count = 0;
2083 s2->dest->count -= s2->count;
2084 s2->dest->frequency -= EDGE_FREQUENCY (s);
2085 if (s2->dest->frequency < 0)
2086 s2->dest->frequency = 0;
2087 if (s2->dest->count < 0)
2088 s2->dest->count = 0;
2091 if (!redirect_edges_to->frequency && !src1->frequency)
2092 s->probability = (s->probability + s2->probability) / 2;
2093 else
2094 s->probability
2095 = ((s->probability * redirect_edges_to->frequency +
2096 s2->probability * src1->frequency)
2097 / (redirect_edges_to->frequency + src1->frequency));
2100 /* Adjust count and frequency for the block. An earlier jump
2101 threading pass may have left the profile in an inconsistent
2102 state (see update_bb_profile_for_threading) so we must be
2103 prepared for overflows. */
2104 tmp = redirect_to;
2107 tmp->count += src1->count;
2108 tmp->frequency += src1->frequency;
2109 if (tmp->frequency > BB_FREQ_MAX)
2110 tmp->frequency = BB_FREQ_MAX;
2111 if (tmp == redirect_edges_to)
2112 break;
2113 tmp = find_fallthru_edge (tmp->succs)->dest;
2115 while (true);
2116 update_br_prob_note (redirect_edges_to);
2118 /* Edit SRC1 to go to REDIRECT_TO at NEWPOS1. */
2120 /* Skip possible basic block header. */
2121 if (LABEL_P (newpos1))
2122 newpos1 = NEXT_INSN (newpos1);
2124 while (DEBUG_INSN_P (newpos1))
2125 newpos1 = NEXT_INSN (newpos1);
2127 if (NOTE_INSN_BASIC_BLOCK_P (newpos1))
2128 newpos1 = NEXT_INSN (newpos1);
2130 while (DEBUG_INSN_P (newpos1))
2131 newpos1 = NEXT_INSN (newpos1);
2133 redirect_from = split_block (src1, PREV_INSN (newpos1))->src;
2134 to_remove = single_succ (redirect_from);
2136 redirect_edge_and_branch_force (single_succ_edge (redirect_from), redirect_to);
2137 delete_basic_block (to_remove);
2139 update_forwarder_flag (redirect_from);
2140 if (redirect_to != src2)
2141 update_forwarder_flag (src2);
2143 return true;
2146 /* Search the predecessors of BB for common insn sequences. When found,
2147 share code between them by redirecting control flow. Return true if
2148 any changes made. */
2150 static bool
2151 try_crossjump_bb (int mode, basic_block bb)
2153 edge e, e2, fallthru;
2154 bool changed;
2155 unsigned max, ix, ix2;
2157 /* Nothing to do if there is not at least two incoming edges. */
2158 if (EDGE_COUNT (bb->preds) < 2)
2159 return false;
2161 /* Don't crossjump if this block ends in a computed jump,
2162 unless we are optimizing for size. */
2163 if (optimize_bb_for_size_p (bb)
2164 && bb != EXIT_BLOCK_PTR_FOR_FN (cfun)
2165 && computed_jump_p (BB_END (bb)))
2166 return false;
2168 /* If we are partitioning hot/cold basic blocks, we don't want to
2169 mess up unconditional or indirect jumps that cross between hot
2170 and cold sections.
2172 Basic block partitioning may result in some jumps that appear to
2173 be optimizable (or blocks that appear to be mergeable), but which really
2174 must be left untouched (they are required to make it safely across
2175 partition boundaries). See the comments at the top of
2176 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
2178 if (BB_PARTITION (EDGE_PRED (bb, 0)->src) !=
2179 BB_PARTITION (EDGE_PRED (bb, 1)->src)
2180 || (EDGE_PRED (bb, 0)->flags & EDGE_CROSSING))
2181 return false;
2183 /* It is always cheapest to redirect a block that ends in a branch to
2184 a block that falls through into BB, as that adds no branches to the
2185 program. We'll try that combination first. */
2186 fallthru = NULL;
2187 max = PARAM_VALUE (PARAM_MAX_CROSSJUMP_EDGES);
2189 if (EDGE_COUNT (bb->preds) > max)
2190 return false;
2192 fallthru = find_fallthru_edge (bb->preds);
2194 changed = false;
2195 for (ix = 0; ix < EDGE_COUNT (bb->preds);)
2197 e = EDGE_PRED (bb, ix);
2198 ix++;
2200 /* As noted above, first try with the fallthru predecessor (or, a
2201 fallthru predecessor if we are in cfglayout mode). */
2202 if (fallthru)
2204 /* Don't combine the fallthru edge into anything else.
2205 If there is a match, we'll do it the other way around. */
2206 if (e == fallthru)
2207 continue;
2208 /* If nothing changed since the last attempt, there is nothing
2209 we can do. */
2210 if (!first_pass
2211 && !((e->src->flags & BB_MODIFIED)
2212 || (fallthru->src->flags & BB_MODIFIED)))
2213 continue;
2215 if (try_crossjump_to_edge (mode, e, fallthru, dir_forward))
2217 changed = true;
2218 ix = 0;
2219 continue;
2223 /* Non-obvious work limiting check: Recognize that we're going
2224 to call try_crossjump_bb on every basic block. So if we have
2225 two blocks with lots of outgoing edges (a switch) and they
2226 share lots of common destinations, then we would do the
2227 cross-jump check once for each common destination.
2229 Now, if the blocks actually are cross-jump candidates, then
2230 all of their destinations will be shared. Which means that
2231 we only need check them for cross-jump candidacy once. We
2232 can eliminate redundant checks of crossjump(A,B) by arbitrarily
2233 choosing to do the check from the block for which the edge
2234 in question is the first successor of A. */
2235 if (EDGE_SUCC (e->src, 0) != e)
2236 continue;
2238 for (ix2 = 0; ix2 < EDGE_COUNT (bb->preds); ix2++)
2240 e2 = EDGE_PRED (bb, ix2);
2242 if (e2 == e)
2243 continue;
2245 /* We've already checked the fallthru edge above. */
2246 if (e2 == fallthru)
2247 continue;
2249 /* The "first successor" check above only prevents multiple
2250 checks of crossjump(A,B). In order to prevent redundant
2251 checks of crossjump(B,A), require that A be the block
2252 with the lowest index. */
2253 if (e->src->index > e2->src->index)
2254 continue;
2256 /* If nothing changed since the last attempt, there is nothing
2257 we can do. */
2258 if (!first_pass
2259 && !((e->src->flags & BB_MODIFIED)
2260 || (e2->src->flags & BB_MODIFIED)))
2261 continue;
2263 /* Both e and e2 are not fallthru edges, so we can crossjump in either
2264 direction. */
2265 if (try_crossjump_to_edge (mode, e, e2, dir_both))
2267 changed = true;
2268 ix = 0;
2269 break;
2274 if (changed)
2275 crossjumps_occured = true;
2277 return changed;
2280 /* Search the successors of BB for common insn sequences. When found,
2281 share code between them by moving it across the basic block
2282 boundary. Return true if any changes made. */
2284 static bool
2285 try_head_merge_bb (basic_block bb)
2287 basic_block final_dest_bb = NULL;
2288 int max_match = INT_MAX;
2289 edge e0;
2290 rtx_insn **headptr, **currptr, **nextptr;
2291 bool changed, moveall;
2292 unsigned ix;
2293 rtx_insn *e0_last_head;
2294 rtx cond;
2295 rtx_insn *move_before;
2296 unsigned nedges = EDGE_COUNT (bb->succs);
2297 rtx_insn *jump = BB_END (bb);
2298 regset live, live_union;
2300 /* Nothing to do if there is not at least two outgoing edges. */
2301 if (nedges < 2)
2302 return false;
2304 /* Don't crossjump if this block ends in a computed jump,
2305 unless we are optimizing for size. */
2306 if (optimize_bb_for_size_p (bb)
2307 && bb != EXIT_BLOCK_PTR_FOR_FN (cfun)
2308 && computed_jump_p (BB_END (bb)))
2309 return false;
2311 cond = get_condition (jump, &move_before, true, false);
2312 if (cond == NULL_RTX)
2314 #ifdef HAVE_cc0
2315 if (reg_mentioned_p (cc0_rtx, jump))
2316 move_before = prev_nonnote_nondebug_insn (jump);
2317 else
2318 #endif
2319 move_before = jump;
2322 for (ix = 0; ix < nedges; ix++)
2323 if (EDGE_SUCC (bb, ix)->dest == EXIT_BLOCK_PTR_FOR_FN (cfun))
2324 return false;
2326 for (ix = 0; ix < nedges; ix++)
2328 edge e = EDGE_SUCC (bb, ix);
2329 basic_block other_bb = e->dest;
2331 if (df_get_bb_dirty (other_bb))
2333 block_was_dirty = true;
2334 return false;
2337 if (e->flags & EDGE_ABNORMAL)
2338 return false;
2340 /* Normally, all destination blocks must only be reachable from this
2341 block, i.e. they must have one incoming edge.
2343 There is one special case we can handle, that of multiple consecutive
2344 jumps where the first jumps to one of the targets of the second jump.
2345 This happens frequently in switch statements for default labels.
2346 The structure is as follows:
2347 FINAL_DEST_BB
2348 ....
2349 if (cond) jump A;
2350 fall through
2352 jump with targets A, B, C, D...
2354 has two incoming edges, from FINAL_DEST_BB and BB
2356 In this case, we can try to move the insns through BB and into
2357 FINAL_DEST_BB. */
2358 if (EDGE_COUNT (other_bb->preds) != 1)
2360 edge incoming_edge, incoming_bb_other_edge;
2361 edge_iterator ei;
2363 if (final_dest_bb != NULL
2364 || EDGE_COUNT (other_bb->preds) != 2)
2365 return false;
2367 /* We must be able to move the insns across the whole block. */
2368 move_before = BB_HEAD (bb);
2369 while (!NONDEBUG_INSN_P (move_before))
2370 move_before = NEXT_INSN (move_before);
2372 if (EDGE_COUNT (bb->preds) != 1)
2373 return false;
2374 incoming_edge = EDGE_PRED (bb, 0);
2375 final_dest_bb = incoming_edge->src;
2376 if (EDGE_COUNT (final_dest_bb->succs) != 2)
2377 return false;
2378 FOR_EACH_EDGE (incoming_bb_other_edge, ei, final_dest_bb->succs)
2379 if (incoming_bb_other_edge != incoming_edge)
2380 break;
2381 if (incoming_bb_other_edge->dest != other_bb)
2382 return false;
2386 e0 = EDGE_SUCC (bb, 0);
2387 e0_last_head = NULL;
2388 changed = false;
2390 for (ix = 1; ix < nedges; ix++)
2392 edge e = EDGE_SUCC (bb, ix);
2393 rtx_insn *e0_last, *e_last;
2394 int nmatch;
2396 nmatch = flow_find_head_matching_sequence (e0->dest, e->dest,
2397 &e0_last, &e_last, 0);
2398 if (nmatch == 0)
2399 return false;
2401 if (nmatch < max_match)
2403 max_match = nmatch;
2404 e0_last_head = e0_last;
2408 /* If we matched an entire block, we probably have to avoid moving the
2409 last insn. */
2410 if (max_match > 0
2411 && e0_last_head == BB_END (e0->dest)
2412 && (find_reg_note (e0_last_head, REG_EH_REGION, 0)
2413 || control_flow_insn_p (e0_last_head)))
2415 max_match--;
2416 if (max_match == 0)
2417 return false;
2419 e0_last_head = prev_real_insn (e0_last_head);
2420 while (DEBUG_INSN_P (e0_last_head));
2423 if (max_match == 0)
2424 return false;
2426 /* We must find a union of the live registers at each of the end points. */
2427 live = BITMAP_ALLOC (NULL);
2428 live_union = BITMAP_ALLOC (NULL);
2430 currptr = XNEWVEC (rtx_insn *, nedges);
2431 headptr = XNEWVEC (rtx_insn *, nedges);
2432 nextptr = XNEWVEC (rtx_insn *, nedges);
2434 for (ix = 0; ix < nedges; ix++)
2436 int j;
2437 basic_block merge_bb = EDGE_SUCC (bb, ix)->dest;
2438 rtx_insn *head = BB_HEAD (merge_bb);
2440 while (!NONDEBUG_INSN_P (head))
2441 head = NEXT_INSN (head);
2442 headptr[ix] = head;
2443 currptr[ix] = head;
2445 /* Compute the end point and live information */
2446 for (j = 1; j < max_match; j++)
2448 head = NEXT_INSN (head);
2449 while (!NONDEBUG_INSN_P (head));
2450 simulate_backwards_to_point (merge_bb, live, head);
2451 IOR_REG_SET (live_union, live);
2454 /* If we're moving across two blocks, verify the validity of the
2455 first move, then adjust the target and let the loop below deal
2456 with the final move. */
2457 if (final_dest_bb != NULL)
2459 rtx_insn *move_upto;
2461 moveall = can_move_insns_across (currptr[0], e0_last_head, move_before,
2462 jump, e0->dest, live_union,
2463 NULL, &move_upto);
2464 if (!moveall)
2466 if (move_upto == NULL_RTX)
2467 goto out;
2469 while (e0_last_head != move_upto)
2471 df_simulate_one_insn_backwards (e0->dest, e0_last_head,
2472 live_union);
2473 e0_last_head = PREV_INSN (e0_last_head);
2476 if (e0_last_head == NULL_RTX)
2477 goto out;
2479 jump = BB_END (final_dest_bb);
2480 cond = get_condition (jump, &move_before, true, false);
2481 if (cond == NULL_RTX)
2483 #ifdef HAVE_cc0
2484 if (reg_mentioned_p (cc0_rtx, jump))
2485 move_before = prev_nonnote_nondebug_insn (jump);
2486 else
2487 #endif
2488 move_before = jump;
2494 rtx_insn *move_upto;
2495 moveall = can_move_insns_across (currptr[0], e0_last_head,
2496 move_before, jump, e0->dest, live_union,
2497 NULL, &move_upto);
2498 if (!moveall && move_upto == NULL_RTX)
2500 if (jump == move_before)
2501 break;
2503 /* Try again, using a different insertion point. */
2504 move_before = jump;
2506 #ifdef HAVE_cc0
2507 /* Don't try moving before a cc0 user, as that may invalidate
2508 the cc0. */
2509 if (reg_mentioned_p (cc0_rtx, jump))
2510 break;
2511 #endif
2513 continue;
2516 if (final_dest_bb && !moveall)
2517 /* We haven't checked whether a partial move would be OK for the first
2518 move, so we have to fail this case. */
2519 break;
2521 changed = true;
2522 for (;;)
2524 if (currptr[0] == move_upto)
2525 break;
2526 for (ix = 0; ix < nedges; ix++)
2528 rtx_insn *curr = currptr[ix];
2530 curr = NEXT_INSN (curr);
2531 while (!NONDEBUG_INSN_P (curr));
2532 currptr[ix] = curr;
2536 /* If we can't currently move all of the identical insns, remember
2537 each insn after the range that we'll merge. */
2538 if (!moveall)
2539 for (ix = 0; ix < nedges; ix++)
2541 rtx_insn *curr = currptr[ix];
2543 curr = NEXT_INSN (curr);
2544 while (!NONDEBUG_INSN_P (curr));
2545 nextptr[ix] = curr;
2548 reorder_insns (headptr[0], currptr[0], PREV_INSN (move_before));
2549 df_set_bb_dirty (EDGE_SUCC (bb, 0)->dest);
2550 if (final_dest_bb != NULL)
2551 df_set_bb_dirty (final_dest_bb);
2552 df_set_bb_dirty (bb);
2553 for (ix = 1; ix < nedges; ix++)
2555 df_set_bb_dirty (EDGE_SUCC (bb, ix)->dest);
2556 delete_insn_chain (headptr[ix], currptr[ix], false);
2558 if (!moveall)
2560 if (jump == move_before)
2561 break;
2563 /* For the unmerged insns, try a different insertion point. */
2564 move_before = jump;
2566 #ifdef HAVE_cc0
2567 /* Don't try moving before a cc0 user, as that may invalidate
2568 the cc0. */
2569 if (reg_mentioned_p (cc0_rtx, jump))
2570 break;
2571 #endif
2573 for (ix = 0; ix < nedges; ix++)
2574 currptr[ix] = headptr[ix] = nextptr[ix];
2577 while (!moveall);
2579 out:
2580 free (currptr);
2581 free (headptr);
2582 free (nextptr);
2584 crossjumps_occured |= changed;
2586 return changed;
2589 /* Return true if BB contains just bb note, or bb note followed
2590 by only DEBUG_INSNs. */
2592 static bool
2593 trivially_empty_bb_p (basic_block bb)
2595 rtx_insn *insn = BB_END (bb);
2597 while (1)
2599 if (insn == BB_HEAD (bb))
2600 return true;
2601 if (!DEBUG_INSN_P (insn))
2602 return false;
2603 insn = PREV_INSN (insn);
2607 /* Do simple CFG optimizations - basic block merging, simplifying of jump
2608 instructions etc. Return nonzero if changes were made. */
2610 static bool
2611 try_optimize_cfg (int mode)
2613 bool changed_overall = false;
2614 bool changed;
2615 int iterations = 0;
2616 basic_block bb, b, next;
2618 if (mode & (CLEANUP_CROSSJUMP | CLEANUP_THREADING))
2619 clear_bb_flags ();
2621 crossjumps_occured = false;
2623 FOR_EACH_BB_FN (bb, cfun)
2624 update_forwarder_flag (bb);
2626 if (! targetm.cannot_modify_jumps_p ())
2628 first_pass = true;
2629 /* Attempt to merge blocks as made possible by edge removal. If
2630 a block has only one successor, and the successor has only
2631 one predecessor, they may be combined. */
2634 block_was_dirty = false;
2635 changed = false;
2636 iterations++;
2638 if (dump_file)
2639 fprintf (dump_file,
2640 "\n\ntry_optimize_cfg iteration %i\n\n",
2641 iterations);
2643 for (b = ENTRY_BLOCK_PTR_FOR_FN (cfun)->next_bb; b
2644 != EXIT_BLOCK_PTR_FOR_FN (cfun);)
2646 basic_block c;
2647 edge s;
2648 bool changed_here = false;
2650 /* Delete trivially dead basic blocks. This is either
2651 blocks with no predecessors, or empty blocks with no
2652 successors. However if the empty block with no
2653 successors is the successor of the ENTRY_BLOCK, it is
2654 kept. This ensures that the ENTRY_BLOCK will have a
2655 successor which is a precondition for many RTL
2656 passes. Empty blocks may result from expanding
2657 __builtin_unreachable (). */
2658 if (EDGE_COUNT (b->preds) == 0
2659 || (EDGE_COUNT (b->succs) == 0
2660 && trivially_empty_bb_p (b)
2661 && single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun))->dest
2662 != b))
2664 c = b->prev_bb;
2665 if (EDGE_COUNT (b->preds) > 0)
2667 edge e;
2668 edge_iterator ei;
2670 if (current_ir_type () == IR_RTL_CFGLAYOUT)
2672 if (BB_FOOTER (b)
2673 && BARRIER_P (BB_FOOTER (b)))
2674 FOR_EACH_EDGE (e, ei, b->preds)
2675 if ((e->flags & EDGE_FALLTHRU)
2676 && BB_FOOTER (e->src) == NULL)
2678 if (BB_FOOTER (b))
2680 BB_FOOTER (e->src) = BB_FOOTER (b);
2681 BB_FOOTER (b) = NULL;
2683 else
2685 start_sequence ();
2686 BB_FOOTER (e->src) = emit_barrier ();
2687 end_sequence ();
2691 else
2693 rtx_insn *last = get_last_bb_insn (b);
2694 if (last && BARRIER_P (last))
2695 FOR_EACH_EDGE (e, ei, b->preds)
2696 if ((e->flags & EDGE_FALLTHRU))
2697 emit_barrier_after (BB_END (e->src));
2700 delete_basic_block (b);
2701 changed = true;
2702 /* Avoid trying to remove the exit block. */
2703 b = (c == ENTRY_BLOCK_PTR_FOR_FN (cfun) ? c->next_bb : c);
2704 continue;
2707 /* Remove code labels no longer used. */
2708 if (single_pred_p (b)
2709 && (single_pred_edge (b)->flags & EDGE_FALLTHRU)
2710 && !(single_pred_edge (b)->flags & EDGE_COMPLEX)
2711 && LABEL_P (BB_HEAD (b))
2712 /* If the previous block ends with a branch to this
2713 block, we can't delete the label. Normally this
2714 is a condjump that is yet to be simplified, but
2715 if CASE_DROPS_THRU, this can be a tablejump with
2716 some element going to the same place as the
2717 default (fallthru). */
2718 && (single_pred (b) == ENTRY_BLOCK_PTR_FOR_FN (cfun)
2719 || !JUMP_P (BB_END (single_pred (b)))
2720 || ! label_is_jump_target_p (BB_HEAD (b),
2721 BB_END (single_pred (b)))))
2723 delete_insn (BB_HEAD (b));
2724 if (dump_file)
2725 fprintf (dump_file, "Deleted label in block %i.\n",
2726 b->index);
2729 /* If we fall through an empty block, we can remove it. */
2730 if (!(mode & (CLEANUP_CFGLAYOUT | CLEANUP_NO_INSN_DEL))
2731 && single_pred_p (b)
2732 && (single_pred_edge (b)->flags & EDGE_FALLTHRU)
2733 && !LABEL_P (BB_HEAD (b))
2734 && FORWARDER_BLOCK_P (b)
2735 /* Note that forwarder_block_p true ensures that
2736 there is a successor for this block. */
2737 && (single_succ_edge (b)->flags & EDGE_FALLTHRU)
2738 && n_basic_blocks_for_fn (cfun) > NUM_FIXED_BLOCKS + 1)
2740 if (dump_file)
2741 fprintf (dump_file,
2742 "Deleting fallthru block %i.\n",
2743 b->index);
2745 c = ((b->prev_bb == ENTRY_BLOCK_PTR_FOR_FN (cfun))
2746 ? b->next_bb : b->prev_bb);
2747 redirect_edge_succ_nodup (single_pred_edge (b),
2748 single_succ (b));
2749 delete_basic_block (b);
2750 changed = true;
2751 b = c;
2752 continue;
2755 /* Merge B with its single successor, if any. */
2756 if (single_succ_p (b)
2757 && (s = single_succ_edge (b))
2758 && !(s->flags & EDGE_COMPLEX)
2759 && (c = s->dest) != EXIT_BLOCK_PTR_FOR_FN (cfun)
2760 && single_pred_p (c)
2761 && b != c)
2763 /* When not in cfg_layout mode use code aware of reordering
2764 INSN. This code possibly creates new basic blocks so it
2765 does not fit merge_blocks interface and is kept here in
2766 hope that it will become useless once more of compiler
2767 is transformed to use cfg_layout mode. */
2769 if ((mode & CLEANUP_CFGLAYOUT)
2770 && can_merge_blocks_p (b, c))
2772 merge_blocks (b, c);
2773 update_forwarder_flag (b);
2774 changed_here = true;
2776 else if (!(mode & CLEANUP_CFGLAYOUT)
2777 /* If the jump insn has side effects,
2778 we can't kill the edge. */
2779 && (!JUMP_P (BB_END (b))
2780 || (reload_completed
2781 ? simplejump_p (BB_END (b))
2782 : (onlyjump_p (BB_END (b))
2783 && !tablejump_p (BB_END (b),
2784 NULL, NULL))))
2785 && (next = merge_blocks_move (s, b, c, mode)))
2787 b = next;
2788 changed_here = true;
2792 /* Simplify branch over branch. */
2793 if ((mode & CLEANUP_EXPENSIVE)
2794 && !(mode & CLEANUP_CFGLAYOUT)
2795 && try_simplify_condjump (b))
2796 changed_here = true;
2798 /* If B has a single outgoing edge, but uses a
2799 non-trivial jump instruction without side-effects, we
2800 can either delete the jump entirely, or replace it
2801 with a simple unconditional jump. */
2802 if (single_succ_p (b)
2803 && single_succ (b) != EXIT_BLOCK_PTR_FOR_FN (cfun)
2804 && onlyjump_p (BB_END (b))
2805 && !CROSSING_JUMP_P (BB_END (b))
2806 && try_redirect_by_replacing_jump (single_succ_edge (b),
2807 single_succ (b),
2808 (mode & CLEANUP_CFGLAYOUT) != 0))
2810 update_forwarder_flag (b);
2811 changed_here = true;
2814 /* Simplify branch to branch. */
2815 if (try_forward_edges (mode, b))
2817 update_forwarder_flag (b);
2818 changed_here = true;
2821 /* Look for shared code between blocks. */
2822 if ((mode & CLEANUP_CROSSJUMP)
2823 && try_crossjump_bb (mode, b))
2824 changed_here = true;
2826 if ((mode & CLEANUP_CROSSJUMP)
2827 /* This can lengthen register lifetimes. Do it only after
2828 reload. */
2829 && reload_completed
2830 && try_head_merge_bb (b))
2831 changed_here = true;
2833 /* Don't get confused by the index shift caused by
2834 deleting blocks. */
2835 if (!changed_here)
2836 b = b->next_bb;
2837 else
2838 changed = true;
2841 if ((mode & CLEANUP_CROSSJUMP)
2842 && try_crossjump_bb (mode, EXIT_BLOCK_PTR_FOR_FN (cfun)))
2843 changed = true;
2845 if (block_was_dirty)
2847 /* This should only be set by head-merging. */
2848 gcc_assert (mode & CLEANUP_CROSSJUMP);
2849 df_analyze ();
2852 if (changed)
2854 /* Edge forwarding in particular can cause hot blocks previously
2855 reached by both hot and cold blocks to become dominated only
2856 by cold blocks. This will cause the verification below to fail,
2857 and lead to now cold code in the hot section. This is not easy
2858 to detect and fix during edge forwarding, and in some cases
2859 is only visible after newly unreachable blocks are deleted,
2860 which will be done in fixup_partitions. */
2861 fixup_partitions ();
2863 #ifdef ENABLE_CHECKING
2864 verify_flow_info ();
2865 #endif
2868 changed_overall |= changed;
2869 first_pass = false;
2871 while (changed);
2874 FOR_ALL_BB_FN (b, cfun)
2875 b->flags &= ~(BB_FORWARDER_BLOCK | BB_NONTHREADABLE_BLOCK);
2877 return changed_overall;
2880 /* Delete all unreachable basic blocks. */
2882 bool
2883 delete_unreachable_blocks (void)
2885 bool changed = false;
2886 basic_block b, prev_bb;
2888 find_unreachable_blocks ();
2890 /* When we're in GIMPLE mode and there may be debug insns, we should
2891 delete blocks in reverse dominator order, so as to get a chance
2892 to substitute all released DEFs into debug stmts. If we don't
2893 have dominators information, walking blocks backward gets us a
2894 better chance of retaining most debug information than
2895 otherwise. */
2896 if (MAY_HAVE_DEBUG_INSNS && current_ir_type () == IR_GIMPLE
2897 && dom_info_available_p (CDI_DOMINATORS))
2899 for (b = EXIT_BLOCK_PTR_FOR_FN (cfun)->prev_bb;
2900 b != ENTRY_BLOCK_PTR_FOR_FN (cfun); b = prev_bb)
2902 prev_bb = b->prev_bb;
2904 if (!(b->flags & BB_REACHABLE))
2906 /* Speed up the removal of blocks that don't dominate
2907 others. Walking backwards, this should be the common
2908 case. */
2909 if (!first_dom_son (CDI_DOMINATORS, b))
2910 delete_basic_block (b);
2911 else
2913 vec<basic_block> h
2914 = get_all_dominated_blocks (CDI_DOMINATORS, b);
2916 while (h.length ())
2918 b = h.pop ();
2920 prev_bb = b->prev_bb;
2922 gcc_assert (!(b->flags & BB_REACHABLE));
2924 delete_basic_block (b);
2927 h.release ();
2930 changed = true;
2934 else
2936 for (b = EXIT_BLOCK_PTR_FOR_FN (cfun)->prev_bb;
2937 b != ENTRY_BLOCK_PTR_FOR_FN (cfun); b = prev_bb)
2939 prev_bb = b->prev_bb;
2941 if (!(b->flags & BB_REACHABLE))
2943 delete_basic_block (b);
2944 changed = true;
2949 if (changed)
2950 tidy_fallthru_edges ();
2951 return changed;
2954 /* Delete any jump tables never referenced. We can't delete them at the
2955 time of removing tablejump insn as they are referenced by the preceding
2956 insns computing the destination, so we delay deleting and garbagecollect
2957 them once life information is computed. */
2958 void
2959 delete_dead_jumptables (void)
2961 basic_block bb;
2963 /* A dead jump table does not belong to any basic block. Scan insns
2964 between two adjacent basic blocks. */
2965 FOR_EACH_BB_FN (bb, cfun)
2967 rtx_insn *insn, *next;
2969 for (insn = NEXT_INSN (BB_END (bb));
2970 insn && !NOTE_INSN_BASIC_BLOCK_P (insn);
2971 insn = next)
2973 next = NEXT_INSN (insn);
2974 if (LABEL_P (insn)
2975 && LABEL_NUSES (insn) == LABEL_PRESERVE_P (insn)
2976 && JUMP_TABLE_DATA_P (next))
2978 rtx_insn *label = insn, *jump = next;
2980 if (dump_file)
2981 fprintf (dump_file, "Dead jumptable %i removed\n",
2982 INSN_UID (insn));
2984 next = NEXT_INSN (next);
2985 delete_insn (jump);
2986 delete_insn (label);
2993 /* Tidy the CFG by deleting unreachable code and whatnot. */
2995 bool
2996 cleanup_cfg (int mode)
2998 bool changed = false;
3000 /* Set the cfglayout mode flag here. We could update all the callers
3001 but that is just inconvenient, especially given that we eventually
3002 want to have cfglayout mode as the default. */
3003 if (current_ir_type () == IR_RTL_CFGLAYOUT)
3004 mode |= CLEANUP_CFGLAYOUT;
3006 timevar_push (TV_CLEANUP_CFG);
3007 if (delete_unreachable_blocks ())
3009 changed = true;
3010 /* We've possibly created trivially dead code. Cleanup it right
3011 now to introduce more opportunities for try_optimize_cfg. */
3012 if (!(mode & (CLEANUP_NO_INSN_DEL))
3013 && !reload_completed)
3014 delete_trivially_dead_insns (get_insns (), max_reg_num ());
3017 compact_blocks ();
3019 /* To tail-merge blocks ending in the same noreturn function (e.g.
3020 a call to abort) we have to insert fake edges to exit. Do this
3021 here once. The fake edges do not interfere with any other CFG
3022 cleanups. */
3023 if (mode & CLEANUP_CROSSJUMP)
3024 add_noreturn_fake_exit_edges ();
3026 if (!dbg_cnt (cfg_cleanup))
3027 return changed;
3029 while (try_optimize_cfg (mode))
3031 delete_unreachable_blocks (), changed = true;
3032 if (!(mode & CLEANUP_NO_INSN_DEL))
3034 /* Try to remove some trivially dead insns when doing an expensive
3035 cleanup. But delete_trivially_dead_insns doesn't work after
3036 reload (it only handles pseudos) and run_fast_dce is too costly
3037 to run in every iteration.
3039 For effective cross jumping, we really want to run a fast DCE to
3040 clean up any dead conditions, or they get in the way of performing
3041 useful tail merges.
3043 Other transformations in cleanup_cfg are not so sensitive to dead
3044 code, so delete_trivially_dead_insns or even doing nothing at all
3045 is good enough. */
3046 if ((mode & CLEANUP_EXPENSIVE) && !reload_completed
3047 && !delete_trivially_dead_insns (get_insns (), max_reg_num ()))
3048 break;
3049 if ((mode & CLEANUP_CROSSJUMP) && crossjumps_occured)
3050 run_fast_dce ();
3052 else
3053 break;
3056 if (mode & CLEANUP_CROSSJUMP)
3057 remove_fake_exit_edges ();
3059 /* Don't call delete_dead_jumptables in cfglayout mode, because
3060 that function assumes that jump tables are in the insns stream.
3061 But we also don't _have_ to delete dead jumptables in cfglayout
3062 mode because we shouldn't even be looking at things that are
3063 not in a basic block. Dead jumptables are cleaned up when
3064 going out of cfglayout mode. */
3065 if (!(mode & CLEANUP_CFGLAYOUT))
3066 delete_dead_jumptables ();
3068 /* ??? We probably do this way too often. */
3069 if (current_loops
3070 && (changed
3071 || (mode & CLEANUP_CFG_CHANGED)))
3073 timevar_push (TV_REPAIR_LOOPS);
3074 /* The above doesn't preserve dominance info if available. */
3075 gcc_assert (!dom_info_available_p (CDI_DOMINATORS));
3076 calculate_dominance_info (CDI_DOMINATORS);
3077 fix_loop_structure (NULL);
3078 free_dominance_info (CDI_DOMINATORS);
3079 timevar_pop (TV_REPAIR_LOOPS);
3082 timevar_pop (TV_CLEANUP_CFG);
3084 return changed;
3087 namespace {
3089 const pass_data pass_data_jump =
3091 RTL_PASS, /* type */
3092 "jump", /* name */
3093 OPTGROUP_NONE, /* optinfo_flags */
3094 TV_JUMP, /* tv_id */
3095 0, /* properties_required */
3096 0, /* properties_provided */
3097 0, /* properties_destroyed */
3098 0, /* todo_flags_start */
3099 0, /* todo_flags_finish */
3102 class pass_jump : public rtl_opt_pass
3104 public:
3105 pass_jump (gcc::context *ctxt)
3106 : rtl_opt_pass (pass_data_jump, ctxt)
3109 /* opt_pass methods: */
3110 virtual unsigned int execute (function *);
3112 }; // class pass_jump
3114 unsigned int
3115 pass_jump::execute (function *)
3117 delete_trivially_dead_insns (get_insns (), max_reg_num ());
3118 if (dump_file)
3119 dump_flow_info (dump_file, dump_flags);
3120 cleanup_cfg ((optimize ? CLEANUP_EXPENSIVE : 0)
3121 | (flag_thread_jumps ? CLEANUP_THREADING : 0));
3122 return 0;
3125 } // anon namespace
3127 rtl_opt_pass *
3128 make_pass_jump (gcc::context *ctxt)
3130 return new pass_jump (ctxt);
3133 namespace {
3135 const pass_data pass_data_jump2 =
3137 RTL_PASS, /* type */
3138 "jump2", /* name */
3139 OPTGROUP_NONE, /* optinfo_flags */
3140 TV_JUMP, /* tv_id */
3141 0, /* properties_required */
3142 0, /* properties_provided */
3143 0, /* properties_destroyed */
3144 0, /* todo_flags_start */
3145 0, /* todo_flags_finish */
3148 class pass_jump2 : public rtl_opt_pass
3150 public:
3151 pass_jump2 (gcc::context *ctxt)
3152 : rtl_opt_pass (pass_data_jump2, ctxt)
3155 /* opt_pass methods: */
3156 virtual unsigned int execute (function *)
3158 cleanup_cfg (flag_crossjumping ? CLEANUP_CROSSJUMP : 0);
3159 return 0;
3162 }; // class pass_jump2
3164 } // anon namespace
3166 rtl_opt_pass *
3167 make_pass_jump2 (gcc::context *ctxt)
3169 return new pass_jump2 (ctxt);