Merge branch 'master' r216746-r217593 into gimple-classes-v2-option-3
[official-gcc.git] / gcc / tree-ssa-threadupdate.c
blob97748cb66a397d06e63efb16551c0cf1fd4cf566
1 /* Thread edges through blocks and update the control flow and SSA graphs.
2 Copyright (C) 2004-2014 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
9 any later version.
11 GCC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License 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 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "tree.h"
24 #include "flags.h"
25 #include "predict.h"
26 #include "vec.h"
27 #include "hashtab.h"
28 #include "hash-set.h"
29 #include "machmode.h"
30 #include "tm.h"
31 #include "hard-reg-set.h"
32 #include "input.h"
33 #include "function.h"
34 #include "dominance.h"
35 #include "cfg.h"
36 #include "cfganal.h"
37 #include "basic-block.h"
38 #include "hash-table.h"
39 #include "tree-ssa-alias.h"
40 #include "internal-fn.h"
41 #include "gimple-expr.h"
42 #include "is-a.h"
43 #include "gimple.h"
44 #include "gimple-iterator.h"
45 #include "gimple-ssa.h"
46 #include "tree-phinodes.h"
47 #include "tree-ssa.h"
48 #include "tree-ssa-threadupdate.h"
49 #include "ssa-iterators.h"
50 #include "dumpfile.h"
51 #include "cfgloop.h"
52 #include "dbgcnt.h"
53 #include "tree-cfg.h"
54 #include "tree-pass.h"
56 /* Given a block B, update the CFG and SSA graph to reflect redirecting
57 one or more in-edges to B to instead reach the destination of an
58 out-edge from B while preserving any side effects in B.
60 i.e., given A->B and B->C, change A->B to be A->C yet still preserve the
61 side effects of executing B.
63 1. Make a copy of B (including its outgoing edges and statements). Call
64 the copy B'. Note B' has no incoming edges or PHIs at this time.
66 2. Remove the control statement at the end of B' and all outgoing edges
67 except B'->C.
69 3. Add a new argument to each PHI in C with the same value as the existing
70 argument associated with edge B->C. Associate the new PHI arguments
71 with the edge B'->C.
73 4. For each PHI in B, find or create a PHI in B' with an identical
74 PHI_RESULT. Add an argument to the PHI in B' which has the same
75 value as the PHI in B associated with the edge A->B. Associate
76 the new argument in the PHI in B' with the edge A->B.
78 5. Change the edge A->B to A->B'.
80 5a. This automatically deletes any PHI arguments associated with the
81 edge A->B in B.
83 5b. This automatically associates each new argument added in step 4
84 with the edge A->B'.
86 6. Repeat for other incoming edges into B.
88 7. Put the duplicated resources in B and all the B' blocks into SSA form.
90 Note that block duplication can be minimized by first collecting the
91 set of unique destination blocks that the incoming edges should
92 be threaded to.
94 We reduce the number of edges and statements we create by not copying all
95 the outgoing edges and the control statement in step #1. We instead create
96 a template block without the outgoing edges and duplicate the template.
98 Another case this code handles is threading through a "joiner" block. In
99 this case, we do not know the destination of the joiner block, but one
100 of the outgoing edges from the joiner block leads to a threadable path. This
101 case largely works as outlined above, except the duplicate of the joiner
102 block still contains a full set of outgoing edges and its control statement.
103 We just redirect one of its outgoing edges to our jump threading path. */
106 /* Steps #5 and #6 of the above algorithm are best implemented by walking
107 all the incoming edges which thread to the same destination edge at
108 the same time. That avoids lots of table lookups to get information
109 for the destination edge.
111 To realize that implementation we create a list of incoming edges
112 which thread to the same outgoing edge. Thus to implement steps
113 #5 and #6 we traverse our hash table of outgoing edge information.
114 For each entry we walk the list of incoming edges which thread to
115 the current outgoing edge. */
117 struct el
119 edge e;
120 struct el *next;
123 /* Main data structure recording information regarding B's duplicate
124 blocks. */
126 /* We need to efficiently record the unique thread destinations of this
127 block and specific information associated with those destinations. We
128 may have many incoming edges threaded to the same outgoing edge. This
129 can be naturally implemented with a hash table. */
131 struct redirection_data : typed_free_remove<redirection_data>
133 /* We support wiring up two block duplicates in a jump threading path.
135 One is a normal block copy where we remove the control statement
136 and wire up its single remaining outgoing edge to the thread path.
138 The other is a joiner block where we leave the control statement
139 in place, but wire one of the outgoing edges to a thread path.
141 In theory we could have multiple block duplicates in a jump
142 threading path, but I haven't tried that.
144 The duplicate blocks appear in this array in the same order in
145 which they appear in the jump thread path. */
146 basic_block dup_blocks[2];
148 /* The jump threading path. */
149 vec<jump_thread_edge *> *path;
151 /* A list of incoming edges which we want to thread to the
152 same path. */
153 struct el *incoming_edges;
155 /* hash_table support. */
156 typedef redirection_data value_type;
157 typedef redirection_data compare_type;
158 static inline hashval_t hash (const value_type *);
159 static inline int equal (const value_type *, const compare_type *);
162 /* Dump a jump threading path, including annotations about each
163 edge in the path. */
165 static void
166 dump_jump_thread_path (FILE *dump_file, vec<jump_thread_edge *> path,
167 bool registering)
169 fprintf (dump_file,
170 " %s jump thread: (%d, %d) incoming edge; ",
171 (registering ? "Registering" : "Cancelling"),
172 path[0]->e->src->index, path[0]->e->dest->index);
174 for (unsigned int i = 1; i < path.length (); i++)
176 /* We can get paths with a NULL edge when the final destination
177 of a jump thread turns out to be a constant address. We dump
178 those paths when debugging, so we have to be prepared for that
179 possibility here. */
180 if (path[i]->e == NULL)
181 continue;
183 if (path[i]->type == EDGE_COPY_SRC_JOINER_BLOCK)
184 fprintf (dump_file, " (%d, %d) joiner; ",
185 path[i]->e->src->index, path[i]->e->dest->index);
186 if (path[i]->type == EDGE_COPY_SRC_BLOCK)
187 fprintf (dump_file, " (%d, %d) normal;",
188 path[i]->e->src->index, path[i]->e->dest->index);
189 if (path[i]->type == EDGE_NO_COPY_SRC_BLOCK)
190 fprintf (dump_file, " (%d, %d) nocopy;",
191 path[i]->e->src->index, path[i]->e->dest->index);
193 fputc ('\n', dump_file);
196 /* Simple hashing function. For any given incoming edge E, we're going
197 to be most concerned with the final destination of its jump thread
198 path. So hash on the block index of the final edge in the path. */
200 inline hashval_t
201 redirection_data::hash (const value_type *p)
203 vec<jump_thread_edge *> *path = p->path;
204 return path->last ()->e->dest->index;
207 /* Given two hash table entries, return true if they have the same
208 jump threading path. */
209 inline int
210 redirection_data::equal (const value_type *p1, const compare_type *p2)
212 vec<jump_thread_edge *> *path1 = p1->path;
213 vec<jump_thread_edge *> *path2 = p2->path;
215 if (path1->length () != path2->length ())
216 return false;
218 for (unsigned int i = 1; i < path1->length (); i++)
220 if ((*path1)[i]->type != (*path2)[i]->type
221 || (*path1)[i]->e != (*path2)[i]->e)
222 return false;
225 return true;
228 /* Data structure of information to pass to hash table traversal routines. */
229 struct ssa_local_info_t
231 /* The current block we are working on. */
232 basic_block bb;
234 /* We only create a template block for the first duplicated block in a
235 jump threading path as we may need many duplicates of that block.
237 The second duplicate block in a path is specific to that path. Creating
238 and sharing a template for that block is considerably more difficult. */
239 basic_block template_block;
241 /* TRUE if we thread one or more jumps, FALSE otherwise. */
242 bool jumps_threaded;
244 /* Blocks duplicated for the thread. */
245 bitmap duplicate_blocks;
248 /* Passes which use the jump threading code register jump threading
249 opportunities as they are discovered. We keep the registered
250 jump threading opportunities in this vector as edge pairs
251 (original_edge, target_edge). */
252 static vec<vec<jump_thread_edge *> *> paths;
254 /* When we start updating the CFG for threading, data necessary for jump
255 threading is attached to the AUX field for the incoming edge. Use these
256 macros to access the underlying structure attached to the AUX field. */
257 #define THREAD_PATH(E) ((vec<jump_thread_edge *> *)(E)->aux)
259 /* Jump threading statistics. */
261 struct thread_stats_d
263 unsigned long num_threaded_edges;
266 struct thread_stats_d thread_stats;
269 /* Remove the last statement in block BB if it is a control statement
270 Also remove all outgoing edges except the edge which reaches DEST_BB.
271 If DEST_BB is NULL, then remove all outgoing edges. */
273 static void
274 remove_ctrl_stmt_and_useless_edges (basic_block bb, basic_block dest_bb)
276 gimple_stmt_iterator gsi;
277 edge e;
278 edge_iterator ei;
280 gsi = gsi_last_bb (bb);
282 /* If the duplicate ends with a control statement, then remove it.
284 Note that if we are duplicating the template block rather than the
285 original basic block, then the duplicate might not have any real
286 statements in it. */
287 if (!gsi_end_p (gsi)
288 && gsi_stmt (gsi)
289 && (gimple_code (gsi_stmt (gsi)) == GIMPLE_COND
290 || gimple_code (gsi_stmt (gsi)) == GIMPLE_GOTO
291 || gimple_code (gsi_stmt (gsi)) == GIMPLE_SWITCH))
292 gsi_remove (&gsi, true);
294 for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
296 if (e->dest != dest_bb)
297 remove_edge (e);
298 else
299 ei_next (&ei);
303 /* Create a duplicate of BB. Record the duplicate block in an array
304 indexed by COUNT stored in RD. */
306 static void
307 create_block_for_threading (basic_block bb,
308 struct redirection_data *rd,
309 unsigned int count,
310 bitmap *duplicate_blocks)
312 edge_iterator ei;
313 edge e;
315 /* We can use the generic block duplication code and simply remove
316 the stuff we do not need. */
317 rd->dup_blocks[count] = duplicate_block (bb, NULL, NULL);
319 FOR_EACH_EDGE (e, ei, rd->dup_blocks[count]->succs)
320 e->aux = NULL;
322 /* Zero out the profile, since the block is unreachable for now. */
323 rd->dup_blocks[count]->frequency = 0;
324 rd->dup_blocks[count]->count = 0;
325 if (duplicate_blocks)
326 bitmap_set_bit (*duplicate_blocks, rd->dup_blocks[count]->index);
329 /* Main data structure to hold information for duplicates of BB. */
331 static hash_table<redirection_data> *redirection_data;
333 /* Given an outgoing edge E lookup and return its entry in our hash table.
335 If INSERT is true, then we insert the entry into the hash table if
336 it is not already present. INCOMING_EDGE is added to the list of incoming
337 edges associated with E in the hash table. */
339 static struct redirection_data *
340 lookup_redirection_data (edge e, enum insert_option insert)
342 struct redirection_data **slot;
343 struct redirection_data *elt;
344 vec<jump_thread_edge *> *path = THREAD_PATH (e);
346 /* Build a hash table element so we can see if E is already
347 in the table. */
348 elt = XNEW (struct redirection_data);
349 elt->path = path;
350 elt->dup_blocks[0] = NULL;
351 elt->dup_blocks[1] = NULL;
352 elt->incoming_edges = NULL;
354 slot = redirection_data->find_slot (elt, insert);
356 /* This will only happen if INSERT is false and the entry is not
357 in the hash table. */
358 if (slot == NULL)
360 free (elt);
361 return NULL;
364 /* This will only happen if E was not in the hash table and
365 INSERT is true. */
366 if (*slot == NULL)
368 *slot = elt;
369 elt->incoming_edges = XNEW (struct el);
370 elt->incoming_edges->e = e;
371 elt->incoming_edges->next = NULL;
372 return elt;
374 /* E was in the hash table. */
375 else
377 /* Free ELT as we do not need it anymore, we will extract the
378 relevant entry from the hash table itself. */
379 free (elt);
381 /* Get the entry stored in the hash table. */
382 elt = *slot;
384 /* If insertion was requested, then we need to add INCOMING_EDGE
385 to the list of incoming edges associated with E. */
386 if (insert)
388 struct el *el = XNEW (struct el);
389 el->next = elt->incoming_edges;
390 el->e = e;
391 elt->incoming_edges = el;
394 return elt;
398 /* Similar to copy_phi_args, except that the PHI arg exists, it just
399 does not have a value associated with it. */
401 static void
402 copy_phi_arg_into_existing_phi (edge src_e, edge tgt_e)
404 int src_idx = src_e->dest_idx;
405 int tgt_idx = tgt_e->dest_idx;
407 /* Iterate over each PHI in e->dest. */
408 for (gphi_iterator gsi = gsi_start_phis (src_e->dest),
409 gsi2 = gsi_start_phis (tgt_e->dest);
410 !gsi_end_p (gsi);
411 gsi_next (&gsi), gsi_next (&gsi2))
413 gphi *src_phi = gsi.phi ();
414 gphi *dest_phi = gsi2.phi ();
415 tree val = gimple_phi_arg_def (src_phi, src_idx);
416 source_location locus = gimple_phi_arg_location (src_phi, src_idx);
418 SET_PHI_ARG_DEF (dest_phi, tgt_idx, val);
419 gimple_phi_arg_set_location (dest_phi, tgt_idx, locus);
423 /* Given ssa_name DEF, backtrack jump threading PATH from node IDX
424 to see if it has constant value in a flow sensitive manner. Set
425 LOCUS to location of the constant phi arg and return the value.
426 Return DEF directly if either PATH or idx is ZERO. */
428 static tree
429 get_value_locus_in_path (tree def, vec<jump_thread_edge *> *path,
430 basic_block bb, int idx, source_location *locus)
432 tree arg;
433 gphi *def_phi;
434 basic_block def_bb;
436 if (path == NULL || idx == 0)
437 return def;
439 def_phi = dyn_cast <gphi *> (SSA_NAME_DEF_STMT (def));
440 if (!def_phi)
441 return def;
443 def_bb = gimple_bb (def_phi);
444 /* Don't propagate loop invariants into deeper loops. */
445 if (!def_bb || bb_loop_depth (def_bb) < bb_loop_depth (bb))
446 return def;
448 /* Backtrack jump threading path from IDX to see if def has constant
449 value. */
450 for (int j = idx - 1; j >= 0; j--)
452 edge e = (*path)[j]->e;
453 if (e->dest == def_bb)
455 arg = gimple_phi_arg_def (def_phi, e->dest_idx);
456 if (is_gimple_min_invariant (arg))
458 *locus = gimple_phi_arg_location (def_phi, e->dest_idx);
459 return arg;
461 break;
465 return def;
468 /* For each PHI in BB, copy the argument associated with SRC_E to TGT_E.
469 Try to backtrack jump threading PATH from node IDX to see if the arg
470 has constant value, copy constant value instead of argument itself
471 if yes. */
473 static void
474 copy_phi_args (basic_block bb, edge src_e, edge tgt_e,
475 vec<jump_thread_edge *> *path, int idx)
477 gphi_iterator gsi;
478 int src_indx = src_e->dest_idx;
480 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
482 gphi *phi = gsi.phi ();
483 tree def = gimple_phi_arg_def (phi, src_indx);
484 source_location locus = gimple_phi_arg_location (phi, src_indx);
486 if (TREE_CODE (def) == SSA_NAME
487 && !virtual_operand_p (gimple_phi_result (phi)))
488 def = get_value_locus_in_path (def, path, bb, idx, &locus);
490 add_phi_arg (phi, def, tgt_e, locus);
494 /* We have recently made a copy of ORIG_BB, including its outgoing
495 edges. The copy is NEW_BB. Every PHI node in every direct successor of
496 ORIG_BB has a new argument associated with edge from NEW_BB to the
497 successor. Initialize the PHI argument so that it is equal to the PHI
498 argument associated with the edge from ORIG_BB to the successor.
499 PATH and IDX are used to check if the new PHI argument has constant
500 value in a flow sensitive manner. */
502 static void
503 update_destination_phis (basic_block orig_bb, basic_block new_bb,
504 vec<jump_thread_edge *> *path, int idx)
506 edge_iterator ei;
507 edge e;
509 FOR_EACH_EDGE (e, ei, orig_bb->succs)
511 edge e2 = find_edge (new_bb, e->dest);
512 copy_phi_args (e->dest, e, e2, path, idx);
516 /* Given a duplicate block and its single destination (both stored
517 in RD). Create an edge between the duplicate and its single
518 destination.
520 Add an additional argument to any PHI nodes at the single
521 destination. IDX is the start node in jump threading path
522 we start to check to see if the new PHI argument has constant
523 value along the jump threading path. */
525 static void
526 create_edge_and_update_destination_phis (struct redirection_data *rd,
527 basic_block bb, int idx)
529 edge e = make_edge (bb, rd->path->last ()->e->dest, EDGE_FALLTHRU);
531 rescan_loop_exit (e, true, false);
532 e->probability = REG_BR_PROB_BASE;
533 e->count = bb->count;
535 /* We used to copy the thread path here. That was added in 2007
536 and dutifully updated through the representation changes in 2013.
538 In 2013 we added code to thread from an interior node through
539 the backedge to another interior node. That runs after the code
540 to thread through loop headers from outside the loop.
542 The latter may delete edges in the CFG, including those
543 which appeared in the jump threading path we copied here. Thus
544 we'd end up using a dangling pointer.
546 After reviewing the 2007/2011 code, I can't see how anything
547 depended on copying the AUX field and clearly copying the jump
548 threading path is problematical due to embedded edge pointers.
549 It has been removed. */
550 e->aux = NULL;
552 /* If there are any PHI nodes at the destination of the outgoing edge
553 from the duplicate block, then we will need to add a new argument
554 to them. The argument should have the same value as the argument
555 associated with the outgoing edge stored in RD. */
556 copy_phi_args (e->dest, rd->path->last ()->e, e, rd->path, idx);
559 /* Look through PATH beginning at START and return TRUE if there are
560 any additional blocks that need to be duplicated. Otherwise,
561 return FALSE. */
562 static bool
563 any_remaining_duplicated_blocks (vec<jump_thread_edge *> *path,
564 unsigned int start)
566 for (unsigned int i = start + 1; i < path->length (); i++)
568 if ((*path)[i]->type == EDGE_COPY_SRC_JOINER_BLOCK
569 || (*path)[i]->type == EDGE_COPY_SRC_BLOCK)
570 return true;
572 return false;
576 /* Compute the amount of profile count/frequency coming into the jump threading
577 path stored in RD that we are duplicating, returned in PATH_IN_COUNT_PTR and
578 PATH_IN_FREQ_PTR, as well as the amount of counts flowing out of the
579 duplicated path, returned in PATH_OUT_COUNT_PTR. LOCAL_INFO is used to
580 identify blocks duplicated for jump threading, which have duplicated
581 edges that need to be ignored in the analysis. Return true if path contains
582 a joiner, false otherwise.
584 In the non-joiner case, this is straightforward - all the counts/frequency
585 flowing into the jump threading path should flow through the duplicated
586 block and out of the duplicated path.
588 In the joiner case, it is very tricky. Some of the counts flowing into
589 the original path go offpath at the joiner. The problem is that while
590 we know how much total count goes off-path in the original control flow,
591 we don't know how many of the counts corresponding to just the jump
592 threading path go offpath at the joiner.
594 For example, assume we have the following control flow and identified
595 jump threading paths:
597 A B C
598 \ | /
599 Ea \ |Eb / Ec
600 \ | /
601 v v v
602 J <-- Joiner
604 Eoff/ \Eon
607 Soff Son <--- Normal
609 Ed/ \ Ee
614 Jump threading paths: A -> J -> Son -> D (path 1)
615 C -> J -> Son -> E (path 2)
617 Note that the control flow could be more complicated:
618 - Each jump threading path may have more than one incoming edge. I.e. A and
619 Ea could represent multiple incoming blocks/edges that are included in
620 path 1.
621 - There could be EDGE_NO_COPY_SRC_BLOCK edges after the joiner (either
622 before or after the "normal" copy block). These are not duplicated onto
623 the jump threading path, as they are single-successor.
624 - Any of the blocks along the path may have other incoming edges that
625 are not part of any jump threading path, but add profile counts along
626 the path.
628 In the aboe example, after all jump threading is complete, we will
629 end up with the following control flow:
631 A B C
632 | | |
633 Ea| |Eb |Ec
634 | | |
635 v v v
636 Ja J Jc
637 / \ / \Eon' / \
638 Eona/ \ ---/---\-------- \Eonc
639 / \ / / \ \
640 v v v v v
641 Sona Soff Son Sonc
642 \ /\ /
643 \___________ / \ _____/
644 \ / \/
645 vv v
648 The main issue to notice here is that when we are processing path 1
649 (A->J->Son->D) we need to figure out the outgoing edge weights to
650 the duplicated edges Ja->Sona and Ja->Soff, while ensuring that the
651 sum of the incoming weights to D remain Ed. The problem with simply
652 assuming that Ja (and Jc when processing path 2) has the same outgoing
653 probabilities to its successors as the original block J, is that after
654 all paths are processed and other edges/counts removed (e.g. none
655 of Ec will reach D after processing path 2), we may end up with not
656 enough count flowing along duplicated edge Sona->D.
658 Therefore, in the case of a joiner, we keep track of all counts
659 coming in along the current path, as well as from predecessors not
660 on any jump threading path (Eb in the above example). While we
661 first assume that the duplicated Eona for Ja->Sona has the same
662 probability as the original, we later compensate for other jump
663 threading paths that may eliminate edges. We do that by keep track
664 of all counts coming into the original path that are not in a jump
665 thread (Eb in the above example, but as noted earlier, there could
666 be other predecessors incoming to the path at various points, such
667 as at Son). Call this cumulative non-path count coming into the path
668 before D as Enonpath. We then ensure that the count from Sona->D is as at
669 least as big as (Ed - Enonpath), but no bigger than the minimum
670 weight along the jump threading path. The probabilities of both the
671 original and duplicated joiner block J and Ja will be adjusted
672 accordingly after the updates. */
674 static bool
675 compute_path_counts (struct redirection_data *rd,
676 ssa_local_info_t *local_info,
677 gcov_type *path_in_count_ptr,
678 gcov_type *path_out_count_ptr,
679 int *path_in_freq_ptr)
681 edge e = rd->incoming_edges->e;
682 vec<jump_thread_edge *> *path = THREAD_PATH (e);
683 edge elast = path->last ()->e;
684 gcov_type nonpath_count = 0;
685 bool has_joiner = false;
686 gcov_type path_in_count = 0;
687 int path_in_freq = 0;
689 /* Start by accumulating incoming edge counts to the path's first bb
690 into a couple buckets:
691 path_in_count: total count of incoming edges that flow into the
692 current path.
693 nonpath_count: total count of incoming edges that are not
694 flowing along *any* path. These are the counts
695 that will still flow along the original path after
696 all path duplication is done by potentially multiple
697 calls to this routine.
698 (any other incoming edge counts are for a different jump threading
699 path that will be handled by a later call to this routine.)
700 To make this easier, start by recording all incoming edges that flow into
701 the current path in a bitmap. We could add up the path's incoming edge
702 counts here, but we still need to walk all the first bb's incoming edges
703 below to add up the counts of the other edges not included in this jump
704 threading path. */
705 struct el *next, *el;
706 bitmap in_edge_srcs = BITMAP_ALLOC (NULL);
707 for (el = rd->incoming_edges; el; el = next)
709 next = el->next;
710 bitmap_set_bit (in_edge_srcs, el->e->src->index);
712 edge ein;
713 edge_iterator ei;
714 FOR_EACH_EDGE (ein, ei, e->dest->preds)
716 vec<jump_thread_edge *> *ein_path = THREAD_PATH (ein);
717 /* Simply check the incoming edge src against the set captured above. */
718 if (ein_path
719 && bitmap_bit_p (in_edge_srcs, (*ein_path)[0]->e->src->index))
721 /* It is necessary but not sufficient that the last path edges
722 are identical. There may be different paths that share the
723 same last path edge in the case where the last edge has a nocopy
724 source block. */
725 gcc_assert (ein_path->last ()->e == elast);
726 path_in_count += ein->count;
727 path_in_freq += EDGE_FREQUENCY (ein);
729 else if (!ein_path)
731 /* Keep track of the incoming edges that are not on any jump-threading
732 path. These counts will still flow out of original path after all
733 jump threading is complete. */
734 nonpath_count += ein->count;
738 /* This is needed due to insane incoming frequencies. */
739 if (path_in_freq > BB_FREQ_MAX)
740 path_in_freq = BB_FREQ_MAX;
742 BITMAP_FREE (in_edge_srcs);
744 /* Now compute the fraction of the total count coming into the first
745 path bb that is from the current threading path. */
746 gcov_type total_count = e->dest->count;
747 /* Handle incoming profile insanities. */
748 if (total_count < path_in_count)
749 path_in_count = total_count;
750 int onpath_scale = GCOV_COMPUTE_SCALE (path_in_count, total_count);
752 /* Walk the entire path to do some more computation in order to estimate
753 how much of the path_in_count will flow out of the duplicated threading
754 path. In the non-joiner case this is straightforward (it should be
755 the same as path_in_count, although we will handle incoming profile
756 insanities by setting it equal to the minimum count along the path).
758 In the joiner case, we need to estimate how much of the path_in_count
759 will stay on the threading path after the joiner's conditional branch.
760 We don't really know for sure how much of the counts
761 associated with this path go to each successor of the joiner, but we'll
762 estimate based on the fraction of the total count coming into the path
763 bb was from the threading paths (computed above in onpath_scale).
764 Afterwards, we will need to do some fixup to account for other threading
765 paths and possible profile insanities.
767 In order to estimate the joiner case's counts we also need to update
768 nonpath_count with any additional counts coming into the path. Other
769 blocks along the path may have additional predecessors from outside
770 the path. */
771 gcov_type path_out_count = path_in_count;
772 gcov_type min_path_count = path_in_count;
773 for (unsigned int i = 1; i < path->length (); i++)
775 edge epath = (*path)[i]->e;
776 gcov_type cur_count = epath->count;
777 if ((*path)[i]->type == EDGE_COPY_SRC_JOINER_BLOCK)
779 has_joiner = true;
780 cur_count = apply_probability (cur_count, onpath_scale);
782 /* In the joiner case we need to update nonpath_count for any edges
783 coming into the path that will contribute to the count flowing
784 into the path successor. */
785 if (has_joiner && epath != elast)
787 /* Look for other incoming edges after joiner. */
788 FOR_EACH_EDGE (ein, ei, epath->dest->preds)
790 if (ein != epath
791 /* Ignore in edges from blocks we have duplicated for a
792 threading path, which have duplicated edge counts until
793 they are redirected by an invocation of this routine. */
794 && !bitmap_bit_p (local_info->duplicate_blocks,
795 ein->src->index))
796 nonpath_count += ein->count;
799 if (cur_count < path_out_count)
800 path_out_count = cur_count;
801 if (epath->count < min_path_count)
802 min_path_count = epath->count;
805 /* We computed path_out_count above assuming that this path targeted
806 the joiner's on-path successor with the same likelihood as it
807 reached the joiner. However, other thread paths through the joiner
808 may take a different path through the normal copy source block
809 (i.e. they have a different elast), meaning that they do not
810 contribute any counts to this path's elast. As a result, it may
811 turn out that this path must have more count flowing to the on-path
812 successor of the joiner. Essentially, all of this path's elast
813 count must be contributed by this path and any nonpath counts
814 (since any path through the joiner with a different elast will not
815 include a copy of this elast in its duplicated path).
816 So ensure that this path's path_out_count is at least the
817 difference between elast->count and nonpath_count. Otherwise the edge
818 counts after threading will not be sane. */
819 if (has_joiner && path_out_count < elast->count - nonpath_count)
821 path_out_count = elast->count - nonpath_count;
822 /* But neither can we go above the minimum count along the path
823 we are duplicating. This can be an issue due to profile
824 insanities coming in to this pass. */
825 if (path_out_count > min_path_count)
826 path_out_count = min_path_count;
829 *path_in_count_ptr = path_in_count;
830 *path_out_count_ptr = path_out_count;
831 *path_in_freq_ptr = path_in_freq;
832 return has_joiner;
836 /* Update the counts and frequencies for both an original path
837 edge EPATH and its duplicate EDUP. The duplicate source block
838 will get a count/frequency of PATH_IN_COUNT and PATH_IN_FREQ,
839 and the duplicate edge EDUP will have a count of PATH_OUT_COUNT. */
840 static void
841 update_profile (edge epath, edge edup, gcov_type path_in_count,
842 gcov_type path_out_count, int path_in_freq)
845 /* First update the duplicated block's count / frequency. */
846 if (edup)
848 basic_block dup_block = edup->src;
849 gcc_assert (dup_block->count == 0);
850 gcc_assert (dup_block->frequency == 0);
851 dup_block->count = path_in_count;
852 dup_block->frequency = path_in_freq;
855 /* Now update the original block's count and frequency in the
856 opposite manner - remove the counts/freq that will flow
857 into the duplicated block. Handle underflow due to precision/
858 rounding issues. */
859 epath->src->count -= path_in_count;
860 if (epath->src->count < 0)
861 epath->src->count = 0;
862 epath->src->frequency -= path_in_freq;
863 if (epath->src->frequency < 0)
864 epath->src->frequency = 0;
866 /* Next update this path edge's original and duplicated counts. We know
867 that the duplicated path will have path_out_count flowing
868 out of it (in the joiner case this is the count along the duplicated path
869 out of the duplicated joiner). This count can then be removed from the
870 original path edge. */
871 if (edup)
872 edup->count = path_out_count;
873 epath->count -= path_out_count;
874 gcc_assert (epath->count >= 0);
878 /* The duplicate and original joiner blocks may end up with different
879 probabilities (different from both the original and from each other).
880 Recompute the probabilities here once we have updated the edge
881 counts and frequencies. */
883 static void
884 recompute_probabilities (basic_block bb)
886 edge esucc;
887 edge_iterator ei;
888 FOR_EACH_EDGE (esucc, ei, bb->succs)
890 if (!bb->count)
891 continue;
893 /* Prevent overflow computation due to insane profiles. */
894 if (esucc->count < bb->count)
895 esucc->probability = GCOV_COMPUTE_SCALE (esucc->count,
896 bb->count);
897 else
898 /* Can happen with missing/guessed probabilities, since we
899 may determine that more is flowing along duplicated
900 path than joiner succ probabilities allowed.
901 Counts and freqs will be insane after jump threading,
902 at least make sure probability is sane or we will
903 get a flow verification error.
904 Not much we can do to make counts/freqs sane without
905 redoing the profile estimation. */
906 esucc->probability = REG_BR_PROB_BASE;
911 /* Update the counts of the original and duplicated edges from a joiner
912 that go off path, given that we have already determined that the
913 duplicate joiner DUP_BB has incoming count PATH_IN_COUNT and
914 outgoing count along the path PATH_OUT_COUNT. The original (on-)path
915 edge from joiner is EPATH. */
917 static void
918 update_joiner_offpath_counts (edge epath, basic_block dup_bb,
919 gcov_type path_in_count,
920 gcov_type path_out_count)
922 /* Compute the count that currently flows off path from the joiner.
923 In other words, the total count of joiner's out edges other than
924 epath. Compute this by walking the successors instead of
925 subtracting epath's count from the joiner bb count, since there
926 are sometimes slight insanities where the total out edge count is
927 larger than the bb count (possibly due to rounding/truncation
928 errors). */
929 gcov_type total_orig_off_path_count = 0;
930 edge enonpath;
931 edge_iterator ei;
932 FOR_EACH_EDGE (enonpath, ei, epath->src->succs)
934 if (enonpath == epath)
935 continue;
936 total_orig_off_path_count += enonpath->count;
939 /* For the path that we are duplicating, the amount that will flow
940 off path from the duplicated joiner is the delta between the
941 path's cumulative in count and the portion of that count we
942 estimated above as flowing from the joiner along the duplicated
943 path. */
944 gcov_type total_dup_off_path_count = path_in_count - path_out_count;
946 /* Now do the actual updates of the off-path edges. */
947 FOR_EACH_EDGE (enonpath, ei, epath->src->succs)
949 /* Look for edges going off of the threading path. */
950 if (enonpath == epath)
951 continue;
953 /* Find the corresponding edge out of the duplicated joiner. */
954 edge enonpathdup = find_edge (dup_bb, enonpath->dest);
955 gcc_assert (enonpathdup);
957 /* We can't use the original probability of the joiner's out
958 edges, since the probabilities of the original branch
959 and the duplicated branches may vary after all threading is
960 complete. But apportion the duplicated joiner's off-path
961 total edge count computed earlier (total_dup_off_path_count)
962 among the duplicated off-path edges based on their original
963 ratio to the full off-path count (total_orig_off_path_count).
965 int scale = GCOV_COMPUTE_SCALE (enonpath->count,
966 total_orig_off_path_count);
967 /* Give the duplicated offpath edge a portion of the duplicated
968 total. */
969 enonpathdup->count = apply_scale (scale,
970 total_dup_off_path_count);
971 /* Now update the original offpath edge count, handling underflow
972 due to rounding errors. */
973 enonpath->count -= enonpathdup->count;
974 if (enonpath->count < 0)
975 enonpath->count = 0;
980 /* Check if the paths through RD all have estimated frequencies but zero
981 profile counts. This is more accurate than checking the entry block
982 for a zero profile count, since profile insanities sometimes creep in. */
984 static bool
985 estimated_freqs_path (struct redirection_data *rd)
987 edge e = rd->incoming_edges->e;
988 vec<jump_thread_edge *> *path = THREAD_PATH (e);
989 edge ein;
990 edge_iterator ei;
991 bool non_zero_freq = false;
992 FOR_EACH_EDGE (ein, ei, e->dest->preds)
994 if (ein->count)
995 return false;
996 non_zero_freq |= ein->src->frequency != 0;
999 for (unsigned int i = 1; i < path->length (); i++)
1001 edge epath = (*path)[i]->e;
1002 if (epath->src->count)
1003 return false;
1004 non_zero_freq |= epath->src->frequency != 0;
1005 edge esucc;
1006 FOR_EACH_EDGE (esucc, ei, epath->src->succs)
1008 if (esucc->count)
1009 return false;
1010 non_zero_freq |= esucc->src->frequency != 0;
1013 return non_zero_freq;
1017 /* Invoked for routines that have guessed frequencies and no profile
1018 counts to record the block and edge frequencies for paths through RD
1019 in the profile count fields of those blocks and edges. This is because
1020 ssa_fix_duplicate_block_edges incrementally updates the block and
1021 edge counts as edges are redirected, and it is difficult to do that
1022 for edge frequencies which are computed on the fly from the source
1023 block frequency and probability. When a block frequency is updated
1024 its outgoing edge frequencies are affected and become difficult to
1025 adjust. */
1027 static void
1028 freqs_to_counts_path (struct redirection_data *rd)
1030 edge e = rd->incoming_edges->e;
1031 vec<jump_thread_edge *> *path = THREAD_PATH (e);
1032 edge ein;
1033 edge_iterator ei;
1034 FOR_EACH_EDGE (ein, ei, e->dest->preds)
1036 /* Scale up the frequency by REG_BR_PROB_BASE, to avoid rounding
1037 errors applying the probability when the frequencies are very
1038 small. */
1039 ein->count = apply_probability (ein->src->frequency * REG_BR_PROB_BASE,
1040 ein->probability);
1043 for (unsigned int i = 1; i < path->length (); i++)
1045 edge epath = (*path)[i]->e;
1046 edge esucc;
1047 /* Scale up the frequency by REG_BR_PROB_BASE, to avoid rounding
1048 errors applying the edge probability when the frequencies are very
1049 small. */
1050 epath->src->count = epath->src->frequency * REG_BR_PROB_BASE;
1051 FOR_EACH_EDGE (esucc, ei, epath->src->succs)
1052 esucc->count = apply_probability (esucc->src->count,
1053 esucc->probability);
1058 /* For routines that have guessed frequencies and no profile counts, where we
1059 used freqs_to_counts_path to record block and edge frequencies for paths
1060 through RD, we clear the counts after completing all updates for RD.
1061 The updates in ssa_fix_duplicate_block_edges are based off the count fields,
1062 but the block frequencies and edge probabilities were updated as well,
1063 so we can simply clear the count fields. */
1065 static void
1066 clear_counts_path (struct redirection_data *rd)
1068 edge e = rd->incoming_edges->e;
1069 vec<jump_thread_edge *> *path = THREAD_PATH (e);
1070 edge ein, esucc;
1071 edge_iterator ei;
1072 FOR_EACH_EDGE (ein, ei, e->dest->preds)
1073 ein->count = 0;
1075 /* First clear counts along original path. */
1076 for (unsigned int i = 1; i < path->length (); i++)
1078 edge epath = (*path)[i]->e;
1079 FOR_EACH_EDGE (esucc, ei, epath->src->succs)
1080 esucc->count = 0;
1081 epath->src->count = 0;
1083 /* Also need to clear the counts along duplicated path. */
1084 for (unsigned int i = 0; i < 2; i++)
1086 basic_block dup = rd->dup_blocks[i];
1087 if (!dup)
1088 continue;
1089 FOR_EACH_EDGE (esucc, ei, dup->succs)
1090 esucc->count = 0;
1091 dup->count = 0;
1095 /* Wire up the outgoing edges from the duplicate blocks and
1096 update any PHIs as needed. Also update the profile counts
1097 on the original and duplicate blocks and edges. */
1098 void
1099 ssa_fix_duplicate_block_edges (struct redirection_data *rd,
1100 ssa_local_info_t *local_info)
1102 bool multi_incomings = (rd->incoming_edges->next != NULL);
1103 edge e = rd->incoming_edges->e;
1104 vec<jump_thread_edge *> *path = THREAD_PATH (e);
1105 edge elast = path->last ()->e;
1106 gcov_type path_in_count = 0;
1107 gcov_type path_out_count = 0;
1108 int path_in_freq = 0;
1110 /* This routine updates profile counts, frequencies, and probabilities
1111 incrementally. Since it is difficult to do the incremental updates
1112 using frequencies/probabilities alone, for routines without profile
1113 data we first take a snapshot of the existing block and edge frequencies
1114 by copying them into the empty profile count fields. These counts are
1115 then used to do the incremental updates, and cleared at the end of this
1116 routine. If the function is marked as having a profile, we still check
1117 to see if the paths through RD are using estimated frequencies because
1118 the routine had zero profile counts. */
1119 bool do_freqs_to_counts = (profile_status_for_fn (cfun) != PROFILE_READ
1120 || estimated_freqs_path (rd));
1121 if (do_freqs_to_counts)
1122 freqs_to_counts_path (rd);
1124 /* First determine how much profile count to move from original
1125 path to the duplicate path. This is tricky in the presence of
1126 a joiner (see comments for compute_path_counts), where some portion
1127 of the path's counts will flow off-path from the joiner. In the
1128 non-joiner case the path_in_count and path_out_count should be the
1129 same. */
1130 bool has_joiner = compute_path_counts (rd, local_info,
1131 &path_in_count, &path_out_count,
1132 &path_in_freq);
1134 int cur_path_freq = path_in_freq;
1135 for (unsigned int count = 0, i = 1; i < path->length (); i++)
1137 edge epath = (*path)[i]->e;
1139 /* If we were threading through an joiner block, then we want
1140 to keep its control statement and redirect an outgoing edge.
1141 Else we want to remove the control statement & edges, then create
1142 a new outgoing edge. In both cases we may need to update PHIs. */
1143 if ((*path)[i]->type == EDGE_COPY_SRC_JOINER_BLOCK)
1145 edge victim;
1146 edge e2;
1148 gcc_assert (has_joiner);
1150 /* This updates the PHIs at the destination of the duplicate
1151 block. Pass 0 instead of i if we are threading a path which
1152 has multiple incoming edges. */
1153 update_destination_phis (local_info->bb, rd->dup_blocks[count],
1154 path, multi_incomings ? 0 : i);
1156 /* Find the edge from the duplicate block to the block we're
1157 threading through. That's the edge we want to redirect. */
1158 victim = find_edge (rd->dup_blocks[count], (*path)[i]->e->dest);
1160 /* If there are no remaining blocks on the path to duplicate,
1161 then redirect VICTIM to the final destination of the jump
1162 threading path. */
1163 if (!any_remaining_duplicated_blocks (path, i))
1165 e2 = redirect_edge_and_branch (victim, elast->dest);
1166 /* If we redirected the edge, then we need to copy PHI arguments
1167 at the target. If the edge already existed (e2 != victim
1168 case), then the PHIs in the target already have the correct
1169 arguments. */
1170 if (e2 == victim)
1171 copy_phi_args (e2->dest, elast, e2,
1172 path, multi_incomings ? 0 : i);
1174 else
1176 /* Redirect VICTIM to the next duplicated block in the path. */
1177 e2 = redirect_edge_and_branch (victim, rd->dup_blocks[count + 1]);
1179 /* We need to update the PHIs in the next duplicated block. We
1180 want the new PHI args to have the same value as they had
1181 in the source of the next duplicate block.
1183 Thus, we need to know which edge we traversed into the
1184 source of the duplicate. Furthermore, we may have
1185 traversed many edges to reach the source of the duplicate.
1187 Walk through the path starting at element I until we
1188 hit an edge marked with EDGE_COPY_SRC_BLOCK. We want
1189 the edge from the prior element. */
1190 for (unsigned int j = i + 1; j < path->length (); j++)
1192 if ((*path)[j]->type == EDGE_COPY_SRC_BLOCK)
1194 copy_phi_arg_into_existing_phi ((*path)[j - 1]->e, e2);
1195 break;
1200 /* Update the counts and frequency of both the original block
1201 and path edge, and the duplicates. The path duplicate's
1202 incoming count and frequency are the totals for all edges
1203 incoming to this jump threading path computed earlier.
1204 And we know that the duplicated path will have path_out_count
1205 flowing out of it (i.e. along the duplicated path out of the
1206 duplicated joiner). */
1207 update_profile (epath, e2, path_in_count, path_out_count,
1208 path_in_freq);
1210 /* Next we need to update the counts of the original and duplicated
1211 edges from the joiner that go off path. */
1212 update_joiner_offpath_counts (epath, e2->src, path_in_count,
1213 path_out_count);
1215 /* Finally, we need to set the probabilities on the duplicated
1216 edges out of the duplicated joiner (e2->src). The probabilities
1217 along the original path will all be updated below after we finish
1218 processing the whole path. */
1219 recompute_probabilities (e2->src);
1221 /* Record the frequency flowing to the downstream duplicated
1222 path blocks. */
1223 cur_path_freq = EDGE_FREQUENCY (e2);
1225 else if ((*path)[i]->type == EDGE_COPY_SRC_BLOCK)
1227 remove_ctrl_stmt_and_useless_edges (rd->dup_blocks[count], NULL);
1228 create_edge_and_update_destination_phis (rd, rd->dup_blocks[count],
1229 multi_incomings ? 0 : i);
1230 if (count == 1)
1231 single_succ_edge (rd->dup_blocks[1])->aux = NULL;
1233 /* Update the counts and frequency of both the original block
1234 and path edge, and the duplicates. Since we are now after
1235 any joiner that may have existed on the path, the count
1236 flowing along the duplicated threaded path is path_out_count.
1237 If we didn't have a joiner, then cur_path_freq was the sum
1238 of the total frequencies along all incoming edges to the
1239 thread path (path_in_freq). If we had a joiner, it would have
1240 been updated at the end of that handling to the edge frequency
1241 along the duplicated joiner path edge. */
1242 update_profile (epath, EDGE_SUCC (rd->dup_blocks[count], 0),
1243 path_out_count, path_out_count,
1244 cur_path_freq);
1246 else
1248 /* No copy case. In this case we don't have an equivalent block
1249 on the duplicated thread path to update, but we do need
1250 to remove the portion of the counts/freqs that were moved
1251 to the duplicated path from the counts/freqs flowing through
1252 this block on the original path. Since all the no-copy edges
1253 are after any joiner, the removed count is the same as
1254 path_out_count.
1256 If we didn't have a joiner, then cur_path_freq was the sum
1257 of the total frequencies along all incoming edges to the
1258 thread path (path_in_freq). If we had a joiner, it would have
1259 been updated at the end of that handling to the edge frequency
1260 along the duplicated joiner path edge. */
1261 update_profile (epath, NULL, path_out_count, path_out_count,
1262 cur_path_freq);
1265 /* Increment the index into the duplicated path when we processed
1266 a duplicated block. */
1267 if ((*path)[i]->type == EDGE_COPY_SRC_JOINER_BLOCK
1268 || (*path)[i]->type == EDGE_COPY_SRC_BLOCK)
1270 count++;
1274 /* Now walk orig blocks and update their probabilities, since the
1275 counts and freqs should be updated properly by above loop. */
1276 for (unsigned int i = 1; i < path->length (); i++)
1278 edge epath = (*path)[i]->e;
1279 recompute_probabilities (epath->src);
1282 /* Done with all profile and frequency updates, clear counts if they
1283 were copied. */
1284 if (do_freqs_to_counts)
1285 clear_counts_path (rd);
1288 /* Hash table traversal callback routine to create duplicate blocks. */
1291 ssa_create_duplicates (struct redirection_data **slot,
1292 ssa_local_info_t *local_info)
1294 struct redirection_data *rd = *slot;
1296 /* The second duplicated block in a jump threading path is specific
1297 to the path. So it gets stored in RD rather than in LOCAL_DATA.
1299 Each time we're called, we have to look through the path and see
1300 if a second block needs to be duplicated.
1302 Note the search starts with the third edge on the path. The first
1303 edge is the incoming edge, the second edge always has its source
1304 duplicated. Thus we start our search with the third edge. */
1305 vec<jump_thread_edge *> *path = rd->path;
1306 for (unsigned int i = 2; i < path->length (); i++)
1308 if ((*path)[i]->type == EDGE_COPY_SRC_BLOCK
1309 || (*path)[i]->type == EDGE_COPY_SRC_JOINER_BLOCK)
1311 create_block_for_threading ((*path)[i]->e->src, rd, 1,
1312 &local_info->duplicate_blocks);
1313 break;
1317 /* Create a template block if we have not done so already. Otherwise
1318 use the template to create a new block. */
1319 if (local_info->template_block == NULL)
1321 create_block_for_threading ((*path)[1]->e->src, rd, 0,
1322 &local_info->duplicate_blocks);
1323 local_info->template_block = rd->dup_blocks[0];
1325 /* We do not create any outgoing edges for the template. We will
1326 take care of that in a later traversal. That way we do not
1327 create edges that are going to just be deleted. */
1329 else
1331 create_block_for_threading (local_info->template_block, rd, 0,
1332 &local_info->duplicate_blocks);
1334 /* Go ahead and wire up outgoing edges and update PHIs for the duplicate
1335 block. */
1336 ssa_fix_duplicate_block_edges (rd, local_info);
1339 /* Keep walking the hash table. */
1340 return 1;
1343 /* We did not create any outgoing edges for the template block during
1344 block creation. This hash table traversal callback creates the
1345 outgoing edge for the template block. */
1347 inline int
1348 ssa_fixup_template_block (struct redirection_data **slot,
1349 ssa_local_info_t *local_info)
1351 struct redirection_data *rd = *slot;
1353 /* If this is the template block halt the traversal after updating
1354 it appropriately.
1356 If we were threading through an joiner block, then we want
1357 to keep its control statement and redirect an outgoing edge.
1358 Else we want to remove the control statement & edges, then create
1359 a new outgoing edge. In both cases we may need to update PHIs. */
1360 if (rd->dup_blocks[0] && rd->dup_blocks[0] == local_info->template_block)
1362 ssa_fix_duplicate_block_edges (rd, local_info);
1363 return 0;
1366 return 1;
1369 /* Hash table traversal callback to redirect each incoming edge
1370 associated with this hash table element to its new destination. */
1373 ssa_redirect_edges (struct redirection_data **slot,
1374 ssa_local_info_t *local_info)
1376 struct redirection_data *rd = *slot;
1377 struct el *next, *el;
1379 /* Walk over all the incoming edges associated associated with this
1380 hash table entry. */
1381 for (el = rd->incoming_edges; el; el = next)
1383 edge e = el->e;
1384 vec<jump_thread_edge *> *path = THREAD_PATH (e);
1386 /* Go ahead and free this element from the list. Doing this now
1387 avoids the need for another list walk when we destroy the hash
1388 table. */
1389 next = el->next;
1390 free (el);
1392 thread_stats.num_threaded_edges++;
1394 if (rd->dup_blocks[0])
1396 edge e2;
1398 if (dump_file && (dump_flags & TDF_DETAILS))
1399 fprintf (dump_file, " Threaded jump %d --> %d to %d\n",
1400 e->src->index, e->dest->index, rd->dup_blocks[0]->index);
1402 /* If we redirect a loop latch edge cancel its loop. */
1403 if (e->src == e->src->loop_father->latch)
1404 mark_loop_for_removal (e->src->loop_father);
1406 /* Redirect the incoming edge (possibly to the joiner block) to the
1407 appropriate duplicate block. */
1408 e2 = redirect_edge_and_branch (e, rd->dup_blocks[0]);
1409 gcc_assert (e == e2);
1410 flush_pending_stmts (e2);
1413 /* Go ahead and clear E->aux. It's not needed anymore and failure
1414 to clear it will cause all kinds of unpleasant problems later. */
1415 delete_jump_thread_path (path);
1416 e->aux = NULL;
1420 /* Indicate that we actually threaded one or more jumps. */
1421 if (rd->incoming_edges)
1422 local_info->jumps_threaded = true;
1424 return 1;
1427 /* Return true if this block has no executable statements other than
1428 a simple ctrl flow instruction. When the number of outgoing edges
1429 is one, this is equivalent to a "forwarder" block. */
1431 static bool
1432 redirection_block_p (basic_block bb)
1434 gimple_stmt_iterator gsi;
1436 /* Advance to the first executable statement. */
1437 gsi = gsi_start_bb (bb);
1438 while (!gsi_end_p (gsi)
1439 && (gimple_code (gsi_stmt (gsi)) == GIMPLE_LABEL
1440 || is_gimple_debug (gsi_stmt (gsi))
1441 || gimple_nop_p (gsi_stmt (gsi))))
1442 gsi_next (&gsi);
1444 /* Check if this is an empty block. */
1445 if (gsi_end_p (gsi))
1446 return true;
1448 /* Test that we've reached the terminating control statement. */
1449 return gsi_stmt (gsi)
1450 && (gimple_code (gsi_stmt (gsi)) == GIMPLE_COND
1451 || gimple_code (gsi_stmt (gsi)) == GIMPLE_GOTO
1452 || gimple_code (gsi_stmt (gsi)) == GIMPLE_SWITCH);
1455 /* BB is a block which ends with a COND_EXPR or SWITCH_EXPR and when BB
1456 is reached via one or more specific incoming edges, we know which
1457 outgoing edge from BB will be traversed.
1459 We want to redirect those incoming edges to the target of the
1460 appropriate outgoing edge. Doing so avoids a conditional branch
1461 and may expose new optimization opportunities. Note that we have
1462 to update dominator tree and SSA graph after such changes.
1464 The key to keeping the SSA graph update manageable is to duplicate
1465 the side effects occurring in BB so that those side effects still
1466 occur on the paths which bypass BB after redirecting edges.
1468 We accomplish this by creating duplicates of BB and arranging for
1469 the duplicates to unconditionally pass control to one specific
1470 successor of BB. We then revector the incoming edges into BB to
1471 the appropriate duplicate of BB.
1473 If NOLOOP_ONLY is true, we only perform the threading as long as it
1474 does not affect the structure of the loops in a nontrivial way.
1476 If JOINERS is true, then thread through joiner blocks as well. */
1478 static bool
1479 thread_block_1 (basic_block bb, bool noloop_only, bool joiners)
1481 /* E is an incoming edge into BB that we may or may not want to
1482 redirect to a duplicate of BB. */
1483 edge e, e2;
1484 edge_iterator ei;
1485 ssa_local_info_t local_info;
1487 local_info.duplicate_blocks = BITMAP_ALLOC (NULL);
1489 /* To avoid scanning a linear array for the element we need we instead
1490 use a hash table. For normal code there should be no noticeable
1491 difference. However, if we have a block with a large number of
1492 incoming and outgoing edges such linear searches can get expensive. */
1493 redirection_data
1494 = new hash_table<struct redirection_data> (EDGE_COUNT (bb->succs));
1496 /* Record each unique threaded destination into a hash table for
1497 efficient lookups. */
1498 FOR_EACH_EDGE (e, ei, bb->preds)
1500 if (e->aux == NULL)
1501 continue;
1503 vec<jump_thread_edge *> *path = THREAD_PATH (e);
1505 if (((*path)[1]->type == EDGE_COPY_SRC_JOINER_BLOCK && !joiners)
1506 || ((*path)[1]->type == EDGE_COPY_SRC_BLOCK && joiners))
1507 continue;
1509 e2 = path->last ()->e;
1510 if (!e2 || noloop_only)
1512 /* If NOLOOP_ONLY is true, we only allow threading through the
1513 header of a loop to exit edges. */
1515 /* One case occurs when there was loop header buried in a jump
1516 threading path that crosses loop boundaries. We do not try
1517 and thread this elsewhere, so just cancel the jump threading
1518 request by clearing the AUX field now. */
1519 if ((bb->loop_father != e2->src->loop_father
1520 && !loop_exit_edge_p (e2->src->loop_father, e2))
1521 || (e2->src->loop_father != e2->dest->loop_father
1522 && !loop_exit_edge_p (e2->src->loop_father, e2)))
1524 /* Since this case is not handled by our special code
1525 to thread through a loop header, we must explicitly
1526 cancel the threading request here. */
1527 delete_jump_thread_path (path);
1528 e->aux = NULL;
1529 continue;
1532 /* Another case occurs when trying to thread through our
1533 own loop header, possibly from inside the loop. We will
1534 thread these later. */
1535 unsigned int i;
1536 for (i = 1; i < path->length (); i++)
1538 if ((*path)[i]->e->src == bb->loop_father->header
1539 && (!loop_exit_edge_p (bb->loop_father, e2)
1540 || (*path)[1]->type == EDGE_COPY_SRC_JOINER_BLOCK))
1541 break;
1544 if (i != path->length ())
1545 continue;
1548 /* Insert the outgoing edge into the hash table if it is not
1549 already in the hash table. */
1550 lookup_redirection_data (e, INSERT);
1553 /* We do not update dominance info. */
1554 free_dominance_info (CDI_DOMINATORS);
1556 /* We know we only thread through the loop header to loop exits.
1557 Let the basic block duplication hook know we are not creating
1558 a multiple entry loop. */
1559 if (noloop_only
1560 && bb == bb->loop_father->header)
1561 set_loop_copy (bb->loop_father, loop_outer (bb->loop_father));
1563 /* Now create duplicates of BB.
1565 Note that for a block with a high outgoing degree we can waste
1566 a lot of time and memory creating and destroying useless edges.
1568 So we first duplicate BB and remove the control structure at the
1569 tail of the duplicate as well as all outgoing edges from the
1570 duplicate. We then use that duplicate block as a template for
1571 the rest of the duplicates. */
1572 local_info.template_block = NULL;
1573 local_info.bb = bb;
1574 local_info.jumps_threaded = false;
1575 redirection_data->traverse <ssa_local_info_t *, ssa_create_duplicates>
1576 (&local_info);
1578 /* The template does not have an outgoing edge. Create that outgoing
1579 edge and update PHI nodes as the edge's target as necessary.
1581 We do this after creating all the duplicates to avoid creating
1582 unnecessary edges. */
1583 redirection_data->traverse <ssa_local_info_t *, ssa_fixup_template_block>
1584 (&local_info);
1586 /* The hash table traversals above created the duplicate blocks (and the
1587 statements within the duplicate blocks). This loop creates PHI nodes for
1588 the duplicated blocks and redirects the incoming edges into BB to reach
1589 the duplicates of BB. */
1590 redirection_data->traverse <ssa_local_info_t *, ssa_redirect_edges>
1591 (&local_info);
1593 /* Done with this block. Clear REDIRECTION_DATA. */
1594 delete redirection_data;
1595 redirection_data = NULL;
1597 if (noloop_only
1598 && bb == bb->loop_father->header)
1599 set_loop_copy (bb->loop_father, NULL);
1601 BITMAP_FREE (local_info.duplicate_blocks);
1602 local_info.duplicate_blocks = NULL;
1604 /* Indicate to our caller whether or not any jumps were threaded. */
1605 return local_info.jumps_threaded;
1608 /* Wrapper for thread_block_1 so that we can first handle jump
1609 thread paths which do not involve copying joiner blocks, then
1610 handle jump thread paths which have joiner blocks.
1612 By doing things this way we can be as aggressive as possible and
1613 not worry that copying a joiner block will create a jump threading
1614 opportunity. */
1616 static bool
1617 thread_block (basic_block bb, bool noloop_only)
1619 bool retval;
1620 retval = thread_block_1 (bb, noloop_only, false);
1621 retval |= thread_block_1 (bb, noloop_only, true);
1622 return retval;
1626 /* Threads edge E through E->dest to the edge THREAD_TARGET (E). Returns the
1627 copy of E->dest created during threading, or E->dest if it was not necessary
1628 to copy it (E is its single predecessor). */
1630 static basic_block
1631 thread_single_edge (edge e)
1633 basic_block bb = e->dest;
1634 struct redirection_data rd;
1635 vec<jump_thread_edge *> *path = THREAD_PATH (e);
1636 edge eto = (*path)[1]->e;
1638 for (unsigned int i = 0; i < path->length (); i++)
1639 delete (*path)[i];
1640 delete path;
1641 e->aux = NULL;
1643 thread_stats.num_threaded_edges++;
1645 if (single_pred_p (bb))
1647 /* If BB has just a single predecessor, we should only remove the
1648 control statements at its end, and successors except for ETO. */
1649 remove_ctrl_stmt_and_useless_edges (bb, eto->dest);
1651 /* And fixup the flags on the single remaining edge. */
1652 eto->flags &= ~(EDGE_TRUE_VALUE | EDGE_FALSE_VALUE | EDGE_ABNORMAL);
1653 eto->flags |= EDGE_FALLTHRU;
1655 return bb;
1658 /* Otherwise, we need to create a copy. */
1659 if (e->dest == eto->src)
1660 update_bb_profile_for_threading (bb, EDGE_FREQUENCY (e), e->count, eto);
1662 vec<jump_thread_edge *> *npath = new vec<jump_thread_edge *> ();
1663 jump_thread_edge *x = new jump_thread_edge (e, EDGE_START_JUMP_THREAD);
1664 npath->safe_push (x);
1666 x = new jump_thread_edge (eto, EDGE_COPY_SRC_BLOCK);
1667 npath->safe_push (x);
1668 rd.path = npath;
1670 create_block_for_threading (bb, &rd, 0, NULL);
1671 remove_ctrl_stmt_and_useless_edges (rd.dup_blocks[0], NULL);
1672 create_edge_and_update_destination_phis (&rd, rd.dup_blocks[0], 0);
1674 if (dump_file && (dump_flags & TDF_DETAILS))
1675 fprintf (dump_file, " Threaded jump %d --> %d to %d\n",
1676 e->src->index, e->dest->index, rd.dup_blocks[0]->index);
1678 rd.dup_blocks[0]->count = e->count;
1679 rd.dup_blocks[0]->frequency = EDGE_FREQUENCY (e);
1680 single_succ_edge (rd.dup_blocks[0])->count = e->count;
1681 redirect_edge_and_branch (e, rd.dup_blocks[0]);
1682 flush_pending_stmts (e);
1684 return rd.dup_blocks[0];
1687 /* Callback for dfs_enumerate_from. Returns true if BB is different
1688 from STOP and DBDS_CE_STOP. */
1690 static basic_block dbds_ce_stop;
1691 static bool
1692 dbds_continue_enumeration_p (const_basic_block bb, const void *stop)
1694 return (bb != (const_basic_block) stop
1695 && bb != dbds_ce_stop);
1698 /* Evaluates the dominance relationship of latch of the LOOP and BB, and
1699 returns the state. */
1701 enum bb_dom_status
1703 /* BB does not dominate latch of the LOOP. */
1704 DOMST_NONDOMINATING,
1705 /* The LOOP is broken (there is no path from the header to its latch. */
1706 DOMST_LOOP_BROKEN,
1707 /* BB dominates the latch of the LOOP. */
1708 DOMST_DOMINATING
1711 static enum bb_dom_status
1712 determine_bb_domination_status (struct loop *loop, basic_block bb)
1714 basic_block *bblocks;
1715 unsigned nblocks, i;
1716 bool bb_reachable = false;
1717 edge_iterator ei;
1718 edge e;
1720 /* This function assumes BB is a successor of LOOP->header.
1721 If that is not the case return DOMST_NONDOMINATING which
1722 is always safe. */
1724 bool ok = false;
1726 FOR_EACH_EDGE (e, ei, bb->preds)
1728 if (e->src == loop->header)
1730 ok = true;
1731 break;
1735 if (!ok)
1736 return DOMST_NONDOMINATING;
1739 if (bb == loop->latch)
1740 return DOMST_DOMINATING;
1742 /* Check that BB dominates LOOP->latch, and that it is back-reachable
1743 from it. */
1745 bblocks = XCNEWVEC (basic_block, loop->num_nodes);
1746 dbds_ce_stop = loop->header;
1747 nblocks = dfs_enumerate_from (loop->latch, 1, dbds_continue_enumeration_p,
1748 bblocks, loop->num_nodes, bb);
1749 for (i = 0; i < nblocks; i++)
1750 FOR_EACH_EDGE (e, ei, bblocks[i]->preds)
1752 if (e->src == loop->header)
1754 free (bblocks);
1755 return DOMST_NONDOMINATING;
1757 if (e->src == bb)
1758 bb_reachable = true;
1761 free (bblocks);
1762 return (bb_reachable ? DOMST_DOMINATING : DOMST_LOOP_BROKEN);
1765 /* Return true if BB is part of the new pre-header that is created
1766 when threading the latch to DATA. */
1768 static bool
1769 def_split_header_continue_p (const_basic_block bb, const void *data)
1771 const_basic_block new_header = (const_basic_block) data;
1772 const struct loop *l;
1774 if (bb == new_header
1775 || loop_depth (bb->loop_father) < loop_depth (new_header->loop_father))
1776 return false;
1777 for (l = bb->loop_father; l; l = loop_outer (l))
1778 if (l == new_header->loop_father)
1779 return true;
1780 return false;
1783 /* Thread jumps through the header of LOOP. Returns true if cfg changes.
1784 If MAY_PEEL_LOOP_HEADERS is false, we avoid threading from entry edges
1785 to the inside of the loop. */
1787 static bool
1788 thread_through_loop_header (struct loop *loop, bool may_peel_loop_headers)
1790 basic_block header = loop->header;
1791 edge e, tgt_edge, latch = loop_latch_edge (loop);
1792 edge_iterator ei;
1793 basic_block tgt_bb, atgt_bb;
1794 enum bb_dom_status domst;
1796 /* We have already threaded through headers to exits, so all the threading
1797 requests now are to the inside of the loop. We need to avoid creating
1798 irreducible regions (i.e., loops with more than one entry block), and
1799 also loop with several latch edges, or new subloops of the loop (although
1800 there are cases where it might be appropriate, it is difficult to decide,
1801 and doing it wrongly may confuse other optimizers).
1803 We could handle more general cases here. However, the intention is to
1804 preserve some information about the loop, which is impossible if its
1805 structure changes significantly, in a way that is not well understood.
1806 Thus we only handle few important special cases, in which also updating
1807 of the loop-carried information should be feasible:
1809 1) Propagation of latch edge to a block that dominates the latch block
1810 of a loop. This aims to handle the following idiom:
1812 first = 1;
1813 while (1)
1815 if (first)
1816 initialize;
1817 first = 0;
1818 body;
1821 After threading the latch edge, this becomes
1823 first = 1;
1824 if (first)
1825 initialize;
1826 while (1)
1828 first = 0;
1829 body;
1832 The original header of the loop is moved out of it, and we may thread
1833 the remaining edges through it without further constraints.
1835 2) All entry edges are propagated to a single basic block that dominates
1836 the latch block of the loop. This aims to handle the following idiom
1837 (normally created for "for" loops):
1839 i = 0;
1840 while (1)
1842 if (i >= 100)
1843 break;
1844 body;
1845 i++;
1848 This becomes
1850 i = 0;
1851 while (1)
1853 body;
1854 i++;
1855 if (i >= 100)
1856 break;
1860 /* Threading through the header won't improve the code if the header has just
1861 one successor. */
1862 if (single_succ_p (header))
1863 goto fail;
1865 /* If we threaded the latch using a joiner block, we cancel the
1866 threading opportunity out of an abundance of caution. However,
1867 still allow threading from outside to inside the loop. */
1868 if (latch->aux)
1870 vec<jump_thread_edge *> *path = THREAD_PATH (latch);
1871 if ((*path)[1]->type == EDGE_COPY_SRC_JOINER_BLOCK)
1873 delete_jump_thread_path (path);
1874 latch->aux = NULL;
1878 if (latch->aux)
1880 vec<jump_thread_edge *> *path = THREAD_PATH (latch);
1881 tgt_edge = (*path)[1]->e;
1882 tgt_bb = tgt_edge->dest;
1884 else if (!may_peel_loop_headers
1885 && !redirection_block_p (loop->header))
1886 goto fail;
1887 else
1889 tgt_bb = NULL;
1890 tgt_edge = NULL;
1891 FOR_EACH_EDGE (e, ei, header->preds)
1893 if (!e->aux)
1895 if (e == latch)
1896 continue;
1898 /* If latch is not threaded, and there is a header
1899 edge that is not threaded, we would create loop
1900 with multiple entries. */
1901 goto fail;
1904 vec<jump_thread_edge *> *path = THREAD_PATH (e);
1906 if ((*path)[1]->type == EDGE_COPY_SRC_JOINER_BLOCK)
1907 goto fail;
1908 tgt_edge = (*path)[1]->e;
1909 atgt_bb = tgt_edge->dest;
1910 if (!tgt_bb)
1911 tgt_bb = atgt_bb;
1912 /* Two targets of threading would make us create loop
1913 with multiple entries. */
1914 else if (tgt_bb != atgt_bb)
1915 goto fail;
1918 if (!tgt_bb)
1920 /* There are no threading requests. */
1921 return false;
1924 /* Redirecting to empty loop latch is useless. */
1925 if (tgt_bb == loop->latch
1926 && empty_block_p (loop->latch))
1927 goto fail;
1930 /* The target block must dominate the loop latch, otherwise we would be
1931 creating a subloop. */
1932 domst = determine_bb_domination_status (loop, tgt_bb);
1933 if (domst == DOMST_NONDOMINATING)
1934 goto fail;
1935 if (domst == DOMST_LOOP_BROKEN)
1937 /* If the loop ceased to exist, mark it as such, and thread through its
1938 original header. */
1939 mark_loop_for_removal (loop);
1940 return thread_block (header, false);
1943 if (tgt_bb->loop_father->header == tgt_bb)
1945 /* If the target of the threading is a header of a subloop, we need
1946 to create a preheader for it, so that the headers of the two loops
1947 do not merge. */
1948 if (EDGE_COUNT (tgt_bb->preds) > 2)
1950 tgt_bb = create_preheader (tgt_bb->loop_father, 0);
1951 gcc_assert (tgt_bb != NULL);
1953 else
1954 tgt_bb = split_edge (tgt_edge);
1957 if (latch->aux)
1959 basic_block *bblocks;
1960 unsigned nblocks, i;
1962 /* First handle the case latch edge is redirected. We are copying
1963 the loop header but not creating a multiple entry loop. Make the
1964 cfg manipulation code aware of that fact. */
1965 set_loop_copy (loop, loop);
1966 loop->latch = thread_single_edge (latch);
1967 set_loop_copy (loop, NULL);
1968 gcc_assert (single_succ (loop->latch) == tgt_bb);
1969 loop->header = tgt_bb;
1971 /* Remove the new pre-header blocks from our loop. */
1972 bblocks = XCNEWVEC (basic_block, loop->num_nodes);
1973 nblocks = dfs_enumerate_from (header, 0, def_split_header_continue_p,
1974 bblocks, loop->num_nodes, tgt_bb);
1975 for (i = 0; i < nblocks; i++)
1976 if (bblocks[i]->loop_father == loop)
1978 remove_bb_from_loops (bblocks[i]);
1979 add_bb_to_loop (bblocks[i], loop_outer (loop));
1981 free (bblocks);
1983 /* If the new header has multiple latches mark it so. */
1984 FOR_EACH_EDGE (e, ei, loop->header->preds)
1985 if (e->src->loop_father == loop
1986 && e->src != loop->latch)
1988 loop->latch = NULL;
1989 loops_state_set (LOOPS_MAY_HAVE_MULTIPLE_LATCHES);
1992 /* Cancel remaining threading requests that would make the
1993 loop a multiple entry loop. */
1994 FOR_EACH_EDGE (e, ei, header->preds)
1996 edge e2;
1998 if (e->aux == NULL)
1999 continue;
2001 vec<jump_thread_edge *> *path = THREAD_PATH (e);
2002 e2 = path->last ()->e;
2004 if (e->src->loop_father != e2->dest->loop_father
2005 && e2->dest != loop->header)
2007 delete_jump_thread_path (path);
2008 e->aux = NULL;
2012 /* Thread the remaining edges through the former header. */
2013 thread_block (header, false);
2015 else
2017 basic_block new_preheader;
2019 /* Now consider the case entry edges are redirected to the new entry
2020 block. Remember one entry edge, so that we can find the new
2021 preheader (its destination after threading). */
2022 FOR_EACH_EDGE (e, ei, header->preds)
2024 if (e->aux)
2025 break;
2028 /* The duplicate of the header is the new preheader of the loop. Ensure
2029 that it is placed correctly in the loop hierarchy. */
2030 set_loop_copy (loop, loop_outer (loop));
2032 thread_block (header, false);
2033 set_loop_copy (loop, NULL);
2034 new_preheader = e->dest;
2036 /* Create the new latch block. This is always necessary, as the latch
2037 must have only a single successor, but the original header had at
2038 least two successors. */
2039 loop->latch = NULL;
2040 mfb_kj_edge = single_succ_edge (new_preheader);
2041 loop->header = mfb_kj_edge->dest;
2042 latch = make_forwarder_block (tgt_bb, mfb_keep_just, NULL);
2043 loop->header = latch->dest;
2044 loop->latch = latch->src;
2047 return true;
2049 fail:
2050 /* We failed to thread anything. Cancel the requests. */
2051 FOR_EACH_EDGE (e, ei, header->preds)
2053 vec<jump_thread_edge *> *path = THREAD_PATH (e);
2055 if (path)
2057 delete_jump_thread_path (path);
2058 e->aux = NULL;
2061 return false;
2064 /* E1 and E2 are edges into the same basic block. Return TRUE if the
2065 PHI arguments associated with those edges are equal or there are no
2066 PHI arguments, otherwise return FALSE. */
2068 static bool
2069 phi_args_equal_on_edges (edge e1, edge e2)
2071 gphi_iterator gsi;
2072 int indx1 = e1->dest_idx;
2073 int indx2 = e2->dest_idx;
2075 for (gsi = gsi_start_phis (e1->dest); !gsi_end_p (gsi); gsi_next (&gsi))
2077 gphi *phi = gsi.phi ();
2079 if (!operand_equal_p (gimple_phi_arg_def (phi, indx1),
2080 gimple_phi_arg_def (phi, indx2), 0))
2081 return false;
2083 return true;
2086 /* Walk through the registered jump threads and convert them into a
2087 form convenient for this pass.
2089 Any block which has incoming edges threaded to outgoing edges
2090 will have its entry in THREADED_BLOCK set.
2092 Any threaded edge will have its new outgoing edge stored in the
2093 original edge's AUX field.
2095 This form avoids the need to walk all the edges in the CFG to
2096 discover blocks which need processing and avoids unnecessary
2097 hash table lookups to map from threaded edge to new target. */
2099 static void
2100 mark_threaded_blocks (bitmap threaded_blocks)
2102 unsigned int i;
2103 bitmap_iterator bi;
2104 bitmap tmp = BITMAP_ALLOC (NULL);
2105 basic_block bb;
2106 edge e;
2107 edge_iterator ei;
2109 /* It is possible to have jump threads in which one is a subpath
2110 of the other. ie, (A, B), (B, C), (C, D) where B is a joiner
2111 block and (B, C), (C, D) where no joiner block exists.
2113 When this occurs ignore the jump thread request with the joiner
2114 block. It's totally subsumed by the simpler jump thread request.
2116 This results in less block copying, simpler CFGs. More importantly,
2117 when we duplicate the joiner block, B, in this case we will create
2118 a new threading opportunity that we wouldn't be able to optimize
2119 until the next jump threading iteration.
2121 So first convert the jump thread requests which do not require a
2122 joiner block. */
2123 for (i = 0; i < paths.length (); i++)
2125 vec<jump_thread_edge *> *path = paths[i];
2127 if ((*path)[1]->type != EDGE_COPY_SRC_JOINER_BLOCK)
2129 edge e = (*path)[0]->e;
2130 e->aux = (void *)path;
2131 bitmap_set_bit (tmp, e->dest->index);
2135 /* Now iterate again, converting cases where we want to thread
2136 through a joiner block, but only if no other edge on the path
2137 already has a jump thread attached to it. We do this in two passes,
2138 to avoid situations where the order in the paths vec can hide overlapping
2139 threads (the path is recorded on the incoming edge, so we would miss
2140 cases where the second path starts at a downstream edge on the same
2141 path). First record all joiner paths, deleting any in the unexpected
2142 case where there is already a path for that incoming edge. */
2143 for (i = 0; i < paths.length (); i++)
2145 vec<jump_thread_edge *> *path = paths[i];
2147 if ((*path)[1]->type == EDGE_COPY_SRC_JOINER_BLOCK)
2149 /* Attach the path to the starting edge if none is yet recorded. */
2150 if ((*path)[0]->e->aux == NULL)
2151 (*path)[0]->e->aux = path;
2152 else if (dump_file && (dump_flags & TDF_DETAILS))
2153 dump_jump_thread_path (dump_file, *path, false);
2156 /* Second, look for paths that have any other jump thread attached to
2157 them, and either finish converting them or cancel them. */
2158 for (i = 0; i < paths.length (); i++)
2160 vec<jump_thread_edge *> *path = paths[i];
2161 edge e = (*path)[0]->e;
2163 if ((*path)[1]->type == EDGE_COPY_SRC_JOINER_BLOCK && e->aux == path)
2165 unsigned int j;
2166 for (j = 1; j < path->length (); j++)
2167 if ((*path)[j]->e->aux != NULL)
2168 break;
2170 /* If we iterated through the entire path without exiting the loop,
2171 then we are good to go, record it. */
2172 if (j == path->length ())
2173 bitmap_set_bit (tmp, e->dest->index);
2174 else
2176 e->aux = NULL;
2177 if (dump_file && (dump_flags & TDF_DETAILS))
2178 dump_jump_thread_path (dump_file, *path, false);
2183 /* If optimizing for size, only thread through block if we don't have
2184 to duplicate it or it's an otherwise empty redirection block. */
2185 if (optimize_function_for_size_p (cfun))
2187 EXECUTE_IF_SET_IN_BITMAP (tmp, 0, i, bi)
2189 bb = BASIC_BLOCK_FOR_FN (cfun, i);
2190 if (EDGE_COUNT (bb->preds) > 1
2191 && !redirection_block_p (bb))
2193 FOR_EACH_EDGE (e, ei, bb->preds)
2195 if (e->aux)
2197 vec<jump_thread_edge *> *path = THREAD_PATH (e);
2198 delete_jump_thread_path (path);
2199 e->aux = NULL;
2203 else
2204 bitmap_set_bit (threaded_blocks, i);
2207 else
2208 bitmap_copy (threaded_blocks, tmp);
2210 /* Look for jump threading paths which cross multiple loop headers.
2212 The code to thread through loop headers will change the CFG in ways
2213 that break assumptions made by the loop optimization code.
2215 We don't want to blindly cancel the requests. We can instead do better
2216 by trimming off the end of the jump thread path. */
2217 EXECUTE_IF_SET_IN_BITMAP (tmp, 0, i, bi)
2219 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, i);
2220 FOR_EACH_EDGE (e, ei, bb->preds)
2222 if (e->aux)
2224 vec<jump_thread_edge *> *path = THREAD_PATH (e);
2226 for (unsigned int i = 0, crossed_headers = 0;
2227 i < path->length ();
2228 i++)
2230 basic_block dest = (*path)[i]->e->dest;
2231 crossed_headers += (dest == dest->loop_father->header);
2232 if (crossed_headers > 1)
2234 /* Trim from entry I onwards. */
2235 for (unsigned int j = i; j < path->length (); j++)
2236 delete (*path)[j];
2237 path->truncate (i);
2239 /* Now that we've truncated the path, make sure
2240 what's left is still valid. We need at least
2241 two edges on the path and the last edge can not
2242 be a joiner. This should never happen, but let's
2243 be safe. */
2244 if (path->length () < 2
2245 || (path->last ()->type
2246 == EDGE_COPY_SRC_JOINER_BLOCK))
2248 delete_jump_thread_path (path);
2249 e->aux = NULL;
2251 break;
2258 /* If we have a joiner block (J) which has two successors S1 and S2 and
2259 we are threading though S1 and the final destination of the thread
2260 is S2, then we must verify that any PHI nodes in S2 have the same
2261 PHI arguments for the edge J->S2 and J->S1->...->S2.
2263 We used to detect this prior to registering the jump thread, but
2264 that prohibits propagation of edge equivalences into non-dominated
2265 PHI nodes as the equivalency test might occur before propagation.
2267 This must also occur after we truncate any jump threading paths
2268 as this scenario may only show up after truncation.
2270 This works for now, but will need improvement as part of the FSA
2271 optimization.
2273 Note since we've moved the thread request data to the edges,
2274 we have to iterate on those rather than the threaded_edges vector. */
2275 EXECUTE_IF_SET_IN_BITMAP (tmp, 0, i, bi)
2277 bb = BASIC_BLOCK_FOR_FN (cfun, i);
2278 FOR_EACH_EDGE (e, ei, bb->preds)
2280 if (e->aux)
2282 vec<jump_thread_edge *> *path = THREAD_PATH (e);
2283 bool have_joiner = ((*path)[1]->type == EDGE_COPY_SRC_JOINER_BLOCK);
2285 if (have_joiner)
2287 basic_block joiner = e->dest;
2288 edge final_edge = path->last ()->e;
2289 basic_block final_dest = final_edge->dest;
2290 edge e2 = find_edge (joiner, final_dest);
2292 if (e2 && !phi_args_equal_on_edges (e2, final_edge))
2294 delete_jump_thread_path (path);
2295 e->aux = NULL;
2302 BITMAP_FREE (tmp);
2306 /* Return TRUE if BB ends with a switch statement or a computed goto.
2307 Otherwise return false. */
2308 static bool
2309 bb_ends_with_multiway_branch (basic_block bb ATTRIBUTE_UNUSED)
2311 gimple stmt = last_stmt (bb);
2312 if (stmt && gimple_code (stmt) == GIMPLE_SWITCH)
2313 return true;
2314 if (stmt && gimple_code (stmt) == GIMPLE_GOTO
2315 && TREE_CODE (gimple_goto_dest (stmt)) == SSA_NAME)
2316 return true;
2317 return false;
2320 /* Walk through all blocks and thread incoming edges to the appropriate
2321 outgoing edge for each edge pair recorded in THREADED_EDGES.
2323 It is the caller's responsibility to fix the dominance information
2324 and rewrite duplicated SSA_NAMEs back into SSA form.
2326 If MAY_PEEL_LOOP_HEADERS is false, we avoid threading edges through
2327 loop headers if it does not simplify the loop.
2329 Returns true if one or more edges were threaded, false otherwise. */
2331 bool
2332 thread_through_all_blocks (bool may_peel_loop_headers)
2334 bool retval = false;
2335 unsigned int i;
2336 bitmap_iterator bi;
2337 bitmap threaded_blocks;
2338 struct loop *loop;
2340 if (!paths.exists ())
2341 return false;
2343 threaded_blocks = BITMAP_ALLOC (NULL);
2344 memset (&thread_stats, 0, sizeof (thread_stats));
2346 mark_threaded_blocks (threaded_blocks);
2348 initialize_original_copy_tables ();
2350 /* First perform the threading requests that do not affect
2351 loop structure. */
2352 EXECUTE_IF_SET_IN_BITMAP (threaded_blocks, 0, i, bi)
2354 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, i);
2356 if (EDGE_COUNT (bb->preds) > 0)
2357 retval |= thread_block (bb, true);
2360 /* Then perform the threading through loop headers. We start with the
2361 innermost loop, so that the changes in cfg we perform won't affect
2362 further threading. */
2363 FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
2365 if (!loop->header
2366 || !bitmap_bit_p (threaded_blocks, loop->header->index))
2367 continue;
2369 retval |= thread_through_loop_header (loop, may_peel_loop_headers);
2372 /* Any jump threading paths that are still attached to edges at this
2373 point must be one of two cases.
2375 First, we could have a jump threading path which went from outside
2376 a loop to inside a loop that was ignored because a prior jump thread
2377 across a backedge was realized (which indirectly causes the loop
2378 above to ignore the latter thread). We can detect these because the
2379 loop structures will be different and we do not currently try to
2380 optimize this case.
2382 Second, we could be threading across a backedge to a point within the
2383 same loop. This occurrs for the FSA/FSM optimization and we would
2384 like to optimize it. However, we have to be very careful as this
2385 may completely scramble the loop structures, with the result being
2386 irreducible loops causing us to throw away our loop structure.
2388 As a compromise for the latter case, if the thread path ends in
2389 a block where the last statement is a multiway branch, then go
2390 ahead and thread it, else ignore it. */
2391 basic_block bb;
2392 edge e;
2393 FOR_EACH_BB_FN (bb, cfun)
2395 /* If we do end up threading here, we can remove elements from
2396 BB->preds. Thus we can not use the FOR_EACH_EDGE iterator. */
2397 for (edge_iterator ei = ei_start (bb->preds);
2398 (e = ei_safe_edge (ei));)
2399 if (e->aux)
2401 vec<jump_thread_edge *> *path = THREAD_PATH (e);
2403 /* Case 1, threading from outside to inside the loop
2404 after we'd already threaded through the header. */
2405 if ((*path)[0]->e->dest->loop_father
2406 != path->last ()->e->src->loop_father)
2408 delete_jump_thread_path (path);
2409 e->aux = NULL;
2410 ei_next (&ei);
2412 else if (bb_ends_with_multiway_branch (path->last ()->e->src))
2414 /* The code to thread through loop headers may have
2415 split a block with jump threads attached to it.
2417 We can identify this with a disjoint jump threading
2418 path. If found, just remove it. */
2419 for (unsigned int i = 0; i < path->length () - 1; i++)
2420 if ((*path)[i]->e->dest != (*path)[i + 1]->e->src)
2422 delete_jump_thread_path (path);
2423 e->aux = NULL;
2424 ei_next (&ei);
2425 break;
2428 /* Our path is still valid, thread it. */
2429 if (e->aux)
2431 struct loop *loop = (*path)[0]->e->dest->loop_father;
2433 if (thread_block ((*path)[0]->e->dest, false))
2435 /* This jump thread likely totally scrambled this loop.
2436 So arrange for it to be fixed up. */
2437 loop->header = NULL;
2438 loop->latch = NULL;
2439 e->aux = NULL;
2441 else
2443 delete_jump_thread_path (path);
2444 e->aux = NULL;
2445 ei_next (&ei);
2449 else
2451 delete_jump_thread_path (path);
2452 e->aux = NULL;
2453 ei_next (&ei);
2456 else
2457 ei_next (&ei);
2460 statistics_counter_event (cfun, "Jumps threaded",
2461 thread_stats.num_threaded_edges);
2463 free_original_copy_tables ();
2465 BITMAP_FREE (threaded_blocks);
2466 threaded_blocks = NULL;
2467 paths.release ();
2469 if (retval)
2470 loops_state_set (LOOPS_NEED_FIXUP);
2472 return retval;
2475 /* Delete the jump threading path PATH. We have to explcitly delete
2476 each entry in the vector, then the container. */
2478 void
2479 delete_jump_thread_path (vec<jump_thread_edge *> *path)
2481 for (unsigned int i = 0; i < path->length (); i++)
2482 delete (*path)[i];
2483 path->release();
2486 /* Register a jump threading opportunity. We queue up all the jump
2487 threading opportunities discovered by a pass and update the CFG
2488 and SSA form all at once.
2490 E is the edge we can thread, E2 is the new target edge, i.e., we
2491 are effectively recording that E->dest can be changed to E2->dest
2492 after fixing the SSA graph. */
2494 void
2495 register_jump_thread (vec<jump_thread_edge *> *path)
2497 if (!dbg_cnt (registered_jump_thread))
2499 delete_jump_thread_path (path);
2500 return;
2503 /* First make sure there are no NULL outgoing edges on the jump threading
2504 path. That can happen for jumping to a constant address. */
2505 for (unsigned int i = 0; i < path->length (); i++)
2506 if ((*path)[i]->e == NULL)
2508 if (dump_file && (dump_flags & TDF_DETAILS))
2510 fprintf (dump_file,
2511 "Found NULL edge in jump threading path. Cancelling jump thread:\n");
2512 dump_jump_thread_path (dump_file, *path, false);
2515 delete_jump_thread_path (path);
2516 return;
2519 if (dump_file && (dump_flags & TDF_DETAILS))
2520 dump_jump_thread_path (dump_file, *path, true);
2522 if (!paths.exists ())
2523 paths.create (5);
2525 paths.safe_push (path);