* config/darwin.c (darwin_assemble_visibility): Treat
[official-gcc.git] / gcc / sched-rgn.c
blob5d39a36d7fac93cd150eb01963b42b1702b12f21
1 /* Instruction scheduling pass.
2 Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2010, 2011
4 Free Software Foundation, Inc.
5 Contributed by Michael Tiemann (tiemann@cygnus.com) Enhanced by,
6 and currently maintained by, Jim Wilson (wilson@cygnus.com)
8 This file is part of GCC.
10 GCC is free software; you can redistribute it and/or modify it under
11 the terms of the GNU General Public License as published by the Free
12 Software Foundation; either version 3, or (at your option) any later
13 version.
15 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
16 WARRANTY; without even the implied warranty of MERCHANTABILITY or
17 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
18 for more details.
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3. If not see
22 <http://www.gnu.org/licenses/>. */
24 /* This pass implements list scheduling within basic blocks. It is
25 run twice: (1) after flow analysis, but before register allocation,
26 and (2) after register allocation.
28 The first run performs interblock scheduling, moving insns between
29 different blocks in the same "region", and the second runs only
30 basic block scheduling.
32 Interblock motions performed are useful motions and speculative
33 motions, including speculative loads. Motions requiring code
34 duplication are not supported. The identification of motion type
35 and the check for validity of speculative motions requires
36 construction and analysis of the function's control flow graph.
38 The main entry point for this pass is schedule_insns(), called for
39 each function. The work of the scheduler is organized in three
40 levels: (1) function level: insns are subject to splitting,
41 control-flow-graph is constructed, regions are computed (after
42 reload, each region is of one block), (2) region level: control
43 flow graph attributes required for interblock scheduling are
44 computed (dominators, reachability, etc.), data dependences and
45 priorities are computed, and (3) block level: insns in the block
46 are actually scheduled. */
48 #include "config.h"
49 #include "system.h"
50 #include "coretypes.h"
51 #include "tm.h"
52 #include "diagnostic-core.h"
53 #include "rtl.h"
54 #include "tm_p.h"
55 #include "hard-reg-set.h"
56 #include "regs.h"
57 #include "function.h"
58 #include "flags.h"
59 #include "insn-config.h"
60 #include "insn-attr.h"
61 #include "except.h"
62 #include "recog.h"
63 #include "params.h"
64 #include "sched-int.h"
65 #include "sel-sched.h"
66 #include "target.h"
67 #include "tree-pass.h"
68 #include "dbgcnt.h"
70 #ifdef INSN_SCHEDULING
72 /* Some accessor macros for h_i_d members only used within this file. */
73 #define FED_BY_SPEC_LOAD(INSN) (HID (INSN)->fed_by_spec_load)
74 #define IS_LOAD_INSN(INSN) (HID (insn)->is_load_insn)
76 /* nr_inter/spec counts interblock/speculative motion for the function. */
77 static int nr_inter, nr_spec;
79 static int is_cfg_nonregular (void);
81 /* Number of regions in the procedure. */
82 int nr_regions = 0;
84 /* Table of region descriptions. */
85 region *rgn_table = NULL;
87 /* Array of lists of regions' blocks. */
88 int *rgn_bb_table = NULL;
90 /* Topological order of blocks in the region (if b2 is reachable from
91 b1, block_to_bb[b2] > block_to_bb[b1]). Note: A basic block is
92 always referred to by either block or b, while its topological
93 order name (in the region) is referred to by bb. */
94 int *block_to_bb = NULL;
96 /* The number of the region containing a block. */
97 int *containing_rgn = NULL;
99 /* ebb_head [i] - is index in rgn_bb_table of the head basic block of i'th ebb.
100 Currently we can get a ebb only through splitting of currently
101 scheduling block, therefore, we don't need ebb_head array for every region,
102 hence, its sufficient to hold it for current one only. */
103 int *ebb_head = NULL;
105 /* The minimum probability of reaching a source block so that it will be
106 considered for speculative scheduling. */
107 static int min_spec_prob;
109 static void find_single_block_region (bool);
110 static void find_rgns (void);
111 static bool too_large (int, int *, int *);
113 /* Blocks of the current region being scheduled. */
114 int current_nr_blocks;
115 int current_blocks;
117 /* A speculative motion requires checking live information on the path
118 from 'source' to 'target'. The split blocks are those to be checked.
119 After a speculative motion, live information should be modified in
120 the 'update' blocks.
122 Lists of split and update blocks for each candidate of the current
123 target are in array bblst_table. */
124 static basic_block *bblst_table;
125 static int bblst_size, bblst_last;
127 /* Target info declarations.
129 The block currently being scheduled is referred to as the "target" block,
130 while other blocks in the region from which insns can be moved to the
131 target are called "source" blocks. The candidate structure holds info
132 about such sources: are they valid? Speculative? Etc. */
133 typedef struct
135 basic_block *first_member;
136 int nr_members;
138 bblst;
140 typedef struct
142 char is_valid;
143 char is_speculative;
144 int src_prob;
145 bblst split_bbs;
146 bblst update_bbs;
148 candidate;
150 static candidate *candidate_table;
151 #define IS_VALID(src) (candidate_table[src].is_valid)
152 #define IS_SPECULATIVE(src) (candidate_table[src].is_speculative)
153 #define IS_SPECULATIVE_INSN(INSN) \
154 (IS_SPECULATIVE (BLOCK_TO_BB (BLOCK_NUM (INSN))))
155 #define SRC_PROB(src) ( candidate_table[src].src_prob )
157 /* The bb being currently scheduled. */
158 int target_bb;
160 /* List of edges. */
161 typedef struct
163 edge *first_member;
164 int nr_members;
166 edgelst;
168 static edge *edgelst_table;
169 static int edgelst_last;
171 static void extract_edgelst (sbitmap, edgelst *);
173 /* Target info functions. */
174 static void split_edges (int, int, edgelst *);
175 static void compute_trg_info (int);
176 void debug_candidate (int);
177 void debug_candidates (int);
179 /* Dominators array: dom[i] contains the sbitmap of dominators of
180 bb i in the region. */
181 static sbitmap *dom;
183 /* bb 0 is the only region entry. */
184 #define IS_RGN_ENTRY(bb) (!bb)
186 /* Is bb_src dominated by bb_trg. */
187 #define IS_DOMINATED(bb_src, bb_trg) \
188 ( TEST_BIT (dom[bb_src], bb_trg) )
190 /* Probability: Prob[i] is an int in [0, REG_BR_PROB_BASE] which is
191 the probability of bb i relative to the region entry. */
192 static int *prob;
194 /* Bit-set of edges, where bit i stands for edge i. */
195 typedef sbitmap edgeset;
197 /* Number of edges in the region. */
198 static int rgn_nr_edges;
200 /* Array of size rgn_nr_edges. */
201 static edge *rgn_edges;
203 /* Mapping from each edge in the graph to its number in the rgn. */
204 #define EDGE_TO_BIT(edge) ((int)(size_t)(edge)->aux)
205 #define SET_EDGE_TO_BIT(edge,nr) ((edge)->aux = (void *)(size_t)(nr))
207 /* The split edges of a source bb is different for each target
208 bb. In order to compute this efficiently, the 'potential-split edges'
209 are computed for each bb prior to scheduling a region. This is actually
210 the split edges of each bb relative to the region entry.
212 pot_split[bb] is the set of potential split edges of bb. */
213 static edgeset *pot_split;
215 /* For every bb, a set of its ancestor edges. */
216 static edgeset *ancestor_edges;
218 #define INSN_PROBABILITY(INSN) (SRC_PROB (BLOCK_TO_BB (BLOCK_NUM (INSN))))
220 /* Speculative scheduling functions. */
221 static int check_live_1 (int, rtx);
222 static void update_live_1 (int, rtx);
223 static int is_pfree (rtx, int, int);
224 static int find_conditional_protection (rtx, int);
225 static int is_conditionally_protected (rtx, int, int);
226 static int is_prisky (rtx, int, int);
227 static int is_exception_free (rtx, int, int);
229 static bool sets_likely_spilled (rtx);
230 static void sets_likely_spilled_1 (rtx, const_rtx, void *);
231 static void add_branch_dependences (rtx, rtx);
232 static void compute_block_dependences (int);
234 static void schedule_region (int);
235 static void concat_insn_mem_list (rtx, rtx, rtx *, rtx *);
236 static void propagate_deps (int, struct deps_desc *);
237 static void free_pending_lists (void);
239 /* Functions for construction of the control flow graph. */
241 /* Return 1 if control flow graph should not be constructed, 0 otherwise.
243 We decide not to build the control flow graph if there is possibly more
244 than one entry to the function, if computed branches exist, if we
245 have nonlocal gotos, or if we have an unreachable loop. */
247 static int
248 is_cfg_nonregular (void)
250 basic_block b;
251 rtx insn;
253 /* If we have a label that could be the target of a nonlocal goto, then
254 the cfg is not well structured. */
255 if (nonlocal_goto_handler_labels)
256 return 1;
258 /* If we have any forced labels, then the cfg is not well structured. */
259 if (forced_labels)
260 return 1;
262 /* If we have exception handlers, then we consider the cfg not well
263 structured. ?!? We should be able to handle this now that we
264 compute an accurate cfg for EH. */
265 if (current_function_has_exception_handlers ())
266 return 1;
268 /* If we have insns which refer to labels as non-jumped-to operands,
269 then we consider the cfg not well structured. */
270 FOR_EACH_BB (b)
271 FOR_BB_INSNS (b, insn)
273 rtx note, next, set, dest;
275 /* If this function has a computed jump, then we consider the cfg
276 not well structured. */
277 if (JUMP_P (insn) && computed_jump_p (insn))
278 return 1;
280 if (!INSN_P (insn))
281 continue;
283 note = find_reg_note (insn, REG_LABEL_OPERAND, NULL_RTX);
284 if (note == NULL_RTX)
285 continue;
287 /* For that label not to be seen as a referred-to label, this
288 must be a single-set which is feeding a jump *only*. This
289 could be a conditional jump with the label split off for
290 machine-specific reasons or a casesi/tablejump. */
291 next = next_nonnote_insn (insn);
292 if (next == NULL_RTX
293 || !JUMP_P (next)
294 || (JUMP_LABEL (next) != XEXP (note, 0)
295 && find_reg_note (next, REG_LABEL_TARGET,
296 XEXP (note, 0)) == NULL_RTX)
297 || BLOCK_FOR_INSN (insn) != BLOCK_FOR_INSN (next))
298 return 1;
300 set = single_set (insn);
301 if (set == NULL_RTX)
302 return 1;
304 dest = SET_DEST (set);
305 if (!REG_P (dest) || !dead_or_set_p (next, dest))
306 return 1;
309 /* Unreachable loops with more than one basic block are detected
310 during the DFS traversal in find_rgns.
312 Unreachable loops with a single block are detected here. This
313 test is redundant with the one in find_rgns, but it's much
314 cheaper to go ahead and catch the trivial case here. */
315 FOR_EACH_BB (b)
317 if (EDGE_COUNT (b->preds) == 0
318 || (single_pred_p (b)
319 && single_pred (b) == b))
320 return 1;
323 /* All the tests passed. Consider the cfg well structured. */
324 return 0;
327 /* Extract list of edges from a bitmap containing EDGE_TO_BIT bits. */
329 static void
330 extract_edgelst (sbitmap set, edgelst *el)
332 unsigned int i = 0;
333 sbitmap_iterator sbi;
335 /* edgelst table space is reused in each call to extract_edgelst. */
336 edgelst_last = 0;
338 el->first_member = &edgelst_table[edgelst_last];
339 el->nr_members = 0;
341 /* Iterate over each word in the bitset. */
342 EXECUTE_IF_SET_IN_SBITMAP (set, 0, i, sbi)
344 edgelst_table[edgelst_last++] = rgn_edges[i];
345 el->nr_members++;
349 /* Functions for the construction of regions. */
351 /* Print the regions, for debugging purposes. Callable from debugger. */
353 DEBUG_FUNCTION void
354 debug_regions (void)
356 int rgn, bb;
358 fprintf (sched_dump, "\n;; ------------ REGIONS ----------\n\n");
359 for (rgn = 0; rgn < nr_regions; rgn++)
361 fprintf (sched_dump, ";;\trgn %d nr_blocks %d:\n", rgn,
362 rgn_table[rgn].rgn_nr_blocks);
363 fprintf (sched_dump, ";;\tbb/block: ");
365 /* We don't have ebb_head initialized yet, so we can't use
366 BB_TO_BLOCK (). */
367 current_blocks = RGN_BLOCKS (rgn);
369 for (bb = 0; bb < rgn_table[rgn].rgn_nr_blocks; bb++)
370 fprintf (sched_dump, " %d/%d ", bb, rgn_bb_table[current_blocks + bb]);
372 fprintf (sched_dump, "\n\n");
376 /* Print the region's basic blocks. */
378 DEBUG_FUNCTION void
379 debug_region (int rgn)
381 int bb;
383 fprintf (stderr, "\n;; ------------ REGION %d ----------\n\n", rgn);
384 fprintf (stderr, ";;\trgn %d nr_blocks %d:\n", rgn,
385 rgn_table[rgn].rgn_nr_blocks);
386 fprintf (stderr, ";;\tbb/block: ");
388 /* We don't have ebb_head initialized yet, so we can't use
389 BB_TO_BLOCK (). */
390 current_blocks = RGN_BLOCKS (rgn);
392 for (bb = 0; bb < rgn_table[rgn].rgn_nr_blocks; bb++)
393 fprintf (stderr, " %d/%d ", bb, rgn_bb_table[current_blocks + bb]);
395 fprintf (stderr, "\n\n");
397 for (bb = 0; bb < rgn_table[rgn].rgn_nr_blocks; bb++)
399 dump_bb (stderr, BASIC_BLOCK (rgn_bb_table[current_blocks + bb]),
400 0, TDF_SLIM | TDF_BLOCKS);
401 fprintf (stderr, "\n");
404 fprintf (stderr, "\n");
408 /* True when a bb with index BB_INDEX contained in region RGN. */
409 static bool
410 bb_in_region_p (int bb_index, int rgn)
412 int i;
414 for (i = 0; i < rgn_table[rgn].rgn_nr_blocks; i++)
415 if (rgn_bb_table[current_blocks + i] == bb_index)
416 return true;
418 return false;
421 /* Dump region RGN to file F using dot syntax. */
422 void
423 dump_region_dot (FILE *f, int rgn)
425 int i;
427 fprintf (f, "digraph Region_%d {\n", rgn);
429 /* We don't have ebb_head initialized yet, so we can't use
430 BB_TO_BLOCK (). */
431 current_blocks = RGN_BLOCKS (rgn);
433 for (i = 0; i < rgn_table[rgn].rgn_nr_blocks; i++)
435 edge e;
436 edge_iterator ei;
437 int src_bb_num = rgn_bb_table[current_blocks + i];
438 basic_block bb = BASIC_BLOCK (src_bb_num);
440 FOR_EACH_EDGE (e, ei, bb->succs)
441 if (bb_in_region_p (e->dest->index, rgn))
442 fprintf (f, "\t%d -> %d\n", src_bb_num, e->dest->index);
444 fprintf (f, "}\n");
447 /* The same, but first open a file specified by FNAME. */
448 void
449 dump_region_dot_file (const char *fname, int rgn)
451 FILE *f = fopen (fname, "wt");
452 dump_region_dot (f, rgn);
453 fclose (f);
456 /* Build a single block region for each basic block in the function.
457 This allows for using the same code for interblock and basic block
458 scheduling. */
460 static void
461 find_single_block_region (bool ebbs_p)
463 basic_block bb, ebb_start;
464 int i = 0;
466 nr_regions = 0;
468 if (ebbs_p) {
469 int probability_cutoff;
470 if (profile_info && flag_branch_probabilities)
471 probability_cutoff = PARAM_VALUE (TRACER_MIN_BRANCH_PROBABILITY_FEEDBACK);
472 else
473 probability_cutoff = PARAM_VALUE (TRACER_MIN_BRANCH_PROBABILITY);
474 probability_cutoff = REG_BR_PROB_BASE / 100 * probability_cutoff;
476 FOR_EACH_BB (ebb_start)
478 RGN_NR_BLOCKS (nr_regions) = 0;
479 RGN_BLOCKS (nr_regions) = i;
480 RGN_DONT_CALC_DEPS (nr_regions) = 0;
481 RGN_HAS_REAL_EBB (nr_regions) = 0;
483 for (bb = ebb_start; ; bb = bb->next_bb)
485 edge e;
487 rgn_bb_table[i] = bb->index;
488 RGN_NR_BLOCKS (nr_regions)++;
489 CONTAINING_RGN (bb->index) = nr_regions;
490 BLOCK_TO_BB (bb->index) = i - RGN_BLOCKS (nr_regions);
491 i++;
493 if (bb->next_bb == EXIT_BLOCK_PTR
494 || LABEL_P (BB_HEAD (bb->next_bb)))
495 break;
497 e = find_fallthru_edge (bb->succs);
498 if (! e)
499 break;
500 if (e->probability <= probability_cutoff)
501 break;
504 ebb_start = bb;
505 nr_regions++;
508 else
509 FOR_EACH_BB (bb)
511 rgn_bb_table[nr_regions] = bb->index;
512 RGN_NR_BLOCKS (nr_regions) = 1;
513 RGN_BLOCKS (nr_regions) = nr_regions;
514 RGN_DONT_CALC_DEPS (nr_regions) = 0;
515 RGN_HAS_REAL_EBB (nr_regions) = 0;
517 CONTAINING_RGN (bb->index) = nr_regions;
518 BLOCK_TO_BB (bb->index) = 0;
519 nr_regions++;
523 /* Estimate number of the insns in the BB. */
524 static int
525 rgn_estimate_number_of_insns (basic_block bb)
527 int count;
529 count = INSN_LUID (BB_END (bb)) - INSN_LUID (BB_HEAD (bb));
531 if (MAY_HAVE_DEBUG_INSNS)
533 rtx insn;
535 FOR_BB_INSNS (bb, insn)
536 if (DEBUG_INSN_P (insn))
537 count--;
540 return count;
543 /* Update number of blocks and the estimate for number of insns
544 in the region. Return true if the region is "too large" for interblock
545 scheduling (compile time considerations). */
547 static bool
548 too_large (int block, int *num_bbs, int *num_insns)
550 (*num_bbs)++;
551 (*num_insns) += (common_sched_info->estimate_number_of_insns
552 (BASIC_BLOCK (block)));
554 return ((*num_bbs > PARAM_VALUE (PARAM_MAX_SCHED_REGION_BLOCKS))
555 || (*num_insns > PARAM_VALUE (PARAM_MAX_SCHED_REGION_INSNS)));
558 /* Update_loop_relations(blk, hdr): Check if the loop headed by max_hdr[blk]
559 is still an inner loop. Put in max_hdr[blk] the header of the most inner
560 loop containing blk. */
561 #define UPDATE_LOOP_RELATIONS(blk, hdr) \
563 if (max_hdr[blk] == -1) \
564 max_hdr[blk] = hdr; \
565 else if (dfs_nr[max_hdr[blk]] > dfs_nr[hdr]) \
566 RESET_BIT (inner, hdr); \
567 else if (dfs_nr[max_hdr[blk]] < dfs_nr[hdr]) \
569 RESET_BIT (inner,max_hdr[blk]); \
570 max_hdr[blk] = hdr; \
574 /* Find regions for interblock scheduling.
576 A region for scheduling can be:
578 * A loop-free procedure, or
580 * A reducible inner loop, or
582 * A basic block not contained in any other region.
584 ?!? In theory we could build other regions based on extended basic
585 blocks or reverse extended basic blocks. Is it worth the trouble?
587 Loop blocks that form a region are put into the region's block list
588 in topological order.
590 This procedure stores its results into the following global (ick) variables
592 * rgn_nr
593 * rgn_table
594 * rgn_bb_table
595 * block_to_bb
596 * containing region
598 We use dominator relationships to avoid making regions out of non-reducible
599 loops.
601 This procedure needs to be converted to work on pred/succ lists instead
602 of edge tables. That would simplify it somewhat. */
604 static void
605 haifa_find_rgns (void)
607 int *max_hdr, *dfs_nr, *degree;
608 char no_loops = 1;
609 int node, child, loop_head, i, head, tail;
610 int count = 0, sp, idx = 0;
611 edge_iterator current_edge;
612 edge_iterator *stack;
613 int num_bbs, num_insns, unreachable;
614 int too_large_failure;
615 basic_block bb;
617 /* Note if a block is a natural loop header. */
618 sbitmap header;
620 /* Note if a block is a natural inner loop header. */
621 sbitmap inner;
623 /* Note if a block is in the block queue. */
624 sbitmap in_queue;
626 /* Note if a block is in the block queue. */
627 sbitmap in_stack;
629 /* Perform a DFS traversal of the cfg. Identify loop headers, inner loops
630 and a mapping from block to its loop header (if the block is contained
631 in a loop, else -1).
633 Store results in HEADER, INNER, and MAX_HDR respectively, these will
634 be used as inputs to the second traversal.
636 STACK, SP and DFS_NR are only used during the first traversal. */
638 /* Allocate and initialize variables for the first traversal. */
639 max_hdr = XNEWVEC (int, last_basic_block);
640 dfs_nr = XCNEWVEC (int, last_basic_block);
641 stack = XNEWVEC (edge_iterator, n_edges);
643 inner = sbitmap_alloc (last_basic_block);
644 sbitmap_ones (inner);
646 header = sbitmap_alloc (last_basic_block);
647 sbitmap_zero (header);
649 in_queue = sbitmap_alloc (last_basic_block);
650 sbitmap_zero (in_queue);
652 in_stack = sbitmap_alloc (last_basic_block);
653 sbitmap_zero (in_stack);
655 for (i = 0; i < last_basic_block; i++)
656 max_hdr[i] = -1;
658 #define EDGE_PASSED(E) (ei_end_p ((E)) || ei_edge ((E))->aux)
659 #define SET_EDGE_PASSED(E) (ei_edge ((E))->aux = ei_edge ((E)))
661 /* DFS traversal to find inner loops in the cfg. */
663 current_edge = ei_start (single_succ (ENTRY_BLOCK_PTR)->succs);
664 sp = -1;
666 while (1)
668 if (EDGE_PASSED (current_edge))
670 /* We have reached a leaf node or a node that was already
671 processed. Pop edges off the stack until we find
672 an edge that has not yet been processed. */
673 while (sp >= 0 && EDGE_PASSED (current_edge))
675 /* Pop entry off the stack. */
676 current_edge = stack[sp--];
677 node = ei_edge (current_edge)->src->index;
678 gcc_assert (node != ENTRY_BLOCK);
679 child = ei_edge (current_edge)->dest->index;
680 gcc_assert (child != EXIT_BLOCK);
681 RESET_BIT (in_stack, child);
682 if (max_hdr[child] >= 0 && TEST_BIT (in_stack, max_hdr[child]))
683 UPDATE_LOOP_RELATIONS (node, max_hdr[child]);
684 ei_next (&current_edge);
687 /* See if have finished the DFS tree traversal. */
688 if (sp < 0 && EDGE_PASSED (current_edge))
689 break;
691 /* Nope, continue the traversal with the popped node. */
692 continue;
695 /* Process a node. */
696 node = ei_edge (current_edge)->src->index;
697 gcc_assert (node != ENTRY_BLOCK);
698 SET_BIT (in_stack, node);
699 dfs_nr[node] = ++count;
701 /* We don't traverse to the exit block. */
702 child = ei_edge (current_edge)->dest->index;
703 if (child == EXIT_BLOCK)
705 SET_EDGE_PASSED (current_edge);
706 ei_next (&current_edge);
707 continue;
710 /* If the successor is in the stack, then we've found a loop.
711 Mark the loop, if it is not a natural loop, then it will
712 be rejected during the second traversal. */
713 if (TEST_BIT (in_stack, child))
715 no_loops = 0;
716 SET_BIT (header, child);
717 UPDATE_LOOP_RELATIONS (node, child);
718 SET_EDGE_PASSED (current_edge);
719 ei_next (&current_edge);
720 continue;
723 /* If the child was already visited, then there is no need to visit
724 it again. Just update the loop relationships and restart
725 with a new edge. */
726 if (dfs_nr[child])
728 if (max_hdr[child] >= 0 && TEST_BIT (in_stack, max_hdr[child]))
729 UPDATE_LOOP_RELATIONS (node, max_hdr[child]);
730 SET_EDGE_PASSED (current_edge);
731 ei_next (&current_edge);
732 continue;
735 /* Push an entry on the stack and continue DFS traversal. */
736 stack[++sp] = current_edge;
737 SET_EDGE_PASSED (current_edge);
738 current_edge = ei_start (ei_edge (current_edge)->dest->succs);
741 /* Reset ->aux field used by EDGE_PASSED. */
742 FOR_ALL_BB (bb)
744 edge_iterator ei;
745 edge e;
746 FOR_EACH_EDGE (e, ei, bb->succs)
747 e->aux = NULL;
751 /* Another check for unreachable blocks. The earlier test in
752 is_cfg_nonregular only finds unreachable blocks that do not
753 form a loop.
755 The DFS traversal will mark every block that is reachable from
756 the entry node by placing a nonzero value in dfs_nr. Thus if
757 dfs_nr is zero for any block, then it must be unreachable. */
758 unreachable = 0;
759 FOR_EACH_BB (bb)
760 if (dfs_nr[bb->index] == 0)
762 unreachable = 1;
763 break;
766 /* Gross. To avoid wasting memory, the second pass uses the dfs_nr array
767 to hold degree counts. */
768 degree = dfs_nr;
770 FOR_EACH_BB (bb)
771 degree[bb->index] = EDGE_COUNT (bb->preds);
773 /* Do not perform region scheduling if there are any unreachable
774 blocks. */
775 if (!unreachable)
777 int *queue, *degree1 = NULL;
778 /* We use EXTENDED_RGN_HEADER as an addition to HEADER and put
779 there basic blocks, which are forced to be region heads.
780 This is done to try to assemble few smaller regions
781 from a too_large region. */
782 sbitmap extended_rgn_header = NULL;
783 bool extend_regions_p;
785 if (no_loops)
786 SET_BIT (header, 0);
788 /* Second traversal:find reducible inner loops and topologically sort
789 block of each region. */
791 queue = XNEWVEC (int, n_basic_blocks);
793 extend_regions_p = PARAM_VALUE (PARAM_MAX_SCHED_EXTEND_REGIONS_ITERS) > 0;
794 if (extend_regions_p)
796 degree1 = XNEWVEC (int, last_basic_block);
797 extended_rgn_header = sbitmap_alloc (last_basic_block);
798 sbitmap_zero (extended_rgn_header);
801 /* Find blocks which are inner loop headers. We still have non-reducible
802 loops to consider at this point. */
803 FOR_EACH_BB (bb)
805 if (TEST_BIT (header, bb->index) && TEST_BIT (inner, bb->index))
807 edge e;
808 edge_iterator ei;
809 basic_block jbb;
811 /* Now check that the loop is reducible. We do this separate
812 from finding inner loops so that we do not find a reducible
813 loop which contains an inner non-reducible loop.
815 A simple way to find reducible/natural loops is to verify
816 that each block in the loop is dominated by the loop
817 header.
819 If there exists a block that is not dominated by the loop
820 header, then the block is reachable from outside the loop
821 and thus the loop is not a natural loop. */
822 FOR_EACH_BB (jbb)
824 /* First identify blocks in the loop, except for the loop
825 entry block. */
826 if (bb->index == max_hdr[jbb->index] && bb != jbb)
828 /* Now verify that the block is dominated by the loop
829 header. */
830 if (!dominated_by_p (CDI_DOMINATORS, jbb, bb))
831 break;
835 /* If we exited the loop early, then I is the header of
836 a non-reducible loop and we should quit processing it
837 now. */
838 if (jbb != EXIT_BLOCK_PTR)
839 continue;
841 /* I is a header of an inner loop, or block 0 in a subroutine
842 with no loops at all. */
843 head = tail = -1;
844 too_large_failure = 0;
845 loop_head = max_hdr[bb->index];
847 if (extend_regions_p)
848 /* We save degree in case when we meet a too_large region
849 and cancel it. We need a correct degree later when
850 calling extend_rgns. */
851 memcpy (degree1, degree, last_basic_block * sizeof (int));
853 /* Decrease degree of all I's successors for topological
854 ordering. */
855 FOR_EACH_EDGE (e, ei, bb->succs)
856 if (e->dest != EXIT_BLOCK_PTR)
857 --degree[e->dest->index];
859 /* Estimate # insns, and count # blocks in the region. */
860 num_bbs = 1;
861 num_insns = common_sched_info->estimate_number_of_insns (bb);
863 /* Find all loop latches (blocks with back edges to the loop
864 header) or all the leaf blocks in the cfg has no loops.
866 Place those blocks into the queue. */
867 if (no_loops)
869 FOR_EACH_BB (jbb)
870 /* Leaf nodes have only a single successor which must
871 be EXIT_BLOCK. */
872 if (single_succ_p (jbb)
873 && single_succ (jbb) == EXIT_BLOCK_PTR)
875 queue[++tail] = jbb->index;
876 SET_BIT (in_queue, jbb->index);
878 if (too_large (jbb->index, &num_bbs, &num_insns))
880 too_large_failure = 1;
881 break;
885 else
887 edge e;
889 FOR_EACH_EDGE (e, ei, bb->preds)
891 if (e->src == ENTRY_BLOCK_PTR)
892 continue;
894 node = e->src->index;
896 if (max_hdr[node] == loop_head && node != bb->index)
898 /* This is a loop latch. */
899 queue[++tail] = node;
900 SET_BIT (in_queue, node);
902 if (too_large (node, &num_bbs, &num_insns))
904 too_large_failure = 1;
905 break;
911 /* Now add all the blocks in the loop to the queue.
913 We know the loop is a natural loop; however the algorithm
914 above will not always mark certain blocks as being in the
915 loop. Consider:
916 node children
917 a b,c
919 c a,d
922 The algorithm in the DFS traversal may not mark B & D as part
923 of the loop (i.e. they will not have max_hdr set to A).
925 We know they can not be loop latches (else they would have
926 had max_hdr set since they'd have a backedge to a dominator
927 block). So we don't need them on the initial queue.
929 We know they are part of the loop because they are dominated
930 by the loop header and can be reached by a backwards walk of
931 the edges starting with nodes on the initial queue.
933 It is safe and desirable to include those nodes in the
934 loop/scheduling region. To do so we would need to decrease
935 the degree of a node if it is the target of a backedge
936 within the loop itself as the node is placed in the queue.
938 We do not do this because I'm not sure that the actual
939 scheduling code will properly handle this case. ?!? */
941 while (head < tail && !too_large_failure)
943 edge e;
944 child = queue[++head];
946 FOR_EACH_EDGE (e, ei, BASIC_BLOCK (child)->preds)
948 node = e->src->index;
950 /* See discussion above about nodes not marked as in
951 this loop during the initial DFS traversal. */
952 if (e->src == ENTRY_BLOCK_PTR
953 || max_hdr[node] != loop_head)
955 tail = -1;
956 break;
958 else if (!TEST_BIT (in_queue, node) && node != bb->index)
960 queue[++tail] = node;
961 SET_BIT (in_queue, node);
963 if (too_large (node, &num_bbs, &num_insns))
965 too_large_failure = 1;
966 break;
972 if (tail >= 0 && !too_large_failure)
974 /* Place the loop header into list of region blocks. */
975 degree[bb->index] = -1;
976 rgn_bb_table[idx] = bb->index;
977 RGN_NR_BLOCKS (nr_regions) = num_bbs;
978 RGN_BLOCKS (nr_regions) = idx++;
979 RGN_DONT_CALC_DEPS (nr_regions) = 0;
980 RGN_HAS_REAL_EBB (nr_regions) = 0;
981 CONTAINING_RGN (bb->index) = nr_regions;
982 BLOCK_TO_BB (bb->index) = count = 0;
984 /* Remove blocks from queue[] when their in degree
985 becomes zero. Repeat until no blocks are left on the
986 list. This produces a topological list of blocks in
987 the region. */
988 while (tail >= 0)
990 if (head < 0)
991 head = tail;
992 child = queue[head];
993 if (degree[child] == 0)
995 edge e;
997 degree[child] = -1;
998 rgn_bb_table[idx++] = child;
999 BLOCK_TO_BB (child) = ++count;
1000 CONTAINING_RGN (child) = nr_regions;
1001 queue[head] = queue[tail--];
1003 FOR_EACH_EDGE (e, ei, BASIC_BLOCK (child)->succs)
1004 if (e->dest != EXIT_BLOCK_PTR)
1005 --degree[e->dest->index];
1007 else
1008 --head;
1010 ++nr_regions;
1012 else if (extend_regions_p)
1014 /* Restore DEGREE. */
1015 int *t = degree;
1017 degree = degree1;
1018 degree1 = t;
1020 /* And force successors of BB to be region heads.
1021 This may provide several smaller regions instead
1022 of one too_large region. */
1023 FOR_EACH_EDGE (e, ei, bb->succs)
1024 if (e->dest != EXIT_BLOCK_PTR)
1025 SET_BIT (extended_rgn_header, e->dest->index);
1029 free (queue);
1031 if (extend_regions_p)
1033 free (degree1);
1035 sbitmap_a_or_b (header, header, extended_rgn_header);
1036 sbitmap_free (extended_rgn_header);
1038 extend_rgns (degree, &idx, header, max_hdr);
1042 /* Any block that did not end up in a region is placed into a region
1043 by itself. */
1044 FOR_EACH_BB (bb)
1045 if (degree[bb->index] >= 0)
1047 rgn_bb_table[idx] = bb->index;
1048 RGN_NR_BLOCKS (nr_regions) = 1;
1049 RGN_BLOCKS (nr_regions) = idx++;
1050 RGN_DONT_CALC_DEPS (nr_regions) = 0;
1051 RGN_HAS_REAL_EBB (nr_regions) = 0;
1052 CONTAINING_RGN (bb->index) = nr_regions++;
1053 BLOCK_TO_BB (bb->index) = 0;
1056 free (max_hdr);
1057 free (degree);
1058 free (stack);
1059 sbitmap_free (header);
1060 sbitmap_free (inner);
1061 sbitmap_free (in_queue);
1062 sbitmap_free (in_stack);
1066 /* Wrapper function.
1067 If FLAG_SEL_SCHED_PIPELINING is set, then use custom function to form
1068 regions. Otherwise just call find_rgns_haifa. */
1069 static void
1070 find_rgns (void)
1072 if (sel_sched_p () && flag_sel_sched_pipelining)
1073 sel_find_rgns ();
1074 else
1075 haifa_find_rgns ();
1078 static int gather_region_statistics (int **);
1079 static void print_region_statistics (int *, int, int *, int);
1081 /* Calculate the histogram that shows the number of regions having the
1082 given number of basic blocks, and store it in the RSP array. Return
1083 the size of this array. */
1084 static int
1085 gather_region_statistics (int **rsp)
1087 int i, *a = 0, a_sz = 0;
1089 /* a[i] is the number of regions that have (i + 1) basic blocks. */
1090 for (i = 0; i < nr_regions; i++)
1092 int nr_blocks = RGN_NR_BLOCKS (i);
1094 gcc_assert (nr_blocks >= 1);
1096 if (nr_blocks > a_sz)
1098 a = XRESIZEVEC (int, a, nr_blocks);
1100 a[a_sz++] = 0;
1101 while (a_sz != nr_blocks);
1104 a[nr_blocks - 1]++;
1107 *rsp = a;
1108 return a_sz;
1111 /* Print regions statistics. S1 and S2 denote the data before and after
1112 calling extend_rgns, respectively. */
1113 static void
1114 print_region_statistics (int *s1, int s1_sz, int *s2, int s2_sz)
1116 int i;
1118 /* We iterate until s2_sz because extend_rgns does not decrease
1119 the maximal region size. */
1120 for (i = 1; i < s2_sz; i++)
1122 int n1, n2;
1124 n2 = s2[i];
1126 if (n2 == 0)
1127 continue;
1129 if (i >= s1_sz)
1130 n1 = 0;
1131 else
1132 n1 = s1[i];
1134 fprintf (sched_dump, ";; Region extension statistics: size %d: " \
1135 "was %d + %d more\n", i + 1, n1, n2 - n1);
1139 /* Extend regions.
1140 DEGREE - Array of incoming edge count, considering only
1141 the edges, that don't have their sources in formed regions yet.
1142 IDXP - pointer to the next available index in rgn_bb_table.
1143 HEADER - set of all region heads.
1144 LOOP_HDR - mapping from block to the containing loop
1145 (two blocks can reside within one region if they have
1146 the same loop header). */
1147 void
1148 extend_rgns (int *degree, int *idxp, sbitmap header, int *loop_hdr)
1150 int *order, i, rescan = 0, idx = *idxp, iter = 0, max_iter, *max_hdr;
1151 int nblocks = n_basic_blocks - NUM_FIXED_BLOCKS;
1153 max_iter = PARAM_VALUE (PARAM_MAX_SCHED_EXTEND_REGIONS_ITERS);
1155 max_hdr = XNEWVEC (int, last_basic_block);
1157 order = XNEWVEC (int, last_basic_block);
1158 post_order_compute (order, false, false);
1160 for (i = nblocks - 1; i >= 0; i--)
1162 int bbn = order[i];
1163 if (degree[bbn] >= 0)
1165 max_hdr[bbn] = bbn;
1166 rescan = 1;
1168 else
1169 /* This block already was processed in find_rgns. */
1170 max_hdr[bbn] = -1;
1173 /* The idea is to topologically walk through CFG in top-down order.
1174 During the traversal, if all the predecessors of a node are
1175 marked to be in the same region (they all have the same max_hdr),
1176 then current node is also marked to be a part of that region.
1177 Otherwise the node starts its own region.
1178 CFG should be traversed until no further changes are made. On each
1179 iteration the set of the region heads is extended (the set of those
1180 blocks that have max_hdr[bbi] == bbi). This set is upper bounded by the
1181 set of all basic blocks, thus the algorithm is guaranteed to
1182 terminate. */
1184 while (rescan && iter < max_iter)
1186 rescan = 0;
1188 for (i = nblocks - 1; i >= 0; i--)
1190 edge e;
1191 edge_iterator ei;
1192 int bbn = order[i];
1194 if (max_hdr[bbn] != -1 && !TEST_BIT (header, bbn))
1196 int hdr = -1;
1198 FOR_EACH_EDGE (e, ei, BASIC_BLOCK (bbn)->preds)
1200 int predn = e->src->index;
1202 if (predn != ENTRY_BLOCK
1203 /* If pred wasn't processed in find_rgns. */
1204 && max_hdr[predn] != -1
1205 /* And pred and bb reside in the same loop.
1206 (Or out of any loop). */
1207 && loop_hdr[bbn] == loop_hdr[predn])
1209 if (hdr == -1)
1210 /* Then bb extends the containing region of pred. */
1211 hdr = max_hdr[predn];
1212 else if (hdr != max_hdr[predn])
1213 /* Too bad, there are at least two predecessors
1214 that reside in different regions. Thus, BB should
1215 begin its own region. */
1217 hdr = bbn;
1218 break;
1221 else
1222 /* BB starts its own region. */
1224 hdr = bbn;
1225 break;
1229 if (hdr == bbn)
1231 /* If BB start its own region,
1232 update set of headers with BB. */
1233 SET_BIT (header, bbn);
1234 rescan = 1;
1236 else
1237 gcc_assert (hdr != -1);
1239 max_hdr[bbn] = hdr;
1243 iter++;
1246 /* Statistics were gathered on the SPEC2000 package of tests with
1247 mainline weekly snapshot gcc-4.1-20051015 on ia64.
1249 Statistics for SPECint:
1250 1 iteration : 1751 cases (38.7%)
1251 2 iterations: 2770 cases (61.3%)
1252 Blocks wrapped in regions by find_rgns without extension: 18295 blocks
1253 Blocks wrapped in regions by 2 iterations in extend_rgns: 23821 blocks
1254 (We don't count single block regions here).
1256 Statistics for SPECfp:
1257 1 iteration : 621 cases (35.9%)
1258 2 iterations: 1110 cases (64.1%)
1259 Blocks wrapped in regions by find_rgns without extension: 6476 blocks
1260 Blocks wrapped in regions by 2 iterations in extend_rgns: 11155 blocks
1261 (We don't count single block regions here).
1263 By default we do at most 2 iterations.
1264 This can be overridden with max-sched-extend-regions-iters parameter:
1265 0 - disable region extension,
1266 N > 0 - do at most N iterations. */
1268 if (sched_verbose && iter != 0)
1269 fprintf (sched_dump, ";; Region extension iterations: %d%s\n", iter,
1270 rescan ? "... failed" : "");
1272 if (!rescan && iter != 0)
1274 int *s1 = NULL, s1_sz = 0;
1276 /* Save the old statistics for later printout. */
1277 if (sched_verbose >= 6)
1278 s1_sz = gather_region_statistics (&s1);
1280 /* We have succeeded. Now assemble the regions. */
1281 for (i = nblocks - 1; i >= 0; i--)
1283 int bbn = order[i];
1285 if (max_hdr[bbn] == bbn)
1286 /* BBN is a region head. */
1288 edge e;
1289 edge_iterator ei;
1290 int num_bbs = 0, j, num_insns = 0, large;
1292 large = too_large (bbn, &num_bbs, &num_insns);
1294 degree[bbn] = -1;
1295 rgn_bb_table[idx] = bbn;
1296 RGN_BLOCKS (nr_regions) = idx++;
1297 RGN_DONT_CALC_DEPS (nr_regions) = 0;
1298 RGN_HAS_REAL_EBB (nr_regions) = 0;
1299 CONTAINING_RGN (bbn) = nr_regions;
1300 BLOCK_TO_BB (bbn) = 0;
1302 FOR_EACH_EDGE (e, ei, BASIC_BLOCK (bbn)->succs)
1303 if (e->dest != EXIT_BLOCK_PTR)
1304 degree[e->dest->index]--;
1306 if (!large)
1307 /* Here we check whether the region is too_large. */
1308 for (j = i - 1; j >= 0; j--)
1310 int succn = order[j];
1311 if (max_hdr[succn] == bbn)
1313 if ((large = too_large (succn, &num_bbs, &num_insns)))
1314 break;
1318 if (large)
1319 /* If the region is too_large, then wrap every block of
1320 the region into single block region.
1321 Here we wrap region head only. Other blocks are
1322 processed in the below cycle. */
1324 RGN_NR_BLOCKS (nr_regions) = 1;
1325 nr_regions++;
1328 num_bbs = 1;
1330 for (j = i - 1; j >= 0; j--)
1332 int succn = order[j];
1334 if (max_hdr[succn] == bbn)
1335 /* This cycle iterates over all basic blocks, that
1336 are supposed to be in the region with head BBN,
1337 and wraps them into that region (or in single
1338 block region). */
1340 gcc_assert (degree[succn] == 0);
1342 degree[succn] = -1;
1343 rgn_bb_table[idx] = succn;
1344 BLOCK_TO_BB (succn) = large ? 0 : num_bbs++;
1345 CONTAINING_RGN (succn) = nr_regions;
1347 if (large)
1348 /* Wrap SUCCN into single block region. */
1350 RGN_BLOCKS (nr_regions) = idx;
1351 RGN_NR_BLOCKS (nr_regions) = 1;
1352 RGN_DONT_CALC_DEPS (nr_regions) = 0;
1353 RGN_HAS_REAL_EBB (nr_regions) = 0;
1354 nr_regions++;
1357 idx++;
1359 FOR_EACH_EDGE (e, ei, BASIC_BLOCK (succn)->succs)
1360 if (e->dest != EXIT_BLOCK_PTR)
1361 degree[e->dest->index]--;
1365 if (!large)
1367 RGN_NR_BLOCKS (nr_regions) = num_bbs;
1368 nr_regions++;
1373 if (sched_verbose >= 6)
1375 int *s2, s2_sz;
1377 /* Get the new statistics and print the comparison with the
1378 one before calling this function. */
1379 s2_sz = gather_region_statistics (&s2);
1380 print_region_statistics (s1, s1_sz, s2, s2_sz);
1381 free (s1);
1382 free (s2);
1386 free (order);
1387 free (max_hdr);
1389 *idxp = idx;
1392 /* Functions for regions scheduling information. */
1394 /* Compute dominators, probability, and potential-split-edges of bb.
1395 Assume that these values were already computed for bb's predecessors. */
1397 static void
1398 compute_dom_prob_ps (int bb)
1400 edge_iterator in_ei;
1401 edge in_edge;
1403 /* We shouldn't have any real ebbs yet. */
1404 gcc_assert (ebb_head [bb] == bb + current_blocks);
1406 if (IS_RGN_ENTRY (bb))
1408 SET_BIT (dom[bb], 0);
1409 prob[bb] = REG_BR_PROB_BASE;
1410 return;
1413 prob[bb] = 0;
1415 /* Initialize dom[bb] to '111..1'. */
1416 sbitmap_ones (dom[bb]);
1418 FOR_EACH_EDGE (in_edge, in_ei, BASIC_BLOCK (BB_TO_BLOCK (bb))->preds)
1420 int pred_bb;
1421 edge out_edge;
1422 edge_iterator out_ei;
1424 if (in_edge->src == ENTRY_BLOCK_PTR)
1425 continue;
1427 pred_bb = BLOCK_TO_BB (in_edge->src->index);
1428 sbitmap_a_and_b (dom[bb], dom[bb], dom[pred_bb]);
1429 sbitmap_a_or_b (ancestor_edges[bb],
1430 ancestor_edges[bb], ancestor_edges[pred_bb]);
1432 SET_BIT (ancestor_edges[bb], EDGE_TO_BIT (in_edge));
1434 sbitmap_a_or_b (pot_split[bb], pot_split[bb], pot_split[pred_bb]);
1436 FOR_EACH_EDGE (out_edge, out_ei, in_edge->src->succs)
1437 SET_BIT (pot_split[bb], EDGE_TO_BIT (out_edge));
1439 prob[bb] += ((prob[pred_bb] * in_edge->probability) / REG_BR_PROB_BASE);
1442 SET_BIT (dom[bb], bb);
1443 sbitmap_difference (pot_split[bb], pot_split[bb], ancestor_edges[bb]);
1445 if (sched_verbose >= 2)
1446 fprintf (sched_dump, ";; bb_prob(%d, %d) = %3d\n", bb, BB_TO_BLOCK (bb),
1447 (100 * prob[bb]) / REG_BR_PROB_BASE);
1450 /* Functions for target info. */
1452 /* Compute in BL the list of split-edges of bb_src relatively to bb_trg.
1453 Note that bb_trg dominates bb_src. */
1455 static void
1456 split_edges (int bb_src, int bb_trg, edgelst *bl)
1458 sbitmap src = sbitmap_alloc (SBITMAP_SIZE (pot_split[bb_src]));
1459 sbitmap_copy (src, pot_split[bb_src]);
1461 sbitmap_difference (src, src, pot_split[bb_trg]);
1462 extract_edgelst (src, bl);
1463 sbitmap_free (src);
1466 /* Find the valid candidate-source-blocks for the target block TRG, compute
1467 their probability, and check if they are speculative or not.
1468 For speculative sources, compute their update-blocks and split-blocks. */
1470 static void
1471 compute_trg_info (int trg)
1473 candidate *sp;
1474 edgelst el = { NULL, 0 };
1475 int i, j, k, update_idx;
1476 basic_block block;
1477 sbitmap visited;
1478 edge_iterator ei;
1479 edge e;
1481 candidate_table = XNEWVEC (candidate, current_nr_blocks);
1483 bblst_last = 0;
1484 /* bblst_table holds split blocks and update blocks for each block after
1485 the current one in the region. split blocks and update blocks are
1486 the TO blocks of region edges, so there can be at most rgn_nr_edges
1487 of them. */
1488 bblst_size = (current_nr_blocks - target_bb) * rgn_nr_edges;
1489 bblst_table = XNEWVEC (basic_block, bblst_size);
1491 edgelst_last = 0;
1492 edgelst_table = XNEWVEC (edge, rgn_nr_edges);
1494 /* Define some of the fields for the target bb as well. */
1495 sp = candidate_table + trg;
1496 sp->is_valid = 1;
1497 sp->is_speculative = 0;
1498 sp->src_prob = REG_BR_PROB_BASE;
1500 visited = sbitmap_alloc (last_basic_block);
1502 for (i = trg + 1; i < current_nr_blocks; i++)
1504 sp = candidate_table + i;
1506 sp->is_valid = IS_DOMINATED (i, trg);
1507 if (sp->is_valid)
1509 int tf = prob[trg], cf = prob[i];
1511 /* In CFGs with low probability edges TF can possibly be zero. */
1512 sp->src_prob = (tf ? ((cf * REG_BR_PROB_BASE) / tf) : 0);
1513 sp->is_valid = (sp->src_prob >= min_spec_prob);
1516 if (sp->is_valid)
1518 split_edges (i, trg, &el);
1519 sp->is_speculative = (el.nr_members) ? 1 : 0;
1520 if (sp->is_speculative && !flag_schedule_speculative)
1521 sp->is_valid = 0;
1524 if (sp->is_valid)
1526 /* Compute split blocks and store them in bblst_table.
1527 The TO block of every split edge is a split block. */
1528 sp->split_bbs.first_member = &bblst_table[bblst_last];
1529 sp->split_bbs.nr_members = el.nr_members;
1530 for (j = 0; j < el.nr_members; bblst_last++, j++)
1531 bblst_table[bblst_last] = el.first_member[j]->dest;
1532 sp->update_bbs.first_member = &bblst_table[bblst_last];
1534 /* Compute update blocks and store them in bblst_table.
1535 For every split edge, look at the FROM block, and check
1536 all out edges. For each out edge that is not a split edge,
1537 add the TO block to the update block list. This list can end
1538 up with a lot of duplicates. We need to weed them out to avoid
1539 overrunning the end of the bblst_table. */
1541 update_idx = 0;
1542 sbitmap_zero (visited);
1543 for (j = 0; j < el.nr_members; j++)
1545 block = el.first_member[j]->src;
1546 FOR_EACH_EDGE (e, ei, block->succs)
1548 if (!TEST_BIT (visited, e->dest->index))
1550 for (k = 0; k < el.nr_members; k++)
1551 if (e == el.first_member[k])
1552 break;
1554 if (k >= el.nr_members)
1556 bblst_table[bblst_last++] = e->dest;
1557 SET_BIT (visited, e->dest->index);
1558 update_idx++;
1563 sp->update_bbs.nr_members = update_idx;
1565 /* Make sure we didn't overrun the end of bblst_table. */
1566 gcc_assert (bblst_last <= bblst_size);
1568 else
1570 sp->split_bbs.nr_members = sp->update_bbs.nr_members = 0;
1572 sp->is_speculative = 0;
1573 sp->src_prob = 0;
1577 sbitmap_free (visited);
1580 /* Free the computed target info. */
1581 static void
1582 free_trg_info (void)
1584 free (candidate_table);
1585 free (bblst_table);
1586 free (edgelst_table);
1589 /* Print candidates info, for debugging purposes. Callable from debugger. */
1591 DEBUG_FUNCTION void
1592 debug_candidate (int i)
1594 if (!candidate_table[i].is_valid)
1595 return;
1597 if (candidate_table[i].is_speculative)
1599 int j;
1600 fprintf (sched_dump, "src b %d bb %d speculative \n", BB_TO_BLOCK (i), i);
1602 fprintf (sched_dump, "split path: ");
1603 for (j = 0; j < candidate_table[i].split_bbs.nr_members; j++)
1605 int b = candidate_table[i].split_bbs.first_member[j]->index;
1607 fprintf (sched_dump, " %d ", b);
1609 fprintf (sched_dump, "\n");
1611 fprintf (sched_dump, "update path: ");
1612 for (j = 0; j < candidate_table[i].update_bbs.nr_members; j++)
1614 int b = candidate_table[i].update_bbs.first_member[j]->index;
1616 fprintf (sched_dump, " %d ", b);
1618 fprintf (sched_dump, "\n");
1620 else
1622 fprintf (sched_dump, " src %d equivalent\n", BB_TO_BLOCK (i));
1626 /* Print candidates info, for debugging purposes. Callable from debugger. */
1628 DEBUG_FUNCTION void
1629 debug_candidates (int trg)
1631 int i;
1633 fprintf (sched_dump, "----------- candidate table: target: b=%d bb=%d ---\n",
1634 BB_TO_BLOCK (trg), trg);
1635 for (i = trg + 1; i < current_nr_blocks; i++)
1636 debug_candidate (i);
1639 /* Functions for speculative scheduling. */
1641 static bitmap_head not_in_df;
1643 /* Return 0 if x is a set of a register alive in the beginning of one
1644 of the split-blocks of src, otherwise return 1. */
1646 static int
1647 check_live_1 (int src, rtx x)
1649 int i;
1650 int regno;
1651 rtx reg = SET_DEST (x);
1653 if (reg == 0)
1654 return 1;
1656 while (GET_CODE (reg) == SUBREG
1657 || GET_CODE (reg) == ZERO_EXTRACT
1658 || GET_CODE (reg) == STRICT_LOW_PART)
1659 reg = XEXP (reg, 0);
1661 if (GET_CODE (reg) == PARALLEL)
1663 int i;
1665 for (i = XVECLEN (reg, 0) - 1; i >= 0; i--)
1666 if (XEXP (XVECEXP (reg, 0, i), 0) != 0)
1667 if (check_live_1 (src, XEXP (XVECEXP (reg, 0, i), 0)))
1668 return 1;
1670 return 0;
1673 if (!REG_P (reg))
1674 return 1;
1676 regno = REGNO (reg);
1678 if (regno < FIRST_PSEUDO_REGISTER && global_regs[regno])
1680 /* Global registers are assumed live. */
1681 return 0;
1683 else
1685 if (regno < FIRST_PSEUDO_REGISTER)
1687 /* Check for hard registers. */
1688 int j = hard_regno_nregs[regno][GET_MODE (reg)];
1689 while (--j >= 0)
1691 for (i = 0; i < candidate_table[src].split_bbs.nr_members; i++)
1693 basic_block b = candidate_table[src].split_bbs.first_member[i];
1694 int t = bitmap_bit_p (&not_in_df, b->index);
1696 /* We can have split blocks, that were recently generated.
1697 Such blocks are always outside current region. */
1698 gcc_assert (!t || (CONTAINING_RGN (b->index)
1699 != CONTAINING_RGN (BB_TO_BLOCK (src))));
1701 if (t || REGNO_REG_SET_P (df_get_live_in (b), regno + j))
1702 return 0;
1706 else
1708 /* Check for pseudo registers. */
1709 for (i = 0; i < candidate_table[src].split_bbs.nr_members; i++)
1711 basic_block b = candidate_table[src].split_bbs.first_member[i];
1712 int t = bitmap_bit_p (&not_in_df, b->index);
1714 gcc_assert (!t || (CONTAINING_RGN (b->index)
1715 != CONTAINING_RGN (BB_TO_BLOCK (src))));
1717 if (t || REGNO_REG_SET_P (df_get_live_in (b), regno))
1718 return 0;
1723 return 1;
1726 /* If x is a set of a register R, mark that R is alive in the beginning
1727 of every update-block of src. */
1729 static void
1730 update_live_1 (int src, rtx x)
1732 int i;
1733 int regno;
1734 rtx reg = SET_DEST (x);
1736 if (reg == 0)
1737 return;
1739 while (GET_CODE (reg) == SUBREG
1740 || GET_CODE (reg) == ZERO_EXTRACT
1741 || GET_CODE (reg) == STRICT_LOW_PART)
1742 reg = XEXP (reg, 0);
1744 if (GET_CODE (reg) == PARALLEL)
1746 int i;
1748 for (i = XVECLEN (reg, 0) - 1; i >= 0; i--)
1749 if (XEXP (XVECEXP (reg, 0, i), 0) != 0)
1750 update_live_1 (src, XEXP (XVECEXP (reg, 0, i), 0));
1752 return;
1755 if (!REG_P (reg))
1756 return;
1758 /* Global registers are always live, so the code below does not apply
1759 to them. */
1761 regno = REGNO (reg);
1763 if (! HARD_REGISTER_NUM_P (regno)
1764 || !global_regs[regno])
1766 for (i = 0; i < candidate_table[src].update_bbs.nr_members; i++)
1768 basic_block b = candidate_table[src].update_bbs.first_member[i];
1770 if (HARD_REGISTER_NUM_P (regno))
1771 bitmap_set_range (df_get_live_in (b), regno,
1772 hard_regno_nregs[regno][GET_MODE (reg)]);
1773 else
1774 bitmap_set_bit (df_get_live_in (b), regno);
1779 /* Return 1 if insn can be speculatively moved from block src to trg,
1780 otherwise return 0. Called before first insertion of insn to
1781 ready-list or before the scheduling. */
1783 static int
1784 check_live (rtx insn, int src)
1786 /* Find the registers set by instruction. */
1787 if (GET_CODE (PATTERN (insn)) == SET
1788 || GET_CODE (PATTERN (insn)) == CLOBBER)
1789 return check_live_1 (src, PATTERN (insn));
1790 else if (GET_CODE (PATTERN (insn)) == PARALLEL)
1792 int j;
1793 for (j = XVECLEN (PATTERN (insn), 0) - 1; j >= 0; j--)
1794 if ((GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == SET
1795 || GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == CLOBBER)
1796 && !check_live_1 (src, XVECEXP (PATTERN (insn), 0, j)))
1797 return 0;
1799 return 1;
1802 return 1;
1805 /* Update the live registers info after insn was moved speculatively from
1806 block src to trg. */
1808 static void
1809 update_live (rtx insn, int src)
1811 /* Find the registers set by instruction. */
1812 if (GET_CODE (PATTERN (insn)) == SET
1813 || GET_CODE (PATTERN (insn)) == CLOBBER)
1814 update_live_1 (src, PATTERN (insn));
1815 else if (GET_CODE (PATTERN (insn)) == PARALLEL)
1817 int j;
1818 for (j = XVECLEN (PATTERN (insn), 0) - 1; j >= 0; j--)
1819 if (GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == SET
1820 || GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == CLOBBER)
1821 update_live_1 (src, XVECEXP (PATTERN (insn), 0, j));
1825 /* Nonzero if block bb_to is equal to, or reachable from block bb_from. */
1826 #define IS_REACHABLE(bb_from, bb_to) \
1827 (bb_from == bb_to \
1828 || IS_RGN_ENTRY (bb_from) \
1829 || (TEST_BIT (ancestor_edges[bb_to], \
1830 EDGE_TO_BIT (single_pred_edge (BASIC_BLOCK (BB_TO_BLOCK (bb_from)))))))
1832 /* Turns on the fed_by_spec_load flag for insns fed by load_insn. */
1834 static void
1835 set_spec_fed (rtx load_insn)
1837 sd_iterator_def sd_it;
1838 dep_t dep;
1840 FOR_EACH_DEP (load_insn, SD_LIST_FORW, sd_it, dep)
1841 if (DEP_TYPE (dep) == REG_DEP_TRUE)
1842 FED_BY_SPEC_LOAD (DEP_CON (dep)) = 1;
1845 /* On the path from the insn to load_insn_bb, find a conditional
1846 branch depending on insn, that guards the speculative load. */
1848 static int
1849 find_conditional_protection (rtx insn, int load_insn_bb)
1851 sd_iterator_def sd_it;
1852 dep_t dep;
1854 /* Iterate through DEF-USE forward dependences. */
1855 FOR_EACH_DEP (insn, SD_LIST_FORW, sd_it, dep)
1857 rtx next = DEP_CON (dep);
1859 if ((CONTAINING_RGN (BLOCK_NUM (next)) ==
1860 CONTAINING_RGN (BB_TO_BLOCK (load_insn_bb)))
1861 && IS_REACHABLE (INSN_BB (next), load_insn_bb)
1862 && load_insn_bb != INSN_BB (next)
1863 && DEP_TYPE (dep) == REG_DEP_TRUE
1864 && (JUMP_P (next)
1865 || find_conditional_protection (next, load_insn_bb)))
1866 return 1;
1868 return 0;
1869 } /* find_conditional_protection */
1871 /* Returns 1 if the same insn1 that participates in the computation
1872 of load_insn's address is feeding a conditional branch that is
1873 guarding on load_insn. This is true if we find two DEF-USE
1874 chains:
1875 insn1 -> ... -> conditional-branch
1876 insn1 -> ... -> load_insn,
1877 and if a flow path exists:
1878 insn1 -> ... -> conditional-branch -> ... -> load_insn,
1879 and if insn1 is on the path
1880 region-entry -> ... -> bb_trg -> ... load_insn.
1882 Locate insn1 by climbing on INSN_BACK_DEPS from load_insn.
1883 Locate the branch by following INSN_FORW_DEPS from insn1. */
1885 static int
1886 is_conditionally_protected (rtx load_insn, int bb_src, int bb_trg)
1888 sd_iterator_def sd_it;
1889 dep_t dep;
1891 FOR_EACH_DEP (load_insn, SD_LIST_BACK, sd_it, dep)
1893 rtx insn1 = DEP_PRO (dep);
1895 /* Must be a DEF-USE dependence upon non-branch. */
1896 if (DEP_TYPE (dep) != REG_DEP_TRUE
1897 || JUMP_P (insn1))
1898 continue;
1900 /* Must exist a path: region-entry -> ... -> bb_trg -> ... load_insn. */
1901 if (INSN_BB (insn1) == bb_src
1902 || (CONTAINING_RGN (BLOCK_NUM (insn1))
1903 != CONTAINING_RGN (BB_TO_BLOCK (bb_src)))
1904 || (!IS_REACHABLE (bb_trg, INSN_BB (insn1))
1905 && !IS_REACHABLE (INSN_BB (insn1), bb_trg)))
1906 continue;
1908 /* Now search for the conditional-branch. */
1909 if (find_conditional_protection (insn1, bb_src))
1910 return 1;
1912 /* Recursive step: search another insn1, "above" current insn1. */
1913 return is_conditionally_protected (insn1, bb_src, bb_trg);
1916 /* The chain does not exist. */
1917 return 0;
1918 } /* is_conditionally_protected */
1920 /* Returns 1 if a clue for "similar load" 'insn2' is found, and hence
1921 load_insn can move speculatively from bb_src to bb_trg. All the
1922 following must hold:
1924 (1) both loads have 1 base register (PFREE_CANDIDATEs).
1925 (2) load_insn and load1 have a def-use dependence upon
1926 the same insn 'insn1'.
1927 (3) either load2 is in bb_trg, or:
1928 - there's only one split-block, and
1929 - load1 is on the escape path, and
1931 From all these we can conclude that the two loads access memory
1932 addresses that differ at most by a constant, and hence if moving
1933 load_insn would cause an exception, it would have been caused by
1934 load2 anyhow. */
1936 static int
1937 is_pfree (rtx load_insn, int bb_src, int bb_trg)
1939 sd_iterator_def back_sd_it;
1940 dep_t back_dep;
1941 candidate *candp = candidate_table + bb_src;
1943 if (candp->split_bbs.nr_members != 1)
1944 /* Must have exactly one escape block. */
1945 return 0;
1947 FOR_EACH_DEP (load_insn, SD_LIST_BACK, back_sd_it, back_dep)
1949 rtx insn1 = DEP_PRO (back_dep);
1951 if (DEP_TYPE (back_dep) == REG_DEP_TRUE)
1952 /* Found a DEF-USE dependence (insn1, load_insn). */
1954 sd_iterator_def fore_sd_it;
1955 dep_t fore_dep;
1957 FOR_EACH_DEP (insn1, SD_LIST_FORW, fore_sd_it, fore_dep)
1959 rtx insn2 = DEP_CON (fore_dep);
1961 if (DEP_TYPE (fore_dep) == REG_DEP_TRUE)
1963 /* Found a DEF-USE dependence (insn1, insn2). */
1964 if (haifa_classify_insn (insn2) != PFREE_CANDIDATE)
1965 /* insn2 not guaranteed to be a 1 base reg load. */
1966 continue;
1968 if (INSN_BB (insn2) == bb_trg)
1969 /* insn2 is the similar load, in the target block. */
1970 return 1;
1972 if (*(candp->split_bbs.first_member) == BLOCK_FOR_INSN (insn2))
1973 /* insn2 is a similar load, in a split-block. */
1974 return 1;
1980 /* Couldn't find a similar load. */
1981 return 0;
1982 } /* is_pfree */
1984 /* Return 1 if load_insn is prisky (i.e. if load_insn is fed by
1985 a load moved speculatively, or if load_insn is protected by
1986 a compare on load_insn's address). */
1988 static int
1989 is_prisky (rtx load_insn, int bb_src, int bb_trg)
1991 if (FED_BY_SPEC_LOAD (load_insn))
1992 return 1;
1994 if (sd_lists_empty_p (load_insn, SD_LIST_BACK))
1995 /* Dependence may 'hide' out of the region. */
1996 return 1;
1998 if (is_conditionally_protected (load_insn, bb_src, bb_trg))
1999 return 1;
2001 return 0;
2004 /* Insn is a candidate to be moved speculatively from bb_src to bb_trg.
2005 Return 1 if insn is exception-free (and the motion is valid)
2006 and 0 otherwise. */
2008 static int
2009 is_exception_free (rtx insn, int bb_src, int bb_trg)
2011 int insn_class = haifa_classify_insn (insn);
2013 /* Handle non-load insns. */
2014 switch (insn_class)
2016 case TRAP_FREE:
2017 return 1;
2018 case TRAP_RISKY:
2019 return 0;
2020 default:;
2023 /* Handle loads. */
2024 if (!flag_schedule_speculative_load)
2025 return 0;
2026 IS_LOAD_INSN (insn) = 1;
2027 switch (insn_class)
2029 case IFREE:
2030 return (1);
2031 case IRISKY:
2032 return 0;
2033 case PFREE_CANDIDATE:
2034 if (is_pfree (insn, bb_src, bb_trg))
2035 return 1;
2036 /* Don't 'break' here: PFREE-candidate is also PRISKY-candidate. */
2037 case PRISKY_CANDIDATE:
2038 if (!flag_schedule_speculative_load_dangerous
2039 || is_prisky (insn, bb_src, bb_trg))
2040 return 0;
2041 break;
2042 default:;
2045 return flag_schedule_speculative_load_dangerous;
2048 /* The number of insns from the current block scheduled so far. */
2049 static int sched_target_n_insns;
2050 /* The number of insns from the current block to be scheduled in total. */
2051 static int target_n_insns;
2052 /* The number of insns from the entire region scheduled so far. */
2053 static int sched_n_insns;
2055 /* Implementations of the sched_info functions for region scheduling. */
2056 static void init_ready_list (void);
2057 static int can_schedule_ready_p (rtx);
2058 static void begin_schedule_ready (rtx);
2059 static ds_t new_ready (rtx, ds_t);
2060 static int schedule_more_p (void);
2061 static const char *rgn_print_insn (const_rtx, int);
2062 static int rgn_rank (rtx, rtx);
2063 static void compute_jump_reg_dependencies (rtx, regset);
2065 /* Functions for speculative scheduling. */
2066 static void rgn_add_remove_insn (rtx, int);
2067 static void rgn_add_block (basic_block, basic_block);
2068 static void rgn_fix_recovery_cfg (int, int, int);
2069 static basic_block advance_target_bb (basic_block, rtx);
2071 /* Return nonzero if there are more insns that should be scheduled. */
2073 static int
2074 schedule_more_p (void)
2076 return sched_target_n_insns < target_n_insns;
2079 /* Add all insns that are initially ready to the ready list READY. Called
2080 once before scheduling a set of insns. */
2082 static void
2083 init_ready_list (void)
2085 rtx prev_head = current_sched_info->prev_head;
2086 rtx next_tail = current_sched_info->next_tail;
2087 int bb_src;
2088 rtx insn;
2090 target_n_insns = 0;
2091 sched_target_n_insns = 0;
2092 sched_n_insns = 0;
2094 /* Print debugging information. */
2095 if (sched_verbose >= 5)
2096 debug_rgn_dependencies (target_bb);
2098 /* Prepare current target block info. */
2099 if (current_nr_blocks > 1)
2100 compute_trg_info (target_bb);
2102 /* Initialize ready list with all 'ready' insns in target block.
2103 Count number of insns in the target block being scheduled. */
2104 for (insn = NEXT_INSN (prev_head); insn != next_tail; insn = NEXT_INSN (insn))
2106 gcc_assert (TODO_SPEC (insn) == HARD_DEP || TODO_SPEC (insn) == DEP_POSTPONED);
2107 TODO_SPEC (insn) = HARD_DEP;
2108 try_ready (insn);
2109 target_n_insns++;
2111 gcc_assert (!(TODO_SPEC (insn) & BEGIN_CONTROL));
2114 /* Add to ready list all 'ready' insns in valid source blocks.
2115 For speculative insns, check-live, exception-free, and
2116 issue-delay. */
2117 for (bb_src = target_bb + 1; bb_src < current_nr_blocks; bb_src++)
2118 if (IS_VALID (bb_src))
2120 rtx src_head;
2121 rtx src_next_tail;
2122 rtx tail, head;
2124 get_ebb_head_tail (EBB_FIRST_BB (bb_src), EBB_LAST_BB (bb_src),
2125 &head, &tail);
2126 src_next_tail = NEXT_INSN (tail);
2127 src_head = head;
2129 for (insn = src_head; insn != src_next_tail; insn = NEXT_INSN (insn))
2130 if (INSN_P (insn))
2132 gcc_assert (TODO_SPEC (insn) == HARD_DEP || TODO_SPEC (insn) == DEP_POSTPONED);
2133 TODO_SPEC (insn) = HARD_DEP;
2134 try_ready (insn);
2139 /* Called after taking INSN from the ready list. Returns nonzero if this
2140 insn can be scheduled, nonzero if we should silently discard it. */
2142 static int
2143 can_schedule_ready_p (rtx insn)
2145 /* An interblock motion? */
2146 if (INSN_BB (insn) != target_bb
2147 && IS_SPECULATIVE_INSN (insn)
2148 && !check_live (insn, INSN_BB (insn)))
2149 return 0;
2150 else
2151 return 1;
2154 /* Updates counter and other information. Split from can_schedule_ready_p ()
2155 because when we schedule insn speculatively then insn passed to
2156 can_schedule_ready_p () differs from the one passed to
2157 begin_schedule_ready (). */
2158 static void
2159 begin_schedule_ready (rtx insn)
2161 /* An interblock motion? */
2162 if (INSN_BB (insn) != target_bb)
2164 if (IS_SPECULATIVE_INSN (insn))
2166 gcc_assert (check_live (insn, INSN_BB (insn)));
2168 update_live (insn, INSN_BB (insn));
2170 /* For speculative load, mark insns fed by it. */
2171 if (IS_LOAD_INSN (insn) || FED_BY_SPEC_LOAD (insn))
2172 set_spec_fed (insn);
2174 nr_spec++;
2176 nr_inter++;
2178 else
2180 /* In block motion. */
2181 sched_target_n_insns++;
2183 sched_n_insns++;
2186 /* Called after INSN has all its hard dependencies resolved and the speculation
2187 of type TS is enough to overcome them all.
2188 Return nonzero if it should be moved to the ready list or the queue, or zero
2189 if we should silently discard it. */
2190 static ds_t
2191 new_ready (rtx next, ds_t ts)
2193 if (INSN_BB (next) != target_bb)
2195 int not_ex_free = 0;
2197 /* For speculative insns, before inserting to ready/queue,
2198 check live, exception-free, and issue-delay. */
2199 if (!IS_VALID (INSN_BB (next))
2200 || CANT_MOVE (next)
2201 || (IS_SPECULATIVE_INSN (next)
2202 && ((recog_memoized (next) >= 0
2203 && min_insn_conflict_delay (curr_state, next, next)
2204 > PARAM_VALUE (PARAM_MAX_SCHED_INSN_CONFLICT_DELAY))
2205 || IS_SPECULATION_CHECK_P (next)
2206 || !check_live (next, INSN_BB (next))
2207 || (not_ex_free = !is_exception_free (next, INSN_BB (next),
2208 target_bb)))))
2210 if (not_ex_free
2211 /* We are here because is_exception_free () == false.
2212 But we possibly can handle that with control speculation. */
2213 && sched_deps_info->generate_spec_deps
2214 && spec_info->mask & BEGIN_CONTROL)
2216 ds_t new_ds;
2218 /* Add control speculation to NEXT's dependency type. */
2219 new_ds = set_dep_weak (ts, BEGIN_CONTROL, MAX_DEP_WEAK);
2221 /* Check if NEXT can be speculated with new dependency type. */
2222 if (sched_insn_is_legitimate_for_speculation_p (next, new_ds))
2223 /* Here we got new control-speculative instruction. */
2224 ts = new_ds;
2225 else
2226 /* NEXT isn't ready yet. */
2227 ts = DEP_POSTPONED;
2229 else
2230 /* NEXT isn't ready yet. */
2231 ts = DEP_POSTPONED;
2235 return ts;
2238 /* Return a string that contains the insn uid and optionally anything else
2239 necessary to identify this insn in an output. It's valid to use a
2240 static buffer for this. The ALIGNED parameter should cause the string
2241 to be formatted so that multiple output lines will line up nicely. */
2243 static const char *
2244 rgn_print_insn (const_rtx insn, int aligned)
2246 static char tmp[80];
2248 if (aligned)
2249 sprintf (tmp, "b%3d: i%4d", INSN_BB (insn), INSN_UID (insn));
2250 else
2252 if (current_nr_blocks > 1 && INSN_BB (insn) != target_bb)
2253 sprintf (tmp, "%d/b%d", INSN_UID (insn), INSN_BB (insn));
2254 else
2255 sprintf (tmp, "%d", INSN_UID (insn));
2257 return tmp;
2260 /* Compare priority of two insns. Return a positive number if the second
2261 insn is to be preferred for scheduling, and a negative one if the first
2262 is to be preferred. Zero if they are equally good. */
2264 static int
2265 rgn_rank (rtx insn1, rtx insn2)
2267 /* Some comparison make sense in interblock scheduling only. */
2268 if (INSN_BB (insn1) != INSN_BB (insn2))
2270 int spec_val, prob_val;
2272 /* Prefer an inblock motion on an interblock motion. */
2273 if ((INSN_BB (insn2) == target_bb) && (INSN_BB (insn1) != target_bb))
2274 return 1;
2275 if ((INSN_BB (insn1) == target_bb) && (INSN_BB (insn2) != target_bb))
2276 return -1;
2278 /* Prefer a useful motion on a speculative one. */
2279 spec_val = IS_SPECULATIVE_INSN (insn1) - IS_SPECULATIVE_INSN (insn2);
2280 if (spec_val)
2281 return spec_val;
2283 /* Prefer a more probable (speculative) insn. */
2284 prob_val = INSN_PROBABILITY (insn2) - INSN_PROBABILITY (insn1);
2285 if (prob_val)
2286 return prob_val;
2288 return 0;
2291 /* NEXT is an instruction that depends on INSN (a backward dependence);
2292 return nonzero if we should include this dependence in priority
2293 calculations. */
2296 contributes_to_priority (rtx next, rtx insn)
2298 /* NEXT and INSN reside in one ebb. */
2299 return BLOCK_TO_BB (BLOCK_NUM (next)) == BLOCK_TO_BB (BLOCK_NUM (insn));
2302 /* INSN is a JUMP_INSN. Store the set of registers that must be
2303 considered as used by this jump in USED. */
2305 static void
2306 compute_jump_reg_dependencies (rtx insn ATTRIBUTE_UNUSED,
2307 regset used ATTRIBUTE_UNUSED)
2309 /* Nothing to do here, since we postprocess jumps in
2310 add_branch_dependences. */
2313 /* This variable holds common_sched_info hooks and data relevant to
2314 the interblock scheduler. */
2315 static struct common_sched_info_def rgn_common_sched_info;
2318 /* This holds data for the dependence analysis relevant to
2319 the interblock scheduler. */
2320 static struct sched_deps_info_def rgn_sched_deps_info;
2322 /* This holds constant data used for initializing the above structure
2323 for the Haifa scheduler. */
2324 static const struct sched_deps_info_def rgn_const_sched_deps_info =
2326 compute_jump_reg_dependencies,
2327 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2328 0, 0, 0
2331 /* Same as above, but for the selective scheduler. */
2332 static const struct sched_deps_info_def rgn_const_sel_sched_deps_info =
2334 compute_jump_reg_dependencies,
2335 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2336 0, 0, 0
2339 /* Return true if scheduling INSN will trigger finish of scheduling
2340 current block. */
2341 static bool
2342 rgn_insn_finishes_block_p (rtx insn)
2344 if (INSN_BB (insn) == target_bb
2345 && sched_target_n_insns + 1 == target_n_insns)
2346 /* INSN is the last not-scheduled instruction in the current block. */
2347 return true;
2349 return false;
2352 /* Used in schedule_insns to initialize current_sched_info for scheduling
2353 regions (or single basic blocks). */
2355 static const struct haifa_sched_info rgn_const_sched_info =
2357 init_ready_list,
2358 can_schedule_ready_p,
2359 schedule_more_p,
2360 new_ready,
2361 rgn_rank,
2362 rgn_print_insn,
2363 contributes_to_priority,
2364 rgn_insn_finishes_block_p,
2366 NULL, NULL,
2367 NULL, NULL,
2368 0, 0,
2370 rgn_add_remove_insn,
2371 begin_schedule_ready,
2372 NULL,
2373 advance_target_bb,
2374 NULL, NULL,
2375 SCHED_RGN
2378 /* This variable holds the data and hooks needed to the Haifa scheduler backend
2379 for the interblock scheduler frontend. */
2380 static struct haifa_sched_info rgn_sched_info;
2382 /* Returns maximum priority that an insn was assigned to. */
2385 get_rgn_sched_max_insns_priority (void)
2387 return rgn_sched_info.sched_max_insns_priority;
2390 /* Determine if PAT sets a TARGET_CLASS_LIKELY_SPILLED_P register. */
2392 static bool
2393 sets_likely_spilled (rtx pat)
2395 bool ret = false;
2396 note_stores (pat, sets_likely_spilled_1, &ret);
2397 return ret;
2400 static void
2401 sets_likely_spilled_1 (rtx x, const_rtx pat, void *data)
2403 bool *ret = (bool *) data;
2405 if (GET_CODE (pat) == SET
2406 && REG_P (x)
2407 && HARD_REGISTER_P (x)
2408 && targetm.class_likely_spilled_p (REGNO_REG_CLASS (REGNO (x))))
2409 *ret = true;
2412 /* A bitmap to note insns that participate in any dependency. Used in
2413 add_branch_dependences. */
2414 static sbitmap insn_referenced;
2416 /* Add dependences so that branches are scheduled to run last in their
2417 block. */
2418 static void
2419 add_branch_dependences (rtx head, rtx tail)
2421 rtx insn, last;
2423 /* For all branches, calls, uses, clobbers, cc0 setters, and instructions
2424 that can throw exceptions, force them to remain in order at the end of
2425 the block by adding dependencies and giving the last a high priority.
2426 There may be notes present, and prev_head may also be a note.
2428 Branches must obviously remain at the end. Calls should remain at the
2429 end since moving them results in worse register allocation. Uses remain
2430 at the end to ensure proper register allocation.
2432 cc0 setters remain at the end because they can't be moved away from
2433 their cc0 user.
2435 COND_EXEC insns cannot be moved past a branch (see e.g. PR17808).
2437 Insns setting TARGET_CLASS_LIKELY_SPILLED_P registers (usually return
2438 values) are not moved before reload because we can wind up with register
2439 allocation failures. */
2441 while (tail != head && DEBUG_INSN_P (tail))
2442 tail = PREV_INSN (tail);
2444 insn = tail;
2445 last = 0;
2446 while (CALL_P (insn)
2447 || JUMP_P (insn)
2448 || (NONJUMP_INSN_P (insn)
2449 && (GET_CODE (PATTERN (insn)) == USE
2450 || GET_CODE (PATTERN (insn)) == CLOBBER
2451 || can_throw_internal (insn)
2452 #ifdef HAVE_cc0
2453 || sets_cc0_p (PATTERN (insn))
2454 #endif
2455 || (!reload_completed
2456 && sets_likely_spilled (PATTERN (insn)))))
2457 || NOTE_P (insn))
2459 if (!NOTE_P (insn))
2461 if (last != 0
2462 && sd_find_dep_between (insn, last, false) == NULL)
2464 if (! sched_insns_conditions_mutex_p (last, insn))
2465 add_dependence (last, insn, REG_DEP_ANTI);
2466 SET_BIT (insn_referenced, INSN_LUID (insn));
2469 CANT_MOVE (insn) = 1;
2471 last = insn;
2474 /* Don't overrun the bounds of the basic block. */
2475 if (insn == head)
2476 break;
2479 insn = PREV_INSN (insn);
2480 while (insn != head && DEBUG_INSN_P (insn));
2483 /* Make sure these insns are scheduled last in their block. */
2484 insn = last;
2485 if (insn != 0)
2486 while (insn != head)
2488 insn = prev_nonnote_insn (insn);
2490 if (TEST_BIT (insn_referenced, INSN_LUID (insn))
2491 || DEBUG_INSN_P (insn))
2492 continue;
2494 if (! sched_insns_conditions_mutex_p (last, insn))
2495 add_dependence (last, insn, REG_DEP_ANTI);
2498 if (!targetm.have_conditional_execution ())
2499 return;
2501 /* Finally, if the block ends in a jump, and we are doing intra-block
2502 scheduling, make sure that the branch depends on any COND_EXEC insns
2503 inside the block to avoid moving the COND_EXECs past the branch insn.
2505 We only have to do this after reload, because (1) before reload there
2506 are no COND_EXEC insns, and (2) the region scheduler is an intra-block
2507 scheduler after reload.
2509 FIXME: We could in some cases move COND_EXEC insns past the branch if
2510 this scheduler would be a little smarter. Consider this code:
2512 T = [addr]
2513 C ? addr += 4
2514 !C ? X += 12
2515 C ? T += 1
2516 C ? jump foo
2518 On a target with a one cycle stall on a memory access the optimal
2519 sequence would be:
2521 T = [addr]
2522 C ? addr += 4
2523 C ? T += 1
2524 C ? jump foo
2525 !C ? X += 12
2527 We don't want to put the 'X += 12' before the branch because it just
2528 wastes a cycle of execution time when the branch is taken.
2530 Note that in the example "!C" will always be true. That is another
2531 possible improvement for handling COND_EXECs in this scheduler: it
2532 could remove always-true predicates. */
2534 if (!reload_completed || ! JUMP_P (tail))
2535 return;
2537 insn = tail;
2538 while (insn != head)
2540 insn = PREV_INSN (insn);
2542 /* Note that we want to add this dependency even when
2543 sched_insns_conditions_mutex_p returns true. The whole point
2544 is that we _want_ this dependency, even if these insns really
2545 are independent. */
2546 if (INSN_P (insn) && GET_CODE (PATTERN (insn)) == COND_EXEC)
2547 add_dependence (tail, insn, REG_DEP_ANTI);
2551 /* Data structures for the computation of data dependences in a regions. We
2552 keep one `deps' structure for every basic block. Before analyzing the
2553 data dependences for a bb, its variables are initialized as a function of
2554 the variables of its predecessors. When the analysis for a bb completes,
2555 we save the contents to the corresponding bb_deps[bb] variable. */
2557 static struct deps_desc *bb_deps;
2559 static void
2560 concat_insn_mem_list (rtx copy_insns, rtx copy_mems, rtx *old_insns_p,
2561 rtx *old_mems_p)
2563 rtx new_insns = *old_insns_p;
2564 rtx new_mems = *old_mems_p;
2566 while (copy_insns)
2568 new_insns = alloc_INSN_LIST (XEXP (copy_insns, 0), new_insns);
2569 new_mems = alloc_EXPR_LIST (VOIDmode, XEXP (copy_mems, 0), new_mems);
2570 copy_insns = XEXP (copy_insns, 1);
2571 copy_mems = XEXP (copy_mems, 1);
2574 *old_insns_p = new_insns;
2575 *old_mems_p = new_mems;
2578 /* Join PRED_DEPS to the SUCC_DEPS. */
2579 void
2580 deps_join (struct deps_desc *succ_deps, struct deps_desc *pred_deps)
2582 unsigned reg;
2583 reg_set_iterator rsi;
2585 /* The reg_last lists are inherited by successor. */
2586 EXECUTE_IF_SET_IN_REG_SET (&pred_deps->reg_last_in_use, 0, reg, rsi)
2588 struct deps_reg *pred_rl = &pred_deps->reg_last[reg];
2589 struct deps_reg *succ_rl = &succ_deps->reg_last[reg];
2591 succ_rl->uses = concat_INSN_LIST (pred_rl->uses, succ_rl->uses);
2592 succ_rl->sets = concat_INSN_LIST (pred_rl->sets, succ_rl->sets);
2593 succ_rl->implicit_sets
2594 = concat_INSN_LIST (pred_rl->implicit_sets, succ_rl->implicit_sets);
2595 succ_rl->clobbers = concat_INSN_LIST (pred_rl->clobbers,
2596 succ_rl->clobbers);
2597 succ_rl->uses_length += pred_rl->uses_length;
2598 succ_rl->clobbers_length += pred_rl->clobbers_length;
2600 IOR_REG_SET (&succ_deps->reg_last_in_use, &pred_deps->reg_last_in_use);
2602 /* Mem read/write lists are inherited by successor. */
2603 concat_insn_mem_list (pred_deps->pending_read_insns,
2604 pred_deps->pending_read_mems,
2605 &succ_deps->pending_read_insns,
2606 &succ_deps->pending_read_mems);
2607 concat_insn_mem_list (pred_deps->pending_write_insns,
2608 pred_deps->pending_write_mems,
2609 &succ_deps->pending_write_insns,
2610 &succ_deps->pending_write_mems);
2612 succ_deps->pending_jump_insns
2613 = concat_INSN_LIST (pred_deps->pending_jump_insns,
2614 succ_deps->pending_jump_insns);
2615 succ_deps->last_pending_memory_flush
2616 = concat_INSN_LIST (pred_deps->last_pending_memory_flush,
2617 succ_deps->last_pending_memory_flush);
2619 succ_deps->pending_read_list_length += pred_deps->pending_read_list_length;
2620 succ_deps->pending_write_list_length += pred_deps->pending_write_list_length;
2621 succ_deps->pending_flush_length += pred_deps->pending_flush_length;
2623 /* last_function_call is inherited by successor. */
2624 succ_deps->last_function_call
2625 = concat_INSN_LIST (pred_deps->last_function_call,
2626 succ_deps->last_function_call);
2628 /* last_function_call_may_noreturn is inherited by successor. */
2629 succ_deps->last_function_call_may_noreturn
2630 = concat_INSN_LIST (pred_deps->last_function_call_may_noreturn,
2631 succ_deps->last_function_call_may_noreturn);
2633 /* sched_before_next_call is inherited by successor. */
2634 succ_deps->sched_before_next_call
2635 = concat_INSN_LIST (pred_deps->sched_before_next_call,
2636 succ_deps->sched_before_next_call);
2639 /* After computing the dependencies for block BB, propagate the dependencies
2640 found in TMP_DEPS to the successors of the block. */
2641 static void
2642 propagate_deps (int bb, struct deps_desc *pred_deps)
2644 basic_block block = BASIC_BLOCK (BB_TO_BLOCK (bb));
2645 edge_iterator ei;
2646 edge e;
2648 /* bb's structures are inherited by its successors. */
2649 FOR_EACH_EDGE (e, ei, block->succs)
2651 /* Only bbs "below" bb, in the same region, are interesting. */
2652 if (e->dest == EXIT_BLOCK_PTR
2653 || CONTAINING_RGN (block->index) != CONTAINING_RGN (e->dest->index)
2654 || BLOCK_TO_BB (e->dest->index) <= bb)
2655 continue;
2657 deps_join (bb_deps + BLOCK_TO_BB (e->dest->index), pred_deps);
2660 /* These lists should point to the right place, for correct
2661 freeing later. */
2662 bb_deps[bb].pending_read_insns = pred_deps->pending_read_insns;
2663 bb_deps[bb].pending_read_mems = pred_deps->pending_read_mems;
2664 bb_deps[bb].pending_write_insns = pred_deps->pending_write_insns;
2665 bb_deps[bb].pending_write_mems = pred_deps->pending_write_mems;
2666 bb_deps[bb].pending_jump_insns = pred_deps->pending_jump_insns;
2668 /* Can't allow these to be freed twice. */
2669 pred_deps->pending_read_insns = 0;
2670 pred_deps->pending_read_mems = 0;
2671 pred_deps->pending_write_insns = 0;
2672 pred_deps->pending_write_mems = 0;
2673 pred_deps->pending_jump_insns = 0;
2676 /* Compute dependences inside bb. In a multiple blocks region:
2677 (1) a bb is analyzed after its predecessors, and (2) the lists in
2678 effect at the end of bb (after analyzing for bb) are inherited by
2679 bb's successors.
2681 Specifically for reg-reg data dependences, the block insns are
2682 scanned by sched_analyze () top-to-bottom. Three lists are
2683 maintained by sched_analyze (): reg_last[].sets for register DEFs,
2684 reg_last[].implicit_sets for implicit hard register DEFs, and
2685 reg_last[].uses for register USEs.
2687 When analysis is completed for bb, we update for its successors:
2688 ; - DEFS[succ] = Union (DEFS [succ], DEFS [bb])
2689 ; - IMPLICIT_DEFS[succ] = Union (IMPLICIT_DEFS [succ], IMPLICIT_DEFS [bb])
2690 ; - USES[succ] = Union (USES [succ], DEFS [bb])
2692 The mechanism for computing mem-mem data dependence is very
2693 similar, and the result is interblock dependences in the region. */
2695 static void
2696 compute_block_dependences (int bb)
2698 rtx head, tail;
2699 struct deps_desc tmp_deps;
2701 tmp_deps = bb_deps[bb];
2703 /* Do the analysis for this block. */
2704 gcc_assert (EBB_FIRST_BB (bb) == EBB_LAST_BB (bb));
2705 get_ebb_head_tail (EBB_FIRST_BB (bb), EBB_LAST_BB (bb), &head, &tail);
2707 sched_analyze (&tmp_deps, head, tail);
2709 /* Selective scheduling handles control dependencies by itself. */
2710 if (!sel_sched_p ())
2711 add_branch_dependences (head, tail);
2713 if (current_nr_blocks > 1)
2714 propagate_deps (bb, &tmp_deps);
2716 /* Free up the INSN_LISTs. */
2717 free_deps (&tmp_deps);
2719 if (targetm.sched.dependencies_evaluation_hook)
2720 targetm.sched.dependencies_evaluation_hook (head, tail);
2723 /* Free dependencies of instructions inside BB. */
2724 static void
2725 free_block_dependencies (int bb)
2727 rtx head;
2728 rtx tail;
2730 get_ebb_head_tail (EBB_FIRST_BB (bb), EBB_LAST_BB (bb), &head, &tail);
2732 if (no_real_insns_p (head, tail))
2733 return;
2735 sched_free_deps (head, tail, true);
2738 /* Remove all INSN_LISTs and EXPR_LISTs from the pending lists and add
2739 them to the unused_*_list variables, so that they can be reused. */
2741 static void
2742 free_pending_lists (void)
2744 int bb;
2746 for (bb = 0; bb < current_nr_blocks; bb++)
2748 free_INSN_LIST_list (&bb_deps[bb].pending_read_insns);
2749 free_INSN_LIST_list (&bb_deps[bb].pending_write_insns);
2750 free_EXPR_LIST_list (&bb_deps[bb].pending_read_mems);
2751 free_EXPR_LIST_list (&bb_deps[bb].pending_write_mems);
2752 free_INSN_LIST_list (&bb_deps[bb].pending_jump_insns);
2756 /* Print dependences for debugging starting from FROM_BB.
2757 Callable from debugger. */
2758 /* Print dependences for debugging starting from FROM_BB.
2759 Callable from debugger. */
2760 DEBUG_FUNCTION void
2761 debug_rgn_dependencies (int from_bb)
2763 int bb;
2765 fprintf (sched_dump,
2766 ";; --------------- forward dependences: ------------ \n");
2768 for (bb = from_bb; bb < current_nr_blocks; bb++)
2770 rtx head, tail;
2772 get_ebb_head_tail (EBB_FIRST_BB (bb), EBB_LAST_BB (bb), &head, &tail);
2773 fprintf (sched_dump, "\n;; --- Region Dependences --- b %d bb %d \n",
2774 BB_TO_BLOCK (bb), bb);
2776 debug_dependencies (head, tail);
2780 /* Print dependencies information for instructions between HEAD and TAIL.
2781 ??? This function would probably fit best in haifa-sched.c. */
2782 void debug_dependencies (rtx head, rtx tail)
2784 rtx insn;
2785 rtx next_tail = NEXT_INSN (tail);
2787 fprintf (sched_dump, ";; %7s%6s%6s%6s%6s%6s%14s\n",
2788 "insn", "code", "bb", "dep", "prio", "cost",
2789 "reservation");
2790 fprintf (sched_dump, ";; %7s%6s%6s%6s%6s%6s%14s\n",
2791 "----", "----", "--", "---", "----", "----",
2792 "-----------");
2794 for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
2796 if (! INSN_P (insn))
2798 int n;
2799 fprintf (sched_dump, ";; %6d ", INSN_UID (insn));
2800 if (NOTE_P (insn))
2802 n = NOTE_KIND (insn);
2803 fprintf (sched_dump, "%s\n", GET_NOTE_INSN_NAME (n));
2805 else
2806 fprintf (sched_dump, " {%s}\n", GET_RTX_NAME (GET_CODE (insn)));
2807 continue;
2810 fprintf (sched_dump,
2811 ";; %s%5d%6d%6d%6d%6d%6d ",
2812 (SCHED_GROUP_P (insn) ? "+" : " "),
2813 INSN_UID (insn),
2814 INSN_CODE (insn),
2815 BLOCK_NUM (insn),
2816 sched_emulate_haifa_p ? -1 : sd_lists_size (insn, SD_LIST_BACK),
2817 (sel_sched_p () ? (sched_emulate_haifa_p ? -1
2818 : INSN_PRIORITY (insn))
2819 : INSN_PRIORITY (insn)),
2820 (sel_sched_p () ? (sched_emulate_haifa_p ? -1
2821 : insn_cost (insn))
2822 : insn_cost (insn)));
2824 if (recog_memoized (insn) < 0)
2825 fprintf (sched_dump, "nothing");
2826 else
2827 print_reservation (sched_dump, insn);
2829 fprintf (sched_dump, "\t: ");
2831 sd_iterator_def sd_it;
2832 dep_t dep;
2834 FOR_EACH_DEP (insn, SD_LIST_FORW, sd_it, dep)
2835 fprintf (sched_dump, "%d%s%s ", INSN_UID (DEP_CON (dep)),
2836 DEP_NONREG (dep) ? "n" : "",
2837 DEP_MULTIPLE (dep) ? "m" : "");
2839 fprintf (sched_dump, "\n");
2842 fprintf (sched_dump, "\n");
2845 /* Returns true if all the basic blocks of the current region have
2846 NOTE_DISABLE_SCHED_OF_BLOCK which means not to schedule that region. */
2847 bool
2848 sched_is_disabled_for_current_region_p (void)
2850 int bb;
2852 for (bb = 0; bb < current_nr_blocks; bb++)
2853 if (!(BASIC_BLOCK (BB_TO_BLOCK (bb))->flags & BB_DISABLE_SCHEDULE))
2854 return false;
2856 return true;
2859 /* Free all region dependencies saved in INSN_BACK_DEPS and
2860 INSN_RESOLVED_BACK_DEPS. The Haifa scheduler does this on the fly
2861 when scheduling, so this function is supposed to be called from
2862 the selective scheduling only. */
2863 void
2864 free_rgn_deps (void)
2866 int bb;
2868 for (bb = 0; bb < current_nr_blocks; bb++)
2870 rtx head, tail;
2872 gcc_assert (EBB_FIRST_BB (bb) == EBB_LAST_BB (bb));
2873 get_ebb_head_tail (EBB_FIRST_BB (bb), EBB_LAST_BB (bb), &head, &tail);
2875 sched_free_deps (head, tail, false);
2879 static int rgn_n_insns;
2881 /* Compute insn priority for a current region. */
2882 void
2883 compute_priorities (void)
2885 int bb;
2887 current_sched_info->sched_max_insns_priority = 0;
2888 for (bb = 0; bb < current_nr_blocks; bb++)
2890 rtx head, tail;
2892 gcc_assert (EBB_FIRST_BB (bb) == EBB_LAST_BB (bb));
2893 get_ebb_head_tail (EBB_FIRST_BB (bb), EBB_LAST_BB (bb), &head, &tail);
2895 if (no_real_insns_p (head, tail))
2896 continue;
2898 rgn_n_insns += set_priorities (head, tail);
2900 current_sched_info->sched_max_insns_priority++;
2903 /* Schedule a region. A region is either an inner loop, a loop-free
2904 subroutine, or a single basic block. Each bb in the region is
2905 scheduled after its flow predecessors. */
2907 static void
2908 schedule_region (int rgn)
2910 int bb;
2911 int sched_rgn_n_insns = 0;
2913 rgn_n_insns = 0;
2915 rgn_setup_region (rgn);
2917 /* Don't schedule region that is marked by
2918 NOTE_DISABLE_SCHED_OF_BLOCK. */
2919 if (sched_is_disabled_for_current_region_p ())
2920 return;
2922 sched_rgn_compute_dependencies (rgn);
2924 sched_rgn_local_init (rgn);
2926 /* Set priorities. */
2927 compute_priorities ();
2929 sched_extend_ready_list (rgn_n_insns);
2931 if (sched_pressure == SCHED_PRESSURE_WEIGHTED)
2933 sched_init_region_reg_pressure_info ();
2934 for (bb = 0; bb < current_nr_blocks; bb++)
2936 basic_block first_bb, last_bb;
2937 rtx head, tail;
2939 first_bb = EBB_FIRST_BB (bb);
2940 last_bb = EBB_LAST_BB (bb);
2942 get_ebb_head_tail (first_bb, last_bb, &head, &tail);
2944 if (no_real_insns_p (head, tail))
2946 gcc_assert (first_bb == last_bb);
2947 continue;
2949 sched_setup_bb_reg_pressure_info (first_bb, PREV_INSN (head));
2953 /* Now we can schedule all blocks. */
2954 for (bb = 0; bb < current_nr_blocks; bb++)
2956 basic_block first_bb, last_bb, curr_bb;
2957 rtx head, tail;
2959 first_bb = EBB_FIRST_BB (bb);
2960 last_bb = EBB_LAST_BB (bb);
2962 get_ebb_head_tail (first_bb, last_bb, &head, &tail);
2964 if (no_real_insns_p (head, tail))
2966 gcc_assert (first_bb == last_bb);
2967 continue;
2970 current_sched_info->prev_head = PREV_INSN (head);
2971 current_sched_info->next_tail = NEXT_INSN (tail);
2973 remove_notes (head, tail);
2975 unlink_bb_notes (first_bb, last_bb);
2977 target_bb = bb;
2979 gcc_assert (flag_schedule_interblock || current_nr_blocks == 1);
2980 current_sched_info->queue_must_finish_empty = current_nr_blocks == 1;
2982 curr_bb = first_bb;
2983 if (dbg_cnt (sched_block))
2985 schedule_block (&curr_bb);
2986 gcc_assert (EBB_FIRST_BB (bb) == first_bb);
2987 sched_rgn_n_insns += sched_n_insns;
2989 else
2991 sched_rgn_n_insns += rgn_n_insns;
2994 /* Clean up. */
2995 if (current_nr_blocks > 1)
2996 free_trg_info ();
2999 /* Sanity check: verify that all region insns were scheduled. */
3000 gcc_assert (sched_rgn_n_insns == rgn_n_insns);
3002 sched_finish_ready_list ();
3004 /* Done with this region. */
3005 sched_rgn_local_finish ();
3007 /* Free dependencies. */
3008 for (bb = 0; bb < current_nr_blocks; ++bb)
3009 free_block_dependencies (bb);
3011 gcc_assert (haifa_recovery_bb_ever_added_p
3012 || deps_pools_are_empty_p ());
3015 /* Initialize data structures for region scheduling. */
3017 void
3018 sched_rgn_init (bool single_blocks_p)
3020 min_spec_prob = ((PARAM_VALUE (PARAM_MIN_SPEC_PROB) * REG_BR_PROB_BASE)
3021 / 100);
3023 nr_inter = 0;
3024 nr_spec = 0;
3026 extend_regions ();
3028 CONTAINING_RGN (ENTRY_BLOCK) = -1;
3029 CONTAINING_RGN (EXIT_BLOCK) = -1;
3031 /* Compute regions for scheduling. */
3032 if (single_blocks_p
3033 || n_basic_blocks == NUM_FIXED_BLOCKS + 1
3034 || !flag_schedule_interblock
3035 || is_cfg_nonregular ())
3037 find_single_block_region (sel_sched_p ());
3039 else
3041 /* Compute the dominators and post dominators. */
3042 if (!sel_sched_p ())
3043 calculate_dominance_info (CDI_DOMINATORS);
3045 /* Find regions. */
3046 find_rgns ();
3048 if (sched_verbose >= 3)
3049 debug_regions ();
3051 /* For now. This will move as more and more of haifa is converted
3052 to using the cfg code. */
3053 if (!sel_sched_p ())
3054 free_dominance_info (CDI_DOMINATORS);
3057 gcc_assert (0 < nr_regions && nr_regions <= n_basic_blocks);
3059 RGN_BLOCKS (nr_regions) = (RGN_BLOCKS (nr_regions - 1) +
3060 RGN_NR_BLOCKS (nr_regions - 1));
3063 /* Free data structures for region scheduling. */
3064 void
3065 sched_rgn_finish (void)
3067 /* Reposition the prologue and epilogue notes in case we moved the
3068 prologue/epilogue insns. */
3069 if (reload_completed)
3070 reposition_prologue_and_epilogue_notes ();
3072 if (sched_verbose)
3074 if (reload_completed == 0
3075 && flag_schedule_interblock)
3077 fprintf (sched_dump,
3078 "\n;; Procedure interblock/speculative motions == %d/%d \n",
3079 nr_inter, nr_spec);
3081 else
3082 gcc_assert (nr_inter <= 0);
3083 fprintf (sched_dump, "\n\n");
3086 nr_regions = 0;
3088 free (rgn_table);
3089 rgn_table = NULL;
3091 free (rgn_bb_table);
3092 rgn_bb_table = NULL;
3094 free (block_to_bb);
3095 block_to_bb = NULL;
3097 free (containing_rgn);
3098 containing_rgn = NULL;
3100 free (ebb_head);
3101 ebb_head = NULL;
3104 /* Setup global variables like CURRENT_BLOCKS and CURRENT_NR_BLOCK to
3105 point to the region RGN. */
3106 void
3107 rgn_setup_region (int rgn)
3109 int bb;
3111 /* Set variables for the current region. */
3112 current_nr_blocks = RGN_NR_BLOCKS (rgn);
3113 current_blocks = RGN_BLOCKS (rgn);
3115 /* EBB_HEAD is a region-scope structure. But we realloc it for
3116 each region to save time/memory/something else.
3117 See comments in add_block1, for what reasons we allocate +1 element. */
3118 ebb_head = XRESIZEVEC (int, ebb_head, current_nr_blocks + 1);
3119 for (bb = 0; bb <= current_nr_blocks; bb++)
3120 ebb_head[bb] = current_blocks + bb;
3123 /* Compute instruction dependencies in region RGN. */
3124 void
3125 sched_rgn_compute_dependencies (int rgn)
3127 if (!RGN_DONT_CALC_DEPS (rgn))
3129 int bb;
3131 if (sel_sched_p ())
3132 sched_emulate_haifa_p = 1;
3134 init_deps_global ();
3136 /* Initializations for region data dependence analysis. */
3137 bb_deps = XNEWVEC (struct deps_desc, current_nr_blocks);
3138 for (bb = 0; bb < current_nr_blocks; bb++)
3139 init_deps (bb_deps + bb, false);
3141 /* Initialize bitmap used in add_branch_dependences. */
3142 insn_referenced = sbitmap_alloc (sched_max_luid);
3143 sbitmap_zero (insn_referenced);
3145 /* Compute backward dependencies. */
3146 for (bb = 0; bb < current_nr_blocks; bb++)
3147 compute_block_dependences (bb);
3149 sbitmap_free (insn_referenced);
3150 free_pending_lists ();
3151 finish_deps_global ();
3152 free (bb_deps);
3154 /* We don't want to recalculate this twice. */
3155 RGN_DONT_CALC_DEPS (rgn) = 1;
3157 if (sel_sched_p ())
3158 sched_emulate_haifa_p = 0;
3160 else
3161 /* (This is a recovery block. It is always a single block region.)
3162 OR (We use selective scheduling.) */
3163 gcc_assert (current_nr_blocks == 1 || sel_sched_p ());
3166 /* Init region data structures. Returns true if this region should
3167 not be scheduled. */
3168 void
3169 sched_rgn_local_init (int rgn)
3171 int bb;
3173 /* Compute interblock info: probabilities, split-edges, dominators, etc. */
3174 if (current_nr_blocks > 1)
3176 basic_block block;
3177 edge e;
3178 edge_iterator ei;
3180 prob = XNEWVEC (int, current_nr_blocks);
3182 dom = sbitmap_vector_alloc (current_nr_blocks, current_nr_blocks);
3183 sbitmap_vector_zero (dom, current_nr_blocks);
3185 /* Use ->aux to implement EDGE_TO_BIT mapping. */
3186 rgn_nr_edges = 0;
3187 FOR_EACH_BB (block)
3189 if (CONTAINING_RGN (block->index) != rgn)
3190 continue;
3191 FOR_EACH_EDGE (e, ei, block->succs)
3192 SET_EDGE_TO_BIT (e, rgn_nr_edges++);
3195 rgn_edges = XNEWVEC (edge, rgn_nr_edges);
3196 rgn_nr_edges = 0;
3197 FOR_EACH_BB (block)
3199 if (CONTAINING_RGN (block->index) != rgn)
3200 continue;
3201 FOR_EACH_EDGE (e, ei, block->succs)
3202 rgn_edges[rgn_nr_edges++] = e;
3205 /* Split edges. */
3206 pot_split = sbitmap_vector_alloc (current_nr_blocks, rgn_nr_edges);
3207 sbitmap_vector_zero (pot_split, current_nr_blocks);
3208 ancestor_edges = sbitmap_vector_alloc (current_nr_blocks, rgn_nr_edges);
3209 sbitmap_vector_zero (ancestor_edges, current_nr_blocks);
3211 /* Compute probabilities, dominators, split_edges. */
3212 for (bb = 0; bb < current_nr_blocks; bb++)
3213 compute_dom_prob_ps (bb);
3215 /* Cleanup ->aux used for EDGE_TO_BIT mapping. */
3216 /* We don't need them anymore. But we want to avoid duplication of
3217 aux fields in the newly created edges. */
3218 FOR_EACH_BB (block)
3220 if (CONTAINING_RGN (block->index) != rgn)
3221 continue;
3222 FOR_EACH_EDGE (e, ei, block->succs)
3223 e->aux = NULL;
3228 /* Free data computed for the finished region. */
3229 void
3230 sched_rgn_local_free (void)
3232 free (prob);
3233 sbitmap_vector_free (dom);
3234 sbitmap_vector_free (pot_split);
3235 sbitmap_vector_free (ancestor_edges);
3236 free (rgn_edges);
3239 /* Free data computed for the finished region. */
3240 void
3241 sched_rgn_local_finish (void)
3243 if (current_nr_blocks > 1 && !sel_sched_p ())
3245 sched_rgn_local_free ();
3249 /* Setup scheduler infos. */
3250 void
3251 rgn_setup_common_sched_info (void)
3253 memcpy (&rgn_common_sched_info, &haifa_common_sched_info,
3254 sizeof (rgn_common_sched_info));
3256 rgn_common_sched_info.fix_recovery_cfg = rgn_fix_recovery_cfg;
3257 rgn_common_sched_info.add_block = rgn_add_block;
3258 rgn_common_sched_info.estimate_number_of_insns
3259 = rgn_estimate_number_of_insns;
3260 rgn_common_sched_info.sched_pass_id = SCHED_RGN_PASS;
3262 common_sched_info = &rgn_common_sched_info;
3265 /* Setup all *_sched_info structures (for the Haifa frontend
3266 and for the dependence analysis) in the interblock scheduler. */
3267 void
3268 rgn_setup_sched_infos (void)
3270 if (!sel_sched_p ())
3271 memcpy (&rgn_sched_deps_info, &rgn_const_sched_deps_info,
3272 sizeof (rgn_sched_deps_info));
3273 else
3274 memcpy (&rgn_sched_deps_info, &rgn_const_sel_sched_deps_info,
3275 sizeof (rgn_sched_deps_info));
3277 sched_deps_info = &rgn_sched_deps_info;
3279 memcpy (&rgn_sched_info, &rgn_const_sched_info, sizeof (rgn_sched_info));
3280 current_sched_info = &rgn_sched_info;
3283 /* The one entry point in this file. */
3284 void
3285 schedule_insns (void)
3287 int rgn;
3289 /* Taking care of this degenerate case makes the rest of
3290 this code simpler. */
3291 if (n_basic_blocks == NUM_FIXED_BLOCKS)
3292 return;
3294 rgn_setup_common_sched_info ();
3295 rgn_setup_sched_infos ();
3297 haifa_sched_init ();
3298 sched_rgn_init (reload_completed);
3300 bitmap_initialize (&not_in_df, 0);
3301 bitmap_clear (&not_in_df);
3303 /* Schedule every region in the subroutine. */
3304 for (rgn = 0; rgn < nr_regions; rgn++)
3305 if (dbg_cnt (sched_region))
3306 schedule_region (rgn);
3308 /* Clean up. */
3309 sched_rgn_finish ();
3310 bitmap_clear (&not_in_df);
3312 haifa_sched_finish ();
3315 /* INSN has been added to/removed from current region. */
3316 static void
3317 rgn_add_remove_insn (rtx insn, int remove_p)
3319 if (!remove_p)
3320 rgn_n_insns++;
3321 else
3322 rgn_n_insns--;
3324 if (INSN_BB (insn) == target_bb)
3326 if (!remove_p)
3327 target_n_insns++;
3328 else
3329 target_n_insns--;
3333 /* Extend internal data structures. */
3334 void
3335 extend_regions (void)
3337 rgn_table = XRESIZEVEC (region, rgn_table, n_basic_blocks);
3338 rgn_bb_table = XRESIZEVEC (int, rgn_bb_table, n_basic_blocks);
3339 block_to_bb = XRESIZEVEC (int, block_to_bb, last_basic_block);
3340 containing_rgn = XRESIZEVEC (int, containing_rgn, last_basic_block);
3343 void
3344 rgn_make_new_region_out_of_new_block (basic_block bb)
3346 int i;
3348 i = RGN_BLOCKS (nr_regions);
3349 /* I - first free position in rgn_bb_table. */
3351 rgn_bb_table[i] = bb->index;
3352 RGN_NR_BLOCKS (nr_regions) = 1;
3353 RGN_HAS_REAL_EBB (nr_regions) = 0;
3354 RGN_DONT_CALC_DEPS (nr_regions) = 0;
3355 CONTAINING_RGN (bb->index) = nr_regions;
3356 BLOCK_TO_BB (bb->index) = 0;
3358 nr_regions++;
3360 RGN_BLOCKS (nr_regions) = i + 1;
3363 /* BB was added to ebb after AFTER. */
3364 static void
3365 rgn_add_block (basic_block bb, basic_block after)
3367 extend_regions ();
3368 bitmap_set_bit (&not_in_df, bb->index);
3370 if (after == 0 || after == EXIT_BLOCK_PTR)
3372 rgn_make_new_region_out_of_new_block (bb);
3373 RGN_DONT_CALC_DEPS (nr_regions - 1) = (after == EXIT_BLOCK_PTR);
3375 else
3377 int i, pos;
3379 /* We need to fix rgn_table, block_to_bb, containing_rgn
3380 and ebb_head. */
3382 BLOCK_TO_BB (bb->index) = BLOCK_TO_BB (after->index);
3384 /* We extend ebb_head to one more position to
3385 easily find the last position of the last ebb in
3386 the current region. Thus, ebb_head[BLOCK_TO_BB (after) + 1]
3387 is _always_ valid for access. */
3389 i = BLOCK_TO_BB (after->index) + 1;
3390 pos = ebb_head[i] - 1;
3391 /* Now POS is the index of the last block in the region. */
3393 /* Find index of basic block AFTER. */
3394 for (; rgn_bb_table[pos] != after->index; pos--)
3397 pos++;
3398 gcc_assert (pos > ebb_head[i - 1]);
3400 /* i - ebb right after "AFTER". */
3401 /* ebb_head[i] - VALID. */
3403 /* Source position: ebb_head[i]
3404 Destination position: ebb_head[i] + 1
3405 Last position:
3406 RGN_BLOCKS (nr_regions) - 1
3407 Number of elements to copy: (last_position) - (source_position) + 1
3410 memmove (rgn_bb_table + pos + 1,
3411 rgn_bb_table + pos,
3412 ((RGN_BLOCKS (nr_regions) - 1) - (pos) + 1)
3413 * sizeof (*rgn_bb_table));
3415 rgn_bb_table[pos] = bb->index;
3417 for (; i <= current_nr_blocks; i++)
3418 ebb_head [i]++;
3420 i = CONTAINING_RGN (after->index);
3421 CONTAINING_RGN (bb->index) = i;
3423 RGN_HAS_REAL_EBB (i) = 1;
3425 for (++i; i <= nr_regions; i++)
3426 RGN_BLOCKS (i)++;
3430 /* Fix internal data after interblock movement of jump instruction.
3431 For parameter meaning please refer to
3432 sched-int.h: struct sched_info: fix_recovery_cfg. */
3433 static void
3434 rgn_fix_recovery_cfg (int bbi, int check_bbi, int check_bb_nexti)
3436 int old_pos, new_pos, i;
3438 BLOCK_TO_BB (check_bb_nexti) = BLOCK_TO_BB (bbi);
3440 for (old_pos = ebb_head[BLOCK_TO_BB (check_bbi) + 1] - 1;
3441 rgn_bb_table[old_pos] != check_bb_nexti;
3442 old_pos--)
3444 gcc_assert (old_pos > ebb_head[BLOCK_TO_BB (check_bbi)]);
3446 for (new_pos = ebb_head[BLOCK_TO_BB (bbi) + 1] - 1;
3447 rgn_bb_table[new_pos] != bbi;
3448 new_pos--)
3450 new_pos++;
3451 gcc_assert (new_pos > ebb_head[BLOCK_TO_BB (bbi)]);
3453 gcc_assert (new_pos < old_pos);
3455 memmove (rgn_bb_table + new_pos + 1,
3456 rgn_bb_table + new_pos,
3457 (old_pos - new_pos) * sizeof (*rgn_bb_table));
3459 rgn_bb_table[new_pos] = check_bb_nexti;
3461 for (i = BLOCK_TO_BB (bbi) + 1; i <= BLOCK_TO_BB (check_bbi); i++)
3462 ebb_head[i]++;
3465 /* Return next block in ebb chain. For parameter meaning please refer to
3466 sched-int.h: struct sched_info: advance_target_bb. */
3467 static basic_block
3468 advance_target_bb (basic_block bb, rtx insn)
3470 if (insn)
3471 return 0;
3473 gcc_assert (BLOCK_TO_BB (bb->index) == target_bb
3474 && BLOCK_TO_BB (bb->next_bb->index) == target_bb);
3475 return bb->next_bb;
3478 #endif
3480 static bool
3481 gate_handle_sched (void)
3483 #ifdef INSN_SCHEDULING
3484 return optimize > 0 && flag_schedule_insns && dbg_cnt (sched_func);
3485 #else
3486 return 0;
3487 #endif
3490 /* Run instruction scheduler. */
3491 static unsigned int
3492 rest_of_handle_sched (void)
3494 #ifdef INSN_SCHEDULING
3495 if (flag_selective_scheduling
3496 && ! maybe_skip_selective_scheduling ())
3497 run_selective_scheduling ();
3498 else
3499 schedule_insns ();
3500 #endif
3501 return 0;
3504 static bool
3505 gate_handle_sched2 (void)
3507 #ifdef INSN_SCHEDULING
3508 return optimize > 0 && flag_schedule_insns_after_reload
3509 && !targetm.delay_sched2 && dbg_cnt (sched2_func);
3510 #else
3511 return 0;
3512 #endif
3515 /* Run second scheduling pass after reload. */
3516 static unsigned int
3517 rest_of_handle_sched2 (void)
3519 #ifdef INSN_SCHEDULING
3520 if (flag_selective_scheduling2
3521 && ! maybe_skip_selective_scheduling ())
3522 run_selective_scheduling ();
3523 else
3525 /* Do control and data sched analysis again,
3526 and write some more of the results to dump file. */
3527 if (flag_sched2_use_superblocks)
3528 schedule_ebbs ();
3529 else
3530 schedule_insns ();
3532 #endif
3533 return 0;
3536 struct rtl_opt_pass pass_sched =
3539 RTL_PASS,
3540 "sched1", /* name */
3541 gate_handle_sched, /* gate */
3542 rest_of_handle_sched, /* execute */
3543 NULL, /* sub */
3544 NULL, /* next */
3545 0, /* static_pass_number */
3546 TV_SCHED, /* tv_id */
3547 0, /* properties_required */
3548 0, /* properties_provided */
3549 0, /* properties_destroyed */
3550 0, /* todo_flags_start */
3551 TODO_df_finish | TODO_verify_rtl_sharing |
3552 TODO_verify_flow |
3553 TODO_ggc_collect /* todo_flags_finish */
3557 struct rtl_opt_pass pass_sched2 =
3560 RTL_PASS,
3561 "sched2", /* name */
3562 gate_handle_sched2, /* gate */
3563 rest_of_handle_sched2, /* execute */
3564 NULL, /* sub */
3565 NULL, /* next */
3566 0, /* static_pass_number */
3567 TV_SCHED2, /* tv_id */
3568 0, /* properties_required */
3569 0, /* properties_provided */
3570 0, /* properties_destroyed */
3571 0, /* todo_flags_start */
3572 TODO_df_finish | TODO_verify_rtl_sharing |
3573 TODO_verify_flow |
3574 TODO_ggc_collect /* todo_flags_finish */