2012-07-26 Kazu Hirata <kazu@codesourcery.com>
[official-gcc.git] / gcc / cfgloop.c
blob95c173ae3bfd5dbb5d75e7871ccefa62b718e2d3
1 /* Natural loop discovery code for GNU compiler.
2 Copyright (C) 2000, 2001, 2003, 2004, 2005, 2006, 2007, 2008, 2010
3 Free Software Foundation, Inc.
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
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/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "rtl.h"
26 #include "function.h"
27 #include "basic-block.h"
28 #include "cfgloop.h"
29 #include "diagnostic-core.h"
30 #include "flags.h"
31 #include "tree.h"
32 #include "tree-flow.h"
33 #include "pointer-set.h"
34 #include "ggc.h"
35 #include "dumpfile.h"
37 static void flow_loops_cfg_dump (FILE *);
39 /* Dump loop related CFG information. */
41 static void
42 flow_loops_cfg_dump (FILE *file)
44 basic_block bb;
46 if (!file)
47 return;
49 FOR_EACH_BB (bb)
51 edge succ;
52 edge_iterator ei;
54 fprintf (file, ";; %d succs { ", bb->index);
55 FOR_EACH_EDGE (succ, ei, bb->succs)
56 fprintf (file, "%d ", succ->dest->index);
57 fprintf (file, "}\n");
61 /* Return nonzero if the nodes of LOOP are a subset of OUTER. */
63 bool
64 flow_loop_nested_p (const struct loop *outer, const struct loop *loop)
66 unsigned odepth = loop_depth (outer);
68 return (loop_depth (loop) > odepth
69 && VEC_index (loop_p, loop->superloops, odepth) == outer);
72 /* Returns the loop such that LOOP is nested DEPTH (indexed from zero)
73 loops within LOOP. */
75 struct loop *
76 superloop_at_depth (struct loop *loop, unsigned depth)
78 unsigned ldepth = loop_depth (loop);
80 gcc_assert (depth <= ldepth);
82 if (depth == ldepth)
83 return loop;
85 return VEC_index (loop_p, loop->superloops, depth);
88 /* Returns the list of the latch edges of LOOP. */
90 static VEC (edge, heap) *
91 get_loop_latch_edges (const struct loop *loop)
93 edge_iterator ei;
94 edge e;
95 VEC (edge, heap) *ret = NULL;
97 FOR_EACH_EDGE (e, ei, loop->header->preds)
99 if (dominated_by_p (CDI_DOMINATORS, e->src, loop->header))
100 VEC_safe_push (edge, heap, ret, e);
103 return ret;
106 /* Dump the loop information specified by LOOP to the stream FILE
107 using auxiliary dump callback function LOOP_DUMP_AUX if non null. */
109 void
110 flow_loop_dump (const struct loop *loop, FILE *file,
111 void (*loop_dump_aux) (const struct loop *, FILE *, int),
112 int verbose)
114 basic_block *bbs;
115 unsigned i;
116 VEC (edge, heap) *latches;
117 edge e;
119 if (! loop || ! loop->header)
120 return;
122 fprintf (file, ";;\n;; Loop %d\n", loop->num);
124 fprintf (file, ";; header %d, ", loop->header->index);
125 if (loop->latch)
126 fprintf (file, "latch %d\n", loop->latch->index);
127 else
129 fprintf (file, "multiple latches:");
130 latches = get_loop_latch_edges (loop);
131 FOR_EACH_VEC_ELT (edge, latches, i, e)
132 fprintf (file, " %d", e->src->index);
133 VEC_free (edge, heap, latches);
134 fprintf (file, "\n");
137 fprintf (file, ";; depth %d, outer %ld\n",
138 loop_depth (loop), (long) (loop_outer (loop)
139 ? loop_outer (loop)->num : -1));
141 fprintf (file, ";; nodes:");
142 bbs = get_loop_body (loop);
143 for (i = 0; i < loop->num_nodes; i++)
144 fprintf (file, " %d", bbs[i]->index);
145 free (bbs);
146 fprintf (file, "\n");
148 if (loop_dump_aux)
149 loop_dump_aux (loop, file, verbose);
152 /* Dump the loop information about loops to the stream FILE,
153 using auxiliary dump callback function LOOP_DUMP_AUX if non null. */
155 void
156 flow_loops_dump (FILE *file, void (*loop_dump_aux) (const struct loop *, FILE *, int), int verbose)
158 loop_iterator li;
159 struct loop *loop;
161 if (!current_loops || ! file)
162 return;
164 fprintf (file, ";; %d loops found\n", number_of_loops ());
166 FOR_EACH_LOOP (li, loop, LI_INCLUDE_ROOT)
168 flow_loop_dump (loop, file, loop_dump_aux, verbose);
171 if (verbose)
172 flow_loops_cfg_dump (file);
175 /* Free data allocated for LOOP. */
177 void
178 flow_loop_free (struct loop *loop)
180 struct loop_exit *exit, *next;
182 VEC_free (loop_p, gc, loop->superloops);
184 /* Break the list of the loop exit records. They will be freed when the
185 corresponding edge is rescanned or removed, and this avoids
186 accessing the (already released) head of the list stored in the
187 loop structure. */
188 for (exit = loop->exits->next; exit != loop->exits; exit = next)
190 next = exit->next;
191 exit->next = exit;
192 exit->prev = exit;
195 ggc_free (loop->exits);
196 ggc_free (loop);
199 /* Free all the memory allocated for LOOPS. */
201 void
202 flow_loops_free (struct loops *loops)
204 if (loops->larray)
206 unsigned i;
207 loop_p loop;
209 /* Free the loop descriptors. */
210 FOR_EACH_VEC_ELT (loop_p, loops->larray, i, loop)
212 if (!loop)
213 continue;
215 flow_loop_free (loop);
218 VEC_free (loop_p, gc, loops->larray);
222 /* Find the nodes contained within the LOOP with header HEADER.
223 Return the number of nodes within the loop. */
226 flow_loop_nodes_find (basic_block header, struct loop *loop)
228 VEC (basic_block, heap) *stack = NULL;
229 int num_nodes = 1;
230 edge latch;
231 edge_iterator latch_ei;
232 unsigned depth = loop_depth (loop);
234 header->loop_father = loop;
235 header->loop_depth = depth;
237 FOR_EACH_EDGE (latch, latch_ei, loop->header->preds)
239 if (latch->src->loop_father == loop
240 || !dominated_by_p (CDI_DOMINATORS, latch->src, loop->header))
241 continue;
243 num_nodes++;
244 VEC_safe_push (basic_block, heap, stack, latch->src);
245 latch->src->loop_father = loop;
246 latch->src->loop_depth = depth;
248 while (!VEC_empty (basic_block, stack))
250 basic_block node;
251 edge e;
252 edge_iterator ei;
254 node = VEC_pop (basic_block, stack);
256 FOR_EACH_EDGE (e, ei, node->preds)
258 basic_block ancestor = e->src;
260 if (ancestor->loop_father != loop)
262 ancestor->loop_father = loop;
263 ancestor->loop_depth = depth;
264 num_nodes++;
265 VEC_safe_push (basic_block, heap, stack, ancestor);
270 VEC_free (basic_block, heap, stack);
272 return num_nodes;
275 /* Records the vector of superloops of the loop LOOP, whose immediate
276 superloop is FATHER. */
278 static void
279 establish_preds (struct loop *loop, struct loop *father)
281 loop_p ploop;
282 unsigned depth = loop_depth (father) + 1;
283 unsigned i;
285 VEC_truncate (loop_p, loop->superloops, 0);
286 VEC_reserve (loop_p, gc, loop->superloops, depth);
287 FOR_EACH_VEC_ELT (loop_p, father->superloops, i, ploop)
288 VEC_quick_push (loop_p, loop->superloops, ploop);
289 VEC_quick_push (loop_p, loop->superloops, father);
291 for (ploop = loop->inner; ploop; ploop = ploop->next)
292 establish_preds (ploop, loop);
295 /* Add LOOP to the loop hierarchy tree where FATHER is father of the
296 added loop. If LOOP has some children, take care of that their
297 pred field will be initialized correctly. */
299 void
300 flow_loop_tree_node_add (struct loop *father, struct loop *loop)
302 loop->next = father->inner;
303 father->inner = loop;
305 establish_preds (loop, father);
308 /* Remove LOOP from the loop hierarchy tree. */
310 void
311 flow_loop_tree_node_remove (struct loop *loop)
313 struct loop *prev, *father;
315 father = loop_outer (loop);
317 /* Remove loop from the list of sons. */
318 if (father->inner == loop)
319 father->inner = loop->next;
320 else
322 for (prev = father->inner; prev->next != loop; prev = prev->next)
323 continue;
324 prev->next = loop->next;
327 VEC_truncate (loop_p, loop->superloops, 0);
330 /* Allocates and returns new loop structure. */
332 struct loop *
333 alloc_loop (void)
335 struct loop *loop = ggc_alloc_cleared_loop ();
337 loop->exits = ggc_alloc_cleared_loop_exit ();
338 loop->exits->next = loop->exits->prev = loop->exits;
339 loop->can_be_parallel = false;
341 return loop;
344 /* Initializes loops structure LOOPS, reserving place for NUM_LOOPS loops
345 (including the root of the loop tree). */
347 static void
348 init_loops_structure (struct loops *loops, unsigned num_loops)
350 struct loop *root;
352 memset (loops, 0, sizeof *loops);
353 loops->larray = VEC_alloc (loop_p, gc, num_loops);
355 /* Dummy loop containing whole function. */
356 root = alloc_loop ();
357 root->num_nodes = n_basic_blocks;
358 root->latch = EXIT_BLOCK_PTR;
359 root->header = ENTRY_BLOCK_PTR;
360 ENTRY_BLOCK_PTR->loop_father = root;
361 EXIT_BLOCK_PTR->loop_father = root;
363 VEC_quick_push (loop_p, loops->larray, root);
364 loops->tree_root = root;
367 /* Find all the natural loops in the function and save in LOOPS structure and
368 recalculate loop_depth information in basic block structures.
369 Return the number of natural loops found. */
372 flow_loops_find (struct loops *loops)
374 int b;
375 int num_loops;
376 edge e;
377 sbitmap headers;
378 int *dfs_order;
379 int *rc_order;
380 basic_block header;
381 basic_block bb;
383 /* Ensure that the dominators are computed. */
384 calculate_dominance_info (CDI_DOMINATORS);
386 /* Taking care of this degenerate case makes the rest of
387 this code simpler. */
388 if (n_basic_blocks == NUM_FIXED_BLOCKS)
390 init_loops_structure (loops, 1);
391 return 1;
394 dfs_order = NULL;
395 rc_order = NULL;
397 /* Count the number of loop headers. This should be the
398 same as the number of natural loops. */
399 headers = sbitmap_alloc (last_basic_block);
400 sbitmap_zero (headers);
402 num_loops = 0;
403 FOR_EACH_BB (header)
405 edge_iterator ei;
407 header->loop_depth = 0;
409 /* If we have an abnormal predecessor, do not consider the
410 loop (not worth the problems). */
411 if (bb_has_abnormal_pred (header))
412 continue;
414 FOR_EACH_EDGE (e, ei, header->preds)
416 basic_block latch = e->src;
418 gcc_assert (!(e->flags & EDGE_ABNORMAL));
420 /* Look for back edges where a predecessor is dominated
421 by this block. A natural loop has a single entry
422 node (header) that dominates all the nodes in the
423 loop. It also has single back edge to the header
424 from a latch node. */
425 if (latch != ENTRY_BLOCK_PTR
426 && dominated_by_p (CDI_DOMINATORS, latch, header))
428 /* Shared headers should be eliminated by now. */
429 SET_BIT (headers, header->index);
430 num_loops++;
435 /* Allocate loop structures. */
436 init_loops_structure (loops, num_loops + 1);
438 /* Find and record information about all the natural loops
439 in the CFG. */
440 FOR_EACH_BB (bb)
441 bb->loop_father = loops->tree_root;
443 if (num_loops)
445 /* Compute depth first search order of the CFG so that outer
446 natural loops will be found before inner natural loops. */
447 dfs_order = XNEWVEC (int, n_basic_blocks);
448 rc_order = XNEWVEC (int, n_basic_blocks);
449 pre_and_rev_post_order_compute (dfs_order, rc_order, false);
451 num_loops = 1;
453 for (b = 0; b < n_basic_blocks - NUM_FIXED_BLOCKS; b++)
455 struct loop *loop;
456 edge_iterator ei;
458 /* Search the nodes of the CFG in reverse completion order
459 so that we can find outer loops first. */
460 if (!TEST_BIT (headers, rc_order[b]))
461 continue;
463 header = BASIC_BLOCK (rc_order[b]);
465 loop = alloc_loop ();
466 VEC_quick_push (loop_p, loops->larray, loop);
468 loop->header = header;
469 loop->num = num_loops;
470 num_loops++;
472 flow_loop_tree_node_add (header->loop_father, loop);
473 loop->num_nodes = flow_loop_nodes_find (loop->header, loop);
475 /* Look for the latch for this header block, if it has just a
476 single one. */
477 FOR_EACH_EDGE (e, ei, header->preds)
479 basic_block latch = e->src;
481 if (flow_bb_inside_loop_p (loop, latch))
483 if (loop->latch != NULL)
485 /* More than one latch edge. */
486 loop->latch = NULL;
487 break;
489 loop->latch = latch;
494 free (dfs_order);
495 free (rc_order);
498 sbitmap_free (headers);
500 loops->exits = NULL;
501 return VEC_length (loop_p, loops->larray);
504 /* Ratio of frequencies of edges so that one of more latch edges is
505 considered to belong to inner loop with same header. */
506 #define HEAVY_EDGE_RATIO 8
508 /* Minimum number of samples for that we apply
509 find_subloop_latch_edge_by_profile heuristics. */
510 #define HEAVY_EDGE_MIN_SAMPLES 10
512 /* If the profile info is available, finds an edge in LATCHES that much more
513 frequent than the remaining edges. Returns such an edge, or NULL if we do
514 not find one.
516 We do not use guessed profile here, only the measured one. The guessed
517 profile is usually too flat and unreliable for this (and it is mostly based
518 on the loop structure of the program, so it does not make much sense to
519 derive the loop structure from it). */
521 static edge
522 find_subloop_latch_edge_by_profile (VEC (edge, heap) *latches)
524 unsigned i;
525 edge e, me = NULL;
526 gcov_type mcount = 0, tcount = 0;
528 FOR_EACH_VEC_ELT (edge, latches, i, e)
530 if (e->count > mcount)
532 me = e;
533 mcount = e->count;
535 tcount += e->count;
538 if (tcount < HEAVY_EDGE_MIN_SAMPLES
539 || (tcount - mcount) * HEAVY_EDGE_RATIO > tcount)
540 return NULL;
542 if (dump_file)
543 fprintf (dump_file,
544 "Found latch edge %d -> %d using profile information.\n",
545 me->src->index, me->dest->index);
546 return me;
549 /* Among LATCHES, guesses a latch edge of LOOP corresponding to subloop, based
550 on the structure of induction variables. Returns this edge, or NULL if we
551 do not find any.
553 We are quite conservative, and look just for an obvious simple innermost
554 loop (which is the case where we would lose the most performance by not
555 disambiguating the loop). More precisely, we look for the following
556 situation: The source of the chosen latch edge dominates sources of all
557 the other latch edges. Additionally, the header does not contain a phi node
558 such that the argument from the chosen edge is equal to the argument from
559 another edge. */
561 static edge
562 find_subloop_latch_edge_by_ivs (struct loop *loop ATTRIBUTE_UNUSED, VEC (edge, heap) *latches)
564 edge e, latch = VEC_index (edge, latches, 0);
565 unsigned i;
566 gimple phi;
567 gimple_stmt_iterator psi;
568 tree lop;
569 basic_block bb;
571 /* Find the candidate for the latch edge. */
572 for (i = 1; VEC_iterate (edge, latches, i, e); i++)
573 if (dominated_by_p (CDI_DOMINATORS, latch->src, e->src))
574 latch = e;
576 /* Verify that it dominates all the latch edges. */
577 FOR_EACH_VEC_ELT (edge, latches, i, e)
578 if (!dominated_by_p (CDI_DOMINATORS, e->src, latch->src))
579 return NULL;
581 /* Check for a phi node that would deny that this is a latch edge of
582 a subloop. */
583 for (psi = gsi_start_phis (loop->header); !gsi_end_p (psi); gsi_next (&psi))
585 phi = gsi_stmt (psi);
586 lop = PHI_ARG_DEF_FROM_EDGE (phi, latch);
588 /* Ignore the values that are not changed inside the subloop. */
589 if (TREE_CODE (lop) != SSA_NAME
590 || SSA_NAME_DEF_STMT (lop) == phi)
591 continue;
592 bb = gimple_bb (SSA_NAME_DEF_STMT (lop));
593 if (!bb || !flow_bb_inside_loop_p (loop, bb))
594 continue;
596 FOR_EACH_VEC_ELT (edge, latches, i, e)
597 if (e != latch
598 && PHI_ARG_DEF_FROM_EDGE (phi, e) == lop)
599 return NULL;
602 if (dump_file)
603 fprintf (dump_file,
604 "Found latch edge %d -> %d using iv structure.\n",
605 latch->src->index, latch->dest->index);
606 return latch;
609 /* If we can determine that one of the several latch edges of LOOP behaves
610 as a latch edge of a separate subloop, returns this edge. Otherwise
611 returns NULL. */
613 static edge
614 find_subloop_latch_edge (struct loop *loop)
616 VEC (edge, heap) *latches = get_loop_latch_edges (loop);
617 edge latch = NULL;
619 if (VEC_length (edge, latches) > 1)
621 latch = find_subloop_latch_edge_by_profile (latches);
623 if (!latch
624 /* We consider ivs to guess the latch edge only in SSA. Perhaps we
625 should use cfghook for this, but it is hard to imagine it would
626 be useful elsewhere. */
627 && current_ir_type () == IR_GIMPLE)
628 latch = find_subloop_latch_edge_by_ivs (loop, latches);
631 VEC_free (edge, heap, latches);
632 return latch;
635 /* Callback for make_forwarder_block. Returns true if the edge E is marked
636 in the set MFB_REIS_SET. */
638 static struct pointer_set_t *mfb_reis_set;
639 static bool
640 mfb_redirect_edges_in_set (edge e)
642 return pointer_set_contains (mfb_reis_set, e);
645 /* Creates a subloop of LOOP with latch edge LATCH. */
647 static void
648 form_subloop (struct loop *loop, edge latch)
650 edge_iterator ei;
651 edge e, new_entry;
652 struct loop *new_loop;
654 mfb_reis_set = pointer_set_create ();
655 FOR_EACH_EDGE (e, ei, loop->header->preds)
657 if (e != latch)
658 pointer_set_insert (mfb_reis_set, e);
660 new_entry = make_forwarder_block (loop->header, mfb_redirect_edges_in_set,
661 NULL);
662 pointer_set_destroy (mfb_reis_set);
664 loop->header = new_entry->src;
666 /* Find the blocks and subloops that belong to the new loop, and add it to
667 the appropriate place in the loop tree. */
668 new_loop = alloc_loop ();
669 new_loop->header = new_entry->dest;
670 new_loop->latch = latch->src;
671 add_loop (new_loop, loop);
674 /* Make all the latch edges of LOOP to go to a single forwarder block --
675 a new latch of LOOP. */
677 static void
678 merge_latch_edges (struct loop *loop)
680 VEC (edge, heap) *latches = get_loop_latch_edges (loop);
681 edge latch, e;
682 unsigned i;
684 gcc_assert (VEC_length (edge, latches) > 0);
686 if (VEC_length (edge, latches) == 1)
687 loop->latch = VEC_index (edge, latches, 0)->src;
688 else
690 if (dump_file)
691 fprintf (dump_file, "Merged latch edges of loop %d\n", loop->num);
693 mfb_reis_set = pointer_set_create ();
694 FOR_EACH_VEC_ELT (edge, latches, i, e)
695 pointer_set_insert (mfb_reis_set, e);
696 latch = make_forwarder_block (loop->header, mfb_redirect_edges_in_set,
697 NULL);
698 pointer_set_destroy (mfb_reis_set);
700 loop->header = latch->dest;
701 loop->latch = latch->src;
704 VEC_free (edge, heap, latches);
707 /* LOOP may have several latch edges. Transform it into (possibly several)
708 loops with single latch edge. */
710 static void
711 disambiguate_multiple_latches (struct loop *loop)
713 edge e;
715 /* We eliminate the multiple latches by splitting the header to the forwarder
716 block F and the rest R, and redirecting the edges. There are two cases:
718 1) If there is a latch edge E that corresponds to a subloop (we guess
719 that based on profile -- if it is taken much more often than the
720 remaining edges; and on trees, using the information about induction
721 variables of the loops), we redirect E to R, all the remaining edges to
722 F, then rescan the loops and try again for the outer loop.
723 2) If there is no such edge, we redirect all latch edges to F, and the
724 entry edges to R, thus making F the single latch of the loop. */
726 if (dump_file)
727 fprintf (dump_file, "Disambiguating loop %d with multiple latches\n",
728 loop->num);
730 /* During latch merging, we may need to redirect the entry edges to a new
731 block. This would cause problems if the entry edge was the one from the
732 entry block. To avoid having to handle this case specially, split
733 such entry edge. */
734 e = find_edge (ENTRY_BLOCK_PTR, loop->header);
735 if (e)
736 split_edge (e);
738 while (1)
740 e = find_subloop_latch_edge (loop);
741 if (!e)
742 break;
744 form_subloop (loop, e);
747 merge_latch_edges (loop);
750 /* Split loops with multiple latch edges. */
752 void
753 disambiguate_loops_with_multiple_latches (void)
755 loop_iterator li;
756 struct loop *loop;
758 FOR_EACH_LOOP (li, loop, 0)
760 if (!loop->latch)
761 disambiguate_multiple_latches (loop);
765 /* Return nonzero if basic block BB belongs to LOOP. */
766 bool
767 flow_bb_inside_loop_p (const struct loop *loop, const_basic_block bb)
769 struct loop *source_loop;
771 if (bb == ENTRY_BLOCK_PTR || bb == EXIT_BLOCK_PTR)
772 return 0;
774 source_loop = bb->loop_father;
775 return loop == source_loop || flow_loop_nested_p (loop, source_loop);
778 /* Enumeration predicate for get_loop_body_with_size. */
779 static bool
780 glb_enum_p (const_basic_block bb, const void *glb_loop)
782 const struct loop *const loop = (const struct loop *) glb_loop;
783 return (bb != loop->header
784 && dominated_by_p (CDI_DOMINATORS, bb, loop->header));
787 /* Gets basic blocks of a LOOP. Header is the 0-th block, rest is in dfs
788 order against direction of edges from latch. Specially, if
789 header != latch, latch is the 1-st block. LOOP cannot be the fake
790 loop tree root, and its size must be at most MAX_SIZE. The blocks
791 in the LOOP body are stored to BODY, and the size of the LOOP is
792 returned. */
794 unsigned
795 get_loop_body_with_size (const struct loop *loop, basic_block *body,
796 unsigned max_size)
798 return dfs_enumerate_from (loop->header, 1, glb_enum_p,
799 body, max_size, loop);
802 /* Gets basic blocks of a LOOP. Header is the 0-th block, rest is in dfs
803 order against direction of edges from latch. Specially, if
804 header != latch, latch is the 1-st block. */
806 basic_block *
807 get_loop_body (const struct loop *loop)
809 basic_block *body, bb;
810 unsigned tv = 0;
812 gcc_assert (loop->num_nodes);
814 body = XCNEWVEC (basic_block, loop->num_nodes);
816 if (loop->latch == EXIT_BLOCK_PTR)
818 /* There may be blocks unreachable from EXIT_BLOCK, hence we need to
819 special-case the fake loop that contains the whole function. */
820 gcc_assert (loop->num_nodes == (unsigned) n_basic_blocks);
821 body[tv++] = loop->header;
822 body[tv++] = EXIT_BLOCK_PTR;
823 FOR_EACH_BB (bb)
824 body[tv++] = bb;
826 else
827 tv = get_loop_body_with_size (loop, body, loop->num_nodes);
829 gcc_assert (tv == loop->num_nodes);
830 return body;
833 /* Fills dominance descendants inside LOOP of the basic block BB into
834 array TOVISIT from index *TV. */
836 static void
837 fill_sons_in_loop (const struct loop *loop, basic_block bb,
838 basic_block *tovisit, int *tv)
840 basic_block son, postpone = NULL;
842 tovisit[(*tv)++] = bb;
843 for (son = first_dom_son (CDI_DOMINATORS, bb);
844 son;
845 son = next_dom_son (CDI_DOMINATORS, son))
847 if (!flow_bb_inside_loop_p (loop, son))
848 continue;
850 if (dominated_by_p (CDI_DOMINATORS, loop->latch, son))
852 postpone = son;
853 continue;
855 fill_sons_in_loop (loop, son, tovisit, tv);
858 if (postpone)
859 fill_sons_in_loop (loop, postpone, tovisit, tv);
862 /* Gets body of a LOOP (that must be different from the outermost loop)
863 sorted by dominance relation. Additionally, if a basic block s dominates
864 the latch, then only blocks dominated by s are be after it. */
866 basic_block *
867 get_loop_body_in_dom_order (const struct loop *loop)
869 basic_block *tovisit;
870 int tv;
872 gcc_assert (loop->num_nodes);
874 tovisit = XCNEWVEC (basic_block, loop->num_nodes);
876 gcc_assert (loop->latch != EXIT_BLOCK_PTR);
878 tv = 0;
879 fill_sons_in_loop (loop, loop->header, tovisit, &tv);
881 gcc_assert (tv == (int) loop->num_nodes);
883 return tovisit;
886 /* Gets body of a LOOP sorted via provided BB_COMPARATOR. */
888 basic_block *
889 get_loop_body_in_custom_order (const struct loop *loop,
890 int (*bb_comparator) (const void *, const void *))
892 basic_block *bbs = get_loop_body (loop);
894 qsort (bbs, loop->num_nodes, sizeof (basic_block), bb_comparator);
896 return bbs;
899 /* Get body of a LOOP in breadth first sort order. */
901 basic_block *
902 get_loop_body_in_bfs_order (const struct loop *loop)
904 basic_block *blocks;
905 basic_block bb;
906 bitmap visited;
907 unsigned int i = 0;
908 unsigned int vc = 1;
910 gcc_assert (loop->num_nodes);
911 gcc_assert (loop->latch != EXIT_BLOCK_PTR);
913 blocks = XCNEWVEC (basic_block, loop->num_nodes);
914 visited = BITMAP_ALLOC (NULL);
916 bb = loop->header;
917 while (i < loop->num_nodes)
919 edge e;
920 edge_iterator ei;
922 if (bitmap_set_bit (visited, bb->index))
923 /* This basic block is now visited */
924 blocks[i++] = bb;
926 FOR_EACH_EDGE (e, ei, bb->succs)
928 if (flow_bb_inside_loop_p (loop, e->dest))
930 if (bitmap_set_bit (visited, e->dest->index))
931 blocks[i++] = e->dest;
935 gcc_assert (i >= vc);
937 bb = blocks[vc++];
940 BITMAP_FREE (visited);
941 return blocks;
944 /* Hash function for struct loop_exit. */
946 static hashval_t
947 loop_exit_hash (const void *ex)
949 const struct loop_exit *const exit = (const struct loop_exit *) ex;
951 return htab_hash_pointer (exit->e);
954 /* Equality function for struct loop_exit. Compares with edge. */
956 static int
957 loop_exit_eq (const void *ex, const void *e)
959 const struct loop_exit *const exit = (const struct loop_exit *) ex;
961 return exit->e == e;
964 /* Frees the list of loop exit descriptions EX. */
966 static void
967 loop_exit_free (void *ex)
969 struct loop_exit *exit = (struct loop_exit *) ex, *next;
971 for (; exit; exit = next)
973 next = exit->next_e;
975 exit->next->prev = exit->prev;
976 exit->prev->next = exit->next;
978 ggc_free (exit);
982 /* Returns the list of records for E as an exit of a loop. */
984 static struct loop_exit *
985 get_exit_descriptions (edge e)
987 return (struct loop_exit *) htab_find_with_hash (current_loops->exits, e,
988 htab_hash_pointer (e));
991 /* Updates the lists of loop exits in that E appears.
992 If REMOVED is true, E is being removed, and we
993 just remove it from the lists of exits.
994 If NEW_EDGE is true and E is not a loop exit, we
995 do not try to remove it from loop exit lists. */
997 void
998 rescan_loop_exit (edge e, bool new_edge, bool removed)
1000 void **slot;
1001 struct loop_exit *exits = NULL, *exit;
1002 struct loop *aloop, *cloop;
1004 if (!loops_state_satisfies_p (LOOPS_HAVE_RECORDED_EXITS))
1005 return;
1007 if (!removed
1008 && e->src->loop_father != NULL
1009 && e->dest->loop_father != NULL
1010 && !flow_bb_inside_loop_p (e->src->loop_father, e->dest))
1012 cloop = find_common_loop (e->src->loop_father, e->dest->loop_father);
1013 for (aloop = e->src->loop_father;
1014 aloop != cloop;
1015 aloop = loop_outer (aloop))
1017 exit = ggc_alloc_loop_exit ();
1018 exit->e = e;
1020 exit->next = aloop->exits->next;
1021 exit->prev = aloop->exits;
1022 exit->next->prev = exit;
1023 exit->prev->next = exit;
1025 exit->next_e = exits;
1026 exits = exit;
1030 if (!exits && new_edge)
1031 return;
1033 slot = htab_find_slot_with_hash (current_loops->exits, e,
1034 htab_hash_pointer (e),
1035 exits ? INSERT : NO_INSERT);
1036 if (!slot)
1037 return;
1039 if (exits)
1041 if (*slot)
1042 loop_exit_free (*slot);
1043 *slot = exits;
1045 else
1046 htab_clear_slot (current_loops->exits, slot);
1049 /* For each loop, record list of exit edges, and start maintaining these
1050 lists. */
1052 void
1053 record_loop_exits (void)
1055 basic_block bb;
1056 edge_iterator ei;
1057 edge e;
1059 if (!current_loops)
1060 return;
1062 if (loops_state_satisfies_p (LOOPS_HAVE_RECORDED_EXITS))
1063 return;
1064 loops_state_set (LOOPS_HAVE_RECORDED_EXITS);
1066 gcc_assert (current_loops->exits == NULL);
1067 current_loops->exits = htab_create_ggc (2 * number_of_loops (),
1068 loop_exit_hash, loop_exit_eq,
1069 loop_exit_free);
1071 FOR_EACH_BB (bb)
1073 FOR_EACH_EDGE (e, ei, bb->succs)
1075 rescan_loop_exit (e, true, false);
1080 /* Dumps information about the exit in *SLOT to FILE.
1081 Callback for htab_traverse. */
1083 static int
1084 dump_recorded_exit (void **slot, void *file)
1086 struct loop_exit *exit = (struct loop_exit *) *slot;
1087 unsigned n = 0;
1088 edge e = exit->e;
1090 for (; exit != NULL; exit = exit->next_e)
1091 n++;
1093 fprintf ((FILE*) file, "Edge %d->%d exits %u loops\n",
1094 e->src->index, e->dest->index, n);
1096 return 1;
1099 /* Dumps the recorded exits of loops to FILE. */
1101 extern void dump_recorded_exits (FILE *);
1102 void
1103 dump_recorded_exits (FILE *file)
1105 if (!current_loops->exits)
1106 return;
1107 htab_traverse (current_loops->exits, dump_recorded_exit, file);
1110 /* Releases lists of loop exits. */
1112 void
1113 release_recorded_exits (void)
1115 gcc_assert (loops_state_satisfies_p (LOOPS_HAVE_RECORDED_EXITS));
1116 htab_delete (current_loops->exits);
1117 current_loops->exits = NULL;
1118 loops_state_clear (LOOPS_HAVE_RECORDED_EXITS);
1121 /* Returns the list of the exit edges of a LOOP. */
1123 VEC (edge, heap) *
1124 get_loop_exit_edges (const struct loop *loop)
1126 VEC (edge, heap) *edges = NULL;
1127 edge e;
1128 unsigned i;
1129 basic_block *body;
1130 edge_iterator ei;
1131 struct loop_exit *exit;
1133 gcc_assert (loop->latch != EXIT_BLOCK_PTR);
1135 /* If we maintain the lists of exits, use them. Otherwise we must
1136 scan the body of the loop. */
1137 if (loops_state_satisfies_p (LOOPS_HAVE_RECORDED_EXITS))
1139 for (exit = loop->exits->next; exit->e; exit = exit->next)
1140 VEC_safe_push (edge, heap, edges, exit->e);
1142 else
1144 body = get_loop_body (loop);
1145 for (i = 0; i < loop->num_nodes; i++)
1146 FOR_EACH_EDGE (e, ei, body[i]->succs)
1148 if (!flow_bb_inside_loop_p (loop, e->dest))
1149 VEC_safe_push (edge, heap, edges, e);
1151 free (body);
1154 return edges;
1157 /* Counts the number of conditional branches inside LOOP. */
1159 unsigned
1160 num_loop_branches (const struct loop *loop)
1162 unsigned i, n;
1163 basic_block * body;
1165 gcc_assert (loop->latch != EXIT_BLOCK_PTR);
1167 body = get_loop_body (loop);
1168 n = 0;
1169 for (i = 0; i < loop->num_nodes; i++)
1170 if (EDGE_COUNT (body[i]->succs) >= 2)
1171 n++;
1172 free (body);
1174 return n;
1177 /* Adds basic block BB to LOOP. */
1178 void
1179 add_bb_to_loop (basic_block bb, struct loop *loop)
1181 unsigned i;
1182 loop_p ploop;
1183 edge_iterator ei;
1184 edge e;
1186 gcc_assert (bb->loop_father == NULL);
1187 bb->loop_father = loop;
1188 bb->loop_depth = loop_depth (loop);
1189 loop->num_nodes++;
1190 FOR_EACH_VEC_ELT (loop_p, loop->superloops, i, ploop)
1191 ploop->num_nodes++;
1193 FOR_EACH_EDGE (e, ei, bb->succs)
1195 rescan_loop_exit (e, true, false);
1197 FOR_EACH_EDGE (e, ei, bb->preds)
1199 rescan_loop_exit (e, true, false);
1203 /* Remove basic block BB from loops. */
1204 void
1205 remove_bb_from_loops (basic_block bb)
1207 int i;
1208 struct loop *loop = bb->loop_father;
1209 loop_p ploop;
1210 edge_iterator ei;
1211 edge e;
1213 gcc_assert (loop != NULL);
1214 loop->num_nodes--;
1215 FOR_EACH_VEC_ELT (loop_p, loop->superloops, i, ploop)
1216 ploop->num_nodes--;
1217 bb->loop_father = NULL;
1218 bb->loop_depth = 0;
1220 FOR_EACH_EDGE (e, ei, bb->succs)
1222 rescan_loop_exit (e, false, true);
1224 FOR_EACH_EDGE (e, ei, bb->preds)
1226 rescan_loop_exit (e, false, true);
1230 /* Finds nearest common ancestor in loop tree for given loops. */
1231 struct loop *
1232 find_common_loop (struct loop *loop_s, struct loop *loop_d)
1234 unsigned sdepth, ddepth;
1236 if (!loop_s) return loop_d;
1237 if (!loop_d) return loop_s;
1239 sdepth = loop_depth (loop_s);
1240 ddepth = loop_depth (loop_d);
1242 if (sdepth < ddepth)
1243 loop_d = VEC_index (loop_p, loop_d->superloops, sdepth);
1244 else if (sdepth > ddepth)
1245 loop_s = VEC_index (loop_p, loop_s->superloops, ddepth);
1247 while (loop_s != loop_d)
1249 loop_s = loop_outer (loop_s);
1250 loop_d = loop_outer (loop_d);
1252 return loop_s;
1255 /* Removes LOOP from structures and frees its data. */
1257 void
1258 delete_loop (struct loop *loop)
1260 /* Remove the loop from structure. */
1261 flow_loop_tree_node_remove (loop);
1263 /* Remove loop from loops array. */
1264 VEC_replace (loop_p, current_loops->larray, loop->num, NULL);
1266 /* Free loop data. */
1267 flow_loop_free (loop);
1270 /* Cancels the LOOP; it must be innermost one. */
1272 static void
1273 cancel_loop (struct loop *loop)
1275 basic_block *bbs;
1276 unsigned i;
1277 struct loop *outer = loop_outer (loop);
1279 gcc_assert (!loop->inner);
1281 /* Move blocks up one level (they should be removed as soon as possible). */
1282 bbs = get_loop_body (loop);
1283 for (i = 0; i < loop->num_nodes; i++)
1284 bbs[i]->loop_father = outer;
1286 free (bbs);
1287 delete_loop (loop);
1290 /* Cancels LOOP and all its subloops. */
1291 void
1292 cancel_loop_tree (struct loop *loop)
1294 while (loop->inner)
1295 cancel_loop_tree (loop->inner);
1296 cancel_loop (loop);
1299 /* Checks that information about loops is correct
1300 -- sizes of loops are all right
1301 -- results of get_loop_body really belong to the loop
1302 -- loop header have just single entry edge and single latch edge
1303 -- loop latches have only single successor that is header of their loop
1304 -- irreducible loops are correctly marked
1306 DEBUG_FUNCTION void
1307 verify_loop_structure (void)
1309 unsigned *sizes, i, j;
1310 sbitmap irreds;
1311 basic_block *bbs, bb;
1312 struct loop *loop;
1313 int err = 0;
1314 edge e;
1315 unsigned num = number_of_loops ();
1316 loop_iterator li;
1317 struct loop_exit *exit, *mexit;
1318 bool dom_available = dom_info_available_p (CDI_DOMINATORS);
1320 /* We need up-to-date dominators, compute or verify them. */
1321 if (!dom_available)
1322 calculate_dominance_info (CDI_DOMINATORS);
1323 else
1324 verify_dominators (CDI_DOMINATORS);
1326 /* Check sizes. */
1327 sizes = XCNEWVEC (unsigned, num);
1328 sizes[0] = 2;
1330 FOR_EACH_BB (bb)
1331 for (loop = bb->loop_father; loop; loop = loop_outer (loop))
1332 sizes[loop->num]++;
1334 FOR_EACH_LOOP (li, loop, LI_INCLUDE_ROOT)
1336 i = loop->num;
1338 if (loop->num_nodes != sizes[i])
1340 error ("size of loop %d should be %d, not %d",
1341 i, sizes[i], loop->num_nodes);
1342 err = 1;
1346 /* Check get_loop_body. */
1347 FOR_EACH_LOOP (li, loop, 0)
1349 bbs = get_loop_body (loop);
1351 for (j = 0; j < loop->num_nodes; j++)
1352 if (!flow_bb_inside_loop_p (loop, bbs[j]))
1354 error ("bb %d do not belong to loop %d",
1355 bbs[j]->index, loop->num);
1356 err = 1;
1358 free (bbs);
1361 /* Check headers and latches. */
1362 FOR_EACH_LOOP (li, loop, 0)
1364 i = loop->num;
1366 if (loops_state_satisfies_p (LOOPS_HAVE_PREHEADERS)
1367 && EDGE_COUNT (loop->header->preds) != 2)
1369 error ("loop %d%'s header does not have exactly 2 entries", i);
1370 err = 1;
1372 if (loops_state_satisfies_p (LOOPS_HAVE_SIMPLE_LATCHES))
1374 if (!single_succ_p (loop->latch))
1376 error ("loop %d%'s latch does not have exactly 1 successor", i);
1377 err = 1;
1379 if (single_succ (loop->latch) != loop->header)
1381 error ("loop %d%'s latch does not have header as successor", i);
1382 err = 1;
1384 if (loop->latch->loop_father != loop)
1386 error ("loop %d%'s latch does not belong directly to it", i);
1387 err = 1;
1390 if (loop->header->loop_father != loop)
1392 error ("loop %d%'s header does not belong directly to it", i);
1393 err = 1;
1395 if (loops_state_satisfies_p (LOOPS_HAVE_MARKED_IRREDUCIBLE_REGIONS)
1396 && (loop_latch_edge (loop)->flags & EDGE_IRREDUCIBLE_LOOP))
1398 error ("loop %d%'s latch is marked as part of irreducible region", i);
1399 err = 1;
1403 /* Check irreducible loops. */
1404 if (loops_state_satisfies_p (LOOPS_HAVE_MARKED_IRREDUCIBLE_REGIONS))
1406 /* Record old info. */
1407 irreds = sbitmap_alloc (last_basic_block);
1408 FOR_EACH_BB (bb)
1410 edge_iterator ei;
1411 if (bb->flags & BB_IRREDUCIBLE_LOOP)
1412 SET_BIT (irreds, bb->index);
1413 else
1414 RESET_BIT (irreds, bb->index);
1415 FOR_EACH_EDGE (e, ei, bb->succs)
1416 if (e->flags & EDGE_IRREDUCIBLE_LOOP)
1417 e->flags |= EDGE_ALL_FLAGS + 1;
1420 /* Recount it. */
1421 mark_irreducible_loops ();
1423 /* Compare. */
1424 FOR_EACH_BB (bb)
1426 edge_iterator ei;
1428 if ((bb->flags & BB_IRREDUCIBLE_LOOP)
1429 && !TEST_BIT (irreds, bb->index))
1431 error ("basic block %d should be marked irreducible", bb->index);
1432 err = 1;
1434 else if (!(bb->flags & BB_IRREDUCIBLE_LOOP)
1435 && TEST_BIT (irreds, bb->index))
1437 error ("basic block %d should not be marked irreducible", bb->index);
1438 err = 1;
1440 FOR_EACH_EDGE (e, ei, bb->succs)
1442 if ((e->flags & EDGE_IRREDUCIBLE_LOOP)
1443 && !(e->flags & (EDGE_ALL_FLAGS + 1)))
1445 error ("edge from %d to %d should be marked irreducible",
1446 e->src->index, e->dest->index);
1447 err = 1;
1449 else if (!(e->flags & EDGE_IRREDUCIBLE_LOOP)
1450 && (e->flags & (EDGE_ALL_FLAGS + 1)))
1452 error ("edge from %d to %d should not be marked irreducible",
1453 e->src->index, e->dest->index);
1454 err = 1;
1456 e->flags &= ~(EDGE_ALL_FLAGS + 1);
1459 free (irreds);
1462 /* Check the recorded loop exits. */
1463 FOR_EACH_LOOP (li, loop, 0)
1465 if (!loop->exits || loop->exits->e != NULL)
1467 error ("corrupted head of the exits list of loop %d",
1468 loop->num);
1469 err = 1;
1471 else
1473 /* Check that the list forms a cycle, and all elements except
1474 for the head are nonnull. */
1475 for (mexit = loop->exits, exit = mexit->next, i = 0;
1476 exit->e && exit != mexit;
1477 exit = exit->next)
1479 if (i++ & 1)
1480 mexit = mexit->next;
1483 if (exit != loop->exits)
1485 error ("corrupted exits list of loop %d", loop->num);
1486 err = 1;
1490 if (!loops_state_satisfies_p (LOOPS_HAVE_RECORDED_EXITS))
1492 if (loop->exits->next != loop->exits)
1494 error ("nonempty exits list of loop %d, but exits are not recorded",
1495 loop->num);
1496 err = 1;
1501 if (loops_state_satisfies_p (LOOPS_HAVE_RECORDED_EXITS))
1503 unsigned n_exits = 0, eloops;
1505 memset (sizes, 0, sizeof (unsigned) * num);
1506 FOR_EACH_BB (bb)
1508 edge_iterator ei;
1509 if (bb->loop_father == current_loops->tree_root)
1510 continue;
1511 FOR_EACH_EDGE (e, ei, bb->succs)
1513 if (flow_bb_inside_loop_p (bb->loop_father, e->dest))
1514 continue;
1516 n_exits++;
1517 exit = get_exit_descriptions (e);
1518 if (!exit)
1520 error ("exit %d->%d not recorded",
1521 e->src->index, e->dest->index);
1522 err = 1;
1524 eloops = 0;
1525 for (; exit; exit = exit->next_e)
1526 eloops++;
1528 for (loop = bb->loop_father;
1529 loop != e->dest->loop_father;
1530 loop = loop_outer (loop))
1532 eloops--;
1533 sizes[loop->num]++;
1536 if (eloops != 0)
1538 error ("wrong list of exited loops for edge %d->%d",
1539 e->src->index, e->dest->index);
1540 err = 1;
1545 if (n_exits != htab_elements (current_loops->exits))
1547 error ("too many loop exits recorded");
1548 err = 1;
1551 FOR_EACH_LOOP (li, loop, 0)
1553 eloops = 0;
1554 for (exit = loop->exits->next; exit->e; exit = exit->next)
1555 eloops++;
1556 if (eloops != sizes[loop->num])
1558 error ("%d exits recorded for loop %d (having %d exits)",
1559 eloops, loop->num, sizes[loop->num]);
1560 err = 1;
1565 gcc_assert (!err);
1567 free (sizes);
1568 if (!dom_available)
1569 free_dominance_info (CDI_DOMINATORS);
1572 /* Returns latch edge of LOOP. */
1573 edge
1574 loop_latch_edge (const struct loop *loop)
1576 return find_edge (loop->latch, loop->header);
1579 /* Returns preheader edge of LOOP. */
1580 edge
1581 loop_preheader_edge (const struct loop *loop)
1583 edge e;
1584 edge_iterator ei;
1586 gcc_assert (loops_state_satisfies_p (LOOPS_HAVE_PREHEADERS));
1588 FOR_EACH_EDGE (e, ei, loop->header->preds)
1589 if (e->src != loop->latch)
1590 break;
1592 return e;
1595 /* Returns true if E is an exit of LOOP. */
1597 bool
1598 loop_exit_edge_p (const struct loop *loop, const_edge e)
1600 return (flow_bb_inside_loop_p (loop, e->src)
1601 && !flow_bb_inside_loop_p (loop, e->dest));
1604 /* Returns the single exit edge of LOOP, or NULL if LOOP has either no exit
1605 or more than one exit. If loops do not have the exits recorded, NULL
1606 is returned always. */
1608 edge
1609 single_exit (const struct loop *loop)
1611 struct loop_exit *exit = loop->exits->next;
1613 if (!loops_state_satisfies_p (LOOPS_HAVE_RECORDED_EXITS))
1614 return NULL;
1616 if (exit->e && exit->next == loop->exits)
1617 return exit->e;
1618 else
1619 return NULL;
1622 /* Returns true when BB has an incoming edge exiting LOOP. */
1624 bool
1625 loop_exits_to_bb_p (struct loop *loop, basic_block bb)
1627 edge e;
1628 edge_iterator ei;
1630 FOR_EACH_EDGE (e, ei, bb->preds)
1631 if (loop_exit_edge_p (loop, e))
1632 return true;
1634 return false;
1637 /* Returns true when BB has an outgoing edge exiting LOOP. */
1639 bool
1640 loop_exits_from_bb_p (struct loop *loop, basic_block bb)
1642 edge e;
1643 edge_iterator ei;
1645 FOR_EACH_EDGE (e, ei, bb->succs)
1646 if (loop_exit_edge_p (loop, e))
1647 return true;
1649 return false;