* sv.po: Update.
[official-gcc.git] / gcc / modulo-sched.c
blobd9596c33e10da75a9e353513b32a8276f96e32b6
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 "backend.h"
26 #include "cfghooks.h"
27 #include "tree.h"
28 #include "rtl.h"
29 #include "df.h"
30 #include "diagnostic-core.h"
31 #include "tm_p.h"
32 #include "regs.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 "cfgrtl.h"
40 #include "sched-int.h"
41 #include "target.h"
42 #include "cfgloop.h"
43 #include "alias.h"
44 #include "insn-codes.h"
45 #include "optabs.h"
46 #include "expmed.h"
47 #include "dojump.h"
48 #include "explow.h"
49 #include "calls.h"
50 #include "emit-rtl.h"
51 #include "varasm.h"
52 #include "stmt.h"
53 #include "expr.h"
54 #include "params.h"
55 #include "gcov-io.h"
56 #include "ddg.h"
57 #include "tree-pass.h"
58 #include "dbgcnt.h"
59 #include "loop-unroll.h"
61 #ifdef INSN_SCHEDULING
63 /* This file contains the implementation of the Swing Modulo Scheduler,
64 described in the following references:
65 [1] J. Llosa, A. Gonzalez, E. Ayguade, M. Valero., and J. Eckhardt.
66 Lifetime--sensitive modulo scheduling in a production environment.
67 IEEE Trans. on Comps., 50(3), March 2001
68 [2] J. Llosa, A. Gonzalez, E. Ayguade, and M. Valero.
69 Swing Modulo Scheduling: A Lifetime Sensitive Approach.
70 PACT '96 , pages 80-87, October 1996 (Boston - Massachusetts - USA).
72 The basic structure is:
73 1. Build a data-dependence graph (DDG) for each loop.
74 2. Use the DDG to order the insns of a loop (not in topological order
75 necessarily, but rather) trying to place each insn after all its
76 predecessors _or_ after all its successors.
77 3. Compute MII: a lower bound on the number of cycles to schedule the loop.
78 4. Use the ordering to perform list-scheduling of the loop:
79 1. Set II = MII. We will try to schedule the loop within II cycles.
80 2. Try to schedule the insns one by one according to the ordering.
81 For each insn compute an interval of cycles by considering already-
82 scheduled preds and succs (and associated latencies); try to place
83 the insn in the cycles of this window checking for potential
84 resource conflicts (using the DFA interface).
85 Note: this is different from the cycle-scheduling of schedule_insns;
86 here the insns are not scheduled monotonically top-down (nor bottom-
87 up).
88 3. If failed in scheduling all insns - bump II++ and try again, unless
89 II reaches an upper bound MaxII, in which case report failure.
90 5. If we succeeded in scheduling the loop within II cycles, we now
91 generate prolog and epilog, decrease the counter of the loop, and
92 perform modulo variable expansion for live ranges that span more than
93 II cycles (i.e. use register copies to prevent a def from overwriting
94 itself before reaching the use).
96 SMS works with countable loops (1) whose control part can be easily
97 decoupled from the rest of the loop and (2) whose loop count can
98 be easily adjusted. This is because we peel a constant number of
99 iterations into a prologue and epilogue for which we want to avoid
100 emitting the control part, and a kernel which is to iterate that
101 constant number of iterations less than the original loop. So the
102 control part should be a set of insns clearly identified and having
103 its own iv, not otherwise used in the loop (at-least for now), which
104 initializes a register before the loop to the number of iterations.
105 Currently SMS relies on the do-loop pattern to recognize such loops,
106 where (1) the control part comprises of all insns defining and/or
107 using a certain 'count' register and (2) the loop count can be
108 adjusted by modifying this register prior to the loop.
109 TODO: Rely on cfgloop analysis instead. */
111 /* This page defines partial-schedule structures and functions for
112 modulo scheduling. */
114 typedef struct partial_schedule *partial_schedule_ptr;
115 typedef struct ps_insn *ps_insn_ptr;
117 /* The minimum (absolute) cycle that a node of ps was scheduled in. */
118 #define PS_MIN_CYCLE(ps) (((partial_schedule_ptr)(ps))->min_cycle)
120 /* The maximum (absolute) cycle that a node of ps was scheduled in. */
121 #define PS_MAX_CYCLE(ps) (((partial_schedule_ptr)(ps))->max_cycle)
123 /* Perform signed modulo, always returning a non-negative value. */
124 #define SMODULO(x,y) ((x) % (y) < 0 ? ((x) % (y) + (y)) : (x) % (y))
126 /* The number of different iterations the nodes in ps span, assuming
127 the stage boundaries are placed efficiently. */
128 #define CALC_STAGE_COUNT(max_cycle,min_cycle,ii) ((max_cycle - min_cycle \
129 + 1 + ii - 1) / ii)
130 /* The stage count of ps. */
131 #define PS_STAGE_COUNT(ps) (((partial_schedule_ptr)(ps))->stage_count)
133 /* A single instruction in the partial schedule. */
134 struct ps_insn
136 /* Identifies the instruction to be scheduled. Values smaller than
137 the ddg's num_nodes refer directly to ddg nodes. A value of
138 X - num_nodes refers to register move X. */
139 int id;
141 /* The (absolute) cycle in which the PS instruction is scheduled.
142 Same as SCHED_TIME (node). */
143 int cycle;
145 /* The next/prev PS_INSN in the same row. */
146 ps_insn_ptr next_in_row,
147 prev_in_row;
151 /* Information about a register move that has been added to a partial
152 schedule. */
153 struct ps_reg_move_info
155 /* The source of the move is defined by the ps_insn with id DEF.
156 The destination is used by the ps_insns with the ids in USES. */
157 int def;
158 sbitmap uses;
160 /* The original form of USES' instructions used OLD_REG, but they
161 should now use NEW_REG. */
162 rtx old_reg;
163 rtx new_reg;
165 /* The number of consecutive stages that the move occupies. */
166 int num_consecutive_stages;
168 /* An instruction that sets NEW_REG to the correct value. The first
169 move associated with DEF will have an rhs of OLD_REG; later moves
170 use the result of the previous move. */
171 rtx_insn *insn;
174 typedef struct ps_reg_move_info ps_reg_move_info;
176 /* Holds the partial schedule as an array of II rows. Each entry of the
177 array points to a linked list of PS_INSNs, which represents the
178 instructions that are scheduled for that row. */
179 struct partial_schedule
181 int ii; /* Number of rows in the partial schedule. */
182 int history; /* Threshold for conflict checking using DFA. */
184 /* rows[i] points to linked list of insns scheduled in row i (0<=i<ii). */
185 ps_insn_ptr *rows;
187 /* All the moves added for this partial schedule. Index X has
188 a ps_insn id of X + g->num_nodes. */
189 vec<ps_reg_move_info> reg_moves;
191 /* rows_length[i] holds the number of instructions in the row.
192 It is used only (as an optimization) to back off quickly from
193 trying to schedule a node in a full row; that is, to avoid running
194 through futile DFA state transitions. */
195 int *rows_length;
197 /* The earliest absolute cycle of an insn in the partial schedule. */
198 int min_cycle;
200 /* The latest absolute cycle of an insn in the partial schedule. */
201 int max_cycle;
203 ddg_ptr g; /* The DDG of the insns in the partial schedule. */
205 int stage_count; /* The stage count of the partial schedule. */
209 static partial_schedule_ptr create_partial_schedule (int ii, ddg_ptr, int history);
210 static void free_partial_schedule (partial_schedule_ptr);
211 static void reset_partial_schedule (partial_schedule_ptr, int new_ii);
212 void print_partial_schedule (partial_schedule_ptr, FILE *);
213 static void verify_partial_schedule (partial_schedule_ptr, sbitmap);
214 static ps_insn_ptr ps_add_node_check_conflicts (partial_schedule_ptr,
215 int, int, sbitmap, sbitmap);
216 static void rotate_partial_schedule (partial_schedule_ptr, int);
217 void set_row_column_for_ps (partial_schedule_ptr);
218 static void ps_insert_empty_row (partial_schedule_ptr, int, sbitmap);
219 static int compute_split_row (sbitmap, int, int, int, ddg_node_ptr);
222 /* This page defines constants and structures for the modulo scheduling
223 driver. */
225 static int sms_order_nodes (ddg_ptr, int, int *, int *);
226 static void set_node_sched_params (ddg_ptr);
227 static partial_schedule_ptr sms_schedule_by_order (ddg_ptr, int, int, int *);
228 static void permute_partial_schedule (partial_schedule_ptr, rtx_insn *);
229 static void generate_prolog_epilog (partial_schedule_ptr, struct loop *,
230 rtx, rtx);
231 static int calculate_stage_count (partial_schedule_ptr, int);
232 static void calculate_must_precede_follow (ddg_node_ptr, int, int,
233 int, int, sbitmap, sbitmap, sbitmap);
234 static int get_sched_window (partial_schedule_ptr, ddg_node_ptr,
235 sbitmap, int, int *, int *, int *);
236 static bool try_scheduling_node_in_cycle (partial_schedule_ptr, int, int,
237 sbitmap, int *, sbitmap, sbitmap);
238 static void remove_node_from_ps (partial_schedule_ptr, ps_insn_ptr);
240 #define NODE_ASAP(node) ((node)->aux.count)
242 #define SCHED_PARAMS(x) (&node_sched_param_vec[x])
243 #define SCHED_TIME(x) (SCHED_PARAMS (x)->time)
244 #define SCHED_ROW(x) (SCHED_PARAMS (x)->row)
245 #define SCHED_STAGE(x) (SCHED_PARAMS (x)->stage)
246 #define SCHED_COLUMN(x) (SCHED_PARAMS (x)->column)
248 /* The scheduling parameters held for each node. */
249 typedef struct node_sched_params
251 int time; /* The absolute scheduling cycle. */
253 int row; /* Holds time % ii. */
254 int stage; /* Holds time / ii. */
256 /* The column of a node inside the ps. If nodes u, v are on the same row,
257 u will precede v if column (u) < column (v). */
258 int column;
259 } *node_sched_params_ptr;
261 typedef struct node_sched_params node_sched_params;
263 /* The following three functions are copied from the current scheduler
264 code in order to use sched_analyze() for computing the dependencies.
265 They are used when initializing the sched_info structure. */
266 static const char *
267 sms_print_insn (const rtx_insn *insn, int aligned ATTRIBUTE_UNUSED)
269 static char tmp[80];
271 sprintf (tmp, "i%4d", INSN_UID (insn));
272 return tmp;
275 static void
276 compute_jump_reg_dependencies (rtx insn ATTRIBUTE_UNUSED,
277 regset used ATTRIBUTE_UNUSED)
281 static struct common_sched_info_def sms_common_sched_info;
283 static struct sched_deps_info_def sms_sched_deps_info =
285 compute_jump_reg_dependencies,
286 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
287 NULL,
288 0, 0, 0
291 static struct haifa_sched_info sms_sched_info =
293 NULL,
294 NULL,
295 NULL,
296 NULL,
297 NULL,
298 sms_print_insn,
299 NULL,
300 NULL, /* insn_finishes_block_p */
301 NULL, NULL,
302 NULL, NULL,
303 0, 0,
305 NULL, NULL, NULL, NULL,
306 NULL, NULL,
310 /* Partial schedule instruction ID in PS is a register move. Return
311 information about it. */
312 static struct ps_reg_move_info *
313 ps_reg_move (partial_schedule_ptr ps, int id)
315 gcc_checking_assert (id >= ps->g->num_nodes);
316 return &ps->reg_moves[id - ps->g->num_nodes];
319 /* Return the rtl instruction that is being scheduled by partial schedule
320 instruction ID, which belongs to schedule PS. */
321 static rtx_insn *
322 ps_rtl_insn (partial_schedule_ptr ps, int id)
324 if (id < ps->g->num_nodes)
325 return ps->g->nodes[id].insn;
326 else
327 return ps_reg_move (ps, id)->insn;
330 /* Partial schedule instruction ID, which belongs to PS, occurred in
331 the original (unscheduled) loop. Return the first instruction
332 in the loop that was associated with ps_rtl_insn (PS, ID).
333 If the instruction had some notes before it, this is the first
334 of those notes. */
335 static rtx_insn *
336 ps_first_note (partial_schedule_ptr ps, int id)
338 gcc_assert (id < ps->g->num_nodes);
339 return ps->g->nodes[id].first_note;
342 /* Return the number of consecutive stages that are occupied by
343 partial schedule instruction ID in PS. */
344 static int
345 ps_num_consecutive_stages (partial_schedule_ptr ps, int id)
347 if (id < ps->g->num_nodes)
348 return 1;
349 else
350 return ps_reg_move (ps, id)->num_consecutive_stages;
353 /* Given HEAD and TAIL which are the first and last insns in a loop;
354 return the register which controls the loop. Return zero if it has
355 more than one occurrence in the loop besides the control part or the
356 do-loop pattern is not of the form we expect. */
357 static rtx
358 doloop_register_get (rtx_insn *head, rtx_insn *tail)
360 rtx reg, condition;
361 rtx_insn *insn, *first_insn_not_to_check;
363 if (!JUMP_P (tail))
364 return NULL_RTX;
366 if (!targetm.code_for_doloop_end)
367 return NULL_RTX;
369 /* TODO: Free SMS's dependence on doloop_condition_get. */
370 condition = doloop_condition_get (tail);
371 if (! condition)
372 return NULL_RTX;
374 if (REG_P (XEXP (condition, 0)))
375 reg = XEXP (condition, 0);
376 else if (GET_CODE (XEXP (condition, 0)) == PLUS
377 && REG_P (XEXP (XEXP (condition, 0), 0)))
378 reg = XEXP (XEXP (condition, 0), 0);
379 else
380 gcc_unreachable ();
382 /* Check that the COUNT_REG has no other occurrences in the loop
383 until the decrement. We assume the control part consists of
384 either a single (parallel) branch-on-count or a (non-parallel)
385 branch immediately preceded by a single (decrement) insn. */
386 first_insn_not_to_check = (GET_CODE (PATTERN (tail)) == PARALLEL ? tail
387 : prev_nondebug_insn (tail));
389 for (insn = head; insn != first_insn_not_to_check; insn = NEXT_INSN (insn))
390 if (!DEBUG_INSN_P (insn) && reg_mentioned_p (reg, insn))
392 if (dump_file)
394 fprintf (dump_file, "SMS count_reg found ");
395 print_rtl_single (dump_file, reg);
396 fprintf (dump_file, " outside control in insn:\n");
397 print_rtl_single (dump_file, insn);
400 return NULL_RTX;
403 return reg;
406 /* Check if COUNT_REG is set to a constant in the PRE_HEADER block, so
407 that the number of iterations is a compile-time constant. If so,
408 return the rtx_insn that sets COUNT_REG to a constant, and set COUNT to
409 this constant. Otherwise return 0. */
410 static rtx_insn *
411 const_iteration_count (rtx count_reg, basic_block pre_header,
412 int64_t * count)
414 rtx_insn *insn;
415 rtx_insn *head, *tail;
417 if (! pre_header)
418 return NULL;
420 get_ebb_head_tail (pre_header, pre_header, &head, &tail);
422 for (insn = tail; insn != PREV_INSN (head); insn = PREV_INSN (insn))
423 if (NONDEBUG_INSN_P (insn) && single_set (insn) &&
424 rtx_equal_p (count_reg, SET_DEST (single_set (insn))))
426 rtx pat = single_set (insn);
428 if (CONST_INT_P (SET_SRC (pat)))
430 *count = INTVAL (SET_SRC (pat));
431 return insn;
434 return NULL;
437 return NULL;
440 /* A very simple resource-based lower bound on the initiation interval.
441 ??? Improve the accuracy of this bound by considering the
442 utilization of various units. */
443 static int
444 res_MII (ddg_ptr g)
446 if (targetm.sched.sms_res_mii)
447 return targetm.sched.sms_res_mii (g);
449 return ((g->num_nodes - g->num_debug) / issue_rate);
453 /* A vector that contains the sched data for each ps_insn. */
454 static vec<node_sched_params> node_sched_param_vec;
456 /* Allocate sched_params for each node and initialize it. */
457 static void
458 set_node_sched_params (ddg_ptr g)
460 node_sched_param_vec.truncate (0);
461 node_sched_param_vec.safe_grow_cleared (g->num_nodes);
464 /* Make sure that node_sched_param_vec has an entry for every move in PS. */
465 static void
466 extend_node_sched_params (partial_schedule_ptr ps)
468 node_sched_param_vec.safe_grow_cleared (ps->g->num_nodes
469 + ps->reg_moves.length ());
472 /* Update the sched_params (time, row and stage) for node U using the II,
473 the CYCLE of U and MIN_CYCLE.
474 We're not simply taking the following
475 SCHED_STAGE (u) = CALC_STAGE_COUNT (SCHED_TIME (u), min_cycle, ii);
476 because the stages may not be aligned on cycle 0. */
477 static void
478 update_node_sched_params (int u, int ii, int cycle, int min_cycle)
480 int sc_until_cycle_zero;
481 int stage;
483 SCHED_TIME (u) = cycle;
484 SCHED_ROW (u) = SMODULO (cycle, ii);
486 /* The calculation of stage count is done adding the number
487 of stages before cycle zero and after cycle zero. */
488 sc_until_cycle_zero = CALC_STAGE_COUNT (-1, min_cycle, ii);
490 if (SCHED_TIME (u) < 0)
492 stage = CALC_STAGE_COUNT (-1, SCHED_TIME (u), ii);
493 SCHED_STAGE (u) = sc_until_cycle_zero - stage;
495 else
497 stage = CALC_STAGE_COUNT (SCHED_TIME (u), 0, ii);
498 SCHED_STAGE (u) = sc_until_cycle_zero + stage - 1;
502 static void
503 print_node_sched_params (FILE *file, int num_nodes, partial_schedule_ptr ps)
505 int i;
507 if (! file)
508 return;
509 for (i = 0; i < num_nodes; i++)
511 node_sched_params_ptr nsp = SCHED_PARAMS (i);
513 fprintf (file, "Node = %d; INSN = %d\n", i,
514 INSN_UID (ps_rtl_insn (ps, i)));
515 fprintf (file, " asap = %d:\n", NODE_ASAP (&ps->g->nodes[i]));
516 fprintf (file, " time = %d:\n", nsp->time);
517 fprintf (file, " stage = %d:\n", nsp->stage);
521 /* Set SCHED_COLUMN for each instruction in row ROW of PS. */
522 static void
523 set_columns_for_row (partial_schedule_ptr ps, int row)
525 ps_insn_ptr cur_insn;
526 int column;
528 column = 0;
529 for (cur_insn = ps->rows[row]; cur_insn; cur_insn = cur_insn->next_in_row)
530 SCHED_COLUMN (cur_insn->id) = column++;
533 /* Set SCHED_COLUMN for each instruction in PS. */
534 static void
535 set_columns_for_ps (partial_schedule_ptr ps)
537 int row;
539 for (row = 0; row < ps->ii; row++)
540 set_columns_for_row (ps, row);
543 /* Try to schedule the move with ps_insn identifier I_REG_MOVE in PS.
544 Its single predecessor has already been scheduled, as has its
545 ddg node successors. (The move may have also another move as its
546 successor, in which case that successor will be scheduled later.)
548 The move is part of a chain that satisfies register dependencies
549 between a producing ddg node and various consuming ddg nodes.
550 If some of these dependencies have a distance of 1 (meaning that
551 the use is upward-exposed) then DISTANCE1_USES is nonnull and
552 contains the set of uses with distance-1 dependencies.
553 DISTANCE1_USES is null otherwise.
555 MUST_FOLLOW is a scratch bitmap that is big enough to hold
556 all current ps_insn ids.
558 Return true on success. */
559 static bool
560 schedule_reg_move (partial_schedule_ptr ps, int i_reg_move,
561 sbitmap distance1_uses, sbitmap must_follow)
563 unsigned int u;
564 int this_time, this_distance, this_start, this_end, this_latency;
565 int start, end, c, ii;
566 sbitmap_iterator sbi;
567 ps_reg_move_info *move;
568 rtx_insn *this_insn;
569 ps_insn_ptr psi;
571 move = ps_reg_move (ps, i_reg_move);
572 ii = ps->ii;
573 if (dump_file)
575 fprintf (dump_file, "Scheduling register move INSN %d; ii = %d"
576 ", min cycle = %d\n\n", INSN_UID (move->insn), ii,
577 PS_MIN_CYCLE (ps));
578 print_rtl_single (dump_file, move->insn);
579 fprintf (dump_file, "\n%11s %11s %5s\n", "start", "end", "time");
580 fprintf (dump_file, "=========== =========== =====\n");
583 start = INT_MIN;
584 end = INT_MAX;
586 /* For dependencies of distance 1 between a producer ddg node A
587 and consumer ddg node B, we have a chain of dependencies:
589 A --(T,L1,1)--> M1 --(T,L2,0)--> M2 ... --(T,Ln,0)--> B
591 where Mi is the ith move. For dependencies of distance 0 between
592 a producer ddg node A and consumer ddg node C, we have a chain of
593 dependencies:
595 A --(T,L1',0)--> M1' --(T,L2',0)--> M2' ... --(T,Ln',0)--> C
597 where Mi' occupies the same position as Mi but occurs a stage later.
598 We can only schedule each move once, so if we have both types of
599 chain, we model the second as:
601 A --(T,L1',1)--> M1 --(T,L2',0)--> M2 ... --(T,Ln',-1)--> C
603 First handle the dependencies between the previously-scheduled
604 predecessor and the move. */
605 this_insn = ps_rtl_insn (ps, move->def);
606 this_latency = insn_latency (this_insn, move->insn);
607 this_distance = distance1_uses && move->def < ps->g->num_nodes ? 1 : 0;
608 this_time = SCHED_TIME (move->def) - this_distance * ii;
609 this_start = this_time + this_latency;
610 this_end = this_time + ii;
611 if (dump_file)
612 fprintf (dump_file, "%11d %11d %5d %d --(T,%d,%d)--> %d\n",
613 this_start, this_end, SCHED_TIME (move->def),
614 INSN_UID (this_insn), this_latency, this_distance,
615 INSN_UID (move->insn));
617 if (start < this_start)
618 start = this_start;
619 if (end > this_end)
620 end = this_end;
622 /* Handle the dependencies between the move and previously-scheduled
623 successors. */
624 EXECUTE_IF_SET_IN_BITMAP (move->uses, 0, u, sbi)
626 this_insn = ps_rtl_insn (ps, u);
627 this_latency = insn_latency (move->insn, this_insn);
628 if (distance1_uses && !bitmap_bit_p (distance1_uses, u))
629 this_distance = -1;
630 else
631 this_distance = 0;
632 this_time = SCHED_TIME (u) + this_distance * ii;
633 this_start = this_time - ii;
634 this_end = this_time - this_latency;
635 if (dump_file)
636 fprintf (dump_file, "%11d %11d %5d %d --(T,%d,%d)--> %d\n",
637 this_start, this_end, SCHED_TIME (u), INSN_UID (move->insn),
638 this_latency, this_distance, INSN_UID (this_insn));
640 if (start < this_start)
641 start = this_start;
642 if (end > this_end)
643 end = this_end;
646 if (dump_file)
648 fprintf (dump_file, "----------- ----------- -----\n");
649 fprintf (dump_file, "%11d %11d %5s %s\n", start, end, "", "(max, min)");
652 bitmap_clear (must_follow);
653 bitmap_set_bit (must_follow, move->def);
655 start = MAX (start, end - (ii - 1));
656 for (c = end; c >= start; c--)
658 psi = ps_add_node_check_conflicts (ps, i_reg_move, c,
659 move->uses, must_follow);
660 if (psi)
662 update_node_sched_params (i_reg_move, ii, c, PS_MIN_CYCLE (ps));
663 if (dump_file)
664 fprintf (dump_file, "\nScheduled register move INSN %d at"
665 " time %d, row %d\n\n", INSN_UID (move->insn), c,
666 SCHED_ROW (i_reg_move));
667 return true;
671 if (dump_file)
672 fprintf (dump_file, "\nNo available slot\n\n");
674 return false;
678 Breaking intra-loop register anti-dependences:
679 Each intra-loop register anti-dependence implies a cross-iteration true
680 dependence of distance 1. Therefore, we can remove such false dependencies
681 and figure out if the partial schedule broke them by checking if (for a
682 true-dependence of distance 1): SCHED_TIME (def) < SCHED_TIME (use) and
683 if so generate a register move. The number of such moves is equal to:
684 SCHED_TIME (use) - SCHED_TIME (def) { 0 broken
685 nreg_moves = ----------------------------------- + 1 - { dependence.
686 ii { 1 if not.
688 static bool
689 schedule_reg_moves (partial_schedule_ptr ps)
691 ddg_ptr g = ps->g;
692 int ii = ps->ii;
693 int i;
695 for (i = 0; i < g->num_nodes; i++)
697 ddg_node_ptr u = &g->nodes[i];
698 ddg_edge_ptr e;
699 int nreg_moves = 0, i_reg_move;
700 rtx prev_reg, old_reg;
701 int first_move;
702 int distances[2];
703 sbitmap must_follow;
704 sbitmap distance1_uses;
705 rtx set = single_set (u->insn);
707 /* Skip instructions that do not set a register. */
708 if ((set && !REG_P (SET_DEST (set))))
709 continue;
711 /* Compute the number of reg_moves needed for u, by looking at life
712 ranges started at u (excluding self-loops). */
713 distances[0] = distances[1] = false;
714 for (e = u->out; e; e = e->next_out)
715 if (e->type == TRUE_DEP && e->dest != e->src)
717 int nreg_moves4e = (SCHED_TIME (e->dest->cuid)
718 - SCHED_TIME (e->src->cuid)) / ii;
720 if (e->distance == 1)
721 nreg_moves4e = (SCHED_TIME (e->dest->cuid)
722 - SCHED_TIME (e->src->cuid) + ii) / ii;
724 /* If dest precedes src in the schedule of the kernel, then dest
725 will read before src writes and we can save one reg_copy. */
726 if (SCHED_ROW (e->dest->cuid) == SCHED_ROW (e->src->cuid)
727 && SCHED_COLUMN (e->dest->cuid) < SCHED_COLUMN (e->src->cuid))
728 nreg_moves4e--;
730 if (nreg_moves4e >= 1)
732 /* !single_set instructions are not supported yet and
733 thus we do not except to encounter them in the loop
734 except from the doloop part. For the latter case
735 we assume no regmoves are generated as the doloop
736 instructions are tied to the branch with an edge. */
737 gcc_assert (set);
738 /* If the instruction contains auto-inc register then
739 validate that the regmov is being generated for the
740 target regsiter rather then the inc'ed register. */
741 gcc_assert (!autoinc_var_is_used_p (u->insn, e->dest->insn));
744 if (nreg_moves4e)
746 gcc_assert (e->distance < 2);
747 distances[e->distance] = true;
749 nreg_moves = MAX (nreg_moves, nreg_moves4e);
752 if (nreg_moves == 0)
753 continue;
755 /* Create NREG_MOVES register moves. */
756 first_move = ps->reg_moves.length ();
757 ps->reg_moves.safe_grow_cleared (first_move + nreg_moves);
758 extend_node_sched_params (ps);
760 /* Record the moves associated with this node. */
761 first_move += ps->g->num_nodes;
763 /* Generate each move. */
764 old_reg = prev_reg = SET_DEST (single_set (u->insn));
765 for (i_reg_move = 0; i_reg_move < nreg_moves; i_reg_move++)
767 ps_reg_move_info *move = ps_reg_move (ps, first_move + i_reg_move);
769 move->def = i_reg_move > 0 ? first_move + i_reg_move - 1 : i;
770 move->uses = sbitmap_alloc (first_move + nreg_moves);
771 move->old_reg = old_reg;
772 move->new_reg = gen_reg_rtx (GET_MODE (prev_reg));
773 move->num_consecutive_stages = distances[0] && distances[1] ? 2 : 1;
774 move->insn = gen_move_insn (move->new_reg, copy_rtx (prev_reg));
775 bitmap_clear (move->uses);
777 prev_reg = move->new_reg;
780 distance1_uses = distances[1] ? sbitmap_alloc (g->num_nodes) : NULL;
782 if (distance1_uses)
783 bitmap_clear (distance1_uses);
785 /* Every use of the register defined by node may require a different
786 copy of this register, depending on the time the use is scheduled.
787 Record which uses require which move results. */
788 for (e = u->out; e; e = e->next_out)
789 if (e->type == TRUE_DEP && e->dest != e->src)
791 int dest_copy = (SCHED_TIME (e->dest->cuid)
792 - SCHED_TIME (e->src->cuid)) / ii;
794 if (e->distance == 1)
795 dest_copy = (SCHED_TIME (e->dest->cuid)
796 - SCHED_TIME (e->src->cuid) + ii) / ii;
798 if (SCHED_ROW (e->dest->cuid) == SCHED_ROW (e->src->cuid)
799 && SCHED_COLUMN (e->dest->cuid) < SCHED_COLUMN (e->src->cuid))
800 dest_copy--;
802 if (dest_copy)
804 ps_reg_move_info *move;
806 move = ps_reg_move (ps, first_move + dest_copy - 1);
807 bitmap_set_bit (move->uses, e->dest->cuid);
808 if (e->distance == 1)
809 bitmap_set_bit (distance1_uses, e->dest->cuid);
813 must_follow = sbitmap_alloc (first_move + nreg_moves);
814 for (i_reg_move = 0; i_reg_move < nreg_moves; i_reg_move++)
815 if (!schedule_reg_move (ps, first_move + i_reg_move,
816 distance1_uses, must_follow))
817 break;
818 sbitmap_free (must_follow);
819 if (distance1_uses)
820 sbitmap_free (distance1_uses);
821 if (i_reg_move < nreg_moves)
822 return false;
824 return true;
827 /* Emit the moves associatied with PS. Apply the substitutions
828 associated with them. */
829 static void
830 apply_reg_moves (partial_schedule_ptr ps)
832 ps_reg_move_info *move;
833 int i;
835 FOR_EACH_VEC_ELT (ps->reg_moves, i, move)
837 unsigned int i_use;
838 sbitmap_iterator sbi;
840 EXECUTE_IF_SET_IN_BITMAP (move->uses, 0, i_use, sbi)
842 replace_rtx (ps->g->nodes[i_use].insn, move->old_reg, move->new_reg);
843 df_insn_rescan (ps->g->nodes[i_use].insn);
848 /* Bump the SCHED_TIMEs of all nodes by AMOUNT. Set the values of
849 SCHED_ROW and SCHED_STAGE. Instruction scheduled on cycle AMOUNT
850 will move to cycle zero. */
851 static void
852 reset_sched_times (partial_schedule_ptr ps, int amount)
854 int row;
855 int ii = ps->ii;
856 ps_insn_ptr crr_insn;
858 for (row = 0; row < ii; row++)
859 for (crr_insn = ps->rows[row]; crr_insn; crr_insn = crr_insn->next_in_row)
861 int u = crr_insn->id;
862 int normalized_time = SCHED_TIME (u) - amount;
863 int new_min_cycle = PS_MIN_CYCLE (ps) - amount;
865 if (dump_file)
867 /* Print the scheduling times after the rotation. */
868 rtx_insn *insn = ps_rtl_insn (ps, u);
870 fprintf (dump_file, "crr_insn->node=%d (insn id %d), "
871 "crr_insn->cycle=%d, min_cycle=%d", u,
872 INSN_UID (insn), normalized_time, new_min_cycle);
873 if (JUMP_P (insn))
874 fprintf (dump_file, " (branch)");
875 fprintf (dump_file, "\n");
878 gcc_assert (SCHED_TIME (u) >= ps->min_cycle);
879 gcc_assert (SCHED_TIME (u) <= ps->max_cycle);
881 crr_insn->cycle = normalized_time;
882 update_node_sched_params (u, ii, normalized_time, new_min_cycle);
886 /* Permute the insns according to their order in PS, from row 0 to
887 row ii-1, and position them right before LAST. This schedules
888 the insns of the loop kernel. */
889 static void
890 permute_partial_schedule (partial_schedule_ptr ps, rtx_insn *last)
892 int ii = ps->ii;
893 int row;
894 ps_insn_ptr ps_ij;
896 for (row = 0; row < ii ; row++)
897 for (ps_ij = ps->rows[row]; ps_ij; ps_ij = ps_ij->next_in_row)
899 rtx_insn *insn = ps_rtl_insn (ps, ps_ij->id);
901 if (PREV_INSN (last) != insn)
903 if (ps_ij->id < ps->g->num_nodes)
904 reorder_insns_nobb (ps_first_note (ps, ps_ij->id), insn,
905 PREV_INSN (last));
906 else
907 add_insn_before (insn, last, NULL);
912 /* Set bitmaps TMP_FOLLOW and TMP_PRECEDE to MUST_FOLLOW and MUST_PRECEDE
913 respectively only if cycle C falls on the border of the scheduling
914 window boundaries marked by START and END cycles. STEP is the
915 direction of the window. */
916 static inline void
917 set_must_precede_follow (sbitmap *tmp_follow, sbitmap must_follow,
918 sbitmap *tmp_precede, sbitmap must_precede, int c,
919 int start, int end, int step)
921 *tmp_precede = NULL;
922 *tmp_follow = NULL;
924 if (c == start)
926 if (step == 1)
927 *tmp_precede = must_precede;
928 else /* step == -1. */
929 *tmp_follow = must_follow;
931 if (c == end - step)
933 if (step == 1)
934 *tmp_follow = must_follow;
935 else /* step == -1. */
936 *tmp_precede = must_precede;
941 /* Return True if the branch can be moved to row ii-1 while
942 normalizing the partial schedule PS to start from cycle zero and thus
943 optimize the SC. Otherwise return False. */
944 static bool
945 optimize_sc (partial_schedule_ptr ps, ddg_ptr g)
947 int amount = PS_MIN_CYCLE (ps);
948 sbitmap sched_nodes = sbitmap_alloc (g->num_nodes);
949 int start, end, step;
950 int ii = ps->ii;
951 bool ok = false;
952 int stage_count, stage_count_curr;
954 /* Compare the SC after normalization and SC after bringing the branch
955 to row ii-1. If they are equal just bail out. */
956 stage_count = calculate_stage_count (ps, amount);
957 stage_count_curr =
958 calculate_stage_count (ps, SCHED_TIME (g->closing_branch->cuid) - (ii - 1));
960 if (stage_count == stage_count_curr)
962 if (dump_file)
963 fprintf (dump_file, "SMS SC already optimized.\n");
965 ok = false;
966 goto clear;
969 if (dump_file)
971 fprintf (dump_file, "SMS Trying to optimize branch location\n");
972 fprintf (dump_file, "SMS partial schedule before trial:\n");
973 print_partial_schedule (ps, dump_file);
976 /* First, normalize the partial scheduling. */
977 reset_sched_times (ps, amount);
978 rotate_partial_schedule (ps, amount);
979 if (dump_file)
981 fprintf (dump_file,
982 "SMS partial schedule after normalization (ii, %d, SC %d):\n",
983 ii, stage_count);
984 print_partial_schedule (ps, dump_file);
987 if (SMODULO (SCHED_TIME (g->closing_branch->cuid), ii) == ii - 1)
989 ok = true;
990 goto clear;
993 bitmap_ones (sched_nodes);
995 /* Calculate the new placement of the branch. It should be in row
996 ii-1 and fall into it's scheduling window. */
997 if (get_sched_window (ps, g->closing_branch, sched_nodes, ii, &start,
998 &step, &end) == 0)
1000 bool success;
1001 ps_insn_ptr next_ps_i;
1002 int branch_cycle = SCHED_TIME (g->closing_branch->cuid);
1003 int row = SMODULO (branch_cycle, ps->ii);
1004 int num_splits = 0;
1005 sbitmap must_precede, must_follow, tmp_precede, tmp_follow;
1006 int c;
1008 if (dump_file)
1009 fprintf (dump_file, "\nTrying to schedule node %d "
1010 "INSN = %d in (%d .. %d) step %d\n",
1011 g->closing_branch->cuid,
1012 (INSN_UID (g->closing_branch->insn)), start, end, step);
1014 gcc_assert ((step > 0 && start < end) || (step < 0 && start > end));
1015 if (step == 1)
1017 c = start + ii - SMODULO (start, ii) - 1;
1018 gcc_assert (c >= start);
1019 if (c >= end)
1021 ok = false;
1022 if (dump_file)
1023 fprintf (dump_file,
1024 "SMS failed to schedule branch at cycle: %d\n", c);
1025 goto clear;
1028 else
1030 c = start - SMODULO (start, ii) - 1;
1031 gcc_assert (c <= start);
1033 if (c <= end)
1035 if (dump_file)
1036 fprintf (dump_file,
1037 "SMS failed to schedule branch at cycle: %d\n", c);
1038 ok = false;
1039 goto clear;
1043 must_precede = sbitmap_alloc (g->num_nodes);
1044 must_follow = sbitmap_alloc (g->num_nodes);
1046 /* Try to schedule the branch is it's new cycle. */
1047 calculate_must_precede_follow (g->closing_branch, start, end,
1048 step, ii, sched_nodes,
1049 must_precede, must_follow);
1051 set_must_precede_follow (&tmp_follow, must_follow, &tmp_precede,
1052 must_precede, c, start, end, step);
1054 /* Find the element in the partial schedule related to the closing
1055 branch so we can remove it from it's current cycle. */
1056 for (next_ps_i = ps->rows[row];
1057 next_ps_i; next_ps_i = next_ps_i->next_in_row)
1058 if (next_ps_i->id == g->closing_branch->cuid)
1059 break;
1061 remove_node_from_ps (ps, next_ps_i);
1062 success =
1063 try_scheduling_node_in_cycle (ps, g->closing_branch->cuid, c,
1064 sched_nodes, &num_splits,
1065 tmp_precede, tmp_follow);
1066 gcc_assert (num_splits == 0);
1067 if (!success)
1069 if (dump_file)
1070 fprintf (dump_file,
1071 "SMS failed to schedule branch at cycle: %d, "
1072 "bringing it back to cycle %d\n", c, branch_cycle);
1074 /* The branch was failed to be placed in row ii - 1.
1075 Put it back in it's original place in the partial
1076 schedualing. */
1077 set_must_precede_follow (&tmp_follow, must_follow, &tmp_precede,
1078 must_precede, branch_cycle, start, end,
1079 step);
1080 success =
1081 try_scheduling_node_in_cycle (ps, g->closing_branch->cuid,
1082 branch_cycle, sched_nodes,
1083 &num_splits, tmp_precede,
1084 tmp_follow);
1085 gcc_assert (success && (num_splits == 0));
1086 ok = false;
1088 else
1090 /* The branch is placed in row ii - 1. */
1091 if (dump_file)
1092 fprintf (dump_file,
1093 "SMS success in moving branch to cycle %d\n", c);
1095 update_node_sched_params (g->closing_branch->cuid, ii, c,
1096 PS_MIN_CYCLE (ps));
1097 ok = true;
1100 free (must_precede);
1101 free (must_follow);
1104 clear:
1105 free (sched_nodes);
1106 return ok;
1109 static void
1110 duplicate_insns_of_cycles (partial_schedule_ptr ps, int from_stage,
1111 int to_stage, rtx count_reg)
1113 int row;
1114 ps_insn_ptr ps_ij;
1116 for (row = 0; row < ps->ii; row++)
1117 for (ps_ij = ps->rows[row]; ps_ij; ps_ij = ps_ij->next_in_row)
1119 int u = ps_ij->id;
1120 int first_u, last_u;
1121 rtx_insn *u_insn;
1123 /* Do not duplicate any insn which refers to count_reg as it
1124 belongs to the control part.
1125 The closing branch is scheduled as well and thus should
1126 be ignored.
1127 TODO: This should be done by analyzing the control part of
1128 the loop. */
1129 u_insn = ps_rtl_insn (ps, u);
1130 if (reg_mentioned_p (count_reg, u_insn)
1131 || JUMP_P (u_insn))
1132 continue;
1134 first_u = SCHED_STAGE (u);
1135 last_u = first_u + ps_num_consecutive_stages (ps, u) - 1;
1136 if (from_stage <= last_u && to_stage >= first_u)
1138 if (u < ps->g->num_nodes)
1139 duplicate_insn_chain (ps_first_note (ps, u), u_insn);
1140 else
1141 emit_insn (copy_rtx (PATTERN (u_insn)));
1147 /* Generate the instructions (including reg_moves) for prolog & epilog. */
1148 static void
1149 generate_prolog_epilog (partial_schedule_ptr ps, struct loop *loop,
1150 rtx count_reg, rtx count_init)
1152 int i;
1153 int last_stage = PS_STAGE_COUNT (ps) - 1;
1154 edge e;
1156 /* Generate the prolog, inserting its insns on the loop-entry edge. */
1157 start_sequence ();
1159 if (!count_init)
1161 /* Generate instructions at the beginning of the prolog to
1162 adjust the loop count by STAGE_COUNT. If loop count is constant
1163 (count_init), this constant is adjusted by STAGE_COUNT in
1164 generate_prolog_epilog function. */
1165 rtx sub_reg = NULL_RTX;
1167 sub_reg = expand_simple_binop (GET_MODE (count_reg), MINUS, count_reg,
1168 gen_int_mode (last_stage,
1169 GET_MODE (count_reg)),
1170 count_reg, 1, OPTAB_DIRECT);
1171 gcc_assert (REG_P (sub_reg));
1172 if (REGNO (sub_reg) != REGNO (count_reg))
1173 emit_move_insn (count_reg, sub_reg);
1176 for (i = 0; i < last_stage; i++)
1177 duplicate_insns_of_cycles (ps, 0, i, count_reg);
1179 /* Put the prolog on the entry edge. */
1180 e = loop_preheader_edge (loop);
1181 split_edge_and_insert (e, get_insns ());
1182 if (!flag_resched_modulo_sched)
1183 e->dest->flags |= BB_DISABLE_SCHEDULE;
1185 end_sequence ();
1187 /* Generate the epilog, inserting its insns on the loop-exit edge. */
1188 start_sequence ();
1190 for (i = 0; i < last_stage; i++)
1191 duplicate_insns_of_cycles (ps, i + 1, last_stage, count_reg);
1193 /* Put the epilogue on the exit edge. */
1194 gcc_assert (single_exit (loop));
1195 e = single_exit (loop);
1196 split_edge_and_insert (e, get_insns ());
1197 if (!flag_resched_modulo_sched)
1198 e->dest->flags |= BB_DISABLE_SCHEDULE;
1200 end_sequence ();
1203 /* Mark LOOP as software pipelined so the later
1204 scheduling passes don't touch it. */
1205 static void
1206 mark_loop_unsched (struct loop *loop)
1208 unsigned i;
1209 basic_block *bbs = get_loop_body (loop);
1211 for (i = 0; i < loop->num_nodes; i++)
1212 bbs[i]->flags |= BB_DISABLE_SCHEDULE;
1214 free (bbs);
1217 /* Return true if all the BBs of the loop are empty except the
1218 loop header. */
1219 static bool
1220 loop_single_full_bb_p (struct loop *loop)
1222 unsigned i;
1223 basic_block *bbs = get_loop_body (loop);
1225 for (i = 0; i < loop->num_nodes ; i++)
1227 rtx_insn *head, *tail;
1228 bool empty_bb = true;
1230 if (bbs[i] == loop->header)
1231 continue;
1233 /* Make sure that basic blocks other than the header
1234 have only notes labels or jumps. */
1235 get_ebb_head_tail (bbs[i], bbs[i], &head, &tail);
1236 for (; head != NEXT_INSN (tail); head = NEXT_INSN (head))
1238 if (NOTE_P (head) || LABEL_P (head)
1239 || (INSN_P (head) && (DEBUG_INSN_P (head) || JUMP_P (head))))
1240 continue;
1241 empty_bb = false;
1242 break;
1245 if (! empty_bb)
1247 free (bbs);
1248 return false;
1251 free (bbs);
1252 return true;
1255 /* Dump file:line from INSN's location info to dump_file. */
1257 static void
1258 dump_insn_location (rtx_insn *insn)
1260 if (dump_file && INSN_HAS_LOCATION (insn))
1262 expanded_location xloc = insn_location (insn);
1263 fprintf (dump_file, " %s:%i", xloc.file, xloc.line);
1267 /* A simple loop from SMS point of view; it is a loop that is composed of
1268 either a single basic block or two BBs - a header and a latch. */
1269 #define SIMPLE_SMS_LOOP_P(loop) ((loop->num_nodes < 3 ) \
1270 && (EDGE_COUNT (loop->latch->preds) == 1) \
1271 && (EDGE_COUNT (loop->latch->succs) == 1))
1273 /* Return true if the loop is in its canonical form and false if not.
1274 i.e. SIMPLE_SMS_LOOP_P and have one preheader block, and single exit. */
1275 static bool
1276 loop_canon_p (struct loop *loop)
1279 if (loop->inner || !loop_outer (loop))
1281 if (dump_file)
1282 fprintf (dump_file, "SMS loop inner or !loop_outer\n");
1283 return false;
1286 if (!single_exit (loop))
1288 if (dump_file)
1290 rtx_insn *insn = BB_END (loop->header);
1292 fprintf (dump_file, "SMS loop many exits");
1293 dump_insn_location (insn);
1294 fprintf (dump_file, "\n");
1296 return false;
1299 if (! SIMPLE_SMS_LOOP_P (loop) && ! loop_single_full_bb_p (loop))
1301 if (dump_file)
1303 rtx_insn *insn = BB_END (loop->header);
1305 fprintf (dump_file, "SMS loop many BBs.");
1306 dump_insn_location (insn);
1307 fprintf (dump_file, "\n");
1309 return false;
1312 return true;
1315 /* If there are more than one entry for the loop,
1316 make it one by splitting the first entry edge and
1317 redirecting the others to the new BB. */
1318 static void
1319 canon_loop (struct loop *loop)
1321 edge e;
1322 edge_iterator i;
1324 /* Avoid annoying special cases of edges going to exit
1325 block. */
1326 FOR_EACH_EDGE (e, i, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
1327 if ((e->flags & EDGE_FALLTHRU) && (EDGE_COUNT (e->src->succs) > 1))
1328 split_edge (e);
1330 if (loop->latch == loop->header
1331 || EDGE_COUNT (loop->latch->succs) > 1)
1333 FOR_EACH_EDGE (e, i, loop->header->preds)
1334 if (e->src == loop->latch)
1335 break;
1336 split_edge (e);
1340 /* Setup infos. */
1341 static void
1342 setup_sched_infos (void)
1344 memcpy (&sms_common_sched_info, &haifa_common_sched_info,
1345 sizeof (sms_common_sched_info));
1346 sms_common_sched_info.sched_pass_id = SCHED_SMS_PASS;
1347 common_sched_info = &sms_common_sched_info;
1349 sched_deps_info = &sms_sched_deps_info;
1350 current_sched_info = &sms_sched_info;
1353 /* Probability in % that the sms-ed loop rolls enough so that optimized
1354 version may be entered. Just a guess. */
1355 #define PROB_SMS_ENOUGH_ITERATIONS 80
1357 /* Used to calculate the upper bound of ii. */
1358 #define MAXII_FACTOR 2
1360 /* Main entry point, perform SMS scheduling on the loops of the function
1361 that consist of single basic blocks. */
1362 static void
1363 sms_schedule (void)
1365 rtx_insn *insn;
1366 ddg_ptr *g_arr, g;
1367 int * node_order;
1368 int maxii, max_asap;
1369 partial_schedule_ptr ps;
1370 basic_block bb = NULL;
1371 struct loop *loop;
1372 basic_block condition_bb = NULL;
1373 edge latch_edge;
1374 gcov_type trip_count = 0;
1376 loop_optimizer_init (LOOPS_HAVE_PREHEADERS
1377 | LOOPS_HAVE_RECORDED_EXITS);
1378 if (number_of_loops (cfun) <= 1)
1380 loop_optimizer_finalize ();
1381 return; /* There are no loops to schedule. */
1384 /* Initialize issue_rate. */
1385 if (targetm.sched.issue_rate)
1387 int temp = reload_completed;
1389 reload_completed = 1;
1390 issue_rate = targetm.sched.issue_rate ();
1391 reload_completed = temp;
1393 else
1394 issue_rate = 1;
1396 /* Initialize the scheduler. */
1397 setup_sched_infos ();
1398 haifa_sched_init ();
1400 /* Allocate memory to hold the DDG array one entry for each loop.
1401 We use loop->num as index into this array. */
1402 g_arr = XCNEWVEC (ddg_ptr, number_of_loops (cfun));
1404 if (dump_file)
1406 fprintf (dump_file, "\n\nSMS analysis phase\n");
1407 fprintf (dump_file, "===================\n\n");
1410 /* Build DDGs for all the relevant loops and hold them in G_ARR
1411 indexed by the loop index. */
1412 FOR_EACH_LOOP (loop, 0)
1414 rtx_insn *head, *tail;
1415 rtx count_reg;
1417 /* For debugging. */
1418 if (dbg_cnt (sms_sched_loop) == false)
1420 if (dump_file)
1421 fprintf (dump_file, "SMS reached max limit... \n");
1423 break;
1426 if (dump_file)
1428 rtx_insn *insn = BB_END (loop->header);
1430 fprintf (dump_file, "SMS loop num: %d", loop->num);
1431 dump_insn_location (insn);
1432 fprintf (dump_file, "\n");
1435 if (! loop_canon_p (loop))
1436 continue;
1438 if (! loop_single_full_bb_p (loop))
1440 if (dump_file)
1441 fprintf (dump_file, "SMS not loop_single_full_bb_p\n");
1442 continue;
1445 bb = loop->header;
1447 get_ebb_head_tail (bb, bb, &head, &tail);
1448 latch_edge = loop_latch_edge (loop);
1449 gcc_assert (single_exit (loop));
1450 if (single_exit (loop)->count)
1451 trip_count = latch_edge->count / single_exit (loop)->count;
1453 /* Perform SMS only on loops that their average count is above threshold. */
1455 if ( latch_edge->count
1456 && (latch_edge->count < single_exit (loop)->count * SMS_LOOP_AVERAGE_COUNT_THRESHOLD))
1458 if (dump_file)
1460 dump_insn_location (tail);
1461 fprintf (dump_file, "\nSMS single-bb-loop\n");
1462 if (profile_info && flag_branch_probabilities)
1464 fprintf (dump_file, "SMS loop-count ");
1465 fprintf (dump_file, "%" PRId64,
1466 (int64_t) bb->count);
1467 fprintf (dump_file, "\n");
1468 fprintf (dump_file, "SMS trip-count ");
1469 fprintf (dump_file, "%" PRId64,
1470 (int64_t) trip_count);
1471 fprintf (dump_file, "\n");
1472 fprintf (dump_file, "SMS profile-sum-max ");
1473 fprintf (dump_file, "%" PRId64,
1474 (int64_t) profile_info->sum_max);
1475 fprintf (dump_file, "\n");
1478 continue;
1481 /* Make sure this is a doloop. */
1482 if ( !(count_reg = doloop_register_get (head, tail)))
1484 if (dump_file)
1485 fprintf (dump_file, "SMS doloop_register_get failed\n");
1486 continue;
1489 /* Don't handle BBs with calls or barriers
1490 or !single_set with the exception of instructions that include
1491 count_reg---these instructions are part of the control part
1492 that do-loop recognizes.
1493 ??? Should handle insns defining subregs. */
1494 for (insn = head; insn != NEXT_INSN (tail); insn = NEXT_INSN (insn))
1496 rtx set;
1498 if (CALL_P (insn)
1499 || BARRIER_P (insn)
1500 || (NONDEBUG_INSN_P (insn) && !JUMP_P (insn)
1501 && !single_set (insn) && GET_CODE (PATTERN (insn)) != USE
1502 && !reg_mentioned_p (count_reg, insn))
1503 || (INSN_P (insn) && (set = single_set (insn))
1504 && GET_CODE (SET_DEST (set)) == SUBREG))
1505 break;
1508 if (insn != NEXT_INSN (tail))
1510 if (dump_file)
1512 if (CALL_P (insn))
1513 fprintf (dump_file, "SMS loop-with-call\n");
1514 else if (BARRIER_P (insn))
1515 fprintf (dump_file, "SMS loop-with-barrier\n");
1516 else if ((NONDEBUG_INSN_P (insn) && !JUMP_P (insn)
1517 && !single_set (insn) && GET_CODE (PATTERN (insn)) != USE))
1518 fprintf (dump_file, "SMS loop-with-not-single-set\n");
1519 else
1520 fprintf (dump_file, "SMS loop with subreg in lhs\n");
1521 print_rtl_single (dump_file, insn);
1524 continue;
1527 /* Always schedule the closing branch with the rest of the
1528 instructions. The branch is rotated to be in row ii-1 at the
1529 end of the scheduling procedure to make sure it's the last
1530 instruction in the iteration. */
1531 if (! (g = create_ddg (bb, 1)))
1533 if (dump_file)
1534 fprintf (dump_file, "SMS create_ddg failed\n");
1535 continue;
1538 g_arr[loop->num] = g;
1539 if (dump_file)
1540 fprintf (dump_file, "...OK\n");
1543 if (dump_file)
1545 fprintf (dump_file, "\nSMS transformation phase\n");
1546 fprintf (dump_file, "=========================\n\n");
1549 /* We don't want to perform SMS on new loops - created by versioning. */
1550 FOR_EACH_LOOP (loop, 0)
1552 rtx_insn *head, *tail;
1553 rtx count_reg;
1554 rtx_insn *count_init;
1555 int mii, rec_mii, stage_count, min_cycle;
1556 int64_t loop_count = 0;
1557 bool opt_sc_p;
1559 if (! (g = g_arr[loop->num]))
1560 continue;
1562 if (dump_file)
1564 rtx_insn *insn = BB_END (loop->header);
1566 fprintf (dump_file, "SMS loop num: %d", loop->num);
1567 dump_insn_location (insn);
1568 fprintf (dump_file, "\n");
1570 print_ddg (dump_file, g);
1573 get_ebb_head_tail (loop->header, loop->header, &head, &tail);
1575 latch_edge = loop_latch_edge (loop);
1576 gcc_assert (single_exit (loop));
1577 if (single_exit (loop)->count)
1578 trip_count = latch_edge->count / single_exit (loop)->count;
1580 if (dump_file)
1582 dump_insn_location (tail);
1583 fprintf (dump_file, "\nSMS single-bb-loop\n");
1584 if (profile_info && flag_branch_probabilities)
1586 fprintf (dump_file, "SMS loop-count ");
1587 fprintf (dump_file, "%" PRId64,
1588 (int64_t) bb->count);
1589 fprintf (dump_file, "\n");
1590 fprintf (dump_file, "SMS profile-sum-max ");
1591 fprintf (dump_file, "%" PRId64,
1592 (int64_t) profile_info->sum_max);
1593 fprintf (dump_file, "\n");
1595 fprintf (dump_file, "SMS doloop\n");
1596 fprintf (dump_file, "SMS built-ddg %d\n", g->num_nodes);
1597 fprintf (dump_file, "SMS num-loads %d\n", g->num_loads);
1598 fprintf (dump_file, "SMS num-stores %d\n", g->num_stores);
1602 /* In case of th loop have doloop register it gets special
1603 handling. */
1604 count_init = NULL;
1605 if ((count_reg = doloop_register_get (head, tail)))
1607 basic_block pre_header;
1609 pre_header = loop_preheader_edge (loop)->src;
1610 count_init = const_iteration_count (count_reg, pre_header,
1611 &loop_count);
1613 gcc_assert (count_reg);
1615 if (dump_file && count_init)
1617 fprintf (dump_file, "SMS const-doloop ");
1618 fprintf (dump_file, "%" PRId64,
1619 loop_count);
1620 fprintf (dump_file, "\n");
1623 node_order = XNEWVEC (int, g->num_nodes);
1625 mii = 1; /* Need to pass some estimate of mii. */
1626 rec_mii = sms_order_nodes (g, mii, node_order, &max_asap);
1627 mii = MAX (res_MII (g), rec_mii);
1628 maxii = MAX (max_asap, MAXII_FACTOR * mii);
1630 if (dump_file)
1631 fprintf (dump_file, "SMS iis %d %d %d (rec_mii, mii, maxii)\n",
1632 rec_mii, mii, maxii);
1634 for (;;)
1636 set_node_sched_params (g);
1638 stage_count = 0;
1639 opt_sc_p = false;
1640 ps = sms_schedule_by_order (g, mii, maxii, node_order);
1642 if (ps)
1644 /* Try to achieve optimized SC by normalizing the partial
1645 schedule (having the cycles start from cycle zero).
1646 The branch location must be placed in row ii-1 in the
1647 final scheduling. If failed, shift all instructions to
1648 position the branch in row ii-1. */
1649 opt_sc_p = optimize_sc (ps, g);
1650 if (opt_sc_p)
1651 stage_count = calculate_stage_count (ps, 0);
1652 else
1654 /* Bring the branch to cycle ii-1. */
1655 int amount = (SCHED_TIME (g->closing_branch->cuid)
1656 - (ps->ii - 1));
1658 if (dump_file)
1659 fprintf (dump_file, "SMS schedule branch at cycle ii-1\n");
1661 stage_count = calculate_stage_count (ps, amount);
1664 gcc_assert (stage_count >= 1);
1667 /* The default value of PARAM_SMS_MIN_SC is 2 as stage count of
1668 1 means that there is no interleaving between iterations thus
1669 we let the scheduling passes do the job in this case. */
1670 if (stage_count < PARAM_VALUE (PARAM_SMS_MIN_SC)
1671 || (count_init && (loop_count <= stage_count))
1672 || (flag_branch_probabilities && (trip_count <= stage_count)))
1674 if (dump_file)
1676 fprintf (dump_file, "SMS failed... \n");
1677 fprintf (dump_file, "SMS sched-failed (stage-count=%d,"
1678 " loop-count=", stage_count);
1679 fprintf (dump_file, "%" PRId64, loop_count);
1680 fprintf (dump_file, ", trip-count=");
1681 fprintf (dump_file, "%" PRId64, trip_count);
1682 fprintf (dump_file, ")\n");
1684 break;
1687 if (!opt_sc_p)
1689 /* Rotate the partial schedule to have the branch in row ii-1. */
1690 int amount = SCHED_TIME (g->closing_branch->cuid) - (ps->ii - 1);
1692 reset_sched_times (ps, amount);
1693 rotate_partial_schedule (ps, amount);
1696 set_columns_for_ps (ps);
1698 min_cycle = PS_MIN_CYCLE (ps) - SMODULO (PS_MIN_CYCLE (ps), ps->ii);
1699 if (!schedule_reg_moves (ps))
1701 mii = ps->ii + 1;
1702 free_partial_schedule (ps);
1703 continue;
1706 /* Moves that handle incoming values might have been added
1707 to a new first stage. Bump the stage count if so.
1709 ??? Perhaps we could consider rotating the schedule here
1710 instead? */
1711 if (PS_MIN_CYCLE (ps) < min_cycle)
1713 reset_sched_times (ps, 0);
1714 stage_count++;
1717 /* The stage count should now be correct without rotation. */
1718 gcc_checking_assert (stage_count == calculate_stage_count (ps, 0));
1719 PS_STAGE_COUNT (ps) = stage_count;
1721 canon_loop (loop);
1723 if (dump_file)
1725 dump_insn_location (tail);
1726 fprintf (dump_file, " SMS succeeded %d %d (with ii, sc)\n",
1727 ps->ii, stage_count);
1728 print_partial_schedule (ps, dump_file);
1731 /* case the BCT count is not known , Do loop-versioning */
1732 if (count_reg && ! count_init)
1734 rtx comp_rtx = gen_rtx_GT (VOIDmode, count_reg,
1735 gen_int_mode (stage_count,
1736 GET_MODE (count_reg)));
1737 unsigned prob = (PROB_SMS_ENOUGH_ITERATIONS
1738 * REG_BR_PROB_BASE) / 100;
1740 loop_version (loop, comp_rtx, &condition_bb,
1741 prob, prob, REG_BR_PROB_BASE - prob,
1742 true);
1745 /* Set new iteration count of loop kernel. */
1746 if (count_reg && count_init)
1747 SET_SRC (single_set (count_init)) = GEN_INT (loop_count
1748 - stage_count + 1);
1750 /* Now apply the scheduled kernel to the RTL of the loop. */
1751 permute_partial_schedule (ps, g->closing_branch->first_note);
1753 /* Mark this loop as software pipelined so the later
1754 scheduling passes don't touch it. */
1755 if (! flag_resched_modulo_sched)
1756 mark_loop_unsched (loop);
1758 /* The life-info is not valid any more. */
1759 df_set_bb_dirty (g->bb);
1761 apply_reg_moves (ps);
1762 if (dump_file)
1763 print_node_sched_params (dump_file, g->num_nodes, ps);
1764 /* Generate prolog and epilog. */
1765 generate_prolog_epilog (ps, loop, count_reg, count_init);
1766 break;
1769 free_partial_schedule (ps);
1770 node_sched_param_vec.release ();
1771 free (node_order);
1772 free_ddg (g);
1775 free (g_arr);
1777 /* Release scheduler data, needed until now because of DFA. */
1778 haifa_sched_finish ();
1779 loop_optimizer_finalize ();
1782 /* The SMS scheduling algorithm itself
1783 -----------------------------------
1784 Input: 'O' an ordered list of insns of a loop.
1785 Output: A scheduling of the loop - kernel, prolog, and epilogue.
1787 'Q' is the empty Set
1788 'PS' is the partial schedule; it holds the currently scheduled nodes with
1789 their cycle/slot.
1790 'PSP' previously scheduled predecessors.
1791 'PSS' previously scheduled successors.
1792 't(u)' the cycle where u is scheduled.
1793 'l(u)' is the latency of u.
1794 'd(v,u)' is the dependence distance from v to u.
1795 'ASAP(u)' the earliest time at which u could be scheduled as computed in
1796 the node ordering phase.
1797 'check_hardware_resources_conflicts(u, PS, c)'
1798 run a trace around cycle/slot through DFA model
1799 to check resource conflicts involving instruction u
1800 at cycle c given the partial schedule PS.
1801 'add_to_partial_schedule_at_time(u, PS, c)'
1802 Add the node/instruction u to the partial schedule
1803 PS at time c.
1804 'calculate_register_pressure(PS)'
1805 Given a schedule of instructions, calculate the register
1806 pressure it implies. One implementation could be the
1807 maximum number of overlapping live ranges.
1808 'maxRP' The maximum allowed register pressure, it is usually derived from the number
1809 registers available in the hardware.
1811 1. II = MII.
1812 2. PS = empty list
1813 3. for each node u in O in pre-computed order
1814 4. if (PSP(u) != Q && PSS(u) == Q) then
1815 5. Early_start(u) = max ( t(v) + l(v) - d(v,u)*II ) over all every v in PSP(u).
1816 6. start = Early_start; end = Early_start + II - 1; step = 1
1817 11. else if (PSP(u) == Q && PSS(u) != Q) then
1818 12. Late_start(u) = min ( t(v) - l(v) + d(v,u)*II ) over all every v in PSS(u).
1819 13. start = Late_start; end = Late_start - II + 1; step = -1
1820 14. else if (PSP(u) != Q && PSS(u) != Q) then
1821 15. Early_start(u) = max ( t(v) + l(v) - d(v,u)*II ) over all every v in PSP(u).
1822 16. Late_start(u) = min ( t(v) - l(v) + d(v,u)*II ) over all every v in PSS(u).
1823 17. start = Early_start;
1824 18. end = min(Early_start + II - 1 , Late_start);
1825 19. step = 1
1826 20. else "if (PSP(u) == Q && PSS(u) == Q)"
1827 21. start = ASAP(u); end = start + II - 1; step = 1
1828 22. endif
1830 23. success = false
1831 24. for (c = start ; c != end ; c += step)
1832 25. if check_hardware_resources_conflicts(u, PS, c) then
1833 26. add_to_partial_schedule_at_time(u, PS, c)
1834 27. success = true
1835 28. break
1836 29. endif
1837 30. endfor
1838 31. if (success == false) then
1839 32. II = II + 1
1840 33. if (II > maxII) then
1841 34. finish - failed to schedule
1842 35. endif
1843 36. goto 2.
1844 37. endif
1845 38. endfor
1846 39. if (calculate_register_pressure(PS) > maxRP) then
1847 40. goto 32.
1848 41. endif
1849 42. compute epilogue & prologue
1850 43. finish - succeeded to schedule
1852 ??? The algorithm restricts the scheduling window to II cycles.
1853 In rare cases, it may be better to allow windows of II+1 cycles.
1854 The window would then start and end on the same row, but with
1855 different "must precede" and "must follow" requirements. */
1857 /* A limit on the number of cycles that resource conflicts can span. ??? Should
1858 be provided by DFA, and be dependent on the type of insn scheduled. Currently
1859 set to 0 to save compile time. */
1860 #define DFA_HISTORY SMS_DFA_HISTORY
1862 /* A threshold for the number of repeated unsuccessful attempts to insert
1863 an empty row, before we flush the partial schedule and start over. */
1864 #define MAX_SPLIT_NUM 10
1865 /* Given the partial schedule PS, this function calculates and returns the
1866 cycles in which we can schedule the node with the given index I.
1867 NOTE: Here we do the backtracking in SMS, in some special cases. We have
1868 noticed that there are several cases in which we fail to SMS the loop
1869 because the sched window of a node is empty due to tight data-deps. In
1870 such cases we want to unschedule some of the predecessors/successors
1871 until we get non-empty scheduling window. It returns -1 if the
1872 scheduling window is empty and zero otherwise. */
1874 static int
1875 get_sched_window (partial_schedule_ptr ps, ddg_node_ptr u_node,
1876 sbitmap sched_nodes, int ii, int *start_p, int *step_p,
1877 int *end_p)
1879 int start, step, end;
1880 int early_start, late_start;
1881 ddg_edge_ptr e;
1882 sbitmap psp = sbitmap_alloc (ps->g->num_nodes);
1883 sbitmap pss = sbitmap_alloc (ps->g->num_nodes);
1884 sbitmap u_node_preds = NODE_PREDECESSORS (u_node);
1885 sbitmap u_node_succs = NODE_SUCCESSORS (u_node);
1886 int psp_not_empty;
1887 int pss_not_empty;
1888 int count_preds;
1889 int count_succs;
1891 /* 1. compute sched window for u (start, end, step). */
1892 bitmap_clear (psp);
1893 bitmap_clear (pss);
1894 psp_not_empty = bitmap_and (psp, u_node_preds, sched_nodes);
1895 pss_not_empty = bitmap_and (pss, u_node_succs, sched_nodes);
1897 /* We first compute a forward range (start <= end), then decide whether
1898 to reverse it. */
1899 early_start = INT_MIN;
1900 late_start = INT_MAX;
1901 start = INT_MIN;
1902 end = INT_MAX;
1903 step = 1;
1905 count_preds = 0;
1906 count_succs = 0;
1908 if (dump_file && (psp_not_empty || pss_not_empty))
1910 fprintf (dump_file, "\nAnalyzing dependencies for node %d (INSN %d)"
1911 "; ii = %d\n\n", u_node->cuid, INSN_UID (u_node->insn), ii);
1912 fprintf (dump_file, "%11s %11s %11s %11s %5s\n",
1913 "start", "early start", "late start", "end", "time");
1914 fprintf (dump_file, "=========== =========== =========== ==========="
1915 " =====\n");
1917 /* Calculate early_start and limit end. Both bounds are inclusive. */
1918 if (psp_not_empty)
1919 for (e = u_node->in; e != 0; e = e->next_in)
1921 int v = e->src->cuid;
1923 if (bitmap_bit_p (sched_nodes, v))
1925 int p_st = SCHED_TIME (v);
1926 int earliest = p_st + e->latency - (e->distance * ii);
1927 int latest = (e->data_type == MEM_DEP ? p_st + ii - 1 : INT_MAX);
1929 if (dump_file)
1931 fprintf (dump_file, "%11s %11d %11s %11d %5d",
1932 "", earliest, "", latest, p_st);
1933 print_ddg_edge (dump_file, e);
1934 fprintf (dump_file, "\n");
1937 early_start = MAX (early_start, earliest);
1938 end = MIN (end, latest);
1940 if (e->type == TRUE_DEP && e->data_type == REG_DEP)
1941 count_preds++;
1945 /* Calculate late_start and limit start. Both bounds are inclusive. */
1946 if (pss_not_empty)
1947 for (e = u_node->out; e != 0; e = e->next_out)
1949 int v = e->dest->cuid;
1951 if (bitmap_bit_p (sched_nodes, v))
1953 int s_st = SCHED_TIME (v);
1954 int earliest = (e->data_type == MEM_DEP ? s_st - ii + 1 : INT_MIN);
1955 int latest = s_st - e->latency + (e->distance * ii);
1957 if (dump_file)
1959 fprintf (dump_file, "%11d %11s %11d %11s %5d",
1960 earliest, "", latest, "", s_st);
1961 print_ddg_edge (dump_file, e);
1962 fprintf (dump_file, "\n");
1965 start = MAX (start, earliest);
1966 late_start = MIN (late_start, latest);
1968 if (e->type == TRUE_DEP && e->data_type == REG_DEP)
1969 count_succs++;
1973 if (dump_file && (psp_not_empty || pss_not_empty))
1975 fprintf (dump_file, "----------- ----------- ----------- -----------"
1976 " -----\n");
1977 fprintf (dump_file, "%11d %11d %11d %11d %5s %s\n",
1978 start, early_start, late_start, end, "",
1979 "(max, max, min, min)");
1982 /* Get a target scheduling window no bigger than ii. */
1983 if (early_start == INT_MIN && late_start == INT_MAX)
1984 early_start = NODE_ASAP (u_node);
1985 else if (early_start == INT_MIN)
1986 early_start = late_start - (ii - 1);
1987 late_start = MIN (late_start, early_start + (ii - 1));
1989 /* Apply memory dependence limits. */
1990 start = MAX (start, early_start);
1991 end = MIN (end, late_start);
1993 if (dump_file && (psp_not_empty || pss_not_empty))
1994 fprintf (dump_file, "%11s %11d %11d %11s %5s final window\n",
1995 "", start, end, "", "");
1997 /* If there are at least as many successors as predecessors, schedule the
1998 node close to its successors. */
1999 if (pss_not_empty && count_succs >= count_preds)
2001 std::swap (start, end);
2002 step = -1;
2005 /* Now that we've finalized the window, make END an exclusive rather
2006 than an inclusive bound. */
2007 end += step;
2009 *start_p = start;
2010 *step_p = step;
2011 *end_p = end;
2012 sbitmap_free (psp);
2013 sbitmap_free (pss);
2015 if ((start >= end && step == 1) || (start <= end && step == -1))
2017 if (dump_file)
2018 fprintf (dump_file, "\nEmpty window: start=%d, end=%d, step=%d\n",
2019 start, end, step);
2020 return -1;
2023 return 0;
2026 /* Calculate MUST_PRECEDE/MUST_FOLLOW bitmaps of U_NODE; which is the
2027 node currently been scheduled. At the end of the calculation
2028 MUST_PRECEDE/MUST_FOLLOW contains all predecessors/successors of
2029 U_NODE which are (1) already scheduled in the first/last row of
2030 U_NODE's scheduling window, (2) whose dependence inequality with U
2031 becomes an equality when U is scheduled in this same row, and (3)
2032 whose dependence latency is zero.
2034 The first and last rows are calculated using the following parameters:
2035 START/END rows - The cycles that begins/ends the traversal on the window;
2036 searching for an empty cycle to schedule U_NODE.
2037 STEP - The direction in which we traverse the window.
2038 II - The initiation interval. */
2040 static void
2041 calculate_must_precede_follow (ddg_node_ptr u_node, int start, int end,
2042 int step, int ii, sbitmap sched_nodes,
2043 sbitmap must_precede, sbitmap must_follow)
2045 ddg_edge_ptr e;
2046 int first_cycle_in_window, last_cycle_in_window;
2048 gcc_assert (must_precede && must_follow);
2050 /* Consider the following scheduling window:
2051 {first_cycle_in_window, first_cycle_in_window+1, ...,
2052 last_cycle_in_window}. If step is 1 then the following will be
2053 the order we traverse the window: {start=first_cycle_in_window,
2054 first_cycle_in_window+1, ..., end=last_cycle_in_window+1},
2055 or {start=last_cycle_in_window, last_cycle_in_window-1, ...,
2056 end=first_cycle_in_window-1} if step is -1. */
2057 first_cycle_in_window = (step == 1) ? start : end - step;
2058 last_cycle_in_window = (step == 1) ? end - step : start;
2060 bitmap_clear (must_precede);
2061 bitmap_clear (must_follow);
2063 if (dump_file)
2064 fprintf (dump_file, "\nmust_precede: ");
2066 /* Instead of checking if:
2067 (SMODULO (SCHED_TIME (e->src), ii) == first_row_in_window)
2068 && ((SCHED_TIME (e->src) + e->latency - (e->distance * ii)) ==
2069 first_cycle_in_window)
2070 && e->latency == 0
2071 we use the fact that latency is non-negative:
2072 SCHED_TIME (e->src) - (e->distance * ii) <=
2073 SCHED_TIME (e->src) + e->latency - (e->distance * ii)) <=
2074 first_cycle_in_window
2075 and check only if
2076 SCHED_TIME (e->src) - (e->distance * ii) == first_cycle_in_window */
2077 for (e = u_node->in; e != 0; e = e->next_in)
2078 if (bitmap_bit_p (sched_nodes, e->src->cuid)
2079 && ((SCHED_TIME (e->src->cuid) - (e->distance * ii)) ==
2080 first_cycle_in_window))
2082 if (dump_file)
2083 fprintf (dump_file, "%d ", e->src->cuid);
2085 bitmap_set_bit (must_precede, e->src->cuid);
2088 if (dump_file)
2089 fprintf (dump_file, "\nmust_follow: ");
2091 /* Instead of checking if:
2092 (SMODULO (SCHED_TIME (e->dest), ii) == last_row_in_window)
2093 && ((SCHED_TIME (e->dest) - e->latency + (e->distance * ii)) ==
2094 last_cycle_in_window)
2095 && e->latency == 0
2096 we use the fact that latency is non-negative:
2097 SCHED_TIME (e->dest) + (e->distance * ii) >=
2098 SCHED_TIME (e->dest) - e->latency + (e->distance * ii)) >=
2099 last_cycle_in_window
2100 and check only if
2101 SCHED_TIME (e->dest) + (e->distance * ii) == last_cycle_in_window */
2102 for (e = u_node->out; e != 0; e = e->next_out)
2103 if (bitmap_bit_p (sched_nodes, e->dest->cuid)
2104 && ((SCHED_TIME (e->dest->cuid) + (e->distance * ii)) ==
2105 last_cycle_in_window))
2107 if (dump_file)
2108 fprintf (dump_file, "%d ", e->dest->cuid);
2110 bitmap_set_bit (must_follow, e->dest->cuid);
2113 if (dump_file)
2114 fprintf (dump_file, "\n");
2117 /* Return 1 if U_NODE can be scheduled in CYCLE. Use the following
2118 parameters to decide if that's possible:
2119 PS - The partial schedule.
2120 U - The serial number of U_NODE.
2121 NUM_SPLITS - The number of row splits made so far.
2122 MUST_PRECEDE - The nodes that must precede U_NODE. (only valid at
2123 the first row of the scheduling window)
2124 MUST_FOLLOW - The nodes that must follow U_NODE. (only valid at the
2125 last row of the scheduling window) */
2127 static bool
2128 try_scheduling_node_in_cycle (partial_schedule_ptr ps,
2129 int u, int cycle, sbitmap sched_nodes,
2130 int *num_splits, sbitmap must_precede,
2131 sbitmap must_follow)
2133 ps_insn_ptr psi;
2134 bool success = 0;
2136 verify_partial_schedule (ps, sched_nodes);
2137 psi = ps_add_node_check_conflicts (ps, u, cycle, must_precede, must_follow);
2138 if (psi)
2140 SCHED_TIME (u) = cycle;
2141 bitmap_set_bit (sched_nodes, u);
2142 success = 1;
2143 *num_splits = 0;
2144 if (dump_file)
2145 fprintf (dump_file, "Scheduled w/o split in %d\n", cycle);
2149 return success;
2152 /* This function implements the scheduling algorithm for SMS according to the
2153 above algorithm. */
2154 static partial_schedule_ptr
2155 sms_schedule_by_order (ddg_ptr g, int mii, int maxii, int *nodes_order)
2157 int ii = mii;
2158 int i, c, success, num_splits = 0;
2159 int flush_and_start_over = true;
2160 int num_nodes = g->num_nodes;
2161 int start, end, step; /* Place together into one struct? */
2162 sbitmap sched_nodes = sbitmap_alloc (num_nodes);
2163 sbitmap must_precede = sbitmap_alloc (num_nodes);
2164 sbitmap must_follow = sbitmap_alloc (num_nodes);
2165 sbitmap tobe_scheduled = sbitmap_alloc (num_nodes);
2167 partial_schedule_ptr ps = create_partial_schedule (ii, g, DFA_HISTORY);
2169 bitmap_ones (tobe_scheduled);
2170 bitmap_clear (sched_nodes);
2172 while (flush_and_start_over && (ii < maxii))
2175 if (dump_file)
2176 fprintf (dump_file, "Starting with ii=%d\n", ii);
2177 flush_and_start_over = false;
2178 bitmap_clear (sched_nodes);
2180 for (i = 0; i < num_nodes; i++)
2182 int u = nodes_order[i];
2183 ddg_node_ptr u_node = &ps->g->nodes[u];
2184 rtx_insn *insn = u_node->insn;
2186 if (!NONDEBUG_INSN_P (insn))
2188 bitmap_clear_bit (tobe_scheduled, u);
2189 continue;
2192 if (bitmap_bit_p (sched_nodes, u))
2193 continue;
2195 /* Try to get non-empty scheduling window. */
2196 success = 0;
2197 if (get_sched_window (ps, u_node, sched_nodes, ii, &start,
2198 &step, &end) == 0)
2200 if (dump_file)
2201 fprintf (dump_file, "\nTrying to schedule node %d "
2202 "INSN = %d in (%d .. %d) step %d\n", u, (INSN_UID
2203 (g->nodes[u].insn)), start, end, step);
2205 gcc_assert ((step > 0 && start < end)
2206 || (step < 0 && start > end));
2208 calculate_must_precede_follow (u_node, start, end, step, ii,
2209 sched_nodes, must_precede,
2210 must_follow);
2212 for (c = start; c != end; c += step)
2214 sbitmap tmp_precede, tmp_follow;
2216 set_must_precede_follow (&tmp_follow, must_follow,
2217 &tmp_precede, must_precede,
2218 c, start, end, step);
2219 success =
2220 try_scheduling_node_in_cycle (ps, u, c,
2221 sched_nodes,
2222 &num_splits, tmp_precede,
2223 tmp_follow);
2224 if (success)
2225 break;
2228 verify_partial_schedule (ps, sched_nodes);
2230 if (!success)
2232 int split_row;
2234 if (ii++ == maxii)
2235 break;
2237 if (num_splits >= MAX_SPLIT_NUM)
2239 num_splits = 0;
2240 flush_and_start_over = true;
2241 verify_partial_schedule (ps, sched_nodes);
2242 reset_partial_schedule (ps, ii);
2243 verify_partial_schedule (ps, sched_nodes);
2244 break;
2247 num_splits++;
2248 /* The scheduling window is exclusive of 'end'
2249 whereas compute_split_window() expects an inclusive,
2250 ordered range. */
2251 if (step == 1)
2252 split_row = compute_split_row (sched_nodes, start, end - 1,
2253 ps->ii, u_node);
2254 else
2255 split_row = compute_split_row (sched_nodes, end + 1, start,
2256 ps->ii, u_node);
2258 ps_insert_empty_row (ps, split_row, sched_nodes);
2259 i--; /* Go back and retry node i. */
2261 if (dump_file)
2262 fprintf (dump_file, "num_splits=%d\n", num_splits);
2265 /* ??? If (success), check register pressure estimates. */
2266 } /* Continue with next node. */
2267 } /* While flush_and_start_over. */
2268 if (ii >= maxii)
2270 free_partial_schedule (ps);
2271 ps = NULL;
2273 else
2274 gcc_assert (bitmap_equal_p (tobe_scheduled, sched_nodes));
2276 sbitmap_free (sched_nodes);
2277 sbitmap_free (must_precede);
2278 sbitmap_free (must_follow);
2279 sbitmap_free (tobe_scheduled);
2281 return ps;
2284 /* This function inserts a new empty row into PS at the position
2285 according to SPLITROW, keeping all already scheduled instructions
2286 intact and updating their SCHED_TIME and cycle accordingly. */
2287 static void
2288 ps_insert_empty_row (partial_schedule_ptr ps, int split_row,
2289 sbitmap sched_nodes)
2291 ps_insn_ptr crr_insn;
2292 ps_insn_ptr *rows_new;
2293 int ii = ps->ii;
2294 int new_ii = ii + 1;
2295 int row;
2296 int *rows_length_new;
2298 verify_partial_schedule (ps, sched_nodes);
2300 /* We normalize sched_time and rotate ps to have only non-negative sched
2301 times, for simplicity of updating cycles after inserting new row. */
2302 split_row -= ps->min_cycle;
2303 split_row = SMODULO (split_row, ii);
2304 if (dump_file)
2305 fprintf (dump_file, "split_row=%d\n", split_row);
2307 reset_sched_times (ps, PS_MIN_CYCLE (ps));
2308 rotate_partial_schedule (ps, PS_MIN_CYCLE (ps));
2310 rows_new = (ps_insn_ptr *) xcalloc (new_ii, sizeof (ps_insn_ptr));
2311 rows_length_new = (int *) xcalloc (new_ii, sizeof (int));
2312 for (row = 0; row < split_row; row++)
2314 rows_new[row] = ps->rows[row];
2315 rows_length_new[row] = ps->rows_length[row];
2316 ps->rows[row] = NULL;
2317 for (crr_insn = rows_new[row];
2318 crr_insn; crr_insn = crr_insn->next_in_row)
2320 int u = crr_insn->id;
2321 int new_time = SCHED_TIME (u) + (SCHED_TIME (u) / ii);
2323 SCHED_TIME (u) = new_time;
2324 crr_insn->cycle = new_time;
2325 SCHED_ROW (u) = new_time % new_ii;
2326 SCHED_STAGE (u) = new_time / new_ii;
2331 rows_new[split_row] = NULL;
2333 for (row = split_row; row < ii; row++)
2335 rows_new[row + 1] = ps->rows[row];
2336 rows_length_new[row + 1] = ps->rows_length[row];
2337 ps->rows[row] = NULL;
2338 for (crr_insn = rows_new[row + 1];
2339 crr_insn; crr_insn = crr_insn->next_in_row)
2341 int u = crr_insn->id;
2342 int new_time = SCHED_TIME (u) + (SCHED_TIME (u) / ii) + 1;
2344 SCHED_TIME (u) = new_time;
2345 crr_insn->cycle = new_time;
2346 SCHED_ROW (u) = new_time % new_ii;
2347 SCHED_STAGE (u) = new_time / new_ii;
2351 /* Updating ps. */
2352 ps->min_cycle = ps->min_cycle + ps->min_cycle / ii
2353 + (SMODULO (ps->min_cycle, ii) >= split_row ? 1 : 0);
2354 ps->max_cycle = ps->max_cycle + ps->max_cycle / ii
2355 + (SMODULO (ps->max_cycle, ii) >= split_row ? 1 : 0);
2356 free (ps->rows);
2357 ps->rows = rows_new;
2358 free (ps->rows_length);
2359 ps->rows_length = rows_length_new;
2360 ps->ii = new_ii;
2361 gcc_assert (ps->min_cycle >= 0);
2363 verify_partial_schedule (ps, sched_nodes);
2365 if (dump_file)
2366 fprintf (dump_file, "min_cycle=%d, max_cycle=%d\n", ps->min_cycle,
2367 ps->max_cycle);
2370 /* Given U_NODE which is the node that failed to be scheduled; LOW and
2371 UP which are the boundaries of it's scheduling window; compute using
2372 SCHED_NODES and II a row in the partial schedule that can be split
2373 which will separate a critical predecessor from a critical successor
2374 thereby expanding the window, and return it. */
2375 static int
2376 compute_split_row (sbitmap sched_nodes, int low, int up, int ii,
2377 ddg_node_ptr u_node)
2379 ddg_edge_ptr e;
2380 int lower = INT_MIN, upper = INT_MAX;
2381 int crit_pred = -1;
2382 int crit_succ = -1;
2383 int crit_cycle;
2385 for (e = u_node->in; e != 0; e = e->next_in)
2387 int v = e->src->cuid;
2389 if (bitmap_bit_p (sched_nodes, v)
2390 && (low == SCHED_TIME (v) + e->latency - (e->distance * ii)))
2391 if (SCHED_TIME (v) > lower)
2393 crit_pred = v;
2394 lower = SCHED_TIME (v);
2398 if (crit_pred >= 0)
2400 crit_cycle = SCHED_TIME (crit_pred) + 1;
2401 return SMODULO (crit_cycle, ii);
2404 for (e = u_node->out; e != 0; e = e->next_out)
2406 int v = e->dest->cuid;
2408 if (bitmap_bit_p (sched_nodes, v)
2409 && (up == SCHED_TIME (v) - e->latency + (e->distance * ii)))
2410 if (SCHED_TIME (v) < upper)
2412 crit_succ = v;
2413 upper = SCHED_TIME (v);
2417 if (crit_succ >= 0)
2419 crit_cycle = SCHED_TIME (crit_succ);
2420 return SMODULO (crit_cycle, ii);
2423 if (dump_file)
2424 fprintf (dump_file, "Both crit_pred and crit_succ are NULL\n");
2426 return SMODULO ((low + up + 1) / 2, ii);
2429 static void
2430 verify_partial_schedule (partial_schedule_ptr ps, sbitmap sched_nodes)
2432 int row;
2433 ps_insn_ptr crr_insn;
2435 for (row = 0; row < ps->ii; row++)
2437 int length = 0;
2439 for (crr_insn = ps->rows[row]; crr_insn; crr_insn = crr_insn->next_in_row)
2441 int u = crr_insn->id;
2443 length++;
2444 gcc_assert (bitmap_bit_p (sched_nodes, u));
2445 /* ??? Test also that all nodes of sched_nodes are in ps, perhaps by
2446 popcount (sched_nodes) == number of insns in ps. */
2447 gcc_assert (SCHED_TIME (u) >= ps->min_cycle);
2448 gcc_assert (SCHED_TIME (u) <= ps->max_cycle);
2451 gcc_assert (ps->rows_length[row] == length);
2456 /* This page implements the algorithm for ordering the nodes of a DDG
2457 for modulo scheduling, activated through the
2458 "int sms_order_nodes (ddg_ptr, int mii, int * result)" API. */
2460 #define ORDER_PARAMS(x) ((struct node_order_params *) (x)->aux.info)
2461 #define ASAP(x) (ORDER_PARAMS ((x))->asap)
2462 #define ALAP(x) (ORDER_PARAMS ((x))->alap)
2463 #define HEIGHT(x) (ORDER_PARAMS ((x))->height)
2464 #define MOB(x) (ALAP ((x)) - ASAP ((x)))
2465 #define DEPTH(x) (ASAP ((x)))
2467 typedef struct node_order_params * nopa;
2469 static void order_nodes_of_sccs (ddg_all_sccs_ptr, int * result);
2470 static int order_nodes_in_scc (ddg_ptr, sbitmap, sbitmap, int*, int);
2471 static nopa calculate_order_params (ddg_ptr, int, int *);
2472 static int find_max_asap (ddg_ptr, sbitmap);
2473 static int find_max_hv_min_mob (ddg_ptr, sbitmap);
2474 static int find_max_dv_min_mob (ddg_ptr, sbitmap);
2476 enum sms_direction {BOTTOMUP, TOPDOWN};
2478 struct node_order_params
2480 int asap;
2481 int alap;
2482 int height;
2485 /* Check if NODE_ORDER contains a permutation of 0 .. NUM_NODES-1. */
2486 static void
2487 check_nodes_order (int *node_order, int num_nodes)
2489 int i;
2490 sbitmap tmp = sbitmap_alloc (num_nodes);
2492 bitmap_clear (tmp);
2494 if (dump_file)
2495 fprintf (dump_file, "SMS final nodes order: \n");
2497 for (i = 0; i < num_nodes; i++)
2499 int u = node_order[i];
2501 if (dump_file)
2502 fprintf (dump_file, "%d ", u);
2503 gcc_assert (u < num_nodes && u >= 0 && !bitmap_bit_p (tmp, u));
2505 bitmap_set_bit (tmp, u);
2508 if (dump_file)
2509 fprintf (dump_file, "\n");
2511 sbitmap_free (tmp);
2514 /* Order the nodes of G for scheduling and pass the result in
2515 NODE_ORDER. Also set aux.count of each node to ASAP.
2516 Put maximal ASAP to PMAX_ASAP. Return the recMII for the given DDG. */
2517 static int
2518 sms_order_nodes (ddg_ptr g, int mii, int * node_order, int *pmax_asap)
2520 int i;
2521 int rec_mii = 0;
2522 ddg_all_sccs_ptr sccs = create_ddg_all_sccs (g);
2524 nopa nops = calculate_order_params (g, mii, pmax_asap);
2526 if (dump_file)
2527 print_sccs (dump_file, sccs, g);
2529 order_nodes_of_sccs (sccs, node_order);
2531 if (sccs->num_sccs > 0)
2532 /* First SCC has the largest recurrence_length. */
2533 rec_mii = sccs->sccs[0]->recurrence_length;
2535 /* Save ASAP before destroying node_order_params. */
2536 for (i = 0; i < g->num_nodes; i++)
2538 ddg_node_ptr v = &g->nodes[i];
2539 v->aux.count = ASAP (v);
2542 free (nops);
2543 free_ddg_all_sccs (sccs);
2544 check_nodes_order (node_order, g->num_nodes);
2546 return rec_mii;
2549 static void
2550 order_nodes_of_sccs (ddg_all_sccs_ptr all_sccs, int * node_order)
2552 int i, pos = 0;
2553 ddg_ptr g = all_sccs->ddg;
2554 int num_nodes = g->num_nodes;
2555 sbitmap prev_sccs = sbitmap_alloc (num_nodes);
2556 sbitmap on_path = sbitmap_alloc (num_nodes);
2557 sbitmap tmp = sbitmap_alloc (num_nodes);
2558 sbitmap ones = sbitmap_alloc (num_nodes);
2560 bitmap_clear (prev_sccs);
2561 bitmap_ones (ones);
2563 /* Perform the node ordering starting from the SCC with the highest recMII.
2564 For each SCC order the nodes according to their ASAP/ALAP/HEIGHT etc. */
2565 for (i = 0; i < all_sccs->num_sccs; i++)
2567 ddg_scc_ptr scc = all_sccs->sccs[i];
2569 /* Add nodes on paths from previous SCCs to the current SCC. */
2570 find_nodes_on_paths (on_path, g, prev_sccs, scc->nodes);
2571 bitmap_ior (tmp, scc->nodes, on_path);
2573 /* Add nodes on paths from the current SCC to previous SCCs. */
2574 find_nodes_on_paths (on_path, g, scc->nodes, prev_sccs);
2575 bitmap_ior (tmp, tmp, on_path);
2577 /* Remove nodes of previous SCCs from current extended SCC. */
2578 bitmap_and_compl (tmp, tmp, prev_sccs);
2580 pos = order_nodes_in_scc (g, prev_sccs, tmp, node_order, pos);
2581 /* Above call to order_nodes_in_scc updated prev_sccs |= tmp. */
2584 /* Handle the remaining nodes that do not belong to any scc. Each call
2585 to order_nodes_in_scc handles a single connected component. */
2586 while (pos < g->num_nodes)
2588 bitmap_and_compl (tmp, ones, prev_sccs);
2589 pos = order_nodes_in_scc (g, prev_sccs, tmp, node_order, pos);
2591 sbitmap_free (prev_sccs);
2592 sbitmap_free (on_path);
2593 sbitmap_free (tmp);
2594 sbitmap_free (ones);
2597 /* MII is needed if we consider backarcs (that do not close recursive cycles). */
2598 static struct node_order_params *
2599 calculate_order_params (ddg_ptr g, int mii ATTRIBUTE_UNUSED, int *pmax_asap)
2601 int u;
2602 int max_asap;
2603 int num_nodes = g->num_nodes;
2604 ddg_edge_ptr e;
2605 /* Allocate a place to hold ordering params for each node in the DDG. */
2606 nopa node_order_params_arr;
2608 /* Initialize of ASAP/ALAP/HEIGHT to zero. */
2609 node_order_params_arr = (nopa) xcalloc (num_nodes,
2610 sizeof (struct node_order_params));
2612 /* Set the aux pointer of each node to point to its order_params structure. */
2613 for (u = 0; u < num_nodes; u++)
2614 g->nodes[u].aux.info = &node_order_params_arr[u];
2616 /* Disregarding a backarc from each recursive cycle to obtain a DAG,
2617 calculate ASAP, ALAP, mobility, distance, and height for each node
2618 in the dependence (direct acyclic) graph. */
2620 /* We assume that the nodes in the array are in topological order. */
2622 max_asap = 0;
2623 for (u = 0; u < num_nodes; u++)
2625 ddg_node_ptr u_node = &g->nodes[u];
2627 ASAP (u_node) = 0;
2628 for (e = u_node->in; e; e = e->next_in)
2629 if (e->distance == 0)
2630 ASAP (u_node) = MAX (ASAP (u_node),
2631 ASAP (e->src) + e->latency);
2632 max_asap = MAX (max_asap, ASAP (u_node));
2635 for (u = num_nodes - 1; u > -1; u--)
2637 ddg_node_ptr u_node = &g->nodes[u];
2639 ALAP (u_node) = max_asap;
2640 HEIGHT (u_node) = 0;
2641 for (e = u_node->out; e; e = e->next_out)
2642 if (e->distance == 0)
2644 ALAP (u_node) = MIN (ALAP (u_node),
2645 ALAP (e->dest) - e->latency);
2646 HEIGHT (u_node) = MAX (HEIGHT (u_node),
2647 HEIGHT (e->dest) + e->latency);
2650 if (dump_file)
2652 fprintf (dump_file, "\nOrder params\n");
2653 for (u = 0; u < num_nodes; u++)
2655 ddg_node_ptr u_node = &g->nodes[u];
2657 fprintf (dump_file, "node %d, ASAP: %d, ALAP: %d, HEIGHT: %d\n", u,
2658 ASAP (u_node), ALAP (u_node), HEIGHT (u_node));
2662 *pmax_asap = max_asap;
2663 return node_order_params_arr;
2666 static int
2667 find_max_asap (ddg_ptr g, sbitmap nodes)
2669 unsigned int u = 0;
2670 int max_asap = -1;
2671 int result = -1;
2672 sbitmap_iterator sbi;
2674 EXECUTE_IF_SET_IN_BITMAP (nodes, 0, u, sbi)
2676 ddg_node_ptr u_node = &g->nodes[u];
2678 if (max_asap < ASAP (u_node))
2680 max_asap = ASAP (u_node);
2681 result = u;
2684 return result;
2687 static int
2688 find_max_hv_min_mob (ddg_ptr g, sbitmap nodes)
2690 unsigned int u = 0;
2691 int max_hv = -1;
2692 int min_mob = INT_MAX;
2693 int result = -1;
2694 sbitmap_iterator sbi;
2696 EXECUTE_IF_SET_IN_BITMAP (nodes, 0, u, sbi)
2698 ddg_node_ptr u_node = &g->nodes[u];
2700 if (max_hv < HEIGHT (u_node))
2702 max_hv = HEIGHT (u_node);
2703 min_mob = MOB (u_node);
2704 result = u;
2706 else if ((max_hv == HEIGHT (u_node))
2707 && (min_mob > MOB (u_node)))
2709 min_mob = MOB (u_node);
2710 result = u;
2713 return result;
2716 static int
2717 find_max_dv_min_mob (ddg_ptr g, sbitmap nodes)
2719 unsigned int u = 0;
2720 int max_dv = -1;
2721 int min_mob = INT_MAX;
2722 int result = -1;
2723 sbitmap_iterator sbi;
2725 EXECUTE_IF_SET_IN_BITMAP (nodes, 0, u, sbi)
2727 ddg_node_ptr u_node = &g->nodes[u];
2729 if (max_dv < DEPTH (u_node))
2731 max_dv = DEPTH (u_node);
2732 min_mob = MOB (u_node);
2733 result = u;
2735 else if ((max_dv == DEPTH (u_node))
2736 && (min_mob > MOB (u_node)))
2738 min_mob = MOB (u_node);
2739 result = u;
2742 return result;
2745 /* Places the nodes of SCC into the NODE_ORDER array starting
2746 at position POS, according to the SMS ordering algorithm.
2747 NODES_ORDERED (in&out parameter) holds the bitset of all nodes in
2748 the NODE_ORDER array, starting from position zero. */
2749 static int
2750 order_nodes_in_scc (ddg_ptr g, sbitmap nodes_ordered, sbitmap scc,
2751 int * node_order, int pos)
2753 enum sms_direction dir;
2754 int num_nodes = g->num_nodes;
2755 sbitmap workset = sbitmap_alloc (num_nodes);
2756 sbitmap tmp = sbitmap_alloc (num_nodes);
2757 sbitmap zero_bitmap = sbitmap_alloc (num_nodes);
2758 sbitmap predecessors = sbitmap_alloc (num_nodes);
2759 sbitmap successors = sbitmap_alloc (num_nodes);
2761 bitmap_clear (predecessors);
2762 find_predecessors (predecessors, g, nodes_ordered);
2764 bitmap_clear (successors);
2765 find_successors (successors, g, nodes_ordered);
2767 bitmap_clear (tmp);
2768 if (bitmap_and (tmp, predecessors, scc))
2770 bitmap_copy (workset, tmp);
2771 dir = BOTTOMUP;
2773 else if (bitmap_and (tmp, successors, scc))
2775 bitmap_copy (workset, tmp);
2776 dir = TOPDOWN;
2778 else
2780 int u;
2782 bitmap_clear (workset);
2783 if ((u = find_max_asap (g, scc)) >= 0)
2784 bitmap_set_bit (workset, u);
2785 dir = BOTTOMUP;
2788 bitmap_clear (zero_bitmap);
2789 while (!bitmap_equal_p (workset, zero_bitmap))
2791 int v;
2792 ddg_node_ptr v_node;
2793 sbitmap v_node_preds;
2794 sbitmap v_node_succs;
2796 if (dir == TOPDOWN)
2798 while (!bitmap_equal_p (workset, zero_bitmap))
2800 v = find_max_hv_min_mob (g, workset);
2801 v_node = &g->nodes[v];
2802 node_order[pos++] = v;
2803 v_node_succs = NODE_SUCCESSORS (v_node);
2804 bitmap_and (tmp, v_node_succs, scc);
2806 /* Don't consider the already ordered successors again. */
2807 bitmap_and_compl (tmp, tmp, nodes_ordered);
2808 bitmap_ior (workset, workset, tmp);
2809 bitmap_clear_bit (workset, v);
2810 bitmap_set_bit (nodes_ordered, v);
2812 dir = BOTTOMUP;
2813 bitmap_clear (predecessors);
2814 find_predecessors (predecessors, g, nodes_ordered);
2815 bitmap_and (workset, predecessors, scc);
2817 else
2819 while (!bitmap_equal_p (workset, zero_bitmap))
2821 v = find_max_dv_min_mob (g, workset);
2822 v_node = &g->nodes[v];
2823 node_order[pos++] = v;
2824 v_node_preds = NODE_PREDECESSORS (v_node);
2825 bitmap_and (tmp, v_node_preds, scc);
2827 /* Don't consider the already ordered predecessors again. */
2828 bitmap_and_compl (tmp, tmp, nodes_ordered);
2829 bitmap_ior (workset, workset, tmp);
2830 bitmap_clear_bit (workset, v);
2831 bitmap_set_bit (nodes_ordered, v);
2833 dir = TOPDOWN;
2834 bitmap_clear (successors);
2835 find_successors (successors, g, nodes_ordered);
2836 bitmap_and (workset, successors, scc);
2839 sbitmap_free (tmp);
2840 sbitmap_free (workset);
2841 sbitmap_free (zero_bitmap);
2842 sbitmap_free (predecessors);
2843 sbitmap_free (successors);
2844 return pos;
2848 /* This page contains functions for manipulating partial-schedules during
2849 modulo scheduling. */
2851 /* Create a partial schedule and allocate a memory to hold II rows. */
2853 static partial_schedule_ptr
2854 create_partial_schedule (int ii, ddg_ptr g, int history)
2856 partial_schedule_ptr ps = XNEW (struct partial_schedule);
2857 ps->rows = (ps_insn_ptr *) xcalloc (ii, sizeof (ps_insn_ptr));
2858 ps->rows_length = (int *) xcalloc (ii, sizeof (int));
2859 ps->reg_moves.create (0);
2860 ps->ii = ii;
2861 ps->history = history;
2862 ps->min_cycle = INT_MAX;
2863 ps->max_cycle = INT_MIN;
2864 ps->g = g;
2866 return ps;
2869 /* Free the PS_INSNs in rows array of the given partial schedule.
2870 ??? Consider caching the PS_INSN's. */
2871 static void
2872 free_ps_insns (partial_schedule_ptr ps)
2874 int i;
2876 for (i = 0; i < ps->ii; i++)
2878 while (ps->rows[i])
2880 ps_insn_ptr ps_insn = ps->rows[i]->next_in_row;
2882 free (ps->rows[i]);
2883 ps->rows[i] = ps_insn;
2885 ps->rows[i] = NULL;
2889 /* Free all the memory allocated to the partial schedule. */
2891 static void
2892 free_partial_schedule (partial_schedule_ptr ps)
2894 ps_reg_move_info *move;
2895 unsigned int i;
2897 if (!ps)
2898 return;
2900 FOR_EACH_VEC_ELT (ps->reg_moves, i, move)
2901 sbitmap_free (move->uses);
2902 ps->reg_moves.release ();
2904 free_ps_insns (ps);
2905 free (ps->rows);
2906 free (ps->rows_length);
2907 free (ps);
2910 /* Clear the rows array with its PS_INSNs, and create a new one with
2911 NEW_II rows. */
2913 static void
2914 reset_partial_schedule (partial_schedule_ptr ps, int new_ii)
2916 if (!ps)
2917 return;
2918 free_ps_insns (ps);
2919 if (new_ii == ps->ii)
2920 return;
2921 ps->rows = (ps_insn_ptr *) xrealloc (ps->rows, new_ii
2922 * sizeof (ps_insn_ptr));
2923 memset (ps->rows, 0, new_ii * sizeof (ps_insn_ptr));
2924 ps->rows_length = (int *) xrealloc (ps->rows_length, new_ii * sizeof (int));
2925 memset (ps->rows_length, 0, new_ii * sizeof (int));
2926 ps->ii = new_ii;
2927 ps->min_cycle = INT_MAX;
2928 ps->max_cycle = INT_MIN;
2931 /* Prints the partial schedule as an ii rows array, for each rows
2932 print the ids of the insns in it. */
2933 void
2934 print_partial_schedule (partial_schedule_ptr ps, FILE *dump)
2936 int i;
2938 for (i = 0; i < ps->ii; i++)
2940 ps_insn_ptr ps_i = ps->rows[i];
2942 fprintf (dump, "\n[ROW %d ]: ", i);
2943 while (ps_i)
2945 rtx_insn *insn = ps_rtl_insn (ps, ps_i->id);
2947 if (JUMP_P (insn))
2948 fprintf (dump, "%d (branch), ", INSN_UID (insn));
2949 else
2950 fprintf (dump, "%d, ", INSN_UID (insn));
2952 ps_i = ps_i->next_in_row;
2957 /* Creates an object of PS_INSN and initializes it to the given parameters. */
2958 static ps_insn_ptr
2959 create_ps_insn (int id, int cycle)
2961 ps_insn_ptr ps_i = XNEW (struct ps_insn);
2963 ps_i->id = id;
2964 ps_i->next_in_row = NULL;
2965 ps_i->prev_in_row = NULL;
2966 ps_i->cycle = cycle;
2968 return ps_i;
2972 /* Removes the given PS_INSN from the partial schedule. */
2973 static void
2974 remove_node_from_ps (partial_schedule_ptr ps, ps_insn_ptr ps_i)
2976 int row;
2978 gcc_assert (ps && ps_i);
2980 row = SMODULO (ps_i->cycle, ps->ii);
2981 if (! ps_i->prev_in_row)
2983 gcc_assert (ps_i == ps->rows[row]);
2984 ps->rows[row] = ps_i->next_in_row;
2985 if (ps->rows[row])
2986 ps->rows[row]->prev_in_row = NULL;
2988 else
2990 ps_i->prev_in_row->next_in_row = ps_i->next_in_row;
2991 if (ps_i->next_in_row)
2992 ps_i->next_in_row->prev_in_row = ps_i->prev_in_row;
2995 ps->rows_length[row] -= 1;
2996 free (ps_i);
2997 return;
3000 /* Unlike what literature describes for modulo scheduling (which focuses
3001 on VLIW machines) the order of the instructions inside a cycle is
3002 important. Given the bitmaps MUST_FOLLOW and MUST_PRECEDE we know
3003 where the current instruction should go relative to the already
3004 scheduled instructions in the given cycle. Go over these
3005 instructions and find the first possible column to put it in. */
3006 static bool
3007 ps_insn_find_column (partial_schedule_ptr ps, ps_insn_ptr ps_i,
3008 sbitmap must_precede, sbitmap must_follow)
3010 ps_insn_ptr next_ps_i;
3011 ps_insn_ptr first_must_follow = NULL;
3012 ps_insn_ptr last_must_precede = NULL;
3013 ps_insn_ptr last_in_row = NULL;
3014 int row;
3016 if (! ps_i)
3017 return false;
3019 row = SMODULO (ps_i->cycle, ps->ii);
3021 /* Find the first must follow and the last must precede
3022 and insert the node immediately after the must precede
3023 but make sure that it there is no must follow after it. */
3024 for (next_ps_i = ps->rows[row];
3025 next_ps_i;
3026 next_ps_i = next_ps_i->next_in_row)
3028 if (must_follow
3029 && bitmap_bit_p (must_follow, next_ps_i->id)
3030 && ! first_must_follow)
3031 first_must_follow = next_ps_i;
3032 if (must_precede && bitmap_bit_p (must_precede, next_ps_i->id))
3034 /* If we have already met a node that must follow, then
3035 there is no possible column. */
3036 if (first_must_follow)
3037 return false;
3038 else
3039 last_must_precede = next_ps_i;
3041 /* The closing branch must be the last in the row. */
3042 if (must_precede
3043 && bitmap_bit_p (must_precede, next_ps_i->id)
3044 && JUMP_P (ps_rtl_insn (ps, next_ps_i->id)))
3045 return false;
3047 last_in_row = next_ps_i;
3050 /* The closing branch is scheduled as well. Make sure there is no
3051 dependent instruction after it as the branch should be the last
3052 instruction in the row. */
3053 if (JUMP_P (ps_rtl_insn (ps, ps_i->id)))
3055 if (first_must_follow)
3056 return false;
3057 if (last_in_row)
3059 /* Make the branch the last in the row. New instructions
3060 will be inserted at the beginning of the row or after the
3061 last must_precede instruction thus the branch is guaranteed
3062 to remain the last instruction in the row. */
3063 last_in_row->next_in_row = ps_i;
3064 ps_i->prev_in_row = last_in_row;
3065 ps_i->next_in_row = NULL;
3067 else
3068 ps->rows[row] = ps_i;
3069 return true;
3072 /* Now insert the node after INSERT_AFTER_PSI. */
3074 if (! last_must_precede)
3076 ps_i->next_in_row = ps->rows[row];
3077 ps_i->prev_in_row = NULL;
3078 if (ps_i->next_in_row)
3079 ps_i->next_in_row->prev_in_row = ps_i;
3080 ps->rows[row] = ps_i;
3082 else
3084 ps_i->next_in_row = last_must_precede->next_in_row;
3085 last_must_precede->next_in_row = ps_i;
3086 ps_i->prev_in_row = last_must_precede;
3087 if (ps_i->next_in_row)
3088 ps_i->next_in_row->prev_in_row = ps_i;
3091 return true;
3094 /* Advances the PS_INSN one column in its current row; returns false
3095 in failure and true in success. Bit N is set in MUST_FOLLOW if
3096 the node with cuid N must be come after the node pointed to by
3097 PS_I when scheduled in the same cycle. */
3098 static int
3099 ps_insn_advance_column (partial_schedule_ptr ps, ps_insn_ptr ps_i,
3100 sbitmap must_follow)
3102 ps_insn_ptr prev, next;
3103 int row;
3105 if (!ps || !ps_i)
3106 return false;
3108 row = SMODULO (ps_i->cycle, ps->ii);
3110 if (! ps_i->next_in_row)
3111 return false;
3113 /* Check if next_in_row is dependent on ps_i, both having same sched
3114 times (typically ANTI_DEP). If so, ps_i cannot skip over it. */
3115 if (must_follow && bitmap_bit_p (must_follow, ps_i->next_in_row->id))
3116 return false;
3118 /* Advance PS_I over its next_in_row in the doubly linked list. */
3119 prev = ps_i->prev_in_row;
3120 next = ps_i->next_in_row;
3122 if (ps_i == ps->rows[row])
3123 ps->rows[row] = next;
3125 ps_i->next_in_row = next->next_in_row;
3127 if (next->next_in_row)
3128 next->next_in_row->prev_in_row = ps_i;
3130 next->next_in_row = ps_i;
3131 ps_i->prev_in_row = next;
3133 next->prev_in_row = prev;
3134 if (prev)
3135 prev->next_in_row = next;
3137 return true;
3140 /* Inserts a DDG_NODE to the given partial schedule at the given cycle.
3141 Returns 0 if this is not possible and a PS_INSN otherwise. Bit N is
3142 set in MUST_PRECEDE/MUST_FOLLOW if the node with cuid N must be come
3143 before/after (respectively) the node pointed to by PS_I when scheduled
3144 in the same cycle. */
3145 static ps_insn_ptr
3146 add_node_to_ps (partial_schedule_ptr ps, int id, int cycle,
3147 sbitmap must_precede, sbitmap must_follow)
3149 ps_insn_ptr ps_i;
3150 int row = SMODULO (cycle, ps->ii);
3152 if (ps->rows_length[row] >= issue_rate)
3153 return NULL;
3155 ps_i = create_ps_insn (id, cycle);
3157 /* Finds and inserts PS_I according to MUST_FOLLOW and
3158 MUST_PRECEDE. */
3159 if (! ps_insn_find_column (ps, ps_i, must_precede, must_follow))
3161 free (ps_i);
3162 return NULL;
3165 ps->rows_length[row] += 1;
3166 return ps_i;
3169 /* Advance time one cycle. Assumes DFA is being used. */
3170 static void
3171 advance_one_cycle (void)
3173 if (targetm.sched.dfa_pre_cycle_insn)
3174 state_transition (curr_state,
3175 targetm.sched.dfa_pre_cycle_insn ());
3177 state_transition (curr_state, NULL);
3179 if (targetm.sched.dfa_post_cycle_insn)
3180 state_transition (curr_state,
3181 targetm.sched.dfa_post_cycle_insn ());
3186 /* Checks if PS has resource conflicts according to DFA, starting from
3187 FROM cycle to TO cycle; returns true if there are conflicts and false
3188 if there are no conflicts. Assumes DFA is being used. */
3189 static int
3190 ps_has_conflicts (partial_schedule_ptr ps, int from, int to)
3192 int cycle;
3194 state_reset (curr_state);
3196 for (cycle = from; cycle <= to; cycle++)
3198 ps_insn_ptr crr_insn;
3199 /* Holds the remaining issue slots in the current row. */
3200 int can_issue_more = issue_rate;
3202 /* Walk through the DFA for the current row. */
3203 for (crr_insn = ps->rows[SMODULO (cycle, ps->ii)];
3204 crr_insn;
3205 crr_insn = crr_insn->next_in_row)
3207 rtx_insn *insn = ps_rtl_insn (ps, crr_insn->id);
3209 if (!NONDEBUG_INSN_P (insn))
3210 continue;
3212 /* Check if there is room for the current insn. */
3213 if (!can_issue_more || state_dead_lock_p (curr_state))
3214 return true;
3216 /* Update the DFA state and return with failure if the DFA found
3217 resource conflicts. */
3218 if (state_transition (curr_state, insn) >= 0)
3219 return true;
3221 if (targetm.sched.variable_issue)
3222 can_issue_more =
3223 targetm.sched.variable_issue (sched_dump, sched_verbose,
3224 insn, can_issue_more);
3225 /* A naked CLOBBER or USE generates no instruction, so don't
3226 let them consume issue slots. */
3227 else if (GET_CODE (PATTERN (insn)) != USE
3228 && GET_CODE (PATTERN (insn)) != CLOBBER)
3229 can_issue_more--;
3232 /* Advance the DFA to the next cycle. */
3233 advance_one_cycle ();
3235 return false;
3238 /* Checks if the given node causes resource conflicts when added to PS at
3239 cycle C. If not the node is added to PS and returned; otherwise zero
3240 is returned. Bit N is set in MUST_PRECEDE/MUST_FOLLOW if the node with
3241 cuid N must be come before/after (respectively) the node pointed to by
3242 PS_I when scheduled in the same cycle. */
3243 ps_insn_ptr
3244 ps_add_node_check_conflicts (partial_schedule_ptr ps, int n,
3245 int c, sbitmap must_precede,
3246 sbitmap must_follow)
3248 int has_conflicts = 0;
3249 ps_insn_ptr ps_i;
3251 /* First add the node to the PS, if this succeeds check for
3252 conflicts, trying different issue slots in the same row. */
3253 if (! (ps_i = add_node_to_ps (ps, n, c, must_precede, must_follow)))
3254 return NULL; /* Failed to insert the node at the given cycle. */
3256 has_conflicts = ps_has_conflicts (ps, c, c)
3257 || (ps->history > 0
3258 && ps_has_conflicts (ps,
3259 c - ps->history,
3260 c + ps->history));
3262 /* Try different issue slots to find one that the given node can be
3263 scheduled in without conflicts. */
3264 while (has_conflicts)
3266 if (! ps_insn_advance_column (ps, ps_i, must_follow))
3267 break;
3268 has_conflicts = ps_has_conflicts (ps, c, c)
3269 || (ps->history > 0
3270 && ps_has_conflicts (ps,
3271 c - ps->history,
3272 c + ps->history));
3275 if (has_conflicts)
3277 remove_node_from_ps (ps, ps_i);
3278 return NULL;
3281 ps->min_cycle = MIN (ps->min_cycle, c);
3282 ps->max_cycle = MAX (ps->max_cycle, c);
3283 return ps_i;
3286 /* Calculate the stage count of the partial schedule PS. The calculation
3287 takes into account the rotation amount passed in ROTATION_AMOUNT. */
3289 calculate_stage_count (partial_schedule_ptr ps, int rotation_amount)
3291 int new_min_cycle = PS_MIN_CYCLE (ps) - rotation_amount;
3292 int new_max_cycle = PS_MAX_CYCLE (ps) - rotation_amount;
3293 int stage_count = CALC_STAGE_COUNT (-1, new_min_cycle, ps->ii);
3295 /* The calculation of stage count is done adding the number of stages
3296 before cycle zero and after cycle zero. */
3297 stage_count += CALC_STAGE_COUNT (new_max_cycle, 0, ps->ii);
3299 return stage_count;
3302 /* Rotate the rows of PS such that insns scheduled at time
3303 START_CYCLE will appear in row 0. Updates max/min_cycles. */
3304 void
3305 rotate_partial_schedule (partial_schedule_ptr ps, int start_cycle)
3307 int i, row, backward_rotates;
3308 int last_row = ps->ii - 1;
3310 if (start_cycle == 0)
3311 return;
3313 backward_rotates = SMODULO (start_cycle, ps->ii);
3315 /* Revisit later and optimize this into a single loop. */
3316 for (i = 0; i < backward_rotates; i++)
3318 ps_insn_ptr first_row = ps->rows[0];
3319 int first_row_length = ps->rows_length[0];
3321 for (row = 0; row < last_row; row++)
3323 ps->rows[row] = ps->rows[row + 1];
3324 ps->rows_length[row] = ps->rows_length[row + 1];
3327 ps->rows[last_row] = first_row;
3328 ps->rows_length[last_row] = first_row_length;
3331 ps->max_cycle -= start_cycle;
3332 ps->min_cycle -= start_cycle;
3335 #endif /* INSN_SCHEDULING */
3337 /* Run instruction scheduler. */
3338 /* Perform SMS module scheduling. */
3340 namespace {
3342 const pass_data pass_data_sms =
3344 RTL_PASS, /* type */
3345 "sms", /* name */
3346 OPTGROUP_NONE, /* optinfo_flags */
3347 TV_SMS, /* tv_id */
3348 0, /* properties_required */
3349 0, /* properties_provided */
3350 0, /* properties_destroyed */
3351 0, /* todo_flags_start */
3352 TODO_df_finish, /* todo_flags_finish */
3355 class pass_sms : public rtl_opt_pass
3357 public:
3358 pass_sms (gcc::context *ctxt)
3359 : rtl_opt_pass (pass_data_sms, ctxt)
3362 /* opt_pass methods: */
3363 virtual bool gate (function *)
3365 return (optimize > 0 && flag_modulo_sched);
3368 virtual unsigned int execute (function *);
3370 }; // class pass_sms
3372 unsigned int
3373 pass_sms::execute (function *fun ATTRIBUTE_UNUSED)
3375 #ifdef INSN_SCHEDULING
3376 basic_block bb;
3378 /* Collect loop information to be used in SMS. */
3379 cfg_layout_initialize (0);
3380 sms_schedule ();
3382 /* Update the life information, because we add pseudos. */
3383 max_regno = max_reg_num ();
3385 /* Finalize layout changes. */
3386 FOR_EACH_BB_FN (bb, fun)
3387 if (bb->next_bb != EXIT_BLOCK_PTR_FOR_FN (fun))
3388 bb->aux = bb->next_bb;
3389 free_dominance_info (CDI_DOMINATORS);
3390 cfg_layout_finalize ();
3391 #endif /* INSN_SCHEDULING */
3392 return 0;
3395 } // anon namespace
3397 rtl_opt_pass *
3398 make_pass_sms (gcc::context *ctxt)
3400 return new pass_sms (ctxt);