reduce conditional compilation based on AUTO_INC_DEC
[official-gcc.git] / gcc / cfgcleanup.c
blob0183ca888fcb9733a94854daa6560eb72283cc2b
1 /* Control flow optimization code for GNU compiler.
2 Copyright (C) 1987-2015 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 /* This file contains optimizer of the control flow. The main entry point is
21 cleanup_cfg. Following optimizations are performed:
23 - Unreachable blocks removal
24 - Edge forwarding (edge to the forwarder block is forwarded to its
25 successor. Simplification of the branch instruction is performed by
26 underlying infrastructure so branch can be converted to simplejump or
27 eliminated).
28 - Cross jumping (tail merging)
29 - Conditional jump-around-simplejump simplification
30 - Basic block merging. */
32 #include "config.h"
33 #include "system.h"
34 #include "coretypes.h"
35 #include "backend.h"
36 #include "tree.h"
37 #include "rtl.h"
38 #include "df.h"
39 #include "alias.h"
40 #include "regs.h"
41 #include "insn-config.h"
42 #include "flags.h"
43 #include "recog.h"
44 #include "diagnostic-core.h"
45 #include "alloc-pool.h"
46 #include "cselib.h"
47 #include "params.h"
48 #include "tm_p.h"
49 #include "target.h"
50 #include "emit-rtl.h"
51 #include "tree-pass.h"
52 #include "cfgloop.h"
53 #include "expmed.h"
54 #include "dojump.h"
55 #include "explow.h"
56 #include "calls.h"
57 #include "varasm.h"
58 #include "stmt.h"
59 #include "expr.h"
60 #include "cfgrtl.h"
61 #include "cfganal.h"
62 #include "cfgbuild.h"
63 #include "cfgcleanup.h"
64 #include "dce.h"
65 #include "dbgcnt.h"
66 #include "rtl-iter.h"
68 #define FORWARDER_BLOCK_P(BB) ((BB)->flags & BB_FORWARDER_BLOCK)
70 /* Set to true when we are running first pass of try_optimize_cfg loop. */
71 static bool first_pass;
73 /* Set to true if crossjumps occurred in the latest run of try_optimize_cfg. */
74 static bool crossjumps_occured;
76 /* Set to true if we couldn't run an optimization due to stale liveness
77 information; we should run df_analyze to enable more opportunities. */
78 static bool block_was_dirty;
80 static bool try_crossjump_to_edge (int, edge, edge, enum replace_direction);
81 static bool try_crossjump_bb (int, basic_block);
82 static bool outgoing_edges_match (int, basic_block, basic_block);
83 static enum replace_direction old_insns_match_p (int, rtx_insn *, rtx_insn *);
85 static void merge_blocks_move_predecessor_nojumps (basic_block, basic_block);
86 static void merge_blocks_move_successor_nojumps (basic_block, basic_block);
87 static bool try_optimize_cfg (int);
88 static bool try_simplify_condjump (basic_block);
89 static bool try_forward_edges (int, basic_block);
90 static edge thread_jump (edge, basic_block);
91 static bool mark_effect (rtx, bitmap);
92 static void notice_new_block (basic_block);
93 static void update_forwarder_flag (basic_block);
94 static void merge_memattrs (rtx, rtx);
96 /* Set flags for newly created block. */
98 static void
99 notice_new_block (basic_block bb)
101 if (!bb)
102 return;
104 if (forwarder_block_p (bb))
105 bb->flags |= BB_FORWARDER_BLOCK;
108 /* Recompute forwarder flag after block has been modified. */
110 static void
111 update_forwarder_flag (basic_block bb)
113 if (forwarder_block_p (bb))
114 bb->flags |= BB_FORWARDER_BLOCK;
115 else
116 bb->flags &= ~BB_FORWARDER_BLOCK;
119 /* Simplify a conditional jump around an unconditional jump.
120 Return true if something changed. */
122 static bool
123 try_simplify_condjump (basic_block cbranch_block)
125 basic_block jump_block, jump_dest_block, cbranch_dest_block;
126 edge cbranch_jump_edge, cbranch_fallthru_edge;
127 rtx_insn *cbranch_insn;
129 /* Verify that there are exactly two successors. */
130 if (EDGE_COUNT (cbranch_block->succs) != 2)
131 return false;
133 /* Verify that we've got a normal conditional branch at the end
134 of the block. */
135 cbranch_insn = BB_END (cbranch_block);
136 if (!any_condjump_p (cbranch_insn))
137 return false;
139 cbranch_fallthru_edge = FALLTHRU_EDGE (cbranch_block);
140 cbranch_jump_edge = BRANCH_EDGE (cbranch_block);
142 /* The next block must not have multiple predecessors, must not
143 be the last block in the function, and must contain just the
144 unconditional jump. */
145 jump_block = cbranch_fallthru_edge->dest;
146 if (!single_pred_p (jump_block)
147 || jump_block->next_bb == EXIT_BLOCK_PTR_FOR_FN (cfun)
148 || !FORWARDER_BLOCK_P (jump_block))
149 return false;
150 jump_dest_block = single_succ (jump_block);
152 /* If we are partitioning hot/cold basic blocks, we don't want to
153 mess up unconditional or indirect jumps that cross between hot
154 and cold sections.
156 Basic block partitioning may result in some jumps that appear to
157 be optimizable (or blocks that appear to be mergeable), but which really
158 must be left untouched (they are required to make it safely across
159 partition boundaries). See the comments at the top of
160 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
162 if (BB_PARTITION (jump_block) != BB_PARTITION (jump_dest_block)
163 || (cbranch_jump_edge->flags & EDGE_CROSSING))
164 return false;
166 /* The conditional branch must target the block after the
167 unconditional branch. */
168 cbranch_dest_block = cbranch_jump_edge->dest;
170 if (cbranch_dest_block == EXIT_BLOCK_PTR_FOR_FN (cfun)
171 || !can_fallthru (jump_block, cbranch_dest_block))
172 return false;
174 /* Invert the conditional branch. */
175 if (!invert_jump (as_a <rtx_jump_insn *> (cbranch_insn),
176 block_label (jump_dest_block), 0))
177 return false;
179 if (dump_file)
180 fprintf (dump_file, "Simplifying condjump %i around jump %i\n",
181 INSN_UID (cbranch_insn), INSN_UID (BB_END (jump_block)));
183 /* Success. Update the CFG to match. Note that after this point
184 the edge variable names appear backwards; the redirection is done
185 this way to preserve edge profile data. */
186 cbranch_jump_edge = redirect_edge_succ_nodup (cbranch_jump_edge,
187 cbranch_dest_block);
188 cbranch_fallthru_edge = redirect_edge_succ_nodup (cbranch_fallthru_edge,
189 jump_dest_block);
190 cbranch_jump_edge->flags |= EDGE_FALLTHRU;
191 cbranch_fallthru_edge->flags &= ~EDGE_FALLTHRU;
192 update_br_prob_note (cbranch_block);
194 /* Delete the block with the unconditional jump, and clean up the mess. */
195 delete_basic_block (jump_block);
196 tidy_fallthru_edge (cbranch_jump_edge);
197 update_forwarder_flag (cbranch_block);
199 return true;
202 /* Attempt to prove that operation is NOOP using CSElib or mark the effect
203 on register. Used by jump threading. */
205 static bool
206 mark_effect (rtx exp, regset nonequal)
208 rtx dest;
209 switch (GET_CODE (exp))
211 /* In case we do clobber the register, mark it as equal, as we know the
212 value is dead so it don't have to match. */
213 case CLOBBER:
214 dest = XEXP (exp, 0);
215 if (REG_P (dest))
216 bitmap_clear_range (nonequal, REGNO (dest), REG_NREGS (dest));
217 return false;
219 case SET:
220 if (rtx_equal_for_cselib_p (SET_DEST (exp), SET_SRC (exp)))
221 return false;
222 dest = SET_DEST (exp);
223 if (dest == pc_rtx)
224 return false;
225 if (!REG_P (dest))
226 return true;
227 bitmap_set_range (nonequal, REGNO (dest), REG_NREGS (dest));
228 return false;
230 default:
231 return false;
235 /* Return true if X contains a register in NONEQUAL. */
236 static bool
237 mentions_nonequal_regs (const_rtx x, regset nonequal)
239 subrtx_iterator::array_type array;
240 FOR_EACH_SUBRTX (iter, array, x, NONCONST)
242 const_rtx x = *iter;
243 if (REG_P (x))
245 unsigned int end_regno = END_REGNO (x);
246 for (unsigned int regno = REGNO (x); regno < end_regno; ++regno)
247 if (REGNO_REG_SET_P (nonequal, regno))
248 return true;
251 return false;
254 /* Attempt to prove that the basic block B will have no side effects and
255 always continues in the same edge if reached via E. Return the edge
256 if exist, NULL otherwise. */
258 static edge
259 thread_jump (edge e, basic_block b)
261 rtx set1, set2, cond1, cond2;
262 rtx_insn *insn;
263 enum rtx_code code1, code2, reversed_code2;
264 bool reverse1 = false;
265 unsigned i;
266 regset nonequal;
267 bool failed = false;
268 reg_set_iterator rsi;
270 if (b->flags & BB_NONTHREADABLE_BLOCK)
271 return NULL;
273 /* At the moment, we do handle only conditional jumps, but later we may
274 want to extend this code to tablejumps and others. */
275 if (EDGE_COUNT (e->src->succs) != 2)
276 return NULL;
277 if (EDGE_COUNT (b->succs) != 2)
279 b->flags |= BB_NONTHREADABLE_BLOCK;
280 return NULL;
283 /* Second branch must end with onlyjump, as we will eliminate the jump. */
284 if (!any_condjump_p (BB_END (e->src)))
285 return NULL;
287 if (!any_condjump_p (BB_END (b)) || !onlyjump_p (BB_END (b)))
289 b->flags |= BB_NONTHREADABLE_BLOCK;
290 return NULL;
293 set1 = pc_set (BB_END (e->src));
294 set2 = pc_set (BB_END (b));
295 if (((e->flags & EDGE_FALLTHRU) != 0)
296 != (XEXP (SET_SRC (set1), 1) == pc_rtx))
297 reverse1 = true;
299 cond1 = XEXP (SET_SRC (set1), 0);
300 cond2 = XEXP (SET_SRC (set2), 0);
301 if (reverse1)
302 code1 = reversed_comparison_code (cond1, BB_END (e->src));
303 else
304 code1 = GET_CODE (cond1);
306 code2 = GET_CODE (cond2);
307 reversed_code2 = reversed_comparison_code (cond2, BB_END (b));
309 if (!comparison_dominates_p (code1, code2)
310 && !comparison_dominates_p (code1, reversed_code2))
311 return NULL;
313 /* Ensure that the comparison operators are equivalent.
314 ??? This is far too pessimistic. We should allow swapped operands,
315 different CCmodes, or for example comparisons for interval, that
316 dominate even when operands are not equivalent. */
317 if (!rtx_equal_p (XEXP (cond1, 0), XEXP (cond2, 0))
318 || !rtx_equal_p (XEXP (cond1, 1), XEXP (cond2, 1)))
319 return NULL;
321 /* Short circuit cases where block B contains some side effects, as we can't
322 safely bypass it. */
323 for (insn = NEXT_INSN (BB_HEAD (b)); insn != NEXT_INSN (BB_END (b));
324 insn = NEXT_INSN (insn))
325 if (INSN_P (insn) && side_effects_p (PATTERN (insn)))
327 b->flags |= BB_NONTHREADABLE_BLOCK;
328 return NULL;
331 cselib_init (0);
333 /* First process all values computed in the source basic block. */
334 for (insn = NEXT_INSN (BB_HEAD (e->src));
335 insn != NEXT_INSN (BB_END (e->src));
336 insn = NEXT_INSN (insn))
337 if (INSN_P (insn))
338 cselib_process_insn (insn);
340 nonequal = BITMAP_ALLOC (NULL);
341 CLEAR_REG_SET (nonequal);
343 /* Now assume that we've continued by the edge E to B and continue
344 processing as if it were same basic block.
345 Our goal is to prove that whole block is an NOOP. */
347 for (insn = NEXT_INSN (BB_HEAD (b));
348 insn != NEXT_INSN (BB_END (b)) && !failed;
349 insn = NEXT_INSN (insn))
351 if (INSN_P (insn))
353 rtx pat = PATTERN (insn);
355 if (GET_CODE (pat) == PARALLEL)
357 for (i = 0; i < (unsigned)XVECLEN (pat, 0); i++)
358 failed |= mark_effect (XVECEXP (pat, 0, i), nonequal);
360 else
361 failed |= mark_effect (pat, nonequal);
364 cselib_process_insn (insn);
367 /* Later we should clear nonequal of dead registers. So far we don't
368 have life information in cfg_cleanup. */
369 if (failed)
371 b->flags |= BB_NONTHREADABLE_BLOCK;
372 goto failed_exit;
375 /* cond2 must not mention any register that is not equal to the
376 former block. */
377 if (mentions_nonequal_regs (cond2, nonequal))
378 goto failed_exit;
380 EXECUTE_IF_SET_IN_REG_SET (nonequal, 0, i, rsi)
381 goto failed_exit;
383 BITMAP_FREE (nonequal);
384 cselib_finish ();
385 if ((comparison_dominates_p (code1, code2) != 0)
386 != (XEXP (SET_SRC (set2), 1) == pc_rtx))
387 return BRANCH_EDGE (b);
388 else
389 return FALLTHRU_EDGE (b);
391 failed_exit:
392 BITMAP_FREE (nonequal);
393 cselib_finish ();
394 return NULL;
397 /* Attempt to forward edges leaving basic block B.
398 Return true if successful. */
400 static bool
401 try_forward_edges (int mode, basic_block b)
403 bool changed = false;
404 edge_iterator ei;
405 edge e, *threaded_edges = NULL;
407 /* If we are partitioning hot/cold basic blocks, we don't want to
408 mess up unconditional or indirect jumps that cross between hot
409 and cold sections.
411 Basic block partitioning may result in some jumps that appear to
412 be optimizable (or blocks that appear to be mergeable), but which really
413 must be left untouched (they are required to make it safely across
414 partition boundaries). See the comments at the top of
415 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
417 if (JUMP_P (BB_END (b)) && CROSSING_JUMP_P (BB_END (b)))
418 return false;
420 for (ei = ei_start (b->succs); (e = ei_safe_edge (ei)); )
422 basic_block target, first;
423 location_t goto_locus;
424 int counter;
425 bool threaded = false;
426 int nthreaded_edges = 0;
427 bool may_thread = first_pass || (b->flags & BB_MODIFIED) != 0;
429 /* Skip complex edges because we don't know how to update them.
431 Still handle fallthru edges, as we can succeed to forward fallthru
432 edge to the same place as the branch edge of conditional branch
433 and turn conditional branch to an unconditional branch. */
434 if (e->flags & EDGE_COMPLEX)
436 ei_next (&ei);
437 continue;
440 target = first = e->dest;
441 counter = NUM_FIXED_BLOCKS;
442 goto_locus = e->goto_locus;
444 /* If we are partitioning hot/cold basic_blocks, we don't want to mess
445 up jumps that cross between hot/cold sections.
447 Basic block partitioning may result in some jumps that appear
448 to be optimizable (or blocks that appear to be mergeable), but which
449 really must be left untouched (they are required to make it safely
450 across partition boundaries). See the comments at the top of
451 bb-reorder.c:partition_hot_cold_basic_blocks for complete
452 details. */
454 if (first != EXIT_BLOCK_PTR_FOR_FN (cfun)
455 && JUMP_P (BB_END (first))
456 && CROSSING_JUMP_P (BB_END (first)))
457 return changed;
459 while (counter < n_basic_blocks_for_fn (cfun))
461 basic_block new_target = NULL;
462 bool new_target_threaded = false;
463 may_thread |= (target->flags & BB_MODIFIED) != 0;
465 if (FORWARDER_BLOCK_P (target)
466 && !(single_succ_edge (target)->flags & EDGE_CROSSING)
467 && single_succ (target) != EXIT_BLOCK_PTR_FOR_FN (cfun))
469 /* Bypass trivial infinite loops. */
470 new_target = single_succ (target);
471 if (target == new_target)
472 counter = n_basic_blocks_for_fn (cfun);
473 else if (!optimize)
475 /* When not optimizing, ensure that edges or forwarder
476 blocks with different locus are not optimized out. */
477 location_t new_locus = single_succ_edge (target)->goto_locus;
478 location_t locus = goto_locus;
480 if (LOCATION_LOCUS (new_locus) != UNKNOWN_LOCATION
481 && LOCATION_LOCUS (locus) != UNKNOWN_LOCATION
482 && new_locus != locus)
483 new_target = NULL;
484 else
486 if (LOCATION_LOCUS (new_locus) != UNKNOWN_LOCATION)
487 locus = new_locus;
489 rtx_insn *last = BB_END (target);
490 if (DEBUG_INSN_P (last))
491 last = prev_nondebug_insn (last);
492 if (last && INSN_P (last))
493 new_locus = INSN_LOCATION (last);
494 else
495 new_locus = UNKNOWN_LOCATION;
497 if (LOCATION_LOCUS (new_locus) != UNKNOWN_LOCATION
498 && LOCATION_LOCUS (locus) != UNKNOWN_LOCATION
499 && new_locus != locus)
500 new_target = NULL;
501 else
503 if (LOCATION_LOCUS (new_locus) != UNKNOWN_LOCATION)
504 locus = new_locus;
506 goto_locus = locus;
512 /* Allow to thread only over one edge at time to simplify updating
513 of probabilities. */
514 else if ((mode & CLEANUP_THREADING) && may_thread)
516 edge t = thread_jump (e, target);
517 if (t)
519 if (!threaded_edges)
520 threaded_edges = XNEWVEC (edge,
521 n_basic_blocks_for_fn (cfun));
522 else
524 int i;
526 /* Detect an infinite loop across blocks not
527 including the start block. */
528 for (i = 0; i < nthreaded_edges; ++i)
529 if (threaded_edges[i] == t)
530 break;
531 if (i < nthreaded_edges)
533 counter = n_basic_blocks_for_fn (cfun);
534 break;
538 /* Detect an infinite loop across the start block. */
539 if (t->dest == b)
540 break;
542 gcc_assert (nthreaded_edges
543 < (n_basic_blocks_for_fn (cfun)
544 - NUM_FIXED_BLOCKS));
545 threaded_edges[nthreaded_edges++] = t;
547 new_target = t->dest;
548 new_target_threaded = true;
552 if (!new_target)
553 break;
555 counter++;
556 target = new_target;
557 threaded |= new_target_threaded;
560 if (counter >= n_basic_blocks_for_fn (cfun))
562 if (dump_file)
563 fprintf (dump_file, "Infinite loop in BB %i.\n",
564 target->index);
566 else if (target == first)
567 ; /* We didn't do anything. */
568 else
570 /* Save the values now, as the edge may get removed. */
571 gcov_type edge_count = e->count;
572 int edge_probability = e->probability;
573 int edge_frequency;
574 int n = 0;
576 e->goto_locus = goto_locus;
578 /* Don't force if target is exit block. */
579 if (threaded && target != EXIT_BLOCK_PTR_FOR_FN (cfun))
581 notice_new_block (redirect_edge_and_branch_force (e, target));
582 if (dump_file)
583 fprintf (dump_file, "Conditionals threaded.\n");
585 else if (!redirect_edge_and_branch (e, target))
587 if (dump_file)
588 fprintf (dump_file,
589 "Forwarding edge %i->%i to %i failed.\n",
590 b->index, e->dest->index, target->index);
591 ei_next (&ei);
592 continue;
595 /* We successfully forwarded the edge. Now update profile
596 data: for each edge we traversed in the chain, remove
597 the original edge's execution count. */
598 edge_frequency = apply_probability (b->frequency, edge_probability);
602 edge t;
604 if (!single_succ_p (first))
606 gcc_assert (n < nthreaded_edges);
607 t = threaded_edges [n++];
608 gcc_assert (t->src == first);
609 update_bb_profile_for_threading (first, edge_frequency,
610 edge_count, t);
611 update_br_prob_note (first);
613 else
615 first->count -= edge_count;
616 if (first->count < 0)
617 first->count = 0;
618 first->frequency -= edge_frequency;
619 if (first->frequency < 0)
620 first->frequency = 0;
621 /* It is possible that as the result of
622 threading we've removed edge as it is
623 threaded to the fallthru edge. Avoid
624 getting out of sync. */
625 if (n < nthreaded_edges
626 && first == threaded_edges [n]->src)
627 n++;
628 t = single_succ_edge (first);
631 t->count -= edge_count;
632 if (t->count < 0)
633 t->count = 0;
634 first = t->dest;
636 while (first != target);
638 changed = true;
639 continue;
641 ei_next (&ei);
644 free (threaded_edges);
645 return changed;
649 /* Blocks A and B are to be merged into a single block. A has no incoming
650 fallthru edge, so it can be moved before B without adding or modifying
651 any jumps (aside from the jump from A to B). */
653 static void
654 merge_blocks_move_predecessor_nojumps (basic_block a, basic_block b)
656 rtx_insn *barrier;
658 /* If we are partitioning hot/cold basic blocks, we don't want to
659 mess up unconditional or indirect jumps that cross between hot
660 and cold sections.
662 Basic block partitioning may result in some jumps that appear to
663 be optimizable (or blocks that appear to be mergeable), but which really
664 must be left untouched (they are required to make it safely across
665 partition boundaries). See the comments at the top of
666 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
668 if (BB_PARTITION (a) != BB_PARTITION (b))
669 return;
671 barrier = next_nonnote_insn (BB_END (a));
672 gcc_assert (BARRIER_P (barrier));
673 delete_insn (barrier);
675 /* Scramble the insn chain. */
676 if (BB_END (a) != PREV_INSN (BB_HEAD (b)))
677 reorder_insns_nobb (BB_HEAD (a), BB_END (a), PREV_INSN (BB_HEAD (b)));
678 df_set_bb_dirty (a);
680 if (dump_file)
681 fprintf (dump_file, "Moved block %d before %d and merged.\n",
682 a->index, b->index);
684 /* Swap the records for the two blocks around. */
686 unlink_block (a);
687 link_block (a, b->prev_bb);
689 /* Now blocks A and B are contiguous. Merge them. */
690 merge_blocks (a, b);
693 /* Blocks A and B are to be merged into a single block. B has no outgoing
694 fallthru edge, so it can be moved after A without adding or modifying
695 any jumps (aside from the jump from A to B). */
697 static void
698 merge_blocks_move_successor_nojumps (basic_block a, basic_block b)
700 rtx_insn *barrier, *real_b_end;
701 rtx label;
702 rtx_jump_table_data *table;
704 /* If we are partitioning hot/cold basic blocks, we don't want to
705 mess up unconditional or indirect jumps that cross between hot
706 and cold sections.
708 Basic block partitioning may result in some jumps that appear to
709 be optimizable (or blocks that appear to be mergeable), but which really
710 must be left untouched (they are required to make it safely across
711 partition boundaries). See the comments at the top of
712 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
714 if (BB_PARTITION (a) != BB_PARTITION (b))
715 return;
717 real_b_end = BB_END (b);
719 /* If there is a jump table following block B temporarily add the jump table
720 to block B so that it will also be moved to the correct location. */
721 if (tablejump_p (BB_END (b), &label, &table)
722 && prev_active_insn (label) == BB_END (b))
724 BB_END (b) = table;
727 /* There had better have been a barrier there. Delete it. */
728 barrier = NEXT_INSN (BB_END (b));
729 if (barrier && BARRIER_P (barrier))
730 delete_insn (barrier);
733 /* Scramble the insn chain. */
734 reorder_insns_nobb (BB_HEAD (b), BB_END (b), BB_END (a));
736 /* Restore the real end of b. */
737 BB_END (b) = real_b_end;
739 if (dump_file)
740 fprintf (dump_file, "Moved block %d after %d and merged.\n",
741 b->index, a->index);
743 /* Now blocks A and B are contiguous. Merge them. */
744 merge_blocks (a, b);
747 /* Attempt to merge basic blocks that are potentially non-adjacent.
748 Return NULL iff the attempt failed, otherwise return basic block
749 where cleanup_cfg should continue. Because the merging commonly
750 moves basic block away or introduces another optimization
751 possibility, return basic block just before B so cleanup_cfg don't
752 need to iterate.
754 It may be good idea to return basic block before C in the case
755 C has been moved after B and originally appeared earlier in the
756 insn sequence, but we have no information available about the
757 relative ordering of these two. Hopefully it is not too common. */
759 static basic_block
760 merge_blocks_move (edge e, basic_block b, basic_block c, int mode)
762 basic_block next;
764 /* If we are partitioning hot/cold basic blocks, we don't want to
765 mess up unconditional or indirect jumps that cross between hot
766 and cold sections.
768 Basic block partitioning may result in some jumps that appear to
769 be optimizable (or blocks that appear to be mergeable), but which really
770 must be left untouched (they are required to make it safely across
771 partition boundaries). See the comments at the top of
772 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
774 if (BB_PARTITION (b) != BB_PARTITION (c))
775 return NULL;
777 /* If B has a fallthru edge to C, no need to move anything. */
778 if (e->flags & EDGE_FALLTHRU)
780 int b_index = b->index, c_index = c->index;
782 /* Protect the loop latches. */
783 if (current_loops && c->loop_father->latch == c)
784 return NULL;
786 merge_blocks (b, c);
787 update_forwarder_flag (b);
789 if (dump_file)
790 fprintf (dump_file, "Merged %d and %d without moving.\n",
791 b_index, c_index);
793 return b->prev_bb == ENTRY_BLOCK_PTR_FOR_FN (cfun) ? b : b->prev_bb;
796 /* Otherwise we will need to move code around. Do that only if expensive
797 transformations are allowed. */
798 else if (mode & CLEANUP_EXPENSIVE)
800 edge tmp_edge, b_fallthru_edge;
801 bool c_has_outgoing_fallthru;
802 bool b_has_incoming_fallthru;
804 /* Avoid overactive code motion, as the forwarder blocks should be
805 eliminated by edge redirection instead. One exception might have
806 been if B is a forwarder block and C has no fallthru edge, but
807 that should be cleaned up by bb-reorder instead. */
808 if (FORWARDER_BLOCK_P (b) || FORWARDER_BLOCK_P (c))
809 return NULL;
811 /* We must make sure to not munge nesting of lexical blocks,
812 and loop notes. This is done by squeezing out all the notes
813 and leaving them there to lie. Not ideal, but functional. */
815 tmp_edge = find_fallthru_edge (c->succs);
816 c_has_outgoing_fallthru = (tmp_edge != NULL);
818 tmp_edge = find_fallthru_edge (b->preds);
819 b_has_incoming_fallthru = (tmp_edge != NULL);
820 b_fallthru_edge = tmp_edge;
821 next = b->prev_bb;
822 if (next == c)
823 next = next->prev_bb;
825 /* Otherwise, we're going to try to move C after B. If C does
826 not have an outgoing fallthru, then it can be moved
827 immediately after B without introducing or modifying jumps. */
828 if (! c_has_outgoing_fallthru)
830 merge_blocks_move_successor_nojumps (b, c);
831 return next == ENTRY_BLOCK_PTR_FOR_FN (cfun) ? next->next_bb : next;
834 /* If B does not have an incoming fallthru, then it can be moved
835 immediately before C without introducing or modifying jumps.
836 C cannot be the first block, so we do not have to worry about
837 accessing a non-existent block. */
839 if (b_has_incoming_fallthru)
841 basic_block bb;
843 if (b_fallthru_edge->src == ENTRY_BLOCK_PTR_FOR_FN (cfun))
844 return NULL;
845 bb = force_nonfallthru (b_fallthru_edge);
846 if (bb)
847 notice_new_block (bb);
850 merge_blocks_move_predecessor_nojumps (b, c);
851 return next == ENTRY_BLOCK_PTR_FOR_FN (cfun) ? next->next_bb : next;
854 return NULL;
858 /* Removes the memory attributes of MEM expression
859 if they are not equal. */
861 static void
862 merge_memattrs (rtx x, rtx y)
864 int i;
865 int j;
866 enum rtx_code code;
867 const char *fmt;
869 if (x == y)
870 return;
871 if (x == 0 || y == 0)
872 return;
874 code = GET_CODE (x);
876 if (code != GET_CODE (y))
877 return;
879 if (GET_MODE (x) != GET_MODE (y))
880 return;
882 if (code == MEM && !mem_attrs_eq_p (MEM_ATTRS (x), MEM_ATTRS (y)))
884 if (! MEM_ATTRS (x))
885 MEM_ATTRS (y) = 0;
886 else if (! MEM_ATTRS (y))
887 MEM_ATTRS (x) = 0;
888 else
890 HOST_WIDE_INT mem_size;
892 if (MEM_ALIAS_SET (x) != MEM_ALIAS_SET (y))
894 set_mem_alias_set (x, 0);
895 set_mem_alias_set (y, 0);
898 if (! mem_expr_equal_p (MEM_EXPR (x), MEM_EXPR (y)))
900 set_mem_expr (x, 0);
901 set_mem_expr (y, 0);
902 clear_mem_offset (x);
903 clear_mem_offset (y);
905 else if (MEM_OFFSET_KNOWN_P (x) != MEM_OFFSET_KNOWN_P (y)
906 || (MEM_OFFSET_KNOWN_P (x)
907 && MEM_OFFSET (x) != MEM_OFFSET (y)))
909 clear_mem_offset (x);
910 clear_mem_offset (y);
913 if (MEM_SIZE_KNOWN_P (x) && MEM_SIZE_KNOWN_P (y))
915 mem_size = MAX (MEM_SIZE (x), MEM_SIZE (y));
916 set_mem_size (x, mem_size);
917 set_mem_size (y, mem_size);
919 else
921 clear_mem_size (x);
922 clear_mem_size (y);
925 set_mem_align (x, MIN (MEM_ALIGN (x), MEM_ALIGN (y)));
926 set_mem_align (y, MEM_ALIGN (x));
929 if (code == MEM)
931 if (MEM_READONLY_P (x) != MEM_READONLY_P (y))
933 MEM_READONLY_P (x) = 0;
934 MEM_READONLY_P (y) = 0;
936 if (MEM_NOTRAP_P (x) != MEM_NOTRAP_P (y))
938 MEM_NOTRAP_P (x) = 0;
939 MEM_NOTRAP_P (y) = 0;
941 if (MEM_VOLATILE_P (x) != MEM_VOLATILE_P (y))
943 MEM_VOLATILE_P (x) = 1;
944 MEM_VOLATILE_P (y) = 1;
948 fmt = GET_RTX_FORMAT (code);
949 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
951 switch (fmt[i])
953 case 'E':
954 /* Two vectors must have the same length. */
955 if (XVECLEN (x, i) != XVECLEN (y, i))
956 return;
958 for (j = 0; j < XVECLEN (x, i); j++)
959 merge_memattrs (XVECEXP (x, i, j), XVECEXP (y, i, j));
961 break;
963 case 'e':
964 merge_memattrs (XEXP (x, i), XEXP (y, i));
967 return;
971 /* Checks if patterns P1 and P2 are equivalent, apart from the possibly
972 different single sets S1 and S2. */
974 static bool
975 equal_different_set_p (rtx p1, rtx s1, rtx p2, rtx s2)
977 int i;
978 rtx e1, e2;
980 if (p1 == s1 && p2 == s2)
981 return true;
983 if (GET_CODE (p1) != PARALLEL || GET_CODE (p2) != PARALLEL)
984 return false;
986 if (XVECLEN (p1, 0) != XVECLEN (p2, 0))
987 return false;
989 for (i = 0; i < XVECLEN (p1, 0); i++)
991 e1 = XVECEXP (p1, 0, i);
992 e2 = XVECEXP (p2, 0, i);
993 if (e1 == s1 && e2 == s2)
994 continue;
995 if (reload_completed
996 ? rtx_renumbered_equal_p (e1, e2) : rtx_equal_p (e1, e2))
997 continue;
999 return false;
1002 return true;
1006 /* NOTE1 is the REG_EQUAL note, if any, attached to an insn
1007 that is a single_set with a SET_SRC of SRC1. Similarly
1008 for NOTE2/SRC2.
1010 So effectively NOTE1/NOTE2 are an alternate form of
1011 SRC1/SRC2 respectively.
1013 Return nonzero if SRC1 or NOTE1 has the same constant
1014 integer value as SRC2 or NOTE2. Else return zero. */
1015 static int
1016 values_equal_p (rtx note1, rtx note2, rtx src1, rtx src2)
1018 if (note1
1019 && note2
1020 && CONST_INT_P (XEXP (note1, 0))
1021 && rtx_equal_p (XEXP (note1, 0), XEXP (note2, 0)))
1022 return 1;
1024 if (!note1
1025 && !note2
1026 && CONST_INT_P (src1)
1027 && CONST_INT_P (src2)
1028 && rtx_equal_p (src1, src2))
1029 return 1;
1031 if (note1
1032 && CONST_INT_P (src2)
1033 && rtx_equal_p (XEXP (note1, 0), src2))
1034 return 1;
1036 if (note2
1037 && CONST_INT_P (src1)
1038 && rtx_equal_p (XEXP (note2, 0), src1))
1039 return 1;
1041 return 0;
1044 /* Examine register notes on I1 and I2 and return:
1045 - dir_forward if I1 can be replaced by I2, or
1046 - dir_backward if I2 can be replaced by I1, or
1047 - dir_both if both are the case. */
1049 static enum replace_direction
1050 can_replace_by (rtx_insn *i1, rtx_insn *i2)
1052 rtx s1, s2, d1, d2, src1, src2, note1, note2;
1053 bool c1, c2;
1055 /* Check for 2 sets. */
1056 s1 = single_set (i1);
1057 s2 = single_set (i2);
1058 if (s1 == NULL_RTX || s2 == NULL_RTX)
1059 return dir_none;
1061 /* Check that the 2 sets set the same dest. */
1062 d1 = SET_DEST (s1);
1063 d2 = SET_DEST (s2);
1064 if (!(reload_completed
1065 ? rtx_renumbered_equal_p (d1, d2) : rtx_equal_p (d1, d2)))
1066 return dir_none;
1068 /* Find identical req_equiv or reg_equal note, which implies that the 2 sets
1069 set dest to the same value. */
1070 note1 = find_reg_equal_equiv_note (i1);
1071 note2 = find_reg_equal_equiv_note (i2);
1073 src1 = SET_SRC (s1);
1074 src2 = SET_SRC (s2);
1076 if (!values_equal_p (note1, note2, src1, src2))
1077 return dir_none;
1079 if (!equal_different_set_p (PATTERN (i1), s1, PATTERN (i2), s2))
1080 return dir_none;
1082 /* Although the 2 sets set dest to the same value, we cannot replace
1083 (set (dest) (const_int))
1085 (set (dest) (reg))
1086 because we don't know if the reg is live and has the same value at the
1087 location of replacement. */
1088 c1 = CONST_INT_P (src1);
1089 c2 = CONST_INT_P (src2);
1090 if (c1 && c2)
1091 return dir_both;
1092 else if (c2)
1093 return dir_forward;
1094 else if (c1)
1095 return dir_backward;
1097 return dir_none;
1100 /* Merges directions A and B. */
1102 static enum replace_direction
1103 merge_dir (enum replace_direction a, enum replace_direction b)
1105 /* Implements the following table:
1106 |bo fw bw no
1107 ---+-----------
1108 bo |bo fw bw no
1109 fw |-- fw no no
1110 bw |-- -- bw no
1111 no |-- -- -- no. */
1113 if (a == b)
1114 return a;
1116 if (a == dir_both)
1117 return b;
1118 if (b == dir_both)
1119 return a;
1121 return dir_none;
1124 /* Examine I1 and I2 and return:
1125 - dir_forward if I1 can be replaced by I2, or
1126 - dir_backward if I2 can be replaced by I1, or
1127 - dir_both if both are the case. */
1129 static enum replace_direction
1130 old_insns_match_p (int mode ATTRIBUTE_UNUSED, rtx_insn *i1, rtx_insn *i2)
1132 rtx p1, p2;
1134 /* Verify that I1 and I2 are equivalent. */
1135 if (GET_CODE (i1) != GET_CODE (i2))
1136 return dir_none;
1138 /* __builtin_unreachable() may lead to empty blocks (ending with
1139 NOTE_INSN_BASIC_BLOCK). They may be crossjumped. */
1140 if (NOTE_INSN_BASIC_BLOCK_P (i1) && NOTE_INSN_BASIC_BLOCK_P (i2))
1141 return dir_both;
1143 /* ??? Do not allow cross-jumping between different stack levels. */
1144 p1 = find_reg_note (i1, REG_ARGS_SIZE, NULL);
1145 p2 = find_reg_note (i2, REG_ARGS_SIZE, NULL);
1146 if (p1 && p2)
1148 p1 = XEXP (p1, 0);
1149 p2 = XEXP (p2, 0);
1150 if (!rtx_equal_p (p1, p2))
1151 return dir_none;
1153 /* ??? Worse, this adjustment had better be constant lest we
1154 have differing incoming stack levels. */
1155 if (!frame_pointer_needed
1156 && find_args_size_adjust (i1) == HOST_WIDE_INT_MIN)
1157 return dir_none;
1159 else if (p1 || p2)
1160 return dir_none;
1162 p1 = PATTERN (i1);
1163 p2 = PATTERN (i2);
1165 if (GET_CODE (p1) != GET_CODE (p2))
1166 return dir_none;
1168 /* If this is a CALL_INSN, compare register usage information.
1169 If we don't check this on stack register machines, the two
1170 CALL_INSNs might be merged leaving reg-stack.c with mismatching
1171 numbers of stack registers in the same basic block.
1172 If we don't check this on machines with delay slots, a delay slot may
1173 be filled that clobbers a parameter expected by the subroutine.
1175 ??? We take the simple route for now and assume that if they're
1176 equal, they were constructed identically.
1178 Also check for identical exception regions. */
1180 if (CALL_P (i1))
1182 /* Ensure the same EH region. */
1183 rtx n1 = find_reg_note (i1, REG_EH_REGION, 0);
1184 rtx n2 = find_reg_note (i2, REG_EH_REGION, 0);
1186 if (!n1 && n2)
1187 return dir_none;
1189 if (n1 && (!n2 || XEXP (n1, 0) != XEXP (n2, 0)))
1190 return dir_none;
1192 if (!rtx_equal_p (CALL_INSN_FUNCTION_USAGE (i1),
1193 CALL_INSN_FUNCTION_USAGE (i2))
1194 || SIBLING_CALL_P (i1) != SIBLING_CALL_P (i2))
1195 return dir_none;
1197 /* For address sanitizer, never crossjump __asan_report_* builtins,
1198 otherwise errors might be reported on incorrect lines. */
1199 if (flag_sanitize & SANITIZE_ADDRESS)
1201 rtx call = get_call_rtx_from (i1);
1202 if (call && GET_CODE (XEXP (XEXP (call, 0), 0)) == SYMBOL_REF)
1204 rtx symbol = XEXP (XEXP (call, 0), 0);
1205 if (SYMBOL_REF_DECL (symbol)
1206 && TREE_CODE (SYMBOL_REF_DECL (symbol)) == FUNCTION_DECL)
1208 if ((DECL_BUILT_IN_CLASS (SYMBOL_REF_DECL (symbol))
1209 == BUILT_IN_NORMAL)
1210 && DECL_FUNCTION_CODE (SYMBOL_REF_DECL (symbol))
1211 >= BUILT_IN_ASAN_REPORT_LOAD1
1212 && DECL_FUNCTION_CODE (SYMBOL_REF_DECL (symbol))
1213 <= BUILT_IN_ASAN_STOREN)
1214 return dir_none;
1220 #ifdef STACK_REGS
1221 /* If cross_jump_death_matters is not 0, the insn's mode
1222 indicates whether or not the insn contains any stack-like
1223 regs. */
1225 if ((mode & CLEANUP_POST_REGSTACK) && stack_regs_mentioned (i1))
1227 /* If register stack conversion has already been done, then
1228 death notes must also be compared before it is certain that
1229 the two instruction streams match. */
1231 rtx note;
1232 HARD_REG_SET i1_regset, i2_regset;
1234 CLEAR_HARD_REG_SET (i1_regset);
1235 CLEAR_HARD_REG_SET (i2_regset);
1237 for (note = REG_NOTES (i1); note; note = XEXP (note, 1))
1238 if (REG_NOTE_KIND (note) == REG_DEAD && STACK_REG_P (XEXP (note, 0)))
1239 SET_HARD_REG_BIT (i1_regset, REGNO (XEXP (note, 0)));
1241 for (note = REG_NOTES (i2); note; note = XEXP (note, 1))
1242 if (REG_NOTE_KIND (note) == REG_DEAD && STACK_REG_P (XEXP (note, 0)))
1243 SET_HARD_REG_BIT (i2_regset, REGNO (XEXP (note, 0)));
1245 if (!hard_reg_set_equal_p (i1_regset, i2_regset))
1246 return dir_none;
1248 #endif
1250 if (reload_completed
1251 ? rtx_renumbered_equal_p (p1, p2) : rtx_equal_p (p1, p2))
1252 return dir_both;
1254 return can_replace_by (i1, i2);
1257 /* When comparing insns I1 and I2 in flow_find_cross_jump or
1258 flow_find_head_matching_sequence, ensure the notes match. */
1260 static void
1261 merge_notes (rtx_insn *i1, rtx_insn *i2)
1263 /* If the merged insns have different REG_EQUAL notes, then
1264 remove them. */
1265 rtx equiv1 = find_reg_equal_equiv_note (i1);
1266 rtx equiv2 = find_reg_equal_equiv_note (i2);
1268 if (equiv1 && !equiv2)
1269 remove_note (i1, equiv1);
1270 else if (!equiv1 && equiv2)
1271 remove_note (i2, equiv2);
1272 else if (equiv1 && equiv2
1273 && !rtx_equal_p (XEXP (equiv1, 0), XEXP (equiv2, 0)))
1275 remove_note (i1, equiv1);
1276 remove_note (i2, equiv2);
1280 /* Walks from I1 in BB1 backward till the next non-debug insn, and returns the
1281 resulting insn in I1, and the corresponding bb in BB1. At the head of a
1282 bb, if there is a predecessor bb that reaches this bb via fallthru, and
1283 FOLLOW_FALLTHRU, walks further in the predecessor bb and registers this in
1284 DID_FALLTHRU. Otherwise, stops at the head of the bb. */
1286 static void
1287 walk_to_nondebug_insn (rtx_insn **i1, basic_block *bb1, bool follow_fallthru,
1288 bool *did_fallthru)
1290 edge fallthru;
1292 *did_fallthru = false;
1294 /* Ignore notes. */
1295 while (!NONDEBUG_INSN_P (*i1))
1297 if (*i1 != BB_HEAD (*bb1))
1299 *i1 = PREV_INSN (*i1);
1300 continue;
1303 if (!follow_fallthru)
1304 return;
1306 fallthru = find_fallthru_edge ((*bb1)->preds);
1307 if (!fallthru || fallthru->src == ENTRY_BLOCK_PTR_FOR_FN (cfun)
1308 || !single_succ_p (fallthru->src))
1309 return;
1311 *bb1 = fallthru->src;
1312 *i1 = BB_END (*bb1);
1313 *did_fallthru = true;
1317 /* Look through the insns at the end of BB1 and BB2 and find the longest
1318 sequence that are either equivalent, or allow forward or backward
1319 replacement. Store the first insns for that sequence in *F1 and *F2 and
1320 return the sequence length.
1322 DIR_P indicates the allowed replacement direction on function entry, and
1323 the actual replacement direction on function exit. If NULL, only equivalent
1324 sequences are allowed.
1326 To simplify callers of this function, if the blocks match exactly,
1327 store the head of the blocks in *F1 and *F2. */
1330 flow_find_cross_jump (basic_block bb1, basic_block bb2, rtx_insn **f1,
1331 rtx_insn **f2, enum replace_direction *dir_p)
1333 rtx_insn *i1, *i2, *last1, *last2, *afterlast1, *afterlast2;
1334 int ninsns = 0;
1335 enum replace_direction dir, last_dir, afterlast_dir;
1336 bool follow_fallthru, did_fallthru;
1338 if (dir_p)
1339 dir = *dir_p;
1340 else
1341 dir = dir_both;
1342 afterlast_dir = dir;
1343 last_dir = afterlast_dir;
1345 /* Skip simple jumps at the end of the blocks. Complex jumps still
1346 need to be compared for equivalence, which we'll do below. */
1348 i1 = BB_END (bb1);
1349 last1 = afterlast1 = last2 = afterlast2 = NULL;
1350 if (onlyjump_p (i1)
1351 || (returnjump_p (i1) && !side_effects_p (PATTERN (i1))))
1353 last1 = i1;
1354 i1 = PREV_INSN (i1);
1357 i2 = BB_END (bb2);
1358 if (onlyjump_p (i2)
1359 || (returnjump_p (i2) && !side_effects_p (PATTERN (i2))))
1361 last2 = i2;
1362 /* Count everything except for unconditional jump as insn.
1363 Don't count any jumps if dir_p is NULL. */
1364 if (!simplejump_p (i2) && !returnjump_p (i2) && last1 && dir_p)
1365 ninsns++;
1366 i2 = PREV_INSN (i2);
1369 while (true)
1371 /* In the following example, we can replace all jumps to C by jumps to A.
1373 This removes 4 duplicate insns.
1374 [bb A] insn1 [bb C] insn1
1375 insn2 insn2
1376 [bb B] insn3 insn3
1377 insn4 insn4
1378 jump_insn jump_insn
1380 We could also replace all jumps to A by jumps to C, but that leaves B
1381 alive, and removes only 2 duplicate insns. In a subsequent crossjump
1382 step, all jumps to B would be replaced with jumps to the middle of C,
1383 achieving the same result with more effort.
1384 So we allow only the first possibility, which means that we don't allow
1385 fallthru in the block that's being replaced. */
1387 follow_fallthru = dir_p && dir != dir_forward;
1388 walk_to_nondebug_insn (&i1, &bb1, follow_fallthru, &did_fallthru);
1389 if (did_fallthru)
1390 dir = dir_backward;
1392 follow_fallthru = dir_p && dir != dir_backward;
1393 walk_to_nondebug_insn (&i2, &bb2, follow_fallthru, &did_fallthru);
1394 if (did_fallthru)
1395 dir = dir_forward;
1397 if (i1 == BB_HEAD (bb1) || i2 == BB_HEAD (bb2))
1398 break;
1400 dir = merge_dir (dir, old_insns_match_p (0, i1, i2));
1401 if (dir == dir_none || (!dir_p && dir != dir_both))
1402 break;
1404 merge_memattrs (i1, i2);
1406 /* Don't begin a cross-jump with a NOTE insn. */
1407 if (INSN_P (i1))
1409 merge_notes (i1, i2);
1411 afterlast1 = last1, afterlast2 = last2;
1412 last1 = i1, last2 = i2;
1413 afterlast_dir = last_dir;
1414 last_dir = dir;
1415 if (active_insn_p (i1))
1416 ninsns++;
1419 i1 = PREV_INSN (i1);
1420 i2 = PREV_INSN (i2);
1423 /* Don't allow the insn after a compare to be shared by
1424 cross-jumping unless the compare is also shared. */
1425 if (HAVE_cc0 && ninsns && reg_mentioned_p (cc0_rtx, last1)
1426 && ! sets_cc0_p (last1))
1427 last1 = afterlast1, last2 = afterlast2, last_dir = afterlast_dir, ninsns--;
1429 /* Include preceding notes and labels in the cross-jump. One,
1430 this may bring us to the head of the blocks as requested above.
1431 Two, it keeps line number notes as matched as may be. */
1432 if (ninsns)
1434 bb1 = BLOCK_FOR_INSN (last1);
1435 while (last1 != BB_HEAD (bb1) && !NONDEBUG_INSN_P (PREV_INSN (last1)))
1436 last1 = PREV_INSN (last1);
1438 if (last1 != BB_HEAD (bb1) && LABEL_P (PREV_INSN (last1)))
1439 last1 = PREV_INSN (last1);
1441 bb2 = BLOCK_FOR_INSN (last2);
1442 while (last2 != BB_HEAD (bb2) && !NONDEBUG_INSN_P (PREV_INSN (last2)))
1443 last2 = PREV_INSN (last2);
1445 if (last2 != BB_HEAD (bb2) && LABEL_P (PREV_INSN (last2)))
1446 last2 = PREV_INSN (last2);
1448 *f1 = last1;
1449 *f2 = last2;
1452 if (dir_p)
1453 *dir_p = last_dir;
1454 return ninsns;
1457 /* Like flow_find_cross_jump, except start looking for a matching sequence from
1458 the head of the two blocks. Do not include jumps at the end.
1459 If STOP_AFTER is nonzero, stop after finding that many matching
1460 instructions. If STOP_AFTER is zero, count all INSN_P insns, if it is
1461 non-zero, only count active insns. */
1464 flow_find_head_matching_sequence (basic_block bb1, basic_block bb2, rtx_insn **f1,
1465 rtx_insn **f2, int stop_after)
1467 rtx_insn *i1, *i2, *last1, *last2, *beforelast1, *beforelast2;
1468 int ninsns = 0;
1469 edge e;
1470 edge_iterator ei;
1471 int nehedges1 = 0, nehedges2 = 0;
1473 FOR_EACH_EDGE (e, ei, bb1->succs)
1474 if (e->flags & EDGE_EH)
1475 nehedges1++;
1476 FOR_EACH_EDGE (e, ei, bb2->succs)
1477 if (e->flags & EDGE_EH)
1478 nehedges2++;
1480 i1 = BB_HEAD (bb1);
1481 i2 = BB_HEAD (bb2);
1482 last1 = beforelast1 = last2 = beforelast2 = NULL;
1484 while (true)
1486 /* Ignore notes, except NOTE_INSN_EPILOGUE_BEG. */
1487 while (!NONDEBUG_INSN_P (i1) && i1 != BB_END (bb1))
1489 if (NOTE_P (i1) && NOTE_KIND (i1) == NOTE_INSN_EPILOGUE_BEG)
1490 break;
1491 i1 = NEXT_INSN (i1);
1494 while (!NONDEBUG_INSN_P (i2) && i2 != BB_END (bb2))
1496 if (NOTE_P (i2) && NOTE_KIND (i2) == NOTE_INSN_EPILOGUE_BEG)
1497 break;
1498 i2 = NEXT_INSN (i2);
1501 if ((i1 == BB_END (bb1) && !NONDEBUG_INSN_P (i1))
1502 || (i2 == BB_END (bb2) && !NONDEBUG_INSN_P (i2)))
1503 break;
1505 if (NOTE_P (i1) || NOTE_P (i2)
1506 || JUMP_P (i1) || JUMP_P (i2))
1507 break;
1509 /* A sanity check to make sure we're not merging insns with different
1510 effects on EH. If only one of them ends a basic block, it shouldn't
1511 have an EH edge; if both end a basic block, there should be the same
1512 number of EH edges. */
1513 if ((i1 == BB_END (bb1) && i2 != BB_END (bb2)
1514 && nehedges1 > 0)
1515 || (i2 == BB_END (bb2) && i1 != BB_END (bb1)
1516 && nehedges2 > 0)
1517 || (i1 == BB_END (bb1) && i2 == BB_END (bb2)
1518 && nehedges1 != nehedges2))
1519 break;
1521 if (old_insns_match_p (0, i1, i2) != dir_both)
1522 break;
1524 merge_memattrs (i1, i2);
1526 /* Don't begin a cross-jump with a NOTE insn. */
1527 if (INSN_P (i1))
1529 merge_notes (i1, i2);
1531 beforelast1 = last1, beforelast2 = last2;
1532 last1 = i1, last2 = i2;
1533 if (!stop_after || active_insn_p (i1))
1534 ninsns++;
1537 if (i1 == BB_END (bb1) || i2 == BB_END (bb2)
1538 || (stop_after > 0 && ninsns == stop_after))
1539 break;
1541 i1 = NEXT_INSN (i1);
1542 i2 = NEXT_INSN (i2);
1545 /* Don't allow a compare to be shared by cross-jumping unless the insn
1546 after the compare is also shared. */
1547 if (HAVE_cc0 && ninsns && reg_mentioned_p (cc0_rtx, last1)
1548 && sets_cc0_p (last1))
1549 last1 = beforelast1, last2 = beforelast2, ninsns--;
1551 if (ninsns)
1553 *f1 = last1;
1554 *f2 = last2;
1557 return ninsns;
1560 /* Return true iff outgoing edges of BB1 and BB2 match, together with
1561 the branch instruction. This means that if we commonize the control
1562 flow before end of the basic block, the semantic remains unchanged.
1564 We may assume that there exists one edge with a common destination. */
1566 static bool
1567 outgoing_edges_match (int mode, basic_block bb1, basic_block bb2)
1569 int nehedges1 = 0, nehedges2 = 0;
1570 edge fallthru1 = 0, fallthru2 = 0;
1571 edge e1, e2;
1572 edge_iterator ei;
1574 /* If we performed shrink-wrapping, edges to the exit block can
1575 only be distinguished for JUMP_INSNs. The two paths may differ in
1576 whether they went through the prologue. Sibcalls are fine, we know
1577 that we either didn't need or inserted an epilogue before them. */
1578 if (crtl->shrink_wrapped
1579 && single_succ_p (bb1)
1580 && single_succ (bb1) == EXIT_BLOCK_PTR_FOR_FN (cfun)
1581 && !JUMP_P (BB_END (bb1))
1582 && !(CALL_P (BB_END (bb1)) && SIBLING_CALL_P (BB_END (bb1))))
1583 return false;
1585 /* If BB1 has only one successor, we may be looking at either an
1586 unconditional jump, or a fake edge to exit. */
1587 if (single_succ_p (bb1)
1588 && (single_succ_edge (bb1)->flags & (EDGE_COMPLEX | EDGE_FAKE)) == 0
1589 && (!JUMP_P (BB_END (bb1)) || simplejump_p (BB_END (bb1))))
1590 return (single_succ_p (bb2)
1591 && (single_succ_edge (bb2)->flags
1592 & (EDGE_COMPLEX | EDGE_FAKE)) == 0
1593 && (!JUMP_P (BB_END (bb2)) || simplejump_p (BB_END (bb2))));
1595 /* Match conditional jumps - this may get tricky when fallthru and branch
1596 edges are crossed. */
1597 if (EDGE_COUNT (bb1->succs) == 2
1598 && any_condjump_p (BB_END (bb1))
1599 && onlyjump_p (BB_END (bb1)))
1601 edge b1, f1, b2, f2;
1602 bool reverse, match;
1603 rtx set1, set2, cond1, cond2;
1604 enum rtx_code code1, code2;
1606 if (EDGE_COUNT (bb2->succs) != 2
1607 || !any_condjump_p (BB_END (bb2))
1608 || !onlyjump_p (BB_END (bb2)))
1609 return false;
1611 b1 = BRANCH_EDGE (bb1);
1612 b2 = BRANCH_EDGE (bb2);
1613 f1 = FALLTHRU_EDGE (bb1);
1614 f2 = FALLTHRU_EDGE (bb2);
1616 /* Get around possible forwarders on fallthru edges. Other cases
1617 should be optimized out already. */
1618 if (FORWARDER_BLOCK_P (f1->dest))
1619 f1 = single_succ_edge (f1->dest);
1621 if (FORWARDER_BLOCK_P (f2->dest))
1622 f2 = single_succ_edge (f2->dest);
1624 /* To simplify use of this function, return false if there are
1625 unneeded forwarder blocks. These will get eliminated later
1626 during cleanup_cfg. */
1627 if (FORWARDER_BLOCK_P (f1->dest)
1628 || FORWARDER_BLOCK_P (f2->dest)
1629 || FORWARDER_BLOCK_P (b1->dest)
1630 || FORWARDER_BLOCK_P (b2->dest))
1631 return false;
1633 if (f1->dest == f2->dest && b1->dest == b2->dest)
1634 reverse = false;
1635 else if (f1->dest == b2->dest && b1->dest == f2->dest)
1636 reverse = true;
1637 else
1638 return false;
1640 set1 = pc_set (BB_END (bb1));
1641 set2 = pc_set (BB_END (bb2));
1642 if ((XEXP (SET_SRC (set1), 1) == pc_rtx)
1643 != (XEXP (SET_SRC (set2), 1) == pc_rtx))
1644 reverse = !reverse;
1646 cond1 = XEXP (SET_SRC (set1), 0);
1647 cond2 = XEXP (SET_SRC (set2), 0);
1648 code1 = GET_CODE (cond1);
1649 if (reverse)
1650 code2 = reversed_comparison_code (cond2, BB_END (bb2));
1651 else
1652 code2 = GET_CODE (cond2);
1654 if (code2 == UNKNOWN)
1655 return false;
1657 /* Verify codes and operands match. */
1658 match = ((code1 == code2
1659 && rtx_renumbered_equal_p (XEXP (cond1, 0), XEXP (cond2, 0))
1660 && rtx_renumbered_equal_p (XEXP (cond1, 1), XEXP (cond2, 1)))
1661 || (code1 == swap_condition (code2)
1662 && rtx_renumbered_equal_p (XEXP (cond1, 1),
1663 XEXP (cond2, 0))
1664 && rtx_renumbered_equal_p (XEXP (cond1, 0),
1665 XEXP (cond2, 1))));
1667 /* If we return true, we will join the blocks. Which means that
1668 we will only have one branch prediction bit to work with. Thus
1669 we require the existing branches to have probabilities that are
1670 roughly similar. */
1671 if (match
1672 && optimize_bb_for_speed_p (bb1)
1673 && optimize_bb_for_speed_p (bb2))
1675 int prob2;
1677 if (b1->dest == b2->dest)
1678 prob2 = b2->probability;
1679 else
1680 /* Do not use f2 probability as f2 may be forwarded. */
1681 prob2 = REG_BR_PROB_BASE - b2->probability;
1683 /* Fail if the difference in probabilities is greater than 50%.
1684 This rules out two well-predicted branches with opposite
1685 outcomes. */
1686 if (abs (b1->probability - prob2) > REG_BR_PROB_BASE / 2)
1688 if (dump_file)
1689 fprintf (dump_file,
1690 "Outcomes of branch in bb %i and %i differ too much (%i %i)\n",
1691 bb1->index, bb2->index, b1->probability, prob2);
1693 return false;
1697 if (dump_file && match)
1698 fprintf (dump_file, "Conditionals in bb %i and %i match.\n",
1699 bb1->index, bb2->index);
1701 return match;
1704 /* Generic case - we are seeing a computed jump, table jump or trapping
1705 instruction. */
1707 /* Check whether there are tablejumps in the end of BB1 and BB2.
1708 Return true if they are identical. */
1710 rtx label1, label2;
1711 rtx_jump_table_data *table1, *table2;
1713 if (tablejump_p (BB_END (bb1), &label1, &table1)
1714 && tablejump_p (BB_END (bb2), &label2, &table2)
1715 && GET_CODE (PATTERN (table1)) == GET_CODE (PATTERN (table2)))
1717 /* The labels should never be the same rtx. If they really are same
1718 the jump tables are same too. So disable crossjumping of blocks BB1
1719 and BB2 because when deleting the common insns in the end of BB1
1720 by delete_basic_block () the jump table would be deleted too. */
1721 /* If LABEL2 is referenced in BB1->END do not do anything
1722 because we would loose information when replacing
1723 LABEL1 by LABEL2 and then LABEL2 by LABEL1 in BB1->END. */
1724 if (label1 != label2 && !rtx_referenced_p (label2, BB_END (bb1)))
1726 /* Set IDENTICAL to true when the tables are identical. */
1727 bool identical = false;
1728 rtx p1, p2;
1730 p1 = PATTERN (table1);
1731 p2 = PATTERN (table2);
1732 if (GET_CODE (p1) == ADDR_VEC && rtx_equal_p (p1, p2))
1734 identical = true;
1736 else if (GET_CODE (p1) == ADDR_DIFF_VEC
1737 && (XVECLEN (p1, 1) == XVECLEN (p2, 1))
1738 && rtx_equal_p (XEXP (p1, 2), XEXP (p2, 2))
1739 && rtx_equal_p (XEXP (p1, 3), XEXP (p2, 3)))
1741 int i;
1743 identical = true;
1744 for (i = XVECLEN (p1, 1) - 1; i >= 0 && identical; i--)
1745 if (!rtx_equal_p (XVECEXP (p1, 1, i), XVECEXP (p2, 1, i)))
1746 identical = false;
1749 if (identical)
1751 bool match;
1753 /* Temporarily replace references to LABEL1 with LABEL2
1754 in BB1->END so that we could compare the instructions. */
1755 replace_label_in_insn (BB_END (bb1), label1, label2, false);
1757 match = (old_insns_match_p (mode, BB_END (bb1), BB_END (bb2))
1758 == dir_both);
1759 if (dump_file && match)
1760 fprintf (dump_file,
1761 "Tablejumps in bb %i and %i match.\n",
1762 bb1->index, bb2->index);
1764 /* Set the original label in BB1->END because when deleting
1765 a block whose end is a tablejump, the tablejump referenced
1766 from the instruction is deleted too. */
1767 replace_label_in_insn (BB_END (bb1), label2, label1, false);
1769 return match;
1772 return false;
1776 /* Find the last non-debug non-note instruction in each bb, except
1777 stop when we see the NOTE_INSN_BASIC_BLOCK, as old_insns_match_p
1778 handles that case specially. old_insns_match_p does not handle
1779 other types of instruction notes. */
1780 rtx_insn *last1 = BB_END (bb1);
1781 rtx_insn *last2 = BB_END (bb2);
1782 while (!NOTE_INSN_BASIC_BLOCK_P (last1) &&
1783 (DEBUG_INSN_P (last1) || NOTE_P (last1)))
1784 last1 = PREV_INSN (last1);
1785 while (!NOTE_INSN_BASIC_BLOCK_P (last2) &&
1786 (DEBUG_INSN_P (last2) || NOTE_P (last2)))
1787 last2 = PREV_INSN (last2);
1788 gcc_assert (last1 && last2);
1790 /* First ensure that the instructions match. There may be many outgoing
1791 edges so this test is generally cheaper. */
1792 if (old_insns_match_p (mode, last1, last2) != dir_both)
1793 return false;
1795 /* Search the outgoing edges, ensure that the counts do match, find possible
1796 fallthru and exception handling edges since these needs more
1797 validation. */
1798 if (EDGE_COUNT (bb1->succs) != EDGE_COUNT (bb2->succs))
1799 return false;
1801 bool nonfakeedges = false;
1802 FOR_EACH_EDGE (e1, ei, bb1->succs)
1804 e2 = EDGE_SUCC (bb2, ei.index);
1806 if ((e1->flags & EDGE_FAKE) == 0)
1807 nonfakeedges = true;
1809 if (e1->flags & EDGE_EH)
1810 nehedges1++;
1812 if (e2->flags & EDGE_EH)
1813 nehedges2++;
1815 if (e1->flags & EDGE_FALLTHRU)
1816 fallthru1 = e1;
1817 if (e2->flags & EDGE_FALLTHRU)
1818 fallthru2 = e2;
1821 /* If number of edges of various types does not match, fail. */
1822 if (nehedges1 != nehedges2
1823 || (fallthru1 != 0) != (fallthru2 != 0))
1824 return false;
1826 /* If !ACCUMULATE_OUTGOING_ARGS, bb1 (and bb2) have no successors
1827 and the last real insn doesn't have REG_ARGS_SIZE note, don't
1828 attempt to optimize, as the two basic blocks might have different
1829 REG_ARGS_SIZE depths. For noreturn calls and unconditional
1830 traps there should be REG_ARG_SIZE notes, they could be missing
1831 for __builtin_unreachable () uses though. */
1832 if (!nonfakeedges
1833 && !ACCUMULATE_OUTGOING_ARGS
1834 && (!INSN_P (last1)
1835 || !find_reg_note (last1, REG_ARGS_SIZE, NULL)))
1836 return false;
1838 /* fallthru edges must be forwarded to the same destination. */
1839 if (fallthru1)
1841 basic_block d1 = (forwarder_block_p (fallthru1->dest)
1842 ? single_succ (fallthru1->dest): fallthru1->dest);
1843 basic_block d2 = (forwarder_block_p (fallthru2->dest)
1844 ? single_succ (fallthru2->dest): fallthru2->dest);
1846 if (d1 != d2)
1847 return false;
1850 /* Ensure the same EH region. */
1852 rtx n1 = find_reg_note (BB_END (bb1), REG_EH_REGION, 0);
1853 rtx n2 = find_reg_note (BB_END (bb2), REG_EH_REGION, 0);
1855 if (!n1 && n2)
1856 return false;
1858 if (n1 && (!n2 || XEXP (n1, 0) != XEXP (n2, 0)))
1859 return false;
1862 /* The same checks as in try_crossjump_to_edge. It is required for RTL
1863 version of sequence abstraction. */
1864 FOR_EACH_EDGE (e1, ei, bb2->succs)
1866 edge e2;
1867 edge_iterator ei;
1868 basic_block d1 = e1->dest;
1870 if (FORWARDER_BLOCK_P (d1))
1871 d1 = EDGE_SUCC (d1, 0)->dest;
1873 FOR_EACH_EDGE (e2, ei, bb1->succs)
1875 basic_block d2 = e2->dest;
1876 if (FORWARDER_BLOCK_P (d2))
1877 d2 = EDGE_SUCC (d2, 0)->dest;
1878 if (d1 == d2)
1879 break;
1882 if (!e2)
1883 return false;
1886 return true;
1889 /* Returns true if BB basic block has a preserve label. */
1891 static bool
1892 block_has_preserve_label (basic_block bb)
1894 return (bb
1895 && block_label (bb)
1896 && LABEL_PRESERVE_P (block_label (bb)));
1899 /* E1 and E2 are edges with the same destination block. Search their
1900 predecessors for common code. If found, redirect control flow from
1901 (maybe the middle of) E1->SRC to (maybe the middle of) E2->SRC (dir_forward),
1902 or the other way around (dir_backward). DIR specifies the allowed
1903 replacement direction. */
1905 static bool
1906 try_crossjump_to_edge (int mode, edge e1, edge e2,
1907 enum replace_direction dir)
1909 int nmatch;
1910 basic_block src1 = e1->src, src2 = e2->src;
1911 basic_block redirect_to, redirect_from, to_remove;
1912 basic_block osrc1, osrc2, redirect_edges_to, tmp;
1913 rtx_insn *newpos1, *newpos2;
1914 edge s;
1915 edge_iterator ei;
1917 newpos1 = newpos2 = NULL;
1919 /* If we have partitioned hot/cold basic blocks, it is a bad idea
1920 to try this optimization.
1922 Basic block partitioning may result in some jumps that appear to
1923 be optimizable (or blocks that appear to be mergeable), but which really
1924 must be left untouched (they are required to make it safely across
1925 partition boundaries). See the comments at the top of
1926 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
1928 if (crtl->has_bb_partition && reload_completed)
1929 return false;
1931 /* Search backward through forwarder blocks. We don't need to worry
1932 about multiple entry or chained forwarders, as they will be optimized
1933 away. We do this to look past the unconditional jump following a
1934 conditional jump that is required due to the current CFG shape. */
1935 if (single_pred_p (src1)
1936 && FORWARDER_BLOCK_P (src1))
1937 e1 = single_pred_edge (src1), src1 = e1->src;
1939 if (single_pred_p (src2)
1940 && FORWARDER_BLOCK_P (src2))
1941 e2 = single_pred_edge (src2), src2 = e2->src;
1943 /* Nothing to do if we reach ENTRY, or a common source block. */
1944 if (src1 == ENTRY_BLOCK_PTR_FOR_FN (cfun) || src2
1945 == ENTRY_BLOCK_PTR_FOR_FN (cfun))
1946 return false;
1947 if (src1 == src2)
1948 return false;
1950 /* Seeing more than 1 forwarder blocks would confuse us later... */
1951 if (FORWARDER_BLOCK_P (e1->dest)
1952 && FORWARDER_BLOCK_P (single_succ (e1->dest)))
1953 return false;
1955 if (FORWARDER_BLOCK_P (e2->dest)
1956 && FORWARDER_BLOCK_P (single_succ (e2->dest)))
1957 return false;
1959 /* Likewise with dead code (possibly newly created by the other optimizations
1960 of cfg_cleanup). */
1961 if (EDGE_COUNT (src1->preds) == 0 || EDGE_COUNT (src2->preds) == 0)
1962 return false;
1964 /* Look for the common insn sequence, part the first ... */
1965 if (!outgoing_edges_match (mode, src1, src2))
1966 return false;
1968 /* ... and part the second. */
1969 nmatch = flow_find_cross_jump (src1, src2, &newpos1, &newpos2, &dir);
1971 osrc1 = src1;
1972 osrc2 = src2;
1973 if (newpos1 != NULL_RTX)
1974 src1 = BLOCK_FOR_INSN (newpos1);
1975 if (newpos2 != NULL_RTX)
1976 src2 = BLOCK_FOR_INSN (newpos2);
1978 if (dir == dir_backward)
1980 #define SWAP(T, X, Y) do { T tmp = (X); (X) = (Y); (Y) = tmp; } while (0)
1981 SWAP (basic_block, osrc1, osrc2);
1982 SWAP (basic_block, src1, src2);
1983 SWAP (edge, e1, e2);
1984 SWAP (rtx_insn *, newpos1, newpos2);
1985 #undef SWAP
1988 /* Don't proceed with the crossjump unless we found a sufficient number
1989 of matching instructions or the 'from' block was totally matched
1990 (such that its predecessors will hopefully be redirected and the
1991 block removed). */
1992 if ((nmatch < PARAM_VALUE (PARAM_MIN_CROSSJUMP_INSNS))
1993 && (newpos1 != BB_HEAD (src1)))
1994 return false;
1996 /* Avoid deleting preserve label when redirecting ABNORMAL edges. */
1997 if (block_has_preserve_label (e1->dest)
1998 && (e1->flags & EDGE_ABNORMAL))
1999 return false;
2001 /* Here we know that the insns in the end of SRC1 which are common with SRC2
2002 will be deleted.
2003 If we have tablejumps in the end of SRC1 and SRC2
2004 they have been already compared for equivalence in outgoing_edges_match ()
2005 so replace the references to TABLE1 by references to TABLE2. */
2007 rtx label1, label2;
2008 rtx_jump_table_data *table1, *table2;
2010 if (tablejump_p (BB_END (osrc1), &label1, &table1)
2011 && tablejump_p (BB_END (osrc2), &label2, &table2)
2012 && label1 != label2)
2014 rtx_insn *insn;
2016 /* Replace references to LABEL1 with LABEL2. */
2017 for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
2019 /* Do not replace the label in SRC1->END because when deleting
2020 a block whose end is a tablejump, the tablejump referenced
2021 from the instruction is deleted too. */
2022 if (insn != BB_END (osrc1))
2023 replace_label_in_insn (insn, label1, label2, true);
2028 /* Avoid splitting if possible. We must always split when SRC2 has
2029 EH predecessor edges, or we may end up with basic blocks with both
2030 normal and EH predecessor edges. */
2031 if (newpos2 == BB_HEAD (src2)
2032 && !(EDGE_PRED (src2, 0)->flags & EDGE_EH))
2033 redirect_to = src2;
2034 else
2036 if (newpos2 == BB_HEAD (src2))
2038 /* Skip possible basic block header. */
2039 if (LABEL_P (newpos2))
2040 newpos2 = NEXT_INSN (newpos2);
2041 while (DEBUG_INSN_P (newpos2))
2042 newpos2 = NEXT_INSN (newpos2);
2043 if (NOTE_P (newpos2))
2044 newpos2 = NEXT_INSN (newpos2);
2045 while (DEBUG_INSN_P (newpos2))
2046 newpos2 = NEXT_INSN (newpos2);
2049 if (dump_file)
2050 fprintf (dump_file, "Splitting bb %i before %i insns\n",
2051 src2->index, nmatch);
2052 redirect_to = split_block (src2, PREV_INSN (newpos2))->dest;
2055 if (dump_file)
2056 fprintf (dump_file,
2057 "Cross jumping from bb %i to bb %i; %i common insns\n",
2058 src1->index, src2->index, nmatch);
2060 /* We may have some registers visible through the block. */
2061 df_set_bb_dirty (redirect_to);
2063 if (osrc2 == src2)
2064 redirect_edges_to = redirect_to;
2065 else
2066 redirect_edges_to = osrc2;
2068 /* Recompute the frequencies and counts of outgoing edges. */
2069 FOR_EACH_EDGE (s, ei, redirect_edges_to->succs)
2071 edge s2;
2072 edge_iterator ei;
2073 basic_block d = s->dest;
2075 if (FORWARDER_BLOCK_P (d))
2076 d = single_succ (d);
2078 FOR_EACH_EDGE (s2, ei, src1->succs)
2080 basic_block d2 = s2->dest;
2081 if (FORWARDER_BLOCK_P (d2))
2082 d2 = single_succ (d2);
2083 if (d == d2)
2084 break;
2087 s->count += s2->count;
2089 /* Take care to update possible forwarder blocks. We verified
2090 that there is no more than one in the chain, so we can't run
2091 into infinite loop. */
2092 if (FORWARDER_BLOCK_P (s->dest))
2094 single_succ_edge (s->dest)->count += s2->count;
2095 s->dest->count += s2->count;
2096 s->dest->frequency += EDGE_FREQUENCY (s);
2099 if (FORWARDER_BLOCK_P (s2->dest))
2101 single_succ_edge (s2->dest)->count -= s2->count;
2102 if (single_succ_edge (s2->dest)->count < 0)
2103 single_succ_edge (s2->dest)->count = 0;
2104 s2->dest->count -= s2->count;
2105 s2->dest->frequency -= EDGE_FREQUENCY (s);
2106 if (s2->dest->frequency < 0)
2107 s2->dest->frequency = 0;
2108 if (s2->dest->count < 0)
2109 s2->dest->count = 0;
2112 if (!redirect_edges_to->frequency && !src1->frequency)
2113 s->probability = (s->probability + s2->probability) / 2;
2114 else
2115 s->probability
2116 = ((s->probability * redirect_edges_to->frequency +
2117 s2->probability * src1->frequency)
2118 / (redirect_edges_to->frequency + src1->frequency));
2121 /* Adjust count and frequency for the block. An earlier jump
2122 threading pass may have left the profile in an inconsistent
2123 state (see update_bb_profile_for_threading) so we must be
2124 prepared for overflows. */
2125 tmp = redirect_to;
2128 tmp->count += src1->count;
2129 tmp->frequency += src1->frequency;
2130 if (tmp->frequency > BB_FREQ_MAX)
2131 tmp->frequency = BB_FREQ_MAX;
2132 if (tmp == redirect_edges_to)
2133 break;
2134 tmp = find_fallthru_edge (tmp->succs)->dest;
2136 while (true);
2137 update_br_prob_note (redirect_edges_to);
2139 /* Edit SRC1 to go to REDIRECT_TO at NEWPOS1. */
2141 /* Skip possible basic block header. */
2142 if (LABEL_P (newpos1))
2143 newpos1 = NEXT_INSN (newpos1);
2145 while (DEBUG_INSN_P (newpos1))
2146 newpos1 = NEXT_INSN (newpos1);
2148 if (NOTE_INSN_BASIC_BLOCK_P (newpos1))
2149 newpos1 = NEXT_INSN (newpos1);
2151 while (DEBUG_INSN_P (newpos1))
2152 newpos1 = NEXT_INSN (newpos1);
2154 redirect_from = split_block (src1, PREV_INSN (newpos1))->src;
2155 to_remove = single_succ (redirect_from);
2157 redirect_edge_and_branch_force (single_succ_edge (redirect_from), redirect_to);
2158 delete_basic_block (to_remove);
2160 update_forwarder_flag (redirect_from);
2161 if (redirect_to != src2)
2162 update_forwarder_flag (src2);
2164 return true;
2167 /* Search the predecessors of BB for common insn sequences. When found,
2168 share code between them by redirecting control flow. Return true if
2169 any changes made. */
2171 static bool
2172 try_crossjump_bb (int mode, basic_block bb)
2174 edge e, e2, fallthru;
2175 bool changed;
2176 unsigned max, ix, ix2;
2178 /* Nothing to do if there is not at least two incoming edges. */
2179 if (EDGE_COUNT (bb->preds) < 2)
2180 return false;
2182 /* Don't crossjump if this block ends in a computed jump,
2183 unless we are optimizing for size. */
2184 if (optimize_bb_for_size_p (bb)
2185 && bb != EXIT_BLOCK_PTR_FOR_FN (cfun)
2186 && computed_jump_p (BB_END (bb)))
2187 return false;
2189 /* If we are partitioning hot/cold basic blocks, we don't want to
2190 mess up unconditional or indirect jumps that cross between hot
2191 and cold sections.
2193 Basic block partitioning may result in some jumps that appear to
2194 be optimizable (or blocks that appear to be mergeable), but which really
2195 must be left untouched (they are required to make it safely across
2196 partition boundaries). See the comments at the top of
2197 bb-reorder.c:partition_hot_cold_basic_blocks for complete details. */
2199 if (BB_PARTITION (EDGE_PRED (bb, 0)->src) !=
2200 BB_PARTITION (EDGE_PRED (bb, 1)->src)
2201 || (EDGE_PRED (bb, 0)->flags & EDGE_CROSSING))
2202 return false;
2204 /* It is always cheapest to redirect a block that ends in a branch to
2205 a block that falls through into BB, as that adds no branches to the
2206 program. We'll try that combination first. */
2207 fallthru = NULL;
2208 max = PARAM_VALUE (PARAM_MAX_CROSSJUMP_EDGES);
2210 if (EDGE_COUNT (bb->preds) > max)
2211 return false;
2213 fallthru = find_fallthru_edge (bb->preds);
2215 changed = false;
2216 for (ix = 0; ix < EDGE_COUNT (bb->preds);)
2218 e = EDGE_PRED (bb, ix);
2219 ix++;
2221 /* As noted above, first try with the fallthru predecessor (or, a
2222 fallthru predecessor if we are in cfglayout mode). */
2223 if (fallthru)
2225 /* Don't combine the fallthru edge into anything else.
2226 If there is a match, we'll do it the other way around. */
2227 if (e == fallthru)
2228 continue;
2229 /* If nothing changed since the last attempt, there is nothing
2230 we can do. */
2231 if (!first_pass
2232 && !((e->src->flags & BB_MODIFIED)
2233 || (fallthru->src->flags & BB_MODIFIED)))
2234 continue;
2236 if (try_crossjump_to_edge (mode, e, fallthru, dir_forward))
2238 changed = true;
2239 ix = 0;
2240 continue;
2244 /* Non-obvious work limiting check: Recognize that we're going
2245 to call try_crossjump_bb on every basic block. So if we have
2246 two blocks with lots of outgoing edges (a switch) and they
2247 share lots of common destinations, then we would do the
2248 cross-jump check once for each common destination.
2250 Now, if the blocks actually are cross-jump candidates, then
2251 all of their destinations will be shared. Which means that
2252 we only need check them for cross-jump candidacy once. We
2253 can eliminate redundant checks of crossjump(A,B) by arbitrarily
2254 choosing to do the check from the block for which the edge
2255 in question is the first successor of A. */
2256 if (EDGE_SUCC (e->src, 0) != e)
2257 continue;
2259 for (ix2 = 0; ix2 < EDGE_COUNT (bb->preds); ix2++)
2261 e2 = EDGE_PRED (bb, ix2);
2263 if (e2 == e)
2264 continue;
2266 /* We've already checked the fallthru edge above. */
2267 if (e2 == fallthru)
2268 continue;
2270 /* The "first successor" check above only prevents multiple
2271 checks of crossjump(A,B). In order to prevent redundant
2272 checks of crossjump(B,A), require that A be the block
2273 with the lowest index. */
2274 if (e->src->index > e2->src->index)
2275 continue;
2277 /* If nothing changed since the last attempt, there is nothing
2278 we can do. */
2279 if (!first_pass
2280 && !((e->src->flags & BB_MODIFIED)
2281 || (e2->src->flags & BB_MODIFIED)))
2282 continue;
2284 /* Both e and e2 are not fallthru edges, so we can crossjump in either
2285 direction. */
2286 if (try_crossjump_to_edge (mode, e, e2, dir_both))
2288 changed = true;
2289 ix = 0;
2290 break;
2295 if (changed)
2296 crossjumps_occured = true;
2298 return changed;
2301 /* Search the successors of BB for common insn sequences. When found,
2302 share code between them by moving it across the basic block
2303 boundary. Return true if any changes made. */
2305 static bool
2306 try_head_merge_bb (basic_block bb)
2308 basic_block final_dest_bb = NULL;
2309 int max_match = INT_MAX;
2310 edge e0;
2311 rtx_insn **headptr, **currptr, **nextptr;
2312 bool changed, moveall;
2313 unsigned ix;
2314 rtx_insn *e0_last_head;
2315 rtx cond;
2316 rtx_insn *move_before;
2317 unsigned nedges = EDGE_COUNT (bb->succs);
2318 rtx_insn *jump = BB_END (bb);
2319 regset live, live_union;
2321 /* Nothing to do if there is not at least two outgoing edges. */
2322 if (nedges < 2)
2323 return false;
2325 /* Don't crossjump if this block ends in a computed jump,
2326 unless we are optimizing for size. */
2327 if (optimize_bb_for_size_p (bb)
2328 && bb != EXIT_BLOCK_PTR_FOR_FN (cfun)
2329 && computed_jump_p (BB_END (bb)))
2330 return false;
2332 cond = get_condition (jump, &move_before, true, false);
2333 if (cond == NULL_RTX)
2335 if (HAVE_cc0 && reg_mentioned_p (cc0_rtx, jump))
2336 move_before = prev_nonnote_nondebug_insn (jump);
2337 else
2338 move_before = jump;
2341 for (ix = 0; ix < nedges; ix++)
2342 if (EDGE_SUCC (bb, ix)->dest == EXIT_BLOCK_PTR_FOR_FN (cfun))
2343 return false;
2345 for (ix = 0; ix < nedges; ix++)
2347 edge e = EDGE_SUCC (bb, ix);
2348 basic_block other_bb = e->dest;
2350 if (df_get_bb_dirty (other_bb))
2352 block_was_dirty = true;
2353 return false;
2356 if (e->flags & EDGE_ABNORMAL)
2357 return false;
2359 /* Normally, all destination blocks must only be reachable from this
2360 block, i.e. they must have one incoming edge.
2362 There is one special case we can handle, that of multiple consecutive
2363 jumps where the first jumps to one of the targets of the second jump.
2364 This happens frequently in switch statements for default labels.
2365 The structure is as follows:
2366 FINAL_DEST_BB
2367 ....
2368 if (cond) jump A;
2369 fall through
2371 jump with targets A, B, C, D...
2373 has two incoming edges, from FINAL_DEST_BB and BB
2375 In this case, we can try to move the insns through BB and into
2376 FINAL_DEST_BB. */
2377 if (EDGE_COUNT (other_bb->preds) != 1)
2379 edge incoming_edge, incoming_bb_other_edge;
2380 edge_iterator ei;
2382 if (final_dest_bb != NULL
2383 || EDGE_COUNT (other_bb->preds) != 2)
2384 return false;
2386 /* We must be able to move the insns across the whole block. */
2387 move_before = BB_HEAD (bb);
2388 while (!NONDEBUG_INSN_P (move_before))
2389 move_before = NEXT_INSN (move_before);
2391 if (EDGE_COUNT (bb->preds) != 1)
2392 return false;
2393 incoming_edge = EDGE_PRED (bb, 0);
2394 final_dest_bb = incoming_edge->src;
2395 if (EDGE_COUNT (final_dest_bb->succs) != 2)
2396 return false;
2397 FOR_EACH_EDGE (incoming_bb_other_edge, ei, final_dest_bb->succs)
2398 if (incoming_bb_other_edge != incoming_edge)
2399 break;
2400 if (incoming_bb_other_edge->dest != other_bb)
2401 return false;
2405 e0 = EDGE_SUCC (bb, 0);
2406 e0_last_head = NULL;
2407 changed = false;
2409 for (ix = 1; ix < nedges; ix++)
2411 edge e = EDGE_SUCC (bb, ix);
2412 rtx_insn *e0_last, *e_last;
2413 int nmatch;
2415 nmatch = flow_find_head_matching_sequence (e0->dest, e->dest,
2416 &e0_last, &e_last, 0);
2417 if (nmatch == 0)
2418 return false;
2420 if (nmatch < max_match)
2422 max_match = nmatch;
2423 e0_last_head = e0_last;
2427 /* If we matched an entire block, we probably have to avoid moving the
2428 last insn. */
2429 if (max_match > 0
2430 && e0_last_head == BB_END (e0->dest)
2431 && (find_reg_note (e0_last_head, REG_EH_REGION, 0)
2432 || control_flow_insn_p (e0_last_head)))
2434 max_match--;
2435 if (max_match == 0)
2436 return false;
2438 e0_last_head = prev_real_insn (e0_last_head);
2439 while (DEBUG_INSN_P (e0_last_head));
2442 if (max_match == 0)
2443 return false;
2445 /* We must find a union of the live registers at each of the end points. */
2446 live = BITMAP_ALLOC (NULL);
2447 live_union = BITMAP_ALLOC (NULL);
2449 currptr = XNEWVEC (rtx_insn *, nedges);
2450 headptr = XNEWVEC (rtx_insn *, nedges);
2451 nextptr = XNEWVEC (rtx_insn *, nedges);
2453 for (ix = 0; ix < nedges; ix++)
2455 int j;
2456 basic_block merge_bb = EDGE_SUCC (bb, ix)->dest;
2457 rtx_insn *head = BB_HEAD (merge_bb);
2459 while (!NONDEBUG_INSN_P (head))
2460 head = NEXT_INSN (head);
2461 headptr[ix] = head;
2462 currptr[ix] = head;
2464 /* Compute the end point and live information */
2465 for (j = 1; j < max_match; j++)
2467 head = NEXT_INSN (head);
2468 while (!NONDEBUG_INSN_P (head));
2469 simulate_backwards_to_point (merge_bb, live, head);
2470 IOR_REG_SET (live_union, live);
2473 /* If we're moving across two blocks, verify the validity of the
2474 first move, then adjust the target and let the loop below deal
2475 with the final move. */
2476 if (final_dest_bb != NULL)
2478 rtx_insn *move_upto;
2480 moveall = can_move_insns_across (currptr[0], e0_last_head, move_before,
2481 jump, e0->dest, live_union,
2482 NULL, &move_upto);
2483 if (!moveall)
2485 if (move_upto == NULL_RTX)
2486 goto out;
2488 while (e0_last_head != move_upto)
2490 df_simulate_one_insn_backwards (e0->dest, e0_last_head,
2491 live_union);
2492 e0_last_head = PREV_INSN (e0_last_head);
2495 if (e0_last_head == NULL_RTX)
2496 goto out;
2498 jump = BB_END (final_dest_bb);
2499 cond = get_condition (jump, &move_before, true, false);
2500 if (cond == NULL_RTX)
2502 if (HAVE_cc0 && reg_mentioned_p (cc0_rtx, jump))
2503 move_before = prev_nonnote_nondebug_insn (jump);
2504 else
2505 move_before = jump;
2511 rtx_insn *move_upto;
2512 moveall = can_move_insns_across (currptr[0], e0_last_head,
2513 move_before, jump, e0->dest, live_union,
2514 NULL, &move_upto);
2515 if (!moveall && move_upto == NULL_RTX)
2517 if (jump == move_before)
2518 break;
2520 /* Try again, using a different insertion point. */
2521 move_before = jump;
2523 /* Don't try moving before a cc0 user, as that may invalidate
2524 the cc0. */
2525 if (HAVE_cc0 && reg_mentioned_p (cc0_rtx, jump))
2526 break;
2528 continue;
2531 if (final_dest_bb && !moveall)
2532 /* We haven't checked whether a partial move would be OK for the first
2533 move, so we have to fail this case. */
2534 break;
2536 changed = true;
2537 for (;;)
2539 if (currptr[0] == move_upto)
2540 break;
2541 for (ix = 0; ix < nedges; ix++)
2543 rtx_insn *curr = currptr[ix];
2545 curr = NEXT_INSN (curr);
2546 while (!NONDEBUG_INSN_P (curr));
2547 currptr[ix] = curr;
2551 /* If we can't currently move all of the identical insns, remember
2552 each insn after the range that we'll merge. */
2553 if (!moveall)
2554 for (ix = 0; ix < nedges; ix++)
2556 rtx_insn *curr = currptr[ix];
2558 curr = NEXT_INSN (curr);
2559 while (!NONDEBUG_INSN_P (curr));
2560 nextptr[ix] = curr;
2563 reorder_insns (headptr[0], currptr[0], PREV_INSN (move_before));
2564 df_set_bb_dirty (EDGE_SUCC (bb, 0)->dest);
2565 if (final_dest_bb != NULL)
2566 df_set_bb_dirty (final_dest_bb);
2567 df_set_bb_dirty (bb);
2568 for (ix = 1; ix < nedges; ix++)
2570 df_set_bb_dirty (EDGE_SUCC (bb, ix)->dest);
2571 delete_insn_chain (headptr[ix], currptr[ix], false);
2573 if (!moveall)
2575 if (jump == move_before)
2576 break;
2578 /* For the unmerged insns, try a different insertion point. */
2579 move_before = jump;
2581 /* Don't try moving before a cc0 user, as that may invalidate
2582 the cc0. */
2583 if (HAVE_cc0 && reg_mentioned_p (cc0_rtx, jump))
2584 break;
2586 for (ix = 0; ix < nedges; ix++)
2587 currptr[ix] = headptr[ix] = nextptr[ix];
2590 while (!moveall);
2592 out:
2593 free (currptr);
2594 free (headptr);
2595 free (nextptr);
2597 crossjumps_occured |= changed;
2599 return changed;
2602 /* Return true if BB contains just bb note, or bb note followed
2603 by only DEBUG_INSNs. */
2605 static bool
2606 trivially_empty_bb_p (basic_block bb)
2608 rtx_insn *insn = BB_END (bb);
2610 while (1)
2612 if (insn == BB_HEAD (bb))
2613 return true;
2614 if (!DEBUG_INSN_P (insn))
2615 return false;
2616 insn = PREV_INSN (insn);
2620 /* Do simple CFG optimizations - basic block merging, simplifying of jump
2621 instructions etc. Return nonzero if changes were made. */
2623 static bool
2624 try_optimize_cfg (int mode)
2626 bool changed_overall = false;
2627 bool changed;
2628 int iterations = 0;
2629 basic_block bb, b, next;
2631 if (mode & (CLEANUP_CROSSJUMP | CLEANUP_THREADING))
2632 clear_bb_flags ();
2634 crossjumps_occured = false;
2636 FOR_EACH_BB_FN (bb, cfun)
2637 update_forwarder_flag (bb);
2639 if (! targetm.cannot_modify_jumps_p ())
2641 first_pass = true;
2642 /* Attempt to merge blocks as made possible by edge removal. If
2643 a block has only one successor, and the successor has only
2644 one predecessor, they may be combined. */
2647 block_was_dirty = false;
2648 changed = false;
2649 iterations++;
2651 if (dump_file)
2652 fprintf (dump_file,
2653 "\n\ntry_optimize_cfg iteration %i\n\n",
2654 iterations);
2656 for (b = ENTRY_BLOCK_PTR_FOR_FN (cfun)->next_bb; b
2657 != EXIT_BLOCK_PTR_FOR_FN (cfun);)
2659 basic_block c;
2660 edge s;
2661 bool changed_here = false;
2663 /* Delete trivially dead basic blocks. This is either
2664 blocks with no predecessors, or empty blocks with no
2665 successors. However if the empty block with no
2666 successors is the successor of the ENTRY_BLOCK, it is
2667 kept. This ensures that the ENTRY_BLOCK will have a
2668 successor which is a precondition for many RTL
2669 passes. Empty blocks may result from expanding
2670 __builtin_unreachable (). */
2671 if (EDGE_COUNT (b->preds) == 0
2672 || (EDGE_COUNT (b->succs) == 0
2673 && trivially_empty_bb_p (b)
2674 && single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun))->dest
2675 != b))
2677 c = b->prev_bb;
2678 if (EDGE_COUNT (b->preds) > 0)
2680 edge e;
2681 edge_iterator ei;
2683 if (current_ir_type () == IR_RTL_CFGLAYOUT)
2685 if (BB_FOOTER (b)
2686 && BARRIER_P (BB_FOOTER (b)))
2687 FOR_EACH_EDGE (e, ei, b->preds)
2688 if ((e->flags & EDGE_FALLTHRU)
2689 && BB_FOOTER (e->src) == NULL)
2691 if (BB_FOOTER (b))
2693 BB_FOOTER (e->src) = BB_FOOTER (b);
2694 BB_FOOTER (b) = NULL;
2696 else
2698 start_sequence ();
2699 BB_FOOTER (e->src) = emit_barrier ();
2700 end_sequence ();
2704 else
2706 rtx_insn *last = get_last_bb_insn (b);
2707 if (last && BARRIER_P (last))
2708 FOR_EACH_EDGE (e, ei, b->preds)
2709 if ((e->flags & EDGE_FALLTHRU))
2710 emit_barrier_after (BB_END (e->src));
2713 delete_basic_block (b);
2714 changed = true;
2715 /* Avoid trying to remove the exit block. */
2716 b = (c == ENTRY_BLOCK_PTR_FOR_FN (cfun) ? c->next_bb : c);
2717 continue;
2720 /* Remove code labels no longer used. */
2721 if (single_pred_p (b)
2722 && (single_pred_edge (b)->flags & EDGE_FALLTHRU)
2723 && !(single_pred_edge (b)->flags & EDGE_COMPLEX)
2724 && LABEL_P (BB_HEAD (b))
2725 && !LABEL_PRESERVE_P (BB_HEAD (b))
2726 /* If the previous block ends with a branch to this
2727 block, we can't delete the label. Normally this
2728 is a condjump that is yet to be simplified, but
2729 if CASE_DROPS_THRU, this can be a tablejump with
2730 some element going to the same place as the
2731 default (fallthru). */
2732 && (single_pred (b) == ENTRY_BLOCK_PTR_FOR_FN (cfun)
2733 || !JUMP_P (BB_END (single_pred (b)))
2734 || ! label_is_jump_target_p (BB_HEAD (b),
2735 BB_END (single_pred (b)))))
2737 delete_insn (BB_HEAD (b));
2738 if (dump_file)
2739 fprintf (dump_file, "Deleted label in block %i.\n",
2740 b->index);
2743 /* If we fall through an empty block, we can remove it. */
2744 if (!(mode & (CLEANUP_CFGLAYOUT | CLEANUP_NO_INSN_DEL))
2745 && single_pred_p (b)
2746 && (single_pred_edge (b)->flags & EDGE_FALLTHRU)
2747 && !LABEL_P (BB_HEAD (b))
2748 && FORWARDER_BLOCK_P (b)
2749 /* Note that forwarder_block_p true ensures that
2750 there is a successor for this block. */
2751 && (single_succ_edge (b)->flags & EDGE_FALLTHRU)
2752 && n_basic_blocks_for_fn (cfun) > NUM_FIXED_BLOCKS + 1)
2754 if (dump_file)
2755 fprintf (dump_file,
2756 "Deleting fallthru block %i.\n",
2757 b->index);
2759 c = ((b->prev_bb == ENTRY_BLOCK_PTR_FOR_FN (cfun))
2760 ? b->next_bb : b->prev_bb);
2761 redirect_edge_succ_nodup (single_pred_edge (b),
2762 single_succ (b));
2763 delete_basic_block (b);
2764 changed = true;
2765 b = c;
2766 continue;
2769 /* Merge B with its single successor, if any. */
2770 if (single_succ_p (b)
2771 && (s = single_succ_edge (b))
2772 && !(s->flags & EDGE_COMPLEX)
2773 && (c = s->dest) != EXIT_BLOCK_PTR_FOR_FN (cfun)
2774 && single_pred_p (c)
2775 && b != c)
2777 /* When not in cfg_layout mode use code aware of reordering
2778 INSN. This code possibly creates new basic blocks so it
2779 does not fit merge_blocks interface and is kept here in
2780 hope that it will become useless once more of compiler
2781 is transformed to use cfg_layout mode. */
2783 if ((mode & CLEANUP_CFGLAYOUT)
2784 && can_merge_blocks_p (b, c))
2786 merge_blocks (b, c);
2787 update_forwarder_flag (b);
2788 changed_here = true;
2790 else if (!(mode & CLEANUP_CFGLAYOUT)
2791 /* If the jump insn has side effects,
2792 we can't kill the edge. */
2793 && (!JUMP_P (BB_END (b))
2794 || (reload_completed
2795 ? simplejump_p (BB_END (b))
2796 : (onlyjump_p (BB_END (b))
2797 && !tablejump_p (BB_END (b),
2798 NULL, NULL))))
2799 && (next = merge_blocks_move (s, b, c, mode)))
2801 b = next;
2802 changed_here = true;
2806 /* Simplify branch over branch. */
2807 if ((mode & CLEANUP_EXPENSIVE)
2808 && !(mode & CLEANUP_CFGLAYOUT)
2809 && try_simplify_condjump (b))
2810 changed_here = true;
2812 /* If B has a single outgoing edge, but uses a
2813 non-trivial jump instruction without side-effects, we
2814 can either delete the jump entirely, or replace it
2815 with a simple unconditional jump. */
2816 if (single_succ_p (b)
2817 && single_succ (b) != EXIT_BLOCK_PTR_FOR_FN (cfun)
2818 && onlyjump_p (BB_END (b))
2819 && !CROSSING_JUMP_P (BB_END (b))
2820 && try_redirect_by_replacing_jump (single_succ_edge (b),
2821 single_succ (b),
2822 (mode & CLEANUP_CFGLAYOUT) != 0))
2824 update_forwarder_flag (b);
2825 changed_here = true;
2828 /* Simplify branch to branch. */
2829 if (try_forward_edges (mode, b))
2831 update_forwarder_flag (b);
2832 changed_here = true;
2835 /* Look for shared code between blocks. */
2836 if ((mode & CLEANUP_CROSSJUMP)
2837 && try_crossjump_bb (mode, b))
2838 changed_here = true;
2840 if ((mode & CLEANUP_CROSSJUMP)
2841 /* This can lengthen register lifetimes. Do it only after
2842 reload. */
2843 && reload_completed
2844 && try_head_merge_bb (b))
2845 changed_here = true;
2847 /* Don't get confused by the index shift caused by
2848 deleting blocks. */
2849 if (!changed_here)
2850 b = b->next_bb;
2851 else
2852 changed = true;
2855 if ((mode & CLEANUP_CROSSJUMP)
2856 && try_crossjump_bb (mode, EXIT_BLOCK_PTR_FOR_FN (cfun)))
2857 changed = true;
2859 if (block_was_dirty)
2861 /* This should only be set by head-merging. */
2862 gcc_assert (mode & CLEANUP_CROSSJUMP);
2863 df_analyze ();
2866 if (changed)
2868 /* Edge forwarding in particular can cause hot blocks previously
2869 reached by both hot and cold blocks to become dominated only
2870 by cold blocks. This will cause the verification below to fail,
2871 and lead to now cold code in the hot section. This is not easy
2872 to detect and fix during edge forwarding, and in some cases
2873 is only visible after newly unreachable blocks are deleted,
2874 which will be done in fixup_partitions. */
2875 fixup_partitions ();
2877 #ifdef ENABLE_CHECKING
2878 verify_flow_info ();
2879 #endif
2882 changed_overall |= changed;
2883 first_pass = false;
2885 while (changed);
2888 FOR_ALL_BB_FN (b, cfun)
2889 b->flags &= ~(BB_FORWARDER_BLOCK | BB_NONTHREADABLE_BLOCK);
2891 return changed_overall;
2894 /* Delete all unreachable basic blocks. */
2896 bool
2897 delete_unreachable_blocks (void)
2899 bool changed = false;
2900 basic_block b, prev_bb;
2902 find_unreachable_blocks ();
2904 /* When we're in GIMPLE mode and there may be debug insns, we should
2905 delete blocks in reverse dominator order, so as to get a chance
2906 to substitute all released DEFs into debug stmts. If we don't
2907 have dominators information, walking blocks backward gets us a
2908 better chance of retaining most debug information than
2909 otherwise. */
2910 if (MAY_HAVE_DEBUG_INSNS && current_ir_type () == IR_GIMPLE
2911 && dom_info_available_p (CDI_DOMINATORS))
2913 for (b = EXIT_BLOCK_PTR_FOR_FN (cfun)->prev_bb;
2914 b != ENTRY_BLOCK_PTR_FOR_FN (cfun); b = prev_bb)
2916 prev_bb = b->prev_bb;
2918 if (!(b->flags & BB_REACHABLE))
2920 /* Speed up the removal of blocks that don't dominate
2921 others. Walking backwards, this should be the common
2922 case. */
2923 if (!first_dom_son (CDI_DOMINATORS, b))
2924 delete_basic_block (b);
2925 else
2927 vec<basic_block> h
2928 = get_all_dominated_blocks (CDI_DOMINATORS, b);
2930 while (h.length ())
2932 b = h.pop ();
2934 prev_bb = b->prev_bb;
2936 gcc_assert (!(b->flags & BB_REACHABLE));
2938 delete_basic_block (b);
2941 h.release ();
2944 changed = true;
2948 else
2950 for (b = EXIT_BLOCK_PTR_FOR_FN (cfun)->prev_bb;
2951 b != ENTRY_BLOCK_PTR_FOR_FN (cfun); b = prev_bb)
2953 prev_bb = b->prev_bb;
2955 if (!(b->flags & BB_REACHABLE))
2957 delete_basic_block (b);
2958 changed = true;
2963 if (changed)
2964 tidy_fallthru_edges ();
2965 return changed;
2968 /* Delete any jump tables never referenced. We can't delete them at the
2969 time of removing tablejump insn as they are referenced by the preceding
2970 insns computing the destination, so we delay deleting and garbagecollect
2971 them once life information is computed. */
2972 void
2973 delete_dead_jumptables (void)
2975 basic_block bb;
2977 /* A dead jump table does not belong to any basic block. Scan insns
2978 between two adjacent basic blocks. */
2979 FOR_EACH_BB_FN (bb, cfun)
2981 rtx_insn *insn, *next;
2983 for (insn = NEXT_INSN (BB_END (bb));
2984 insn && !NOTE_INSN_BASIC_BLOCK_P (insn);
2985 insn = next)
2987 next = NEXT_INSN (insn);
2988 if (LABEL_P (insn)
2989 && LABEL_NUSES (insn) == LABEL_PRESERVE_P (insn)
2990 && JUMP_TABLE_DATA_P (next))
2992 rtx_insn *label = insn, *jump = next;
2994 if (dump_file)
2995 fprintf (dump_file, "Dead jumptable %i removed\n",
2996 INSN_UID (insn));
2998 next = NEXT_INSN (next);
2999 delete_insn (jump);
3000 delete_insn (label);
3007 /* Tidy the CFG by deleting unreachable code and whatnot. */
3009 bool
3010 cleanup_cfg (int mode)
3012 bool changed = false;
3014 /* Set the cfglayout mode flag here. We could update all the callers
3015 but that is just inconvenient, especially given that we eventually
3016 want to have cfglayout mode as the default. */
3017 if (current_ir_type () == IR_RTL_CFGLAYOUT)
3018 mode |= CLEANUP_CFGLAYOUT;
3020 timevar_push (TV_CLEANUP_CFG);
3021 if (delete_unreachable_blocks ())
3023 changed = true;
3024 /* We've possibly created trivially dead code. Cleanup it right
3025 now to introduce more opportunities for try_optimize_cfg. */
3026 if (!(mode & (CLEANUP_NO_INSN_DEL))
3027 && !reload_completed)
3028 delete_trivially_dead_insns (get_insns (), max_reg_num ());
3031 compact_blocks ();
3033 /* To tail-merge blocks ending in the same noreturn function (e.g.
3034 a call to abort) we have to insert fake edges to exit. Do this
3035 here once. The fake edges do not interfere with any other CFG
3036 cleanups. */
3037 if (mode & CLEANUP_CROSSJUMP)
3038 add_noreturn_fake_exit_edges ();
3040 if (!dbg_cnt (cfg_cleanup))
3041 return changed;
3043 while (try_optimize_cfg (mode))
3045 delete_unreachable_blocks (), changed = true;
3046 if (!(mode & CLEANUP_NO_INSN_DEL))
3048 /* Try to remove some trivially dead insns when doing an expensive
3049 cleanup. But delete_trivially_dead_insns doesn't work after
3050 reload (it only handles pseudos) and run_fast_dce is too costly
3051 to run in every iteration.
3053 For effective cross jumping, we really want to run a fast DCE to
3054 clean up any dead conditions, or they get in the way of performing
3055 useful tail merges.
3057 Other transformations in cleanup_cfg are not so sensitive to dead
3058 code, so delete_trivially_dead_insns or even doing nothing at all
3059 is good enough. */
3060 if ((mode & CLEANUP_EXPENSIVE) && !reload_completed
3061 && !delete_trivially_dead_insns (get_insns (), max_reg_num ()))
3062 break;
3063 if ((mode & CLEANUP_CROSSJUMP) && crossjumps_occured)
3064 run_fast_dce ();
3066 else
3067 break;
3070 if (mode & CLEANUP_CROSSJUMP)
3071 remove_fake_exit_edges ();
3073 /* Don't call delete_dead_jumptables in cfglayout mode, because
3074 that function assumes that jump tables are in the insns stream.
3075 But we also don't _have_ to delete dead jumptables in cfglayout
3076 mode because we shouldn't even be looking at things that are
3077 not in a basic block. Dead jumptables are cleaned up when
3078 going out of cfglayout mode. */
3079 if (!(mode & CLEANUP_CFGLAYOUT))
3080 delete_dead_jumptables ();
3082 /* ??? We probably do this way too often. */
3083 if (current_loops
3084 && (changed
3085 || (mode & CLEANUP_CFG_CHANGED)))
3087 timevar_push (TV_REPAIR_LOOPS);
3088 /* The above doesn't preserve dominance info if available. */
3089 gcc_assert (!dom_info_available_p (CDI_DOMINATORS));
3090 calculate_dominance_info (CDI_DOMINATORS);
3091 fix_loop_structure (NULL);
3092 free_dominance_info (CDI_DOMINATORS);
3093 timevar_pop (TV_REPAIR_LOOPS);
3096 timevar_pop (TV_CLEANUP_CFG);
3098 return changed;
3101 namespace {
3103 const pass_data pass_data_jump =
3105 RTL_PASS, /* type */
3106 "jump", /* name */
3107 OPTGROUP_NONE, /* optinfo_flags */
3108 TV_JUMP, /* tv_id */
3109 0, /* properties_required */
3110 0, /* properties_provided */
3111 0, /* properties_destroyed */
3112 0, /* todo_flags_start */
3113 0, /* todo_flags_finish */
3116 class pass_jump : public rtl_opt_pass
3118 public:
3119 pass_jump (gcc::context *ctxt)
3120 : rtl_opt_pass (pass_data_jump, ctxt)
3123 /* opt_pass methods: */
3124 virtual unsigned int execute (function *);
3126 }; // class pass_jump
3128 unsigned int
3129 pass_jump::execute (function *)
3131 delete_trivially_dead_insns (get_insns (), max_reg_num ());
3132 if (dump_file)
3133 dump_flow_info (dump_file, dump_flags);
3134 cleanup_cfg ((optimize ? CLEANUP_EXPENSIVE : 0)
3135 | (flag_thread_jumps ? CLEANUP_THREADING : 0));
3136 return 0;
3139 } // anon namespace
3141 rtl_opt_pass *
3142 make_pass_jump (gcc::context *ctxt)
3144 return new pass_jump (ctxt);
3147 namespace {
3149 const pass_data pass_data_jump2 =
3151 RTL_PASS, /* type */
3152 "jump2", /* name */
3153 OPTGROUP_NONE, /* optinfo_flags */
3154 TV_JUMP, /* tv_id */
3155 0, /* properties_required */
3156 0, /* properties_provided */
3157 0, /* properties_destroyed */
3158 0, /* todo_flags_start */
3159 0, /* todo_flags_finish */
3162 class pass_jump2 : public rtl_opt_pass
3164 public:
3165 pass_jump2 (gcc::context *ctxt)
3166 : rtl_opt_pass (pass_data_jump2, ctxt)
3169 /* opt_pass methods: */
3170 virtual unsigned int execute (function *)
3172 cleanup_cfg (flag_crossjumping ? CLEANUP_CROSSJUMP : 0);
3173 return 0;
3176 }; // class pass_jump2
3178 } // anon namespace
3180 rtl_opt_pass *
3181 make_pass_jump2 (gcc::context *ctxt)
3183 return new pass_jump2 (ctxt);