OSDN Git Service

2010-09-18 Kai Tietz <kai.tietz@onevision.com>
[pf3gnuchains/gcc-fork.git] / gcc / modulo-sched.c
1 /* Swing Modulo Scheduling implementation.
2    Copyright (C) 2004, 2005, 2006, 2007, 2008
3    Free Software Foundation, Inc.
4    Contributed by Ayal Zaks and Mustafa Hagog <zaks,mustafa@il.ibm.com>
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "tm.h"
27 #include "diagnostic-core.h"
28 #include "toplev.h"
29 #include "rtl.h"
30 #include "tm_p.h"
31 #include "hard-reg-set.h"
32 #include "regs.h"
33 #include "function.h"
34 #include "flags.h"
35 #include "insn-config.h"
36 #include "insn-attr.h"
37 #include "except.h"
38 #include "toplev.h"
39 #include "recog.h"
40 #include "sched-int.h"
41 #include "target.h"
42 #include "cfglayout.h"
43 #include "cfgloop.h"
44 #include "cfghooks.h"
45 #include "expr.h"
46 #include "params.h"
47 #include "gcov-io.h"
48 #include "ddg.h"
49 #include "timevar.h"
50 #include "tree-pass.h"
51 #include "dbgcnt.h"
52 #include "df.h"
53
54 #ifdef INSN_SCHEDULING
55
56 /* This file contains the implementation of the Swing Modulo Scheduler,
57    described in the following references:
58    [1] J. Llosa, A. Gonzalez, E. Ayguade, M. Valero., and J. Eckhardt.
59        Lifetime--sensitive modulo scheduling in a production environment.
60        IEEE Trans. on Comps., 50(3), March 2001
61    [2] J. Llosa, A. Gonzalez, E. Ayguade, and M. Valero.
62        Swing Modulo Scheduling: A Lifetime Sensitive Approach.
63        PACT '96 , pages 80-87, October 1996 (Boston - Massachusetts - USA).
64
65    The basic structure is:
66    1. Build a data-dependence graph (DDG) for each loop.
67    2. Use the DDG to order the insns of a loop (not in topological order
68       necessarily, but rather) trying to place each insn after all its
69       predecessors _or_ after all its successors.
70    3. Compute MII: a lower bound on the number of cycles to schedule the loop.
71    4. Use the ordering to perform list-scheduling of the loop:
72       1. Set II = MII.  We will try to schedule the loop within II cycles.
73       2. Try to schedule the insns one by one according to the ordering.
74          For each insn compute an interval of cycles by considering already-
75          scheduled preds and succs (and associated latencies); try to place
76          the insn in the cycles of this window checking for potential
77          resource conflicts (using the DFA interface).
78          Note: this is different from the cycle-scheduling of schedule_insns;
79          here the insns are not scheduled monotonically top-down (nor bottom-
80          up).
81       3. If failed in scheduling all insns - bump II++ and try again, unless
82          II reaches an upper bound MaxII, in which case report failure.
83    5. If we succeeded in scheduling the loop within II cycles, we now
84       generate prolog and epilog, decrease the counter of the loop, and
85       perform modulo variable expansion for live ranges that span more than
86       II cycles (i.e. use register copies to prevent a def from overwriting
87       itself before reaching the use).
88
89     SMS works with countable loops (1) whose control part can be easily
90     decoupled from the rest of the loop and (2) whose loop count can
91     be easily adjusted.  This is because we peel a constant number of
92     iterations into a prologue and epilogue for which we want to avoid
93     emitting the control part, and a kernel which is to iterate that
94     constant number of iterations less than the original loop.  So the
95     control part should be a set of insns clearly identified and having
96     its own iv, not otherwise used in the loop (at-least for now), which
97     initializes a register before the loop to the number of iterations.
98     Currently SMS relies on the do-loop pattern to recognize such loops,
99     where (1) the control part comprises of all insns defining and/or
100     using a certain 'count' register and (2) the loop count can be
101     adjusted by modifying this register prior to the loop.
102     TODO: Rely on cfgloop analysis instead.  */
103 \f
104 /* This page defines partial-schedule structures and functions for
105    modulo scheduling.  */
106
107 typedef struct partial_schedule *partial_schedule_ptr;
108 typedef struct ps_insn *ps_insn_ptr;
109
110 /* The minimum (absolute) cycle that a node of ps was scheduled in.  */
111 #define PS_MIN_CYCLE(ps) (((partial_schedule_ptr)(ps))->min_cycle)
112
113 /* The maximum (absolute) cycle that a node of ps was scheduled in.  */
114 #define PS_MAX_CYCLE(ps) (((partial_schedule_ptr)(ps))->max_cycle)
115
116 /* Perform signed modulo, always returning a non-negative value.  */
117 #define SMODULO(x,y) ((x) % (y) < 0 ? ((x) % (y) + (y)) : (x) % (y))
118
119 /* The number of different iterations the nodes in ps span, assuming
120    the stage boundaries are placed efficiently.  */
121 #define PS_STAGE_COUNT(ps) ((PS_MAX_CYCLE (ps) - PS_MIN_CYCLE (ps) \
122                              + 1 + (ps)->ii - 1) / (ps)->ii)
123
124 /* A single instruction in the partial schedule.  */
125 struct ps_insn
126 {
127   /* The corresponding DDG_NODE.  */
128   ddg_node_ptr node;
129
130   /* The (absolute) cycle in which the PS instruction is scheduled.
131      Same as SCHED_TIME (node).  */
132   int cycle;
133
134   /* The next/prev PS_INSN in the same row.  */
135   ps_insn_ptr next_in_row,
136               prev_in_row;
137
138   /* The number of nodes in the same row that come after this node.  */
139   int row_rest_count;
140 };
141
142 /* Holds the partial schedule as an array of II rows.  Each entry of the
143    array points to a linked list of PS_INSNs, which represents the
144    instructions that are scheduled for that row.  */
145 struct partial_schedule
146 {
147   int ii;       /* Number of rows in the partial schedule.  */
148   int history;  /* Threshold for conflict checking using DFA.  */
149
150   /* rows[i] points to linked list of insns scheduled in row i (0<=i<ii).  */
151   ps_insn_ptr *rows;
152
153   /* The earliest absolute cycle of an insn in the partial schedule.  */
154   int min_cycle;
155
156   /* The latest absolute cycle of an insn in the partial schedule.  */
157   int max_cycle;
158
159   ddg_ptr g;    /* The DDG of the insns in the partial schedule.  */
160 };
161
162 /* We use this to record all the register replacements we do in
163    the kernel so we can undo SMS if it is not profitable.  */
164 struct undo_replace_buff_elem
165 {
166   rtx insn;
167   rtx orig_reg;
168   rtx new_reg;
169   struct undo_replace_buff_elem *next;
170 };
171
172
173
174 static partial_schedule_ptr create_partial_schedule (int ii, ddg_ptr, int history);
175 static void free_partial_schedule (partial_schedule_ptr);
176 static void reset_partial_schedule (partial_schedule_ptr, int new_ii);
177 void print_partial_schedule (partial_schedule_ptr, FILE *);
178 static void verify_partial_schedule (partial_schedule_ptr, sbitmap);
179 static ps_insn_ptr ps_add_node_check_conflicts (partial_schedule_ptr,
180                                                 ddg_node_ptr node, int cycle,
181                                                 sbitmap must_precede,
182                                                 sbitmap must_follow);
183 static void rotate_partial_schedule (partial_schedule_ptr, int);
184 void set_row_column_for_ps (partial_schedule_ptr);
185 static void ps_insert_empty_row (partial_schedule_ptr, int, sbitmap);
186 static int compute_split_row (sbitmap, int, int, int, ddg_node_ptr);
187
188 \f
189 /* This page defines constants and structures for the modulo scheduling
190    driver.  */
191
192 static int sms_order_nodes (ddg_ptr, int, int *, int *);
193 static void set_node_sched_params (ddg_ptr);
194 static partial_schedule_ptr sms_schedule_by_order (ddg_ptr, int, int, int *);
195 static void permute_partial_schedule (partial_schedule_ptr, rtx);
196 static void generate_prolog_epilog (partial_schedule_ptr, struct loop *,
197                                     rtx, rtx);
198 static void duplicate_insns_of_cycles (partial_schedule_ptr,
199                                        int, int, int, rtx);
200
201 #define SCHED_ASAP(x) (((node_sched_params_ptr)(x)->aux.info)->asap)
202 #define SCHED_TIME(x) (((node_sched_params_ptr)(x)->aux.info)->time)
203 #define SCHED_FIRST_REG_MOVE(x) \
204         (((node_sched_params_ptr)(x)->aux.info)->first_reg_move)
205 #define SCHED_NREG_MOVES(x) \
206         (((node_sched_params_ptr)(x)->aux.info)->nreg_moves)
207 #define SCHED_ROW(x) (((node_sched_params_ptr)(x)->aux.info)->row)
208 #define SCHED_STAGE(x) (((node_sched_params_ptr)(x)->aux.info)->stage)
209 #define SCHED_COLUMN(x) (((node_sched_params_ptr)(x)->aux.info)->column)
210
211 /* The scheduling parameters held for each node.  */
212 typedef struct node_sched_params
213 {
214   int asap;     /* A lower-bound on the absolute scheduling cycle.  */
215   int time;     /* The absolute scheduling cycle (time >= asap).  */
216
217   /* The following field (first_reg_move) is a pointer to the first
218      register-move instruction added to handle the modulo-variable-expansion
219      of the register defined by this node.  This register-move copies the
220      original register defined by the node.  */
221   rtx first_reg_move;
222
223   /* The number of register-move instructions added, immediately preceding
224      first_reg_move.  */
225   int nreg_moves;
226
227   int row;    /* Holds time % ii.  */
228   int stage;  /* Holds time / ii.  */
229
230   /* The column of a node inside the ps.  If nodes u, v are on the same row,
231      u will precede v if column (u) < column (v).  */
232   int column;
233 } *node_sched_params_ptr;
234
235 \f
236 /* The following three functions are copied from the current scheduler
237    code in order to use sched_analyze() for computing the dependencies.
238    They are used when initializing the sched_info structure.  */
239 static const char *
240 sms_print_insn (const_rtx insn, int aligned ATTRIBUTE_UNUSED)
241 {
242   static char tmp[80];
243
244   sprintf (tmp, "i%4d", INSN_UID (insn));
245   return tmp;
246 }
247
248 static void
249 compute_jump_reg_dependencies (rtx insn ATTRIBUTE_UNUSED,
250                                regset cond_exec ATTRIBUTE_UNUSED,
251                                regset used ATTRIBUTE_UNUSED,
252                                regset set ATTRIBUTE_UNUSED)
253 {
254 }
255
256 static struct common_sched_info_def sms_common_sched_info;
257
258 static struct sched_deps_info_def sms_sched_deps_info =
259   {
260     compute_jump_reg_dependencies,
261     NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
262     NULL,
263     0, 0, 0
264   };
265
266 static struct haifa_sched_info sms_sched_info =
267 {
268   NULL,
269   NULL,
270   NULL,
271   NULL,
272   NULL,
273   sms_print_insn,
274   NULL,
275   NULL, /* insn_finishes_block_p */
276   NULL, NULL,
277   NULL, NULL,
278   0, 0,
279
280   NULL, NULL, NULL,
281   0
282 };
283
284 /* Given HEAD and TAIL which are the first and last insns in a loop;
285    return the register which controls the loop.  Return zero if it has
286    more than one occurrence in the loop besides the control part or the
287    do-loop pattern is not of the form we expect.  */
288 static rtx
289 doloop_register_get (rtx head ATTRIBUTE_UNUSED, rtx tail ATTRIBUTE_UNUSED)
290 {
291 #ifdef HAVE_doloop_end
292   rtx reg, condition, insn, first_insn_not_to_check;
293
294   if (!JUMP_P (tail))
295     return NULL_RTX;
296
297   /* TODO: Free SMS's dependence on doloop_condition_get.  */
298   condition = doloop_condition_get (tail);
299   if (! condition)
300     return NULL_RTX;
301
302   if (REG_P (XEXP (condition, 0)))
303     reg = XEXP (condition, 0);
304   else if (GET_CODE (XEXP (condition, 0)) == PLUS
305            && REG_P (XEXP (XEXP (condition, 0), 0)))
306     reg = XEXP (XEXP (condition, 0), 0);
307   else
308     gcc_unreachable ();
309
310   /* Check that the COUNT_REG has no other occurrences in the loop
311      until the decrement.  We assume the control part consists of
312      either a single (parallel) branch-on-count or a (non-parallel)
313      branch immediately preceded by a single (decrement) insn.  */
314   first_insn_not_to_check = (GET_CODE (PATTERN (tail)) == PARALLEL ? tail
315                              : PREV_INSN (tail));
316
317   for (insn = head; insn != first_insn_not_to_check; insn = NEXT_INSN (insn))
318     if (reg_mentioned_p (reg, insn))
319       {
320         if (dump_file)
321         {
322           fprintf (dump_file, "SMS count_reg found ");
323           print_rtl_single (dump_file, reg);
324           fprintf (dump_file, " outside control in insn:\n");
325           print_rtl_single (dump_file, insn);
326         }
327
328         return NULL_RTX;
329       }
330
331   return reg;
332 #else
333   return NULL_RTX;
334 #endif
335 }
336
337 /* Check if COUNT_REG is set to a constant in the PRE_HEADER block, so
338    that the number of iterations is a compile-time constant.  If so,
339    return the rtx that sets COUNT_REG to a constant, and set COUNT to
340    this constant.  Otherwise return 0.  */
341 static rtx
342 const_iteration_count (rtx count_reg, basic_block pre_header,
343                        HOST_WIDEST_INT * count)
344 {
345   rtx insn;
346   rtx head, tail;
347
348   if (! pre_header)
349     return NULL_RTX;
350
351   get_ebb_head_tail (pre_header, pre_header, &head, &tail);
352
353   for (insn = tail; insn != PREV_INSN (head); insn = PREV_INSN (insn))
354     if (NONDEBUG_INSN_P (insn) && single_set (insn) &&
355         rtx_equal_p (count_reg, SET_DEST (single_set (insn))))
356       {
357         rtx pat = single_set (insn);
358
359         if (CONST_INT_P (SET_SRC (pat)))
360           {
361             *count = INTVAL (SET_SRC (pat));
362             return insn;
363           }
364
365         return NULL_RTX;
366       }
367
368   return NULL_RTX;
369 }
370
371 /* A very simple resource-based lower bound on the initiation interval.
372    ??? Improve the accuracy of this bound by considering the
373    utilization of various units.  */
374 static int
375 res_MII (ddg_ptr g)
376 {
377   if (targetm.sched.sms_res_mii)
378     return targetm.sched.sms_res_mii (g);
379
380   return ((g->num_nodes - g->num_debug) / issue_rate);
381 }
382
383
384 /* Points to the array that contains the sched data for each node.  */
385 static node_sched_params_ptr node_sched_params;
386
387 /* Allocate sched_params for each node and initialize it.  Assumes that
388    the aux field of each node contain the asap bound (computed earlier),
389    and copies it into the sched_params field.  */
390 static void
391 set_node_sched_params (ddg_ptr g)
392 {
393   int i;
394
395   /* Allocate for each node in the DDG a place to hold the "sched_data".  */
396   /* Initialize ASAP/ALAP/HIGHT to zero.  */
397   node_sched_params = (node_sched_params_ptr)
398                        xcalloc (g->num_nodes,
399                                 sizeof (struct node_sched_params));
400
401   /* Set the pointer of the general data of the node to point to the
402      appropriate sched_params structure.  */
403   for (i = 0; i < g->num_nodes; i++)
404     {
405       /* Watch out for aliasing problems?  */
406       node_sched_params[i].asap = g->nodes[i].aux.count;
407       g->nodes[i].aux.info = &node_sched_params[i];
408     }
409 }
410
411 static void
412 print_node_sched_params (FILE *file, int num_nodes, ddg_ptr g)
413 {
414   int i;
415
416   if (! file)
417     return;
418   for (i = 0; i < num_nodes; i++)
419     {
420       node_sched_params_ptr nsp = &node_sched_params[i];
421       rtx reg_move = nsp->first_reg_move;
422       int j;
423
424       fprintf (file, "Node = %d; INSN = %d\n", i,
425                (INSN_UID (g->nodes[i].insn)));
426       fprintf (file, " asap = %d:\n", nsp->asap);
427       fprintf (file, " time = %d:\n", nsp->time);
428       fprintf (file, " nreg_moves = %d:\n", nsp->nreg_moves);
429       for (j = 0; j < nsp->nreg_moves; j++)
430         {
431           fprintf (file, " reg_move = ");
432           print_rtl_single (file, reg_move);
433           reg_move = PREV_INSN (reg_move);
434         }
435     }
436 }
437
438 /*
439    Breaking intra-loop register anti-dependences:
440    Each intra-loop register anti-dependence implies a cross-iteration true
441    dependence of distance 1. Therefore, we can remove such false dependencies
442    and figure out if the partial schedule broke them by checking if (for a
443    true-dependence of distance 1): SCHED_TIME (def) < SCHED_TIME (use) and
444    if so generate a register move.   The number of such moves is equal to:
445               SCHED_TIME (use) - SCHED_TIME (def)       { 0 broken
446    nreg_moves = ----------------------------------- + 1 - {   dependence.
447                             ii                          { 1 if not.
448 */
449 static struct undo_replace_buff_elem *
450 generate_reg_moves (partial_schedule_ptr ps, bool rescan)
451 {
452   ddg_ptr g = ps->g;
453   int ii = ps->ii;
454   int i;
455   struct undo_replace_buff_elem *reg_move_replaces = NULL;
456
457   for (i = 0; i < g->num_nodes; i++)
458     {
459       ddg_node_ptr u = &g->nodes[i];
460       ddg_edge_ptr e;
461       int nreg_moves = 0, i_reg_move;
462       sbitmap *uses_of_defs;
463       rtx last_reg_move;
464       rtx prev_reg, old_reg;
465
466       /* Compute the number of reg_moves needed for u, by looking at life
467          ranges started at u (excluding self-loops).  */
468       for (e = u->out; e; e = e->next_out)
469         if (e->type == TRUE_DEP && e->dest != e->src)
470           {
471             int nreg_moves4e = (SCHED_TIME (e->dest) - SCHED_TIME (e->src)) / ii;
472
473             if (e->distance == 1)
474               nreg_moves4e = (SCHED_TIME (e->dest) - SCHED_TIME (e->src) + ii) / ii;
475
476             /* If dest precedes src in the schedule of the kernel, then dest
477                will read before src writes and we can save one reg_copy.  */
478             if (SCHED_ROW (e->dest) == SCHED_ROW (e->src)
479                 && SCHED_COLUMN (e->dest) < SCHED_COLUMN (e->src))
480               nreg_moves4e--;
481
482             nreg_moves = MAX (nreg_moves, nreg_moves4e);
483           }
484
485       if (nreg_moves == 0)
486         continue;
487
488       /* Every use of the register defined by node may require a different
489          copy of this register, depending on the time the use is scheduled.
490          Set a bitmap vector, telling which nodes use each copy of this
491          register.  */
492       uses_of_defs = sbitmap_vector_alloc (nreg_moves, g->num_nodes);
493       sbitmap_vector_zero (uses_of_defs, nreg_moves);
494       for (e = u->out; e; e = e->next_out)
495         if (e->type == TRUE_DEP && e->dest != e->src)
496           {
497             int dest_copy = (SCHED_TIME (e->dest) - SCHED_TIME (e->src)) / ii;
498
499             if (e->distance == 1)
500               dest_copy = (SCHED_TIME (e->dest) - SCHED_TIME (e->src) + ii) / ii;
501
502             if (SCHED_ROW (e->dest) == SCHED_ROW (e->src)
503                 && SCHED_COLUMN (e->dest) < SCHED_COLUMN (e->src))
504               dest_copy--;
505
506             if (dest_copy)
507               SET_BIT (uses_of_defs[dest_copy - 1], e->dest->cuid);
508           }
509
510       /* Now generate the reg_moves, attaching relevant uses to them.  */
511       SCHED_NREG_MOVES (u) = nreg_moves;
512       old_reg = prev_reg = copy_rtx (SET_DEST (single_set (u->insn)));
513       /* Insert the reg-moves right before the notes which precede
514          the insn they relates to.  */
515       last_reg_move = u->first_note;
516
517       for (i_reg_move = 0; i_reg_move < nreg_moves; i_reg_move++)
518         {
519           unsigned int i_use = 0;
520           rtx new_reg = gen_reg_rtx (GET_MODE (prev_reg));
521           rtx reg_move = gen_move_insn (new_reg, prev_reg);
522           sbitmap_iterator sbi;
523
524           add_insn_before (reg_move, last_reg_move, NULL);
525           last_reg_move = reg_move;
526
527           if (!SCHED_FIRST_REG_MOVE (u))
528             SCHED_FIRST_REG_MOVE (u) = reg_move;
529
530           EXECUTE_IF_SET_IN_SBITMAP (uses_of_defs[i_reg_move], 0, i_use, sbi)
531             {
532               struct undo_replace_buff_elem *rep;
533
534               rep = (struct undo_replace_buff_elem *)
535                     xcalloc (1, sizeof (struct undo_replace_buff_elem));
536               rep->insn = g->nodes[i_use].insn;
537               rep->orig_reg = old_reg;
538               rep->new_reg = new_reg;
539
540               if (! reg_move_replaces)
541                 reg_move_replaces = rep;
542               else
543                 {
544                   rep->next = reg_move_replaces;
545                   reg_move_replaces = rep;
546                 }
547
548               replace_rtx (g->nodes[i_use].insn, old_reg, new_reg);
549               if (rescan)
550                 df_insn_rescan (g->nodes[i_use].insn);
551             }
552
553           prev_reg = new_reg;
554         }
555       sbitmap_vector_free (uses_of_defs);
556     }
557   return reg_move_replaces;
558 }
559
560 /* Free memory allocated for the undo buffer.  */
561 static void
562 free_undo_replace_buff (struct undo_replace_buff_elem *reg_move_replaces)
563 {
564
565   while (reg_move_replaces)
566     {
567       struct undo_replace_buff_elem *rep = reg_move_replaces;
568
569       reg_move_replaces = reg_move_replaces->next;
570       free (rep);
571     }
572 }
573
574 /* Bump the SCHED_TIMEs of all nodes to start from zero.  Set the values
575    of SCHED_ROW and SCHED_STAGE.  */
576 static void
577 normalize_sched_times (partial_schedule_ptr ps)
578 {
579   int row;
580   int amount = PS_MIN_CYCLE (ps);
581   int ii = ps->ii;
582   ps_insn_ptr crr_insn;
583
584   for (row = 0; row < ii; row++)
585     for (crr_insn = ps->rows[row]; crr_insn; crr_insn = crr_insn->next_in_row)
586       {
587         ddg_node_ptr u = crr_insn->node;
588         int normalized_time = SCHED_TIME (u) - amount;
589
590         if (dump_file)
591           fprintf (dump_file, "crr_insn->node=%d, crr_insn->cycle=%d,\
592                    min_cycle=%d\n", crr_insn->node->cuid, SCHED_TIME
593                    (u), ps->min_cycle);
594         gcc_assert (SCHED_TIME (u) >= ps->min_cycle);
595         gcc_assert (SCHED_TIME (u) <= ps->max_cycle);
596         SCHED_TIME (u) = normalized_time;
597         SCHED_ROW (u) = normalized_time % ii;
598         SCHED_STAGE (u) = normalized_time / ii;
599       }
600 }
601
602 /* Set SCHED_COLUMN of each node according to its position in PS.  */
603 static void
604 set_columns_for_ps (partial_schedule_ptr ps)
605 {
606   int row;
607
608   for (row = 0; row < ps->ii; row++)
609     {
610       ps_insn_ptr cur_insn = ps->rows[row];
611       int column = 0;
612
613       for (; cur_insn; cur_insn = cur_insn->next_in_row)
614         SCHED_COLUMN (cur_insn->node) = column++;
615     }
616 }
617
618 /* Permute the insns according to their order in PS, from row 0 to
619    row ii-1, and position them right before LAST.  This schedules
620    the insns of the loop kernel.  */
621 static void
622 permute_partial_schedule (partial_schedule_ptr ps, rtx last)
623 {
624   int ii = ps->ii;
625   int row;
626   ps_insn_ptr ps_ij;
627
628   for (row = 0; row < ii ; row++)
629     for (ps_ij = ps->rows[row]; ps_ij; ps_ij = ps_ij->next_in_row)
630       if (PREV_INSN (last) != ps_ij->node->insn)
631         reorder_insns_nobb (ps_ij->node->first_note, ps_ij->node->insn,
632                             PREV_INSN (last));
633 }
634
635 static void
636 duplicate_insns_of_cycles (partial_schedule_ptr ps, int from_stage,
637                            int to_stage, int for_prolog, rtx count_reg)
638 {
639   int row;
640   ps_insn_ptr ps_ij;
641
642   for (row = 0; row < ps->ii; row++)
643     for (ps_ij = ps->rows[row]; ps_ij; ps_ij = ps_ij->next_in_row)
644       {
645         ddg_node_ptr u_node = ps_ij->node;
646         int j, i_reg_moves;
647         rtx reg_move = NULL_RTX;
648
649         /* Do not duplicate any insn which refers to count_reg as it
650            belongs to the control part.
651            TODO: This should be done by analyzing the control part of
652            the loop.  */
653         if (reg_mentioned_p (count_reg, u_node->insn))
654           continue;
655
656         if (for_prolog)
657           {
658             /* SCHED_STAGE (u_node) >= from_stage == 0.  Generate increasing
659                number of reg_moves starting with the second occurrence of
660                u_node, which is generated if its SCHED_STAGE <= to_stage.  */
661             i_reg_moves = to_stage - SCHED_STAGE (u_node) + 1;
662             i_reg_moves = MAX (i_reg_moves, 0);
663             i_reg_moves = MIN (i_reg_moves, SCHED_NREG_MOVES (u_node));
664
665             /* The reg_moves start from the *first* reg_move backwards.  */
666             if (i_reg_moves)
667               {
668                 reg_move = SCHED_FIRST_REG_MOVE (u_node);
669                 for (j = 1; j < i_reg_moves; j++)
670                   reg_move = PREV_INSN (reg_move);
671               }
672           }
673         else /* It's for the epilog.  */
674           {
675             /* SCHED_STAGE (u_node) <= to_stage.  Generate all reg_moves,
676                starting to decrease one stage after u_node no longer occurs;
677                that is, generate all reg_moves until
678                SCHED_STAGE (u_node) == from_stage - 1.  */
679             i_reg_moves = SCHED_NREG_MOVES (u_node)
680                        - (from_stage - SCHED_STAGE (u_node) - 1);
681             i_reg_moves = MAX (i_reg_moves, 0);
682             i_reg_moves = MIN (i_reg_moves, SCHED_NREG_MOVES (u_node));
683
684             /* The reg_moves start from the *last* reg_move forwards.  */
685             if (i_reg_moves)
686               {
687                 reg_move = SCHED_FIRST_REG_MOVE (u_node);
688                 for (j = 1; j < SCHED_NREG_MOVES (u_node); j++)
689                   reg_move = PREV_INSN (reg_move);
690               }
691           }
692
693         for (j = 0; j < i_reg_moves; j++, reg_move = NEXT_INSN (reg_move))
694           emit_insn (copy_rtx (PATTERN (reg_move)));
695         if (SCHED_STAGE (u_node) >= from_stage
696             && SCHED_STAGE (u_node) <= to_stage)
697           duplicate_insn_chain (u_node->first_note, u_node->insn);
698       }
699 }
700
701
702 /* Generate the instructions (including reg_moves) for prolog & epilog.  */
703 static void
704 generate_prolog_epilog (partial_schedule_ptr ps, struct loop *loop,
705                         rtx count_reg, rtx count_init)
706 {
707   int i;
708   int last_stage = PS_STAGE_COUNT (ps) - 1;
709   edge e;
710
711   /* Generate the prolog, inserting its insns on the loop-entry edge.  */
712   start_sequence ();
713
714   if (!count_init)
715     {
716       /* Generate instructions at the beginning of the prolog to
717          adjust the loop count by STAGE_COUNT.  If loop count is constant
718          (count_init), this constant is adjusted by STAGE_COUNT in
719          generate_prolog_epilog function.  */
720       rtx sub_reg = NULL_RTX;
721
722       sub_reg = expand_simple_binop (GET_MODE (count_reg), MINUS,
723                                      count_reg, GEN_INT (last_stage),
724                                      count_reg, 1, OPTAB_DIRECT);
725       gcc_assert (REG_P (sub_reg));
726       if (REGNO (sub_reg) != REGNO (count_reg))
727         emit_move_insn (count_reg, sub_reg);
728     }
729
730   for (i = 0; i < last_stage; i++)
731     duplicate_insns_of_cycles (ps, 0, i, 1, count_reg);
732
733   /* Put the prolog on the entry edge.  */
734   e = loop_preheader_edge (loop);
735   split_edge_and_insert (e, get_insns ());
736
737   end_sequence ();
738
739   /* Generate the epilog, inserting its insns on the loop-exit edge.  */
740   start_sequence ();
741
742   for (i = 0; i < last_stage; i++)
743     duplicate_insns_of_cycles (ps, i + 1, last_stage, 0, count_reg);
744
745   /* Put the epilogue on the exit edge.  */
746   gcc_assert (single_exit (loop));
747   e = single_exit (loop);
748   split_edge_and_insert (e, get_insns ());
749   end_sequence ();
750 }
751
752 /* Return true if all the BBs of the loop are empty except the
753    loop header.  */
754 static bool
755 loop_single_full_bb_p (struct loop *loop)
756 {
757   unsigned i;
758   basic_block *bbs = get_loop_body (loop);
759
760   for (i = 0; i < loop->num_nodes ; i++)
761     {
762       rtx head, tail;
763       bool empty_bb = true;
764
765       if (bbs[i] == loop->header)
766         continue;
767
768       /* Make sure that basic blocks other than the header
769          have only notes labels or jumps.  */
770       get_ebb_head_tail (bbs[i], bbs[i], &head, &tail);
771       for (; head != NEXT_INSN (tail); head = NEXT_INSN (head))
772         {
773           if (NOTE_P (head) || LABEL_P (head)
774               || (INSN_P (head) && (DEBUG_INSN_P (head) || JUMP_P (head))))
775             continue;
776           empty_bb = false;
777           break;
778         }
779
780       if (! empty_bb)
781         {
782           free (bbs);
783           return false;
784         }
785     }
786   free (bbs);
787   return true;
788 }
789
790 /* A simple loop from SMS point of view; it is a loop that is composed of
791    either a single basic block or two BBs - a header and a latch.  */
792 #define SIMPLE_SMS_LOOP_P(loop) ((loop->num_nodes < 3 )                     \
793                                   && (EDGE_COUNT (loop->latch->preds) == 1) \
794                                   && (EDGE_COUNT (loop->latch->succs) == 1))
795
796 /* Return true if the loop is in its canonical form and false if not.
797    i.e. SIMPLE_SMS_LOOP_P and have one preheader block, and single exit.  */
798 static bool
799 loop_canon_p (struct loop *loop)
800 {
801
802   if (loop->inner || !loop_outer (loop))
803   {
804     if (dump_file)
805       fprintf (dump_file, "SMS loop inner or !loop_outer\n");
806     return false;
807   }
808
809   if (!single_exit (loop))
810     {
811       if (dump_file)
812         {
813           rtx insn = BB_END (loop->header);
814
815           fprintf (dump_file, "SMS loop many exits ");
816                   fprintf (dump_file, " %s %d (file, line)\n",
817                            insn_file (insn), insn_line (insn));
818         }
819       return false;
820     }
821
822   if (! SIMPLE_SMS_LOOP_P (loop) && ! loop_single_full_bb_p (loop))
823     {
824       if (dump_file)
825         {
826           rtx insn = BB_END (loop->header);
827
828           fprintf (dump_file, "SMS loop many BBs. ");
829           fprintf (dump_file, " %s %d (file, line)\n",
830                    insn_file (insn), insn_line (insn));
831         }
832       return false;
833     }
834
835     return true;
836 }
837
838 /* If there are more than one entry for the loop,
839    make it one by splitting the first entry edge and
840    redirecting the others to the new BB.  */
841 static void
842 canon_loop (struct loop *loop)
843 {
844   edge e;
845   edge_iterator i;
846
847   /* Avoid annoying special cases of edges going to exit
848      block.  */
849   FOR_EACH_EDGE (e, i, EXIT_BLOCK_PTR->preds)
850     if ((e->flags & EDGE_FALLTHRU) && (EDGE_COUNT (e->src->succs) > 1))
851       split_edge (e);
852
853   if (loop->latch == loop->header
854       || EDGE_COUNT (loop->latch->succs) > 1)
855     {
856       FOR_EACH_EDGE (e, i, loop->header->preds)
857         if (e->src == loop->latch)
858           break;
859       split_edge (e);
860     }
861 }
862
863 /* Setup infos.  */
864 static void
865 setup_sched_infos (void)
866 {
867   memcpy (&sms_common_sched_info, &haifa_common_sched_info,
868           sizeof (sms_common_sched_info));
869   sms_common_sched_info.sched_pass_id = SCHED_SMS_PASS;
870   common_sched_info = &sms_common_sched_info;
871
872   sched_deps_info = &sms_sched_deps_info;
873   current_sched_info = &sms_sched_info;
874 }
875
876 /* Probability in % that the sms-ed loop rolls enough so that optimized
877    version may be entered.  Just a guess.  */
878 #define PROB_SMS_ENOUGH_ITERATIONS 80
879
880 /* Used to calculate the upper bound of ii.  */
881 #define MAXII_FACTOR 2
882
883 /* Main entry point, perform SMS scheduling on the loops of the function
884    that consist of single basic blocks.  */
885 static void
886 sms_schedule (void)
887 {
888   rtx insn;
889   ddg_ptr *g_arr, g;
890   int * node_order;
891   int maxii, max_asap;
892   loop_iterator li;
893   partial_schedule_ptr ps;
894   basic_block bb = NULL;
895   struct loop *loop;
896   basic_block condition_bb = NULL;
897   edge latch_edge;
898   gcov_type trip_count = 0;
899
900   loop_optimizer_init (LOOPS_HAVE_PREHEADERS
901                        | LOOPS_HAVE_RECORDED_EXITS);
902   if (number_of_loops () <= 1)
903     {
904       loop_optimizer_finalize ();
905       return;  /* There are no loops to schedule.  */
906     }
907
908   /* Initialize issue_rate.  */
909   if (targetm.sched.issue_rate)
910     {
911       int temp = reload_completed;
912
913       reload_completed = 1;
914       issue_rate = targetm.sched.issue_rate ();
915       reload_completed = temp;
916     }
917   else
918     issue_rate = 1;
919
920   /* Initialize the scheduler.  */
921   setup_sched_infos ();
922   haifa_sched_init ();
923
924   /* Allocate memory to hold the DDG array one entry for each loop.
925      We use loop->num as index into this array.  */
926   g_arr = XCNEWVEC (ddg_ptr, number_of_loops ());
927
928   if (dump_file)
929   {
930     fprintf (dump_file, "\n\nSMS analysis phase\n");
931     fprintf (dump_file, "===================\n\n");
932   }
933
934   /* Build DDGs for all the relevant loops and hold them in G_ARR
935      indexed by the loop index.  */
936   FOR_EACH_LOOP (li, loop, 0)
937     {
938       rtx head, tail;
939       rtx count_reg;
940
941       /* For debugging.  */
942       if (dbg_cnt (sms_sched_loop) == false)
943         {
944           if (dump_file)
945             fprintf (dump_file, "SMS reached max limit... \n");
946
947           break;
948         }
949
950       if (dump_file)
951       {
952          rtx insn = BB_END (loop->header);
953
954          fprintf (dump_file, "SMS loop num: %d, file: %s, line: %d\n",
955                   loop->num, insn_file (insn), insn_line (insn));
956
957       }
958
959       if (! loop_canon_p (loop))
960         continue;
961
962       if (! loop_single_full_bb_p (loop))
963       {
964         if (dump_file)
965           fprintf (dump_file, "SMS not loop_single_full_bb_p\n");
966         continue;
967       }
968
969       bb = loop->header;
970
971       get_ebb_head_tail (bb, bb, &head, &tail);
972       latch_edge = loop_latch_edge (loop);
973       gcc_assert (single_exit (loop));
974       if (single_exit (loop)->count)
975         trip_count = latch_edge->count / single_exit (loop)->count;
976
977       /* Perform SMS only on loops that their average count is above threshold.  */
978
979       if ( latch_edge->count
980           && (latch_edge->count < single_exit (loop)->count * SMS_LOOP_AVERAGE_COUNT_THRESHOLD))
981         {
982           if (dump_file)
983             {
984               fprintf (dump_file, " %s %d (file, line)\n",
985                        insn_file (tail), insn_line (tail));
986               fprintf (dump_file, "SMS single-bb-loop\n");
987               if (profile_info && flag_branch_probabilities)
988                 {
989                   fprintf (dump_file, "SMS loop-count ");
990                   fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
991                            (HOST_WIDEST_INT) bb->count);
992                   fprintf (dump_file, "\n");
993                   fprintf (dump_file, "SMS trip-count ");
994                   fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
995                            (HOST_WIDEST_INT) trip_count);
996                   fprintf (dump_file, "\n");
997                   fprintf (dump_file, "SMS profile-sum-max ");
998                   fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
999                            (HOST_WIDEST_INT) profile_info->sum_max);
1000                   fprintf (dump_file, "\n");
1001                 }
1002             }
1003           continue;
1004         }
1005
1006       /* Make sure this is a doloop.  */
1007       if ( !(count_reg = doloop_register_get (head, tail)))
1008       {
1009         if (dump_file)
1010           fprintf (dump_file, "SMS doloop_register_get failed\n");
1011         continue;
1012       }
1013
1014       /* Don't handle BBs with calls or barriers, or !single_set insns,
1015          or auto-increment insns (to avoid creating invalid reg-moves
1016          for the auto-increment insns).
1017          ??? Should handle auto-increment insns.
1018          ??? Should handle insns defining subregs.  */
1019      for (insn = head; insn != NEXT_INSN (tail); insn = NEXT_INSN (insn))
1020       {
1021          rtx set;
1022
1023         if (CALL_P (insn)
1024             || BARRIER_P (insn)
1025             || (NONDEBUG_INSN_P (insn) && !JUMP_P (insn)
1026                 && !single_set (insn) && GET_CODE (PATTERN (insn)) != USE)
1027             || (FIND_REG_INC_NOTE (insn, NULL_RTX) != 0)
1028             || (INSN_P (insn) && (set = single_set (insn))
1029                 && GET_CODE (SET_DEST (set)) == SUBREG))
1030         break;
1031       }
1032
1033       if (insn != NEXT_INSN (tail))
1034         {
1035           if (dump_file)
1036             {
1037               if (CALL_P (insn))
1038                 fprintf (dump_file, "SMS loop-with-call\n");
1039               else if (BARRIER_P (insn))
1040                 fprintf (dump_file, "SMS loop-with-barrier\n");
1041               else if (FIND_REG_INC_NOTE (insn, NULL_RTX) != 0)
1042                 fprintf (dump_file, "SMS reg inc\n");
1043               else if ((NONDEBUG_INSN_P (insn) && !JUMP_P (insn)
1044                 && !single_set (insn) && GET_CODE (PATTERN (insn)) != USE))
1045                 fprintf (dump_file, "SMS loop-with-not-single-set\n");
1046               else
1047                fprintf (dump_file, "SMS loop with subreg in lhs\n");
1048               print_rtl_single (dump_file, insn);
1049             }
1050
1051           continue;
1052         }
1053
1054       if (! (g = create_ddg (bb, 0)))
1055         {
1056           if (dump_file)
1057             fprintf (dump_file, "SMS create_ddg failed\n");
1058           continue;
1059         }
1060
1061       g_arr[loop->num] = g;
1062       if (dump_file)
1063         fprintf (dump_file, "...OK\n");
1064
1065     }
1066   if (dump_file)
1067   {
1068     fprintf (dump_file, "\nSMS transformation phase\n");
1069     fprintf (dump_file, "=========================\n\n");
1070   }
1071
1072   /* We don't want to perform SMS on new loops - created by versioning.  */
1073   FOR_EACH_LOOP (li, loop, 0)
1074     {
1075       rtx head, tail;
1076       rtx count_reg, count_init;
1077       int mii, rec_mii;
1078       unsigned stage_count = 0;
1079       HOST_WIDEST_INT loop_count = 0;
1080
1081       if (! (g = g_arr[loop->num]))
1082         continue;
1083
1084       if (dump_file)
1085       {
1086          rtx insn = BB_END (loop->header);
1087
1088          fprintf (dump_file, "SMS loop num: %d, file: %s, line: %d\n",
1089                   loop->num, insn_file (insn), insn_line (insn));
1090
1091          print_ddg (dump_file, g);
1092       }
1093
1094       get_ebb_head_tail (loop->header, loop->header, &head, &tail);
1095
1096       latch_edge = loop_latch_edge (loop);
1097       gcc_assert (single_exit (loop));
1098       if (single_exit (loop)->count)
1099         trip_count = latch_edge->count / single_exit (loop)->count;
1100
1101       if (dump_file)
1102         {
1103           fprintf (dump_file, " %s %d (file, line)\n",
1104                    insn_file (tail), insn_line (tail));
1105           fprintf (dump_file, "SMS single-bb-loop\n");
1106           if (profile_info && flag_branch_probabilities)
1107             {
1108               fprintf (dump_file, "SMS loop-count ");
1109               fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
1110                        (HOST_WIDEST_INT) bb->count);
1111               fprintf (dump_file, "\n");
1112               fprintf (dump_file, "SMS profile-sum-max ");
1113               fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
1114                        (HOST_WIDEST_INT) profile_info->sum_max);
1115               fprintf (dump_file, "\n");
1116             }
1117           fprintf (dump_file, "SMS doloop\n");
1118           fprintf (dump_file, "SMS built-ddg %d\n", g->num_nodes);
1119           fprintf (dump_file, "SMS num-loads %d\n", g->num_loads);
1120           fprintf (dump_file, "SMS num-stores %d\n", g->num_stores);
1121         }
1122
1123
1124       /* In case of th loop have doloop register it gets special
1125          handling.  */
1126       count_init = NULL_RTX;
1127       if ((count_reg = doloop_register_get (head, tail)))
1128         {
1129           basic_block pre_header;
1130
1131           pre_header = loop_preheader_edge (loop)->src;
1132           count_init = const_iteration_count (count_reg, pre_header,
1133                                               &loop_count);
1134         }
1135       gcc_assert (count_reg);
1136
1137       if (dump_file && count_init)
1138         {
1139           fprintf (dump_file, "SMS const-doloop ");
1140           fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
1141                      loop_count);
1142           fprintf (dump_file, "\n");
1143         }
1144
1145       node_order = XNEWVEC (int, g->num_nodes);
1146
1147       mii = 1; /* Need to pass some estimate of mii.  */
1148       rec_mii = sms_order_nodes (g, mii, node_order, &max_asap);
1149       mii = MAX (res_MII (g), rec_mii);
1150       maxii = MAX (max_asap, MAXII_FACTOR * mii);
1151
1152       if (dump_file)
1153         fprintf (dump_file, "SMS iis %d %d %d (rec_mii, mii, maxii)\n",
1154                  rec_mii, mii, maxii);
1155
1156       /* After sms_order_nodes and before sms_schedule_by_order, to copy over
1157          ASAP.  */
1158       set_node_sched_params (g);
1159
1160       ps = sms_schedule_by_order (g, mii, maxii, node_order);
1161
1162       if (ps){
1163         stage_count = PS_STAGE_COUNT (ps);
1164         gcc_assert(stage_count >= 1);
1165       }
1166
1167       /* Stage count of 1 means that there is no interleaving between
1168          iterations, let the scheduling passes do the job.  */
1169       if (stage_count <= 1
1170           || (count_init && (loop_count <= stage_count))
1171           || (flag_branch_probabilities && (trip_count <= stage_count)))
1172         {
1173           if (dump_file)
1174             {
1175               fprintf (dump_file, "SMS failed... \n");
1176               fprintf (dump_file, "SMS sched-failed (stage-count=%d, loop-count=", stage_count);
1177               fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC, loop_count);
1178               fprintf (dump_file, ", trip-count=");
1179               fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC, trip_count);
1180               fprintf (dump_file, ")\n");
1181             }
1182           continue;
1183         }
1184       else
1185         {
1186           struct undo_replace_buff_elem *reg_move_replaces;
1187
1188           if (dump_file)
1189             {
1190               fprintf (dump_file,
1191                        "SMS succeeded %d %d (with ii, sc)\n", ps->ii,
1192                        stage_count);
1193               print_partial_schedule (ps, dump_file);
1194               fprintf (dump_file,
1195                        "SMS Branch (%d) will later be scheduled at cycle %d.\n",
1196                        g->closing_branch->cuid, PS_MIN_CYCLE (ps) - 1);
1197             }
1198
1199           /* Set the stage boundaries.  If the DDG is built with closing_branch_deps,
1200              the closing_branch was scheduled and should appear in the last (ii-1)
1201              row.  Otherwise, we are free to schedule the branch, and we let nodes
1202              that were scheduled at the first PS_MIN_CYCLE cycle appear in the first
1203              row; this should reduce stage_count to minimum.
1204              TODO: Revisit the issue of scheduling the insns of the
1205              control part relative to the branch when the control part
1206              has more than one insn.  */
1207           normalize_sched_times (ps);
1208           rotate_partial_schedule (ps, PS_MIN_CYCLE (ps));
1209           set_columns_for_ps (ps);
1210
1211           canon_loop (loop);
1212
1213           /* case the BCT count is not known , Do loop-versioning */
1214           if (count_reg && ! count_init)
1215             {
1216               rtx comp_rtx = gen_rtx_fmt_ee (GT, VOIDmode, count_reg,
1217                                              GEN_INT(stage_count));
1218               unsigned prob = (PROB_SMS_ENOUGH_ITERATIONS
1219                                * REG_BR_PROB_BASE) / 100;
1220
1221               loop_version (loop, comp_rtx, &condition_bb,
1222                             prob, prob, REG_BR_PROB_BASE - prob,
1223                             true);
1224              }
1225
1226           /* Set new iteration count of loop kernel.  */
1227           if (count_reg && count_init)
1228             SET_SRC (single_set (count_init)) = GEN_INT (loop_count
1229                                                      - stage_count + 1);
1230
1231           /* Now apply the scheduled kernel to the RTL of the loop.  */
1232           permute_partial_schedule (ps, g->closing_branch->first_note);
1233
1234           /* Mark this loop as software pipelined so the later
1235              scheduling passes doesn't touch it.  */
1236           if (! flag_resched_modulo_sched)
1237             g->bb->flags |= BB_DISABLE_SCHEDULE;
1238           /* The life-info is not valid any more.  */
1239           df_set_bb_dirty (g->bb);
1240
1241           reg_move_replaces = generate_reg_moves (ps, true);
1242           if (dump_file)
1243             print_node_sched_params (dump_file, g->num_nodes, g);
1244           /* Generate prolog and epilog.  */
1245           generate_prolog_epilog (ps, loop, count_reg, count_init);
1246
1247           free_undo_replace_buff (reg_move_replaces);
1248         }
1249
1250       free_partial_schedule (ps);
1251       free (node_sched_params);
1252       free (node_order);
1253       free_ddg (g);
1254     }
1255
1256   free (g_arr);
1257
1258   /* Release scheduler data, needed until now because of DFA.  */
1259   haifa_sched_finish ();
1260   loop_optimizer_finalize ();
1261 }
1262
1263 /* The SMS scheduling algorithm itself
1264    -----------------------------------
1265    Input: 'O' an ordered list of insns of a loop.
1266    Output: A scheduling of the loop - kernel, prolog, and epilogue.
1267
1268    'Q' is the empty Set
1269    'PS' is the partial schedule; it holds the currently scheduled nodes with
1270         their cycle/slot.
1271    'PSP' previously scheduled predecessors.
1272    'PSS' previously scheduled successors.
1273    't(u)' the cycle where u is scheduled.
1274    'l(u)' is the latency of u.
1275    'd(v,u)' is the dependence distance from v to u.
1276    'ASAP(u)' the earliest time at which u could be scheduled as computed in
1277              the node ordering phase.
1278    'check_hardware_resources_conflicts(u, PS, c)'
1279                              run a trace around cycle/slot through DFA model
1280                              to check resource conflicts involving instruction u
1281                              at cycle c given the partial schedule PS.
1282    'add_to_partial_schedule_at_time(u, PS, c)'
1283                              Add the node/instruction u to the partial schedule
1284                              PS at time c.
1285    'calculate_register_pressure(PS)'
1286                              Given a schedule of instructions, calculate the register
1287                              pressure it implies.  One implementation could be the
1288                              maximum number of overlapping live ranges.
1289    'maxRP' The maximum allowed register pressure, it is usually derived from the number
1290            registers available in the hardware.
1291
1292    1. II = MII.
1293    2. PS = empty list
1294    3. for each node u in O in pre-computed order
1295    4.   if (PSP(u) != Q && PSS(u) == Q) then
1296    5.     Early_start(u) = max ( t(v) + l(v) - d(v,u)*II ) over all every v in PSP(u).
1297    6.     start = Early_start; end = Early_start + II - 1; step = 1
1298    11.  else if (PSP(u) == Q && PSS(u) != Q) then
1299    12.      Late_start(u) = min ( t(v) - l(v) + d(v,u)*II ) over all every v in PSS(u).
1300    13.     start = Late_start; end = Late_start - II + 1; step = -1
1301    14.  else if (PSP(u) != Q && PSS(u) != Q) then
1302    15.     Early_start(u) = max ( t(v) + l(v) - d(v,u)*II ) over all every v in PSP(u).
1303    16.     Late_start(u) = min ( t(v) - l(v) + d(v,u)*II ) over all every v in PSS(u).
1304    17.     start = Early_start;
1305    18.     end = min(Early_start + II - 1 , Late_start);
1306    19.     step = 1
1307    20.     else "if (PSP(u) == Q && PSS(u) == Q)"
1308    21.    start = ASAP(u); end = start + II - 1; step = 1
1309    22.  endif
1310
1311    23.  success = false
1312    24.  for (c = start ; c != end ; c += step)
1313    25.     if check_hardware_resources_conflicts(u, PS, c) then
1314    26.       add_to_partial_schedule_at_time(u, PS, c)
1315    27.       success = true
1316    28.       break
1317    29.     endif
1318    30.  endfor
1319    31.  if (success == false) then
1320    32.    II = II + 1
1321    33.    if (II > maxII) then
1322    34.       finish - failed to schedule
1323    35.   endif
1324    36.    goto 2.
1325    37.  endif
1326    38. endfor
1327    39. if (calculate_register_pressure(PS) > maxRP) then
1328    40.    goto 32.
1329    41. endif
1330    42. compute epilogue & prologue
1331    43. finish - succeeded to schedule
1332 */
1333
1334 /* A limit on the number of cycles that resource conflicts can span.  ??? Should
1335    be provided by DFA, and be dependent on the type of insn scheduled.  Currently
1336    set to 0 to save compile time.  */
1337 #define DFA_HISTORY SMS_DFA_HISTORY
1338
1339 /* A threshold for the number of repeated unsuccessful attempts to insert
1340    an empty row, before we flush the partial schedule and start over.  */
1341 #define MAX_SPLIT_NUM 10
1342 /* Given the partial schedule PS, this function calculates and returns the
1343    cycles in which we can schedule the node with the given index I.
1344    NOTE: Here we do the backtracking in SMS, in some special cases. We have
1345    noticed that there are several cases in which we fail    to SMS the loop
1346    because the sched window of a node is empty    due to tight data-deps. In
1347    such cases we want to unschedule    some of the predecessors/successors
1348    until we get non-empty    scheduling window.  It returns -1 if the
1349    scheduling window is empty and zero otherwise.  */
1350
1351 static int
1352 get_sched_window (partial_schedule_ptr ps, int *nodes_order, int i,
1353                   sbitmap sched_nodes, int ii, int *start_p, int *step_p, int *end_p)
1354 {
1355   int start, step, end;
1356   ddg_edge_ptr e;
1357   int u = nodes_order [i];
1358   ddg_node_ptr u_node = &ps->g->nodes[u];
1359   sbitmap psp = sbitmap_alloc (ps->g->num_nodes);
1360   sbitmap pss = sbitmap_alloc (ps->g->num_nodes);
1361   sbitmap u_node_preds = NODE_PREDECESSORS (u_node);
1362   sbitmap u_node_succs = NODE_SUCCESSORS (u_node);
1363   int psp_not_empty;
1364   int pss_not_empty;
1365
1366   /* 1. compute sched window for u (start, end, step).  */
1367   sbitmap_zero (psp);
1368   sbitmap_zero (pss);
1369   psp_not_empty = sbitmap_a_and_b_cg (psp, u_node_preds, sched_nodes);
1370   pss_not_empty = sbitmap_a_and_b_cg (pss, u_node_succs, sched_nodes);
1371
1372   if (psp_not_empty && !pss_not_empty)
1373     {
1374       int early_start = INT_MIN;
1375
1376       end = INT_MAX;
1377       for (e = u_node->in; e != 0; e = e->next_in)
1378         {
1379           ddg_node_ptr v_node = e->src;
1380
1381           if (dump_file)
1382             {
1383               fprintf (dump_file, "\nProcessing edge: ");
1384               print_ddg_edge (dump_file, e);
1385               fprintf (dump_file,
1386                        "\nScheduling %d (%d) in psp_not_empty,"
1387                        " checking p %d (%d): ", u_node->cuid,
1388                        INSN_UID (u_node->insn), v_node->cuid, INSN_UID
1389                        (v_node->insn));
1390             }
1391
1392           if (TEST_BIT (sched_nodes, v_node->cuid))
1393             {
1394               int p_st = SCHED_TIME (v_node);
1395
1396               early_start =
1397                 MAX (early_start, p_st + e->latency - (e->distance * ii));
1398
1399               if (dump_file)
1400                 fprintf (dump_file,
1401                          "pred st = %d; early_start = %d; latency: %d",
1402                          p_st, early_start, e->latency);
1403
1404               if (e->data_type == MEM_DEP)
1405                 end = MIN (end, SCHED_TIME (v_node) + ii - 1);
1406             }
1407          else if (dump_file)
1408             fprintf (dump_file, "the node is not scheduled\n");
1409         }
1410       start = early_start;
1411       end = MIN (end, early_start + ii);
1412       /* Schedule the node close to it's predecessors.  */
1413       step = 1;
1414
1415       if (dump_file)
1416         fprintf (dump_file,
1417                  "\nScheduling %d (%d) in a window (%d..%d) with step %d\n",
1418                  u_node->cuid, INSN_UID (u_node->insn), start, end, step);
1419     }
1420
1421   else if (!psp_not_empty && pss_not_empty)
1422     {
1423       int late_start = INT_MAX;
1424
1425       end = INT_MIN;
1426       for (e = u_node->out; e != 0; e = e->next_out)
1427         {
1428           ddg_node_ptr v_node = e->dest;
1429
1430           if (dump_file)
1431             {
1432               fprintf (dump_file, "\nProcessing edge:");
1433               print_ddg_edge (dump_file, e);
1434               fprintf (dump_file,
1435                        "\nScheduling %d (%d) in pss_not_empty,"
1436                        " checking s %d (%d): ", u_node->cuid,
1437                        INSN_UID (u_node->insn), v_node->cuid, INSN_UID
1438                        (v_node->insn));
1439             }
1440
1441           if (TEST_BIT (sched_nodes, v_node->cuid))
1442             {
1443               int s_st = SCHED_TIME (v_node);
1444
1445               late_start = MIN (late_start,
1446                                 s_st - e->latency + (e->distance * ii));
1447
1448               if (dump_file)
1449                 fprintf (dump_file,
1450                          "succ st = %d; late_start = %d; latency = %d",
1451                          s_st, late_start, e->latency);
1452
1453               if (e->data_type == MEM_DEP)
1454                 end = MAX (end, SCHED_TIME (v_node) - ii + 1);
1455              if (dump_file)
1456                  fprintf (dump_file, "end = %d\n", end);
1457
1458             }
1459           else if (dump_file)
1460             fprintf (dump_file, "the node is not scheduled\n");
1461
1462         }
1463       start = late_start;
1464       end = MAX (end, late_start - ii);
1465       /* Schedule the node close to it's successors.  */
1466       step = -1;
1467
1468       if (dump_file)
1469         fprintf (dump_file,
1470                  "\nScheduling %d (%d) in a window (%d..%d) with step %d\n",
1471                  u_node->cuid, INSN_UID (u_node->insn), start, end, step);
1472
1473     }
1474
1475   else if (psp_not_empty && pss_not_empty)
1476     {
1477       int early_start = INT_MIN;
1478       int late_start = INT_MAX;
1479       int count_preds = 0;
1480       int count_succs = 0;
1481
1482       start = INT_MIN;
1483       end = INT_MAX;
1484       for (e = u_node->in; e != 0; e = e->next_in)
1485         {
1486           ddg_node_ptr v_node = e->src;
1487
1488           if (dump_file)
1489             {
1490               fprintf (dump_file, "\nProcessing edge:");
1491               print_ddg_edge (dump_file, e);
1492               fprintf (dump_file,
1493                        "\nScheduling %d (%d) in psp_pss_not_empty,"
1494                        " checking p %d (%d): ", u_node->cuid, INSN_UID
1495                        (u_node->insn), v_node->cuid, INSN_UID
1496                        (v_node->insn));
1497             }
1498
1499           if (TEST_BIT (sched_nodes, v_node->cuid))
1500             {
1501               int p_st = SCHED_TIME (v_node);
1502
1503               early_start = MAX (early_start,
1504                                  p_st + e->latency
1505                                  - (e->distance * ii));
1506
1507               if (dump_file)
1508                 fprintf (dump_file,
1509                          "pred st = %d; early_start = %d; latency = %d",
1510                          p_st, early_start, e->latency);
1511
1512               if (e->type == TRUE_DEP && e->data_type == REG_DEP)
1513                 count_preds++;
1514
1515               if (e->data_type == MEM_DEP)
1516                 end = MIN (end, SCHED_TIME (v_node) + ii - 1);
1517             }
1518           else if (dump_file)
1519             fprintf (dump_file, "the node is not scheduled\n");
1520
1521         }
1522       for (e = u_node->out; e != 0; e = e->next_out)
1523         {
1524           ddg_node_ptr v_node = e->dest;
1525
1526           if (dump_file)
1527             {
1528               fprintf (dump_file, "\nProcessing edge:");
1529               print_ddg_edge (dump_file, e);
1530               fprintf (dump_file,
1531                        "\nScheduling %d (%d) in psp_pss_not_empty,"
1532                        " checking s %d (%d): ", u_node->cuid, INSN_UID
1533                        (u_node->insn), v_node->cuid, INSN_UID
1534                        (v_node->insn));
1535             }
1536
1537           if (TEST_BIT (sched_nodes, v_node->cuid))
1538             {
1539               int s_st = SCHED_TIME (v_node);
1540
1541               late_start = MIN (late_start,
1542                                 s_st - e->latency
1543                                 + (e->distance * ii));
1544
1545               if (dump_file)
1546                 fprintf (dump_file,
1547                          "succ st = %d; late_start = %d; latency = %d",
1548                          s_st, late_start, e->latency);
1549
1550                if (e->type == TRUE_DEP && e->data_type == REG_DEP)
1551                  count_succs++;
1552
1553               if (e->data_type == MEM_DEP)
1554                 start = MAX (start, SCHED_TIME (v_node) - ii + 1);
1555             }
1556           else if (dump_file)
1557             fprintf (dump_file, "the node is not scheduled\n");
1558
1559         }
1560       start = MAX (start, early_start);
1561       end = MIN (end, MIN (early_start + ii, late_start + 1));
1562       step = 1;
1563       /* If there are more successors than predecessors schedule the
1564          node close to it's successors.  */
1565       if (count_succs >= count_preds)
1566         {
1567           int old_start = start;
1568
1569           start = end - 1;
1570           end = old_start - 1;
1571           step = -1;
1572         }
1573     }
1574   else /* psp is empty && pss is empty.  */
1575     {
1576       start = SCHED_ASAP (u_node);
1577       end = start + ii;
1578       step = 1;
1579     }
1580
1581   *start_p = start;
1582   *step_p = step;
1583   *end_p = end;
1584   sbitmap_free (psp);
1585   sbitmap_free (pss);
1586
1587   if ((start >= end && step == 1) || (start <= end && step == -1))
1588     {
1589       if (dump_file)
1590         fprintf (dump_file, "\nEmpty window: start=%d, end=%d, step=%d\n",
1591                  start, end, step);
1592     return -1;
1593     }
1594
1595     return 0;
1596 }
1597
1598 /* Calculate MUST_PRECEDE/MUST_FOLLOW bitmaps of U_NODE; which is the
1599    node currently been scheduled.  At the end of the calculation
1600    MUST_PRECEDE/MUST_FOLLOW contains all predecessors/successors of
1601    U_NODE which are (1) already scheduled in the first/last row of
1602    U_NODE's scheduling window, (2) whose dependence inequality with U
1603    becomes an equality when U is scheduled in this same row, and (3)
1604    whose dependence latency is zero.
1605
1606    The first and last rows are calculated using the following parameters:
1607    START/END rows - The cycles that begins/ends the traversal on the window;
1608    searching for an empty cycle to schedule U_NODE.
1609    STEP - The direction in which we traverse the window.
1610    II - The initiation interval.  */
1611
1612 static void
1613 calculate_must_precede_follow (ddg_node_ptr u_node, int start, int end,
1614                                int step, int ii, sbitmap sched_nodes,
1615                                sbitmap must_precede, sbitmap must_follow)
1616 {
1617   ddg_edge_ptr e;
1618   int first_cycle_in_window, last_cycle_in_window;
1619
1620   gcc_assert (must_precede && must_follow);
1621
1622   /* Consider the following scheduling window:
1623      {first_cycle_in_window, first_cycle_in_window+1, ...,
1624      last_cycle_in_window}.  If step is 1 then the following will be
1625      the order we traverse the window: {start=first_cycle_in_window,
1626      first_cycle_in_window+1, ..., end=last_cycle_in_window+1},
1627      or {start=last_cycle_in_window, last_cycle_in_window-1, ...,
1628      end=first_cycle_in_window-1} if step is -1.  */
1629   first_cycle_in_window = (step == 1) ? start : end - step;
1630   last_cycle_in_window = (step == 1) ? end - step : start;
1631
1632   sbitmap_zero (must_precede);
1633   sbitmap_zero (must_follow);
1634
1635   if (dump_file)
1636     fprintf (dump_file, "\nmust_precede: ");
1637
1638   /* Instead of checking if:
1639       (SMODULO (SCHED_TIME (e->src), ii) == first_row_in_window)
1640       && ((SCHED_TIME (e->src) + e->latency - (e->distance * ii)) ==
1641              first_cycle_in_window)
1642       && e->latency == 0
1643      we use the fact that latency is non-negative:
1644       SCHED_TIME (e->src) - (e->distance * ii) <=
1645       SCHED_TIME (e->src) + e->latency - (e->distance * ii)) <=
1646       first_cycle_in_window
1647      and check only if
1648       SCHED_TIME (e->src) - (e->distance * ii) == first_cycle_in_window  */
1649   for (e = u_node->in; e != 0; e = e->next_in)
1650     if (TEST_BIT (sched_nodes, e->src->cuid)
1651         && ((SCHED_TIME (e->src) - (e->distance * ii)) ==
1652              first_cycle_in_window))
1653       {
1654         if (dump_file)
1655           fprintf (dump_file, "%d ", e->src->cuid);
1656
1657         SET_BIT (must_precede, e->src->cuid);
1658       }
1659
1660   if (dump_file)
1661     fprintf (dump_file, "\nmust_follow: ");
1662
1663   /* Instead of checking if:
1664       (SMODULO (SCHED_TIME (e->dest), ii) == last_row_in_window)
1665       && ((SCHED_TIME (e->dest) - e->latency + (e->distance * ii)) ==
1666              last_cycle_in_window)
1667       && e->latency == 0
1668      we use the fact that latency is non-negative:
1669       SCHED_TIME (e->dest) + (e->distance * ii) >=
1670       SCHED_TIME (e->dest) - e->latency + (e->distance * ii)) >=
1671       last_cycle_in_window
1672      and check only if
1673       SCHED_TIME (e->dest) + (e->distance * ii) == last_cycle_in_window  */
1674   for (e = u_node->out; e != 0; e = e->next_out)
1675     if (TEST_BIT (sched_nodes, e->dest->cuid)
1676         && ((SCHED_TIME (e->dest) + (e->distance * ii)) ==
1677              last_cycle_in_window))
1678       {
1679         if (dump_file)
1680           fprintf (dump_file, "%d ", e->dest->cuid);
1681
1682         SET_BIT (must_follow, e->dest->cuid);
1683       }
1684
1685   if (dump_file)
1686     fprintf (dump_file, "\n");
1687 }
1688
1689 /* Return 1 if U_NODE can be scheduled in CYCLE.  Use the following
1690    parameters to decide if that's possible:
1691    PS - The partial schedule.
1692    U - The serial number of U_NODE.
1693    NUM_SPLITS - The number of row splits made so far.
1694    MUST_PRECEDE - The nodes that must precede U_NODE. (only valid at
1695    the first row of the scheduling window)
1696    MUST_FOLLOW - The nodes that must follow U_NODE. (only valid at the
1697    last row of the scheduling window)  */
1698
1699 static bool
1700 try_scheduling_node_in_cycle (partial_schedule_ptr ps, ddg_node_ptr u_node,
1701                               int u, int cycle, sbitmap sched_nodes,
1702                               int *num_splits, sbitmap must_precede,
1703                               sbitmap must_follow)
1704 {
1705   ps_insn_ptr psi;
1706   bool success = 0;
1707
1708   verify_partial_schedule (ps, sched_nodes);
1709   psi = ps_add_node_check_conflicts (ps, u_node, cycle,
1710                                      must_precede, must_follow);
1711   if (psi)
1712     {
1713       SCHED_TIME (u_node) = cycle;
1714       SET_BIT (sched_nodes, u);
1715       success = 1;
1716       *num_splits = 0;
1717       if (dump_file)
1718         fprintf (dump_file, "Scheduled w/o split in %d\n", cycle);
1719
1720     }
1721
1722   return success;
1723 }
1724
1725 /* This function implements the scheduling algorithm for SMS according to the
1726    above algorithm.  */
1727 static partial_schedule_ptr
1728 sms_schedule_by_order (ddg_ptr g, int mii, int maxii, int *nodes_order)
1729 {
1730   int ii = mii;
1731   int i, c, success, num_splits = 0;
1732   int flush_and_start_over = true;
1733   int num_nodes = g->num_nodes;
1734   int start, end, step; /* Place together into one struct?  */
1735   sbitmap sched_nodes = sbitmap_alloc (num_nodes);
1736   sbitmap must_precede = sbitmap_alloc (num_nodes);
1737   sbitmap must_follow = sbitmap_alloc (num_nodes);
1738   sbitmap tobe_scheduled = sbitmap_alloc (num_nodes);
1739
1740   partial_schedule_ptr ps = create_partial_schedule (ii, g, DFA_HISTORY);
1741
1742   sbitmap_ones (tobe_scheduled);
1743   sbitmap_zero (sched_nodes);
1744
1745   while (flush_and_start_over && (ii < maxii))
1746     {
1747
1748       if (dump_file)
1749         fprintf (dump_file, "Starting with ii=%d\n", ii);
1750       flush_and_start_over = false;
1751       sbitmap_zero (sched_nodes);
1752
1753       for (i = 0; i < num_nodes; i++)
1754         {
1755           int u = nodes_order[i];
1756           ddg_node_ptr u_node = &ps->g->nodes[u];
1757           rtx insn = u_node->insn;
1758
1759           if (!NONDEBUG_INSN_P (insn))
1760             {
1761               RESET_BIT (tobe_scheduled, u);
1762               continue;
1763             }
1764
1765           if (JUMP_P (insn)) /* Closing branch handled later.  */
1766             {
1767               RESET_BIT (tobe_scheduled, u);
1768               continue;
1769             }
1770
1771           if (TEST_BIT (sched_nodes, u))
1772             continue;
1773
1774           /* Try to get non-empty scheduling window.  */
1775          success = 0;
1776          if (get_sched_window (ps, nodes_order, i, sched_nodes, ii, &start,
1777                                 &step, &end) == 0)
1778             {
1779               if (dump_file)
1780                 fprintf (dump_file, "\nTrying to schedule node %d \
1781                         INSN = %d  in (%d .. %d) step %d\n", u, (INSN_UID
1782                         (g->nodes[u].insn)), start, end, step);
1783
1784               gcc_assert ((step > 0 && start < end)
1785                           || (step < 0 && start > end));
1786
1787               calculate_must_precede_follow (u_node, start, end, step, ii,
1788                                              sched_nodes, must_precede,
1789                                              must_follow);
1790
1791               for (c = start; c != end; c += step)
1792                 {
1793                   sbitmap tmp_precede = NULL;
1794                   sbitmap tmp_follow = NULL;
1795
1796                   if (c == start)
1797                     {
1798                       if (step == 1)
1799                         tmp_precede = must_precede;
1800                       else      /* step == -1.  */
1801                         tmp_follow = must_follow;
1802                     }
1803                   if (c == end - step)
1804                     {
1805                       if (step == 1)
1806                         tmp_follow = must_follow;
1807                       else      /* step == -1.  */
1808                         tmp_precede = must_precede;
1809                     }
1810
1811                   success =
1812                     try_scheduling_node_in_cycle (ps, u_node, u, c,
1813                                                   sched_nodes,
1814                                                   &num_splits, tmp_precede,
1815                                                   tmp_follow);
1816                   if (success)
1817                     break;
1818                 }
1819
1820               verify_partial_schedule (ps, sched_nodes);
1821             }
1822             if (!success)
1823             {
1824               int split_row;
1825
1826               if (ii++ == maxii)
1827                 break;
1828
1829               if (num_splits >= MAX_SPLIT_NUM)
1830                 {
1831                   num_splits = 0;
1832                   flush_and_start_over = true;
1833                   verify_partial_schedule (ps, sched_nodes);
1834                   reset_partial_schedule (ps, ii);
1835                   verify_partial_schedule (ps, sched_nodes);
1836                   break;
1837                 }
1838
1839               num_splits++;
1840               /* The scheduling window is exclusive of 'end'
1841                  whereas compute_split_window() expects an inclusive,
1842                  ordered range.  */
1843               if (step == 1)
1844                 split_row = compute_split_row (sched_nodes, start, end - 1,
1845                                                ps->ii, u_node);
1846               else
1847                 split_row = compute_split_row (sched_nodes, end + 1, start,
1848                                                ps->ii, u_node);
1849
1850               ps_insert_empty_row (ps, split_row, sched_nodes);
1851               i--;              /* Go back and retry node i.  */
1852
1853               if (dump_file)
1854                 fprintf (dump_file, "num_splits=%d\n", num_splits);
1855             }
1856
1857           /* ??? If (success), check register pressure estimates.  */
1858         }                       /* Continue with next node.  */
1859     }                           /* While flush_and_start_over.  */
1860   if (ii >= maxii)
1861     {
1862       free_partial_schedule (ps);
1863       ps = NULL;
1864     }
1865   else
1866     gcc_assert (sbitmap_equal (tobe_scheduled, sched_nodes));
1867
1868   sbitmap_free (sched_nodes);
1869   sbitmap_free (must_precede);
1870   sbitmap_free (must_follow);
1871   sbitmap_free (tobe_scheduled);
1872
1873   return ps;
1874 }
1875
1876 /* This function inserts a new empty row into PS at the position
1877    according to SPLITROW, keeping all already scheduled instructions
1878    intact and updating their SCHED_TIME and cycle accordingly.  */
1879 static void
1880 ps_insert_empty_row (partial_schedule_ptr ps, int split_row,
1881                      sbitmap sched_nodes)
1882 {
1883   ps_insn_ptr crr_insn;
1884   ps_insn_ptr *rows_new;
1885   int ii = ps->ii;
1886   int new_ii = ii + 1;
1887   int row;
1888
1889   verify_partial_schedule (ps, sched_nodes);
1890
1891   /* We normalize sched_time and rotate ps to have only non-negative sched
1892      times, for simplicity of updating cycles after inserting new row.  */
1893   split_row -= ps->min_cycle;
1894   split_row = SMODULO (split_row, ii);
1895   if (dump_file)
1896     fprintf (dump_file, "split_row=%d\n", split_row);
1897
1898   normalize_sched_times (ps);
1899   rotate_partial_schedule (ps, ps->min_cycle);
1900
1901   rows_new = (ps_insn_ptr *) xcalloc (new_ii, sizeof (ps_insn_ptr));
1902   for (row = 0; row < split_row; row++)
1903     {
1904       rows_new[row] = ps->rows[row];
1905       ps->rows[row] = NULL;
1906       for (crr_insn = rows_new[row];
1907            crr_insn; crr_insn = crr_insn->next_in_row)
1908         {
1909           ddg_node_ptr u = crr_insn->node;
1910           int new_time = SCHED_TIME (u) + (SCHED_TIME (u) / ii);
1911
1912           SCHED_TIME (u) = new_time;
1913           crr_insn->cycle = new_time;
1914           SCHED_ROW (u) = new_time % new_ii;
1915           SCHED_STAGE (u) = new_time / new_ii;
1916         }
1917
1918     }
1919
1920   rows_new[split_row] = NULL;
1921
1922   for (row = split_row; row < ii; row++)
1923     {
1924       rows_new[row + 1] = ps->rows[row];
1925       ps->rows[row] = NULL;
1926       for (crr_insn = rows_new[row + 1];
1927            crr_insn; crr_insn = crr_insn->next_in_row)
1928         {
1929           ddg_node_ptr u = crr_insn->node;
1930           int new_time = SCHED_TIME (u) + (SCHED_TIME (u) / ii) + 1;
1931
1932           SCHED_TIME (u) = new_time;
1933           crr_insn->cycle = new_time;
1934           SCHED_ROW (u) = new_time % new_ii;
1935           SCHED_STAGE (u) = new_time / new_ii;
1936         }
1937     }
1938
1939   /* Updating ps.  */
1940   ps->min_cycle = ps->min_cycle + ps->min_cycle / ii
1941     + (SMODULO (ps->min_cycle, ii) >= split_row ? 1 : 0);
1942   ps->max_cycle = ps->max_cycle + ps->max_cycle / ii
1943     + (SMODULO (ps->max_cycle, ii) >= split_row ? 1 : 0);
1944   free (ps->rows);
1945   ps->rows = rows_new;
1946   ps->ii = new_ii;
1947   gcc_assert (ps->min_cycle >= 0);
1948
1949   verify_partial_schedule (ps, sched_nodes);
1950
1951   if (dump_file)
1952     fprintf (dump_file, "min_cycle=%d, max_cycle=%d\n", ps->min_cycle,
1953              ps->max_cycle);
1954 }
1955
1956 /* Given U_NODE which is the node that failed to be scheduled; LOW and
1957    UP which are the boundaries of it's scheduling window; compute using
1958    SCHED_NODES and II a row in the partial schedule that can be split
1959    which will separate a critical predecessor from a critical successor
1960    thereby expanding the window, and return it.  */
1961 static int
1962 compute_split_row (sbitmap sched_nodes, int low, int up, int ii,
1963                    ddg_node_ptr u_node)
1964 {
1965   ddg_edge_ptr e;
1966   int lower = INT_MIN, upper = INT_MAX;
1967   ddg_node_ptr crit_pred = NULL;
1968   ddg_node_ptr crit_succ = NULL;
1969   int crit_cycle;
1970
1971   for (e = u_node->in; e != 0; e = e->next_in)
1972     {
1973       ddg_node_ptr v_node = e->src;
1974
1975       if (TEST_BIT (sched_nodes, v_node->cuid)
1976           && (low == SCHED_TIME (v_node) + e->latency - (e->distance * ii)))
1977         if (SCHED_TIME (v_node) > lower)
1978           {
1979             crit_pred = v_node;
1980             lower = SCHED_TIME (v_node);
1981           }
1982     }
1983
1984   if (crit_pred != NULL)
1985     {
1986       crit_cycle = SCHED_TIME (crit_pred) + 1;
1987       return SMODULO (crit_cycle, ii);
1988     }
1989
1990   for (e = u_node->out; e != 0; e = e->next_out)
1991     {
1992       ddg_node_ptr v_node = e->dest;
1993       if (TEST_BIT (sched_nodes, v_node->cuid)
1994           && (up == SCHED_TIME (v_node) - e->latency + (e->distance * ii)))
1995         if (SCHED_TIME (v_node) < upper)
1996           {
1997             crit_succ = v_node;
1998             upper = SCHED_TIME (v_node);
1999           }
2000     }
2001
2002   if (crit_succ != NULL)
2003     {
2004       crit_cycle = SCHED_TIME (crit_succ);
2005       return SMODULO (crit_cycle, ii);
2006     }
2007
2008   if (dump_file)
2009     fprintf (dump_file, "Both crit_pred and crit_succ are NULL\n");
2010
2011   return SMODULO ((low + up + 1) / 2, ii);
2012 }
2013
2014 static void
2015 verify_partial_schedule (partial_schedule_ptr ps, sbitmap sched_nodes)
2016 {
2017   int row;
2018   ps_insn_ptr crr_insn;
2019
2020   for (row = 0; row < ps->ii; row++)
2021     for (crr_insn = ps->rows[row]; crr_insn; crr_insn = crr_insn->next_in_row)
2022       {
2023         ddg_node_ptr u = crr_insn->node;
2024
2025         gcc_assert (TEST_BIT (sched_nodes, u->cuid));
2026         /* ??? Test also that all nodes of sched_nodes are in ps, perhaps by
2027            popcount (sched_nodes) == number of insns in ps.  */
2028         gcc_assert (SCHED_TIME (u) >= ps->min_cycle);
2029         gcc_assert (SCHED_TIME (u) <= ps->max_cycle);
2030       }
2031 }
2032
2033 \f
2034 /* This page implements the algorithm for ordering the nodes of a DDG
2035    for modulo scheduling, activated through the
2036    "int sms_order_nodes (ddg_ptr, int mii, int * result)" API.  */
2037
2038 #define ORDER_PARAMS(x) ((struct node_order_params *) (x)->aux.info)
2039 #define ASAP(x) (ORDER_PARAMS ((x))->asap)
2040 #define ALAP(x) (ORDER_PARAMS ((x))->alap)
2041 #define HEIGHT(x) (ORDER_PARAMS ((x))->height)
2042 #define MOB(x) (ALAP ((x)) - ASAP ((x)))
2043 #define DEPTH(x) (ASAP ((x)))
2044
2045 typedef struct node_order_params * nopa;
2046
2047 static void order_nodes_of_sccs (ddg_all_sccs_ptr, int * result);
2048 static int order_nodes_in_scc (ddg_ptr, sbitmap, sbitmap, int*, int);
2049 static nopa  calculate_order_params (ddg_ptr, int, int *);
2050 static int find_max_asap (ddg_ptr, sbitmap);
2051 static int find_max_hv_min_mob (ddg_ptr, sbitmap);
2052 static int find_max_dv_min_mob (ddg_ptr, sbitmap);
2053
2054 enum sms_direction {BOTTOMUP, TOPDOWN};
2055
2056 struct node_order_params
2057 {
2058   int asap;
2059   int alap;
2060   int height;
2061 };
2062
2063 /* Check if NODE_ORDER contains a permutation of 0 .. NUM_NODES-1.  */
2064 static void
2065 check_nodes_order (int *node_order, int num_nodes)
2066 {
2067   int i;
2068   sbitmap tmp = sbitmap_alloc (num_nodes);
2069
2070   sbitmap_zero (tmp);
2071
2072   if (dump_file)
2073     fprintf (dump_file, "SMS final nodes order: \n");
2074
2075   for (i = 0; i < num_nodes; i++)
2076     {
2077       int u = node_order[i];
2078
2079       if (dump_file)
2080         fprintf (dump_file, "%d ", u);
2081       gcc_assert (u < num_nodes && u >= 0 && !TEST_BIT (tmp, u));
2082
2083       SET_BIT (tmp, u);
2084     }
2085
2086   if (dump_file)
2087     fprintf (dump_file, "\n");
2088
2089   sbitmap_free (tmp);
2090 }
2091
2092 /* Order the nodes of G for scheduling and pass the result in
2093    NODE_ORDER.  Also set aux.count of each node to ASAP.
2094    Put maximal ASAP to PMAX_ASAP.  Return the recMII for the given DDG.  */
2095 static int
2096 sms_order_nodes (ddg_ptr g, int mii, int * node_order, int *pmax_asap)
2097 {
2098   int i;
2099   int rec_mii = 0;
2100   ddg_all_sccs_ptr sccs = create_ddg_all_sccs (g);
2101
2102   nopa nops = calculate_order_params (g, mii, pmax_asap);
2103
2104   if (dump_file)
2105     print_sccs (dump_file, sccs, g);
2106
2107   order_nodes_of_sccs (sccs, node_order);
2108
2109   if (sccs->num_sccs > 0)
2110     /* First SCC has the largest recurrence_length.  */
2111     rec_mii = sccs->sccs[0]->recurrence_length;
2112
2113   /* Save ASAP before destroying node_order_params.  */
2114   for (i = 0; i < g->num_nodes; i++)
2115     {
2116       ddg_node_ptr v = &g->nodes[i];
2117       v->aux.count = ASAP (v);
2118     }
2119
2120   free (nops);
2121   free_ddg_all_sccs (sccs);
2122   check_nodes_order (node_order, g->num_nodes);
2123
2124   return rec_mii;
2125 }
2126
2127 static void
2128 order_nodes_of_sccs (ddg_all_sccs_ptr all_sccs, int * node_order)
2129 {
2130   int i, pos = 0;
2131   ddg_ptr g = all_sccs->ddg;
2132   int num_nodes = g->num_nodes;
2133   sbitmap prev_sccs = sbitmap_alloc (num_nodes);
2134   sbitmap on_path = sbitmap_alloc (num_nodes);
2135   sbitmap tmp = sbitmap_alloc (num_nodes);
2136   sbitmap ones = sbitmap_alloc (num_nodes);
2137
2138   sbitmap_zero (prev_sccs);
2139   sbitmap_ones (ones);
2140
2141   /* Perform the node ordering starting from the SCC with the highest recMII.
2142      For each SCC order the nodes according to their ASAP/ALAP/HEIGHT etc.  */
2143   for (i = 0; i < all_sccs->num_sccs; i++)
2144     {
2145       ddg_scc_ptr scc = all_sccs->sccs[i];
2146
2147       /* Add nodes on paths from previous SCCs to the current SCC.  */
2148       find_nodes_on_paths (on_path, g, prev_sccs, scc->nodes);
2149       sbitmap_a_or_b (tmp, scc->nodes, on_path);
2150
2151       /* Add nodes on paths from the current SCC to previous SCCs.  */
2152       find_nodes_on_paths (on_path, g, scc->nodes, prev_sccs);
2153       sbitmap_a_or_b (tmp, tmp, on_path);
2154
2155       /* Remove nodes of previous SCCs from current extended SCC.  */
2156       sbitmap_difference (tmp, tmp, prev_sccs);
2157
2158       pos = order_nodes_in_scc (g, prev_sccs, tmp, node_order, pos);
2159       /* Above call to order_nodes_in_scc updated prev_sccs |= tmp.  */
2160     }
2161
2162   /* Handle the remaining nodes that do not belong to any scc.  Each call
2163      to order_nodes_in_scc handles a single connected component.  */
2164   while (pos < g->num_nodes)
2165     {
2166       sbitmap_difference (tmp, ones, prev_sccs);
2167       pos = order_nodes_in_scc (g, prev_sccs, tmp, node_order, pos);
2168     }
2169   sbitmap_free (prev_sccs);
2170   sbitmap_free (on_path);
2171   sbitmap_free (tmp);
2172   sbitmap_free (ones);
2173 }
2174
2175 /* MII is needed if we consider backarcs (that do not close recursive cycles).  */
2176 static struct node_order_params *
2177 calculate_order_params (ddg_ptr g, int mii ATTRIBUTE_UNUSED, int *pmax_asap)
2178 {
2179   int u;
2180   int max_asap;
2181   int num_nodes = g->num_nodes;
2182   ddg_edge_ptr e;
2183   /* Allocate a place to hold ordering params for each node in the DDG.  */
2184   nopa node_order_params_arr;
2185
2186   /* Initialize of ASAP/ALAP/HEIGHT to zero.  */
2187   node_order_params_arr = (nopa) xcalloc (num_nodes,
2188                                           sizeof (struct node_order_params));
2189
2190   /* Set the aux pointer of each node to point to its order_params structure.  */
2191   for (u = 0; u < num_nodes; u++)
2192     g->nodes[u].aux.info = &node_order_params_arr[u];
2193
2194   /* Disregarding a backarc from each recursive cycle to obtain a DAG,
2195      calculate ASAP, ALAP, mobility, distance, and height for each node
2196      in the dependence (direct acyclic) graph.  */
2197
2198   /* We assume that the nodes in the array are in topological order.  */
2199
2200   max_asap = 0;
2201   for (u = 0; u < num_nodes; u++)
2202     {
2203       ddg_node_ptr u_node = &g->nodes[u];
2204
2205       ASAP (u_node) = 0;
2206       for (e = u_node->in; e; e = e->next_in)
2207         if (e->distance == 0)
2208           ASAP (u_node) = MAX (ASAP (u_node),
2209                                ASAP (e->src) + e->latency);
2210       max_asap = MAX (max_asap, ASAP (u_node));
2211     }
2212
2213   for (u = num_nodes - 1; u > -1; u--)
2214     {
2215       ddg_node_ptr u_node = &g->nodes[u];
2216
2217       ALAP (u_node) = max_asap;
2218       HEIGHT (u_node) = 0;
2219       for (e = u_node->out; e; e = e->next_out)
2220         if (e->distance == 0)
2221           {
2222             ALAP (u_node) = MIN (ALAP (u_node),
2223                                  ALAP (e->dest) - e->latency);
2224             HEIGHT (u_node) = MAX (HEIGHT (u_node),
2225                                    HEIGHT (e->dest) + e->latency);
2226           }
2227     }
2228   if (dump_file)
2229   {
2230     fprintf (dump_file, "\nOrder params\n");
2231     for (u = 0; u < num_nodes; u++)
2232       {
2233         ddg_node_ptr u_node = &g->nodes[u];
2234
2235         fprintf (dump_file, "node %d, ASAP: %d, ALAP: %d, HEIGHT: %d\n", u,
2236                  ASAP (u_node), ALAP (u_node), HEIGHT (u_node));
2237       }
2238   }
2239
2240   *pmax_asap = max_asap;
2241   return node_order_params_arr;
2242 }
2243
2244 static int
2245 find_max_asap (ddg_ptr g, sbitmap nodes)
2246 {
2247   unsigned int u = 0;
2248   int max_asap = -1;
2249   int result = -1;
2250   sbitmap_iterator sbi;
2251
2252   EXECUTE_IF_SET_IN_SBITMAP (nodes, 0, u, sbi)
2253     {
2254       ddg_node_ptr u_node = &g->nodes[u];
2255
2256       if (max_asap < ASAP (u_node))
2257         {
2258           max_asap = ASAP (u_node);
2259           result = u;
2260         }
2261     }
2262   return result;
2263 }
2264
2265 static int
2266 find_max_hv_min_mob (ddg_ptr g, sbitmap nodes)
2267 {
2268   unsigned int u = 0;
2269   int max_hv = -1;
2270   int min_mob = INT_MAX;
2271   int result = -1;
2272   sbitmap_iterator sbi;
2273
2274   EXECUTE_IF_SET_IN_SBITMAP (nodes, 0, u, sbi)
2275     {
2276       ddg_node_ptr u_node = &g->nodes[u];
2277
2278       if (max_hv < HEIGHT (u_node))
2279         {
2280           max_hv = HEIGHT (u_node);
2281           min_mob = MOB (u_node);
2282           result = u;
2283         }
2284       else if ((max_hv == HEIGHT (u_node))
2285                && (min_mob > MOB (u_node)))
2286         {
2287           min_mob = MOB (u_node);
2288           result = u;
2289         }
2290     }
2291   return result;
2292 }
2293
2294 static int
2295 find_max_dv_min_mob (ddg_ptr g, sbitmap nodes)
2296 {
2297   unsigned int u = 0;
2298   int max_dv = -1;
2299   int min_mob = INT_MAX;
2300   int result = -1;
2301   sbitmap_iterator sbi;
2302
2303   EXECUTE_IF_SET_IN_SBITMAP (nodes, 0, u, sbi)
2304     {
2305       ddg_node_ptr u_node = &g->nodes[u];
2306
2307       if (max_dv < DEPTH (u_node))
2308         {
2309           max_dv = DEPTH (u_node);
2310           min_mob = MOB (u_node);
2311           result = u;
2312         }
2313       else if ((max_dv == DEPTH (u_node))
2314                && (min_mob > MOB (u_node)))
2315         {
2316           min_mob = MOB (u_node);
2317           result = u;
2318         }
2319     }
2320   return result;
2321 }
2322
2323 /* Places the nodes of SCC into the NODE_ORDER array starting
2324    at position POS, according to the SMS ordering algorithm.
2325    NODES_ORDERED (in&out parameter) holds the bitset of all nodes in
2326    the NODE_ORDER array, starting from position zero.  */
2327 static int
2328 order_nodes_in_scc (ddg_ptr g, sbitmap nodes_ordered, sbitmap scc,
2329                     int * node_order, int pos)
2330 {
2331   enum sms_direction dir;
2332   int num_nodes = g->num_nodes;
2333   sbitmap workset = sbitmap_alloc (num_nodes);
2334   sbitmap tmp = sbitmap_alloc (num_nodes);
2335   sbitmap zero_bitmap = sbitmap_alloc (num_nodes);
2336   sbitmap predecessors = sbitmap_alloc (num_nodes);
2337   sbitmap successors = sbitmap_alloc (num_nodes);
2338
2339   sbitmap_zero (predecessors);
2340   find_predecessors (predecessors, g, nodes_ordered);
2341
2342   sbitmap_zero (successors);
2343   find_successors (successors, g, nodes_ordered);
2344
2345   sbitmap_zero (tmp);
2346   if (sbitmap_a_and_b_cg (tmp, predecessors, scc))
2347     {
2348       sbitmap_copy (workset, tmp);
2349       dir = BOTTOMUP;
2350     }
2351   else if (sbitmap_a_and_b_cg (tmp, successors, scc))
2352     {
2353       sbitmap_copy (workset, tmp);
2354       dir = TOPDOWN;
2355     }
2356   else
2357     {
2358       int u;
2359
2360       sbitmap_zero (workset);
2361       if ((u = find_max_asap (g, scc)) >= 0)
2362         SET_BIT (workset, u);
2363       dir = BOTTOMUP;
2364     }
2365
2366   sbitmap_zero (zero_bitmap);
2367   while (!sbitmap_equal (workset, zero_bitmap))
2368     {
2369       int v;
2370       ddg_node_ptr v_node;
2371       sbitmap v_node_preds;
2372       sbitmap v_node_succs;
2373
2374       if (dir == TOPDOWN)
2375         {
2376           while (!sbitmap_equal (workset, zero_bitmap))
2377             {
2378               v = find_max_hv_min_mob (g, workset);
2379               v_node = &g->nodes[v];
2380               node_order[pos++] = v;
2381               v_node_succs = NODE_SUCCESSORS (v_node);
2382               sbitmap_a_and_b (tmp, v_node_succs, scc);
2383
2384               /* Don't consider the already ordered successors again.  */
2385               sbitmap_difference (tmp, tmp, nodes_ordered);
2386               sbitmap_a_or_b (workset, workset, tmp);
2387               RESET_BIT (workset, v);
2388               SET_BIT (nodes_ordered, v);
2389             }
2390           dir = BOTTOMUP;
2391           sbitmap_zero (predecessors);
2392           find_predecessors (predecessors, g, nodes_ordered);
2393           sbitmap_a_and_b (workset, predecessors, scc);
2394         }
2395       else
2396         {
2397           while (!sbitmap_equal (workset, zero_bitmap))
2398             {
2399               v = find_max_dv_min_mob (g, workset);
2400               v_node = &g->nodes[v];
2401               node_order[pos++] = v;
2402               v_node_preds = NODE_PREDECESSORS (v_node);
2403               sbitmap_a_and_b (tmp, v_node_preds, scc);
2404
2405               /* Don't consider the already ordered predecessors again.  */
2406               sbitmap_difference (tmp, tmp, nodes_ordered);
2407               sbitmap_a_or_b (workset, workset, tmp);
2408               RESET_BIT (workset, v);
2409               SET_BIT (nodes_ordered, v);
2410             }
2411           dir = TOPDOWN;
2412           sbitmap_zero (successors);
2413           find_successors (successors, g, nodes_ordered);
2414           sbitmap_a_and_b (workset, successors, scc);
2415         }
2416     }
2417   sbitmap_free (tmp);
2418   sbitmap_free (workset);
2419   sbitmap_free (zero_bitmap);
2420   sbitmap_free (predecessors);
2421   sbitmap_free (successors);
2422   return pos;
2423 }
2424
2425 \f
2426 /* This page contains functions for manipulating partial-schedules during
2427    modulo scheduling.  */
2428
2429 /* Create a partial schedule and allocate a memory to hold II rows.  */
2430
2431 static partial_schedule_ptr
2432 create_partial_schedule (int ii, ddg_ptr g, int history)
2433 {
2434   partial_schedule_ptr ps = XNEW (struct partial_schedule);
2435   ps->rows = (ps_insn_ptr *) xcalloc (ii, sizeof (ps_insn_ptr));
2436   ps->ii = ii;
2437   ps->history = history;
2438   ps->min_cycle = INT_MAX;
2439   ps->max_cycle = INT_MIN;
2440   ps->g = g;
2441
2442   return ps;
2443 }
2444
2445 /* Free the PS_INSNs in rows array of the given partial schedule.
2446    ??? Consider caching the PS_INSN's.  */
2447 static void
2448 free_ps_insns (partial_schedule_ptr ps)
2449 {
2450   int i;
2451
2452   for (i = 0; i < ps->ii; i++)
2453     {
2454       while (ps->rows[i])
2455         {
2456           ps_insn_ptr ps_insn = ps->rows[i]->next_in_row;
2457
2458           free (ps->rows[i]);
2459           ps->rows[i] = ps_insn;
2460         }
2461       ps->rows[i] = NULL;
2462     }
2463 }
2464
2465 /* Free all the memory allocated to the partial schedule.  */
2466
2467 static void
2468 free_partial_schedule (partial_schedule_ptr ps)
2469 {
2470   if (!ps)
2471     return;
2472   free_ps_insns (ps);
2473   free (ps->rows);
2474   free (ps);
2475 }
2476
2477 /* Clear the rows array with its PS_INSNs, and create a new one with
2478    NEW_II rows.  */
2479
2480 static void
2481 reset_partial_schedule (partial_schedule_ptr ps, int new_ii)
2482 {
2483   if (!ps)
2484     return;
2485   free_ps_insns (ps);
2486   if (new_ii == ps->ii)
2487     return;
2488   ps->rows = (ps_insn_ptr *) xrealloc (ps->rows, new_ii
2489                                                  * sizeof (ps_insn_ptr));
2490   memset (ps->rows, 0, new_ii * sizeof (ps_insn_ptr));
2491   ps->ii = new_ii;
2492   ps->min_cycle = INT_MAX;
2493   ps->max_cycle = INT_MIN;
2494 }
2495
2496 /* Prints the partial schedule as an ii rows array, for each rows
2497    print the ids of the insns in it.  */
2498 void
2499 print_partial_schedule (partial_schedule_ptr ps, FILE *dump)
2500 {
2501   int i;
2502
2503   for (i = 0; i < ps->ii; i++)
2504     {
2505       ps_insn_ptr ps_i = ps->rows[i];
2506
2507       fprintf (dump, "\n[ROW %d ]: ", i);
2508       while (ps_i)
2509         {
2510           fprintf (dump, "%d, ",
2511                    INSN_UID (ps_i->node->insn));
2512           ps_i = ps_i->next_in_row;
2513         }
2514     }
2515 }
2516
2517 /* Creates an object of PS_INSN and initializes it to the given parameters.  */
2518 static ps_insn_ptr
2519 create_ps_insn (ddg_node_ptr node, int rest_count, int cycle)
2520 {
2521   ps_insn_ptr ps_i = XNEW (struct ps_insn);
2522
2523   ps_i->node = node;
2524   ps_i->next_in_row = NULL;
2525   ps_i->prev_in_row = NULL;
2526   ps_i->row_rest_count = rest_count;
2527   ps_i->cycle = cycle;
2528
2529   return ps_i;
2530 }
2531
2532
2533 /* Removes the given PS_INSN from the partial schedule.  Returns false if the
2534    node is not found in the partial schedule, else returns true.  */
2535 static bool
2536 remove_node_from_ps (partial_schedule_ptr ps, ps_insn_ptr ps_i)
2537 {
2538   int row;
2539
2540   if (!ps || !ps_i)
2541     return false;
2542
2543   row = SMODULO (ps_i->cycle, ps->ii);
2544   if (! ps_i->prev_in_row)
2545     {
2546       if (ps_i != ps->rows[row])
2547         return false;
2548
2549       ps->rows[row] = ps_i->next_in_row;
2550       if (ps->rows[row])
2551         ps->rows[row]->prev_in_row = NULL;
2552     }
2553   else
2554     {
2555       ps_i->prev_in_row->next_in_row = ps_i->next_in_row;
2556       if (ps_i->next_in_row)
2557         ps_i->next_in_row->prev_in_row = ps_i->prev_in_row;
2558     }
2559   free (ps_i);
2560   return true;
2561 }
2562
2563 /* Unlike what literature describes for modulo scheduling (which focuses
2564    on VLIW machines) the order of the instructions inside a cycle is
2565    important.  Given the bitmaps MUST_FOLLOW and MUST_PRECEDE we know
2566    where the current instruction should go relative to the already
2567    scheduled instructions in the given cycle.  Go over these
2568    instructions and find the first possible column to put it in.  */
2569 static bool
2570 ps_insn_find_column (partial_schedule_ptr ps, ps_insn_ptr ps_i,
2571                      sbitmap must_precede, sbitmap must_follow)
2572 {
2573   ps_insn_ptr next_ps_i;
2574   ps_insn_ptr first_must_follow = NULL;
2575   ps_insn_ptr last_must_precede = NULL;
2576   int row;
2577
2578   if (! ps_i)
2579     return false;
2580
2581   row = SMODULO (ps_i->cycle, ps->ii);
2582
2583   /* Find the first must follow and the last must precede
2584      and insert the node immediately after the must precede
2585      but make sure that it there is no must follow after it.  */
2586   for (next_ps_i = ps->rows[row];
2587        next_ps_i;
2588        next_ps_i = next_ps_i->next_in_row)
2589     {
2590       if (must_follow && TEST_BIT (must_follow, next_ps_i->node->cuid)
2591           && ! first_must_follow)
2592         first_must_follow = next_ps_i;
2593       if (must_precede && TEST_BIT (must_precede, next_ps_i->node->cuid))
2594         {
2595           /* If we have already met a node that must follow, then
2596              there is no possible column.  */
2597           if (first_must_follow)
2598             return false;
2599           else
2600             last_must_precede = next_ps_i;
2601         }
2602     }
2603
2604   /* Now insert the node after INSERT_AFTER_PSI.  */
2605
2606   if (! last_must_precede)
2607     {
2608       ps_i->next_in_row = ps->rows[row];
2609       ps_i->prev_in_row = NULL;
2610       if (ps_i->next_in_row)
2611         ps_i->next_in_row->prev_in_row = ps_i;
2612       ps->rows[row] = ps_i;
2613     }
2614   else
2615     {
2616       ps_i->next_in_row = last_must_precede->next_in_row;
2617       last_must_precede->next_in_row = ps_i;
2618       ps_i->prev_in_row = last_must_precede;
2619       if (ps_i->next_in_row)
2620         ps_i->next_in_row->prev_in_row = ps_i;
2621     }
2622
2623   return true;
2624 }
2625
2626 /* Advances the PS_INSN one column in its current row; returns false
2627    in failure and true in success.  Bit N is set in MUST_FOLLOW if
2628    the node with cuid N must be come after the node pointed to by
2629    PS_I when scheduled in the same cycle.  */
2630 static int
2631 ps_insn_advance_column (partial_schedule_ptr ps, ps_insn_ptr ps_i,
2632                         sbitmap must_follow)
2633 {
2634   ps_insn_ptr prev, next;
2635   int row;
2636   ddg_node_ptr next_node;
2637
2638   if (!ps || !ps_i)
2639     return false;
2640
2641   row = SMODULO (ps_i->cycle, ps->ii);
2642
2643   if (! ps_i->next_in_row)
2644     return false;
2645
2646   next_node = ps_i->next_in_row->node;
2647
2648   /* Check if next_in_row is dependent on ps_i, both having same sched
2649      times (typically ANTI_DEP).  If so, ps_i cannot skip over it.  */
2650   if (must_follow && TEST_BIT (must_follow, next_node->cuid))
2651     return false;
2652
2653   /* Advance PS_I over its next_in_row in the doubly linked list.  */
2654   prev = ps_i->prev_in_row;
2655   next = ps_i->next_in_row;
2656
2657   if (ps_i == ps->rows[row])
2658     ps->rows[row] = next;
2659
2660   ps_i->next_in_row = next->next_in_row;
2661
2662   if (next->next_in_row)
2663     next->next_in_row->prev_in_row = ps_i;
2664
2665   next->next_in_row = ps_i;
2666   ps_i->prev_in_row = next;
2667
2668   next->prev_in_row = prev;
2669   if (prev)
2670     prev->next_in_row = next;
2671
2672   return true;
2673 }
2674
2675 /* Inserts a DDG_NODE to the given partial schedule at the given cycle.
2676    Returns 0 if this is not possible and a PS_INSN otherwise.  Bit N is
2677    set in MUST_PRECEDE/MUST_FOLLOW if the node with cuid N must be come
2678    before/after (respectively) the node pointed to by PS_I when scheduled
2679    in the same cycle.  */
2680 static ps_insn_ptr
2681 add_node_to_ps (partial_schedule_ptr ps, ddg_node_ptr node, int cycle,
2682                 sbitmap must_precede, sbitmap must_follow)
2683 {
2684   ps_insn_ptr ps_i;
2685   int rest_count = 1;
2686   int row = SMODULO (cycle, ps->ii);
2687
2688   if (ps->rows[row]
2689       && ps->rows[row]->row_rest_count >= issue_rate)
2690     return NULL;
2691
2692   if (ps->rows[row])
2693     rest_count += ps->rows[row]->row_rest_count;
2694
2695   ps_i = create_ps_insn (node, rest_count, cycle);
2696
2697   /* Finds and inserts PS_I according to MUST_FOLLOW and
2698      MUST_PRECEDE.  */
2699   if (! ps_insn_find_column (ps, ps_i, must_precede, must_follow))
2700     {
2701       free (ps_i);
2702       return NULL;
2703     }
2704
2705   return ps_i;
2706 }
2707
2708 /* Advance time one cycle.  Assumes DFA is being used.  */
2709 static void
2710 advance_one_cycle (void)
2711 {
2712   if (targetm.sched.dfa_pre_cycle_insn)
2713     state_transition (curr_state,
2714                       targetm.sched.dfa_pre_cycle_insn ());
2715
2716   state_transition (curr_state, NULL);
2717
2718   if (targetm.sched.dfa_post_cycle_insn)
2719     state_transition (curr_state,
2720                       targetm.sched.dfa_post_cycle_insn ());
2721 }
2722
2723
2724
2725 /* Checks if PS has resource conflicts according to DFA, starting from
2726    FROM cycle to TO cycle; returns true if there are conflicts and false
2727    if there are no conflicts.  Assumes DFA is being used.  */
2728 static int
2729 ps_has_conflicts (partial_schedule_ptr ps, int from, int to)
2730 {
2731   int cycle;
2732
2733   state_reset (curr_state);
2734
2735   for (cycle = from; cycle <= to; cycle++)
2736     {
2737       ps_insn_ptr crr_insn;
2738       /* Holds the remaining issue slots in the current row.  */
2739       int can_issue_more = issue_rate;
2740
2741       /* Walk through the DFA for the current row.  */
2742       for (crr_insn = ps->rows[SMODULO (cycle, ps->ii)];
2743            crr_insn;
2744            crr_insn = crr_insn->next_in_row)
2745         {
2746           rtx insn = crr_insn->node->insn;
2747
2748           if (!NONDEBUG_INSN_P (insn))
2749             continue;
2750
2751           /* Check if there is room for the current insn.  */
2752           if (!can_issue_more || state_dead_lock_p (curr_state))
2753             return true;
2754
2755           /* Update the DFA state and return with failure if the DFA found
2756              resource conflicts.  */
2757           if (state_transition (curr_state, insn) >= 0)
2758             return true;
2759
2760           if (targetm.sched.variable_issue)
2761             can_issue_more =
2762               targetm.sched.variable_issue (sched_dump, sched_verbose,
2763                                             insn, can_issue_more);
2764           /* A naked CLOBBER or USE generates no instruction, so don't
2765              let them consume issue slots.  */
2766           else if (GET_CODE (PATTERN (insn)) != USE
2767                    && GET_CODE (PATTERN (insn)) != CLOBBER)
2768             can_issue_more--;
2769         }
2770
2771       /* Advance the DFA to the next cycle.  */
2772       advance_one_cycle ();
2773     }
2774   return false;
2775 }
2776
2777 /* Checks if the given node causes resource conflicts when added to PS at
2778    cycle C.  If not the node is added to PS and returned; otherwise zero
2779    is returned.  Bit N is set in MUST_PRECEDE/MUST_FOLLOW if the node with
2780    cuid N must be come before/after (respectively) the node pointed to by
2781    PS_I when scheduled in the same cycle.  */
2782 ps_insn_ptr
2783 ps_add_node_check_conflicts (partial_schedule_ptr ps, ddg_node_ptr n,
2784                              int c, sbitmap must_precede,
2785                              sbitmap must_follow)
2786 {
2787   int has_conflicts = 0;
2788   ps_insn_ptr ps_i;
2789
2790   /* First add the node to the PS, if this succeeds check for
2791      conflicts, trying different issue slots in the same row.  */
2792   if (! (ps_i = add_node_to_ps (ps, n, c, must_precede, must_follow)))
2793     return NULL; /* Failed to insert the node at the given cycle.  */
2794
2795   has_conflicts = ps_has_conflicts (ps, c, c)
2796                   || (ps->history > 0
2797                       && ps_has_conflicts (ps,
2798                                            c - ps->history,
2799                                            c + ps->history));
2800
2801   /* Try different issue slots to find one that the given node can be
2802      scheduled in without conflicts.  */
2803   while (has_conflicts)
2804     {
2805       if (! ps_insn_advance_column (ps, ps_i, must_follow))
2806         break;
2807       has_conflicts = ps_has_conflicts (ps, c, c)
2808                       || (ps->history > 0
2809                           && ps_has_conflicts (ps,
2810                                                c - ps->history,
2811                                                c + ps->history));
2812     }
2813
2814   if (has_conflicts)
2815     {
2816       remove_node_from_ps (ps, ps_i);
2817       return NULL;
2818     }
2819
2820   ps->min_cycle = MIN (ps->min_cycle, c);
2821   ps->max_cycle = MAX (ps->max_cycle, c);
2822   return ps_i;
2823 }
2824
2825 /* Rotate the rows of PS such that insns scheduled at time
2826    START_CYCLE will appear in row 0.  Updates max/min_cycles.  */
2827 void
2828 rotate_partial_schedule (partial_schedule_ptr ps, int start_cycle)
2829 {
2830   int i, row, backward_rotates;
2831   int last_row = ps->ii - 1;
2832
2833   if (start_cycle == 0)
2834     return;
2835
2836   backward_rotates = SMODULO (start_cycle, ps->ii);
2837
2838   /* Revisit later and optimize this into a single loop.  */
2839   for (i = 0; i < backward_rotates; i++)
2840     {
2841       ps_insn_ptr first_row = ps->rows[0];
2842
2843       for (row = 0; row < last_row; row++)
2844         ps->rows[row] = ps->rows[row+1];
2845
2846       ps->rows[last_row] = first_row;
2847     }
2848
2849   ps->max_cycle -= start_cycle;
2850   ps->min_cycle -= start_cycle;
2851 }
2852
2853 #endif /* INSN_SCHEDULING */
2854 \f
2855 static bool
2856 gate_handle_sms (void)
2857 {
2858   return (optimize > 0 && flag_modulo_sched);
2859 }
2860
2861
2862 /* Run instruction scheduler.  */
2863 /* Perform SMS module scheduling.  */
2864 static unsigned int
2865 rest_of_handle_sms (void)
2866 {
2867 #ifdef INSN_SCHEDULING
2868   basic_block bb;
2869
2870   /* Collect loop information to be used in SMS.  */
2871   cfg_layout_initialize (0);
2872   sms_schedule ();
2873
2874   /* Update the life information, because we add pseudos.  */
2875   max_regno = max_reg_num ();
2876
2877   /* Finalize layout changes.  */
2878   FOR_EACH_BB (bb)
2879     if (bb->next_bb != EXIT_BLOCK_PTR)
2880       bb->aux = bb->next_bb;
2881   free_dominance_info (CDI_DOMINATORS);
2882   cfg_layout_finalize ();
2883 #endif /* INSN_SCHEDULING */
2884   return 0;
2885 }
2886
2887 struct rtl_opt_pass pass_sms =
2888 {
2889  {
2890   RTL_PASS,
2891   "sms",                                /* name */
2892   gate_handle_sms,                      /* gate */
2893   rest_of_handle_sms,                   /* execute */
2894   NULL,                                 /* sub */
2895   NULL,                                 /* next */
2896   0,                                    /* static_pass_number */
2897   TV_SMS,                               /* tv_id */
2898   0,                                    /* properties_required */
2899   0,                                    /* properties_provided */
2900   0,                                    /* properties_destroyed */
2901   TODO_dump_func,                       /* todo_flags_start */
2902   TODO_df_finish | TODO_verify_rtl_sharing |
2903   TODO_dump_func |
2904   TODO_ggc_collect                      /* todo_flags_finish */
2905  }
2906 };
2907