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