OSDN Git Service

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