OSDN Git Service

* tree-sra.c (generate_element_init): Remove any useless conversions.
[pf3gnuchains/gcc-fork.git] / gcc / haifa-sched.c
1 /* Instruction scheduling pass.
2    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3    1999, 2000, 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
4    Contributed by Michael Tiemann (tiemann@cygnus.com) Enhanced by,
5    and currently maintained by, Jim Wilson (wilson@cygnus.com)
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 2, or (at your option) any later
12 version.
13
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
17 for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING.  If not, write to the Free
21 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
22 02111-1307, USA.  */
23
24 /* Instruction scheduling pass.  This file, along with sched-deps.c,
25    contains the generic parts.  The actual entry point is found for
26    the normal instruction scheduling pass is found in sched-rgn.c.
27
28    We compute insn priorities based on data dependencies.  Flow
29    analysis only creates a fraction of the data-dependencies we must
30    observe: namely, only those dependencies which the combiner can be
31    expected to use.  For this pass, we must therefore create the
32    remaining dependencies we need to observe: register dependencies,
33    memory dependencies, dependencies to keep function calls in order,
34    and the dependence between a conditional branch and the setting of
35    condition codes are all dealt with here.
36
37    The scheduler first traverses the data flow graph, starting with
38    the last instruction, and proceeding to the first, assigning values
39    to insn_priority as it goes.  This sorts the instructions
40    topologically by data dependence.
41
42    Once priorities have been established, we order the insns using
43    list scheduling.  This works as follows: starting with a list of
44    all the ready insns, and sorted according to priority number, we
45    schedule the insn from the end of the list by placing its
46    predecessors in the list according to their priority order.  We
47    consider this insn scheduled by setting the pointer to the "end" of
48    the list to point to the previous insn.  When an insn has no
49    predecessors, we either queue it until sufficient time has elapsed
50    or add it to the ready list.  As the instructions are scheduled or
51    when stalls are introduced, the queue advances and dumps insns into
52    the ready list.  When all insns down to the lowest priority have
53    been scheduled, the critical path of the basic block has been made
54    as short as possible.  The remaining insns are then scheduled in
55    remaining slots.
56
57    Function unit conflicts are resolved during forward list scheduling
58    by tracking the time when each insn is committed to the schedule
59    and from that, the time the function units it uses must be free.
60    As insns on the ready list are considered for scheduling, those
61    that would result in a blockage of the already committed insns are
62    queued until no blockage will result.
63
64    The following list shows the order in which we want to break ties
65    among insns in the ready list:
66
67    1.  choose insn with the longest path to end of bb, ties
68    broken by
69    2.  choose insn with least contribution to register pressure,
70    ties broken by
71    3.  prefer in-block upon interblock motion, ties broken by
72    4.  prefer useful upon speculative motion, ties broken by
73    5.  choose insn with largest control flow probability, ties
74    broken by
75    6.  choose insn with the least dependences upon the previously
76    scheduled insn, or finally
77    7   choose the insn which has the most insns dependent on it.
78    8.  choose insn with lowest UID.
79
80    Memory references complicate matters.  Only if we can be certain
81    that memory references are not part of the data dependency graph
82    (via true, anti, or output dependence), can we move operations past
83    memory references.  To first approximation, reads can be done
84    independently, while writes introduce dependencies.  Better
85    approximations will yield fewer dependencies.
86
87    Before reload, an extended analysis of interblock data dependences
88    is required for interblock scheduling.  This is performed in
89    compute_block_backward_dependences ().
90
91    Dependencies set up by memory references are treated in exactly the
92    same way as other dependencies, by using LOG_LINKS backward
93    dependences.  LOG_LINKS are translated into INSN_DEPEND forward
94    dependences for the purpose of forward list scheduling.
95
96    Having optimized the critical path, we may have also unduly
97    extended the lifetimes of some registers.  If an operation requires
98    that constants be loaded into registers, it is certainly desirable
99    to load those constants as early as necessary, but no earlier.
100    I.e., it will not do to load up a bunch of registers at the
101    beginning of a basic block only to use them at the end, if they
102    could be loaded later, since this may result in excessive register
103    utilization.
104
105    Note that since branches are never in basic blocks, but only end
106    basic blocks, this pass will not move branches.  But that is ok,
107    since we can use GNU's delayed branch scheduling pass to take care
108    of this case.
109
110    Also note that no further optimizations based on algebraic
111    identities are performed, so this pass would be a good one to
112    perform instruction splitting, such as breaking up a multiply
113    instruction into shifts and adds where that is profitable.
114
115    Given the memory aliasing analysis that this pass should perform,
116    it should be possible to remove redundant stores to memory, and to
117    load values from registers instead of hitting memory.
118
119    Before reload, speculative insns are moved only if a 'proof' exists
120    that no exception will be caused by this, and if no live registers
121    exist that inhibit the motion (live registers constraints are not
122    represented by data dependence edges).
123
124    This pass must update information that subsequent passes expect to
125    be correct.  Namely: reg_n_refs, reg_n_sets, reg_n_deaths,
126    reg_n_calls_crossed, and reg_live_length.  Also, BB_HEAD, BB_END.
127
128    The information in the line number notes is carefully retained by
129    this pass.  Notes that refer to the starting and ending of
130    exception regions are also carefully retained by this pass.  All
131    other NOTE insns are grouped in their same relative order at the
132    beginning of basic blocks and regions that have been scheduled.  */
133 \f
134 #include "config.h"
135 #include "system.h"
136 #include "coretypes.h"
137 #include "tm.h"
138 #include "toplev.h"
139 #include "rtl.h"
140 #include "tm_p.h"
141 #include "hard-reg-set.h"
142 #include "basic-block.h"
143 #include "regs.h"
144 #include "function.h"
145 #include "flags.h"
146 #include "insn-config.h"
147 #include "insn-attr.h"
148 #include "except.h"
149 #include "toplev.h"
150 #include "recog.h"
151 #include "sched-int.h"
152 #include "target.h"
153
154 #ifdef INSN_SCHEDULING
155
156 /* issue_rate is the number of insns that can be scheduled in the same
157    machine cycle.  It can be defined in the config/mach/mach.h file,
158    otherwise we set it to 1.  */
159
160 static int issue_rate;
161
162 /* If the following variable value is nonzero, the scheduler inserts
163    bubbles (nop insns).  The value of variable affects on scheduler
164    behavior only if automaton pipeline interface with multipass
165    scheduling is used and hook dfa_bubble is defined.  */
166 int insert_schedule_bubbles_p = 0;
167
168 /* sched-verbose controls the amount of debugging output the
169    scheduler prints.  It is controlled by -fsched-verbose=N:
170    N>0 and no -DSR : the output is directed to stderr.
171    N>=10 will direct the printouts to stderr (regardless of -dSR).
172    N=1: same as -dSR.
173    N=2: bb's probabilities, detailed ready list info, unit/insn info.
174    N=3: rtl at abort point, control-flow, regions info.
175    N=5: dependences info.  */
176
177 static int sched_verbose_param = 0;
178 int sched_verbose = 0;
179
180 /* Debugging file.  All printouts are sent to dump, which is always set,
181    either to stderr, or to the dump listing file (-dRS).  */
182 FILE *sched_dump = 0;
183
184 /* Highest uid before scheduling.  */
185 static int old_max_uid;
186
187 /* fix_sched_param() is called from toplev.c upon detection
188    of the -fsched-verbose=N option.  */
189
190 void
191 fix_sched_param (const char *param, const char *val)
192 {
193   if (!strcmp (param, "verbose"))
194     sched_verbose_param = atoi (val);
195   else
196     warning ("fix_sched_param: unknown param: %s", param);
197 }
198
199 struct haifa_insn_data *h_i_d;
200
201 #define LINE_NOTE(INSN)         (h_i_d[INSN_UID (INSN)].line_note)
202 #define INSN_TICK(INSN)         (h_i_d[INSN_UID (INSN)].tick)
203
204 /* Vector indexed by basic block number giving the starting line-number
205    for each basic block.  */
206 static rtx *line_note_head;
207
208 /* List of important notes we must keep around.  This is a pointer to the
209    last element in the list.  */
210 static rtx note_list;
211
212 /* Queues, etc.  */
213
214 /* An instruction is ready to be scheduled when all insns preceding it
215    have already been scheduled.  It is important to ensure that all
216    insns which use its result will not be executed until its result
217    has been computed.  An insn is maintained in one of four structures:
218
219    (P) the "Pending" set of insns which cannot be scheduled until
220    their dependencies have been satisfied.
221    (Q) the "Queued" set of insns that can be scheduled when sufficient
222    time has passed.
223    (R) the "Ready" list of unscheduled, uncommitted insns.
224    (S) the "Scheduled" list of insns.
225
226    Initially, all insns are either "Pending" or "Ready" depending on
227    whether their dependencies are satisfied.
228
229    Insns move from the "Ready" list to the "Scheduled" list as they
230    are committed to the schedule.  As this occurs, the insns in the
231    "Pending" list have their dependencies satisfied and move to either
232    the "Ready" list or the "Queued" set depending on whether
233    sufficient time has passed to make them ready.  As time passes,
234    insns move from the "Queued" set to the "Ready" list.  Insns may
235    move from the "Ready" list to the "Queued" set if they are blocked
236    due to a function unit conflict.
237
238    The "Pending" list (P) are the insns in the INSN_DEPEND of the unscheduled
239    insns, i.e., those that are ready, queued, and pending.
240    The "Queued" set (Q) is implemented by the variable `insn_queue'.
241    The "Ready" list (R) is implemented by the variables `ready' and
242    `n_ready'.
243    The "Scheduled" list (S) is the new insn chain built by this pass.
244
245    The transition (R->S) is implemented in the scheduling loop in
246    `schedule_block' when the best insn to schedule is chosen.
247    The transition (R->Q) is implemented in `queue_insn' when an
248    insn is found to have a function unit conflict with the already
249    committed insns.
250    The transitions (P->R and P->Q) are implemented in `schedule_insn' as
251    insns move from the ready list to the scheduled list.
252    The transition (Q->R) is implemented in 'queue_to_insn' as time
253    passes or stalls are introduced.  */
254
255 /* Implement a circular buffer to delay instructions until sufficient
256    time has passed.  For the old pipeline description interface,
257    INSN_QUEUE_SIZE is a power of two larger than MAX_BLOCKAGE and
258    MAX_READY_COST computed by genattr.c.  For the new pipeline
259    description interface, MAX_INSN_QUEUE_INDEX is a power of two minus
260    one which is larger than maximal time of instruction execution
261    computed by genattr.c on the base maximal time of functional unit
262    reservations and getting a result.  This is the longest time an
263    insn may be queued.  */
264
265 #define MAX_INSN_QUEUE_INDEX max_insn_queue_index_macro_value
266
267 static rtx *insn_queue;
268 static int q_ptr = 0;
269 static int q_size = 0;
270 #define NEXT_Q(X) (((X)+1) & MAX_INSN_QUEUE_INDEX)
271 #define NEXT_Q_AFTER(X, C) (((X)+C) & MAX_INSN_QUEUE_INDEX)
272
273 /* The following variable defines value for macro
274    MAX_INSN_QUEUE_INDEX.  */
275 static int max_insn_queue_index_macro_value;
276
277 /* The following variable value refers for all current and future
278    reservations of the processor units.  */
279 state_t curr_state;
280
281 /* The following variable value is size of memory representing all
282    current and future reservations of the processor units.  It is used
283    only by DFA based scheduler.  */
284 static size_t dfa_state_size;
285
286 /* The following array is used to find the best insn from ready when
287    the automaton pipeline interface is used.  */
288 static char *ready_try;
289
290 /* Describe the ready list of the scheduler.
291    VEC holds space enough for all insns in the current region.  VECLEN
292    says how many exactly.
293    FIRST is the index of the element with the highest priority; i.e. the
294    last one in the ready list, since elements are ordered by ascending
295    priority.
296    N_READY determines how many insns are on the ready list.  */
297
298 struct ready_list
299 {
300   rtx *vec;
301   int veclen;
302   int first;
303   int n_ready;
304 };
305
306 static int may_trap_exp (rtx, int);
307
308 /* Nonzero iff the address is comprised from at most 1 register.  */
309 #define CONST_BASED_ADDRESS_P(x)                        \
310   (REG_P (x)                                    \
311    || ((GET_CODE (x) == PLUS || GET_CODE (x) == MINUS   \
312         || (GET_CODE (x) == LO_SUM))                    \
313        && (CONSTANT_P (XEXP (x, 0))                     \
314            || CONSTANT_P (XEXP (x, 1)))))
315
316 /* Returns a class that insn with GET_DEST(insn)=x may belong to,
317    as found by analyzing insn's expression.  */
318
319 static int
320 may_trap_exp (rtx x, int is_store)
321 {
322   enum rtx_code code;
323
324   if (x == 0)
325     return TRAP_FREE;
326   code = GET_CODE (x);
327   if (is_store)
328     {
329       if (code == MEM && may_trap_p (x))
330         return TRAP_RISKY;
331       else
332         return TRAP_FREE;
333     }
334   if (code == MEM)
335     {
336       /* The insn uses memory:  a volatile load.  */
337       if (MEM_VOLATILE_P (x))
338         return IRISKY;
339       /* An exception-free load.  */
340       if (!may_trap_p (x))
341         return IFREE;
342       /* A load with 1 base register, to be further checked.  */
343       if (CONST_BASED_ADDRESS_P (XEXP (x, 0)))
344         return PFREE_CANDIDATE;
345       /* No info on the load, to be further checked.  */
346       return PRISKY_CANDIDATE;
347     }
348   else
349     {
350       const char *fmt;
351       int i, insn_class = TRAP_FREE;
352
353       /* Neither store nor load, check if it may cause a trap.  */
354       if (may_trap_p (x))
355         return TRAP_RISKY;
356       /* Recursive step: walk the insn...  */
357       fmt = GET_RTX_FORMAT (code);
358       for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
359         {
360           if (fmt[i] == 'e')
361             {
362               int tmp_class = may_trap_exp (XEXP (x, i), is_store);
363               insn_class = WORST_CLASS (insn_class, tmp_class);
364             }
365           else if (fmt[i] == 'E')
366             {
367               int j;
368               for (j = 0; j < XVECLEN (x, i); j++)
369                 {
370                   int tmp_class = may_trap_exp (XVECEXP (x, i, j), is_store);
371                   insn_class = WORST_CLASS (insn_class, tmp_class);
372                   if (insn_class == TRAP_RISKY || insn_class == IRISKY)
373                     break;
374                 }
375             }
376           if (insn_class == TRAP_RISKY || insn_class == IRISKY)
377             break;
378         }
379       return insn_class;
380     }
381 }
382
383 /* Classifies insn for the purpose of verifying that it can be
384    moved speculatively, by examining it's patterns, returning:
385    TRAP_RISKY: store, or risky non-load insn (e.g. division by variable).
386    TRAP_FREE: non-load insn.
387    IFREE: load from a globally safe location.
388    IRISKY: volatile load.
389    PFREE_CANDIDATE, PRISKY_CANDIDATE: load that need to be checked for
390    being either PFREE or PRISKY.  */
391
392 int
393 haifa_classify_insn (rtx insn)
394 {
395   rtx pat = PATTERN (insn);
396   int tmp_class = TRAP_FREE;
397   int insn_class = TRAP_FREE;
398   enum rtx_code code;
399
400   if (GET_CODE (pat) == PARALLEL)
401     {
402       int i, len = XVECLEN (pat, 0);
403
404       for (i = len - 1; i >= 0; i--)
405         {
406           code = GET_CODE (XVECEXP (pat, 0, i));
407           switch (code)
408             {
409             case CLOBBER:
410               /* Test if it is a 'store'.  */
411               tmp_class = may_trap_exp (XEXP (XVECEXP (pat, 0, i), 0), 1);
412               break;
413             case SET:
414               /* Test if it is a store.  */
415               tmp_class = may_trap_exp (SET_DEST (XVECEXP (pat, 0, i)), 1);
416               if (tmp_class == TRAP_RISKY)
417                 break;
418               /* Test if it is a load.  */
419               tmp_class
420                 = WORST_CLASS (tmp_class,
421                                may_trap_exp (SET_SRC (XVECEXP (pat, 0, i)),
422                                              0));
423               break;
424             case COND_EXEC:
425             case TRAP_IF:
426               tmp_class = TRAP_RISKY;
427               break;
428             default:
429               ;
430             }
431           insn_class = WORST_CLASS (insn_class, tmp_class);
432           if (insn_class == TRAP_RISKY || insn_class == IRISKY)
433             break;
434         }
435     }
436   else
437     {
438       code = GET_CODE (pat);
439       switch (code)
440         {
441         case CLOBBER:
442           /* Test if it is a 'store'.  */
443           tmp_class = may_trap_exp (XEXP (pat, 0), 1);
444           break;
445         case SET:
446           /* Test if it is a store.  */
447           tmp_class = may_trap_exp (SET_DEST (pat), 1);
448           if (tmp_class == TRAP_RISKY)
449             break;
450           /* Test if it is a load.  */
451           tmp_class =
452             WORST_CLASS (tmp_class,
453                          may_trap_exp (SET_SRC (pat), 0));
454           break;
455         case COND_EXEC:
456         case TRAP_IF:
457           tmp_class = TRAP_RISKY;
458           break;
459         default:;
460         }
461       insn_class = tmp_class;
462     }
463
464   return insn_class;
465 }
466
467 /* Forward declarations.  */
468
469 /* The scheduler using only DFA description should never use the
470    following five functions:  */
471 static unsigned int blockage_range (int, rtx);
472 static void clear_units (void);
473 static void schedule_unit (int, rtx, int);
474 static int actual_hazard (int, rtx, int, int);
475 static int potential_hazard (int, rtx, int);
476
477 static int priority (rtx);
478 static int rank_for_schedule (const void *, const void *);
479 static void swap_sort (rtx *, int);
480 static void queue_insn (rtx, int);
481 static int schedule_insn (rtx, struct ready_list *, int);
482 static int find_set_reg_weight (rtx);
483 static void find_insn_reg_weight (int);
484 static void adjust_priority (rtx);
485 static void advance_one_cycle (void);
486
487 /* Notes handling mechanism:
488    =========================
489    Generally, NOTES are saved before scheduling and restored after scheduling.
490    The scheduler distinguishes between three types of notes:
491
492    (1) LINE_NUMBER notes, generated and used for debugging.  Here,
493    before scheduling a region, a pointer to the LINE_NUMBER note is
494    added to the insn following it (in save_line_notes()), and the note
495    is removed (in rm_line_notes() and unlink_line_notes()).  After
496    scheduling the region, this pointer is used for regeneration of
497    the LINE_NUMBER note (in restore_line_notes()).
498
499    (2) LOOP_BEGIN, LOOP_END, SETJMP, EHREGION_BEG, EHREGION_END notes:
500    Before scheduling a region, a pointer to the note is added to the insn
501    that follows or precedes it.  (This happens as part of the data dependence
502    computation).  After scheduling an insn, the pointer contained in it is
503    used for regenerating the corresponding note (in reemit_notes).
504
505    (3) All other notes (e.g. INSN_DELETED):  Before scheduling a block,
506    these notes are put in a list (in rm_other_notes() and
507    unlink_other_notes ()).  After scheduling the block, these notes are
508    inserted at the beginning of the block (in schedule_block()).  */
509
510 static rtx unlink_other_notes (rtx, rtx);
511 static rtx unlink_line_notes (rtx, rtx);
512 static rtx reemit_notes (rtx, rtx);
513
514 static rtx *ready_lastpos (struct ready_list *);
515 static void ready_sort (struct ready_list *);
516 static rtx ready_remove_first (struct ready_list *);
517
518 static void queue_to_ready (struct ready_list *);
519 static int early_queue_to_ready (state_t, struct ready_list *);
520
521 static void debug_ready_list (struct ready_list *);
522
523 static rtx move_insn1 (rtx, rtx);
524 static rtx move_insn (rtx, rtx);
525
526 /* The following functions are used to implement multi-pass scheduling
527    on the first cycle.  It is used only for DFA based scheduler.  */
528 static rtx ready_element (struct ready_list *, int);
529 static rtx ready_remove (struct ready_list *, int);
530 static int max_issue (struct ready_list *, int *);
531
532 static rtx choose_ready (struct ready_list *);
533
534 #endif /* INSN_SCHEDULING */
535 \f
536 /* Point to state used for the current scheduling pass.  */
537 struct sched_info *current_sched_info;
538 \f
539 #ifndef INSN_SCHEDULING
540 void
541 schedule_insns (FILE *dump_file ATTRIBUTE_UNUSED)
542 {
543 }
544 #else
545
546 /* Pointer to the last instruction scheduled.  Used by rank_for_schedule,
547    so that insns independent of the last scheduled insn will be preferred
548    over dependent instructions.  */
549
550 static rtx last_scheduled_insn;
551
552 /* Compute the function units used by INSN.  This caches the value
553    returned by function_units_used.  A function unit is encoded as the
554    unit number if the value is non-negative and the complement of a
555    mask if the value is negative.  A function unit index is the
556    non-negative encoding.  The scheduler using only DFA description
557    should never use the following function.  */
558
559 HAIFA_INLINE int
560 insn_unit (rtx insn)
561 {
562   int unit = INSN_UNIT (insn);
563
564   if (unit == 0)
565     {
566       recog_memoized (insn);
567
568       /* A USE insn, or something else we don't need to understand.
569          We can't pass these directly to function_units_used because it will
570          trigger a fatal error for unrecognizable insns.  */
571       if (INSN_CODE (insn) < 0)
572         unit = -1;
573       else
574         {
575           unit = function_units_used (insn);
576           /* Increment non-negative values so we can cache zero.  */
577           if (unit >= 0)
578             unit++;
579         }
580       /* We only cache 16 bits of the result, so if the value is out of
581          range, don't cache it.  */
582       if (FUNCTION_UNITS_SIZE < HOST_BITS_PER_SHORT
583           || unit >= 0
584           || (unit & ~((1 << (HOST_BITS_PER_SHORT - 1)) - 1)) == 0)
585         INSN_UNIT (insn) = unit;
586     }
587   return (unit > 0 ? unit - 1 : unit);
588 }
589
590 /* Compute the blockage range for executing INSN on UNIT.  This caches
591    the value returned by the blockage_range_function for the unit.
592    These values are encoded in an int where the upper half gives the
593    minimum value and the lower half gives the maximum value.  The
594    scheduler using only DFA description should never use the following
595    function.  */
596
597 HAIFA_INLINE static unsigned int
598 blockage_range (int unit, rtx insn)
599 {
600   unsigned int blockage = INSN_BLOCKAGE (insn);
601   unsigned int range;
602
603   if ((int) UNIT_BLOCKED (blockage) != unit + 1)
604     {
605       range = function_units[unit].blockage_range_function (insn);
606       /* We only cache the blockage range for one unit and then only if
607          the values fit.  */
608       if (HOST_BITS_PER_INT >= UNIT_BITS + 2 * BLOCKAGE_BITS)
609         INSN_BLOCKAGE (insn) = ENCODE_BLOCKAGE (unit + 1, range);
610     }
611   else
612     range = BLOCKAGE_RANGE (blockage);
613
614   return range;
615 }
616
617 /* A vector indexed by function unit instance giving the last insn to
618    use the unit.  The value of the function unit instance index for
619    unit U instance I is (U + I * FUNCTION_UNITS_SIZE).  The scheduler
620    using only DFA description should never use the following variable.  */
621 #if FUNCTION_UNITS_SIZE
622 static rtx unit_last_insn[FUNCTION_UNITS_SIZE * MAX_MULTIPLICITY];
623 #else
624 static rtx unit_last_insn[1];
625 #endif
626
627 /* A vector indexed by function unit instance giving the minimum time
628    when the unit will unblock based on the maximum blockage cost.  The
629    scheduler using only DFA description should never use the following
630    variable.  */
631 #if FUNCTION_UNITS_SIZE
632 static int unit_tick[FUNCTION_UNITS_SIZE * MAX_MULTIPLICITY];
633 #else
634 static int unit_tick[1];
635 #endif
636
637 /* A vector indexed by function unit number giving the number of insns
638    that remain to use the unit.  The scheduler using only DFA
639    description should never use the following variable.  */
640 #if FUNCTION_UNITS_SIZE
641 static int unit_n_insns[FUNCTION_UNITS_SIZE];
642 #else
643 static int unit_n_insns[1];
644 #endif
645
646 /* Access the unit_last_insn array.  Used by the visualization code.
647    The scheduler using only DFA description should never use the
648    following function.  */
649
650 rtx
651 get_unit_last_insn (int instance)
652 {
653   return unit_last_insn[instance];
654 }
655
656 /* Reset the function unit state to the null state.  */
657
658 static void
659 clear_units (void)
660 {
661   memset (unit_last_insn, 0, sizeof (unit_last_insn));
662   memset (unit_tick, 0, sizeof (unit_tick));
663   memset (unit_n_insns, 0, sizeof (unit_n_insns));
664 }
665
666 /* Return the issue-delay of an insn.  The scheduler using only DFA
667    description should never use the following function.  */
668
669 HAIFA_INLINE int
670 insn_issue_delay (rtx insn)
671 {
672   int i, delay = 0;
673   int unit = insn_unit (insn);
674
675   /* Efficiency note: in fact, we are working 'hard' to compute a
676      value that was available in md file, and is not available in
677      function_units[] structure.  It would be nice to have this
678      value there, too.  */
679   if (unit >= 0)
680     {
681       if (function_units[unit].blockage_range_function &&
682           function_units[unit].blockage_function)
683         delay = function_units[unit].blockage_function (insn, insn);
684     }
685   else
686     for (i = 0, unit = ~unit; unit; i++, unit >>= 1)
687       if ((unit & 1) != 0 && function_units[i].blockage_range_function
688           && function_units[i].blockage_function)
689         delay = MAX (delay, function_units[i].blockage_function (insn, insn));
690
691   return delay;
692 }
693
694 /* Return the actual hazard cost of executing INSN on the unit UNIT,
695    instance INSTANCE at time CLOCK if the previous actual hazard cost
696    was COST.  The scheduler using only DFA description should never
697    use the following function.  */
698
699 HAIFA_INLINE int
700 actual_hazard_this_instance (int unit, int instance, rtx insn, int clock, int cost)
701 {
702   int tick = unit_tick[instance]; /* Issue time of the last issued insn.  */
703
704   if (tick - clock > cost)
705     {
706       /* The scheduler is operating forward, so unit's last insn is the
707          executing insn and INSN is the candidate insn.  We want a
708          more exact measure of the blockage if we execute INSN at CLOCK
709          given when we committed the execution of the unit's last insn.
710
711          The blockage value is given by either the unit's max blockage
712          constant, blockage range function, or blockage function.  Use
713          the most exact form for the given unit.  */
714
715       if (function_units[unit].blockage_range_function)
716         {
717           if (function_units[unit].blockage_function)
718             tick += (function_units[unit].blockage_function
719                      (unit_last_insn[instance], insn)
720                      - function_units[unit].max_blockage);
721           else
722             tick += ((int) MAX_BLOCKAGE_COST (blockage_range (unit, insn))
723                      - function_units[unit].max_blockage);
724         }
725       if (tick - clock > cost)
726         cost = tick - clock;
727     }
728   return cost;
729 }
730
731 /* Record INSN as having begun execution on the units encoded by UNIT
732    at time CLOCK.  The scheduler using only DFA description should
733    never use the following function.  */
734
735 static void
736 schedule_unit (int unit, rtx insn, int clock)
737 {
738   int i;
739
740   if (unit >= 0)
741     {
742       int instance = unit;
743 #if MAX_MULTIPLICITY > 1
744       /* Find the first free instance of the function unit and use that
745          one.  We assume that one is free.  */
746       for (i = function_units[unit].multiplicity - 1; i > 0; i--)
747         {
748           if (!actual_hazard_this_instance (unit, instance, insn, clock, 0))
749             break;
750           instance += FUNCTION_UNITS_SIZE;
751         }
752 #endif
753       unit_last_insn[instance] = insn;
754       unit_tick[instance] = (clock + function_units[unit].max_blockage);
755     }
756   else
757     for (i = 0, unit = ~unit; unit; i++, unit >>= 1)
758       if ((unit & 1) != 0)
759         schedule_unit (i, insn, clock);
760 }
761
762 /* Return the actual hazard cost of executing INSN on the units
763    encoded by UNIT at time CLOCK if the previous actual hazard cost
764    was COST.  The scheduler using only DFA description should never
765    use the following function.  */
766
767 static int
768 actual_hazard (int unit, rtx insn, int clock, int cost)
769 {
770   int i;
771
772   if (unit >= 0)
773     {
774       /* Find the instance of the function unit with the minimum hazard.  */
775       int instance = unit;
776       int best_cost = actual_hazard_this_instance (unit, instance, insn,
777                                                    clock, cost);
778 #if MAX_MULTIPLICITY > 1
779       int this_cost;
780
781       if (best_cost > cost)
782         {
783           for (i = function_units[unit].multiplicity - 1; i > 0; i--)
784             {
785               instance += FUNCTION_UNITS_SIZE;
786               this_cost = actual_hazard_this_instance (unit, instance, insn,
787                                                        clock, cost);
788               if (this_cost < best_cost)
789                 {
790                   best_cost = this_cost;
791                   if (this_cost <= cost)
792                     break;
793                 }
794             }
795         }
796 #endif
797       cost = MAX (cost, best_cost);
798     }
799   else
800     for (i = 0, unit = ~unit; unit; i++, unit >>= 1)
801       if ((unit & 1) != 0)
802         cost = actual_hazard (i, insn, clock, cost);
803
804   return cost;
805 }
806
807 /* Return the potential hazard cost of executing an instruction on the
808    units encoded by UNIT if the previous potential hazard cost was
809    COST.  An insn with a large blockage time is chosen in preference
810    to one with a smaller time; an insn that uses a unit that is more
811    likely to be used is chosen in preference to one with a unit that
812    is less used.  We are trying to minimize a subsequent actual
813    hazard.  The scheduler using only DFA description should never use
814    the following function.  */
815
816 HAIFA_INLINE static int
817 potential_hazard (int unit, rtx insn, int cost)
818 {
819   int i, ncost;
820   unsigned int minb, maxb;
821
822   if (unit >= 0)
823     {
824       minb = maxb = function_units[unit].max_blockage;
825       if (maxb > 1)
826         {
827           if (function_units[unit].blockage_range_function)
828             {
829               maxb = minb = blockage_range (unit, insn);
830               maxb = MAX_BLOCKAGE_COST (maxb);
831               minb = MIN_BLOCKAGE_COST (minb);
832             }
833
834           if (maxb > 1)
835             {
836               /* Make the number of instructions left dominate.  Make the
837                  minimum delay dominate the maximum delay.  If all these
838                  are the same, use the unit number to add an arbitrary
839                  ordering.  Other terms can be added.  */
840               ncost = minb * 0x40 + maxb;
841               ncost *= (unit_n_insns[unit] - 1) * 0x1000 + unit;
842               if (ncost > cost)
843                 cost = ncost;
844             }
845         }
846     }
847   else
848     for (i = 0, unit = ~unit; unit; i++, unit >>= 1)
849       if ((unit & 1) != 0)
850         cost = potential_hazard (i, insn, cost);
851
852   return cost;
853 }
854
855 /* Compute cost of executing INSN given the dependence LINK on the insn USED.
856    This is the number of cycles between instruction issue and
857    instruction results.  */
858
859 HAIFA_INLINE int
860 insn_cost (rtx insn, rtx link, rtx used)
861 {
862   int cost = INSN_COST (insn);
863
864   if (cost < 0)
865     {
866       /* A USE insn, or something else we don't need to
867          understand.  We can't pass these directly to
868          result_ready_cost or insn_default_latency because it will
869          trigger a fatal error for unrecognizable insns.  */
870       if (recog_memoized (insn) < 0)
871         {
872           INSN_COST (insn) = 0;
873           return 0;
874         }
875       else
876         {
877           if (targetm.sched.use_dfa_pipeline_interface
878               && targetm.sched.use_dfa_pipeline_interface ())
879             cost = insn_default_latency (insn);
880           else
881             cost = result_ready_cost (insn);
882
883           if (cost < 0)
884             cost = 0;
885
886           INSN_COST (insn) = cost;
887         }
888     }
889
890   /* In this case estimate cost without caring how insn is used.  */
891   if (link == 0 || used == 0)
892     return cost;
893
894   /* A USE insn should never require the value used to be computed.
895      This allows the computation of a function's result and parameter
896      values to overlap the return and call.  */
897   if (recog_memoized (used) < 0)
898     cost = 0;
899   else
900     {
901       if (targetm.sched.use_dfa_pipeline_interface
902           && targetm.sched.use_dfa_pipeline_interface ())
903         {
904           if (INSN_CODE (insn) >= 0)
905             {
906               if (REG_NOTE_KIND (link) == REG_DEP_ANTI)
907                 cost = 0;
908               else if (REG_NOTE_KIND (link) == REG_DEP_OUTPUT)
909                 {
910                   cost = (insn_default_latency (insn)
911                           - insn_default_latency (used));
912                   if (cost <= 0)
913                     cost = 1;
914                 }
915               else if (bypass_p (insn))
916                 cost = insn_latency (insn, used);
917             }
918         }
919
920       if (targetm.sched.adjust_cost)
921         cost = targetm.sched.adjust_cost (used, link, insn, cost);
922
923       if (cost < 0)
924         cost = 0;
925     }
926
927   return cost;
928 }
929
930 /* Compute the priority number for INSN.  */
931
932 static int
933 priority (rtx insn)
934 {
935   rtx link;
936
937   if (! INSN_P (insn))
938     return 0;
939
940   if (! INSN_PRIORITY_KNOWN (insn))
941     {
942       int this_priority = 0;
943
944       if (INSN_DEPEND (insn) == 0)
945         this_priority = insn_cost (insn, 0, 0);
946       else
947         {
948           for (link = INSN_DEPEND (insn); link; link = XEXP (link, 1))
949             {
950               rtx next;
951               int next_priority;
952
953               next = XEXP (link, 0);
954
955               /* Critical path is meaningful in block boundaries only.  */
956               if (! (*current_sched_info->contributes_to_priority) (next, insn))
957                 continue;
958
959               next_priority = insn_cost (insn, link, next) + priority (next);
960               if (next_priority > this_priority)
961                 this_priority = next_priority;
962             }
963         }
964       INSN_PRIORITY (insn) = this_priority;
965       INSN_PRIORITY_KNOWN (insn) = 1;
966     }
967
968   return INSN_PRIORITY (insn);
969 }
970 \f
971 /* Macros and functions for keeping the priority queue sorted, and
972    dealing with queuing and dequeuing of instructions.  */
973
974 #define SCHED_SORT(READY, N_READY)                                   \
975 do { if ((N_READY) == 2)                                             \
976        swap_sort (READY, N_READY);                                   \
977      else if ((N_READY) > 2)                                         \
978          qsort (READY, N_READY, sizeof (rtx), rank_for_schedule); }  \
979 while (0)
980
981 /* Returns a positive value if x is preferred; returns a negative value if
982    y is preferred.  Should never return 0, since that will make the sort
983    unstable.  */
984
985 static int
986 rank_for_schedule (const void *x, const void *y)
987 {
988   rtx tmp = *(const rtx *) y;
989   rtx tmp2 = *(const rtx *) x;
990   rtx link;
991   int tmp_class, tmp2_class, depend_count1, depend_count2;
992   int val, priority_val, weight_val, info_val;
993
994   /* The insn in a schedule group should be issued the first.  */
995   if (SCHED_GROUP_P (tmp) != SCHED_GROUP_P (tmp2))
996     return SCHED_GROUP_P (tmp2) ? 1 : -1;
997
998   /* Prefer insn with higher priority.  */
999   priority_val = INSN_PRIORITY (tmp2) - INSN_PRIORITY (tmp);
1000
1001   if (priority_val)
1002     return priority_val;
1003
1004   /* Prefer an insn with smaller contribution to registers-pressure.  */
1005   if (!reload_completed &&
1006       (weight_val = INSN_REG_WEIGHT (tmp) - INSN_REG_WEIGHT (tmp2)))
1007     return weight_val;
1008
1009   info_val = (*current_sched_info->rank) (tmp, tmp2);
1010   if (info_val)
1011     return info_val;
1012
1013   /* Compare insns based on their relation to the last-scheduled-insn.  */
1014   if (last_scheduled_insn)
1015     {
1016       /* Classify the instructions into three classes:
1017          1) Data dependent on last schedule insn.
1018          2) Anti/Output dependent on last scheduled insn.
1019          3) Independent of last scheduled insn, or has latency of one.
1020          Choose the insn from the highest numbered class if different.  */
1021       link = find_insn_list (tmp, INSN_DEPEND (last_scheduled_insn));
1022       if (link == 0 || insn_cost (last_scheduled_insn, link, tmp) == 1)
1023         tmp_class = 3;
1024       else if (REG_NOTE_KIND (link) == 0)       /* Data dependence.  */
1025         tmp_class = 1;
1026       else
1027         tmp_class = 2;
1028
1029       link = find_insn_list (tmp2, INSN_DEPEND (last_scheduled_insn));
1030       if (link == 0 || insn_cost (last_scheduled_insn, link, tmp2) == 1)
1031         tmp2_class = 3;
1032       else if (REG_NOTE_KIND (link) == 0)       /* Data dependence.  */
1033         tmp2_class = 1;
1034       else
1035         tmp2_class = 2;
1036
1037       if ((val = tmp2_class - tmp_class))
1038         return val;
1039     }
1040
1041   /* Prefer the insn which has more later insns that depend on it.
1042      This gives the scheduler more freedom when scheduling later
1043      instructions at the expense of added register pressure.  */
1044   depend_count1 = 0;
1045   for (link = INSN_DEPEND (tmp); link; link = XEXP (link, 1))
1046     depend_count1++;
1047
1048   depend_count2 = 0;
1049   for (link = INSN_DEPEND (tmp2); link; link = XEXP (link, 1))
1050     depend_count2++;
1051
1052   val = depend_count2 - depend_count1;
1053   if (val)
1054     return val;
1055
1056   /* If insns are equally good, sort by INSN_LUID (original insn order),
1057      so that we make the sort stable.  This minimizes instruction movement,
1058      thus minimizing sched's effect on debugging and cross-jumping.  */
1059   return INSN_LUID (tmp) - INSN_LUID (tmp2);
1060 }
1061
1062 /* Resort the array A in which only element at index N may be out of order.  */
1063
1064 HAIFA_INLINE static void
1065 swap_sort (rtx *a, int n)
1066 {
1067   rtx insn = a[n - 1];
1068   int i = n - 2;
1069
1070   while (i >= 0 && rank_for_schedule (a + i, &insn) >= 0)
1071     {
1072       a[i + 1] = a[i];
1073       i -= 1;
1074     }
1075   a[i + 1] = insn;
1076 }
1077
1078 /* Add INSN to the insn queue so that it can be executed at least
1079    N_CYCLES after the currently executing insn.  Preserve insns
1080    chain for debugging purposes.  */
1081
1082 HAIFA_INLINE static void
1083 queue_insn (rtx insn, int n_cycles)
1084 {
1085   int next_q = NEXT_Q_AFTER (q_ptr, n_cycles);
1086   rtx link = alloc_INSN_LIST (insn, insn_queue[next_q]);
1087   insn_queue[next_q] = link;
1088   q_size += 1;
1089
1090   if (sched_verbose >= 2)
1091     {
1092       fprintf (sched_dump, ";;\t\tReady-->Q: insn %s: ",
1093                (*current_sched_info->print_insn) (insn, 0));
1094
1095       fprintf (sched_dump, "queued for %d cycles.\n", n_cycles);
1096     }
1097 }
1098
1099 /* Return a pointer to the bottom of the ready list, i.e. the insn
1100    with the lowest priority.  */
1101
1102 HAIFA_INLINE static rtx *
1103 ready_lastpos (struct ready_list *ready)
1104 {
1105   if (ready->n_ready == 0)
1106     abort ();
1107   return ready->vec + ready->first - ready->n_ready + 1;
1108 }
1109
1110 /* Add an element INSN to the ready list so that it ends up with the lowest
1111    priority.  */
1112
1113 HAIFA_INLINE void
1114 ready_add (struct ready_list *ready, rtx insn)
1115 {
1116   if (ready->first == ready->n_ready)
1117     {
1118       memmove (ready->vec + ready->veclen - ready->n_ready,
1119                ready_lastpos (ready),
1120                ready->n_ready * sizeof (rtx));
1121       ready->first = ready->veclen - 1;
1122     }
1123   ready->vec[ready->first - ready->n_ready] = insn;
1124   ready->n_ready++;
1125 }
1126
1127 /* Remove the element with the highest priority from the ready list and
1128    return it.  */
1129
1130 HAIFA_INLINE static rtx
1131 ready_remove_first (struct ready_list *ready)
1132 {
1133   rtx t;
1134   if (ready->n_ready == 0)
1135     abort ();
1136   t = ready->vec[ready->first--];
1137   ready->n_ready--;
1138   /* If the queue becomes empty, reset it.  */
1139   if (ready->n_ready == 0)
1140     ready->first = ready->veclen - 1;
1141   return t;
1142 }
1143
1144 /* The following code implements multi-pass scheduling for the first
1145    cycle.  In other words, we will try to choose ready insn which
1146    permits to start maximum number of insns on the same cycle.  */
1147
1148 /* Return a pointer to the element INDEX from the ready.  INDEX for
1149    insn with the highest priority is 0, and the lowest priority has
1150    N_READY - 1.  */
1151
1152 HAIFA_INLINE static rtx
1153 ready_element (struct ready_list *ready, int index)
1154 {
1155 #ifdef ENABLE_CHECKING
1156   if (ready->n_ready == 0 || index >= ready->n_ready)
1157     abort ();
1158 #endif
1159   return ready->vec[ready->first - index];
1160 }
1161
1162 /* Remove the element INDEX from the ready list and return it.  INDEX
1163    for insn with the highest priority is 0, and the lowest priority
1164    has N_READY - 1.  */
1165
1166 HAIFA_INLINE static rtx
1167 ready_remove (struct ready_list *ready, int index)
1168 {
1169   rtx t;
1170   int i;
1171
1172   if (index == 0)
1173     return ready_remove_first (ready);
1174   if (ready->n_ready == 0 || index >= ready->n_ready)
1175     abort ();
1176   t = ready->vec[ready->first - index];
1177   ready->n_ready--;
1178   for (i = index; i < ready->n_ready; i++)
1179     ready->vec[ready->first - i] = ready->vec[ready->first - i - 1];
1180   return t;
1181 }
1182
1183
1184 /* Sort the ready list READY by ascending priority, using the SCHED_SORT
1185    macro.  */
1186
1187 HAIFA_INLINE static void
1188 ready_sort (struct ready_list *ready)
1189 {
1190   rtx *first = ready_lastpos (ready);
1191   SCHED_SORT (first, ready->n_ready);
1192 }
1193
1194 /* PREV is an insn that is ready to execute.  Adjust its priority if that
1195    will help shorten or lengthen register lifetimes as appropriate.  Also
1196    provide a hook for the target to tweek itself.  */
1197
1198 HAIFA_INLINE static void
1199 adjust_priority (rtx prev)
1200 {
1201   /* ??? There used to be code here to try and estimate how an insn
1202      affected register lifetimes, but it did it by looking at REG_DEAD
1203      notes, which we removed in schedule_region.  Nor did it try to
1204      take into account register pressure or anything useful like that.
1205
1206      Revisit when we have a machine model to work with and not before.  */
1207
1208   if (targetm.sched.adjust_priority)
1209     INSN_PRIORITY (prev) =
1210       targetm.sched.adjust_priority (prev, INSN_PRIORITY (prev));
1211 }
1212
1213 /* Advance time on one cycle.  */
1214 HAIFA_INLINE static void
1215 advance_one_cycle (void)
1216 {
1217   if (targetm.sched.use_dfa_pipeline_interface
1218       && targetm.sched.use_dfa_pipeline_interface ())
1219     {
1220       if (targetm.sched.dfa_pre_cycle_insn)
1221         state_transition (curr_state,
1222                           targetm.sched.dfa_pre_cycle_insn ());
1223
1224       state_transition (curr_state, NULL);
1225
1226       if (targetm.sched.dfa_post_cycle_insn)
1227         state_transition (curr_state,
1228                           targetm.sched.dfa_post_cycle_insn ());
1229     }
1230 }
1231
1232 /* Clock at which the previous instruction was issued.  */
1233 static int last_clock_var;
1234
1235 /* INSN is the "currently executing insn".  Launch each insn which was
1236    waiting on INSN.  READY is the ready list which contains the insns
1237    that are ready to fire.  CLOCK is the current cycle.  The function
1238    returns necessary cycle advance after issuing the insn (it is not
1239    zero for insns in a schedule group).  */
1240
1241 static int
1242 schedule_insn (rtx insn, struct ready_list *ready, int clock)
1243 {
1244   rtx link;
1245   int advance = 0;
1246   int unit = 0;
1247   int premature_issue = 0;
1248
1249   if (!targetm.sched.use_dfa_pipeline_interface
1250       || !targetm.sched.use_dfa_pipeline_interface ())
1251     unit = insn_unit (insn);
1252
1253   if (targetm.sched.use_dfa_pipeline_interface
1254       && targetm.sched.use_dfa_pipeline_interface ()
1255       && sched_verbose >= 1)
1256     {
1257       char buf[2048];
1258
1259       print_insn (buf, insn, 0);
1260       buf[40] = 0;
1261       fprintf (sched_dump, ";;\t%3i--> %-40s:", clock, buf);
1262
1263       if (recog_memoized (insn) < 0)
1264         fprintf (sched_dump, "nothing");
1265       else
1266         print_reservation (sched_dump, insn);
1267       fputc ('\n', sched_dump);
1268     }
1269   else if (sched_verbose >= 2)
1270     {
1271       fprintf (sched_dump, ";;\t\t--> scheduling insn <<<%d>>> on unit ",
1272                INSN_UID (insn));
1273       insn_print_units (insn);
1274       fputc ('\n', sched_dump);
1275     }
1276
1277   if (!targetm.sched.use_dfa_pipeline_interface
1278       || !targetm.sched.use_dfa_pipeline_interface ())
1279     {
1280       if (sched_verbose && unit == -1)
1281         visualize_no_unit (insn);
1282
1283
1284       if (MAX_BLOCKAGE > 1 || issue_rate > 1 || sched_verbose)
1285         schedule_unit (unit, insn, clock);
1286
1287       if (INSN_DEPEND (insn) == 0)
1288         return 0;
1289     }
1290
1291   if (INSN_TICK (insn) > clock)
1292     {
1293       /* 'insn' has been prematurely moved from the queue to the
1294          ready list.  */
1295       premature_issue = INSN_TICK (insn) - clock;
1296     }
1297
1298   for (link = INSN_DEPEND (insn); link != 0; link = XEXP (link, 1))
1299     {
1300       rtx next = XEXP (link, 0);
1301       int cost = insn_cost (insn, link, next);
1302
1303       INSN_TICK (next) = MAX (INSN_TICK (next), clock + cost + premature_issue);
1304
1305       if ((INSN_DEP_COUNT (next) -= 1) == 0)
1306         {
1307           int effective_cost = INSN_TICK (next) - clock;
1308
1309           if (! (*current_sched_info->new_ready) (next))
1310             continue;
1311
1312           if (sched_verbose >= 2)
1313             {
1314               fprintf (sched_dump, ";;\t\tdependences resolved: insn %s ",
1315                        (*current_sched_info->print_insn) (next, 0));
1316
1317               if (effective_cost < 1)
1318                 fprintf (sched_dump, "into ready\n");
1319               else
1320                 fprintf (sched_dump, "into queue with cost=%d\n",
1321                          effective_cost);
1322             }
1323
1324           /* Adjust the priority of NEXT and either put it on the ready
1325              list or queue it.  */
1326           adjust_priority (next);
1327           if (effective_cost < 1)
1328             ready_add (ready, next);
1329           else
1330             {
1331               queue_insn (next, effective_cost);
1332
1333               if (SCHED_GROUP_P (next) && advance < effective_cost)
1334                 advance = effective_cost;
1335             }
1336         }
1337     }
1338
1339   /* Annotate the instruction with issue information -- TImode
1340      indicates that the instruction is expected not to be able
1341      to issue on the same cycle as the previous insn.  A machine
1342      may use this information to decide how the instruction should
1343      be aligned.  */
1344   if (issue_rate > 1
1345       && GET_CODE (PATTERN (insn)) != USE
1346       && GET_CODE (PATTERN (insn)) != CLOBBER)
1347     {
1348       if (reload_completed)
1349         PUT_MODE (insn, clock > last_clock_var ? TImode : VOIDmode);
1350       last_clock_var = clock;
1351     }
1352   return advance;
1353 }
1354
1355 /* Functions for handling of notes.  */
1356
1357 /* Delete notes beginning with INSN and put them in the chain
1358    of notes ended by NOTE_LIST.
1359    Returns the insn following the notes.  */
1360
1361 static rtx
1362 unlink_other_notes (rtx insn, rtx tail)
1363 {
1364   rtx prev = PREV_INSN (insn);
1365
1366   while (insn != tail && GET_CODE (insn) == NOTE)
1367     {
1368       rtx next = NEXT_INSN (insn);
1369       /* Delete the note from its current position.  */
1370       if (prev)
1371         NEXT_INSN (prev) = next;
1372       if (next)
1373         PREV_INSN (next) = prev;
1374
1375       /* See sched_analyze to see how these are handled.  */
1376       if (NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_BEG
1377           && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_END
1378           && NOTE_LINE_NUMBER (insn) != NOTE_INSN_BASIC_BLOCK
1379           && NOTE_LINE_NUMBER (insn) != NOTE_INSN_EH_REGION_BEG
1380           && NOTE_LINE_NUMBER (insn) != NOTE_INSN_EH_REGION_END)
1381         {
1382           /* Insert the note at the end of the notes list.  */
1383           PREV_INSN (insn) = note_list;
1384           if (note_list)
1385             NEXT_INSN (note_list) = insn;
1386           note_list = insn;
1387         }
1388
1389       insn = next;
1390     }
1391   return insn;
1392 }
1393
1394 /* Delete line notes beginning with INSN. Record line-number notes so
1395    they can be reused.  Returns the insn following the notes.  */
1396
1397 static rtx
1398 unlink_line_notes (rtx insn, rtx tail)
1399 {
1400   rtx prev = PREV_INSN (insn);
1401
1402   while (insn != tail && GET_CODE (insn) == NOTE)
1403     {
1404       rtx next = NEXT_INSN (insn);
1405
1406       if (write_symbols != NO_DEBUG && NOTE_LINE_NUMBER (insn) > 0)
1407         {
1408           /* Delete the note from its current position.  */
1409           if (prev)
1410             NEXT_INSN (prev) = next;
1411           if (next)
1412             PREV_INSN (next) = prev;
1413
1414           /* Record line-number notes so they can be reused.  */
1415           LINE_NOTE (insn) = insn;
1416         }
1417       else
1418         prev = insn;
1419
1420       insn = next;
1421     }
1422   return insn;
1423 }
1424
1425 /* Return the head and tail pointers of BB.  */
1426
1427 void
1428 get_block_head_tail (int b, rtx *headp, rtx *tailp)
1429 {
1430   /* HEAD and TAIL delimit the basic block being scheduled.  */
1431   rtx head = BB_HEAD (BASIC_BLOCK (b));
1432   rtx tail = BB_END (BASIC_BLOCK (b));
1433
1434   /* Don't include any notes or labels at the beginning of the
1435      basic block, or notes at the ends of basic blocks.  */
1436   while (head != tail)
1437     {
1438       if (GET_CODE (head) == NOTE)
1439         head = NEXT_INSN (head);
1440       else if (GET_CODE (tail) == NOTE)
1441         tail = PREV_INSN (tail);
1442       else if (GET_CODE (head) == CODE_LABEL)
1443         head = NEXT_INSN (head);
1444       else
1445         break;
1446     }
1447
1448   *headp = head;
1449   *tailp = tail;
1450 }
1451
1452 /* Return nonzero if there are no real insns in the range [ HEAD, TAIL ].  */
1453
1454 int
1455 no_real_insns_p (rtx head, rtx tail)
1456 {
1457   while (head != NEXT_INSN (tail))
1458     {
1459       if (GET_CODE (head) != NOTE && GET_CODE (head) != CODE_LABEL)
1460         return 0;
1461       head = NEXT_INSN (head);
1462     }
1463   return 1;
1464 }
1465
1466 /* Delete line notes from one block. Save them so they can be later restored
1467    (in restore_line_notes).  HEAD and TAIL are the boundaries of the
1468    block in which notes should be processed.  */
1469
1470 void
1471 rm_line_notes (rtx head, rtx tail)
1472 {
1473   rtx next_tail;
1474   rtx insn;
1475
1476   next_tail = NEXT_INSN (tail);
1477   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
1478     {
1479       rtx prev;
1480
1481       /* Farm out notes, and maybe save them in NOTE_LIST.
1482          This is needed to keep the debugger from
1483          getting completely deranged.  */
1484       if (GET_CODE (insn) == NOTE)
1485         {
1486           prev = insn;
1487           insn = unlink_line_notes (insn, next_tail);
1488
1489           if (prev == tail)
1490             abort ();
1491           if (prev == head)
1492             abort ();
1493           if (insn == next_tail)
1494             abort ();
1495         }
1496     }
1497 }
1498
1499 /* Save line number notes for each insn in block B.  HEAD and TAIL are
1500    the boundaries of the block in which notes should be processed.  */
1501
1502 void
1503 save_line_notes (int b, rtx head, rtx tail)
1504 {
1505   rtx next_tail;
1506
1507   /* We must use the true line number for the first insn in the block
1508      that was computed and saved at the start of this pass.  We can't
1509      use the current line number, because scheduling of the previous
1510      block may have changed the current line number.  */
1511
1512   rtx line = line_note_head[b];
1513   rtx insn;
1514
1515   next_tail = NEXT_INSN (tail);
1516
1517   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
1518     if (GET_CODE (insn) == NOTE && NOTE_LINE_NUMBER (insn) > 0)
1519       line = insn;
1520     else
1521       LINE_NOTE (insn) = line;
1522 }
1523
1524 /* After a block was scheduled, insert line notes into the insns list.
1525    HEAD and TAIL are the boundaries of the block in which notes should
1526    be processed.  */
1527
1528 void
1529 restore_line_notes (rtx head, rtx tail)
1530 {
1531   rtx line, note, prev, new;
1532   int added_notes = 0;
1533   rtx next_tail, insn;
1534
1535   head = head;
1536   next_tail = NEXT_INSN (tail);
1537
1538   /* Determine the current line-number.  We want to know the current
1539      line number of the first insn of the block here, in case it is
1540      different from the true line number that was saved earlier.  If
1541      different, then we need a line number note before the first insn
1542      of this block.  If it happens to be the same, then we don't want to
1543      emit another line number note here.  */
1544   for (line = head; line; line = PREV_INSN (line))
1545     if (GET_CODE (line) == NOTE && NOTE_LINE_NUMBER (line) > 0)
1546       break;
1547
1548   /* Walk the insns keeping track of the current line-number and inserting
1549      the line-number notes as needed.  */
1550   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
1551     if (GET_CODE (insn) == NOTE && NOTE_LINE_NUMBER (insn) > 0)
1552       line = insn;
1553   /* This used to emit line number notes before every non-deleted note.
1554      However, this confuses a debugger, because line notes not separated
1555      by real instructions all end up at the same address.  I can find no
1556      use for line number notes before other notes, so none are emitted.  */
1557     else if (GET_CODE (insn) != NOTE
1558              && INSN_UID (insn) < old_max_uid
1559              && (note = LINE_NOTE (insn)) != 0
1560              && note != line
1561              && (line == 0
1562 #ifdef USE_MAPPED_LOCATION
1563                  || NOTE_SOURCE_LOCATION (note) != NOTE_SOURCE_LOCATION (line)
1564 #else
1565                  || NOTE_LINE_NUMBER (note) != NOTE_LINE_NUMBER (line)
1566                  || NOTE_SOURCE_FILE (note) != NOTE_SOURCE_FILE (line)
1567 #endif
1568                  ))
1569       {
1570         line = note;
1571         prev = PREV_INSN (insn);
1572         if (LINE_NOTE (note))
1573           {
1574             /* Re-use the original line-number note.  */
1575             LINE_NOTE (note) = 0;
1576             PREV_INSN (note) = prev;
1577             NEXT_INSN (prev) = note;
1578             PREV_INSN (insn) = note;
1579             NEXT_INSN (note) = insn;
1580           }
1581         else
1582           {
1583             added_notes++;
1584             new = emit_note_after (NOTE_LINE_NUMBER (note), prev);
1585 #ifndef USE_MAPPED_LOCATION
1586             NOTE_SOURCE_FILE (new) = NOTE_SOURCE_FILE (note);
1587 #endif
1588           }
1589       }
1590   if (sched_verbose && added_notes)
1591     fprintf (sched_dump, ";; added %d line-number notes\n", added_notes);
1592 }
1593
1594 /* After scheduling the function, delete redundant line notes from the
1595    insns list.  */
1596
1597 void
1598 rm_redundant_line_notes (void)
1599 {
1600   rtx line = 0;
1601   rtx insn = get_insns ();
1602   int active_insn = 0;
1603   int notes = 0;
1604
1605   /* Walk the insns deleting redundant line-number notes.  Many of these
1606      are already present.  The remainder tend to occur at basic
1607      block boundaries.  */
1608   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
1609     if (GET_CODE (insn) == NOTE && NOTE_LINE_NUMBER (insn) > 0)
1610       {
1611         /* If there are no active insns following, INSN is redundant.  */
1612         if (active_insn == 0)
1613           {
1614             notes++;
1615             SET_INSN_DELETED (insn);
1616           }
1617         /* If the line number is unchanged, LINE is redundant.  */
1618         else if (line
1619 #ifdef USE_MAPPED_LOCATION
1620                  && NOTE_SOURCE_LOCATION (line) == NOTE_SOURCE_LOCATION (insn)
1621 #else
1622                  && NOTE_LINE_NUMBER (line) == NOTE_LINE_NUMBER (insn)
1623                  && NOTE_SOURCE_FILE (line) == NOTE_SOURCE_FILE (insn)
1624 #endif
1625 )
1626           {
1627             notes++;
1628             SET_INSN_DELETED (line);
1629             line = insn;
1630           }
1631         else
1632           line = insn;
1633         active_insn = 0;
1634       }
1635     else if (!((GET_CODE (insn) == NOTE
1636                 && NOTE_LINE_NUMBER (insn) == NOTE_INSN_DELETED)
1637                || (GET_CODE (insn) == INSN
1638                    && (GET_CODE (PATTERN (insn)) == USE
1639                        || GET_CODE (PATTERN (insn)) == CLOBBER))))
1640       active_insn++;
1641
1642   if (sched_verbose && notes)
1643     fprintf (sched_dump, ";; deleted %d line-number notes\n", notes);
1644 }
1645
1646 /* Delete notes between HEAD and TAIL and put them in the chain
1647    of notes ended by NOTE_LIST.  */
1648
1649 void
1650 rm_other_notes (rtx head, rtx tail)
1651 {
1652   rtx next_tail;
1653   rtx insn;
1654
1655   note_list = 0;
1656   if (head == tail && (! INSN_P (head)))
1657     return;
1658
1659   next_tail = NEXT_INSN (tail);
1660   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
1661     {
1662       rtx prev;
1663
1664       /* Farm out notes, and maybe save them in NOTE_LIST.
1665          This is needed to keep the debugger from
1666          getting completely deranged.  */
1667       if (GET_CODE (insn) == NOTE)
1668         {
1669           prev = insn;
1670
1671           insn = unlink_other_notes (insn, next_tail);
1672
1673           if (prev == tail)
1674             abort ();
1675           if (prev == head)
1676             abort ();
1677           if (insn == next_tail)
1678             abort ();
1679         }
1680     }
1681 }
1682
1683 /* Functions for computation of registers live/usage info.  */
1684
1685 /* This function looks for a new register being defined.
1686    If the destination register is already used by the source,
1687    a new register is not needed.  */
1688
1689 static int
1690 find_set_reg_weight (rtx x)
1691 {
1692   if (GET_CODE (x) == CLOBBER
1693       && register_operand (SET_DEST (x), VOIDmode))
1694     return 1;
1695   if (GET_CODE (x) == SET
1696       && register_operand (SET_DEST (x), VOIDmode))
1697     {
1698       if (REG_P (SET_DEST (x)))
1699         {
1700           if (!reg_mentioned_p (SET_DEST (x), SET_SRC (x)))
1701             return 1;
1702           else
1703             return 0;
1704         }
1705       return 1;
1706     }
1707   return 0;
1708 }
1709
1710 /* Calculate INSN_REG_WEIGHT for all insns of a block.  */
1711
1712 static void
1713 find_insn_reg_weight (int b)
1714 {
1715   rtx insn, next_tail, head, tail;
1716
1717   get_block_head_tail (b, &head, &tail);
1718   next_tail = NEXT_INSN (tail);
1719
1720   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
1721     {
1722       int reg_weight = 0;
1723       rtx x;
1724
1725       /* Handle register life information.  */
1726       if (! INSN_P (insn))
1727         continue;
1728
1729       /* Increment weight for each register born here.  */
1730       x = PATTERN (insn);
1731       reg_weight += find_set_reg_weight (x);
1732       if (GET_CODE (x) == PARALLEL)
1733         {
1734           int j;
1735           for (j = XVECLEN (x, 0) - 1; j >= 0; j--)
1736             {
1737               x = XVECEXP (PATTERN (insn), 0, j);
1738               reg_weight += find_set_reg_weight (x);
1739             }
1740         }
1741       /* Decrement weight for each register that dies here.  */
1742       for (x = REG_NOTES (insn); x; x = XEXP (x, 1))
1743         {
1744           if (REG_NOTE_KIND (x) == REG_DEAD
1745               || REG_NOTE_KIND (x) == REG_UNUSED)
1746             reg_weight--;
1747         }
1748
1749       INSN_REG_WEIGHT (insn) = reg_weight;
1750     }
1751 }
1752
1753 /* Scheduling clock, modified in schedule_block() and queue_to_ready ().  */
1754 static int clock_var;
1755
1756 /* Move insns that became ready to fire from queue to ready list.  */
1757
1758 static void
1759 queue_to_ready (struct ready_list *ready)
1760 {
1761   rtx insn;
1762   rtx link;
1763
1764   q_ptr = NEXT_Q (q_ptr);
1765
1766   /* Add all pending insns that can be scheduled without stalls to the
1767      ready list.  */
1768   for (link = insn_queue[q_ptr]; link; link = XEXP (link, 1))
1769     {
1770       insn = XEXP (link, 0);
1771       q_size -= 1;
1772
1773       if (sched_verbose >= 2)
1774         fprintf (sched_dump, ";;\t\tQ-->Ready: insn %s: ",
1775                  (*current_sched_info->print_insn) (insn, 0));
1776
1777       ready_add (ready, insn);
1778       if (sched_verbose >= 2)
1779         fprintf (sched_dump, "moving to ready without stalls\n");
1780     }
1781   insn_queue[q_ptr] = 0;
1782
1783   /* If there are no ready insns, stall until one is ready and add all
1784      of the pending insns at that point to the ready list.  */
1785   if (ready->n_ready == 0)
1786     {
1787       int stalls;
1788
1789       for (stalls = 1; stalls <= MAX_INSN_QUEUE_INDEX; stalls++)
1790         {
1791           if ((link = insn_queue[NEXT_Q_AFTER (q_ptr, stalls)]))
1792             {
1793               for (; link; link = XEXP (link, 1))
1794                 {
1795                   insn = XEXP (link, 0);
1796                   q_size -= 1;
1797
1798                   if (sched_verbose >= 2)
1799                     fprintf (sched_dump, ";;\t\tQ-->Ready: insn %s: ",
1800                              (*current_sched_info->print_insn) (insn, 0));
1801
1802                   ready_add (ready, insn);
1803                   if (sched_verbose >= 2)
1804                     fprintf (sched_dump, "moving to ready with %d stalls\n", stalls);
1805                 }
1806               insn_queue[NEXT_Q_AFTER (q_ptr, stalls)] = 0;
1807
1808               advance_one_cycle ();
1809
1810               break;
1811             }
1812
1813           advance_one_cycle ();
1814         }
1815
1816       if ((!targetm.sched.use_dfa_pipeline_interface
1817            || !targetm.sched.use_dfa_pipeline_interface ())
1818           && sched_verbose && stalls)
1819         visualize_stall_cycles (stalls);
1820
1821       q_ptr = NEXT_Q_AFTER (q_ptr, stalls);
1822       clock_var += stalls;
1823     }
1824 }
1825
1826 /* Used by early_queue_to_ready.  Determines whether it is "ok" to
1827    prematurely move INSN from the queue to the ready list.  Currently, 
1828    if a target defines the hook 'is_costly_dependence', this function 
1829    uses the hook to check whether there exist any dependences which are
1830    considered costly by the target, between INSN and other insns that 
1831    have already been scheduled.  Dependences are checked up to Y cycles
1832    back, with default Y=1; The flag -fsched-stalled-insns-dep=Y allows
1833    controlling this value. 
1834    (Other considerations could be taken into account instead (or in 
1835    addition) depending on user flags and target hooks.  */
1836
1837 static bool 
1838 ok_for_early_queue_removal (rtx insn)
1839 {
1840   int n_cycles;
1841   rtx prev_insn = last_scheduled_insn;
1842
1843   if (targetm.sched.is_costly_dependence)
1844     {
1845       for (n_cycles = flag_sched_stalled_insns_dep; n_cycles; n_cycles--)
1846         {
1847           for ( ; prev_insn; prev_insn = PREV_INSN (prev_insn))
1848             {
1849               rtx dep_link = 0;
1850               int dep_cost;
1851
1852               if (GET_CODE (prev_insn) != NOTE)
1853                 {
1854                   dep_link = find_insn_list (insn, INSN_DEPEND (prev_insn));
1855                   if (dep_link)
1856                     {
1857                       dep_cost = insn_cost (prev_insn, dep_link, insn) ;
1858                       if (targetm.sched.is_costly_dependence (prev_insn, insn, 
1859                                 dep_link, dep_cost, 
1860                                 flag_sched_stalled_insns_dep - n_cycles))
1861                         return false;
1862                     }
1863                 }
1864
1865               if (GET_MODE (prev_insn) == TImode) /* end of dispatch group */
1866                 break;
1867             }
1868
1869           if (!prev_insn) 
1870             break;
1871           prev_insn = PREV_INSN (prev_insn);     
1872         }
1873     }
1874
1875   return true;
1876 }
1877
1878
1879 /* Remove insns from the queue, before they become "ready" with respect
1880    to FU latency considerations.  */
1881
1882 static int 
1883 early_queue_to_ready (state_t state, struct ready_list *ready)
1884 {
1885   rtx insn;
1886   rtx link;
1887   rtx next_link;
1888   rtx prev_link;
1889   bool move_to_ready;
1890   int cost;
1891   state_t temp_state = alloca (dfa_state_size);
1892   int stalls;
1893   int insns_removed = 0;
1894
1895   /*
1896      Flag '-fsched-stalled-insns=X' determines the aggressiveness of this 
1897      function: 
1898
1899      X == 0: There is no limit on how many queued insns can be removed          
1900              prematurely.  (flag_sched_stalled_insns = -1).
1901
1902      X >= 1: Only X queued insns can be removed prematurely in each 
1903              invocation.  (flag_sched_stalled_insns = X).
1904
1905      Otherwise: Early queue removal is disabled.
1906          (flag_sched_stalled_insns = 0)
1907   */
1908
1909   if (! flag_sched_stalled_insns)   
1910     return 0;
1911
1912   for (stalls = 0; stalls <= MAX_INSN_QUEUE_INDEX; stalls++)
1913     {
1914       if ((link = insn_queue[NEXT_Q_AFTER (q_ptr, stalls)]))
1915         {
1916           if (sched_verbose > 6)
1917             fprintf (sched_dump, ";; look at index %d + %d\n", q_ptr, stalls);
1918
1919           prev_link = 0;
1920           while (link)
1921             {
1922               next_link = XEXP (link, 1);
1923               insn = XEXP (link, 0);
1924               if (insn && sched_verbose > 6)
1925                 print_rtl_single (sched_dump, insn);
1926
1927               memcpy (temp_state, state, dfa_state_size);
1928               if (recog_memoized (insn) < 0) 
1929                 /* non-negative to indicate that it's not ready
1930                    to avoid infinite Q->R->Q->R... */
1931                 cost = 0;
1932               else
1933                 cost = state_transition (temp_state, insn);
1934
1935               if (sched_verbose >= 6)
1936                 fprintf (sched_dump, "transition cost = %d\n", cost);
1937
1938               move_to_ready = false;
1939               if (cost < 0) 
1940                 {
1941                   move_to_ready = ok_for_early_queue_removal (insn);
1942                   if (move_to_ready == true)
1943                     {
1944                       /* move from Q to R */
1945                       q_size -= 1;
1946                       ready_add (ready, insn);
1947
1948                       if (prev_link)   
1949                         XEXP (prev_link, 1) = next_link;
1950                       else
1951                         insn_queue[NEXT_Q_AFTER (q_ptr, stalls)] = next_link;
1952
1953                       free_INSN_LIST_node (link);
1954
1955                       if (sched_verbose >= 2)
1956                         fprintf (sched_dump, ";;\t\tEarly Q-->Ready: insn %s\n",
1957                                  (*current_sched_info->print_insn) (insn, 0));
1958
1959                       insns_removed++;
1960                       if (insns_removed == flag_sched_stalled_insns)
1961                         /* Remove only one insn from Q at a time.  */
1962                         return insns_removed;
1963                     }
1964                 }
1965
1966               if (move_to_ready == false)
1967                 prev_link = link;
1968
1969               link = next_link;
1970             } /* while link */
1971         } /* if link */    
1972
1973     } /* for stalls.. */
1974
1975   return insns_removed; 
1976 }
1977
1978
1979 /* Print the ready list for debugging purposes.  Callable from debugger.  */
1980
1981 static void
1982 debug_ready_list (struct ready_list *ready)
1983 {
1984   rtx *p;
1985   int i;
1986
1987   if (ready->n_ready == 0)
1988     {
1989       fprintf (sched_dump, "\n");
1990       return;
1991     }
1992
1993   p = ready_lastpos (ready);
1994   for (i = 0; i < ready->n_ready; i++)
1995     fprintf (sched_dump, "  %s", (*current_sched_info->print_insn) (p[i], 0));
1996   fprintf (sched_dump, "\n");
1997 }
1998
1999 /* move_insn1: Remove INSN from insn chain, and link it after LAST insn.  */
2000
2001 static rtx
2002 move_insn1 (rtx insn, rtx last)
2003 {
2004   NEXT_INSN (PREV_INSN (insn)) = NEXT_INSN (insn);
2005   PREV_INSN (NEXT_INSN (insn)) = PREV_INSN (insn);
2006
2007   NEXT_INSN (insn) = NEXT_INSN (last);
2008   PREV_INSN (NEXT_INSN (last)) = insn;
2009
2010   NEXT_INSN (last) = insn;
2011   PREV_INSN (insn) = last;
2012
2013   return insn;
2014 }
2015
2016 /* Search INSN for REG_SAVE_NOTE note pairs for
2017    NOTE_INSN_{LOOP,EHREGION}_{BEG,END}; and convert them back into
2018    NOTEs.  The REG_SAVE_NOTE note following first one is contains the
2019    saved value for NOTE_BLOCK_NUMBER which is useful for
2020    NOTE_INSN_EH_REGION_{BEG,END} NOTEs.  LAST is the last instruction
2021    output by the instruction scheduler.  Return the new value of LAST.  */
2022
2023 static rtx
2024 reemit_notes (rtx insn, rtx last)
2025 {
2026   rtx note, retval;
2027
2028   retval = last;
2029   for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
2030     {
2031       if (REG_NOTE_KIND (note) == REG_SAVE_NOTE)
2032         {
2033           enum insn_note note_type = INTVAL (XEXP (note, 0));
2034
2035           last = emit_note_before (note_type, last);
2036           remove_note (insn, note);
2037           note = XEXP (note, 1);
2038           if (note_type == NOTE_INSN_EH_REGION_BEG
2039               || note_type == NOTE_INSN_EH_REGION_END)
2040             NOTE_EH_HANDLER (last) = INTVAL (XEXP (note, 0));
2041           remove_note (insn, note);
2042         }
2043     }
2044   return retval;
2045 }
2046
2047 /* Move INSN.  Reemit notes if needed.
2048
2049    Return the last insn emitted by the scheduler, which is the
2050    return value from the first call to reemit_notes.  */
2051
2052 static rtx
2053 move_insn (rtx insn, rtx last)
2054 {
2055   rtx retval = NULL;
2056
2057   move_insn1 (insn, last);
2058
2059   /* If this is the first call to reemit_notes, then record
2060      its return value.  */
2061   if (retval == NULL_RTX)
2062     retval = reemit_notes (insn, insn);
2063   else
2064     reemit_notes (insn, insn);
2065
2066   SCHED_GROUP_P (insn) = 0;
2067
2068   return retval;
2069 }
2070
2071 /* The following structure describe an entry of the stack of choices.  */
2072 struct choice_entry
2073 {
2074   /* Ordinal number of the issued insn in the ready queue.  */
2075   int index;
2076   /* The number of the rest insns whose issues we should try.  */
2077   int rest;
2078   /* The number of issued essential insns.  */
2079   int n;
2080   /* State after issuing the insn.  */
2081   state_t state;
2082 };
2083
2084 /* The following array is used to implement a stack of choices used in
2085    function max_issue.  */
2086 static struct choice_entry *choice_stack;
2087
2088 /* The following variable value is number of essential insns issued on
2089    the current cycle.  An insn is essential one if it changes the
2090    processors state.  */
2091 static int cycle_issued_insns;
2092
2093 /* The following variable value is maximal number of tries of issuing
2094    insns for the first cycle multipass insn scheduling.  We define
2095    this value as constant*(DFA_LOOKAHEAD**ISSUE_RATE).  We would not
2096    need this constraint if all real insns (with non-negative codes)
2097    had reservations because in this case the algorithm complexity is
2098    O(DFA_LOOKAHEAD**ISSUE_RATE).  Unfortunately, the dfa descriptions
2099    might be incomplete and such insn might occur.  For such
2100    descriptions, the complexity of algorithm (without the constraint)
2101    could achieve DFA_LOOKAHEAD ** N , where N is the queue length.  */
2102 static int max_lookahead_tries;
2103
2104 /* The following value is value of hook
2105    `first_cycle_multipass_dfa_lookahead' at the last call of
2106    `max_issue'.  */
2107 static int cached_first_cycle_multipass_dfa_lookahead = 0;
2108
2109 /* The following value is value of `issue_rate' at the last call of
2110    `sched_init'.  */
2111 static int cached_issue_rate = 0;
2112
2113 /* The following function returns maximal (or close to maximal) number
2114    of insns which can be issued on the same cycle and one of which
2115    insns is insns with the best rank (the first insn in READY).  To
2116    make this function tries different samples of ready insns.  READY
2117    is current queue `ready'.  Global array READY_TRY reflects what
2118    insns are already issued in this try.  INDEX will contain index
2119    of the best insn in READY.  The following function is used only for
2120    first cycle multipass scheduling.  */
2121 static int
2122 max_issue (struct ready_list *ready, int *index)
2123 {
2124   int n, i, all, n_ready, best, delay, tries_num;
2125   struct choice_entry *top;
2126   rtx insn;
2127
2128   best = 0;
2129   memcpy (choice_stack->state, curr_state, dfa_state_size);
2130   top = choice_stack;
2131   top->rest = cached_first_cycle_multipass_dfa_lookahead;
2132   top->n = 0;
2133   n_ready = ready->n_ready;
2134   for (all = i = 0; i < n_ready; i++)
2135     if (!ready_try [i])
2136       all++;
2137   i = 0;
2138   tries_num = 0;
2139   for (;;)
2140     {
2141       if (top->rest == 0 || i >= n_ready)
2142         {
2143           if (top == choice_stack)
2144             break;
2145           if (best < top - choice_stack && ready_try [0])
2146             {
2147               best = top - choice_stack;
2148               *index = choice_stack [1].index;
2149               if (top->n == issue_rate - cycle_issued_insns || best == all)
2150                 break;
2151             }
2152           i = top->index;
2153           ready_try [i] = 0;
2154           top--;
2155           memcpy (curr_state, top->state, dfa_state_size);
2156         }
2157       else if (!ready_try [i])
2158         {
2159           tries_num++;
2160           if (tries_num > max_lookahead_tries)
2161             break;
2162           insn = ready_element (ready, i);
2163           delay = state_transition (curr_state, insn);
2164           if (delay < 0)
2165             {
2166               if (state_dead_lock_p (curr_state))
2167                 top->rest = 0;
2168               else
2169                 top->rest--;
2170               n = top->n;
2171               if (memcmp (top->state, curr_state, dfa_state_size) != 0)
2172                 n++;
2173               top++;
2174               top->rest = cached_first_cycle_multipass_dfa_lookahead;
2175               top->index = i;
2176               top->n = n;
2177               memcpy (top->state, curr_state, dfa_state_size);
2178               ready_try [i] = 1;
2179               i = -1;
2180             }
2181         }
2182       i++;
2183     }
2184   while (top != choice_stack)
2185     {
2186       ready_try [top->index] = 0;
2187       top--;
2188     }
2189   memcpy (curr_state, choice_stack->state, dfa_state_size);
2190   return best;
2191 }
2192
2193 /* The following function chooses insn from READY and modifies
2194    *N_READY and READY.  The following function is used only for first
2195    cycle multipass scheduling.  */
2196
2197 static rtx
2198 choose_ready (struct ready_list *ready)
2199 {
2200   int lookahead = 0;
2201
2202   if (targetm.sched.first_cycle_multipass_dfa_lookahead)
2203     lookahead = targetm.sched.first_cycle_multipass_dfa_lookahead ();
2204   if (lookahead <= 0 || SCHED_GROUP_P (ready_element (ready, 0)))
2205     return ready_remove_first (ready);
2206   else
2207     {
2208       /* Try to choose the better insn.  */
2209       int index = 0, i;
2210       rtx insn;
2211
2212       if (cached_first_cycle_multipass_dfa_lookahead != lookahead)
2213         {
2214           cached_first_cycle_multipass_dfa_lookahead = lookahead;
2215           max_lookahead_tries = 100;
2216           for (i = 0; i < issue_rate; i++)
2217             max_lookahead_tries *= lookahead;
2218         }
2219       insn = ready_element (ready, 0);
2220       if (INSN_CODE (insn) < 0)
2221         return ready_remove_first (ready);
2222       for (i = 1; i < ready->n_ready; i++)
2223         {
2224           insn = ready_element (ready, i);
2225           ready_try [i]
2226             = (INSN_CODE (insn) < 0
2227                || (targetm.sched.first_cycle_multipass_dfa_lookahead_guard
2228                    && !targetm.sched.first_cycle_multipass_dfa_lookahead_guard (insn)));
2229         }
2230       if (max_issue (ready, &index) == 0)
2231         return ready_remove_first (ready);
2232       else
2233         return ready_remove (ready, index);
2234     }
2235 }
2236
2237 /* Use forward list scheduling to rearrange insns of block B in region RGN,
2238    possibly bringing insns from subsequent blocks in the same region.  */
2239
2240 void
2241 schedule_block (int b, int rgn_n_insns)
2242 {
2243   struct ready_list ready;
2244   int i, first_cycle_insn_p;
2245   int can_issue_more;
2246   state_t temp_state = NULL;  /* It is used for multipass scheduling.  */
2247   int sort_p, advance, start_clock_var;
2248
2249   /* Head/tail info for this block.  */
2250   rtx prev_head = current_sched_info->prev_head;
2251   rtx next_tail = current_sched_info->next_tail;
2252   rtx head = NEXT_INSN (prev_head);
2253   rtx tail = PREV_INSN (next_tail);
2254
2255   /* We used to have code to avoid getting parameters moved from hard
2256      argument registers into pseudos.
2257
2258      However, it was removed when it proved to be of marginal benefit
2259      and caused problems because schedule_block and compute_forward_dependences
2260      had different notions of what the "head" insn was.  */
2261
2262   if (head == tail && (! INSN_P (head)))
2263     abort ();
2264
2265   /* Debug info.  */
2266   if (sched_verbose)
2267     {
2268       fprintf (sched_dump, ";;   ======================================================\n");
2269       fprintf (sched_dump,
2270                ";;   -- basic block %d from %d to %d -- %s reload\n",
2271                b, INSN_UID (head), INSN_UID (tail),
2272                (reload_completed ? "after" : "before"));
2273       fprintf (sched_dump, ";;   ======================================================\n");
2274       fprintf (sched_dump, "\n");
2275
2276       visualize_alloc ();
2277       init_block_visualization ();
2278     }
2279
2280   if (targetm.sched.use_dfa_pipeline_interface
2281       && targetm.sched.use_dfa_pipeline_interface ())
2282     state_reset (curr_state);
2283   else
2284     clear_units ();
2285
2286   /* Allocate the ready list.  */
2287   ready.veclen = rgn_n_insns + 1 + issue_rate;
2288   ready.first = ready.veclen - 1;
2289   ready.vec = xmalloc (ready.veclen * sizeof (rtx));
2290   ready.n_ready = 0;
2291
2292   if (targetm.sched.use_dfa_pipeline_interface
2293       && targetm.sched.use_dfa_pipeline_interface ())
2294     {
2295       /* It is used for first cycle multipass scheduling.  */
2296       temp_state = alloca (dfa_state_size);
2297       ready_try = xcalloc ((rgn_n_insns + 1), sizeof (char));
2298       choice_stack = xmalloc ((rgn_n_insns + 1)
2299                               * sizeof (struct choice_entry));
2300       for (i = 0; i <= rgn_n_insns; i++)
2301         choice_stack[i].state = xmalloc (dfa_state_size);
2302     }
2303
2304   (*current_sched_info->init_ready_list) (&ready);
2305
2306   if (targetm.sched.md_init)
2307     targetm.sched.md_init (sched_dump, sched_verbose, ready.veclen);
2308
2309   /* We start inserting insns after PREV_HEAD.  */
2310   last_scheduled_insn = prev_head;
2311
2312   /* Initialize INSN_QUEUE.  Q_SIZE is the total number of insns in the
2313      queue.  */
2314   q_ptr = 0;
2315   q_size = 0;
2316
2317   if (!targetm.sched.use_dfa_pipeline_interface
2318       || !targetm.sched.use_dfa_pipeline_interface ())
2319     max_insn_queue_index_macro_value = INSN_QUEUE_SIZE - 1;
2320   else
2321     max_insn_queue_index_macro_value = max_insn_queue_index;
2322
2323   insn_queue = alloca ((MAX_INSN_QUEUE_INDEX + 1) * sizeof (rtx));
2324   memset (insn_queue, 0, (MAX_INSN_QUEUE_INDEX + 1) * sizeof (rtx));
2325   last_clock_var = -1;
2326
2327   /* Start just before the beginning of time.  */
2328   clock_var = -1;
2329   advance = 0;
2330
2331   sort_p = TRUE;
2332   /* Loop until all the insns in BB are scheduled.  */
2333   while ((*current_sched_info->schedule_more_p) ())
2334     {
2335       do
2336         {
2337           start_clock_var = clock_var;
2338
2339           clock_var++;
2340
2341           advance_one_cycle ();
2342
2343           /* Add to the ready list all pending insns that can be issued now.
2344              If there are no ready insns, increment clock until one
2345              is ready and add all pending insns at that point to the ready
2346              list.  */
2347           queue_to_ready (&ready);
2348
2349           if (ready.n_ready == 0)
2350             abort ();
2351
2352           if (sched_verbose >= 2)
2353             {
2354               fprintf (sched_dump, ";;\t\tReady list after queue_to_ready:  ");
2355               debug_ready_list (&ready);
2356             }
2357           advance -= clock_var - start_clock_var;
2358         }
2359       while (advance > 0);
2360
2361       if (sort_p)
2362         {
2363           /* Sort the ready list based on priority.  */
2364           ready_sort (&ready);
2365
2366           if (sched_verbose >= 2)
2367             {
2368               fprintf (sched_dump, ";;\t\tReady list after ready_sort:  ");
2369               debug_ready_list (&ready);
2370             }
2371         }
2372
2373       /* Allow the target to reorder the list, typically for
2374          better instruction bundling.  */
2375       if (sort_p && targetm.sched.reorder
2376           && (ready.n_ready == 0
2377               || !SCHED_GROUP_P (ready_element (&ready, 0))))
2378         can_issue_more =
2379           targetm.sched.reorder (sched_dump, sched_verbose,
2380                                  ready_lastpos (&ready),
2381                                  &ready.n_ready, clock_var);
2382       else
2383         can_issue_more = issue_rate;
2384
2385       first_cycle_insn_p = 1;
2386       cycle_issued_insns = 0;
2387       for (;;)
2388         {
2389           rtx insn;
2390           int cost;
2391           bool asm_p = false;
2392
2393           if (sched_verbose >= 2)
2394             {
2395               fprintf (sched_dump, ";;\tReady list (t =%3d):  ",
2396                        clock_var);
2397               debug_ready_list (&ready);
2398             }
2399
2400           if (!targetm.sched.use_dfa_pipeline_interface
2401               || !targetm.sched.use_dfa_pipeline_interface ())
2402             {
2403               if (ready.n_ready == 0 || !can_issue_more
2404                   || !(*current_sched_info->schedule_more_p) ())
2405                 break;
2406               insn = ready_remove_first (&ready);
2407               cost = actual_hazard (insn_unit (insn), insn, clock_var, 0);
2408             }
2409           else
2410             {
2411               if (ready.n_ready == 0 
2412                   && can_issue_more 
2413                   && reload_completed) 
2414                 {
2415                   /* Allow scheduling insns directly from the queue in case
2416                      there's nothing better to do (ready list is empty) but
2417                      there are still vacant dispatch slots in the current cycle.  */
2418                   if (sched_verbose >= 6)
2419                     fprintf(sched_dump,";;\t\tSecond chance\n");
2420                   memcpy (temp_state, curr_state, dfa_state_size);
2421                   if (early_queue_to_ready (temp_state, &ready))
2422                     ready_sort (&ready);
2423                 }
2424
2425               if (ready.n_ready == 0 || !can_issue_more
2426                   || state_dead_lock_p (curr_state)
2427                   || !(*current_sched_info->schedule_more_p) ())
2428                 break;
2429
2430               /* Select and remove the insn from the ready list.  */
2431               if (sort_p)
2432                 insn = choose_ready (&ready);
2433               else
2434                 insn = ready_remove_first (&ready);
2435
2436               if (targetm.sched.dfa_new_cycle
2437                   && targetm.sched.dfa_new_cycle (sched_dump, sched_verbose,
2438                                                   insn, last_clock_var,
2439                                                   clock_var, &sort_p))
2440                 {
2441                   ready_add (&ready, insn);
2442                   break;
2443                 }
2444
2445               sort_p = TRUE;
2446               memcpy (temp_state, curr_state, dfa_state_size);
2447               if (recog_memoized (insn) < 0)
2448                 {
2449                   asm_p = (GET_CODE (PATTERN (insn)) == ASM_INPUT
2450                            || asm_noperands (PATTERN (insn)) >= 0);
2451                   if (!first_cycle_insn_p && asm_p)
2452                     /* This is asm insn which is tryed to be issued on the
2453                        cycle not first.  Issue it on the next cycle.  */
2454                     cost = 1;
2455                   else
2456                     /* A USE insn, or something else we don't need to
2457                        understand.  We can't pass these directly to
2458                        state_transition because it will trigger a
2459                        fatal error for unrecognizable insns.  */
2460                     cost = 0;
2461                 }
2462               else
2463                 {
2464                   cost = state_transition (temp_state, insn);
2465
2466                   if (targetm.sched.first_cycle_multipass_dfa_lookahead
2467                       && targetm.sched.dfa_bubble)
2468                     {
2469                       if (cost == 0)
2470                         {
2471                           int j;
2472                           rtx bubble;
2473
2474                           for (j = 0;
2475                                (bubble = targetm.sched.dfa_bubble (j))
2476                                  != NULL_RTX;
2477                                j++)
2478                             {
2479                               memcpy (temp_state, curr_state, dfa_state_size);
2480
2481                               if (state_transition (temp_state, bubble) < 0
2482                                   && state_transition (temp_state, insn) < 0)
2483                                 break;
2484                             }
2485
2486                           if (bubble != NULL_RTX)
2487                             {
2488                               if (insert_schedule_bubbles_p)
2489                                 {
2490                                   rtx copy;
2491
2492                                   copy = copy_rtx (PATTERN (bubble));
2493                                   emit_insn_after (copy, last_scheduled_insn);
2494                                   last_scheduled_insn
2495                                     = NEXT_INSN (last_scheduled_insn);
2496                                   INSN_CODE (last_scheduled_insn)
2497                                     = INSN_CODE (bubble);
2498
2499                                   /* Annotate the same for the first insns
2500                                      scheduling by using mode.  */
2501                                   PUT_MODE (last_scheduled_insn,
2502                                             (clock_var > last_clock_var
2503                                              ? clock_var - last_clock_var
2504                                              : VOIDmode));
2505                                   last_clock_var = clock_var;
2506
2507                                   if (sched_verbose >= 2)
2508                                     {
2509                                       fprintf (sched_dump,
2510                                                ";;\t\t--> scheduling bubble insn <<<%d>>>:reservation ",
2511                                                INSN_UID (last_scheduled_insn));
2512
2513                                       if (recog_memoized (last_scheduled_insn)
2514                                           < 0)
2515                                         fprintf (sched_dump, "nothing");
2516                                       else
2517                                         print_reservation
2518                                           (sched_dump, last_scheduled_insn);
2519
2520                                       fprintf (sched_dump, "\n");
2521                                     }
2522                                 }
2523                               cost = -1;
2524                             }
2525                         }
2526                     }
2527
2528                   if (cost < 0)
2529                     cost = 0;
2530                   else if (cost == 0)
2531                     cost = 1;
2532                 }
2533             }
2534
2535
2536           if (cost >= 1)
2537             {
2538               queue_insn (insn, cost);
2539               continue;
2540             }
2541
2542           if (! (*current_sched_info->can_schedule_ready_p) (insn))
2543             goto next;
2544
2545           last_scheduled_insn = move_insn (insn, last_scheduled_insn);
2546
2547           if (targetm.sched.use_dfa_pipeline_interface
2548               && targetm.sched.use_dfa_pipeline_interface ())
2549             {
2550               if (memcmp (curr_state, temp_state, dfa_state_size) != 0)
2551                 cycle_issued_insns++;
2552               memcpy (curr_state, temp_state, dfa_state_size);
2553             }
2554
2555           if (targetm.sched.variable_issue)
2556             can_issue_more =
2557               targetm.sched.variable_issue (sched_dump, sched_verbose,
2558                                                insn, can_issue_more);
2559           /* A naked CLOBBER or USE generates no instruction, so do
2560              not count them against the issue rate.  */
2561           else if (GET_CODE (PATTERN (insn)) != USE
2562                    && GET_CODE (PATTERN (insn)) != CLOBBER)
2563             can_issue_more--;
2564
2565           advance = schedule_insn (insn, &ready, clock_var);
2566
2567           /* After issuing an asm insn we should start a new cycle.  */
2568           if (advance == 0 && asm_p)
2569             advance = 1;
2570           if (advance != 0)
2571             break;
2572
2573         next:
2574           first_cycle_insn_p = 0;
2575
2576           /* Sort the ready list based on priority.  This must be
2577              redone here, as schedule_insn may have readied additional
2578              insns that will not be sorted correctly.  */
2579           if (ready.n_ready > 0)
2580             ready_sort (&ready);
2581
2582           if (targetm.sched.reorder2
2583               && (ready.n_ready == 0
2584                   || !SCHED_GROUP_P (ready_element (&ready, 0))))
2585             {
2586               can_issue_more =
2587                 targetm.sched.reorder2 (sched_dump, sched_verbose,
2588                                         ready.n_ready
2589                                         ? ready_lastpos (&ready) : NULL,
2590                                         &ready.n_ready, clock_var);
2591             }
2592         }
2593
2594       if ((!targetm.sched.use_dfa_pipeline_interface
2595            || !targetm.sched.use_dfa_pipeline_interface ())
2596           && sched_verbose)
2597         /* Debug info.  */
2598         visualize_scheduled_insns (clock_var);
2599     }
2600
2601   if (targetm.sched.md_finish)
2602     targetm.sched.md_finish (sched_dump, sched_verbose);
2603
2604   /* Debug info.  */
2605   if (sched_verbose)
2606     {
2607       fprintf (sched_dump, ";;\tReady list (final):  ");
2608       debug_ready_list (&ready);
2609       if (!targetm.sched.use_dfa_pipeline_interface
2610           || !targetm.sched.use_dfa_pipeline_interface ())
2611         print_block_visualization ("");
2612     }
2613
2614   /* Sanity check -- queue must be empty now.  Meaningless if region has
2615      multiple bbs.  */
2616   if (current_sched_info->queue_must_finish_empty && q_size != 0)
2617       abort ();
2618
2619   /* Update head/tail boundaries.  */
2620   head = NEXT_INSN (prev_head);
2621   tail = last_scheduled_insn;
2622
2623   if (!reload_completed)
2624     {
2625       rtx insn, link, next;
2626
2627       /* INSN_TICK (minimum clock tick at which the insn becomes
2628          ready) may be not correct for the insn in the subsequent
2629          blocks of the region.  We should use a correct value of
2630          `clock_var' or modify INSN_TICK.  It is better to keep
2631          clock_var value equal to 0 at the start of a basic block.
2632          Therefore we modify INSN_TICK here.  */
2633       for (insn = head; insn != tail; insn = NEXT_INSN (insn))
2634         if (INSN_P (insn))
2635           {
2636             for (link = INSN_DEPEND (insn); link != 0; link = XEXP (link, 1))
2637               {
2638                 next = XEXP (link, 0);
2639                 INSN_TICK (next) -= clock_var;
2640               }
2641           }
2642     }
2643
2644   /* Restore-other-notes: NOTE_LIST is the end of a chain of notes
2645      previously found among the insns.  Insert them at the beginning
2646      of the insns.  */
2647   if (note_list != 0)
2648     {
2649       rtx note_head = note_list;
2650
2651       while (PREV_INSN (note_head))
2652         {
2653           note_head = PREV_INSN (note_head);
2654         }
2655
2656       PREV_INSN (note_head) = PREV_INSN (head);
2657       NEXT_INSN (PREV_INSN (head)) = note_head;
2658       PREV_INSN (head) = note_list;
2659       NEXT_INSN (note_list) = head;
2660       head = note_head;
2661     }
2662
2663   /* Debugging.  */
2664   if (sched_verbose)
2665     {
2666       fprintf (sched_dump, ";;   total time = %d\n;;   new head = %d\n",
2667                clock_var, INSN_UID (head));
2668       fprintf (sched_dump, ";;   new tail = %d\n\n",
2669                INSN_UID (tail));
2670       visualize_free ();
2671     }
2672
2673   current_sched_info->head = head;
2674   current_sched_info->tail = tail;
2675
2676   free (ready.vec);
2677
2678   if (targetm.sched.use_dfa_pipeline_interface
2679       && targetm.sched.use_dfa_pipeline_interface ())
2680     {
2681       free (ready_try);
2682       for (i = 0; i <= rgn_n_insns; i++)
2683         free (choice_stack [i].state);
2684       free (choice_stack);
2685     }
2686 }
2687 \f
2688 /* Set_priorities: compute priority of each insn in the block.  */
2689
2690 int
2691 set_priorities (rtx head, rtx tail)
2692 {
2693   rtx insn;
2694   int n_insn;
2695   int sched_max_insns_priority = 
2696         current_sched_info->sched_max_insns_priority;
2697   rtx prev_head;
2698
2699   prev_head = PREV_INSN (head);
2700
2701   if (head == tail && (! INSN_P (head)))
2702     return 0;
2703
2704   n_insn = 0;
2705   sched_max_insns_priority = 0;
2706   for (insn = tail; insn != prev_head; insn = PREV_INSN (insn))
2707     {
2708       if (GET_CODE (insn) == NOTE)
2709         continue;
2710
2711       n_insn++;
2712       (void) priority (insn);
2713
2714       if (INSN_PRIORITY_KNOWN (insn))
2715         sched_max_insns_priority =
2716           MAX (sched_max_insns_priority, INSN_PRIORITY (insn)); 
2717     }
2718   sched_max_insns_priority += 1;
2719   current_sched_info->sched_max_insns_priority =
2720         sched_max_insns_priority;
2721
2722   return n_insn;
2723 }
2724
2725 /* Initialize some global state for the scheduler.  DUMP_FILE is to be used
2726    for debugging output.  */
2727
2728 void
2729 sched_init (FILE *dump_file)
2730 {
2731   int luid;
2732   basic_block b;
2733   rtx insn;
2734   int i;
2735
2736   /* Disable speculative loads in their presence if cc0 defined.  */
2737 #ifdef HAVE_cc0
2738   flag_schedule_speculative_load = 0;
2739 #endif
2740
2741   /* Set dump and sched_verbose for the desired debugging output.  If no
2742      dump-file was specified, but -fsched-verbose=N (any N), print to stderr.
2743      For -fsched-verbose=N, N>=10, print everything to stderr.  */
2744   sched_verbose = sched_verbose_param;
2745   if (sched_verbose_param == 0 && dump_file)
2746     sched_verbose = 1;
2747   sched_dump = ((sched_verbose_param >= 10 || !dump_file)
2748                 ? stderr : dump_file);
2749
2750   /* Initialize issue_rate.  */
2751   if (targetm.sched.issue_rate)
2752     issue_rate = targetm.sched.issue_rate ();
2753   else
2754     issue_rate = 1;
2755
2756   if (cached_issue_rate != issue_rate)
2757     {
2758       cached_issue_rate = issue_rate;
2759       /* To invalidate max_lookahead_tries:  */
2760       cached_first_cycle_multipass_dfa_lookahead = 0;
2761     }
2762
2763   /* We use LUID 0 for the fake insn (UID 0) which holds dependencies for
2764      pseudos which do not cross calls.  */
2765   old_max_uid = get_max_uid () + 1;
2766
2767   h_i_d = xcalloc (old_max_uid, sizeof (*h_i_d));
2768
2769   for (i = 0; i < old_max_uid; i++)
2770     h_i_d [i].cost = -1;
2771
2772   if (targetm.sched.use_dfa_pipeline_interface
2773       && targetm.sched.use_dfa_pipeline_interface ())
2774     {
2775       if (targetm.sched.init_dfa_pre_cycle_insn)
2776         targetm.sched.init_dfa_pre_cycle_insn ();
2777
2778       if (targetm.sched.init_dfa_post_cycle_insn)
2779         targetm.sched.init_dfa_post_cycle_insn ();
2780
2781       if (targetm.sched.first_cycle_multipass_dfa_lookahead
2782           && targetm.sched.init_dfa_bubbles)
2783         targetm.sched.init_dfa_bubbles ();
2784
2785       dfa_start ();
2786       dfa_state_size = state_size ();
2787       curr_state = xmalloc (dfa_state_size);
2788     }
2789
2790   h_i_d[0].luid = 0;
2791   luid = 1;
2792   FOR_EACH_BB (b)
2793     for (insn = BB_HEAD (b); ; insn = NEXT_INSN (insn))
2794       {
2795         INSN_LUID (insn) = luid;
2796
2797         /* Increment the next luid, unless this is a note.  We don't
2798            really need separate IDs for notes and we don't want to
2799            schedule differently depending on whether or not there are
2800            line-number notes, i.e., depending on whether or not we're
2801            generating debugging information.  */
2802         if (GET_CODE (insn) != NOTE)
2803           ++luid;
2804
2805         if (insn == BB_END (b))
2806           break;
2807       }
2808
2809   init_dependency_caches (luid);
2810
2811   init_alias_analysis ();
2812
2813   if (write_symbols != NO_DEBUG)
2814     {
2815       rtx line;
2816
2817       line_note_head = xcalloc (last_basic_block, sizeof (rtx));
2818
2819       /* Save-line-note-head:
2820          Determine the line-number at the start of each basic block.
2821          This must be computed and saved now, because after a basic block's
2822          predecessor has been scheduled, it is impossible to accurately
2823          determine the correct line number for the first insn of the block.  */
2824
2825       FOR_EACH_BB (b)
2826         {
2827           for (line = BB_HEAD (b); line; line = PREV_INSN (line))
2828             if (GET_CODE (line) == NOTE && NOTE_LINE_NUMBER (line) > 0)
2829               {
2830                 line_note_head[b->index] = line;
2831                 break;
2832               }
2833           /* Do a forward search as well, since we won't get to see the first
2834              notes in a basic block.  */
2835           for (line = BB_HEAD (b); line; line = NEXT_INSN (line))
2836             {
2837               if (INSN_P (line))
2838                 break;
2839               if (GET_CODE (line) == NOTE && NOTE_LINE_NUMBER (line) > 0)
2840                 line_note_head[b->index] = line;
2841             }
2842         }
2843     }
2844
2845   if ((!targetm.sched.use_dfa_pipeline_interface
2846        || !targetm.sched.use_dfa_pipeline_interface ())
2847       && sched_verbose)
2848     /* Find units used in this function, for visualization.  */
2849     init_target_units ();
2850
2851   /* ??? Add a NOTE after the last insn of the last basic block.  It is not
2852      known why this is done.  */
2853
2854   insn = BB_END (EXIT_BLOCK_PTR->prev_bb);
2855   if (NEXT_INSN (insn) == 0
2856       || (GET_CODE (insn) != NOTE
2857           && GET_CODE (insn) != CODE_LABEL
2858           /* Don't emit a NOTE if it would end up before a BARRIER.  */
2859           && GET_CODE (NEXT_INSN (insn)) != BARRIER))
2860     {
2861       emit_note_after (NOTE_INSN_DELETED, BB_END (EXIT_BLOCK_PTR->prev_bb));
2862       /* Make insn to appear outside BB.  */
2863       BB_END (EXIT_BLOCK_PTR->prev_bb) = PREV_INSN (BB_END (EXIT_BLOCK_PTR->prev_bb));
2864     }
2865
2866   /* Compute INSN_REG_WEIGHT for all blocks.  We must do this before
2867      removing death notes.  */
2868   FOR_EACH_BB_REVERSE (b)
2869     find_insn_reg_weight (b->index);
2870
2871   if (targetm.sched.md_init_global)
2872       targetm.sched.md_init_global (sched_dump, sched_verbose, old_max_uid);
2873 }
2874
2875 /* Free global data used during insn scheduling.  */
2876
2877 void
2878 sched_finish (void)
2879 {
2880   free (h_i_d);
2881
2882   if (targetm.sched.use_dfa_pipeline_interface
2883       && targetm.sched.use_dfa_pipeline_interface ())
2884     {
2885       free (curr_state);
2886       dfa_finish ();
2887     }
2888   free_dependency_caches ();
2889   end_alias_analysis ();
2890   if (write_symbols != NO_DEBUG)
2891     free (line_note_head);
2892
2893   if (targetm.sched.md_finish_global)
2894       targetm.sched.md_finish_global (sched_dump, sched_verbose);
2895 }
2896 #endif /* INSN_SCHEDULING */