OSDN Git Service

3b8bcec7b2225fad4798c84f6c9460cc68087616
[pf3gnuchains/gcc-fork.git] / gcc / cfgloopmanip.c
1 /* Loop manipulation code for GNU compiler.
2    Copyright (C) 2002, 2003, 2004 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 2, or (at your option) any later
9 version.
10
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING.  If not, write to the Free
18 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
19 02111-1307, USA.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "rtl.h"
26 #include "hard-reg-set.h"
27 #include "basic-block.h"
28 #include "cfgloop.h"
29 #include "cfglayout.h"
30 #include "output.h"
31
32 static struct loop * duplicate_loop (struct loops *, struct loop *,
33                                      struct loop *);
34 static void duplicate_subloops (struct loops *, struct loop *, struct loop *);
35 static void copy_loops_to (struct loops *, struct loop **, int,
36                            struct loop *);
37 static void loop_redirect_edge (edge, basic_block);
38 static bool loop_delete_branch_edge (edge, int);
39 static void remove_bbs (basic_block *, int);
40 static bool rpe_enum_p (basic_block, void *);
41 static int find_path (edge, basic_block **);
42 static bool alp_enum_p (basic_block, void *);
43 static void add_loop (struct loops *, struct loop *);
44 static void fix_loop_placements (struct loop *);
45 static bool fix_bb_placement (struct loops *, basic_block);
46 static void fix_bb_placements (struct loops *, basic_block);
47 static void place_new_loop (struct loops *, struct loop *);
48 static void scale_loop_frequencies (struct loop *, int, int);
49 static void scale_bbs_frequencies (basic_block *, int, int, int);
50 static basic_block create_preheader (struct loop *, int);
51 static void fix_irreducible_loops (basic_block);
52
53 /* Splits basic block BB after INSN, returns created edge.  Updates loops
54    and dominators.  */
55 edge
56 split_loop_bb (basic_block bb, rtx insn)
57 {
58   edge e;
59
60   /* Split the block.  */
61   e = split_block (bb, insn);
62
63   /* Add dest to loop.  */
64   add_bb_to_loop (e->dest, e->src->loop_father);
65
66   return e;
67 }
68
69 /* Checks whether basic block BB is dominated by DATA.  */
70 static bool
71 rpe_enum_p (basic_block bb, void *data)
72 {
73   return dominated_by_p (CDI_DOMINATORS, bb, data);
74 }
75
76 /* Remove basic blocks BBS from loop structure and dominance info,
77    and delete them afterwards.  */
78 static void
79 remove_bbs (basic_block *bbs, int nbbs)
80 {
81   int i;
82
83   for (i = 0; i < nbbs; i++)
84     {
85       remove_bb_from_loops (bbs[i]);
86       delete_basic_block (bbs[i]);
87     }
88 }
89
90 /* Find path -- i.e. the basic blocks dominated by edge E and put them
91    into array BBS, that will be allocated large enough to contain them.
92    E->dest must have exactly one predecessor for this to work (it is
93    easy to achieve and we do not put it here because we do not want to
94    alter anything by this function).  The number of basic blocks in the
95    path is returned.  */
96 static int
97 find_path (edge e, basic_block **bbs)
98 {
99   if (e->dest->pred->pred_next)
100     abort ();
101
102   /* Find bbs in the path.  */
103   *bbs = xcalloc (n_basic_blocks, sizeof (basic_block));
104   return dfs_enumerate_from (e->dest, 0, rpe_enum_p, *bbs,
105                              n_basic_blocks, e->dest);
106 }
107
108 /* Fix placement of basic block BB inside loop hierarchy stored in LOOPS --
109    Let L be a loop to that BB belongs.  Then every successor of BB must either
110      1) belong to some superloop of loop L, or
111      2) be a header of loop K such that K->outer is superloop of L
112    Returns true if we had to move BB into other loop to enforce this condition,
113    false if the placement of BB was already correct (provided that placements
114    of its successors are correct).  */
115 static bool
116 fix_bb_placement (struct loops *loops, basic_block bb)
117 {
118   edge e;
119   struct loop *loop = loops->tree_root, *act;
120
121   for (e = bb->succ; e; e = e->succ_next)
122     {
123       if (e->dest == EXIT_BLOCK_PTR)
124         continue;
125
126       act = e->dest->loop_father;
127       if (act->header == e->dest)
128         act = act->outer;
129
130       if (flow_loop_nested_p (loop, act))
131         loop = act;
132     }
133
134   if (loop == bb->loop_father)
135     return false;
136
137   remove_bb_from_loops (bb);
138   add_bb_to_loop (bb, loop);
139
140   return true;
141 }
142
143 /* Fix placements of basic blocks inside loop hierarchy stored in loops; i.e.
144    enforce condition condition stated in description of fix_bb_placement. We
145    start from basic block FROM that had some of its successors removed, so that
146    his placement no longer has to be correct, and iteratively fix placement of
147    its predecessors that may change if placement of FROM changed.  Also fix
148    placement of subloops of FROM->loop_father, that might also be altered due
149    to this change; the condition for them is similar, except that instead of
150    successors we consider edges coming out of the loops.  */
151 static void
152 fix_bb_placements (struct loops *loops, basic_block from)
153 {
154   sbitmap in_queue;
155   basic_block *queue, *qtop, *qbeg, *qend;
156   struct loop *base_loop;
157   edge e;
158
159   /* We pass through blocks back-reachable from FROM, testing whether some
160      of their successors moved to outer loop.  It may be necessary to
161      iterate several times, but it is finite, as we stop unless we move
162      the basic block up the loop structure.  The whole story is a bit
163      more complicated due to presence of subloops, those are moved using
164      fix_loop_placement.  */
165
166   base_loop = from->loop_father;
167   if (base_loop == loops->tree_root)
168     return;
169
170   in_queue = sbitmap_alloc (last_basic_block);
171   sbitmap_zero (in_queue);
172   SET_BIT (in_queue, from->index);
173   /* Prevent us from going out of the base_loop.  */
174   SET_BIT (in_queue, base_loop->header->index);
175
176   queue = xmalloc ((base_loop->num_nodes + 1) * sizeof (basic_block));
177   qtop = queue + base_loop->num_nodes + 1;
178   qbeg = queue;
179   qend = queue + 1;
180   *qbeg = from;
181
182   while (qbeg != qend)
183     {
184       from = *qbeg;
185       qbeg++;
186       if (qbeg == qtop)
187         qbeg = queue;
188       RESET_BIT (in_queue, from->index);
189
190       if (from->loop_father->header == from)
191         {
192           /* Subloop header, maybe move the loop upward.  */
193           if (!fix_loop_placement (from->loop_father))
194             continue;
195         }
196       else
197         {
198           /* Ordinary basic block.  */
199           if (!fix_bb_placement (loops, from))
200             continue;
201         }
202
203       /* Something has changed, insert predecessors into queue.  */
204       for (e = from->pred; e; e = e->pred_next)
205         {
206           basic_block pred = e->src;
207           struct loop *nca;
208
209           if (TEST_BIT (in_queue, pred->index))
210             continue;
211
212           /* If it is subloop, then it either was not moved, or
213              the path up the loop tree from base_loop do not contain
214              it.  */
215           nca = find_common_loop (pred->loop_father, base_loop);
216           if (pred->loop_father != base_loop
217               && (nca == base_loop
218                   || nca != pred->loop_father))
219             pred = pred->loop_father->header;
220           else if (!flow_loop_nested_p (from->loop_father, pred->loop_father))
221             {
222               /* No point in processing it.  */
223               continue;
224             }
225
226           if (TEST_BIT (in_queue, pred->index))
227             continue;
228
229           /* Schedule the basic block.  */
230           *qend = pred;
231           qend++;
232           if (qend == qtop)
233             qend = queue;
234           SET_BIT (in_queue, pred->index);
235         }
236     }
237   free (in_queue);
238   free (queue);
239 }
240
241 /* Basic block from has lost one or more of its predecessors, so it might
242    mo longer be part irreducible loop.  Fix it and proceed recursively
243    for its successors if needed.  */
244 static void
245 fix_irreducible_loops (basic_block from)
246 {
247   basic_block bb;
248   basic_block *stack;
249   int stack_top;
250   sbitmap on_stack;
251   edge *edges, e;
252   unsigned n_edges, i;
253
254   if (!(from->flags & BB_IRREDUCIBLE_LOOP))
255     return;
256
257   on_stack = sbitmap_alloc (last_basic_block);
258   sbitmap_zero (on_stack);
259   SET_BIT (on_stack, from->index);
260   stack = xmalloc (from->loop_father->num_nodes * sizeof (basic_block));
261   stack[0] = from;
262   stack_top = 1;
263
264   while (stack_top)
265     {
266       bb = stack[--stack_top];
267       RESET_BIT (on_stack, bb->index);
268
269       for (e = bb->pred; e; e = e->pred_next)
270         if (e->flags & EDGE_IRREDUCIBLE_LOOP)
271           break;
272       if (e)
273         continue;
274
275       bb->flags &= ~BB_IRREDUCIBLE_LOOP;
276       if (bb->loop_father->header == bb)
277         edges = get_loop_exit_edges (bb->loop_father, &n_edges);
278       else
279         {
280           n_edges = 0;
281           for (e = bb->succ; e; e = e->succ_next)
282             n_edges++;
283           edges = xmalloc (n_edges * sizeof (edge));
284           n_edges = 0;
285           for (e = bb->succ; e; e = e->succ_next)
286             edges[n_edges++] = e;
287         }
288
289       for (i = 0; i < n_edges; i++)
290         {
291           e = edges[i];
292
293           if (e->flags & EDGE_IRREDUCIBLE_LOOP)
294             {
295               if (!flow_bb_inside_loop_p (from->loop_father, e->dest))
296                 continue;
297
298               e->flags &= ~EDGE_IRREDUCIBLE_LOOP;
299               if (TEST_BIT (on_stack, e->dest->index))
300                 continue;
301
302               SET_BIT (on_stack, e->dest->index);
303               stack[stack_top++] = e->dest;
304             }
305         }
306       free (edges);
307     }
308
309   free (on_stack);
310   free (stack);
311 }
312
313 /* Removes path beginning at edge E, i.e. remove basic blocks dominated by E
314    and update loop structure stored in LOOPS and dominators.  Return true if
315    we were able to remove the path, false otherwise (and nothing is affected
316    then).  */
317 bool
318 remove_path (struct loops *loops, edge e)
319 {
320   edge ae;
321   basic_block *rem_bbs, *bord_bbs, *dom_bbs, from, bb;
322   int i, nrem, n_bord_bbs, n_dom_bbs;
323   sbitmap seen;
324
325   if (!loop_delete_branch_edge (e, 0))
326     return false;
327
328   /* We need to check whether basic blocks are dominated by the edge
329      e, but we only have basic block dominators.  This is easy to
330      fix -- when e->dest has exactly one predecessor, this corresponds
331      to blocks dominated by e->dest, if not, split the edge.  */
332   if (e->dest->pred->pred_next)
333     e = loop_split_edge_with (e, NULL_RTX)->pred;
334
335   /* It may happen that by removing path we remove one or more loops
336      we belong to.  In this case first unloop the loops, then proceed
337      normally.   We may assume that e->dest is not a header of any loop,
338      as it now has exactly one predecessor.  */
339   while (e->src->loop_father->outer
340          && dominated_by_p (CDI_DOMINATORS,
341                             e->src->loop_father->latch, e->dest))
342     unloop (loops, e->src->loop_father);
343
344   /* Identify the path.  */
345   nrem = find_path (e, &rem_bbs);
346
347   n_bord_bbs = 0;
348   bord_bbs = xcalloc (n_basic_blocks, sizeof (basic_block));
349   seen = sbitmap_alloc (last_basic_block);
350   sbitmap_zero (seen);
351
352   /* Find "border" hexes -- i.e. those with predecessor in removed path.  */
353   for (i = 0; i < nrem; i++)
354     SET_BIT (seen, rem_bbs[i]->index);
355   for (i = 0; i < nrem; i++)
356     {
357       bb = rem_bbs[i];
358       for (ae = rem_bbs[i]->succ; ae; ae = ae->succ_next)
359         if (ae->dest != EXIT_BLOCK_PTR && !TEST_BIT (seen, ae->dest->index))
360           {
361             SET_BIT (seen, ae->dest->index);
362             bord_bbs[n_bord_bbs++] = ae->dest;
363           }
364     }
365
366   /* Remove the path.  */
367   from = e->src;
368   if (!loop_delete_branch_edge (e, 1))
369     abort ();
370   dom_bbs = xcalloc (n_basic_blocks, sizeof (basic_block));
371
372   /* Cancel loops contained in the path.  */
373   for (i = 0; i < nrem; i++)
374     if (rem_bbs[i]->loop_father->header == rem_bbs[i])
375       cancel_loop_tree (loops, rem_bbs[i]->loop_father);
376
377   remove_bbs (rem_bbs, nrem);
378   free (rem_bbs);
379
380   /* Find blocks whose dominators may be affected.  */
381   n_dom_bbs = 0;
382   sbitmap_zero (seen);
383   for (i = 0; i < n_bord_bbs; i++)
384     {
385       basic_block ldom;
386
387       bb = get_immediate_dominator (CDI_DOMINATORS, bord_bbs[i]);
388       if (TEST_BIT (seen, bb->index))
389         continue;
390       SET_BIT (seen, bb->index);
391
392       for (ldom = first_dom_son (CDI_DOMINATORS, bb);
393            ldom;
394            ldom = next_dom_son (CDI_DOMINATORS, ldom))
395         if (!dominated_by_p (CDI_DOMINATORS, from, ldom))
396           dom_bbs[n_dom_bbs++] = ldom;
397     }
398
399   free (seen);
400
401   /* Recount dominators.  */
402   iterate_fix_dominators (CDI_DOMINATORS, dom_bbs, n_dom_bbs);
403   free (dom_bbs);
404
405   /* These blocks have lost some predecessor(s), thus their irreducible
406      status could be changed.  */
407   for (i = 0; i < n_bord_bbs; i++)
408     fix_irreducible_loops (bord_bbs[i]);
409   free (bord_bbs);
410
411   /* Fix placements of basic blocks inside loops and the placement of
412      loops in the loop tree.  */
413   fix_bb_placements (loops, from);
414   fix_loop_placements (from->loop_father);
415
416   return true;
417 }
418
419 /* Predicate for enumeration in add_loop.  */
420 static bool
421 alp_enum_p (basic_block bb, void *alp_header)
422 {
423   return bb != (basic_block) alp_header;
424 }
425
426 /* Given LOOP structure with filled header and latch, find the body of the
427    corresponding loop and add it to LOOPS tree.  */
428 static void
429 add_loop (struct loops *loops, struct loop *loop)
430 {
431   basic_block *bbs;
432   int i, n;
433
434   /* Add it to loop structure.  */
435   place_new_loop (loops, loop);
436   loop->level = 1;
437
438   /* Find its nodes.  */
439   bbs = xcalloc (n_basic_blocks, sizeof (basic_block));
440   n = dfs_enumerate_from (loop->latch, 1, alp_enum_p,
441                           bbs, n_basic_blocks, loop->header);
442
443   for (i = 0; i < n; i++)
444     add_bb_to_loop (bbs[i], loop);
445   add_bb_to_loop (loop->header, loop);
446
447   free (bbs);
448 }
449
450 /* Multiply all frequencies of basic blocks in array BBS of length NBBS
451    by NUM/DEN.  */
452 static void
453 scale_bbs_frequencies (basic_block *bbs, int nbbs, int num, int den)
454 {
455   int i;
456   edge e;
457
458   for (i = 0; i < nbbs; i++)
459     {
460       bbs[i]->frequency = (bbs[i]->frequency * num) / den;
461       bbs[i]->count = (bbs[i]->count * num) / den;
462       for (e = bbs[i]->succ; e; e = e->succ_next)
463         e->count = (e->count * num) /den;
464     }
465 }
466
467 /* Multiply all frequencies in LOOP by NUM/DEN.  */
468 static void
469 scale_loop_frequencies (struct loop *loop, int num, int den)
470 {
471   basic_block *bbs;
472
473   bbs = get_loop_body (loop);
474   scale_bbs_frequencies (bbs, loop->num_nodes, num, den);
475   free (bbs);
476 }
477
478 /* Make area between HEADER_EDGE and LATCH_EDGE a loop by connecting
479    latch to header and update loop tree stored in LOOPS and dominators
480    accordingly. Everything between them plus LATCH_EDGE destination must
481    be dominated by HEADER_EDGE destination, and back-reachable from
482    LATCH_EDGE source.  HEADER_EDGE is redirected to basic block SWITCH_BB,
483    SWITCH_BB->succ to original destination of LATCH_EDGE and
484    SWITCH_BB->succ->succ_next to original destination of HEADER_EDGE.
485    Returns newly created loop.  */
486 struct loop *
487 loopify (struct loops *loops, edge latch_edge, edge header_edge, basic_block switch_bb)
488 {
489   basic_block succ_bb = latch_edge->dest;
490   basic_block pred_bb = header_edge->src;
491   basic_block *dom_bbs, *body;
492   unsigned n_dom_bbs, i;
493   sbitmap seen;
494   struct loop *loop = xcalloc (1, sizeof (struct loop));
495   struct loop *outer = succ_bb->loop_father->outer;
496   int freq, prob, tot_prob;
497   gcov_type cnt;
498   edge e;
499
500   loop->header = header_edge->dest;
501   loop->latch = latch_edge->src;
502
503   freq = EDGE_FREQUENCY (header_edge);
504   cnt = header_edge->count;
505   prob = switch_bb->succ->probability;
506   tot_prob = prob + switch_bb->succ->succ_next->probability;
507   if (tot_prob == 0)
508     tot_prob = 1;
509
510   /* Redirect edges.  */
511   loop_redirect_edge (latch_edge, loop->header);
512   loop_redirect_edge (header_edge, switch_bb);
513   loop_redirect_edge (switch_bb->succ->succ_next, loop->header);
514   loop_redirect_edge (switch_bb->succ, succ_bb);
515
516   /* Update dominators.  */
517   set_immediate_dominator (CDI_DOMINATORS, switch_bb, pred_bb);
518   set_immediate_dominator (CDI_DOMINATORS, loop->header, switch_bb);
519   set_immediate_dominator (CDI_DOMINATORS, succ_bb, switch_bb);
520
521   /* Compute new loop.  */
522   add_loop (loops, loop);
523   flow_loop_tree_node_add (outer, loop);
524
525   /* Add switch_bb to appropriate loop.  */
526   add_bb_to_loop (switch_bb, outer);
527
528   /* Fix frequencies.  */
529   switch_bb->frequency = freq;
530   switch_bb->count = cnt;
531   for (e = switch_bb->succ; e; e = e->succ_next)
532     e->count = (switch_bb->count * e->probability) / REG_BR_PROB_BASE;
533   scale_loop_frequencies (loop, prob, tot_prob);
534   scale_loop_frequencies (succ_bb->loop_father, tot_prob - prob, tot_prob);
535
536   /* Update dominators of blocks outside of LOOP.  */
537   dom_bbs = xcalloc (n_basic_blocks, sizeof (basic_block));
538   n_dom_bbs = 0;
539   seen = sbitmap_alloc (last_basic_block);
540   sbitmap_zero (seen);
541   body = get_loop_body (loop);
542
543   for (i = 0; i < loop->num_nodes; i++)
544     SET_BIT (seen, body[i]->index);
545
546   for (i = 0; i < loop->num_nodes; i++)
547     {
548       basic_block ldom;
549
550       for (ldom = first_dom_son (CDI_DOMINATORS, body[i]);
551            ldom;
552            ldom = next_dom_son (CDI_DOMINATORS, ldom))
553         if (!TEST_BIT (seen, ldom->index))
554           {
555             SET_BIT (seen, ldom->index);
556             dom_bbs[n_dom_bbs++] = ldom;
557           }
558     }
559
560   iterate_fix_dominators (CDI_DOMINATORS, dom_bbs, n_dom_bbs);
561
562   free (body);
563   free (seen);
564   free (dom_bbs);
565
566   return loop;
567 }
568
569 /* Remove the latch edge of a LOOP and update LOOPS tree to indicate that
570    the LOOP was removed.  After this function, original loop latch will
571    have no successor, which caller is expected to fix somehow.  */
572 void
573 unloop (struct loops *loops, struct loop *loop)
574 {
575   basic_block *body;
576   struct loop *ploop;
577   unsigned i, n;
578   basic_block latch = loop->latch;
579   edge *edges;
580   unsigned n_edges;
581
582   /* This is relatively straightforward.  The dominators are unchanged, as
583      loop header dominates loop latch, so the only thing we have to care of
584      is the placement of loops and basic blocks inside the loop tree.  We
585      move them all to the loop->outer, and then let fix_bb_placements do
586      its work.  */
587
588   body = get_loop_body (loop);
589   edges = get_loop_exit_edges (loop, &n_edges);
590   n = loop->num_nodes;
591   for (i = 0; i < n; i++)
592     if (body[i]->loop_father == loop)
593       {
594         remove_bb_from_loops (body[i]);
595         add_bb_to_loop (body[i], loop->outer);
596       }
597   free(body);
598
599   while (loop->inner)
600     {
601       ploop = loop->inner;
602       flow_loop_tree_node_remove (ploop);
603       flow_loop_tree_node_add (loop->outer, ploop);
604     }
605
606   /* Remove the loop and free its data.  */
607   flow_loop_tree_node_remove (loop);
608   loops->parray[loop->num] = NULL;
609   flow_loop_free (loop);
610
611   remove_edge (latch->succ);
612   fix_bb_placements (loops, latch);
613
614   /* If the loop was inside an irreducible region, we would have to somehow
615      update the irreducible marks inside its body.  While it is certainly
616      possible to do, it is a bit complicated and this situation should be
617      very rare, so we just remark all loops in this case.  */
618   for (i = 0; i < n_edges; i++)
619     if (edges[i]->flags & EDGE_IRREDUCIBLE_LOOP)
620       break;
621   if (i != n_edges)
622     mark_irreducible_loops (loops);
623   free (edges);
624 }
625
626 /* Fix placement of LOOP inside loop tree, i.e. find the innermost superloop
627    FATHER of LOOP such that all of the edges coming out of LOOP belong to
628    FATHER, and set it as outer loop of LOOP.  Return 1 if placement of
629    LOOP changed.  */
630 int
631 fix_loop_placement (struct loop *loop)
632 {
633   basic_block *body;
634   unsigned i;
635   edge e;
636   struct loop *father = loop->pred[0], *act;
637
638   body = get_loop_body (loop);
639   for (i = 0; i < loop->num_nodes; i++)
640     for (e = body[i]->succ; e; e = e->succ_next)
641       if (!flow_bb_inside_loop_p (loop, e->dest))
642         {
643           act = find_common_loop (loop, e->dest->loop_father);
644           if (flow_loop_nested_p (father, act))
645             father = act;
646         }
647   free (body);
648
649   if (father != loop->outer)
650     {
651       for (act = loop->outer; act != father; act = act->outer)
652         act->num_nodes -= loop->num_nodes;
653       flow_loop_tree_node_remove (loop);
654       flow_loop_tree_node_add (father, loop);
655       return 1;
656     }
657   return 0;
658 }
659
660 /* Fix placement of superloops of LOOP inside loop tree, i.e. ensure that
661    condition stated in description of fix_loop_placement holds for them.
662    It is used in case when we removed some edges coming out of LOOP, which
663    may cause the right placement of LOOP inside loop tree to change.  */
664 static void
665 fix_loop_placements (struct loop *loop)
666 {
667   struct loop *outer;
668
669   while (loop->outer)
670     {
671       outer = loop->outer;
672       if (!fix_loop_placement (loop))
673         break;
674       loop = outer;
675     }
676 }
677
678 /* Creates place for a new LOOP in LOOPS structure.  */
679 static void
680 place_new_loop (struct loops *loops, struct loop *loop)
681 {
682   loops->parray =
683     xrealloc (loops->parray, (loops->num + 1) * sizeof (struct loop *));
684   loops->parray[loops->num] = loop;
685
686   loop->num = loops->num++;
687 }
688
689 /* Copies copy of LOOP as subloop of TARGET loop, placing newly
690    created loop into LOOPS structure.  */
691 static struct loop *
692 duplicate_loop (struct loops *loops, struct loop *loop, struct loop *target)
693 {
694   struct loop *cloop;
695   cloop = xcalloc (1, sizeof (struct loop));
696   place_new_loop (loops, cloop);
697
698   /* Initialize copied loop.  */
699   cloop->level = loop->level;
700
701   /* Set it as copy of loop.  */
702   loop->copy = cloop;
703
704   /* Add it to target.  */
705   flow_loop_tree_node_add (target, cloop);
706
707   return cloop;
708 }
709
710 /* Copies structure of subloops of LOOP into TARGET loop, placing
711    newly created loops into loop tree stored in LOOPS.  */
712 static void
713 duplicate_subloops (struct loops *loops, struct loop *loop, struct loop *target)
714 {
715   struct loop *aloop, *cloop;
716
717   for (aloop = loop->inner; aloop; aloop = aloop->next)
718     {
719       cloop = duplicate_loop (loops, aloop, target);
720       duplicate_subloops (loops, aloop, cloop);
721     }
722 }
723
724 /* Copies structure of subloops of N loops, stored in array COPIED_LOOPS,
725    into TARGET loop, placing newly created loops into loop tree LOOPS.  */
726 static void
727 copy_loops_to (struct loops *loops, struct loop **copied_loops, int n, struct loop *target)
728 {
729   struct loop *aloop;
730   int i;
731
732   for (i = 0; i < n; i++)
733     {
734       aloop = duplicate_loop (loops, copied_loops[i], target);
735       duplicate_subloops (loops, copied_loops[i], aloop);
736     }
737 }
738
739 /* Redirects edge E to basic block DEST.  */
740 static void
741 loop_redirect_edge (edge e, basic_block dest)
742 {
743   if (e->dest == dest)
744     return;
745
746   redirect_edge_and_branch_force (e, dest);
747 }
748
749 /* Deletes edge E from a branch if possible.  Unless REALLY_DELETE is set,
750    just test whether it is possible to remove the edge.  */
751 static bool
752 loop_delete_branch_edge (edge e, int really_delete)
753 {
754   basic_block src = e->src;
755   int irr;
756   edge snd;
757
758   if (src->succ->succ_next)
759     {
760       basic_block newdest;
761
762       /* Cannot handle more than two exit edges.  */
763       if (src->succ->succ_next->succ_next)
764         return false;
765       /* And it must be just a simple branch.  */
766       if (!any_condjump_p (BB_END (src)))
767         return false;
768
769       snd = e == src->succ ? src->succ->succ_next : src->succ;
770       newdest = snd->dest;
771       if (newdest == EXIT_BLOCK_PTR)
772         return false;
773
774       /* Hopefully the above conditions should suffice.  */
775       if (!really_delete)
776         return true;
777
778       /* Redirecting behaves wrongly wrto this flag.  */
779       irr = snd->flags & EDGE_IRREDUCIBLE_LOOP;
780
781       if (!redirect_edge_and_branch (e, newdest))
782         return false;
783       src->succ->flags &= ~EDGE_IRREDUCIBLE_LOOP;
784       src->succ->flags |= irr;
785
786       return true;
787     }
788   else
789     {
790       /* Cannot happen -- we are using this only to remove an edge
791          from branch.  */
792       abort ();
793     }
794
795   return false;  /* To avoid warning, cannot get here.  */
796 }
797
798 /* Check whether LOOP's body can be duplicated.  */
799 bool
800 can_duplicate_loop_p (struct loop *loop)
801 {
802   int ret;
803   basic_block *bbs = get_loop_body (loop);
804
805   ret = can_copy_bbs_p (bbs, loop->num_nodes);
806   free (bbs);
807   
808   return ret;
809 }
810
811 #define RDIV(X,Y) (((X) + (Y) / 2) / (Y))
812
813 /* Duplicates body of LOOP to given edge E NDUPL times.  Takes care of updating
814    LOOPS structure and dominators.  E's destination must be LOOP header for
815    this to work, i.e. it must be entry or latch edge of this loop; these are
816    unique, as the loops must have preheaders for this function to work
817    correctly (in case E is latch, the function unrolls the loop, if E is entry
818    edge, it peels the loop).  Store edges created by copying ORIG edge from
819    copies corresponding to set bits in WONT_EXIT bitmap (bit 0 corresponds to
820    original LOOP body, the other copies are numbered in order given by control
821    flow through them) into TO_REMOVE array.  Returns false if duplication is
822    impossible.  */
823 int
824 duplicate_loop_to_header_edge (struct loop *loop, edge e, struct loops *loops,
825                                unsigned int ndupl, sbitmap wont_exit,
826                                edge orig, edge *to_remove,
827                                unsigned int *n_to_remove, int flags)
828 {
829   struct loop *target, *aloop;
830   struct loop **orig_loops;
831   unsigned n_orig_loops;
832   basic_block header = loop->header, latch = loop->latch;
833   basic_block *new_bbs, *bbs, *first_active;
834   basic_block new_bb, bb, first_active_latch = NULL;
835   edge ae, latch_edge;
836   edge spec_edges[2], new_spec_edges[2];
837 #define SE_LATCH 0
838 #define SE_ORIG 1
839   unsigned i, j, n;
840   int is_latch = (latch == e->src);
841   int scale_act = 0, *scale_step = NULL, scale_main = 0;
842   int p, freq_in, freq_le, freq_out_orig;
843   int prob_pass_thru, prob_pass_wont_exit, prob_pass_main;
844   int add_irreducible_flag;
845
846   if (e->dest != loop->header)
847     abort ();
848   if (ndupl <= 0)
849     abort ();
850
851   if (orig)
852     {
853       /* Orig must be edge out of the loop.  */
854       if (!flow_bb_inside_loop_p (loop, orig->src))
855         abort ();
856       if (flow_bb_inside_loop_p (loop, orig->dest))
857         abort ();
858     }
859
860   bbs = get_loop_body (loop);
861
862   /* Check whether duplication is possible.  */
863   if (!can_copy_bbs_p (bbs, loop->num_nodes))
864     {
865       free (bbs);
866       return false;
867     }
868   new_bbs = xmalloc (sizeof (basic_block) * loop->num_nodes);
869
870   /* In case we are doing loop peeling and the loop is in the middle of
871      irreducible region, the peeled copies will be inside it too.  */
872   add_irreducible_flag = e->flags & EDGE_IRREDUCIBLE_LOOP;
873   if (is_latch && add_irreducible_flag)
874     abort ();
875
876   /* Find edge from latch.  */
877   latch_edge = loop_latch_edge (loop);
878
879   if (flags & DLTHE_FLAG_UPDATE_FREQ)
880     {
881       /* Calculate coefficients by that we have to scale frequencies
882          of duplicated loop bodies.  */
883       freq_in = header->frequency;
884       freq_le = EDGE_FREQUENCY (latch_edge);
885       if (freq_in == 0)
886         freq_in = 1;
887       if (freq_in < freq_le)
888         freq_in = freq_le;
889       freq_out_orig = orig ? EDGE_FREQUENCY (orig) : freq_in - freq_le;
890       if (freq_out_orig > freq_in - freq_le)
891         freq_out_orig = freq_in - freq_le;
892       prob_pass_thru = RDIV (REG_BR_PROB_BASE * freq_le, freq_in);
893       prob_pass_wont_exit =
894               RDIV (REG_BR_PROB_BASE * (freq_le + freq_out_orig), freq_in);
895
896       scale_step = xmalloc (ndupl * sizeof (int));
897
898         for (i = 1; i <= ndupl; i++)
899           scale_step[i - 1] = TEST_BIT (wont_exit, i)
900                                 ? prob_pass_wont_exit
901                                 : prob_pass_thru;
902
903       if (is_latch)
904         {
905           prob_pass_main = TEST_BIT (wont_exit, 0)
906                                 ? prob_pass_wont_exit
907                                 : prob_pass_thru;
908           p = prob_pass_main;
909           scale_main = REG_BR_PROB_BASE;
910           for (i = 0; i < ndupl; i++)
911             {
912               scale_main += p;
913               p = RDIV (p * scale_step[i], REG_BR_PROB_BASE);
914             }
915           scale_main = RDIV (REG_BR_PROB_BASE * REG_BR_PROB_BASE, scale_main);
916           scale_act = RDIV (scale_main * prob_pass_main, REG_BR_PROB_BASE);
917         }
918       else
919         {
920           scale_main = REG_BR_PROB_BASE;
921           for (i = 0; i < ndupl; i++)
922             scale_main = RDIV (scale_main * scale_step[i], REG_BR_PROB_BASE);
923           scale_act = REG_BR_PROB_BASE - prob_pass_thru;
924         }
925       for (i = 0; i < ndupl; i++)
926         if (scale_step[i] < 0 || scale_step[i] > REG_BR_PROB_BASE)
927           abort ();
928       if (scale_main < 0 || scale_main > REG_BR_PROB_BASE
929           || scale_act < 0  || scale_act > REG_BR_PROB_BASE)
930         abort ();
931     }
932
933   /* Loop the new bbs will belong to.  */
934   target = e->src->loop_father;
935
936   /* Original loops.  */
937   n_orig_loops = 0;
938   for (aloop = loop->inner; aloop; aloop = aloop->next)
939     n_orig_loops++;
940   orig_loops = xcalloc (n_orig_loops, sizeof (struct loop *));
941   for (aloop = loop->inner, i = 0; aloop; aloop = aloop->next, i++)
942     orig_loops[i] = aloop;
943
944   loop->copy = target;
945
946   n = loop->num_nodes;
947
948   first_active = xmalloc (n * sizeof (basic_block));
949   if (is_latch)
950     {
951       memcpy (first_active, bbs, n * sizeof (basic_block));
952       first_active_latch = latch;
953     }
954
955   /* Record exit edge in original loop body.  */
956   if (orig && TEST_BIT (wont_exit, 0))
957     to_remove[(*n_to_remove)++] = orig;
958
959   spec_edges[SE_ORIG] = orig;
960   spec_edges[SE_LATCH] = latch_edge;
961
962   for (j = 0; j < ndupl; j++)
963     {
964       /* Copy loops.  */
965       copy_loops_to (loops, orig_loops, n_orig_loops, target);
966
967       /* Copy bbs.  */
968       copy_bbs (bbs, n, new_bbs, spec_edges, 2, new_spec_edges, loop);
969
970       /* Note whether the blocks and edges belong to an irreducible loop.  */
971       if (add_irreducible_flag)
972         {
973           for (i = 0; i < n; i++)
974             new_bbs[i]->rbi->duplicated = 1;
975           for (i = 0; i < n; i++)
976             {
977               new_bb = new_bbs[i];
978               if (new_bb->loop_father == target)
979                 new_bb->flags |= BB_IRREDUCIBLE_LOOP;
980
981               for (ae = new_bb->succ; ae; ae = ae->succ_next)
982                 if (ae->dest->rbi->duplicated
983                     && (ae->src->loop_father == target
984                         || ae->dest->loop_father == target))
985                   ae->flags |= EDGE_IRREDUCIBLE_LOOP;
986             }
987           for (i = 0; i < n; i++)
988             new_bbs[i]->rbi->duplicated = 0;
989         }
990
991       /* Redirect the special edges.  */
992       if (is_latch)
993         {
994           redirect_edge_and_branch_force (latch_edge, new_bbs[0]);
995           redirect_edge_and_branch_force (new_spec_edges[SE_LATCH],
996                                           loop->header);
997           set_immediate_dominator (CDI_DOMINATORS, new_bbs[0], latch);
998           latch = loop->latch = new_bbs[1];
999           e = latch_edge = new_spec_edges[SE_LATCH];
1000         }
1001       else
1002         {
1003           redirect_edge_and_branch_force (new_spec_edges[SE_LATCH],
1004                                           loop->header);
1005           redirect_edge_and_branch_force (e, new_bbs[0]);
1006           set_immediate_dominator (CDI_DOMINATORS, new_bbs[0], e->src);
1007           e = new_spec_edges[SE_LATCH];
1008         }
1009
1010       /* Record exit edge in this copy.  */
1011       if (orig && TEST_BIT (wont_exit, j + 1))
1012         to_remove[(*n_to_remove)++] = new_spec_edges[SE_ORIG];
1013
1014       /* Record the first copy in the control flow order if it is not
1015          the original loop (i.e. in case of peeling).  */
1016       if (!first_active_latch)
1017         {
1018           memcpy (first_active, new_bbs, n * sizeof (basic_block));
1019           first_active_latch = new_bbs[1];
1020         }
1021
1022       /* Set counts and frequencies.  */
1023       if (flags & DLTHE_FLAG_UPDATE_FREQ)
1024         {
1025           scale_bbs_frequencies (new_bbs, n, scale_act, REG_BR_PROB_BASE);
1026           scale_act = RDIV (scale_act * scale_step[j], REG_BR_PROB_BASE);
1027         }
1028     }
1029   free (new_bbs);
1030   free (orig_loops);
1031   
1032   /* Update the original loop.  */
1033   if (!is_latch)
1034     set_immediate_dominator (CDI_DOMINATORS, e->dest, e->src);
1035   if (flags & DLTHE_FLAG_UPDATE_FREQ)
1036     {
1037       scale_bbs_frequencies (bbs, n, scale_main, REG_BR_PROB_BASE);
1038       free (scale_step);
1039     }
1040
1041   /* Update dominators of outer blocks if affected.  */
1042   for (i = 0; i < n; i++)
1043     {
1044       basic_block dominated, dom_bb, *dom_bbs;
1045       int n_dom_bbs,j;
1046
1047       bb = bbs[i];
1048       n_dom_bbs = get_dominated_by (CDI_DOMINATORS, bb, &dom_bbs);
1049       for (j = 0; j < n_dom_bbs; j++)
1050         {
1051           dominated = dom_bbs[j];
1052           if (flow_bb_inside_loop_p (loop, dominated))
1053             continue;
1054           dom_bb = nearest_common_dominator (
1055                         CDI_DOMINATORS, first_active[i], first_active_latch);
1056           set_immediate_dominator (CDI_DOMINATORS, dominated, dom_bb);
1057         }
1058       free (dom_bbs);
1059     }
1060   free (first_active);
1061
1062   free (bbs);
1063
1064   return true;
1065 }
1066
1067 /* A callback for make_forwarder block, to redirect all edges except for
1068    MFB_KJ_EDGE to the entry part.  E is the edge for that we should decide
1069    whether to redirect it.  */
1070
1071 static edge mfb_kj_edge;
1072 static bool
1073 mfb_keep_just (edge e)
1074 {
1075   return e != mfb_kj_edge;
1076 }
1077
1078 /* A callback for make_forwarder block, to update data structures for a basic
1079    block JUMP created by redirecting an edge (only the latch edge is being
1080    redirected).  */
1081
1082 static void
1083 mfb_update_loops (basic_block jump)
1084 {
1085   struct loop *loop = jump->succ->dest->loop_father;
1086
1087   if (dom_computed[CDI_DOMINATORS])
1088     set_immediate_dominator (CDI_DOMINATORS, jump, jump->pred->src);
1089   add_bb_to_loop (jump, loop);
1090   loop->latch = jump;
1091 }
1092
1093 /* Creates a pre-header for a LOOP.  Returns newly created block.  Unless
1094    CP_SIMPLE_PREHEADERS is set in FLAGS, we only force LOOP to have single
1095    entry; otherwise we also force preheader block to have only one successor.
1096    The function also updates dominators.  */
1097
1098 static basic_block
1099 create_preheader (struct loop *loop, int flags)
1100 {
1101   edge e, fallthru;
1102   basic_block dummy;
1103   struct loop *cloop, *ploop;
1104   int nentry = 0;
1105   bool irred = false;
1106
1107   cloop = loop->outer;
1108
1109   for (e = loop->header->pred; e; e = e->pred_next)
1110     {
1111       if (e->src == loop->latch)
1112         continue;
1113       irred |= (e->flags & EDGE_IRREDUCIBLE_LOOP) != 0;
1114       nentry++;
1115     }
1116   if (!nentry)
1117     abort ();
1118   if (nentry == 1)
1119     {
1120       for (e = loop->header->pred; e->src == loop->latch; e = e->pred_next);
1121       if (!(flags & CP_SIMPLE_PREHEADERS)
1122           || !e->src->succ->succ_next)
1123         return NULL;
1124     }
1125
1126   mfb_kj_edge = loop_latch_edge (loop);
1127   fallthru = make_forwarder_block (loop->header, mfb_keep_just,
1128                                    mfb_update_loops);
1129   dummy = fallthru->src;
1130   loop->header = fallthru->dest;
1131
1132   /* The header could be a latch of some superloop(s); due to design of
1133      split_block, it would now move to fallthru->dest.  */
1134   for (ploop = loop; ploop; ploop = ploop->outer)
1135     if (ploop->latch == dummy)
1136       ploop->latch = fallthru->dest;
1137
1138   /* Reorganize blocks so that the preheader is not stuck in the middle of the
1139      loop.  */
1140   for (e = dummy->pred; e; e = e->pred_next)
1141     if (e->src != loop->latch)
1142       break;
1143   move_block_after (dummy, e->src);
1144
1145   loop->header->loop_father = loop;
1146   add_bb_to_loop (dummy, cloop);
1147
1148   if (irred)
1149     {
1150       dummy->flags |= BB_IRREDUCIBLE_LOOP;
1151       dummy->succ->flags |= EDGE_IRREDUCIBLE_LOOP;
1152     }
1153
1154   if (rtl_dump_file)
1155     fprintf (rtl_dump_file, "Created preheader block for loop %i\n",
1156              loop->num);
1157
1158   return dummy;
1159 }
1160
1161 /* Create preheaders for each loop from loop tree stored in LOOPS; for meaning
1162    of FLAGS see create_preheader.  */
1163 void
1164 create_preheaders (struct loops *loops, int flags)
1165 {
1166   unsigned i;
1167   for (i = 1; i < loops->num; i++)
1168     create_preheader (loops->parray[i], flags);
1169   loops->state |= LOOPS_HAVE_PREHEADERS;
1170 }
1171
1172 /* Forces all loop latches of loops from loop tree LOOPS to have only single
1173    successor.  */
1174 void
1175 force_single_succ_latches (struct loops *loops)
1176 {
1177   unsigned i;
1178   struct loop *loop;
1179   edge e;
1180
1181   for (i = 1; i < loops->num; i++)
1182     {
1183       loop = loops->parray[i];
1184       if (loop->latch != loop->header
1185           && !loop->latch->succ->succ_next)
1186         continue;
1187
1188       for (e = loop->header->pred; e->src != loop->latch; e = e->pred_next)
1189         continue;
1190
1191       loop_split_edge_with (e, NULL_RTX);
1192     }
1193   loops->state |= LOOPS_HAVE_SIMPLE_LATCHES;
1194 }
1195
1196 /* A quite stupid function to put INSNS on edge E. They are supposed to form
1197    just one basic block.  Jumps in INSNS are not handled, so cfg do not have to
1198    be ok after this function.  The created block is placed on correct place
1199    in LOOPS structure and its dominator is set.  */
1200 basic_block
1201 loop_split_edge_with (edge e, rtx insns)
1202 {
1203   basic_block src, dest, new_bb;
1204   struct loop *loop_c;
1205   edge new_e;
1206
1207   src = e->src;
1208   dest = e->dest;
1209
1210   loop_c = find_common_loop (src->loop_father, dest->loop_father);
1211
1212   /* Create basic block for it.  */
1213
1214   new_bb = split_edge (e);
1215   add_bb_to_loop (new_bb, loop_c);
1216   new_bb->flags = insns ? BB_SUPERBLOCK : 0;
1217
1218   new_e = new_bb->succ;
1219   if (e->flags & EDGE_IRREDUCIBLE_LOOP)
1220     {
1221       new_bb->flags |= BB_IRREDUCIBLE_LOOP;
1222       new_e->flags |= EDGE_IRREDUCIBLE_LOOP;
1223     }
1224
1225   if (insns)
1226     emit_insn_after (insns, BB_END (new_bb));
1227
1228   if (dest->loop_father->latch == src)
1229     dest->loop_father->latch = new_bb;
1230
1231   return new_bb;
1232 }