Update gcc-50 to SVN version 220677
[dragonfly.git] / contrib / gcc-5.0 / gcc / haifa-sched.c
1 /* Instruction scheduling pass.
2    Copyright (C) 1992-2015 Free Software Foundation, Inc.
3    Contributed by Michael Tiemann (tiemann@cygnus.com) Enhanced by,
4    and currently maintained by, Jim Wilson (wilson@cygnus.com)
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22 /* Instruction scheduling pass.  This file, along with sched-deps.c,
23    contains the generic parts.  The actual entry point for
24    the normal instruction scheduling pass is found in sched-rgn.c.
25
26    We compute insn priorities based on data dependencies.  Flow
27    analysis only creates a fraction of the data-dependencies we must
28    observe: namely, only those dependencies which the combiner can be
29    expected to use.  For this pass, we must therefore create the
30    remaining dependencies we need to observe: register dependencies,
31    memory dependencies, dependencies to keep function calls in order,
32    and the dependence between a conditional branch and the setting of
33    condition codes are all dealt with here.
34
35    The scheduler first traverses the data flow graph, starting with
36    the last instruction, and proceeding to the first, assigning values
37    to insn_priority as it goes.  This sorts the instructions
38    topologically by data dependence.
39
40    Once priorities have been established, we order the insns using
41    list scheduling.  This works as follows: starting with a list of
42    all the ready insns, and sorted according to priority number, we
43    schedule the insn from the end of the list by placing its
44    predecessors in the list according to their priority order.  We
45    consider this insn scheduled by setting the pointer to the "end" of
46    the list to point to the previous insn.  When an insn has no
47    predecessors, we either queue it until sufficient time has elapsed
48    or add it to the ready list.  As the instructions are scheduled or
49    when stalls are introduced, the queue advances and dumps insns into
50    the ready list.  When all insns down to the lowest priority have
51    been scheduled, the critical path of the basic block has been made
52    as short as possible.  The remaining insns are then scheduled in
53    remaining slots.
54
55    The following list shows the order in which we want to break ties
56    among insns in the ready list:
57
58    1.  choose insn with the longest path to end of bb, ties
59    broken by
60    2.  choose insn with least contribution to register pressure,
61    ties broken by
62    3.  prefer in-block upon interblock motion, ties broken by
63    4.  prefer useful upon speculative motion, ties broken by
64    5.  choose insn with largest control flow probability, ties
65    broken by
66    6.  choose insn with the least dependences upon the previously
67    scheduled insn, or finally
68    7   choose the insn which has the most insns dependent on it.
69    8.  choose insn with lowest UID.
70
71    Memory references complicate matters.  Only if we can be certain
72    that memory references are not part of the data dependency graph
73    (via true, anti, or output dependence), can we move operations past
74    memory references.  To first approximation, reads can be done
75    independently, while writes introduce dependencies.  Better
76    approximations will yield fewer dependencies.
77
78    Before reload, an extended analysis of interblock data dependences
79    is required for interblock scheduling.  This is performed in
80    compute_block_dependences ().
81
82    Dependencies set up by memory references are treated in exactly the
83    same way as other dependencies, by using insn backward dependences
84    INSN_BACK_DEPS.  INSN_BACK_DEPS are translated into forward dependences
85    INSN_FORW_DEPS for the purpose of forward list scheduling.
86
87    Having optimized the critical path, we may have also unduly
88    extended the lifetimes of some registers.  If an operation requires
89    that constants be loaded into registers, it is certainly desirable
90    to load those constants as early as necessary, but no earlier.
91    I.e., it will not do to load up a bunch of registers at the
92    beginning of a basic block only to use them at the end, if they
93    could be loaded later, since this may result in excessive register
94    utilization.
95
96    Note that since branches are never in basic blocks, but only end
97    basic blocks, this pass will not move branches.  But that is ok,
98    since we can use GNU's delayed branch scheduling pass to take care
99    of this case.
100
101    Also note that no further optimizations based on algebraic
102    identities are performed, so this pass would be a good one to
103    perform instruction splitting, such as breaking up a multiply
104    instruction into shifts and adds where that is profitable.
105
106    Given the memory aliasing analysis that this pass should perform,
107    it should be possible to remove redundant stores to memory, and to
108    load values from registers instead of hitting memory.
109
110    Before reload, speculative insns are moved only if a 'proof' exists
111    that no exception will be caused by this, and if no live registers
112    exist that inhibit the motion (live registers constraints are not
113    represented by data dependence edges).
114
115    This pass must update information that subsequent passes expect to
116    be correct.  Namely: reg_n_refs, reg_n_sets, reg_n_deaths,
117    reg_n_calls_crossed, and reg_live_length.  Also, BB_HEAD, BB_END.
118
119    The information in the line number notes is carefully retained by
120    this pass.  Notes that refer to the starting and ending of
121    exception regions are also carefully retained by this pass.  All
122    other NOTE insns are grouped in their same relative order at the
123    beginning of basic blocks and regions that have been scheduled.  */
124 \f
125 #include "config.h"
126 #include "system.h"
127 #include "coretypes.h"
128 #include "tm.h"
129 #include "diagnostic-core.h"
130 #include "hard-reg-set.h"
131 #include "rtl.h"
132 #include "tm_p.h"
133 #include "regs.h"
134 #include "hashtab.h"
135 #include "hash-set.h"
136 #include "vec.h"
137 #include "machmode.h"
138 #include "input.h"
139 #include "function.h"
140 #include "flags.h"
141 #include "insn-config.h"
142 #include "insn-attr.h"
143 #include "except.h"
144 #include "recog.h"
145 #include "dominance.h"
146 #include "cfg.h"
147 #include "cfgrtl.h"
148 #include "cfgbuild.h"
149 #include "predict.h"
150 #include "basic-block.h"
151 #include "sched-int.h"
152 #include "target.h"
153 #include "common/common-target.h"
154 #include "params.h"
155 #include "dbgcnt.h"
156 #include "cfgloop.h"
157 #include "ira.h"
158 #include "emit-rtl.h"  /* FIXME: Can go away once crtl is moved to rtl.h.  */
159 #include "hash-table.h"
160 #include "dumpfile.h"
161
162 #ifdef INSN_SCHEDULING
163
164 /* True if we do register pressure relief through live-range
165    shrinkage.  */
166 static bool live_range_shrinkage_p;
167
168 /* Switch on live range shrinkage.  */
169 void
170 initialize_live_range_shrinkage (void)
171 {
172   live_range_shrinkage_p = true;
173 }
174
175 /* Switch off live range shrinkage.  */
176 void
177 finish_live_range_shrinkage (void)
178 {
179   live_range_shrinkage_p = false;
180 }
181
182 /* issue_rate is the number of insns that can be scheduled in the same
183    machine cycle.  It can be defined in the config/mach/mach.h file,
184    otherwise we set it to 1.  */
185
186 int issue_rate;
187
188 /* This can be set to true by a backend if the scheduler should not
189    enable a DCE pass.  */
190 bool sched_no_dce;
191
192 /* The current initiation interval used when modulo scheduling.  */
193 static int modulo_ii;
194
195 /* The maximum number of stages we are prepared to handle.  */
196 static int modulo_max_stages;
197
198 /* The number of insns that exist in each iteration of the loop.  We use this
199    to detect when we've scheduled all insns from the first iteration.  */
200 static int modulo_n_insns;
201
202 /* The current count of insns in the first iteration of the loop that have
203    already been scheduled.  */
204 static int modulo_insns_scheduled;
205
206 /* The maximum uid of insns from the first iteration of the loop.  */
207 static int modulo_iter0_max_uid;
208
209 /* The number of times we should attempt to backtrack when modulo scheduling.
210    Decreased each time we have to backtrack.  */
211 static int modulo_backtracks_left;
212
213 /* The stage in which the last insn from the original loop was
214    scheduled.  */
215 static int modulo_last_stage;
216
217 /* sched-verbose controls the amount of debugging output the
218    scheduler prints.  It is controlled by -fsched-verbose=N:
219    N>0 and no -DSR : the output is directed to stderr.
220    N>=10 will direct the printouts to stderr (regardless of -dSR).
221    N=1: same as -dSR.
222    N=2: bb's probabilities, detailed ready list info, unit/insn info.
223    N=3: rtl at abort point, control-flow, regions info.
224    N=5: dependences info.  */
225
226 int sched_verbose = 0;
227
228 /* Debugging file.  All printouts are sent to dump, which is always set,
229    either to stderr, or to the dump listing file (-dRS).  */
230 FILE *sched_dump = 0;
231
232 /* This is a placeholder for the scheduler parameters common
233    to all schedulers.  */
234 struct common_sched_info_def *common_sched_info;
235
236 #define INSN_TICK(INSN) (HID (INSN)->tick)
237 #define INSN_EXACT_TICK(INSN) (HID (INSN)->exact_tick)
238 #define INSN_TICK_ESTIMATE(INSN) (HID (INSN)->tick_estimate)
239 #define INTER_TICK(INSN) (HID (INSN)->inter_tick)
240 #define FEEDS_BACKTRACK_INSN(INSN) (HID (INSN)->feeds_backtrack_insn)
241 #define SHADOW_P(INSN) (HID (INSN)->shadow_p)
242 #define MUST_RECOMPUTE_SPEC_P(INSN) (HID (INSN)->must_recompute_spec)
243 /* Cached cost of the instruction.  Use insn_cost to get cost of the
244    insn.  -1 here means that the field is not initialized.  */
245 #define INSN_COST(INSN) (HID (INSN)->cost)
246
247 /* If INSN_TICK of an instruction is equal to INVALID_TICK,
248    then it should be recalculated from scratch.  */
249 #define INVALID_TICK (-(max_insn_queue_index + 1))
250 /* The minimal value of the INSN_TICK of an instruction.  */
251 #define MIN_TICK (-max_insn_queue_index)
252
253 /* Original order of insns in the ready list.
254    Used to keep order of normal insns while separating DEBUG_INSNs.  */
255 #define INSN_RFS_DEBUG_ORIG_ORDER(INSN) (HID (INSN)->rfs_debug_orig_order)
256
257 /* The deciding reason for INSN's place in the ready list.  */
258 #define INSN_LAST_RFS_WIN(INSN) (HID (INSN)->last_rfs_win)
259
260 /* List of important notes we must keep around.  This is a pointer to the
261    last element in the list.  */
262 rtx_insn *note_list;
263
264 static struct spec_info_def spec_info_var;
265 /* Description of the speculative part of the scheduling.
266    If NULL - no speculation.  */
267 spec_info_t spec_info = NULL;
268
269 /* True, if recovery block was added during scheduling of current block.
270    Used to determine, if we need to fix INSN_TICKs.  */
271 static bool haifa_recovery_bb_recently_added_p;
272
273 /* True, if recovery block was added during this scheduling pass.
274    Used to determine if we should have empty memory pools of dependencies
275    after finishing current region.  */
276 bool haifa_recovery_bb_ever_added_p;
277
278 /* Counters of different types of speculative instructions.  */
279 static int nr_begin_data, nr_be_in_data, nr_begin_control, nr_be_in_control;
280
281 /* Array used in {unlink, restore}_bb_notes.  */
282 static rtx_insn **bb_header = 0;
283
284 /* Basic block after which recovery blocks will be created.  */
285 static basic_block before_recovery;
286
287 /* Basic block just before the EXIT_BLOCK and after recovery, if we have
288    created it.  */
289 basic_block after_recovery;
290
291 /* FALSE if we add bb to another region, so we don't need to initialize it.  */
292 bool adding_bb_to_current_region_p = true;
293
294 /* Queues, etc.  */
295
296 /* An instruction is ready to be scheduled when all insns preceding it
297    have already been scheduled.  It is important to ensure that all
298    insns which use its result will not be executed until its result
299    has been computed.  An insn is maintained in one of four structures:
300
301    (P) the "Pending" set of insns which cannot be scheduled until
302    their dependencies have been satisfied.
303    (Q) the "Queued" set of insns that can be scheduled when sufficient
304    time has passed.
305    (R) the "Ready" list of unscheduled, uncommitted insns.
306    (S) the "Scheduled" list of insns.
307
308    Initially, all insns are either "Pending" or "Ready" depending on
309    whether their dependencies are satisfied.
310
311    Insns move from the "Ready" list to the "Scheduled" list as they
312    are committed to the schedule.  As this occurs, the insns in the
313    "Pending" list have their dependencies satisfied and move to either
314    the "Ready" list or the "Queued" set depending on whether
315    sufficient time has passed to make them ready.  As time passes,
316    insns move from the "Queued" set to the "Ready" list.
317
318    The "Pending" list (P) are the insns in the INSN_FORW_DEPS of the
319    unscheduled insns, i.e., those that are ready, queued, and pending.
320    The "Queued" set (Q) is implemented by the variable `insn_queue'.
321    The "Ready" list (R) is implemented by the variables `ready' and
322    `n_ready'.
323    The "Scheduled" list (S) is the new insn chain built by this pass.
324
325    The transition (R->S) is implemented in the scheduling loop in
326    `schedule_block' when the best insn to schedule is chosen.
327    The transitions (P->R and P->Q) are implemented in `schedule_insn' as
328    insns move from the ready list to the scheduled list.
329    The transition (Q->R) is implemented in 'queue_to_insn' as time
330    passes or stalls are introduced.  */
331
332 /* Implement a circular buffer to delay instructions until sufficient
333    time has passed.  For the new pipeline description interface,
334    MAX_INSN_QUEUE_INDEX is a power of two minus one which is not less
335    than maximal time of instruction execution computed by genattr.c on
336    the base maximal time of functional unit reservations and getting a
337    result.  This is the longest time an insn may be queued.  */
338
339 static rtx_insn_list **insn_queue;
340 static int q_ptr = 0;
341 static int q_size = 0;
342 #define NEXT_Q(X) (((X)+1) & max_insn_queue_index)
343 #define NEXT_Q_AFTER(X, C) (((X)+C) & max_insn_queue_index)
344
345 #define QUEUE_SCHEDULED (-3)
346 #define QUEUE_NOWHERE   (-2)
347 #define QUEUE_READY     (-1)
348 /* QUEUE_SCHEDULED - INSN is scheduled.
349    QUEUE_NOWHERE   - INSN isn't scheduled yet and is neither in
350    queue or ready list.
351    QUEUE_READY     - INSN is in ready list.
352    N >= 0 - INSN queued for X [where NEXT_Q_AFTER (q_ptr, X) == N] cycles.  */
353
354 #define QUEUE_INDEX(INSN) (HID (INSN)->queue_index)
355
356 /* The following variable value refers for all current and future
357    reservations of the processor units.  */
358 state_t curr_state;
359
360 /* The following variable value is size of memory representing all
361    current and future reservations of the processor units.  */
362 size_t dfa_state_size;
363
364 /* The following array is used to find the best insn from ready when
365    the automaton pipeline interface is used.  */
366 signed char *ready_try = NULL;
367
368 /* The ready list.  */
369 struct ready_list ready = {NULL, 0, 0, 0, 0};
370
371 /* The pointer to the ready list (to be removed).  */
372 static struct ready_list *readyp = &ready;
373
374 /* Scheduling clock.  */
375 static int clock_var;
376
377 /* Clock at which the previous instruction was issued.  */
378 static int last_clock_var;
379
380 /* Set to true if, when queuing a shadow insn, we discover that it would be
381    scheduled too late.  */
382 static bool must_backtrack;
383
384 /* The following variable value is number of essential insns issued on
385    the current cycle.  An insn is essential one if it changes the
386    processors state.  */
387 int cycle_issued_insns;
388
389 /* This records the actual schedule.  It is built up during the main phase
390    of schedule_block, and afterwards used to reorder the insns in the RTL.  */
391 static vec<rtx_insn *> scheduled_insns;
392
393 static int may_trap_exp (const_rtx, int);
394
395 /* Nonzero iff the address is comprised from at most 1 register.  */
396 #define CONST_BASED_ADDRESS_P(x)                        \
397   (REG_P (x)                                    \
398    || ((GET_CODE (x) == PLUS || GET_CODE (x) == MINUS   \
399         || (GET_CODE (x) == LO_SUM))                    \
400        && (CONSTANT_P (XEXP (x, 0))                     \
401            || CONSTANT_P (XEXP (x, 1)))))
402
403 /* Returns a class that insn with GET_DEST(insn)=x may belong to,
404    as found by analyzing insn's expression.  */
405
406 \f
407 static int haifa_luid_for_non_insn (rtx x);
408
409 /* Haifa version of sched_info hooks common to all headers.  */
410 const struct common_sched_info_def haifa_common_sched_info =
411   {
412     NULL, /* fix_recovery_cfg */
413     NULL, /* add_block */
414     NULL, /* estimate_number_of_insns */
415     haifa_luid_for_non_insn, /* luid_for_non_insn */
416     SCHED_PASS_UNKNOWN /* sched_pass_id */
417   };
418
419 /* Mapping from instruction UID to its Logical UID.  */
420 vec<int> sched_luids = vNULL;
421
422 /* Next LUID to assign to an instruction.  */
423 int sched_max_luid = 1;
424
425 /* Haifa Instruction Data.  */
426 vec<haifa_insn_data_def> h_i_d = vNULL;
427
428 void (* sched_init_only_bb) (basic_block, basic_block);
429
430 /* Split block function.  Different schedulers might use different functions
431    to handle their internal data consistent.  */
432 basic_block (* sched_split_block) (basic_block, rtx);
433
434 /* Create empty basic block after the specified block.  */
435 basic_block (* sched_create_empty_bb) (basic_block);
436
437 /* Return the number of cycles until INSN is expected to be ready.
438    Return zero if it already is.  */
439 static int
440 insn_delay (rtx_insn *insn)
441 {
442   return MAX (INSN_TICK (insn) - clock_var, 0);
443 }
444
445 static int
446 may_trap_exp (const_rtx x, int is_store)
447 {
448   enum rtx_code code;
449
450   if (x == 0)
451     return TRAP_FREE;
452   code = GET_CODE (x);
453   if (is_store)
454     {
455       if (code == MEM && may_trap_p (x))
456         return TRAP_RISKY;
457       else
458         return TRAP_FREE;
459     }
460   if (code == MEM)
461     {
462       /* The insn uses memory:  a volatile load.  */
463       if (MEM_VOLATILE_P (x))
464         return IRISKY;
465       /* An exception-free load.  */
466       if (!may_trap_p (x))
467         return IFREE;
468       /* A load with 1 base register, to be further checked.  */
469       if (CONST_BASED_ADDRESS_P (XEXP (x, 0)))
470         return PFREE_CANDIDATE;
471       /* No info on the load, to be further checked.  */
472       return PRISKY_CANDIDATE;
473     }
474   else
475     {
476       const char *fmt;
477       int i, insn_class = TRAP_FREE;
478
479       /* Neither store nor load, check if it may cause a trap.  */
480       if (may_trap_p (x))
481         return TRAP_RISKY;
482       /* Recursive step: walk the insn...  */
483       fmt = GET_RTX_FORMAT (code);
484       for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
485         {
486           if (fmt[i] == 'e')
487             {
488               int tmp_class = may_trap_exp (XEXP (x, i), is_store);
489               insn_class = WORST_CLASS (insn_class, tmp_class);
490             }
491           else if (fmt[i] == 'E')
492             {
493               int j;
494               for (j = 0; j < XVECLEN (x, i); j++)
495                 {
496                   int tmp_class = may_trap_exp (XVECEXP (x, i, j), is_store);
497                   insn_class = WORST_CLASS (insn_class, tmp_class);
498                   if (insn_class == TRAP_RISKY || insn_class == IRISKY)
499                     break;
500                 }
501             }
502           if (insn_class == TRAP_RISKY || insn_class == IRISKY)
503             break;
504         }
505       return insn_class;
506     }
507 }
508
509 /* Classifies rtx X of an insn for the purpose of verifying that X can be
510    executed speculatively (and consequently the insn can be moved
511    speculatively), by examining X, returning:
512    TRAP_RISKY: store, or risky non-load insn (e.g. division by variable).
513    TRAP_FREE: non-load insn.
514    IFREE: load from a globally safe location.
515    IRISKY: volatile load.
516    PFREE_CANDIDATE, PRISKY_CANDIDATE: load that need to be checked for
517    being either PFREE or PRISKY.  */
518
519 static int
520 haifa_classify_rtx (const_rtx x)
521 {
522   int tmp_class = TRAP_FREE;
523   int insn_class = TRAP_FREE;
524   enum rtx_code code;
525
526   if (GET_CODE (x) == PARALLEL)
527     {
528       int i, len = XVECLEN (x, 0);
529
530       for (i = len - 1; i >= 0; i--)
531         {
532           tmp_class = haifa_classify_rtx (XVECEXP (x, 0, i));
533           insn_class = WORST_CLASS (insn_class, tmp_class);
534           if (insn_class == TRAP_RISKY || insn_class == IRISKY)
535             break;
536         }
537     }
538   else
539     {
540       code = GET_CODE (x);
541       switch (code)
542         {
543         case CLOBBER:
544           /* Test if it is a 'store'.  */
545           tmp_class = may_trap_exp (XEXP (x, 0), 1);
546           break;
547         case SET:
548           /* Test if it is a store.  */
549           tmp_class = may_trap_exp (SET_DEST (x), 1);
550           if (tmp_class == TRAP_RISKY)
551             break;
552           /* Test if it is a load.  */
553           tmp_class =
554             WORST_CLASS (tmp_class,
555                          may_trap_exp (SET_SRC (x), 0));
556           break;
557         case COND_EXEC:
558           tmp_class = haifa_classify_rtx (COND_EXEC_CODE (x));
559           if (tmp_class == TRAP_RISKY)
560             break;
561           tmp_class = WORST_CLASS (tmp_class,
562                                    may_trap_exp (COND_EXEC_TEST (x), 0));
563           break;
564         case TRAP_IF:
565           tmp_class = TRAP_RISKY;
566           break;
567         default:;
568         }
569       insn_class = tmp_class;
570     }
571
572   return insn_class;
573 }
574
575 int
576 haifa_classify_insn (const_rtx insn)
577 {
578   return haifa_classify_rtx (PATTERN (insn));
579 }
580 \f
581 /* After the scheduler initialization function has been called, this function
582    can be called to enable modulo scheduling.  II is the initiation interval
583    we should use, it affects the delays for delay_pairs that were recorded as
584    separated by a given number of stages.
585
586    MAX_STAGES provides us with a limit
587    after which we give up scheduling; the caller must have unrolled at least
588    as many copies of the loop body and recorded delay_pairs for them.
589    
590    INSNS is the number of real (non-debug) insns in one iteration of
591    the loop.  MAX_UID can be used to test whether an insn belongs to
592    the first iteration of the loop; all of them have a uid lower than
593    MAX_UID.  */
594 void
595 set_modulo_params (int ii, int max_stages, int insns, int max_uid)
596 {
597   modulo_ii = ii;
598   modulo_max_stages = max_stages;
599   modulo_n_insns = insns;
600   modulo_iter0_max_uid = max_uid;
601   modulo_backtracks_left = PARAM_VALUE (PARAM_MAX_MODULO_BACKTRACK_ATTEMPTS);
602 }
603
604 /* A structure to record a pair of insns where the first one is a real
605    insn that has delay slots, and the second is its delayed shadow.
606    I1 is scheduled normally and will emit an assembly instruction,
607    while I2 describes the side effect that takes place at the
608    transition between cycles CYCLES and (CYCLES + 1) after I1.  */
609 struct delay_pair
610 {
611   struct delay_pair *next_same_i1;
612   rtx_insn *i1, *i2;
613   int cycles;
614   /* When doing modulo scheduling, we a delay_pair can also be used to
615      show that I1 and I2 are the same insn in a different stage.  If that
616      is the case, STAGES will be nonzero.  */
617   int stages;
618 };
619
620 /* Helpers for delay hashing.  */
621
622 struct delay_i1_hasher : typed_noop_remove <delay_pair>
623 {
624   typedef delay_pair value_type;
625   typedef void compare_type;
626   static inline hashval_t hash (const value_type *);
627   static inline bool equal (const value_type *, const compare_type *);
628 };
629
630 /* Returns a hash value for X, based on hashing just I1.  */
631
632 inline hashval_t
633 delay_i1_hasher::hash (const value_type *x)
634 {
635   return htab_hash_pointer (x->i1);
636 }
637
638 /* Return true if I1 of pair X is the same as that of pair Y.  */
639
640 inline bool
641 delay_i1_hasher::equal (const value_type *x, const compare_type *y)
642 {
643   return x->i1 == y;
644 }
645
646 struct delay_i2_hasher : typed_free_remove <delay_pair>
647 {
648   typedef delay_pair value_type;
649   typedef void compare_type;
650   static inline hashval_t hash (const value_type *);
651   static inline bool equal (const value_type *, const compare_type *);
652 };
653
654 /* Returns a hash value for X, based on hashing just I2.  */
655
656 inline hashval_t
657 delay_i2_hasher::hash (const value_type *x)
658 {
659   return htab_hash_pointer (x->i2);
660 }
661
662 /* Return true if I2 of pair X is the same as that of pair Y.  */
663
664 inline bool
665 delay_i2_hasher::equal (const value_type *x, const compare_type *y)
666 {
667   return x->i2 == y;
668 }
669
670 /* Two hash tables to record delay_pairs, one indexed by I1 and the other
671    indexed by I2.  */
672 static hash_table<delay_i1_hasher> *delay_htab;
673 static hash_table<delay_i2_hasher> *delay_htab_i2;
674
675 /* Called through htab_traverse.  Walk the hashtable using I2 as
676    index, and delete all elements involving an UID higher than
677    that pointed to by *DATA.  */
678 int
679 haifa_htab_i2_traverse (delay_pair **slot, int *data)
680 {
681   int maxuid = *data;
682   struct delay_pair *p = *slot;
683   if (INSN_UID (p->i2) >= maxuid || INSN_UID (p->i1) >= maxuid)
684     {
685       delay_htab_i2->clear_slot (slot);
686     }
687   return 1;
688 }
689
690 /* Called through htab_traverse.  Walk the hashtable using I2 as
691    index, and delete all elements involving an UID higher than
692    that pointed to by *DATA.  */
693 int
694 haifa_htab_i1_traverse (delay_pair **pslot, int *data)
695 {
696   int maxuid = *data;
697   struct delay_pair *p, *first, **pprev;
698
699   if (INSN_UID ((*pslot)->i1) >= maxuid)
700     {
701       delay_htab->clear_slot (pslot);
702       return 1;
703     }
704   pprev = &first;
705   for (p = *pslot; p; p = p->next_same_i1)
706     {
707       if (INSN_UID (p->i2) < maxuid)
708         {
709           *pprev = p;
710           pprev = &p->next_same_i1;
711         }
712     }
713   *pprev = NULL;
714   if (first == NULL)
715     delay_htab->clear_slot (pslot);
716   else
717     *pslot = first;
718   return 1;
719 }
720
721 /* Discard all delay pairs which involve an insn with an UID higher
722    than MAX_UID.  */
723 void
724 discard_delay_pairs_above (int max_uid)
725 {
726   delay_htab->traverse <int *, haifa_htab_i1_traverse> (&max_uid);
727   delay_htab_i2->traverse <int *, haifa_htab_i2_traverse> (&max_uid);
728 }
729
730 /* This function can be called by a port just before it starts the final
731    scheduling pass.  It records the fact that an instruction with delay
732    slots has been split into two insns, I1 and I2.  The first one will be
733    scheduled normally and initiates the operation.  The second one is a
734    shadow which must follow a specific number of cycles after I1; its only
735    purpose is to show the side effect that occurs at that cycle in the RTL.
736    If a JUMP_INSN or a CALL_INSN has been split, I1 should be a normal INSN,
737    while I2 retains the original insn type.
738
739    There are two ways in which the number of cycles can be specified,
740    involving the CYCLES and STAGES arguments to this function.  If STAGES
741    is zero, we just use the value of CYCLES.  Otherwise, STAGES is a factor
742    which is multiplied by MODULO_II to give the number of cycles.  This is
743    only useful if the caller also calls set_modulo_params to enable modulo
744    scheduling.  */
745
746 void
747 record_delay_slot_pair (rtx_insn *i1, rtx_insn *i2, int cycles, int stages)
748 {
749   struct delay_pair *p = XNEW (struct delay_pair);
750   struct delay_pair **slot;
751
752   p->i1 = i1;
753   p->i2 = i2;
754   p->cycles = cycles;
755   p->stages = stages;
756
757   if (!delay_htab)
758     {
759       delay_htab = new hash_table<delay_i1_hasher> (10);
760       delay_htab_i2 = new hash_table<delay_i2_hasher> (10);
761     }
762   slot = delay_htab->find_slot_with_hash (i1, htab_hash_pointer (i1), INSERT);
763   p->next_same_i1 = *slot;
764   *slot = p;
765   slot = delay_htab_i2->find_slot (p, INSERT);
766   *slot = p;
767 }
768
769 /* Examine the delay pair hashtable to see if INSN is a shadow for another,
770    and return the other insn if so.  Return NULL otherwise.  */
771 rtx_insn *
772 real_insn_for_shadow (rtx_insn *insn)
773 {
774   struct delay_pair *pair;
775
776   if (!delay_htab)
777     return NULL;
778
779   pair = delay_htab_i2->find_with_hash (insn, htab_hash_pointer (insn));
780   if (!pair || pair->stages > 0)
781     return NULL;
782   return pair->i1;
783 }
784
785 /* For a pair P of insns, return the fixed distance in cycles from the first
786    insn after which the second must be scheduled.  */
787 static int
788 pair_delay (struct delay_pair *p)
789 {
790   if (p->stages == 0)
791     return p->cycles;
792   else
793     return p->stages * modulo_ii;
794 }
795
796 /* Given an insn INSN, add a dependence on its delayed shadow if it
797    has one.  Also try to find situations where shadows depend on each other
798    and add dependencies to the real insns to limit the amount of backtracking
799    needed.  */
800 void
801 add_delay_dependencies (rtx_insn *insn)
802 {
803   struct delay_pair *pair;
804   sd_iterator_def sd_it;
805   dep_t dep;
806
807   if (!delay_htab)
808     return;
809
810   pair = delay_htab_i2->find_with_hash (insn, htab_hash_pointer (insn));
811   if (!pair)
812     return;
813   add_dependence (insn, pair->i1, REG_DEP_ANTI);
814   if (pair->stages)
815     return;
816
817   FOR_EACH_DEP (pair->i2, SD_LIST_BACK, sd_it, dep)
818     {
819       rtx_insn *pro = DEP_PRO (dep);
820       struct delay_pair *other_pair
821         = delay_htab_i2->find_with_hash (pro, htab_hash_pointer (pro));
822       if (!other_pair || other_pair->stages)
823         continue;
824       if (pair_delay (other_pair) >= pair_delay (pair))
825         {
826           if (sched_verbose >= 4)
827             {
828               fprintf (sched_dump, ";;\tadding dependence %d <- %d\n",
829                        INSN_UID (other_pair->i1),
830                        INSN_UID (pair->i1));
831               fprintf (sched_dump, ";;\tpair1 %d <- %d, cost %d\n",
832                        INSN_UID (pair->i1),
833                        INSN_UID (pair->i2),
834                        pair_delay (pair));
835               fprintf (sched_dump, ";;\tpair2 %d <- %d, cost %d\n",
836                        INSN_UID (other_pair->i1),
837                        INSN_UID (other_pair->i2),
838                        pair_delay (other_pair));
839             }
840           add_dependence (pair->i1, other_pair->i1, REG_DEP_ANTI);
841         }
842     }
843 }
844 \f
845 /* Forward declarations.  */
846
847 static int priority (rtx_insn *);
848 static int autopref_rank_for_schedule (const rtx_insn *, const rtx_insn *);
849 static int rank_for_schedule (const void *, const void *);
850 static void swap_sort (rtx_insn **, int);
851 static void queue_insn (rtx_insn *, int, const char *);
852 static int schedule_insn (rtx_insn *);
853 static void adjust_priority (rtx_insn *);
854 static void advance_one_cycle (void);
855 static void extend_h_i_d (void);
856
857
858 /* Notes handling mechanism:
859    =========================
860    Generally, NOTES are saved before scheduling and restored after scheduling.
861    The scheduler distinguishes between two types of notes:
862
863    (1) LOOP_BEGIN, LOOP_END, SETJMP, EHREGION_BEG, EHREGION_END notes:
864    Before scheduling a region, a pointer to the note is added to the insn
865    that follows or precedes it.  (This happens as part of the data dependence
866    computation).  After scheduling an insn, the pointer contained in it is
867    used for regenerating the corresponding note (in reemit_notes).
868
869    (2) All other notes (e.g. INSN_DELETED):  Before scheduling a block,
870    these notes are put in a list (in rm_other_notes() and
871    unlink_other_notes ()).  After scheduling the block, these notes are
872    inserted at the beginning of the block (in schedule_block()).  */
873
874 static void ready_add (struct ready_list *, rtx_insn *, bool);
875 static rtx_insn *ready_remove_first (struct ready_list *);
876 static rtx_insn *ready_remove_first_dispatch (struct ready_list *ready);
877
878 static void queue_to_ready (struct ready_list *);
879 static int early_queue_to_ready (state_t, struct ready_list *);
880
881 /* The following functions are used to implement multi-pass scheduling
882    on the first cycle.  */
883 static rtx_insn *ready_remove (struct ready_list *, int);
884 static void ready_remove_insn (rtx);
885
886 static void fix_inter_tick (rtx_insn *, rtx_insn *);
887 static int fix_tick_ready (rtx_insn *);
888 static void change_queue_index (rtx_insn *, int);
889
890 /* The following functions are used to implement scheduling of data/control
891    speculative instructions.  */
892
893 static void extend_h_i_d (void);
894 static void init_h_i_d (rtx_insn *);
895 static int haifa_speculate_insn (rtx_insn *, ds_t, rtx *);
896 static void generate_recovery_code (rtx_insn *);
897 static void process_insn_forw_deps_be_in_spec (rtx, rtx_insn *, ds_t);
898 static void begin_speculative_block (rtx_insn *);
899 static void add_to_speculative_block (rtx_insn *);
900 static void init_before_recovery (basic_block *);
901 static void create_check_block_twin (rtx_insn *, bool);
902 static void fix_recovery_deps (basic_block);
903 static bool haifa_change_pattern (rtx_insn *, rtx);
904 static void dump_new_block_header (int, basic_block, rtx_insn *, rtx_insn *);
905 static void restore_bb_notes (basic_block);
906 static void fix_jump_move (rtx_insn *);
907 static void move_block_after_check (rtx_insn *);
908 static void move_succs (vec<edge, va_gc> **, basic_block);
909 static void sched_remove_insn (rtx_insn *);
910 static void clear_priorities (rtx_insn *, rtx_vec_t *);
911 static void calc_priorities (rtx_vec_t);
912 static void add_jump_dependencies (rtx_insn *, rtx_insn *);
913
914 #endif /* INSN_SCHEDULING */
915 \f
916 /* Point to state used for the current scheduling pass.  */
917 struct haifa_sched_info *current_sched_info;
918 \f
919 #ifndef INSN_SCHEDULING
920 void
921 schedule_insns (void)
922 {
923 }
924 #else
925
926 /* Do register pressure sensitive insn scheduling if the flag is set
927    up.  */
928 enum sched_pressure_algorithm sched_pressure;
929
930 /* Map regno -> its pressure class.  The map defined only when
931    SCHED_PRESSURE != SCHED_PRESSURE_NONE.  */
932 enum reg_class *sched_regno_pressure_class;
933
934 /* The current register pressure.  Only elements corresponding pressure
935    classes are defined.  */
936 static int curr_reg_pressure[N_REG_CLASSES];
937
938 /* Saved value of the previous array.  */
939 static int saved_reg_pressure[N_REG_CLASSES];
940
941 /* Register living at given scheduling point.  */
942 static bitmap curr_reg_live;
943
944 /* Saved value of the previous array.  */
945 static bitmap saved_reg_live;
946
947 /* Registers mentioned in the current region.  */
948 static bitmap region_ref_regs;
949
950 /* Effective number of available registers of a given class (see comment
951    in sched_pressure_start_bb).  */
952 static int sched_class_regs_num[N_REG_CLASSES];
953 /* Number of call_used_regs.  This is a helper for calculating of
954    sched_class_regs_num.  */
955 static int call_used_regs_num[N_REG_CLASSES];
956
957 /* Initiate register pressure relative info for scheduling the current
958    region.  Currently it is only clearing register mentioned in the
959    current region.  */
960 void
961 sched_init_region_reg_pressure_info (void)
962 {
963   bitmap_clear (region_ref_regs);
964 }
965
966 /* PRESSURE[CL] describes the pressure on register class CL.  Update it
967    for the birth (if BIRTH_P) or death (if !BIRTH_P) of register REGNO.
968    LIVE tracks the set of live registers; if it is null, assume that
969    every birth or death is genuine.  */
970 static inline void
971 mark_regno_birth_or_death (bitmap live, int *pressure, int regno, bool birth_p)
972 {
973   enum reg_class pressure_class;
974
975   pressure_class = sched_regno_pressure_class[regno];
976   if (regno >= FIRST_PSEUDO_REGISTER)
977     {
978       if (pressure_class != NO_REGS)
979         {
980           if (birth_p)
981             {
982               if (!live || bitmap_set_bit (live, regno))
983                 pressure[pressure_class]
984                   += (ira_reg_class_max_nregs
985                       [pressure_class][PSEUDO_REGNO_MODE (regno)]);
986             }
987           else
988             {
989               if (!live || bitmap_clear_bit (live, regno))
990                 pressure[pressure_class]
991                   -= (ira_reg_class_max_nregs
992                       [pressure_class][PSEUDO_REGNO_MODE (regno)]);
993             }
994         }
995     }
996   else if (pressure_class != NO_REGS
997            && ! TEST_HARD_REG_BIT (ira_no_alloc_regs, regno))
998     {
999       if (birth_p)
1000         {
1001           if (!live || bitmap_set_bit (live, regno))
1002             pressure[pressure_class]++;
1003         }
1004       else
1005         {
1006           if (!live || bitmap_clear_bit (live, regno))
1007             pressure[pressure_class]--;
1008         }
1009     }
1010 }
1011
1012 /* Initiate current register pressure related info from living
1013    registers given by LIVE.  */
1014 static void
1015 initiate_reg_pressure_info (bitmap live)
1016 {
1017   int i;
1018   unsigned int j;
1019   bitmap_iterator bi;
1020
1021   for (i = 0; i < ira_pressure_classes_num; i++)
1022     curr_reg_pressure[ira_pressure_classes[i]] = 0;
1023   bitmap_clear (curr_reg_live);
1024   EXECUTE_IF_SET_IN_BITMAP (live, 0, j, bi)
1025     if (sched_pressure == SCHED_PRESSURE_MODEL
1026         || current_nr_blocks == 1
1027         || bitmap_bit_p (region_ref_regs, j))
1028       mark_regno_birth_or_death (curr_reg_live, curr_reg_pressure, j, true);
1029 }
1030
1031 /* Mark registers in X as mentioned in the current region.  */
1032 static void
1033 setup_ref_regs (rtx x)
1034 {
1035   int i, j, regno;
1036   const RTX_CODE code = GET_CODE (x);
1037   const char *fmt;
1038
1039   if (REG_P (x))
1040     {
1041       regno = REGNO (x);
1042       if (HARD_REGISTER_NUM_P (regno))
1043         bitmap_set_range (region_ref_regs, regno,
1044                           hard_regno_nregs[regno][GET_MODE (x)]);
1045       else
1046         bitmap_set_bit (region_ref_regs, REGNO (x));
1047       return;
1048     }
1049   fmt = GET_RTX_FORMAT (code);
1050   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1051     if (fmt[i] == 'e')
1052       setup_ref_regs (XEXP (x, i));
1053     else if (fmt[i] == 'E')
1054       {
1055         for (j = 0; j < XVECLEN (x, i); j++)
1056           setup_ref_regs (XVECEXP (x, i, j));
1057       }
1058 }
1059
1060 /* Initiate current register pressure related info at the start of
1061    basic block BB.  */
1062 static void
1063 initiate_bb_reg_pressure_info (basic_block bb)
1064 {
1065   unsigned int i ATTRIBUTE_UNUSED;
1066   rtx_insn *insn;
1067
1068   if (current_nr_blocks > 1)
1069     FOR_BB_INSNS (bb, insn)
1070       if (NONDEBUG_INSN_P (insn))
1071         setup_ref_regs (PATTERN (insn));
1072   initiate_reg_pressure_info (df_get_live_in (bb));
1073 #ifdef EH_RETURN_DATA_REGNO
1074   if (bb_has_eh_pred (bb))
1075     for (i = 0; ; ++i)
1076       {
1077         unsigned int regno = EH_RETURN_DATA_REGNO (i);
1078
1079         if (regno == INVALID_REGNUM)
1080           break;
1081         if (! bitmap_bit_p (df_get_live_in (bb), regno))
1082           mark_regno_birth_or_death (curr_reg_live, curr_reg_pressure,
1083                                      regno, true);
1084       }
1085 #endif
1086 }
1087
1088 /* Save current register pressure related info.  */
1089 static void
1090 save_reg_pressure (void)
1091 {
1092   int i;
1093
1094   for (i = 0; i < ira_pressure_classes_num; i++)
1095     saved_reg_pressure[ira_pressure_classes[i]]
1096       = curr_reg_pressure[ira_pressure_classes[i]];
1097   bitmap_copy (saved_reg_live, curr_reg_live);
1098 }
1099
1100 /* Restore saved register pressure related info.  */
1101 static void
1102 restore_reg_pressure (void)
1103 {
1104   int i;
1105
1106   for (i = 0; i < ira_pressure_classes_num; i++)
1107     curr_reg_pressure[ira_pressure_classes[i]]
1108       = saved_reg_pressure[ira_pressure_classes[i]];
1109   bitmap_copy (curr_reg_live, saved_reg_live);
1110 }
1111
1112 /* Return TRUE if the register is dying after its USE.  */
1113 static bool
1114 dying_use_p (struct reg_use_data *use)
1115 {
1116   struct reg_use_data *next;
1117
1118   for (next = use->next_regno_use; next != use; next = next->next_regno_use)
1119     if (NONDEBUG_INSN_P (next->insn)
1120         && QUEUE_INDEX (next->insn) != QUEUE_SCHEDULED)
1121       return false;
1122   return true;
1123 }
1124
1125 /* Print info about the current register pressure and its excess for
1126    each pressure class.  */
1127 static void
1128 print_curr_reg_pressure (void)
1129 {
1130   int i;
1131   enum reg_class cl;
1132
1133   fprintf (sched_dump, ";;\t");
1134   for (i = 0; i < ira_pressure_classes_num; i++)
1135     {
1136       cl = ira_pressure_classes[i];
1137       gcc_assert (curr_reg_pressure[cl] >= 0);
1138       fprintf (sched_dump, "  %s:%d(%d)", reg_class_names[cl],
1139                curr_reg_pressure[cl],
1140                curr_reg_pressure[cl] - sched_class_regs_num[cl]);
1141     }
1142   fprintf (sched_dump, "\n");
1143 }
1144 \f
1145 /* Determine if INSN has a condition that is clobbered if a register
1146    in SET_REGS is modified.  */
1147 static bool
1148 cond_clobbered_p (rtx_insn *insn, HARD_REG_SET set_regs)
1149 {
1150   rtx pat = PATTERN (insn);
1151   gcc_assert (GET_CODE (pat) == COND_EXEC);
1152   if (TEST_HARD_REG_BIT (set_regs, REGNO (XEXP (COND_EXEC_TEST (pat), 0))))
1153     {
1154       sd_iterator_def sd_it;
1155       dep_t dep;
1156       haifa_change_pattern (insn, ORIG_PAT (insn));
1157       FOR_EACH_DEP (insn, SD_LIST_BACK, sd_it, dep)
1158         DEP_STATUS (dep) &= ~DEP_CANCELLED;
1159       TODO_SPEC (insn) = HARD_DEP;
1160       if (sched_verbose >= 2)
1161         fprintf (sched_dump,
1162                  ";;\t\tdequeue insn %s because of clobbered condition\n",
1163                  (*current_sched_info->print_insn) (insn, 0));
1164       return true;
1165     }
1166
1167   return false;
1168 }
1169
1170 /* This function should be called after modifying the pattern of INSN,
1171    to update scheduler data structures as needed.  */
1172 static void
1173 update_insn_after_change (rtx_insn *insn)
1174 {
1175   sd_iterator_def sd_it;
1176   dep_t dep;
1177
1178   dfa_clear_single_insn_cache (insn);
1179
1180   sd_it = sd_iterator_start (insn,
1181                              SD_LIST_FORW | SD_LIST_BACK | SD_LIST_RES_BACK);
1182   while (sd_iterator_cond (&sd_it, &dep))
1183     {
1184       DEP_COST (dep) = UNKNOWN_DEP_COST;
1185       sd_iterator_next (&sd_it);
1186     }
1187
1188   /* Invalidate INSN_COST, so it'll be recalculated.  */
1189   INSN_COST (insn) = -1;
1190   /* Invalidate INSN_TICK, so it'll be recalculated.  */
1191   INSN_TICK (insn) = INVALID_TICK;
1192
1193   /* Invalidate autoprefetch data entry.  */
1194   INSN_AUTOPREF_MULTIPASS_DATA (insn)[0].status
1195     = AUTOPREF_MULTIPASS_DATA_UNINITIALIZED;
1196   INSN_AUTOPREF_MULTIPASS_DATA (insn)[1].status
1197     = AUTOPREF_MULTIPASS_DATA_UNINITIALIZED;
1198 }
1199
1200
1201 /* Two VECs, one to hold dependencies for which pattern replacements
1202    need to be applied or restored at the start of the next cycle, and
1203    another to hold an integer that is either one, to apply the
1204    corresponding replacement, or zero to restore it.  */
1205 static vec<dep_t> next_cycle_replace_deps;
1206 static vec<int> next_cycle_apply;
1207
1208 static void apply_replacement (dep_t, bool);
1209 static void restore_pattern (dep_t, bool);
1210
1211 /* Look at the remaining dependencies for insn NEXT, and compute and return
1212    the TODO_SPEC value we should use for it.  This is called after one of
1213    NEXT's dependencies has been resolved.
1214    We also perform pattern replacements for predication, and for broken
1215    replacement dependencies.  The latter is only done if FOR_BACKTRACK is
1216    false.  */
1217
1218 static ds_t
1219 recompute_todo_spec (rtx_insn *next, bool for_backtrack)
1220 {
1221   ds_t new_ds;
1222   sd_iterator_def sd_it;
1223   dep_t dep, modify_dep = NULL;
1224   int n_spec = 0;
1225   int n_control = 0;
1226   int n_replace = 0;
1227   bool first_p = true;
1228
1229   if (sd_lists_empty_p (next, SD_LIST_BACK))
1230     /* NEXT has all its dependencies resolved.  */
1231     return 0;
1232
1233   if (!sd_lists_empty_p (next, SD_LIST_HARD_BACK))
1234     return HARD_DEP;
1235
1236   /* Now we've got NEXT with speculative deps only.
1237      1. Look at the deps to see what we have to do.
1238      2. Check if we can do 'todo'.  */
1239   new_ds = 0;
1240
1241   FOR_EACH_DEP (next, SD_LIST_BACK, sd_it, dep)
1242     {
1243       rtx_insn *pro = DEP_PRO (dep);
1244       ds_t ds = DEP_STATUS (dep) & SPECULATIVE;
1245
1246       if (DEBUG_INSN_P (pro) && !DEBUG_INSN_P (next))
1247         continue;
1248
1249       if (ds)
1250         {
1251           n_spec++;
1252           if (first_p)
1253             {
1254               first_p = false;
1255
1256               new_ds = ds;
1257             }
1258           else
1259             new_ds = ds_merge (new_ds, ds);
1260         }
1261       else if (DEP_TYPE (dep) == REG_DEP_CONTROL)
1262         {
1263           if (QUEUE_INDEX (pro) != QUEUE_SCHEDULED)
1264             {
1265               n_control++;
1266               modify_dep = dep;
1267             }
1268           DEP_STATUS (dep) &= ~DEP_CANCELLED;
1269         }
1270       else if (DEP_REPLACE (dep) != NULL)
1271         {
1272           if (QUEUE_INDEX (pro) != QUEUE_SCHEDULED)
1273             {
1274               n_replace++;
1275               modify_dep = dep;
1276             }
1277           DEP_STATUS (dep) &= ~DEP_CANCELLED;
1278         }
1279     }
1280
1281   if (n_replace > 0 && n_control == 0 && n_spec == 0)
1282     {
1283       if (!dbg_cnt (sched_breakdep))
1284         return HARD_DEP;
1285       FOR_EACH_DEP (next, SD_LIST_BACK, sd_it, dep)
1286         {
1287           struct dep_replacement *desc = DEP_REPLACE (dep);
1288           if (desc != NULL)
1289             {
1290               if (desc->insn == next && !for_backtrack)
1291                 {
1292                   gcc_assert (n_replace == 1);
1293                   apply_replacement (dep, true);
1294                 }
1295               DEP_STATUS (dep) |= DEP_CANCELLED;
1296             }
1297         }
1298       return 0;
1299     }
1300   
1301   else if (n_control == 1 && n_replace == 0 && n_spec == 0)
1302     {
1303       rtx_insn *pro, *other;
1304       rtx new_pat;
1305       rtx cond = NULL_RTX;
1306       bool success;
1307       rtx_insn *prev = NULL;
1308       int i;
1309       unsigned regno;
1310   
1311       if ((current_sched_info->flags & DO_PREDICATION) == 0
1312           || (ORIG_PAT (next) != NULL_RTX
1313               && PREDICATED_PAT (next) == NULL_RTX))
1314         return HARD_DEP;
1315
1316       pro = DEP_PRO (modify_dep);
1317       other = real_insn_for_shadow (pro);
1318       if (other != NULL_RTX)
1319         pro = other;
1320
1321       cond = sched_get_reverse_condition_uncached (pro);
1322       regno = REGNO (XEXP (cond, 0));
1323
1324       /* Find the last scheduled insn that modifies the condition register.
1325          We can stop looking once we find the insn we depend on through the
1326          REG_DEP_CONTROL; if the condition register isn't modified after it,
1327          we know that it still has the right value.  */
1328       if (QUEUE_INDEX (pro) == QUEUE_SCHEDULED)
1329         FOR_EACH_VEC_ELT_REVERSE (scheduled_insns, i, prev)
1330           {
1331             HARD_REG_SET t;
1332
1333             find_all_hard_reg_sets (prev, &t, true);
1334             if (TEST_HARD_REG_BIT (t, regno))
1335               return HARD_DEP;
1336             if (prev == pro)
1337               break;
1338           }
1339       if (ORIG_PAT (next) == NULL_RTX)
1340         {
1341           ORIG_PAT (next) = PATTERN (next);
1342
1343           new_pat = gen_rtx_COND_EXEC (VOIDmode, cond, PATTERN (next));
1344           success = haifa_change_pattern (next, new_pat);
1345           if (!success)
1346             return HARD_DEP;
1347           PREDICATED_PAT (next) = new_pat;
1348         }
1349       else if (PATTERN (next) != PREDICATED_PAT (next))
1350         {
1351           bool success = haifa_change_pattern (next,
1352                                                PREDICATED_PAT (next));
1353           gcc_assert (success);
1354         }
1355       DEP_STATUS (modify_dep) |= DEP_CANCELLED;
1356       return DEP_CONTROL;
1357     }
1358
1359   if (PREDICATED_PAT (next) != NULL_RTX)
1360     {
1361       int tick = INSN_TICK (next);
1362       bool success = haifa_change_pattern (next,
1363                                            ORIG_PAT (next));
1364       INSN_TICK (next) = tick;
1365       gcc_assert (success);
1366     }
1367
1368   /* We can't handle the case where there are both speculative and control
1369      dependencies, so we return HARD_DEP in such a case.  Also fail if
1370      we have speculative dependencies with not enough points, or more than
1371      one control dependency.  */
1372   if ((n_spec > 0 && (n_control > 0 || n_replace > 0))
1373       || (n_spec > 0
1374           /* Too few points?  */
1375           && ds_weak (new_ds) < spec_info->data_weakness_cutoff)
1376       || n_control > 0
1377       || n_replace > 0)
1378     return HARD_DEP;
1379
1380   return new_ds;
1381 }
1382 \f
1383 /* Pointer to the last instruction scheduled.  */
1384 static rtx_insn *last_scheduled_insn;
1385
1386 /* Pointer to the last nondebug instruction scheduled within the
1387    block, or the prev_head of the scheduling block.  Used by
1388    rank_for_schedule, so that insns independent of the last scheduled
1389    insn will be preferred over dependent instructions.  */
1390 static rtx last_nondebug_scheduled_insn;
1391
1392 /* Pointer that iterates through the list of unscheduled insns if we
1393    have a dbg_cnt enabled.  It always points at an insn prior to the
1394    first unscheduled one.  */
1395 static rtx_insn *nonscheduled_insns_begin;
1396
1397 /* Compute cost of executing INSN.
1398    This is the number of cycles between instruction issue and
1399    instruction results.  */
1400 int
1401 insn_cost (rtx_insn *insn)
1402 {
1403   int cost;
1404
1405   if (sched_fusion)
1406     return 0;
1407
1408   if (sel_sched_p ())
1409     {
1410       if (recog_memoized (insn) < 0)
1411         return 0;
1412
1413       cost = insn_default_latency (insn);
1414       if (cost < 0)
1415         cost = 0;
1416
1417       return cost;
1418     }
1419
1420   cost = INSN_COST (insn);
1421
1422   if (cost < 0)
1423     {
1424       /* A USE insn, or something else we don't need to
1425          understand.  We can't pass these directly to
1426          result_ready_cost or insn_default_latency because it will
1427          trigger a fatal error for unrecognizable insns.  */
1428       if (recog_memoized (insn) < 0)
1429         {
1430           INSN_COST (insn) = 0;
1431           return 0;
1432         }
1433       else
1434         {
1435           cost = insn_default_latency (insn);
1436           if (cost < 0)
1437             cost = 0;
1438
1439           INSN_COST (insn) = cost;
1440         }
1441     }
1442
1443   return cost;
1444 }
1445
1446 /* Compute cost of dependence LINK.
1447    This is the number of cycles between instruction issue and
1448    instruction results.
1449    ??? We also use this function to call recog_memoized on all insns.  */
1450 int
1451 dep_cost_1 (dep_t link, dw_t dw)
1452 {
1453   rtx_insn *insn = DEP_PRO (link);
1454   rtx_insn *used = DEP_CON (link);
1455   int cost;
1456
1457   if (DEP_COST (link) != UNKNOWN_DEP_COST)
1458     return DEP_COST (link);
1459
1460   if (delay_htab)
1461     {
1462       struct delay_pair *delay_entry;
1463       delay_entry
1464         = delay_htab_i2->find_with_hash (used, htab_hash_pointer (used));
1465       if (delay_entry)
1466         {
1467           if (delay_entry->i1 == insn)
1468             {
1469               DEP_COST (link) = pair_delay (delay_entry);
1470               return DEP_COST (link);
1471             }
1472         }
1473     }
1474
1475   /* A USE insn should never require the value used to be computed.
1476      This allows the computation of a function's result and parameter
1477      values to overlap the return and call.  We don't care about the
1478      dependence cost when only decreasing register pressure.  */
1479   if (recog_memoized (used) < 0)
1480     {
1481       cost = 0;
1482       recog_memoized (insn);
1483     }
1484   else
1485     {
1486       enum reg_note dep_type = DEP_TYPE (link);
1487
1488       cost = insn_cost (insn);
1489
1490       if (INSN_CODE (insn) >= 0)
1491         {
1492           if (dep_type == REG_DEP_ANTI)
1493             cost = 0;
1494           else if (dep_type == REG_DEP_OUTPUT)
1495             {
1496               cost = (insn_default_latency (insn)
1497                       - insn_default_latency (used));
1498               if (cost <= 0)
1499                 cost = 1;
1500             }
1501           else if (bypass_p (insn))
1502             cost = insn_latency (insn, used);
1503         }
1504
1505
1506       if (targetm.sched.adjust_cost_2)
1507         cost = targetm.sched.adjust_cost_2 (used, (int) dep_type, insn, cost,
1508                                             dw);
1509       else if (targetm.sched.adjust_cost != NULL)
1510         {
1511           /* This variable is used for backward compatibility with the
1512              targets.  */
1513           rtx_insn_list *dep_cost_rtx_link =
1514             alloc_INSN_LIST (NULL_RTX, NULL);
1515
1516           /* Make it self-cycled, so that if some tries to walk over this
1517              incomplete list he/she will be caught in an endless loop.  */
1518           XEXP (dep_cost_rtx_link, 1) = dep_cost_rtx_link;
1519
1520           /* Targets use only REG_NOTE_KIND of the link.  */
1521           PUT_REG_NOTE_KIND (dep_cost_rtx_link, DEP_TYPE (link));
1522
1523           cost = targetm.sched.adjust_cost (used, dep_cost_rtx_link,
1524                                             insn, cost);
1525
1526           free_INSN_LIST_node (dep_cost_rtx_link);
1527         }
1528
1529       if (cost < 0)
1530         cost = 0;
1531     }
1532
1533   DEP_COST (link) = cost;
1534   return cost;
1535 }
1536
1537 /* Compute cost of dependence LINK.
1538    This is the number of cycles between instruction issue and
1539    instruction results.  */
1540 int
1541 dep_cost (dep_t link)
1542 {
1543   return dep_cost_1 (link, 0);
1544 }
1545
1546 /* Use this sel-sched.c friendly function in reorder2 instead of increasing
1547    INSN_PRIORITY explicitly.  */
1548 void
1549 increase_insn_priority (rtx_insn *insn, int amount)
1550 {
1551   if (!sel_sched_p ())
1552     {
1553       /* We're dealing with haifa-sched.c INSN_PRIORITY.  */
1554       if (INSN_PRIORITY_KNOWN (insn))
1555           INSN_PRIORITY (insn) += amount;
1556     }
1557   else
1558     {
1559       /* In sel-sched.c INSN_PRIORITY is not kept up to date.
1560          Use EXPR_PRIORITY instead. */
1561       sel_add_to_insn_priority (insn, amount);
1562     }
1563 }
1564
1565 /* Return 'true' if DEP should be included in priority calculations.  */
1566 static bool
1567 contributes_to_priority_p (dep_t dep)
1568 {
1569   if (DEBUG_INSN_P (DEP_CON (dep))
1570       || DEBUG_INSN_P (DEP_PRO (dep)))
1571     return false;
1572
1573   /* Critical path is meaningful in block boundaries only.  */
1574   if (!current_sched_info->contributes_to_priority (DEP_CON (dep),
1575                                                     DEP_PRO (dep)))
1576     return false;
1577
1578   if (DEP_REPLACE (dep) != NULL)
1579     return false;
1580
1581   /* If flag COUNT_SPEC_IN_CRITICAL_PATH is set,
1582      then speculative instructions will less likely be
1583      scheduled.  That is because the priority of
1584      their producers will increase, and, thus, the
1585      producers will more likely be scheduled, thus,
1586      resolving the dependence.  */
1587   if (sched_deps_info->generate_spec_deps
1588       && !(spec_info->flags & COUNT_SPEC_IN_CRITICAL_PATH)
1589       && (DEP_STATUS (dep) & SPECULATIVE))
1590     return false;
1591
1592   return true;
1593 }
1594
1595 /* Compute the number of nondebug deps in list LIST for INSN.  */
1596
1597 static int
1598 dep_list_size (rtx insn, sd_list_types_def list)
1599 {
1600   sd_iterator_def sd_it;
1601   dep_t dep;
1602   int dbgcount = 0, nodbgcount = 0;
1603
1604   if (!MAY_HAVE_DEBUG_INSNS)
1605     return sd_lists_size (insn, list);
1606
1607   FOR_EACH_DEP (insn, list, sd_it, dep)
1608     {
1609       if (DEBUG_INSN_P (DEP_CON (dep)))
1610         dbgcount++;
1611       else if (!DEBUG_INSN_P (DEP_PRO (dep)))
1612         nodbgcount++;
1613     }
1614
1615   gcc_assert (dbgcount + nodbgcount == sd_lists_size (insn, list));
1616
1617   return nodbgcount;
1618 }
1619
1620 bool sched_fusion;
1621
1622 /* Compute the priority number for INSN.  */
1623 static int
1624 priority (rtx_insn *insn)
1625 {
1626   if (! INSN_P (insn))
1627     return 0;
1628
1629   /* We should not be interested in priority of an already scheduled insn.  */
1630   gcc_assert (QUEUE_INDEX (insn) != QUEUE_SCHEDULED);
1631
1632   if (!INSN_PRIORITY_KNOWN (insn))
1633     {
1634       int this_priority = -1;
1635
1636       if (sched_fusion)
1637         {
1638           int this_fusion_priority;
1639
1640           targetm.sched.fusion_priority (insn, FUSION_MAX_PRIORITY,
1641                                          &this_fusion_priority, &this_priority);
1642           INSN_FUSION_PRIORITY (insn) = this_fusion_priority;
1643         }
1644       else if (dep_list_size (insn, SD_LIST_FORW) == 0)
1645         /* ??? We should set INSN_PRIORITY to insn_cost when and insn has
1646            some forward deps but all of them are ignored by
1647            contributes_to_priority hook.  At the moment we set priority of
1648            such insn to 0.  */
1649         this_priority = insn_cost (insn);
1650       else
1651         {
1652           rtx_insn *prev_first, *twin;
1653           basic_block rec;
1654
1655           /* For recovery check instructions we calculate priority slightly
1656              different than that of normal instructions.  Instead of walking
1657              through INSN_FORW_DEPS (check) list, we walk through
1658              INSN_FORW_DEPS list of each instruction in the corresponding
1659              recovery block.  */
1660
1661           /* Selective scheduling does not define RECOVERY_BLOCK macro.  */
1662           rec = sel_sched_p () ? NULL : RECOVERY_BLOCK (insn);
1663           if (!rec || rec == EXIT_BLOCK_PTR_FOR_FN (cfun))
1664             {
1665               prev_first = PREV_INSN (insn);
1666               twin = insn;
1667             }
1668           else
1669             {
1670               prev_first = NEXT_INSN (BB_HEAD (rec));
1671               twin = PREV_INSN (BB_END (rec));
1672             }
1673
1674           do
1675             {
1676               sd_iterator_def sd_it;
1677               dep_t dep;
1678
1679               FOR_EACH_DEP (twin, SD_LIST_FORW, sd_it, dep)
1680                 {
1681                   rtx_insn *next;
1682                   int next_priority;
1683
1684                   next = DEP_CON (dep);
1685
1686                   if (BLOCK_FOR_INSN (next) != rec)
1687                     {
1688                       int cost;
1689
1690                       if (!contributes_to_priority_p (dep))
1691                         continue;
1692
1693                       if (twin == insn)
1694                         cost = dep_cost (dep);
1695                       else
1696                         {
1697                           struct _dep _dep1, *dep1 = &_dep1;
1698
1699                           init_dep (dep1, insn, next, REG_DEP_ANTI);
1700
1701                           cost = dep_cost (dep1);
1702                         }
1703
1704                       next_priority = cost + priority (next);
1705
1706                       if (next_priority > this_priority)
1707                         this_priority = next_priority;
1708                     }
1709                 }
1710
1711               twin = PREV_INSN (twin);
1712             }
1713           while (twin != prev_first);
1714         }
1715
1716       if (this_priority < 0)
1717         {
1718           gcc_assert (this_priority == -1);
1719
1720           this_priority = insn_cost (insn);
1721         }
1722
1723       INSN_PRIORITY (insn) = this_priority;
1724       INSN_PRIORITY_STATUS (insn) = 1;
1725     }
1726
1727   return INSN_PRIORITY (insn);
1728 }
1729 \f
1730 /* Macros and functions for keeping the priority queue sorted, and
1731    dealing with queuing and dequeuing of instructions.  */
1732
1733 /* For each pressure class CL, set DEATH[CL] to the number of registers
1734    in that class that die in INSN.  */
1735
1736 static void
1737 calculate_reg_deaths (rtx_insn *insn, int *death)
1738 {
1739   int i;
1740   struct reg_use_data *use;
1741
1742   for (i = 0; i < ira_pressure_classes_num; i++)
1743     death[ira_pressure_classes[i]] = 0;
1744   for (use = INSN_REG_USE_LIST (insn); use != NULL; use = use->next_insn_use)
1745     if (dying_use_p (use))
1746       mark_regno_birth_or_death (0, death, use->regno, true);
1747 }
1748
1749 /* Setup info about the current register pressure impact of scheduling
1750    INSN at the current scheduling point.  */
1751 static void
1752 setup_insn_reg_pressure_info (rtx_insn *insn)
1753 {
1754   int i, change, before, after, hard_regno;
1755   int excess_cost_change;
1756   machine_mode mode;
1757   enum reg_class cl;
1758   struct reg_pressure_data *pressure_info;
1759   int *max_reg_pressure;
1760   static int death[N_REG_CLASSES];
1761
1762   gcc_checking_assert (!DEBUG_INSN_P (insn));
1763
1764   excess_cost_change = 0;
1765   calculate_reg_deaths (insn, death);
1766   pressure_info = INSN_REG_PRESSURE (insn);
1767   max_reg_pressure = INSN_MAX_REG_PRESSURE (insn);
1768   gcc_assert (pressure_info != NULL && max_reg_pressure != NULL);
1769   for (i = 0; i < ira_pressure_classes_num; i++)
1770     {
1771       cl = ira_pressure_classes[i];
1772       gcc_assert (curr_reg_pressure[cl] >= 0);
1773       change = (int) pressure_info[i].set_increase - death[cl];
1774       before = MAX (0, max_reg_pressure[i] - sched_class_regs_num[cl]);
1775       after = MAX (0, max_reg_pressure[i] + change
1776                    - sched_class_regs_num[cl]);
1777       hard_regno = ira_class_hard_regs[cl][0];
1778       gcc_assert (hard_regno >= 0);
1779       mode = reg_raw_mode[hard_regno];
1780       excess_cost_change += ((after - before)
1781                              * (ira_memory_move_cost[mode][cl][0]
1782                                 + ira_memory_move_cost[mode][cl][1]));
1783     }
1784   INSN_REG_PRESSURE_EXCESS_COST_CHANGE (insn) = excess_cost_change;
1785 }
1786 \f
1787 /* This is the first page of code related to SCHED_PRESSURE_MODEL.
1788    It tries to make the scheduler take register pressure into account
1789    without introducing too many unnecessary stalls.  It hooks into the
1790    main scheduling algorithm at several points:
1791
1792     - Before scheduling starts, model_start_schedule constructs a
1793       "model schedule" for the current block.  This model schedule is
1794       chosen solely to keep register pressure down.  It does not take the
1795       target's pipeline or the original instruction order into account,
1796       except as a tie-breaker.  It also doesn't work to a particular
1797       pressure limit.
1798
1799       This model schedule gives us an idea of what pressure can be
1800       achieved for the block and gives us an example of a schedule that
1801       keeps to that pressure.  It also makes the final schedule less
1802       dependent on the original instruction order.  This is important
1803       because the original order can either be "wide" (many values live
1804       at once, such as in user-scheduled code) or "narrow" (few values
1805       live at once, such as after loop unrolling, where several
1806       iterations are executed sequentially).
1807
1808       We do not apply this model schedule to the rtx stream.  We simply
1809       record it in model_schedule.  We also compute the maximum pressure,
1810       MP, that was seen during this schedule.
1811
1812     - Instructions are added to the ready queue even if they require
1813       a stall.  The length of the stall is instead computed as:
1814
1815          MAX (INSN_TICK (INSN) - clock_var, 0)
1816
1817       (= insn_delay).  This allows rank_for_schedule to choose between
1818       introducing a deliberate stall or increasing pressure.
1819
1820     - Before sorting the ready queue, model_set_excess_costs assigns
1821       a pressure-based cost to each ready instruction in the queue.
1822       This is the instruction's INSN_REG_PRESSURE_EXCESS_COST_CHANGE
1823       (ECC for short) and is effectively measured in cycles.
1824
1825     - rank_for_schedule ranks instructions based on:
1826
1827         ECC (insn) + insn_delay (insn)
1828
1829       then as:
1830
1831         insn_delay (insn)
1832
1833       So, for example, an instruction X1 with an ECC of 1 that can issue
1834       now will win over an instruction X0 with an ECC of zero that would
1835       introduce a stall of one cycle.  However, an instruction X2 with an
1836       ECC of 2 that can issue now will lose to both X0 and X1.
1837
1838     - When an instruction is scheduled, model_recompute updates the model
1839       schedule with the new pressures (some of which might now exceed the
1840       original maximum pressure MP).  model_update_limit_points then searches
1841       for the new point of maximum pressure, if not already known.  */
1842
1843 /* Used to separate high-verbosity debug information for SCHED_PRESSURE_MODEL
1844    from surrounding debug information.  */
1845 #define MODEL_BAR \
1846   ";;\t\t+------------------------------------------------------\n"
1847
1848 /* Information about the pressure on a particular register class at a
1849    particular point of the model schedule.  */
1850 struct model_pressure_data {
1851   /* The pressure at this point of the model schedule, or -1 if the
1852      point is associated with an instruction that has already been
1853      scheduled.  */
1854   int ref_pressure;
1855
1856   /* The maximum pressure during or after this point of the model schedule.  */
1857   int max_pressure;
1858 };
1859
1860 /* Per-instruction information that is used while building the model
1861    schedule.  Here, "schedule" refers to the model schedule rather
1862    than the main schedule.  */
1863 struct model_insn_info {
1864   /* The instruction itself.  */
1865   rtx_insn *insn;
1866
1867   /* If this instruction is in model_worklist, these fields link to the
1868      previous (higher-priority) and next (lower-priority) instructions
1869      in the list.  */
1870   struct model_insn_info *prev;
1871   struct model_insn_info *next;
1872
1873   /* While constructing the schedule, QUEUE_INDEX describes whether an
1874      instruction has already been added to the schedule (QUEUE_SCHEDULED),
1875      is in model_worklist (QUEUE_READY), or neither (QUEUE_NOWHERE).
1876      old_queue records the value that QUEUE_INDEX had before scheduling
1877      started, so that we can restore it once the schedule is complete.  */
1878   int old_queue;
1879
1880   /* The relative importance of an unscheduled instruction.  Higher
1881      values indicate greater importance.  */
1882   unsigned int model_priority;
1883
1884   /* The length of the longest path of satisfied true dependencies
1885      that leads to this instruction.  */
1886   unsigned int depth;
1887
1888   /* The length of the longest path of dependencies of any kind
1889      that leads from this instruction.  */
1890   unsigned int alap;
1891
1892   /* The number of predecessor nodes that must still be scheduled.  */
1893   int unscheduled_preds;
1894 };
1895
1896 /* Information about the pressure limit for a particular register class.
1897    This structure is used when applying a model schedule to the main
1898    schedule.  */
1899 struct model_pressure_limit {
1900   /* The maximum register pressure seen in the original model schedule.  */
1901   int orig_pressure;
1902
1903   /* The maximum register pressure seen in the current model schedule
1904      (which excludes instructions that have already been scheduled).  */
1905   int pressure;
1906
1907   /* The point of the current model schedule at which PRESSURE is first
1908      reached.  It is set to -1 if the value needs to be recomputed.  */
1909   int point;
1910 };
1911
1912 /* Describes a particular way of measuring register pressure.  */
1913 struct model_pressure_group {
1914   /* Index PCI describes the maximum pressure on ira_pressure_classes[PCI].  */
1915   struct model_pressure_limit limits[N_REG_CLASSES];
1916
1917   /* Index (POINT * ira_num_pressure_classes + PCI) describes the pressure
1918      on register class ira_pressure_classes[PCI] at point POINT of the
1919      current model schedule.  A POINT of model_num_insns describes the
1920      pressure at the end of the schedule.  */
1921   struct model_pressure_data *model;
1922 };
1923
1924 /* Index POINT gives the instruction at point POINT of the model schedule.
1925    This array doesn't change during main scheduling.  */
1926 static vec<rtx_insn *> model_schedule;
1927
1928 /* The list of instructions in the model worklist, sorted in order of
1929    decreasing priority.  */
1930 static struct model_insn_info *model_worklist;
1931
1932 /* Index I describes the instruction with INSN_LUID I.  */
1933 static struct model_insn_info *model_insns;
1934
1935 /* The number of instructions in the model schedule.  */
1936 static int model_num_insns;
1937
1938 /* The index of the first instruction in model_schedule that hasn't yet been
1939    added to the main schedule, or model_num_insns if all of them have.  */
1940 static int model_curr_point;
1941
1942 /* Describes the pressure before each instruction in the model schedule.  */
1943 static struct model_pressure_group model_before_pressure;
1944
1945 /* The first unused model_priority value (as used in model_insn_info).  */
1946 static unsigned int model_next_priority;
1947
1948
1949 /* The model_pressure_data for ira_pressure_classes[PCI] in GROUP
1950    at point POINT of the model schedule.  */
1951 #define MODEL_PRESSURE_DATA(GROUP, POINT, PCI) \
1952   (&(GROUP)->model[(POINT) * ira_pressure_classes_num + (PCI)])
1953
1954 /* The maximum pressure on ira_pressure_classes[PCI] in GROUP at or
1955    after point POINT of the model schedule.  */
1956 #define MODEL_MAX_PRESSURE(GROUP, POINT, PCI) \
1957   (MODEL_PRESSURE_DATA (GROUP, POINT, PCI)->max_pressure)
1958
1959 /* The pressure on ira_pressure_classes[PCI] in GROUP at point POINT
1960    of the model schedule.  */
1961 #define MODEL_REF_PRESSURE(GROUP, POINT, PCI) \
1962   (MODEL_PRESSURE_DATA (GROUP, POINT, PCI)->ref_pressure)
1963
1964 /* Information about INSN that is used when creating the model schedule.  */
1965 #define MODEL_INSN_INFO(INSN) \
1966   (&model_insns[INSN_LUID (INSN)])
1967
1968 /* The instruction at point POINT of the model schedule.  */
1969 #define MODEL_INSN(POINT) \
1970   (model_schedule[POINT])
1971
1972
1973 /* Return INSN's index in the model schedule, or model_num_insns if it
1974    doesn't belong to that schedule.  */
1975
1976 static int
1977 model_index (rtx_insn *insn)
1978 {
1979   if (INSN_MODEL_INDEX (insn) == 0)
1980     return model_num_insns;
1981   return INSN_MODEL_INDEX (insn) - 1;
1982 }
1983
1984 /* Make sure that GROUP->limits is up-to-date for the current point
1985    of the model schedule.  */
1986
1987 static void
1988 model_update_limit_points_in_group (struct model_pressure_group *group)
1989 {
1990   int pci, max_pressure, point;
1991
1992   for (pci = 0; pci < ira_pressure_classes_num; pci++)
1993     {
1994       /* We may have passed the final point at which the pressure in
1995          group->limits[pci].pressure was reached.  Update the limit if so.  */
1996       max_pressure = MODEL_MAX_PRESSURE (group, model_curr_point, pci);
1997       group->limits[pci].pressure = max_pressure;
1998
1999       /* Find the point at which MAX_PRESSURE is first reached.  We need
2000          to search in three cases:
2001
2002          - We've already moved past the previous pressure point.
2003            In this case we search forward from model_curr_point.
2004
2005          - We scheduled the previous point of maximum pressure ahead of
2006            its position in the model schedule, but doing so didn't bring
2007            the pressure point earlier.  In this case we search forward
2008            from that previous pressure point.
2009
2010          - Scheduling an instruction early caused the maximum pressure
2011            to decrease.  In this case we will have set the pressure
2012            point to -1, and we search forward from model_curr_point.  */
2013       point = MAX (group->limits[pci].point, model_curr_point);
2014       while (point < model_num_insns
2015              && MODEL_REF_PRESSURE (group, point, pci) < max_pressure)
2016         point++;
2017       group->limits[pci].point = point;
2018
2019       gcc_assert (MODEL_REF_PRESSURE (group, point, pci) == max_pressure);
2020       gcc_assert (MODEL_MAX_PRESSURE (group, point, pci) == max_pressure);
2021     }
2022 }
2023
2024 /* Make sure that all register-pressure limits are up-to-date for the
2025    current position in the model schedule.  */
2026
2027 static void
2028 model_update_limit_points (void)
2029 {
2030   model_update_limit_points_in_group (&model_before_pressure);
2031 }
2032
2033 /* Return the model_index of the last unscheduled use in chain USE
2034    outside of USE's instruction.  Return -1 if there are no other uses,
2035    or model_num_insns if the register is live at the end of the block.  */
2036
2037 static int
2038 model_last_use_except (struct reg_use_data *use)
2039 {
2040   struct reg_use_data *next;
2041   int last, index;
2042
2043   last = -1;
2044   for (next = use->next_regno_use; next != use; next = next->next_regno_use)
2045     if (NONDEBUG_INSN_P (next->insn)
2046         && QUEUE_INDEX (next->insn) != QUEUE_SCHEDULED)
2047       {
2048         index = model_index (next->insn);
2049         if (index == model_num_insns)
2050           return model_num_insns;
2051         if (last < index)
2052           last = index;
2053       }
2054   return last;
2055 }
2056
2057 /* An instruction with model_index POINT has just been scheduled, and it
2058    adds DELTA to the pressure on ira_pressure_classes[PCI] after POINT - 1.
2059    Update MODEL_REF_PRESSURE (GROUP, POINT, PCI) and
2060    MODEL_MAX_PRESSURE (GROUP, POINT, PCI) accordingly.  */
2061
2062 static void
2063 model_start_update_pressure (struct model_pressure_group *group,
2064                              int point, int pci, int delta)
2065 {
2066   int next_max_pressure;
2067
2068   if (point == model_num_insns)
2069     {
2070       /* The instruction wasn't part of the model schedule; it was moved
2071          from a different block.  Update the pressure for the end of
2072          the model schedule.  */
2073       MODEL_REF_PRESSURE (group, point, pci) += delta;
2074       MODEL_MAX_PRESSURE (group, point, pci) += delta;
2075     }
2076   else
2077     {
2078       /* Record that this instruction has been scheduled.  Nothing now
2079          changes between POINT and POINT + 1, so get the maximum pressure
2080          from the latter.  If the maximum pressure decreases, the new
2081          pressure point may be before POINT.  */
2082       MODEL_REF_PRESSURE (group, point, pci) = -1;
2083       next_max_pressure = MODEL_MAX_PRESSURE (group, point + 1, pci);
2084       if (MODEL_MAX_PRESSURE (group, point, pci) > next_max_pressure)
2085         {
2086           MODEL_MAX_PRESSURE (group, point, pci) = next_max_pressure;
2087           if (group->limits[pci].point == point)
2088             group->limits[pci].point = -1;
2089         }
2090     }
2091 }
2092
2093 /* Record that scheduling a later instruction has changed the pressure
2094    at point POINT of the model schedule by DELTA (which might be 0).
2095    Update GROUP accordingly.  Return nonzero if these changes might
2096    trigger changes to previous points as well.  */
2097
2098 static int
2099 model_update_pressure (struct model_pressure_group *group,
2100                        int point, int pci, int delta)
2101 {
2102   int ref_pressure, max_pressure, next_max_pressure;
2103
2104   /* If POINT hasn't yet been scheduled, update its pressure.  */
2105   ref_pressure = MODEL_REF_PRESSURE (group, point, pci);
2106   if (ref_pressure >= 0 && delta != 0)
2107     {
2108       ref_pressure += delta;
2109       MODEL_REF_PRESSURE (group, point, pci) = ref_pressure;
2110
2111       /* Check whether the maximum pressure in the overall schedule
2112          has increased.  (This means that the MODEL_MAX_PRESSURE of
2113          every point <= POINT will need to increase too; see below.)  */
2114       if (group->limits[pci].pressure < ref_pressure)
2115         group->limits[pci].pressure = ref_pressure;
2116
2117       /* If we are at maximum pressure, and the maximum pressure
2118          point was previously unknown or later than POINT,
2119          bring it forward.  */
2120       if (group->limits[pci].pressure == ref_pressure
2121           && !IN_RANGE (group->limits[pci].point, 0, point))
2122         group->limits[pci].point = point;
2123
2124       /* If POINT used to be the point of maximum pressure, but isn't
2125          any longer, we need to recalculate it using a forward walk.  */
2126       if (group->limits[pci].pressure > ref_pressure
2127           && group->limits[pci].point == point)
2128         group->limits[pci].point = -1;
2129     }
2130
2131   /* Update the maximum pressure at POINT.  Changes here might also
2132      affect the maximum pressure at POINT - 1.  */
2133   next_max_pressure = MODEL_MAX_PRESSURE (group, point + 1, pci);
2134   max_pressure = MAX (ref_pressure, next_max_pressure);
2135   if (MODEL_MAX_PRESSURE (group, point, pci) != max_pressure)
2136     {
2137       MODEL_MAX_PRESSURE (group, point, pci) = max_pressure;
2138       return 1;
2139     }
2140   return 0;
2141 }
2142
2143 /* INSN has just been scheduled.  Update the model schedule accordingly.  */
2144
2145 static void
2146 model_recompute (rtx_insn *insn)
2147 {
2148   struct {
2149     int last_use;
2150     int regno;
2151   } uses[FIRST_PSEUDO_REGISTER + MAX_RECOG_OPERANDS];
2152   struct reg_use_data *use;
2153   struct reg_pressure_data *reg_pressure;
2154   int delta[N_REG_CLASSES];
2155   int pci, point, mix, new_last, cl, ref_pressure, queue;
2156   unsigned int i, num_uses, num_pending_births;
2157   bool print_p;
2158
2159   /* The destinations of INSN were previously live from POINT onwards, but are
2160      now live from model_curr_point onwards.  Set up DELTA accordingly.  */
2161   point = model_index (insn);
2162   reg_pressure = INSN_REG_PRESSURE (insn);
2163   for (pci = 0; pci < ira_pressure_classes_num; pci++)
2164     {
2165       cl = ira_pressure_classes[pci];
2166       delta[cl] = reg_pressure[pci].set_increase;
2167     }
2168
2169   /* Record which registers previously died at POINT, but which now die
2170      before POINT.  Adjust DELTA so that it represents the effect of
2171      this change after POINT - 1.  Set NUM_PENDING_BIRTHS to the number of
2172      registers that will be born in the range [model_curr_point, POINT).  */
2173   num_uses = 0;
2174   num_pending_births = 0;
2175   for (use = INSN_REG_USE_LIST (insn); use != NULL; use = use->next_insn_use)
2176     {
2177       new_last = model_last_use_except (use);
2178       if (new_last < point)
2179         {
2180           gcc_assert (num_uses < ARRAY_SIZE (uses));
2181           uses[num_uses].last_use = new_last;
2182           uses[num_uses].regno = use->regno;
2183           /* This register is no longer live after POINT - 1.  */
2184           mark_regno_birth_or_death (NULL, delta, use->regno, false);
2185           num_uses++;
2186           if (new_last >= 0)
2187             num_pending_births++;
2188         }
2189     }
2190
2191   /* Update the MODEL_REF_PRESSURE and MODEL_MAX_PRESSURE for POINT.
2192      Also set each group pressure limit for POINT.  */
2193   for (pci = 0; pci < ira_pressure_classes_num; pci++)
2194     {
2195       cl = ira_pressure_classes[pci];
2196       model_start_update_pressure (&model_before_pressure,
2197                                    point, pci, delta[cl]);
2198     }
2199
2200   /* Walk the model schedule backwards, starting immediately before POINT.  */
2201   print_p = false;
2202   if (point != model_curr_point)
2203     do
2204       {
2205         point--;
2206         insn = MODEL_INSN (point);
2207         queue = QUEUE_INDEX (insn);
2208
2209         if (queue != QUEUE_SCHEDULED)
2210           {
2211             /* DELTA describes the effect of the move on the register pressure
2212                after POINT.  Make it describe the effect on the pressure
2213                before POINT.  */
2214             i = 0;
2215             while (i < num_uses)
2216               {
2217                 if (uses[i].last_use == point)
2218                   {
2219                     /* This register is now live again.  */
2220                     mark_regno_birth_or_death (NULL, delta,
2221                                                uses[i].regno, true);
2222
2223                     /* Remove this use from the array.  */
2224                     uses[i] = uses[num_uses - 1];
2225                     num_uses--;
2226                     num_pending_births--;
2227                   }
2228                 else
2229                   i++;
2230               }
2231
2232             if (sched_verbose >= 5)
2233               {
2234                 if (!print_p)
2235                   {
2236                     fprintf (sched_dump, MODEL_BAR);
2237                     fprintf (sched_dump, ";;\t\t| New pressure for model"
2238                              " schedule\n");
2239                     fprintf (sched_dump, MODEL_BAR);
2240                     print_p = true;
2241                   }
2242
2243                 fprintf (sched_dump, ";;\t\t| %3d %4d %-30s ",
2244                          point, INSN_UID (insn),
2245                          str_pattern_slim (PATTERN (insn)));
2246                 for (pci = 0; pci < ira_pressure_classes_num; pci++)
2247                   {
2248                     cl = ira_pressure_classes[pci];
2249                     ref_pressure = MODEL_REF_PRESSURE (&model_before_pressure,
2250                                                        point, pci);
2251                     fprintf (sched_dump, " %s:[%d->%d]",
2252                              reg_class_names[ira_pressure_classes[pci]],
2253                              ref_pressure, ref_pressure + delta[cl]);
2254                   }
2255                 fprintf (sched_dump, "\n");
2256               }
2257           }
2258
2259         /* Adjust the pressure at POINT.  Set MIX to nonzero if POINT - 1
2260            might have changed as well.  */
2261         mix = num_pending_births;
2262         for (pci = 0; pci < ira_pressure_classes_num; pci++)
2263           {
2264             cl = ira_pressure_classes[pci];
2265             mix |= delta[cl];
2266             mix |= model_update_pressure (&model_before_pressure,
2267                                           point, pci, delta[cl]);
2268           }
2269       }
2270     while (mix && point > model_curr_point);
2271
2272   if (print_p)
2273     fprintf (sched_dump, MODEL_BAR);
2274 }
2275
2276 /* After DEP, which was cancelled, has been resolved for insn NEXT,
2277    check whether the insn's pattern needs restoring.  */
2278 static bool
2279 must_restore_pattern_p (rtx_insn *next, dep_t dep)
2280 {
2281   if (QUEUE_INDEX (next) == QUEUE_SCHEDULED)
2282     return false;
2283
2284   if (DEP_TYPE (dep) == REG_DEP_CONTROL)
2285     {
2286       gcc_assert (ORIG_PAT (next) != NULL_RTX);
2287       gcc_assert (next == DEP_CON (dep));
2288     }
2289   else
2290     {
2291       struct dep_replacement *desc = DEP_REPLACE (dep);
2292       if (desc->insn != next)
2293         {
2294           gcc_assert (*desc->loc == desc->orig);
2295           return false;
2296         }
2297     }
2298   return true;
2299 }
2300 \f
2301 /* model_spill_cost (CL, P, P') returns the cost of increasing the
2302    pressure on CL from P to P'.  We use this to calculate a "base ECC",
2303    baseECC (CL, X), for each pressure class CL and each instruction X.
2304    Supposing X changes the pressure on CL from P to P', and that the
2305    maximum pressure on CL in the current model schedule is MP', then:
2306
2307    * if X occurs before or at the next point of maximum pressure in
2308      the model schedule and P' > MP', then:
2309
2310        baseECC (CL, X) = model_spill_cost (CL, MP, P')
2311
2312      The idea is that the pressure after scheduling a fixed set of
2313      instructions -- in this case, the set up to and including the
2314      next maximum pressure point -- is going to be the same regardless
2315      of the order; we simply want to keep the intermediate pressure
2316      under control.  Thus X has a cost of zero unless scheduling it
2317      now would exceed MP'.
2318
2319      If all increases in the set are by the same amount, no zero-cost
2320      instruction will ever cause the pressure to exceed MP'.  However,
2321      if X is instead moved past an instruction X' with pressure in the
2322      range (MP' - (P' - P), MP'), the pressure at X' will increase
2323      beyond MP'.  Since baseECC is very much a heuristic anyway,
2324      it doesn't seem worth the overhead of tracking cases like these.
2325
2326      The cost of exceeding MP' is always based on the original maximum
2327      pressure MP.  This is so that going 2 registers over the original
2328      limit has the same cost regardless of whether it comes from two
2329      separate +1 deltas or from a single +2 delta.
2330
2331    * if X occurs after the next point of maximum pressure in the model
2332      schedule and P' > P, then:
2333
2334        baseECC (CL, X) = model_spill_cost (CL, MP, MP' + (P' - P))
2335
2336      That is, if we move X forward across a point of maximum pressure,
2337      and if X increases the pressure by P' - P, then we conservatively
2338      assume that scheduling X next would increase the maximum pressure
2339      by P' - P.  Again, the cost of doing this is based on the original
2340      maximum pressure MP, for the same reason as above.
2341
2342    * if P' < P, P > MP, and X occurs at or after the next point of
2343      maximum pressure, then:
2344
2345        baseECC (CL, X) = -model_spill_cost (CL, MAX (MP, P'), P)
2346
2347      That is, if we have already exceeded the original maximum pressure MP,
2348      and if X might reduce the maximum pressure again -- or at least push
2349      it further back, and thus allow more scheduling freedom -- it is given
2350      a negative cost to reflect the improvement.
2351
2352    * otherwise,
2353
2354        baseECC (CL, X) = 0
2355
2356      In this case, X is not expected to affect the maximum pressure MP',
2357      so it has zero cost.
2358
2359    We then create a combined value baseECC (X) that is the sum of
2360    baseECC (CL, X) for each pressure class CL.
2361
2362    baseECC (X) could itself be used as the ECC value described above.
2363    However, this is often too conservative, in the sense that it
2364    tends to make high-priority instructions that increase pressure
2365    wait too long in cases where introducing a spill would be better.
2366    For this reason the final ECC is a priority-adjusted form of
2367    baseECC (X).  Specifically, we calculate:
2368
2369      P (X) = INSN_PRIORITY (X) - insn_delay (X) - baseECC (X)
2370      baseP = MAX { P (X) | baseECC (X) <= 0 }
2371
2372    Then:
2373
2374      ECC (X) = MAX (MIN (baseP - P (X), baseECC (X)), 0)
2375
2376    Thus an instruction's effect on pressure is ignored if it has a high
2377    enough priority relative to the ones that don't increase pressure.
2378    Negative values of baseECC (X) do not increase the priority of X
2379    itself, but they do make it harder for other instructions to
2380    increase the pressure further.
2381
2382    This pressure cost is deliberately timid.  The intention has been
2383    to choose a heuristic that rarely interferes with the normal list
2384    scheduler in cases where that scheduler would produce good code.
2385    We simply want to curb some of its worst excesses.  */
2386
2387 /* Return the cost of increasing the pressure in class CL from FROM to TO.
2388
2389    Here we use the very simplistic cost model that every register above
2390    sched_class_regs_num[CL] has a spill cost of 1.  We could use other
2391    measures instead, such as one based on MEMORY_MOVE_COST.  However:
2392
2393       (1) In order for an instruction to be scheduled, the higher cost
2394           would need to be justified in a single saving of that many stalls.
2395           This is overly pessimistic, because the benefit of spilling is
2396           often to avoid a sequence of several short stalls rather than
2397           a single long one.
2398
2399       (2) The cost is still arbitrary.  Because we are not allocating
2400           registers during scheduling, we have no way of knowing for
2401           sure how many memory accesses will be required by each spill,
2402           where the spills will be placed within the block, or even
2403           which block(s) will contain the spills.
2404
2405    So a higher cost than 1 is often too conservative in practice,
2406    forcing blocks to contain unnecessary stalls instead of spill code.
2407    The simple cost below seems to be the best compromise.  It reduces
2408    the interference with the normal list scheduler, which helps make
2409    it more suitable for a default-on option.  */
2410
2411 static int
2412 model_spill_cost (int cl, int from, int to)
2413 {
2414   from = MAX (from, sched_class_regs_num[cl]);
2415   return MAX (to, from) - from;
2416 }
2417
2418 /* Return baseECC (ira_pressure_classes[PCI], POINT), given that
2419    P = curr_reg_pressure[ira_pressure_classes[PCI]] and that
2420    P' = P + DELTA.  */
2421
2422 static int
2423 model_excess_group_cost (struct model_pressure_group *group,
2424                          int point, int pci, int delta)
2425 {
2426   int pressure, cl;
2427
2428   cl = ira_pressure_classes[pci];
2429   if (delta < 0 && point >= group->limits[pci].point)
2430     {
2431       pressure = MAX (group->limits[pci].orig_pressure,
2432                       curr_reg_pressure[cl] + delta);
2433       return -model_spill_cost (cl, pressure, curr_reg_pressure[cl]);
2434     }
2435
2436   if (delta > 0)
2437     {
2438       if (point > group->limits[pci].point)
2439         pressure = group->limits[pci].pressure + delta;
2440       else
2441         pressure = curr_reg_pressure[cl] + delta;
2442
2443       if (pressure > group->limits[pci].pressure)
2444         return model_spill_cost (cl, group->limits[pci].orig_pressure,
2445                                  pressure);
2446     }
2447
2448   return 0;
2449 }
2450
2451 /* Return baseECC (MODEL_INSN (INSN)).  Dump the costs to sched_dump
2452    if PRINT_P.  */
2453
2454 static int
2455 model_excess_cost (rtx_insn *insn, bool print_p)
2456 {
2457   int point, pci, cl, cost, this_cost, delta;
2458   struct reg_pressure_data *insn_reg_pressure;
2459   int insn_death[N_REG_CLASSES];
2460
2461   calculate_reg_deaths (insn, insn_death);
2462   point = model_index (insn);
2463   insn_reg_pressure = INSN_REG_PRESSURE (insn);
2464   cost = 0;
2465
2466   if (print_p)
2467     fprintf (sched_dump, ";;\t\t| %3d %4d | %4d %+3d |", point,
2468              INSN_UID (insn), INSN_PRIORITY (insn), insn_delay (insn));
2469
2470   /* Sum up the individual costs for each register class.  */
2471   for (pci = 0; pci < ira_pressure_classes_num; pci++)
2472     {
2473       cl = ira_pressure_classes[pci];
2474       delta = insn_reg_pressure[pci].set_increase - insn_death[cl];
2475       this_cost = model_excess_group_cost (&model_before_pressure,
2476                                            point, pci, delta);
2477       cost += this_cost;
2478       if (print_p)
2479         fprintf (sched_dump, " %s:[%d base cost %d]",
2480                  reg_class_names[cl], delta, this_cost);
2481     }
2482
2483   if (print_p)
2484     fprintf (sched_dump, "\n");
2485
2486   return cost;
2487 }
2488
2489 /* Dump the next points of maximum pressure for GROUP.  */
2490
2491 static void
2492 model_dump_pressure_points (struct model_pressure_group *group)
2493 {
2494   int pci, cl;
2495
2496   fprintf (sched_dump, ";;\t\t|  pressure points");
2497   for (pci = 0; pci < ira_pressure_classes_num; pci++)
2498     {
2499       cl = ira_pressure_classes[pci];
2500       fprintf (sched_dump, " %s:[%d->%d at ", reg_class_names[cl],
2501                curr_reg_pressure[cl], group->limits[pci].pressure);
2502       if (group->limits[pci].point < model_num_insns)
2503         fprintf (sched_dump, "%d:%d]", group->limits[pci].point,
2504                  INSN_UID (MODEL_INSN (group->limits[pci].point)));
2505       else
2506         fprintf (sched_dump, "end]");
2507     }
2508   fprintf (sched_dump, "\n");
2509 }
2510
2511 /* Set INSN_REG_PRESSURE_EXCESS_COST_CHANGE for INSNS[0...COUNT-1].  */
2512
2513 static void
2514 model_set_excess_costs (rtx_insn **insns, int count)
2515 {
2516   int i, cost, priority_base, priority;
2517   bool print_p;
2518
2519   /* Record the baseECC value for each instruction in the model schedule,
2520      except that negative costs are converted to zero ones now rather than
2521      later.  Do not assign a cost to debug instructions, since they must
2522      not change code-generation decisions.  Experiments suggest we also
2523      get better results by not assigning a cost to instructions from
2524      a different block.
2525
2526      Set PRIORITY_BASE to baseP in the block comment above.  This is the
2527      maximum priority of the "cheap" instructions, which should always
2528      include the next model instruction.  */
2529   priority_base = 0;
2530   print_p = false;
2531   for (i = 0; i < count; i++)
2532     if (INSN_MODEL_INDEX (insns[i]))
2533       {
2534         if (sched_verbose >= 6 && !print_p)
2535           {
2536             fprintf (sched_dump, MODEL_BAR);
2537             fprintf (sched_dump, ";;\t\t| Pressure costs for ready queue\n");
2538             model_dump_pressure_points (&model_before_pressure);
2539             fprintf (sched_dump, MODEL_BAR);
2540             print_p = true;
2541           }
2542         cost = model_excess_cost (insns[i], print_p);
2543         if (cost <= 0)
2544           {
2545             priority = INSN_PRIORITY (insns[i]) - insn_delay (insns[i]) - cost;
2546             priority_base = MAX (priority_base, priority);
2547             cost = 0;
2548           }
2549         INSN_REG_PRESSURE_EXCESS_COST_CHANGE (insns[i]) = cost;
2550       }
2551   if (print_p)
2552     fprintf (sched_dump, MODEL_BAR);
2553
2554   /* Use MAX (baseECC, 0) and baseP to calculcate ECC for each
2555      instruction.  */
2556   for (i = 0; i < count; i++)
2557     {
2558       cost = INSN_REG_PRESSURE_EXCESS_COST_CHANGE (insns[i]);
2559       priority = INSN_PRIORITY (insns[i]) - insn_delay (insns[i]);
2560       if (cost > 0 && priority > priority_base)
2561         {
2562           cost += priority_base - priority;
2563           INSN_REG_PRESSURE_EXCESS_COST_CHANGE (insns[i]) = MAX (cost, 0);
2564         }
2565     }
2566 }
2567 \f
2568
2569 /* Enum of rank_for_schedule heuristic decisions.  */
2570 enum rfs_decision {
2571   RFS_DEBUG, RFS_LIVE_RANGE_SHRINK1, RFS_LIVE_RANGE_SHRINK2,
2572   RFS_SCHED_GROUP, RFS_PRESSURE_DELAY, RFS_PRESSURE_TICK,
2573   RFS_FEEDS_BACKTRACK_INSN, RFS_PRIORITY, RFS_SPECULATION,
2574   RFS_SCHED_RANK, RFS_LAST_INSN, RFS_PRESSURE_INDEX,
2575   RFS_DEP_COUNT, RFS_TIE, RFS_FUSION, RFS_N };
2576
2577 /* Corresponding strings for print outs.  */
2578 static const char *rfs_str[RFS_N] = {
2579   "RFS_DEBUG", "RFS_LIVE_RANGE_SHRINK1", "RFS_LIVE_RANGE_SHRINK2",
2580   "RFS_SCHED_GROUP", "RFS_PRESSURE_DELAY", "RFS_PRESSURE_TICK",
2581   "RFS_FEEDS_BACKTRACK_INSN", "RFS_PRIORITY", "RFS_SPECULATION",
2582   "RFS_SCHED_RANK", "RFS_LAST_INSN", "RFS_PRESSURE_INDEX",
2583   "RFS_DEP_COUNT", "RFS_TIE", "RFS_FUSION" };
2584
2585 /* Statistical breakdown of rank_for_schedule decisions.  */
2586 typedef struct { unsigned stats[RFS_N]; } rank_for_schedule_stats_t;
2587 static rank_for_schedule_stats_t rank_for_schedule_stats;
2588
2589 /* Return the result of comparing insns TMP and TMP2 and update
2590    Rank_For_Schedule statistics.  */
2591 static int
2592 rfs_result (enum rfs_decision decision, int result, rtx tmp, rtx tmp2)
2593 {
2594   ++rank_for_schedule_stats.stats[decision];
2595   if (result < 0)
2596     INSN_LAST_RFS_WIN (tmp) = decision;
2597   else if (result > 0)
2598     INSN_LAST_RFS_WIN (tmp2) = decision;
2599   else
2600     gcc_unreachable ();
2601   return result;
2602 }
2603
2604 /* Sorting predicate to move DEBUG_INSNs to the top of ready list, while
2605    keeping normal insns in original order.  */
2606
2607 static int
2608 rank_for_schedule_debug (const void *x, const void *y)
2609 {
2610   rtx_insn *tmp = *(rtx_insn * const *) y;
2611   rtx_insn *tmp2 = *(rtx_insn * const *) x;
2612
2613   /* Schedule debug insns as early as possible.  */
2614   if (DEBUG_INSN_P (tmp) && !DEBUG_INSN_P (tmp2))
2615     return rfs_result (RFS_DEBUG, -1, tmp, tmp2);
2616   else if (!DEBUG_INSN_P (tmp) && DEBUG_INSN_P (tmp2))
2617     return rfs_result (RFS_DEBUG, 1, tmp, tmp2);
2618   else if (DEBUG_INSN_P (tmp) && DEBUG_INSN_P (tmp2))
2619     return rfs_result (RFS_DEBUG, INSN_LUID (tmp) - INSN_LUID (tmp2),
2620                        tmp, tmp2);
2621   else
2622     return INSN_RFS_DEBUG_ORIG_ORDER (tmp2) - INSN_RFS_DEBUG_ORIG_ORDER (tmp);
2623 }
2624
2625 /* Returns a positive value if x is preferred; returns a negative value if
2626    y is preferred.  Should never return 0, since that will make the sort
2627    unstable.  */
2628
2629 static int
2630 rank_for_schedule (const void *x, const void *y)
2631 {
2632   rtx_insn *tmp = *(rtx_insn * const *) y;
2633   rtx_insn *tmp2 = *(rtx_insn * const *) x;
2634   int tmp_class, tmp2_class;
2635   int val, priority_val, info_val, diff;
2636
2637   if (live_range_shrinkage_p)
2638     {
2639       /* Don't use SCHED_PRESSURE_MODEL -- it results in much worse
2640          code.  */
2641       gcc_assert (sched_pressure == SCHED_PRESSURE_WEIGHTED);
2642       if ((INSN_REG_PRESSURE_EXCESS_COST_CHANGE (tmp) < 0
2643            || INSN_REG_PRESSURE_EXCESS_COST_CHANGE (tmp2) < 0)
2644           && (diff = (INSN_REG_PRESSURE_EXCESS_COST_CHANGE (tmp)
2645                       - INSN_REG_PRESSURE_EXCESS_COST_CHANGE (tmp2))) != 0)
2646         return rfs_result (RFS_LIVE_RANGE_SHRINK1, diff, tmp, tmp2);
2647       /* Sort by INSN_LUID (original insn order), so that we make the
2648          sort stable.  This minimizes instruction movement, thus
2649          minimizing sched's effect on debugging and cross-jumping.  */
2650       return rfs_result (RFS_LIVE_RANGE_SHRINK2,
2651                          INSN_LUID (tmp) - INSN_LUID (tmp2), tmp, tmp2);
2652     }
2653
2654   /* The insn in a schedule group should be issued the first.  */
2655   if (flag_sched_group_heuristic &&
2656       SCHED_GROUP_P (tmp) != SCHED_GROUP_P (tmp2))
2657     return rfs_result (RFS_SCHED_GROUP, SCHED_GROUP_P (tmp2) ? 1 : -1,
2658                        tmp, tmp2);
2659
2660   /* Make sure that priority of TMP and TMP2 are initialized.  */
2661   gcc_assert (INSN_PRIORITY_KNOWN (tmp) && INSN_PRIORITY_KNOWN (tmp2));
2662
2663   if (sched_fusion)
2664     {
2665       /* The instruction that has the same fusion priority as the last
2666          instruction is the instruction we picked next.  If that is not
2667          the case, we sort ready list firstly by fusion priority, then
2668          by priority, and at last by INSN_LUID.  */
2669       int a = INSN_FUSION_PRIORITY (tmp);
2670       int b = INSN_FUSION_PRIORITY (tmp2);
2671       int last = -1;
2672
2673       if (last_nondebug_scheduled_insn
2674           && !NOTE_P (last_nondebug_scheduled_insn)
2675           && BLOCK_FOR_INSN (tmp)
2676                == BLOCK_FOR_INSN (last_nondebug_scheduled_insn))
2677         last = INSN_FUSION_PRIORITY (last_nondebug_scheduled_insn);
2678
2679       if (a != last && b != last)
2680         {
2681           if (a == b)
2682             {
2683               a = INSN_PRIORITY (tmp);
2684               b = INSN_PRIORITY (tmp2);
2685             }
2686           if (a != b)
2687             return rfs_result (RFS_FUSION, b - a, tmp, tmp2);
2688           else
2689             return rfs_result (RFS_FUSION,
2690                                INSN_LUID (tmp) - INSN_LUID (tmp2), tmp, tmp2);
2691         }
2692       else if (a == b)
2693         {
2694           gcc_assert (last_nondebug_scheduled_insn
2695                       && !NOTE_P (last_nondebug_scheduled_insn));
2696           last = INSN_PRIORITY (last_nondebug_scheduled_insn);
2697
2698           a = abs (INSN_PRIORITY (tmp) - last);
2699           b = abs (INSN_PRIORITY (tmp2) - last);
2700           if (a != b)
2701             return rfs_result (RFS_FUSION, a - b, tmp, tmp2);
2702           else
2703             return rfs_result (RFS_FUSION,
2704                                INSN_LUID (tmp) - INSN_LUID (tmp2), tmp, tmp2);
2705         }
2706       else if (a == last)
2707         return rfs_result (RFS_FUSION, -1, tmp, tmp2);
2708       else
2709         return rfs_result (RFS_FUSION, 1, tmp, tmp2);
2710     }
2711
2712   if (sched_pressure != SCHED_PRESSURE_NONE)
2713     {
2714       /* Prefer insn whose scheduling results in the smallest register
2715          pressure excess.  */
2716       if ((diff = (INSN_REG_PRESSURE_EXCESS_COST_CHANGE (tmp)
2717                    + insn_delay (tmp)
2718                    - INSN_REG_PRESSURE_EXCESS_COST_CHANGE (tmp2)
2719                    - insn_delay (tmp2))))
2720         return rfs_result (RFS_PRESSURE_DELAY, diff, tmp, tmp2);
2721     }
2722
2723   if (sched_pressure != SCHED_PRESSURE_NONE
2724       && (INSN_TICK (tmp2) > clock_var || INSN_TICK (tmp) > clock_var)
2725       && INSN_TICK (tmp2) != INSN_TICK (tmp))
2726     {
2727       diff = INSN_TICK (tmp) - INSN_TICK (tmp2);
2728       return rfs_result (RFS_PRESSURE_TICK, diff, tmp, tmp2);
2729     }
2730
2731   /* If we are doing backtracking in this schedule, prefer insns that
2732      have forward dependencies with negative cost against an insn that
2733      was already scheduled.  */
2734   if (current_sched_info->flags & DO_BACKTRACKING)
2735     {
2736       priority_val = FEEDS_BACKTRACK_INSN (tmp2) - FEEDS_BACKTRACK_INSN (tmp);
2737       if (priority_val)
2738         return rfs_result (RFS_FEEDS_BACKTRACK_INSN, priority_val, tmp, tmp2);
2739     }
2740
2741   /* Prefer insn with higher priority.  */
2742   priority_val = INSN_PRIORITY (tmp2) - INSN_PRIORITY (tmp);
2743
2744   if (flag_sched_critical_path_heuristic && priority_val)
2745     return rfs_result (RFS_PRIORITY, priority_val, tmp, tmp2);
2746
2747   if (PARAM_VALUE (PARAM_SCHED_AUTOPREF_QUEUE_DEPTH) >= 0)
2748     {
2749       int autopref = autopref_rank_for_schedule (tmp, tmp2);
2750       if (autopref != 0)
2751         return autopref;
2752     }
2753
2754   /* Prefer speculative insn with greater dependencies weakness.  */
2755   if (flag_sched_spec_insn_heuristic && spec_info)
2756     {
2757       ds_t ds1, ds2;
2758       dw_t dw1, dw2;
2759       int dw;
2760
2761       ds1 = TODO_SPEC (tmp) & SPECULATIVE;
2762       if (ds1)
2763         dw1 = ds_weak (ds1);
2764       else
2765         dw1 = NO_DEP_WEAK;
2766
2767       ds2 = TODO_SPEC (tmp2) & SPECULATIVE;
2768       if (ds2)
2769         dw2 = ds_weak (ds2);
2770       else
2771         dw2 = NO_DEP_WEAK;
2772
2773       dw = dw2 - dw1;
2774       if (dw > (NO_DEP_WEAK / 8) || dw < -(NO_DEP_WEAK / 8))
2775         return rfs_result (RFS_SPECULATION, dw, tmp, tmp2);
2776     }
2777
2778   info_val = (*current_sched_info->rank) (tmp, tmp2);
2779   if (flag_sched_rank_heuristic && info_val)
2780     return rfs_result (RFS_SCHED_RANK, info_val, tmp, tmp2);
2781
2782   /* Compare insns based on their relation to the last scheduled
2783      non-debug insn.  */
2784   if (flag_sched_last_insn_heuristic && last_nondebug_scheduled_insn)
2785     {
2786       dep_t dep1;
2787       dep_t dep2;
2788       rtx last = last_nondebug_scheduled_insn;
2789
2790       /* Classify the instructions into three classes:
2791          1) Data dependent on last schedule insn.
2792          2) Anti/Output dependent on last scheduled insn.
2793          3) Independent of last scheduled insn, or has latency of one.
2794          Choose the insn from the highest numbered class if different.  */
2795       dep1 = sd_find_dep_between (last, tmp, true);
2796
2797       if (dep1 == NULL || dep_cost (dep1) == 1)
2798         tmp_class = 3;
2799       else if (/* Data dependence.  */
2800                DEP_TYPE (dep1) == REG_DEP_TRUE)
2801         tmp_class = 1;
2802       else
2803         tmp_class = 2;
2804
2805       dep2 = sd_find_dep_between (last, tmp2, true);
2806
2807       if (dep2 == NULL || dep_cost (dep2)  == 1)
2808         tmp2_class = 3;
2809       else if (/* Data dependence.  */
2810                DEP_TYPE (dep2) == REG_DEP_TRUE)
2811         tmp2_class = 1;
2812       else
2813         tmp2_class = 2;
2814
2815       if ((val = tmp2_class - tmp_class))
2816         return rfs_result (RFS_LAST_INSN, val, tmp, tmp2);
2817     }
2818
2819   /* Prefer instructions that occur earlier in the model schedule.  */
2820   if (sched_pressure == SCHED_PRESSURE_MODEL
2821       && INSN_BB (tmp) == target_bb && INSN_BB (tmp2) == target_bb)
2822     {
2823       diff = model_index (tmp) - model_index (tmp2);
2824       gcc_assert (diff != 0);
2825       return rfs_result (RFS_PRESSURE_INDEX, diff, tmp, tmp2);
2826     }
2827
2828   /* Prefer the insn which has more later insns that depend on it.
2829      This gives the scheduler more freedom when scheduling later
2830      instructions at the expense of added register pressure.  */
2831
2832   val = (dep_list_size (tmp2, SD_LIST_FORW)
2833          - dep_list_size (tmp, SD_LIST_FORW));
2834
2835   if (flag_sched_dep_count_heuristic && val != 0)
2836     return rfs_result (RFS_DEP_COUNT, val, tmp, tmp2);
2837
2838   /* If insns are equally good, sort by INSN_LUID (original insn order),
2839      so that we make the sort stable.  This minimizes instruction movement,
2840      thus minimizing sched's effect on debugging and cross-jumping.  */
2841   return rfs_result (RFS_TIE, INSN_LUID (tmp) - INSN_LUID (tmp2), tmp, tmp2);
2842 }
2843
2844 /* Resort the array A in which only element at index N may be out of order.  */
2845
2846 HAIFA_INLINE static void
2847 swap_sort (rtx_insn **a, int n)
2848 {
2849   rtx_insn *insn = a[n - 1];
2850   int i = n - 2;
2851
2852   while (i >= 0 && rank_for_schedule (a + i, &insn) >= 0)
2853     {
2854       a[i + 1] = a[i];
2855       i -= 1;
2856     }
2857   a[i + 1] = insn;
2858 }
2859
2860 /* Add INSN to the insn queue so that it can be executed at least
2861    N_CYCLES after the currently executing insn.  Preserve insns
2862    chain for debugging purposes.  REASON will be printed in debugging
2863    output.  */
2864
2865 HAIFA_INLINE static void
2866 queue_insn (rtx_insn *insn, int n_cycles, const char *reason)
2867 {
2868   int next_q = NEXT_Q_AFTER (q_ptr, n_cycles);
2869   rtx_insn_list *link = alloc_INSN_LIST (insn, insn_queue[next_q]);
2870   int new_tick;
2871
2872   gcc_assert (n_cycles <= max_insn_queue_index);
2873   gcc_assert (!DEBUG_INSN_P (insn));
2874
2875   insn_queue[next_q] = link;
2876   q_size += 1;
2877
2878   if (sched_verbose >= 2)
2879     {
2880       fprintf (sched_dump, ";;\t\tReady-->Q: insn %s: ",
2881                (*current_sched_info->print_insn) (insn, 0));
2882
2883       fprintf (sched_dump, "queued for %d cycles (%s).\n", n_cycles, reason);
2884     }
2885
2886   QUEUE_INDEX (insn) = next_q;
2887
2888   if (current_sched_info->flags & DO_BACKTRACKING)
2889     {
2890       new_tick = clock_var + n_cycles;
2891       if (INSN_TICK (insn) == INVALID_TICK || INSN_TICK (insn) < new_tick)
2892         INSN_TICK (insn) = new_tick;
2893
2894       if (INSN_EXACT_TICK (insn) != INVALID_TICK
2895           && INSN_EXACT_TICK (insn) < clock_var + n_cycles)
2896         {
2897           must_backtrack = true;
2898           if (sched_verbose >= 2)
2899             fprintf (sched_dump, ";;\t\tcausing a backtrack.\n");
2900         }
2901     }
2902 }
2903
2904 /* Remove INSN from queue.  */
2905 static void
2906 queue_remove (rtx_insn *insn)
2907 {
2908   gcc_assert (QUEUE_INDEX (insn) >= 0);
2909   remove_free_INSN_LIST_elem (insn, &insn_queue[QUEUE_INDEX (insn)]);
2910   q_size--;
2911   QUEUE_INDEX (insn) = QUEUE_NOWHERE;
2912 }
2913
2914 /* Return a pointer to the bottom of the ready list, i.e. the insn
2915    with the lowest priority.  */
2916
2917 rtx_insn **
2918 ready_lastpos (struct ready_list *ready)
2919 {
2920   gcc_assert (ready->n_ready >= 1);
2921   return ready->vec + ready->first - ready->n_ready + 1;
2922 }
2923
2924 /* Add an element INSN to the ready list so that it ends up with the
2925    lowest/highest priority depending on FIRST_P.  */
2926
2927 HAIFA_INLINE static void
2928 ready_add (struct ready_list *ready, rtx_insn *insn, bool first_p)
2929 {
2930   if (!first_p)
2931     {
2932       if (ready->first == ready->n_ready)
2933         {
2934           memmove (ready->vec + ready->veclen - ready->n_ready,
2935                    ready_lastpos (ready),
2936                    ready->n_ready * sizeof (rtx));
2937           ready->first = ready->veclen - 1;
2938         }
2939       ready->vec[ready->first - ready->n_ready] = insn;
2940     }
2941   else
2942     {
2943       if (ready->first == ready->veclen - 1)
2944         {
2945           if (ready->n_ready)
2946             /* ready_lastpos() fails when called with (ready->n_ready == 0).  */
2947             memmove (ready->vec + ready->veclen - ready->n_ready - 1,
2948                      ready_lastpos (ready),
2949                      ready->n_ready * sizeof (rtx));
2950           ready->first = ready->veclen - 2;
2951         }
2952       ready->vec[++(ready->first)] = insn;
2953     }
2954
2955   ready->n_ready++;
2956   if (DEBUG_INSN_P (insn))
2957     ready->n_debug++;
2958
2959   gcc_assert (QUEUE_INDEX (insn) != QUEUE_READY);
2960   QUEUE_INDEX (insn) = QUEUE_READY;
2961
2962   if (INSN_EXACT_TICK (insn) != INVALID_TICK
2963       && INSN_EXACT_TICK (insn) < clock_var)
2964     {
2965       must_backtrack = true;
2966     }
2967 }
2968
2969 /* Remove the element with the highest priority from the ready list and
2970    return it.  */
2971
2972 HAIFA_INLINE static rtx_insn *
2973 ready_remove_first (struct ready_list *ready)
2974 {
2975   rtx_insn *t;
2976
2977   gcc_assert (ready->n_ready);
2978   t = ready->vec[ready->first--];
2979   ready->n_ready--;
2980   if (DEBUG_INSN_P (t))
2981     ready->n_debug--;
2982   /* If the queue becomes empty, reset it.  */
2983   if (ready->n_ready == 0)
2984     ready->first = ready->veclen - 1;
2985
2986   gcc_assert (QUEUE_INDEX (t) == QUEUE_READY);
2987   QUEUE_INDEX (t) = QUEUE_NOWHERE;
2988
2989   return t;
2990 }
2991
2992 /* The following code implements multi-pass scheduling for the first
2993    cycle.  In other words, we will try to choose ready insn which
2994    permits to start maximum number of insns on the same cycle.  */
2995
2996 /* Return a pointer to the element INDEX from the ready.  INDEX for
2997    insn with the highest priority is 0, and the lowest priority has
2998    N_READY - 1.  */
2999
3000 rtx_insn *
3001 ready_element (struct ready_list *ready, int index)
3002 {
3003   gcc_assert (ready->n_ready && index < ready->n_ready);
3004
3005   return ready->vec[ready->first - index];
3006 }
3007
3008 /* Remove the element INDEX from the ready list and return it.  INDEX
3009    for insn with the highest priority is 0, and the lowest priority
3010    has N_READY - 1.  */
3011
3012 HAIFA_INLINE static rtx_insn *
3013 ready_remove (struct ready_list *ready, int index)
3014 {
3015   rtx_insn *t;
3016   int i;
3017
3018   if (index == 0)
3019     return ready_remove_first (ready);
3020   gcc_assert (ready->n_ready && index < ready->n_ready);
3021   t = ready->vec[ready->first - index];
3022   ready->n_ready--;
3023   if (DEBUG_INSN_P (t))
3024     ready->n_debug--;
3025   for (i = index; i < ready->n_ready; i++)
3026     ready->vec[ready->first - i] = ready->vec[ready->first - i - 1];
3027   QUEUE_INDEX (t) = QUEUE_NOWHERE;
3028   return t;
3029 }
3030
3031 /* Remove INSN from the ready list.  */
3032 static void
3033 ready_remove_insn (rtx insn)
3034 {
3035   int i;
3036
3037   for (i = 0; i < readyp->n_ready; i++)
3038     if (ready_element (readyp, i) == insn)
3039       {
3040         ready_remove (readyp, i);
3041         return;
3042       }
3043   gcc_unreachable ();
3044 }
3045
3046 /* Calculate difference of two statistics set WAS and NOW.
3047    Result returned in WAS.  */
3048 static void
3049 rank_for_schedule_stats_diff (rank_for_schedule_stats_t *was,
3050                               const rank_for_schedule_stats_t *now)
3051 {
3052   for (int i = 0; i < RFS_N; ++i)
3053     was->stats[i] = now->stats[i] - was->stats[i];
3054 }
3055
3056 /* Print rank_for_schedule statistics.  */
3057 static void
3058 print_rank_for_schedule_stats (const char *prefix,
3059                                const rank_for_schedule_stats_t *stats,
3060                                struct ready_list *ready)
3061 {
3062   for (int i = 0; i < RFS_N; ++i)
3063     if (stats->stats[i])
3064       {
3065         fprintf (sched_dump, "%s%20s: %u", prefix, rfs_str[i], stats->stats[i]);
3066
3067         if (ready != NULL)
3068           /* Print out insns that won due to RFS_<I>.  */
3069           {
3070             rtx_insn **p = ready_lastpos (ready);
3071
3072             fprintf (sched_dump, ":");
3073             /* Start with 1 since least-priority insn didn't have any wins.  */
3074             for (int j = 1; j < ready->n_ready; ++j)
3075               if (INSN_LAST_RFS_WIN (p[j]) == i)
3076                 fprintf (sched_dump, " %s",
3077                          (*current_sched_info->print_insn) (p[j], 0));
3078           }
3079         fprintf (sched_dump, "\n");
3080       }
3081 }
3082
3083 /* Sort the ready list READY by ascending priority, using the SCHED_SORT
3084    macro.  */
3085
3086 void
3087 ready_sort (struct ready_list *ready)
3088 {
3089   int i;
3090   rtx_insn **first = ready_lastpos (ready);
3091   int n_ready_non_debug = ready->n_ready;
3092
3093   for (i = 0; i < ready->n_ready; ++i)
3094     {
3095       if (DEBUG_INSN_P (first[i]))
3096         --n_ready_non_debug;
3097       else
3098         {
3099           INSN_RFS_DEBUG_ORIG_ORDER (first[i]) = i;
3100
3101           if (sched_pressure == SCHED_PRESSURE_WEIGHTED)
3102             setup_insn_reg_pressure_info (first[i]);
3103         }
3104     }
3105
3106   if (sched_pressure == SCHED_PRESSURE_MODEL
3107       && model_curr_point < model_num_insns)
3108     model_set_excess_costs (first, ready->n_ready);
3109
3110   rank_for_schedule_stats_t stats1;
3111   if (sched_verbose >= 4)
3112     stats1 = rank_for_schedule_stats;
3113
3114   if (n_ready_non_debug < ready->n_ready)
3115     /* Separate DEBUG_INSNS from normal insns.  DEBUG_INSNs go to the end
3116        of array.  */
3117     qsort (first, ready->n_ready, sizeof (rtx), rank_for_schedule_debug);
3118   else
3119     {
3120       if (n_ready_non_debug == 2)
3121         swap_sort (first, n_ready_non_debug);
3122       else if (n_ready_non_debug > 2)
3123         qsort (first, n_ready_non_debug, sizeof (rtx), rank_for_schedule);
3124     }
3125
3126   if (sched_verbose >= 4)
3127     {
3128       rank_for_schedule_stats_diff (&stats1, &rank_for_schedule_stats);
3129       print_rank_for_schedule_stats (";;\t\t", &stats1, ready);
3130     }
3131 }
3132
3133 /* PREV is an insn that is ready to execute.  Adjust its priority if that
3134    will help shorten or lengthen register lifetimes as appropriate.  Also
3135    provide a hook for the target to tweak itself.  */
3136
3137 HAIFA_INLINE static void
3138 adjust_priority (rtx_insn *prev)
3139 {
3140   /* ??? There used to be code here to try and estimate how an insn
3141      affected register lifetimes, but it did it by looking at REG_DEAD
3142      notes, which we removed in schedule_region.  Nor did it try to
3143      take into account register pressure or anything useful like that.
3144
3145      Revisit when we have a machine model to work with and not before.  */
3146
3147   if (targetm.sched.adjust_priority)
3148     INSN_PRIORITY (prev) =
3149       targetm.sched.adjust_priority (prev, INSN_PRIORITY (prev));
3150 }
3151
3152 /* Advance DFA state STATE on one cycle.  */
3153 void
3154 advance_state (state_t state)
3155 {
3156   if (targetm.sched.dfa_pre_advance_cycle)
3157     targetm.sched.dfa_pre_advance_cycle ();
3158
3159   if (targetm.sched.dfa_pre_cycle_insn)
3160     state_transition (state,
3161                       targetm.sched.dfa_pre_cycle_insn ());
3162
3163   state_transition (state, NULL);
3164
3165   if (targetm.sched.dfa_post_cycle_insn)
3166     state_transition (state,
3167                       targetm.sched.dfa_post_cycle_insn ());
3168
3169   if (targetm.sched.dfa_post_advance_cycle)
3170     targetm.sched.dfa_post_advance_cycle ();
3171 }
3172
3173 /* Advance time on one cycle.  */
3174 HAIFA_INLINE static void
3175 advance_one_cycle (void)
3176 {
3177   advance_state (curr_state);
3178   if (sched_verbose >= 4)
3179     fprintf (sched_dump, ";;\tAdvance the current state.\n");
3180 }
3181
3182 /* Update register pressure after scheduling INSN.  */
3183 static void
3184 update_register_pressure (rtx_insn *insn)
3185 {
3186   struct reg_use_data *use;
3187   struct reg_set_data *set;
3188
3189   gcc_checking_assert (!DEBUG_INSN_P (insn));
3190
3191   for (use = INSN_REG_USE_LIST (insn); use != NULL; use = use->next_insn_use)
3192     if (dying_use_p (use))
3193       mark_regno_birth_or_death (curr_reg_live, curr_reg_pressure,
3194                                  use->regno, false);
3195   for (set = INSN_REG_SET_LIST (insn); set != NULL; set = set->next_insn_set)
3196     mark_regno_birth_or_death (curr_reg_live, curr_reg_pressure,
3197                                set->regno, true);
3198 }
3199
3200 /* Set up or update (if UPDATE_P) max register pressure (see its
3201    meaning in sched-int.h::_haifa_insn_data) for all current BB insns
3202    after insn AFTER.  */
3203 static void
3204 setup_insn_max_reg_pressure (rtx_insn *after, bool update_p)
3205 {
3206   int i, p;
3207   bool eq_p;
3208   rtx_insn *insn;
3209   static int max_reg_pressure[N_REG_CLASSES];
3210
3211   save_reg_pressure ();
3212   for (i = 0; i < ira_pressure_classes_num; i++)
3213     max_reg_pressure[ira_pressure_classes[i]]
3214       = curr_reg_pressure[ira_pressure_classes[i]];
3215   for (insn = NEXT_INSN (after);
3216        insn != NULL_RTX && ! BARRIER_P (insn)
3217          && BLOCK_FOR_INSN (insn) == BLOCK_FOR_INSN (after);
3218        insn = NEXT_INSN (insn))
3219     if (NONDEBUG_INSN_P (insn))
3220       {
3221         eq_p = true;
3222         for (i = 0; i < ira_pressure_classes_num; i++)
3223           {
3224             p = max_reg_pressure[ira_pressure_classes[i]];
3225             if (INSN_MAX_REG_PRESSURE (insn)[i] != p)
3226               {
3227                 eq_p = false;
3228                 INSN_MAX_REG_PRESSURE (insn)[i]
3229                   = max_reg_pressure[ira_pressure_classes[i]];
3230               }
3231           }
3232         if (update_p && eq_p)
3233           break;
3234         update_register_pressure (insn);
3235         for (i = 0; i < ira_pressure_classes_num; i++)
3236           if (max_reg_pressure[ira_pressure_classes[i]]
3237               < curr_reg_pressure[ira_pressure_classes[i]])
3238             max_reg_pressure[ira_pressure_classes[i]]
3239               = curr_reg_pressure[ira_pressure_classes[i]];
3240       }
3241   restore_reg_pressure ();
3242 }
3243
3244 /* Update the current register pressure after scheduling INSN.  Update
3245    also max register pressure for unscheduled insns of the current
3246    BB.  */
3247 static void
3248 update_reg_and_insn_max_reg_pressure (rtx_insn *insn)
3249 {
3250   int i;
3251   int before[N_REG_CLASSES];
3252
3253   for (i = 0; i < ira_pressure_classes_num; i++)
3254     before[i] = curr_reg_pressure[ira_pressure_classes[i]];
3255   update_register_pressure (insn);
3256   for (i = 0; i < ira_pressure_classes_num; i++)
3257     if (curr_reg_pressure[ira_pressure_classes[i]] != before[i])
3258       break;
3259   if (i < ira_pressure_classes_num)
3260     setup_insn_max_reg_pressure (insn, true);
3261 }
3262
3263 /* Set up register pressure at the beginning of basic block BB whose
3264    insns starting after insn AFTER.  Set up also max register pressure
3265    for all insns of the basic block.  */
3266 void
3267 sched_setup_bb_reg_pressure_info (basic_block bb, rtx_insn *after)
3268 {
3269   gcc_assert (sched_pressure == SCHED_PRESSURE_WEIGHTED);
3270   initiate_bb_reg_pressure_info (bb);
3271   setup_insn_max_reg_pressure (after, false);
3272 }
3273 \f
3274 /* If doing predication while scheduling, verify whether INSN, which
3275    has just been scheduled, clobbers the conditions of any
3276    instructions that must be predicated in order to break their
3277    dependencies.  If so, remove them from the queues so that they will
3278    only be scheduled once their control dependency is resolved.  */
3279
3280 static void
3281 check_clobbered_conditions (rtx insn)
3282 {
3283   HARD_REG_SET t;
3284   int i;
3285
3286   if ((current_sched_info->flags & DO_PREDICATION) == 0)
3287     return;
3288
3289   find_all_hard_reg_sets (insn, &t, true);
3290
3291  restart:
3292   for (i = 0; i < ready.n_ready; i++)
3293     {
3294       rtx_insn *x = ready_element (&ready, i);
3295       if (TODO_SPEC (x) == DEP_CONTROL && cond_clobbered_p (x, t))
3296         {
3297           ready_remove_insn (x);
3298           goto restart;
3299         }
3300     }
3301   for (i = 0; i <= max_insn_queue_index; i++)
3302     {
3303       rtx_insn_list *link;
3304       int q = NEXT_Q_AFTER (q_ptr, i);
3305
3306     restart_queue:
3307       for (link = insn_queue[q]; link; link = link->next ())
3308         {
3309           rtx_insn *x = link->insn ();
3310           if (TODO_SPEC (x) == DEP_CONTROL && cond_clobbered_p (x, t))
3311             {
3312               queue_remove (x);
3313               goto restart_queue;
3314             }
3315         }
3316     }
3317 }
3318 \f
3319 /* Return (in order):
3320
3321    - positive if INSN adversely affects the pressure on one
3322      register class
3323
3324    - negative if INSN reduces the pressure on one register class
3325
3326    - 0 if INSN doesn't affect the pressure on any register class.  */
3327
3328 static int
3329 model_classify_pressure (struct model_insn_info *insn)
3330 {
3331   struct reg_pressure_data *reg_pressure;
3332   int death[N_REG_CLASSES];
3333   int pci, cl, sum;
3334
3335   calculate_reg_deaths (insn->insn, death);
3336   reg_pressure = INSN_REG_PRESSURE (insn->insn);
3337   sum = 0;
3338   for (pci = 0; pci < ira_pressure_classes_num; pci++)
3339     {
3340       cl = ira_pressure_classes[pci];
3341       if (death[cl] < reg_pressure[pci].set_increase)
3342         return 1;
3343       sum += reg_pressure[pci].set_increase - death[cl];
3344     }
3345   return sum;
3346 }
3347
3348 /* Return true if INSN1 should come before INSN2 in the model schedule.  */
3349
3350 static int
3351 model_order_p (struct model_insn_info *insn1, struct model_insn_info *insn2)
3352 {
3353   unsigned int height1, height2;
3354   unsigned int priority1, priority2;
3355
3356   /* Prefer instructions with a higher model priority.  */
3357   if (insn1->model_priority != insn2->model_priority)
3358     return insn1->model_priority > insn2->model_priority;
3359
3360   /* Combine the length of the longest path of satisfied true dependencies
3361      that leads to each instruction (depth) with the length of the longest
3362      path of any dependencies that leads from the instruction (alap).
3363      Prefer instructions with the greatest combined length.  If the combined
3364      lengths are equal, prefer instructions with the greatest depth.
3365
3366      The idea is that, if we have a set S of "equal" instructions that each
3367      have ALAP value X, and we pick one such instruction I, any true-dependent
3368      successors of I that have ALAP value X - 1 should be preferred over S.
3369      This encourages the schedule to be "narrow" rather than "wide".
3370      However, if I is a low-priority instruction that we decided to
3371      schedule because of its model_classify_pressure, and if there
3372      is a set of higher-priority instructions T, the aforementioned
3373      successors of I should not have the edge over T.  */
3374   height1 = insn1->depth + insn1->alap;
3375   height2 = insn2->depth + insn2->alap;
3376   if (height1 != height2)
3377     return height1 > height2;
3378   if (insn1->depth != insn2->depth)
3379     return insn1->depth > insn2->depth;
3380
3381   /* We have no real preference between INSN1 an INSN2 as far as attempts
3382      to reduce pressure go.  Prefer instructions with higher priorities.  */
3383   priority1 = INSN_PRIORITY (insn1->insn);
3384   priority2 = INSN_PRIORITY (insn2->insn);
3385   if (priority1 != priority2)
3386     return priority1 > priority2;
3387
3388   /* Use the original rtl sequence as a tie-breaker.  */
3389   return insn1 < insn2;
3390 }
3391
3392 /* Add INSN to the model worklist immediately after PREV.  Add it to the
3393    beginning of the list if PREV is null.  */
3394
3395 static void
3396 model_add_to_worklist_at (struct model_insn_info *insn,
3397                           struct model_insn_info *prev)
3398 {
3399   gcc_assert (QUEUE_INDEX (insn->insn) == QUEUE_NOWHERE);
3400   QUEUE_INDEX (insn->insn) = QUEUE_READY;
3401
3402   insn->prev = prev;
3403   if (prev)
3404     {
3405       insn->next = prev->next;
3406       prev->next = insn;
3407     }
3408   else
3409     {
3410       insn->next = model_worklist;
3411       model_worklist = insn;
3412     }
3413   if (insn->next)
3414     insn->next->prev = insn;
3415 }
3416
3417 /* Remove INSN from the model worklist.  */
3418
3419 static void
3420 model_remove_from_worklist (struct model_insn_info *insn)
3421 {
3422   gcc_assert (QUEUE_INDEX (insn->insn) == QUEUE_READY);
3423   QUEUE_INDEX (insn->insn) = QUEUE_NOWHERE;
3424
3425   if (insn->prev)
3426     insn->prev->next = insn->next;
3427   else
3428     model_worklist = insn->next;
3429   if (insn->next)
3430     insn->next->prev = insn->prev;
3431 }
3432
3433 /* Add INSN to the model worklist.  Start looking for a suitable position
3434    between neighbors PREV and NEXT, testing at most MAX_SCHED_READY_INSNS
3435    insns either side.  A null PREV indicates the beginning of the list and
3436    a null NEXT indicates the end.  */
3437
3438 static void
3439 model_add_to_worklist (struct model_insn_info *insn,
3440                        struct model_insn_info *prev,
3441                        struct model_insn_info *next)
3442 {
3443   int count;
3444
3445   count = MAX_SCHED_READY_INSNS;
3446   if (count > 0 && prev && model_order_p (insn, prev))
3447     do
3448       {
3449         count--;
3450         prev = prev->prev;
3451       }
3452     while (count > 0 && prev && model_order_p (insn, prev));
3453   else
3454     while (count > 0 && next && model_order_p (next, insn))
3455       {
3456         count--;
3457         prev = next;
3458         next = next->next;
3459       }
3460   model_add_to_worklist_at (insn, prev);
3461 }
3462
3463 /* INSN may now have a higher priority (in the model_order_p sense)
3464    than before.  Move it up the worklist if necessary.  */
3465
3466 static void
3467 model_promote_insn (struct model_insn_info *insn)
3468 {
3469   struct model_insn_info *prev;
3470   int count;
3471
3472   prev = insn->prev;
3473   count = MAX_SCHED_READY_INSNS;
3474   while (count > 0 && prev && model_order_p (insn, prev))
3475     {
3476       count--;
3477       prev = prev->prev;
3478     }
3479   if (prev != insn->prev)
3480     {
3481       model_remove_from_worklist (insn);
3482       model_add_to_worklist_at (insn, prev);
3483     }
3484 }
3485
3486 /* Add INSN to the end of the model schedule.  */
3487
3488 static void
3489 model_add_to_schedule (rtx_insn *insn)
3490 {
3491   unsigned int point;
3492
3493   gcc_assert (QUEUE_INDEX (insn) == QUEUE_NOWHERE);
3494   QUEUE_INDEX (insn) = QUEUE_SCHEDULED;
3495
3496   point = model_schedule.length ();
3497   model_schedule.quick_push (insn);
3498   INSN_MODEL_INDEX (insn) = point + 1;
3499 }
3500
3501 /* Analyze the instructions that are to be scheduled, setting up
3502    MODEL_INSN_INFO (...) and model_num_insns accordingly.  Add ready
3503    instructions to model_worklist.  */
3504
3505 static void
3506 model_analyze_insns (void)
3507 {
3508   rtx_insn *start, *end, *iter;
3509   sd_iterator_def sd_it;
3510   dep_t dep;
3511   struct model_insn_info *insn, *con;
3512
3513   model_num_insns = 0;
3514   start = PREV_INSN (current_sched_info->next_tail);
3515   end = current_sched_info->prev_head;
3516   for (iter = start; iter != end; iter = PREV_INSN (iter))
3517     if (NONDEBUG_INSN_P (iter))
3518       {
3519         insn = MODEL_INSN_INFO (iter);
3520         insn->insn = iter;
3521         FOR_EACH_DEP (iter, SD_LIST_FORW, sd_it, dep)
3522           {
3523             con = MODEL_INSN_INFO (DEP_CON (dep));
3524             if (con->insn && insn->alap < con->alap + 1)
3525               insn->alap = con->alap + 1;
3526           }
3527
3528         insn->old_queue = QUEUE_INDEX (iter);
3529         QUEUE_INDEX (iter) = QUEUE_NOWHERE;
3530
3531         insn->unscheduled_preds = dep_list_size (iter, SD_LIST_HARD_BACK);
3532         if (insn->unscheduled_preds == 0)
3533           model_add_to_worklist (insn, NULL, model_worklist);
3534
3535         model_num_insns++;
3536       }
3537 }
3538
3539 /* The global state describes the register pressure at the start of the
3540    model schedule.  Initialize GROUP accordingly.  */
3541
3542 static void
3543 model_init_pressure_group (struct model_pressure_group *group)
3544 {
3545   int pci, cl;
3546
3547   for (pci = 0; pci < ira_pressure_classes_num; pci++)
3548     {
3549       cl = ira_pressure_classes[pci];
3550       group->limits[pci].pressure = curr_reg_pressure[cl];
3551       group->limits[pci].point = 0;
3552     }
3553   /* Use index model_num_insns to record the state after the last
3554      instruction in the model schedule.  */
3555   group->model = XNEWVEC (struct model_pressure_data,
3556                           (model_num_insns + 1) * ira_pressure_classes_num);
3557 }
3558
3559 /* Record that MODEL_REF_PRESSURE (GROUP, POINT, PCI) is PRESSURE.
3560    Update the maximum pressure for the whole schedule.  */
3561
3562 static void
3563 model_record_pressure (struct model_pressure_group *group,
3564                        int point, int pci, int pressure)
3565 {
3566   MODEL_REF_PRESSURE (group, point, pci) = pressure;
3567   if (group->limits[pci].pressure < pressure)
3568     {
3569       group->limits[pci].pressure = pressure;
3570       group->limits[pci].point = point;
3571     }
3572 }
3573
3574 /* INSN has just been added to the end of the model schedule.  Record its
3575    register-pressure information.  */
3576
3577 static void
3578 model_record_pressures (struct model_insn_info *insn)
3579 {
3580   struct reg_pressure_data *reg_pressure;
3581   int point, pci, cl, delta;
3582   int death[N_REG_CLASSES];
3583
3584   point = model_index (insn->insn);
3585   if (sched_verbose >= 2)
3586     {
3587       if (point == 0)
3588         {
3589           fprintf (sched_dump, "\n;;\tModel schedule:\n;;\n");
3590           fprintf (sched_dump, ";;\t| idx insn | mpri hght dpth prio |\n");
3591         }
3592       fprintf (sched_dump, ";;\t| %3d %4d | %4d %4d %4d %4d | %-30s ",
3593                point, INSN_UID (insn->insn), insn->model_priority,
3594                insn->depth + insn->alap, insn->depth,
3595                INSN_PRIORITY (insn->insn),
3596                str_pattern_slim (PATTERN (insn->insn)));
3597     }
3598   calculate_reg_deaths (insn->insn, death);
3599   reg_pressure = INSN_REG_PRESSURE (insn->insn);
3600   for (pci = 0; pci < ira_pressure_classes_num; pci++)
3601     {
3602       cl = ira_pressure_classes[pci];
3603       delta = reg_pressure[pci].set_increase - death[cl];
3604       if (sched_verbose >= 2)
3605         fprintf (sched_dump, " %s:[%d,%+d]", reg_class_names[cl],
3606                  curr_reg_pressure[cl], delta);
3607       model_record_pressure (&model_before_pressure, point, pci,
3608                              curr_reg_pressure[cl]);
3609     }
3610   if (sched_verbose >= 2)
3611     fprintf (sched_dump, "\n");
3612 }
3613
3614 /* All instructions have been added to the model schedule.  Record the
3615    final register pressure in GROUP and set up all MODEL_MAX_PRESSUREs.  */
3616
3617 static void
3618 model_record_final_pressures (struct model_pressure_group *group)
3619 {
3620   int point, pci, max_pressure, ref_pressure, cl;
3621
3622   for (pci = 0; pci < ira_pressure_classes_num; pci++)
3623     {
3624       /* Record the final pressure for this class.  */
3625       cl = ira_pressure_classes[pci];
3626       point = model_num_insns;
3627       ref_pressure = curr_reg_pressure[cl];
3628       model_record_pressure (group, point, pci, ref_pressure);
3629
3630       /* Record the original maximum pressure.  */
3631       group->limits[pci].orig_pressure = group->limits[pci].pressure;
3632
3633       /* Update the MODEL_MAX_PRESSURE for every point of the schedule.  */
3634       max_pressure = ref_pressure;
3635       MODEL_MAX_PRESSURE (group, point, pci) = max_pressure;
3636       while (point > 0)
3637         {
3638           point--;
3639           ref_pressure = MODEL_REF_PRESSURE (group, point, pci);
3640           max_pressure = MAX (max_pressure, ref_pressure);
3641           MODEL_MAX_PRESSURE (group, point, pci) = max_pressure;
3642         }
3643     }
3644 }
3645
3646 /* Update all successors of INSN, given that INSN has just been scheduled.  */
3647
3648 static void
3649 model_add_successors_to_worklist (struct model_insn_info *insn)
3650 {
3651   sd_iterator_def sd_it;
3652   struct model_insn_info *con;
3653   dep_t dep;
3654
3655   FOR_EACH_DEP (insn->insn, SD_LIST_FORW, sd_it, dep)
3656     {
3657       con = MODEL_INSN_INFO (DEP_CON (dep));
3658       /* Ignore debug instructions, and instructions from other blocks.  */
3659       if (con->insn)
3660         {
3661           con->unscheduled_preds--;
3662
3663           /* Update the depth field of each true-dependent successor.
3664              Increasing the depth gives them a higher priority than
3665              before.  */
3666           if (DEP_TYPE (dep) == REG_DEP_TRUE && con->depth < insn->depth + 1)
3667             {
3668               con->depth = insn->depth + 1;
3669               if (QUEUE_INDEX (con->insn) == QUEUE_READY)
3670                 model_promote_insn (con);
3671             }
3672
3673           /* If this is a true dependency, or if there are no remaining
3674              dependencies for CON (meaning that CON only had non-true
3675              dependencies), make sure that CON is on the worklist.
3676              We don't bother otherwise because it would tend to fill the
3677              worklist with a lot of low-priority instructions that are not
3678              yet ready to issue.  */
3679           if ((con->depth > 0 || con->unscheduled_preds == 0)
3680               && QUEUE_INDEX (con->insn) == QUEUE_NOWHERE)
3681             model_add_to_worklist (con, insn, insn->next);
3682         }
3683     }
3684 }
3685
3686 /* Give INSN a higher priority than any current instruction, then give
3687    unscheduled predecessors of INSN a higher priority still.  If any of
3688    those predecessors are not on the model worklist, do the same for its
3689    predecessors, and so on.  */
3690
3691 static void
3692 model_promote_predecessors (struct model_insn_info *insn)
3693 {
3694   struct model_insn_info *pro, *first;
3695   sd_iterator_def sd_it;
3696   dep_t dep;
3697
3698   if (sched_verbose >= 7)
3699     fprintf (sched_dump, ";;\t+--- priority of %d = %d, priority of",
3700              INSN_UID (insn->insn), model_next_priority);
3701   insn->model_priority = model_next_priority++;
3702   model_remove_from_worklist (insn);
3703   model_add_to_worklist_at (insn, NULL);
3704
3705   first = NULL;
3706   for (;;)
3707     {
3708       FOR_EACH_DEP (insn->insn, SD_LIST_HARD_BACK, sd_it, dep)
3709         {
3710           pro = MODEL_INSN_INFO (DEP_PRO (dep));
3711           /* The first test is to ignore debug instructions, and instructions
3712              from other blocks.  */
3713           if (pro->insn
3714               && pro->model_priority != model_next_priority
3715               && QUEUE_INDEX (pro->insn) != QUEUE_SCHEDULED)
3716             {
3717               pro->model_priority = model_next_priority;
3718               if (sched_verbose >= 7)
3719                 fprintf (sched_dump, " %d", INSN_UID (pro->insn));
3720               if (QUEUE_INDEX (pro->insn) == QUEUE_READY)
3721                 {
3722                   /* PRO is already in the worklist, but it now has
3723                      a higher priority than before.  Move it at the
3724                      appropriate place.  */
3725                   model_remove_from_worklist (pro);
3726                   model_add_to_worklist (pro, NULL, model_worklist);
3727                 }
3728               else
3729                 {
3730                   /* PRO isn't in the worklist.  Recursively process
3731                      its predecessors until we find one that is.  */
3732                   pro->next = first;
3733                   first = pro;
3734                 }
3735             }
3736         }
3737       if (!first)
3738         break;
3739       insn = first;
3740       first = insn->next;
3741     }
3742   if (sched_verbose >= 7)
3743     fprintf (sched_dump, " = %d\n", model_next_priority);
3744   model_next_priority++;
3745 }
3746
3747 /* Pick one instruction from model_worklist and process it.  */
3748
3749 static void
3750 model_choose_insn (void)
3751 {
3752   struct model_insn_info *insn, *fallback;
3753   int count;
3754
3755   if (sched_verbose >= 7)
3756     {
3757       fprintf (sched_dump, ";;\t+--- worklist:\n");
3758       insn = model_worklist;
3759       count = MAX_SCHED_READY_INSNS;
3760       while (count > 0 && insn)
3761         {
3762           fprintf (sched_dump, ";;\t+---   %d [%d, %d, %d, %d]\n",
3763                    INSN_UID (insn->insn), insn->model_priority,
3764                    insn->depth + insn->alap, insn->depth,
3765                    INSN_PRIORITY (insn->insn));
3766           count--;
3767           insn = insn->next;
3768         }
3769     }
3770
3771   /* Look for a ready instruction whose model_classify_priority is zero
3772      or negative, picking the highest-priority one.  Adding such an
3773      instruction to the schedule now should do no harm, and may actually
3774      do some good.
3775
3776      Failing that, see whether there is an instruction with the highest
3777      extant model_priority that is not yet ready, but which would reduce
3778      pressure if it became ready.  This is designed to catch cases like:
3779
3780        (set (mem (reg R1)) (reg R2))
3781
3782      where the instruction is the last remaining use of R1 and where the
3783      value of R2 is not yet available (or vice versa).  The death of R1
3784      means that this instruction already reduces pressure.  It is of
3785      course possible that the computation of R2 involves other registers
3786      that are hard to kill, but such cases are rare enough for this
3787      heuristic to be a win in general.
3788
3789      Failing that, just pick the highest-priority instruction in the
3790      worklist.  */
3791   count = MAX_SCHED_READY_INSNS;
3792   insn = model_worklist;
3793   fallback = 0;
3794   for (;;)
3795     {
3796       if (count == 0 || !insn)
3797         {
3798           insn = fallback ? fallback : model_worklist;
3799           break;
3800         }
3801       if (insn->unscheduled_preds)
3802         {
3803           if (model_worklist->model_priority == insn->model_priority
3804               && !fallback
3805               && model_classify_pressure (insn) < 0)
3806             fallback = insn;
3807         }
3808       else
3809         {
3810           if (model_classify_pressure (insn) <= 0)
3811             break;
3812         }
3813       count--;
3814       insn = insn->next;
3815     }
3816
3817   if (sched_verbose >= 7 && insn != model_worklist)
3818     {
3819       if (insn->unscheduled_preds)
3820         fprintf (sched_dump, ";;\t+--- promoting insn %d, with dependencies\n",
3821                  INSN_UID (insn->insn));
3822       else
3823         fprintf (sched_dump, ";;\t+--- promoting insn %d, which is ready\n",
3824                  INSN_UID (insn->insn));
3825     }
3826   if (insn->unscheduled_preds)
3827     /* INSN isn't yet ready to issue.  Give all its predecessors the
3828        highest priority.  */
3829     model_promote_predecessors (insn);
3830   else
3831     {
3832       /* INSN is ready.  Add it to the end of model_schedule and
3833          process its successors.  */
3834       model_add_successors_to_worklist (insn);
3835       model_remove_from_worklist (insn);
3836       model_add_to_schedule (insn->insn);
3837       model_record_pressures (insn);
3838       update_register_pressure (insn->insn);
3839     }
3840 }
3841
3842 /* Restore all QUEUE_INDEXs to the values that they had before
3843    model_start_schedule was called.  */
3844
3845 static void
3846 model_reset_queue_indices (void)
3847 {
3848   unsigned int i;
3849   rtx_insn *insn;
3850
3851   FOR_EACH_VEC_ELT (model_schedule, i, insn)
3852     QUEUE_INDEX (insn) = MODEL_INSN_INFO (insn)->old_queue;
3853 }
3854
3855 /* We have calculated the model schedule and spill costs.  Print a summary
3856    to sched_dump.  */
3857
3858 static void
3859 model_dump_pressure_summary (void)
3860 {
3861   int pci, cl;
3862
3863   fprintf (sched_dump, ";; Pressure summary:");
3864   for (pci = 0; pci < ira_pressure_classes_num; pci++)
3865     {
3866       cl = ira_pressure_classes[pci];
3867       fprintf (sched_dump, " %s:%d", reg_class_names[cl],
3868                model_before_pressure.limits[pci].pressure);
3869     }
3870   fprintf (sched_dump, "\n\n");
3871 }
3872
3873 /* Initialize the SCHED_PRESSURE_MODEL information for the current
3874    scheduling region.  */
3875
3876 static void
3877 model_start_schedule (basic_block bb)
3878 {
3879   model_next_priority = 1;
3880   model_schedule.create (sched_max_luid);
3881   model_insns = XCNEWVEC (struct model_insn_info, sched_max_luid);
3882
3883   gcc_assert (bb == BLOCK_FOR_INSN (NEXT_INSN (current_sched_info->prev_head)));
3884   initiate_reg_pressure_info (df_get_live_in (bb));
3885
3886   model_analyze_insns ();
3887   model_init_pressure_group (&model_before_pressure);
3888   while (model_worklist)
3889     model_choose_insn ();
3890   gcc_assert (model_num_insns == (int) model_schedule.length ());
3891   if (sched_verbose >= 2)
3892     fprintf (sched_dump, "\n");
3893
3894   model_record_final_pressures (&model_before_pressure);
3895   model_reset_queue_indices ();
3896
3897   XDELETEVEC (model_insns);
3898
3899   model_curr_point = 0;
3900   initiate_reg_pressure_info (df_get_live_in (bb));
3901   if (sched_verbose >= 1)
3902     model_dump_pressure_summary ();
3903 }
3904
3905 /* Free the information associated with GROUP.  */
3906
3907 static void
3908 model_finalize_pressure_group (struct model_pressure_group *group)
3909 {
3910   XDELETEVEC (group->model);
3911 }
3912
3913 /* Free the information created by model_start_schedule.  */
3914
3915 static void
3916 model_end_schedule (void)
3917 {
3918   model_finalize_pressure_group (&model_before_pressure);
3919   model_schedule.release ();
3920 }
3921
3922 /* Prepare reg pressure scheduling for basic block BB.  */
3923 static void
3924 sched_pressure_start_bb (basic_block bb)
3925 {
3926   /* Set the number of available registers for each class taking into account
3927      relative probability of current basic block versus function prologue and
3928      epilogue.
3929      * If the basic block executes much more often than the prologue/epilogue
3930      (e.g., inside a hot loop), then cost of spill in the prologue is close to
3931      nil, so the effective number of available registers is
3932      (ira_class_hard_regs_num[cl] - 0).
3933      * If the basic block executes as often as the prologue/epilogue,
3934      then spill in the block is as costly as in the prologue, so the effective
3935      number of available registers is
3936      (ira_class_hard_regs_num[cl] - call_used_regs_num[cl]).
3937      Note that all-else-equal, we prefer to spill in the prologue, since that
3938      allows "extra" registers for other basic blocks of the function.
3939      * If the basic block is on the cold path of the function and executes
3940      rarely, then we should always prefer to spill in the block, rather than
3941      in the prologue/epilogue.  The effective number of available register is
3942      (ira_class_hard_regs_num[cl] - call_used_regs_num[cl]).  */
3943   {
3944     int i;
3945     int entry_freq = ENTRY_BLOCK_PTR_FOR_FN (cfun)->frequency;
3946     int bb_freq = bb->frequency;
3947
3948     if (bb_freq == 0)
3949       {
3950         if (entry_freq == 0)
3951           entry_freq = bb_freq = 1;
3952       }
3953     if (bb_freq < entry_freq)
3954       bb_freq = entry_freq;
3955
3956     for (i = 0; i < ira_pressure_classes_num; ++i)
3957       {
3958         enum reg_class cl = ira_pressure_classes[i];
3959         sched_class_regs_num[cl] = ira_class_hard_regs_num[cl];
3960         sched_class_regs_num[cl]
3961           -= (call_used_regs_num[cl] * entry_freq) / bb_freq;
3962       }
3963   }
3964
3965   if (sched_pressure == SCHED_PRESSURE_MODEL)
3966     model_start_schedule (bb);
3967 }
3968 \f
3969 /* A structure that holds local state for the loop in schedule_block.  */
3970 struct sched_block_state
3971 {
3972   /* True if no real insns have been scheduled in the current cycle.  */
3973   bool first_cycle_insn_p;
3974   /* True if a shadow insn has been scheduled in the current cycle, which
3975      means that no more normal insns can be issued.  */
3976   bool shadows_only_p;
3977   /* True if we're winding down a modulo schedule, which means that we only
3978      issue insns with INSN_EXACT_TICK set.  */
3979   bool modulo_epilogue;
3980   /* Initialized with the machine's issue rate every cycle, and updated
3981      by calls to the variable_issue hook.  */
3982   int can_issue_more;
3983 };
3984
3985 /* INSN is the "currently executing insn".  Launch each insn which was
3986    waiting on INSN.  READY is the ready list which contains the insns
3987    that are ready to fire.  CLOCK is the current cycle.  The function
3988    returns necessary cycle advance after issuing the insn (it is not
3989    zero for insns in a schedule group).  */
3990
3991 static int
3992 schedule_insn (rtx_insn *insn)
3993 {
3994   sd_iterator_def sd_it;
3995   dep_t dep;
3996   int i;
3997   int advance = 0;
3998
3999   if (sched_verbose >= 1)
4000     {
4001       struct reg_pressure_data *pressure_info;
4002       fprintf (sched_dump, ";;\t%3i--> %s %-40s:",
4003                clock_var, (*current_sched_info->print_insn) (insn, 1),
4004                str_pattern_slim (PATTERN (insn)));
4005
4006       if (recog_memoized (insn) < 0)
4007         fprintf (sched_dump, "nothing");
4008       else
4009         print_reservation (sched_dump, insn);
4010       pressure_info = INSN_REG_PRESSURE (insn);
4011       if (pressure_info != NULL)
4012         {
4013           fputc (':', sched_dump);
4014           for (i = 0; i < ira_pressure_classes_num; i++)
4015             fprintf (sched_dump, "%s%s%+d(%d)",
4016                      scheduled_insns.length () > 1
4017                      && INSN_LUID (insn)
4018                      < INSN_LUID (scheduled_insns[scheduled_insns.length () - 2]) ? "@" : "",
4019                      reg_class_names[ira_pressure_classes[i]],
4020                      pressure_info[i].set_increase, pressure_info[i].change);
4021         }
4022       if (sched_pressure == SCHED_PRESSURE_MODEL
4023           && model_curr_point < model_num_insns
4024           && model_index (insn) == model_curr_point)
4025         fprintf (sched_dump, ":model %d", model_curr_point);
4026       fputc ('\n', sched_dump);
4027     }
4028
4029   if (sched_pressure == SCHED_PRESSURE_WEIGHTED && !DEBUG_INSN_P (insn))
4030     update_reg_and_insn_max_reg_pressure (insn);
4031
4032   /* Scheduling instruction should have all its dependencies resolved and
4033      should have been removed from the ready list.  */
4034   gcc_assert (sd_lists_empty_p (insn, SD_LIST_HARD_BACK));
4035
4036   /* Reset debug insns invalidated by moving this insn.  */
4037   if (MAY_HAVE_DEBUG_INSNS && !DEBUG_INSN_P (insn))
4038     for (sd_it = sd_iterator_start (insn, SD_LIST_BACK);
4039          sd_iterator_cond (&sd_it, &dep);)
4040       {
4041         rtx_insn *dbg = DEP_PRO (dep);
4042         struct reg_use_data *use, *next;
4043
4044         if (DEP_STATUS (dep) & DEP_CANCELLED)
4045           {
4046             sd_iterator_next (&sd_it);
4047             continue;
4048           }
4049
4050         gcc_assert (DEBUG_INSN_P (dbg));
4051
4052         if (sched_verbose >= 6)
4053           fprintf (sched_dump, ";;\t\tresetting: debug insn %d\n",
4054                    INSN_UID (dbg));
4055
4056         /* ??? Rather than resetting the debug insn, we might be able
4057            to emit a debug temp before the just-scheduled insn, but
4058            this would involve checking that the expression at the
4059            point of the debug insn is equivalent to the expression
4060            before the just-scheduled insn.  They might not be: the
4061            expression in the debug insn may depend on other insns not
4062            yet scheduled that set MEMs, REGs or even other debug
4063            insns.  It's not clear that attempting to preserve debug
4064            information in these cases is worth the effort, given how
4065            uncommon these resets are and the likelihood that the debug
4066            temps introduced won't survive the schedule change.  */
4067         INSN_VAR_LOCATION_LOC (dbg) = gen_rtx_UNKNOWN_VAR_LOC ();
4068         df_insn_rescan (dbg);
4069
4070         /* Unknown location doesn't use any registers.  */
4071         for (use = INSN_REG_USE_LIST (dbg); use != NULL; use = next)
4072           {
4073             struct reg_use_data *prev = use;
4074
4075             /* Remove use from the cyclic next_regno_use chain first.  */
4076             while (prev->next_regno_use != use)
4077               prev = prev->next_regno_use;
4078             prev->next_regno_use = use->next_regno_use;
4079             next = use->next_insn_use;
4080             free (use);
4081           }
4082         INSN_REG_USE_LIST (dbg) = NULL;
4083
4084         /* We delete rather than resolve these deps, otherwise we
4085            crash in sched_free_deps(), because forward deps are
4086            expected to be released before backward deps.  */
4087         sd_delete_dep (sd_it);
4088       }
4089
4090   gcc_assert (QUEUE_INDEX (insn) == QUEUE_NOWHERE);
4091   QUEUE_INDEX (insn) = QUEUE_SCHEDULED;
4092
4093   if (sched_pressure == SCHED_PRESSURE_MODEL
4094       && model_curr_point < model_num_insns
4095       && NONDEBUG_INSN_P (insn))
4096     {
4097       if (model_index (insn) == model_curr_point)
4098         do
4099           model_curr_point++;
4100         while (model_curr_point < model_num_insns
4101                && (QUEUE_INDEX (MODEL_INSN (model_curr_point))
4102                    == QUEUE_SCHEDULED));
4103       else
4104         model_recompute (insn);
4105       model_update_limit_points ();
4106       update_register_pressure (insn);
4107       if (sched_verbose >= 2)
4108         print_curr_reg_pressure ();
4109     }
4110
4111   gcc_assert (INSN_TICK (insn) >= MIN_TICK);
4112   if (INSN_TICK (insn) > clock_var)
4113     /* INSN has been prematurely moved from the queue to the ready list.
4114        This is possible only if following flags are set.  */
4115     gcc_assert (flag_sched_stalled_insns || sched_fusion);
4116
4117   /* ??? Probably, if INSN is scheduled prematurely, we should leave
4118      INSN_TICK untouched.  This is a machine-dependent issue, actually.  */
4119   INSN_TICK (insn) = clock_var;
4120
4121   check_clobbered_conditions (insn);
4122
4123   /* Update dependent instructions.  First, see if by scheduling this insn
4124      now we broke a dependence in a way that requires us to change another
4125      insn.  */
4126   for (sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
4127        sd_iterator_cond (&sd_it, &dep); sd_iterator_next (&sd_it))
4128     {
4129       struct dep_replacement *desc = DEP_REPLACE (dep);
4130       rtx_insn *pro = DEP_PRO (dep);
4131       if (QUEUE_INDEX (pro) != QUEUE_SCHEDULED
4132           && desc != NULL && desc->insn == pro)
4133         apply_replacement (dep, false);
4134     }
4135
4136   /* Go through and resolve forward dependencies.  */
4137   for (sd_it = sd_iterator_start (insn, SD_LIST_FORW);
4138        sd_iterator_cond (&sd_it, &dep);)
4139     {
4140       rtx_insn *next = DEP_CON (dep);
4141       bool cancelled = (DEP_STATUS (dep) & DEP_CANCELLED) != 0;
4142
4143       /* Resolve the dependence between INSN and NEXT.
4144          sd_resolve_dep () moves current dep to another list thus
4145          advancing the iterator.  */
4146       sd_resolve_dep (sd_it);
4147
4148       if (cancelled)
4149         {
4150           if (must_restore_pattern_p (next, dep))
4151             restore_pattern (dep, false);
4152           continue;
4153         }
4154
4155       /* Don't bother trying to mark next as ready if insn is a debug
4156          insn.  If insn is the last hard dependency, it will have
4157          already been discounted.  */
4158       if (DEBUG_INSN_P (insn) && !DEBUG_INSN_P (next))
4159         continue;
4160
4161       if (!IS_SPECULATION_BRANCHY_CHECK_P (insn))
4162         {
4163           int effective_cost;
4164
4165           effective_cost = try_ready (next);
4166
4167           if (effective_cost >= 0
4168               && SCHED_GROUP_P (next)
4169               && advance < effective_cost)
4170             advance = effective_cost;
4171         }
4172       else
4173         /* Check always has only one forward dependence (to the first insn in
4174            the recovery block), therefore, this will be executed only once.  */
4175         {
4176           gcc_assert (sd_lists_empty_p (insn, SD_LIST_FORW));
4177           fix_recovery_deps (RECOVERY_BLOCK (insn));
4178         }
4179     }
4180
4181   /* Annotate the instruction with issue information -- TImode
4182      indicates that the instruction is expected not to be able
4183      to issue on the same cycle as the previous insn.  A machine
4184      may use this information to decide how the instruction should
4185      be aligned.  */
4186   if (issue_rate > 1
4187       && GET_CODE (PATTERN (insn)) != USE
4188       && GET_CODE (PATTERN (insn)) != CLOBBER
4189       && !DEBUG_INSN_P (insn))
4190     {
4191       if (reload_completed)
4192         PUT_MODE (insn, clock_var > last_clock_var ? TImode : VOIDmode);
4193       last_clock_var = clock_var;
4194     }
4195
4196   if (nonscheduled_insns_begin != NULL_RTX)
4197     /* Indicate to debug counters that INSN is scheduled.  */
4198     nonscheduled_insns_begin = insn;
4199
4200   return advance;
4201 }
4202
4203 /* Functions for handling of notes.  */
4204
4205 /* Add note list that ends on FROM_END to the end of TO_ENDP.  */
4206 void
4207 concat_note_lists (rtx_insn *from_end, rtx_insn **to_endp)
4208 {
4209   rtx_insn *from_start;
4210
4211   /* It's easy when have nothing to concat.  */
4212   if (from_end == NULL)
4213     return;
4214
4215   /* It's also easy when destination is empty.  */
4216   if (*to_endp == NULL)
4217     {
4218       *to_endp = from_end;
4219       return;
4220     }
4221
4222   from_start = from_end;
4223   while (PREV_INSN (from_start) != NULL)
4224     from_start = PREV_INSN (from_start);
4225
4226   SET_PREV_INSN (from_start) = *to_endp;
4227   SET_NEXT_INSN (*to_endp) = from_start;
4228   *to_endp = from_end;
4229 }
4230
4231 /* Delete notes between HEAD and TAIL and put them in the chain
4232    of notes ended by NOTE_LIST.  */
4233 void
4234 remove_notes (rtx_insn *head, rtx_insn *tail)
4235 {
4236   rtx_insn *next_tail, *insn, *next;
4237
4238   note_list = 0;
4239   if (head == tail && !INSN_P (head))
4240     return;
4241
4242   next_tail = NEXT_INSN (tail);
4243   for (insn = head; insn != next_tail; insn = next)
4244     {
4245       next = NEXT_INSN (insn);
4246       if (!NOTE_P (insn))
4247         continue;
4248
4249       switch (NOTE_KIND (insn))
4250         {
4251         case NOTE_INSN_BASIC_BLOCK:
4252           continue;
4253
4254         case NOTE_INSN_EPILOGUE_BEG:
4255           if (insn != tail)
4256             {
4257               remove_insn (insn);
4258               add_reg_note (next, REG_SAVE_NOTE,
4259                             GEN_INT (NOTE_INSN_EPILOGUE_BEG));
4260               break;
4261             }
4262           /* FALLTHRU */
4263
4264         default:
4265           remove_insn (insn);
4266
4267           /* Add the note to list that ends at NOTE_LIST.  */
4268           SET_PREV_INSN (insn) = note_list;
4269           SET_NEXT_INSN (insn) = NULL_RTX;
4270           if (note_list)
4271             SET_NEXT_INSN (note_list) = insn;
4272           note_list = insn;
4273           break;
4274         }
4275
4276       gcc_assert ((sel_sched_p () || insn != tail) && insn != head);
4277     }
4278 }
4279
4280 /* A structure to record enough data to allow us to backtrack the scheduler to
4281    a previous state.  */
4282 struct haifa_saved_data
4283 {
4284   /* Next entry on the list.  */
4285   struct haifa_saved_data *next;
4286
4287   /* Backtracking is associated with scheduling insns that have delay slots.
4288      DELAY_PAIR points to the structure that contains the insns involved, and
4289      the number of cycles between them.  */
4290   struct delay_pair *delay_pair;
4291
4292   /* Data used by the frontend (e.g. sched-ebb or sched-rgn).  */
4293   void *fe_saved_data;
4294   /* Data used by the backend.  */
4295   void *be_saved_data;
4296
4297   /* Copies of global state.  */
4298   int clock_var, last_clock_var;
4299   struct ready_list ready;
4300   state_t curr_state;
4301
4302   rtx_insn *last_scheduled_insn;
4303   rtx last_nondebug_scheduled_insn;
4304   rtx_insn *nonscheduled_insns_begin;
4305   int cycle_issued_insns;
4306
4307   /* Copies of state used in the inner loop of schedule_block.  */
4308   struct sched_block_state sched_block;
4309
4310   /* We don't need to save q_ptr, as its value is arbitrary and we can set it
4311      to 0 when restoring.  */
4312   int q_size;
4313   rtx_insn_list **insn_queue;
4314
4315   /* Describe pattern replacements that occurred since this backtrack point
4316      was queued.  */
4317   vec<dep_t> replacement_deps;
4318   vec<int> replace_apply;
4319
4320   /* A copy of the next-cycle replacement vectors at the time of the backtrack
4321      point.  */
4322   vec<dep_t> next_cycle_deps;
4323   vec<int> next_cycle_apply;
4324 };
4325
4326 /* A record, in reverse order, of all scheduled insns which have delay slots
4327    and may require backtracking.  */
4328 static struct haifa_saved_data *backtrack_queue;
4329
4330 /* For every dependency of INSN, set the FEEDS_BACKTRACK_INSN bit according
4331    to SET_P.  */
4332 static void
4333 mark_backtrack_feeds (rtx insn, int set_p)
4334 {
4335   sd_iterator_def sd_it;
4336   dep_t dep;
4337   FOR_EACH_DEP (insn, SD_LIST_HARD_BACK, sd_it, dep)
4338     {
4339       FEEDS_BACKTRACK_INSN (DEP_PRO (dep)) = set_p;
4340     }
4341 }
4342
4343 /* Save the current scheduler state so that we can backtrack to it
4344    later if necessary.  PAIR gives the insns that make it necessary to
4345    save this point.  SCHED_BLOCK is the local state of schedule_block
4346    that need to be saved.  */
4347 static void
4348 save_backtrack_point (struct delay_pair *pair,
4349                       struct sched_block_state sched_block)
4350 {
4351   int i;
4352   struct haifa_saved_data *save = XNEW (struct haifa_saved_data);
4353
4354   save->curr_state = xmalloc (dfa_state_size);
4355   memcpy (save->curr_state, curr_state, dfa_state_size);
4356
4357   save->ready.first = ready.first;
4358   save->ready.n_ready = ready.n_ready;
4359   save->ready.n_debug = ready.n_debug;
4360   save->ready.veclen = ready.veclen;
4361   save->ready.vec = XNEWVEC (rtx_insn *, ready.veclen);
4362   memcpy (save->ready.vec, ready.vec, ready.veclen * sizeof (rtx));
4363
4364   save->insn_queue = XNEWVEC (rtx_insn_list *, max_insn_queue_index + 1);
4365   save->q_size = q_size;
4366   for (i = 0; i <= max_insn_queue_index; i++)
4367     {
4368       int q = NEXT_Q_AFTER (q_ptr, i);
4369       save->insn_queue[i] = copy_INSN_LIST (insn_queue[q]);
4370     }
4371
4372   save->clock_var = clock_var;
4373   save->last_clock_var = last_clock_var;
4374   save->cycle_issued_insns = cycle_issued_insns;
4375   save->last_scheduled_insn = last_scheduled_insn;
4376   save->last_nondebug_scheduled_insn = last_nondebug_scheduled_insn;
4377   save->nonscheduled_insns_begin = nonscheduled_insns_begin;
4378
4379   save->sched_block = sched_block;
4380
4381   save->replacement_deps.create (0);
4382   save->replace_apply.create (0);
4383   save->next_cycle_deps = next_cycle_replace_deps.copy ();
4384   save->next_cycle_apply = next_cycle_apply.copy ();
4385
4386   if (current_sched_info->save_state)
4387     save->fe_saved_data = (*current_sched_info->save_state) ();
4388
4389   if (targetm.sched.alloc_sched_context)
4390     {
4391       save->be_saved_data = targetm.sched.alloc_sched_context ();
4392       targetm.sched.init_sched_context (save->be_saved_data, false);
4393     }
4394   else
4395     save->be_saved_data = NULL;
4396
4397   save->delay_pair = pair;
4398
4399   save->next = backtrack_queue;
4400   backtrack_queue = save;
4401
4402   while (pair)
4403     {
4404       mark_backtrack_feeds (pair->i2, 1);
4405       INSN_TICK (pair->i2) = INVALID_TICK;
4406       INSN_EXACT_TICK (pair->i2) = clock_var + pair_delay (pair);
4407       SHADOW_P (pair->i2) = pair->stages == 0;
4408       pair = pair->next_same_i1;
4409     }
4410 }
4411
4412 /* Walk the ready list and all queues. If any insns have unresolved backwards
4413    dependencies, these must be cancelled deps, broken by predication.  Set or
4414    clear (depending on SET) the DEP_CANCELLED bit in DEP_STATUS.  */
4415
4416 static void
4417 toggle_cancelled_flags (bool set)
4418 {
4419   int i;
4420   sd_iterator_def sd_it;
4421   dep_t dep;
4422
4423   if (ready.n_ready > 0)
4424     {
4425       rtx_insn **first = ready_lastpos (&ready);
4426       for (i = 0; i < ready.n_ready; i++)
4427         FOR_EACH_DEP (first[i], SD_LIST_BACK, sd_it, dep)
4428           if (!DEBUG_INSN_P (DEP_PRO (dep)))
4429             {
4430               if (set)
4431                 DEP_STATUS (dep) |= DEP_CANCELLED;
4432               else
4433                 DEP_STATUS (dep) &= ~DEP_CANCELLED;
4434             }
4435     }
4436   for (i = 0; i <= max_insn_queue_index; i++)
4437     {
4438       int q = NEXT_Q_AFTER (q_ptr, i);
4439       rtx_insn_list *link;
4440       for (link = insn_queue[q]; link; link = link->next ())
4441         {
4442           rtx_insn *insn = link->insn ();
4443           FOR_EACH_DEP (insn, SD_LIST_BACK, sd_it, dep)
4444             if (!DEBUG_INSN_P (DEP_PRO (dep)))
4445               {
4446                 if (set)
4447                   DEP_STATUS (dep) |= DEP_CANCELLED;
4448                 else
4449                   DEP_STATUS (dep) &= ~DEP_CANCELLED;
4450               }
4451         }
4452     }
4453 }
4454
4455 /* Undo the replacements that have occurred after backtrack point SAVE
4456    was placed.  */
4457 static void
4458 undo_replacements_for_backtrack (struct haifa_saved_data *save)
4459 {
4460   while (!save->replacement_deps.is_empty ())
4461     {
4462       dep_t dep = save->replacement_deps.pop ();
4463       int apply_p = save->replace_apply.pop ();
4464
4465       if (apply_p)
4466         restore_pattern (dep, true);
4467       else
4468         apply_replacement (dep, true);
4469     }
4470   save->replacement_deps.release ();
4471   save->replace_apply.release ();
4472 }
4473
4474 /* Pop entries from the SCHEDULED_INSNS vector up to and including INSN.
4475    Restore their dependencies to an unresolved state, and mark them as
4476    queued nowhere.  */
4477
4478 static void
4479 unschedule_insns_until (rtx insn)
4480 {
4481   auto_vec<rtx_insn *> recompute_vec;
4482
4483   /* Make two passes over the insns to be unscheduled.  First, we clear out
4484      dependencies and other trivial bookkeeping.  */
4485   for (;;)
4486     {
4487       rtx_insn *last;
4488       sd_iterator_def sd_it;
4489       dep_t dep;
4490
4491       last = scheduled_insns.pop ();
4492
4493       /* This will be changed by restore_backtrack_point if the insn is in
4494          any queue.  */
4495       QUEUE_INDEX (last) = QUEUE_NOWHERE;
4496       if (last != insn)
4497         INSN_TICK (last) = INVALID_TICK;
4498
4499       if (modulo_ii > 0 && INSN_UID (last) < modulo_iter0_max_uid)
4500         modulo_insns_scheduled--;
4501
4502       for (sd_it = sd_iterator_start (last, SD_LIST_RES_FORW);
4503            sd_iterator_cond (&sd_it, &dep);)
4504         {
4505           rtx_insn *con = DEP_CON (dep);
4506           sd_unresolve_dep (sd_it);
4507           if (!MUST_RECOMPUTE_SPEC_P (con))
4508             {
4509               MUST_RECOMPUTE_SPEC_P (con) = 1;
4510               recompute_vec.safe_push (con);
4511             }
4512         }
4513
4514       if (last == insn)
4515         break;
4516     }
4517
4518   /* A second pass, to update ready and speculation status for insns
4519      depending on the unscheduled ones.  The first pass must have
4520      popped the scheduled_insns vector up to the point where we
4521      restart scheduling, as recompute_todo_spec requires it to be
4522      up-to-date.  */
4523   while (!recompute_vec.is_empty ())
4524     {
4525       rtx_insn *con;
4526
4527       con = recompute_vec.pop ();
4528       MUST_RECOMPUTE_SPEC_P (con) = 0;
4529       if (!sd_lists_empty_p (con, SD_LIST_HARD_BACK))
4530         {
4531           TODO_SPEC (con) = HARD_DEP;
4532           INSN_TICK (con) = INVALID_TICK;
4533           if (PREDICATED_PAT (con) != NULL_RTX)
4534             haifa_change_pattern (con, ORIG_PAT (con));
4535         }
4536       else if (QUEUE_INDEX (con) != QUEUE_SCHEDULED)
4537         TODO_SPEC (con) = recompute_todo_spec (con, true);
4538     }
4539 }
4540
4541 /* Restore scheduler state from the topmost entry on the backtracking queue.
4542    PSCHED_BLOCK_P points to the local data of schedule_block that we must
4543    overwrite with the saved data.
4544    The caller must already have called unschedule_insns_until.  */
4545
4546 static void
4547 restore_last_backtrack_point (struct sched_block_state *psched_block)
4548 {
4549   int i;
4550   struct haifa_saved_data *save = backtrack_queue;
4551
4552   backtrack_queue = save->next;
4553
4554   if (current_sched_info->restore_state)
4555     (*current_sched_info->restore_state) (save->fe_saved_data);
4556
4557   if (targetm.sched.alloc_sched_context)
4558     {
4559       targetm.sched.set_sched_context (save->be_saved_data);
4560       targetm.sched.free_sched_context (save->be_saved_data);
4561     }
4562
4563   /* Do this first since it clobbers INSN_TICK of the involved
4564      instructions.  */
4565   undo_replacements_for_backtrack (save);
4566
4567   /* Clear the QUEUE_INDEX of everything in the ready list or one
4568      of the queues.  */
4569   if (ready.n_ready > 0)
4570     {
4571       rtx_insn **first = ready_lastpos (&ready);
4572       for (i = 0; i < ready.n_ready; i++)
4573         {
4574           rtx_insn *insn = first[i];
4575           QUEUE_INDEX (insn) = QUEUE_NOWHERE;
4576           INSN_TICK (insn) = INVALID_TICK;
4577         }
4578     }
4579   for (i = 0; i <= max_insn_queue_index; i++)
4580     {
4581       int q = NEXT_Q_AFTER (q_ptr, i);
4582
4583       for (rtx_insn_list *link = insn_queue[q]; link; link = link->next ())
4584         {
4585           rtx_insn *x = link->insn ();
4586           QUEUE_INDEX (x) = QUEUE_NOWHERE;
4587           INSN_TICK (x) = INVALID_TICK;
4588         }
4589       free_INSN_LIST_list (&insn_queue[q]);
4590     }
4591
4592   free (ready.vec);
4593   ready = save->ready;
4594
4595   if (ready.n_ready > 0)
4596     {
4597       rtx_insn **first = ready_lastpos (&ready);
4598       for (i = 0; i < ready.n_ready; i++)
4599         {
4600           rtx_insn *insn = first[i];
4601           QUEUE_INDEX (insn) = QUEUE_READY;
4602           TODO_SPEC (insn) = recompute_todo_spec (insn, true);
4603           INSN_TICK (insn) = save->clock_var;
4604         }
4605     }
4606
4607   q_ptr = 0;
4608   q_size = save->q_size;
4609   for (i = 0; i <= max_insn_queue_index; i++)
4610     {
4611       int q = NEXT_Q_AFTER (q_ptr, i);
4612
4613       insn_queue[q] = save->insn_queue[q];
4614
4615       for (rtx_insn_list *link = insn_queue[q]; link; link = link->next ())
4616         {
4617           rtx_insn *x = link->insn ();
4618           QUEUE_INDEX (x) = i;
4619           TODO_SPEC (x) = recompute_todo_spec (x, true);
4620           INSN_TICK (x) = save->clock_var + i;
4621         }
4622     }
4623   free (save->insn_queue);
4624
4625   toggle_cancelled_flags (true);
4626
4627   clock_var = save->clock_var;
4628   last_clock_var = save->last_clock_var;
4629   cycle_issued_insns = save->cycle_issued_insns;
4630   last_scheduled_insn = save->last_scheduled_insn;
4631   last_nondebug_scheduled_insn = save->last_nondebug_scheduled_insn;
4632   nonscheduled_insns_begin = save->nonscheduled_insns_begin;
4633
4634   *psched_block = save->sched_block;
4635
4636   memcpy (curr_state, save->curr_state, dfa_state_size);
4637   free (save->curr_state);
4638
4639   mark_backtrack_feeds (save->delay_pair->i2, 0);
4640
4641   gcc_assert (next_cycle_replace_deps.is_empty ());
4642   next_cycle_replace_deps = save->next_cycle_deps.copy ();
4643   next_cycle_apply = save->next_cycle_apply.copy ();
4644
4645   free (save);
4646
4647   for (save = backtrack_queue; save; save = save->next)
4648     {
4649       mark_backtrack_feeds (save->delay_pair->i2, 1);
4650     }
4651 }
4652
4653 /* Discard all data associated with the topmost entry in the backtrack
4654    queue.  If RESET_TICK is false, we just want to free the data.  If true,
4655    we are doing this because we discovered a reason to backtrack.  In the
4656    latter case, also reset the INSN_TICK for the shadow insn.  */
4657 static void
4658 free_topmost_backtrack_point (bool reset_tick)
4659 {
4660   struct haifa_saved_data *save = backtrack_queue;
4661   int i;
4662
4663   backtrack_queue = save->next;
4664
4665   if (reset_tick)
4666     {
4667       struct delay_pair *pair = save->delay_pair;
4668       while (pair)
4669         {
4670           INSN_TICK (pair->i2) = INVALID_TICK;
4671           INSN_EXACT_TICK (pair->i2) = INVALID_TICK;
4672           pair = pair->next_same_i1;
4673         }
4674       undo_replacements_for_backtrack (save);
4675     }
4676   else
4677     {
4678       save->replacement_deps.release ();
4679       save->replace_apply.release ();
4680     }
4681
4682   if (targetm.sched.free_sched_context)
4683     targetm.sched.free_sched_context (save->be_saved_data);
4684   if (current_sched_info->restore_state)
4685     free (save->fe_saved_data);
4686   for (i = 0; i <= max_insn_queue_index; i++)
4687     free_INSN_LIST_list (&save->insn_queue[i]);
4688   free (save->insn_queue);
4689   free (save->curr_state);
4690   free (save->ready.vec);
4691   free (save);
4692 }
4693
4694 /* Free the entire backtrack queue.  */
4695 static void
4696 free_backtrack_queue (void)
4697 {
4698   while (backtrack_queue)
4699     free_topmost_backtrack_point (false);
4700 }
4701
4702 /* Apply a replacement described by DESC.  If IMMEDIATELY is false, we
4703    may have to postpone the replacement until the start of the next cycle,
4704    at which point we will be called again with IMMEDIATELY true.  This is
4705    only done for machines which have instruction packets with explicit
4706    parallelism however.  */
4707 static void
4708 apply_replacement (dep_t dep, bool immediately)
4709 {
4710   struct dep_replacement *desc = DEP_REPLACE (dep);
4711   if (!immediately && targetm.sched.exposed_pipeline && reload_completed)
4712     {
4713       next_cycle_replace_deps.safe_push (dep);
4714       next_cycle_apply.safe_push (1);
4715     }
4716   else
4717     {
4718       bool success;
4719
4720       if (QUEUE_INDEX (desc->insn) == QUEUE_SCHEDULED)
4721         return;
4722
4723       if (sched_verbose >= 5)
4724         fprintf (sched_dump, "applying replacement for insn %d\n",
4725                  INSN_UID (desc->insn));
4726
4727       success = validate_change (desc->insn, desc->loc, desc->newval, 0);
4728       gcc_assert (success);
4729
4730       update_insn_after_change (desc->insn);
4731       if ((TODO_SPEC (desc->insn) & (HARD_DEP | DEP_POSTPONED)) == 0)
4732         fix_tick_ready (desc->insn);
4733
4734       if (backtrack_queue != NULL)
4735         {
4736           backtrack_queue->replacement_deps.safe_push (dep);
4737           backtrack_queue->replace_apply.safe_push (1);
4738         }
4739     }
4740 }
4741
4742 /* We have determined that a pattern involved in DEP must be restored.
4743    If IMMEDIATELY is false, we may have to postpone the replacement
4744    until the start of the next cycle, at which point we will be called
4745    again with IMMEDIATELY true.  */
4746 static void
4747 restore_pattern (dep_t dep, bool immediately)
4748 {
4749   rtx_insn *next = DEP_CON (dep);
4750   int tick = INSN_TICK (next);
4751
4752   /* If we already scheduled the insn, the modified version is
4753      correct.  */
4754   if (QUEUE_INDEX (next) == QUEUE_SCHEDULED)
4755     return;
4756
4757   if (!immediately && targetm.sched.exposed_pipeline && reload_completed)
4758     {
4759       next_cycle_replace_deps.safe_push (dep);
4760       next_cycle_apply.safe_push (0);
4761       return;
4762     }
4763
4764
4765   if (DEP_TYPE (dep) == REG_DEP_CONTROL)
4766     {
4767       if (sched_verbose >= 5)
4768         fprintf (sched_dump, "restoring pattern for insn %d\n",
4769                  INSN_UID (next));
4770       haifa_change_pattern (next, ORIG_PAT (next));
4771     }
4772   else
4773     {
4774       struct dep_replacement *desc = DEP_REPLACE (dep);
4775       bool success;
4776
4777       if (sched_verbose >= 5)
4778         fprintf (sched_dump, "restoring pattern for insn %d\n",
4779                  INSN_UID (desc->insn));
4780       tick = INSN_TICK (desc->insn);
4781
4782       success = validate_change (desc->insn, desc->loc, desc->orig, 0);
4783       gcc_assert (success);
4784       update_insn_after_change (desc->insn);
4785       if (backtrack_queue != NULL)
4786         {
4787           backtrack_queue->replacement_deps.safe_push (dep);
4788           backtrack_queue->replace_apply.safe_push (0);
4789         }
4790     }
4791   INSN_TICK (next) = tick;
4792   if (TODO_SPEC (next) == DEP_POSTPONED)
4793     return;
4794
4795   if (sd_lists_empty_p (next, SD_LIST_BACK))
4796     TODO_SPEC (next) = 0;
4797   else if (!sd_lists_empty_p (next, SD_LIST_HARD_BACK))
4798     TODO_SPEC (next) = HARD_DEP;
4799 }
4800
4801 /* Perform pattern replacements that were queued up until the next
4802    cycle.  */
4803 static void
4804 perform_replacements_new_cycle (void)
4805 {
4806   int i;
4807   dep_t dep;
4808   FOR_EACH_VEC_ELT (next_cycle_replace_deps, i, dep)
4809     {
4810       int apply_p = next_cycle_apply[i];
4811       if (apply_p)
4812         apply_replacement (dep, true);
4813       else
4814         restore_pattern (dep, true);
4815     }
4816   next_cycle_replace_deps.truncate (0);
4817   next_cycle_apply.truncate (0);
4818 }
4819
4820 /* Compute INSN_TICK_ESTIMATE for INSN.  PROCESSED is a bitmap of
4821    instructions we've previously encountered, a set bit prevents
4822    recursion.  BUDGET is a limit on how far ahead we look, it is
4823    reduced on recursive calls.  Return true if we produced a good
4824    estimate, or false if we exceeded the budget.  */
4825 static bool
4826 estimate_insn_tick (bitmap processed, rtx_insn *insn, int budget)
4827 {
4828   sd_iterator_def sd_it;
4829   dep_t dep;
4830   int earliest = INSN_TICK (insn);
4831
4832   FOR_EACH_DEP (insn, SD_LIST_BACK, sd_it, dep)
4833     {
4834       rtx_insn *pro = DEP_PRO (dep);
4835       int t;
4836
4837       if (DEP_STATUS (dep) & DEP_CANCELLED)
4838         continue;
4839
4840       if (QUEUE_INDEX (pro) == QUEUE_SCHEDULED)
4841         gcc_assert (INSN_TICK (pro) + dep_cost (dep) <= INSN_TICK (insn));
4842       else
4843         {
4844           int cost = dep_cost (dep);
4845           if (cost >= budget)
4846             return false;
4847           if (!bitmap_bit_p (processed, INSN_LUID (pro)))
4848             {
4849               if (!estimate_insn_tick (processed, pro, budget - cost))
4850                 return false;
4851             }
4852           gcc_assert (INSN_TICK_ESTIMATE (pro) != INVALID_TICK);
4853           t = INSN_TICK_ESTIMATE (pro) + cost;
4854           if (earliest == INVALID_TICK || t > earliest)
4855             earliest = t;
4856         }
4857     }
4858   bitmap_set_bit (processed, INSN_LUID (insn));
4859   INSN_TICK_ESTIMATE (insn) = earliest;
4860   return true;
4861 }
4862
4863 /* Examine the pair of insns in P, and estimate (optimistically, assuming
4864    infinite resources) the cycle in which the delayed shadow can be issued.
4865    Return the number of cycles that must pass before the real insn can be
4866    issued in order to meet this constraint.  */
4867 static int
4868 estimate_shadow_tick (struct delay_pair *p)
4869 {
4870   bitmap_head processed;
4871   int t;
4872   bool cutoff;
4873   bitmap_initialize (&processed, 0);
4874
4875   cutoff = !estimate_insn_tick (&processed, p->i2,
4876                                 max_insn_queue_index + pair_delay (p));
4877   bitmap_clear (&processed);
4878   if (cutoff)
4879     return max_insn_queue_index;
4880   t = INSN_TICK_ESTIMATE (p->i2) - (clock_var + pair_delay (p) + 1);
4881   if (t > 0)
4882     return t;
4883   return 0;
4884 }
4885
4886 /* If INSN has no unresolved backwards dependencies, add it to the schedule and
4887    recursively resolve all its forward dependencies.  */
4888 static void
4889 resolve_dependencies (rtx_insn *insn)
4890 {
4891   sd_iterator_def sd_it;
4892   dep_t dep;
4893
4894   /* Don't use sd_lists_empty_p; it ignores debug insns.  */
4895   if (DEPS_LIST_FIRST (INSN_HARD_BACK_DEPS (insn)) != NULL
4896       || DEPS_LIST_FIRST (INSN_SPEC_BACK_DEPS (insn)) != NULL)
4897     return;
4898
4899   if (sched_verbose >= 4)
4900     fprintf (sched_dump, ";;\tquickly resolving %d\n", INSN_UID (insn));
4901
4902   if (QUEUE_INDEX (insn) >= 0)
4903     queue_remove (insn);
4904
4905   scheduled_insns.safe_push (insn);
4906
4907   /* Update dependent instructions.  */
4908   for (sd_it = sd_iterator_start (insn, SD_LIST_FORW);
4909        sd_iterator_cond (&sd_it, &dep);)
4910     {
4911       rtx_insn *next = DEP_CON (dep);
4912
4913       if (sched_verbose >= 4)
4914         fprintf (sched_dump, ";;\t\tdep %d against %d\n", INSN_UID (insn),
4915                  INSN_UID (next));
4916
4917       /* Resolve the dependence between INSN and NEXT.
4918          sd_resolve_dep () moves current dep to another list thus
4919          advancing the iterator.  */
4920       sd_resolve_dep (sd_it);
4921
4922       if (!IS_SPECULATION_BRANCHY_CHECK_P (insn))
4923         {
4924           resolve_dependencies (next);
4925         }
4926       else
4927         /* Check always has only one forward dependence (to the first insn in
4928            the recovery block), therefore, this will be executed only once.  */
4929         {
4930           gcc_assert (sd_lists_empty_p (insn, SD_LIST_FORW));
4931         }
4932     }
4933 }
4934
4935
4936 /* Return the head and tail pointers of ebb starting at BEG and ending
4937    at END.  */
4938 void
4939 get_ebb_head_tail (basic_block beg, basic_block end,
4940                    rtx_insn **headp, rtx_insn **tailp)
4941 {
4942   rtx_insn *beg_head = BB_HEAD (beg);
4943   rtx_insn * beg_tail = BB_END (beg);
4944   rtx_insn * end_head = BB_HEAD (end);
4945   rtx_insn * end_tail = BB_END (end);
4946
4947   /* Don't include any notes or labels at the beginning of the BEG
4948      basic block, or notes at the end of the END basic blocks.  */
4949
4950   if (LABEL_P (beg_head))
4951     beg_head = NEXT_INSN (beg_head);
4952
4953   while (beg_head != beg_tail)
4954     if (NOTE_P (beg_head))
4955       beg_head = NEXT_INSN (beg_head);
4956     else if (DEBUG_INSN_P (beg_head))
4957       {
4958         rtx_insn * note, *next;
4959
4960         for (note = NEXT_INSN (beg_head);
4961              note != beg_tail;
4962              note = next)
4963           {
4964             next = NEXT_INSN (note);
4965             if (NOTE_P (note))
4966               {
4967                 if (sched_verbose >= 9)
4968                   fprintf (sched_dump, "reorder %i\n", INSN_UID (note));
4969
4970                 reorder_insns_nobb (note, note, PREV_INSN (beg_head));
4971
4972                 if (BLOCK_FOR_INSN (note) != beg)
4973                   df_insn_change_bb (note, beg);
4974               }
4975             else if (!DEBUG_INSN_P (note))
4976               break;
4977           }
4978
4979         break;
4980       }
4981     else
4982       break;
4983
4984   *headp = beg_head;
4985
4986   if (beg == end)
4987     end_head = beg_head;
4988   else if (LABEL_P (end_head))
4989     end_head = NEXT_INSN (end_head);
4990
4991   while (end_head != end_tail)
4992     if (NOTE_P (end_tail))
4993       end_tail = PREV_INSN (end_tail);
4994     else if (DEBUG_INSN_P (end_tail))
4995       {
4996         rtx_insn * note, *prev;
4997
4998         for (note = PREV_INSN (end_tail);
4999              note != end_head;
5000              note = prev)
5001           {
5002             prev = PREV_INSN (note);
5003             if (NOTE_P (note))
5004               {
5005                 if (sched_verbose >= 9)
5006                   fprintf (sched_dump, "reorder %i\n", INSN_UID (note));
5007
5008                 reorder_insns_nobb (note, note, end_tail);
5009
5010                 if (end_tail == BB_END (end))
5011                   BB_END (end) = note;
5012
5013                 if (BLOCK_FOR_INSN (note) != end)
5014                   df_insn_change_bb (note, end);
5015               }
5016             else if (!DEBUG_INSN_P (note))
5017               break;
5018           }
5019
5020         break;
5021       }
5022     else
5023       break;
5024
5025   *tailp = end_tail;
5026 }
5027
5028 /* Return nonzero if there are no real insns in the range [ HEAD, TAIL ].  */
5029
5030 int
5031 no_real_insns_p (const rtx_insn *head, const rtx_insn *tail)
5032 {
5033   while (head != NEXT_INSN (tail))
5034     {
5035       if (!NOTE_P (head) && !LABEL_P (head))
5036         return 0;
5037       head = NEXT_INSN (head);
5038     }
5039   return 1;
5040 }
5041
5042 /* Restore-other-notes: NOTE_LIST is the end of a chain of notes
5043    previously found among the insns.  Insert them just before HEAD.  */
5044 rtx_insn *
5045 restore_other_notes (rtx_insn *head, basic_block head_bb)
5046 {
5047   if (note_list != 0)
5048     {
5049       rtx_insn *note_head = note_list;
5050
5051       if (head)
5052         head_bb = BLOCK_FOR_INSN (head);
5053       else
5054         head = NEXT_INSN (bb_note (head_bb));
5055
5056       while (PREV_INSN (note_head))
5057         {
5058           set_block_for_insn (note_head, head_bb);
5059           note_head = PREV_INSN (note_head);
5060         }
5061       /* In the above cycle we've missed this note.  */
5062       set_block_for_insn (note_head, head_bb);
5063
5064       SET_PREV_INSN (note_head) = PREV_INSN (head);
5065       SET_NEXT_INSN (PREV_INSN (head)) = note_head;
5066       SET_PREV_INSN (head) = note_list;
5067       SET_NEXT_INSN (note_list) = head;
5068
5069       if (BLOCK_FOR_INSN (head) != head_bb)
5070         BB_END (head_bb) = note_list;
5071
5072       head = note_head;
5073     }
5074
5075   return head;
5076 }
5077
5078 /* When we know we are going to discard the schedule due to a failed attempt
5079    at modulo scheduling, undo all replacements.  */
5080 static void
5081 undo_all_replacements (void)
5082 {
5083   rtx_insn *insn;
5084   int i;
5085
5086   FOR_EACH_VEC_ELT (scheduled_insns, i, insn)
5087     {
5088       sd_iterator_def sd_it;
5089       dep_t dep;
5090
5091       /* See if we must undo a replacement.  */
5092       for (sd_it = sd_iterator_start (insn, SD_LIST_RES_FORW);
5093            sd_iterator_cond (&sd_it, &dep); sd_iterator_next (&sd_it))
5094         {
5095           struct dep_replacement *desc = DEP_REPLACE (dep);
5096           if (desc != NULL)
5097             validate_change (desc->insn, desc->loc, desc->orig, 0);
5098         }
5099     }
5100 }
5101
5102 /* Return first non-scheduled insn in the current scheduling block.
5103    This is mostly used for debug-counter purposes.  */
5104 static rtx_insn *
5105 first_nonscheduled_insn (void)
5106 {
5107   rtx_insn *insn = (nonscheduled_insns_begin != NULL_RTX
5108                     ? nonscheduled_insns_begin
5109                     : current_sched_info->prev_head);
5110
5111   do
5112     {
5113       insn = next_nonnote_nondebug_insn (insn);
5114     }
5115   while (QUEUE_INDEX (insn) == QUEUE_SCHEDULED);
5116
5117   return insn;
5118 }
5119
5120 /* Move insns that became ready to fire from queue to ready list.  */
5121
5122 static void
5123 queue_to_ready (struct ready_list *ready)
5124 {
5125   rtx_insn *insn;
5126   rtx_insn_list *link;
5127   rtx skip_insn;
5128
5129   q_ptr = NEXT_Q (q_ptr);
5130
5131   if (dbg_cnt (sched_insn) == false)
5132     /* If debug counter is activated do not requeue the first
5133        nonscheduled insn.  */
5134     skip_insn = first_nonscheduled_insn ();
5135   else
5136     skip_insn = NULL_RTX;
5137
5138   /* Add all pending insns that can be scheduled without stalls to the
5139      ready list.  */
5140   for (link = insn_queue[q_ptr]; link; link = link->next ())
5141     {
5142       insn = link->insn ();
5143       q_size -= 1;
5144
5145       if (sched_verbose >= 2)
5146         fprintf (sched_dump, ";;\t\tQ-->Ready: insn %s: ",
5147                  (*current_sched_info->print_insn) (insn, 0));
5148
5149       /* If the ready list is full, delay the insn for 1 cycle.
5150          See the comment in schedule_block for the rationale.  */
5151       if (!reload_completed
5152           && (ready->n_ready - ready->n_debug > MAX_SCHED_READY_INSNS
5153               || (sched_pressure == SCHED_PRESSURE_MODEL
5154                   /* Limit pressure recalculations to MAX_SCHED_READY_INSNS
5155                      instructions too.  */
5156                   && model_index (insn) > (model_curr_point
5157                                            + MAX_SCHED_READY_INSNS)))
5158           && !(sched_pressure == SCHED_PRESSURE_MODEL
5159                && model_curr_point < model_num_insns
5160                /* Always allow the next model instruction to issue.  */
5161                && model_index (insn) == model_curr_point)
5162           && !SCHED_GROUP_P (insn)
5163           && insn != skip_insn)
5164         {
5165           if (sched_verbose >= 2)
5166             fprintf (sched_dump, "keeping in queue, ready full\n");
5167           queue_insn (insn, 1, "ready full");
5168         }
5169       else
5170         {
5171           ready_add (ready, insn, false);
5172           if (sched_verbose >= 2)
5173             fprintf (sched_dump, "moving to ready without stalls\n");
5174         }
5175     }
5176   free_INSN_LIST_list (&insn_queue[q_ptr]);
5177
5178   /* If there are no ready insns, stall until one is ready and add all
5179      of the pending insns at that point to the ready list.  */
5180   if (ready->n_ready == 0)
5181     {
5182       int stalls;
5183
5184       for (stalls = 1; stalls <= max_insn_queue_index; stalls++)
5185         {
5186           if ((link = insn_queue[NEXT_Q_AFTER (q_ptr, stalls)]))
5187             {
5188               for (; link; link = link->next ())
5189                 {
5190                   insn = link->insn ();
5191                   q_size -= 1;
5192
5193                   if (sched_verbose >= 2)
5194                     fprintf (sched_dump, ";;\t\tQ-->Ready: insn %s: ",
5195                              (*current_sched_info->print_insn) (insn, 0));
5196
5197                   ready_add (ready, insn, false);
5198                   if (sched_verbose >= 2)
5199                     fprintf (sched_dump, "moving to ready with %d stalls\n", stalls);
5200                 }
5201               free_INSN_LIST_list (&insn_queue[NEXT_Q_AFTER (q_ptr, stalls)]);
5202
5203               advance_one_cycle ();
5204
5205               break;
5206             }
5207
5208           advance_one_cycle ();
5209         }
5210
5211       q_ptr = NEXT_Q_AFTER (q_ptr, stalls);
5212       clock_var += stalls;
5213       if (sched_verbose >= 2)
5214         fprintf (sched_dump, ";;\tAdvancing clock by %d cycle[s] to %d\n",
5215                  stalls, clock_var);
5216     }
5217 }
5218
5219 /* Used by early_queue_to_ready.  Determines whether it is "ok" to
5220    prematurely move INSN from the queue to the ready list.  Currently,
5221    if a target defines the hook 'is_costly_dependence', this function
5222    uses the hook to check whether there exist any dependences which are
5223    considered costly by the target, between INSN and other insns that
5224    have already been scheduled.  Dependences are checked up to Y cycles
5225    back, with default Y=1; The flag -fsched-stalled-insns-dep=Y allows
5226    controlling this value.
5227    (Other considerations could be taken into account instead (or in
5228    addition) depending on user flags and target hooks.  */
5229
5230 static bool
5231 ok_for_early_queue_removal (rtx insn)
5232 {
5233   if (targetm.sched.is_costly_dependence)
5234     {
5235       rtx prev_insn;
5236       int n_cycles;
5237       int i = scheduled_insns.length ();
5238       for (n_cycles = flag_sched_stalled_insns_dep; n_cycles; n_cycles--)
5239         {
5240           while (i-- > 0)
5241             {
5242               int cost;
5243
5244               prev_insn = scheduled_insns[i];
5245
5246               if (!NOTE_P (prev_insn))
5247                 {
5248                   dep_t dep;
5249
5250                   dep = sd_find_dep_between (prev_insn, insn, true);
5251
5252                   if (dep != NULL)
5253                     {
5254                       cost = dep_cost (dep);
5255
5256                       if (targetm.sched.is_costly_dependence (dep, cost,
5257                                 flag_sched_stalled_insns_dep - n_cycles))
5258                         return false;
5259                     }
5260                 }
5261
5262               if (GET_MODE (prev_insn) == TImode) /* end of dispatch group */
5263                 break;
5264             }
5265
5266           if (i == 0)
5267             break;
5268         }
5269     }
5270
5271   return true;
5272 }
5273
5274
5275 /* Remove insns from the queue, before they become "ready" with respect
5276    to FU latency considerations.  */
5277
5278 static int
5279 early_queue_to_ready (state_t state, struct ready_list *ready)
5280 {
5281   rtx_insn *insn;
5282   rtx_insn_list *link;
5283   rtx_insn_list *next_link;
5284   rtx_insn_list *prev_link;
5285   bool move_to_ready;
5286   int cost;
5287   state_t temp_state = alloca (dfa_state_size);
5288   int stalls;
5289   int insns_removed = 0;
5290
5291   /*
5292      Flag '-fsched-stalled-insns=X' determines the aggressiveness of this
5293      function:
5294
5295      X == 0: There is no limit on how many queued insns can be removed
5296              prematurely.  (flag_sched_stalled_insns = -1).
5297
5298      X >= 1: Only X queued insns can be removed prematurely in each
5299              invocation.  (flag_sched_stalled_insns = X).
5300
5301      Otherwise: Early queue removal is disabled.
5302          (flag_sched_stalled_insns = 0)
5303   */
5304
5305   if (! flag_sched_stalled_insns)
5306     return 0;
5307
5308   for (stalls = 0; stalls <= max_insn_queue_index; stalls++)
5309     {
5310       if ((link = insn_queue[NEXT_Q_AFTER (q_ptr, stalls)]))
5311         {
5312           if (sched_verbose > 6)
5313             fprintf (sched_dump, ";; look at index %d + %d\n", q_ptr, stalls);
5314
5315           prev_link = 0;
5316           while (link)
5317             {
5318               next_link = link->next ();
5319               insn = link->insn ();
5320               if (insn && sched_verbose > 6)
5321                 print_rtl_single (sched_dump, insn);
5322
5323               memcpy (temp_state, state, dfa_state_size);
5324               if (recog_memoized (insn) < 0)
5325                 /* non-negative to indicate that it's not ready
5326                    to avoid infinite Q->R->Q->R... */
5327                 cost = 0;
5328               else
5329                 cost = state_transition (temp_state, insn);
5330
5331               if (sched_verbose >= 6)
5332                 fprintf (sched_dump, "transition cost = %d\n", cost);
5333
5334               move_to_ready = false;
5335               if (cost < 0)
5336                 {
5337                   move_to_ready = ok_for_early_queue_removal (insn);
5338                   if (move_to_ready == true)
5339                     {
5340                       /* move from Q to R */
5341                       q_size -= 1;
5342                       ready_add (ready, insn, false);
5343
5344                       if (prev_link)
5345                         XEXP (prev_link, 1) = next_link;
5346                       else
5347                         insn_queue[NEXT_Q_AFTER (q_ptr, stalls)] = next_link;
5348
5349                       free_INSN_LIST_node (link);
5350
5351                       if (sched_verbose >= 2)
5352                         fprintf (sched_dump, ";;\t\tEarly Q-->Ready: insn %s\n",
5353                                  (*current_sched_info->print_insn) (insn, 0));
5354
5355                       insns_removed++;
5356                       if (insns_removed == flag_sched_stalled_insns)
5357                         /* Remove no more than flag_sched_stalled_insns insns
5358                            from Q at a time.  */
5359                         return insns_removed;
5360                     }
5361                 }
5362
5363               if (move_to_ready == false)
5364                 prev_link = link;
5365
5366               link = next_link;
5367             } /* while link */
5368         } /* if link */
5369
5370     } /* for stalls.. */
5371
5372   return insns_removed;
5373 }
5374
5375
5376 /* Print the ready list for debugging purposes.
5377    If READY_TRY is non-zero then only print insns that max_issue
5378    will consider.  */
5379 static void
5380 debug_ready_list_1 (struct ready_list *ready, signed char *ready_try)
5381 {
5382   rtx_insn **p;
5383   int i;
5384
5385   if (ready->n_ready == 0)
5386     {
5387       fprintf (sched_dump, "\n");
5388       return;
5389     }
5390
5391   p = ready_lastpos (ready);
5392   for (i = 0; i < ready->n_ready; i++)
5393     {
5394       if (ready_try != NULL && ready_try[ready->n_ready - i - 1])
5395         continue;
5396
5397       fprintf (sched_dump, "  %s:%d",
5398                (*current_sched_info->print_insn) (p[i], 0),
5399                INSN_LUID (p[i]));
5400       if (sched_pressure != SCHED_PRESSURE_NONE)
5401         fprintf (sched_dump, "(cost=%d",
5402                  INSN_REG_PRESSURE_EXCESS_COST_CHANGE (p[i]));
5403       fprintf (sched_dump, ":prio=%d", INSN_PRIORITY (p[i]));
5404       if (INSN_TICK (p[i]) > clock_var)
5405         fprintf (sched_dump, ":delay=%d", INSN_TICK (p[i]) - clock_var);
5406       if (sched_pressure == SCHED_PRESSURE_MODEL)
5407         fprintf (sched_dump, ":idx=%d",
5408                  model_index (p[i]));
5409       if (sched_pressure != SCHED_PRESSURE_NONE)
5410         fprintf (sched_dump, ")");
5411     }
5412   fprintf (sched_dump, "\n");
5413 }
5414
5415 /* Print the ready list.  Callable from debugger.  */
5416 static void
5417 debug_ready_list (struct ready_list *ready)
5418 {
5419   debug_ready_list_1 (ready, NULL);
5420 }
5421
5422 /* Search INSN for REG_SAVE_NOTE notes and convert them back into insn
5423    NOTEs.  This is used for NOTE_INSN_EPILOGUE_BEG, so that sched-ebb
5424    replaces the epilogue note in the correct basic block.  */
5425 void
5426 reemit_notes (rtx_insn *insn)
5427 {
5428   rtx note;
5429   rtx_insn *last = insn;
5430
5431   for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
5432     {
5433       if (REG_NOTE_KIND (note) == REG_SAVE_NOTE)
5434         {
5435           enum insn_note note_type = (enum insn_note) INTVAL (XEXP (note, 0));
5436
5437           last = emit_note_before (note_type, last);
5438           remove_note (insn, note);
5439         }
5440     }
5441 }
5442
5443 /* Move INSN.  Reemit notes if needed.  Update CFG, if needed.  */
5444 static void
5445 move_insn (rtx_insn *insn, rtx_insn *last, rtx nt)
5446 {
5447   if (PREV_INSN (insn) != last)
5448     {
5449       basic_block bb;
5450       rtx_insn *note;
5451       int jump_p = 0;
5452
5453       bb = BLOCK_FOR_INSN (insn);
5454
5455       /* BB_HEAD is either LABEL or NOTE.  */
5456       gcc_assert (BB_HEAD (bb) != insn);
5457
5458       if (BB_END (bb) == insn)
5459         /* If this is last instruction in BB, move end marker one
5460            instruction up.  */
5461         {
5462           /* Jumps are always placed at the end of basic block.  */
5463           jump_p = control_flow_insn_p (insn);
5464
5465           gcc_assert (!jump_p
5466                       || ((common_sched_info->sched_pass_id == SCHED_RGN_PASS)
5467                           && IS_SPECULATION_BRANCHY_CHECK_P (insn))
5468                       || (common_sched_info->sched_pass_id
5469                           == SCHED_EBB_PASS));
5470
5471           gcc_assert (BLOCK_FOR_INSN (PREV_INSN (insn)) == bb);
5472
5473           BB_END (bb) = PREV_INSN (insn);
5474         }
5475
5476       gcc_assert (BB_END (bb) != last);
5477
5478       if (jump_p)
5479         /* We move the block note along with jump.  */
5480         {
5481           gcc_assert (nt);
5482
5483           note = NEXT_INSN (insn);
5484           while (NOTE_NOT_BB_P (note) && note != nt)
5485             note = NEXT_INSN (note);
5486
5487           if (note != nt
5488               && (LABEL_P (note)
5489                   || BARRIER_P (note)))
5490             note = NEXT_INSN (note);
5491
5492           gcc_assert (NOTE_INSN_BASIC_BLOCK_P (note));
5493         }
5494       else
5495         note = insn;
5496
5497       SET_NEXT_INSN (PREV_INSN (insn)) = NEXT_INSN (note);
5498       SET_PREV_INSN (NEXT_INSN (note)) = PREV_INSN (insn);
5499
5500       SET_NEXT_INSN (note) = NEXT_INSN (last);
5501       SET_PREV_INSN (NEXT_INSN (last)) = note;
5502
5503       SET_NEXT_INSN (last) = insn;
5504       SET_PREV_INSN (insn) = last;
5505
5506       bb = BLOCK_FOR_INSN (last);
5507
5508       if (jump_p)
5509         {
5510           fix_jump_move (insn);
5511
5512           if (BLOCK_FOR_INSN (insn) != bb)
5513             move_block_after_check (insn);
5514
5515           gcc_assert (BB_END (bb) == last);
5516         }
5517
5518       df_insn_change_bb (insn, bb);
5519
5520       /* Update BB_END, if needed.  */
5521       if (BB_END (bb) == last)
5522         BB_END (bb) = insn;
5523     }
5524
5525   SCHED_GROUP_P (insn) = 0;
5526 }
5527
5528 /* Return true if scheduling INSN will finish current clock cycle.  */
5529 static bool
5530 insn_finishes_cycle_p (rtx_insn *insn)
5531 {
5532   if (SCHED_GROUP_P (insn))
5533     /* After issuing INSN, rest of the sched_group will be forced to issue
5534        in order.  Don't make any plans for the rest of cycle.  */
5535     return true;
5536
5537   /* Finishing the block will, apparently, finish the cycle.  */
5538   if (current_sched_info->insn_finishes_block_p
5539       && current_sched_info->insn_finishes_block_p (insn))
5540     return true;
5541
5542   return false;
5543 }
5544
5545 /* Functions to model cache auto-prefetcher.
5546
5547    Some of the CPUs have cache auto-prefetcher, which /seems/ to initiate
5548    memory prefetches if it sees instructions with consequitive memory accesses
5549    in the instruction stream.  Details of such hardware units are not published,
5550    so we can only guess what exactly is going on there.
5551    In the scheduler, we model abstract auto-prefetcher.  If there are memory
5552    insns in the ready list (or the queue) that have same memory base, but
5553    different offsets, then we delay the insns with larger offsets until insns
5554    with smaller offsets get scheduled.  If PARAM_SCHED_AUTOPREF_QUEUE_DEPTH
5555    is "1", then we look at the ready list; if it is N>1, then we also look
5556    through N-1 queue entries.
5557    If the param is N>=0, then rank_for_schedule will consider auto-prefetching
5558    among its heuristics.
5559    Param value of "-1" disables modelling of the auto-prefetcher.  */
5560
5561 /* Initialize autoprefetcher model data for INSN.  */
5562 static void
5563 autopref_multipass_init (const rtx_insn *insn, int write)
5564 {
5565   autopref_multipass_data_t data = &INSN_AUTOPREF_MULTIPASS_DATA (insn)[write];
5566
5567   gcc_assert (data->status == AUTOPREF_MULTIPASS_DATA_UNINITIALIZED);
5568   data->base = NULL_RTX;
5569   data->offset = 0;
5570   /* Set insn entry initialized, but not relevant for auto-prefetcher.  */
5571   data->status = AUTOPREF_MULTIPASS_DATA_IRRELEVANT;
5572
5573   rtx set = single_set (insn);
5574   if (set == NULL_RTX)
5575     return;
5576
5577   rtx mem = write ? SET_DEST (set) : SET_SRC (set);
5578   if (!MEM_P (mem))
5579     return;
5580
5581   struct address_info info;
5582   decompose_mem_address (&info, mem);
5583
5584   /* TODO: Currently only (base+const) addressing is supported.  */
5585   if (info.base == NULL || !REG_P (*info.base)
5586       || (info.disp != NULL && !CONST_INT_P (*info.disp)))
5587     return;
5588
5589   /* This insn is relevant for auto-prefetcher.  */
5590   data->base = *info.base;
5591   data->offset = info.disp ? INTVAL (*info.disp) : 0;
5592   data->status = AUTOPREF_MULTIPASS_DATA_NORMAL;
5593 }
5594
5595 /* Helper function for rank_for_schedule sorting.  */
5596 static int
5597 autopref_rank_for_schedule (const rtx_insn *insn1, const rtx_insn *insn2)
5598 {
5599   for (int write = 0; write < 2; ++write)
5600     {
5601       autopref_multipass_data_t data1
5602         = &INSN_AUTOPREF_MULTIPASS_DATA (insn1)[write];
5603       autopref_multipass_data_t data2
5604         = &INSN_AUTOPREF_MULTIPASS_DATA (insn2)[write];
5605
5606       if (data1->status == AUTOPREF_MULTIPASS_DATA_UNINITIALIZED)
5607         autopref_multipass_init (insn1, write);
5608       if (data1->status == AUTOPREF_MULTIPASS_DATA_IRRELEVANT)
5609         continue;
5610
5611       if (data2->status == AUTOPREF_MULTIPASS_DATA_UNINITIALIZED)
5612         autopref_multipass_init (insn2, write);
5613       if (data2->status == AUTOPREF_MULTIPASS_DATA_IRRELEVANT)
5614         continue;
5615
5616       if (!rtx_equal_p (data1->base, data2->base))
5617         continue;
5618
5619       return data1->offset - data2->offset;
5620     }
5621
5622   return 0;
5623 }
5624
5625 /* True if header of debug dump was printed.  */
5626 static bool autopref_multipass_dfa_lookahead_guard_started_dump_p;
5627
5628 /* Helper for autopref_multipass_dfa_lookahead_guard.
5629    Return "1" if INSN1 should be delayed in favor of INSN2.  */
5630 static int
5631 autopref_multipass_dfa_lookahead_guard_1 (const rtx_insn *insn1,
5632                                           const rtx_insn *insn2, int write)
5633 {
5634   autopref_multipass_data_t data1
5635     = &INSN_AUTOPREF_MULTIPASS_DATA (insn1)[write];
5636   autopref_multipass_data_t data2
5637     = &INSN_AUTOPREF_MULTIPASS_DATA (insn2)[write];
5638
5639   if (data2->status == AUTOPREF_MULTIPASS_DATA_UNINITIALIZED)
5640     autopref_multipass_init (insn2, write);
5641   if (data2->status == AUTOPREF_MULTIPASS_DATA_IRRELEVANT)
5642     return 0;
5643
5644   if (rtx_equal_p (data1->base, data2->base)
5645       && data1->offset > data2->offset)
5646     {
5647       if (sched_verbose >= 2)
5648         {
5649           if (!autopref_multipass_dfa_lookahead_guard_started_dump_p)
5650             {
5651               fprintf (sched_dump,
5652                        ";;\t\tnot trying in max_issue due to autoprefetch "
5653                        "model: ");
5654               autopref_multipass_dfa_lookahead_guard_started_dump_p = true;
5655             }
5656
5657           fprintf (sched_dump, " %d(%d)", INSN_UID (insn1), INSN_UID (insn2));
5658         }
5659
5660       return 1;
5661     }
5662
5663   return 0;
5664 }
5665
5666 /* General note:
5667
5668    We could have also hooked autoprefetcher model into
5669    first_cycle_multipass_backtrack / first_cycle_multipass_issue hooks
5670    to enable intelligent selection of "[r1+0]=r2; [r1+4]=r3" on the same cycle
5671    (e.g., once "[r1+0]=r2" is issued in max_issue(), "[r1+4]=r3" gets
5672    unblocked).  We don't bother about this yet because target of interest
5673    (ARM Cortex-A15) can issue only 1 memory operation per cycle.  */
5674
5675 /* Implementation of first_cycle_multipass_dfa_lookahead_guard hook.
5676    Return "1" if INSN1 should not be considered in max_issue due to
5677    auto-prefetcher considerations.  */
5678 int
5679 autopref_multipass_dfa_lookahead_guard (rtx_insn *insn1, int ready_index)
5680 {
5681   int r = 0;
5682
5683   if (PARAM_VALUE (PARAM_SCHED_AUTOPREF_QUEUE_DEPTH) <= 0)
5684     return 0;
5685
5686   if (sched_verbose >= 2 && ready_index == 0)
5687     autopref_multipass_dfa_lookahead_guard_started_dump_p = false;
5688
5689   for (int write = 0; write < 2; ++write)
5690     {
5691       autopref_multipass_data_t data1
5692         = &INSN_AUTOPREF_MULTIPASS_DATA (insn1)[write];
5693
5694       if (data1->status == AUTOPREF_MULTIPASS_DATA_UNINITIALIZED)
5695         autopref_multipass_init (insn1, write);
5696       if (data1->status == AUTOPREF_MULTIPASS_DATA_IRRELEVANT)
5697         continue;
5698
5699       if (ready_index == 0
5700           && data1->status == AUTOPREF_MULTIPASS_DATA_DONT_DELAY)
5701         /* We allow only a single delay on priviledged instructions.
5702            Doing otherwise would cause infinite loop.  */
5703         {
5704           if (sched_verbose >= 2)
5705             {
5706               if (!autopref_multipass_dfa_lookahead_guard_started_dump_p)
5707                 {
5708                   fprintf (sched_dump,
5709                            ";;\t\tnot trying in max_issue due to autoprefetch "
5710                            "model: ");
5711                   autopref_multipass_dfa_lookahead_guard_started_dump_p = true;
5712                 }
5713
5714               fprintf (sched_dump, " *%d*", INSN_UID (insn1));
5715             }
5716           continue;
5717         }
5718
5719       for (int i2 = 0; i2 < ready.n_ready; ++i2)
5720         {
5721           rtx_insn *insn2 = get_ready_element (i2);
5722           if (insn1 == insn2)
5723             continue;
5724           r = autopref_multipass_dfa_lookahead_guard_1 (insn1, insn2, write);
5725           if (r)
5726             {
5727               if (ready_index == 0)
5728                 {
5729                   r = -1;
5730                   data1->status = AUTOPREF_MULTIPASS_DATA_DONT_DELAY;
5731                 }
5732               goto finish;
5733             }
5734         }
5735
5736       if (PARAM_VALUE (PARAM_SCHED_AUTOPREF_QUEUE_DEPTH) == 1)
5737         continue;
5738
5739       /* Everything from the current queue slot should have been moved to
5740          the ready list.  */
5741       gcc_assert (insn_queue[NEXT_Q_AFTER (q_ptr, 0)] == NULL_RTX);
5742
5743       int n_stalls = PARAM_VALUE (PARAM_SCHED_AUTOPREF_QUEUE_DEPTH) - 1;
5744       if (n_stalls > max_insn_queue_index)
5745         n_stalls = max_insn_queue_index;
5746
5747       for (int stalls = 1; stalls <= n_stalls; ++stalls)
5748         {
5749           for (rtx_insn_list *link = insn_queue[NEXT_Q_AFTER (q_ptr, stalls)];
5750                link != NULL_RTX;
5751                link = link->next ())
5752             {
5753               rtx_insn *insn2 = link->insn ();
5754               r = autopref_multipass_dfa_lookahead_guard_1 (insn1, insn2,
5755                                                             write);
5756               if (r)
5757                 {
5758                   /* Queue INSN1 until INSN2 can issue.  */
5759                   r = -stalls;
5760                   if (ready_index == 0)
5761                     data1->status = AUTOPREF_MULTIPASS_DATA_DONT_DELAY;
5762                   goto finish;
5763                 }
5764             }
5765         }
5766     }
5767
5768     finish:
5769   if (sched_verbose >= 2
5770       && autopref_multipass_dfa_lookahead_guard_started_dump_p
5771       && (ready_index == ready.n_ready - 1 || r < 0))
5772     /* This does not /always/ trigger.  We don't output EOL if the last
5773        insn is not recognized (INSN_CODE < 0) and lookahead_guard is not
5774        called.  We can live with this.  */
5775     fprintf (sched_dump, "\n");
5776
5777   return r;
5778 }
5779
5780 /* Define type for target data used in multipass scheduling.  */
5781 #ifndef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DATA_T
5782 # define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DATA_T int
5783 #endif
5784 typedef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DATA_T first_cycle_multipass_data_t;
5785
5786 /* The following structure describe an entry of the stack of choices.  */
5787 struct choice_entry
5788 {
5789   /* Ordinal number of the issued insn in the ready queue.  */
5790   int index;
5791   /* The number of the rest insns whose issues we should try.  */
5792   int rest;
5793   /* The number of issued essential insns.  */
5794   int n;
5795   /* State after issuing the insn.  */
5796   state_t state;
5797   /* Target-specific data.  */
5798   first_cycle_multipass_data_t target_data;
5799 };
5800
5801 /* The following array is used to implement a stack of choices used in
5802    function max_issue.  */
5803 static struct choice_entry *choice_stack;
5804
5805 /* This holds the value of the target dfa_lookahead hook.  */
5806 int dfa_lookahead;
5807
5808 /* The following variable value is maximal number of tries of issuing
5809    insns for the first cycle multipass insn scheduling.  We define
5810    this value as constant*(DFA_LOOKAHEAD**ISSUE_RATE).  We would not
5811    need this constraint if all real insns (with non-negative codes)
5812    had reservations because in this case the algorithm complexity is
5813    O(DFA_LOOKAHEAD**ISSUE_RATE).  Unfortunately, the dfa descriptions
5814    might be incomplete and such insn might occur.  For such
5815    descriptions, the complexity of algorithm (without the constraint)
5816    could achieve DFA_LOOKAHEAD ** N , where N is the queue length.  */
5817 static int max_lookahead_tries;
5818
5819 /* The following function returns maximal (or close to maximal) number
5820    of insns which can be issued on the same cycle and one of which
5821    insns is insns with the best rank (the first insn in READY).  To
5822    make this function tries different samples of ready insns.  READY
5823    is current queue `ready'.  Global array READY_TRY reflects what
5824    insns are already issued in this try.  The function stops immediately,
5825    if it reached the such a solution, that all instruction can be issued.
5826    INDEX will contain index of the best insn in READY.  The following
5827    function is used only for first cycle multipass scheduling.
5828
5829    PRIVILEGED_N >= 0
5830
5831    This function expects recognized insns only.  All USEs,
5832    CLOBBERs, etc must be filtered elsewhere.  */
5833 int
5834 max_issue (struct ready_list *ready, int privileged_n, state_t state,
5835            bool first_cycle_insn_p, int *index)
5836 {
5837   int n, i, all, n_ready, best, delay, tries_num;
5838   int more_issue;
5839   struct choice_entry *top;
5840   rtx_insn *insn;
5841
5842   if (sched_fusion)
5843     return 0;
5844
5845   n_ready = ready->n_ready;
5846   gcc_assert (dfa_lookahead >= 1 && privileged_n >= 0
5847               && privileged_n <= n_ready);
5848
5849   /* Init MAX_LOOKAHEAD_TRIES.  */
5850   if (max_lookahead_tries == 0)
5851     {
5852       max_lookahead_tries = 100;
5853       for (i = 0; i < issue_rate; i++)
5854         max_lookahead_tries *= dfa_lookahead;
5855     }
5856
5857   /* Init max_points.  */
5858   more_issue = issue_rate - cycle_issued_insns;
5859   gcc_assert (more_issue >= 0);
5860
5861   /* The number of the issued insns in the best solution.  */
5862   best = 0;
5863
5864   top = choice_stack;
5865
5866   /* Set initial state of the search.  */
5867   memcpy (top->state, state, dfa_state_size);
5868   top->rest = dfa_lookahead;
5869   top->n = 0;
5870   if (targetm.sched.first_cycle_multipass_begin)
5871     targetm.sched.first_cycle_multipass_begin (&top->target_data,
5872                                                ready_try, n_ready,
5873                                                first_cycle_insn_p);
5874
5875   /* Count the number of the insns to search among.  */
5876   for (all = i = 0; i < n_ready; i++)
5877     if (!ready_try [i])
5878       all++;
5879
5880   if (sched_verbose >= 2)
5881     {
5882       fprintf (sched_dump, ";;\t\tmax_issue among %d insns:", all);
5883       debug_ready_list_1 (ready, ready_try);
5884     }
5885
5886   /* I is the index of the insn to try next.  */
5887   i = 0;
5888   tries_num = 0;
5889   for (;;)
5890     {
5891       if (/* If we've reached a dead end or searched enough of what we have
5892              been asked...  */
5893           top->rest == 0
5894           /* or have nothing else to try...  */
5895           || i >= n_ready
5896           /* or should not issue more.  */
5897           || top->n >= more_issue)
5898         {
5899           /* ??? (... || i == n_ready).  */
5900           gcc_assert (i <= n_ready);
5901
5902           /* We should not issue more than issue_rate instructions.  */
5903           gcc_assert (top->n <= more_issue);
5904
5905           if (top == choice_stack)
5906             break;
5907
5908           if (best < top - choice_stack)
5909             {
5910               if (privileged_n)
5911                 {
5912                   n = privileged_n;
5913                   /* Try to find issued privileged insn.  */
5914                   while (n && !ready_try[--n])
5915                     ;
5916                 }
5917
5918               if (/* If all insns are equally good...  */
5919                   privileged_n == 0
5920                   /* Or a privileged insn will be issued.  */
5921                   || ready_try[n])
5922                 /* Then we have a solution.  */
5923                 {
5924                   best = top - choice_stack;
5925                   /* This is the index of the insn issued first in this
5926                      solution.  */
5927                   *index = choice_stack [1].index;
5928                   if (top->n == more_issue || best == all)
5929                     break;
5930                 }
5931             }
5932
5933           /* Set ready-list index to point to the last insn
5934              ('i++' below will advance it to the next insn).  */
5935           i = top->index;
5936
5937           /* Backtrack.  */
5938           ready_try [i] = 0;
5939
5940           if (targetm.sched.first_cycle_multipass_backtrack)
5941             targetm.sched.first_cycle_multipass_backtrack (&top->target_data,
5942                                                            ready_try, n_ready);
5943
5944           top--;
5945           memcpy (state, top->state, dfa_state_size);
5946         }
5947       else if (!ready_try [i])
5948         {
5949           tries_num++;
5950           if (tries_num > max_lookahead_tries)
5951             break;
5952           insn = ready_element (ready, i);
5953           delay = state_transition (state, insn);
5954           if (delay < 0)
5955             {
5956               if (state_dead_lock_p (state)
5957                   || insn_finishes_cycle_p (insn))
5958                 /* We won't issue any more instructions in the next
5959                    choice_state.  */
5960                 top->rest = 0;
5961               else
5962                 top->rest--;
5963
5964               n = top->n;
5965               if (memcmp (top->state, state, dfa_state_size) != 0)
5966                 n++;
5967
5968               /* Advance to the next choice_entry.  */
5969               top++;
5970               /* Initialize it.  */
5971               top->rest = dfa_lookahead;
5972               top->index = i;
5973               top->n = n;
5974               memcpy (top->state, state, dfa_state_size);
5975               ready_try [i] = 1;
5976
5977               if (targetm.sched.first_cycle_multipass_issue)
5978                 targetm.sched.first_cycle_multipass_issue (&top->target_data,
5979                                                            ready_try, n_ready,
5980                                                            insn,
5981                                                            &((top - 1)
5982                                                              ->target_data));
5983
5984               i = -1;
5985             }
5986         }
5987
5988       /* Increase ready-list index.  */
5989       i++;
5990     }
5991
5992   if (targetm.sched.first_cycle_multipass_end)
5993     targetm.sched.first_cycle_multipass_end (best != 0
5994                                              ? &choice_stack[1].target_data
5995                                              : NULL);
5996
5997   /* Restore the original state of the DFA.  */
5998   memcpy (state, choice_stack->state, dfa_state_size);
5999
6000   return best;
6001 }
6002
6003 /* The following function chooses insn from READY and modifies
6004    READY.  The following function is used only for first
6005    cycle multipass scheduling.
6006    Return:
6007    -1 if cycle should be advanced,
6008    0 if INSN_PTR is set to point to the desirable insn,
6009    1 if choose_ready () should be restarted without advancing the cycle.  */
6010 static int
6011 choose_ready (struct ready_list *ready, bool first_cycle_insn_p,
6012               rtx_insn **insn_ptr)
6013 {
6014   if (dbg_cnt (sched_insn) == false)
6015     {
6016       if (nonscheduled_insns_begin == NULL_RTX)
6017         nonscheduled_insns_begin = current_sched_info->prev_head;
6018
6019       rtx_insn *insn = first_nonscheduled_insn ();
6020
6021       if (QUEUE_INDEX (insn) == QUEUE_READY)
6022         /* INSN is in the ready_list.  */
6023         {
6024           ready_remove_insn (insn);
6025           *insn_ptr = insn;
6026           return 0;
6027         }
6028
6029       /* INSN is in the queue.  Advance cycle to move it to the ready list.  */
6030       gcc_assert (QUEUE_INDEX (insn) >= 0);
6031       return -1;
6032     }
6033
6034   if (dfa_lookahead <= 0 || SCHED_GROUP_P (ready_element (ready, 0))
6035       || DEBUG_INSN_P (ready_element (ready, 0)))
6036     {
6037       if (targetm.sched.dispatch (NULL, IS_DISPATCH_ON))
6038         *insn_ptr = ready_remove_first_dispatch (ready);
6039       else
6040         *insn_ptr = ready_remove_first (ready);
6041
6042       return 0;
6043     }
6044   else
6045     {
6046       /* Try to choose the best insn.  */
6047       int index = 0, i;
6048       rtx_insn *insn;
6049
6050       insn = ready_element (ready, 0);
6051       if (INSN_CODE (insn) < 0)
6052         {
6053           *insn_ptr = ready_remove_first (ready);
6054           return 0;
6055         }
6056
6057       /* Filter the search space.  */
6058       for (i = 0; i < ready->n_ready; i++)
6059         {
6060           ready_try[i] = 0;
6061
6062           insn = ready_element (ready, i);
6063
6064           /* If this insn is recognizable we should have already
6065              recognized it earlier.
6066              ??? Not very clear where this is supposed to be done.
6067              See dep_cost_1.  */
6068           gcc_checking_assert (INSN_CODE (insn) >= 0
6069                                || recog_memoized (insn) < 0);
6070           if (INSN_CODE (insn) < 0)
6071             {
6072               /* Non-recognized insns at position 0 are handled above.  */
6073               gcc_assert (i > 0);
6074               ready_try[i] = 1;
6075               continue;
6076             }
6077
6078           if (targetm.sched.first_cycle_multipass_dfa_lookahead_guard)
6079             {
6080               ready_try[i]
6081                 = (targetm.sched.first_cycle_multipass_dfa_lookahead_guard
6082                     (insn, i));
6083
6084               if (ready_try[i] < 0)
6085                 /* Queue instruction for several cycles.
6086                    We need to restart choose_ready as we have changed
6087                    the ready list.  */
6088                 {
6089                   change_queue_index (insn, -ready_try[i]);
6090                   return 1;
6091                 }
6092
6093               /* Make sure that we didn't end up with 0'th insn filtered out.
6094                  Don't be tempted to make life easier for backends and just
6095                  requeue 0'th insn if (ready_try[0] == 0) and restart
6096                  choose_ready.  Backends should be very considerate about
6097                  requeueing instructions -- especially the highest priority
6098                  one at position 0.  */
6099               gcc_assert (ready_try[i] == 0 || i > 0);
6100               if (ready_try[i])
6101                 continue;
6102             }
6103
6104           gcc_assert (ready_try[i] == 0);
6105           /* INSN made it through the scrutiny of filters!  */
6106         }
6107
6108       if (max_issue (ready, 1, curr_state, first_cycle_insn_p, &index) == 0)
6109         {
6110           *insn_ptr = ready_remove_first (ready);
6111           if (sched_verbose >= 4)
6112             fprintf (sched_dump, ";;\t\tChosen insn (but can't issue) : %s \n",
6113                      (*current_sched_info->print_insn) (*insn_ptr, 0));
6114           return 0;
6115         }
6116       else
6117         {
6118           if (sched_verbose >= 4)
6119             fprintf (sched_dump, ";;\t\tChosen insn : %s\n",
6120                      (*current_sched_info->print_insn)
6121                      (ready_element (ready, index), 0));
6122
6123           *insn_ptr = ready_remove (ready, index);
6124           return 0;
6125         }
6126     }
6127 }
6128
6129 /* This function is called when we have successfully scheduled a
6130    block.  It uses the schedule stored in the scheduled_insns vector
6131    to rearrange the RTL.  PREV_HEAD is used as the anchor to which we
6132    append the scheduled insns; TAIL is the insn after the scheduled
6133    block.  TARGET_BB is the argument passed to schedule_block.  */
6134
6135 static void
6136 commit_schedule (rtx_insn *prev_head, rtx_insn *tail, basic_block *target_bb)
6137 {
6138   unsigned int i;
6139   rtx_insn *insn;
6140
6141   last_scheduled_insn = prev_head;
6142   for (i = 0;
6143        scheduled_insns.iterate (i, &insn);
6144        i++)
6145     {
6146       if (control_flow_insn_p (last_scheduled_insn)
6147           || current_sched_info->advance_target_bb (*target_bb, insn))
6148         {
6149           *target_bb = current_sched_info->advance_target_bb (*target_bb, 0);
6150
6151           if (sched_verbose)
6152             {
6153               rtx_insn *x;
6154
6155               x = next_real_insn (last_scheduled_insn);
6156               gcc_assert (x);
6157               dump_new_block_header (1, *target_bb, x, tail);
6158             }
6159
6160           last_scheduled_insn = bb_note (*target_bb);
6161         }
6162
6163       if (current_sched_info->begin_move_insn)
6164         (*current_sched_info->begin_move_insn) (insn, last_scheduled_insn);
6165       move_insn (insn, last_scheduled_insn,
6166                  current_sched_info->next_tail);
6167       if (!DEBUG_INSN_P (insn))
6168         reemit_notes (insn);
6169       last_scheduled_insn = insn;
6170     }
6171
6172   scheduled_insns.truncate (0);
6173 }
6174
6175 /* Examine all insns on the ready list and queue those which can't be
6176    issued in this cycle.  TEMP_STATE is temporary scheduler state we
6177    can use as scratch space.  If FIRST_CYCLE_INSN_P is true, no insns
6178    have been issued for the current cycle, which means it is valid to
6179    issue an asm statement.
6180
6181    If SHADOWS_ONLY_P is true, we eliminate all real insns and only
6182    leave those for which SHADOW_P is true.  If MODULO_EPILOGUE is true,
6183    we only leave insns which have an INSN_EXACT_TICK.  */
6184
6185 static void
6186 prune_ready_list (state_t temp_state, bool first_cycle_insn_p,
6187                   bool shadows_only_p, bool modulo_epilogue_p)
6188 {
6189   int i, pass;
6190   bool sched_group_found = false;
6191   int min_cost_group = 1;
6192
6193   if (sched_fusion)
6194     return;
6195
6196   for (i = 0; i < ready.n_ready; i++)
6197     {
6198       rtx_insn *insn = ready_element (&ready, i);
6199       if (SCHED_GROUP_P (insn))
6200         {
6201           sched_group_found = true;
6202           break;
6203         }
6204     }
6205
6206   /* Make two passes if there's a SCHED_GROUP_P insn; make sure to handle
6207      such an insn first and note its cost, then schedule all other insns
6208      for one cycle later.  */
6209   for (pass = sched_group_found ? 0 : 1; pass < 2; )
6210     {
6211       int n = ready.n_ready;
6212       for (i = 0; i < n; i++)
6213         {
6214           rtx_insn *insn = ready_element (&ready, i);
6215           int cost = 0;
6216           const char *reason = "resource conflict";
6217
6218           if (DEBUG_INSN_P (insn))
6219             continue;
6220
6221           if (sched_group_found && !SCHED_GROUP_P (insn))
6222             {
6223               if (pass == 0)
6224                 continue;
6225               cost = min_cost_group;
6226               reason = "not in sched group";
6227             }
6228           else if (modulo_epilogue_p
6229                    && INSN_EXACT_TICK (insn) == INVALID_TICK)
6230             {
6231               cost = max_insn_queue_index;
6232               reason = "not an epilogue insn";
6233             }
6234           else if (shadows_only_p && !SHADOW_P (insn))
6235             {
6236               cost = 1;
6237               reason = "not a shadow";
6238             }
6239           else if (recog_memoized (insn) < 0)
6240             {
6241               if (!first_cycle_insn_p
6242                   && (GET_CODE (PATTERN (insn)) == ASM_INPUT
6243                       || asm_noperands (PATTERN (insn)) >= 0))
6244                 cost = 1;
6245               reason = "asm";
6246             }
6247           else if (sched_pressure != SCHED_PRESSURE_NONE)
6248             {
6249               if (sched_pressure == SCHED_PRESSURE_MODEL
6250                   && INSN_TICK (insn) <= clock_var)
6251                 {
6252                   memcpy (temp_state, curr_state, dfa_state_size);
6253                   if (state_transition (temp_state, insn) >= 0)
6254                     INSN_TICK (insn) = clock_var + 1;
6255                 }
6256               cost = 0;
6257             }
6258           else
6259             {
6260               int delay_cost = 0;
6261
6262               if (delay_htab)
6263                 {
6264                   struct delay_pair *delay_entry;
6265                   delay_entry
6266                     = delay_htab->find_with_hash (insn,
6267                                                   htab_hash_pointer (insn));
6268                   while (delay_entry && delay_cost == 0)
6269                     {
6270                       delay_cost = estimate_shadow_tick (delay_entry);
6271                       if (delay_cost > max_insn_queue_index)
6272                         delay_cost = max_insn_queue_index;
6273                       delay_entry = delay_entry->next_same_i1;
6274                     }
6275                 }
6276
6277               memcpy (temp_state, curr_state, dfa_state_size);
6278               cost = state_transition (temp_state, insn);
6279               if (cost < 0)
6280                 cost = 0;
6281               else if (cost == 0)
6282                 cost = 1;
6283               if (cost < delay_cost)
6284                 {
6285                   cost = delay_cost;
6286                   reason = "shadow tick";
6287                 }
6288             }
6289           if (cost >= 1)
6290             {
6291               if (SCHED_GROUP_P (insn) && cost > min_cost_group)
6292                 min_cost_group = cost;
6293               ready_remove (&ready, i);
6294               /* Normally we'd want to queue INSN for COST cycles.  However,
6295                  if SCHED_GROUP_P is set, then we must ensure that nothing
6296                  else comes between INSN and its predecessor.  If there is
6297                  some other insn ready to fire on the next cycle, then that
6298                  invariant would be broken.
6299
6300                  So when SCHED_GROUP_P is set, just queue this insn for a
6301                  single cycle.  */
6302               queue_insn (insn, SCHED_GROUP_P (insn) ? 1 : cost, reason);
6303               if (i + 1 < n)
6304                 break;
6305             }
6306         }
6307       if (i == n)
6308         pass++;
6309     }
6310 }
6311
6312 /* Called when we detect that the schedule is impossible.  We examine the
6313    backtrack queue to find the earliest insn that caused this condition.  */
6314
6315 static struct haifa_saved_data *
6316 verify_shadows (void)
6317 {
6318   struct haifa_saved_data *save, *earliest_fail = NULL;
6319   for (save = backtrack_queue; save; save = save->next)
6320     {
6321       int t;
6322       struct delay_pair *pair = save->delay_pair;
6323       rtx_insn *i1 = pair->i1;
6324
6325       for (; pair; pair = pair->next_same_i1)
6326         {
6327           rtx_insn *i2 = pair->i2;
6328
6329           if (QUEUE_INDEX (i2) == QUEUE_SCHEDULED)
6330             continue;
6331
6332           t = INSN_TICK (i1) + pair_delay (pair);
6333           if (t < clock_var)
6334             {
6335               if (sched_verbose >= 2)
6336                 fprintf (sched_dump,
6337                          ";;\t\tfailed delay requirements for %d/%d (%d->%d)"
6338                          ", not ready\n",
6339                          INSN_UID (pair->i1), INSN_UID (pair->i2),
6340                          INSN_TICK (pair->i1), INSN_EXACT_TICK (pair->i2));
6341               earliest_fail = save;
6342               break;
6343             }
6344           if (QUEUE_INDEX (i2) >= 0)
6345             {
6346               int queued_for = INSN_TICK (i2);
6347
6348               if (t < queued_for)
6349                 {
6350                   if (sched_verbose >= 2)
6351                     fprintf (sched_dump,
6352                              ";;\t\tfailed delay requirements for %d/%d"
6353                              " (%d->%d), queued too late\n",
6354                              INSN_UID (pair->i1), INSN_UID (pair->i2),
6355                              INSN_TICK (pair->i1), INSN_EXACT_TICK (pair->i2));
6356                   earliest_fail = save;
6357                   break;
6358                 }
6359             }
6360         }
6361     }
6362
6363   return earliest_fail;
6364 }
6365
6366 /* Print instructions together with useful scheduling information between
6367    HEAD and TAIL (inclusive).  */
6368 static void
6369 dump_insn_stream (rtx_insn *head, rtx_insn *tail)
6370 {
6371   fprintf (sched_dump, ";;\t| insn | prio |\n");
6372
6373   rtx_insn *next_tail = NEXT_INSN (tail);
6374   for (rtx_insn *insn = head; insn != next_tail; insn = NEXT_INSN (insn))
6375     {
6376       int priority = NOTE_P (insn) ? 0 : INSN_PRIORITY (insn);
6377       const char *pattern = (NOTE_P (insn)
6378                              ? "note"
6379                              : str_pattern_slim (PATTERN (insn)));
6380
6381       fprintf (sched_dump, ";;\t| %4d | %4d | %-30s ",
6382                INSN_UID (insn), priority, pattern);
6383
6384       if (sched_verbose >= 4)
6385         {
6386           if (NOTE_P (insn) || recog_memoized (insn) < 0)
6387             fprintf (sched_dump, "nothing");
6388           else
6389             print_reservation (sched_dump, insn);
6390         }
6391       fprintf (sched_dump, "\n");
6392     }
6393 }
6394
6395 /* Use forward list scheduling to rearrange insns of block pointed to by
6396    TARGET_BB, possibly bringing insns from subsequent blocks in the same
6397    region.  */
6398
6399 bool
6400 schedule_block (basic_block *target_bb, state_t init_state)
6401 {
6402   int i;
6403   bool success = modulo_ii == 0;
6404   struct sched_block_state ls;
6405   state_t temp_state = NULL;  /* It is used for multipass scheduling.  */
6406   int sort_p, advance, start_clock_var;
6407
6408   /* Head/tail info for this block.  */
6409   rtx_insn *prev_head = current_sched_info->prev_head;
6410   rtx_insn *next_tail = current_sched_info->next_tail;
6411   rtx_insn *head = NEXT_INSN (prev_head);
6412   rtx_insn *tail = PREV_INSN (next_tail);
6413
6414   if ((current_sched_info->flags & DONT_BREAK_DEPENDENCIES) == 0
6415       && sched_pressure != SCHED_PRESSURE_MODEL && !sched_fusion)
6416     find_modifiable_mems (head, tail);
6417
6418   /* We used to have code to avoid getting parameters moved from hard
6419      argument registers into pseudos.
6420
6421      However, it was removed when it proved to be of marginal benefit
6422      and caused problems because schedule_block and compute_forward_dependences
6423      had different notions of what the "head" insn was.  */
6424
6425   gcc_assert (head != tail || INSN_P (head));
6426
6427   haifa_recovery_bb_recently_added_p = false;
6428
6429   backtrack_queue = NULL;
6430
6431   /* Debug info.  */
6432   if (sched_verbose)
6433     {
6434       dump_new_block_header (0, *target_bb, head, tail);
6435
6436       if (sched_verbose >= 2)
6437         {
6438           dump_insn_stream (head, tail);
6439           memset (&rank_for_schedule_stats, 0,
6440                   sizeof (rank_for_schedule_stats));
6441         }
6442     }
6443
6444   if (init_state == NULL)
6445     state_reset (curr_state);
6446   else
6447     memcpy (curr_state, init_state, dfa_state_size);
6448
6449   /* Clear the ready list.  */
6450   ready.first = ready.veclen - 1;
6451   ready.n_ready = 0;
6452   ready.n_debug = 0;
6453
6454   /* It is used for first cycle multipass scheduling.  */
6455   temp_state = alloca (dfa_state_size);
6456
6457   if (targetm.sched.init)
6458     targetm.sched.init (sched_dump, sched_verbose, ready.veclen);
6459
6460   /* We start inserting insns after PREV_HEAD.  */
6461   last_scheduled_insn = prev_head;
6462   last_nondebug_scheduled_insn = NULL_RTX;
6463   nonscheduled_insns_begin = NULL;
6464
6465   gcc_assert ((NOTE_P (last_scheduled_insn)
6466                || DEBUG_INSN_P (last_scheduled_insn))
6467               && BLOCK_FOR_INSN (last_scheduled_insn) == *target_bb);
6468
6469   /* Initialize INSN_QUEUE.  Q_SIZE is the total number of insns in the
6470      queue.  */
6471   q_ptr = 0;
6472   q_size = 0;
6473
6474   insn_queue = XALLOCAVEC (rtx_insn_list *, max_insn_queue_index + 1);
6475   memset (insn_queue, 0, (max_insn_queue_index + 1) * sizeof (rtx));
6476
6477   /* Start just before the beginning of time.  */
6478   clock_var = -1;
6479
6480   /* We need queue and ready lists and clock_var be initialized
6481      in try_ready () (which is called through init_ready_list ()).  */
6482   (*current_sched_info->init_ready_list) ();
6483
6484   if (sched_pressure)
6485     sched_pressure_start_bb (*target_bb);
6486
6487   /* The algorithm is O(n^2) in the number of ready insns at any given
6488      time in the worst case.  Before reload we are more likely to have
6489      big lists so truncate them to a reasonable size.  */
6490   if (!reload_completed
6491       && ready.n_ready - ready.n_debug > MAX_SCHED_READY_INSNS)
6492     {
6493       ready_sort (&ready);
6494
6495       /* Find first free-standing insn past MAX_SCHED_READY_INSNS.
6496          If there are debug insns, we know they're first.  */
6497       for (i = MAX_SCHED_READY_INSNS + ready.n_debug; i < ready.n_ready; i++)
6498         if (!SCHED_GROUP_P (ready_element (&ready, i)))
6499           break;
6500
6501       if (sched_verbose >= 2)
6502         {
6503           fprintf (sched_dump,
6504                    ";;\t\tReady list on entry: %d insns\n", ready.n_ready);
6505           fprintf (sched_dump,
6506                    ";;\t\t before reload => truncated to %d insns\n", i);
6507         }
6508
6509       /* Delay all insns past it for 1 cycle.  If debug counter is
6510          activated make an exception for the insn right after
6511          nonscheduled_insns_begin.  */
6512       {
6513         rtx_insn *skip_insn;
6514
6515         if (dbg_cnt (sched_insn) == false)
6516           skip_insn = first_nonscheduled_insn ();
6517         else
6518           skip_insn = NULL;
6519
6520         while (i < ready.n_ready)
6521           {
6522             rtx_insn *insn;
6523
6524             insn = ready_remove (&ready, i);
6525
6526             if (insn != skip_insn)
6527               queue_insn (insn, 1, "list truncated");
6528           }
6529         if (skip_insn)
6530           ready_add (&ready, skip_insn, true);
6531       }
6532     }
6533
6534   /* Now we can restore basic block notes and maintain precise cfg.  */
6535   restore_bb_notes (*target_bb);
6536
6537   last_clock_var = -1;
6538
6539   advance = 0;
6540
6541   gcc_assert (scheduled_insns.length () == 0);
6542   sort_p = TRUE;
6543   must_backtrack = false;
6544   modulo_insns_scheduled = 0;
6545
6546   ls.modulo_epilogue = false;
6547   ls.first_cycle_insn_p = true;
6548
6549   /* Loop until all the insns in BB are scheduled.  */
6550   while ((*current_sched_info->schedule_more_p) ())
6551     {
6552       perform_replacements_new_cycle ();
6553       do
6554         {
6555           start_clock_var = clock_var;
6556
6557           clock_var++;
6558
6559           advance_one_cycle ();
6560
6561           /* Add to the ready list all pending insns that can be issued now.
6562              If there are no ready insns, increment clock until one
6563              is ready and add all pending insns at that point to the ready
6564              list.  */
6565           queue_to_ready (&ready);
6566
6567           gcc_assert (ready.n_ready);
6568
6569           if (sched_verbose >= 2)
6570             {
6571               fprintf (sched_dump, ";;\t\tReady list after queue_to_ready:");
6572               debug_ready_list (&ready);
6573             }
6574           advance -= clock_var - start_clock_var;
6575         }
6576       while (advance > 0);
6577
6578       if (ls.modulo_epilogue)
6579         {
6580           int stage = clock_var / modulo_ii;
6581           if (stage > modulo_last_stage * 2 + 2)
6582             {
6583               if (sched_verbose >= 2)
6584                 fprintf (sched_dump,
6585                          ";;\t\tmodulo scheduled succeeded at II %d\n",
6586                          modulo_ii);
6587               success = true;
6588               goto end_schedule;
6589             }
6590         }
6591       else if (modulo_ii > 0)
6592         {
6593           int stage = clock_var / modulo_ii;
6594           if (stage > modulo_max_stages)
6595             {
6596               if (sched_verbose >= 2)
6597                 fprintf (sched_dump,
6598                          ";;\t\tfailing schedule due to excessive stages\n");
6599               goto end_schedule;
6600             }
6601           if (modulo_n_insns == modulo_insns_scheduled
6602               && stage > modulo_last_stage)
6603             {
6604               if (sched_verbose >= 2)
6605                 fprintf (sched_dump,
6606                          ";;\t\tfound kernel after %d stages, II %d\n",
6607                          stage, modulo_ii);
6608               ls.modulo_epilogue = true;
6609             }
6610         }
6611
6612       prune_ready_list (temp_state, true, false, ls.modulo_epilogue);
6613       if (ready.n_ready == 0)
6614         continue;
6615       if (must_backtrack)
6616         goto do_backtrack;
6617
6618       ls.shadows_only_p = false;
6619       cycle_issued_insns = 0;
6620       ls.can_issue_more = issue_rate;
6621       for (;;)
6622         {
6623           rtx_insn *insn;
6624           int cost;
6625           bool asm_p;
6626
6627           if (sort_p && ready.n_ready > 0)
6628             {
6629               /* Sort the ready list based on priority.  This must be
6630                  done every iteration through the loop, as schedule_insn
6631                  may have readied additional insns that will not be
6632                  sorted correctly.  */
6633               ready_sort (&ready);
6634
6635               if (sched_verbose >= 2)
6636                 {
6637                   fprintf (sched_dump,
6638                            ";;\t\tReady list after ready_sort:    ");
6639                   debug_ready_list (&ready);
6640                 }
6641             }
6642
6643           /* We don't want md sched reorder to even see debug isns, so put
6644              them out right away.  */
6645           if (ready.n_ready && DEBUG_INSN_P (ready_element (&ready, 0))
6646               && (*current_sched_info->schedule_more_p) ())
6647             {
6648               while (ready.n_ready && DEBUG_INSN_P (ready_element (&ready, 0)))
6649                 {
6650                   rtx_insn *insn = ready_remove_first (&ready);
6651                   gcc_assert (DEBUG_INSN_P (insn));
6652                   (*current_sched_info->begin_schedule_ready) (insn);
6653                   scheduled_insns.safe_push (insn);
6654                   last_scheduled_insn = insn;
6655                   advance = schedule_insn (insn);
6656                   gcc_assert (advance == 0);
6657                   if (ready.n_ready > 0)
6658                     ready_sort (&ready);
6659                 }
6660             }
6661
6662           if (ls.first_cycle_insn_p && !ready.n_ready)
6663             break;
6664
6665         resume_after_backtrack:
6666           /* Allow the target to reorder the list, typically for
6667              better instruction bundling.  */
6668           if (sort_p
6669               && (ready.n_ready == 0
6670                   || !SCHED_GROUP_P (ready_element (&ready, 0))))
6671             {
6672               if (ls.first_cycle_insn_p && targetm.sched.reorder)
6673                 ls.can_issue_more
6674                   = targetm.sched.reorder (sched_dump, sched_verbose,
6675                                            ready_lastpos (&ready),
6676                                            &ready.n_ready, clock_var);
6677               else if (!ls.first_cycle_insn_p && targetm.sched.reorder2)
6678                 ls.can_issue_more
6679                   = targetm.sched.reorder2 (sched_dump, sched_verbose,
6680                                             ready.n_ready
6681                                             ? ready_lastpos (&ready) : NULL,
6682                                             &ready.n_ready, clock_var);
6683             }
6684
6685         restart_choose_ready:
6686           if (sched_verbose >= 2)
6687             {
6688               fprintf (sched_dump, ";;\tReady list (t = %3d):  ",
6689                        clock_var);
6690               debug_ready_list (&ready);
6691               if (sched_pressure == SCHED_PRESSURE_WEIGHTED)
6692                 print_curr_reg_pressure ();
6693             }
6694
6695           if (ready.n_ready == 0
6696               && ls.can_issue_more
6697               && reload_completed)
6698             {
6699               /* Allow scheduling insns directly from the queue in case
6700                  there's nothing better to do (ready list is empty) but
6701                  there are still vacant dispatch slots in the current cycle.  */
6702               if (sched_verbose >= 6)
6703                 fprintf (sched_dump,";;\t\tSecond chance\n");
6704               memcpy (temp_state, curr_state, dfa_state_size);
6705               if (early_queue_to_ready (temp_state, &ready))
6706                 ready_sort (&ready);
6707             }
6708
6709           if (ready.n_ready == 0
6710               || !ls.can_issue_more
6711               || state_dead_lock_p (curr_state)
6712               || !(*current_sched_info->schedule_more_p) ())
6713             break;
6714
6715           /* Select and remove the insn from the ready list.  */
6716           if (sort_p)
6717             {
6718               int res;
6719
6720               insn = NULL;
6721               res = choose_ready (&ready, ls.first_cycle_insn_p, &insn);
6722
6723               if (res < 0)
6724                 /* Finish cycle.  */
6725                 break;
6726               if (res > 0)
6727                 goto restart_choose_ready;
6728
6729               gcc_assert (insn != NULL_RTX);
6730             }
6731           else
6732             insn = ready_remove_first (&ready);
6733
6734           if (sched_pressure != SCHED_PRESSURE_NONE
6735               && INSN_TICK (insn) > clock_var)
6736             {
6737               ready_add (&ready, insn, true);
6738               advance = 1;
6739               break;
6740             }
6741
6742           if (targetm.sched.dfa_new_cycle
6743               && targetm.sched.dfa_new_cycle (sched_dump, sched_verbose,
6744                                               insn, last_clock_var,
6745                                               clock_var, &sort_p))
6746             /* SORT_P is used by the target to override sorting
6747                of the ready list.  This is needed when the target
6748                has modified its internal structures expecting that
6749                the insn will be issued next.  As we need the insn
6750                to have the highest priority (so it will be returned by
6751                the ready_remove_first call above), we invoke
6752                ready_add (&ready, insn, true).
6753                But, still, there is one issue: INSN can be later
6754                discarded by scheduler's front end through
6755                current_sched_info->can_schedule_ready_p, hence, won't
6756                be issued next.  */
6757             {
6758               ready_add (&ready, insn, true);
6759               break;
6760             }
6761
6762           sort_p = TRUE;
6763
6764           if (current_sched_info->can_schedule_ready_p
6765               && ! (*current_sched_info->can_schedule_ready_p) (insn))
6766             /* We normally get here only if we don't want to move
6767                insn from the split block.  */
6768             {
6769               TODO_SPEC (insn) = DEP_POSTPONED;
6770               goto restart_choose_ready;
6771             }
6772
6773           if (delay_htab)
6774             {
6775               /* If this insn is the first part of a delay-slot pair, record a
6776                  backtrack point.  */
6777               struct delay_pair *delay_entry;
6778               delay_entry
6779                 = delay_htab->find_with_hash (insn, htab_hash_pointer (insn));
6780               if (delay_entry)
6781                 {
6782                   save_backtrack_point (delay_entry, ls);
6783                   if (sched_verbose >= 2)
6784                     fprintf (sched_dump, ";;\t\tsaving backtrack point\n");
6785                 }
6786             }
6787
6788           /* DECISION is made.  */
6789
6790           if (modulo_ii > 0 && INSN_UID (insn) < modulo_iter0_max_uid)
6791             {
6792               modulo_insns_scheduled++;
6793               modulo_last_stage = clock_var / modulo_ii;
6794             }
6795           if (TODO_SPEC (insn) & SPECULATIVE)
6796             generate_recovery_code (insn);
6797
6798           if (targetm.sched.dispatch (NULL, IS_DISPATCH_ON))
6799             targetm.sched.dispatch_do (insn, ADD_TO_DISPATCH_WINDOW);
6800
6801           /* Update counters, etc in the scheduler's front end.  */
6802           (*current_sched_info->begin_schedule_ready) (insn);
6803           scheduled_insns.safe_push (insn);
6804           gcc_assert (NONDEBUG_INSN_P (insn));
6805           last_nondebug_scheduled_insn = last_scheduled_insn = insn;
6806
6807           if (recog_memoized (insn) >= 0)
6808             {
6809               memcpy (temp_state, curr_state, dfa_state_size);
6810               cost = state_transition (curr_state, insn);
6811               if (sched_pressure != SCHED_PRESSURE_WEIGHTED && !sched_fusion)
6812                 gcc_assert (cost < 0);
6813               if (memcmp (temp_state, curr_state, dfa_state_size) != 0)
6814                 cycle_issued_insns++;
6815               asm_p = false;
6816             }
6817           else
6818             asm_p = (GET_CODE (PATTERN (insn)) == ASM_INPUT
6819                      || asm_noperands (PATTERN (insn)) >= 0);
6820
6821           if (targetm.sched.variable_issue)
6822             ls.can_issue_more =
6823               targetm.sched.variable_issue (sched_dump, sched_verbose,
6824                                             insn, ls.can_issue_more);
6825           /* A naked CLOBBER or USE generates no instruction, so do
6826              not count them against the issue rate.  */
6827           else if (GET_CODE (PATTERN (insn)) != USE
6828                    && GET_CODE (PATTERN (insn)) != CLOBBER)
6829             ls.can_issue_more--;
6830           advance = schedule_insn (insn);
6831
6832           if (SHADOW_P (insn))
6833             ls.shadows_only_p = true;
6834
6835           /* After issuing an asm insn we should start a new cycle.  */
6836           if (advance == 0 && asm_p)
6837             advance = 1;
6838
6839           if (must_backtrack)
6840             break;
6841
6842           if (advance != 0)
6843             break;
6844
6845           ls.first_cycle_insn_p = false;
6846           if (ready.n_ready > 0)
6847             prune_ready_list (temp_state, false, ls.shadows_only_p,
6848                               ls.modulo_epilogue);
6849         }
6850
6851     do_backtrack:
6852       if (!must_backtrack)
6853         for (i = 0; i < ready.n_ready; i++)
6854           {
6855             rtx_insn *insn = ready_element (&ready, i);
6856             if (INSN_EXACT_TICK (insn) == clock_var)
6857               {
6858                 must_backtrack = true;
6859                 clock_var++;
6860                 break;
6861               }
6862           }
6863       if (must_backtrack && modulo_ii > 0)
6864         {
6865           if (modulo_backtracks_left == 0)
6866             goto end_schedule;
6867           modulo_backtracks_left--;
6868         }
6869       while (must_backtrack)
6870         {
6871           struct haifa_saved_data *failed;
6872           rtx_insn *failed_insn;
6873
6874           must_backtrack = false;
6875           failed = verify_shadows ();
6876           gcc_assert (failed);
6877
6878           failed_insn = failed->delay_pair->i1;
6879           /* Clear these queues.  */
6880           perform_replacements_new_cycle ();
6881           toggle_cancelled_flags (false);
6882           unschedule_insns_until (failed_insn);
6883           while (failed != backtrack_queue)
6884             free_topmost_backtrack_point (true);
6885           restore_last_backtrack_point (&ls);
6886           if (sched_verbose >= 2)
6887             fprintf (sched_dump, ";;\t\trewind to cycle %d\n", clock_var);
6888           /* Delay by at least a cycle.  This could cause additional
6889              backtracking.  */
6890           queue_insn (failed_insn, 1, "backtracked");
6891           advance = 0;
6892           if (must_backtrack)
6893             continue;
6894           if (ready.n_ready > 0)
6895             goto resume_after_backtrack;
6896           else
6897             {
6898               if (clock_var == 0 && ls.first_cycle_insn_p)
6899                 goto end_schedule;
6900               advance = 1;
6901               break;
6902             }
6903         }
6904       ls.first_cycle_insn_p = true;
6905     }
6906   if (ls.modulo_epilogue)
6907     success = true;
6908  end_schedule:
6909   if (!ls.first_cycle_insn_p || advance)
6910     advance_one_cycle ();
6911   perform_replacements_new_cycle ();
6912   if (modulo_ii > 0)
6913     {
6914       /* Once again, debug insn suckiness: they can be on the ready list
6915          even if they have unresolved dependencies.  To make our view
6916          of the world consistent, remove such "ready" insns.  */
6917     restart_debug_insn_loop:
6918       for (i = ready.n_ready - 1; i >= 0; i--)
6919         {
6920           rtx_insn *x;
6921
6922           x = ready_element (&ready, i);
6923           if (DEPS_LIST_FIRST (INSN_HARD_BACK_DEPS (x)) != NULL
6924               || DEPS_LIST_FIRST (INSN_SPEC_BACK_DEPS (x)) != NULL)
6925             {
6926               ready_remove (&ready, i);
6927               goto restart_debug_insn_loop;
6928             }
6929         }
6930       for (i = ready.n_ready - 1; i >= 0; i--)
6931         {
6932           rtx_insn *x;
6933
6934           x = ready_element (&ready, i);
6935           resolve_dependencies (x);
6936         }
6937       for (i = 0; i <= max_insn_queue_index; i++)
6938         {
6939           rtx_insn_list *link;
6940           while ((link = insn_queue[i]) != NULL)
6941             {
6942               rtx_insn *x = link->insn ();
6943               insn_queue[i] = link->next ();
6944               QUEUE_INDEX (x) = QUEUE_NOWHERE;
6945               free_INSN_LIST_node (link);
6946               resolve_dependencies (x);
6947             }
6948         }
6949     }
6950
6951   if (!success)
6952     undo_all_replacements ();
6953
6954   /* Debug info.  */
6955   if (sched_verbose)
6956     {
6957       fprintf (sched_dump, ";;\tReady list (final):  ");
6958       debug_ready_list (&ready);
6959     }
6960
6961   if (modulo_ii == 0 && current_sched_info->queue_must_finish_empty)
6962     /* Sanity check -- queue must be empty now.  Meaningless if region has
6963        multiple bbs.  */
6964     gcc_assert (!q_size && !ready.n_ready && !ready.n_debug);
6965   else if (modulo_ii == 0)
6966     {
6967       /* We must maintain QUEUE_INDEX between blocks in region.  */
6968       for (i = ready.n_ready - 1; i >= 0; i--)
6969         {
6970           rtx_insn *x;
6971
6972           x = ready_element (&ready, i);
6973           QUEUE_INDEX (x) = QUEUE_NOWHERE;
6974           TODO_SPEC (x) = HARD_DEP;
6975         }
6976
6977       if (q_size)
6978         for (i = 0; i <= max_insn_queue_index; i++)
6979           {
6980             rtx_insn_list *link;
6981             for (link = insn_queue[i]; link; link = link->next ())
6982               {
6983                 rtx_insn *x;
6984
6985                 x = link->insn ();
6986                 QUEUE_INDEX (x) = QUEUE_NOWHERE;
6987                 TODO_SPEC (x) = HARD_DEP;
6988               }
6989             free_INSN_LIST_list (&insn_queue[i]);
6990           }
6991     }
6992
6993   if (sched_pressure == SCHED_PRESSURE_MODEL)
6994     model_end_schedule ();
6995
6996   if (success)
6997     {
6998       commit_schedule (prev_head, tail, target_bb);
6999       if (sched_verbose)
7000         fprintf (sched_dump, ";;   total time = %d\n", clock_var);
7001     }
7002   else
7003     last_scheduled_insn = tail;
7004
7005   scheduled_insns.truncate (0);
7006
7007   if (!current_sched_info->queue_must_finish_empty
7008       || haifa_recovery_bb_recently_added_p)
7009     {
7010       /* INSN_TICK (minimum clock tick at which the insn becomes
7011          ready) may be not correct for the insn in the subsequent
7012          blocks of the region.  We should use a correct value of
7013          `clock_var' or modify INSN_TICK.  It is better to keep
7014          clock_var value equal to 0 at the start of a basic block.
7015          Therefore we modify INSN_TICK here.  */
7016       fix_inter_tick (NEXT_INSN (prev_head), last_scheduled_insn);
7017     }
7018
7019   if (targetm.sched.finish)
7020     {
7021       targetm.sched.finish (sched_dump, sched_verbose);
7022       /* Target might have added some instructions to the scheduled block
7023          in its md_finish () hook.  These new insns don't have any data
7024          initialized and to identify them we extend h_i_d so that they'll
7025          get zero luids.  */
7026       sched_extend_luids ();
7027     }
7028
7029   /* Update head/tail boundaries.  */
7030   head = NEXT_INSN (prev_head);
7031   tail = last_scheduled_insn;
7032
7033   if (sched_verbose)
7034     {
7035       fprintf (sched_dump, ";;   new head = %d\n;;   new tail = %d\n",
7036                INSN_UID (head), INSN_UID (tail));
7037
7038       if (sched_verbose >= 2)
7039         {
7040           dump_insn_stream (head, tail);
7041           print_rank_for_schedule_stats (";; TOTAL ", &rank_for_schedule_stats,
7042                                          NULL);
7043         }
7044
7045       fprintf (sched_dump, "\n");
7046     }
7047
7048   head = restore_other_notes (head, NULL);
7049
7050   current_sched_info->head = head;
7051   current_sched_info->tail = tail;
7052
7053   free_backtrack_queue ();
7054
7055   return success;
7056 }
7057 \f
7058 /* Set_priorities: compute priority of each insn in the block.  */
7059
7060 int
7061 set_priorities (rtx_insn *head, rtx_insn *tail)
7062 {
7063   rtx_insn *insn;
7064   int n_insn;
7065   int sched_max_insns_priority =
7066         current_sched_info->sched_max_insns_priority;
7067   rtx_insn *prev_head;
7068
7069   if (head == tail && ! INSN_P (head))
7070     gcc_unreachable ();
7071
7072   n_insn = 0;
7073
7074   prev_head = PREV_INSN (head);
7075   for (insn = tail; insn != prev_head; insn = PREV_INSN (insn))
7076     {
7077       if (!INSN_P (insn))
7078         continue;
7079
7080       n_insn++;
7081       (void) priority (insn);
7082
7083       gcc_assert (INSN_PRIORITY_KNOWN (insn));
7084
7085       sched_max_insns_priority = MAX (sched_max_insns_priority,
7086                                       INSN_PRIORITY (insn));
7087     }
7088
7089   current_sched_info->sched_max_insns_priority = sched_max_insns_priority;
7090
7091   return n_insn;
7092 }
7093
7094 /* Set dump and sched_verbose for the desired debugging output.  If no
7095    dump-file was specified, but -fsched-verbose=N (any N), print to stderr.
7096    For -fsched-verbose=N, N>=10, print everything to stderr.  */
7097 void
7098 setup_sched_dump (void)
7099 {
7100   sched_verbose = sched_verbose_param;
7101   if (sched_verbose_param == 0 && dump_file)
7102     sched_verbose = 1;
7103   sched_dump = ((sched_verbose_param >= 10 || !dump_file)
7104                 ? stderr : dump_file);
7105 }
7106
7107 /* Allocate data for register pressure sensitive scheduling.  */
7108 static void
7109 alloc_global_sched_pressure_data (void)
7110 {
7111   if (sched_pressure != SCHED_PRESSURE_NONE)
7112     {
7113       int i, max_regno = max_reg_num ();
7114
7115       if (sched_dump != NULL)
7116         /* We need info about pseudos for rtl dumps about pseudo
7117            classes and costs.  */
7118         regstat_init_n_sets_and_refs ();
7119       ira_set_pseudo_classes (true, sched_verbose ? sched_dump : NULL);
7120       sched_regno_pressure_class
7121         = (enum reg_class *) xmalloc (max_regno * sizeof (enum reg_class));
7122       for (i = 0; i < max_regno; i++)
7123         sched_regno_pressure_class[i]
7124           = (i < FIRST_PSEUDO_REGISTER
7125              ? ira_pressure_class_translate[REGNO_REG_CLASS (i)]
7126              : ira_pressure_class_translate[reg_allocno_class (i)]);
7127       curr_reg_live = BITMAP_ALLOC (NULL);
7128       if (sched_pressure == SCHED_PRESSURE_WEIGHTED)
7129         {
7130           saved_reg_live = BITMAP_ALLOC (NULL);
7131           region_ref_regs = BITMAP_ALLOC (NULL);
7132         }
7133
7134       /* Calculate number of CALL_USED_REGS in register classes that
7135          we calculate register pressure for.  */
7136       for (int c = 0; c < ira_pressure_classes_num; ++c)
7137         {
7138           enum reg_class cl = ira_pressure_classes[c];
7139
7140           call_used_regs_num[cl] = 0;
7141
7142           for (int i = 0; i < ira_class_hard_regs_num[cl]; ++i)
7143             if (call_used_regs[ira_class_hard_regs[cl][i]])
7144               ++call_used_regs_num[cl];
7145         }
7146     }
7147 }
7148
7149 /*  Free data for register pressure sensitive scheduling.  Also called
7150     from schedule_region when stopping sched-pressure early.  */
7151 void
7152 free_global_sched_pressure_data (void)
7153 {
7154   if (sched_pressure != SCHED_PRESSURE_NONE)
7155     {
7156       if (regstat_n_sets_and_refs != NULL)
7157         regstat_free_n_sets_and_refs ();
7158       if (sched_pressure == SCHED_PRESSURE_WEIGHTED)
7159         {
7160           BITMAP_FREE (region_ref_regs);
7161           BITMAP_FREE (saved_reg_live);
7162         }
7163       BITMAP_FREE (curr_reg_live);
7164       free (sched_regno_pressure_class);
7165     }
7166 }
7167
7168 /* Initialize some global state for the scheduler.  This function works
7169    with the common data shared between all the schedulers.  It is called
7170    from the scheduler specific initialization routine.  */
7171
7172 void
7173 sched_init (void)
7174 {
7175   /* Disable speculative loads in their presence if cc0 defined.  */
7176 #ifdef HAVE_cc0
7177   flag_schedule_speculative_load = 0;
7178 #endif
7179
7180   if (targetm.sched.dispatch (NULL, IS_DISPATCH_ON))
7181     targetm.sched.dispatch_do (NULL, DISPATCH_INIT);
7182
7183   if (live_range_shrinkage_p)
7184     sched_pressure = SCHED_PRESSURE_WEIGHTED;
7185   else if (flag_sched_pressure
7186            && !reload_completed
7187            && common_sched_info->sched_pass_id == SCHED_RGN_PASS)
7188     sched_pressure = ((enum sched_pressure_algorithm)
7189                       PARAM_VALUE (PARAM_SCHED_PRESSURE_ALGORITHM));
7190   else
7191     sched_pressure = SCHED_PRESSURE_NONE;
7192
7193   if (sched_pressure != SCHED_PRESSURE_NONE)
7194     ira_setup_eliminable_regset ();
7195
7196   /* Initialize SPEC_INFO.  */
7197   if (targetm.sched.set_sched_flags)
7198     {
7199       spec_info = &spec_info_var;
7200       targetm.sched.set_sched_flags (spec_info);
7201
7202       if (spec_info->mask != 0)
7203         {
7204           spec_info->data_weakness_cutoff =
7205             (PARAM_VALUE (PARAM_SCHED_SPEC_PROB_CUTOFF) * MAX_DEP_WEAK) / 100;
7206           spec_info->control_weakness_cutoff =
7207             (PARAM_VALUE (PARAM_SCHED_SPEC_PROB_CUTOFF)
7208              * REG_BR_PROB_BASE) / 100;
7209         }
7210       else
7211         /* So we won't read anything accidentally.  */
7212         spec_info = NULL;
7213
7214     }
7215   else
7216     /* So we won't read anything accidentally.  */
7217     spec_info = 0;
7218
7219   /* Initialize issue_rate.  */
7220   if (targetm.sched.issue_rate)
7221     issue_rate = targetm.sched.issue_rate ();
7222   else
7223     issue_rate = 1;
7224
7225   if (targetm.sched.first_cycle_multipass_dfa_lookahead
7226       /* Don't use max_issue with reg_pressure scheduling.  Multipass
7227          scheduling and reg_pressure scheduling undo each other's decisions.  */
7228       && sched_pressure == SCHED_PRESSURE_NONE)
7229     dfa_lookahead = targetm.sched.first_cycle_multipass_dfa_lookahead ();
7230   else
7231     dfa_lookahead = 0;
7232
7233   /* Set to "0" so that we recalculate.  */
7234   max_lookahead_tries = 0;
7235
7236   if (targetm.sched.init_dfa_pre_cycle_insn)
7237     targetm.sched.init_dfa_pre_cycle_insn ();
7238
7239   if (targetm.sched.init_dfa_post_cycle_insn)
7240     targetm.sched.init_dfa_post_cycle_insn ();
7241
7242   dfa_start ();
7243   dfa_state_size = state_size ();
7244
7245   init_alias_analysis ();
7246
7247   if (!sched_no_dce)
7248     df_set_flags (DF_LR_RUN_DCE);
7249   df_note_add_problem ();
7250
7251   /* More problems needed for interloop dep calculation in SMS.  */
7252   if (common_sched_info->sched_pass_id == SCHED_SMS_PASS)
7253     {
7254       df_rd_add_problem ();
7255       df_chain_add_problem (DF_DU_CHAIN + DF_UD_CHAIN);
7256     }
7257
7258   df_analyze ();
7259
7260   /* Do not run DCE after reload, as this can kill nops inserted
7261      by bundling.  */
7262   if (reload_completed)
7263     df_clear_flags (DF_LR_RUN_DCE);
7264
7265   regstat_compute_calls_crossed ();
7266
7267   if (targetm.sched.init_global)
7268     targetm.sched.init_global (sched_dump, sched_verbose, get_max_uid () + 1);
7269
7270   alloc_global_sched_pressure_data ();
7271
7272   curr_state = xmalloc (dfa_state_size);
7273 }
7274
7275 static void haifa_init_only_bb (basic_block, basic_block);
7276
7277 /* Initialize data structures specific to the Haifa scheduler.  */
7278 void
7279 haifa_sched_init (void)
7280 {
7281   setup_sched_dump ();
7282   sched_init ();
7283
7284   scheduled_insns.create (0);
7285
7286   if (spec_info != NULL)
7287     {
7288       sched_deps_info->use_deps_list = 1;
7289       sched_deps_info->generate_spec_deps = 1;
7290     }
7291
7292   /* Initialize luids, dependency caches, target and h_i_d for the
7293      whole function.  */
7294   {
7295     bb_vec_t bbs;
7296     bbs.create (n_basic_blocks_for_fn (cfun));
7297     basic_block bb;
7298
7299     sched_init_bbs ();
7300
7301     FOR_EACH_BB_FN (bb, cfun)
7302       bbs.quick_push (bb);
7303     sched_init_luids (bbs);
7304     sched_deps_init (true);
7305     sched_extend_target ();
7306     haifa_init_h_i_d (bbs);
7307
7308     bbs.release ();
7309   }
7310
7311   sched_init_only_bb = haifa_init_only_bb;
7312   sched_split_block = sched_split_block_1;
7313   sched_create_empty_bb = sched_create_empty_bb_1;
7314   haifa_recovery_bb_ever_added_p = false;
7315
7316   nr_begin_data = nr_begin_control = nr_be_in_data = nr_be_in_control = 0;
7317   before_recovery = 0;
7318   after_recovery = 0;
7319
7320   modulo_ii = 0;
7321 }
7322
7323 /* Finish work with the data specific to the Haifa scheduler.  */
7324 void
7325 haifa_sched_finish (void)
7326 {
7327   sched_create_empty_bb = NULL;
7328   sched_split_block = NULL;
7329   sched_init_only_bb = NULL;
7330
7331   if (spec_info && spec_info->dump)
7332     {
7333       char c = reload_completed ? 'a' : 'b';
7334
7335       fprintf (spec_info->dump,
7336                ";; %s:\n", current_function_name ());
7337
7338       fprintf (spec_info->dump,
7339                ";; Procedure %cr-begin-data-spec motions == %d\n",
7340                c, nr_begin_data);
7341       fprintf (spec_info->dump,
7342                ";; Procedure %cr-be-in-data-spec motions == %d\n",
7343                c, nr_be_in_data);
7344       fprintf (spec_info->dump,
7345                ";; Procedure %cr-begin-control-spec motions == %d\n",
7346                c, nr_begin_control);
7347       fprintf (spec_info->dump,
7348                ";; Procedure %cr-be-in-control-spec motions == %d\n",
7349                c, nr_be_in_control);
7350     }
7351
7352   scheduled_insns.release ();
7353
7354   /* Finalize h_i_d, dependency caches, and luids for the whole
7355      function.  Target will be finalized in md_global_finish ().  */
7356   sched_deps_finish ();
7357   sched_finish_luids ();
7358   current_sched_info = NULL;
7359   sched_finish ();
7360 }
7361
7362 /* Free global data used during insn scheduling.  This function works with
7363    the common data shared between the schedulers.  */
7364
7365 void
7366 sched_finish (void)
7367 {
7368   haifa_finish_h_i_d ();
7369   free_global_sched_pressure_data ();
7370   free (curr_state);
7371
7372   if (targetm.sched.finish_global)
7373     targetm.sched.finish_global (sched_dump, sched_verbose);
7374
7375   end_alias_analysis ();
7376
7377   regstat_free_calls_crossed ();
7378
7379   dfa_finish ();
7380 }
7381
7382 /* Free all delay_pair structures that were recorded.  */
7383 void
7384 free_delay_pairs (void)
7385 {
7386   if (delay_htab)
7387     {
7388       delay_htab->empty ();
7389       delay_htab_i2->empty ();
7390     }
7391 }
7392
7393 /* Fix INSN_TICKs of the instructions in the current block as well as
7394    INSN_TICKs of their dependents.
7395    HEAD and TAIL are the begin and the end of the current scheduled block.  */
7396 static void
7397 fix_inter_tick (rtx_insn *head, rtx_insn *tail)
7398 {
7399   /* Set of instructions with corrected INSN_TICK.  */
7400   bitmap_head processed;
7401   /* ??? It is doubtful if we should assume that cycle advance happens on
7402      basic block boundaries.  Basically insns that are unconditionally ready
7403      on the start of the block are more preferable then those which have
7404      a one cycle dependency over insn from the previous block.  */
7405   int next_clock = clock_var + 1;
7406
7407   bitmap_initialize (&processed, 0);
7408
7409   /* Iterates over scheduled instructions and fix their INSN_TICKs and
7410      INSN_TICKs of dependent instructions, so that INSN_TICKs are consistent
7411      across different blocks.  */
7412   for (tail = NEXT_INSN (tail); head != tail; head = NEXT_INSN (head))
7413     {
7414       if (INSN_P (head))
7415         {
7416           int tick;
7417           sd_iterator_def sd_it;
7418           dep_t dep;
7419
7420           tick = INSN_TICK (head);
7421           gcc_assert (tick >= MIN_TICK);
7422
7423           /* Fix INSN_TICK of instruction from just scheduled block.  */
7424           if (bitmap_set_bit (&processed, INSN_LUID (head)))
7425             {
7426               tick -= next_clock;
7427
7428               if (tick < MIN_TICK)
7429                 tick = MIN_TICK;
7430
7431               INSN_TICK (head) = tick;
7432             }
7433
7434           if (DEBUG_INSN_P (head))
7435             continue;
7436
7437           FOR_EACH_DEP (head, SD_LIST_RES_FORW, sd_it, dep)
7438             {
7439               rtx_insn *next;
7440
7441               next = DEP_CON (dep);
7442               tick = INSN_TICK (next);
7443
7444               if (tick != INVALID_TICK
7445                   /* If NEXT has its INSN_TICK calculated, fix it.
7446                      If not - it will be properly calculated from
7447                      scratch later in fix_tick_ready.  */
7448                   && bitmap_set_bit (&processed, INSN_LUID (next)))
7449                 {
7450                   tick -= next_clock;
7451
7452                   if (tick < MIN_TICK)
7453                     tick = MIN_TICK;
7454
7455                   if (tick > INTER_TICK (next))
7456                     INTER_TICK (next) = tick;
7457                   else
7458                     tick = INTER_TICK (next);
7459
7460                   INSN_TICK (next) = tick;
7461                 }
7462             }
7463         }
7464     }
7465   bitmap_clear (&processed);
7466 }
7467
7468 /* Check if NEXT is ready to be added to the ready or queue list.
7469    If "yes", add it to the proper list.
7470    Returns:
7471       -1 - is not ready yet,
7472        0 - added to the ready list,
7473    0 < N - queued for N cycles.  */
7474 int
7475 try_ready (rtx_insn *next)
7476 {
7477   ds_t old_ts, new_ts;
7478
7479   old_ts = TODO_SPEC (next);
7480
7481   gcc_assert (!(old_ts & ~(SPECULATIVE | HARD_DEP | DEP_CONTROL | DEP_POSTPONED))
7482               && (old_ts == HARD_DEP
7483                   || old_ts == DEP_POSTPONED
7484                   || (old_ts & SPECULATIVE)
7485                   || old_ts == DEP_CONTROL));
7486
7487   new_ts = recompute_todo_spec (next, false);
7488
7489   if (new_ts & (HARD_DEP | DEP_POSTPONED))
7490     gcc_assert (new_ts == old_ts
7491                 && QUEUE_INDEX (next) == QUEUE_NOWHERE);
7492   else if (current_sched_info->new_ready)
7493     new_ts = current_sched_info->new_ready (next, new_ts);
7494
7495   /* * if !(old_ts & SPECULATIVE) (e.g. HARD_DEP or 0), then insn might
7496      have its original pattern or changed (speculative) one.  This is due
7497      to changing ebb in region scheduling.
7498      * But if (old_ts & SPECULATIVE), then we are pretty sure that insn
7499      has speculative pattern.
7500
7501      We can't assert (!(new_ts & HARD_DEP) || new_ts == old_ts) here because
7502      control-speculative NEXT could have been discarded by sched-rgn.c
7503      (the same case as when discarded by can_schedule_ready_p ()).  */
7504
7505   if ((new_ts & SPECULATIVE)
7506       /* If (old_ts == new_ts), then (old_ts & SPECULATIVE) and we don't
7507          need to change anything.  */
7508       && new_ts != old_ts)
7509     {
7510       int res;
7511       rtx new_pat;
7512
7513       gcc_assert ((new_ts & SPECULATIVE) && !(new_ts & ~SPECULATIVE));
7514
7515       res = haifa_speculate_insn (next, new_ts, &new_pat);
7516
7517       switch (res)
7518         {
7519         case -1:
7520           /* It would be nice to change DEP_STATUS of all dependences,
7521              which have ((DEP_STATUS & SPECULATIVE) == new_ts) to HARD_DEP,
7522              so we won't reanalyze anything.  */
7523           new_ts = HARD_DEP;
7524           break;
7525
7526         case 0:
7527           /* We follow the rule, that every speculative insn
7528              has non-null ORIG_PAT.  */
7529           if (!ORIG_PAT (next))
7530             ORIG_PAT (next) = PATTERN (next);
7531           break;
7532
7533         case 1:
7534           if (!ORIG_PAT (next))
7535             /* If we gonna to overwrite the original pattern of insn,
7536                save it.  */
7537             ORIG_PAT (next) = PATTERN (next);
7538
7539           res = haifa_change_pattern (next, new_pat);
7540           gcc_assert (res);
7541           break;
7542
7543         default:
7544           gcc_unreachable ();
7545         }
7546     }
7547
7548   /* We need to restore pattern only if (new_ts == 0), because otherwise it is
7549      either correct (new_ts & SPECULATIVE),
7550      or we simply don't care (new_ts & HARD_DEP).  */
7551
7552   gcc_assert (!ORIG_PAT (next)
7553               || !IS_SPECULATION_BRANCHY_CHECK_P (next));
7554
7555   TODO_SPEC (next) = new_ts;
7556
7557   if (new_ts & (HARD_DEP | DEP_POSTPONED))
7558     {
7559       /* We can't assert (QUEUE_INDEX (next) == QUEUE_NOWHERE) here because
7560          control-speculative NEXT could have been discarded by sched-rgn.c
7561          (the same case as when discarded by can_schedule_ready_p ()).  */
7562       /*gcc_assert (QUEUE_INDEX (next) == QUEUE_NOWHERE);*/
7563
7564       change_queue_index (next, QUEUE_NOWHERE);
7565
7566       return -1;
7567     }
7568   else if (!(new_ts & BEGIN_SPEC)
7569            && ORIG_PAT (next) && PREDICATED_PAT (next) == NULL_RTX
7570            && !IS_SPECULATION_CHECK_P (next))
7571     /* We should change pattern of every previously speculative
7572        instruction - and we determine if NEXT was speculative by using
7573        ORIG_PAT field.  Except one case - speculation checks have ORIG_PAT
7574        pat too, so skip them.  */
7575     {
7576       bool success = haifa_change_pattern (next, ORIG_PAT (next));
7577       gcc_assert (success);
7578       ORIG_PAT (next) = 0;
7579     }
7580
7581   if (sched_verbose >= 2)
7582     {
7583       fprintf (sched_dump, ";;\t\tdependencies resolved: insn %s",
7584                (*current_sched_info->print_insn) (next, 0));
7585
7586       if (spec_info && spec_info->dump)
7587         {
7588           if (new_ts & BEGIN_DATA)
7589             fprintf (spec_info->dump, "; data-spec;");
7590           if (new_ts & BEGIN_CONTROL)
7591             fprintf (spec_info->dump, "; control-spec;");
7592           if (new_ts & BE_IN_CONTROL)
7593             fprintf (spec_info->dump, "; in-control-spec;");
7594         }
7595       if (TODO_SPEC (next) & DEP_CONTROL)
7596         fprintf (sched_dump, " predicated");
7597       fprintf (sched_dump, "\n");
7598     }
7599
7600   adjust_priority (next);
7601
7602   return fix_tick_ready (next);
7603 }
7604
7605 /* Calculate INSN_TICK of NEXT and add it to either ready or queue list.  */
7606 static int
7607 fix_tick_ready (rtx_insn *next)
7608 {
7609   int tick, delay;
7610
7611   if (!DEBUG_INSN_P (next) && !sd_lists_empty_p (next, SD_LIST_RES_BACK))
7612     {
7613       int full_p;
7614       sd_iterator_def sd_it;
7615       dep_t dep;
7616
7617       tick = INSN_TICK (next);
7618       /* if tick is not equal to INVALID_TICK, then update
7619          INSN_TICK of NEXT with the most recent resolved dependence
7620          cost.  Otherwise, recalculate from scratch.  */
7621       full_p = (tick == INVALID_TICK);
7622
7623       FOR_EACH_DEP (next, SD_LIST_RES_BACK, sd_it, dep)
7624         {
7625           rtx_insn *pro = DEP_PRO (dep);
7626           int tick1;
7627
7628           gcc_assert (INSN_TICK (pro) >= MIN_TICK);
7629
7630           tick1 = INSN_TICK (pro) + dep_cost (dep);
7631           if (tick1 > tick)
7632             tick = tick1;
7633
7634           if (!full_p)
7635             break;
7636         }
7637     }
7638   else
7639     tick = -1;
7640
7641   INSN_TICK (next) = tick;
7642
7643   delay = tick - clock_var;
7644   if (delay <= 0 || sched_pressure != SCHED_PRESSURE_NONE || sched_fusion)
7645     delay = QUEUE_READY;
7646
7647   change_queue_index (next, delay);
7648
7649   return delay;
7650 }
7651
7652 /* Move NEXT to the proper queue list with (DELAY >= 1),
7653    or add it to the ready list (DELAY == QUEUE_READY),
7654    or remove it from ready and queue lists at all (DELAY == QUEUE_NOWHERE).  */
7655 static void
7656 change_queue_index (rtx_insn *next, int delay)
7657 {
7658   int i = QUEUE_INDEX (next);
7659
7660   gcc_assert (QUEUE_NOWHERE <= delay && delay <= max_insn_queue_index
7661               && delay != 0);
7662   gcc_assert (i != QUEUE_SCHEDULED);
7663
7664   if ((delay > 0 && NEXT_Q_AFTER (q_ptr, delay) == i)
7665       || (delay < 0 && delay == i))
7666     /* We have nothing to do.  */
7667     return;
7668
7669   /* Remove NEXT from wherever it is now.  */
7670   if (i == QUEUE_READY)
7671     ready_remove_insn (next);
7672   else if (i >= 0)
7673     queue_remove (next);
7674
7675   /* Add it to the proper place.  */
7676   if (delay == QUEUE_READY)
7677     ready_add (readyp, next, false);
7678   else if (delay >= 1)
7679     queue_insn (next, delay, "change queue index");
7680
7681   if (sched_verbose >= 2)
7682     {
7683       fprintf (sched_dump, ";;\t\ttick updated: insn %s",
7684                (*current_sched_info->print_insn) (next, 0));
7685
7686       if (delay == QUEUE_READY)
7687         fprintf (sched_dump, " into ready\n");
7688       else if (delay >= 1)
7689         fprintf (sched_dump, " into queue with cost=%d\n", delay);
7690       else
7691         fprintf (sched_dump, " removed from ready or queue lists\n");
7692     }
7693 }
7694
7695 static int sched_ready_n_insns = -1;
7696
7697 /* Initialize per region data structures.  */
7698 void
7699 sched_extend_ready_list (int new_sched_ready_n_insns)
7700 {
7701   int i;
7702
7703   if (sched_ready_n_insns == -1)
7704     /* At the first call we need to initialize one more choice_stack
7705        entry.  */
7706     {
7707       i = 0;
7708       sched_ready_n_insns = 0;
7709       scheduled_insns.reserve (new_sched_ready_n_insns);
7710     }
7711   else
7712     i = sched_ready_n_insns + 1;
7713
7714   ready.veclen = new_sched_ready_n_insns + issue_rate;
7715   ready.vec = XRESIZEVEC (rtx_insn *, ready.vec, ready.veclen);
7716
7717   gcc_assert (new_sched_ready_n_insns >= sched_ready_n_insns);
7718
7719   ready_try = (signed char *) xrecalloc (ready_try, new_sched_ready_n_insns,
7720                                          sched_ready_n_insns,
7721                                          sizeof (*ready_try));
7722
7723   /* We allocate +1 element to save initial state in the choice_stack[0]
7724      entry.  */
7725   choice_stack = XRESIZEVEC (struct choice_entry, choice_stack,
7726                              new_sched_ready_n_insns + 1);
7727
7728   for (; i <= new_sched_ready_n_insns; i++)
7729     {
7730       choice_stack[i].state = xmalloc (dfa_state_size);
7731
7732       if (targetm.sched.first_cycle_multipass_init)
7733         targetm.sched.first_cycle_multipass_init (&(choice_stack[i]
7734                                                     .target_data));
7735     }
7736
7737   sched_ready_n_insns = new_sched_ready_n_insns;
7738 }
7739
7740 /* Free per region data structures.  */
7741 void
7742 sched_finish_ready_list (void)
7743 {
7744   int i;
7745
7746   free (ready.vec);
7747   ready.vec = NULL;
7748   ready.veclen = 0;
7749
7750   free (ready_try);
7751   ready_try = NULL;
7752
7753   for (i = 0; i <= sched_ready_n_insns; i++)
7754     {
7755       if (targetm.sched.first_cycle_multipass_fini)
7756         targetm.sched.first_cycle_multipass_fini (&(choice_stack[i]
7757                                                     .target_data));
7758
7759       free (choice_stack [i].state);
7760     }
7761   free (choice_stack);
7762   choice_stack = NULL;
7763
7764   sched_ready_n_insns = -1;
7765 }
7766
7767 static int
7768 haifa_luid_for_non_insn (rtx x)
7769 {
7770   gcc_assert (NOTE_P (x) || LABEL_P (x));
7771
7772   return 0;
7773 }
7774
7775 /* Generates recovery code for INSN.  */
7776 static void
7777 generate_recovery_code (rtx_insn *insn)
7778 {
7779   if (TODO_SPEC (insn) & BEGIN_SPEC)
7780     begin_speculative_block (insn);
7781
7782   /* Here we have insn with no dependencies to
7783      instructions other then CHECK_SPEC ones.  */
7784
7785   if (TODO_SPEC (insn) & BE_IN_SPEC)
7786     add_to_speculative_block (insn);
7787 }
7788
7789 /* Helper function.
7790    Tries to add speculative dependencies of type FS between instructions
7791    in deps_list L and TWIN.  */
7792 static void
7793 process_insn_forw_deps_be_in_spec (rtx insn, rtx_insn *twin, ds_t fs)
7794 {
7795   sd_iterator_def sd_it;
7796   dep_t dep;
7797
7798   FOR_EACH_DEP (insn, SD_LIST_FORW, sd_it, dep)
7799     {
7800       ds_t ds;
7801       rtx_insn *consumer;
7802
7803       consumer = DEP_CON (dep);
7804
7805       ds = DEP_STATUS (dep);
7806
7807       if (/* If we want to create speculative dep.  */
7808           fs
7809           /* And we can do that because this is a true dep.  */
7810           && (ds & DEP_TYPES) == DEP_TRUE)
7811         {
7812           gcc_assert (!(ds & BE_IN_SPEC));
7813
7814           if (/* If this dep can be overcome with 'begin speculation'.  */
7815               ds & BEGIN_SPEC)
7816             /* Then we have a choice: keep the dep 'begin speculative'
7817                or transform it into 'be in speculative'.  */
7818             {
7819               if (/* In try_ready we assert that if insn once became ready
7820                      it can be removed from the ready (or queue) list only
7821                      due to backend decision.  Hence we can't let the
7822                      probability of the speculative dep to decrease.  */
7823                   ds_weak (ds) <= ds_weak (fs))
7824                 {
7825                   ds_t new_ds;
7826
7827                   new_ds = (ds & ~BEGIN_SPEC) | fs;
7828
7829                   if (/* consumer can 'be in speculative'.  */
7830                       sched_insn_is_legitimate_for_speculation_p (consumer,
7831                                                                   new_ds))
7832                     /* Transform it to be in speculative.  */
7833                     ds = new_ds;
7834                 }
7835             }
7836           else
7837             /* Mark the dep as 'be in speculative'.  */
7838             ds |= fs;
7839         }
7840
7841       {
7842         dep_def _new_dep, *new_dep = &_new_dep;
7843
7844         init_dep_1 (new_dep, twin, consumer, DEP_TYPE (dep), ds);
7845         sd_add_dep (new_dep, false);
7846       }
7847     }
7848 }
7849
7850 /* Generates recovery code for BEGIN speculative INSN.  */
7851 static void
7852 begin_speculative_block (rtx_insn *insn)
7853 {
7854   if (TODO_SPEC (insn) & BEGIN_DATA)
7855     nr_begin_data++;
7856   if (TODO_SPEC (insn) & BEGIN_CONTROL)
7857     nr_begin_control++;
7858
7859   create_check_block_twin (insn, false);
7860
7861   TODO_SPEC (insn) &= ~BEGIN_SPEC;
7862 }
7863
7864 static void haifa_init_insn (rtx_insn *);
7865
7866 /* Generates recovery code for BE_IN speculative INSN.  */
7867 static void
7868 add_to_speculative_block (rtx_insn *insn)
7869 {
7870   ds_t ts;
7871   sd_iterator_def sd_it;
7872   dep_t dep;
7873   rtx_insn_list *twins = NULL;
7874   rtx_vec_t priorities_roots;
7875
7876   ts = TODO_SPEC (insn);
7877   gcc_assert (!(ts & ~BE_IN_SPEC));
7878
7879   if (ts & BE_IN_DATA)
7880     nr_be_in_data++;
7881   if (ts & BE_IN_CONTROL)
7882     nr_be_in_control++;
7883
7884   TODO_SPEC (insn) &= ~BE_IN_SPEC;
7885   gcc_assert (!TODO_SPEC (insn));
7886
7887   DONE_SPEC (insn) |= ts;
7888
7889   /* First we convert all simple checks to branchy.  */
7890   for (sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
7891        sd_iterator_cond (&sd_it, &dep);)
7892     {
7893       rtx_insn *check = DEP_PRO (dep);
7894
7895       if (IS_SPECULATION_SIMPLE_CHECK_P (check))
7896         {
7897           create_check_block_twin (check, true);
7898
7899           /* Restart search.  */
7900           sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
7901         }
7902       else
7903         /* Continue search.  */
7904         sd_iterator_next (&sd_it);
7905     }
7906
7907   priorities_roots.create (0);
7908   clear_priorities (insn, &priorities_roots);
7909
7910   while (1)
7911     {
7912       rtx_insn *check, *twin;
7913       basic_block rec;
7914
7915       /* Get the first backward dependency of INSN.  */
7916       sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
7917       if (!sd_iterator_cond (&sd_it, &dep))
7918         /* INSN has no backward dependencies left.  */
7919         break;
7920
7921       gcc_assert ((DEP_STATUS (dep) & BEGIN_SPEC) == 0
7922                   && (DEP_STATUS (dep) & BE_IN_SPEC) != 0
7923                   && (DEP_STATUS (dep) & DEP_TYPES) == DEP_TRUE);
7924
7925       check = DEP_PRO (dep);
7926
7927       gcc_assert (!IS_SPECULATION_CHECK_P (check) && !ORIG_PAT (check)
7928                   && QUEUE_INDEX (check) == QUEUE_NOWHERE);
7929
7930       rec = BLOCK_FOR_INSN (check);
7931
7932       twin = emit_insn_before (copy_insn (PATTERN (insn)), BB_END (rec));
7933       haifa_init_insn (twin);
7934
7935       sd_copy_back_deps (twin, insn, true);
7936
7937       if (sched_verbose && spec_info->dump)
7938         /* INSN_BB (insn) isn't determined for twin insns yet.
7939            So we can't use current_sched_info->print_insn.  */
7940         fprintf (spec_info->dump, ";;\t\tGenerated twin insn : %d/rec%d\n",
7941                  INSN_UID (twin), rec->index);
7942
7943       twins = alloc_INSN_LIST (twin, twins);
7944
7945       /* Add dependences between TWIN and all appropriate
7946          instructions from REC.  */
7947       FOR_EACH_DEP (insn, SD_LIST_SPEC_BACK, sd_it, dep)
7948         {
7949           rtx_insn *pro = DEP_PRO (dep);
7950
7951           gcc_assert (DEP_TYPE (dep) == REG_DEP_TRUE);
7952
7953           /* INSN might have dependencies from the instructions from
7954              several recovery blocks.  At this iteration we process those
7955              producers that reside in REC.  */
7956           if (BLOCK_FOR_INSN (pro) == rec)
7957             {
7958               dep_def _new_dep, *new_dep = &_new_dep;
7959
7960               init_dep (new_dep, pro, twin, REG_DEP_TRUE);
7961               sd_add_dep (new_dep, false);
7962             }
7963         }
7964
7965       process_insn_forw_deps_be_in_spec (insn, twin, ts);
7966
7967       /* Remove all dependencies between INSN and insns in REC.  */
7968       for (sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
7969            sd_iterator_cond (&sd_it, &dep);)
7970         {
7971           rtx_insn *pro = DEP_PRO (dep);
7972
7973           if (BLOCK_FOR_INSN (pro) == rec)
7974             sd_delete_dep (sd_it);
7975           else
7976             sd_iterator_next (&sd_it);
7977         }
7978     }
7979
7980   /* We couldn't have added the dependencies between INSN and TWINS earlier
7981      because that would make TWINS appear in the INSN_BACK_DEPS (INSN).  */
7982   while (twins)
7983     {
7984       rtx_insn *twin;
7985       rtx_insn_list *next_node;
7986
7987       twin = twins->insn ();
7988
7989       {
7990         dep_def _new_dep, *new_dep = &_new_dep;
7991
7992         init_dep (new_dep, insn, twin, REG_DEP_OUTPUT);
7993         sd_add_dep (new_dep, false);
7994       }
7995
7996       next_node = twins->next ();
7997       free_INSN_LIST_node (twins);
7998       twins = next_node;
7999     }
8000
8001   calc_priorities (priorities_roots);
8002   priorities_roots.release ();
8003 }
8004
8005 /* Extends and fills with zeros (only the new part) array pointed to by P.  */
8006 void *
8007 xrecalloc (void *p, size_t new_nmemb, size_t old_nmemb, size_t size)
8008 {
8009   gcc_assert (new_nmemb >= old_nmemb);
8010   p = XRESIZEVAR (void, p, new_nmemb * size);
8011   memset (((char *) p) + old_nmemb * size, 0, (new_nmemb - old_nmemb) * size);
8012   return p;
8013 }
8014
8015 /* Helper function.
8016    Find fallthru edge from PRED.  */
8017 edge
8018 find_fallthru_edge_from (basic_block pred)
8019 {
8020   edge e;
8021   basic_block succ;
8022
8023   succ = pred->next_bb;
8024   gcc_assert (succ->prev_bb == pred);
8025
8026   if (EDGE_COUNT (pred->succs) <= EDGE_COUNT (succ->preds))
8027     {
8028       e = find_fallthru_edge (pred->succs);
8029
8030       if (e)
8031         {
8032           gcc_assert (e->dest == succ);
8033           return e;
8034         }
8035     }
8036   else
8037     {
8038       e = find_fallthru_edge (succ->preds);
8039
8040       if (e)
8041         {
8042           gcc_assert (e->src == pred);
8043           return e;
8044         }
8045     }
8046
8047   return NULL;
8048 }
8049
8050 /* Extend per basic block data structures.  */
8051 static void
8052 sched_extend_bb (void)
8053 {
8054   /* The following is done to keep current_sched_info->next_tail non null.  */
8055   rtx_insn *end = BB_END (EXIT_BLOCK_PTR_FOR_FN (cfun)->prev_bb);
8056   rtx_insn *insn = DEBUG_INSN_P (end) ? prev_nondebug_insn (end) : end;
8057   if (NEXT_INSN (end) == 0
8058       || (!NOTE_P (insn)
8059           && !LABEL_P (insn)
8060           /* Don't emit a NOTE if it would end up before a BARRIER.  */
8061           && !BARRIER_P (NEXT_INSN (end))))
8062     {
8063       rtx_note *note = emit_note_after (NOTE_INSN_DELETED, end);
8064       /* Make note appear outside BB.  */
8065       set_block_for_insn (note, NULL);
8066       BB_END (EXIT_BLOCK_PTR_FOR_FN (cfun)->prev_bb) = end;
8067     }
8068 }
8069
8070 /* Init per basic block data structures.  */
8071 void
8072 sched_init_bbs (void)
8073 {
8074   sched_extend_bb ();
8075 }
8076
8077 /* Initialize BEFORE_RECOVERY variable.  */
8078 static void
8079 init_before_recovery (basic_block *before_recovery_ptr)
8080 {
8081   basic_block last;
8082   edge e;
8083
8084   last = EXIT_BLOCK_PTR_FOR_FN (cfun)->prev_bb;
8085   e = find_fallthru_edge_from (last);
8086
8087   if (e)
8088     {
8089       /* We create two basic blocks:
8090          1. Single instruction block is inserted right after E->SRC
8091          and has jump to
8092          2. Empty block right before EXIT_BLOCK.
8093          Between these two blocks recovery blocks will be emitted.  */
8094
8095       basic_block single, empty;
8096       rtx_insn *x;
8097       rtx label;
8098
8099       /* If the fallthrough edge to exit we've found is from the block we've
8100          created before, don't do anything more.  */
8101       if (last == after_recovery)
8102         return;
8103
8104       adding_bb_to_current_region_p = false;
8105
8106       single = sched_create_empty_bb (last);
8107       empty = sched_create_empty_bb (single);
8108
8109       /* Add new blocks to the root loop.  */
8110       if (current_loops != NULL)
8111         {
8112           add_bb_to_loop (single, (*current_loops->larray)[0]);
8113           add_bb_to_loop (empty, (*current_loops->larray)[0]);
8114         }
8115
8116       single->count = last->count;
8117       empty->count = last->count;
8118       single->frequency = last->frequency;
8119       empty->frequency = last->frequency;
8120       BB_COPY_PARTITION (single, last);
8121       BB_COPY_PARTITION (empty, last);
8122
8123       redirect_edge_succ (e, single);
8124       make_single_succ_edge (single, empty, 0);
8125       make_single_succ_edge (empty, EXIT_BLOCK_PTR_FOR_FN (cfun),
8126                              EDGE_FALLTHRU);
8127
8128       label = block_label (empty);
8129       x = emit_jump_insn_after (gen_jump (label), BB_END (single));
8130       JUMP_LABEL (x) = label;
8131       LABEL_NUSES (label)++;
8132       haifa_init_insn (x);
8133
8134       emit_barrier_after (x);
8135
8136       sched_init_only_bb (empty, NULL);
8137       sched_init_only_bb (single, NULL);
8138       sched_extend_bb ();
8139
8140       adding_bb_to_current_region_p = true;
8141       before_recovery = single;
8142       after_recovery = empty;
8143
8144       if (before_recovery_ptr)
8145         *before_recovery_ptr = before_recovery;
8146
8147       if (sched_verbose >= 2 && spec_info->dump)
8148         fprintf (spec_info->dump,
8149                  ";;\t\tFixed fallthru to EXIT : %d->>%d->%d->>EXIT\n",
8150                  last->index, single->index, empty->index);
8151     }
8152   else
8153     before_recovery = last;
8154 }
8155
8156 /* Returns new recovery block.  */
8157 basic_block
8158 sched_create_recovery_block (basic_block *before_recovery_ptr)
8159 {
8160   rtx label;
8161   rtx_insn *barrier;
8162   basic_block rec;
8163
8164   haifa_recovery_bb_recently_added_p = true;
8165   haifa_recovery_bb_ever_added_p = true;
8166
8167   init_before_recovery (before_recovery_ptr);
8168
8169   barrier = get_last_bb_insn (before_recovery);
8170   gcc_assert (BARRIER_P (barrier));
8171
8172   label = emit_label_after (gen_label_rtx (), barrier);
8173
8174   rec = create_basic_block (label, label, before_recovery);
8175
8176   /* A recovery block always ends with an unconditional jump.  */
8177   emit_barrier_after (BB_END (rec));
8178
8179   if (BB_PARTITION (before_recovery) != BB_UNPARTITIONED)
8180     BB_SET_PARTITION (rec, BB_COLD_PARTITION);
8181
8182   if (sched_verbose && spec_info->dump)
8183     fprintf (spec_info->dump, ";;\t\tGenerated recovery block rec%d\n",
8184              rec->index);
8185
8186   return rec;
8187 }
8188
8189 /* Create edges: FIRST_BB -> REC; FIRST_BB -> SECOND_BB; REC -> SECOND_BB
8190    and emit necessary jumps.  */
8191 void
8192 sched_create_recovery_edges (basic_block first_bb, basic_block rec,
8193                              basic_block second_bb)
8194 {
8195   rtx label;
8196   rtx jump;
8197   int edge_flags;
8198
8199   /* This is fixing of incoming edge.  */
8200   /* ??? Which other flags should be specified?  */
8201   if (BB_PARTITION (first_bb) != BB_PARTITION (rec))
8202     /* Partition type is the same, if it is "unpartitioned".  */
8203     edge_flags = EDGE_CROSSING;
8204   else
8205     edge_flags = 0;
8206
8207   make_edge (first_bb, rec, edge_flags);
8208   label = block_label (second_bb);
8209   jump = emit_jump_insn_after (gen_jump (label), BB_END (rec));
8210   JUMP_LABEL (jump) = label;
8211   LABEL_NUSES (label)++;
8212
8213   if (BB_PARTITION (second_bb) != BB_PARTITION (rec))
8214     /* Partition type is the same, if it is "unpartitioned".  */
8215     {
8216       /* Rewritten from cfgrtl.c.  */
8217       if (flag_reorder_blocks_and_partition
8218           && targetm_common.have_named_sections)
8219         {
8220           /* We don't need the same note for the check because
8221              any_condjump_p (check) == true.  */
8222           CROSSING_JUMP_P (jump) = 1;
8223         }
8224       edge_flags = EDGE_CROSSING;
8225     }
8226   else
8227     edge_flags = 0;
8228
8229   make_single_succ_edge (rec, second_bb, edge_flags);
8230   if (dom_info_available_p (CDI_DOMINATORS))
8231     set_immediate_dominator (CDI_DOMINATORS, rec, first_bb);
8232 }
8233
8234 /* This function creates recovery code for INSN.  If MUTATE_P is nonzero,
8235    INSN is a simple check, that should be converted to branchy one.  */
8236 static void
8237 create_check_block_twin (rtx_insn *insn, bool mutate_p)
8238 {
8239   basic_block rec;
8240   rtx_insn *label, *check, *twin;
8241   rtx check_pat;
8242   ds_t fs;
8243   sd_iterator_def sd_it;
8244   dep_t dep;
8245   dep_def _new_dep, *new_dep = &_new_dep;
8246   ds_t todo_spec;
8247
8248   gcc_assert (ORIG_PAT (insn) != NULL_RTX);
8249
8250   if (!mutate_p)
8251     todo_spec = TODO_SPEC (insn);
8252   else
8253     {
8254       gcc_assert (IS_SPECULATION_SIMPLE_CHECK_P (insn)
8255                   && (TODO_SPEC (insn) & SPECULATIVE) == 0);
8256
8257       todo_spec = CHECK_SPEC (insn);
8258     }
8259
8260   todo_spec &= SPECULATIVE;
8261
8262   /* Create recovery block.  */
8263   if (mutate_p || targetm.sched.needs_block_p (todo_spec))
8264     {
8265       rec = sched_create_recovery_block (NULL);
8266       label = BB_HEAD (rec);
8267     }
8268   else
8269     {
8270       rec = EXIT_BLOCK_PTR_FOR_FN (cfun);
8271       label = NULL;
8272     }
8273
8274   /* Emit CHECK.  */
8275   check_pat = targetm.sched.gen_spec_check (insn, label, todo_spec);
8276
8277   if (rec != EXIT_BLOCK_PTR_FOR_FN (cfun))
8278     {
8279       /* To have mem_reg alive at the beginning of second_bb,
8280          we emit check BEFORE insn, so insn after splitting
8281          insn will be at the beginning of second_bb, which will
8282          provide us with the correct life information.  */
8283       check = emit_jump_insn_before (check_pat, insn);
8284       JUMP_LABEL (check) = label;
8285       LABEL_NUSES (label)++;
8286     }
8287   else
8288     check = emit_insn_before (check_pat, insn);
8289
8290   /* Extend data structures.  */
8291   haifa_init_insn (check);
8292
8293   /* CHECK is being added to current region.  Extend ready list.  */
8294   gcc_assert (sched_ready_n_insns != -1);
8295   sched_extend_ready_list (sched_ready_n_insns + 1);
8296
8297   if (current_sched_info->add_remove_insn)
8298     current_sched_info->add_remove_insn (insn, 0);
8299
8300   RECOVERY_BLOCK (check) = rec;
8301
8302   if (sched_verbose && spec_info->dump)
8303     fprintf (spec_info->dump, ";;\t\tGenerated check insn : %s\n",
8304              (*current_sched_info->print_insn) (check, 0));
8305
8306   gcc_assert (ORIG_PAT (insn));
8307
8308   /* Initialize TWIN (twin is a duplicate of original instruction
8309      in the recovery block).  */
8310   if (rec != EXIT_BLOCK_PTR_FOR_FN (cfun))
8311     {
8312       sd_iterator_def sd_it;
8313       dep_t dep;
8314
8315       FOR_EACH_DEP (insn, SD_LIST_RES_BACK, sd_it, dep)
8316         if ((DEP_STATUS (dep) & DEP_OUTPUT) != 0)
8317           {
8318             struct _dep _dep2, *dep2 = &_dep2;
8319
8320             init_dep (dep2, DEP_PRO (dep), check, REG_DEP_TRUE);
8321
8322             sd_add_dep (dep2, true);
8323           }
8324
8325       twin = emit_insn_after (ORIG_PAT (insn), BB_END (rec));
8326       haifa_init_insn (twin);
8327
8328       if (sched_verbose && spec_info->dump)
8329         /* INSN_BB (insn) isn't determined for twin insns yet.
8330            So we can't use current_sched_info->print_insn.  */
8331         fprintf (spec_info->dump, ";;\t\tGenerated twin insn : %d/rec%d\n",
8332                  INSN_UID (twin), rec->index);
8333     }
8334   else
8335     {
8336       ORIG_PAT (check) = ORIG_PAT (insn);
8337       HAS_INTERNAL_DEP (check) = 1;
8338       twin = check;
8339       /* ??? We probably should change all OUTPUT dependencies to
8340          (TRUE | OUTPUT).  */
8341     }
8342
8343   /* Copy all resolved back dependencies of INSN to TWIN.  This will
8344      provide correct value for INSN_TICK (TWIN).  */
8345   sd_copy_back_deps (twin, insn, true);
8346
8347   if (rec != EXIT_BLOCK_PTR_FOR_FN (cfun))
8348     /* In case of branchy check, fix CFG.  */
8349     {
8350       basic_block first_bb, second_bb;
8351       rtx_insn *jump;
8352
8353       first_bb = BLOCK_FOR_INSN (check);
8354       second_bb = sched_split_block (first_bb, check);
8355
8356       sched_create_recovery_edges (first_bb, rec, second_bb);
8357
8358       sched_init_only_bb (second_bb, first_bb);
8359       sched_init_only_bb (rec, EXIT_BLOCK_PTR_FOR_FN (cfun));
8360
8361       jump = BB_END (rec);
8362       haifa_init_insn (jump);
8363     }
8364
8365   /* Move backward dependences from INSN to CHECK and
8366      move forward dependences from INSN to TWIN.  */
8367
8368   /* First, create dependencies between INSN's producers and CHECK & TWIN.  */
8369   FOR_EACH_DEP (insn, SD_LIST_BACK, sd_it, dep)
8370     {
8371       rtx_insn *pro = DEP_PRO (dep);
8372       ds_t ds;
8373
8374       /* If BEGIN_DATA: [insn ~~TRUE~~> producer]:
8375          check --TRUE--> producer  ??? or ANTI ???
8376          twin  --TRUE--> producer
8377          twin  --ANTI--> check
8378
8379          If BEGIN_CONTROL: [insn ~~ANTI~~> producer]:
8380          check --ANTI--> producer
8381          twin  --ANTI--> producer
8382          twin  --ANTI--> check
8383
8384          If BE_IN_SPEC: [insn ~~TRUE~~> producer]:
8385          check ~~TRUE~~> producer
8386          twin  ~~TRUE~~> producer
8387          twin  --ANTI--> check  */
8388
8389       ds = DEP_STATUS (dep);
8390
8391       if (ds & BEGIN_SPEC)
8392         {
8393           gcc_assert (!mutate_p);
8394           ds &= ~BEGIN_SPEC;
8395         }
8396
8397       init_dep_1 (new_dep, pro, check, DEP_TYPE (dep), ds);
8398       sd_add_dep (new_dep, false);
8399
8400       if (rec != EXIT_BLOCK_PTR_FOR_FN (cfun))
8401         {
8402           DEP_CON (new_dep) = twin;
8403           sd_add_dep (new_dep, false);
8404         }
8405     }
8406
8407   /* Second, remove backward dependencies of INSN.  */
8408   for (sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
8409        sd_iterator_cond (&sd_it, &dep);)
8410     {
8411       if ((DEP_STATUS (dep) & BEGIN_SPEC)
8412           || mutate_p)
8413         /* We can delete this dep because we overcome it with
8414            BEGIN_SPECULATION.  */
8415         sd_delete_dep (sd_it);
8416       else
8417         sd_iterator_next (&sd_it);
8418     }
8419
8420   /* Future Speculations.  Determine what BE_IN speculations will be like.  */
8421   fs = 0;
8422
8423   /* Fields (DONE_SPEC (x) & BEGIN_SPEC) and CHECK_SPEC (x) are set only
8424      here.  */
8425
8426   gcc_assert (!DONE_SPEC (insn));
8427
8428   if (!mutate_p)
8429     {
8430       ds_t ts = TODO_SPEC (insn);
8431
8432       DONE_SPEC (insn) = ts & BEGIN_SPEC;
8433       CHECK_SPEC (check) = ts & BEGIN_SPEC;
8434
8435       /* Luckiness of future speculations solely depends upon initial
8436          BEGIN speculation.  */
8437       if (ts & BEGIN_DATA)
8438         fs = set_dep_weak (fs, BE_IN_DATA, get_dep_weak (ts, BEGIN_DATA));
8439       if (ts & BEGIN_CONTROL)
8440         fs = set_dep_weak (fs, BE_IN_CONTROL,
8441                            get_dep_weak (ts, BEGIN_CONTROL));
8442     }
8443   else
8444     CHECK_SPEC (check) = CHECK_SPEC (insn);
8445
8446   /* Future speculations: call the helper.  */
8447   process_insn_forw_deps_be_in_spec (insn, twin, fs);
8448
8449   if (rec != EXIT_BLOCK_PTR_FOR_FN (cfun))
8450     {
8451       /* Which types of dependencies should we use here is,
8452          generally, machine-dependent question...  But, for now,
8453          it is not.  */
8454
8455       if (!mutate_p)
8456         {
8457           init_dep (new_dep, insn, check, REG_DEP_TRUE);
8458           sd_add_dep (new_dep, false);
8459
8460           init_dep (new_dep, insn, twin, REG_DEP_OUTPUT);
8461           sd_add_dep (new_dep, false);
8462         }
8463       else
8464         {
8465           if (spec_info->dump)
8466             fprintf (spec_info->dump, ";;\t\tRemoved simple check : %s\n",
8467                      (*current_sched_info->print_insn) (insn, 0));
8468
8469           /* Remove all dependencies of the INSN.  */
8470           {
8471             sd_it = sd_iterator_start (insn, (SD_LIST_FORW
8472                                               | SD_LIST_BACK
8473                                               | SD_LIST_RES_BACK));
8474             while (sd_iterator_cond (&sd_it, &dep))
8475               sd_delete_dep (sd_it);
8476           }
8477
8478           /* If former check (INSN) already was moved to the ready (or queue)
8479              list, add new check (CHECK) there too.  */
8480           if (QUEUE_INDEX (insn) != QUEUE_NOWHERE)
8481             try_ready (check);
8482
8483           /* Remove old check from instruction stream and free its
8484              data.  */
8485           sched_remove_insn (insn);
8486         }
8487
8488       init_dep (new_dep, check, twin, REG_DEP_ANTI);
8489       sd_add_dep (new_dep, false);
8490     }
8491   else
8492     {
8493       init_dep_1 (new_dep, insn, check, REG_DEP_TRUE, DEP_TRUE | DEP_OUTPUT);
8494       sd_add_dep (new_dep, false);
8495     }
8496
8497   if (!mutate_p)
8498     /* Fix priorities.  If MUTATE_P is nonzero, this is not necessary,
8499        because it'll be done later in add_to_speculative_block.  */
8500     {
8501       rtx_vec_t priorities_roots = rtx_vec_t ();
8502
8503       clear_priorities (twin, &priorities_roots);
8504       calc_priorities (priorities_roots);
8505       priorities_roots.release ();
8506     }
8507 }
8508
8509 /* Removes dependency between instructions in the recovery block REC
8510    and usual region instructions.  It keeps inner dependences so it
8511    won't be necessary to recompute them.  */
8512 static void
8513 fix_recovery_deps (basic_block rec)
8514 {
8515   rtx_insn *note, *insn, *jump;
8516   rtx_insn_list *ready_list = 0;
8517   bitmap_head in_ready;
8518   rtx_insn_list *link;
8519
8520   bitmap_initialize (&in_ready, 0);
8521
8522   /* NOTE - a basic block note.  */
8523   note = NEXT_INSN (BB_HEAD (rec));
8524   gcc_assert (NOTE_INSN_BASIC_BLOCK_P (note));
8525   insn = BB_END (rec);
8526   gcc_assert (JUMP_P (insn));
8527   insn = PREV_INSN (insn);
8528
8529   do
8530     {
8531       sd_iterator_def sd_it;
8532       dep_t dep;
8533
8534       for (sd_it = sd_iterator_start (insn, SD_LIST_FORW);
8535            sd_iterator_cond (&sd_it, &dep);)
8536         {
8537           rtx_insn *consumer = DEP_CON (dep);
8538
8539           if (BLOCK_FOR_INSN (consumer) != rec)
8540             {
8541               sd_delete_dep (sd_it);
8542
8543               if (bitmap_set_bit (&in_ready, INSN_LUID (consumer)))
8544                 ready_list = alloc_INSN_LIST (consumer, ready_list);
8545             }
8546           else
8547             {
8548               gcc_assert ((DEP_STATUS (dep) & DEP_TYPES) == DEP_TRUE);
8549
8550               sd_iterator_next (&sd_it);
8551             }
8552         }
8553
8554       insn = PREV_INSN (insn);
8555     }
8556   while (insn != note);
8557
8558   bitmap_clear (&in_ready);
8559
8560   /* Try to add instructions to the ready or queue list.  */
8561   for (link = ready_list; link; link = link->next ())
8562     try_ready (link->insn ());
8563   free_INSN_LIST_list (&ready_list);
8564
8565   /* Fixing jump's dependences.  */
8566   insn = BB_HEAD (rec);
8567   jump = BB_END (rec);
8568
8569   gcc_assert (LABEL_P (insn));
8570   insn = NEXT_INSN (insn);
8571
8572   gcc_assert (NOTE_INSN_BASIC_BLOCK_P (insn));
8573   add_jump_dependencies (insn, jump);
8574 }
8575
8576 /* Change pattern of INSN to NEW_PAT.  Invalidate cached haifa
8577    instruction data.  */
8578 static bool
8579 haifa_change_pattern (rtx_insn *insn, rtx new_pat)
8580 {
8581   int t;
8582
8583   t = validate_change (insn, &PATTERN (insn), new_pat, 0);
8584   if (!t)
8585     return false;
8586
8587   update_insn_after_change (insn);
8588   return true;
8589 }
8590
8591 /* -1 - can't speculate,
8592    0 - for speculation with REQUEST mode it is OK to use
8593    current instruction pattern,
8594    1 - need to change pattern for *NEW_PAT to be speculative.  */
8595 int
8596 sched_speculate_insn (rtx_insn *insn, ds_t request, rtx *new_pat)
8597 {
8598   gcc_assert (current_sched_info->flags & DO_SPECULATION
8599               && (request & SPECULATIVE)
8600               && sched_insn_is_legitimate_for_speculation_p (insn, request));
8601
8602   if ((request & spec_info->mask) != request)
8603     return -1;
8604
8605   if (request & BE_IN_SPEC
8606       && !(request & BEGIN_SPEC))
8607     return 0;
8608
8609   return targetm.sched.speculate_insn (insn, request, new_pat);
8610 }
8611
8612 static int
8613 haifa_speculate_insn (rtx_insn *insn, ds_t request, rtx *new_pat)
8614 {
8615   gcc_assert (sched_deps_info->generate_spec_deps
8616               && !IS_SPECULATION_CHECK_P (insn));
8617
8618   if (HAS_INTERNAL_DEP (insn)
8619       || SCHED_GROUP_P (insn))
8620     return -1;
8621
8622   return sched_speculate_insn (insn, request, new_pat);
8623 }
8624
8625 /* Print some information about block BB, which starts with HEAD and
8626    ends with TAIL, before scheduling it.
8627    I is zero, if scheduler is about to start with the fresh ebb.  */
8628 static void
8629 dump_new_block_header (int i, basic_block bb, rtx_insn *head, rtx_insn *tail)
8630 {
8631   if (!i)
8632     fprintf (sched_dump,
8633              ";;   ======================================================\n");
8634   else
8635     fprintf (sched_dump,
8636              ";;   =====================ADVANCING TO=====================\n");
8637   fprintf (sched_dump,
8638            ";;   -- basic block %d from %d to %d -- %s reload\n",
8639            bb->index, INSN_UID (head), INSN_UID (tail),
8640            (reload_completed ? "after" : "before"));
8641   fprintf (sched_dump,
8642            ";;   ======================================================\n");
8643   fprintf (sched_dump, "\n");
8644 }
8645
8646 /* Unlink basic block notes and labels and saves them, so they
8647    can be easily restored.  We unlink basic block notes in EBB to
8648    provide back-compatibility with the previous code, as target backends
8649    assume, that there'll be only instructions between
8650    current_sched_info->{head and tail}.  We restore these notes as soon
8651    as we can.
8652    FIRST (LAST) is the first (last) basic block in the ebb.
8653    NB: In usual case (FIRST == LAST) nothing is really done.  */
8654 void
8655 unlink_bb_notes (basic_block first, basic_block last)
8656 {
8657   /* We DON'T unlink basic block notes of the first block in the ebb.  */
8658   if (first == last)
8659     return;
8660
8661   bb_header = XNEWVEC (rtx_insn *, last_basic_block_for_fn (cfun));
8662
8663   /* Make a sentinel.  */
8664   if (last->next_bb != EXIT_BLOCK_PTR_FOR_FN (cfun))
8665     bb_header[last->next_bb->index] = 0;
8666
8667   first = first->next_bb;
8668   do
8669     {
8670       rtx_insn *prev, *label, *note, *next;
8671
8672       label = BB_HEAD (last);
8673       if (LABEL_P (label))
8674         note = NEXT_INSN (label);
8675       else
8676         note = label;
8677       gcc_assert (NOTE_INSN_BASIC_BLOCK_P (note));
8678
8679       prev = PREV_INSN (label);
8680       next = NEXT_INSN (note);
8681       gcc_assert (prev && next);
8682
8683       SET_NEXT_INSN (prev) = next;
8684       SET_PREV_INSN (next) = prev;
8685
8686       bb_header[last->index] = label;
8687
8688       if (last == first)
8689         break;
8690
8691       last = last->prev_bb;
8692     }
8693   while (1);
8694 }
8695
8696 /* Restore basic block notes.
8697    FIRST is the first basic block in the ebb.  */
8698 static void
8699 restore_bb_notes (basic_block first)
8700 {
8701   if (!bb_header)
8702     return;
8703
8704   /* We DON'T unlink basic block notes of the first block in the ebb.  */
8705   first = first->next_bb;
8706   /* Remember: FIRST is actually a second basic block in the ebb.  */
8707
8708   while (first != EXIT_BLOCK_PTR_FOR_FN (cfun)
8709          && bb_header[first->index])
8710     {
8711       rtx_insn *prev, *label, *note, *next;
8712
8713       label = bb_header[first->index];
8714       prev = PREV_INSN (label);
8715       next = NEXT_INSN (prev);
8716
8717       if (LABEL_P (label))
8718         note = NEXT_INSN (label);
8719       else
8720         note = label;
8721       gcc_assert (NOTE_INSN_BASIC_BLOCK_P (note));
8722
8723       bb_header[first->index] = 0;
8724
8725       SET_NEXT_INSN (prev) = label;
8726       SET_NEXT_INSN (note) = next;
8727       SET_PREV_INSN (next) = note;
8728
8729       first = first->next_bb;
8730     }
8731
8732   free (bb_header);
8733   bb_header = 0;
8734 }
8735
8736 /* Helper function.
8737    Fix CFG after both in- and inter-block movement of
8738    control_flow_insn_p JUMP.  */
8739 static void
8740 fix_jump_move (rtx_insn *jump)
8741 {
8742   basic_block bb, jump_bb, jump_bb_next;
8743
8744   bb = BLOCK_FOR_INSN (PREV_INSN (jump));
8745   jump_bb = BLOCK_FOR_INSN (jump);
8746   jump_bb_next = jump_bb->next_bb;
8747
8748   gcc_assert (common_sched_info->sched_pass_id == SCHED_EBB_PASS
8749               || IS_SPECULATION_BRANCHY_CHECK_P (jump));
8750
8751   if (!NOTE_INSN_BASIC_BLOCK_P (BB_END (jump_bb_next)))
8752     /* if jump_bb_next is not empty.  */
8753     BB_END (jump_bb) = BB_END (jump_bb_next);
8754
8755   if (BB_END (bb) != PREV_INSN (jump))
8756     /* Then there are instruction after jump that should be placed
8757        to jump_bb_next.  */
8758     BB_END (jump_bb_next) = BB_END (bb);
8759   else
8760     /* Otherwise jump_bb_next is empty.  */
8761     BB_END (jump_bb_next) = NEXT_INSN (BB_HEAD (jump_bb_next));
8762
8763   /* To make assertion in move_insn happy.  */
8764   BB_END (bb) = PREV_INSN (jump);
8765
8766   update_bb_for_insn (jump_bb_next);
8767 }
8768
8769 /* Fix CFG after interblock movement of control_flow_insn_p JUMP.  */
8770 static void
8771 move_block_after_check (rtx_insn *jump)
8772 {
8773   basic_block bb, jump_bb, jump_bb_next;
8774   vec<edge, va_gc> *t;
8775
8776   bb = BLOCK_FOR_INSN (PREV_INSN (jump));
8777   jump_bb = BLOCK_FOR_INSN (jump);
8778   jump_bb_next = jump_bb->next_bb;
8779
8780   update_bb_for_insn (jump_bb);
8781
8782   gcc_assert (IS_SPECULATION_CHECK_P (jump)
8783               || IS_SPECULATION_CHECK_P (BB_END (jump_bb_next)));
8784
8785   unlink_block (jump_bb_next);
8786   link_block (jump_bb_next, bb);
8787
8788   t = bb->succs;
8789   bb->succs = 0;
8790   move_succs (&(jump_bb->succs), bb);
8791   move_succs (&(jump_bb_next->succs), jump_bb);
8792   move_succs (&t, jump_bb_next);
8793
8794   df_mark_solutions_dirty ();
8795
8796   common_sched_info->fix_recovery_cfg
8797     (bb->index, jump_bb->index, jump_bb_next->index);
8798 }
8799
8800 /* Helper function for move_block_after_check.
8801    This functions attaches edge vector pointed to by SUCCSP to
8802    block TO.  */
8803 static void
8804 move_succs (vec<edge, va_gc> **succsp, basic_block to)
8805 {
8806   edge e;
8807   edge_iterator ei;
8808
8809   gcc_assert (to->succs == 0);
8810
8811   to->succs = *succsp;
8812
8813   FOR_EACH_EDGE (e, ei, to->succs)
8814     e->src = to;
8815
8816   *succsp = 0;
8817 }
8818
8819 /* Remove INSN from the instruction stream.
8820    INSN should have any dependencies.  */
8821 static void
8822 sched_remove_insn (rtx_insn *insn)
8823 {
8824   sd_finish_insn (insn);
8825
8826   change_queue_index (insn, QUEUE_NOWHERE);
8827   current_sched_info->add_remove_insn (insn, 1);
8828   delete_insn (insn);
8829 }
8830
8831 /* Clear priorities of all instructions, that are forward dependent on INSN.
8832    Store in vector pointed to by ROOTS_PTR insns on which priority () should
8833    be invoked to initialize all cleared priorities.  */
8834 static void
8835 clear_priorities (rtx_insn *insn, rtx_vec_t *roots_ptr)
8836 {
8837   sd_iterator_def sd_it;
8838   dep_t dep;
8839   bool insn_is_root_p = true;
8840
8841   gcc_assert (QUEUE_INDEX (insn) != QUEUE_SCHEDULED);
8842
8843   FOR_EACH_DEP (insn, SD_LIST_BACK, sd_it, dep)
8844     {
8845       rtx_insn *pro = DEP_PRO (dep);
8846
8847       if (INSN_PRIORITY_STATUS (pro) >= 0
8848           && QUEUE_INDEX (insn) != QUEUE_SCHEDULED)
8849         {
8850           /* If DEP doesn't contribute to priority then INSN itself should
8851              be added to priority roots.  */
8852           if (contributes_to_priority_p (dep))
8853             insn_is_root_p = false;
8854
8855           INSN_PRIORITY_STATUS (pro) = -1;
8856           clear_priorities (pro, roots_ptr);
8857         }
8858     }
8859
8860   if (insn_is_root_p)
8861     roots_ptr->safe_push (insn);
8862 }
8863
8864 /* Recompute priorities of instructions, whose priorities might have been
8865    changed.  ROOTS is a vector of instructions whose priority computation will
8866    trigger initialization of all cleared priorities.  */
8867 static void
8868 calc_priorities (rtx_vec_t roots)
8869 {
8870   int i;
8871   rtx_insn *insn;
8872
8873   FOR_EACH_VEC_ELT (roots, i, insn)
8874     priority (insn);
8875 }
8876
8877
8878 /* Add dependences between JUMP and other instructions in the recovery
8879    block.  INSN is the first insn the recovery block.  */
8880 static void
8881 add_jump_dependencies (rtx_insn *insn, rtx_insn *jump)
8882 {
8883   do
8884     {
8885       insn = NEXT_INSN (insn);
8886       if (insn == jump)
8887         break;
8888
8889       if (dep_list_size (insn, SD_LIST_FORW) == 0)
8890         {
8891           dep_def _new_dep, *new_dep = &_new_dep;
8892
8893           init_dep (new_dep, insn, jump, REG_DEP_ANTI);
8894           sd_add_dep (new_dep, false);
8895         }
8896     }
8897   while (1);
8898
8899   gcc_assert (!sd_lists_empty_p (jump, SD_LIST_BACK));
8900 }
8901
8902 /* Extend data structures for logical insn UID.  */
8903 void
8904 sched_extend_luids (void)
8905 {
8906   int new_luids_max_uid = get_max_uid () + 1;
8907
8908   sched_luids.safe_grow_cleared (new_luids_max_uid);
8909 }
8910
8911 /* Initialize LUID for INSN.  */
8912 void
8913 sched_init_insn_luid (rtx_insn *insn)
8914 {
8915   int i = INSN_P (insn) ? 1 : common_sched_info->luid_for_non_insn (insn);
8916   int luid;
8917
8918   if (i >= 0)
8919     {
8920       luid = sched_max_luid;
8921       sched_max_luid += i;
8922     }
8923   else
8924     luid = -1;
8925
8926   SET_INSN_LUID (insn, luid);
8927 }
8928
8929 /* Initialize luids for BBS.
8930    The hook common_sched_info->luid_for_non_insn () is used to determine
8931    if notes, labels, etc. need luids.  */
8932 void
8933 sched_init_luids (bb_vec_t bbs)
8934 {
8935   int i;
8936   basic_block bb;
8937
8938   sched_extend_luids ();
8939   FOR_EACH_VEC_ELT (bbs, i, bb)
8940     {
8941       rtx_insn *insn;
8942
8943       FOR_BB_INSNS (bb, insn)
8944         sched_init_insn_luid (insn);
8945     }
8946 }
8947
8948 /* Free LUIDs.  */
8949 void
8950 sched_finish_luids (void)
8951 {
8952   sched_luids.release ();
8953   sched_max_luid = 1;
8954 }
8955
8956 /* Return logical uid of INSN.  Helpful while debugging.  */
8957 int
8958 insn_luid (rtx_insn *insn)
8959 {
8960   return INSN_LUID (insn);
8961 }
8962
8963 /* Extend per insn data in the target.  */
8964 void
8965 sched_extend_target (void)
8966 {
8967   if (targetm.sched.h_i_d_extended)
8968     targetm.sched.h_i_d_extended ();
8969 }
8970
8971 /* Extend global scheduler structures (those, that live across calls to
8972    schedule_block) to include information about just emitted INSN.  */
8973 static void
8974 extend_h_i_d (void)
8975 {
8976   int reserve = (get_max_uid () + 1 - h_i_d.length ());
8977   if (reserve > 0
8978       && ! h_i_d.space (reserve))
8979     {
8980       h_i_d.safe_grow_cleared (3 * get_max_uid () / 2);
8981       sched_extend_target ();
8982     }
8983 }
8984
8985 /* Initialize h_i_d entry of the INSN with default values.
8986    Values, that are not explicitly initialized here, hold zero.  */
8987 static void
8988 init_h_i_d (rtx_insn *insn)
8989 {
8990   if (INSN_LUID (insn) > 0)
8991     {
8992       INSN_COST (insn) = -1;
8993       QUEUE_INDEX (insn) = QUEUE_NOWHERE;
8994       INSN_TICK (insn) = INVALID_TICK;
8995       INSN_EXACT_TICK (insn) = INVALID_TICK;
8996       INTER_TICK (insn) = INVALID_TICK;
8997       TODO_SPEC (insn) = HARD_DEP;
8998       INSN_AUTOPREF_MULTIPASS_DATA (insn)[0].status
8999         = AUTOPREF_MULTIPASS_DATA_UNINITIALIZED;
9000       INSN_AUTOPREF_MULTIPASS_DATA (insn)[1].status
9001         = AUTOPREF_MULTIPASS_DATA_UNINITIALIZED;
9002     }
9003 }
9004
9005 /* Initialize haifa_insn_data for BBS.  */
9006 void
9007 haifa_init_h_i_d (bb_vec_t bbs)
9008 {
9009   int i;
9010   basic_block bb;
9011
9012   extend_h_i_d ();
9013   FOR_EACH_VEC_ELT (bbs, i, bb)
9014     {
9015       rtx_insn *insn;
9016
9017       FOR_BB_INSNS (bb, insn)
9018         init_h_i_d (insn);
9019     }
9020 }
9021
9022 /* Finalize haifa_insn_data.  */
9023 void
9024 haifa_finish_h_i_d (void)
9025 {
9026   int i;
9027   haifa_insn_data_t data;
9028   struct reg_use_data *use, *next;
9029
9030   FOR_EACH_VEC_ELT (h_i_d, i, data)
9031     {
9032       free (data->max_reg_pressure);
9033       free (data->reg_pressure);
9034       for (use = data->reg_use_list; use != NULL; use = next)
9035         {
9036           next = use->next_insn_use;
9037           free (use);
9038         }
9039     }
9040   h_i_d.release ();
9041 }
9042
9043 /* Init data for the new insn INSN.  */
9044 static void
9045 haifa_init_insn (rtx_insn *insn)
9046 {
9047   gcc_assert (insn != NULL);
9048
9049   sched_extend_luids ();
9050   sched_init_insn_luid (insn);
9051   sched_extend_target ();
9052   sched_deps_init (false);
9053   extend_h_i_d ();
9054   init_h_i_d (insn);
9055
9056   if (adding_bb_to_current_region_p)
9057     {
9058       sd_init_insn (insn);
9059
9060       /* Extend dependency caches by one element.  */
9061       extend_dependency_caches (1, false);
9062     }
9063   if (sched_pressure != SCHED_PRESSURE_NONE)
9064     init_insn_reg_pressure_info (insn);
9065 }
9066
9067 /* Init data for the new basic block BB which comes after AFTER.  */
9068 static void
9069 haifa_init_only_bb (basic_block bb, basic_block after)
9070 {
9071   gcc_assert (bb != NULL);
9072
9073   sched_init_bbs ();
9074
9075   if (common_sched_info->add_block)
9076     /* This changes only data structures of the front-end.  */
9077     common_sched_info->add_block (bb, after);
9078 }
9079
9080 /* A generic version of sched_split_block ().  */
9081 basic_block
9082 sched_split_block_1 (basic_block first_bb, rtx after)
9083 {
9084   edge e;
9085
9086   e = split_block (first_bb, after);
9087   gcc_assert (e->src == first_bb);
9088
9089   /* sched_split_block emits note if *check == BB_END.  Probably it
9090      is better to rip that note off.  */
9091
9092   return e->dest;
9093 }
9094
9095 /* A generic version of sched_create_empty_bb ().  */
9096 basic_block
9097 sched_create_empty_bb_1 (basic_block after)
9098 {
9099   return create_empty_bb (after);
9100 }
9101
9102 /* Insert PAT as an INSN into the schedule and update the necessary data
9103    structures to account for it. */
9104 rtx_insn *
9105 sched_emit_insn (rtx pat)
9106 {
9107   rtx_insn *insn = emit_insn_before (pat, first_nonscheduled_insn ());
9108   haifa_init_insn (insn);
9109
9110   if (current_sched_info->add_remove_insn)
9111     current_sched_info->add_remove_insn (insn, 0);
9112
9113   (*current_sched_info->begin_schedule_ready) (insn);
9114   scheduled_insns.safe_push (insn);
9115
9116   last_scheduled_insn = insn;
9117   return insn;
9118 }
9119
9120 /* This function returns a candidate satisfying dispatch constraints from
9121    the ready list.  */
9122
9123 static rtx_insn *
9124 ready_remove_first_dispatch (struct ready_list *ready)
9125 {
9126   int i;
9127   rtx_insn *insn = ready_element (ready, 0);
9128
9129   if (ready->n_ready == 1
9130       || !INSN_P (insn)
9131       || INSN_CODE (insn) < 0
9132       || !active_insn_p (insn)
9133       || targetm.sched.dispatch (insn, FITS_DISPATCH_WINDOW))
9134     return ready_remove_first (ready);
9135
9136   for (i = 1; i < ready->n_ready; i++)
9137     {
9138       insn = ready_element (ready, i);
9139
9140       if (!INSN_P (insn)
9141           || INSN_CODE (insn) < 0
9142           || !active_insn_p (insn))
9143         continue;
9144
9145       if (targetm.sched.dispatch (insn, FITS_DISPATCH_WINDOW))
9146         {
9147           /* Return ith element of ready.  */
9148           insn = ready_remove (ready, i);
9149           return insn;
9150         }
9151     }
9152
9153   if (targetm.sched.dispatch (NULL, DISPATCH_VIOLATION))
9154     return ready_remove_first (ready);
9155
9156   for (i = 1; i < ready->n_ready; i++)
9157     {
9158       insn = ready_element (ready, i);
9159
9160       if (!INSN_P (insn)
9161           || INSN_CODE (insn) < 0
9162           || !active_insn_p (insn))
9163         continue;
9164
9165       /* Return i-th element of ready.  */
9166       if (targetm.sched.dispatch (insn, IS_CMP))
9167         return ready_remove (ready, i);
9168     }
9169
9170   return ready_remove_first (ready);
9171 }
9172
9173 /* Get number of ready insn in the ready list.  */
9174
9175 int
9176 number_in_ready (void)
9177 {
9178   return ready.n_ready;
9179 }
9180
9181 /* Get number of ready's in the ready list.  */
9182
9183 rtx_insn *
9184 get_ready_element (int i)
9185 {
9186   return ready_element (&ready, i);
9187 }
9188
9189 #endif /* INSN_SCHEDULING */