OSDN Git Service

PR c++/46245
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-threadupdate.c
1 /* Thread edges through blocks and update the control flow and SSA graphs.
2    Copyright (C) 2004, 2005, 2006, 2007, 2008, 2010 Free Software Foundation,
3    Inc.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "tree.h"
26 #include "flags.h"
27 #include "tm_p.h"
28 #include "basic-block.h"
29 #include "output.h"
30 #include "function.h"
31 #include "tree-flow.h"
32 #include "tree-dump.h"
33 #include "tree-pass.h"
34 #include "cfgloop.h"
35
36 /* Given a block B, update the CFG and SSA graph to reflect redirecting
37    one or more in-edges to B to instead reach the destination of an
38    out-edge from B while preserving any side effects in B.
39
40    i.e., given A->B and B->C, change A->B to be A->C yet still preserve the
41    side effects of executing B.
42
43      1. Make a copy of B (including its outgoing edges and statements).  Call
44         the copy B'.  Note B' has no incoming edges or PHIs at this time.
45
46      2. Remove the control statement at the end of B' and all outgoing edges
47         except B'->C.
48
49      3. Add a new argument to each PHI in C with the same value as the existing
50         argument associated with edge B->C.  Associate the new PHI arguments
51         with the edge B'->C.
52
53      4. For each PHI in B, find or create a PHI in B' with an identical
54         PHI_RESULT.  Add an argument to the PHI in B' which has the same
55         value as the PHI in B associated with the edge A->B.  Associate
56         the new argument in the PHI in B' with the edge A->B.
57
58      5. Change the edge A->B to A->B'.
59
60         5a. This automatically deletes any PHI arguments associated with the
61             edge A->B in B.
62
63         5b. This automatically associates each new argument added in step 4
64             with the edge A->B'.
65
66      6. Repeat for other incoming edges into B.
67
68      7. Put the duplicated resources in B and all the B' blocks into SSA form.
69
70    Note that block duplication can be minimized by first collecting the
71    set of unique destination blocks that the incoming edges should
72    be threaded to.
73
74    Block duplication can be further minimized by using B instead of 
75    creating B' for one destination if all edges into B are going to be
76    threaded to a successor of B.  We had code to do this at one time, but
77    I'm not convinced it is correct with the changes to avoid mucking up
78    the loop structure (which may cancel threading requests, thus a block
79    which we thought was going to become unreachable may still be reachable).
80    This code was also going to get ugly with the introduction of the ability
81    for a single jump thread request to bypass multiple blocks. 
82
83    We further reduce the number of edges and statements we create by
84    not copying all the outgoing edges and the control statement in
85    step #1.  We instead create a template block without the outgoing
86    edges and duplicate the template.  */
87
88
89 /* Steps #5 and #6 of the above algorithm are best implemented by walking
90    all the incoming edges which thread to the same destination edge at
91    the same time.  That avoids lots of table lookups to get information
92    for the destination edge.
93
94    To realize that implementation we create a list of incoming edges
95    which thread to the same outgoing edge.  Thus to implement steps
96    #5 and #6 we traverse our hash table of outgoing edge information.
97    For each entry we walk the list of incoming edges which thread to
98    the current outgoing edge.  */
99
100 struct el
101 {
102   edge e;
103   struct el *next;
104 };
105
106 /* Main data structure recording information regarding B's duplicate
107    blocks.  */
108
109 /* We need to efficiently record the unique thread destinations of this
110    block and specific information associated with those destinations.  We
111    may have many incoming edges threaded to the same outgoing edge.  This
112    can be naturally implemented with a hash table.  */
113
114 struct redirection_data
115 {
116   /* A duplicate of B with the trailing control statement removed and which
117      targets a single successor of B.  */
118   basic_block dup_block;
119
120   /* An outgoing edge from B.  DUP_BLOCK will have OUTGOING_EDGE->dest as
121      its single successor.  */
122   edge outgoing_edge;
123
124   /* A list of incoming edges which we want to thread to
125      OUTGOING_EDGE->dest.  */
126   struct el *incoming_edges;
127 };
128
129 /* Main data structure to hold information for duplicates of BB.  */
130 static htab_t redirection_data;
131
132 /* Data structure of information to pass to hash table traversal routines.  */
133 struct local_info
134 {
135   /* The current block we are working on.  */
136   basic_block bb;
137
138   /* A template copy of BB with no outgoing edges or control statement that
139      we use for creating copies.  */
140   basic_block template_block;
141
142   /* TRUE if we thread one or more jumps, FALSE otherwise.  */
143   bool jumps_threaded;
144 };
145
146 /* Passes which use the jump threading code register jump threading
147    opportunities as they are discovered.  We keep the registered
148    jump threading opportunities in this vector as edge pairs
149    (original_edge, target_edge).  */
150 static VEC(edge,heap) *threaded_edges;
151
152 /* When we start updating the CFG for threading, data necessary for jump
153    threading is attached to the AUX field for the incoming edge.  Use these
154    macros to access the underlying structure attached to the AUX field.  */
155 #define THREAD_TARGET(E) ((edge *)(E)->aux)[0]
156
157 /* Jump threading statistics.  */
158
159 struct thread_stats_d
160 {
161   unsigned long num_threaded_edges;
162 };
163
164 struct thread_stats_d thread_stats;
165
166
167 /* Remove the last statement in block BB if it is a control statement
168    Also remove all outgoing edges except the edge which reaches DEST_BB.
169    If DEST_BB is NULL, then remove all outgoing edges.  */
170
171 static void
172 remove_ctrl_stmt_and_useless_edges (basic_block bb, basic_block dest_bb)
173 {
174   gimple_stmt_iterator gsi;
175   edge e;
176   edge_iterator ei;
177
178   gsi = gsi_last_bb (bb);
179
180   /* If the duplicate ends with a control statement, then remove it.
181
182      Note that if we are duplicating the template block rather than the
183      original basic block, then the duplicate might not have any real
184      statements in it.  */
185   if (!gsi_end_p (gsi)
186       && gsi_stmt (gsi)
187       && (gimple_code (gsi_stmt (gsi)) == GIMPLE_COND
188           || gimple_code (gsi_stmt (gsi)) == GIMPLE_GOTO
189           || gimple_code (gsi_stmt (gsi)) == GIMPLE_SWITCH))
190     gsi_remove (&gsi, true);
191
192   for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
193     {
194       if (e->dest != dest_bb)
195         remove_edge (e);
196       else
197         ei_next (&ei);
198     }
199 }
200
201 /* Create a duplicate of BB.  Record the duplicate block in RD.  */
202
203 static void
204 create_block_for_threading (basic_block bb, struct redirection_data *rd)
205 {
206   edge_iterator ei;
207   edge e;
208
209   /* We can use the generic block duplication code and simply remove
210      the stuff we do not need.  */
211   rd->dup_block = duplicate_block (bb, NULL, NULL);
212
213   FOR_EACH_EDGE (e, ei, rd->dup_block->succs)
214     e->aux = NULL;
215
216   /* Zero out the profile, since the block is unreachable for now.  */
217   rd->dup_block->frequency = 0;
218   rd->dup_block->count = 0;
219 }
220
221 /* Hashing and equality routines for our hash table.  */
222 static hashval_t
223 redirection_data_hash (const void *p)
224 {
225   edge e = ((const struct redirection_data *)p)->outgoing_edge;
226   return e->dest->index;
227 }
228
229 static int
230 redirection_data_eq (const void *p1, const void *p2)
231 {
232   edge e1 = ((const struct redirection_data *)p1)->outgoing_edge;
233   edge e2 = ((const struct redirection_data *)p2)->outgoing_edge;
234
235   return e1 == e2;
236 }
237
238 /* Given an outgoing edge E lookup and return its entry in our hash table.
239
240    If INSERT is true, then we insert the entry into the hash table if
241    it is not already present.  INCOMING_EDGE is added to the list of incoming
242    edges associated with E in the hash table.  */
243
244 static struct redirection_data *
245 lookup_redirection_data (edge e, edge incoming_edge, enum insert_option insert)
246 {
247   void **slot;
248   struct redirection_data *elt;
249
250  /* Build a hash table element so we can see if E is already
251      in the table.  */
252   elt = XNEW (struct redirection_data);
253   elt->outgoing_edge = e;
254   elt->dup_block = NULL;
255   elt->incoming_edges = NULL;
256
257   slot = htab_find_slot (redirection_data, elt, insert);
258
259   /* This will only happen if INSERT is false and the entry is not
260      in the hash table.  */
261   if (slot == NULL)
262     {
263       free (elt);
264       return NULL;
265     }
266
267   /* This will only happen if E was not in the hash table and
268      INSERT is true.  */
269   if (*slot == NULL)
270     {
271       *slot = (void *)elt;
272       elt->incoming_edges = XNEW (struct el);
273       elt->incoming_edges->e = incoming_edge;
274       elt->incoming_edges->next = NULL;
275       return elt;
276     }
277   /* E was in the hash table.  */
278   else
279     {
280       /* Free ELT as we do not need it anymore, we will extract the
281          relevant entry from the hash table itself.  */
282       free (elt);
283
284       /* Get the entry stored in the hash table.  */
285       elt = (struct redirection_data *) *slot;
286
287       /* If insertion was requested, then we need to add INCOMING_EDGE
288          to the list of incoming edges associated with E.  */
289       if (insert)
290         {
291           struct el *el = XNEW (struct el);
292           el->next = elt->incoming_edges;
293           el->e = incoming_edge;
294           elt->incoming_edges = el;
295         }
296
297       return elt;
298     }
299 }
300
301 /* Given a duplicate block and its single destination (both stored
302    in RD).  Create an edge between the duplicate and its single
303    destination.
304
305    Add an additional argument to any PHI nodes at the single
306    destination.  */
307
308 static void
309 create_edge_and_update_destination_phis (struct redirection_data *rd,
310                                          basic_block bb)
311 {
312   edge e = make_edge (bb, rd->outgoing_edge->dest, EDGE_FALLTHRU);
313   gimple_stmt_iterator gsi;
314
315   rescan_loop_exit (e, true, false);
316   e->probability = REG_BR_PROB_BASE;
317   e->count = bb->count;
318
319   if (rd->outgoing_edge->aux)
320     {
321       e->aux = (edge *) XNEWVEC (edge, 1);
322       THREAD_TARGET(e) = THREAD_TARGET (rd->outgoing_edge);
323     }
324   else
325     {
326       e->aux = NULL;
327     }
328
329   /* If there are any PHI nodes at the destination of the outgoing edge
330      from the duplicate block, then we will need to add a new argument
331      to them.  The argument should have the same value as the argument
332      associated with the outgoing edge stored in RD.  */
333   for (gsi = gsi_start_phis (e->dest); !gsi_end_p (gsi); gsi_next (&gsi))
334     {
335       gimple phi = gsi_stmt (gsi);
336       source_location locus;
337       int indx = rd->outgoing_edge->dest_idx;
338
339       locus = gimple_phi_arg_location (phi, indx);
340       add_phi_arg (phi, gimple_phi_arg_def (phi, indx), e, locus);
341     }
342 }
343
344 /* Hash table traversal callback routine to create duplicate blocks.  */
345
346 static int
347 create_duplicates (void **slot, void *data)
348 {
349   struct redirection_data *rd = (struct redirection_data *) *slot;
350   struct local_info *local_info = (struct local_info *)data;
351
352   /* Create a template block if we have not done so already.  Otherwise
353      use the template to create a new block.  */
354   if (local_info->template_block == NULL)
355     {
356       create_block_for_threading (local_info->bb, rd);
357       local_info->template_block = rd->dup_block;
358
359       /* We do not create any outgoing edges for the template.  We will
360          take care of that in a later traversal.  That way we do not
361          create edges that are going to just be deleted.  */
362     }
363   else
364     {
365       create_block_for_threading (local_info->template_block, rd);
366
367       /* Go ahead and wire up outgoing edges and update PHIs for the duplicate
368          block.  */
369       remove_ctrl_stmt_and_useless_edges (rd->dup_block, NULL);
370       create_edge_and_update_destination_phis (rd, rd->dup_block);
371     }
372
373   /* Keep walking the hash table.  */
374   return 1;
375 }
376
377 /* We did not create any outgoing edges for the template block during
378    block creation.  This hash table traversal callback creates the
379    outgoing edge for the template block.  */
380
381 static int
382 fixup_template_block (void **slot, void *data)
383 {
384   struct redirection_data *rd = (struct redirection_data *) *slot;
385   struct local_info *local_info = (struct local_info *)data;
386
387   /* If this is the template block, then create its outgoing edges
388      and halt the hash table traversal.  */
389   if (rd->dup_block && rd->dup_block == local_info->template_block)
390     {
391       remove_ctrl_stmt_and_useless_edges (rd->dup_block, NULL);
392       create_edge_and_update_destination_phis (rd, rd->dup_block);
393       return 0;
394     }
395
396   return 1;
397 }
398
399 /* Hash table traversal callback to redirect each incoming edge
400    associated with this hash table element to its new destination.  */
401
402 static int
403 redirect_edges (void **slot, void *data)
404 {
405   struct redirection_data *rd = (struct redirection_data *) *slot;
406   struct local_info *local_info = (struct local_info *)data;
407   struct el *next, *el;
408
409   /* Walk over all the incoming edges associated associated with this
410      hash table entry.  */
411   for (el = rd->incoming_edges; el; el = next)
412     {
413       edge e = el->e;
414
415       /* Go ahead and free this element from the list.  Doing this now
416          avoids the need for another list walk when we destroy the hash
417          table.  */
418       next = el->next;
419       free (el);
420
421       thread_stats.num_threaded_edges++;
422
423       if (rd->dup_block)
424         {
425           edge e2;
426
427           if (dump_file && (dump_flags & TDF_DETAILS))
428             fprintf (dump_file, "  Threaded jump %d --> %d to %d\n",
429                      e->src->index, e->dest->index, rd->dup_block->index);
430
431           rd->dup_block->count += e->count;
432           rd->dup_block->frequency += EDGE_FREQUENCY (e);
433           EDGE_SUCC (rd->dup_block, 0)->count += e->count;
434           /* Redirect the incoming edge to the appropriate duplicate
435              block.  */
436           e2 = redirect_edge_and_branch (e, rd->dup_block);
437           gcc_assert (e == e2);
438           flush_pending_stmts (e2);
439         }
440
441       /* Go ahead and clear E->aux.  It's not needed anymore and failure
442          to clear it will cause all kinds of unpleasant problems later.  */
443       free (e->aux);
444       e->aux = NULL;
445
446     }
447
448   /* Indicate that we actually threaded one or more jumps.  */
449   if (rd->incoming_edges)
450     local_info->jumps_threaded = true;
451
452   return 1;
453 }
454
455 /* Return true if this block has no executable statements other than
456    a simple ctrl flow instruction.  When the number of outgoing edges
457    is one, this is equivalent to a "forwarder" block.  */
458
459 static bool
460 redirection_block_p (basic_block bb)
461 {
462   gimple_stmt_iterator gsi;
463
464   /* Advance to the first executable statement.  */
465   gsi = gsi_start_bb (bb);
466   while (!gsi_end_p (gsi)
467          && (gimple_code (gsi_stmt (gsi)) == GIMPLE_LABEL
468              || is_gimple_debug (gsi_stmt (gsi))
469              || gimple_nop_p (gsi_stmt (gsi))))
470     gsi_next (&gsi);
471
472   /* Check if this is an empty block.  */
473   if (gsi_end_p (gsi))
474     return true;
475
476   /* Test that we've reached the terminating control statement.  */
477   return gsi_stmt (gsi)
478          && (gimple_code (gsi_stmt (gsi)) == GIMPLE_COND
479              || gimple_code (gsi_stmt (gsi)) == GIMPLE_GOTO
480              || gimple_code (gsi_stmt (gsi)) == GIMPLE_SWITCH);
481 }
482
483 /* BB is a block which ends with a COND_EXPR or SWITCH_EXPR and when BB
484    is reached via one or more specific incoming edges, we know which
485    outgoing edge from BB will be traversed.
486
487    We want to redirect those incoming edges to the target of the
488    appropriate outgoing edge.  Doing so avoids a conditional branch
489    and may expose new optimization opportunities.  Note that we have
490    to update dominator tree and SSA graph after such changes.
491
492    The key to keeping the SSA graph update manageable is to duplicate
493    the side effects occurring in BB so that those side effects still
494    occur on the paths which bypass BB after redirecting edges.
495
496    We accomplish this by creating duplicates of BB and arranging for
497    the duplicates to unconditionally pass control to one specific
498    successor of BB.  We then revector the incoming edges into BB to
499    the appropriate duplicate of BB.
500
501    If NOLOOP_ONLY is true, we only perform the threading as long as it
502    does not affect the structure of the loops in a nontrivial way.  */
503
504 static bool
505 thread_block (basic_block bb, bool noloop_only)
506 {
507   /* E is an incoming edge into BB that we may or may not want to
508      redirect to a duplicate of BB.  */
509   edge e, e2;
510   edge_iterator ei;
511   struct local_info local_info;
512   struct loop *loop = bb->loop_father;
513
514   /* To avoid scanning a linear array for the element we need we instead
515      use a hash table.  For normal code there should be no noticeable
516      difference.  However, if we have a block with a large number of
517      incoming and outgoing edges such linear searches can get expensive.  */
518   redirection_data = htab_create (EDGE_COUNT (bb->succs),
519                                   redirection_data_hash,
520                                   redirection_data_eq,
521                                   free);
522
523   /* If we thread the latch of the loop to its exit, the loop ceases to
524      exist.  Make sure we do not restrict ourselves in order to preserve
525      this loop.  */
526   if (loop->header == bb)
527     {
528       e = loop_latch_edge (loop);
529
530       if (e->aux)
531         e2 = THREAD_TARGET (e);
532       else
533         e2 = NULL;
534
535       if (e2 && loop_exit_edge_p (loop, e2))
536         {
537           loop->header = NULL;
538           loop->latch = NULL;
539         }
540     }
541
542   /* Record each unique threaded destination into a hash table for
543      efficient lookups.  */
544   FOR_EACH_EDGE (e, ei, bb->preds)
545     {
546       if (e->aux == NULL)
547         continue;
548
549       e2 = THREAD_TARGET (e);
550
551       if (!e2
552           /* If NOLOOP_ONLY is true, we only allow threading through the
553              header of a loop to exit edges.  */
554           || (noloop_only
555               && bb == bb->loop_father->header
556               && (!loop_exit_edge_p (bb->loop_father, e2))))
557         continue;
558
559       if (e->dest == e2->src)
560         update_bb_profile_for_threading (e->dest, EDGE_FREQUENCY (e),
561                                          e->count, THREAD_TARGET (e));
562
563       /* Insert the outgoing edge into the hash table if it is not
564          already in the hash table.  */
565       lookup_redirection_data (e2, e, INSERT);
566     }
567
568   /* We do not update dominance info.  */
569   free_dominance_info (CDI_DOMINATORS);
570
571   /* Now create duplicates of BB.
572
573      Note that for a block with a high outgoing degree we can waste
574      a lot of time and memory creating and destroying useless edges.
575
576      So we first duplicate BB and remove the control structure at the
577      tail of the duplicate as well as all outgoing edges from the
578      duplicate.  We then use that duplicate block as a template for
579      the rest of the duplicates.  */
580   local_info.template_block = NULL;
581   local_info.bb = bb;
582   local_info.jumps_threaded = false;
583   htab_traverse (redirection_data, create_duplicates, &local_info);
584
585   /* The template does not have an outgoing edge.  Create that outgoing
586      edge and update PHI nodes as the edge's target as necessary.
587
588      We do this after creating all the duplicates to avoid creating
589      unnecessary edges.  */
590   htab_traverse (redirection_data, fixup_template_block, &local_info);
591
592   /* The hash table traversals above created the duplicate blocks (and the
593      statements within the duplicate blocks).  This loop creates PHI nodes for
594      the duplicated blocks and redirects the incoming edges into BB to reach
595      the duplicates of BB.  */
596   htab_traverse (redirection_data, redirect_edges, &local_info);
597
598   /* Done with this block.  Clear REDIRECTION_DATA.  */
599   htab_delete (redirection_data);
600   redirection_data = NULL;
601
602   /* Indicate to our caller whether or not any jumps were threaded.  */
603   return local_info.jumps_threaded;
604 }
605
606 /* Threads edge E through E->dest to the edge THREAD_TARGET (E).  Returns the
607    copy of E->dest created during threading, or E->dest if it was not necessary
608    to copy it (E is its single predecessor).  */
609
610 static basic_block
611 thread_single_edge (edge e)
612 {
613   basic_block bb = e->dest;
614   edge eto = THREAD_TARGET (e);
615   struct redirection_data rd;
616
617   free (e->aux);
618   e->aux = NULL;
619
620   thread_stats.num_threaded_edges++;
621
622   if (single_pred_p (bb))
623     {
624       /* If BB has just a single predecessor, we should only remove the
625          control statements at its end, and successors except for ETO.  */
626       remove_ctrl_stmt_and_useless_edges (bb, eto->dest);
627
628       /* And fixup the flags on the single remaining edge.  */
629       eto->flags &= ~(EDGE_TRUE_VALUE | EDGE_FALSE_VALUE | EDGE_ABNORMAL);
630       eto->flags |= EDGE_FALLTHRU;
631
632       return bb;
633     }
634
635   /* Otherwise, we need to create a copy.  */
636   if (e->dest == eto->src)
637     update_bb_profile_for_threading (bb, EDGE_FREQUENCY (e), e->count, eto);
638
639   rd.outgoing_edge = eto;
640
641   create_block_for_threading (bb, &rd);
642   remove_ctrl_stmt_and_useless_edges (rd.dup_block, NULL);
643   create_edge_and_update_destination_phis (&rd, rd.dup_block);
644
645   if (dump_file && (dump_flags & TDF_DETAILS))
646     fprintf (dump_file, "  Threaded jump %d --> %d to %d\n",
647              e->src->index, e->dest->index, rd.dup_block->index);
648
649   rd.dup_block->count = e->count;
650   rd.dup_block->frequency = EDGE_FREQUENCY (e);
651   single_succ_edge (rd.dup_block)->count = e->count;
652   redirect_edge_and_branch (e, rd.dup_block);
653   flush_pending_stmts (e);
654
655   return rd.dup_block;
656 }
657
658 /* Callback for dfs_enumerate_from.  Returns true if BB is different
659    from STOP and DBDS_CE_STOP.  */
660
661 static basic_block dbds_ce_stop;
662 static bool
663 dbds_continue_enumeration_p (const_basic_block bb, const void *stop)
664 {
665   return (bb != (const_basic_block) stop
666           && bb != dbds_ce_stop);
667 }
668
669 /* Evaluates the dominance relationship of latch of the LOOP and BB, and
670    returns the state.  */
671
672 enum bb_dom_status
673 {
674   /* BB does not dominate latch of the LOOP.  */
675   DOMST_NONDOMINATING,
676   /* The LOOP is broken (there is no path from the header to its latch.  */
677   DOMST_LOOP_BROKEN,
678   /* BB dominates the latch of the LOOP.  */
679   DOMST_DOMINATING
680 };
681
682 static enum bb_dom_status
683 determine_bb_domination_status (struct loop *loop, basic_block bb)
684 {
685   basic_block *bblocks;
686   unsigned nblocks, i;
687   bool bb_reachable = false;
688   edge_iterator ei;
689   edge e;
690
691   /* This function assumes BB is a successor of LOOP->header.
692      If that is not the case return DOMST_NONDOMINATING which
693      is always safe.  */
694     {
695       bool ok = false;
696
697       FOR_EACH_EDGE (e, ei, bb->preds)
698         {
699           if (e->src == loop->header)
700             {
701               ok = true;
702               break;
703             }
704         }
705
706       if (!ok)
707         return DOMST_NONDOMINATING;
708     }
709
710   if (bb == loop->latch)
711     return DOMST_DOMINATING;
712
713   /* Check that BB dominates LOOP->latch, and that it is back-reachable
714      from it.  */
715
716   bblocks = XCNEWVEC (basic_block, loop->num_nodes);
717   dbds_ce_stop = loop->header;
718   nblocks = dfs_enumerate_from (loop->latch, 1, dbds_continue_enumeration_p,
719                                 bblocks, loop->num_nodes, bb);
720   for (i = 0; i < nblocks; i++)
721     FOR_EACH_EDGE (e, ei, bblocks[i]->preds)
722       {
723         if (e->src == loop->header)
724           {
725             free (bblocks);
726             return DOMST_NONDOMINATING;
727           }
728         if (e->src == bb)
729           bb_reachable = true;
730       }
731
732   free (bblocks);
733   return (bb_reachable ? DOMST_DOMINATING : DOMST_LOOP_BROKEN);
734 }
735
736 /* Thread jumps through the header of LOOP.  Returns true if cfg changes.
737    If MAY_PEEL_LOOP_HEADERS is false, we avoid threading from entry edges
738    to the inside of the loop.  */
739
740 static bool
741 thread_through_loop_header (struct loop *loop, bool may_peel_loop_headers)
742 {
743   basic_block header = loop->header;
744   edge e, tgt_edge, latch = loop_latch_edge (loop);
745   edge_iterator ei;
746   basic_block tgt_bb, atgt_bb;
747   enum bb_dom_status domst;
748
749   /* We have already threaded through headers to exits, so all the threading
750      requests now are to the inside of the loop.  We need to avoid creating
751      irreducible regions (i.e., loops with more than one entry block), and
752      also loop with several latch edges, or new subloops of the loop (although
753      there are cases where it might be appropriate, it is difficult to decide,
754      and doing it wrongly may confuse other optimizers).
755
756      We could handle more general cases here.  However, the intention is to
757      preserve some information about the loop, which is impossible if its
758      structure changes significantly, in a way that is not well understood.
759      Thus we only handle few important special cases, in which also updating
760      of the loop-carried information should be feasible:
761
762      1) Propagation of latch edge to a block that dominates the latch block
763         of a loop.  This aims to handle the following idiom:
764
765         first = 1;
766         while (1)
767           {
768             if (first)
769               initialize;
770             first = 0;
771             body;
772           }
773
774         After threading the latch edge, this becomes
775
776         first = 1;
777         if (first)
778           initialize;
779         while (1)
780           {
781             first = 0;
782             body;
783           }
784
785         The original header of the loop is moved out of it, and we may thread
786         the remaining edges through it without further constraints.
787
788      2) All entry edges are propagated to a single basic block that dominates
789         the latch block of the loop.  This aims to handle the following idiom
790         (normally created for "for" loops):
791
792         i = 0;
793         while (1)
794           {
795             if (i >= 100)
796               break;
797             body;
798             i++;
799           }
800
801         This becomes
802
803         i = 0;
804         while (1)
805           {
806             body;
807             i++;
808             if (i >= 100)
809               break;
810           }
811      */
812
813   /* Threading through the header won't improve the code if the header has just
814      one successor.  */
815   if (single_succ_p (header))
816     goto fail;
817
818   if (latch->aux)
819     {
820       tgt_edge = THREAD_TARGET (latch);
821       tgt_bb = tgt_edge->dest;
822     }
823   else if (!may_peel_loop_headers
824            && !redirection_block_p (loop->header))
825     goto fail;
826   else
827     {
828       tgt_bb = NULL;
829       tgt_edge = NULL;
830       FOR_EACH_EDGE (e, ei, header->preds)
831         {
832           if (!e->aux)
833             {
834               if (e == latch)
835                 continue;
836
837               /* If latch is not threaded, and there is a header
838                  edge that is not threaded, we would create loop
839                  with multiple entries.  */
840               goto fail;
841             }
842
843           tgt_edge = THREAD_TARGET (e);
844           atgt_bb = tgt_edge->dest;
845           if (!tgt_bb)
846             tgt_bb = atgt_bb;
847           /* Two targets of threading would make us create loop
848              with multiple entries.  */
849           else if (tgt_bb != atgt_bb)
850             goto fail;
851         }
852
853       if (!tgt_bb)
854         {
855           /* There are no threading requests.  */
856           return false;
857         }
858
859       /* Redirecting to empty loop latch is useless.  */
860       if (tgt_bb == loop->latch
861           && empty_block_p (loop->latch))
862         goto fail;
863     }
864
865   /* The target block must dominate the loop latch, otherwise we would be
866      creating a subloop.  */
867   domst = determine_bb_domination_status (loop, tgt_bb);
868   if (domst == DOMST_NONDOMINATING)
869     goto fail;
870   if (domst == DOMST_LOOP_BROKEN)
871     {
872       /* If the loop ceased to exist, mark it as such, and thread through its
873          original header.  */
874       loop->header = NULL;
875       loop->latch = NULL;
876       return thread_block (header, false);
877     }
878
879   if (tgt_bb->loop_father->header == tgt_bb)
880     {
881       /* If the target of the threading is a header of a subloop, we need
882          to create a preheader for it, so that the headers of the two loops
883          do not merge.  */
884       if (EDGE_COUNT (tgt_bb->preds) > 2)
885         {
886           tgt_bb = create_preheader (tgt_bb->loop_father, 0);
887           gcc_assert (tgt_bb != NULL);
888         }
889       else
890         tgt_bb = split_edge (tgt_edge);
891     }
892
893   if (latch->aux)
894     {
895       /* First handle the case latch edge is redirected.  */
896       loop->latch = thread_single_edge (latch);
897       gcc_assert (single_succ (loop->latch) == tgt_bb);
898       loop->header = tgt_bb;
899
900       /* Thread the remaining edges through the former header.  */
901       thread_block (header, false);
902     }
903   else
904     {
905       basic_block new_preheader;
906
907       /* Now consider the case entry edges are redirected to the new entry
908          block.  Remember one entry edge, so that we can find the new
909          preheader (its destination after threading).  */
910       FOR_EACH_EDGE (e, ei, header->preds)
911         {
912           if (e->aux)
913             break;
914         }
915
916       /* The duplicate of the header is the new preheader of the loop.  Ensure
917          that it is placed correctly in the loop hierarchy.  */
918       set_loop_copy (loop, loop_outer (loop));
919
920       thread_block (header, false);
921       set_loop_copy (loop, NULL);
922       new_preheader = e->dest;
923
924       /* Create the new latch block.  This is always necessary, as the latch
925          must have only a single successor, but the original header had at
926          least two successors.  */
927       loop->latch = NULL;
928       mfb_kj_edge = single_succ_edge (new_preheader);
929       loop->header = mfb_kj_edge->dest;
930       latch = make_forwarder_block (tgt_bb, mfb_keep_just, NULL);
931       loop->header = latch->dest;
932       loop->latch = latch->src;
933     }
934
935   return true;
936
937 fail:
938   /* We failed to thread anything.  Cancel the requests.  */
939   FOR_EACH_EDGE (e, ei, header->preds)
940     {
941       free (e->aux);
942       e->aux = NULL;
943     }
944   return false;
945 }
946
947 /* Walk through the registered jump threads and convert them into a
948    form convenient for this pass.
949
950    Any block which has incoming edges threaded to outgoing edges
951    will have its entry in THREADED_BLOCK set.
952
953    Any threaded edge will have its new outgoing edge stored in the
954    original edge's AUX field.
955
956    This form avoids the need to walk all the edges in the CFG to
957    discover blocks which need processing and avoids unnecessary
958    hash table lookups to map from threaded edge to new target.  */
959
960 static void
961 mark_threaded_blocks (bitmap threaded_blocks)
962 {
963   unsigned int i;
964   bitmap_iterator bi;
965   bitmap tmp = BITMAP_ALLOC (NULL);
966   basic_block bb;
967   edge e;
968   edge_iterator ei;
969
970   for (i = 0; i < VEC_length (edge, threaded_edges); i += 2)
971     {
972       edge e = VEC_index (edge, threaded_edges, i);
973       edge *x = (edge *) XNEWVEC (edge, 1);
974
975       e->aux = x;
976       THREAD_TARGET (e) = VEC_index (edge, threaded_edges, i + 1);
977       bitmap_set_bit (tmp, e->dest->index);
978     }
979
980   /* If optimizing for size, only thread through block if we don't have
981      to duplicate it or it's an otherwise empty redirection block.  */
982   if (optimize_function_for_size_p (cfun))
983     {
984       EXECUTE_IF_SET_IN_BITMAP (tmp, 0, i, bi)
985         {
986           bb = BASIC_BLOCK (i);
987           if (EDGE_COUNT (bb->preds) > 1
988               && !redirection_block_p (bb))
989             {
990               FOR_EACH_EDGE (e, ei, bb->preds)
991                 {
992                   free (e->aux);
993                   e->aux = NULL;
994                 }
995             }
996           else
997             bitmap_set_bit (threaded_blocks, i);
998         }
999     }
1000   else
1001     bitmap_copy (threaded_blocks, tmp);
1002
1003   BITMAP_FREE(tmp);
1004 }
1005
1006
1007 /* Walk through all blocks and thread incoming edges to the appropriate
1008    outgoing edge for each edge pair recorded in THREADED_EDGES.
1009
1010    It is the caller's responsibility to fix the dominance information
1011    and rewrite duplicated SSA_NAMEs back into SSA form.
1012
1013    If MAY_PEEL_LOOP_HEADERS is false, we avoid threading edges through
1014    loop headers if it does not simplify the loop.
1015
1016    Returns true if one or more edges were threaded, false otherwise.  */
1017
1018 bool
1019 thread_through_all_blocks (bool may_peel_loop_headers)
1020 {
1021   bool retval = false;
1022   unsigned int i;
1023   bitmap_iterator bi;
1024   bitmap threaded_blocks;
1025   struct loop *loop;
1026   loop_iterator li;
1027
1028   /* We must know about loops in order to preserve them.  */
1029   gcc_assert (current_loops != NULL);
1030
1031   if (threaded_edges == NULL)
1032     return false;
1033
1034   threaded_blocks = BITMAP_ALLOC (NULL);
1035   memset (&thread_stats, 0, sizeof (thread_stats));
1036
1037   mark_threaded_blocks (threaded_blocks);
1038
1039   initialize_original_copy_tables ();
1040
1041   /* First perform the threading requests that do not affect
1042      loop structure.  */
1043   EXECUTE_IF_SET_IN_BITMAP (threaded_blocks, 0, i, bi)
1044     {
1045       basic_block bb = BASIC_BLOCK (i);
1046
1047       if (EDGE_COUNT (bb->preds) > 0)
1048         retval |= thread_block (bb, true);
1049     }
1050
1051   /* Then perform the threading through loop headers.  We start with the
1052      innermost loop, so that the changes in cfg we perform won't affect
1053      further threading.  */
1054   FOR_EACH_LOOP (li, loop, LI_FROM_INNERMOST)
1055     {
1056       if (!loop->header
1057           || !bitmap_bit_p (threaded_blocks, loop->header->index))
1058         continue;
1059
1060       retval |= thread_through_loop_header (loop, may_peel_loop_headers);
1061     }
1062
1063   statistics_counter_event (cfun, "Jumps threaded",
1064                             thread_stats.num_threaded_edges);
1065
1066   free_original_copy_tables ();
1067
1068   BITMAP_FREE (threaded_blocks);
1069   threaded_blocks = NULL;
1070   VEC_free (edge, heap, threaded_edges);
1071   threaded_edges = NULL;
1072
1073   if (retval)
1074     loops_state_set (LOOPS_NEED_FIXUP);
1075
1076   return retval;
1077 }
1078
1079 /* Register a jump threading opportunity.  We queue up all the jump
1080    threading opportunities discovered by a pass and update the CFG
1081    and SSA form all at once.
1082
1083    E is the edge we can thread, E2 is the new target edge, i.e., we
1084    are effectively recording that E->dest can be changed to E2->dest
1085    after fixing the SSA graph.  */
1086
1087 void
1088 register_jump_thread (edge e, edge e2)
1089 {
1090   /* This can occur if we're jumping to a constant address or
1091      or something similar.  Just get out now.  */
1092   if (e2 == NULL)
1093     return;
1094
1095   if (threaded_edges == NULL)
1096     threaded_edges = VEC_alloc (edge, heap, 15);
1097
1098   if (dump_file && (dump_flags & TDF_DETAILS)
1099       && e->dest != e2->src)
1100     fprintf (dump_file,
1101              "  Registering jump thread around one or more intermediate blocks\n");
1102
1103   VEC_safe_push (edge, heap, threaded_edges, e);
1104   VEC_safe_push (edge, heap, threaded_edges, e2);
1105 }