Implement TARGET_IRA_CHANGE_PSEUDO_ALLOCNO_CLASS hook.
[official-gcc.git] / gcc / modulo-sched.c
blob94b79c35f9305d2d676d8588576256a106f203bd
1 /* Swing Modulo Scheduling implementation.
2 Copyright (C) 2004-2015 Free Software Foundation, Inc.
3 Contributed by Ayal Zaks and Mustafa Hagog <zaks,mustafa@il.ibm.com>
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "diagnostic-core.h"
27 #include "rtl.h"
28 #include "tm_p.h"
29 #include "hard-reg-set.h"
30 #include "regs.h"
31 #include "input.h"
32 #include "function.h"
33 #include "profile.h"
34 #include "flags.h"
35 #include "insn-config.h"
36 #include "insn-attr.h"
37 #include "except.h"
38 #include "recog.h"
39 #include "dominance.h"
40 #include "cfg.h"
41 #include "cfgrtl.h"
42 #include "predict.h"
43 #include "basic-block.h"
44 #include "sched-int.h"
45 #include "target.h"
46 #include "cfgloop.h"
47 #include "alias.h"
48 #include "symtab.h"
49 #include "tree.h"
50 #include "insn-codes.h"
51 #include "optabs.h"
52 #include "expmed.h"
53 #include "dojump.h"
54 #include "explow.h"
55 #include "calls.h"
56 #include "emit-rtl.h"
57 #include "varasm.h"
58 #include "stmt.h"
59 #include "expr.h"
60 #include "params.h"
61 #include "gcov-io.h"
62 #include "sbitmap.h"
63 #include "df.h"
64 #include "ddg.h"
65 #include "tree-pass.h"
66 #include "dbgcnt.h"
67 #include "loop-unroll.h"
69 #ifdef INSN_SCHEDULING
71 /* This file contains the implementation of the Swing Modulo Scheduler,
72 described in the following references:
73 [1] J. Llosa, A. Gonzalez, E. Ayguade, M. Valero., and J. Eckhardt.
74 Lifetime--sensitive modulo scheduling in a production environment.
75 IEEE Trans. on Comps., 50(3), March 2001
76 [2] J. Llosa, A. Gonzalez, E. Ayguade, and M. Valero.
77 Swing Modulo Scheduling: A Lifetime Sensitive Approach.
78 PACT '96 , pages 80-87, October 1996 (Boston - Massachusetts - USA).
80 The basic structure is:
81 1. Build a data-dependence graph (DDG) for each loop.
82 2. Use the DDG to order the insns of a loop (not in topological order
83 necessarily, but rather) trying to place each insn after all its
84 predecessors _or_ after all its successors.
85 3. Compute MII: a lower bound on the number of cycles to schedule the loop.
86 4. Use the ordering to perform list-scheduling of the loop:
87 1. Set II = MII. We will try to schedule the loop within II cycles.
88 2. Try to schedule the insns one by one according to the ordering.
89 For each insn compute an interval of cycles by considering already-
90 scheduled preds and succs (and associated latencies); try to place
91 the insn in the cycles of this window checking for potential
92 resource conflicts (using the DFA interface).
93 Note: this is different from the cycle-scheduling of schedule_insns;
94 here the insns are not scheduled monotonically top-down (nor bottom-
95 up).
96 3. If failed in scheduling all insns - bump II++ and try again, unless
97 II reaches an upper bound MaxII, in which case report failure.
98 5. If we succeeded in scheduling the loop within II cycles, we now
99 generate prolog and epilog, decrease the counter of the loop, and
100 perform modulo variable expansion for live ranges that span more than
101 II cycles (i.e. use register copies to prevent a def from overwriting
102 itself before reaching the use).
104 SMS works with countable loops (1) whose control part can be easily
105 decoupled from the rest of the loop and (2) whose loop count can
106 be easily adjusted. This is because we peel a constant number of
107 iterations into a prologue and epilogue for which we want to avoid
108 emitting the control part, and a kernel which is to iterate that
109 constant number of iterations less than the original loop. So the
110 control part should be a set of insns clearly identified and having
111 its own iv, not otherwise used in the loop (at-least for now), which
112 initializes a register before the loop to the number of iterations.
113 Currently SMS relies on the do-loop pattern to recognize such loops,
114 where (1) the control part comprises of all insns defining and/or
115 using a certain 'count' register and (2) the loop count can be
116 adjusted by modifying this register prior to the loop.
117 TODO: Rely on cfgloop analysis instead. */
119 /* This page defines partial-schedule structures and functions for
120 modulo scheduling. */
122 typedef struct partial_schedule *partial_schedule_ptr;
123 typedef struct ps_insn *ps_insn_ptr;
125 /* The minimum (absolute) cycle that a node of ps was scheduled in. */
126 #define PS_MIN_CYCLE(ps) (((partial_schedule_ptr)(ps))->min_cycle)
128 /* The maximum (absolute) cycle that a node of ps was scheduled in. */
129 #define PS_MAX_CYCLE(ps) (((partial_schedule_ptr)(ps))->max_cycle)
131 /* Perform signed modulo, always returning a non-negative value. */
132 #define SMODULO(x,y) ((x) % (y) < 0 ? ((x) % (y) + (y)) : (x) % (y))
134 /* The number of different iterations the nodes in ps span, assuming
135 the stage boundaries are placed efficiently. */
136 #define CALC_STAGE_COUNT(max_cycle,min_cycle,ii) ((max_cycle - min_cycle \
137 + 1 + ii - 1) / ii)
138 /* The stage count of ps. */
139 #define PS_STAGE_COUNT(ps) (((partial_schedule_ptr)(ps))->stage_count)
141 /* A single instruction in the partial schedule. */
142 struct ps_insn
144 /* Identifies the instruction to be scheduled. Values smaller than
145 the ddg's num_nodes refer directly to ddg nodes. A value of
146 X - num_nodes refers to register move X. */
147 int id;
149 /* The (absolute) cycle in which the PS instruction is scheduled.
150 Same as SCHED_TIME (node). */
151 int cycle;
153 /* The next/prev PS_INSN in the same row. */
154 ps_insn_ptr next_in_row,
155 prev_in_row;
159 /* Information about a register move that has been added to a partial
160 schedule. */
161 struct ps_reg_move_info
163 /* The source of the move is defined by the ps_insn with id DEF.
164 The destination is used by the ps_insns with the ids in USES. */
165 int def;
166 sbitmap uses;
168 /* The original form of USES' instructions used OLD_REG, but they
169 should now use NEW_REG. */
170 rtx old_reg;
171 rtx new_reg;
173 /* The number of consecutive stages that the move occupies. */
174 int num_consecutive_stages;
176 /* An instruction that sets NEW_REG to the correct value. The first
177 move associated with DEF will have an rhs of OLD_REG; later moves
178 use the result of the previous move. */
179 rtx_insn *insn;
182 typedef struct ps_reg_move_info ps_reg_move_info;
184 /* Holds the partial schedule as an array of II rows. Each entry of the
185 array points to a linked list of PS_INSNs, which represents the
186 instructions that are scheduled for that row. */
187 struct partial_schedule
189 int ii; /* Number of rows in the partial schedule. */
190 int history; /* Threshold for conflict checking using DFA. */
192 /* rows[i] points to linked list of insns scheduled in row i (0<=i<ii). */
193 ps_insn_ptr *rows;
195 /* All the moves added for this partial schedule. Index X has
196 a ps_insn id of X + g->num_nodes. */
197 vec<ps_reg_move_info> reg_moves;
199 /* rows_length[i] holds the number of instructions in the row.
200 It is used only (as an optimization) to back off quickly from
201 trying to schedule a node in a full row; that is, to avoid running
202 through futile DFA state transitions. */
203 int *rows_length;
205 /* The earliest absolute cycle of an insn in the partial schedule. */
206 int min_cycle;
208 /* The latest absolute cycle of an insn in the partial schedule. */
209 int max_cycle;
211 ddg_ptr g; /* The DDG of the insns in the partial schedule. */
213 int stage_count; /* The stage count of the partial schedule. */
217 static partial_schedule_ptr create_partial_schedule (int ii, ddg_ptr, int history);
218 static void free_partial_schedule (partial_schedule_ptr);
219 static void reset_partial_schedule (partial_schedule_ptr, int new_ii);
220 void print_partial_schedule (partial_schedule_ptr, FILE *);
221 static void verify_partial_schedule (partial_schedule_ptr, sbitmap);
222 static ps_insn_ptr ps_add_node_check_conflicts (partial_schedule_ptr,
223 int, int, sbitmap, sbitmap);
224 static void rotate_partial_schedule (partial_schedule_ptr, int);
225 void set_row_column_for_ps (partial_schedule_ptr);
226 static void ps_insert_empty_row (partial_schedule_ptr, int, sbitmap);
227 static int compute_split_row (sbitmap, int, int, int, ddg_node_ptr);
230 /* This page defines constants and structures for the modulo scheduling
231 driver. */
233 static int sms_order_nodes (ddg_ptr, int, int *, int *);
234 static void set_node_sched_params (ddg_ptr);
235 static partial_schedule_ptr sms_schedule_by_order (ddg_ptr, int, int, int *);
236 static void permute_partial_schedule (partial_schedule_ptr, rtx_insn *);
237 static void generate_prolog_epilog (partial_schedule_ptr, struct loop *,
238 rtx, rtx);
239 static int calculate_stage_count (partial_schedule_ptr, int);
240 static void calculate_must_precede_follow (ddg_node_ptr, int, int,
241 int, int, sbitmap, sbitmap, sbitmap);
242 static int get_sched_window (partial_schedule_ptr, ddg_node_ptr,
243 sbitmap, int, int *, int *, int *);
244 static bool try_scheduling_node_in_cycle (partial_schedule_ptr, int, int,
245 sbitmap, int *, sbitmap, sbitmap);
246 static void remove_node_from_ps (partial_schedule_ptr, ps_insn_ptr);
248 #define NODE_ASAP(node) ((node)->aux.count)
250 #define SCHED_PARAMS(x) (&node_sched_param_vec[x])
251 #define SCHED_TIME(x) (SCHED_PARAMS (x)->time)
252 #define SCHED_ROW(x) (SCHED_PARAMS (x)->row)
253 #define SCHED_STAGE(x) (SCHED_PARAMS (x)->stage)
254 #define SCHED_COLUMN(x) (SCHED_PARAMS (x)->column)
256 /* The scheduling parameters held for each node. */
257 typedef struct node_sched_params
259 int time; /* The absolute scheduling cycle. */
261 int row; /* Holds time % ii. */
262 int stage; /* Holds time / ii. */
264 /* The column of a node inside the ps. If nodes u, v are on the same row,
265 u will precede v if column (u) < column (v). */
266 int column;
267 } *node_sched_params_ptr;
269 typedef struct node_sched_params node_sched_params;
271 /* The following three functions are copied from the current scheduler
272 code in order to use sched_analyze() for computing the dependencies.
273 They are used when initializing the sched_info structure. */
274 static const char *
275 sms_print_insn (const rtx_insn *insn, int aligned ATTRIBUTE_UNUSED)
277 static char tmp[80];
279 sprintf (tmp, "i%4d", INSN_UID (insn));
280 return tmp;
283 static void
284 compute_jump_reg_dependencies (rtx insn ATTRIBUTE_UNUSED,
285 regset used ATTRIBUTE_UNUSED)
289 static struct common_sched_info_def sms_common_sched_info;
291 static struct sched_deps_info_def sms_sched_deps_info =
293 compute_jump_reg_dependencies,
294 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
295 NULL,
296 0, 0, 0
299 static struct haifa_sched_info sms_sched_info =
301 NULL,
302 NULL,
303 NULL,
304 NULL,
305 NULL,
306 sms_print_insn,
307 NULL,
308 NULL, /* insn_finishes_block_p */
309 NULL, NULL,
310 NULL, NULL,
311 0, 0,
313 NULL, NULL, NULL, NULL,
314 NULL, NULL,
318 /* Partial schedule instruction ID in PS is a register move. Return
319 information about it. */
320 static struct ps_reg_move_info *
321 ps_reg_move (partial_schedule_ptr ps, int id)
323 gcc_checking_assert (id >= ps->g->num_nodes);
324 return &ps->reg_moves[id - ps->g->num_nodes];
327 /* Return the rtl instruction that is being scheduled by partial schedule
328 instruction ID, which belongs to schedule PS. */
329 static rtx_insn *
330 ps_rtl_insn (partial_schedule_ptr ps, int id)
332 if (id < ps->g->num_nodes)
333 return ps->g->nodes[id].insn;
334 else
335 return ps_reg_move (ps, id)->insn;
338 /* Partial schedule instruction ID, which belongs to PS, occurred in
339 the original (unscheduled) loop. Return the first instruction
340 in the loop that was associated with ps_rtl_insn (PS, ID).
341 If the instruction had some notes before it, this is the first
342 of those notes. */
343 static rtx_insn *
344 ps_first_note (partial_schedule_ptr ps, int id)
346 gcc_assert (id < ps->g->num_nodes);
347 return ps->g->nodes[id].first_note;
350 /* Return the number of consecutive stages that are occupied by
351 partial schedule instruction ID in PS. */
352 static int
353 ps_num_consecutive_stages (partial_schedule_ptr ps, int id)
355 if (id < ps->g->num_nodes)
356 return 1;
357 else
358 return ps_reg_move (ps, id)->num_consecutive_stages;
361 /* Given HEAD and TAIL which are the first and last insns in a loop;
362 return the register which controls the loop. Return zero if it has
363 more than one occurrence in the loop besides the control part or the
364 do-loop pattern is not of the form we expect. */
365 static rtx
366 doloop_register_get (rtx_insn *head ATTRIBUTE_UNUSED, rtx_insn *tail ATTRIBUTE_UNUSED)
368 #ifdef HAVE_doloop_end
369 rtx reg, condition;
370 rtx_insn *insn, *first_insn_not_to_check;
372 if (!JUMP_P (tail))
373 return NULL_RTX;
375 /* TODO: Free SMS's dependence on doloop_condition_get. */
376 condition = doloop_condition_get (tail);
377 if (! condition)
378 return NULL_RTX;
380 if (REG_P (XEXP (condition, 0)))
381 reg = XEXP (condition, 0);
382 else if (GET_CODE (XEXP (condition, 0)) == PLUS
383 && REG_P (XEXP (XEXP (condition, 0), 0)))
384 reg = XEXP (XEXP (condition, 0), 0);
385 else
386 gcc_unreachable ();
388 /* Check that the COUNT_REG has no other occurrences in the loop
389 until the decrement. We assume the control part consists of
390 either a single (parallel) branch-on-count or a (non-parallel)
391 branch immediately preceded by a single (decrement) insn. */
392 first_insn_not_to_check = (GET_CODE (PATTERN (tail)) == PARALLEL ? tail
393 : prev_nondebug_insn (tail));
395 for (insn = head; insn != first_insn_not_to_check; insn = NEXT_INSN (insn))
396 if (!DEBUG_INSN_P (insn) && reg_mentioned_p (reg, insn))
398 if (dump_file)
400 fprintf (dump_file, "SMS count_reg found ");
401 print_rtl_single (dump_file, reg);
402 fprintf (dump_file, " outside control in insn:\n");
403 print_rtl_single (dump_file, insn);
406 return NULL_RTX;
409 return reg;
410 #else
411 return NULL_RTX;
412 #endif
415 /* Check if COUNT_REG is set to a constant in the PRE_HEADER block, so
416 that the number of iterations is a compile-time constant. If so,
417 return the rtx_insn that sets COUNT_REG to a constant, and set COUNT to
418 this constant. Otherwise return 0. */
419 static rtx_insn *
420 const_iteration_count (rtx count_reg, basic_block pre_header,
421 int64_t * count)
423 rtx_insn *insn;
424 rtx_insn *head, *tail;
426 if (! pre_header)
427 return NULL;
429 get_ebb_head_tail (pre_header, pre_header, &head, &tail);
431 for (insn = tail; insn != PREV_INSN (head); insn = PREV_INSN (insn))
432 if (NONDEBUG_INSN_P (insn) && single_set (insn) &&
433 rtx_equal_p (count_reg, SET_DEST (single_set (insn))))
435 rtx pat = single_set (insn);
437 if (CONST_INT_P (SET_SRC (pat)))
439 *count = INTVAL (SET_SRC (pat));
440 return insn;
443 return NULL;
446 return NULL;
449 /* A very simple resource-based lower bound on the initiation interval.
450 ??? Improve the accuracy of this bound by considering the
451 utilization of various units. */
452 static int
453 res_MII (ddg_ptr g)
455 if (targetm.sched.sms_res_mii)
456 return targetm.sched.sms_res_mii (g);
458 return ((g->num_nodes - g->num_debug) / issue_rate);
462 /* A vector that contains the sched data for each ps_insn. */
463 static vec<node_sched_params> node_sched_param_vec;
465 /* Allocate sched_params for each node and initialize it. */
466 static void
467 set_node_sched_params (ddg_ptr g)
469 node_sched_param_vec.truncate (0);
470 node_sched_param_vec.safe_grow_cleared (g->num_nodes);
473 /* Make sure that node_sched_param_vec has an entry for every move in PS. */
474 static void
475 extend_node_sched_params (partial_schedule_ptr ps)
477 node_sched_param_vec.safe_grow_cleared (ps->g->num_nodes
478 + ps->reg_moves.length ());
481 /* Update the sched_params (time, row and stage) for node U using the II,
482 the CYCLE of U and MIN_CYCLE.
483 We're not simply taking the following
484 SCHED_STAGE (u) = CALC_STAGE_COUNT (SCHED_TIME (u), min_cycle, ii);
485 because the stages may not be aligned on cycle 0. */
486 static void
487 update_node_sched_params (int u, int ii, int cycle, int min_cycle)
489 int sc_until_cycle_zero;
490 int stage;
492 SCHED_TIME (u) = cycle;
493 SCHED_ROW (u) = SMODULO (cycle, ii);
495 /* The calculation of stage count is done adding the number
496 of stages before cycle zero and after cycle zero. */
497 sc_until_cycle_zero = CALC_STAGE_COUNT (-1, min_cycle, ii);
499 if (SCHED_TIME (u) < 0)
501 stage = CALC_STAGE_COUNT (-1, SCHED_TIME (u), ii);
502 SCHED_STAGE (u) = sc_until_cycle_zero - stage;
504 else
506 stage = CALC_STAGE_COUNT (SCHED_TIME (u), 0, ii);
507 SCHED_STAGE (u) = sc_until_cycle_zero + stage - 1;
511 static void
512 print_node_sched_params (FILE *file, int num_nodes, partial_schedule_ptr ps)
514 int i;
516 if (! file)
517 return;
518 for (i = 0; i < num_nodes; i++)
520 node_sched_params_ptr nsp = SCHED_PARAMS (i);
522 fprintf (file, "Node = %d; INSN = %d\n", i,
523 INSN_UID (ps_rtl_insn (ps, i)));
524 fprintf (file, " asap = %d:\n", NODE_ASAP (&ps->g->nodes[i]));
525 fprintf (file, " time = %d:\n", nsp->time);
526 fprintf (file, " stage = %d:\n", nsp->stage);
530 /* Set SCHED_COLUMN for each instruction in row ROW of PS. */
531 static void
532 set_columns_for_row (partial_schedule_ptr ps, int row)
534 ps_insn_ptr cur_insn;
535 int column;
537 column = 0;
538 for (cur_insn = ps->rows[row]; cur_insn; cur_insn = cur_insn->next_in_row)
539 SCHED_COLUMN (cur_insn->id) = column++;
542 /* Set SCHED_COLUMN for each instruction in PS. */
543 static void
544 set_columns_for_ps (partial_schedule_ptr ps)
546 int row;
548 for (row = 0; row < ps->ii; row++)
549 set_columns_for_row (ps, row);
552 /* Try to schedule the move with ps_insn identifier I_REG_MOVE in PS.
553 Its single predecessor has already been scheduled, as has its
554 ddg node successors. (The move may have also another move as its
555 successor, in which case that successor will be scheduled later.)
557 The move is part of a chain that satisfies register dependencies
558 between a producing ddg node and various consuming ddg nodes.
559 If some of these dependencies have a distance of 1 (meaning that
560 the use is upward-exposed) then DISTANCE1_USES is nonnull and
561 contains the set of uses with distance-1 dependencies.
562 DISTANCE1_USES is null otherwise.
564 MUST_FOLLOW is a scratch bitmap that is big enough to hold
565 all current ps_insn ids.
567 Return true on success. */
568 static bool
569 schedule_reg_move (partial_schedule_ptr ps, int i_reg_move,
570 sbitmap distance1_uses, sbitmap must_follow)
572 unsigned int u;
573 int this_time, this_distance, this_start, this_end, this_latency;
574 int start, end, c, ii;
575 sbitmap_iterator sbi;
576 ps_reg_move_info *move;
577 rtx_insn *this_insn;
578 ps_insn_ptr psi;
580 move = ps_reg_move (ps, i_reg_move);
581 ii = ps->ii;
582 if (dump_file)
584 fprintf (dump_file, "Scheduling register move INSN %d; ii = %d"
585 ", min cycle = %d\n\n", INSN_UID (move->insn), ii,
586 PS_MIN_CYCLE (ps));
587 print_rtl_single (dump_file, move->insn);
588 fprintf (dump_file, "\n%11s %11s %5s\n", "start", "end", "time");
589 fprintf (dump_file, "=========== =========== =====\n");
592 start = INT_MIN;
593 end = INT_MAX;
595 /* For dependencies of distance 1 between a producer ddg node A
596 and consumer ddg node B, we have a chain of dependencies:
598 A --(T,L1,1)--> M1 --(T,L2,0)--> M2 ... --(T,Ln,0)--> B
600 where Mi is the ith move. For dependencies of distance 0 between
601 a producer ddg node A and consumer ddg node C, we have a chain of
602 dependencies:
604 A --(T,L1',0)--> M1' --(T,L2',0)--> M2' ... --(T,Ln',0)--> C
606 where Mi' occupies the same position as Mi but occurs a stage later.
607 We can only schedule each move once, so if we have both types of
608 chain, we model the second as:
610 A --(T,L1',1)--> M1 --(T,L2',0)--> M2 ... --(T,Ln',-1)--> C
612 First handle the dependencies between the previously-scheduled
613 predecessor and the move. */
614 this_insn = ps_rtl_insn (ps, move->def);
615 this_latency = insn_latency (this_insn, move->insn);
616 this_distance = distance1_uses && move->def < ps->g->num_nodes ? 1 : 0;
617 this_time = SCHED_TIME (move->def) - this_distance * ii;
618 this_start = this_time + this_latency;
619 this_end = this_time + ii;
620 if (dump_file)
621 fprintf (dump_file, "%11d %11d %5d %d --(T,%d,%d)--> %d\n",
622 this_start, this_end, SCHED_TIME (move->def),
623 INSN_UID (this_insn), this_latency, this_distance,
624 INSN_UID (move->insn));
626 if (start < this_start)
627 start = this_start;
628 if (end > this_end)
629 end = this_end;
631 /* Handle the dependencies between the move and previously-scheduled
632 successors. */
633 EXECUTE_IF_SET_IN_BITMAP (move->uses, 0, u, sbi)
635 this_insn = ps_rtl_insn (ps, u);
636 this_latency = insn_latency (move->insn, this_insn);
637 if (distance1_uses && !bitmap_bit_p (distance1_uses, u))
638 this_distance = -1;
639 else
640 this_distance = 0;
641 this_time = SCHED_TIME (u) + this_distance * ii;
642 this_start = this_time - ii;
643 this_end = this_time - this_latency;
644 if (dump_file)
645 fprintf (dump_file, "%11d %11d %5d %d --(T,%d,%d)--> %d\n",
646 this_start, this_end, SCHED_TIME (u), INSN_UID (move->insn),
647 this_latency, this_distance, INSN_UID (this_insn));
649 if (start < this_start)
650 start = this_start;
651 if (end > this_end)
652 end = this_end;
655 if (dump_file)
657 fprintf (dump_file, "----------- ----------- -----\n");
658 fprintf (dump_file, "%11d %11d %5s %s\n", start, end, "", "(max, min)");
661 bitmap_clear (must_follow);
662 bitmap_set_bit (must_follow, move->def);
664 start = MAX (start, end - (ii - 1));
665 for (c = end; c >= start; c--)
667 psi = ps_add_node_check_conflicts (ps, i_reg_move, c,
668 move->uses, must_follow);
669 if (psi)
671 update_node_sched_params (i_reg_move, ii, c, PS_MIN_CYCLE (ps));
672 if (dump_file)
673 fprintf (dump_file, "\nScheduled register move INSN %d at"
674 " time %d, row %d\n\n", INSN_UID (move->insn), c,
675 SCHED_ROW (i_reg_move));
676 return true;
680 if (dump_file)
681 fprintf (dump_file, "\nNo available slot\n\n");
683 return false;
687 Breaking intra-loop register anti-dependences:
688 Each intra-loop register anti-dependence implies a cross-iteration true
689 dependence of distance 1. Therefore, we can remove such false dependencies
690 and figure out if the partial schedule broke them by checking if (for a
691 true-dependence of distance 1): SCHED_TIME (def) < SCHED_TIME (use) and
692 if so generate a register move. The number of such moves is equal to:
693 SCHED_TIME (use) - SCHED_TIME (def) { 0 broken
694 nreg_moves = ----------------------------------- + 1 - { dependence.
695 ii { 1 if not.
697 static bool
698 schedule_reg_moves (partial_schedule_ptr ps)
700 ddg_ptr g = ps->g;
701 int ii = ps->ii;
702 int i;
704 for (i = 0; i < g->num_nodes; i++)
706 ddg_node_ptr u = &g->nodes[i];
707 ddg_edge_ptr e;
708 int nreg_moves = 0, i_reg_move;
709 rtx prev_reg, old_reg;
710 int first_move;
711 int distances[2];
712 sbitmap must_follow;
713 sbitmap distance1_uses;
714 rtx set = single_set (u->insn);
716 /* Skip instructions that do not set a register. */
717 if ((set && !REG_P (SET_DEST (set))))
718 continue;
720 /* Compute the number of reg_moves needed for u, by looking at life
721 ranges started at u (excluding self-loops). */
722 distances[0] = distances[1] = false;
723 for (e = u->out; e; e = e->next_out)
724 if (e->type == TRUE_DEP && e->dest != e->src)
726 int nreg_moves4e = (SCHED_TIME (e->dest->cuid)
727 - SCHED_TIME (e->src->cuid)) / ii;
729 if (e->distance == 1)
730 nreg_moves4e = (SCHED_TIME (e->dest->cuid)
731 - SCHED_TIME (e->src->cuid) + ii) / ii;
733 /* If dest precedes src in the schedule of the kernel, then dest
734 will read before src writes and we can save one reg_copy. */
735 if (SCHED_ROW (e->dest->cuid) == SCHED_ROW (e->src->cuid)
736 && SCHED_COLUMN (e->dest->cuid) < SCHED_COLUMN (e->src->cuid))
737 nreg_moves4e--;
739 if (nreg_moves4e >= 1)
741 /* !single_set instructions are not supported yet and
742 thus we do not except to encounter them in the loop
743 except from the doloop part. For the latter case
744 we assume no regmoves are generated as the doloop
745 instructions are tied to the branch with an edge. */
746 gcc_assert (set);
747 /* If the instruction contains auto-inc register then
748 validate that the regmov is being generated for the
749 target regsiter rather then the inc'ed register. */
750 gcc_assert (!autoinc_var_is_used_p (u->insn, e->dest->insn));
753 if (nreg_moves4e)
755 gcc_assert (e->distance < 2);
756 distances[e->distance] = true;
758 nreg_moves = MAX (nreg_moves, nreg_moves4e);
761 if (nreg_moves == 0)
762 continue;
764 /* Create NREG_MOVES register moves. */
765 first_move = ps->reg_moves.length ();
766 ps->reg_moves.safe_grow_cleared (first_move + nreg_moves);
767 extend_node_sched_params (ps);
769 /* Record the moves associated with this node. */
770 first_move += ps->g->num_nodes;
772 /* Generate each move. */
773 old_reg = prev_reg = SET_DEST (single_set (u->insn));
774 for (i_reg_move = 0; i_reg_move < nreg_moves; i_reg_move++)
776 ps_reg_move_info *move = ps_reg_move (ps, first_move + i_reg_move);
778 move->def = i_reg_move > 0 ? first_move + i_reg_move - 1 : i;
779 move->uses = sbitmap_alloc (first_move + nreg_moves);
780 move->old_reg = old_reg;
781 move->new_reg = gen_reg_rtx (GET_MODE (prev_reg));
782 move->num_consecutive_stages = distances[0] && distances[1] ? 2 : 1;
783 move->insn = gen_move_insn (move->new_reg, copy_rtx (prev_reg));
784 bitmap_clear (move->uses);
786 prev_reg = move->new_reg;
789 distance1_uses = distances[1] ? sbitmap_alloc (g->num_nodes) : NULL;
791 if (distance1_uses)
792 bitmap_clear (distance1_uses);
794 /* Every use of the register defined by node may require a different
795 copy of this register, depending on the time the use is scheduled.
796 Record which uses require which move results. */
797 for (e = u->out; e; e = e->next_out)
798 if (e->type == TRUE_DEP && e->dest != e->src)
800 int dest_copy = (SCHED_TIME (e->dest->cuid)
801 - SCHED_TIME (e->src->cuid)) / ii;
803 if (e->distance == 1)
804 dest_copy = (SCHED_TIME (e->dest->cuid)
805 - SCHED_TIME (e->src->cuid) + ii) / ii;
807 if (SCHED_ROW (e->dest->cuid) == SCHED_ROW (e->src->cuid)
808 && SCHED_COLUMN (e->dest->cuid) < SCHED_COLUMN (e->src->cuid))
809 dest_copy--;
811 if (dest_copy)
813 ps_reg_move_info *move;
815 move = ps_reg_move (ps, first_move + dest_copy - 1);
816 bitmap_set_bit (move->uses, e->dest->cuid);
817 if (e->distance == 1)
818 bitmap_set_bit (distance1_uses, e->dest->cuid);
822 must_follow = sbitmap_alloc (first_move + nreg_moves);
823 for (i_reg_move = 0; i_reg_move < nreg_moves; i_reg_move++)
824 if (!schedule_reg_move (ps, first_move + i_reg_move,
825 distance1_uses, must_follow))
826 break;
827 sbitmap_free (must_follow);
828 if (distance1_uses)
829 sbitmap_free (distance1_uses);
830 if (i_reg_move < nreg_moves)
831 return false;
833 return true;
836 /* Emit the moves associatied with PS. Apply the substitutions
837 associated with them. */
838 static void
839 apply_reg_moves (partial_schedule_ptr ps)
841 ps_reg_move_info *move;
842 int i;
844 FOR_EACH_VEC_ELT (ps->reg_moves, i, move)
846 unsigned int i_use;
847 sbitmap_iterator sbi;
849 EXECUTE_IF_SET_IN_BITMAP (move->uses, 0, i_use, sbi)
851 replace_rtx (ps->g->nodes[i_use].insn, move->old_reg, move->new_reg);
852 df_insn_rescan (ps->g->nodes[i_use].insn);
857 /* Bump the SCHED_TIMEs of all nodes by AMOUNT. Set the values of
858 SCHED_ROW and SCHED_STAGE. Instruction scheduled on cycle AMOUNT
859 will move to cycle zero. */
860 static void
861 reset_sched_times (partial_schedule_ptr ps, int amount)
863 int row;
864 int ii = ps->ii;
865 ps_insn_ptr crr_insn;
867 for (row = 0; row < ii; row++)
868 for (crr_insn = ps->rows[row]; crr_insn; crr_insn = crr_insn->next_in_row)
870 int u = crr_insn->id;
871 int normalized_time = SCHED_TIME (u) - amount;
872 int new_min_cycle = PS_MIN_CYCLE (ps) - amount;
874 if (dump_file)
876 /* Print the scheduling times after the rotation. */
877 rtx_insn *insn = ps_rtl_insn (ps, u);
879 fprintf (dump_file, "crr_insn->node=%d (insn id %d), "
880 "crr_insn->cycle=%d, min_cycle=%d", u,
881 INSN_UID (insn), normalized_time, new_min_cycle);
882 if (JUMP_P (insn))
883 fprintf (dump_file, " (branch)");
884 fprintf (dump_file, "\n");
887 gcc_assert (SCHED_TIME (u) >= ps->min_cycle);
888 gcc_assert (SCHED_TIME (u) <= ps->max_cycle);
890 crr_insn->cycle = normalized_time;
891 update_node_sched_params (u, ii, normalized_time, new_min_cycle);
895 /* Permute the insns according to their order in PS, from row 0 to
896 row ii-1, and position them right before LAST. This schedules
897 the insns of the loop kernel. */
898 static void
899 permute_partial_schedule (partial_schedule_ptr ps, rtx_insn *last)
901 int ii = ps->ii;
902 int row;
903 ps_insn_ptr ps_ij;
905 for (row = 0; row < ii ; row++)
906 for (ps_ij = ps->rows[row]; ps_ij; ps_ij = ps_ij->next_in_row)
908 rtx_insn *insn = ps_rtl_insn (ps, ps_ij->id);
910 if (PREV_INSN (last) != insn)
912 if (ps_ij->id < ps->g->num_nodes)
913 reorder_insns_nobb (ps_first_note (ps, ps_ij->id), insn,
914 PREV_INSN (last));
915 else
916 add_insn_before (insn, last, NULL);
921 /* Set bitmaps TMP_FOLLOW and TMP_PRECEDE to MUST_FOLLOW and MUST_PRECEDE
922 respectively only if cycle C falls on the border of the scheduling
923 window boundaries marked by START and END cycles. STEP is the
924 direction of the window. */
925 static inline void
926 set_must_precede_follow (sbitmap *tmp_follow, sbitmap must_follow,
927 sbitmap *tmp_precede, sbitmap must_precede, int c,
928 int start, int end, int step)
930 *tmp_precede = NULL;
931 *tmp_follow = NULL;
933 if (c == start)
935 if (step == 1)
936 *tmp_precede = must_precede;
937 else /* step == -1. */
938 *tmp_follow = must_follow;
940 if (c == end - step)
942 if (step == 1)
943 *tmp_follow = must_follow;
944 else /* step == -1. */
945 *tmp_precede = must_precede;
950 /* Return True if the branch can be moved to row ii-1 while
951 normalizing the partial schedule PS to start from cycle zero and thus
952 optimize the SC. Otherwise return False. */
953 static bool
954 optimize_sc (partial_schedule_ptr ps, ddg_ptr g)
956 int amount = PS_MIN_CYCLE (ps);
957 sbitmap sched_nodes = sbitmap_alloc (g->num_nodes);
958 int start, end, step;
959 int ii = ps->ii;
960 bool ok = false;
961 int stage_count, stage_count_curr;
963 /* Compare the SC after normalization and SC after bringing the branch
964 to row ii-1. If they are equal just bail out. */
965 stage_count = calculate_stage_count (ps, amount);
966 stage_count_curr =
967 calculate_stage_count (ps, SCHED_TIME (g->closing_branch->cuid) - (ii - 1));
969 if (stage_count == stage_count_curr)
971 if (dump_file)
972 fprintf (dump_file, "SMS SC already optimized.\n");
974 ok = false;
975 goto clear;
978 if (dump_file)
980 fprintf (dump_file, "SMS Trying to optimize branch location\n");
981 fprintf (dump_file, "SMS partial schedule before trial:\n");
982 print_partial_schedule (ps, dump_file);
985 /* First, normalize the partial scheduling. */
986 reset_sched_times (ps, amount);
987 rotate_partial_schedule (ps, amount);
988 if (dump_file)
990 fprintf (dump_file,
991 "SMS partial schedule after normalization (ii, %d, SC %d):\n",
992 ii, stage_count);
993 print_partial_schedule (ps, dump_file);
996 if (SMODULO (SCHED_TIME (g->closing_branch->cuid), ii) == ii - 1)
998 ok = true;
999 goto clear;
1002 bitmap_ones (sched_nodes);
1004 /* Calculate the new placement of the branch. It should be in row
1005 ii-1 and fall into it's scheduling window. */
1006 if (get_sched_window (ps, g->closing_branch, sched_nodes, ii, &start,
1007 &step, &end) == 0)
1009 bool success;
1010 ps_insn_ptr next_ps_i;
1011 int branch_cycle = SCHED_TIME (g->closing_branch->cuid);
1012 int row = SMODULO (branch_cycle, ps->ii);
1013 int num_splits = 0;
1014 sbitmap must_precede, must_follow, tmp_precede, tmp_follow;
1015 int c;
1017 if (dump_file)
1018 fprintf (dump_file, "\nTrying to schedule node %d "
1019 "INSN = %d in (%d .. %d) step %d\n",
1020 g->closing_branch->cuid,
1021 (INSN_UID (g->closing_branch->insn)), start, end, step);
1023 gcc_assert ((step > 0 && start < end) || (step < 0 && start > end));
1024 if (step == 1)
1026 c = start + ii - SMODULO (start, ii) - 1;
1027 gcc_assert (c >= start);
1028 if (c >= end)
1030 ok = false;
1031 if (dump_file)
1032 fprintf (dump_file,
1033 "SMS failed to schedule branch at cycle: %d\n", c);
1034 goto clear;
1037 else
1039 c = start - SMODULO (start, ii) - 1;
1040 gcc_assert (c <= start);
1042 if (c <= end)
1044 if (dump_file)
1045 fprintf (dump_file,
1046 "SMS failed to schedule branch at cycle: %d\n", c);
1047 ok = false;
1048 goto clear;
1052 must_precede = sbitmap_alloc (g->num_nodes);
1053 must_follow = sbitmap_alloc (g->num_nodes);
1055 /* Try to schedule the branch is it's new cycle. */
1056 calculate_must_precede_follow (g->closing_branch, start, end,
1057 step, ii, sched_nodes,
1058 must_precede, must_follow);
1060 set_must_precede_follow (&tmp_follow, must_follow, &tmp_precede,
1061 must_precede, c, start, end, step);
1063 /* Find the element in the partial schedule related to the closing
1064 branch so we can remove it from it's current cycle. */
1065 for (next_ps_i = ps->rows[row];
1066 next_ps_i; next_ps_i = next_ps_i->next_in_row)
1067 if (next_ps_i->id == g->closing_branch->cuid)
1068 break;
1070 remove_node_from_ps (ps, next_ps_i);
1071 success =
1072 try_scheduling_node_in_cycle (ps, g->closing_branch->cuid, c,
1073 sched_nodes, &num_splits,
1074 tmp_precede, tmp_follow);
1075 gcc_assert (num_splits == 0);
1076 if (!success)
1078 if (dump_file)
1079 fprintf (dump_file,
1080 "SMS failed to schedule branch at cycle: %d, "
1081 "bringing it back to cycle %d\n", c, branch_cycle);
1083 /* The branch was failed to be placed in row ii - 1.
1084 Put it back in it's original place in the partial
1085 schedualing. */
1086 set_must_precede_follow (&tmp_follow, must_follow, &tmp_precede,
1087 must_precede, branch_cycle, start, end,
1088 step);
1089 success =
1090 try_scheduling_node_in_cycle (ps, g->closing_branch->cuid,
1091 branch_cycle, sched_nodes,
1092 &num_splits, tmp_precede,
1093 tmp_follow);
1094 gcc_assert (success && (num_splits == 0));
1095 ok = false;
1097 else
1099 /* The branch is placed in row ii - 1. */
1100 if (dump_file)
1101 fprintf (dump_file,
1102 "SMS success in moving branch to cycle %d\n", c);
1104 update_node_sched_params (g->closing_branch->cuid, ii, c,
1105 PS_MIN_CYCLE (ps));
1106 ok = true;
1109 free (must_precede);
1110 free (must_follow);
1113 clear:
1114 free (sched_nodes);
1115 return ok;
1118 static void
1119 duplicate_insns_of_cycles (partial_schedule_ptr ps, int from_stage,
1120 int to_stage, rtx count_reg)
1122 int row;
1123 ps_insn_ptr ps_ij;
1125 for (row = 0; row < ps->ii; row++)
1126 for (ps_ij = ps->rows[row]; ps_ij; ps_ij = ps_ij->next_in_row)
1128 int u = ps_ij->id;
1129 int first_u, last_u;
1130 rtx_insn *u_insn;
1132 /* Do not duplicate any insn which refers to count_reg as it
1133 belongs to the control part.
1134 The closing branch is scheduled as well and thus should
1135 be ignored.
1136 TODO: This should be done by analyzing the control part of
1137 the loop. */
1138 u_insn = ps_rtl_insn (ps, u);
1139 if (reg_mentioned_p (count_reg, u_insn)
1140 || JUMP_P (u_insn))
1141 continue;
1143 first_u = SCHED_STAGE (u);
1144 last_u = first_u + ps_num_consecutive_stages (ps, u) - 1;
1145 if (from_stage <= last_u && to_stage >= first_u)
1147 if (u < ps->g->num_nodes)
1148 duplicate_insn_chain (ps_first_note (ps, u), u_insn);
1149 else
1150 emit_insn (copy_rtx (PATTERN (u_insn)));
1156 /* Generate the instructions (including reg_moves) for prolog & epilog. */
1157 static void
1158 generate_prolog_epilog (partial_schedule_ptr ps, struct loop *loop,
1159 rtx count_reg, rtx count_init)
1161 int i;
1162 int last_stage = PS_STAGE_COUNT (ps) - 1;
1163 edge e;
1165 /* Generate the prolog, inserting its insns on the loop-entry edge. */
1166 start_sequence ();
1168 if (!count_init)
1170 /* Generate instructions at the beginning of the prolog to
1171 adjust the loop count by STAGE_COUNT. If loop count is constant
1172 (count_init), this constant is adjusted by STAGE_COUNT in
1173 generate_prolog_epilog function. */
1174 rtx sub_reg = NULL_RTX;
1176 sub_reg = expand_simple_binop (GET_MODE (count_reg), MINUS, count_reg,
1177 gen_int_mode (last_stage,
1178 GET_MODE (count_reg)),
1179 count_reg, 1, OPTAB_DIRECT);
1180 gcc_assert (REG_P (sub_reg));
1181 if (REGNO (sub_reg) != REGNO (count_reg))
1182 emit_move_insn (count_reg, sub_reg);
1185 for (i = 0; i < last_stage; i++)
1186 duplicate_insns_of_cycles (ps, 0, i, count_reg);
1188 /* Put the prolog on the entry edge. */
1189 e = loop_preheader_edge (loop);
1190 split_edge_and_insert (e, get_insns ());
1191 if (!flag_resched_modulo_sched)
1192 e->dest->flags |= BB_DISABLE_SCHEDULE;
1194 end_sequence ();
1196 /* Generate the epilog, inserting its insns on the loop-exit edge. */
1197 start_sequence ();
1199 for (i = 0; i < last_stage; i++)
1200 duplicate_insns_of_cycles (ps, i + 1, last_stage, count_reg);
1202 /* Put the epilogue on the exit edge. */
1203 gcc_assert (single_exit (loop));
1204 e = single_exit (loop);
1205 split_edge_and_insert (e, get_insns ());
1206 if (!flag_resched_modulo_sched)
1207 e->dest->flags |= BB_DISABLE_SCHEDULE;
1209 end_sequence ();
1212 /* Mark LOOP as software pipelined so the later
1213 scheduling passes don't touch it. */
1214 static void
1215 mark_loop_unsched (struct loop *loop)
1217 unsigned i;
1218 basic_block *bbs = get_loop_body (loop);
1220 for (i = 0; i < loop->num_nodes; i++)
1221 bbs[i]->flags |= BB_DISABLE_SCHEDULE;
1223 free (bbs);
1226 /* Return true if all the BBs of the loop are empty except the
1227 loop header. */
1228 static bool
1229 loop_single_full_bb_p (struct loop *loop)
1231 unsigned i;
1232 basic_block *bbs = get_loop_body (loop);
1234 for (i = 0; i < loop->num_nodes ; i++)
1236 rtx_insn *head, *tail;
1237 bool empty_bb = true;
1239 if (bbs[i] == loop->header)
1240 continue;
1242 /* Make sure that basic blocks other than the header
1243 have only notes labels or jumps. */
1244 get_ebb_head_tail (bbs[i], bbs[i], &head, &tail);
1245 for (; head != NEXT_INSN (tail); head = NEXT_INSN (head))
1247 if (NOTE_P (head) || LABEL_P (head)
1248 || (INSN_P (head) && (DEBUG_INSN_P (head) || JUMP_P (head))))
1249 continue;
1250 empty_bb = false;
1251 break;
1254 if (! empty_bb)
1256 free (bbs);
1257 return false;
1260 free (bbs);
1261 return true;
1264 /* Dump file:line from INSN's location info to dump_file. */
1266 static void
1267 dump_insn_location (rtx_insn *insn)
1269 if (dump_file && INSN_HAS_LOCATION (insn))
1271 expanded_location xloc = insn_location (insn);
1272 fprintf (dump_file, " %s:%i", xloc.file, xloc.line);
1276 /* A simple loop from SMS point of view; it is a loop that is composed of
1277 either a single basic block or two BBs - a header and a latch. */
1278 #define SIMPLE_SMS_LOOP_P(loop) ((loop->num_nodes < 3 ) \
1279 && (EDGE_COUNT (loop->latch->preds) == 1) \
1280 && (EDGE_COUNT (loop->latch->succs) == 1))
1282 /* Return true if the loop is in its canonical form and false if not.
1283 i.e. SIMPLE_SMS_LOOP_P and have one preheader block, and single exit. */
1284 static bool
1285 loop_canon_p (struct loop *loop)
1288 if (loop->inner || !loop_outer (loop))
1290 if (dump_file)
1291 fprintf (dump_file, "SMS loop inner or !loop_outer\n");
1292 return false;
1295 if (!single_exit (loop))
1297 if (dump_file)
1299 rtx_insn *insn = BB_END (loop->header);
1301 fprintf (dump_file, "SMS loop many exits");
1302 dump_insn_location (insn);
1303 fprintf (dump_file, "\n");
1305 return false;
1308 if (! SIMPLE_SMS_LOOP_P (loop) && ! loop_single_full_bb_p (loop))
1310 if (dump_file)
1312 rtx_insn *insn = BB_END (loop->header);
1314 fprintf (dump_file, "SMS loop many BBs.");
1315 dump_insn_location (insn);
1316 fprintf (dump_file, "\n");
1318 return false;
1321 return true;
1324 /* If there are more than one entry for the loop,
1325 make it one by splitting the first entry edge and
1326 redirecting the others to the new BB. */
1327 static void
1328 canon_loop (struct loop *loop)
1330 edge e;
1331 edge_iterator i;
1333 /* Avoid annoying special cases of edges going to exit
1334 block. */
1335 FOR_EACH_EDGE (e, i, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
1336 if ((e->flags & EDGE_FALLTHRU) && (EDGE_COUNT (e->src->succs) > 1))
1337 split_edge (e);
1339 if (loop->latch == loop->header
1340 || EDGE_COUNT (loop->latch->succs) > 1)
1342 FOR_EACH_EDGE (e, i, loop->header->preds)
1343 if (e->src == loop->latch)
1344 break;
1345 split_edge (e);
1349 /* Setup infos. */
1350 static void
1351 setup_sched_infos (void)
1353 memcpy (&sms_common_sched_info, &haifa_common_sched_info,
1354 sizeof (sms_common_sched_info));
1355 sms_common_sched_info.sched_pass_id = SCHED_SMS_PASS;
1356 common_sched_info = &sms_common_sched_info;
1358 sched_deps_info = &sms_sched_deps_info;
1359 current_sched_info = &sms_sched_info;
1362 /* Probability in % that the sms-ed loop rolls enough so that optimized
1363 version may be entered. Just a guess. */
1364 #define PROB_SMS_ENOUGH_ITERATIONS 80
1366 /* Used to calculate the upper bound of ii. */
1367 #define MAXII_FACTOR 2
1369 /* Main entry point, perform SMS scheduling on the loops of the function
1370 that consist of single basic blocks. */
1371 static void
1372 sms_schedule (void)
1374 rtx_insn *insn;
1375 ddg_ptr *g_arr, g;
1376 int * node_order;
1377 int maxii, max_asap;
1378 partial_schedule_ptr ps;
1379 basic_block bb = NULL;
1380 struct loop *loop;
1381 basic_block condition_bb = NULL;
1382 edge latch_edge;
1383 gcov_type trip_count = 0;
1385 loop_optimizer_init (LOOPS_HAVE_PREHEADERS
1386 | LOOPS_HAVE_RECORDED_EXITS);
1387 if (number_of_loops (cfun) <= 1)
1389 loop_optimizer_finalize ();
1390 return; /* There are no loops to schedule. */
1393 /* Initialize issue_rate. */
1394 if (targetm.sched.issue_rate)
1396 int temp = reload_completed;
1398 reload_completed = 1;
1399 issue_rate = targetm.sched.issue_rate ();
1400 reload_completed = temp;
1402 else
1403 issue_rate = 1;
1405 /* Initialize the scheduler. */
1406 setup_sched_infos ();
1407 haifa_sched_init ();
1409 /* Allocate memory to hold the DDG array one entry for each loop.
1410 We use loop->num as index into this array. */
1411 g_arr = XCNEWVEC (ddg_ptr, number_of_loops (cfun));
1413 if (dump_file)
1415 fprintf (dump_file, "\n\nSMS analysis phase\n");
1416 fprintf (dump_file, "===================\n\n");
1419 /* Build DDGs for all the relevant loops and hold them in G_ARR
1420 indexed by the loop index. */
1421 FOR_EACH_LOOP (loop, 0)
1423 rtx_insn *head, *tail;
1424 rtx count_reg;
1426 /* For debugging. */
1427 if (dbg_cnt (sms_sched_loop) == false)
1429 if (dump_file)
1430 fprintf (dump_file, "SMS reached max limit... \n");
1432 break;
1435 if (dump_file)
1437 rtx_insn *insn = BB_END (loop->header);
1439 fprintf (dump_file, "SMS loop num: %d", loop->num);
1440 dump_insn_location (insn);
1441 fprintf (dump_file, "\n");
1444 if (! loop_canon_p (loop))
1445 continue;
1447 if (! loop_single_full_bb_p (loop))
1449 if (dump_file)
1450 fprintf (dump_file, "SMS not loop_single_full_bb_p\n");
1451 continue;
1454 bb = loop->header;
1456 get_ebb_head_tail (bb, bb, &head, &tail);
1457 latch_edge = loop_latch_edge (loop);
1458 gcc_assert (single_exit (loop));
1459 if (single_exit (loop)->count)
1460 trip_count = latch_edge->count / single_exit (loop)->count;
1462 /* Perform SMS only on loops that their average count is above threshold. */
1464 if ( latch_edge->count
1465 && (latch_edge->count < single_exit (loop)->count * SMS_LOOP_AVERAGE_COUNT_THRESHOLD))
1467 if (dump_file)
1469 dump_insn_location (tail);
1470 fprintf (dump_file, "\nSMS single-bb-loop\n");
1471 if (profile_info && flag_branch_probabilities)
1473 fprintf (dump_file, "SMS loop-count ");
1474 fprintf (dump_file, "%" PRId64,
1475 (int64_t) bb->count);
1476 fprintf (dump_file, "\n");
1477 fprintf (dump_file, "SMS trip-count ");
1478 fprintf (dump_file, "%" PRId64,
1479 (int64_t) trip_count);
1480 fprintf (dump_file, "\n");
1481 fprintf (dump_file, "SMS profile-sum-max ");
1482 fprintf (dump_file, "%" PRId64,
1483 (int64_t) profile_info->sum_max);
1484 fprintf (dump_file, "\n");
1487 continue;
1490 /* Make sure this is a doloop. */
1491 if ( !(count_reg = doloop_register_get (head, tail)))
1493 if (dump_file)
1494 fprintf (dump_file, "SMS doloop_register_get failed\n");
1495 continue;
1498 /* Don't handle BBs with calls or barriers
1499 or !single_set with the exception of instructions that include
1500 count_reg---these instructions are part of the control part
1501 that do-loop recognizes.
1502 ??? Should handle insns defining subregs. */
1503 for (insn = head; insn != NEXT_INSN (tail); insn = NEXT_INSN (insn))
1505 rtx set;
1507 if (CALL_P (insn)
1508 || BARRIER_P (insn)
1509 || (NONDEBUG_INSN_P (insn) && !JUMP_P (insn)
1510 && !single_set (insn) && GET_CODE (PATTERN (insn)) != USE
1511 && !reg_mentioned_p (count_reg, insn))
1512 || (INSN_P (insn) && (set = single_set (insn))
1513 && GET_CODE (SET_DEST (set)) == SUBREG))
1514 break;
1517 if (insn != NEXT_INSN (tail))
1519 if (dump_file)
1521 if (CALL_P (insn))
1522 fprintf (dump_file, "SMS loop-with-call\n");
1523 else if (BARRIER_P (insn))
1524 fprintf (dump_file, "SMS loop-with-barrier\n");
1525 else if ((NONDEBUG_INSN_P (insn) && !JUMP_P (insn)
1526 && !single_set (insn) && GET_CODE (PATTERN (insn)) != USE))
1527 fprintf (dump_file, "SMS loop-with-not-single-set\n");
1528 else
1529 fprintf (dump_file, "SMS loop with subreg in lhs\n");
1530 print_rtl_single (dump_file, insn);
1533 continue;
1536 /* Always schedule the closing branch with the rest of the
1537 instructions. The branch is rotated to be in row ii-1 at the
1538 end of the scheduling procedure to make sure it's the last
1539 instruction in the iteration. */
1540 if (! (g = create_ddg (bb, 1)))
1542 if (dump_file)
1543 fprintf (dump_file, "SMS create_ddg failed\n");
1544 continue;
1547 g_arr[loop->num] = g;
1548 if (dump_file)
1549 fprintf (dump_file, "...OK\n");
1552 if (dump_file)
1554 fprintf (dump_file, "\nSMS transformation phase\n");
1555 fprintf (dump_file, "=========================\n\n");
1558 /* We don't want to perform SMS on new loops - created by versioning. */
1559 FOR_EACH_LOOP (loop, 0)
1561 rtx_insn *head, *tail;
1562 rtx count_reg;
1563 rtx_insn *count_init;
1564 int mii, rec_mii, stage_count, min_cycle;
1565 int64_t loop_count = 0;
1566 bool opt_sc_p;
1568 if (! (g = g_arr[loop->num]))
1569 continue;
1571 if (dump_file)
1573 rtx_insn *insn = BB_END (loop->header);
1575 fprintf (dump_file, "SMS loop num: %d", loop->num);
1576 dump_insn_location (insn);
1577 fprintf (dump_file, "\n");
1579 print_ddg (dump_file, g);
1582 get_ebb_head_tail (loop->header, loop->header, &head, &tail);
1584 latch_edge = loop_latch_edge (loop);
1585 gcc_assert (single_exit (loop));
1586 if (single_exit (loop)->count)
1587 trip_count = latch_edge->count / single_exit (loop)->count;
1589 if (dump_file)
1591 dump_insn_location (tail);
1592 fprintf (dump_file, "\nSMS single-bb-loop\n");
1593 if (profile_info && flag_branch_probabilities)
1595 fprintf (dump_file, "SMS loop-count ");
1596 fprintf (dump_file, "%" PRId64,
1597 (int64_t) bb->count);
1598 fprintf (dump_file, "\n");
1599 fprintf (dump_file, "SMS profile-sum-max ");
1600 fprintf (dump_file, "%" PRId64,
1601 (int64_t) profile_info->sum_max);
1602 fprintf (dump_file, "\n");
1604 fprintf (dump_file, "SMS doloop\n");
1605 fprintf (dump_file, "SMS built-ddg %d\n", g->num_nodes);
1606 fprintf (dump_file, "SMS num-loads %d\n", g->num_loads);
1607 fprintf (dump_file, "SMS num-stores %d\n", g->num_stores);
1611 /* In case of th loop have doloop register it gets special
1612 handling. */
1613 count_init = NULL;
1614 if ((count_reg = doloop_register_get (head, tail)))
1616 basic_block pre_header;
1618 pre_header = loop_preheader_edge (loop)->src;
1619 count_init = const_iteration_count (count_reg, pre_header,
1620 &loop_count);
1622 gcc_assert (count_reg);
1624 if (dump_file && count_init)
1626 fprintf (dump_file, "SMS const-doloop ");
1627 fprintf (dump_file, "%" PRId64,
1628 loop_count);
1629 fprintf (dump_file, "\n");
1632 node_order = XNEWVEC (int, g->num_nodes);
1634 mii = 1; /* Need to pass some estimate of mii. */
1635 rec_mii = sms_order_nodes (g, mii, node_order, &max_asap);
1636 mii = MAX (res_MII (g), rec_mii);
1637 maxii = MAX (max_asap, MAXII_FACTOR * mii);
1639 if (dump_file)
1640 fprintf (dump_file, "SMS iis %d %d %d (rec_mii, mii, maxii)\n",
1641 rec_mii, mii, maxii);
1643 for (;;)
1645 set_node_sched_params (g);
1647 stage_count = 0;
1648 opt_sc_p = false;
1649 ps = sms_schedule_by_order (g, mii, maxii, node_order);
1651 if (ps)
1653 /* Try to achieve optimized SC by normalizing the partial
1654 schedule (having the cycles start from cycle zero).
1655 The branch location must be placed in row ii-1 in the
1656 final scheduling. If failed, shift all instructions to
1657 position the branch in row ii-1. */
1658 opt_sc_p = optimize_sc (ps, g);
1659 if (opt_sc_p)
1660 stage_count = calculate_stage_count (ps, 0);
1661 else
1663 /* Bring the branch to cycle ii-1. */
1664 int amount = (SCHED_TIME (g->closing_branch->cuid)
1665 - (ps->ii - 1));
1667 if (dump_file)
1668 fprintf (dump_file, "SMS schedule branch at cycle ii-1\n");
1670 stage_count = calculate_stage_count (ps, amount);
1673 gcc_assert (stage_count >= 1);
1676 /* The default value of PARAM_SMS_MIN_SC is 2 as stage count of
1677 1 means that there is no interleaving between iterations thus
1678 we let the scheduling passes do the job in this case. */
1679 if (stage_count < PARAM_VALUE (PARAM_SMS_MIN_SC)
1680 || (count_init && (loop_count <= stage_count))
1681 || (flag_branch_probabilities && (trip_count <= stage_count)))
1683 if (dump_file)
1685 fprintf (dump_file, "SMS failed... \n");
1686 fprintf (dump_file, "SMS sched-failed (stage-count=%d,"
1687 " loop-count=", stage_count);
1688 fprintf (dump_file, "%" PRId64, loop_count);
1689 fprintf (dump_file, ", trip-count=");
1690 fprintf (dump_file, "%" PRId64, trip_count);
1691 fprintf (dump_file, ")\n");
1693 break;
1696 if (!opt_sc_p)
1698 /* Rotate the partial schedule to have the branch in row ii-1. */
1699 int amount = SCHED_TIME (g->closing_branch->cuid) - (ps->ii - 1);
1701 reset_sched_times (ps, amount);
1702 rotate_partial_schedule (ps, amount);
1705 set_columns_for_ps (ps);
1707 min_cycle = PS_MIN_CYCLE (ps) - SMODULO (PS_MIN_CYCLE (ps), ps->ii);
1708 if (!schedule_reg_moves (ps))
1710 mii = ps->ii + 1;
1711 free_partial_schedule (ps);
1712 continue;
1715 /* Moves that handle incoming values might have been added
1716 to a new first stage. Bump the stage count if so.
1718 ??? Perhaps we could consider rotating the schedule here
1719 instead? */
1720 if (PS_MIN_CYCLE (ps) < min_cycle)
1722 reset_sched_times (ps, 0);
1723 stage_count++;
1726 /* The stage count should now be correct without rotation. */
1727 gcc_checking_assert (stage_count == calculate_stage_count (ps, 0));
1728 PS_STAGE_COUNT (ps) = stage_count;
1730 canon_loop (loop);
1732 if (dump_file)
1734 dump_insn_location (tail);
1735 fprintf (dump_file, " SMS succeeded %d %d (with ii, sc)\n",
1736 ps->ii, stage_count);
1737 print_partial_schedule (ps, dump_file);
1740 /* case the BCT count is not known , Do loop-versioning */
1741 if (count_reg && ! count_init)
1743 rtx comp_rtx = gen_rtx_GT (VOIDmode, count_reg,
1744 gen_int_mode (stage_count,
1745 GET_MODE (count_reg)));
1746 unsigned prob = (PROB_SMS_ENOUGH_ITERATIONS
1747 * REG_BR_PROB_BASE) / 100;
1749 loop_version (loop, comp_rtx, &condition_bb,
1750 prob, prob, REG_BR_PROB_BASE - prob,
1751 true);
1754 /* Set new iteration count of loop kernel. */
1755 if (count_reg && count_init)
1756 SET_SRC (single_set (count_init)) = GEN_INT (loop_count
1757 - stage_count + 1);
1759 /* Now apply the scheduled kernel to the RTL of the loop. */
1760 permute_partial_schedule (ps, g->closing_branch->first_note);
1762 /* Mark this loop as software pipelined so the later
1763 scheduling passes don't touch it. */
1764 if (! flag_resched_modulo_sched)
1765 mark_loop_unsched (loop);
1767 /* The life-info is not valid any more. */
1768 df_set_bb_dirty (g->bb);
1770 apply_reg_moves (ps);
1771 if (dump_file)
1772 print_node_sched_params (dump_file, g->num_nodes, ps);
1773 /* Generate prolog and epilog. */
1774 generate_prolog_epilog (ps, loop, count_reg, count_init);
1775 break;
1778 free_partial_schedule (ps);
1779 node_sched_param_vec.release ();
1780 free (node_order);
1781 free_ddg (g);
1784 free (g_arr);
1786 /* Release scheduler data, needed until now because of DFA. */
1787 haifa_sched_finish ();
1788 loop_optimizer_finalize ();
1791 /* The SMS scheduling algorithm itself
1792 -----------------------------------
1793 Input: 'O' an ordered list of insns of a loop.
1794 Output: A scheduling of the loop - kernel, prolog, and epilogue.
1796 'Q' is the empty Set
1797 'PS' is the partial schedule; it holds the currently scheduled nodes with
1798 their cycle/slot.
1799 'PSP' previously scheduled predecessors.
1800 'PSS' previously scheduled successors.
1801 't(u)' the cycle where u is scheduled.
1802 'l(u)' is the latency of u.
1803 'd(v,u)' is the dependence distance from v to u.
1804 'ASAP(u)' the earliest time at which u could be scheduled as computed in
1805 the node ordering phase.
1806 'check_hardware_resources_conflicts(u, PS, c)'
1807 run a trace around cycle/slot through DFA model
1808 to check resource conflicts involving instruction u
1809 at cycle c given the partial schedule PS.
1810 'add_to_partial_schedule_at_time(u, PS, c)'
1811 Add the node/instruction u to the partial schedule
1812 PS at time c.
1813 'calculate_register_pressure(PS)'
1814 Given a schedule of instructions, calculate the register
1815 pressure it implies. One implementation could be the
1816 maximum number of overlapping live ranges.
1817 'maxRP' The maximum allowed register pressure, it is usually derived from the number
1818 registers available in the hardware.
1820 1. II = MII.
1821 2. PS = empty list
1822 3. for each node u in O in pre-computed order
1823 4. if (PSP(u) != Q && PSS(u) == Q) then
1824 5. Early_start(u) = max ( t(v) + l(v) - d(v,u)*II ) over all every v in PSP(u).
1825 6. start = Early_start; end = Early_start + II - 1; step = 1
1826 11. else if (PSP(u) == Q && PSS(u) != Q) then
1827 12. Late_start(u) = min ( t(v) - l(v) + d(v,u)*II ) over all every v in PSS(u).
1828 13. start = Late_start; end = Late_start - II + 1; step = -1
1829 14. else if (PSP(u) != Q && PSS(u) != Q) then
1830 15. Early_start(u) = max ( t(v) + l(v) - d(v,u)*II ) over all every v in PSP(u).
1831 16. Late_start(u) = min ( t(v) - l(v) + d(v,u)*II ) over all every v in PSS(u).
1832 17. start = Early_start;
1833 18. end = min(Early_start + II - 1 , Late_start);
1834 19. step = 1
1835 20. else "if (PSP(u) == Q && PSS(u) == Q)"
1836 21. start = ASAP(u); end = start + II - 1; step = 1
1837 22. endif
1839 23. success = false
1840 24. for (c = start ; c != end ; c += step)
1841 25. if check_hardware_resources_conflicts(u, PS, c) then
1842 26. add_to_partial_schedule_at_time(u, PS, c)
1843 27. success = true
1844 28. break
1845 29. endif
1846 30. endfor
1847 31. if (success == false) then
1848 32. II = II + 1
1849 33. if (II > maxII) then
1850 34. finish - failed to schedule
1851 35. endif
1852 36. goto 2.
1853 37. endif
1854 38. endfor
1855 39. if (calculate_register_pressure(PS) > maxRP) then
1856 40. goto 32.
1857 41. endif
1858 42. compute epilogue & prologue
1859 43. finish - succeeded to schedule
1861 ??? The algorithm restricts the scheduling window to II cycles.
1862 In rare cases, it may be better to allow windows of II+1 cycles.
1863 The window would then start and end on the same row, but with
1864 different "must precede" and "must follow" requirements. */
1866 /* A limit on the number of cycles that resource conflicts can span. ??? Should
1867 be provided by DFA, and be dependent on the type of insn scheduled. Currently
1868 set to 0 to save compile time. */
1869 #define DFA_HISTORY SMS_DFA_HISTORY
1871 /* A threshold for the number of repeated unsuccessful attempts to insert
1872 an empty row, before we flush the partial schedule and start over. */
1873 #define MAX_SPLIT_NUM 10
1874 /* Given the partial schedule PS, this function calculates and returns the
1875 cycles in which we can schedule the node with the given index I.
1876 NOTE: Here we do the backtracking in SMS, in some special cases. We have
1877 noticed that there are several cases in which we fail to SMS the loop
1878 because the sched window of a node is empty due to tight data-deps. In
1879 such cases we want to unschedule some of the predecessors/successors
1880 until we get non-empty scheduling window. It returns -1 if the
1881 scheduling window is empty and zero otherwise. */
1883 static int
1884 get_sched_window (partial_schedule_ptr ps, ddg_node_ptr u_node,
1885 sbitmap sched_nodes, int ii, int *start_p, int *step_p,
1886 int *end_p)
1888 int start, step, end;
1889 int early_start, late_start;
1890 ddg_edge_ptr e;
1891 sbitmap psp = sbitmap_alloc (ps->g->num_nodes);
1892 sbitmap pss = sbitmap_alloc (ps->g->num_nodes);
1893 sbitmap u_node_preds = NODE_PREDECESSORS (u_node);
1894 sbitmap u_node_succs = NODE_SUCCESSORS (u_node);
1895 int psp_not_empty;
1896 int pss_not_empty;
1897 int count_preds;
1898 int count_succs;
1900 /* 1. compute sched window for u (start, end, step). */
1901 bitmap_clear (psp);
1902 bitmap_clear (pss);
1903 psp_not_empty = bitmap_and (psp, u_node_preds, sched_nodes);
1904 pss_not_empty = bitmap_and (pss, u_node_succs, sched_nodes);
1906 /* We first compute a forward range (start <= end), then decide whether
1907 to reverse it. */
1908 early_start = INT_MIN;
1909 late_start = INT_MAX;
1910 start = INT_MIN;
1911 end = INT_MAX;
1912 step = 1;
1914 count_preds = 0;
1915 count_succs = 0;
1917 if (dump_file && (psp_not_empty || pss_not_empty))
1919 fprintf (dump_file, "\nAnalyzing dependencies for node %d (INSN %d)"
1920 "; ii = %d\n\n", u_node->cuid, INSN_UID (u_node->insn), ii);
1921 fprintf (dump_file, "%11s %11s %11s %11s %5s\n",
1922 "start", "early start", "late start", "end", "time");
1923 fprintf (dump_file, "=========== =========== =========== ==========="
1924 " =====\n");
1926 /* Calculate early_start and limit end. Both bounds are inclusive. */
1927 if (psp_not_empty)
1928 for (e = u_node->in; e != 0; e = e->next_in)
1930 int v = e->src->cuid;
1932 if (bitmap_bit_p (sched_nodes, v))
1934 int p_st = SCHED_TIME (v);
1935 int earliest = p_st + e->latency - (e->distance * ii);
1936 int latest = (e->data_type == MEM_DEP ? p_st + ii - 1 : INT_MAX);
1938 if (dump_file)
1940 fprintf (dump_file, "%11s %11d %11s %11d %5d",
1941 "", earliest, "", latest, p_st);
1942 print_ddg_edge (dump_file, e);
1943 fprintf (dump_file, "\n");
1946 early_start = MAX (early_start, earliest);
1947 end = MIN (end, latest);
1949 if (e->type == TRUE_DEP && e->data_type == REG_DEP)
1950 count_preds++;
1954 /* Calculate late_start and limit start. Both bounds are inclusive. */
1955 if (pss_not_empty)
1956 for (e = u_node->out; e != 0; e = e->next_out)
1958 int v = e->dest->cuid;
1960 if (bitmap_bit_p (sched_nodes, v))
1962 int s_st = SCHED_TIME (v);
1963 int earliest = (e->data_type == MEM_DEP ? s_st - ii + 1 : INT_MIN);
1964 int latest = s_st - e->latency + (e->distance * ii);
1966 if (dump_file)
1968 fprintf (dump_file, "%11d %11s %11d %11s %5d",
1969 earliest, "", latest, "", s_st);
1970 print_ddg_edge (dump_file, e);
1971 fprintf (dump_file, "\n");
1974 start = MAX (start, earliest);
1975 late_start = MIN (late_start, latest);
1977 if (e->type == TRUE_DEP && e->data_type == REG_DEP)
1978 count_succs++;
1982 if (dump_file && (psp_not_empty || pss_not_empty))
1984 fprintf (dump_file, "----------- ----------- ----------- -----------"
1985 " -----\n");
1986 fprintf (dump_file, "%11d %11d %11d %11d %5s %s\n",
1987 start, early_start, late_start, end, "",
1988 "(max, max, min, min)");
1991 /* Get a target scheduling window no bigger than ii. */
1992 if (early_start == INT_MIN && late_start == INT_MAX)
1993 early_start = NODE_ASAP (u_node);
1994 else if (early_start == INT_MIN)
1995 early_start = late_start - (ii - 1);
1996 late_start = MIN (late_start, early_start + (ii - 1));
1998 /* Apply memory dependence limits. */
1999 start = MAX (start, early_start);
2000 end = MIN (end, late_start);
2002 if (dump_file && (psp_not_empty || pss_not_empty))
2003 fprintf (dump_file, "%11s %11d %11d %11s %5s final window\n",
2004 "", start, end, "", "");
2006 /* If there are at least as many successors as predecessors, schedule the
2007 node close to its successors. */
2008 if (pss_not_empty && count_succs >= count_preds)
2010 int tmp = end;
2011 end = start;
2012 start = tmp;
2013 step = -1;
2016 /* Now that we've finalized the window, make END an exclusive rather
2017 than an inclusive bound. */
2018 end += step;
2020 *start_p = start;
2021 *step_p = step;
2022 *end_p = end;
2023 sbitmap_free (psp);
2024 sbitmap_free (pss);
2026 if ((start >= end && step == 1) || (start <= end && step == -1))
2028 if (dump_file)
2029 fprintf (dump_file, "\nEmpty window: start=%d, end=%d, step=%d\n",
2030 start, end, step);
2031 return -1;
2034 return 0;
2037 /* Calculate MUST_PRECEDE/MUST_FOLLOW bitmaps of U_NODE; which is the
2038 node currently been scheduled. At the end of the calculation
2039 MUST_PRECEDE/MUST_FOLLOW contains all predecessors/successors of
2040 U_NODE which are (1) already scheduled in the first/last row of
2041 U_NODE's scheduling window, (2) whose dependence inequality with U
2042 becomes an equality when U is scheduled in this same row, and (3)
2043 whose dependence latency is zero.
2045 The first and last rows are calculated using the following parameters:
2046 START/END rows - The cycles that begins/ends the traversal on the window;
2047 searching for an empty cycle to schedule U_NODE.
2048 STEP - The direction in which we traverse the window.
2049 II - The initiation interval. */
2051 static void
2052 calculate_must_precede_follow (ddg_node_ptr u_node, int start, int end,
2053 int step, int ii, sbitmap sched_nodes,
2054 sbitmap must_precede, sbitmap must_follow)
2056 ddg_edge_ptr e;
2057 int first_cycle_in_window, last_cycle_in_window;
2059 gcc_assert (must_precede && must_follow);
2061 /* Consider the following scheduling window:
2062 {first_cycle_in_window, first_cycle_in_window+1, ...,
2063 last_cycle_in_window}. If step is 1 then the following will be
2064 the order we traverse the window: {start=first_cycle_in_window,
2065 first_cycle_in_window+1, ..., end=last_cycle_in_window+1},
2066 or {start=last_cycle_in_window, last_cycle_in_window-1, ...,
2067 end=first_cycle_in_window-1} if step is -1. */
2068 first_cycle_in_window = (step == 1) ? start : end - step;
2069 last_cycle_in_window = (step == 1) ? end - step : start;
2071 bitmap_clear (must_precede);
2072 bitmap_clear (must_follow);
2074 if (dump_file)
2075 fprintf (dump_file, "\nmust_precede: ");
2077 /* Instead of checking if:
2078 (SMODULO (SCHED_TIME (e->src), ii) == first_row_in_window)
2079 && ((SCHED_TIME (e->src) + e->latency - (e->distance * ii)) ==
2080 first_cycle_in_window)
2081 && e->latency == 0
2082 we use the fact that latency is non-negative:
2083 SCHED_TIME (e->src) - (e->distance * ii) <=
2084 SCHED_TIME (e->src) + e->latency - (e->distance * ii)) <=
2085 first_cycle_in_window
2086 and check only if
2087 SCHED_TIME (e->src) - (e->distance * ii) == first_cycle_in_window */
2088 for (e = u_node->in; e != 0; e = e->next_in)
2089 if (bitmap_bit_p (sched_nodes, e->src->cuid)
2090 && ((SCHED_TIME (e->src->cuid) - (e->distance * ii)) ==
2091 first_cycle_in_window))
2093 if (dump_file)
2094 fprintf (dump_file, "%d ", e->src->cuid);
2096 bitmap_set_bit (must_precede, e->src->cuid);
2099 if (dump_file)
2100 fprintf (dump_file, "\nmust_follow: ");
2102 /* Instead of checking if:
2103 (SMODULO (SCHED_TIME (e->dest), ii) == last_row_in_window)
2104 && ((SCHED_TIME (e->dest) - e->latency + (e->distance * ii)) ==
2105 last_cycle_in_window)
2106 && e->latency == 0
2107 we use the fact that latency is non-negative:
2108 SCHED_TIME (e->dest) + (e->distance * ii) >=
2109 SCHED_TIME (e->dest) - e->latency + (e->distance * ii)) >=
2110 last_cycle_in_window
2111 and check only if
2112 SCHED_TIME (e->dest) + (e->distance * ii) == last_cycle_in_window */
2113 for (e = u_node->out; e != 0; e = e->next_out)
2114 if (bitmap_bit_p (sched_nodes, e->dest->cuid)
2115 && ((SCHED_TIME (e->dest->cuid) + (e->distance * ii)) ==
2116 last_cycle_in_window))
2118 if (dump_file)
2119 fprintf (dump_file, "%d ", e->dest->cuid);
2121 bitmap_set_bit (must_follow, e->dest->cuid);
2124 if (dump_file)
2125 fprintf (dump_file, "\n");
2128 /* Return 1 if U_NODE can be scheduled in CYCLE. Use the following
2129 parameters to decide if that's possible:
2130 PS - The partial schedule.
2131 U - The serial number of U_NODE.
2132 NUM_SPLITS - The number of row splits made so far.
2133 MUST_PRECEDE - The nodes that must precede U_NODE. (only valid at
2134 the first row of the scheduling window)
2135 MUST_FOLLOW - The nodes that must follow U_NODE. (only valid at the
2136 last row of the scheduling window) */
2138 static bool
2139 try_scheduling_node_in_cycle (partial_schedule_ptr ps,
2140 int u, int cycle, sbitmap sched_nodes,
2141 int *num_splits, sbitmap must_precede,
2142 sbitmap must_follow)
2144 ps_insn_ptr psi;
2145 bool success = 0;
2147 verify_partial_schedule (ps, sched_nodes);
2148 psi = ps_add_node_check_conflicts (ps, u, cycle, must_precede, must_follow);
2149 if (psi)
2151 SCHED_TIME (u) = cycle;
2152 bitmap_set_bit (sched_nodes, u);
2153 success = 1;
2154 *num_splits = 0;
2155 if (dump_file)
2156 fprintf (dump_file, "Scheduled w/o split in %d\n", cycle);
2160 return success;
2163 /* This function implements the scheduling algorithm for SMS according to the
2164 above algorithm. */
2165 static partial_schedule_ptr
2166 sms_schedule_by_order (ddg_ptr g, int mii, int maxii, int *nodes_order)
2168 int ii = mii;
2169 int i, c, success, num_splits = 0;
2170 int flush_and_start_over = true;
2171 int num_nodes = g->num_nodes;
2172 int start, end, step; /* Place together into one struct? */
2173 sbitmap sched_nodes = sbitmap_alloc (num_nodes);
2174 sbitmap must_precede = sbitmap_alloc (num_nodes);
2175 sbitmap must_follow = sbitmap_alloc (num_nodes);
2176 sbitmap tobe_scheduled = sbitmap_alloc (num_nodes);
2178 partial_schedule_ptr ps = create_partial_schedule (ii, g, DFA_HISTORY);
2180 bitmap_ones (tobe_scheduled);
2181 bitmap_clear (sched_nodes);
2183 while (flush_and_start_over && (ii < maxii))
2186 if (dump_file)
2187 fprintf (dump_file, "Starting with ii=%d\n", ii);
2188 flush_and_start_over = false;
2189 bitmap_clear (sched_nodes);
2191 for (i = 0; i < num_nodes; i++)
2193 int u = nodes_order[i];
2194 ddg_node_ptr u_node = &ps->g->nodes[u];
2195 rtx_insn *insn = u_node->insn;
2197 if (!NONDEBUG_INSN_P (insn))
2199 bitmap_clear_bit (tobe_scheduled, u);
2200 continue;
2203 if (bitmap_bit_p (sched_nodes, u))
2204 continue;
2206 /* Try to get non-empty scheduling window. */
2207 success = 0;
2208 if (get_sched_window (ps, u_node, sched_nodes, ii, &start,
2209 &step, &end) == 0)
2211 if (dump_file)
2212 fprintf (dump_file, "\nTrying to schedule node %d "
2213 "INSN = %d in (%d .. %d) step %d\n", u, (INSN_UID
2214 (g->nodes[u].insn)), start, end, step);
2216 gcc_assert ((step > 0 && start < end)
2217 || (step < 0 && start > end));
2219 calculate_must_precede_follow (u_node, start, end, step, ii,
2220 sched_nodes, must_precede,
2221 must_follow);
2223 for (c = start; c != end; c += step)
2225 sbitmap tmp_precede, tmp_follow;
2227 set_must_precede_follow (&tmp_follow, must_follow,
2228 &tmp_precede, must_precede,
2229 c, start, end, step);
2230 success =
2231 try_scheduling_node_in_cycle (ps, u, c,
2232 sched_nodes,
2233 &num_splits, tmp_precede,
2234 tmp_follow);
2235 if (success)
2236 break;
2239 verify_partial_schedule (ps, sched_nodes);
2241 if (!success)
2243 int split_row;
2245 if (ii++ == maxii)
2246 break;
2248 if (num_splits >= MAX_SPLIT_NUM)
2250 num_splits = 0;
2251 flush_and_start_over = true;
2252 verify_partial_schedule (ps, sched_nodes);
2253 reset_partial_schedule (ps, ii);
2254 verify_partial_schedule (ps, sched_nodes);
2255 break;
2258 num_splits++;
2259 /* The scheduling window is exclusive of 'end'
2260 whereas compute_split_window() expects an inclusive,
2261 ordered range. */
2262 if (step == 1)
2263 split_row = compute_split_row (sched_nodes, start, end - 1,
2264 ps->ii, u_node);
2265 else
2266 split_row = compute_split_row (sched_nodes, end + 1, start,
2267 ps->ii, u_node);
2269 ps_insert_empty_row (ps, split_row, sched_nodes);
2270 i--; /* Go back and retry node i. */
2272 if (dump_file)
2273 fprintf (dump_file, "num_splits=%d\n", num_splits);
2276 /* ??? If (success), check register pressure estimates. */
2277 } /* Continue with next node. */
2278 } /* While flush_and_start_over. */
2279 if (ii >= maxii)
2281 free_partial_schedule (ps);
2282 ps = NULL;
2284 else
2285 gcc_assert (bitmap_equal_p (tobe_scheduled, sched_nodes));
2287 sbitmap_free (sched_nodes);
2288 sbitmap_free (must_precede);
2289 sbitmap_free (must_follow);
2290 sbitmap_free (tobe_scheduled);
2292 return ps;
2295 /* This function inserts a new empty row into PS at the position
2296 according to SPLITROW, keeping all already scheduled instructions
2297 intact and updating their SCHED_TIME and cycle accordingly. */
2298 static void
2299 ps_insert_empty_row (partial_schedule_ptr ps, int split_row,
2300 sbitmap sched_nodes)
2302 ps_insn_ptr crr_insn;
2303 ps_insn_ptr *rows_new;
2304 int ii = ps->ii;
2305 int new_ii = ii + 1;
2306 int row;
2307 int *rows_length_new;
2309 verify_partial_schedule (ps, sched_nodes);
2311 /* We normalize sched_time and rotate ps to have only non-negative sched
2312 times, for simplicity of updating cycles after inserting new row. */
2313 split_row -= ps->min_cycle;
2314 split_row = SMODULO (split_row, ii);
2315 if (dump_file)
2316 fprintf (dump_file, "split_row=%d\n", split_row);
2318 reset_sched_times (ps, PS_MIN_CYCLE (ps));
2319 rotate_partial_schedule (ps, PS_MIN_CYCLE (ps));
2321 rows_new = (ps_insn_ptr *) xcalloc (new_ii, sizeof (ps_insn_ptr));
2322 rows_length_new = (int *) xcalloc (new_ii, sizeof (int));
2323 for (row = 0; row < split_row; row++)
2325 rows_new[row] = ps->rows[row];
2326 rows_length_new[row] = ps->rows_length[row];
2327 ps->rows[row] = NULL;
2328 for (crr_insn = rows_new[row];
2329 crr_insn; crr_insn = crr_insn->next_in_row)
2331 int u = crr_insn->id;
2332 int new_time = SCHED_TIME (u) + (SCHED_TIME (u) / ii);
2334 SCHED_TIME (u) = new_time;
2335 crr_insn->cycle = new_time;
2336 SCHED_ROW (u) = new_time % new_ii;
2337 SCHED_STAGE (u) = new_time / new_ii;
2342 rows_new[split_row] = NULL;
2344 for (row = split_row; row < ii; row++)
2346 rows_new[row + 1] = ps->rows[row];
2347 rows_length_new[row + 1] = ps->rows_length[row];
2348 ps->rows[row] = NULL;
2349 for (crr_insn = rows_new[row + 1];
2350 crr_insn; crr_insn = crr_insn->next_in_row)
2352 int u = crr_insn->id;
2353 int new_time = SCHED_TIME (u) + (SCHED_TIME (u) / ii) + 1;
2355 SCHED_TIME (u) = new_time;
2356 crr_insn->cycle = new_time;
2357 SCHED_ROW (u) = new_time % new_ii;
2358 SCHED_STAGE (u) = new_time / new_ii;
2362 /* Updating ps. */
2363 ps->min_cycle = ps->min_cycle + ps->min_cycle / ii
2364 + (SMODULO (ps->min_cycle, ii) >= split_row ? 1 : 0);
2365 ps->max_cycle = ps->max_cycle + ps->max_cycle / ii
2366 + (SMODULO (ps->max_cycle, ii) >= split_row ? 1 : 0);
2367 free (ps->rows);
2368 ps->rows = rows_new;
2369 free (ps->rows_length);
2370 ps->rows_length = rows_length_new;
2371 ps->ii = new_ii;
2372 gcc_assert (ps->min_cycle >= 0);
2374 verify_partial_schedule (ps, sched_nodes);
2376 if (dump_file)
2377 fprintf (dump_file, "min_cycle=%d, max_cycle=%d\n", ps->min_cycle,
2378 ps->max_cycle);
2381 /* Given U_NODE which is the node that failed to be scheduled; LOW and
2382 UP which are the boundaries of it's scheduling window; compute using
2383 SCHED_NODES and II a row in the partial schedule that can be split
2384 which will separate a critical predecessor from a critical successor
2385 thereby expanding the window, and return it. */
2386 static int
2387 compute_split_row (sbitmap sched_nodes, int low, int up, int ii,
2388 ddg_node_ptr u_node)
2390 ddg_edge_ptr e;
2391 int lower = INT_MIN, upper = INT_MAX;
2392 int crit_pred = -1;
2393 int crit_succ = -1;
2394 int crit_cycle;
2396 for (e = u_node->in; e != 0; e = e->next_in)
2398 int v = e->src->cuid;
2400 if (bitmap_bit_p (sched_nodes, v)
2401 && (low == SCHED_TIME (v) + e->latency - (e->distance * ii)))
2402 if (SCHED_TIME (v) > lower)
2404 crit_pred = v;
2405 lower = SCHED_TIME (v);
2409 if (crit_pred >= 0)
2411 crit_cycle = SCHED_TIME (crit_pred) + 1;
2412 return SMODULO (crit_cycle, ii);
2415 for (e = u_node->out; e != 0; e = e->next_out)
2417 int v = e->dest->cuid;
2419 if (bitmap_bit_p (sched_nodes, v)
2420 && (up == SCHED_TIME (v) - e->latency + (e->distance * ii)))
2421 if (SCHED_TIME (v) < upper)
2423 crit_succ = v;
2424 upper = SCHED_TIME (v);
2428 if (crit_succ >= 0)
2430 crit_cycle = SCHED_TIME (crit_succ);
2431 return SMODULO (crit_cycle, ii);
2434 if (dump_file)
2435 fprintf (dump_file, "Both crit_pred and crit_succ are NULL\n");
2437 return SMODULO ((low + up + 1) / 2, ii);
2440 static void
2441 verify_partial_schedule (partial_schedule_ptr ps, sbitmap sched_nodes)
2443 int row;
2444 ps_insn_ptr crr_insn;
2446 for (row = 0; row < ps->ii; row++)
2448 int length = 0;
2450 for (crr_insn = ps->rows[row]; crr_insn; crr_insn = crr_insn->next_in_row)
2452 int u = crr_insn->id;
2454 length++;
2455 gcc_assert (bitmap_bit_p (sched_nodes, u));
2456 /* ??? Test also that all nodes of sched_nodes are in ps, perhaps by
2457 popcount (sched_nodes) == number of insns in ps. */
2458 gcc_assert (SCHED_TIME (u) >= ps->min_cycle);
2459 gcc_assert (SCHED_TIME (u) <= ps->max_cycle);
2462 gcc_assert (ps->rows_length[row] == length);
2467 /* This page implements the algorithm for ordering the nodes of a DDG
2468 for modulo scheduling, activated through the
2469 "int sms_order_nodes (ddg_ptr, int mii, int * result)" API. */
2471 #define ORDER_PARAMS(x) ((struct node_order_params *) (x)->aux.info)
2472 #define ASAP(x) (ORDER_PARAMS ((x))->asap)
2473 #define ALAP(x) (ORDER_PARAMS ((x))->alap)
2474 #define HEIGHT(x) (ORDER_PARAMS ((x))->height)
2475 #define MOB(x) (ALAP ((x)) - ASAP ((x)))
2476 #define DEPTH(x) (ASAP ((x)))
2478 typedef struct node_order_params * nopa;
2480 static void order_nodes_of_sccs (ddg_all_sccs_ptr, int * result);
2481 static int order_nodes_in_scc (ddg_ptr, sbitmap, sbitmap, int*, int);
2482 static nopa calculate_order_params (ddg_ptr, int, int *);
2483 static int find_max_asap (ddg_ptr, sbitmap);
2484 static int find_max_hv_min_mob (ddg_ptr, sbitmap);
2485 static int find_max_dv_min_mob (ddg_ptr, sbitmap);
2487 enum sms_direction {BOTTOMUP, TOPDOWN};
2489 struct node_order_params
2491 int asap;
2492 int alap;
2493 int height;
2496 /* Check if NODE_ORDER contains a permutation of 0 .. NUM_NODES-1. */
2497 static void
2498 check_nodes_order (int *node_order, int num_nodes)
2500 int i;
2501 sbitmap tmp = sbitmap_alloc (num_nodes);
2503 bitmap_clear (tmp);
2505 if (dump_file)
2506 fprintf (dump_file, "SMS final nodes order: \n");
2508 for (i = 0; i < num_nodes; i++)
2510 int u = node_order[i];
2512 if (dump_file)
2513 fprintf (dump_file, "%d ", u);
2514 gcc_assert (u < num_nodes && u >= 0 && !bitmap_bit_p (tmp, u));
2516 bitmap_set_bit (tmp, u);
2519 if (dump_file)
2520 fprintf (dump_file, "\n");
2522 sbitmap_free (tmp);
2525 /* Order the nodes of G for scheduling and pass the result in
2526 NODE_ORDER. Also set aux.count of each node to ASAP.
2527 Put maximal ASAP to PMAX_ASAP. Return the recMII for the given DDG. */
2528 static int
2529 sms_order_nodes (ddg_ptr g, int mii, int * node_order, int *pmax_asap)
2531 int i;
2532 int rec_mii = 0;
2533 ddg_all_sccs_ptr sccs = create_ddg_all_sccs (g);
2535 nopa nops = calculate_order_params (g, mii, pmax_asap);
2537 if (dump_file)
2538 print_sccs (dump_file, sccs, g);
2540 order_nodes_of_sccs (sccs, node_order);
2542 if (sccs->num_sccs > 0)
2543 /* First SCC has the largest recurrence_length. */
2544 rec_mii = sccs->sccs[0]->recurrence_length;
2546 /* Save ASAP before destroying node_order_params. */
2547 for (i = 0; i < g->num_nodes; i++)
2549 ddg_node_ptr v = &g->nodes[i];
2550 v->aux.count = ASAP (v);
2553 free (nops);
2554 free_ddg_all_sccs (sccs);
2555 check_nodes_order (node_order, g->num_nodes);
2557 return rec_mii;
2560 static void
2561 order_nodes_of_sccs (ddg_all_sccs_ptr all_sccs, int * node_order)
2563 int i, pos = 0;
2564 ddg_ptr g = all_sccs->ddg;
2565 int num_nodes = g->num_nodes;
2566 sbitmap prev_sccs = sbitmap_alloc (num_nodes);
2567 sbitmap on_path = sbitmap_alloc (num_nodes);
2568 sbitmap tmp = sbitmap_alloc (num_nodes);
2569 sbitmap ones = sbitmap_alloc (num_nodes);
2571 bitmap_clear (prev_sccs);
2572 bitmap_ones (ones);
2574 /* Perform the node ordering starting from the SCC with the highest recMII.
2575 For each SCC order the nodes according to their ASAP/ALAP/HEIGHT etc. */
2576 for (i = 0; i < all_sccs->num_sccs; i++)
2578 ddg_scc_ptr scc = all_sccs->sccs[i];
2580 /* Add nodes on paths from previous SCCs to the current SCC. */
2581 find_nodes_on_paths (on_path, g, prev_sccs, scc->nodes);
2582 bitmap_ior (tmp, scc->nodes, on_path);
2584 /* Add nodes on paths from the current SCC to previous SCCs. */
2585 find_nodes_on_paths (on_path, g, scc->nodes, prev_sccs);
2586 bitmap_ior (tmp, tmp, on_path);
2588 /* Remove nodes of previous SCCs from current extended SCC. */
2589 bitmap_and_compl (tmp, tmp, prev_sccs);
2591 pos = order_nodes_in_scc (g, prev_sccs, tmp, node_order, pos);
2592 /* Above call to order_nodes_in_scc updated prev_sccs |= tmp. */
2595 /* Handle the remaining nodes that do not belong to any scc. Each call
2596 to order_nodes_in_scc handles a single connected component. */
2597 while (pos < g->num_nodes)
2599 bitmap_and_compl (tmp, ones, prev_sccs);
2600 pos = order_nodes_in_scc (g, prev_sccs, tmp, node_order, pos);
2602 sbitmap_free (prev_sccs);
2603 sbitmap_free (on_path);
2604 sbitmap_free (tmp);
2605 sbitmap_free (ones);
2608 /* MII is needed if we consider backarcs (that do not close recursive cycles). */
2609 static struct node_order_params *
2610 calculate_order_params (ddg_ptr g, int mii ATTRIBUTE_UNUSED, int *pmax_asap)
2612 int u;
2613 int max_asap;
2614 int num_nodes = g->num_nodes;
2615 ddg_edge_ptr e;
2616 /* Allocate a place to hold ordering params for each node in the DDG. */
2617 nopa node_order_params_arr;
2619 /* Initialize of ASAP/ALAP/HEIGHT to zero. */
2620 node_order_params_arr = (nopa) xcalloc (num_nodes,
2621 sizeof (struct node_order_params));
2623 /* Set the aux pointer of each node to point to its order_params structure. */
2624 for (u = 0; u < num_nodes; u++)
2625 g->nodes[u].aux.info = &node_order_params_arr[u];
2627 /* Disregarding a backarc from each recursive cycle to obtain a DAG,
2628 calculate ASAP, ALAP, mobility, distance, and height for each node
2629 in the dependence (direct acyclic) graph. */
2631 /* We assume that the nodes in the array are in topological order. */
2633 max_asap = 0;
2634 for (u = 0; u < num_nodes; u++)
2636 ddg_node_ptr u_node = &g->nodes[u];
2638 ASAP (u_node) = 0;
2639 for (e = u_node->in; e; e = e->next_in)
2640 if (e->distance == 0)
2641 ASAP (u_node) = MAX (ASAP (u_node),
2642 ASAP (e->src) + e->latency);
2643 max_asap = MAX (max_asap, ASAP (u_node));
2646 for (u = num_nodes - 1; u > -1; u--)
2648 ddg_node_ptr u_node = &g->nodes[u];
2650 ALAP (u_node) = max_asap;
2651 HEIGHT (u_node) = 0;
2652 for (e = u_node->out; e; e = e->next_out)
2653 if (e->distance == 0)
2655 ALAP (u_node) = MIN (ALAP (u_node),
2656 ALAP (e->dest) - e->latency);
2657 HEIGHT (u_node) = MAX (HEIGHT (u_node),
2658 HEIGHT (e->dest) + e->latency);
2661 if (dump_file)
2663 fprintf (dump_file, "\nOrder params\n");
2664 for (u = 0; u < num_nodes; u++)
2666 ddg_node_ptr u_node = &g->nodes[u];
2668 fprintf (dump_file, "node %d, ASAP: %d, ALAP: %d, HEIGHT: %d\n", u,
2669 ASAP (u_node), ALAP (u_node), HEIGHT (u_node));
2673 *pmax_asap = max_asap;
2674 return node_order_params_arr;
2677 static int
2678 find_max_asap (ddg_ptr g, sbitmap nodes)
2680 unsigned int u = 0;
2681 int max_asap = -1;
2682 int result = -1;
2683 sbitmap_iterator sbi;
2685 EXECUTE_IF_SET_IN_BITMAP (nodes, 0, u, sbi)
2687 ddg_node_ptr u_node = &g->nodes[u];
2689 if (max_asap < ASAP (u_node))
2691 max_asap = ASAP (u_node);
2692 result = u;
2695 return result;
2698 static int
2699 find_max_hv_min_mob (ddg_ptr g, sbitmap nodes)
2701 unsigned int u = 0;
2702 int max_hv = -1;
2703 int min_mob = INT_MAX;
2704 int result = -1;
2705 sbitmap_iterator sbi;
2707 EXECUTE_IF_SET_IN_BITMAP (nodes, 0, u, sbi)
2709 ddg_node_ptr u_node = &g->nodes[u];
2711 if (max_hv < HEIGHT (u_node))
2713 max_hv = HEIGHT (u_node);
2714 min_mob = MOB (u_node);
2715 result = u;
2717 else if ((max_hv == HEIGHT (u_node))
2718 && (min_mob > MOB (u_node)))
2720 min_mob = MOB (u_node);
2721 result = u;
2724 return result;
2727 static int
2728 find_max_dv_min_mob (ddg_ptr g, sbitmap nodes)
2730 unsigned int u = 0;
2731 int max_dv = -1;
2732 int min_mob = INT_MAX;
2733 int result = -1;
2734 sbitmap_iterator sbi;
2736 EXECUTE_IF_SET_IN_BITMAP (nodes, 0, u, sbi)
2738 ddg_node_ptr u_node = &g->nodes[u];
2740 if (max_dv < DEPTH (u_node))
2742 max_dv = DEPTH (u_node);
2743 min_mob = MOB (u_node);
2744 result = u;
2746 else if ((max_dv == DEPTH (u_node))
2747 && (min_mob > MOB (u_node)))
2749 min_mob = MOB (u_node);
2750 result = u;
2753 return result;
2756 /* Places the nodes of SCC into the NODE_ORDER array starting
2757 at position POS, according to the SMS ordering algorithm.
2758 NODES_ORDERED (in&out parameter) holds the bitset of all nodes in
2759 the NODE_ORDER array, starting from position zero. */
2760 static int
2761 order_nodes_in_scc (ddg_ptr g, sbitmap nodes_ordered, sbitmap scc,
2762 int * node_order, int pos)
2764 enum sms_direction dir;
2765 int num_nodes = g->num_nodes;
2766 sbitmap workset = sbitmap_alloc (num_nodes);
2767 sbitmap tmp = sbitmap_alloc (num_nodes);
2768 sbitmap zero_bitmap = sbitmap_alloc (num_nodes);
2769 sbitmap predecessors = sbitmap_alloc (num_nodes);
2770 sbitmap successors = sbitmap_alloc (num_nodes);
2772 bitmap_clear (predecessors);
2773 find_predecessors (predecessors, g, nodes_ordered);
2775 bitmap_clear (successors);
2776 find_successors (successors, g, nodes_ordered);
2778 bitmap_clear (tmp);
2779 if (bitmap_and (tmp, predecessors, scc))
2781 bitmap_copy (workset, tmp);
2782 dir = BOTTOMUP;
2784 else if (bitmap_and (tmp, successors, scc))
2786 bitmap_copy (workset, tmp);
2787 dir = TOPDOWN;
2789 else
2791 int u;
2793 bitmap_clear (workset);
2794 if ((u = find_max_asap (g, scc)) >= 0)
2795 bitmap_set_bit (workset, u);
2796 dir = BOTTOMUP;
2799 bitmap_clear (zero_bitmap);
2800 while (!bitmap_equal_p (workset, zero_bitmap))
2802 int v;
2803 ddg_node_ptr v_node;
2804 sbitmap v_node_preds;
2805 sbitmap v_node_succs;
2807 if (dir == TOPDOWN)
2809 while (!bitmap_equal_p (workset, zero_bitmap))
2811 v = find_max_hv_min_mob (g, workset);
2812 v_node = &g->nodes[v];
2813 node_order[pos++] = v;
2814 v_node_succs = NODE_SUCCESSORS (v_node);
2815 bitmap_and (tmp, v_node_succs, scc);
2817 /* Don't consider the already ordered successors again. */
2818 bitmap_and_compl (tmp, tmp, nodes_ordered);
2819 bitmap_ior (workset, workset, tmp);
2820 bitmap_clear_bit (workset, v);
2821 bitmap_set_bit (nodes_ordered, v);
2823 dir = BOTTOMUP;
2824 bitmap_clear (predecessors);
2825 find_predecessors (predecessors, g, nodes_ordered);
2826 bitmap_and (workset, predecessors, scc);
2828 else
2830 while (!bitmap_equal_p (workset, zero_bitmap))
2832 v = find_max_dv_min_mob (g, workset);
2833 v_node = &g->nodes[v];
2834 node_order[pos++] = v;
2835 v_node_preds = NODE_PREDECESSORS (v_node);
2836 bitmap_and (tmp, v_node_preds, scc);
2838 /* Don't consider the already ordered predecessors again. */
2839 bitmap_and_compl (tmp, tmp, nodes_ordered);
2840 bitmap_ior (workset, workset, tmp);
2841 bitmap_clear_bit (workset, v);
2842 bitmap_set_bit (nodes_ordered, v);
2844 dir = TOPDOWN;
2845 bitmap_clear (successors);
2846 find_successors (successors, g, nodes_ordered);
2847 bitmap_and (workset, successors, scc);
2850 sbitmap_free (tmp);
2851 sbitmap_free (workset);
2852 sbitmap_free (zero_bitmap);
2853 sbitmap_free (predecessors);
2854 sbitmap_free (successors);
2855 return pos;
2859 /* This page contains functions for manipulating partial-schedules during
2860 modulo scheduling. */
2862 /* Create a partial schedule and allocate a memory to hold II rows. */
2864 static partial_schedule_ptr
2865 create_partial_schedule (int ii, ddg_ptr g, int history)
2867 partial_schedule_ptr ps = XNEW (struct partial_schedule);
2868 ps->rows = (ps_insn_ptr *) xcalloc (ii, sizeof (ps_insn_ptr));
2869 ps->rows_length = (int *) xcalloc (ii, sizeof (int));
2870 ps->reg_moves.create (0);
2871 ps->ii = ii;
2872 ps->history = history;
2873 ps->min_cycle = INT_MAX;
2874 ps->max_cycle = INT_MIN;
2875 ps->g = g;
2877 return ps;
2880 /* Free the PS_INSNs in rows array of the given partial schedule.
2881 ??? Consider caching the PS_INSN's. */
2882 static void
2883 free_ps_insns (partial_schedule_ptr ps)
2885 int i;
2887 for (i = 0; i < ps->ii; i++)
2889 while (ps->rows[i])
2891 ps_insn_ptr ps_insn = ps->rows[i]->next_in_row;
2893 free (ps->rows[i]);
2894 ps->rows[i] = ps_insn;
2896 ps->rows[i] = NULL;
2900 /* Free all the memory allocated to the partial schedule. */
2902 static void
2903 free_partial_schedule (partial_schedule_ptr ps)
2905 ps_reg_move_info *move;
2906 unsigned int i;
2908 if (!ps)
2909 return;
2911 FOR_EACH_VEC_ELT (ps->reg_moves, i, move)
2912 sbitmap_free (move->uses);
2913 ps->reg_moves.release ();
2915 free_ps_insns (ps);
2916 free (ps->rows);
2917 free (ps->rows_length);
2918 free (ps);
2921 /* Clear the rows array with its PS_INSNs, and create a new one with
2922 NEW_II rows. */
2924 static void
2925 reset_partial_schedule (partial_schedule_ptr ps, int new_ii)
2927 if (!ps)
2928 return;
2929 free_ps_insns (ps);
2930 if (new_ii == ps->ii)
2931 return;
2932 ps->rows = (ps_insn_ptr *) xrealloc (ps->rows, new_ii
2933 * sizeof (ps_insn_ptr));
2934 memset (ps->rows, 0, new_ii * sizeof (ps_insn_ptr));
2935 ps->rows_length = (int *) xrealloc (ps->rows_length, new_ii * sizeof (int));
2936 memset (ps->rows_length, 0, new_ii * sizeof (int));
2937 ps->ii = new_ii;
2938 ps->min_cycle = INT_MAX;
2939 ps->max_cycle = INT_MIN;
2942 /* Prints the partial schedule as an ii rows array, for each rows
2943 print the ids of the insns in it. */
2944 void
2945 print_partial_schedule (partial_schedule_ptr ps, FILE *dump)
2947 int i;
2949 for (i = 0; i < ps->ii; i++)
2951 ps_insn_ptr ps_i = ps->rows[i];
2953 fprintf (dump, "\n[ROW %d ]: ", i);
2954 while (ps_i)
2956 rtx_insn *insn = ps_rtl_insn (ps, ps_i->id);
2958 if (JUMP_P (insn))
2959 fprintf (dump, "%d (branch), ", INSN_UID (insn));
2960 else
2961 fprintf (dump, "%d, ", INSN_UID (insn));
2963 ps_i = ps_i->next_in_row;
2968 /* Creates an object of PS_INSN and initializes it to the given parameters. */
2969 static ps_insn_ptr
2970 create_ps_insn (int id, int cycle)
2972 ps_insn_ptr ps_i = XNEW (struct ps_insn);
2974 ps_i->id = id;
2975 ps_i->next_in_row = NULL;
2976 ps_i->prev_in_row = NULL;
2977 ps_i->cycle = cycle;
2979 return ps_i;
2983 /* Removes the given PS_INSN from the partial schedule. */
2984 static void
2985 remove_node_from_ps (partial_schedule_ptr ps, ps_insn_ptr ps_i)
2987 int row;
2989 gcc_assert (ps && ps_i);
2991 row = SMODULO (ps_i->cycle, ps->ii);
2992 if (! ps_i->prev_in_row)
2994 gcc_assert (ps_i == ps->rows[row]);
2995 ps->rows[row] = ps_i->next_in_row;
2996 if (ps->rows[row])
2997 ps->rows[row]->prev_in_row = NULL;
2999 else
3001 ps_i->prev_in_row->next_in_row = ps_i->next_in_row;
3002 if (ps_i->next_in_row)
3003 ps_i->next_in_row->prev_in_row = ps_i->prev_in_row;
3006 ps->rows_length[row] -= 1;
3007 free (ps_i);
3008 return;
3011 /* Unlike what literature describes for modulo scheduling (which focuses
3012 on VLIW machines) the order of the instructions inside a cycle is
3013 important. Given the bitmaps MUST_FOLLOW and MUST_PRECEDE we know
3014 where the current instruction should go relative to the already
3015 scheduled instructions in the given cycle. Go over these
3016 instructions and find the first possible column to put it in. */
3017 static bool
3018 ps_insn_find_column (partial_schedule_ptr ps, ps_insn_ptr ps_i,
3019 sbitmap must_precede, sbitmap must_follow)
3021 ps_insn_ptr next_ps_i;
3022 ps_insn_ptr first_must_follow = NULL;
3023 ps_insn_ptr last_must_precede = NULL;
3024 ps_insn_ptr last_in_row = NULL;
3025 int row;
3027 if (! ps_i)
3028 return false;
3030 row = SMODULO (ps_i->cycle, ps->ii);
3032 /* Find the first must follow and the last must precede
3033 and insert the node immediately after the must precede
3034 but make sure that it there is no must follow after it. */
3035 for (next_ps_i = ps->rows[row];
3036 next_ps_i;
3037 next_ps_i = next_ps_i->next_in_row)
3039 if (must_follow
3040 && bitmap_bit_p (must_follow, next_ps_i->id)
3041 && ! first_must_follow)
3042 first_must_follow = next_ps_i;
3043 if (must_precede && bitmap_bit_p (must_precede, next_ps_i->id))
3045 /* If we have already met a node that must follow, then
3046 there is no possible column. */
3047 if (first_must_follow)
3048 return false;
3049 else
3050 last_must_precede = next_ps_i;
3052 /* The closing branch must be the last in the row. */
3053 if (must_precede
3054 && bitmap_bit_p (must_precede, next_ps_i->id)
3055 && JUMP_P (ps_rtl_insn (ps, next_ps_i->id)))
3056 return false;
3058 last_in_row = next_ps_i;
3061 /* The closing branch is scheduled as well. Make sure there is no
3062 dependent instruction after it as the branch should be the last
3063 instruction in the row. */
3064 if (JUMP_P (ps_rtl_insn (ps, ps_i->id)))
3066 if (first_must_follow)
3067 return false;
3068 if (last_in_row)
3070 /* Make the branch the last in the row. New instructions
3071 will be inserted at the beginning of the row or after the
3072 last must_precede instruction thus the branch is guaranteed
3073 to remain the last instruction in the row. */
3074 last_in_row->next_in_row = ps_i;
3075 ps_i->prev_in_row = last_in_row;
3076 ps_i->next_in_row = NULL;
3078 else
3079 ps->rows[row] = ps_i;
3080 return true;
3083 /* Now insert the node after INSERT_AFTER_PSI. */
3085 if (! last_must_precede)
3087 ps_i->next_in_row = ps->rows[row];
3088 ps_i->prev_in_row = NULL;
3089 if (ps_i->next_in_row)
3090 ps_i->next_in_row->prev_in_row = ps_i;
3091 ps->rows[row] = ps_i;
3093 else
3095 ps_i->next_in_row = last_must_precede->next_in_row;
3096 last_must_precede->next_in_row = ps_i;
3097 ps_i->prev_in_row = last_must_precede;
3098 if (ps_i->next_in_row)
3099 ps_i->next_in_row->prev_in_row = ps_i;
3102 return true;
3105 /* Advances the PS_INSN one column in its current row; returns false
3106 in failure and true in success. Bit N is set in MUST_FOLLOW if
3107 the node with cuid N must be come after the node pointed to by
3108 PS_I when scheduled in the same cycle. */
3109 static int
3110 ps_insn_advance_column (partial_schedule_ptr ps, ps_insn_ptr ps_i,
3111 sbitmap must_follow)
3113 ps_insn_ptr prev, next;
3114 int row;
3116 if (!ps || !ps_i)
3117 return false;
3119 row = SMODULO (ps_i->cycle, ps->ii);
3121 if (! ps_i->next_in_row)
3122 return false;
3124 /* Check if next_in_row is dependent on ps_i, both having same sched
3125 times (typically ANTI_DEP). If so, ps_i cannot skip over it. */
3126 if (must_follow && bitmap_bit_p (must_follow, ps_i->next_in_row->id))
3127 return false;
3129 /* Advance PS_I over its next_in_row in the doubly linked list. */
3130 prev = ps_i->prev_in_row;
3131 next = ps_i->next_in_row;
3133 if (ps_i == ps->rows[row])
3134 ps->rows[row] = next;
3136 ps_i->next_in_row = next->next_in_row;
3138 if (next->next_in_row)
3139 next->next_in_row->prev_in_row = ps_i;
3141 next->next_in_row = ps_i;
3142 ps_i->prev_in_row = next;
3144 next->prev_in_row = prev;
3145 if (prev)
3146 prev->next_in_row = next;
3148 return true;
3151 /* Inserts a DDG_NODE to the given partial schedule at the given cycle.
3152 Returns 0 if this is not possible and a PS_INSN otherwise. Bit N is
3153 set in MUST_PRECEDE/MUST_FOLLOW if the node with cuid N must be come
3154 before/after (respectively) the node pointed to by PS_I when scheduled
3155 in the same cycle. */
3156 static ps_insn_ptr
3157 add_node_to_ps (partial_schedule_ptr ps, int id, int cycle,
3158 sbitmap must_precede, sbitmap must_follow)
3160 ps_insn_ptr ps_i;
3161 int row = SMODULO (cycle, ps->ii);
3163 if (ps->rows_length[row] >= issue_rate)
3164 return NULL;
3166 ps_i = create_ps_insn (id, cycle);
3168 /* Finds and inserts PS_I according to MUST_FOLLOW and
3169 MUST_PRECEDE. */
3170 if (! ps_insn_find_column (ps, ps_i, must_precede, must_follow))
3172 free (ps_i);
3173 return NULL;
3176 ps->rows_length[row] += 1;
3177 return ps_i;
3180 /* Advance time one cycle. Assumes DFA is being used. */
3181 static void
3182 advance_one_cycle (void)
3184 if (targetm.sched.dfa_pre_cycle_insn)
3185 state_transition (curr_state,
3186 targetm.sched.dfa_pre_cycle_insn ());
3188 state_transition (curr_state, NULL);
3190 if (targetm.sched.dfa_post_cycle_insn)
3191 state_transition (curr_state,
3192 targetm.sched.dfa_post_cycle_insn ());
3197 /* Checks if PS has resource conflicts according to DFA, starting from
3198 FROM cycle to TO cycle; returns true if there are conflicts and false
3199 if there are no conflicts. Assumes DFA is being used. */
3200 static int
3201 ps_has_conflicts (partial_schedule_ptr ps, int from, int to)
3203 int cycle;
3205 state_reset (curr_state);
3207 for (cycle = from; cycle <= to; cycle++)
3209 ps_insn_ptr crr_insn;
3210 /* Holds the remaining issue slots in the current row. */
3211 int can_issue_more = issue_rate;
3213 /* Walk through the DFA for the current row. */
3214 for (crr_insn = ps->rows[SMODULO (cycle, ps->ii)];
3215 crr_insn;
3216 crr_insn = crr_insn->next_in_row)
3218 rtx_insn *insn = ps_rtl_insn (ps, crr_insn->id);
3220 if (!NONDEBUG_INSN_P (insn))
3221 continue;
3223 /* Check if there is room for the current insn. */
3224 if (!can_issue_more || state_dead_lock_p (curr_state))
3225 return true;
3227 /* Update the DFA state and return with failure if the DFA found
3228 resource conflicts. */
3229 if (state_transition (curr_state, insn) >= 0)
3230 return true;
3232 if (targetm.sched.variable_issue)
3233 can_issue_more =
3234 targetm.sched.variable_issue (sched_dump, sched_verbose,
3235 insn, can_issue_more);
3236 /* A naked CLOBBER or USE generates no instruction, so don't
3237 let them consume issue slots. */
3238 else if (GET_CODE (PATTERN (insn)) != USE
3239 && GET_CODE (PATTERN (insn)) != CLOBBER)
3240 can_issue_more--;
3243 /* Advance the DFA to the next cycle. */
3244 advance_one_cycle ();
3246 return false;
3249 /* Checks if the given node causes resource conflicts when added to PS at
3250 cycle C. If not the node is added to PS and returned; otherwise zero
3251 is returned. Bit N is set in MUST_PRECEDE/MUST_FOLLOW if the node with
3252 cuid N must be come before/after (respectively) the node pointed to by
3253 PS_I when scheduled in the same cycle. */
3254 ps_insn_ptr
3255 ps_add_node_check_conflicts (partial_schedule_ptr ps, int n,
3256 int c, sbitmap must_precede,
3257 sbitmap must_follow)
3259 int has_conflicts = 0;
3260 ps_insn_ptr ps_i;
3262 /* First add the node to the PS, if this succeeds check for
3263 conflicts, trying different issue slots in the same row. */
3264 if (! (ps_i = add_node_to_ps (ps, n, c, must_precede, must_follow)))
3265 return NULL; /* Failed to insert the node at the given cycle. */
3267 has_conflicts = ps_has_conflicts (ps, c, c)
3268 || (ps->history > 0
3269 && ps_has_conflicts (ps,
3270 c - ps->history,
3271 c + ps->history));
3273 /* Try different issue slots to find one that the given node can be
3274 scheduled in without conflicts. */
3275 while (has_conflicts)
3277 if (! ps_insn_advance_column (ps, ps_i, must_follow))
3278 break;
3279 has_conflicts = ps_has_conflicts (ps, c, c)
3280 || (ps->history > 0
3281 && ps_has_conflicts (ps,
3282 c - ps->history,
3283 c + ps->history));
3286 if (has_conflicts)
3288 remove_node_from_ps (ps, ps_i);
3289 return NULL;
3292 ps->min_cycle = MIN (ps->min_cycle, c);
3293 ps->max_cycle = MAX (ps->max_cycle, c);
3294 return ps_i;
3297 /* Calculate the stage count of the partial schedule PS. The calculation
3298 takes into account the rotation amount passed in ROTATION_AMOUNT. */
3300 calculate_stage_count (partial_schedule_ptr ps, int rotation_amount)
3302 int new_min_cycle = PS_MIN_CYCLE (ps) - rotation_amount;
3303 int new_max_cycle = PS_MAX_CYCLE (ps) - rotation_amount;
3304 int stage_count = CALC_STAGE_COUNT (-1, new_min_cycle, ps->ii);
3306 /* The calculation of stage count is done adding the number of stages
3307 before cycle zero and after cycle zero. */
3308 stage_count += CALC_STAGE_COUNT (new_max_cycle, 0, ps->ii);
3310 return stage_count;
3313 /* Rotate the rows of PS such that insns scheduled at time
3314 START_CYCLE will appear in row 0. Updates max/min_cycles. */
3315 void
3316 rotate_partial_schedule (partial_schedule_ptr ps, int start_cycle)
3318 int i, row, backward_rotates;
3319 int last_row = ps->ii - 1;
3321 if (start_cycle == 0)
3322 return;
3324 backward_rotates = SMODULO (start_cycle, ps->ii);
3326 /* Revisit later and optimize this into a single loop. */
3327 for (i = 0; i < backward_rotates; i++)
3329 ps_insn_ptr first_row = ps->rows[0];
3330 int first_row_length = ps->rows_length[0];
3332 for (row = 0; row < last_row; row++)
3334 ps->rows[row] = ps->rows[row + 1];
3335 ps->rows_length[row] = ps->rows_length[row + 1];
3338 ps->rows[last_row] = first_row;
3339 ps->rows_length[last_row] = first_row_length;
3342 ps->max_cycle -= start_cycle;
3343 ps->min_cycle -= start_cycle;
3346 #endif /* INSN_SCHEDULING */
3348 /* Run instruction scheduler. */
3349 /* Perform SMS module scheduling. */
3351 namespace {
3353 const pass_data pass_data_sms =
3355 RTL_PASS, /* type */
3356 "sms", /* name */
3357 OPTGROUP_NONE, /* optinfo_flags */
3358 TV_SMS, /* tv_id */
3359 0, /* properties_required */
3360 0, /* properties_provided */
3361 0, /* properties_destroyed */
3362 0, /* todo_flags_start */
3363 TODO_df_finish, /* todo_flags_finish */
3366 class pass_sms : public rtl_opt_pass
3368 public:
3369 pass_sms (gcc::context *ctxt)
3370 : rtl_opt_pass (pass_data_sms, ctxt)
3373 /* opt_pass methods: */
3374 virtual bool gate (function *)
3376 return (optimize > 0 && flag_modulo_sched);
3379 virtual unsigned int execute (function *);
3381 }; // class pass_sms
3383 unsigned int
3384 pass_sms::execute (function *fun ATTRIBUTE_UNUSED)
3386 #ifdef INSN_SCHEDULING
3387 basic_block bb;
3389 /* Collect loop information to be used in SMS. */
3390 cfg_layout_initialize (0);
3391 sms_schedule ();
3393 /* Update the life information, because we add pseudos. */
3394 max_regno = max_reg_num ();
3396 /* Finalize layout changes. */
3397 FOR_EACH_BB_FN (bb, fun)
3398 if (bb->next_bb != EXIT_BLOCK_PTR_FOR_FN (fun))
3399 bb->aux = bb->next_bb;
3400 free_dominance_info (CDI_DOMINATORS);
3401 cfg_layout_finalize ();
3402 #endif /* INSN_SCHEDULING */
3403 return 0;
3406 } // anon namespace
3408 rtl_opt_pass *
3409 make_pass_sms (gcc::context *ctxt)
3411 return new pass_sms (ctxt);