OSDN Git Service

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