OSDN Git Service

2011-04-29 Jerry DeLisle <jvdelisle@gcc.gnu.org>
[pf3gnuchains/gcc-fork.git] / gcc / haifa-sched.c
1 /* Instruction scheduling pass.
2    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3    2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
4    Free Software Foundation, Inc.
5    Contributed by Michael Tiemann (tiemann@cygnus.com) Enhanced by,
6    and currently maintained by, Jim Wilson (wilson@cygnus.com)
7
8 This file is part of GCC.
9
10 GCC is free software; you can redistribute it and/or modify it under
11 the terms of the GNU General Public License as published by the Free
12 Software Foundation; either version 3, or (at your option) any later
13 version.
14
15 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
16 WARRANTY; without even the implied warranty of MERCHANTABILITY or
17 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
18 for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3.  If not see
22 <http://www.gnu.org/licenses/>.  */
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    The following list shows the order in which we want to break ties
58    among insns in the ready list:
59
60    1.  choose insn with the longest path to end of bb, ties
61    broken by
62    2.  choose insn with least contribution to register pressure,
63    ties broken by
64    3.  prefer in-block upon interblock motion, ties broken by
65    4.  prefer useful upon speculative motion, ties broken by
66    5.  choose insn with largest control flow probability, ties
67    broken by
68    6.  choose insn with the least dependences upon the previously
69    scheduled insn, or finally
70    7   choose the insn which has the most insns dependent on it.
71    8.  choose insn with lowest UID.
72
73    Memory references complicate matters.  Only if we can be certain
74    that memory references are not part of the data dependency graph
75    (via true, anti, or output dependence), can we move operations past
76    memory references.  To first approximation, reads can be done
77    independently, while writes introduce dependencies.  Better
78    approximations will yield fewer dependencies.
79
80    Before reload, an extended analysis of interblock data dependences
81    is required for interblock scheduling.  This is performed in
82    compute_block_backward_dependences ().
83
84    Dependencies set up by memory references are treated in exactly the
85    same way as other dependencies, by using insn backward dependences
86    INSN_BACK_DEPS.  INSN_BACK_DEPS are translated into forward dependences
87    INSN_FORW_DEPS the purpose of forward list scheduling.
88
89    Having optimized the critical path, we may have also unduly
90    extended the lifetimes of some registers.  If an operation requires
91    that constants be loaded into registers, it is certainly desirable
92    to load those constants as early as necessary, but no earlier.
93    I.e., it will not do to load up a bunch of registers at the
94    beginning of a basic block only to use them at the end, if they
95    could be loaded later, since this may result in excessive register
96    utilization.
97
98    Note that since branches are never in basic blocks, but only end
99    basic blocks, this pass will not move branches.  But that is ok,
100    since we can use GNU's delayed branch scheduling pass to take care
101    of this case.
102
103    Also note that no further optimizations based on algebraic
104    identities are performed, so this pass would be a good one to
105    perform instruction splitting, such as breaking up a multiply
106    instruction into shifts and adds where that is profitable.
107
108    Given the memory aliasing analysis that this pass should perform,
109    it should be possible to remove redundant stores to memory, and to
110    load values from registers instead of hitting memory.
111
112    Before reload, speculative insns are moved only if a 'proof' exists
113    that no exception will be caused by this, and if no live registers
114    exist that inhibit the motion (live registers constraints are not
115    represented by data dependence edges).
116
117    This pass must update information that subsequent passes expect to
118    be correct.  Namely: reg_n_refs, reg_n_sets, reg_n_deaths,
119    reg_n_calls_crossed, and reg_live_length.  Also, BB_HEAD, BB_END.
120
121    The information in the line number notes is carefully retained by
122    this pass.  Notes that refer to the starting and ending of
123    exception regions are also carefully retained by this pass.  All
124    other NOTE insns are grouped in their same relative order at the
125    beginning of basic blocks and regions that have been scheduled.  */
126 \f
127 #include "config.h"
128 #include "system.h"
129 #include "coretypes.h"
130 #include "tm.h"
131 #include "diagnostic-core.h"
132 #include "rtl.h"
133 #include "tm_p.h"
134 #include "hard-reg-set.h"
135 #include "regs.h"
136 #include "function.h"
137 #include "flags.h"
138 #include "insn-config.h"
139 #include "insn-attr.h"
140 #include "except.h"
141 #include "recog.h"
142 #include "sched-int.h"
143 #include "target.h"
144 #include "output.h"
145 #include "params.h"
146 #include "vecprim.h"
147 #include "dbgcnt.h"
148 #include "cfgloop.h"
149 #include "ira.h"
150 #include "emit-rtl.h"  /* FIXME: Can go away once crtl is moved to rtl.h.  */
151
152 #ifdef INSN_SCHEDULING
153
154 /* issue_rate is the number of insns that can be scheduled in the same
155    machine cycle.  It can be defined in the config/mach/mach.h file,
156    otherwise we set it to 1.  */
157
158 int issue_rate;
159
160 /* sched-verbose controls the amount of debugging output the
161    scheduler prints.  It is controlled by -fsched-verbose=N:
162    N>0 and no -DSR : the output is directed to stderr.
163    N>=10 will direct the printouts to stderr (regardless of -dSR).
164    N=1: same as -dSR.
165    N=2: bb's probabilities, detailed ready list info, unit/insn info.
166    N=3: rtl at abort point, control-flow, regions info.
167    N=5: dependences info.  */
168
169 int sched_verbose = 0;
170
171 /* Debugging file.  All printouts are sent to dump, which is always set,
172    either to stderr, or to the dump listing file (-dRS).  */
173 FILE *sched_dump = 0;
174
175 /* This is a placeholder for the scheduler parameters common
176    to all schedulers.  */
177 struct common_sched_info_def *common_sched_info;
178
179 #define INSN_TICK(INSN) (HID (INSN)->tick)
180 #define INTER_TICK(INSN) (HID (INSN)->inter_tick)
181
182 /* If INSN_TICK of an instruction is equal to INVALID_TICK,
183    then it should be recalculated from scratch.  */
184 #define INVALID_TICK (-(max_insn_queue_index + 1))
185 /* The minimal value of the INSN_TICK of an instruction.  */
186 #define MIN_TICK (-max_insn_queue_index)
187
188 /* List of important notes we must keep around.  This is a pointer to the
189    last element in the list.  */
190 rtx note_list;
191
192 static struct spec_info_def spec_info_var;
193 /* Description of the speculative part of the scheduling.
194    If NULL - no speculation.  */
195 spec_info_t spec_info = NULL;
196
197 /* True, if recovery block was added during scheduling of current block.
198    Used to determine, if we need to fix INSN_TICKs.  */
199 static bool haifa_recovery_bb_recently_added_p;
200
201 /* True, if recovery block was added during this scheduling pass.
202    Used to determine if we should have empty memory pools of dependencies
203    after finishing current region.  */
204 bool haifa_recovery_bb_ever_added_p;
205
206 /* Counters of different types of speculative instructions.  */
207 static int nr_begin_data, nr_be_in_data, nr_begin_control, nr_be_in_control;
208
209 /* Array used in {unlink, restore}_bb_notes.  */
210 static rtx *bb_header = 0;
211
212 /* Basic block after which recovery blocks will be created.  */
213 static basic_block before_recovery;
214
215 /* Basic block just before the EXIT_BLOCK and after recovery, if we have
216    created it.  */
217 basic_block after_recovery;
218
219 /* FALSE if we add bb to another region, so we don't need to initialize it.  */
220 bool adding_bb_to_current_region_p = true;
221
222 /* Queues, etc.  */
223
224 /* An instruction is ready to be scheduled when all insns preceding it
225    have already been scheduled.  It is important to ensure that all
226    insns which use its result will not be executed until its result
227    has been computed.  An insn is maintained in one of four structures:
228
229    (P) the "Pending" set of insns which cannot be scheduled until
230    their dependencies have been satisfied.
231    (Q) the "Queued" set of insns that can be scheduled when sufficient
232    time has passed.
233    (R) the "Ready" list of unscheduled, uncommitted insns.
234    (S) the "Scheduled" list of insns.
235
236    Initially, all insns are either "Pending" or "Ready" depending on
237    whether their dependencies are satisfied.
238
239    Insns move from the "Ready" list to the "Scheduled" list as they
240    are committed to the schedule.  As this occurs, the insns in the
241    "Pending" list have their dependencies satisfied and move to either
242    the "Ready" list or the "Queued" set depending on whether
243    sufficient time has passed to make them ready.  As time passes,
244    insns move from the "Queued" set to the "Ready" list.
245
246    The "Pending" list (P) are the insns in the INSN_FORW_DEPS of the
247    unscheduled insns, i.e., those that are ready, queued, and pending.
248    The "Queued" set (Q) is implemented by the variable `insn_queue'.
249    The "Ready" list (R) is implemented by the variables `ready' and
250    `n_ready'.
251    The "Scheduled" list (S) is the new insn chain built by this pass.
252
253    The transition (R->S) is implemented in the scheduling loop in
254    `schedule_block' when the best insn to schedule is chosen.
255    The transitions (P->R and P->Q) are implemented in `schedule_insn' as
256    insns move from the ready list to the scheduled list.
257    The transition (Q->R) is implemented in 'queue_to_insn' as time
258    passes or stalls are introduced.  */
259
260 /* Implement a circular buffer to delay instructions until sufficient
261    time has passed.  For the new pipeline description interface,
262    MAX_INSN_QUEUE_INDEX is a power of two minus one which is not less
263    than maximal time of instruction execution computed by genattr.c on
264    the base maximal time of functional unit reservations and getting a
265    result.  This is the longest time an insn may be queued.  */
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 #define QUEUE_SCHEDULED (-3)
274 #define QUEUE_NOWHERE   (-2)
275 #define QUEUE_READY     (-1)
276 /* QUEUE_SCHEDULED - INSN is scheduled.
277    QUEUE_NOWHERE   - INSN isn't scheduled yet and is neither in
278    queue or ready list.
279    QUEUE_READY     - INSN is in ready list.
280    N >= 0 - INSN queued for X [where NEXT_Q_AFTER (q_ptr, X) == N] cycles.  */
281
282 #define QUEUE_INDEX(INSN) (HID (INSN)->queue_index)
283
284 /* The following variable value refers for all current and future
285    reservations of the processor units.  */
286 state_t curr_state;
287
288 /* The following variable value is size of memory representing all
289    current and future reservations of the processor units.  */
290 size_t dfa_state_size;
291
292 /* The following array is used to find the best insn from ready when
293    the automaton pipeline interface is used.  */
294 char *ready_try = NULL;
295
296 /* The ready list.  */
297 struct ready_list ready = {NULL, 0, 0, 0, 0};
298
299 /* The pointer to the ready list (to be removed).  */
300 static struct ready_list *readyp = &ready;
301
302 /* Scheduling clock.  */
303 static int clock_var;
304
305 /* This records the actual schedule.  It is built up during the main phase
306    of schedule_block, and afterwards used to reorder the insns in the RTL.  */
307 static VEC(rtx, heap) *scheduled_insns;
308
309 static int may_trap_exp (const_rtx, int);
310
311 /* Nonzero iff the address is comprised from at most 1 register.  */
312 #define CONST_BASED_ADDRESS_P(x)                        \
313   (REG_P (x)                                    \
314    || ((GET_CODE (x) == PLUS || GET_CODE (x) == MINUS   \
315         || (GET_CODE (x) == LO_SUM))                    \
316        && (CONSTANT_P (XEXP (x, 0))                     \
317            || CONSTANT_P (XEXP (x, 1)))))
318
319 /* Returns a class that insn with GET_DEST(insn)=x may belong to,
320    as found by analyzing insn's expression.  */
321
322 \f
323 static int haifa_luid_for_non_insn (rtx x);
324
325 /* Haifa version of sched_info hooks common to all headers.  */
326 const struct common_sched_info_def haifa_common_sched_info =
327   {
328     NULL, /* fix_recovery_cfg */
329     NULL, /* add_block */
330     NULL, /* estimate_number_of_insns */
331     haifa_luid_for_non_insn, /* luid_for_non_insn */
332     SCHED_PASS_UNKNOWN /* sched_pass_id */
333   };
334
335 const struct sched_scan_info_def *sched_scan_info;
336
337 /* Mapping from instruction UID to its Logical UID.  */
338 VEC (int, heap) *sched_luids = NULL;
339
340 /* Next LUID to assign to an instruction.  */
341 int sched_max_luid = 1;
342
343 /* Haifa Instruction Data.  */
344 VEC (haifa_insn_data_def, heap) *h_i_d = NULL;
345
346 void (* sched_init_only_bb) (basic_block, basic_block);
347
348 /* Split block function.  Different schedulers might use different functions
349    to handle their internal data consistent.  */
350 basic_block (* sched_split_block) (basic_block, rtx);
351
352 /* Create empty basic block after the specified block.  */
353 basic_block (* sched_create_empty_bb) (basic_block);
354
355 static int
356 may_trap_exp (const_rtx x, int is_store)
357 {
358   enum rtx_code code;
359
360   if (x == 0)
361     return TRAP_FREE;
362   code = GET_CODE (x);
363   if (is_store)
364     {
365       if (code == MEM && may_trap_p (x))
366         return TRAP_RISKY;
367       else
368         return TRAP_FREE;
369     }
370   if (code == MEM)
371     {
372       /* The insn uses memory:  a volatile load.  */
373       if (MEM_VOLATILE_P (x))
374         return IRISKY;
375       /* An exception-free load.  */
376       if (!may_trap_p (x))
377         return IFREE;
378       /* A load with 1 base register, to be further checked.  */
379       if (CONST_BASED_ADDRESS_P (XEXP (x, 0)))
380         return PFREE_CANDIDATE;
381       /* No info on the load, to be further checked.  */
382       return PRISKY_CANDIDATE;
383     }
384   else
385     {
386       const char *fmt;
387       int i, insn_class = TRAP_FREE;
388
389       /* Neither store nor load, check if it may cause a trap.  */
390       if (may_trap_p (x))
391         return TRAP_RISKY;
392       /* Recursive step: walk the insn...  */
393       fmt = GET_RTX_FORMAT (code);
394       for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
395         {
396           if (fmt[i] == 'e')
397             {
398               int tmp_class = may_trap_exp (XEXP (x, i), is_store);
399               insn_class = WORST_CLASS (insn_class, tmp_class);
400             }
401           else if (fmt[i] == 'E')
402             {
403               int j;
404               for (j = 0; j < XVECLEN (x, i); j++)
405                 {
406                   int tmp_class = may_trap_exp (XVECEXP (x, i, j), is_store);
407                   insn_class = WORST_CLASS (insn_class, tmp_class);
408                   if (insn_class == TRAP_RISKY || insn_class == IRISKY)
409                     break;
410                 }
411             }
412           if (insn_class == TRAP_RISKY || insn_class == IRISKY)
413             break;
414         }
415       return insn_class;
416     }
417 }
418
419 /* Classifies rtx X of an insn for the purpose of verifying that X can be
420    executed speculatively (and consequently the insn can be moved
421    speculatively), by examining X, returning:
422    TRAP_RISKY: store, or risky non-load insn (e.g. division by variable).
423    TRAP_FREE: non-load insn.
424    IFREE: load from a globally safe location.
425    IRISKY: volatile load.
426    PFREE_CANDIDATE, PRISKY_CANDIDATE: load that need to be checked for
427    being either PFREE or PRISKY.  */
428
429 static int
430 haifa_classify_rtx (const_rtx x)
431 {
432   int tmp_class = TRAP_FREE;
433   int insn_class = TRAP_FREE;
434   enum rtx_code code;
435
436   if (GET_CODE (x) == PARALLEL)
437     {
438       int i, len = XVECLEN (x, 0);
439
440       for (i = len - 1; i >= 0; i--)
441         {
442           tmp_class = haifa_classify_rtx (XVECEXP (x, 0, i));
443           insn_class = WORST_CLASS (insn_class, tmp_class);
444           if (insn_class == TRAP_RISKY || insn_class == IRISKY)
445             break;
446         }
447     }
448   else
449     {
450       code = GET_CODE (x);
451       switch (code)
452         {
453         case CLOBBER:
454           /* Test if it is a 'store'.  */
455           tmp_class = may_trap_exp (XEXP (x, 0), 1);
456           break;
457         case SET:
458           /* Test if it is a store.  */
459           tmp_class = may_trap_exp (SET_DEST (x), 1);
460           if (tmp_class == TRAP_RISKY)
461             break;
462           /* Test if it is a load.  */
463           tmp_class =
464             WORST_CLASS (tmp_class,
465                          may_trap_exp (SET_SRC (x), 0));
466           break;
467         case COND_EXEC:
468           tmp_class = haifa_classify_rtx (COND_EXEC_CODE (x));
469           if (tmp_class == TRAP_RISKY)
470             break;
471           tmp_class = WORST_CLASS (tmp_class,
472                                    may_trap_exp (COND_EXEC_TEST (x), 0));
473           break;
474         case TRAP_IF:
475           tmp_class = TRAP_RISKY;
476           break;
477         default:;
478         }
479       insn_class = tmp_class;
480     }
481
482   return insn_class;
483 }
484
485 int
486 haifa_classify_insn (const_rtx insn)
487 {
488   return haifa_classify_rtx (PATTERN (insn));
489 }
490
491 /* Forward declarations.  */
492
493 static int priority (rtx);
494 static int rank_for_schedule (const void *, const void *);
495 static void swap_sort (rtx *, int);
496 static void queue_insn (rtx, int, const char *);
497 static int schedule_insn (rtx);
498 static void adjust_priority (rtx);
499 static void advance_one_cycle (void);
500 static void extend_h_i_d (void);
501
502
503 /* Notes handling mechanism:
504    =========================
505    Generally, NOTES are saved before scheduling and restored after scheduling.
506    The scheduler distinguishes between two types of notes:
507
508    (1) LOOP_BEGIN, LOOP_END, SETJMP, EHREGION_BEG, EHREGION_END notes:
509    Before scheduling a region, a pointer to the note is added to the insn
510    that follows or precedes it.  (This happens as part of the data dependence
511    computation).  After scheduling an insn, the pointer contained in it is
512    used for regenerating the corresponding note (in reemit_notes).
513
514    (2) All other notes (e.g. INSN_DELETED):  Before scheduling a block,
515    these notes are put in a list (in rm_other_notes() and
516    unlink_other_notes ()).  After scheduling the block, these notes are
517    inserted at the beginning of the block (in schedule_block()).  */
518
519 static void ready_add (struct ready_list *, rtx, bool);
520 static rtx ready_remove_first (struct ready_list *);
521 static rtx ready_remove_first_dispatch (struct ready_list *ready);
522
523 static void queue_to_ready (struct ready_list *);
524 static int early_queue_to_ready (state_t, struct ready_list *);
525
526 static void debug_ready_list (struct ready_list *);
527
528 /* The following functions are used to implement multi-pass scheduling
529    on the first cycle.  */
530 static rtx ready_remove (struct ready_list *, int);
531 static void ready_remove_insn (rtx);
532
533 static void fix_inter_tick (rtx, rtx);
534 static int fix_tick_ready (rtx);
535 static void change_queue_index (rtx, int);
536
537 /* The following functions are used to implement scheduling of data/control
538    speculative instructions.  */
539
540 static void extend_h_i_d (void);
541 static void init_h_i_d (rtx);
542 static void generate_recovery_code (rtx);
543 static void process_insn_forw_deps_be_in_spec (rtx, rtx, ds_t);
544 static void begin_speculative_block (rtx);
545 static void add_to_speculative_block (rtx);
546 static void init_before_recovery (basic_block *);
547 static void create_check_block_twin (rtx, bool);
548 static void fix_recovery_deps (basic_block);
549 static void haifa_change_pattern (rtx, rtx);
550 static void dump_new_block_header (int, basic_block, rtx, rtx);
551 static void restore_bb_notes (basic_block);
552 static void fix_jump_move (rtx);
553 static void move_block_after_check (rtx);
554 static void move_succs (VEC(edge,gc) **, basic_block);
555 static void sched_remove_insn (rtx);
556 static void clear_priorities (rtx, rtx_vec_t *);
557 static void calc_priorities (rtx_vec_t);
558 static void add_jump_dependencies (rtx, rtx);
559 #ifdef ENABLE_CHECKING
560 static int has_edge_p (VEC(edge,gc) *, int);
561 static void check_cfg (rtx, rtx);
562 #endif
563
564 #endif /* INSN_SCHEDULING */
565 \f
566 /* Point to state used for the current scheduling pass.  */
567 struct haifa_sched_info *current_sched_info;
568 \f
569 #ifndef INSN_SCHEDULING
570 void
571 schedule_insns (void)
572 {
573 }
574 #else
575
576 /* Do register pressure sensitive insn scheduling if the flag is set
577    up.  */
578 bool sched_pressure_p;
579
580 /* Map regno -> its pressure class.  The map defined only when
581    SCHED_PRESSURE_P is true.  */
582 enum reg_class *sched_regno_pressure_class;
583
584 /* The current register pressure.  Only elements corresponding pressure
585    classes are defined.  */
586 static int curr_reg_pressure[N_REG_CLASSES];
587
588 /* Saved value of the previous array.  */
589 static int saved_reg_pressure[N_REG_CLASSES];
590
591 /* Register living at given scheduling point.  */
592 static bitmap curr_reg_live;
593
594 /* Saved value of the previous array.  */
595 static bitmap saved_reg_live;
596
597 /* Registers mentioned in the current region.  */
598 static bitmap region_ref_regs;
599
600 /* Initiate register pressure relative info for scheduling the current
601    region.  Currently it is only clearing register mentioned in the
602    current region.  */
603 void
604 sched_init_region_reg_pressure_info (void)
605 {
606   bitmap_clear (region_ref_regs);
607 }
608
609 /* Update current register pressure related info after birth (if
610    BIRTH_P) or death of register REGNO.  */
611 static void
612 mark_regno_birth_or_death (int regno, bool birth_p)
613 {
614   enum reg_class pressure_class;
615
616   pressure_class = sched_regno_pressure_class[regno];
617   if (regno >= FIRST_PSEUDO_REGISTER)
618     {
619       if (pressure_class != NO_REGS)
620         {
621           if (birth_p)
622             {
623               bitmap_set_bit (curr_reg_live, regno);
624               curr_reg_pressure[pressure_class]
625                 += (ira_reg_class_max_nregs
626                     [pressure_class][PSEUDO_REGNO_MODE (regno)]);
627             }
628           else
629             {
630               bitmap_clear_bit (curr_reg_live, regno);
631               curr_reg_pressure[pressure_class]
632                 -= (ira_reg_class_max_nregs
633                     [pressure_class][PSEUDO_REGNO_MODE (regno)]);
634             }
635         }
636     }
637   else if (pressure_class != NO_REGS
638            && ! TEST_HARD_REG_BIT (ira_no_alloc_regs, regno))
639     {
640       if (birth_p)
641         {
642           bitmap_set_bit (curr_reg_live, regno);
643           curr_reg_pressure[pressure_class]++;
644         }
645       else
646         {
647           bitmap_clear_bit (curr_reg_live, regno);
648           curr_reg_pressure[pressure_class]--;
649         }
650     }
651 }
652
653 /* Initiate current register pressure related info from living
654    registers given by LIVE.  */
655 static void
656 initiate_reg_pressure_info (bitmap live)
657 {
658   int i;
659   unsigned int j;
660   bitmap_iterator bi;
661
662   for (i = 0; i < ira_pressure_classes_num; i++)
663     curr_reg_pressure[ira_pressure_classes[i]] = 0;
664   bitmap_clear (curr_reg_live);
665   EXECUTE_IF_SET_IN_BITMAP (live, 0, j, bi)
666     if (current_nr_blocks == 1 || bitmap_bit_p (region_ref_regs, j))
667       mark_regno_birth_or_death (j, true);
668 }
669
670 /* Mark registers in X as mentioned in the current region.  */
671 static void
672 setup_ref_regs (rtx x)
673 {
674   int i, j, regno;
675   const RTX_CODE code = GET_CODE (x);
676   const char *fmt;
677
678   if (REG_P (x))
679     {
680       regno = REGNO (x);
681       if (HARD_REGISTER_NUM_P (regno))
682         bitmap_set_range (region_ref_regs, regno,
683                           hard_regno_nregs[regno][GET_MODE (x)]);
684       else
685         bitmap_set_bit (region_ref_regs, REGNO (x));
686       return;
687     }
688   fmt = GET_RTX_FORMAT (code);
689   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
690     if (fmt[i] == 'e')
691       setup_ref_regs (XEXP (x, i));
692     else if (fmt[i] == 'E')
693       {
694         for (j = 0; j < XVECLEN (x, i); j++)
695           setup_ref_regs (XVECEXP (x, i, j));
696       }
697 }
698
699 /* Initiate current register pressure related info at the start of
700    basic block BB.  */
701 static void
702 initiate_bb_reg_pressure_info (basic_block bb)
703 {
704   unsigned int i ATTRIBUTE_UNUSED;
705   rtx insn;
706
707   if (current_nr_blocks > 1)
708     FOR_BB_INSNS (bb, insn)
709       if (NONDEBUG_INSN_P (insn))
710         setup_ref_regs (PATTERN (insn));
711   initiate_reg_pressure_info (df_get_live_in (bb));
712 #ifdef EH_RETURN_DATA_REGNO
713   if (bb_has_eh_pred (bb))
714     for (i = 0; ; ++i)
715       {
716         unsigned int regno = EH_RETURN_DATA_REGNO (i);
717
718         if (regno == INVALID_REGNUM)
719           break;
720         if (! bitmap_bit_p (df_get_live_in (bb), regno))
721           mark_regno_birth_or_death (regno, true);
722       }
723 #endif
724 }
725
726 /* Save current register pressure related info.  */
727 static void
728 save_reg_pressure (void)
729 {
730   int i;
731
732   for (i = 0; i < ira_pressure_classes_num; i++)
733     saved_reg_pressure[ira_pressure_classes[i]]
734       = curr_reg_pressure[ira_pressure_classes[i]];
735   bitmap_copy (saved_reg_live, curr_reg_live);
736 }
737
738 /* Restore saved register pressure related info.  */
739 static void
740 restore_reg_pressure (void)
741 {
742   int i;
743
744   for (i = 0; i < ira_pressure_classes_num; i++)
745     curr_reg_pressure[ira_pressure_classes[i]]
746       = saved_reg_pressure[ira_pressure_classes[i]];
747   bitmap_copy (curr_reg_live, saved_reg_live);
748 }
749
750 /* Return TRUE if the register is dying after its USE.  */
751 static bool
752 dying_use_p (struct reg_use_data *use)
753 {
754   struct reg_use_data *next;
755
756   for (next = use->next_regno_use; next != use; next = next->next_regno_use)
757     if (NONDEBUG_INSN_P (next->insn)
758         && QUEUE_INDEX (next->insn) != QUEUE_SCHEDULED)
759       return false;
760   return true;
761 }
762
763 /* Print info about the current register pressure and its excess for
764    each pressure class.  */
765 static void
766 print_curr_reg_pressure (void)
767 {
768   int i;
769   enum reg_class cl;
770
771   fprintf (sched_dump, ";;\t");
772   for (i = 0; i < ira_pressure_classes_num; i++)
773     {
774       cl = ira_pressure_classes[i];
775       gcc_assert (curr_reg_pressure[cl] >= 0);
776       fprintf (sched_dump, "  %s:%d(%d)", reg_class_names[cl],
777                curr_reg_pressure[cl],
778                curr_reg_pressure[cl] - ira_available_class_regs[cl]);
779     }
780   fprintf (sched_dump, "\n");
781 }
782
783 /* Pointer to the last instruction scheduled.  */
784 static rtx last_scheduled_insn;
785
786 /* Pointer to the last nondebug instruction scheduled within the
787    block, or the prev_head of the scheduling block.  Used by
788    rank_for_schedule, so that insns independent of the last scheduled
789    insn will be preferred over dependent instructions.  */
790 static rtx last_nondebug_scheduled_insn;
791
792 /* Pointer that iterates through the list of unscheduled insns if we
793    have a dbg_cnt enabled.  It always points at an insn prior to the
794    first unscheduled one.  */
795 static rtx nonscheduled_insns_begin;
796
797 /* Cached cost of the instruction.  Use below function to get cost of the
798    insn.  -1 here means that the field is not initialized.  */
799 #define INSN_COST(INSN) (HID (INSN)->cost)
800
801 /* Compute cost of executing INSN.
802    This is the number of cycles between instruction issue and
803    instruction results.  */
804 int
805 insn_cost (rtx insn)
806 {
807   int cost;
808
809   if (sel_sched_p ())
810     {
811       if (recog_memoized (insn) < 0)
812         return 0;
813
814       cost = insn_default_latency (insn);
815       if (cost < 0)
816         cost = 0;
817
818       return cost;
819     }
820
821   cost = INSN_COST (insn);
822
823   if (cost < 0)
824     {
825       /* A USE insn, or something else we don't need to
826          understand.  We can't pass these directly to
827          result_ready_cost or insn_default_latency because it will
828          trigger a fatal error for unrecognizable insns.  */
829       if (recog_memoized (insn) < 0)
830         {
831           INSN_COST (insn) = 0;
832           return 0;
833         }
834       else
835         {
836           cost = insn_default_latency (insn);
837           if (cost < 0)
838             cost = 0;
839
840           INSN_COST (insn) = cost;
841         }
842     }
843
844   return cost;
845 }
846
847 /* Compute cost of dependence LINK.
848    This is the number of cycles between instruction issue and
849    instruction results.
850    ??? We also use this function to call recog_memoized on all insns.  */
851 int
852 dep_cost_1 (dep_t link, dw_t dw)
853 {
854   rtx insn = DEP_PRO (link);
855   rtx used = DEP_CON (link);
856   int cost;
857
858   /* A USE insn should never require the value used to be computed.
859      This allows the computation of a function's result and parameter
860      values to overlap the return and call.  We don't care about the
861      dependence cost when only decreasing register pressure.  */
862   if (recog_memoized (used) < 0)
863     {
864       cost = 0;
865       recog_memoized (insn);
866     }
867   else
868     {
869       enum reg_note dep_type = DEP_TYPE (link);
870
871       cost = insn_cost (insn);
872
873       if (INSN_CODE (insn) >= 0)
874         {
875           if (dep_type == REG_DEP_ANTI)
876             cost = 0;
877           else if (dep_type == REG_DEP_OUTPUT)
878             {
879               cost = (insn_default_latency (insn)
880                       - insn_default_latency (used));
881               if (cost <= 0)
882                 cost = 1;
883             }
884           else if (bypass_p (insn))
885             cost = insn_latency (insn, used);
886         }
887
888
889       if (targetm.sched.adjust_cost_2)
890         cost = targetm.sched.adjust_cost_2 (used, (int) dep_type, insn, cost,
891                                             dw);
892       else if (targetm.sched.adjust_cost != NULL)
893         {
894           /* This variable is used for backward compatibility with the
895              targets.  */
896           rtx dep_cost_rtx_link = alloc_INSN_LIST (NULL_RTX, NULL_RTX);
897
898           /* Make it self-cycled, so that if some tries to walk over this
899              incomplete list he/she will be caught in an endless loop.  */
900           XEXP (dep_cost_rtx_link, 1) = dep_cost_rtx_link;
901
902           /* Targets use only REG_NOTE_KIND of the link.  */
903           PUT_REG_NOTE_KIND (dep_cost_rtx_link, DEP_TYPE (link));
904
905           cost = targetm.sched.adjust_cost (used, dep_cost_rtx_link,
906                                             insn, cost);
907
908           free_INSN_LIST_node (dep_cost_rtx_link);
909         }
910
911       if (cost < 0)
912         cost = 0;
913     }
914
915   return cost;
916 }
917
918 /* Compute cost of dependence LINK.
919    This is the number of cycles between instruction issue and
920    instruction results.  */
921 int
922 dep_cost (dep_t link)
923 {
924   return dep_cost_1 (link, 0);
925 }
926
927 /* Use this sel-sched.c friendly function in reorder2 instead of increasing
928    INSN_PRIORITY explicitly.  */
929 void
930 increase_insn_priority (rtx insn, int amount)
931 {
932   if (!sel_sched_p ())
933     {
934       /* We're dealing with haifa-sched.c INSN_PRIORITY.  */
935       if (INSN_PRIORITY_KNOWN (insn))
936           INSN_PRIORITY (insn) += amount;
937     }
938   else
939     {
940       /* In sel-sched.c INSN_PRIORITY is not kept up to date.
941          Use EXPR_PRIORITY instead. */
942       sel_add_to_insn_priority (insn, amount);
943     }
944 }
945
946 /* Return 'true' if DEP should be included in priority calculations.  */
947 static bool
948 contributes_to_priority_p (dep_t dep)
949 {
950   if (DEBUG_INSN_P (DEP_CON (dep))
951       || DEBUG_INSN_P (DEP_PRO (dep)))
952     return false;
953
954   /* Critical path is meaningful in block boundaries only.  */
955   if (!current_sched_info->contributes_to_priority (DEP_CON (dep),
956                                                     DEP_PRO (dep)))
957     return false;
958
959   /* If flag COUNT_SPEC_IN_CRITICAL_PATH is set,
960      then speculative instructions will less likely be
961      scheduled.  That is because the priority of
962      their producers will increase, and, thus, the
963      producers will more likely be scheduled, thus,
964      resolving the dependence.  */
965   if (sched_deps_info->generate_spec_deps
966       && !(spec_info->flags & COUNT_SPEC_IN_CRITICAL_PATH)
967       && (DEP_STATUS (dep) & SPECULATIVE))
968     return false;
969
970   return true;
971 }
972
973 /* Compute the number of nondebug forward deps of an insn.  */
974
975 static int
976 dep_list_size (rtx insn)
977 {
978   sd_iterator_def sd_it;
979   dep_t dep;
980   int dbgcount = 0, nodbgcount = 0;
981
982   if (!MAY_HAVE_DEBUG_INSNS)
983     return sd_lists_size (insn, SD_LIST_FORW);
984
985   FOR_EACH_DEP (insn, SD_LIST_FORW, sd_it, dep)
986     {
987       if (DEBUG_INSN_P (DEP_CON (dep)))
988         dbgcount++;
989       else if (!DEBUG_INSN_P (DEP_PRO (dep)))
990         nodbgcount++;
991     }
992
993   gcc_assert (dbgcount + nodbgcount == sd_lists_size (insn, SD_LIST_FORW));
994
995   return nodbgcount;
996 }
997
998 /* Compute the priority number for INSN.  */
999 static int
1000 priority (rtx insn)
1001 {
1002   if (! INSN_P (insn))
1003     return 0;
1004
1005   /* We should not be interested in priority of an already scheduled insn.  */
1006   gcc_assert (QUEUE_INDEX (insn) != QUEUE_SCHEDULED);
1007
1008   if (!INSN_PRIORITY_KNOWN (insn))
1009     {
1010       int this_priority = -1;
1011
1012       if (dep_list_size (insn) == 0)
1013         /* ??? We should set INSN_PRIORITY to insn_cost when and insn has
1014            some forward deps but all of them are ignored by
1015            contributes_to_priority hook.  At the moment we set priority of
1016            such insn to 0.  */
1017         this_priority = insn_cost (insn);
1018       else
1019         {
1020           rtx prev_first, twin;
1021           basic_block rec;
1022
1023           /* For recovery check instructions we calculate priority slightly
1024              different than that of normal instructions.  Instead of walking
1025              through INSN_FORW_DEPS (check) list, we walk through
1026              INSN_FORW_DEPS list of each instruction in the corresponding
1027              recovery block.  */
1028
1029           /* Selective scheduling does not define RECOVERY_BLOCK macro.  */
1030           rec = sel_sched_p () ? NULL : RECOVERY_BLOCK (insn);
1031           if (!rec || rec == EXIT_BLOCK_PTR)
1032             {
1033               prev_first = PREV_INSN (insn);
1034               twin = insn;
1035             }
1036           else
1037             {
1038               prev_first = NEXT_INSN (BB_HEAD (rec));
1039               twin = PREV_INSN (BB_END (rec));
1040             }
1041
1042           do
1043             {
1044               sd_iterator_def sd_it;
1045               dep_t dep;
1046
1047               FOR_EACH_DEP (twin, SD_LIST_FORW, sd_it, dep)
1048                 {
1049                   rtx next;
1050                   int next_priority;
1051
1052                   next = DEP_CON (dep);
1053
1054                   if (BLOCK_FOR_INSN (next) != rec)
1055                     {
1056                       int cost;
1057
1058                       if (!contributes_to_priority_p (dep))
1059                         continue;
1060
1061                       if (twin == insn)
1062                         cost = dep_cost (dep);
1063                       else
1064                         {
1065                           struct _dep _dep1, *dep1 = &_dep1;
1066
1067                           init_dep (dep1, insn, next, REG_DEP_ANTI);
1068
1069                           cost = dep_cost (dep1);
1070                         }
1071
1072                       next_priority = cost + priority (next);
1073
1074                       if (next_priority > this_priority)
1075                         this_priority = next_priority;
1076                     }
1077                 }
1078
1079               twin = PREV_INSN (twin);
1080             }
1081           while (twin != prev_first);
1082         }
1083
1084       if (this_priority < 0)
1085         {
1086           gcc_assert (this_priority == -1);
1087
1088           this_priority = insn_cost (insn);
1089         }
1090
1091       INSN_PRIORITY (insn) = this_priority;
1092       INSN_PRIORITY_STATUS (insn) = 1;
1093     }
1094
1095   return INSN_PRIORITY (insn);
1096 }
1097 \f
1098 /* Macros and functions for keeping the priority queue sorted, and
1099    dealing with queuing and dequeuing of instructions.  */
1100
1101 #define SCHED_SORT(READY, N_READY)                                   \
1102 do { if ((N_READY) == 2)                                             \
1103        swap_sort (READY, N_READY);                                   \
1104      else if ((N_READY) > 2)                                         \
1105          qsort (READY, N_READY, sizeof (rtx), rank_for_schedule); }  \
1106 while (0)
1107
1108 /* Setup info about the current register pressure impact of scheduling
1109    INSN at the current scheduling point.  */
1110 static void
1111 setup_insn_reg_pressure_info (rtx insn)
1112 {
1113   int i, change, before, after, hard_regno;
1114   int excess_cost_change;
1115   enum machine_mode mode;
1116   enum reg_class cl;
1117   struct reg_pressure_data *pressure_info;
1118   int *max_reg_pressure;
1119   struct reg_use_data *use;
1120   static int death[N_REG_CLASSES];
1121
1122   gcc_checking_assert (!DEBUG_INSN_P (insn));
1123
1124   excess_cost_change = 0;
1125   for (i = 0; i < ira_pressure_classes_num; i++)
1126     death[ira_pressure_classes[i]] = 0;
1127   for (use = INSN_REG_USE_LIST (insn); use != NULL; use = use->next_insn_use)
1128     if (dying_use_p (use))
1129       {
1130         cl = sched_regno_pressure_class[use->regno];
1131         if (use->regno < FIRST_PSEUDO_REGISTER)
1132           death[cl]++;
1133         else
1134           death[cl]
1135             += ira_reg_class_max_nregs[cl][PSEUDO_REGNO_MODE (use->regno)];
1136       }
1137   pressure_info = INSN_REG_PRESSURE (insn);
1138   max_reg_pressure = INSN_MAX_REG_PRESSURE (insn);
1139   gcc_assert (pressure_info != NULL && max_reg_pressure != NULL);
1140   for (i = 0; i < ira_pressure_classes_num; i++)
1141     {
1142       cl = ira_pressure_classes[i];
1143       gcc_assert (curr_reg_pressure[cl] >= 0);
1144       change = (int) pressure_info[i].set_increase - death[cl];
1145       before = MAX (0, max_reg_pressure[i] - ira_available_class_regs[cl]);
1146       after = MAX (0, max_reg_pressure[i] + change
1147                    - ira_available_class_regs[cl]);
1148       hard_regno = ira_class_hard_regs[cl][0];
1149       gcc_assert (hard_regno >= 0);
1150       mode = reg_raw_mode[hard_regno];
1151       excess_cost_change += ((after - before)
1152                              * (ira_memory_move_cost[mode][cl][0]
1153                                 + ira_memory_move_cost[mode][cl][1]));
1154     }
1155   INSN_REG_PRESSURE_EXCESS_COST_CHANGE (insn) = excess_cost_change;
1156 }
1157
1158 /* Returns a positive value if x is preferred; returns a negative value if
1159    y is preferred.  Should never return 0, since that will make the sort
1160    unstable.  */
1161
1162 static int
1163 rank_for_schedule (const void *x, const void *y)
1164 {
1165   rtx tmp = *(const rtx *) y;
1166   rtx tmp2 = *(const rtx *) x;
1167   int tmp_class, tmp2_class;
1168   int val, priority_val, info_val;
1169
1170   if (MAY_HAVE_DEBUG_INSNS)
1171     {
1172       /* Schedule debug insns as early as possible.  */
1173       if (DEBUG_INSN_P (tmp) && !DEBUG_INSN_P (tmp2))
1174         return -1;
1175       else if (DEBUG_INSN_P (tmp2))
1176         return 1;
1177     }
1178
1179   /* The insn in a schedule group should be issued the first.  */
1180   if (flag_sched_group_heuristic &&
1181       SCHED_GROUP_P (tmp) != SCHED_GROUP_P (tmp2))
1182     return SCHED_GROUP_P (tmp2) ? 1 : -1;
1183
1184   /* Make sure that priority of TMP and TMP2 are initialized.  */
1185   gcc_assert (INSN_PRIORITY_KNOWN (tmp) && INSN_PRIORITY_KNOWN (tmp2));
1186
1187   if (sched_pressure_p)
1188     {
1189       int diff;
1190
1191       /* Prefer insn whose scheduling results in the smallest register
1192          pressure excess.  */
1193       if ((diff = (INSN_REG_PRESSURE_EXCESS_COST_CHANGE (tmp)
1194                    + (INSN_TICK (tmp) > clock_var
1195                       ? INSN_TICK (tmp) - clock_var : 0)
1196                    - INSN_REG_PRESSURE_EXCESS_COST_CHANGE (tmp2)
1197                    - (INSN_TICK (tmp2) > clock_var
1198                       ? INSN_TICK (tmp2) - clock_var : 0))) != 0)
1199         return diff;
1200     }
1201
1202
1203   if (sched_pressure_p
1204       && (INSN_TICK (tmp2) > clock_var || INSN_TICK (tmp) > clock_var))
1205     {
1206       if (INSN_TICK (tmp) <= clock_var)
1207         return -1;
1208       else if (INSN_TICK (tmp2) <= clock_var)
1209         return 1;
1210       else
1211         return INSN_TICK (tmp) - INSN_TICK (tmp2);
1212     }
1213   /* Prefer insn with higher priority.  */
1214   priority_val = INSN_PRIORITY (tmp2) - INSN_PRIORITY (tmp);
1215
1216   if (flag_sched_critical_path_heuristic && priority_val)
1217     return priority_val;
1218
1219   /* Prefer speculative insn with greater dependencies weakness.  */
1220   if (flag_sched_spec_insn_heuristic && spec_info)
1221     {
1222       ds_t ds1, ds2;
1223       dw_t dw1, dw2;
1224       int dw;
1225
1226       ds1 = TODO_SPEC (tmp) & SPECULATIVE;
1227       if (ds1)
1228         dw1 = ds_weak (ds1);
1229       else
1230         dw1 = NO_DEP_WEAK;
1231
1232       ds2 = TODO_SPEC (tmp2) & SPECULATIVE;
1233       if (ds2)
1234         dw2 = ds_weak (ds2);
1235       else
1236         dw2 = NO_DEP_WEAK;
1237
1238       dw = dw2 - dw1;
1239       if (dw > (NO_DEP_WEAK / 8) || dw < -(NO_DEP_WEAK / 8))
1240         return dw;
1241     }
1242
1243   info_val = (*current_sched_info->rank) (tmp, tmp2);
1244   if(flag_sched_rank_heuristic && info_val)
1245     return info_val;
1246
1247   /* Compare insns based on their relation to the last scheduled
1248      non-debug insn.  */
1249   if (flag_sched_last_insn_heuristic && last_nondebug_scheduled_insn)
1250     {
1251       dep_t dep1;
1252       dep_t dep2;
1253       rtx last = last_nondebug_scheduled_insn;
1254
1255       /* Classify the instructions into three classes:
1256          1) Data dependent on last schedule insn.
1257          2) Anti/Output dependent on last scheduled insn.
1258          3) Independent of last scheduled insn, or has latency of one.
1259          Choose the insn from the highest numbered class if different.  */
1260       dep1 = sd_find_dep_between (last, tmp, true);
1261
1262       if (dep1 == NULL || dep_cost (dep1) == 1)
1263         tmp_class = 3;
1264       else if (/* Data dependence.  */
1265                DEP_TYPE (dep1) == REG_DEP_TRUE)
1266         tmp_class = 1;
1267       else
1268         tmp_class = 2;
1269
1270       dep2 = sd_find_dep_between (last, tmp2, true);
1271
1272       if (dep2 == NULL || dep_cost (dep2)  == 1)
1273         tmp2_class = 3;
1274       else if (/* Data dependence.  */
1275                DEP_TYPE (dep2) == REG_DEP_TRUE)
1276         tmp2_class = 1;
1277       else
1278         tmp2_class = 2;
1279
1280       if ((val = tmp2_class - tmp_class))
1281         return val;
1282     }
1283
1284   /* Prefer the insn which has more later insns that depend on it.
1285      This gives the scheduler more freedom when scheduling later
1286      instructions at the expense of added register pressure.  */
1287
1288   val = (dep_list_size (tmp2) - dep_list_size (tmp));
1289
1290   if (flag_sched_dep_count_heuristic && val != 0)
1291     return val;
1292
1293   /* If insns are equally good, sort by INSN_LUID (original insn order),
1294      so that we make the sort stable.  This minimizes instruction movement,
1295      thus minimizing sched's effect on debugging and cross-jumping.  */
1296   return INSN_LUID (tmp) - INSN_LUID (tmp2);
1297 }
1298
1299 /* Resort the array A in which only element at index N may be out of order.  */
1300
1301 HAIFA_INLINE static void
1302 swap_sort (rtx *a, int n)
1303 {
1304   rtx insn = a[n - 1];
1305   int i = n - 2;
1306
1307   while (i >= 0 && rank_for_schedule (a + i, &insn) >= 0)
1308     {
1309       a[i + 1] = a[i];
1310       i -= 1;
1311     }
1312   a[i + 1] = insn;
1313 }
1314
1315 /* Add INSN to the insn queue so that it can be executed at least
1316    N_CYCLES after the currently executing insn.  Preserve insns
1317    chain for debugging purposes.  REASON will be printed in debugging
1318    output.  */
1319
1320 HAIFA_INLINE static void
1321 queue_insn (rtx insn, int n_cycles, const char *reason)
1322 {
1323   int next_q = NEXT_Q_AFTER (q_ptr, n_cycles);
1324   rtx link = alloc_INSN_LIST (insn, insn_queue[next_q]);
1325
1326   gcc_assert (n_cycles <= max_insn_queue_index);
1327   gcc_assert (!DEBUG_INSN_P (insn));
1328
1329   insn_queue[next_q] = link;
1330   q_size += 1;
1331
1332   if (sched_verbose >= 2)
1333     {
1334       fprintf (sched_dump, ";;\t\tReady-->Q: insn %s: ",
1335                (*current_sched_info->print_insn) (insn, 0));
1336
1337       fprintf (sched_dump, "queued for %d cycles (%s).\n", n_cycles, reason);
1338     }
1339
1340   QUEUE_INDEX (insn) = next_q;
1341 }
1342
1343 /* Remove INSN from queue.  */
1344 static void
1345 queue_remove (rtx insn)
1346 {
1347   gcc_assert (QUEUE_INDEX (insn) >= 0);
1348   remove_free_INSN_LIST_elem (insn, &insn_queue[QUEUE_INDEX (insn)]);
1349   q_size--;
1350   QUEUE_INDEX (insn) = QUEUE_NOWHERE;
1351 }
1352
1353 /* Return a pointer to the bottom of the ready list, i.e. the insn
1354    with the lowest priority.  */
1355
1356 rtx *
1357 ready_lastpos (struct ready_list *ready)
1358 {
1359   gcc_assert (ready->n_ready >= 1);
1360   return ready->vec + ready->first - ready->n_ready + 1;
1361 }
1362
1363 /* Add an element INSN to the ready list so that it ends up with the
1364    lowest/highest priority depending on FIRST_P.  */
1365
1366 HAIFA_INLINE static void
1367 ready_add (struct ready_list *ready, rtx insn, bool first_p)
1368 {
1369   if (!first_p)
1370     {
1371       if (ready->first == ready->n_ready)
1372         {
1373           memmove (ready->vec + ready->veclen - ready->n_ready,
1374                    ready_lastpos (ready),
1375                    ready->n_ready * sizeof (rtx));
1376           ready->first = ready->veclen - 1;
1377         }
1378       ready->vec[ready->first - ready->n_ready] = insn;
1379     }
1380   else
1381     {
1382       if (ready->first == ready->veclen - 1)
1383         {
1384           if (ready->n_ready)
1385             /* ready_lastpos() fails when called with (ready->n_ready == 0).  */
1386             memmove (ready->vec + ready->veclen - ready->n_ready - 1,
1387                      ready_lastpos (ready),
1388                      ready->n_ready * sizeof (rtx));
1389           ready->first = ready->veclen - 2;
1390         }
1391       ready->vec[++(ready->first)] = insn;
1392     }
1393
1394   ready->n_ready++;
1395   if (DEBUG_INSN_P (insn))
1396     ready->n_debug++;
1397
1398   gcc_assert (QUEUE_INDEX (insn) != QUEUE_READY);
1399   QUEUE_INDEX (insn) = QUEUE_READY;
1400 }
1401
1402 /* Remove the element with the highest priority from the ready list and
1403    return it.  */
1404
1405 HAIFA_INLINE static rtx
1406 ready_remove_first (struct ready_list *ready)
1407 {
1408   rtx t;
1409
1410   gcc_assert (ready->n_ready);
1411   t = ready->vec[ready->first--];
1412   ready->n_ready--;
1413   if (DEBUG_INSN_P (t))
1414     ready->n_debug--;
1415   /* If the queue becomes empty, reset it.  */
1416   if (ready->n_ready == 0)
1417     ready->first = ready->veclen - 1;
1418
1419   gcc_assert (QUEUE_INDEX (t) == QUEUE_READY);
1420   QUEUE_INDEX (t) = QUEUE_NOWHERE;
1421
1422   return t;
1423 }
1424
1425 /* The following code implements multi-pass scheduling for the first
1426    cycle.  In other words, we will try to choose ready insn which
1427    permits to start maximum number of insns on the same cycle.  */
1428
1429 /* Return a pointer to the element INDEX from the ready.  INDEX for
1430    insn with the highest priority is 0, and the lowest priority has
1431    N_READY - 1.  */
1432
1433 rtx
1434 ready_element (struct ready_list *ready, int index)
1435 {
1436   gcc_assert (ready->n_ready && index < ready->n_ready);
1437
1438   return ready->vec[ready->first - index];
1439 }
1440
1441 /* Remove the element INDEX from the ready list and return it.  INDEX
1442    for insn with the highest priority is 0, and the lowest priority
1443    has N_READY - 1.  */
1444
1445 HAIFA_INLINE static rtx
1446 ready_remove (struct ready_list *ready, int index)
1447 {
1448   rtx t;
1449   int i;
1450
1451   if (index == 0)
1452     return ready_remove_first (ready);
1453   gcc_assert (ready->n_ready && index < ready->n_ready);
1454   t = ready->vec[ready->first - index];
1455   ready->n_ready--;
1456   if (DEBUG_INSN_P (t))
1457     ready->n_debug--;
1458   for (i = index; i < ready->n_ready; i++)
1459     ready->vec[ready->first - i] = ready->vec[ready->first - i - 1];
1460   QUEUE_INDEX (t) = QUEUE_NOWHERE;
1461   return t;
1462 }
1463
1464 /* Remove INSN from the ready list.  */
1465 static void
1466 ready_remove_insn (rtx insn)
1467 {
1468   int i;
1469
1470   for (i = 0; i < readyp->n_ready; i++)
1471     if (ready_element (readyp, i) == insn)
1472       {
1473         ready_remove (readyp, i);
1474         return;
1475       }
1476   gcc_unreachable ();
1477 }
1478
1479 /* Sort the ready list READY by ascending priority, using the SCHED_SORT
1480    macro.  */
1481
1482 void
1483 ready_sort (struct ready_list *ready)
1484 {
1485   int i;
1486   rtx *first = ready_lastpos (ready);
1487
1488   if (sched_pressure_p)
1489     {
1490       for (i = 0; i < ready->n_ready; i++)
1491         if (!DEBUG_INSN_P (first[i]))
1492           setup_insn_reg_pressure_info (first[i]);
1493     }
1494   SCHED_SORT (first, ready->n_ready);
1495 }
1496
1497 /* PREV is an insn that is ready to execute.  Adjust its priority if that
1498    will help shorten or lengthen register lifetimes as appropriate.  Also
1499    provide a hook for the target to tweak itself.  */
1500
1501 HAIFA_INLINE static void
1502 adjust_priority (rtx prev)
1503 {
1504   /* ??? There used to be code here to try and estimate how an insn
1505      affected register lifetimes, but it did it by looking at REG_DEAD
1506      notes, which we removed in schedule_region.  Nor did it try to
1507      take into account register pressure or anything useful like that.
1508
1509      Revisit when we have a machine model to work with and not before.  */
1510
1511   if (targetm.sched.adjust_priority)
1512     INSN_PRIORITY (prev) =
1513       targetm.sched.adjust_priority (prev, INSN_PRIORITY (prev));
1514 }
1515
1516 /* Advance DFA state STATE on one cycle.  */
1517 void
1518 advance_state (state_t state)
1519 {
1520   if (targetm.sched.dfa_pre_advance_cycle)
1521     targetm.sched.dfa_pre_advance_cycle ();
1522
1523   if (targetm.sched.dfa_pre_cycle_insn)
1524     state_transition (state,
1525                       targetm.sched.dfa_pre_cycle_insn ());
1526
1527   state_transition (state, NULL);
1528
1529   if (targetm.sched.dfa_post_cycle_insn)
1530     state_transition (state,
1531                       targetm.sched.dfa_post_cycle_insn ());
1532
1533   if (targetm.sched.dfa_post_advance_cycle)
1534     targetm.sched.dfa_post_advance_cycle ();
1535 }
1536
1537 /* Advance time on one cycle.  */
1538 HAIFA_INLINE static void
1539 advance_one_cycle (void)
1540 {
1541   advance_state (curr_state);
1542   if (sched_verbose >= 6)
1543     fprintf (sched_dump, ";;\tAdvanced a state.\n");
1544 }
1545
1546 /* Clock at which the previous instruction was issued.  */
1547 static int last_clock_var;
1548
1549 /* Update register pressure after scheduling INSN.  */
1550 static void
1551 update_register_pressure (rtx insn)
1552 {
1553   struct reg_use_data *use;
1554   struct reg_set_data *set;
1555
1556   gcc_checking_assert (!DEBUG_INSN_P (insn));
1557
1558   for (use = INSN_REG_USE_LIST (insn); use != NULL; use = use->next_insn_use)
1559     if (dying_use_p (use) && bitmap_bit_p (curr_reg_live, use->regno))
1560       mark_regno_birth_or_death (use->regno, false);
1561   for (set = INSN_REG_SET_LIST (insn); set != NULL; set = set->next_insn_set)
1562     mark_regno_birth_or_death (set->regno, true);
1563 }
1564
1565 /* Set up or update (if UPDATE_P) max register pressure (see its
1566    meaning in sched-int.h::_haifa_insn_data) for all current BB insns
1567    after insn AFTER.  */
1568 static void
1569 setup_insn_max_reg_pressure (rtx after, bool update_p)
1570 {
1571   int i, p;
1572   bool eq_p;
1573   rtx insn;
1574   static int max_reg_pressure[N_REG_CLASSES];
1575
1576   save_reg_pressure ();
1577   for (i = 0; i < ira_pressure_classes_num; i++)
1578     max_reg_pressure[ira_pressure_classes[i]]
1579       = curr_reg_pressure[ira_pressure_classes[i]];
1580   for (insn = NEXT_INSN (after);
1581        insn != NULL_RTX && ! BARRIER_P (insn)
1582          && BLOCK_FOR_INSN (insn) == BLOCK_FOR_INSN (after);
1583        insn = NEXT_INSN (insn))
1584     if (NONDEBUG_INSN_P (insn))
1585       {
1586         eq_p = true;
1587         for (i = 0; i < ira_pressure_classes_num; i++)
1588           {
1589             p = max_reg_pressure[ira_pressure_classes[i]];
1590             if (INSN_MAX_REG_PRESSURE (insn)[i] != p)
1591               {
1592                 eq_p = false;
1593                 INSN_MAX_REG_PRESSURE (insn)[i]
1594                   = max_reg_pressure[ira_pressure_classes[i]];
1595               }
1596           }
1597         if (update_p && eq_p)
1598           break;
1599         update_register_pressure (insn);
1600         for (i = 0; i < ira_pressure_classes_num; i++)
1601           if (max_reg_pressure[ira_pressure_classes[i]]
1602               < curr_reg_pressure[ira_pressure_classes[i]])
1603             max_reg_pressure[ira_pressure_classes[i]]
1604               = curr_reg_pressure[ira_pressure_classes[i]];
1605       }
1606   restore_reg_pressure ();
1607 }
1608
1609 /* Update the current register pressure after scheduling INSN.  Update
1610    also max register pressure for unscheduled insns of the current
1611    BB.  */
1612 static void
1613 update_reg_and_insn_max_reg_pressure (rtx insn)
1614 {
1615   int i;
1616   int before[N_REG_CLASSES];
1617
1618   for (i = 0; i < ira_pressure_classes_num; i++)
1619     before[i] = curr_reg_pressure[ira_pressure_classes[i]];
1620   update_register_pressure (insn);
1621   for (i = 0; i < ira_pressure_classes_num; i++)
1622     if (curr_reg_pressure[ira_pressure_classes[i]] != before[i])
1623       break;
1624   if (i < ira_pressure_classes_num)
1625     setup_insn_max_reg_pressure (insn, true);
1626 }
1627
1628 /* Set up register pressure at the beginning of basic block BB whose
1629    insns starting after insn AFTER.  Set up also max register pressure
1630    for all insns of the basic block.  */
1631 void
1632 sched_setup_bb_reg_pressure_info (basic_block bb, rtx after)
1633 {
1634   gcc_assert (sched_pressure_p);
1635   initiate_bb_reg_pressure_info (bb);
1636   setup_insn_max_reg_pressure (after, false);
1637 }
1638
1639 /* INSN is the "currently executing insn".  Launch each insn which was
1640    waiting on INSN.  READY is the ready list which contains the insns
1641    that are ready to fire.  CLOCK is the current cycle.  The function
1642    returns necessary cycle advance after issuing the insn (it is not
1643    zero for insns in a schedule group).  */
1644
1645 static int
1646 schedule_insn (rtx insn)
1647 {
1648   sd_iterator_def sd_it;
1649   dep_t dep;
1650   int i;
1651   int advance = 0;
1652
1653   if (sched_verbose >= 1)
1654     {
1655       struct reg_pressure_data *pressure_info;
1656       char buf[2048];
1657
1658       print_insn (buf, insn, 0);
1659       buf[40] = 0;
1660       fprintf (sched_dump, ";;\t%3i--> %-40s:", clock_var, buf);
1661
1662       if (recog_memoized (insn) < 0)
1663         fprintf (sched_dump, "nothing");
1664       else
1665         print_reservation (sched_dump, insn);
1666       pressure_info = INSN_REG_PRESSURE (insn);
1667       if (pressure_info != NULL)
1668         {
1669           fputc (':', sched_dump);
1670           for (i = 0; i < ira_pressure_classes_num; i++)
1671             fprintf (sched_dump, "%s%+d(%d)",
1672                      reg_class_names[ira_pressure_classes[i]],
1673                      pressure_info[i].set_increase, pressure_info[i].change);
1674         }
1675       fputc ('\n', sched_dump);
1676     }
1677
1678   if (sched_pressure_p && !DEBUG_INSN_P (insn))
1679     update_reg_and_insn_max_reg_pressure (insn);
1680
1681   /* Scheduling instruction should have all its dependencies resolved and
1682      should have been removed from the ready list.  */
1683   gcc_assert (sd_lists_empty_p (insn, SD_LIST_BACK));
1684
1685   /* Reset debug insns invalidated by moving this insn.  */
1686   if (MAY_HAVE_DEBUG_INSNS && !DEBUG_INSN_P (insn))
1687     for (sd_it = sd_iterator_start (insn, SD_LIST_BACK);
1688          sd_iterator_cond (&sd_it, &dep);)
1689       {
1690         rtx dbg = DEP_PRO (dep);
1691         struct reg_use_data *use, *next;
1692
1693         gcc_assert (DEBUG_INSN_P (dbg));
1694
1695         if (sched_verbose >= 6)
1696           fprintf (sched_dump, ";;\t\tresetting: debug insn %d\n",
1697                    INSN_UID (dbg));
1698
1699         /* ??? Rather than resetting the debug insn, we might be able
1700            to emit a debug temp before the just-scheduled insn, but
1701            this would involve checking that the expression at the
1702            point of the debug insn is equivalent to the expression
1703            before the just-scheduled insn.  They might not be: the
1704            expression in the debug insn may depend on other insns not
1705            yet scheduled that set MEMs, REGs or even other debug
1706            insns.  It's not clear that attempting to preserve debug
1707            information in these cases is worth the effort, given how
1708            uncommon these resets are and the likelihood that the debug
1709            temps introduced won't survive the schedule change.  */
1710         INSN_VAR_LOCATION_LOC (dbg) = gen_rtx_UNKNOWN_VAR_LOC ();
1711         df_insn_rescan (dbg);
1712
1713         /* Unknown location doesn't use any registers.  */
1714         for (use = INSN_REG_USE_LIST (dbg); use != NULL; use = next)
1715           {
1716             struct reg_use_data *prev = use;
1717
1718             /* Remove use from the cyclic next_regno_use chain first.  */
1719             while (prev->next_regno_use != use)
1720               prev = prev->next_regno_use;
1721             prev->next_regno_use = use->next_regno_use;
1722             next = use->next_insn_use;
1723             free (use);
1724           }
1725         INSN_REG_USE_LIST (dbg) = NULL;
1726
1727         /* We delete rather than resolve these deps, otherwise we
1728            crash in sched_free_deps(), because forward deps are
1729            expected to be released before backward deps.  */
1730         sd_delete_dep (sd_it);
1731       }
1732
1733   gcc_assert (QUEUE_INDEX (insn) == QUEUE_NOWHERE);
1734   QUEUE_INDEX (insn) = QUEUE_SCHEDULED;
1735
1736   gcc_assert (INSN_TICK (insn) >= MIN_TICK);
1737   if (INSN_TICK (insn) > clock_var)
1738     /* INSN has been prematurely moved from the queue to the ready list.
1739        This is possible only if following flag is set.  */
1740     gcc_assert (flag_sched_stalled_insns);
1741
1742   /* ??? Probably, if INSN is scheduled prematurely, we should leave
1743      INSN_TICK untouched.  This is a machine-dependent issue, actually.  */
1744   INSN_TICK (insn) = clock_var;
1745
1746   /* Update dependent instructions.  */
1747   for (sd_it = sd_iterator_start (insn, SD_LIST_FORW);
1748        sd_iterator_cond (&sd_it, &dep);)
1749     {
1750       rtx next = DEP_CON (dep);
1751
1752       /* Resolve the dependence between INSN and NEXT.
1753          sd_resolve_dep () moves current dep to another list thus
1754          advancing the iterator.  */
1755       sd_resolve_dep (sd_it);
1756
1757       /* Don't bother trying to mark next as ready if insn is a debug
1758          insn.  If insn is the last hard dependency, it will have
1759          already been discounted.  */
1760       if (DEBUG_INSN_P (insn) && !DEBUG_INSN_P (next))
1761         continue;
1762
1763       if (!IS_SPECULATION_BRANCHY_CHECK_P (insn))
1764         {
1765           int effective_cost;
1766
1767           effective_cost = try_ready (next);
1768
1769           if (effective_cost >= 0
1770               && SCHED_GROUP_P (next)
1771               && advance < effective_cost)
1772             advance = effective_cost;
1773         }
1774       else
1775         /* Check always has only one forward dependence (to the first insn in
1776            the recovery block), therefore, this will be executed only once.  */
1777         {
1778           gcc_assert (sd_lists_empty_p (insn, SD_LIST_FORW));
1779           fix_recovery_deps (RECOVERY_BLOCK (insn));
1780         }
1781     }
1782
1783   /* This is the place where scheduler doesn't *basically* need backward and
1784      forward dependencies for INSN anymore.  Nevertheless they are used in
1785      heuristics in rank_for_schedule (), early_queue_to_ready () and in
1786      some targets (e.g. rs6000).  Thus the earliest place where we *can*
1787      remove dependencies is after targetm.sched.finish () call in
1788      schedule_block ().  But, on the other side, the safest place to remove
1789      dependencies is when we are finishing scheduling entire region.  As we
1790      don't generate [many] dependencies during scheduling itself, we won't
1791      need memory until beginning of next region.
1792      Bottom line: Dependencies are removed for all insns in the end of
1793      scheduling the region.  */
1794
1795   /* Annotate the instruction with issue information -- TImode
1796      indicates that the instruction is expected not to be able
1797      to issue on the same cycle as the previous insn.  A machine
1798      may use this information to decide how the instruction should
1799      be aligned.  */
1800   if (issue_rate > 1
1801       && GET_CODE (PATTERN (insn)) != USE
1802       && GET_CODE (PATTERN (insn)) != CLOBBER
1803       && !DEBUG_INSN_P (insn))
1804     {
1805       if (reload_completed)
1806         PUT_MODE (insn, clock_var > last_clock_var ? TImode : VOIDmode);
1807       last_clock_var = clock_var;
1808     }
1809
1810   return advance;
1811 }
1812
1813 /* Functions for handling of notes.  */
1814
1815 /* Add note list that ends on FROM_END to the end of TO_ENDP.  */
1816 void
1817 concat_note_lists (rtx from_end, rtx *to_endp)
1818 {
1819   rtx from_start;
1820
1821   /* It's easy when have nothing to concat.  */
1822   if (from_end == NULL)
1823     return;
1824
1825   /* It's also easy when destination is empty.  */
1826   if (*to_endp == NULL)
1827     {
1828       *to_endp = from_end;
1829       return;
1830     }
1831
1832   from_start = from_end;
1833   while (PREV_INSN (from_start) != NULL)
1834     from_start = PREV_INSN (from_start);
1835
1836   PREV_INSN (from_start) = *to_endp;
1837   NEXT_INSN (*to_endp) = from_start;
1838   *to_endp = from_end;
1839 }
1840
1841 /* Delete notes between HEAD and TAIL and put them in the chain
1842    of notes ended by NOTE_LIST.  */
1843 void
1844 remove_notes (rtx head, rtx tail)
1845 {
1846   rtx next_tail, insn, next;
1847
1848   note_list = 0;
1849   if (head == tail && !INSN_P (head))
1850     return;
1851
1852   next_tail = NEXT_INSN (tail);
1853   for (insn = head; insn != next_tail; insn = next)
1854     {
1855       next = NEXT_INSN (insn);
1856       if (!NOTE_P (insn))
1857         continue;
1858
1859       switch (NOTE_KIND (insn))
1860         {
1861         case NOTE_INSN_BASIC_BLOCK:
1862           continue;
1863
1864         case NOTE_INSN_EPILOGUE_BEG:
1865           if (insn != tail)
1866             {
1867               remove_insn (insn);
1868               add_reg_note (next, REG_SAVE_NOTE,
1869                             GEN_INT (NOTE_INSN_EPILOGUE_BEG));
1870               break;
1871             }
1872           /* FALLTHRU */
1873
1874         default:
1875           remove_insn (insn);
1876
1877           /* Add the note to list that ends at NOTE_LIST.  */
1878           PREV_INSN (insn) = note_list;
1879           NEXT_INSN (insn) = NULL_RTX;
1880           if (note_list)
1881             NEXT_INSN (note_list) = insn;
1882           note_list = insn;
1883           break;
1884         }
1885
1886       gcc_assert ((sel_sched_p () || insn != tail) && insn != head);
1887     }
1888 }
1889
1890
1891 /* Return the head and tail pointers of ebb starting at BEG and ending
1892    at END.  */
1893 void
1894 get_ebb_head_tail (basic_block beg, basic_block end, rtx *headp, rtx *tailp)
1895 {
1896   rtx beg_head = BB_HEAD (beg);
1897   rtx beg_tail = BB_END (beg);
1898   rtx end_head = BB_HEAD (end);
1899   rtx end_tail = BB_END (end);
1900
1901   /* Don't include any notes or labels at the beginning of the BEG
1902      basic block, or notes at the end of the END basic blocks.  */
1903
1904   if (LABEL_P (beg_head))
1905     beg_head = NEXT_INSN (beg_head);
1906
1907   while (beg_head != beg_tail)
1908     if (NOTE_P (beg_head))
1909       beg_head = NEXT_INSN (beg_head);
1910     else if (DEBUG_INSN_P (beg_head))
1911       {
1912         rtx note, next;
1913
1914         for (note = NEXT_INSN (beg_head);
1915              note != beg_tail;
1916              note = next)
1917           {
1918             next = NEXT_INSN (note);
1919             if (NOTE_P (note))
1920               {
1921                 if (sched_verbose >= 9)
1922                   fprintf (sched_dump, "reorder %i\n", INSN_UID (note));
1923
1924                 reorder_insns_nobb (note, note, PREV_INSN (beg_head));
1925
1926                 if (BLOCK_FOR_INSN (note) != beg)
1927                   df_insn_change_bb (note, beg);
1928               }
1929             else if (!DEBUG_INSN_P (note))
1930               break;
1931           }
1932
1933         break;
1934       }
1935     else
1936       break;
1937
1938   *headp = beg_head;
1939
1940   if (beg == end)
1941     end_head = beg_head;
1942   else if (LABEL_P (end_head))
1943     end_head = NEXT_INSN (end_head);
1944
1945   while (end_head != end_tail)
1946     if (NOTE_P (end_tail))
1947       end_tail = PREV_INSN (end_tail);
1948     else if (DEBUG_INSN_P (end_tail))
1949       {
1950         rtx note, prev;
1951
1952         for (note = PREV_INSN (end_tail);
1953              note != end_head;
1954              note = prev)
1955           {
1956             prev = PREV_INSN (note);
1957             if (NOTE_P (note))
1958               {
1959                 if (sched_verbose >= 9)
1960                   fprintf (sched_dump, "reorder %i\n", INSN_UID (note));
1961
1962                 reorder_insns_nobb (note, note, end_tail);
1963
1964                 if (end_tail == BB_END (end))
1965                   BB_END (end) = note;
1966
1967                 if (BLOCK_FOR_INSN (note) != end)
1968                   df_insn_change_bb (note, end);
1969               }
1970             else if (!DEBUG_INSN_P (note))
1971               break;
1972           }
1973
1974         break;
1975       }
1976     else
1977       break;
1978
1979   *tailp = end_tail;
1980 }
1981
1982 /* Return nonzero if there are no real insns in the range [ HEAD, TAIL ].  */
1983
1984 int
1985 no_real_insns_p (const_rtx head, const_rtx tail)
1986 {
1987   while (head != NEXT_INSN (tail))
1988     {
1989       if (!NOTE_P (head) && !LABEL_P (head))
1990         return 0;
1991       head = NEXT_INSN (head);
1992     }
1993   return 1;
1994 }
1995
1996 /* Restore-other-notes: NOTE_LIST is the end of a chain of notes
1997    previously found among the insns.  Insert them just before HEAD.  */
1998 rtx
1999 restore_other_notes (rtx head, basic_block head_bb)
2000 {
2001   if (note_list != 0)
2002     {
2003       rtx note_head = note_list;
2004
2005       if (head)
2006         head_bb = BLOCK_FOR_INSN (head);
2007       else
2008         head = NEXT_INSN (bb_note (head_bb));
2009
2010       while (PREV_INSN (note_head))
2011         {
2012           set_block_for_insn (note_head, head_bb);
2013           note_head = PREV_INSN (note_head);
2014         }
2015       /* In the above cycle we've missed this note.  */
2016       set_block_for_insn (note_head, head_bb);
2017
2018       PREV_INSN (note_head) = PREV_INSN (head);
2019       NEXT_INSN (PREV_INSN (head)) = note_head;
2020       PREV_INSN (head) = note_list;
2021       NEXT_INSN (note_list) = head;
2022
2023       if (BLOCK_FOR_INSN (head) != head_bb)
2024         BB_END (head_bb) = note_list;
2025
2026       head = note_head;
2027     }
2028
2029   return head;
2030 }
2031
2032 /* Move insns that became ready to fire from queue to ready list.  */
2033
2034 static void
2035 queue_to_ready (struct ready_list *ready)
2036 {
2037   rtx insn;
2038   rtx link;
2039   rtx skip_insn;
2040
2041   q_ptr = NEXT_Q (q_ptr);
2042
2043   if (dbg_cnt (sched_insn) == false)
2044     {
2045       /* If debug counter is activated do not requeue the first
2046          nonscheduled insn.  */
2047       skip_insn = nonscheduled_insns_begin;
2048       do
2049         {
2050           skip_insn = next_nonnote_nondebug_insn (skip_insn);
2051         }
2052       while (QUEUE_INDEX (skip_insn) == QUEUE_SCHEDULED);
2053     }
2054   else
2055     skip_insn = NULL_RTX;
2056
2057   /* Add all pending insns that can be scheduled without stalls to the
2058      ready list.  */
2059   for (link = insn_queue[q_ptr]; link; link = XEXP (link, 1))
2060     {
2061       insn = XEXP (link, 0);
2062       q_size -= 1;
2063
2064       if (sched_verbose >= 2)
2065         fprintf (sched_dump, ";;\t\tQ-->Ready: insn %s: ",
2066                  (*current_sched_info->print_insn) (insn, 0));
2067
2068       /* If the ready list is full, delay the insn for 1 cycle.
2069          See the comment in schedule_block for the rationale.  */
2070       if (!reload_completed
2071           && ready->n_ready - ready->n_debug > MAX_SCHED_READY_INSNS
2072           && !SCHED_GROUP_P (insn)
2073           && insn != skip_insn)
2074         queue_insn (insn, 1, "ready full");
2075       else
2076         {
2077           ready_add (ready, insn, false);
2078           if (sched_verbose >= 2)
2079             fprintf (sched_dump, "moving to ready without stalls\n");
2080         }
2081     }
2082   free_INSN_LIST_list (&insn_queue[q_ptr]);
2083
2084   /* If there are no ready insns, stall until one is ready and add all
2085      of the pending insns at that point to the ready list.  */
2086   if (ready->n_ready == 0)
2087     {
2088       int stalls;
2089
2090       for (stalls = 1; stalls <= max_insn_queue_index; stalls++)
2091         {
2092           if ((link = insn_queue[NEXT_Q_AFTER (q_ptr, stalls)]))
2093             {
2094               for (; link; link = XEXP (link, 1))
2095                 {
2096                   insn = XEXP (link, 0);
2097                   q_size -= 1;
2098
2099                   if (sched_verbose >= 2)
2100                     fprintf (sched_dump, ";;\t\tQ-->Ready: insn %s: ",
2101                              (*current_sched_info->print_insn) (insn, 0));
2102
2103                   ready_add (ready, insn, false);
2104                   if (sched_verbose >= 2)
2105                     fprintf (sched_dump, "moving to ready with %d stalls\n", stalls);
2106                 }
2107               free_INSN_LIST_list (&insn_queue[NEXT_Q_AFTER (q_ptr, stalls)]);
2108
2109               advance_one_cycle ();
2110
2111               break;
2112             }
2113
2114           advance_one_cycle ();
2115         }
2116
2117       q_ptr = NEXT_Q_AFTER (q_ptr, stalls);
2118       clock_var += stalls;
2119     }
2120 }
2121
2122 /* Used by early_queue_to_ready.  Determines whether it is "ok" to
2123    prematurely move INSN from the queue to the ready list.  Currently,
2124    if a target defines the hook 'is_costly_dependence', this function
2125    uses the hook to check whether there exist any dependences which are
2126    considered costly by the target, between INSN and other insns that
2127    have already been scheduled.  Dependences are checked up to Y cycles
2128    back, with default Y=1; The flag -fsched-stalled-insns-dep=Y allows
2129    controlling this value.
2130    (Other considerations could be taken into account instead (or in
2131    addition) depending on user flags and target hooks.  */
2132
2133 static bool
2134 ok_for_early_queue_removal (rtx insn)
2135 {
2136   if (targetm.sched.is_costly_dependence)
2137     {
2138       rtx prev_insn;
2139       int n_cycles;
2140       int i = VEC_length (rtx, scheduled_insns);
2141       for (n_cycles = flag_sched_stalled_insns_dep; n_cycles; n_cycles--)
2142         {
2143           while (i-- > 0)
2144             {
2145               int cost;
2146
2147               prev_insn = VEC_index (rtx, scheduled_insns, i);
2148
2149               if (!NOTE_P (prev_insn))
2150                 {
2151                   dep_t dep;
2152
2153                   dep = sd_find_dep_between (prev_insn, insn, true);
2154
2155                   if (dep != NULL)
2156                     {
2157                       cost = dep_cost (dep);
2158
2159                       if (targetm.sched.is_costly_dependence (dep, cost,
2160                                 flag_sched_stalled_insns_dep - n_cycles))
2161                         return false;
2162                     }
2163                 }
2164
2165               if (GET_MODE (prev_insn) == TImode) /* end of dispatch group */
2166                 break;
2167             }
2168
2169           if (i == 0)
2170             break;
2171         }
2172     }
2173
2174   return true;
2175 }
2176
2177
2178 /* Remove insns from the queue, before they become "ready" with respect
2179    to FU latency considerations.  */
2180
2181 static int
2182 early_queue_to_ready (state_t state, struct ready_list *ready)
2183 {
2184   rtx insn;
2185   rtx link;
2186   rtx next_link;
2187   rtx prev_link;
2188   bool move_to_ready;
2189   int cost;
2190   state_t temp_state = alloca (dfa_state_size);
2191   int stalls;
2192   int insns_removed = 0;
2193
2194   /*
2195      Flag '-fsched-stalled-insns=X' determines the aggressiveness of this
2196      function:
2197
2198      X == 0: There is no limit on how many queued insns can be removed
2199              prematurely.  (flag_sched_stalled_insns = -1).
2200
2201      X >= 1: Only X queued insns can be removed prematurely in each
2202              invocation.  (flag_sched_stalled_insns = X).
2203
2204      Otherwise: Early queue removal is disabled.
2205          (flag_sched_stalled_insns = 0)
2206   */
2207
2208   if (! flag_sched_stalled_insns)
2209     return 0;
2210
2211   for (stalls = 0; stalls <= max_insn_queue_index; stalls++)
2212     {
2213       if ((link = insn_queue[NEXT_Q_AFTER (q_ptr, stalls)]))
2214         {
2215           if (sched_verbose > 6)
2216             fprintf (sched_dump, ";; look at index %d + %d\n", q_ptr, stalls);
2217
2218           prev_link = 0;
2219           while (link)
2220             {
2221               next_link = XEXP (link, 1);
2222               insn = XEXP (link, 0);
2223               if (insn && sched_verbose > 6)
2224                 print_rtl_single (sched_dump, insn);
2225
2226               memcpy (temp_state, state, dfa_state_size);
2227               if (recog_memoized (insn) < 0)
2228                 /* non-negative to indicate that it's not ready
2229                    to avoid infinite Q->R->Q->R... */
2230                 cost = 0;
2231               else
2232                 cost = state_transition (temp_state, insn);
2233
2234               if (sched_verbose >= 6)
2235                 fprintf (sched_dump, "transition cost = %d\n", cost);
2236
2237               move_to_ready = false;
2238               if (cost < 0)
2239                 {
2240                   move_to_ready = ok_for_early_queue_removal (insn);
2241                   if (move_to_ready == true)
2242                     {
2243                       /* move from Q to R */
2244                       q_size -= 1;
2245                       ready_add (ready, insn, false);
2246
2247                       if (prev_link)
2248                         XEXP (prev_link, 1) = next_link;
2249                       else
2250                         insn_queue[NEXT_Q_AFTER (q_ptr, stalls)] = next_link;
2251
2252                       free_INSN_LIST_node (link);
2253
2254                       if (sched_verbose >= 2)
2255                         fprintf (sched_dump, ";;\t\tEarly Q-->Ready: insn %s\n",
2256                                  (*current_sched_info->print_insn) (insn, 0));
2257
2258                       insns_removed++;
2259                       if (insns_removed == flag_sched_stalled_insns)
2260                         /* Remove no more than flag_sched_stalled_insns insns
2261                            from Q at a time.  */
2262                         return insns_removed;
2263                     }
2264                 }
2265
2266               if (move_to_ready == false)
2267                 prev_link = link;
2268
2269               link = next_link;
2270             } /* while link */
2271         } /* if link */
2272
2273     } /* for stalls.. */
2274
2275   return insns_removed;
2276 }
2277
2278
2279 /* Print the ready list for debugging purposes.  Callable from debugger.  */
2280
2281 static void
2282 debug_ready_list (struct ready_list *ready)
2283 {
2284   rtx *p;
2285   int i;
2286
2287   if (ready->n_ready == 0)
2288     {
2289       fprintf (sched_dump, "\n");
2290       return;
2291     }
2292
2293   p = ready_lastpos (ready);
2294   for (i = 0; i < ready->n_ready; i++)
2295     {
2296       fprintf (sched_dump, "  %s:%d",
2297                (*current_sched_info->print_insn) (p[i], 0),
2298                INSN_LUID (p[i]));
2299       if (sched_pressure_p)
2300         fprintf (sched_dump, "(cost=%d",
2301                  INSN_REG_PRESSURE_EXCESS_COST_CHANGE (p[i]));
2302       if (INSN_TICK (p[i]) > clock_var)
2303         fprintf (sched_dump, ":delay=%d", INSN_TICK (p[i]) - clock_var);
2304       if (sched_pressure_p)
2305         fprintf (sched_dump, ")");
2306     }
2307   fprintf (sched_dump, "\n");
2308 }
2309
2310 /* Search INSN for REG_SAVE_NOTE notes and convert them back into insn
2311    NOTEs.  This is used for NOTE_INSN_EPILOGUE_BEG, so that sched-ebb
2312    replaces the epilogue note in the correct basic block.  */
2313 void
2314 reemit_notes (rtx insn)
2315 {
2316   rtx note, last = insn;
2317
2318   for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
2319     {
2320       if (REG_NOTE_KIND (note) == REG_SAVE_NOTE)
2321         {
2322           enum insn_note note_type = (enum insn_note) INTVAL (XEXP (note, 0));
2323
2324           last = emit_note_before (note_type, last);
2325           remove_note (insn, note);
2326         }
2327     }
2328 }
2329
2330 /* Move INSN.  Reemit notes if needed.  Update CFG, if needed.  */
2331 static void
2332 move_insn (rtx insn, rtx last, rtx nt)
2333 {
2334   if (PREV_INSN (insn) != last)
2335     {
2336       basic_block bb;
2337       rtx note;
2338       int jump_p = 0;
2339
2340       bb = BLOCK_FOR_INSN (insn);
2341
2342       /* BB_HEAD is either LABEL or NOTE.  */
2343       gcc_assert (BB_HEAD (bb) != insn);
2344
2345       if (BB_END (bb) == insn)
2346         /* If this is last instruction in BB, move end marker one
2347            instruction up.  */
2348         {
2349           /* Jumps are always placed at the end of basic block.  */
2350           jump_p = control_flow_insn_p (insn);
2351
2352           gcc_assert (!jump_p
2353                       || ((common_sched_info->sched_pass_id == SCHED_RGN_PASS)
2354                           && IS_SPECULATION_BRANCHY_CHECK_P (insn))
2355                       || (common_sched_info->sched_pass_id
2356                           == SCHED_EBB_PASS));
2357
2358           gcc_assert (BLOCK_FOR_INSN (PREV_INSN (insn)) == bb);
2359
2360           BB_END (bb) = PREV_INSN (insn);
2361         }
2362
2363       gcc_assert (BB_END (bb) != last);
2364
2365       if (jump_p)
2366         /* We move the block note along with jump.  */
2367         {
2368           gcc_assert (nt);
2369
2370           note = NEXT_INSN (insn);
2371           while (NOTE_NOT_BB_P (note) && note != nt)
2372             note = NEXT_INSN (note);
2373
2374           if (note != nt
2375               && (LABEL_P (note)
2376                   || BARRIER_P (note)))
2377             note = NEXT_INSN (note);
2378
2379           gcc_assert (NOTE_INSN_BASIC_BLOCK_P (note));
2380         }
2381       else
2382         note = insn;
2383
2384       NEXT_INSN (PREV_INSN (insn)) = NEXT_INSN (note);
2385       PREV_INSN (NEXT_INSN (note)) = PREV_INSN (insn);
2386
2387       NEXT_INSN (note) = NEXT_INSN (last);
2388       PREV_INSN (NEXT_INSN (last)) = note;
2389
2390       NEXT_INSN (last) = insn;
2391       PREV_INSN (insn) = last;
2392
2393       bb = BLOCK_FOR_INSN (last);
2394
2395       if (jump_p)
2396         {
2397           fix_jump_move (insn);
2398
2399           if (BLOCK_FOR_INSN (insn) != bb)
2400             move_block_after_check (insn);
2401
2402           gcc_assert (BB_END (bb) == last);
2403         }
2404
2405       df_insn_change_bb (insn, bb);
2406
2407       /* Update BB_END, if needed.  */
2408       if (BB_END (bb) == last)
2409         BB_END (bb) = insn;
2410     }
2411
2412   SCHED_GROUP_P (insn) = 0;
2413 }
2414
2415 /* Return true if scheduling INSN will finish current clock cycle.  */
2416 static bool
2417 insn_finishes_cycle_p (rtx insn)
2418 {
2419   if (SCHED_GROUP_P (insn))
2420     /* After issuing INSN, rest of the sched_group will be forced to issue
2421        in order.  Don't make any plans for the rest of cycle.  */
2422     return true;
2423
2424   /* Finishing the block will, apparently, finish the cycle.  */
2425   if (current_sched_info->insn_finishes_block_p
2426       && current_sched_info->insn_finishes_block_p (insn))
2427     return true;
2428
2429   return false;
2430 }
2431
2432 /* Define type for target data used in multipass scheduling.  */
2433 #ifndef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DATA_T
2434 # define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DATA_T int
2435 #endif
2436 typedef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DATA_T first_cycle_multipass_data_t;
2437
2438 /* The following structure describe an entry of the stack of choices.  */
2439 struct choice_entry
2440 {
2441   /* Ordinal number of the issued insn in the ready queue.  */
2442   int index;
2443   /* The number of the rest insns whose issues we should try.  */
2444   int rest;
2445   /* The number of issued essential insns.  */
2446   int n;
2447   /* State after issuing the insn.  */
2448   state_t state;
2449   /* Target-specific data.  */
2450   first_cycle_multipass_data_t target_data;
2451 };
2452
2453 /* The following array is used to implement a stack of choices used in
2454    function max_issue.  */
2455 static struct choice_entry *choice_stack;
2456
2457 /* The following variable value is number of essential insns issued on
2458    the current cycle.  An insn is essential one if it changes the
2459    processors state.  */
2460 int cycle_issued_insns;
2461
2462 /* This holds the value of the target dfa_lookahead hook.  */
2463 int dfa_lookahead;
2464
2465 /* The following variable value is maximal number of tries of issuing
2466    insns for the first cycle multipass insn scheduling.  We define
2467    this value as constant*(DFA_LOOKAHEAD**ISSUE_RATE).  We would not
2468    need this constraint if all real insns (with non-negative codes)
2469    had reservations because in this case the algorithm complexity is
2470    O(DFA_LOOKAHEAD**ISSUE_RATE).  Unfortunately, the dfa descriptions
2471    might be incomplete and such insn might occur.  For such
2472    descriptions, the complexity of algorithm (without the constraint)
2473    could achieve DFA_LOOKAHEAD ** N , where N is the queue length.  */
2474 static int max_lookahead_tries;
2475
2476 /* The following value is value of hook
2477    `first_cycle_multipass_dfa_lookahead' at the last call of
2478    `max_issue'.  */
2479 static int cached_first_cycle_multipass_dfa_lookahead = 0;
2480
2481 /* The following value is value of `issue_rate' at the last call of
2482    `sched_init'.  */
2483 static int cached_issue_rate = 0;
2484
2485 /* The following function returns maximal (or close to maximal) number
2486    of insns which can be issued on the same cycle and one of which
2487    insns is insns with the best rank (the first insn in READY).  To
2488    make this function tries different samples of ready insns.  READY
2489    is current queue `ready'.  Global array READY_TRY reflects what
2490    insns are already issued in this try.  The function stops immediately,
2491    if it reached the such a solution, that all instruction can be issued.
2492    INDEX will contain index of the best insn in READY.  The following
2493    function is used only for first cycle multipass scheduling.
2494
2495    PRIVILEGED_N >= 0
2496
2497    This function expects recognized insns only.  All USEs,
2498    CLOBBERs, etc must be filtered elsewhere.  */
2499 int
2500 max_issue (struct ready_list *ready, int privileged_n, state_t state,
2501            bool first_cycle_insn_p, int *index)
2502 {
2503   int n, i, all, n_ready, best, delay, tries_num;
2504   int more_issue;
2505   struct choice_entry *top;
2506   rtx insn;
2507
2508   n_ready = ready->n_ready;
2509   gcc_assert (dfa_lookahead >= 1 && privileged_n >= 0
2510               && privileged_n <= n_ready);
2511
2512   /* Init MAX_LOOKAHEAD_TRIES.  */
2513   if (cached_first_cycle_multipass_dfa_lookahead != dfa_lookahead)
2514     {
2515       cached_first_cycle_multipass_dfa_lookahead = dfa_lookahead;
2516       max_lookahead_tries = 100;
2517       for (i = 0; i < issue_rate; i++)
2518         max_lookahead_tries *= dfa_lookahead;
2519     }
2520
2521   /* Init max_points.  */
2522   more_issue = issue_rate - cycle_issued_insns;
2523   gcc_assert (more_issue >= 0);
2524
2525   /* The number of the issued insns in the best solution.  */
2526   best = 0;
2527
2528   top = choice_stack;
2529
2530   /* Set initial state of the search.  */
2531   memcpy (top->state, state, dfa_state_size);
2532   top->rest = dfa_lookahead;
2533   top->n = 0;
2534   if (targetm.sched.first_cycle_multipass_begin)
2535     targetm.sched.first_cycle_multipass_begin (&top->target_data,
2536                                                ready_try, n_ready,
2537                                                first_cycle_insn_p);
2538
2539   /* Count the number of the insns to search among.  */
2540   for (all = i = 0; i < n_ready; i++)
2541     if (!ready_try [i])
2542       all++;
2543
2544   /* I is the index of the insn to try next.  */
2545   i = 0;
2546   tries_num = 0;
2547   for (;;)
2548     {
2549       if (/* If we've reached a dead end or searched enough of what we have
2550              been asked...  */
2551           top->rest == 0
2552           /* or have nothing else to try...  */
2553           || i >= n_ready
2554           /* or should not issue more.  */
2555           || top->n >= more_issue)
2556         {
2557           /* ??? (... || i == n_ready).  */
2558           gcc_assert (i <= n_ready);
2559
2560           /* We should not issue more than issue_rate instructions.  */
2561           gcc_assert (top->n <= more_issue);
2562
2563           if (top == choice_stack)
2564             break;
2565
2566           if (best < top - choice_stack)
2567             {
2568               if (privileged_n)
2569                 {
2570                   n = privileged_n;
2571                   /* Try to find issued privileged insn.  */
2572                   while (n && !ready_try[--n]);
2573                 }
2574
2575               if (/* If all insns are equally good...  */
2576                   privileged_n == 0
2577                   /* Or a privileged insn will be issued.  */
2578                   || ready_try[n])
2579                 /* Then we have a solution.  */
2580                 {
2581                   best = top - choice_stack;
2582                   /* This is the index of the insn issued first in this
2583                      solution.  */
2584                   *index = choice_stack [1].index;
2585                   if (top->n == more_issue || best == all)
2586                     break;
2587                 }
2588             }
2589
2590           /* Set ready-list index to point to the last insn
2591              ('i++' below will advance it to the next insn).  */
2592           i = top->index;
2593
2594           /* Backtrack.  */
2595           ready_try [i] = 0;
2596
2597           if (targetm.sched.first_cycle_multipass_backtrack)
2598             targetm.sched.first_cycle_multipass_backtrack (&top->target_data,
2599                                                            ready_try, n_ready);
2600
2601           top--;
2602           memcpy (state, top->state, dfa_state_size);
2603         }
2604       else if (!ready_try [i])
2605         {
2606           tries_num++;
2607           if (tries_num > max_lookahead_tries)
2608             break;
2609           insn = ready_element (ready, i);
2610           delay = state_transition (state, insn);
2611           if (delay < 0)
2612             {
2613               if (state_dead_lock_p (state)
2614                   || insn_finishes_cycle_p (insn))
2615                 /* We won't issue any more instructions in the next
2616                    choice_state.  */
2617                 top->rest = 0;
2618               else
2619                 top->rest--;
2620
2621               n = top->n;
2622               if (memcmp (top->state, state, dfa_state_size) != 0)
2623                 n++;
2624
2625               /* Advance to the next choice_entry.  */
2626               top++;
2627               /* Initialize it.  */
2628               top->rest = dfa_lookahead;
2629               top->index = i;
2630               top->n = n;
2631               memcpy (top->state, state, dfa_state_size);
2632               ready_try [i] = 1;
2633
2634               if (targetm.sched.first_cycle_multipass_issue)
2635                 targetm.sched.first_cycle_multipass_issue (&top->target_data,
2636                                                            ready_try, n_ready,
2637                                                            insn,
2638                                                            &((top - 1)
2639                                                              ->target_data));
2640
2641               i = -1;
2642             }
2643         }
2644
2645       /* Increase ready-list index.  */
2646       i++;
2647     }
2648
2649   if (targetm.sched.first_cycle_multipass_end)
2650     targetm.sched.first_cycle_multipass_end (best != 0
2651                                              ? &choice_stack[1].target_data
2652                                              : NULL);
2653
2654   /* Restore the original state of the DFA.  */
2655   memcpy (state, choice_stack->state, dfa_state_size);
2656
2657   return best;
2658 }
2659
2660 /* The following function chooses insn from READY and modifies
2661    READY.  The following function is used only for first
2662    cycle multipass scheduling.
2663    Return:
2664    -1 if cycle should be advanced,
2665    0 if INSN_PTR is set to point to the desirable insn,
2666    1 if choose_ready () should be restarted without advancing the cycle.  */
2667 static int
2668 choose_ready (struct ready_list *ready, bool first_cycle_insn_p,
2669               rtx *insn_ptr)
2670 {
2671   int lookahead;
2672
2673   if (dbg_cnt (sched_insn) == false)
2674     {
2675       rtx insn = nonscheduled_insns_begin;
2676       do
2677         {
2678           insn = next_nonnote_insn (insn);
2679         }
2680       while (QUEUE_INDEX (insn) == QUEUE_SCHEDULED);
2681
2682       if (QUEUE_INDEX (insn) == QUEUE_READY)
2683         /* INSN is in the ready_list.  */
2684         {
2685           nonscheduled_insns_begin = insn;
2686           ready_remove_insn (insn);
2687           *insn_ptr = insn;
2688           return 0;
2689         }
2690
2691       /* INSN is in the queue.  Advance cycle to move it to the ready list.  */
2692       return -1;
2693     }
2694
2695   lookahead = 0;
2696
2697   if (targetm.sched.first_cycle_multipass_dfa_lookahead)
2698     lookahead = targetm.sched.first_cycle_multipass_dfa_lookahead ();
2699   if (lookahead <= 0 || SCHED_GROUP_P (ready_element (ready, 0))
2700       || DEBUG_INSN_P (ready_element (ready, 0)))
2701     {
2702       if (targetm.sched.dispatch (NULL_RTX, IS_DISPATCH_ON))
2703         *insn_ptr = ready_remove_first_dispatch (ready);
2704       else
2705         *insn_ptr = ready_remove_first (ready);
2706
2707       return 0;
2708     }
2709   else
2710     {
2711       /* Try to choose the better insn.  */
2712       int index = 0, i, n;
2713       rtx insn;
2714       int try_data = 1, try_control = 1;
2715       ds_t ts;
2716
2717       insn = ready_element (ready, 0);
2718       if (INSN_CODE (insn) < 0)
2719         {
2720           *insn_ptr = ready_remove_first (ready);
2721           return 0;
2722         }
2723
2724       if (spec_info
2725           && spec_info->flags & (PREFER_NON_DATA_SPEC
2726                                  | PREFER_NON_CONTROL_SPEC))
2727         {
2728           for (i = 0, n = ready->n_ready; i < n; i++)
2729             {
2730               rtx x;
2731               ds_t s;
2732
2733               x = ready_element (ready, i);
2734               s = TODO_SPEC (x);
2735
2736               if (spec_info->flags & PREFER_NON_DATA_SPEC
2737                   && !(s & DATA_SPEC))
2738                 {
2739                   try_data = 0;
2740                   if (!(spec_info->flags & PREFER_NON_CONTROL_SPEC)
2741                       || !try_control)
2742                     break;
2743                 }
2744
2745               if (spec_info->flags & PREFER_NON_CONTROL_SPEC
2746                   && !(s & CONTROL_SPEC))
2747                 {
2748                   try_control = 0;
2749                   if (!(spec_info->flags & PREFER_NON_DATA_SPEC) || !try_data)
2750                     break;
2751                 }
2752             }
2753         }
2754
2755       ts = TODO_SPEC (insn);
2756       if ((ts & SPECULATIVE)
2757           && (((!try_data && (ts & DATA_SPEC))
2758                || (!try_control && (ts & CONTROL_SPEC)))
2759               || (targetm.sched.first_cycle_multipass_dfa_lookahead_guard_spec
2760                   && !targetm.sched
2761                   .first_cycle_multipass_dfa_lookahead_guard_spec (insn))))
2762         /* Discard speculative instruction that stands first in the ready
2763            list.  */
2764         {
2765           change_queue_index (insn, 1);
2766           return 1;
2767         }
2768
2769       ready_try[0] = 0;
2770
2771       for (i = 1; i < ready->n_ready; i++)
2772         {
2773           insn = ready_element (ready, i);
2774
2775           ready_try [i]
2776             = ((!try_data && (TODO_SPEC (insn) & DATA_SPEC))
2777                || (!try_control && (TODO_SPEC (insn) & CONTROL_SPEC)));
2778         }
2779
2780       /* Let the target filter the search space.  */
2781       for (i = 1; i < ready->n_ready; i++)
2782         if (!ready_try[i])
2783           {
2784             insn = ready_element (ready, i);
2785
2786             /* If this insn is recognizable we should have already
2787                recognized it earlier.
2788                ??? Not very clear where this is supposed to be done.
2789                See dep_cost_1.  */
2790             gcc_checking_assert (INSN_CODE (insn) >= 0
2791                                  || recog_memoized (insn) < 0);
2792
2793             ready_try [i]
2794               = (/* INSN_CODE check can be omitted here as it is also done later
2795                     in max_issue ().  */
2796                  INSN_CODE (insn) < 0
2797                  || (targetm.sched.first_cycle_multipass_dfa_lookahead_guard
2798                      && !targetm.sched.first_cycle_multipass_dfa_lookahead_guard
2799                      (insn)));
2800           }
2801
2802       if (max_issue (ready, 1, curr_state, first_cycle_insn_p, &index) == 0)
2803         {
2804           *insn_ptr = ready_remove_first (ready);
2805           if (sched_verbose >= 4)
2806             fprintf (sched_dump, ";;\t\tChosen insn (but can't issue) : %s \n",
2807                      (*current_sched_info->print_insn) (*insn_ptr, 0));
2808           return 0;
2809         }
2810       else
2811         {
2812           if (sched_verbose >= 4)
2813             fprintf (sched_dump, ";;\t\tChosen insn : %s\n",
2814                      (*current_sched_info->print_insn)
2815                      (ready_element (ready, index), 0));
2816
2817           *insn_ptr = ready_remove (ready, index);
2818           return 0;
2819         }
2820     }
2821 }
2822
2823 /* This function is called when we have successfully scheduled a
2824    block.  It uses the schedule stored in the scheduled_insns vector
2825    to rearrange the RTL.  PREV_HEAD is used as the anchor to which we
2826    append the scheduled insns; TAIL is the insn after the scheduled
2827    block.  TARGET_BB is the argument passed to schedule_block.  */
2828
2829 static void
2830 commit_schedule (rtx prev_head, rtx tail, basic_block *target_bb)
2831 {
2832   unsigned int i;
2833   rtx insn;
2834
2835   last_scheduled_insn = prev_head;
2836   for (i = 0;
2837        VEC_iterate (rtx, scheduled_insns, i, insn);
2838        i++)
2839     {
2840       if (control_flow_insn_p (last_scheduled_insn)
2841           || current_sched_info->advance_target_bb (*target_bb, insn))
2842         {
2843           *target_bb = current_sched_info->advance_target_bb (*target_bb, 0);
2844
2845           if (sched_verbose)
2846             {
2847               rtx x;
2848
2849               x = next_real_insn (last_scheduled_insn);
2850               gcc_assert (x);
2851               dump_new_block_header (1, *target_bb, x, tail);
2852             }
2853
2854           last_scheduled_insn = bb_note (*target_bb);
2855         }
2856
2857       if (current_sched_info->begin_move_insn)
2858         (*current_sched_info->begin_move_insn) (insn, last_scheduled_insn);
2859       move_insn (insn, last_scheduled_insn,
2860                  current_sched_info->next_tail);
2861       if (!DEBUG_INSN_P (insn))
2862         reemit_notes (insn);
2863       last_scheduled_insn = insn;
2864     }
2865
2866   VEC_truncate (rtx, scheduled_insns, 0);
2867 }
2868
2869 /* Examine all insns on the ready list and queue those which can't be
2870    issued in this cycle.  TEMP_STATE is temporary scheduler state we
2871    can use as scratch space.  If FIRST_CYCLE_INSN_P is true, no insns
2872    have been issued for the current cycle, which means it is valid to
2873    issue an asm statement.  */
2874
2875 static void
2876 prune_ready_list (state_t temp_state, bool first_cycle_insn_p)
2877 {
2878   int i;
2879
2880  restart:
2881   for (i = 0; i < ready.n_ready; i++)
2882     {
2883       rtx insn = ready_element (&ready, i);
2884       int cost = 0;
2885       const char *reason = "resource conflict";
2886
2887       if (recog_memoized (insn) < 0)
2888         {
2889           if (!first_cycle_insn_p
2890               && (GET_CODE (PATTERN (insn)) == ASM_INPUT
2891                   || asm_noperands (PATTERN (insn)) >= 0))
2892             cost = 1;
2893           reason = "asm";
2894         }
2895       else if (sched_pressure_p)
2896         cost = 0;
2897       else
2898         {
2899           memcpy (temp_state, curr_state, dfa_state_size);
2900           cost = state_transition (temp_state, insn);
2901           if (cost < 0)
2902             cost = 0;
2903           else if (cost == 0)
2904             cost = 1;
2905         }
2906       if (cost >= 1)
2907         {
2908           ready_remove (&ready, i);
2909           queue_insn (insn, cost, reason);
2910           goto restart;
2911         }
2912     }
2913 }
2914
2915 /* Use forward list scheduling to rearrange insns of block pointed to by
2916    TARGET_BB, possibly bringing insns from subsequent blocks in the same
2917    region.  */
2918
2919 void
2920 schedule_block (basic_block *target_bb)
2921 {
2922   int i;
2923   bool first_cycle_insn_p;
2924   int can_issue_more;
2925   state_t temp_state = NULL;  /* It is used for multipass scheduling.  */
2926   int sort_p, advance, start_clock_var;
2927
2928   /* Head/tail info for this block.  */
2929   rtx prev_head = current_sched_info->prev_head;
2930   rtx next_tail = current_sched_info->next_tail;
2931   rtx head = NEXT_INSN (prev_head);
2932   rtx tail = PREV_INSN (next_tail);
2933
2934   /* We used to have code to avoid getting parameters moved from hard
2935      argument registers into pseudos.
2936
2937      However, it was removed when it proved to be of marginal benefit
2938      and caused problems because schedule_block and compute_forward_dependences
2939      had different notions of what the "head" insn was.  */
2940
2941   gcc_assert (head != tail || INSN_P (head));
2942
2943   haifa_recovery_bb_recently_added_p = false;
2944
2945   /* Debug info.  */
2946   if (sched_verbose)
2947     dump_new_block_header (0, *target_bb, head, tail);
2948
2949   state_reset (curr_state);
2950
2951   /* Clear the ready list.  */
2952   ready.first = ready.veclen - 1;
2953   ready.n_ready = 0;
2954   ready.n_debug = 0;
2955
2956   /* It is used for first cycle multipass scheduling.  */
2957   temp_state = alloca (dfa_state_size);
2958
2959   if (targetm.sched.init)
2960     targetm.sched.init (sched_dump, sched_verbose, ready.veclen);
2961
2962   /* We start inserting insns after PREV_HEAD.  */
2963   last_scheduled_insn = nonscheduled_insns_begin = prev_head;
2964   last_nondebug_scheduled_insn = NULL_RTX;
2965
2966   gcc_assert ((NOTE_P (last_scheduled_insn)
2967                || DEBUG_INSN_P (last_scheduled_insn))
2968               && BLOCK_FOR_INSN (last_scheduled_insn) == *target_bb);
2969
2970   /* Initialize INSN_QUEUE.  Q_SIZE is the total number of insns in the
2971      queue.  */
2972   q_ptr = 0;
2973   q_size = 0;
2974
2975   insn_queue = XALLOCAVEC (rtx, max_insn_queue_index + 1);
2976   memset (insn_queue, 0, (max_insn_queue_index + 1) * sizeof (rtx));
2977
2978   /* Start just before the beginning of time.  */
2979   clock_var = -1;
2980
2981   /* We need queue and ready lists and clock_var be initialized
2982      in try_ready () (which is called through init_ready_list ()).  */
2983   (*current_sched_info->init_ready_list) ();
2984
2985   /* The algorithm is O(n^2) in the number of ready insns at any given
2986      time in the worst case.  Before reload we are more likely to have
2987      big lists so truncate them to a reasonable size.  */
2988   if (!reload_completed
2989       && ready.n_ready - ready.n_debug > MAX_SCHED_READY_INSNS)
2990     {
2991       ready_sort (&ready);
2992
2993       /* Find first free-standing insn past MAX_SCHED_READY_INSNS.
2994          If there are debug insns, we know they're first.  */
2995       for (i = MAX_SCHED_READY_INSNS + ready.n_debug; i < ready.n_ready; i++)
2996         if (!SCHED_GROUP_P (ready_element (&ready, i)))
2997           break;
2998
2999       if (sched_verbose >= 2)
3000         {
3001           fprintf (sched_dump,
3002                    ";;\t\tReady list on entry: %d insns\n", ready.n_ready);
3003           fprintf (sched_dump,
3004                    ";;\t\t before reload => truncated to %d insns\n", i);
3005         }
3006
3007       /* Delay all insns past it for 1 cycle.  If debug counter is
3008          activated make an exception for the insn right after
3009          nonscheduled_insns_begin.  */
3010       {
3011         rtx skip_insn;
3012
3013         if (dbg_cnt (sched_insn) == false)
3014           skip_insn = next_nonnote_insn (nonscheduled_insns_begin);
3015         else
3016           skip_insn = NULL_RTX;
3017
3018         while (i < ready.n_ready)
3019           {
3020             rtx insn;
3021
3022             insn = ready_remove (&ready, i);
3023
3024             if (insn != skip_insn)
3025               queue_insn (insn, 1, "list truncated");
3026           }
3027         if (skip_insn)
3028           ready_add (&ready, skip_insn, true);
3029       }
3030     }
3031
3032   /* Now we can restore basic block notes and maintain precise cfg.  */
3033   restore_bb_notes (*target_bb);
3034
3035   last_clock_var = -1;
3036
3037   advance = 0;
3038
3039   gcc_assert (VEC_length (rtx, scheduled_insns) == 0);
3040   sort_p = TRUE;
3041   /* Loop until all the insns in BB are scheduled.  */
3042   while ((*current_sched_info->schedule_more_p) ())
3043     {
3044       do
3045         {
3046           start_clock_var = clock_var;
3047
3048           clock_var++;
3049
3050           advance_one_cycle ();
3051
3052           /* Add to the ready list all pending insns that can be issued now.
3053              If there are no ready insns, increment clock until one
3054              is ready and add all pending insns at that point to the ready
3055              list.  */
3056           queue_to_ready (&ready);
3057
3058           gcc_assert (ready.n_ready);
3059
3060           if (sched_verbose >= 2)
3061             {
3062               fprintf (sched_dump, ";;\t\tReady list after queue_to_ready:  ");
3063               debug_ready_list (&ready);
3064             }
3065           advance -= clock_var - start_clock_var;
3066         }
3067       while (advance > 0);
3068
3069       prune_ready_list (temp_state, true);
3070       if (ready.n_ready == 0)
3071         continue;
3072
3073       if (sort_p)
3074         {
3075           /* Sort the ready list based on priority.  */
3076           ready_sort (&ready);
3077
3078           if (sched_verbose >= 2)
3079             {
3080               fprintf (sched_dump, ";;\t\tReady list after ready_sort:  ");
3081               debug_ready_list (&ready);
3082             }
3083         }
3084
3085       /* We don't want md sched reorder to even see debug isns, so put
3086          them out right away.  */
3087       if (ready.n_ready && DEBUG_INSN_P (ready_element (&ready, 0)))
3088         {
3089           while (ready.n_ready && DEBUG_INSN_P (ready_element (&ready, 0)))
3090             {
3091               rtx insn = ready_remove_first (&ready);
3092               gcc_assert (DEBUG_INSN_P (insn));
3093               (*current_sched_info->begin_schedule_ready) (insn);
3094               VEC_safe_push (rtx, heap, scheduled_insns, insn);
3095               last_scheduled_insn = insn;
3096               advance = schedule_insn (insn);
3097               gcc_assert (advance == 0);
3098               if (ready.n_ready > 0)
3099                 ready_sort (&ready);
3100             }
3101
3102           if (!ready.n_ready)
3103             continue;
3104         }
3105
3106       /* Allow the target to reorder the list, typically for
3107          better instruction bundling.  */
3108       if (sort_p && targetm.sched.reorder
3109           && (ready.n_ready == 0
3110               || !SCHED_GROUP_P (ready_element (&ready, 0))))
3111         can_issue_more =
3112           targetm.sched.reorder (sched_dump, sched_verbose,
3113                                  ready_lastpos (&ready),
3114                                  &ready.n_ready, clock_var);
3115       else
3116         can_issue_more = issue_rate;
3117
3118       first_cycle_insn_p = true;
3119       cycle_issued_insns = 0;
3120       for (;;)
3121         {
3122           rtx insn;
3123           int cost;
3124           bool asm_p = false;
3125
3126           if (sched_verbose >= 2)
3127             {
3128               fprintf (sched_dump, ";;\tReady list (t = %3d):  ",
3129                        clock_var);
3130               debug_ready_list (&ready);
3131               if (sched_pressure_p)
3132                 print_curr_reg_pressure ();
3133             }
3134
3135           if (ready.n_ready == 0
3136               && can_issue_more
3137               && reload_completed)
3138             {
3139               /* Allow scheduling insns directly from the queue in case
3140                  there's nothing better to do (ready list is empty) but
3141                  there are still vacant dispatch slots in the current cycle.  */
3142               if (sched_verbose >= 6)
3143                 fprintf (sched_dump,";;\t\tSecond chance\n");
3144               memcpy (temp_state, curr_state, dfa_state_size);
3145               if (early_queue_to_ready (temp_state, &ready))
3146                 ready_sort (&ready);
3147             }
3148
3149           if (ready.n_ready == 0
3150               || !can_issue_more
3151               || state_dead_lock_p (curr_state)
3152               || !(*current_sched_info->schedule_more_p) ())
3153             break;
3154
3155           /* Select and remove the insn from the ready list.  */
3156           if (sort_p)
3157             {
3158               int res;
3159
3160               insn = NULL_RTX;
3161               res = choose_ready (&ready, first_cycle_insn_p, &insn);
3162
3163               if (res < 0)
3164                 /* Finish cycle.  */
3165                 break;
3166               if (res > 0)
3167                 /* Restart choose_ready ().  */
3168                 continue;
3169
3170               gcc_assert (insn != NULL_RTX);
3171             }
3172           else
3173             insn = ready_remove_first (&ready);
3174
3175           if (sched_pressure_p && INSN_TICK (insn) > clock_var)
3176             {
3177               ready_add (&ready, insn, true);
3178               advance = 1;
3179               break;
3180             }
3181
3182           if (targetm.sched.dfa_new_cycle
3183               && targetm.sched.dfa_new_cycle (sched_dump, sched_verbose,
3184                                               insn, last_clock_var,
3185                                               clock_var, &sort_p))
3186             /* SORT_P is used by the target to override sorting
3187                of the ready list.  This is needed when the target
3188                has modified its internal structures expecting that
3189                the insn will be issued next.  As we need the insn
3190                to have the highest priority (so it will be returned by
3191                the ready_remove_first call above), we invoke
3192                ready_add (&ready, insn, true).
3193                But, still, there is one issue: INSN can be later
3194                discarded by scheduler's front end through
3195                current_sched_info->can_schedule_ready_p, hence, won't
3196                be issued next.  */
3197             {
3198               ready_add (&ready, insn, true);
3199               break;
3200             }
3201
3202           sort_p = TRUE;
3203
3204           if (current_sched_info->can_schedule_ready_p
3205               && ! (*current_sched_info->can_schedule_ready_p) (insn))
3206             /* We normally get here only if we don't want to move
3207                insn from the split block.  */
3208             {
3209               TODO_SPEC (insn) = (TODO_SPEC (insn) & ~SPECULATIVE) | HARD_DEP;
3210               continue;
3211             }
3212
3213           /* DECISION is made.  */
3214
3215           if (TODO_SPEC (insn) & SPECULATIVE)
3216             generate_recovery_code (insn);
3217
3218           if (targetm.sched.dispatch (NULL_RTX, IS_DISPATCH_ON))
3219             targetm.sched.dispatch_do (insn, ADD_TO_DISPATCH_WINDOW);
3220
3221           /* Update counters, etc in the scheduler's front end.  */
3222           (*current_sched_info->begin_schedule_ready) (insn);
3223           VEC_safe_push (rtx, heap, scheduled_insns, insn);
3224           gcc_assert (NONDEBUG_INSN_P (insn));
3225           last_nondebug_scheduled_insn = last_scheduled_insn = insn;
3226
3227           if (recog_memoized (insn) >= 0)
3228             {
3229               memcpy (temp_state, curr_state, dfa_state_size);
3230               cost = state_transition (curr_state, insn);
3231               if (!sched_pressure_p)
3232                 gcc_assert (cost < 0);
3233               if (memcmp (temp_state, curr_state, dfa_state_size) != 0)
3234                 cycle_issued_insns++;
3235               asm_p = false;
3236             }
3237           else
3238             asm_p = (GET_CODE (PATTERN (insn)) == ASM_INPUT
3239                      || asm_noperands (PATTERN (insn)) >= 0);
3240
3241           if (targetm.sched.variable_issue)
3242             can_issue_more =
3243               targetm.sched.variable_issue (sched_dump, sched_verbose,
3244                                             insn, can_issue_more);
3245           /* A naked CLOBBER or USE generates no instruction, so do
3246              not count them against the issue rate.  */
3247           else if (GET_CODE (PATTERN (insn)) != USE
3248                    && GET_CODE (PATTERN (insn)) != CLOBBER)
3249             can_issue_more--;
3250           advance = schedule_insn (insn);
3251
3252           /* After issuing an asm insn we should start a new cycle.  */
3253           if (advance == 0 && asm_p)
3254             advance = 1;
3255           if (advance != 0)
3256             break;
3257
3258           first_cycle_insn_p = false;
3259
3260           if (ready.n_ready > 0)
3261             prune_ready_list (temp_state, false);
3262
3263           /* Sort the ready list based on priority.  This must be
3264              redone here, as schedule_insn may have readied additional
3265              insns that will not be sorted correctly.  */
3266           if (ready.n_ready > 0)
3267             ready_sort (&ready);
3268
3269           /* Quickly go through debug insns such that md sched
3270              reorder2 doesn't have to deal with debug insns.  */
3271           if (ready.n_ready && DEBUG_INSN_P (ready_element (&ready, 0))
3272               && (*current_sched_info->schedule_more_p) ())
3273             {
3274               while (ready.n_ready && DEBUG_INSN_P (ready_element (&ready, 0)))
3275                 {
3276                   insn = ready_remove_first (&ready);
3277                   gcc_assert (DEBUG_INSN_P (insn));
3278                   (*current_sched_info->begin_schedule_ready) (insn);
3279                   VEC_safe_push (rtx, heap, scheduled_insns, insn);
3280                   advance = schedule_insn (insn);
3281                   last_scheduled_insn = insn;
3282                   gcc_assert (advance == 0);
3283                   if (ready.n_ready > 0)
3284                     ready_sort (&ready);
3285                 }
3286             }
3287
3288           if (targetm.sched.reorder2
3289               && (ready.n_ready == 0
3290                   || !SCHED_GROUP_P (ready_element (&ready, 0))))
3291             {
3292               can_issue_more =
3293                 targetm.sched.reorder2 (sched_dump, sched_verbose,
3294                                         ready.n_ready
3295                                         ? ready_lastpos (&ready) : NULL,
3296                                         &ready.n_ready, clock_var);
3297             }
3298         }
3299     }
3300
3301   /* Debug info.  */
3302   if (sched_verbose)
3303     {
3304       fprintf (sched_dump, ";;\tReady list (final):  ");
3305       debug_ready_list (&ready);
3306     }
3307
3308   if (current_sched_info->queue_must_finish_empty)
3309     /* Sanity check -- queue must be empty now.  Meaningless if region has
3310        multiple bbs.  */
3311     gcc_assert (!q_size && !ready.n_ready && !ready.n_debug);
3312   else
3313     {
3314       /* We must maintain QUEUE_INDEX between blocks in region.  */
3315       for (i = ready.n_ready - 1; i >= 0; i--)
3316         {
3317           rtx x;
3318
3319           x = ready_element (&ready, i);
3320           QUEUE_INDEX (x) = QUEUE_NOWHERE;
3321           TODO_SPEC (x) = (TODO_SPEC (x) & ~SPECULATIVE) | HARD_DEP;
3322         }
3323
3324       if (q_size)
3325         for (i = 0; i <= max_insn_queue_index; i++)
3326           {
3327             rtx link;
3328             for (link = insn_queue[i]; link; link = XEXP (link, 1))
3329               {
3330                 rtx x;
3331
3332                 x = XEXP (link, 0);
3333                 QUEUE_INDEX (x) = QUEUE_NOWHERE;
3334                 TODO_SPEC (x) = (TODO_SPEC (x) & ~SPECULATIVE) | HARD_DEP;
3335               }
3336             free_INSN_LIST_list (&insn_queue[i]);
3337           }
3338     }
3339
3340   commit_schedule (prev_head, tail, target_bb);
3341   if (sched_verbose)
3342     fprintf (sched_dump, ";;   total time = %d\n", clock_var);
3343
3344   if (!current_sched_info->queue_must_finish_empty
3345       || haifa_recovery_bb_recently_added_p)
3346     {
3347       /* INSN_TICK (minimum clock tick at which the insn becomes
3348          ready) may be not correct for the insn in the subsequent
3349          blocks of the region.  We should use a correct value of
3350          `clock_var' or modify INSN_TICK.  It is better to keep
3351          clock_var value equal to 0 at the start of a basic block.
3352          Therefore we modify INSN_TICK here.  */
3353       fix_inter_tick (NEXT_INSN (prev_head), last_scheduled_insn);
3354     }
3355
3356   if (targetm.sched.finish)
3357     {
3358       targetm.sched.finish (sched_dump, sched_verbose);
3359       /* Target might have added some instructions to the scheduled block
3360          in its md_finish () hook.  These new insns don't have any data
3361          initialized and to identify them we extend h_i_d so that they'll
3362          get zero luids.  */
3363       sched_init_luids (NULL, NULL, NULL, NULL);
3364     }
3365
3366   if (sched_verbose)
3367     fprintf (sched_dump, ";;   new head = %d\n;;   new tail = %d\n\n",
3368              INSN_UID (head), INSN_UID (tail));
3369
3370   /* Update head/tail boundaries.  */
3371   head = NEXT_INSN (prev_head);
3372   tail = last_scheduled_insn;
3373
3374   head = restore_other_notes (head, NULL);
3375
3376   current_sched_info->head = head;
3377   current_sched_info->tail = tail;
3378 }
3379 \f
3380 /* Set_priorities: compute priority of each insn in the block.  */
3381
3382 int
3383 set_priorities (rtx head, rtx tail)
3384 {
3385   rtx insn;
3386   int n_insn;
3387   int sched_max_insns_priority =
3388         current_sched_info->sched_max_insns_priority;
3389   rtx prev_head;
3390
3391   if (head == tail && ! INSN_P (head))
3392     gcc_unreachable ();
3393
3394   n_insn = 0;
3395
3396   prev_head = PREV_INSN (head);
3397   for (insn = tail; insn != prev_head; insn = PREV_INSN (insn))
3398     {
3399       if (!INSN_P (insn))
3400         continue;
3401
3402       n_insn++;
3403       (void) priority (insn);
3404
3405       gcc_assert (INSN_PRIORITY_KNOWN (insn));
3406
3407       sched_max_insns_priority = MAX (sched_max_insns_priority,
3408                                       INSN_PRIORITY (insn));
3409     }
3410
3411   current_sched_info->sched_max_insns_priority = sched_max_insns_priority;
3412
3413   return n_insn;
3414 }
3415
3416 /* Set dump and sched_verbose for the desired debugging output.  If no
3417    dump-file was specified, but -fsched-verbose=N (any N), print to stderr.
3418    For -fsched-verbose=N, N>=10, print everything to stderr.  */
3419 void
3420 setup_sched_dump (void)
3421 {
3422   sched_verbose = sched_verbose_param;
3423   if (sched_verbose_param == 0 && dump_file)
3424     sched_verbose = 1;
3425   sched_dump = ((sched_verbose_param >= 10 || !dump_file)
3426                 ? stderr : dump_file);
3427 }
3428
3429 /* Initialize some global state for the scheduler.  This function works
3430    with the common data shared between all the schedulers.  It is called
3431    from the scheduler specific initialization routine.  */
3432
3433 void
3434 sched_init (void)
3435 {
3436   /* Disable speculative loads in their presence if cc0 defined.  */
3437 #ifdef HAVE_cc0
3438   flag_schedule_speculative_load = 0;
3439 #endif
3440
3441   if (targetm.sched.dispatch (NULL_RTX, IS_DISPATCH_ON))
3442     targetm.sched.dispatch_do (NULL_RTX, DISPATCH_INIT);
3443
3444   sched_pressure_p = (flag_sched_pressure && ! reload_completed
3445                       && common_sched_info->sched_pass_id == SCHED_RGN_PASS);
3446
3447   if (sched_pressure_p)
3448     ira_setup_eliminable_regset ();
3449
3450   /* Initialize SPEC_INFO.  */
3451   if (targetm.sched.set_sched_flags)
3452     {
3453       spec_info = &spec_info_var;
3454       targetm.sched.set_sched_flags (spec_info);
3455
3456       if (spec_info->mask != 0)
3457         {
3458           spec_info->data_weakness_cutoff =
3459             (PARAM_VALUE (PARAM_SCHED_SPEC_PROB_CUTOFF) * MAX_DEP_WEAK) / 100;
3460           spec_info->control_weakness_cutoff =
3461             (PARAM_VALUE (PARAM_SCHED_SPEC_PROB_CUTOFF)
3462              * REG_BR_PROB_BASE) / 100;
3463         }
3464       else
3465         /* So we won't read anything accidentally.  */
3466         spec_info = NULL;
3467
3468     }
3469   else
3470     /* So we won't read anything accidentally.  */
3471     spec_info = 0;
3472
3473   /* Initialize issue_rate.  */
3474   if (targetm.sched.issue_rate)
3475     issue_rate = targetm.sched.issue_rate ();
3476   else
3477     issue_rate = 1;
3478
3479   if (cached_issue_rate != issue_rate)
3480     {
3481       cached_issue_rate = issue_rate;
3482       /* To invalidate max_lookahead_tries:  */
3483       cached_first_cycle_multipass_dfa_lookahead = 0;
3484     }
3485
3486   if (targetm.sched.first_cycle_multipass_dfa_lookahead)
3487     dfa_lookahead = targetm.sched.first_cycle_multipass_dfa_lookahead ();
3488   else
3489     dfa_lookahead = 0;
3490
3491   if (targetm.sched.init_dfa_pre_cycle_insn)
3492     targetm.sched.init_dfa_pre_cycle_insn ();
3493
3494   if (targetm.sched.init_dfa_post_cycle_insn)
3495     targetm.sched.init_dfa_post_cycle_insn ();
3496
3497   dfa_start ();
3498   dfa_state_size = state_size ();
3499
3500   init_alias_analysis ();
3501
3502   df_set_flags (DF_LR_RUN_DCE);
3503   df_note_add_problem ();
3504
3505   /* More problems needed for interloop dep calculation in SMS.  */
3506   if (common_sched_info->sched_pass_id == SCHED_SMS_PASS)
3507     {
3508       df_rd_add_problem ();
3509       df_chain_add_problem (DF_DU_CHAIN + DF_UD_CHAIN);
3510     }
3511
3512   df_analyze ();
3513
3514   /* Do not run DCE after reload, as this can kill nops inserted
3515      by bundling.  */
3516   if (reload_completed)
3517     df_clear_flags (DF_LR_RUN_DCE);
3518
3519   regstat_compute_calls_crossed ();
3520
3521   if (targetm.sched.init_global)
3522     targetm.sched.init_global (sched_dump, sched_verbose, get_max_uid () + 1);
3523
3524   if (sched_pressure_p)
3525     {
3526       int i, max_regno = max_reg_num ();
3527
3528       ira_set_pseudo_classes (sched_verbose ? sched_dump : NULL);
3529       sched_regno_pressure_class
3530         = (enum reg_class *) xmalloc (max_regno * sizeof (enum reg_class));
3531       for (i = 0; i < max_regno; i++)
3532         sched_regno_pressure_class[i]
3533           = (i < FIRST_PSEUDO_REGISTER
3534              ? ira_pressure_class_translate[REGNO_REG_CLASS (i)]
3535              : ira_pressure_class_translate[reg_allocno_class (i)]);
3536       curr_reg_live = BITMAP_ALLOC (NULL);
3537       saved_reg_live = BITMAP_ALLOC (NULL);
3538       region_ref_regs = BITMAP_ALLOC (NULL);
3539     }
3540
3541   curr_state = xmalloc (dfa_state_size);
3542 }
3543
3544 static void haifa_init_only_bb (basic_block, basic_block);
3545
3546 /* Initialize data structures specific to the Haifa scheduler.  */
3547 void
3548 haifa_sched_init (void)
3549 {
3550   setup_sched_dump ();
3551   sched_init ();
3552
3553   scheduled_insns = VEC_alloc (rtx, heap, 0);
3554
3555   if (spec_info != NULL)
3556     {
3557       sched_deps_info->use_deps_list = 1;
3558       sched_deps_info->generate_spec_deps = 1;
3559     }
3560
3561   /* Initialize luids, dependency caches, target and h_i_d for the
3562      whole function.  */
3563   {
3564     bb_vec_t bbs = VEC_alloc (basic_block, heap, n_basic_blocks);
3565     basic_block bb;
3566
3567     sched_init_bbs ();
3568
3569     FOR_EACH_BB (bb)
3570       VEC_quick_push (basic_block, bbs, bb);
3571     sched_init_luids (bbs, NULL, NULL, NULL);
3572     sched_deps_init (true);
3573     sched_extend_target ();
3574     haifa_init_h_i_d (bbs, NULL, NULL, NULL);
3575
3576     VEC_free (basic_block, heap, bbs);
3577   }
3578
3579   sched_init_only_bb = haifa_init_only_bb;
3580   sched_split_block = sched_split_block_1;
3581   sched_create_empty_bb = sched_create_empty_bb_1;
3582   haifa_recovery_bb_ever_added_p = false;
3583
3584 #ifdef ENABLE_CHECKING
3585   /* This is used preferably for finding bugs in check_cfg () itself.
3586      We must call sched_bbs_init () before check_cfg () because check_cfg ()
3587      assumes that the last insn in the last bb has a non-null successor.  */
3588   check_cfg (0, 0);
3589 #endif
3590
3591   nr_begin_data = nr_begin_control = nr_be_in_data = nr_be_in_control = 0;
3592   before_recovery = 0;
3593   after_recovery = 0;
3594 }
3595
3596 /* Finish work with the data specific to the Haifa scheduler.  */
3597 void
3598 haifa_sched_finish (void)
3599 {
3600   sched_create_empty_bb = NULL;
3601   sched_split_block = NULL;
3602   sched_init_only_bb = NULL;
3603
3604   if (spec_info && spec_info->dump)
3605     {
3606       char c = reload_completed ? 'a' : 'b';
3607
3608       fprintf (spec_info->dump,
3609                ";; %s:\n", current_function_name ());
3610
3611       fprintf (spec_info->dump,
3612                ";; Procedure %cr-begin-data-spec motions == %d\n",
3613                c, nr_begin_data);
3614       fprintf (spec_info->dump,
3615                ";; Procedure %cr-be-in-data-spec motions == %d\n",
3616                c, nr_be_in_data);
3617       fprintf (spec_info->dump,
3618                ";; Procedure %cr-begin-control-spec motions == %d\n",
3619                c, nr_begin_control);
3620       fprintf (spec_info->dump,
3621                ";; Procedure %cr-be-in-control-spec motions == %d\n",
3622                c, nr_be_in_control);
3623     }
3624
3625   VEC_free (rtx, heap, scheduled_insns);
3626
3627   /* Finalize h_i_d, dependency caches, and luids for the whole
3628      function.  Target will be finalized in md_global_finish ().  */
3629   sched_deps_finish ();
3630   sched_finish_luids ();
3631   current_sched_info = NULL;
3632   sched_finish ();
3633 }
3634
3635 /* Free global data used during insn scheduling.  This function works with
3636    the common data shared between the schedulers.  */
3637
3638 void
3639 sched_finish (void)
3640 {
3641   haifa_finish_h_i_d ();
3642   if (sched_pressure_p)
3643     {
3644       free (sched_regno_pressure_class);
3645       BITMAP_FREE (region_ref_regs);
3646       BITMAP_FREE (saved_reg_live);
3647       BITMAP_FREE (curr_reg_live);
3648     }
3649   free (curr_state);
3650
3651   if (targetm.sched.finish_global)
3652     targetm.sched.finish_global (sched_dump, sched_verbose);
3653
3654   end_alias_analysis ();
3655
3656   regstat_free_calls_crossed ();
3657
3658   dfa_finish ();
3659
3660 #ifdef ENABLE_CHECKING
3661   /* After reload ia64 backend clobbers CFG, so can't check anything.  */
3662   if (!reload_completed)
3663     check_cfg (0, 0);
3664 #endif
3665 }
3666
3667 /* Fix INSN_TICKs of the instructions in the current block as well as
3668    INSN_TICKs of their dependents.
3669    HEAD and TAIL are the begin and the end of the current scheduled block.  */
3670 static void
3671 fix_inter_tick (rtx head, rtx tail)
3672 {
3673   /* Set of instructions with corrected INSN_TICK.  */
3674   bitmap_head processed;
3675   /* ??? It is doubtful if we should assume that cycle advance happens on
3676      basic block boundaries.  Basically insns that are unconditionally ready
3677      on the start of the block are more preferable then those which have
3678      a one cycle dependency over insn from the previous block.  */
3679   int next_clock = clock_var + 1;
3680
3681   bitmap_initialize (&processed, 0);
3682
3683   /* Iterates over scheduled instructions and fix their INSN_TICKs and
3684      INSN_TICKs of dependent instructions, so that INSN_TICKs are consistent
3685      across different blocks.  */
3686   for (tail = NEXT_INSN (tail); head != tail; head = NEXT_INSN (head))
3687     {
3688       if (INSN_P (head))
3689         {
3690           int tick;
3691           sd_iterator_def sd_it;
3692           dep_t dep;
3693
3694           tick = INSN_TICK (head);
3695           gcc_assert (tick >= MIN_TICK);
3696
3697           /* Fix INSN_TICK of instruction from just scheduled block.  */
3698           if (bitmap_set_bit (&processed, INSN_LUID (head)))
3699             {
3700               tick -= next_clock;
3701
3702               if (tick < MIN_TICK)
3703                 tick = MIN_TICK;
3704
3705               INSN_TICK (head) = tick;
3706             }
3707
3708           FOR_EACH_DEP (head, SD_LIST_RES_FORW, sd_it, dep)
3709             {
3710               rtx next;
3711
3712               next = DEP_CON (dep);
3713               tick = INSN_TICK (next);
3714
3715               if (tick != INVALID_TICK
3716                   /* If NEXT has its INSN_TICK calculated, fix it.
3717                      If not - it will be properly calculated from
3718                      scratch later in fix_tick_ready.  */
3719                   && bitmap_set_bit (&processed, INSN_LUID (next)))
3720                 {
3721                   tick -= next_clock;
3722
3723                   if (tick < MIN_TICK)
3724                     tick = MIN_TICK;
3725
3726                   if (tick > INTER_TICK (next))
3727                     INTER_TICK (next) = tick;
3728                   else
3729                     tick = INTER_TICK (next);
3730
3731                   INSN_TICK (next) = tick;
3732                 }
3733             }
3734         }
3735     }
3736   bitmap_clear (&processed);
3737 }
3738
3739 static int haifa_speculate_insn (rtx, ds_t, rtx *);
3740
3741 /* Check if NEXT is ready to be added to the ready or queue list.
3742    If "yes", add it to the proper list.
3743    Returns:
3744       -1 - is not ready yet,
3745        0 - added to the ready list,
3746    0 < N - queued for N cycles.  */
3747 int
3748 try_ready (rtx next)
3749 {
3750   ds_t old_ts, *ts;
3751
3752   ts = &TODO_SPEC (next);
3753   old_ts = *ts;
3754
3755   gcc_assert (!(old_ts & ~(SPECULATIVE | HARD_DEP))
3756               && ((old_ts & HARD_DEP)
3757                   || (old_ts & SPECULATIVE)));
3758
3759   if (sd_lists_empty_p (next, SD_LIST_BACK))
3760     /* NEXT has all its dependencies resolved.  */
3761     {
3762       /* Remove HARD_DEP bit from NEXT's status.  */
3763       *ts &= ~HARD_DEP;
3764
3765       if (current_sched_info->flags & DO_SPECULATION)
3766         /* Remove all speculative bits from NEXT's status.  */
3767         *ts &= ~SPECULATIVE;
3768     }
3769   else
3770     {
3771       /* One of the NEXT's dependencies has been resolved.
3772          Recalculate NEXT's status.  */
3773
3774       *ts &= ~SPECULATIVE & ~HARD_DEP;
3775
3776       if (sd_lists_empty_p (next, SD_LIST_HARD_BACK))
3777         /* Now we've got NEXT with speculative deps only.
3778            1. Look at the deps to see what we have to do.
3779            2. Check if we can do 'todo'.  */
3780         {
3781           sd_iterator_def sd_it;
3782           dep_t dep;
3783           bool first_p = true;
3784
3785           FOR_EACH_DEP (next, SD_LIST_BACK, sd_it, dep)
3786             {
3787               ds_t ds = DEP_STATUS (dep) & SPECULATIVE;
3788
3789               if (DEBUG_INSN_P (DEP_PRO (dep))
3790                   && !DEBUG_INSN_P (next))
3791                 continue;
3792
3793               if (first_p)
3794                 {
3795                   first_p = false;
3796
3797                   *ts = ds;
3798                 }
3799               else
3800                 *ts = ds_merge (*ts, ds);
3801             }
3802
3803           if (ds_weak (*ts) < spec_info->data_weakness_cutoff)
3804             /* Too few points.  */
3805             *ts = (*ts & ~SPECULATIVE) | HARD_DEP;
3806         }
3807       else
3808         *ts |= HARD_DEP;
3809     }
3810
3811   if (*ts & HARD_DEP)
3812     gcc_assert (*ts == old_ts
3813                 && QUEUE_INDEX (next) == QUEUE_NOWHERE);
3814   else if (current_sched_info->new_ready)
3815     *ts = current_sched_info->new_ready (next, *ts);
3816
3817   /* * if !(old_ts & SPECULATIVE) (e.g. HARD_DEP or 0), then insn might
3818      have its original pattern or changed (speculative) one.  This is due
3819      to changing ebb in region scheduling.
3820      * But if (old_ts & SPECULATIVE), then we are pretty sure that insn
3821      has speculative pattern.
3822
3823      We can't assert (!(*ts & HARD_DEP) || *ts == old_ts) here because
3824      control-speculative NEXT could have been discarded by sched-rgn.c
3825      (the same case as when discarded by can_schedule_ready_p ()).  */
3826
3827   if ((*ts & SPECULATIVE)
3828       /* If (old_ts == *ts), then (old_ts & SPECULATIVE) and we don't
3829          need to change anything.  */
3830       && *ts != old_ts)
3831     {
3832       int res;
3833       rtx new_pat;
3834
3835       gcc_assert ((*ts & SPECULATIVE) && !(*ts & ~SPECULATIVE));
3836
3837       res = haifa_speculate_insn (next, *ts, &new_pat);
3838
3839       switch (res)
3840         {
3841         case -1:
3842           /* It would be nice to change DEP_STATUS of all dependences,
3843              which have ((DEP_STATUS & SPECULATIVE) == *ts) to HARD_DEP,
3844              so we won't reanalyze anything.  */
3845           *ts = (*ts & ~SPECULATIVE) | HARD_DEP;
3846           break;
3847
3848         case 0:
3849           /* We follow the rule, that every speculative insn
3850              has non-null ORIG_PAT.  */
3851           if (!ORIG_PAT (next))
3852             ORIG_PAT (next) = PATTERN (next);
3853           break;
3854
3855         case 1:
3856           if (!ORIG_PAT (next))
3857             /* If we gonna to overwrite the original pattern of insn,
3858                save it.  */
3859             ORIG_PAT (next) = PATTERN (next);
3860
3861           haifa_change_pattern (next, new_pat);
3862           break;
3863
3864         default:
3865           gcc_unreachable ();
3866         }
3867     }
3868
3869   /* We need to restore pattern only if (*ts == 0), because otherwise it is
3870      either correct (*ts & SPECULATIVE),
3871      or we simply don't care (*ts & HARD_DEP).  */
3872
3873   gcc_assert (!ORIG_PAT (next)
3874               || !IS_SPECULATION_BRANCHY_CHECK_P (next));
3875
3876   if (*ts & HARD_DEP)
3877     {
3878       /* We can't assert (QUEUE_INDEX (next) == QUEUE_NOWHERE) here because
3879          control-speculative NEXT could have been discarded by sched-rgn.c
3880          (the same case as when discarded by can_schedule_ready_p ()).  */
3881       /*gcc_assert (QUEUE_INDEX (next) == QUEUE_NOWHERE);*/
3882
3883       change_queue_index (next, QUEUE_NOWHERE);
3884       return -1;
3885     }
3886   else if (!(*ts & BEGIN_SPEC) && ORIG_PAT (next) && !IS_SPECULATION_CHECK_P (next))
3887     /* We should change pattern of every previously speculative
3888        instruction - and we determine if NEXT was speculative by using
3889        ORIG_PAT field.  Except one case - speculation checks have ORIG_PAT
3890        pat too, so skip them.  */
3891     {
3892       haifa_change_pattern (next, ORIG_PAT (next));
3893       ORIG_PAT (next) = 0;
3894     }
3895
3896   if (sched_verbose >= 2)
3897     {
3898       int s = TODO_SPEC (next);
3899
3900       fprintf (sched_dump, ";;\t\tdependencies resolved: insn %s",
3901                (*current_sched_info->print_insn) (next, 0));
3902
3903       if (spec_info && spec_info->dump)
3904         {
3905           if (s & BEGIN_DATA)
3906             fprintf (spec_info->dump, "; data-spec;");
3907           if (s & BEGIN_CONTROL)
3908             fprintf (spec_info->dump, "; control-spec;");
3909           if (s & BE_IN_CONTROL)
3910             fprintf (spec_info->dump, "; in-control-spec;");
3911         }
3912
3913       fprintf (sched_dump, "\n");
3914     }
3915
3916   adjust_priority (next);
3917
3918   return fix_tick_ready (next);
3919 }
3920
3921 /* Calculate INSN_TICK of NEXT and add it to either ready or queue list.  */
3922 static int
3923 fix_tick_ready (rtx next)
3924 {
3925   int tick, delay;
3926
3927   if (!DEBUG_INSN_P (next) && !sd_lists_empty_p (next, SD_LIST_RES_BACK))
3928     {
3929       int full_p;
3930       sd_iterator_def sd_it;
3931       dep_t dep;
3932
3933       tick = INSN_TICK (next);
3934       /* if tick is not equal to INVALID_TICK, then update
3935          INSN_TICK of NEXT with the most recent resolved dependence
3936          cost.  Otherwise, recalculate from scratch.  */
3937       full_p = (tick == INVALID_TICK);
3938
3939       FOR_EACH_DEP (next, SD_LIST_RES_BACK, sd_it, dep)
3940         {
3941           rtx pro = DEP_PRO (dep);
3942           int tick1;
3943
3944           gcc_assert (INSN_TICK (pro) >= MIN_TICK);
3945
3946           tick1 = INSN_TICK (pro) + dep_cost (dep);
3947           if (tick1 > tick)
3948             tick = tick1;
3949
3950           if (!full_p)
3951             break;
3952         }
3953     }
3954   else
3955     tick = -1;
3956
3957   INSN_TICK (next) = tick;
3958
3959   delay = tick - clock_var;
3960   if (delay <= 0 || sched_pressure_p)
3961     delay = QUEUE_READY;
3962
3963   change_queue_index (next, delay);
3964
3965   return delay;
3966 }
3967
3968 /* Move NEXT to the proper queue list with (DELAY >= 1),
3969    or add it to the ready list (DELAY == QUEUE_READY),
3970    or remove it from ready and queue lists at all (DELAY == QUEUE_NOWHERE).  */
3971 static void
3972 change_queue_index (rtx next, int delay)
3973 {
3974   int i = QUEUE_INDEX (next);
3975
3976   gcc_assert (QUEUE_NOWHERE <= delay && delay <= max_insn_queue_index
3977               && delay != 0);
3978   gcc_assert (i != QUEUE_SCHEDULED);
3979
3980   if ((delay > 0 && NEXT_Q_AFTER (q_ptr, delay) == i)
3981       || (delay < 0 && delay == i))
3982     /* We have nothing to do.  */
3983     return;
3984
3985   /* Remove NEXT from wherever it is now.  */
3986   if (i == QUEUE_READY)
3987     ready_remove_insn (next);
3988   else if (i >= 0)
3989     queue_remove (next);
3990
3991   /* Add it to the proper place.  */
3992   if (delay == QUEUE_READY)
3993     ready_add (readyp, next, false);
3994   else if (delay >= 1)
3995     queue_insn (next, delay, "change queue index");
3996
3997   if (sched_verbose >= 2)
3998     {
3999       fprintf (sched_dump, ";;\t\ttick updated: insn %s",
4000                (*current_sched_info->print_insn) (next, 0));
4001
4002       if (delay == QUEUE_READY)
4003         fprintf (sched_dump, " into ready\n");
4004       else if (delay >= 1)
4005         fprintf (sched_dump, " into queue with cost=%d\n", delay);
4006       else
4007         fprintf (sched_dump, " removed from ready or queue lists\n");
4008     }
4009 }
4010
4011 static int sched_ready_n_insns = -1;
4012
4013 /* Initialize per region data structures.  */
4014 void
4015 sched_extend_ready_list (int new_sched_ready_n_insns)
4016 {
4017   int i;
4018
4019   if (sched_ready_n_insns == -1)
4020     /* At the first call we need to initialize one more choice_stack
4021        entry.  */
4022     {
4023       i = 0;
4024       sched_ready_n_insns = 0;
4025       VEC_reserve (rtx, heap, scheduled_insns, new_sched_ready_n_insns);
4026     }
4027   else
4028     i = sched_ready_n_insns + 1;
4029
4030   ready.veclen = new_sched_ready_n_insns + issue_rate;
4031   ready.vec = XRESIZEVEC (rtx, ready.vec, ready.veclen);
4032
4033   gcc_assert (new_sched_ready_n_insns >= sched_ready_n_insns);
4034
4035   ready_try = (char *) xrecalloc (ready_try, new_sched_ready_n_insns,
4036                                   sched_ready_n_insns, sizeof (*ready_try));
4037
4038   /* We allocate +1 element to save initial state in the choice_stack[0]
4039      entry.  */
4040   choice_stack = XRESIZEVEC (struct choice_entry, choice_stack,
4041                              new_sched_ready_n_insns + 1);
4042
4043   for (; i <= new_sched_ready_n_insns; i++)
4044     {
4045       choice_stack[i].state = xmalloc (dfa_state_size);
4046
4047       if (targetm.sched.first_cycle_multipass_init)
4048         targetm.sched.first_cycle_multipass_init (&(choice_stack[i]
4049                                                     .target_data));
4050     }
4051
4052   sched_ready_n_insns = new_sched_ready_n_insns;
4053 }
4054
4055 /* Free per region data structures.  */
4056 void
4057 sched_finish_ready_list (void)
4058 {
4059   int i;
4060
4061   free (ready.vec);
4062   ready.vec = NULL;
4063   ready.veclen = 0;
4064
4065   free (ready_try);
4066   ready_try = NULL;
4067
4068   for (i = 0; i <= sched_ready_n_insns; i++)
4069     {
4070       if (targetm.sched.first_cycle_multipass_fini)
4071         targetm.sched.first_cycle_multipass_fini (&(choice_stack[i]
4072                                                     .target_data));
4073
4074       free (choice_stack [i].state);
4075     }
4076   free (choice_stack);
4077   choice_stack = NULL;
4078
4079   sched_ready_n_insns = -1;
4080 }
4081
4082 static int
4083 haifa_luid_for_non_insn (rtx x)
4084 {
4085   gcc_assert (NOTE_P (x) || LABEL_P (x));
4086
4087   return 0;
4088 }
4089
4090 /* Generates recovery code for INSN.  */
4091 static void
4092 generate_recovery_code (rtx insn)
4093 {
4094   if (TODO_SPEC (insn) & BEGIN_SPEC)
4095     begin_speculative_block (insn);
4096
4097   /* Here we have insn with no dependencies to
4098      instructions other then CHECK_SPEC ones.  */
4099
4100   if (TODO_SPEC (insn) & BE_IN_SPEC)
4101     add_to_speculative_block (insn);
4102 }
4103
4104 /* Helper function.
4105    Tries to add speculative dependencies of type FS between instructions
4106    in deps_list L and TWIN.  */
4107 static void
4108 process_insn_forw_deps_be_in_spec (rtx insn, rtx twin, ds_t fs)
4109 {
4110   sd_iterator_def sd_it;
4111   dep_t dep;
4112
4113   FOR_EACH_DEP (insn, SD_LIST_FORW, sd_it, dep)
4114     {
4115       ds_t ds;
4116       rtx consumer;
4117
4118       consumer = DEP_CON (dep);
4119
4120       ds = DEP_STATUS (dep);
4121
4122       if (/* If we want to create speculative dep.  */
4123           fs
4124           /* And we can do that because this is a true dep.  */
4125           && (ds & DEP_TYPES) == DEP_TRUE)
4126         {
4127           gcc_assert (!(ds & BE_IN_SPEC));
4128
4129           if (/* If this dep can be overcome with 'begin speculation'.  */
4130               ds & BEGIN_SPEC)
4131             /* Then we have a choice: keep the dep 'begin speculative'
4132                or transform it into 'be in speculative'.  */
4133             {
4134               if (/* In try_ready we assert that if insn once became ready
4135                      it can be removed from the ready (or queue) list only
4136                      due to backend decision.  Hence we can't let the
4137                      probability of the speculative dep to decrease.  */
4138                   ds_weak (ds) <= ds_weak (fs))
4139                 {
4140                   ds_t new_ds;
4141
4142                   new_ds = (ds & ~BEGIN_SPEC) | fs;
4143
4144                   if (/* consumer can 'be in speculative'.  */
4145                       sched_insn_is_legitimate_for_speculation_p (consumer,
4146                                                                   new_ds))
4147                     /* Transform it to be in speculative.  */
4148                     ds = new_ds;
4149                 }
4150             }
4151           else
4152             /* Mark the dep as 'be in speculative'.  */
4153             ds |= fs;
4154         }
4155
4156       {
4157         dep_def _new_dep, *new_dep = &_new_dep;
4158
4159         init_dep_1 (new_dep, twin, consumer, DEP_TYPE (dep), ds);
4160         sd_add_dep (new_dep, false);
4161       }
4162     }
4163 }
4164
4165 /* Generates recovery code for BEGIN speculative INSN.  */
4166 static void
4167 begin_speculative_block (rtx insn)
4168 {
4169   if (TODO_SPEC (insn) & BEGIN_DATA)
4170     nr_begin_data++;
4171   if (TODO_SPEC (insn) & BEGIN_CONTROL)
4172     nr_begin_control++;
4173
4174   create_check_block_twin (insn, false);
4175
4176   TODO_SPEC (insn) &= ~BEGIN_SPEC;
4177 }
4178
4179 static void haifa_init_insn (rtx);
4180
4181 /* Generates recovery code for BE_IN speculative INSN.  */
4182 static void
4183 add_to_speculative_block (rtx insn)
4184 {
4185   ds_t ts;
4186   sd_iterator_def sd_it;
4187   dep_t dep;
4188   rtx twins = NULL;
4189   rtx_vec_t priorities_roots;
4190
4191   ts = TODO_SPEC (insn);
4192   gcc_assert (!(ts & ~BE_IN_SPEC));
4193
4194   if (ts & BE_IN_DATA)
4195     nr_be_in_data++;
4196   if (ts & BE_IN_CONTROL)
4197     nr_be_in_control++;
4198
4199   TODO_SPEC (insn) &= ~BE_IN_SPEC;
4200   gcc_assert (!TODO_SPEC (insn));
4201
4202   DONE_SPEC (insn) |= ts;
4203
4204   /* First we convert all simple checks to branchy.  */
4205   for (sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
4206        sd_iterator_cond (&sd_it, &dep);)
4207     {
4208       rtx check = DEP_PRO (dep);
4209
4210       if (IS_SPECULATION_SIMPLE_CHECK_P (check))
4211         {
4212           create_check_block_twin (check, true);
4213
4214           /* Restart search.  */
4215           sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
4216         }
4217       else
4218         /* Continue search.  */
4219         sd_iterator_next (&sd_it);
4220     }
4221
4222   priorities_roots = NULL;
4223   clear_priorities (insn, &priorities_roots);
4224
4225   while (1)
4226     {
4227       rtx check, twin;
4228       basic_block rec;
4229
4230       /* Get the first backward dependency of INSN.  */
4231       sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
4232       if (!sd_iterator_cond (&sd_it, &dep))
4233         /* INSN has no backward dependencies left.  */
4234         break;
4235
4236       gcc_assert ((DEP_STATUS (dep) & BEGIN_SPEC) == 0
4237                   && (DEP_STATUS (dep) & BE_IN_SPEC) != 0
4238                   && (DEP_STATUS (dep) & DEP_TYPES) == DEP_TRUE);
4239
4240       check = DEP_PRO (dep);
4241
4242       gcc_assert (!IS_SPECULATION_CHECK_P (check) && !ORIG_PAT (check)
4243                   && QUEUE_INDEX (check) == QUEUE_NOWHERE);
4244
4245       rec = BLOCK_FOR_INSN (check);
4246
4247       twin = emit_insn_before (copy_insn (PATTERN (insn)), BB_END (rec));
4248       haifa_init_insn (twin);
4249
4250       sd_copy_back_deps (twin, insn, true);
4251
4252       if (sched_verbose && spec_info->dump)
4253         /* INSN_BB (insn) isn't determined for twin insns yet.
4254            So we can't use current_sched_info->print_insn.  */
4255         fprintf (spec_info->dump, ";;\t\tGenerated twin insn : %d/rec%d\n",
4256                  INSN_UID (twin), rec->index);
4257
4258       twins = alloc_INSN_LIST (twin, twins);
4259
4260       /* Add dependences between TWIN and all appropriate
4261          instructions from REC.  */
4262       FOR_EACH_DEP (insn, SD_LIST_SPEC_BACK, sd_it, dep)
4263         {
4264           rtx pro = DEP_PRO (dep);
4265
4266           gcc_assert (DEP_TYPE (dep) == REG_DEP_TRUE);
4267
4268           /* INSN might have dependencies from the instructions from
4269              several recovery blocks.  At this iteration we process those
4270              producers that reside in REC.  */
4271           if (BLOCK_FOR_INSN (pro) == rec)
4272             {
4273               dep_def _new_dep, *new_dep = &_new_dep;
4274
4275               init_dep (new_dep, pro, twin, REG_DEP_TRUE);
4276               sd_add_dep (new_dep, false);
4277             }
4278         }
4279
4280       process_insn_forw_deps_be_in_spec (insn, twin, ts);
4281
4282       /* Remove all dependencies between INSN and insns in REC.  */
4283       for (sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
4284            sd_iterator_cond (&sd_it, &dep);)
4285         {
4286           rtx pro = DEP_PRO (dep);
4287
4288           if (BLOCK_FOR_INSN (pro) == rec)
4289             sd_delete_dep (sd_it);
4290           else
4291             sd_iterator_next (&sd_it);
4292         }
4293     }
4294
4295   /* We couldn't have added the dependencies between INSN and TWINS earlier
4296      because that would make TWINS appear in the INSN_BACK_DEPS (INSN).  */
4297   while (twins)
4298     {
4299       rtx twin;
4300
4301       twin = XEXP (twins, 0);
4302
4303       {
4304         dep_def _new_dep, *new_dep = &_new_dep;
4305
4306         init_dep (new_dep, insn, twin, REG_DEP_OUTPUT);
4307         sd_add_dep (new_dep, false);
4308       }
4309
4310       twin = XEXP (twins, 1);
4311       free_INSN_LIST_node (twins);
4312       twins = twin;
4313     }
4314
4315   calc_priorities (priorities_roots);
4316   VEC_free (rtx, heap, priorities_roots);
4317 }
4318
4319 /* Extends and fills with zeros (only the new part) array pointed to by P.  */
4320 void *
4321 xrecalloc (void *p, size_t new_nmemb, size_t old_nmemb, size_t size)
4322 {
4323   gcc_assert (new_nmemb >= old_nmemb);
4324   p = XRESIZEVAR (void, p, new_nmemb * size);
4325   memset (((char *) p) + old_nmemb * size, 0, (new_nmemb - old_nmemb) * size);
4326   return p;
4327 }
4328
4329 /* Helper function.
4330    Find fallthru edge from PRED.  */
4331 edge
4332 find_fallthru_edge_from (basic_block pred)
4333 {
4334   edge e;
4335   basic_block succ;
4336
4337   succ = pred->next_bb;
4338   gcc_assert (succ->prev_bb == pred);
4339
4340   if (EDGE_COUNT (pred->succs) <= EDGE_COUNT (succ->preds))
4341     {
4342       e = find_fallthru_edge (pred->succs);
4343
4344       if (e)
4345         {
4346           gcc_assert (e->dest == succ);
4347           return e;
4348         }
4349     }
4350   else
4351     {
4352       e = find_fallthru_edge (succ->preds);
4353
4354       if (e)
4355         {
4356           gcc_assert (e->src == pred);
4357           return e;
4358         }
4359     }
4360
4361   return NULL;
4362 }
4363
4364 /* Extend per basic block data structures.  */
4365 static void
4366 sched_extend_bb (void)
4367 {
4368   rtx insn;
4369
4370   /* The following is done to keep current_sched_info->next_tail non null.  */
4371   insn = BB_END (EXIT_BLOCK_PTR->prev_bb);
4372   if (NEXT_INSN (insn) == 0
4373       || (!NOTE_P (insn)
4374           && !LABEL_P (insn)
4375           /* Don't emit a NOTE if it would end up before a BARRIER.  */
4376           && !BARRIER_P (NEXT_INSN (insn))))
4377     {
4378       rtx note = emit_note_after (NOTE_INSN_DELETED, insn);
4379       /* Make insn appear outside BB.  */
4380       set_block_for_insn (note, NULL);
4381       BB_END (EXIT_BLOCK_PTR->prev_bb) = insn;
4382     }
4383 }
4384
4385 /* Init per basic block data structures.  */
4386 void
4387 sched_init_bbs (void)
4388 {
4389   sched_extend_bb ();
4390 }
4391
4392 /* Initialize BEFORE_RECOVERY variable.  */
4393 static void
4394 init_before_recovery (basic_block *before_recovery_ptr)
4395 {
4396   basic_block last;
4397   edge e;
4398
4399   last = EXIT_BLOCK_PTR->prev_bb;
4400   e = find_fallthru_edge_from (last);
4401
4402   if (e)
4403     {
4404       /* We create two basic blocks:
4405          1. Single instruction block is inserted right after E->SRC
4406          and has jump to
4407          2. Empty block right before EXIT_BLOCK.
4408          Between these two blocks recovery blocks will be emitted.  */
4409
4410       basic_block single, empty;
4411       rtx x, label;
4412
4413       /* If the fallthrough edge to exit we've found is from the block we've
4414          created before, don't do anything more.  */
4415       if (last == after_recovery)
4416         return;
4417
4418       adding_bb_to_current_region_p = false;
4419
4420       single = sched_create_empty_bb (last);
4421       empty = sched_create_empty_bb (single);
4422
4423       /* Add new blocks to the root loop.  */
4424       if (current_loops != NULL)
4425         {
4426           add_bb_to_loop (single, VEC_index (loop_p, current_loops->larray, 0));
4427           add_bb_to_loop (empty, VEC_index (loop_p, current_loops->larray, 0));
4428         }
4429
4430       single->count = last->count;
4431       empty->count = last->count;
4432       single->frequency = last->frequency;
4433       empty->frequency = last->frequency;
4434       BB_COPY_PARTITION (single, last);
4435       BB_COPY_PARTITION (empty, last);
4436
4437       redirect_edge_succ (e, single);
4438       make_single_succ_edge (single, empty, 0);
4439       make_single_succ_edge (empty, EXIT_BLOCK_PTR,
4440                              EDGE_FALLTHRU | EDGE_CAN_FALLTHRU);
4441
4442       label = block_label (empty);
4443       x = emit_jump_insn_after (gen_jump (label), BB_END (single));
4444       JUMP_LABEL (x) = label;
4445       LABEL_NUSES (label)++;
4446       haifa_init_insn (x);
4447
4448       emit_barrier_after (x);
4449
4450       sched_init_only_bb (empty, NULL);
4451       sched_init_only_bb (single, NULL);
4452       sched_extend_bb ();
4453
4454       adding_bb_to_current_region_p = true;
4455       before_recovery = single;
4456       after_recovery = empty;
4457
4458       if (before_recovery_ptr)
4459         *before_recovery_ptr = before_recovery;
4460
4461       if (sched_verbose >= 2 && spec_info->dump)
4462         fprintf (spec_info->dump,
4463                  ";;\t\tFixed fallthru to EXIT : %d->>%d->%d->>EXIT\n",
4464                  last->index, single->index, empty->index);
4465     }
4466   else
4467     before_recovery = last;
4468 }
4469
4470 /* Returns new recovery block.  */
4471 basic_block
4472 sched_create_recovery_block (basic_block *before_recovery_ptr)
4473 {
4474   rtx label;
4475   rtx barrier;
4476   basic_block rec;
4477
4478   haifa_recovery_bb_recently_added_p = true;
4479   haifa_recovery_bb_ever_added_p = true;
4480
4481   init_before_recovery (before_recovery_ptr);
4482
4483   barrier = get_last_bb_insn (before_recovery);
4484   gcc_assert (BARRIER_P (barrier));
4485
4486   label = emit_label_after (gen_label_rtx (), barrier);
4487
4488   rec = create_basic_block (label, label, before_recovery);
4489
4490   /* A recovery block always ends with an unconditional jump.  */
4491   emit_barrier_after (BB_END (rec));
4492
4493   if (BB_PARTITION (before_recovery) != BB_UNPARTITIONED)
4494     BB_SET_PARTITION (rec, BB_COLD_PARTITION);
4495
4496   if (sched_verbose && spec_info->dump)
4497     fprintf (spec_info->dump, ";;\t\tGenerated recovery block rec%d\n",
4498              rec->index);
4499
4500   return rec;
4501 }
4502
4503 /* Create edges: FIRST_BB -> REC; FIRST_BB -> SECOND_BB; REC -> SECOND_BB
4504    and emit necessary jumps.  */
4505 void
4506 sched_create_recovery_edges (basic_block first_bb, basic_block rec,
4507                              basic_block second_bb)
4508 {
4509   rtx label;
4510   rtx jump;
4511   int edge_flags;
4512
4513   /* This is fixing of incoming edge.  */
4514   /* ??? Which other flags should be specified?  */
4515   if (BB_PARTITION (first_bb) != BB_PARTITION (rec))
4516     /* Partition type is the same, if it is "unpartitioned".  */
4517     edge_flags = EDGE_CROSSING;
4518   else
4519     edge_flags = 0;
4520
4521   make_edge (first_bb, rec, edge_flags);
4522   label = block_label (second_bb);
4523   jump = emit_jump_insn_after (gen_jump (label), BB_END (rec));
4524   JUMP_LABEL (jump) = label;
4525   LABEL_NUSES (label)++;
4526
4527   if (BB_PARTITION (second_bb) != BB_PARTITION (rec))
4528     /* Partition type is the same, if it is "unpartitioned".  */
4529     {
4530       /* Rewritten from cfgrtl.c.  */
4531       if (flag_reorder_blocks_and_partition
4532           && targetm.have_named_sections)
4533         {
4534           /* We don't need the same note for the check because
4535              any_condjump_p (check) == true.  */
4536           add_reg_note (jump, REG_CROSSING_JUMP, NULL_RTX);
4537         }
4538       edge_flags = EDGE_CROSSING;
4539     }
4540   else
4541     edge_flags = 0;
4542
4543   make_single_succ_edge (rec, second_bb, edge_flags);
4544   if (dom_info_available_p (CDI_DOMINATORS))
4545     set_immediate_dominator (CDI_DOMINATORS, rec, first_bb);
4546 }
4547
4548 /* This function creates recovery code for INSN.  If MUTATE_P is nonzero,
4549    INSN is a simple check, that should be converted to branchy one.  */
4550 static void
4551 create_check_block_twin (rtx insn, bool mutate_p)
4552 {
4553   basic_block rec;
4554   rtx label, check, twin;
4555   ds_t fs;
4556   sd_iterator_def sd_it;
4557   dep_t dep;
4558   dep_def _new_dep, *new_dep = &_new_dep;
4559   ds_t todo_spec;
4560
4561   gcc_assert (ORIG_PAT (insn) != NULL_RTX);
4562
4563   if (!mutate_p)
4564     todo_spec = TODO_SPEC (insn);
4565   else
4566     {
4567       gcc_assert (IS_SPECULATION_SIMPLE_CHECK_P (insn)
4568                   && (TODO_SPEC (insn) & SPECULATIVE) == 0);
4569
4570       todo_spec = CHECK_SPEC (insn);
4571     }
4572
4573   todo_spec &= SPECULATIVE;
4574
4575   /* Create recovery block.  */
4576   if (mutate_p || targetm.sched.needs_block_p (todo_spec))
4577     {
4578       rec = sched_create_recovery_block (NULL);
4579       label = BB_HEAD (rec);
4580     }
4581   else
4582     {
4583       rec = EXIT_BLOCK_PTR;
4584       label = NULL_RTX;
4585     }
4586
4587   /* Emit CHECK.  */
4588   check = targetm.sched.gen_spec_check (insn, label, todo_spec);
4589
4590   if (rec != EXIT_BLOCK_PTR)
4591     {
4592       /* To have mem_reg alive at the beginning of second_bb,
4593          we emit check BEFORE insn, so insn after splitting
4594          insn will be at the beginning of second_bb, which will
4595          provide us with the correct life information.  */
4596       check = emit_jump_insn_before (check, insn);
4597       JUMP_LABEL (check) = label;
4598       LABEL_NUSES (label)++;
4599     }
4600   else
4601     check = emit_insn_before (check, insn);
4602
4603   /* Extend data structures.  */
4604   haifa_init_insn (check);
4605
4606   /* CHECK is being added to current region.  Extend ready list.  */
4607   gcc_assert (sched_ready_n_insns != -1);
4608   sched_extend_ready_list (sched_ready_n_insns + 1);
4609
4610   if (current_sched_info->add_remove_insn)
4611     current_sched_info->add_remove_insn (insn, 0);
4612
4613   RECOVERY_BLOCK (check) = rec;
4614
4615   if (sched_verbose && spec_info->dump)
4616     fprintf (spec_info->dump, ";;\t\tGenerated check insn : %s\n",
4617              (*current_sched_info->print_insn) (check, 0));
4618
4619   gcc_assert (ORIG_PAT (insn));
4620
4621   /* Initialize TWIN (twin is a duplicate of original instruction
4622      in the recovery block).  */
4623   if (rec != EXIT_BLOCK_PTR)
4624     {
4625       sd_iterator_def sd_it;
4626       dep_t dep;
4627
4628       FOR_EACH_DEP (insn, SD_LIST_RES_BACK, sd_it, dep)
4629         if ((DEP_STATUS (dep) & DEP_OUTPUT) != 0)
4630           {
4631             struct _dep _dep2, *dep2 = &_dep2;
4632
4633             init_dep (dep2, DEP_PRO (dep), check, REG_DEP_TRUE);
4634
4635             sd_add_dep (dep2, true);
4636           }
4637
4638       twin = emit_insn_after (ORIG_PAT (insn), BB_END (rec));
4639       haifa_init_insn (twin);
4640
4641       if (sched_verbose && spec_info->dump)
4642         /* INSN_BB (insn) isn't determined for twin insns yet.
4643            So we can't use current_sched_info->print_insn.  */
4644         fprintf (spec_info->dump, ";;\t\tGenerated twin insn : %d/rec%d\n",
4645                  INSN_UID (twin), rec->index);
4646     }
4647   else
4648     {
4649       ORIG_PAT (check) = ORIG_PAT (insn);
4650       HAS_INTERNAL_DEP (check) = 1;
4651       twin = check;
4652       /* ??? We probably should change all OUTPUT dependencies to
4653          (TRUE | OUTPUT).  */
4654     }
4655
4656   /* Copy all resolved back dependencies of INSN to TWIN.  This will
4657      provide correct value for INSN_TICK (TWIN).  */
4658   sd_copy_back_deps (twin, insn, true);
4659
4660   if (rec != EXIT_BLOCK_PTR)
4661     /* In case of branchy check, fix CFG.  */
4662     {
4663       basic_block first_bb, second_bb;
4664       rtx jump;
4665
4666       first_bb = BLOCK_FOR_INSN (check);
4667       second_bb = sched_split_block (first_bb, check);
4668
4669       sched_create_recovery_edges (first_bb, rec, second_bb);
4670
4671       sched_init_only_bb (second_bb, first_bb);
4672       sched_init_only_bb (rec, EXIT_BLOCK_PTR);
4673
4674       jump = BB_END (rec);
4675       haifa_init_insn (jump);
4676     }
4677
4678   /* Move backward dependences from INSN to CHECK and
4679      move forward dependences from INSN to TWIN.  */
4680
4681   /* First, create dependencies between INSN's producers and CHECK & TWIN.  */
4682   FOR_EACH_DEP (insn, SD_LIST_BACK, sd_it, dep)
4683     {
4684       rtx pro = DEP_PRO (dep);
4685       ds_t ds;
4686
4687       /* If BEGIN_DATA: [insn ~~TRUE~~> producer]:
4688          check --TRUE--> producer  ??? or ANTI ???
4689          twin  --TRUE--> producer
4690          twin  --ANTI--> check
4691
4692          If BEGIN_CONTROL: [insn ~~ANTI~~> producer]:
4693          check --ANTI--> producer
4694          twin  --ANTI--> producer
4695          twin  --ANTI--> check
4696
4697          If BE_IN_SPEC: [insn ~~TRUE~~> producer]:
4698          check ~~TRUE~~> producer
4699          twin  ~~TRUE~~> producer
4700          twin  --ANTI--> check  */
4701
4702       ds = DEP_STATUS (dep);
4703
4704       if (ds & BEGIN_SPEC)
4705         {
4706           gcc_assert (!mutate_p);
4707           ds &= ~BEGIN_SPEC;
4708         }
4709
4710       init_dep_1 (new_dep, pro, check, DEP_TYPE (dep), ds);
4711       sd_add_dep (new_dep, false);
4712
4713       if (rec != EXIT_BLOCK_PTR)
4714         {
4715           DEP_CON (new_dep) = twin;
4716           sd_add_dep (new_dep, false);
4717         }
4718     }
4719
4720   /* Second, remove backward dependencies of INSN.  */
4721   for (sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
4722        sd_iterator_cond (&sd_it, &dep);)
4723     {
4724       if ((DEP_STATUS (dep) & BEGIN_SPEC)
4725           || mutate_p)
4726         /* We can delete this dep because we overcome it with
4727            BEGIN_SPECULATION.  */
4728         sd_delete_dep (sd_it);
4729       else
4730         sd_iterator_next (&sd_it);
4731     }
4732
4733   /* Future Speculations.  Determine what BE_IN speculations will be like.  */
4734   fs = 0;
4735
4736   /* Fields (DONE_SPEC (x) & BEGIN_SPEC) and CHECK_SPEC (x) are set only
4737      here.  */
4738
4739   gcc_assert (!DONE_SPEC (insn));
4740
4741   if (!mutate_p)
4742     {
4743       ds_t ts = TODO_SPEC (insn);
4744
4745       DONE_SPEC (insn) = ts & BEGIN_SPEC;
4746       CHECK_SPEC (check) = ts & BEGIN_SPEC;
4747
4748       /* Luckiness of future speculations solely depends upon initial
4749          BEGIN speculation.  */
4750       if (ts & BEGIN_DATA)
4751         fs = set_dep_weak (fs, BE_IN_DATA, get_dep_weak (ts, BEGIN_DATA));
4752       if (ts & BEGIN_CONTROL)
4753         fs = set_dep_weak (fs, BE_IN_CONTROL,
4754                            get_dep_weak (ts, BEGIN_CONTROL));
4755     }
4756   else
4757     CHECK_SPEC (check) = CHECK_SPEC (insn);
4758
4759   /* Future speculations: call the helper.  */
4760   process_insn_forw_deps_be_in_spec (insn, twin, fs);
4761
4762   if (rec != EXIT_BLOCK_PTR)
4763     {
4764       /* Which types of dependencies should we use here is,
4765          generally, machine-dependent question...  But, for now,
4766          it is not.  */
4767
4768       if (!mutate_p)
4769         {
4770           init_dep (new_dep, insn, check, REG_DEP_TRUE);
4771           sd_add_dep (new_dep, false);
4772
4773           init_dep (new_dep, insn, twin, REG_DEP_OUTPUT);
4774           sd_add_dep (new_dep, false);
4775         }
4776       else
4777         {
4778           if (spec_info->dump)
4779             fprintf (spec_info->dump, ";;\t\tRemoved simple check : %s\n",
4780                      (*current_sched_info->print_insn) (insn, 0));
4781
4782           /* Remove all dependencies of the INSN.  */
4783           {
4784             sd_it = sd_iterator_start (insn, (SD_LIST_FORW
4785                                               | SD_LIST_BACK
4786                                               | SD_LIST_RES_BACK));
4787             while (sd_iterator_cond (&sd_it, &dep))
4788               sd_delete_dep (sd_it);
4789           }
4790
4791           /* If former check (INSN) already was moved to the ready (or queue)
4792              list, add new check (CHECK) there too.  */
4793           if (QUEUE_INDEX (insn) != QUEUE_NOWHERE)
4794             try_ready (check);
4795
4796           /* Remove old check from instruction stream and free its
4797              data.  */
4798           sched_remove_insn (insn);
4799         }
4800
4801       init_dep (new_dep, check, twin, REG_DEP_ANTI);
4802       sd_add_dep (new_dep, false);
4803     }
4804   else
4805     {
4806       init_dep_1 (new_dep, insn, check, REG_DEP_TRUE, DEP_TRUE | DEP_OUTPUT);
4807       sd_add_dep (new_dep, false);
4808     }
4809
4810   if (!mutate_p)
4811     /* Fix priorities.  If MUTATE_P is nonzero, this is not necessary,
4812        because it'll be done later in add_to_speculative_block.  */
4813     {
4814       rtx_vec_t priorities_roots = NULL;
4815
4816       clear_priorities (twin, &priorities_roots);
4817       calc_priorities (priorities_roots);
4818       VEC_free (rtx, heap, priorities_roots);
4819     }
4820 }
4821
4822 /* Removes dependency between instructions in the recovery block REC
4823    and usual region instructions.  It keeps inner dependences so it
4824    won't be necessary to recompute them.  */
4825 static void
4826 fix_recovery_deps (basic_block rec)
4827 {
4828   rtx note, insn, jump, ready_list = 0;
4829   bitmap_head in_ready;
4830   rtx link;
4831
4832   bitmap_initialize (&in_ready, 0);
4833
4834   /* NOTE - a basic block note.  */
4835   note = NEXT_INSN (BB_HEAD (rec));
4836   gcc_assert (NOTE_INSN_BASIC_BLOCK_P (note));
4837   insn = BB_END (rec);
4838   gcc_assert (JUMP_P (insn));
4839   insn = PREV_INSN (insn);
4840
4841   do
4842     {
4843       sd_iterator_def sd_it;
4844       dep_t dep;
4845
4846       for (sd_it = sd_iterator_start (insn, SD_LIST_FORW);
4847            sd_iterator_cond (&sd_it, &dep);)
4848         {
4849           rtx consumer = DEP_CON (dep);
4850
4851           if (BLOCK_FOR_INSN (consumer) != rec)
4852             {
4853               sd_delete_dep (sd_it);
4854
4855               if (bitmap_set_bit (&in_ready, INSN_LUID (consumer)))
4856                 ready_list = alloc_INSN_LIST (consumer, ready_list);
4857             }
4858           else
4859             {
4860               gcc_assert ((DEP_STATUS (dep) & DEP_TYPES) == DEP_TRUE);
4861
4862               sd_iterator_next (&sd_it);
4863             }
4864         }
4865
4866       insn = PREV_INSN (insn);
4867     }
4868   while (insn != note);
4869
4870   bitmap_clear (&in_ready);
4871
4872   /* Try to add instructions to the ready or queue list.  */
4873   for (link = ready_list; link; link = XEXP (link, 1))
4874     try_ready (XEXP (link, 0));
4875   free_INSN_LIST_list (&ready_list);
4876
4877   /* Fixing jump's dependences.  */
4878   insn = BB_HEAD (rec);
4879   jump = BB_END (rec);
4880
4881   gcc_assert (LABEL_P (insn));
4882   insn = NEXT_INSN (insn);
4883
4884   gcc_assert (NOTE_INSN_BASIC_BLOCK_P (insn));
4885   add_jump_dependencies (insn, jump);
4886 }
4887
4888 /* Change pattern of INSN to NEW_PAT.  */
4889 void
4890 sched_change_pattern (rtx insn, rtx new_pat)
4891 {
4892   int t;
4893
4894   t = validate_change (insn, &PATTERN (insn), new_pat, 0);
4895   gcc_assert (t);
4896   dfa_clear_single_insn_cache (insn);
4897 }
4898
4899 /* Change pattern of INSN to NEW_PAT.  Invalidate cached haifa
4900    instruction data.  */
4901 static void
4902 haifa_change_pattern (rtx insn, rtx new_pat)
4903 {
4904   sched_change_pattern (insn, new_pat);
4905
4906   /* Invalidate INSN_COST, so it'll be recalculated.  */
4907   INSN_COST (insn) = -1;
4908   /* Invalidate INSN_TICK, so it'll be recalculated.  */
4909   INSN_TICK (insn) = INVALID_TICK;
4910 }
4911
4912 /* -1 - can't speculate,
4913    0 - for speculation with REQUEST mode it is OK to use
4914    current instruction pattern,
4915    1 - need to change pattern for *NEW_PAT to be speculative.  */
4916 int
4917 sched_speculate_insn (rtx insn, ds_t request, rtx *new_pat)
4918 {
4919   gcc_assert (current_sched_info->flags & DO_SPECULATION
4920               && (request & SPECULATIVE)
4921               && sched_insn_is_legitimate_for_speculation_p (insn, request));
4922
4923   if ((request & spec_info->mask) != request)
4924     return -1;
4925
4926   if (request & BE_IN_SPEC
4927       && !(request & BEGIN_SPEC))
4928     return 0;
4929
4930   return targetm.sched.speculate_insn (insn, request, new_pat);
4931 }
4932
4933 static int
4934 haifa_speculate_insn (rtx insn, ds_t request, rtx *new_pat)
4935 {
4936   gcc_assert (sched_deps_info->generate_spec_deps
4937               && !IS_SPECULATION_CHECK_P (insn));
4938
4939   if (HAS_INTERNAL_DEP (insn)
4940       || SCHED_GROUP_P (insn))
4941     return -1;
4942
4943   return sched_speculate_insn (insn, request, new_pat);
4944 }
4945
4946 /* Print some information about block BB, which starts with HEAD and
4947    ends with TAIL, before scheduling it.
4948    I is zero, if scheduler is about to start with the fresh ebb.  */
4949 static void
4950 dump_new_block_header (int i, basic_block bb, rtx head, rtx tail)
4951 {
4952   if (!i)
4953     fprintf (sched_dump,
4954              ";;   ======================================================\n");
4955   else
4956     fprintf (sched_dump,
4957              ";;   =====================ADVANCING TO=====================\n");
4958   fprintf (sched_dump,
4959            ";;   -- basic block %d from %d to %d -- %s reload\n",
4960            bb->index, INSN_UID (head), INSN_UID (tail),
4961            (reload_completed ? "after" : "before"));
4962   fprintf (sched_dump,
4963            ";;   ======================================================\n");
4964   fprintf (sched_dump, "\n");
4965 }
4966
4967 /* Unlink basic block notes and labels and saves them, so they
4968    can be easily restored.  We unlink basic block notes in EBB to
4969    provide back-compatibility with the previous code, as target backends
4970    assume, that there'll be only instructions between
4971    current_sched_info->{head and tail}.  We restore these notes as soon
4972    as we can.
4973    FIRST (LAST) is the first (last) basic block in the ebb.
4974    NB: In usual case (FIRST == LAST) nothing is really done.  */
4975 void
4976 unlink_bb_notes (basic_block first, basic_block last)
4977 {
4978   /* We DON'T unlink basic block notes of the first block in the ebb.  */
4979   if (first == last)
4980     return;
4981
4982   bb_header = XNEWVEC (rtx, last_basic_block);
4983
4984   /* Make a sentinel.  */
4985   if (last->next_bb != EXIT_BLOCK_PTR)
4986     bb_header[last->next_bb->index] = 0;
4987
4988   first = first->next_bb;
4989   do
4990     {
4991       rtx prev, label, note, next;
4992
4993       label = BB_HEAD (last);
4994       if (LABEL_P (label))
4995         note = NEXT_INSN (label);
4996       else
4997         note = label;
4998       gcc_assert (NOTE_INSN_BASIC_BLOCK_P (note));
4999
5000       prev = PREV_INSN (label);
5001       next = NEXT_INSN (note);
5002       gcc_assert (prev && next);
5003
5004       NEXT_INSN (prev) = next;
5005       PREV_INSN (next) = prev;
5006
5007       bb_header[last->index] = label;
5008
5009       if (last == first)
5010         break;
5011
5012       last = last->prev_bb;
5013     }
5014   while (1);
5015 }
5016
5017 /* Restore basic block notes.
5018    FIRST is the first basic block in the ebb.  */
5019 static void
5020 restore_bb_notes (basic_block first)
5021 {
5022   if (!bb_header)
5023     return;
5024
5025   /* We DON'T unlink basic block notes of the first block in the ebb.  */
5026   first = first->next_bb;
5027   /* Remember: FIRST is actually a second basic block in the ebb.  */
5028
5029   while (first != EXIT_BLOCK_PTR
5030          && bb_header[first->index])
5031     {
5032       rtx prev, label, note, next;
5033
5034       label = bb_header[first->index];
5035       prev = PREV_INSN (label);
5036       next = NEXT_INSN (prev);
5037
5038       if (LABEL_P (label))
5039         note = NEXT_INSN (label);
5040       else
5041         note = label;
5042       gcc_assert (NOTE_INSN_BASIC_BLOCK_P (note));
5043
5044       bb_header[first->index] = 0;
5045
5046       NEXT_INSN (prev) = label;
5047       NEXT_INSN (note) = next;
5048       PREV_INSN (next) = note;
5049
5050       first = first->next_bb;
5051     }
5052
5053   free (bb_header);
5054   bb_header = 0;
5055 }
5056
5057 /* Helper function.
5058    Fix CFG after both in- and inter-block movement of
5059    control_flow_insn_p JUMP.  */
5060 static void
5061 fix_jump_move (rtx jump)
5062 {
5063   basic_block bb, jump_bb, jump_bb_next;
5064
5065   bb = BLOCK_FOR_INSN (PREV_INSN (jump));
5066   jump_bb = BLOCK_FOR_INSN (jump);
5067   jump_bb_next = jump_bb->next_bb;
5068
5069   gcc_assert (common_sched_info->sched_pass_id == SCHED_EBB_PASS
5070               || IS_SPECULATION_BRANCHY_CHECK_P (jump));
5071
5072   if (!NOTE_INSN_BASIC_BLOCK_P (BB_END (jump_bb_next)))
5073     /* if jump_bb_next is not empty.  */
5074     BB_END (jump_bb) = BB_END (jump_bb_next);
5075
5076   if (BB_END (bb) != PREV_INSN (jump))
5077     /* Then there are instruction after jump that should be placed
5078        to jump_bb_next.  */
5079     BB_END (jump_bb_next) = BB_END (bb);
5080   else
5081     /* Otherwise jump_bb_next is empty.  */
5082     BB_END (jump_bb_next) = NEXT_INSN (BB_HEAD (jump_bb_next));
5083
5084   /* To make assertion in move_insn happy.  */
5085   BB_END (bb) = PREV_INSN (jump);
5086
5087   update_bb_for_insn (jump_bb_next);
5088 }
5089
5090 /* Fix CFG after interblock movement of control_flow_insn_p JUMP.  */
5091 static void
5092 move_block_after_check (rtx jump)
5093 {
5094   basic_block bb, jump_bb, jump_bb_next;
5095   VEC(edge,gc) *t;
5096
5097   bb = BLOCK_FOR_INSN (PREV_INSN (jump));
5098   jump_bb = BLOCK_FOR_INSN (jump);
5099   jump_bb_next = jump_bb->next_bb;
5100
5101   update_bb_for_insn (jump_bb);
5102
5103   gcc_assert (IS_SPECULATION_CHECK_P (jump)
5104               || IS_SPECULATION_CHECK_P (BB_END (jump_bb_next)));
5105
5106   unlink_block (jump_bb_next);
5107   link_block (jump_bb_next, bb);
5108
5109   t = bb->succs;
5110   bb->succs = 0;
5111   move_succs (&(jump_bb->succs), bb);
5112   move_succs (&(jump_bb_next->succs), jump_bb);
5113   move_succs (&t, jump_bb_next);
5114
5115   df_mark_solutions_dirty ();
5116
5117   common_sched_info->fix_recovery_cfg
5118     (bb->index, jump_bb->index, jump_bb_next->index);
5119 }
5120
5121 /* Helper function for move_block_after_check.
5122    This functions attaches edge vector pointed to by SUCCSP to
5123    block TO.  */
5124 static void
5125 move_succs (VEC(edge,gc) **succsp, basic_block to)
5126 {
5127   edge e;
5128   edge_iterator ei;
5129
5130   gcc_assert (to->succs == 0);
5131
5132   to->succs = *succsp;
5133
5134   FOR_EACH_EDGE (e, ei, to->succs)
5135     e->src = to;
5136
5137   *succsp = 0;
5138 }
5139
5140 /* Remove INSN from the instruction stream.
5141    INSN should have any dependencies.  */
5142 static void
5143 sched_remove_insn (rtx insn)
5144 {
5145   sd_finish_insn (insn);
5146
5147   change_queue_index (insn, QUEUE_NOWHERE);
5148   current_sched_info->add_remove_insn (insn, 1);
5149   remove_insn (insn);
5150 }
5151
5152 /* Clear priorities of all instructions, that are forward dependent on INSN.
5153    Store in vector pointed to by ROOTS_PTR insns on which priority () should
5154    be invoked to initialize all cleared priorities.  */
5155 static void
5156 clear_priorities (rtx insn, rtx_vec_t *roots_ptr)
5157 {
5158   sd_iterator_def sd_it;
5159   dep_t dep;
5160   bool insn_is_root_p = true;
5161
5162   gcc_assert (QUEUE_INDEX (insn) != QUEUE_SCHEDULED);
5163
5164   FOR_EACH_DEP (insn, SD_LIST_BACK, sd_it, dep)
5165     {
5166       rtx pro = DEP_PRO (dep);
5167
5168       if (INSN_PRIORITY_STATUS (pro) >= 0
5169           && QUEUE_INDEX (insn) != QUEUE_SCHEDULED)
5170         {
5171           /* If DEP doesn't contribute to priority then INSN itself should
5172              be added to priority roots.  */
5173           if (contributes_to_priority_p (dep))
5174             insn_is_root_p = false;
5175
5176           INSN_PRIORITY_STATUS (pro) = -1;
5177           clear_priorities (pro, roots_ptr);
5178         }
5179     }
5180
5181   if (insn_is_root_p)
5182     VEC_safe_push (rtx, heap, *roots_ptr, insn);
5183 }
5184
5185 /* Recompute priorities of instructions, whose priorities might have been
5186    changed.  ROOTS is a vector of instructions whose priority computation will
5187    trigger initialization of all cleared priorities.  */
5188 static void
5189 calc_priorities (rtx_vec_t roots)
5190 {
5191   int i;
5192   rtx insn;
5193
5194   FOR_EACH_VEC_ELT (rtx, roots, i, insn)
5195     priority (insn);
5196 }
5197
5198
5199 /* Add dependences between JUMP and other instructions in the recovery
5200    block.  INSN is the first insn the recovery block.  */
5201 static void
5202 add_jump_dependencies (rtx insn, rtx jump)
5203 {
5204   do
5205     {
5206       insn = NEXT_INSN (insn);
5207       if (insn == jump)
5208         break;
5209
5210       if (dep_list_size (insn) == 0)
5211         {
5212           dep_def _new_dep, *new_dep = &_new_dep;
5213
5214           init_dep (new_dep, insn, jump, REG_DEP_ANTI);
5215           sd_add_dep (new_dep, false);
5216         }
5217     }
5218   while (1);
5219
5220   gcc_assert (!sd_lists_empty_p (jump, SD_LIST_BACK));
5221 }
5222
5223 /* Return the NOTE_INSN_BASIC_BLOCK of BB.  */
5224 rtx
5225 bb_note (basic_block bb)
5226 {
5227   rtx note;
5228
5229   note = BB_HEAD (bb);
5230   if (LABEL_P (note))
5231     note = NEXT_INSN (note);
5232
5233   gcc_assert (NOTE_INSN_BASIC_BLOCK_P (note));
5234   return note;
5235 }
5236
5237 #ifdef ENABLE_CHECKING
5238 /* Helper function for check_cfg.
5239    Return nonzero, if edge vector pointed to by EL has edge with TYPE in
5240    its flags.  */
5241 static int
5242 has_edge_p (VEC(edge,gc) *el, int type)
5243 {
5244   edge e;
5245   edge_iterator ei;
5246
5247   FOR_EACH_EDGE (e, ei, el)
5248     if (e->flags & type)
5249       return 1;
5250   return 0;
5251 }
5252
5253 /* Search back, starting at INSN, for an insn that is not a
5254    NOTE_INSN_VAR_LOCATION.  Don't search beyond HEAD, and return it if
5255    no such insn can be found.  */
5256 static inline rtx
5257 prev_non_location_insn (rtx insn, rtx head)
5258 {
5259   while (insn != head && NOTE_P (insn)
5260          && NOTE_KIND (insn) == NOTE_INSN_VAR_LOCATION)
5261     insn = PREV_INSN (insn);
5262
5263   return insn;
5264 }
5265
5266 /* Check few properties of CFG between HEAD and TAIL.
5267    If HEAD (TAIL) is NULL check from the beginning (till the end) of the
5268    instruction stream.  */
5269 static void
5270 check_cfg (rtx head, rtx tail)
5271 {
5272   rtx next_tail;
5273   basic_block bb = 0;
5274   int not_first = 0, not_last;
5275
5276   if (head == NULL)
5277     head = get_insns ();
5278   if (tail == NULL)
5279     tail = get_last_insn ();
5280   next_tail = NEXT_INSN (tail);
5281
5282   do
5283     {
5284       not_last = head != tail;
5285
5286       if (not_first)
5287         gcc_assert (NEXT_INSN (PREV_INSN (head)) == head);
5288       if (not_last)
5289         gcc_assert (PREV_INSN (NEXT_INSN (head)) == head);
5290
5291       if (LABEL_P (head)
5292           || (NOTE_INSN_BASIC_BLOCK_P (head)
5293               && (!not_first
5294                   || (not_first && !LABEL_P (PREV_INSN (head))))))
5295         {
5296           gcc_assert (bb == 0);
5297           bb = BLOCK_FOR_INSN (head);
5298           if (bb != 0)
5299             gcc_assert (BB_HEAD (bb) == head);
5300           else
5301             /* This is the case of jump table.  See inside_basic_block_p ().  */
5302             gcc_assert (LABEL_P (head) && !inside_basic_block_p (head));
5303         }
5304
5305       if (bb == 0)
5306         {
5307           gcc_assert (!inside_basic_block_p (head));
5308           head = NEXT_INSN (head);
5309         }
5310       else
5311         {
5312           gcc_assert (inside_basic_block_p (head)
5313                       || NOTE_P (head));
5314           gcc_assert (BLOCK_FOR_INSN (head) == bb);
5315
5316           if (LABEL_P (head))
5317             {
5318               head = NEXT_INSN (head);
5319               gcc_assert (NOTE_INSN_BASIC_BLOCK_P (head));
5320             }
5321           else
5322             {
5323               if (control_flow_insn_p (head))
5324                 {
5325                   gcc_assert (prev_non_location_insn (BB_END (bb), head)
5326                               == head);
5327
5328                   if (any_uncondjump_p (head))
5329                     gcc_assert (EDGE_COUNT (bb->succs) == 1
5330                                 && BARRIER_P (NEXT_INSN (head)));
5331                   else if (any_condjump_p (head))
5332                     gcc_assert (/* Usual case.  */
5333                                 (EDGE_COUNT (bb->succs) > 1
5334                                  && !BARRIER_P (NEXT_INSN (head)))
5335                                 /* Or jump to the next instruction.  */
5336                                 || (EDGE_COUNT (bb->succs) == 1
5337                                     && (BB_HEAD (EDGE_I (bb->succs, 0)->dest)
5338                                         == JUMP_LABEL (head))));
5339                 }
5340               if (BB_END (bb) == head)
5341                 {
5342                   if (EDGE_COUNT (bb->succs) > 1)
5343                     gcc_assert (control_flow_insn_p (prev_non_location_insn
5344                                                      (head, BB_HEAD (bb)))
5345                                 || has_edge_p (bb->succs, EDGE_COMPLEX));
5346                   bb = 0;
5347                 }
5348
5349               head = NEXT_INSN (head);
5350             }
5351         }
5352
5353       not_first = 1;
5354     }
5355   while (head != next_tail);
5356
5357   gcc_assert (bb == 0);
5358 }
5359
5360 #endif /* ENABLE_CHECKING */
5361
5362 /* Extend per basic block data structures.  */
5363 static void
5364 extend_bb (void)
5365 {
5366   if (sched_scan_info->extend_bb)
5367     sched_scan_info->extend_bb ();
5368 }
5369
5370 /* Init data for BB.  */
5371 static void
5372 init_bb (basic_block bb)
5373 {
5374   if (sched_scan_info->init_bb)
5375     sched_scan_info->init_bb (bb);
5376 }
5377
5378 /* Extend per insn data structures.  */
5379 static void
5380 extend_insn (void)
5381 {
5382   if (sched_scan_info->extend_insn)
5383     sched_scan_info->extend_insn ();
5384 }
5385
5386 /* Init data structures for INSN.  */
5387 static void
5388 init_insn (rtx insn)
5389 {
5390   if (sched_scan_info->init_insn)
5391     sched_scan_info->init_insn (insn);
5392 }
5393
5394 /* Init all insns in BB.  */
5395 static void
5396 init_insns_in_bb (basic_block bb)
5397 {
5398   rtx insn;
5399
5400   FOR_BB_INSNS (bb, insn)
5401     init_insn (insn);
5402 }
5403
5404 /* A driver function to add a set of basic blocks (BBS),
5405    a single basic block (BB), a set of insns (INSNS) or a single insn (INSN)
5406    to the scheduling region.  */
5407 void
5408 sched_scan (const struct sched_scan_info_def *ssi,
5409             bb_vec_t bbs, basic_block bb, insn_vec_t insns, rtx insn)
5410 {
5411   sched_scan_info = ssi;
5412
5413   if (bbs != NULL || bb != NULL)
5414     {
5415       extend_bb ();
5416
5417       if (bbs != NULL)
5418         {
5419           unsigned i;
5420           basic_block x;
5421
5422           FOR_EACH_VEC_ELT (basic_block, bbs, i, x)
5423             init_bb (x);
5424         }
5425
5426       if (bb != NULL)
5427         init_bb (bb);
5428     }
5429
5430   extend_insn ();
5431
5432   if (bbs != NULL)
5433     {
5434       unsigned i;
5435       basic_block x;
5436
5437       FOR_EACH_VEC_ELT (basic_block, bbs, i, x)
5438         init_insns_in_bb (x);
5439     }
5440
5441   if (bb != NULL)
5442     init_insns_in_bb (bb);
5443
5444   if (insns != NULL)
5445     {
5446       unsigned i;
5447       rtx x;
5448
5449       FOR_EACH_VEC_ELT (rtx, insns, i, x)
5450         init_insn (x);
5451     }
5452
5453   if (insn != NULL)
5454     init_insn (insn);
5455 }
5456
5457
5458 /* Extend data structures for logical insn UID.  */
5459 static void
5460 luids_extend_insn (void)
5461 {
5462   int new_luids_max_uid = get_max_uid () + 1;
5463
5464   VEC_safe_grow_cleared (int, heap, sched_luids, new_luids_max_uid);
5465 }
5466
5467 /* Initialize LUID for INSN.  */
5468 static void
5469 luids_init_insn (rtx insn)
5470 {
5471   int i = INSN_P (insn) ? 1 : common_sched_info->luid_for_non_insn (insn);
5472   int luid;
5473
5474   if (i >= 0)
5475     {
5476       luid = sched_max_luid;
5477       sched_max_luid += i;
5478     }
5479   else
5480     luid = -1;
5481
5482   SET_INSN_LUID (insn, luid);
5483 }
5484
5485 /* Initialize luids for BBS, BB, INSNS and INSN.
5486    The hook common_sched_info->luid_for_non_insn () is used to determine
5487    if notes, labels, etc. need luids.  */
5488 void
5489 sched_init_luids (bb_vec_t bbs, basic_block bb, insn_vec_t insns, rtx insn)
5490 {
5491   const struct sched_scan_info_def ssi =
5492     {
5493       NULL, /* extend_bb */
5494       NULL, /* init_bb */
5495       luids_extend_insn, /* extend_insn */
5496       luids_init_insn /* init_insn */
5497     };
5498
5499   sched_scan (&ssi, bbs, bb, insns, insn);
5500 }
5501
5502 /* Free LUIDs.  */
5503 void
5504 sched_finish_luids (void)
5505 {
5506   VEC_free (int, heap, sched_luids);
5507   sched_max_luid = 1;
5508 }
5509
5510 /* Return logical uid of INSN.  Helpful while debugging.  */
5511 int
5512 insn_luid (rtx insn)
5513 {
5514   return INSN_LUID (insn);
5515 }
5516
5517 /* Extend per insn data in the target.  */
5518 void
5519 sched_extend_target (void)
5520 {
5521   if (targetm.sched.h_i_d_extended)
5522     targetm.sched.h_i_d_extended ();
5523 }
5524
5525 /* Extend global scheduler structures (those, that live across calls to
5526    schedule_block) to include information about just emitted INSN.  */
5527 static void
5528 extend_h_i_d (void)
5529 {
5530   int reserve = (get_max_uid () + 1
5531                  - VEC_length (haifa_insn_data_def, h_i_d));
5532   if (reserve > 0
5533       && ! VEC_space (haifa_insn_data_def, h_i_d, reserve))
5534     {
5535       VEC_safe_grow_cleared (haifa_insn_data_def, heap, h_i_d,
5536                              3 * get_max_uid () / 2);
5537       sched_extend_target ();
5538     }
5539 }
5540
5541 /* Initialize h_i_d entry of the INSN with default values.
5542    Values, that are not explicitly initialized here, hold zero.  */
5543 static void
5544 init_h_i_d (rtx insn)
5545 {
5546   if (INSN_LUID (insn) > 0)
5547     {
5548       INSN_COST (insn) = -1;
5549       QUEUE_INDEX (insn) = QUEUE_NOWHERE;
5550       INSN_TICK (insn) = INVALID_TICK;
5551       INTER_TICK (insn) = INVALID_TICK;
5552       TODO_SPEC (insn) = HARD_DEP;
5553     }
5554 }
5555
5556 /* Initialize haifa_insn_data for BBS, BB, INSNS and INSN.  */
5557 void
5558 haifa_init_h_i_d (bb_vec_t bbs, basic_block bb, insn_vec_t insns, rtx insn)
5559 {
5560   const struct sched_scan_info_def ssi =
5561     {
5562       NULL, /* extend_bb */
5563       NULL, /* init_bb */
5564       extend_h_i_d, /* extend_insn */
5565       init_h_i_d /* init_insn */
5566     };
5567
5568   sched_scan (&ssi, bbs, bb, insns, insn);
5569 }
5570
5571 /* Finalize haifa_insn_data.  */
5572 void
5573 haifa_finish_h_i_d (void)
5574 {
5575   int i;
5576   haifa_insn_data_t data;
5577   struct reg_use_data *use, *next;
5578
5579   FOR_EACH_VEC_ELT (haifa_insn_data_def, h_i_d, i, data)
5580     {
5581       free (data->reg_pressure);
5582       for (use = data->reg_use_list; use != NULL; use = next)
5583         {
5584           next = use->next_insn_use;
5585           free (use);
5586         }
5587     }
5588   VEC_free (haifa_insn_data_def, heap, h_i_d);
5589 }
5590
5591 /* Init data for the new insn INSN.  */
5592 static void
5593 haifa_init_insn (rtx insn)
5594 {
5595   gcc_assert (insn != NULL);
5596
5597   sched_init_luids (NULL, NULL, NULL, insn);
5598   sched_extend_target ();
5599   sched_deps_init (false);
5600   haifa_init_h_i_d (NULL, NULL, NULL, insn);
5601
5602   if (adding_bb_to_current_region_p)
5603     {
5604       sd_init_insn (insn);
5605
5606       /* Extend dependency caches by one element.  */
5607       extend_dependency_caches (1, false);
5608     }
5609   if (sched_pressure_p)
5610     init_insn_reg_pressure_info (insn);
5611 }
5612
5613 /* Init data for the new basic block BB which comes after AFTER.  */
5614 static void
5615 haifa_init_only_bb (basic_block bb, basic_block after)
5616 {
5617   gcc_assert (bb != NULL);
5618
5619   sched_init_bbs ();
5620
5621   if (common_sched_info->add_block)
5622     /* This changes only data structures of the front-end.  */
5623     common_sched_info->add_block (bb, after);
5624 }
5625
5626 /* A generic version of sched_split_block ().  */
5627 basic_block
5628 sched_split_block_1 (basic_block first_bb, rtx after)
5629 {
5630   edge e;
5631
5632   e = split_block (first_bb, after);
5633   gcc_assert (e->src == first_bb);
5634
5635   /* sched_split_block emits note if *check == BB_END.  Probably it
5636      is better to rip that note off.  */
5637
5638   return e->dest;
5639 }
5640
5641 /* A generic version of sched_create_empty_bb ().  */
5642 basic_block
5643 sched_create_empty_bb_1 (basic_block after)
5644 {
5645   return create_empty_bb (after);
5646 }
5647
5648 /* Insert PAT as an INSN into the schedule and update the necessary data
5649    structures to account for it. */
5650 rtx
5651 sched_emit_insn (rtx pat)
5652 {
5653   rtx insn = emit_insn_after (pat, last_scheduled_insn);
5654   last_scheduled_insn = insn;
5655   haifa_init_insn (insn);
5656   return insn;
5657 }
5658
5659 /* This function returns a candidate satisfying dispatch constraints from
5660    the ready list.  */
5661
5662 static rtx
5663 ready_remove_first_dispatch (struct ready_list *ready)
5664 {
5665   int i;
5666   rtx insn = ready_element (ready, 0);
5667
5668   if (ready->n_ready == 1
5669       || INSN_CODE (insn) < 0
5670       || !INSN_P (insn)
5671       || !active_insn_p (insn)
5672       || targetm.sched.dispatch (insn, FITS_DISPATCH_WINDOW))
5673     return ready_remove_first (ready);
5674
5675   for (i = 1; i < ready->n_ready; i++)
5676     {
5677       insn = ready_element (ready, i);
5678
5679       if (INSN_CODE (insn) < 0
5680           || !INSN_P (insn)
5681           || !active_insn_p (insn))
5682         continue;
5683
5684       if (targetm.sched.dispatch (insn, FITS_DISPATCH_WINDOW))
5685         {
5686           /* Return ith element of ready.  */
5687           insn = ready_remove (ready, i);
5688           return insn;
5689         }
5690     }
5691
5692   if (targetm.sched.dispatch (NULL_RTX, DISPATCH_VIOLATION))
5693     return ready_remove_first (ready);
5694
5695   for (i = 1; i < ready->n_ready; i++)
5696     {
5697       insn = ready_element (ready, i);
5698
5699       if (INSN_CODE (insn) < 0
5700           || !INSN_P (insn)
5701           || !active_insn_p (insn))
5702         continue;
5703
5704       /* Return i-th element of ready.  */
5705       if (targetm.sched.dispatch (insn, IS_CMP))
5706         return ready_remove (ready, i);
5707     }
5708
5709   return ready_remove_first (ready);
5710 }
5711
5712 /* Get number of ready insn in the ready list.  */
5713
5714 int
5715 number_in_ready (void)
5716 {
5717   return ready.n_ready;
5718 }
5719
5720 /* Get number of ready's in the ready list.  */
5721
5722 rtx
5723 get_ready_element (int i)
5724 {
5725   return ready_element (&ready, i);
5726 }
5727
5728 #endif /* INSN_SCHEDULING */