-dA enhancement
[official-gcc.git] / gcc / haifa-sched.c
blob6908a113e634f401df5cc3dad882cdbd90353b71
1 /* Instruction scheduling pass.
2 Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
4 Free Software Foundation, Inc.
5 Contributed by Michael Tiemann (tiemann@cygnus.com) Enhanced by,
6 and currently maintained by, Jim Wilson (wilson@cygnus.com)
8 This file is part of GCC.
10 GCC is free software; you can redistribute it and/or modify it under
11 the terms of the GNU General Public License as published by the Free
12 Software Foundation; either version 3, or (at your option) any later
13 version.
15 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
16 WARRANTY; without even the implied warranty of MERCHANTABILITY or
17 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
18 for more details.
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3. If not see
22 <http://www.gnu.org/licenses/>. */
24 /* Instruction scheduling pass. This file, along with sched-deps.c,
25 contains the generic parts. The actual entry point is found for
26 the normal instruction scheduling pass is found in sched-rgn.c.
28 We compute insn priorities based on data dependencies. Flow
29 analysis only creates a fraction of the data-dependencies we must
30 observe: namely, only those dependencies which the combiner can be
31 expected to use. For this pass, we must therefore create the
32 remaining dependencies we need to observe: register dependencies,
33 memory dependencies, dependencies to keep function calls in order,
34 and the dependence between a conditional branch and the setting of
35 condition codes are all dealt with here.
37 The scheduler first traverses the data flow graph, starting with
38 the last instruction, and proceeding to the first, assigning values
39 to insn_priority as it goes. This sorts the instructions
40 topologically by data dependence.
42 Once priorities have been established, we order the insns using
43 list scheduling. This works as follows: starting with a list of
44 all the ready insns, and sorted according to priority number, we
45 schedule the insn from the end of the list by placing its
46 predecessors in the list according to their priority order. We
47 consider this insn scheduled by setting the pointer to the "end" of
48 the list to point to the previous insn. When an insn has no
49 predecessors, we either queue it until sufficient time has elapsed
50 or add it to the ready list. As the instructions are scheduled or
51 when stalls are introduced, the queue advances and dumps insns into
52 the ready list. When all insns down to the lowest priority have
53 been scheduled, the critical path of the basic block has been made
54 as short as possible. The remaining insns are then scheduled in
55 remaining slots.
57 The following list shows the order in which we want to break ties
58 among insns in the ready list:
60 1. choose insn with the longest path to end of bb, ties
61 broken by
62 2. choose insn with least contribution to register pressure,
63 ties broken by
64 3. prefer in-block upon interblock motion, ties broken by
65 4. prefer useful upon speculative motion, ties broken by
66 5. choose insn with largest control flow probability, ties
67 broken by
68 6. choose insn with the least dependences upon the previously
69 scheduled insn, or finally
70 7 choose the insn which has the most insns dependent on it.
71 8. choose insn with lowest UID.
73 Memory references complicate matters. Only if we can be certain
74 that memory references are not part of the data dependency graph
75 (via true, anti, or output dependence), can we move operations past
76 memory references. To first approximation, reads can be done
77 independently, while writes introduce dependencies. Better
78 approximations will yield fewer dependencies.
80 Before reload, an extended analysis of interblock data dependences
81 is required for interblock scheduling. This is performed in
82 compute_block_backward_dependences ().
84 Dependencies set up by memory references are treated in exactly the
85 same way as other dependencies, by using insn backward dependences
86 INSN_BACK_DEPS. INSN_BACK_DEPS are translated into forward dependences
87 INSN_FORW_DEPS the purpose of forward list scheduling.
89 Having optimized the critical path, we may have also unduly
90 extended the lifetimes of some registers. If an operation requires
91 that constants be loaded into registers, it is certainly desirable
92 to load those constants as early as necessary, but no earlier.
93 I.e., it will not do to load up a bunch of registers at the
94 beginning of a basic block only to use them at the end, if they
95 could be loaded later, since this may result in excessive register
96 utilization.
98 Note that since branches are never in basic blocks, but only end
99 basic blocks, this pass will not move branches. But that is ok,
100 since we can use GNU's delayed branch scheduling pass to take care
101 of this case.
103 Also note that no further optimizations based on algebraic
104 identities are performed, so this pass would be a good one to
105 perform instruction splitting, such as breaking up a multiply
106 instruction into shifts and adds where that is profitable.
108 Given the memory aliasing analysis that this pass should perform,
109 it should be possible to remove redundant stores to memory, and to
110 load values from registers instead of hitting memory.
112 Before reload, speculative insns are moved only if a 'proof' exists
113 that no exception will be caused by this, and if no live registers
114 exist that inhibit the motion (live registers constraints are not
115 represented by data dependence edges).
117 This pass must update information that subsequent passes expect to
118 be correct. Namely: reg_n_refs, reg_n_sets, reg_n_deaths,
119 reg_n_calls_crossed, and reg_live_length. Also, BB_HEAD, BB_END.
121 The information in the line number notes is carefully retained by
122 this pass. Notes that refer to the starting and ending of
123 exception regions are also carefully retained by this pass. All
124 other NOTE insns are grouped in their same relative order at the
125 beginning of basic blocks and regions that have been scheduled. */
127 #include "config.h"
128 #include "system.h"
129 #include "coretypes.h"
130 #include "tm.h"
131 #include "diagnostic-core.h"
132 #include "rtl.h"
133 #include "tm_p.h"
134 #include "hard-reg-set.h"
135 #include "regs.h"
136 #include "function.h"
137 #include "flags.h"
138 #include "insn-config.h"
139 #include "insn-attr.h"
140 #include "except.h"
141 #include "recog.h"
142 #include "sched-int.h"
143 #include "target.h"
144 #include "output.h"
145 #include "params.h"
146 #include "vecprim.h"
147 #include "dbgcnt.h"
148 #include "cfgloop.h"
149 #include "ira.h"
150 #include "emit-rtl.h" /* FIXME: Can go away once crtl is moved to rtl.h. */
152 #ifdef INSN_SCHEDULING
154 /* issue_rate is the number of insns that can be scheduled in the same
155 machine cycle. It can be defined in the config/mach/mach.h file,
156 otherwise we set it to 1. */
158 int issue_rate;
160 /* sched-verbose controls the amount of debugging output the
161 scheduler prints. It is controlled by -fsched-verbose=N:
162 N>0 and no -DSR : the output is directed to stderr.
163 N>=10 will direct the printouts to stderr (regardless of -dSR).
164 N=1: same as -dSR.
165 N=2: bb's probabilities, detailed ready list info, unit/insn info.
166 N=3: rtl at abort point, control-flow, regions info.
167 N=5: dependences info. */
169 int sched_verbose = 0;
171 /* Debugging file. All printouts are sent to dump, which is always set,
172 either to stderr, or to the dump listing file (-dRS). */
173 FILE *sched_dump = 0;
175 /* This is a placeholder for the scheduler parameters common
176 to all schedulers. */
177 struct common_sched_info_def *common_sched_info;
179 #define INSN_TICK(INSN) (HID (INSN)->tick)
180 #define INTER_TICK(INSN) (HID (INSN)->inter_tick)
182 /* If INSN_TICK of an instruction is equal to INVALID_TICK,
183 then it should be recalculated from scratch. */
184 #define INVALID_TICK (-(max_insn_queue_index + 1))
185 /* The minimal value of the INSN_TICK of an instruction. */
186 #define MIN_TICK (-max_insn_queue_index)
188 /* List of important notes we must keep around. This is a pointer to the
189 last element in the list. */
190 rtx note_list;
192 static struct spec_info_def spec_info_var;
193 /* Description of the speculative part of the scheduling.
194 If NULL - no speculation. */
195 spec_info_t spec_info = NULL;
197 /* True, if recovery block was added during scheduling of current block.
198 Used to determine, if we need to fix INSN_TICKs. */
199 static bool haifa_recovery_bb_recently_added_p;
201 /* True, if recovery block was added during this scheduling pass.
202 Used to determine if we should have empty memory pools of dependencies
203 after finishing current region. */
204 bool haifa_recovery_bb_ever_added_p;
206 /* Counters of different types of speculative instructions. */
207 static int nr_begin_data, nr_be_in_data, nr_begin_control, nr_be_in_control;
209 /* Array used in {unlink, restore}_bb_notes. */
210 static rtx *bb_header = 0;
212 /* Basic block after which recovery blocks will be created. */
213 static basic_block before_recovery;
215 /* Basic block just before the EXIT_BLOCK and after recovery, if we have
216 created it. */
217 basic_block after_recovery;
219 /* FALSE if we add bb to another region, so we don't need to initialize it. */
220 bool adding_bb_to_current_region_p = true;
222 /* Queues, etc. */
224 /* An instruction is ready to be scheduled when all insns preceding it
225 have already been scheduled. It is important to ensure that all
226 insns which use its result will not be executed until its result
227 has been computed. An insn is maintained in one of four structures:
229 (P) the "Pending" set of insns which cannot be scheduled until
230 their dependencies have been satisfied.
231 (Q) the "Queued" set of insns that can be scheduled when sufficient
232 time has passed.
233 (R) the "Ready" list of unscheduled, uncommitted insns.
234 (S) the "Scheduled" list of insns.
236 Initially, all insns are either "Pending" or "Ready" depending on
237 whether their dependencies are satisfied.
239 Insns move from the "Ready" list to the "Scheduled" list as they
240 are committed to the schedule. As this occurs, the insns in the
241 "Pending" list have their dependencies satisfied and move to either
242 the "Ready" list or the "Queued" set depending on whether
243 sufficient time has passed to make them ready. As time passes,
244 insns move from the "Queued" set to the "Ready" list.
246 The "Pending" list (P) are the insns in the INSN_FORW_DEPS of the
247 unscheduled insns, i.e., those that are ready, queued, and pending.
248 The "Queued" set (Q) is implemented by the variable `insn_queue'.
249 The "Ready" list (R) is implemented by the variables `ready' and
250 `n_ready'.
251 The "Scheduled" list (S) is the new insn chain built by this pass.
253 The transition (R->S) is implemented in the scheduling loop in
254 `schedule_block' when the best insn to schedule is chosen.
255 The transitions (P->R and P->Q) are implemented in `schedule_insn' as
256 insns move from the ready list to the scheduled list.
257 The transition (Q->R) is implemented in 'queue_to_insn' as time
258 passes or stalls are introduced. */
260 /* Implement a circular buffer to delay instructions until sufficient
261 time has passed. For the new pipeline description interface,
262 MAX_INSN_QUEUE_INDEX is a power of two minus one which is not less
263 than maximal time of instruction execution computed by genattr.c on
264 the base maximal time of functional unit reservations and getting a
265 result. This is the longest time an insn may be queued. */
267 static rtx *insn_queue;
268 static int q_ptr = 0;
269 static int q_size = 0;
270 #define NEXT_Q(X) (((X)+1) & max_insn_queue_index)
271 #define NEXT_Q_AFTER(X, C) (((X)+C) & max_insn_queue_index)
273 #define QUEUE_SCHEDULED (-3)
274 #define QUEUE_NOWHERE (-2)
275 #define QUEUE_READY (-1)
276 /* QUEUE_SCHEDULED - INSN is scheduled.
277 QUEUE_NOWHERE - INSN isn't scheduled yet and is neither in
278 queue or ready list.
279 QUEUE_READY - INSN is in ready list.
280 N >= 0 - INSN queued for X [where NEXT_Q_AFTER (q_ptr, X) == N] cycles. */
282 #define QUEUE_INDEX(INSN) (HID (INSN)->queue_index)
284 /* The following variable value refers for all current and future
285 reservations of the processor units. */
286 state_t curr_state;
288 /* The following variable value is size of memory representing all
289 current and future reservations of the processor units. */
290 size_t dfa_state_size;
292 /* The following array is used to find the best insn from ready when
293 the automaton pipeline interface is used. */
294 char *ready_try = NULL;
296 /* The ready list. */
297 struct ready_list ready = {NULL, 0, 0, 0, 0};
299 /* The pointer to the ready list (to be removed). */
300 static struct ready_list *readyp = &ready;
302 /* Scheduling clock. */
303 static int clock_var;
305 /* This records the actual schedule. It is built up during the main phase
306 of schedule_block, and afterwards used to reorder the insns in the RTL. */
307 static VEC(rtx, heap) *scheduled_insns;
309 static int may_trap_exp (const_rtx, int);
311 /* Nonzero iff the address is comprised from at most 1 register. */
312 #define CONST_BASED_ADDRESS_P(x) \
313 (REG_P (x) \
314 || ((GET_CODE (x) == PLUS || GET_CODE (x) == MINUS \
315 || (GET_CODE (x) == LO_SUM)) \
316 && (CONSTANT_P (XEXP (x, 0)) \
317 || CONSTANT_P (XEXP (x, 1)))))
319 /* Returns a class that insn with GET_DEST(insn)=x may belong to,
320 as found by analyzing insn's expression. */
323 static int haifa_luid_for_non_insn (rtx x);
325 /* Haifa version of sched_info hooks common to all headers. */
326 const struct common_sched_info_def haifa_common_sched_info =
328 NULL, /* fix_recovery_cfg */
329 NULL, /* add_block */
330 NULL, /* estimate_number_of_insns */
331 haifa_luid_for_non_insn, /* luid_for_non_insn */
332 SCHED_PASS_UNKNOWN /* sched_pass_id */
335 const struct sched_scan_info_def *sched_scan_info;
337 /* Mapping from instruction UID to its Logical UID. */
338 VEC (int, heap) *sched_luids = NULL;
340 /* Next LUID to assign to an instruction. */
341 int sched_max_luid = 1;
343 /* Haifa Instruction Data. */
344 VEC (haifa_insn_data_def, heap) *h_i_d = NULL;
346 void (* sched_init_only_bb) (basic_block, basic_block);
348 /* Split block function. Different schedulers might use different functions
349 to handle their internal data consistent. */
350 basic_block (* sched_split_block) (basic_block, rtx);
352 /* Create empty basic block after the specified block. */
353 basic_block (* sched_create_empty_bb) (basic_block);
355 static int
356 may_trap_exp (const_rtx x, int is_store)
358 enum rtx_code code;
360 if (x == 0)
361 return TRAP_FREE;
362 code = GET_CODE (x);
363 if (is_store)
365 if (code == MEM && may_trap_p (x))
366 return TRAP_RISKY;
367 else
368 return TRAP_FREE;
370 if (code == MEM)
372 /* The insn uses memory: a volatile load. */
373 if (MEM_VOLATILE_P (x))
374 return IRISKY;
375 /* An exception-free load. */
376 if (!may_trap_p (x))
377 return IFREE;
378 /* A load with 1 base register, to be further checked. */
379 if (CONST_BASED_ADDRESS_P (XEXP (x, 0)))
380 return PFREE_CANDIDATE;
381 /* No info on the load, to be further checked. */
382 return PRISKY_CANDIDATE;
384 else
386 const char *fmt;
387 int i, insn_class = TRAP_FREE;
389 /* Neither store nor load, check if it may cause a trap. */
390 if (may_trap_p (x))
391 return TRAP_RISKY;
392 /* Recursive step: walk the insn... */
393 fmt = GET_RTX_FORMAT (code);
394 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
396 if (fmt[i] == 'e')
398 int tmp_class = may_trap_exp (XEXP (x, i), is_store);
399 insn_class = WORST_CLASS (insn_class, tmp_class);
401 else if (fmt[i] == 'E')
403 int j;
404 for (j = 0; j < XVECLEN (x, i); j++)
406 int tmp_class = may_trap_exp (XVECEXP (x, i, j), is_store);
407 insn_class = WORST_CLASS (insn_class, tmp_class);
408 if (insn_class == TRAP_RISKY || insn_class == IRISKY)
409 break;
412 if (insn_class == TRAP_RISKY || insn_class == IRISKY)
413 break;
415 return insn_class;
419 /* Classifies rtx X of an insn for the purpose of verifying that X can be
420 executed speculatively (and consequently the insn can be moved
421 speculatively), by examining X, returning:
422 TRAP_RISKY: store, or risky non-load insn (e.g. division by variable).
423 TRAP_FREE: non-load insn.
424 IFREE: load from a globally safe location.
425 IRISKY: volatile load.
426 PFREE_CANDIDATE, PRISKY_CANDIDATE: load that need to be checked for
427 being either PFREE or PRISKY. */
429 static int
430 haifa_classify_rtx (const_rtx x)
432 int tmp_class = TRAP_FREE;
433 int insn_class = TRAP_FREE;
434 enum rtx_code code;
436 if (GET_CODE (x) == PARALLEL)
438 int i, len = XVECLEN (x, 0);
440 for (i = len - 1; i >= 0; i--)
442 tmp_class = haifa_classify_rtx (XVECEXP (x, 0, i));
443 insn_class = WORST_CLASS (insn_class, tmp_class);
444 if (insn_class == TRAP_RISKY || insn_class == IRISKY)
445 break;
448 else
450 code = GET_CODE (x);
451 switch (code)
453 case CLOBBER:
454 /* Test if it is a 'store'. */
455 tmp_class = may_trap_exp (XEXP (x, 0), 1);
456 break;
457 case SET:
458 /* Test if it is a store. */
459 tmp_class = may_trap_exp (SET_DEST (x), 1);
460 if (tmp_class == TRAP_RISKY)
461 break;
462 /* Test if it is a load. */
463 tmp_class =
464 WORST_CLASS (tmp_class,
465 may_trap_exp (SET_SRC (x), 0));
466 break;
467 case COND_EXEC:
468 tmp_class = haifa_classify_rtx (COND_EXEC_CODE (x));
469 if (tmp_class == TRAP_RISKY)
470 break;
471 tmp_class = WORST_CLASS (tmp_class,
472 may_trap_exp (COND_EXEC_TEST (x), 0));
473 break;
474 case TRAP_IF:
475 tmp_class = TRAP_RISKY;
476 break;
477 default:;
479 insn_class = tmp_class;
482 return insn_class;
486 haifa_classify_insn (const_rtx insn)
488 return haifa_classify_rtx (PATTERN (insn));
491 /* Forward declarations. */
493 static int priority (rtx);
494 static int rank_for_schedule (const void *, const void *);
495 static void swap_sort (rtx *, int);
496 static void queue_insn (rtx, int, const char *);
497 static int schedule_insn (rtx);
498 static void adjust_priority (rtx);
499 static void advance_one_cycle (void);
500 static void extend_h_i_d (void);
503 /* Notes handling mechanism:
504 =========================
505 Generally, NOTES are saved before scheduling and restored after scheduling.
506 The scheduler distinguishes between two types of notes:
508 (1) LOOP_BEGIN, LOOP_END, SETJMP, EHREGION_BEG, EHREGION_END notes:
509 Before scheduling a region, a pointer to the note is added to the insn
510 that follows or precedes it. (This happens as part of the data dependence
511 computation). After scheduling an insn, the pointer contained in it is
512 used for regenerating the corresponding note (in reemit_notes).
514 (2) All other notes (e.g. INSN_DELETED): Before scheduling a block,
515 these notes are put in a list (in rm_other_notes() and
516 unlink_other_notes ()). After scheduling the block, these notes are
517 inserted at the beginning of the block (in schedule_block()). */
519 static void ready_add (struct ready_list *, rtx, bool);
520 static rtx ready_remove_first (struct ready_list *);
521 static rtx ready_remove_first_dispatch (struct ready_list *ready);
523 static void queue_to_ready (struct ready_list *);
524 static int early_queue_to_ready (state_t, struct ready_list *);
526 static void debug_ready_list (struct ready_list *);
528 /* The following functions are used to implement multi-pass scheduling
529 on the first cycle. */
530 static rtx ready_remove (struct ready_list *, int);
531 static void ready_remove_insn (rtx);
533 static void fix_inter_tick (rtx, rtx);
534 static int fix_tick_ready (rtx);
535 static void change_queue_index (rtx, int);
537 /* The following functions are used to implement scheduling of data/control
538 speculative instructions. */
540 static void extend_h_i_d (void);
541 static void init_h_i_d (rtx);
542 static void generate_recovery_code (rtx);
543 static void process_insn_forw_deps_be_in_spec (rtx, rtx, ds_t);
544 static void begin_speculative_block (rtx);
545 static void add_to_speculative_block (rtx);
546 static void init_before_recovery (basic_block *);
547 static void create_check_block_twin (rtx, bool);
548 static void fix_recovery_deps (basic_block);
549 static void haifa_change_pattern (rtx, rtx);
550 static void dump_new_block_header (int, basic_block, rtx, rtx);
551 static void restore_bb_notes (basic_block);
552 static void fix_jump_move (rtx);
553 static void move_block_after_check (rtx);
554 static void move_succs (VEC(edge,gc) **, basic_block);
555 static void sched_remove_insn (rtx);
556 static void clear_priorities (rtx, rtx_vec_t *);
557 static void calc_priorities (rtx_vec_t);
558 static void add_jump_dependencies (rtx, rtx);
559 #ifdef ENABLE_CHECKING
560 static int has_edge_p (VEC(edge,gc) *, int);
561 static void check_cfg (rtx, rtx);
562 #endif
564 #endif /* INSN_SCHEDULING */
566 /* Point to state used for the current scheduling pass. */
567 struct haifa_sched_info *current_sched_info;
569 #ifndef INSN_SCHEDULING
570 void
571 schedule_insns (void)
574 #else
576 /* Do register pressure sensitive insn scheduling if the flag is set
577 up. */
578 bool sched_pressure_p;
580 /* Map regno -> its pressure class. The map defined only when
581 SCHED_PRESSURE_P is true. */
582 enum reg_class *sched_regno_pressure_class;
584 /* The current register pressure. Only elements corresponding pressure
585 classes are defined. */
586 static int curr_reg_pressure[N_REG_CLASSES];
588 /* Saved value of the previous array. */
589 static int saved_reg_pressure[N_REG_CLASSES];
591 /* Register living at given scheduling point. */
592 static bitmap curr_reg_live;
594 /* Saved value of the previous array. */
595 static bitmap saved_reg_live;
597 /* Registers mentioned in the current region. */
598 static bitmap region_ref_regs;
600 /* Initiate register pressure relative info for scheduling the current
601 region. Currently it is only clearing register mentioned in the
602 current region. */
603 void
604 sched_init_region_reg_pressure_info (void)
606 bitmap_clear (region_ref_regs);
609 /* Update current register pressure related info after birth (if
610 BIRTH_P) or death of register REGNO. */
611 static void
612 mark_regno_birth_or_death (int regno, bool birth_p)
614 enum reg_class pressure_class;
616 pressure_class = sched_regno_pressure_class[regno];
617 if (regno >= FIRST_PSEUDO_REGISTER)
619 if (pressure_class != NO_REGS)
621 if (birth_p)
623 bitmap_set_bit (curr_reg_live, regno);
624 curr_reg_pressure[pressure_class]
625 += (ira_reg_class_max_nregs
626 [pressure_class][PSEUDO_REGNO_MODE (regno)]);
628 else
630 bitmap_clear_bit (curr_reg_live, regno);
631 curr_reg_pressure[pressure_class]
632 -= (ira_reg_class_max_nregs
633 [pressure_class][PSEUDO_REGNO_MODE (regno)]);
637 else if (pressure_class != NO_REGS
638 && ! TEST_HARD_REG_BIT (ira_no_alloc_regs, regno))
640 if (birth_p)
642 bitmap_set_bit (curr_reg_live, regno);
643 curr_reg_pressure[pressure_class]++;
645 else
647 bitmap_clear_bit (curr_reg_live, regno);
648 curr_reg_pressure[pressure_class]--;
653 /* Initiate current register pressure related info from living
654 registers given by LIVE. */
655 static void
656 initiate_reg_pressure_info (bitmap live)
658 int i;
659 unsigned int j;
660 bitmap_iterator bi;
662 for (i = 0; i < ira_pressure_classes_num; i++)
663 curr_reg_pressure[ira_pressure_classes[i]] = 0;
664 bitmap_clear (curr_reg_live);
665 EXECUTE_IF_SET_IN_BITMAP (live, 0, j, bi)
666 if (current_nr_blocks == 1 || bitmap_bit_p (region_ref_regs, j))
667 mark_regno_birth_or_death (j, true);
670 /* Mark registers in X as mentioned in the current region. */
671 static void
672 setup_ref_regs (rtx x)
674 int i, j, regno;
675 const RTX_CODE code = GET_CODE (x);
676 const char *fmt;
678 if (REG_P (x))
680 regno = REGNO (x);
681 if (HARD_REGISTER_NUM_P (regno))
682 bitmap_set_range (region_ref_regs, regno,
683 hard_regno_nregs[regno][GET_MODE (x)]);
684 else
685 bitmap_set_bit (region_ref_regs, REGNO (x));
686 return;
688 fmt = GET_RTX_FORMAT (code);
689 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
690 if (fmt[i] == 'e')
691 setup_ref_regs (XEXP (x, i));
692 else if (fmt[i] == 'E')
694 for (j = 0; j < XVECLEN (x, i); j++)
695 setup_ref_regs (XVECEXP (x, i, j));
699 /* Initiate current register pressure related info at the start of
700 basic block BB. */
701 static void
702 initiate_bb_reg_pressure_info (basic_block bb)
704 unsigned int i ATTRIBUTE_UNUSED;
705 rtx insn;
707 if (current_nr_blocks > 1)
708 FOR_BB_INSNS (bb, insn)
709 if (NONDEBUG_INSN_P (insn))
710 setup_ref_regs (PATTERN (insn));
711 initiate_reg_pressure_info (df_get_live_in (bb));
712 #ifdef EH_RETURN_DATA_REGNO
713 if (bb_has_eh_pred (bb))
714 for (i = 0; ; ++i)
716 unsigned int regno = EH_RETURN_DATA_REGNO (i);
718 if (regno == INVALID_REGNUM)
719 break;
720 if (! bitmap_bit_p (df_get_live_in (bb), regno))
721 mark_regno_birth_or_death (regno, true);
723 #endif
726 /* Save current register pressure related info. */
727 static void
728 save_reg_pressure (void)
730 int i;
732 for (i = 0; i < ira_pressure_classes_num; i++)
733 saved_reg_pressure[ira_pressure_classes[i]]
734 = curr_reg_pressure[ira_pressure_classes[i]];
735 bitmap_copy (saved_reg_live, curr_reg_live);
738 /* Restore saved register pressure related info. */
739 static void
740 restore_reg_pressure (void)
742 int i;
744 for (i = 0; i < ira_pressure_classes_num; i++)
745 curr_reg_pressure[ira_pressure_classes[i]]
746 = saved_reg_pressure[ira_pressure_classes[i]];
747 bitmap_copy (curr_reg_live, saved_reg_live);
750 /* Return TRUE if the register is dying after its USE. */
751 static bool
752 dying_use_p (struct reg_use_data *use)
754 struct reg_use_data *next;
756 for (next = use->next_regno_use; next != use; next = next->next_regno_use)
757 if (NONDEBUG_INSN_P (next->insn)
758 && QUEUE_INDEX (next->insn) != QUEUE_SCHEDULED)
759 return false;
760 return true;
763 /* Print info about the current register pressure and its excess for
764 each pressure class. */
765 static void
766 print_curr_reg_pressure (void)
768 int i;
769 enum reg_class cl;
771 fprintf (sched_dump, ";;\t");
772 for (i = 0; i < ira_pressure_classes_num; i++)
774 cl = ira_pressure_classes[i];
775 gcc_assert (curr_reg_pressure[cl] >= 0);
776 fprintf (sched_dump, " %s:%d(%d)", reg_class_names[cl],
777 curr_reg_pressure[cl],
778 curr_reg_pressure[cl] - ira_available_class_regs[cl]);
780 fprintf (sched_dump, "\n");
783 /* Pointer to the last instruction scheduled. */
784 static rtx last_scheduled_insn;
786 /* Pointer that iterates through the list of unscheduled insns if we
787 have a dbg_cnt enabled. It always points at an insn prior to the
788 first unscheduled one. */
789 static rtx nonscheduled_insns_begin;
791 /* Cached cost of the instruction. Use below function to get cost of the
792 insn. -1 here means that the field is not initialized. */
793 #define INSN_COST(INSN) (HID (INSN)->cost)
795 /* Compute cost of executing INSN.
796 This is the number of cycles between instruction issue and
797 instruction results. */
799 insn_cost (rtx insn)
801 int cost;
803 if (sel_sched_p ())
805 if (recog_memoized (insn) < 0)
806 return 0;
808 cost = insn_default_latency (insn);
809 if (cost < 0)
810 cost = 0;
812 return cost;
815 cost = INSN_COST (insn);
817 if (cost < 0)
819 /* A USE insn, or something else we don't need to
820 understand. We can't pass these directly to
821 result_ready_cost or insn_default_latency because it will
822 trigger a fatal error for unrecognizable insns. */
823 if (recog_memoized (insn) < 0)
825 INSN_COST (insn) = 0;
826 return 0;
828 else
830 cost = insn_default_latency (insn);
831 if (cost < 0)
832 cost = 0;
834 INSN_COST (insn) = cost;
838 return cost;
841 /* Compute cost of dependence LINK.
842 This is the number of cycles between instruction issue and
843 instruction results.
844 ??? We also use this function to call recog_memoized on all insns. */
846 dep_cost_1 (dep_t link, dw_t dw)
848 rtx insn = DEP_PRO (link);
849 rtx used = DEP_CON (link);
850 int cost;
852 /* A USE insn should never require the value used to be computed.
853 This allows the computation of a function's result and parameter
854 values to overlap the return and call. We don't care about the
855 the dependence cost when only decreasing register pressure. */
856 if (recog_memoized (used) < 0)
858 cost = 0;
859 recog_memoized (insn);
861 else
863 enum reg_note dep_type = DEP_TYPE (link);
865 cost = insn_cost (insn);
867 if (INSN_CODE (insn) >= 0)
869 if (dep_type == REG_DEP_ANTI)
870 cost = 0;
871 else if (dep_type == REG_DEP_OUTPUT)
873 cost = (insn_default_latency (insn)
874 - insn_default_latency (used));
875 if (cost <= 0)
876 cost = 1;
878 else if (bypass_p (insn))
879 cost = insn_latency (insn, used);
883 if (targetm.sched.adjust_cost_2)
884 cost = targetm.sched.adjust_cost_2 (used, (int) dep_type, insn, cost,
885 dw);
886 else if (targetm.sched.adjust_cost != NULL)
888 /* This variable is used for backward compatibility with the
889 targets. */
890 rtx dep_cost_rtx_link = alloc_INSN_LIST (NULL_RTX, NULL_RTX);
892 /* Make it self-cycled, so that if some tries to walk over this
893 incomplete list he/she will be caught in an endless loop. */
894 XEXP (dep_cost_rtx_link, 1) = dep_cost_rtx_link;
896 /* Targets use only REG_NOTE_KIND of the link. */
897 PUT_REG_NOTE_KIND (dep_cost_rtx_link, DEP_TYPE (link));
899 cost = targetm.sched.adjust_cost (used, dep_cost_rtx_link,
900 insn, cost);
902 free_INSN_LIST_node (dep_cost_rtx_link);
905 if (cost < 0)
906 cost = 0;
909 return cost;
912 /* Compute cost of dependence LINK.
913 This is the number of cycles between instruction issue and
914 instruction results. */
916 dep_cost (dep_t link)
918 return dep_cost_1 (link, 0);
921 /* Use this sel-sched.c friendly function in reorder2 instead of increasing
922 INSN_PRIORITY explicitly. */
923 void
924 increase_insn_priority (rtx insn, int amount)
926 if (!sel_sched_p ())
928 /* We're dealing with haifa-sched.c INSN_PRIORITY. */
929 if (INSN_PRIORITY_KNOWN (insn))
930 INSN_PRIORITY (insn) += amount;
932 else
934 /* In sel-sched.c INSN_PRIORITY is not kept up to date.
935 Use EXPR_PRIORITY instead. */
936 sel_add_to_insn_priority (insn, amount);
940 /* Return 'true' if DEP should be included in priority calculations. */
941 static bool
942 contributes_to_priority_p (dep_t dep)
944 if (DEBUG_INSN_P (DEP_CON (dep))
945 || DEBUG_INSN_P (DEP_PRO (dep)))
946 return false;
948 /* Critical path is meaningful in block boundaries only. */
949 if (!current_sched_info->contributes_to_priority (DEP_CON (dep),
950 DEP_PRO (dep)))
951 return false;
953 /* If flag COUNT_SPEC_IN_CRITICAL_PATH is set,
954 then speculative instructions will less likely be
955 scheduled. That is because the priority of
956 their producers will increase, and, thus, the
957 producers will more likely be scheduled, thus,
958 resolving the dependence. */
959 if (sched_deps_info->generate_spec_deps
960 && !(spec_info->flags & COUNT_SPEC_IN_CRITICAL_PATH)
961 && (DEP_STATUS (dep) & SPECULATIVE))
962 return false;
964 return true;
967 /* Compute the number of nondebug forward deps of an insn. */
969 static int
970 dep_list_size (rtx insn)
972 sd_iterator_def sd_it;
973 dep_t dep;
974 int dbgcount = 0, nodbgcount = 0;
976 if (!MAY_HAVE_DEBUG_INSNS)
977 return sd_lists_size (insn, SD_LIST_FORW);
979 FOR_EACH_DEP (insn, SD_LIST_FORW, sd_it, dep)
981 if (DEBUG_INSN_P (DEP_CON (dep)))
982 dbgcount++;
983 else if (!DEBUG_INSN_P (DEP_PRO (dep)))
984 nodbgcount++;
987 gcc_assert (dbgcount + nodbgcount == sd_lists_size (insn, SD_LIST_FORW));
989 return nodbgcount;
992 /* Compute the priority number for INSN. */
993 static int
994 priority (rtx insn)
996 if (! INSN_P (insn))
997 return 0;
999 /* We should not be interested in priority of an already scheduled insn. */
1000 gcc_assert (QUEUE_INDEX (insn) != QUEUE_SCHEDULED);
1002 if (!INSN_PRIORITY_KNOWN (insn))
1004 int this_priority = -1;
1006 if (dep_list_size (insn) == 0)
1007 /* ??? We should set INSN_PRIORITY to insn_cost when and insn has
1008 some forward deps but all of them are ignored by
1009 contributes_to_priority hook. At the moment we set priority of
1010 such insn to 0. */
1011 this_priority = insn_cost (insn);
1012 else
1014 rtx prev_first, twin;
1015 basic_block rec;
1017 /* For recovery check instructions we calculate priority slightly
1018 different than that of normal instructions. Instead of walking
1019 through INSN_FORW_DEPS (check) list, we walk through
1020 INSN_FORW_DEPS list of each instruction in the corresponding
1021 recovery block. */
1023 /* Selective scheduling does not define RECOVERY_BLOCK macro. */
1024 rec = sel_sched_p () ? NULL : RECOVERY_BLOCK (insn);
1025 if (!rec || rec == EXIT_BLOCK_PTR)
1027 prev_first = PREV_INSN (insn);
1028 twin = insn;
1030 else
1032 prev_first = NEXT_INSN (BB_HEAD (rec));
1033 twin = PREV_INSN (BB_END (rec));
1038 sd_iterator_def sd_it;
1039 dep_t dep;
1041 FOR_EACH_DEP (twin, SD_LIST_FORW, sd_it, dep)
1043 rtx next;
1044 int next_priority;
1046 next = DEP_CON (dep);
1048 if (BLOCK_FOR_INSN (next) != rec)
1050 int cost;
1052 if (!contributes_to_priority_p (dep))
1053 continue;
1055 if (twin == insn)
1056 cost = dep_cost (dep);
1057 else
1059 struct _dep _dep1, *dep1 = &_dep1;
1061 init_dep (dep1, insn, next, REG_DEP_ANTI);
1063 cost = dep_cost (dep1);
1066 next_priority = cost + priority (next);
1068 if (next_priority > this_priority)
1069 this_priority = next_priority;
1073 twin = PREV_INSN (twin);
1075 while (twin != prev_first);
1078 if (this_priority < 0)
1080 gcc_assert (this_priority == -1);
1082 this_priority = insn_cost (insn);
1085 INSN_PRIORITY (insn) = this_priority;
1086 INSN_PRIORITY_STATUS (insn) = 1;
1089 return INSN_PRIORITY (insn);
1092 /* Macros and functions for keeping the priority queue sorted, and
1093 dealing with queuing and dequeuing of instructions. */
1095 #define SCHED_SORT(READY, N_READY) \
1096 do { if ((N_READY) == 2) \
1097 swap_sort (READY, N_READY); \
1098 else if ((N_READY) > 2) \
1099 qsort (READY, N_READY, sizeof (rtx), rank_for_schedule); } \
1100 while (0)
1102 /* Setup info about the current register pressure impact of scheduling
1103 INSN at the current scheduling point. */
1104 static void
1105 setup_insn_reg_pressure_info (rtx insn)
1107 int i, change, before, after, hard_regno;
1108 int excess_cost_change;
1109 enum machine_mode mode;
1110 enum reg_class cl;
1111 struct reg_pressure_data *pressure_info;
1112 int *max_reg_pressure;
1113 struct reg_use_data *use;
1114 static int death[N_REG_CLASSES];
1116 gcc_checking_assert (!DEBUG_INSN_P (insn));
1118 excess_cost_change = 0;
1119 for (i = 0; i < ira_pressure_classes_num; i++)
1120 death[ira_pressure_classes[i]] = 0;
1121 for (use = INSN_REG_USE_LIST (insn); use != NULL; use = use->next_insn_use)
1122 if (dying_use_p (use))
1124 cl = sched_regno_pressure_class[use->regno];
1125 if (use->regno < FIRST_PSEUDO_REGISTER)
1126 death[cl]++;
1127 else
1128 death[cl]
1129 += ira_reg_class_max_nregs[cl][PSEUDO_REGNO_MODE (use->regno)];
1131 pressure_info = INSN_REG_PRESSURE (insn);
1132 max_reg_pressure = INSN_MAX_REG_PRESSURE (insn);
1133 gcc_assert (pressure_info != NULL && max_reg_pressure != NULL);
1134 for (i = 0; i < ira_pressure_classes_num; i++)
1136 cl = ira_pressure_classes[i];
1137 gcc_assert (curr_reg_pressure[cl] >= 0);
1138 change = (int) pressure_info[i].set_increase - death[cl];
1139 before = MAX (0, max_reg_pressure[i] - ira_available_class_regs[cl]);
1140 after = MAX (0, max_reg_pressure[i] + change
1141 - ira_available_class_regs[cl]);
1142 hard_regno = ira_class_hard_regs[cl][0];
1143 gcc_assert (hard_regno >= 0);
1144 mode = reg_raw_mode[hard_regno];
1145 excess_cost_change += ((after - before)
1146 * (ira_memory_move_cost[mode][cl][0]
1147 + ira_memory_move_cost[mode][cl][1]));
1149 INSN_REG_PRESSURE_EXCESS_COST_CHANGE (insn) = excess_cost_change;
1152 /* Returns a positive value if x is preferred; returns a negative value if
1153 y is preferred. Should never return 0, since that will make the sort
1154 unstable. */
1156 static int
1157 rank_for_schedule (const void *x, const void *y)
1159 rtx tmp = *(const rtx *) y;
1160 rtx tmp2 = *(const rtx *) x;
1161 rtx last;
1162 int tmp_class, tmp2_class;
1163 int val, priority_val, info_val;
1165 if (MAY_HAVE_DEBUG_INSNS)
1167 /* Schedule debug insns as early as possible. */
1168 if (DEBUG_INSN_P (tmp) && !DEBUG_INSN_P (tmp2))
1169 return -1;
1170 else if (DEBUG_INSN_P (tmp2))
1171 return 1;
1174 /* The insn in a schedule group should be issued the first. */
1175 if (flag_sched_group_heuristic &&
1176 SCHED_GROUP_P (tmp) != SCHED_GROUP_P (tmp2))
1177 return SCHED_GROUP_P (tmp2) ? 1 : -1;
1179 /* Make sure that priority of TMP and TMP2 are initialized. */
1180 gcc_assert (INSN_PRIORITY_KNOWN (tmp) && INSN_PRIORITY_KNOWN (tmp2));
1182 if (sched_pressure_p)
1184 int diff;
1186 /* Prefer insn whose scheduling results in the smallest register
1187 pressure excess. */
1188 if ((diff = (INSN_REG_PRESSURE_EXCESS_COST_CHANGE (tmp)
1189 + (INSN_TICK (tmp) > clock_var
1190 ? INSN_TICK (tmp) - clock_var : 0)
1191 - INSN_REG_PRESSURE_EXCESS_COST_CHANGE (tmp2)
1192 - (INSN_TICK (tmp2) > clock_var
1193 ? INSN_TICK (tmp2) - clock_var : 0))) != 0)
1194 return diff;
1198 if (sched_pressure_p
1199 && (INSN_TICK (tmp2) > clock_var || INSN_TICK (tmp) > clock_var))
1201 if (INSN_TICK (tmp) <= clock_var)
1202 return -1;
1203 else if (INSN_TICK (tmp2) <= clock_var)
1204 return 1;
1205 else
1206 return INSN_TICK (tmp) - INSN_TICK (tmp2);
1208 /* Prefer insn with higher priority. */
1209 priority_val = INSN_PRIORITY (tmp2) - INSN_PRIORITY (tmp);
1211 if (flag_sched_critical_path_heuristic && priority_val)
1212 return priority_val;
1214 /* Prefer speculative insn with greater dependencies weakness. */
1215 if (flag_sched_spec_insn_heuristic && spec_info)
1217 ds_t ds1, ds2;
1218 dw_t dw1, dw2;
1219 int dw;
1221 ds1 = TODO_SPEC (tmp) & SPECULATIVE;
1222 if (ds1)
1223 dw1 = ds_weak (ds1);
1224 else
1225 dw1 = NO_DEP_WEAK;
1227 ds2 = TODO_SPEC (tmp2) & SPECULATIVE;
1228 if (ds2)
1229 dw2 = ds_weak (ds2);
1230 else
1231 dw2 = NO_DEP_WEAK;
1233 dw = dw2 - dw1;
1234 if (dw > (NO_DEP_WEAK / 8) || dw < -(NO_DEP_WEAK / 8))
1235 return dw;
1238 info_val = (*current_sched_info->rank) (tmp, tmp2);
1239 if(flag_sched_rank_heuristic && info_val)
1240 return info_val;
1242 if (flag_sched_last_insn_heuristic)
1244 int i = VEC_length (rtx, scheduled_insns);
1245 last = NULL_RTX;
1246 while (i-- > 0)
1248 last = VEC_index (rtx, scheduled_insns, i);
1249 if (NONDEBUG_INSN_P (last))
1250 break;
1254 /* Compare insns based on their relation to the last scheduled
1255 non-debug insn. */
1256 if (flag_sched_last_insn_heuristic && last && NONDEBUG_INSN_P (last))
1258 dep_t dep1;
1259 dep_t dep2;
1261 /* Classify the instructions into three classes:
1262 1) Data dependent on last schedule insn.
1263 2) Anti/Output dependent on last scheduled insn.
1264 3) Independent of last scheduled insn, or has latency of one.
1265 Choose the insn from the highest numbered class if different. */
1266 dep1 = sd_find_dep_between (last, tmp, true);
1268 if (dep1 == NULL || dep_cost (dep1) == 1)
1269 tmp_class = 3;
1270 else if (/* Data dependence. */
1271 DEP_TYPE (dep1) == REG_DEP_TRUE)
1272 tmp_class = 1;
1273 else
1274 tmp_class = 2;
1276 dep2 = sd_find_dep_between (last, tmp2, true);
1278 if (dep2 == NULL || dep_cost (dep2) == 1)
1279 tmp2_class = 3;
1280 else if (/* Data dependence. */
1281 DEP_TYPE (dep2) == REG_DEP_TRUE)
1282 tmp2_class = 1;
1283 else
1284 tmp2_class = 2;
1286 if ((val = tmp2_class - tmp_class))
1287 return val;
1290 /* Prefer the insn which has more later insns that depend on it.
1291 This gives the scheduler more freedom when scheduling later
1292 instructions at the expense of added register pressure. */
1294 val = (dep_list_size (tmp2) - dep_list_size (tmp));
1296 if (flag_sched_dep_count_heuristic && val != 0)
1297 return val;
1299 /* If insns are equally good, sort by INSN_LUID (original insn order),
1300 so that we make the sort stable. This minimizes instruction movement,
1301 thus minimizing sched's effect on debugging and cross-jumping. */
1302 return INSN_LUID (tmp) - INSN_LUID (tmp2);
1305 /* Resort the array A in which only element at index N may be out of order. */
1307 HAIFA_INLINE static void
1308 swap_sort (rtx *a, int n)
1310 rtx insn = a[n - 1];
1311 int i = n - 2;
1313 while (i >= 0 && rank_for_schedule (a + i, &insn) >= 0)
1315 a[i + 1] = a[i];
1316 i -= 1;
1318 a[i + 1] = insn;
1321 /* Add INSN to the insn queue so that it can be executed at least
1322 N_CYCLES after the currently executing insn. Preserve insns
1323 chain for debugging purposes. REASON will be printed in debugging
1324 output. */
1326 HAIFA_INLINE static void
1327 queue_insn (rtx insn, int n_cycles, const char *reason)
1329 int next_q = NEXT_Q_AFTER (q_ptr, n_cycles);
1330 rtx link = alloc_INSN_LIST (insn, insn_queue[next_q]);
1332 gcc_assert (n_cycles <= max_insn_queue_index);
1333 gcc_assert (!DEBUG_INSN_P (insn));
1335 insn_queue[next_q] = link;
1336 q_size += 1;
1338 if (sched_verbose >= 2)
1340 fprintf (sched_dump, ";;\t\tReady-->Q: insn %s: ",
1341 (*current_sched_info->print_insn) (insn, 0));
1343 fprintf (sched_dump, "queued for %d cycles (%s).\n", n_cycles, reason);
1346 QUEUE_INDEX (insn) = next_q;
1349 /* Remove INSN from queue. */
1350 static void
1351 queue_remove (rtx insn)
1353 gcc_assert (QUEUE_INDEX (insn) >= 0);
1354 remove_free_INSN_LIST_elem (insn, &insn_queue[QUEUE_INDEX (insn)]);
1355 q_size--;
1356 QUEUE_INDEX (insn) = QUEUE_NOWHERE;
1359 /* Return a pointer to the bottom of the ready list, i.e. the insn
1360 with the lowest priority. */
1362 rtx *
1363 ready_lastpos (struct ready_list *ready)
1365 gcc_assert (ready->n_ready >= 1);
1366 return ready->vec + ready->first - ready->n_ready + 1;
1369 /* Add an element INSN to the ready list so that it ends up with the
1370 lowest/highest priority depending on FIRST_P. */
1372 HAIFA_INLINE static void
1373 ready_add (struct ready_list *ready, rtx insn, bool first_p)
1375 if (!first_p)
1377 if (ready->first == ready->n_ready)
1379 memmove (ready->vec + ready->veclen - ready->n_ready,
1380 ready_lastpos (ready),
1381 ready->n_ready * sizeof (rtx));
1382 ready->first = ready->veclen - 1;
1384 ready->vec[ready->first - ready->n_ready] = insn;
1386 else
1388 if (ready->first == ready->veclen - 1)
1390 if (ready->n_ready)
1391 /* ready_lastpos() fails when called with (ready->n_ready == 0). */
1392 memmove (ready->vec + ready->veclen - ready->n_ready - 1,
1393 ready_lastpos (ready),
1394 ready->n_ready * sizeof (rtx));
1395 ready->first = ready->veclen - 2;
1397 ready->vec[++(ready->first)] = insn;
1400 ready->n_ready++;
1401 if (DEBUG_INSN_P (insn))
1402 ready->n_debug++;
1404 gcc_assert (QUEUE_INDEX (insn) != QUEUE_READY);
1405 QUEUE_INDEX (insn) = QUEUE_READY;
1408 /* Remove the element with the highest priority from the ready list and
1409 return it. */
1411 HAIFA_INLINE static rtx
1412 ready_remove_first (struct ready_list *ready)
1414 rtx t;
1416 gcc_assert (ready->n_ready);
1417 t = ready->vec[ready->first--];
1418 ready->n_ready--;
1419 if (DEBUG_INSN_P (t))
1420 ready->n_debug--;
1421 /* If the queue becomes empty, reset it. */
1422 if (ready->n_ready == 0)
1423 ready->first = ready->veclen - 1;
1425 gcc_assert (QUEUE_INDEX (t) == QUEUE_READY);
1426 QUEUE_INDEX (t) = QUEUE_NOWHERE;
1428 return t;
1431 /* The following code implements multi-pass scheduling for the first
1432 cycle. In other words, we will try to choose ready insn which
1433 permits to start maximum number of insns on the same cycle. */
1435 /* Return a pointer to the element INDEX from the ready. INDEX for
1436 insn with the highest priority is 0, and the lowest priority has
1437 N_READY - 1. */
1440 ready_element (struct ready_list *ready, int index)
1442 gcc_assert (ready->n_ready && index < ready->n_ready);
1444 return ready->vec[ready->first - index];
1447 /* Remove the element INDEX from the ready list and return it. INDEX
1448 for insn with the highest priority is 0, and the lowest priority
1449 has N_READY - 1. */
1451 HAIFA_INLINE static rtx
1452 ready_remove (struct ready_list *ready, int index)
1454 rtx t;
1455 int i;
1457 if (index == 0)
1458 return ready_remove_first (ready);
1459 gcc_assert (ready->n_ready && index < ready->n_ready);
1460 t = ready->vec[ready->first - index];
1461 ready->n_ready--;
1462 if (DEBUG_INSN_P (t))
1463 ready->n_debug--;
1464 for (i = index; i < ready->n_ready; i++)
1465 ready->vec[ready->first - i] = ready->vec[ready->first - i - 1];
1466 QUEUE_INDEX (t) = QUEUE_NOWHERE;
1467 return t;
1470 /* Remove INSN from the ready list. */
1471 static void
1472 ready_remove_insn (rtx insn)
1474 int i;
1476 for (i = 0; i < readyp->n_ready; i++)
1477 if (ready_element (readyp, i) == insn)
1479 ready_remove (readyp, i);
1480 return;
1482 gcc_unreachable ();
1485 /* Sort the ready list READY by ascending priority, using the SCHED_SORT
1486 macro. */
1488 void
1489 ready_sort (struct ready_list *ready)
1491 int i;
1492 rtx *first = ready_lastpos (ready);
1494 if (sched_pressure_p)
1496 for (i = 0; i < ready->n_ready; i++)
1497 if (!DEBUG_INSN_P (first[i]))
1498 setup_insn_reg_pressure_info (first[i]);
1500 SCHED_SORT (first, ready->n_ready);
1503 /* PREV is an insn that is ready to execute. Adjust its priority if that
1504 will help shorten or lengthen register lifetimes as appropriate. Also
1505 provide a hook for the target to tweak itself. */
1507 HAIFA_INLINE static void
1508 adjust_priority (rtx prev)
1510 /* ??? There used to be code here to try and estimate how an insn
1511 affected register lifetimes, but it did it by looking at REG_DEAD
1512 notes, which we removed in schedule_region. Nor did it try to
1513 take into account register pressure or anything useful like that.
1515 Revisit when we have a machine model to work with and not before. */
1517 if (targetm.sched.adjust_priority)
1518 INSN_PRIORITY (prev) =
1519 targetm.sched.adjust_priority (prev, INSN_PRIORITY (prev));
1522 /* Advance DFA state STATE on one cycle. */
1523 void
1524 advance_state (state_t state)
1526 if (targetm.sched.dfa_pre_advance_cycle)
1527 targetm.sched.dfa_pre_advance_cycle ();
1529 if (targetm.sched.dfa_pre_cycle_insn)
1530 state_transition (state,
1531 targetm.sched.dfa_pre_cycle_insn ());
1533 state_transition (state, NULL);
1535 if (targetm.sched.dfa_post_cycle_insn)
1536 state_transition (state,
1537 targetm.sched.dfa_post_cycle_insn ());
1539 if (targetm.sched.dfa_post_advance_cycle)
1540 targetm.sched.dfa_post_advance_cycle ();
1543 /* Advance time on one cycle. */
1544 HAIFA_INLINE static void
1545 advance_one_cycle (void)
1547 advance_state (curr_state);
1548 if (sched_verbose >= 6)
1549 fprintf (sched_dump, ";;\tAdvanced a state.\n");
1552 /* Clock at which the previous instruction was issued. */
1553 static int last_clock_var;
1555 /* Update register pressure after scheduling INSN. */
1556 static void
1557 update_register_pressure (rtx insn)
1559 struct reg_use_data *use;
1560 struct reg_set_data *set;
1562 gcc_checking_assert (!DEBUG_INSN_P (insn));
1564 for (use = INSN_REG_USE_LIST (insn); use != NULL; use = use->next_insn_use)
1565 if (dying_use_p (use) && bitmap_bit_p (curr_reg_live, use->regno))
1566 mark_regno_birth_or_death (use->regno, false);
1567 for (set = INSN_REG_SET_LIST (insn); set != NULL; set = set->next_insn_set)
1568 mark_regno_birth_or_death (set->regno, true);
1571 /* Set up or update (if UPDATE_P) max register pressure (see its
1572 meaning in sched-int.h::_haifa_insn_data) for all current BB insns
1573 after insn AFTER. */
1574 static void
1575 setup_insn_max_reg_pressure (rtx after, bool update_p)
1577 int i, p;
1578 bool eq_p;
1579 rtx insn;
1580 static int max_reg_pressure[N_REG_CLASSES];
1582 save_reg_pressure ();
1583 for (i = 0; i < ira_pressure_classes_num; i++)
1584 max_reg_pressure[ira_pressure_classes[i]]
1585 = curr_reg_pressure[ira_pressure_classes[i]];
1586 for (insn = NEXT_INSN (after);
1587 insn != NULL_RTX && ! BARRIER_P (insn)
1588 && BLOCK_FOR_INSN (insn) == BLOCK_FOR_INSN (after);
1589 insn = NEXT_INSN (insn))
1590 if (NONDEBUG_INSN_P (insn))
1592 eq_p = true;
1593 for (i = 0; i < ira_pressure_classes_num; i++)
1595 p = max_reg_pressure[ira_pressure_classes[i]];
1596 if (INSN_MAX_REG_PRESSURE (insn)[i] != p)
1598 eq_p = false;
1599 INSN_MAX_REG_PRESSURE (insn)[i]
1600 = max_reg_pressure[ira_pressure_classes[i]];
1603 if (update_p && eq_p)
1604 break;
1605 update_register_pressure (insn);
1606 for (i = 0; i < ira_pressure_classes_num; i++)
1607 if (max_reg_pressure[ira_pressure_classes[i]]
1608 < curr_reg_pressure[ira_pressure_classes[i]])
1609 max_reg_pressure[ira_pressure_classes[i]]
1610 = curr_reg_pressure[ira_pressure_classes[i]];
1612 restore_reg_pressure ();
1615 /* Update the current register pressure after scheduling INSN. Update
1616 also max register pressure for unscheduled insns of the current
1617 BB. */
1618 static void
1619 update_reg_and_insn_max_reg_pressure (rtx insn)
1621 int i;
1622 int before[N_REG_CLASSES];
1624 for (i = 0; i < ira_pressure_classes_num; i++)
1625 before[i] = curr_reg_pressure[ira_pressure_classes[i]];
1626 update_register_pressure (insn);
1627 for (i = 0; i < ira_pressure_classes_num; i++)
1628 if (curr_reg_pressure[ira_pressure_classes[i]] != before[i])
1629 break;
1630 if (i < ira_pressure_classes_num)
1631 setup_insn_max_reg_pressure (insn, true);
1634 /* Set up register pressure at the beginning of basic block BB whose
1635 insns starting after insn AFTER. Set up also max register pressure
1636 for all insns of the basic block. */
1637 void
1638 sched_setup_bb_reg_pressure_info (basic_block bb, rtx after)
1640 gcc_assert (sched_pressure_p);
1641 initiate_bb_reg_pressure_info (bb);
1642 setup_insn_max_reg_pressure (after, false);
1645 /* INSN is the "currently executing insn". Launch each insn which was
1646 waiting on INSN. READY is the ready list which contains the insns
1647 that are ready to fire. CLOCK is the current cycle. The function
1648 returns necessary cycle advance after issuing the insn (it is not
1649 zero for insns in a schedule group). */
1651 static int
1652 schedule_insn (rtx insn)
1654 sd_iterator_def sd_it;
1655 dep_t dep;
1656 int i;
1657 int advance = 0;
1659 if (sched_verbose >= 1)
1661 struct reg_pressure_data *pressure_info;
1662 char buf[2048];
1664 print_insn (buf, insn, 0);
1665 buf[40] = 0;
1666 fprintf (sched_dump, ";;\t%3i--> %-40s:", clock_var, buf);
1668 if (recog_memoized (insn) < 0)
1669 fprintf (sched_dump, "nothing");
1670 else
1671 print_reservation (sched_dump, insn);
1672 pressure_info = INSN_REG_PRESSURE (insn);
1673 if (pressure_info != NULL)
1675 fputc (':', sched_dump);
1676 for (i = 0; i < ira_pressure_classes_num; i++)
1677 fprintf (sched_dump, "%s%+d(%d)",
1678 reg_class_names[ira_pressure_classes[i]],
1679 pressure_info[i].set_increase, pressure_info[i].change);
1681 fputc ('\n', sched_dump);
1684 if (sched_pressure_p && !DEBUG_INSN_P (insn))
1685 update_reg_and_insn_max_reg_pressure (insn);
1687 /* Scheduling instruction should have all its dependencies resolved and
1688 should have been removed from the ready list. */
1689 gcc_assert (sd_lists_empty_p (insn, SD_LIST_BACK));
1691 /* Reset debug insns invalidated by moving this insn. */
1692 if (MAY_HAVE_DEBUG_INSNS && !DEBUG_INSN_P (insn))
1693 for (sd_it = sd_iterator_start (insn, SD_LIST_BACK);
1694 sd_iterator_cond (&sd_it, &dep);)
1696 rtx dbg = DEP_PRO (dep);
1697 struct reg_use_data *use, *next;
1699 gcc_assert (DEBUG_INSN_P (dbg));
1701 if (sched_verbose >= 6)
1702 fprintf (sched_dump, ";;\t\tresetting: debug insn %d\n",
1703 INSN_UID (dbg));
1705 /* ??? Rather than resetting the debug insn, we might be able
1706 to emit a debug temp before the just-scheduled insn, but
1707 this would involve checking that the expression at the
1708 point of the debug insn is equivalent to the expression
1709 before the just-scheduled insn. They might not be: the
1710 expression in the debug insn may depend on other insns not
1711 yet scheduled that set MEMs, REGs or even other debug
1712 insns. It's not clear that attempting to preserve debug
1713 information in these cases is worth the effort, given how
1714 uncommon these resets are and the likelihood that the debug
1715 temps introduced won't survive the schedule change. */
1716 INSN_VAR_LOCATION_LOC (dbg) = gen_rtx_UNKNOWN_VAR_LOC ();
1717 df_insn_rescan (dbg);
1719 /* Unknown location doesn't use any registers. */
1720 for (use = INSN_REG_USE_LIST (dbg); use != NULL; use = next)
1722 struct reg_use_data *prev = use;
1724 /* Remove use from the cyclic next_regno_use chain first. */
1725 while (prev->next_regno_use != use)
1726 prev = prev->next_regno_use;
1727 prev->next_regno_use = use->next_regno_use;
1728 next = use->next_insn_use;
1729 free (use);
1731 INSN_REG_USE_LIST (dbg) = NULL;
1733 /* We delete rather than resolve these deps, otherwise we
1734 crash in sched_free_deps(), because forward deps are
1735 expected to be released before backward deps. */
1736 sd_delete_dep (sd_it);
1739 gcc_assert (QUEUE_INDEX (insn) == QUEUE_NOWHERE);
1740 QUEUE_INDEX (insn) = QUEUE_SCHEDULED;
1742 gcc_assert (INSN_TICK (insn) >= MIN_TICK);
1743 if (INSN_TICK (insn) > clock_var)
1744 /* INSN has been prematurely moved from the queue to the ready list.
1745 This is possible only if following flag is set. */
1746 gcc_assert (flag_sched_stalled_insns);
1748 /* ??? Probably, if INSN is scheduled prematurely, we should leave
1749 INSN_TICK untouched. This is a machine-dependent issue, actually. */
1750 INSN_TICK (insn) = clock_var;
1752 /* Update dependent instructions. */
1753 for (sd_it = sd_iterator_start (insn, SD_LIST_FORW);
1754 sd_iterator_cond (&sd_it, &dep);)
1756 rtx next = DEP_CON (dep);
1758 /* Resolve the dependence between INSN and NEXT.
1759 sd_resolve_dep () moves current dep to another list thus
1760 advancing the iterator. */
1761 sd_resolve_dep (sd_it);
1763 /* Don't bother trying to mark next as ready if insn is a debug
1764 insn. If insn is the last hard dependency, it will have
1765 already been discounted. */
1766 if (DEBUG_INSN_P (insn) && !DEBUG_INSN_P (next))
1767 continue;
1769 if (!IS_SPECULATION_BRANCHY_CHECK_P (insn))
1771 int effective_cost;
1773 effective_cost = try_ready (next);
1775 if (effective_cost >= 0
1776 && SCHED_GROUP_P (next)
1777 && advance < effective_cost)
1778 advance = effective_cost;
1780 else
1781 /* Check always has only one forward dependence (to the first insn in
1782 the recovery block), therefore, this will be executed only once. */
1784 gcc_assert (sd_lists_empty_p (insn, SD_LIST_FORW));
1785 fix_recovery_deps (RECOVERY_BLOCK (insn));
1789 /* This is the place where scheduler doesn't *basically* need backward and
1790 forward dependencies for INSN anymore. Nevertheless they are used in
1791 heuristics in rank_for_schedule (), early_queue_to_ready () and in
1792 some targets (e.g. rs6000). Thus the earliest place where we *can*
1793 remove dependencies is after targetm.sched.finish () call in
1794 schedule_block (). But, on the other side, the safest place to remove
1795 dependencies is when we are finishing scheduling entire region. As we
1796 don't generate [many] dependencies during scheduling itself, we won't
1797 need memory until beginning of next region.
1798 Bottom line: Dependencies are removed for all insns in the end of
1799 scheduling the region. */
1801 /* Annotate the instruction with issue information -- TImode
1802 indicates that the instruction is expected not to be able
1803 to issue on the same cycle as the previous insn. A machine
1804 may use this information to decide how the instruction should
1805 be aligned. */
1806 if (issue_rate > 1
1807 && GET_CODE (PATTERN (insn)) != USE
1808 && GET_CODE (PATTERN (insn)) != CLOBBER
1809 && !DEBUG_INSN_P (insn))
1811 if (reload_completed)
1812 PUT_MODE (insn, clock_var > last_clock_var ? TImode : VOIDmode);
1813 last_clock_var = clock_var;
1816 return advance;
1819 /* Functions for handling of notes. */
1821 /* Add note list that ends on FROM_END to the end of TO_ENDP. */
1822 void
1823 concat_note_lists (rtx from_end, rtx *to_endp)
1825 rtx from_start;
1827 /* It's easy when have nothing to concat. */
1828 if (from_end == NULL)
1829 return;
1831 /* It's also easy when destination is empty. */
1832 if (*to_endp == NULL)
1834 *to_endp = from_end;
1835 return;
1838 from_start = from_end;
1839 while (PREV_INSN (from_start) != NULL)
1840 from_start = PREV_INSN (from_start);
1842 PREV_INSN (from_start) = *to_endp;
1843 NEXT_INSN (*to_endp) = from_start;
1844 *to_endp = from_end;
1847 /* Delete notes between HEAD and TAIL and put them in the chain
1848 of notes ended by NOTE_LIST. */
1849 void
1850 remove_notes (rtx head, rtx tail)
1852 rtx next_tail, insn, next;
1854 note_list = 0;
1855 if (head == tail && !INSN_P (head))
1856 return;
1858 next_tail = NEXT_INSN (tail);
1859 for (insn = head; insn != next_tail; insn = next)
1861 next = NEXT_INSN (insn);
1862 if (!NOTE_P (insn))
1863 continue;
1865 switch (NOTE_KIND (insn))
1867 case NOTE_INSN_BASIC_BLOCK:
1868 continue;
1870 case NOTE_INSN_EPILOGUE_BEG:
1871 if (insn != tail)
1873 remove_insn (insn);
1874 add_reg_note (next, REG_SAVE_NOTE,
1875 GEN_INT (NOTE_INSN_EPILOGUE_BEG));
1876 break;
1878 /* FALLTHRU */
1880 default:
1881 remove_insn (insn);
1883 /* Add the note to list that ends at NOTE_LIST. */
1884 PREV_INSN (insn) = note_list;
1885 NEXT_INSN (insn) = NULL_RTX;
1886 if (note_list)
1887 NEXT_INSN (note_list) = insn;
1888 note_list = insn;
1889 break;
1892 gcc_assert ((sel_sched_p () || insn != tail) && insn != head);
1897 /* Return the head and tail pointers of ebb starting at BEG and ending
1898 at END. */
1899 void
1900 get_ebb_head_tail (basic_block beg, basic_block end, rtx *headp, rtx *tailp)
1902 rtx beg_head = BB_HEAD (beg);
1903 rtx beg_tail = BB_END (beg);
1904 rtx end_head = BB_HEAD (end);
1905 rtx end_tail = BB_END (end);
1907 /* Don't include any notes or labels at the beginning of the BEG
1908 basic block, or notes at the end of the END basic blocks. */
1910 if (LABEL_P (beg_head))
1911 beg_head = NEXT_INSN (beg_head);
1913 while (beg_head != beg_tail)
1914 if (NOTE_P (beg_head))
1915 beg_head = NEXT_INSN (beg_head);
1916 else if (DEBUG_INSN_P (beg_head))
1918 rtx note, next;
1920 for (note = NEXT_INSN (beg_head);
1921 note != beg_tail;
1922 note = next)
1924 next = NEXT_INSN (note);
1925 if (NOTE_P (note))
1927 if (sched_verbose >= 9)
1928 fprintf (sched_dump, "reorder %i\n", INSN_UID (note));
1930 reorder_insns_nobb (note, note, PREV_INSN (beg_head));
1932 if (BLOCK_FOR_INSN (note) != beg)
1933 df_insn_change_bb (note, beg);
1935 else if (!DEBUG_INSN_P (note))
1936 break;
1939 break;
1941 else
1942 break;
1944 *headp = beg_head;
1946 if (beg == end)
1947 end_head = beg_head;
1948 else if (LABEL_P (end_head))
1949 end_head = NEXT_INSN (end_head);
1951 while (end_head != end_tail)
1952 if (NOTE_P (end_tail))
1953 end_tail = PREV_INSN (end_tail);
1954 else if (DEBUG_INSN_P (end_tail))
1956 rtx note, prev;
1958 for (note = PREV_INSN (end_tail);
1959 note != end_head;
1960 note = prev)
1962 prev = PREV_INSN (note);
1963 if (NOTE_P (note))
1965 if (sched_verbose >= 9)
1966 fprintf (sched_dump, "reorder %i\n", INSN_UID (note));
1968 reorder_insns_nobb (note, note, end_tail);
1970 if (end_tail == BB_END (end))
1971 BB_END (end) = note;
1973 if (BLOCK_FOR_INSN (note) != end)
1974 df_insn_change_bb (note, end);
1976 else if (!DEBUG_INSN_P (note))
1977 break;
1980 break;
1982 else
1983 break;
1985 *tailp = end_tail;
1988 /* Return nonzero if there are no real insns in the range [ HEAD, TAIL ]. */
1991 no_real_insns_p (const_rtx head, const_rtx tail)
1993 while (head != NEXT_INSN (tail))
1995 if (!NOTE_P (head) && !LABEL_P (head))
1996 return 0;
1997 head = NEXT_INSN (head);
1999 return 1;
2002 /* Restore-other-notes: NOTE_LIST is the end of a chain of notes
2003 previously found among the insns. Insert them just before HEAD. */
2005 restore_other_notes (rtx head, basic_block head_bb)
2007 if (note_list != 0)
2009 rtx note_head = note_list;
2011 if (head)
2012 head_bb = BLOCK_FOR_INSN (head);
2013 else
2014 head = NEXT_INSN (bb_note (head_bb));
2016 while (PREV_INSN (note_head))
2018 set_block_for_insn (note_head, head_bb);
2019 note_head = PREV_INSN (note_head);
2021 /* In the above cycle we've missed this note. */
2022 set_block_for_insn (note_head, head_bb);
2024 PREV_INSN (note_head) = PREV_INSN (head);
2025 NEXT_INSN (PREV_INSN (head)) = note_head;
2026 PREV_INSN (head) = note_list;
2027 NEXT_INSN (note_list) = head;
2029 if (BLOCK_FOR_INSN (head) != head_bb)
2030 BB_END (head_bb) = note_list;
2032 head = note_head;
2035 return head;
2038 /* Move insns that became ready to fire from queue to ready list. */
2040 static void
2041 queue_to_ready (struct ready_list *ready)
2043 rtx insn;
2044 rtx link;
2045 rtx skip_insn;
2047 q_ptr = NEXT_Q (q_ptr);
2049 if (dbg_cnt (sched_insn) == false)
2051 /* If debug counter is activated do not requeue the first
2052 nonscheduled insn. */
2053 skip_insn = nonscheduled_insns_begin;
2056 skip_insn = next_nonnote_nondebug_insn (skip_insn);
2058 while (QUEUE_INDEX (skip_insn) == QUEUE_SCHEDULED);
2060 else
2061 skip_insn = NULL_RTX;
2063 /* Add all pending insns that can be scheduled without stalls to the
2064 ready list. */
2065 for (link = insn_queue[q_ptr]; link; link = XEXP (link, 1))
2067 insn = XEXP (link, 0);
2068 q_size -= 1;
2070 if (sched_verbose >= 2)
2071 fprintf (sched_dump, ";;\t\tQ-->Ready: insn %s: ",
2072 (*current_sched_info->print_insn) (insn, 0));
2074 /* If the ready list is full, delay the insn for 1 cycle.
2075 See the comment in schedule_block for the rationale. */
2076 if (!reload_completed
2077 && ready->n_ready - ready->n_debug > MAX_SCHED_READY_INSNS
2078 && !SCHED_GROUP_P (insn)
2079 && insn != skip_insn)
2080 queue_insn (insn, 1, "ready full");
2081 else
2083 ready_add (ready, insn, false);
2084 if (sched_verbose >= 2)
2085 fprintf (sched_dump, "moving to ready without stalls\n");
2088 free_INSN_LIST_list (&insn_queue[q_ptr]);
2090 /* If there are no ready insns, stall until one is ready and add all
2091 of the pending insns at that point to the ready list. */
2092 if (ready->n_ready == 0)
2094 int stalls;
2096 for (stalls = 1; stalls <= max_insn_queue_index; stalls++)
2098 if ((link = insn_queue[NEXT_Q_AFTER (q_ptr, stalls)]))
2100 for (; link; link = XEXP (link, 1))
2102 insn = XEXP (link, 0);
2103 q_size -= 1;
2105 if (sched_verbose >= 2)
2106 fprintf (sched_dump, ";;\t\tQ-->Ready: insn %s: ",
2107 (*current_sched_info->print_insn) (insn, 0));
2109 ready_add (ready, insn, false);
2110 if (sched_verbose >= 2)
2111 fprintf (sched_dump, "moving to ready with %d stalls\n", stalls);
2113 free_INSN_LIST_list (&insn_queue[NEXT_Q_AFTER (q_ptr, stalls)]);
2115 advance_one_cycle ();
2117 break;
2120 advance_one_cycle ();
2123 q_ptr = NEXT_Q_AFTER (q_ptr, stalls);
2124 clock_var += stalls;
2128 /* Used by early_queue_to_ready. Determines whether it is "ok" to
2129 prematurely move INSN from the queue to the ready list. Currently,
2130 if a target defines the hook 'is_costly_dependence', this function
2131 uses the hook to check whether there exist any dependences which are
2132 considered costly by the target, between INSN and other insns that
2133 have already been scheduled. Dependences are checked up to Y cycles
2134 back, with default Y=1; The flag -fsched-stalled-insns-dep=Y allows
2135 controlling this value.
2136 (Other considerations could be taken into account instead (or in
2137 addition) depending on user flags and target hooks. */
2139 static bool
2140 ok_for_early_queue_removal (rtx insn)
2142 if (targetm.sched.is_costly_dependence)
2144 rtx prev_insn;
2145 int n_cycles;
2146 int i = VEC_length (rtx, scheduled_insns);
2147 for (n_cycles = flag_sched_stalled_insns_dep; n_cycles; n_cycles--)
2149 while (i-- > 0)
2151 int cost;
2153 prev_insn = VEC_index (rtx, scheduled_insns, i);
2155 if (!NOTE_P (prev_insn))
2157 dep_t dep;
2159 dep = sd_find_dep_between (prev_insn, insn, true);
2161 if (dep != NULL)
2163 cost = dep_cost (dep);
2165 if (targetm.sched.is_costly_dependence (dep, cost,
2166 flag_sched_stalled_insns_dep - n_cycles))
2167 return false;
2171 if (GET_MODE (prev_insn) == TImode) /* end of dispatch group */
2172 break;
2175 if (i == 0)
2176 break;
2180 return true;
2184 /* Remove insns from the queue, before they become "ready" with respect
2185 to FU latency considerations. */
2187 static int
2188 early_queue_to_ready (state_t state, struct ready_list *ready)
2190 rtx insn;
2191 rtx link;
2192 rtx next_link;
2193 rtx prev_link;
2194 bool move_to_ready;
2195 int cost;
2196 state_t temp_state = alloca (dfa_state_size);
2197 int stalls;
2198 int insns_removed = 0;
2201 Flag '-fsched-stalled-insns=X' determines the aggressiveness of this
2202 function:
2204 X == 0: There is no limit on how many queued insns can be removed
2205 prematurely. (flag_sched_stalled_insns = -1).
2207 X >= 1: Only X queued insns can be removed prematurely in each
2208 invocation. (flag_sched_stalled_insns = X).
2210 Otherwise: Early queue removal is disabled.
2211 (flag_sched_stalled_insns = 0)
2214 if (! flag_sched_stalled_insns)
2215 return 0;
2217 for (stalls = 0; stalls <= max_insn_queue_index; stalls++)
2219 if ((link = insn_queue[NEXT_Q_AFTER (q_ptr, stalls)]))
2221 if (sched_verbose > 6)
2222 fprintf (sched_dump, ";; look at index %d + %d\n", q_ptr, stalls);
2224 prev_link = 0;
2225 while (link)
2227 next_link = XEXP (link, 1);
2228 insn = XEXP (link, 0);
2229 if (insn && sched_verbose > 6)
2230 print_rtl_single (sched_dump, insn);
2232 memcpy (temp_state, state, dfa_state_size);
2233 if (recog_memoized (insn) < 0)
2234 /* non-negative to indicate that it's not ready
2235 to avoid infinite Q->R->Q->R... */
2236 cost = 0;
2237 else
2238 cost = state_transition (temp_state, insn);
2240 if (sched_verbose >= 6)
2241 fprintf (sched_dump, "transition cost = %d\n", cost);
2243 move_to_ready = false;
2244 if (cost < 0)
2246 move_to_ready = ok_for_early_queue_removal (insn);
2247 if (move_to_ready == true)
2249 /* move from Q to R */
2250 q_size -= 1;
2251 ready_add (ready, insn, false);
2253 if (prev_link)
2254 XEXP (prev_link, 1) = next_link;
2255 else
2256 insn_queue[NEXT_Q_AFTER (q_ptr, stalls)] = next_link;
2258 free_INSN_LIST_node (link);
2260 if (sched_verbose >= 2)
2261 fprintf (sched_dump, ";;\t\tEarly Q-->Ready: insn %s\n",
2262 (*current_sched_info->print_insn) (insn, 0));
2264 insns_removed++;
2265 if (insns_removed == flag_sched_stalled_insns)
2266 /* Remove no more than flag_sched_stalled_insns insns
2267 from Q at a time. */
2268 return insns_removed;
2272 if (move_to_ready == false)
2273 prev_link = link;
2275 link = next_link;
2276 } /* while link */
2277 } /* if link */
2279 } /* for stalls.. */
2281 return insns_removed;
2285 /* Print the ready list for debugging purposes. Callable from debugger. */
2287 static void
2288 debug_ready_list (struct ready_list *ready)
2290 rtx *p;
2291 int i;
2293 if (ready->n_ready == 0)
2295 fprintf (sched_dump, "\n");
2296 return;
2299 p = ready_lastpos (ready);
2300 for (i = 0; i < ready->n_ready; i++)
2302 fprintf (sched_dump, " %s:%d",
2303 (*current_sched_info->print_insn) (p[i], 0),
2304 INSN_LUID (p[i]));
2305 if (sched_pressure_p)
2306 fprintf (sched_dump, "(cost=%d",
2307 INSN_REG_PRESSURE_EXCESS_COST_CHANGE (p[i]));
2308 if (INSN_TICK (p[i]) > clock_var)
2309 fprintf (sched_dump, ":delay=%d", INSN_TICK (p[i]) - clock_var);
2310 if (sched_pressure_p)
2311 fprintf (sched_dump, ")");
2313 fprintf (sched_dump, "\n");
2316 /* Search INSN for REG_SAVE_NOTE notes and convert them back into insn
2317 NOTEs. This is used for NOTE_INSN_EPILOGUE_BEG, so that sched-ebb
2318 replaces the epilogue note in the correct basic block. */
2319 void
2320 reemit_notes (rtx insn)
2322 rtx note, last = insn;
2324 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
2326 if (REG_NOTE_KIND (note) == REG_SAVE_NOTE)
2328 enum insn_note note_type = (enum insn_note) INTVAL (XEXP (note, 0));
2330 last = emit_note_before (note_type, last);
2331 remove_note (insn, note);
2336 /* Move INSN. Reemit notes if needed. Update CFG, if needed. */
2337 static void
2338 move_insn (rtx insn, rtx last, rtx nt)
2340 if (PREV_INSN (insn) != last)
2342 basic_block bb;
2343 rtx note;
2344 int jump_p = 0;
2346 bb = BLOCK_FOR_INSN (insn);
2348 /* BB_HEAD is either LABEL or NOTE. */
2349 gcc_assert (BB_HEAD (bb) != insn);
2351 if (BB_END (bb) == insn)
2352 /* If this is last instruction in BB, move end marker one
2353 instruction up. */
2355 /* Jumps are always placed at the end of basic block. */
2356 jump_p = control_flow_insn_p (insn);
2358 gcc_assert (!jump_p
2359 || ((common_sched_info->sched_pass_id == SCHED_RGN_PASS)
2360 && IS_SPECULATION_BRANCHY_CHECK_P (insn))
2361 || (common_sched_info->sched_pass_id
2362 == SCHED_EBB_PASS));
2364 gcc_assert (BLOCK_FOR_INSN (PREV_INSN (insn)) == bb);
2366 BB_END (bb) = PREV_INSN (insn);
2369 gcc_assert (BB_END (bb) != last);
2371 if (jump_p)
2372 /* We move the block note along with jump. */
2374 gcc_assert (nt);
2376 note = NEXT_INSN (insn);
2377 while (NOTE_NOT_BB_P (note) && note != nt)
2378 note = NEXT_INSN (note);
2380 if (note != nt
2381 && (LABEL_P (note)
2382 || BARRIER_P (note)))
2383 note = NEXT_INSN (note);
2385 gcc_assert (NOTE_INSN_BASIC_BLOCK_P (note));
2387 else
2388 note = insn;
2390 NEXT_INSN (PREV_INSN (insn)) = NEXT_INSN (note);
2391 PREV_INSN (NEXT_INSN (note)) = PREV_INSN (insn);
2393 NEXT_INSN (note) = NEXT_INSN (last);
2394 PREV_INSN (NEXT_INSN (last)) = note;
2396 NEXT_INSN (last) = insn;
2397 PREV_INSN (insn) = last;
2399 bb = BLOCK_FOR_INSN (last);
2401 if (jump_p)
2403 fix_jump_move (insn);
2405 if (BLOCK_FOR_INSN (insn) != bb)
2406 move_block_after_check (insn);
2408 gcc_assert (BB_END (bb) == last);
2411 df_insn_change_bb (insn, bb);
2413 /* Update BB_END, if needed. */
2414 if (BB_END (bb) == last)
2415 BB_END (bb) = insn;
2418 SCHED_GROUP_P (insn) = 0;
2421 /* Return true if scheduling INSN will finish current clock cycle. */
2422 static bool
2423 insn_finishes_cycle_p (rtx insn)
2425 if (SCHED_GROUP_P (insn))
2426 /* After issuing INSN, rest of the sched_group will be forced to issue
2427 in order. Don't make any plans for the rest of cycle. */
2428 return true;
2430 /* Finishing the block will, apparently, finish the cycle. */
2431 if (current_sched_info->insn_finishes_block_p
2432 && current_sched_info->insn_finishes_block_p (insn))
2433 return true;
2435 return false;
2438 /* Define type for target data used in multipass scheduling. */
2439 #ifndef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DATA_T
2440 # define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DATA_T int
2441 #endif
2442 typedef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DATA_T first_cycle_multipass_data_t;
2444 /* The following structure describe an entry of the stack of choices. */
2445 struct choice_entry
2447 /* Ordinal number of the issued insn in the ready queue. */
2448 int index;
2449 /* The number of the rest insns whose issues we should try. */
2450 int rest;
2451 /* The number of issued essential insns. */
2452 int n;
2453 /* State after issuing the insn. */
2454 state_t state;
2455 /* Target-specific data. */
2456 first_cycle_multipass_data_t target_data;
2459 /* The following array is used to implement a stack of choices used in
2460 function max_issue. */
2461 static struct choice_entry *choice_stack;
2463 /* The following variable value is number of essential insns issued on
2464 the current cycle. An insn is essential one if it changes the
2465 processors state. */
2466 int cycle_issued_insns;
2468 /* This holds the value of the target dfa_lookahead hook. */
2469 int dfa_lookahead;
2471 /* The following variable value is maximal number of tries of issuing
2472 insns for the first cycle multipass insn scheduling. We define
2473 this value as constant*(DFA_LOOKAHEAD**ISSUE_RATE). We would not
2474 need this constraint if all real insns (with non-negative codes)
2475 had reservations because in this case the algorithm complexity is
2476 O(DFA_LOOKAHEAD**ISSUE_RATE). Unfortunately, the dfa descriptions
2477 might be incomplete and such insn might occur. For such
2478 descriptions, the complexity of algorithm (without the constraint)
2479 could achieve DFA_LOOKAHEAD ** N , where N is the queue length. */
2480 static int max_lookahead_tries;
2482 /* The following value is value of hook
2483 `first_cycle_multipass_dfa_lookahead' at the last call of
2484 `max_issue'. */
2485 static int cached_first_cycle_multipass_dfa_lookahead = 0;
2487 /* The following value is value of `issue_rate' at the last call of
2488 `sched_init'. */
2489 static int cached_issue_rate = 0;
2491 /* The following function returns maximal (or close to maximal) number
2492 of insns which can be issued on the same cycle and one of which
2493 insns is insns with the best rank (the first insn in READY). To
2494 make this function tries different samples of ready insns. READY
2495 is current queue `ready'. Global array READY_TRY reflects what
2496 insns are already issued in this try. The function stops immediately,
2497 if it reached the such a solution, that all instruction can be issued.
2498 INDEX will contain index of the best insn in READY. The following
2499 function is used only for first cycle multipass scheduling.
2501 PRIVILEGED_N >= 0
2503 This function expects recognized insns only. All USEs,
2504 CLOBBERs, etc must be filtered elsewhere. */
2506 max_issue (struct ready_list *ready, int privileged_n, state_t state,
2507 bool first_cycle_insn_p, int *index)
2509 int n, i, all, n_ready, best, delay, tries_num;
2510 int more_issue;
2511 struct choice_entry *top;
2512 rtx insn;
2514 n_ready = ready->n_ready;
2515 gcc_assert (dfa_lookahead >= 1 && privileged_n >= 0
2516 && privileged_n <= n_ready);
2518 /* Init MAX_LOOKAHEAD_TRIES. */
2519 if (cached_first_cycle_multipass_dfa_lookahead != dfa_lookahead)
2521 cached_first_cycle_multipass_dfa_lookahead = dfa_lookahead;
2522 max_lookahead_tries = 100;
2523 for (i = 0; i < issue_rate; i++)
2524 max_lookahead_tries *= dfa_lookahead;
2527 /* Init max_points. */
2528 more_issue = issue_rate - cycle_issued_insns;
2529 gcc_assert (more_issue >= 0);
2531 /* The number of the issued insns in the best solution. */
2532 best = 0;
2534 top = choice_stack;
2536 /* Set initial state of the search. */
2537 memcpy (top->state, state, dfa_state_size);
2538 top->rest = dfa_lookahead;
2539 top->n = 0;
2540 if (targetm.sched.first_cycle_multipass_begin)
2541 targetm.sched.first_cycle_multipass_begin (&top->target_data,
2542 ready_try, n_ready,
2543 first_cycle_insn_p);
2545 /* Count the number of the insns to search among. */
2546 for (all = i = 0; i < n_ready; i++)
2547 if (!ready_try [i])
2548 all++;
2550 /* I is the index of the insn to try next. */
2551 i = 0;
2552 tries_num = 0;
2553 for (;;)
2555 if (/* If we've reached a dead end or searched enough of what we have
2556 been asked... */
2557 top->rest == 0
2558 /* or have nothing else to try... */
2559 || i >= n_ready
2560 /* or should not issue more. */
2561 || top->n >= more_issue)
2563 /* ??? (... || i == n_ready). */
2564 gcc_assert (i <= n_ready);
2566 /* We should not issue more than issue_rate instructions. */
2567 gcc_assert (top->n <= more_issue);
2569 if (top == choice_stack)
2570 break;
2572 if (best < top - choice_stack)
2574 if (privileged_n)
2576 n = privileged_n;
2577 /* Try to find issued privileged insn. */
2578 while (n && !ready_try[--n]);
2581 if (/* If all insns are equally good... */
2582 privileged_n == 0
2583 /* Or a privileged insn will be issued. */
2584 || ready_try[n])
2585 /* Then we have a solution. */
2587 best = top - choice_stack;
2588 /* This is the index of the insn issued first in this
2589 solution. */
2590 *index = choice_stack [1].index;
2591 if (top->n == more_issue || best == all)
2592 break;
2596 /* Set ready-list index to point to the last insn
2597 ('i++' below will advance it to the next insn). */
2598 i = top->index;
2600 /* Backtrack. */
2601 ready_try [i] = 0;
2603 if (targetm.sched.first_cycle_multipass_backtrack)
2604 targetm.sched.first_cycle_multipass_backtrack (&top->target_data,
2605 ready_try, n_ready);
2607 top--;
2608 memcpy (state, top->state, dfa_state_size);
2610 else if (!ready_try [i])
2612 tries_num++;
2613 if (tries_num > max_lookahead_tries)
2614 break;
2615 insn = ready_element (ready, i);
2616 delay = state_transition (state, insn);
2617 if (delay < 0)
2619 if (state_dead_lock_p (state)
2620 || insn_finishes_cycle_p (insn))
2621 /* We won't issue any more instructions in the next
2622 choice_state. */
2623 top->rest = 0;
2624 else
2625 top->rest--;
2627 n = top->n;
2628 if (memcmp (top->state, state, dfa_state_size) != 0)
2629 n++;
2631 /* Advance to the next choice_entry. */
2632 top++;
2633 /* Initialize it. */
2634 top->rest = dfa_lookahead;
2635 top->index = i;
2636 top->n = n;
2637 memcpy (top->state, state, dfa_state_size);
2638 ready_try [i] = 1;
2640 if (targetm.sched.first_cycle_multipass_issue)
2641 targetm.sched.first_cycle_multipass_issue (&top->target_data,
2642 ready_try, n_ready,
2643 insn,
2644 &((top - 1)
2645 ->target_data));
2647 i = -1;
2651 /* Increase ready-list index. */
2652 i++;
2655 if (targetm.sched.first_cycle_multipass_end)
2656 targetm.sched.first_cycle_multipass_end (best != 0
2657 ? &choice_stack[1].target_data
2658 : NULL);
2660 /* Restore the original state of the DFA. */
2661 memcpy (state, choice_stack->state, dfa_state_size);
2663 return best;
2666 /* The following function chooses insn from READY and modifies
2667 READY. The following function is used only for first
2668 cycle multipass scheduling.
2669 Return:
2670 -1 if cycle should be advanced,
2671 0 if INSN_PTR is set to point to the desirable insn,
2672 1 if choose_ready () should be restarted without advancing the cycle. */
2673 static int
2674 choose_ready (struct ready_list *ready, bool first_cycle_insn_p,
2675 rtx *insn_ptr)
2677 int lookahead;
2679 if (dbg_cnt (sched_insn) == false)
2681 rtx insn = nonscheduled_insns_begin;
2684 insn = next_nonnote_insn (insn);
2686 while (QUEUE_INDEX (insn) == QUEUE_SCHEDULED);
2688 if (QUEUE_INDEX (insn) == QUEUE_READY)
2689 /* INSN is in the ready_list. */
2691 nonscheduled_insns_begin = insn;
2692 ready_remove_insn (insn);
2693 *insn_ptr = insn;
2694 return 0;
2697 /* INSN is in the queue. Advance cycle to move it to the ready list. */
2698 return -1;
2701 lookahead = 0;
2703 if (targetm.sched.first_cycle_multipass_dfa_lookahead)
2704 lookahead = targetm.sched.first_cycle_multipass_dfa_lookahead ();
2705 if (lookahead <= 0 || SCHED_GROUP_P (ready_element (ready, 0))
2706 || DEBUG_INSN_P (ready_element (ready, 0)))
2708 if (targetm.sched.dispatch (NULL_RTX, IS_DISPATCH_ON))
2709 *insn_ptr = ready_remove_first_dispatch (ready);
2710 else
2711 *insn_ptr = ready_remove_first (ready);
2713 return 0;
2715 else
2717 /* Try to choose the better insn. */
2718 int index = 0, i, n;
2719 rtx insn;
2720 int try_data = 1, try_control = 1;
2721 ds_t ts;
2723 insn = ready_element (ready, 0);
2724 if (INSN_CODE (insn) < 0)
2726 *insn_ptr = ready_remove_first (ready);
2727 return 0;
2730 if (spec_info
2731 && spec_info->flags & (PREFER_NON_DATA_SPEC
2732 | PREFER_NON_CONTROL_SPEC))
2734 for (i = 0, n = ready->n_ready; i < n; i++)
2736 rtx x;
2737 ds_t s;
2739 x = ready_element (ready, i);
2740 s = TODO_SPEC (x);
2742 if (spec_info->flags & PREFER_NON_DATA_SPEC
2743 && !(s & DATA_SPEC))
2745 try_data = 0;
2746 if (!(spec_info->flags & PREFER_NON_CONTROL_SPEC)
2747 || !try_control)
2748 break;
2751 if (spec_info->flags & PREFER_NON_CONTROL_SPEC
2752 && !(s & CONTROL_SPEC))
2754 try_control = 0;
2755 if (!(spec_info->flags & PREFER_NON_DATA_SPEC) || !try_data)
2756 break;
2761 ts = TODO_SPEC (insn);
2762 if ((ts & SPECULATIVE)
2763 && (((!try_data && (ts & DATA_SPEC))
2764 || (!try_control && (ts & CONTROL_SPEC)))
2765 || (targetm.sched.first_cycle_multipass_dfa_lookahead_guard_spec
2766 && !targetm.sched
2767 .first_cycle_multipass_dfa_lookahead_guard_spec (insn))))
2768 /* Discard speculative instruction that stands first in the ready
2769 list. */
2771 change_queue_index (insn, 1);
2772 return 1;
2775 ready_try[0] = 0;
2777 for (i = 1; i < ready->n_ready; i++)
2779 insn = ready_element (ready, i);
2781 ready_try [i]
2782 = ((!try_data && (TODO_SPEC (insn) & DATA_SPEC))
2783 || (!try_control && (TODO_SPEC (insn) & CONTROL_SPEC)));
2786 /* Let the target filter the search space. */
2787 for (i = 1; i < ready->n_ready; i++)
2788 if (!ready_try[i])
2790 insn = ready_element (ready, i);
2792 /* If this insn is recognizable we should have already
2793 recognized it earlier.
2794 ??? Not very clear where this is supposed to be done.
2795 See dep_cost_1. */
2796 gcc_checking_assert (INSN_CODE (insn) >= 0
2797 || recog_memoized (insn) < 0);
2799 ready_try [i]
2800 = (/* INSN_CODE check can be omitted here as it is also done later
2801 in max_issue (). */
2802 INSN_CODE (insn) < 0
2803 || (targetm.sched.first_cycle_multipass_dfa_lookahead_guard
2804 && !targetm.sched.first_cycle_multipass_dfa_lookahead_guard
2805 (insn)));
2808 if (max_issue (ready, 1, curr_state, first_cycle_insn_p, &index) == 0)
2810 *insn_ptr = ready_remove_first (ready);
2811 if (sched_verbose >= 4)
2812 fprintf (sched_dump, ";;\t\tChosen insn (but can't issue) : %s \n",
2813 (*current_sched_info->print_insn) (*insn_ptr, 0));
2814 return 0;
2816 else
2818 if (sched_verbose >= 4)
2819 fprintf (sched_dump, ";;\t\tChosen insn : %s\n",
2820 (*current_sched_info->print_insn)
2821 (ready_element (ready, index), 0));
2823 *insn_ptr = ready_remove (ready, index);
2824 return 0;
2829 /* This function is called when we have successfully scheduled a
2830 block. It uses the schedule stored in the scheduled_insns vector
2831 to rearrange the RTL. PREV_HEAD is used as the anchor to which we
2832 append the scheduled insns; TAIL is the insn after the scheduled
2833 block. TARGET_BB is the argument passed to schedule_block. */
2835 static void
2836 commit_schedule (rtx prev_head, rtx tail, basic_block *target_bb)
2838 unsigned int i;
2839 rtx insn;
2841 last_scheduled_insn = prev_head;
2842 for (i = 0;
2843 VEC_iterate (rtx, scheduled_insns, i, insn);
2844 i++)
2846 if (control_flow_insn_p (last_scheduled_insn)
2847 || current_sched_info->advance_target_bb (*target_bb, insn))
2849 *target_bb = current_sched_info->advance_target_bb (*target_bb, 0);
2851 if (sched_verbose)
2853 rtx x;
2855 x = next_real_insn (last_scheduled_insn);
2856 gcc_assert (x);
2857 dump_new_block_header (1, *target_bb, x, tail);
2860 last_scheduled_insn = bb_note (*target_bb);
2863 if (current_sched_info->begin_move_insn)
2864 (*current_sched_info->begin_move_insn) (insn, last_scheduled_insn);
2865 move_insn (insn, last_scheduled_insn,
2866 current_sched_info->next_tail);
2867 if (!DEBUG_INSN_P (insn))
2868 reemit_notes (insn);
2869 last_scheduled_insn = insn;
2872 VEC_truncate (rtx, scheduled_insns, 0);
2875 /* Examine all insns on the ready list and queue those which can't be
2876 issued in this cycle. TEMP_STATE is temporary scheduler state we
2877 can use as scratch space. If FIRST_CYCLE_INSN_P is true, no insns
2878 have been issued for the current cycle, which means it is valid to
2879 issue an asm statement. */
2881 static void
2882 prune_ready_list (state_t temp_state, bool first_cycle_insn_p)
2884 int i;
2886 restart:
2887 for (i = 0; i < ready.n_ready; i++)
2889 rtx insn = ready_element (&ready, i);
2890 int cost = 0;
2891 const char *reason = "resource conflict";
2893 if (recog_memoized (insn) < 0)
2895 if (!first_cycle_insn_p
2896 && (GET_CODE (PATTERN (insn)) == ASM_INPUT
2897 || asm_noperands (PATTERN (insn)) >= 0))
2898 cost = 1;
2899 reason = "asm";
2901 else if (flag_sched_pressure)
2902 cost = 0;
2903 else
2905 memcpy (temp_state, curr_state, dfa_state_size);
2906 cost = state_transition (temp_state, insn);
2907 if (cost < 0)
2908 cost = 0;
2909 else if (cost == 0)
2910 cost = 1;
2912 if (cost >= 1)
2914 ready_remove (&ready, i);
2915 queue_insn (insn, cost, reason);
2916 goto restart;
2921 /* Use forward list scheduling to rearrange insns of block pointed to by
2922 TARGET_BB, possibly bringing insns from subsequent blocks in the same
2923 region. */
2925 void
2926 schedule_block (basic_block *target_bb)
2928 int i;
2929 bool first_cycle_insn_p;
2930 int can_issue_more;
2931 state_t temp_state = NULL; /* It is used for multipass scheduling. */
2932 int sort_p, advance, start_clock_var;
2934 /* Head/tail info for this block. */
2935 rtx prev_head = current_sched_info->prev_head;
2936 rtx next_tail = current_sched_info->next_tail;
2937 rtx head = NEXT_INSN (prev_head);
2938 rtx tail = PREV_INSN (next_tail);
2940 /* We used to have code to avoid getting parameters moved from hard
2941 argument registers into pseudos.
2943 However, it was removed when it proved to be of marginal benefit
2944 and caused problems because schedule_block and compute_forward_dependences
2945 had different notions of what the "head" insn was. */
2947 gcc_assert (head != tail || INSN_P (head));
2949 haifa_recovery_bb_recently_added_p = false;
2951 /* Debug info. */
2952 if (sched_verbose)
2953 dump_new_block_header (0, *target_bb, head, tail);
2955 state_reset (curr_state);
2957 /* Clear the ready list. */
2958 ready.first = ready.veclen - 1;
2959 ready.n_ready = 0;
2960 ready.n_debug = 0;
2962 /* It is used for first cycle multipass scheduling. */
2963 temp_state = alloca (dfa_state_size);
2965 if (targetm.sched.init)
2966 targetm.sched.init (sched_dump, sched_verbose, ready.veclen);
2968 /* We start inserting insns after PREV_HEAD. */
2969 last_scheduled_insn = nonscheduled_insns_begin = prev_head;
2971 gcc_assert ((NOTE_P (last_scheduled_insn)
2972 || DEBUG_INSN_P (last_scheduled_insn))
2973 && BLOCK_FOR_INSN (last_scheduled_insn) == *target_bb);
2975 /* Initialize INSN_QUEUE. Q_SIZE is the total number of insns in the
2976 queue. */
2977 q_ptr = 0;
2978 q_size = 0;
2980 insn_queue = XALLOCAVEC (rtx, max_insn_queue_index + 1);
2981 memset (insn_queue, 0, (max_insn_queue_index + 1) * sizeof (rtx));
2983 /* Start just before the beginning of time. */
2984 clock_var = -1;
2986 /* We need queue and ready lists and clock_var be initialized
2987 in try_ready () (which is called through init_ready_list ()). */
2988 (*current_sched_info->init_ready_list) ();
2990 /* The algorithm is O(n^2) in the number of ready insns at any given
2991 time in the worst case. Before reload we are more likely to have
2992 big lists so truncate them to a reasonable size. */
2993 if (!reload_completed
2994 && ready.n_ready - ready.n_debug > MAX_SCHED_READY_INSNS)
2996 ready_sort (&ready);
2998 /* Find first free-standing insn past MAX_SCHED_READY_INSNS.
2999 If there are debug insns, we know they're first. */
3000 for (i = MAX_SCHED_READY_INSNS + ready.n_debug; i < ready.n_ready; i++)
3001 if (!SCHED_GROUP_P (ready_element (&ready, i)))
3002 break;
3004 if (sched_verbose >= 2)
3006 fprintf (sched_dump,
3007 ";;\t\tReady list on entry: %d insns\n", ready.n_ready);
3008 fprintf (sched_dump,
3009 ";;\t\t before reload => truncated to %d insns\n", i);
3012 /* Delay all insns past it for 1 cycle. If debug counter is
3013 activated make an exception for the insn right after
3014 nonscheduled_insns_begin. */
3016 rtx skip_insn;
3018 if (dbg_cnt (sched_insn) == false)
3019 skip_insn = next_nonnote_insn (nonscheduled_insns_begin);
3020 else
3021 skip_insn = NULL_RTX;
3023 while (i < ready.n_ready)
3025 rtx insn;
3027 insn = ready_remove (&ready, i);
3029 if (insn != skip_insn)
3030 queue_insn (insn, 1, "list truncated");
3032 if (skip_insn)
3033 ready_add (&ready, skip_insn, true);
3037 /* Now we can restore basic block notes and maintain precise cfg. */
3038 restore_bb_notes (*target_bb);
3040 last_clock_var = -1;
3042 advance = 0;
3044 gcc_assert (VEC_length (rtx, scheduled_insns) == 0);
3045 sort_p = TRUE;
3046 /* Loop until all the insns in BB are scheduled. */
3047 while ((*current_sched_info->schedule_more_p) ())
3051 start_clock_var = clock_var;
3053 clock_var++;
3055 advance_one_cycle ();
3057 /* Add to the ready list all pending insns that can be issued now.
3058 If there are no ready insns, increment clock until one
3059 is ready and add all pending insns at that point to the ready
3060 list. */
3061 queue_to_ready (&ready);
3063 gcc_assert (ready.n_ready);
3065 if (sched_verbose >= 2)
3067 fprintf (sched_dump, ";;\t\tReady list after queue_to_ready: ");
3068 debug_ready_list (&ready);
3070 advance -= clock_var - start_clock_var;
3072 while (advance > 0);
3074 prune_ready_list (temp_state, true);
3075 if (ready.n_ready == 0)
3076 continue;
3078 if (sort_p)
3080 /* Sort the ready list based on priority. */
3081 ready_sort (&ready);
3083 if (sched_verbose >= 2)
3085 fprintf (sched_dump, ";;\t\tReady list after ready_sort: ");
3086 debug_ready_list (&ready);
3090 /* We don't want md sched reorder to even see debug isns, so put
3091 them out right away. */
3092 if (ready.n_ready && DEBUG_INSN_P (ready_element (&ready, 0)))
3094 while (ready.n_ready && DEBUG_INSN_P (ready_element (&ready, 0)))
3096 rtx insn = ready_remove_first (&ready);
3097 gcc_assert (DEBUG_INSN_P (insn));
3098 (*current_sched_info->begin_schedule_ready) (insn);
3099 VEC_safe_push (rtx, heap, scheduled_insns, insn);
3100 last_scheduled_insn = insn;
3101 advance = schedule_insn (insn);
3102 gcc_assert (advance == 0);
3103 if (ready.n_ready > 0)
3104 ready_sort (&ready);
3107 if (!ready.n_ready)
3108 continue;
3111 /* Allow the target to reorder the list, typically for
3112 better instruction bundling. */
3113 if (sort_p && targetm.sched.reorder
3114 && (ready.n_ready == 0
3115 || !SCHED_GROUP_P (ready_element (&ready, 0))))
3116 can_issue_more =
3117 targetm.sched.reorder (sched_dump, sched_verbose,
3118 ready_lastpos (&ready),
3119 &ready.n_ready, clock_var);
3120 else
3121 can_issue_more = issue_rate;
3123 first_cycle_insn_p = true;
3124 cycle_issued_insns = 0;
3125 for (;;)
3127 rtx insn;
3128 int cost;
3129 bool asm_p = false;
3131 if (sched_verbose >= 2)
3133 fprintf (sched_dump, ";;\tReady list (t = %3d): ",
3134 clock_var);
3135 debug_ready_list (&ready);
3136 if (sched_pressure_p)
3137 print_curr_reg_pressure ();
3140 if (ready.n_ready == 0
3141 && can_issue_more
3142 && reload_completed)
3144 /* Allow scheduling insns directly from the queue in case
3145 there's nothing better to do (ready list is empty) but
3146 there are still vacant dispatch slots in the current cycle. */
3147 if (sched_verbose >= 6)
3148 fprintf (sched_dump,";;\t\tSecond chance\n");
3149 memcpy (temp_state, curr_state, dfa_state_size);
3150 if (early_queue_to_ready (temp_state, &ready))
3151 ready_sort (&ready);
3154 if (ready.n_ready == 0
3155 || !can_issue_more
3156 || state_dead_lock_p (curr_state)
3157 || !(*current_sched_info->schedule_more_p) ())
3158 break;
3160 /* Select and remove the insn from the ready list. */
3161 if (sort_p)
3163 int res;
3165 insn = NULL_RTX;
3166 res = choose_ready (&ready, first_cycle_insn_p, &insn);
3168 if (res < 0)
3169 /* Finish cycle. */
3170 break;
3171 if (res > 0)
3172 /* Restart choose_ready (). */
3173 continue;
3175 gcc_assert (insn != NULL_RTX);
3177 else
3178 insn = ready_remove_first (&ready);
3180 if (sched_pressure_p && INSN_TICK (insn) > clock_var)
3182 ready_add (&ready, insn, true);
3183 advance = 1;
3184 break;
3187 if (targetm.sched.dfa_new_cycle
3188 && targetm.sched.dfa_new_cycle (sched_dump, sched_verbose,
3189 insn, last_clock_var,
3190 clock_var, &sort_p))
3191 /* SORT_P is used by the target to override sorting
3192 of the ready list. This is needed when the target
3193 has modified its internal structures expecting that
3194 the insn will be issued next. As we need the insn
3195 to have the highest priority (so it will be returned by
3196 the ready_remove_first call above), we invoke
3197 ready_add (&ready, insn, true).
3198 But, still, there is one issue: INSN can be later
3199 discarded by scheduler's front end through
3200 current_sched_info->can_schedule_ready_p, hence, won't
3201 be issued next. */
3203 ready_add (&ready, insn, true);
3204 break;
3207 sort_p = TRUE;
3209 if (current_sched_info->can_schedule_ready_p
3210 && ! (*current_sched_info->can_schedule_ready_p) (insn))
3211 /* We normally get here only if we don't want to move
3212 insn from the split block. */
3214 TODO_SPEC (insn) = (TODO_SPEC (insn) & ~SPECULATIVE) | HARD_DEP;
3215 continue;
3218 /* DECISION is made. */
3220 if (TODO_SPEC (insn) & SPECULATIVE)
3221 generate_recovery_code (insn);
3223 if (targetm.sched.dispatch (NULL_RTX, IS_DISPATCH_ON))
3224 targetm.sched.dispatch_do (insn, ADD_TO_DISPATCH_WINDOW);
3226 /* Update counters, etc in the scheduler's front end. */
3227 (*current_sched_info->begin_schedule_ready) (insn);
3228 VEC_safe_push (rtx, heap, scheduled_insns, insn);
3229 last_scheduled_insn = insn;
3231 if (recog_memoized (insn) >= 0)
3233 memcpy (temp_state, curr_state, dfa_state_size);
3234 cost = state_transition (curr_state, insn);
3235 if (!flag_sched_pressure)
3236 gcc_assert (cost < 0);
3237 if (memcmp (temp_state, curr_state, dfa_state_size) != 0)
3238 cycle_issued_insns++;
3239 asm_p = false;
3241 else
3242 asm_p = (GET_CODE (PATTERN (insn)) == ASM_INPUT
3243 || asm_noperands (PATTERN (insn)) >= 0);
3245 if (targetm.sched.variable_issue)
3246 can_issue_more =
3247 targetm.sched.variable_issue (sched_dump, sched_verbose,
3248 insn, can_issue_more);
3249 /* A naked CLOBBER or USE generates no instruction, so do
3250 not count them against the issue rate. */
3251 else if (GET_CODE (PATTERN (insn)) != USE
3252 && GET_CODE (PATTERN (insn)) != CLOBBER)
3253 can_issue_more--;
3254 advance = schedule_insn (insn);
3256 /* After issuing an asm insn we should start a new cycle. */
3257 if (advance == 0 && asm_p)
3258 advance = 1;
3259 if (advance != 0)
3260 break;
3262 first_cycle_insn_p = false;
3264 if (ready.n_ready > 0)
3265 prune_ready_list (temp_state, false);
3267 /* Sort the ready list based on priority. This must be
3268 redone here, as schedule_insn may have readied additional
3269 insns that will not be sorted correctly. */
3270 if (ready.n_ready > 0)
3271 ready_sort (&ready);
3273 /* Quickly go through debug insns such that md sched
3274 reorder2 doesn't have to deal with debug insns. */
3275 if (ready.n_ready && DEBUG_INSN_P (ready_element (&ready, 0))
3276 && (*current_sched_info->schedule_more_p) ())
3278 while (ready.n_ready && DEBUG_INSN_P (ready_element (&ready, 0)))
3280 insn = ready_remove_first (&ready);
3281 gcc_assert (DEBUG_INSN_P (insn));
3282 (*current_sched_info->begin_schedule_ready) (insn);
3283 VEC_safe_push (rtx, heap, scheduled_insns, insn);
3284 advance = schedule_insn (insn);
3285 last_scheduled_insn = insn;
3286 gcc_assert (advance == 0);
3287 if (ready.n_ready > 0)
3288 ready_sort (&ready);
3292 if (targetm.sched.reorder2
3293 && (ready.n_ready == 0
3294 || !SCHED_GROUP_P (ready_element (&ready, 0))))
3296 can_issue_more =
3297 targetm.sched.reorder2 (sched_dump, sched_verbose,
3298 ready.n_ready
3299 ? ready_lastpos (&ready) : NULL,
3300 &ready.n_ready, clock_var);
3305 /* Debug info. */
3306 if (sched_verbose)
3308 fprintf (sched_dump, ";;\tReady list (final): ");
3309 debug_ready_list (&ready);
3312 if (current_sched_info->queue_must_finish_empty)
3313 /* Sanity check -- queue must be empty now. Meaningless if region has
3314 multiple bbs. */
3315 gcc_assert (!q_size && !ready.n_ready && !ready.n_debug);
3316 else
3318 /* We must maintain QUEUE_INDEX between blocks in region. */
3319 for (i = ready.n_ready - 1; i >= 0; i--)
3321 rtx x;
3323 x = ready_element (&ready, i);
3324 QUEUE_INDEX (x) = QUEUE_NOWHERE;
3325 TODO_SPEC (x) = (TODO_SPEC (x) & ~SPECULATIVE) | HARD_DEP;
3328 if (q_size)
3329 for (i = 0; i <= max_insn_queue_index; i++)
3331 rtx link;
3332 for (link = insn_queue[i]; link; link = XEXP (link, 1))
3334 rtx x;
3336 x = XEXP (link, 0);
3337 QUEUE_INDEX (x) = QUEUE_NOWHERE;
3338 TODO_SPEC (x) = (TODO_SPEC (x) & ~SPECULATIVE) | HARD_DEP;
3340 free_INSN_LIST_list (&insn_queue[i]);
3344 commit_schedule (prev_head, tail, target_bb);
3345 if (sched_verbose)
3346 fprintf (sched_dump, ";; total time = %d\n", clock_var);
3348 if (!current_sched_info->queue_must_finish_empty
3349 || haifa_recovery_bb_recently_added_p)
3351 /* INSN_TICK (minimum clock tick at which the insn becomes
3352 ready) may be not correct for the insn in the subsequent
3353 blocks of the region. We should use a correct value of
3354 `clock_var' or modify INSN_TICK. It is better to keep
3355 clock_var value equal to 0 at the start of a basic block.
3356 Therefore we modify INSN_TICK here. */
3357 fix_inter_tick (NEXT_INSN (prev_head), last_scheduled_insn);
3360 if (targetm.sched.finish)
3362 targetm.sched.finish (sched_dump, sched_verbose);
3363 /* Target might have added some instructions to the scheduled block
3364 in its md_finish () hook. These new insns don't have any data
3365 initialized and to identify them we extend h_i_d so that they'll
3366 get zero luids. */
3367 sched_init_luids (NULL, NULL, NULL, NULL);
3370 if (sched_verbose)
3371 fprintf (sched_dump, ";; new head = %d\n;; new tail = %d\n\n",
3372 INSN_UID (head), INSN_UID (tail));
3374 /* Update head/tail boundaries. */
3375 head = NEXT_INSN (prev_head);
3376 tail = last_scheduled_insn;
3378 head = restore_other_notes (head, NULL);
3380 current_sched_info->head = head;
3381 current_sched_info->tail = tail;
3384 /* Set_priorities: compute priority of each insn in the block. */
3387 set_priorities (rtx head, rtx tail)
3389 rtx insn;
3390 int n_insn;
3391 int sched_max_insns_priority =
3392 current_sched_info->sched_max_insns_priority;
3393 rtx prev_head;
3395 if (head == tail && ! INSN_P (head))
3396 gcc_unreachable ();
3398 n_insn = 0;
3400 prev_head = PREV_INSN (head);
3401 for (insn = tail; insn != prev_head; insn = PREV_INSN (insn))
3403 if (!INSN_P (insn))
3404 continue;
3406 n_insn++;
3407 (void) priority (insn);
3409 gcc_assert (INSN_PRIORITY_KNOWN (insn));
3411 sched_max_insns_priority = MAX (sched_max_insns_priority,
3412 INSN_PRIORITY (insn));
3415 current_sched_info->sched_max_insns_priority = sched_max_insns_priority;
3417 return n_insn;
3420 /* Set dump and sched_verbose for the desired debugging output. If no
3421 dump-file was specified, but -fsched-verbose=N (any N), print to stderr.
3422 For -fsched-verbose=N, N>=10, print everything to stderr. */
3423 void
3424 setup_sched_dump (void)
3426 sched_verbose = sched_verbose_param;
3427 if (sched_verbose_param == 0 && dump_file)
3428 sched_verbose = 1;
3429 sched_dump = ((sched_verbose_param >= 10 || !dump_file)
3430 ? stderr : dump_file);
3433 /* Initialize some global state for the scheduler. This function works
3434 with the common data shared between all the schedulers. It is called
3435 from the scheduler specific initialization routine. */
3437 void
3438 sched_init (void)
3440 /* Disable speculative loads in their presence if cc0 defined. */
3441 #ifdef HAVE_cc0
3442 flag_schedule_speculative_load = 0;
3443 #endif
3445 if (targetm.sched.dispatch (NULL_RTX, IS_DISPATCH_ON))
3446 targetm.sched.dispatch_do (NULL_RTX, DISPATCH_INIT);
3448 sched_pressure_p = (flag_sched_pressure && ! reload_completed
3449 && common_sched_info->sched_pass_id == SCHED_RGN_PASS);
3451 if (sched_pressure_p)
3452 ira_setup_eliminable_regset ();
3454 /* Initialize SPEC_INFO. */
3455 if (targetm.sched.set_sched_flags)
3457 spec_info = &spec_info_var;
3458 targetm.sched.set_sched_flags (spec_info);
3460 if (spec_info->mask != 0)
3462 spec_info->data_weakness_cutoff =
3463 (PARAM_VALUE (PARAM_SCHED_SPEC_PROB_CUTOFF) * MAX_DEP_WEAK) / 100;
3464 spec_info->control_weakness_cutoff =
3465 (PARAM_VALUE (PARAM_SCHED_SPEC_PROB_CUTOFF)
3466 * REG_BR_PROB_BASE) / 100;
3468 else
3469 /* So we won't read anything accidentally. */
3470 spec_info = NULL;
3473 else
3474 /* So we won't read anything accidentally. */
3475 spec_info = 0;
3477 /* Initialize issue_rate. */
3478 if (targetm.sched.issue_rate)
3479 issue_rate = targetm.sched.issue_rate ();
3480 else
3481 issue_rate = 1;
3483 if (cached_issue_rate != issue_rate)
3485 cached_issue_rate = issue_rate;
3486 /* To invalidate max_lookahead_tries: */
3487 cached_first_cycle_multipass_dfa_lookahead = 0;
3490 if (targetm.sched.first_cycle_multipass_dfa_lookahead)
3491 dfa_lookahead = targetm.sched.first_cycle_multipass_dfa_lookahead ();
3492 else
3493 dfa_lookahead = 0;
3495 if (targetm.sched.init_dfa_pre_cycle_insn)
3496 targetm.sched.init_dfa_pre_cycle_insn ();
3498 if (targetm.sched.init_dfa_post_cycle_insn)
3499 targetm.sched.init_dfa_post_cycle_insn ();
3501 dfa_start ();
3502 dfa_state_size = state_size ();
3504 init_alias_analysis ();
3506 df_set_flags (DF_LR_RUN_DCE);
3507 df_note_add_problem ();
3509 /* More problems needed for interloop dep calculation in SMS. */
3510 if (common_sched_info->sched_pass_id == SCHED_SMS_PASS)
3512 df_rd_add_problem ();
3513 df_chain_add_problem (DF_DU_CHAIN + DF_UD_CHAIN);
3516 df_analyze ();
3518 /* Do not run DCE after reload, as this can kill nops inserted
3519 by bundling. */
3520 if (reload_completed)
3521 df_clear_flags (DF_LR_RUN_DCE);
3523 regstat_compute_calls_crossed ();
3525 if (targetm.sched.init_global)
3526 targetm.sched.init_global (sched_dump, sched_verbose, get_max_uid () + 1);
3528 if (sched_pressure_p)
3530 int i, max_regno = max_reg_num ();
3532 ira_set_pseudo_classes (sched_verbose ? sched_dump : NULL);
3533 sched_regno_pressure_class
3534 = (enum reg_class *) xmalloc (max_regno * sizeof (enum reg_class));
3535 for (i = 0; i < max_regno; i++)
3536 sched_regno_pressure_class[i]
3537 = (i < FIRST_PSEUDO_REGISTER
3538 ? ira_pressure_class_translate[REGNO_REG_CLASS (i)]
3539 : ira_pressure_class_translate[reg_allocno_class (i)]);
3540 curr_reg_live = BITMAP_ALLOC (NULL);
3541 saved_reg_live = BITMAP_ALLOC (NULL);
3542 region_ref_regs = BITMAP_ALLOC (NULL);
3545 curr_state = xmalloc (dfa_state_size);
3548 static void haifa_init_only_bb (basic_block, basic_block);
3550 /* Initialize data structures specific to the Haifa scheduler. */
3551 void
3552 haifa_sched_init (void)
3554 setup_sched_dump ();
3555 sched_init ();
3557 scheduled_insns = VEC_alloc (rtx, heap, 0);
3559 if (spec_info != NULL)
3561 sched_deps_info->use_deps_list = 1;
3562 sched_deps_info->generate_spec_deps = 1;
3565 /* Initialize luids, dependency caches, target and h_i_d for the
3566 whole function. */
3568 bb_vec_t bbs = VEC_alloc (basic_block, heap, n_basic_blocks);
3569 basic_block bb;
3571 sched_init_bbs ();
3573 FOR_EACH_BB (bb)
3574 VEC_quick_push (basic_block, bbs, bb);
3575 sched_init_luids (bbs, NULL, NULL, NULL);
3576 sched_deps_init (true);
3577 sched_extend_target ();
3578 haifa_init_h_i_d (bbs, NULL, NULL, NULL);
3580 VEC_free (basic_block, heap, bbs);
3583 sched_init_only_bb = haifa_init_only_bb;
3584 sched_split_block = sched_split_block_1;
3585 sched_create_empty_bb = sched_create_empty_bb_1;
3586 haifa_recovery_bb_ever_added_p = false;
3588 #ifdef ENABLE_CHECKING
3589 /* This is used preferably for finding bugs in check_cfg () itself.
3590 We must call sched_bbs_init () before check_cfg () because check_cfg ()
3591 assumes that the last insn in the last bb has a non-null successor. */
3592 check_cfg (0, 0);
3593 #endif
3595 nr_begin_data = nr_begin_control = nr_be_in_data = nr_be_in_control = 0;
3596 before_recovery = 0;
3597 after_recovery = 0;
3600 /* Finish work with the data specific to the Haifa scheduler. */
3601 void
3602 haifa_sched_finish (void)
3604 sched_create_empty_bb = NULL;
3605 sched_split_block = NULL;
3606 sched_init_only_bb = NULL;
3608 if (spec_info && spec_info->dump)
3610 char c = reload_completed ? 'a' : 'b';
3612 fprintf (spec_info->dump,
3613 ";; %s:\n", current_function_name ());
3615 fprintf (spec_info->dump,
3616 ";; Procedure %cr-begin-data-spec motions == %d\n",
3617 c, nr_begin_data);
3618 fprintf (spec_info->dump,
3619 ";; Procedure %cr-be-in-data-spec motions == %d\n",
3620 c, nr_be_in_data);
3621 fprintf (spec_info->dump,
3622 ";; Procedure %cr-begin-control-spec motions == %d\n",
3623 c, nr_begin_control);
3624 fprintf (spec_info->dump,
3625 ";; Procedure %cr-be-in-control-spec motions == %d\n",
3626 c, nr_be_in_control);
3629 VEC_free (rtx, heap, scheduled_insns);
3631 /* Finalize h_i_d, dependency caches, and luids for the whole
3632 function. Target will be finalized in md_global_finish (). */
3633 sched_deps_finish ();
3634 sched_finish_luids ();
3635 current_sched_info = NULL;
3636 sched_finish ();
3639 /* Free global data used during insn scheduling. This function works with
3640 the common data shared between the schedulers. */
3642 void
3643 sched_finish (void)
3645 haifa_finish_h_i_d ();
3646 if (sched_pressure_p)
3648 free (sched_regno_pressure_class);
3649 BITMAP_FREE (region_ref_regs);
3650 BITMAP_FREE (saved_reg_live);
3651 BITMAP_FREE (curr_reg_live);
3653 free (curr_state);
3655 if (targetm.sched.finish_global)
3656 targetm.sched.finish_global (sched_dump, sched_verbose);
3658 end_alias_analysis ();
3660 regstat_free_calls_crossed ();
3662 dfa_finish ();
3664 #ifdef ENABLE_CHECKING
3665 /* After reload ia64 backend clobbers CFG, so can't check anything. */
3666 if (!reload_completed)
3667 check_cfg (0, 0);
3668 #endif
3671 /* Fix INSN_TICKs of the instructions in the current block as well as
3672 INSN_TICKs of their dependents.
3673 HEAD and TAIL are the begin and the end of the current scheduled block. */
3674 static void
3675 fix_inter_tick (rtx head, rtx tail)
3677 /* Set of instructions with corrected INSN_TICK. */
3678 bitmap_head processed;
3679 /* ??? It is doubtful if we should assume that cycle advance happens on
3680 basic block boundaries. Basically insns that are unconditionally ready
3681 on the start of the block are more preferable then those which have
3682 a one cycle dependency over insn from the previous block. */
3683 int next_clock = clock_var + 1;
3685 bitmap_initialize (&processed, 0);
3687 /* Iterates over scheduled instructions and fix their INSN_TICKs and
3688 INSN_TICKs of dependent instructions, so that INSN_TICKs are consistent
3689 across different blocks. */
3690 for (tail = NEXT_INSN (tail); head != tail; head = NEXT_INSN (head))
3692 if (INSN_P (head))
3694 int tick;
3695 sd_iterator_def sd_it;
3696 dep_t dep;
3698 tick = INSN_TICK (head);
3699 gcc_assert (tick >= MIN_TICK);
3701 /* Fix INSN_TICK of instruction from just scheduled block. */
3702 if (bitmap_set_bit (&processed, INSN_LUID (head)))
3704 tick -= next_clock;
3706 if (tick < MIN_TICK)
3707 tick = MIN_TICK;
3709 INSN_TICK (head) = tick;
3712 FOR_EACH_DEP (head, SD_LIST_RES_FORW, sd_it, dep)
3714 rtx next;
3716 next = DEP_CON (dep);
3717 tick = INSN_TICK (next);
3719 if (tick != INVALID_TICK
3720 /* If NEXT has its INSN_TICK calculated, fix it.
3721 If not - it will be properly calculated from
3722 scratch later in fix_tick_ready. */
3723 && bitmap_set_bit (&processed, INSN_LUID (next)))
3725 tick -= next_clock;
3727 if (tick < MIN_TICK)
3728 tick = MIN_TICK;
3730 if (tick > INTER_TICK (next))
3731 INTER_TICK (next) = tick;
3732 else
3733 tick = INTER_TICK (next);
3735 INSN_TICK (next) = tick;
3740 bitmap_clear (&processed);
3743 static int haifa_speculate_insn (rtx, ds_t, rtx *);
3745 /* Check if NEXT is ready to be added to the ready or queue list.
3746 If "yes", add it to the proper list.
3747 Returns:
3748 -1 - is not ready yet,
3749 0 - added to the ready list,
3750 0 < N - queued for N cycles. */
3752 try_ready (rtx next)
3754 ds_t old_ts, *ts;
3756 ts = &TODO_SPEC (next);
3757 old_ts = *ts;
3759 gcc_assert (!(old_ts & ~(SPECULATIVE | HARD_DEP))
3760 && ((old_ts & HARD_DEP)
3761 || (old_ts & SPECULATIVE)));
3763 if (sd_lists_empty_p (next, SD_LIST_BACK))
3764 /* NEXT has all its dependencies resolved. */
3766 /* Remove HARD_DEP bit from NEXT's status. */
3767 *ts &= ~HARD_DEP;
3769 if (current_sched_info->flags & DO_SPECULATION)
3770 /* Remove all speculative bits from NEXT's status. */
3771 *ts &= ~SPECULATIVE;
3773 else
3775 /* One of the NEXT's dependencies has been resolved.
3776 Recalculate NEXT's status. */
3778 *ts &= ~SPECULATIVE & ~HARD_DEP;
3780 if (sd_lists_empty_p (next, SD_LIST_HARD_BACK))
3781 /* Now we've got NEXT with speculative deps only.
3782 1. Look at the deps to see what we have to do.
3783 2. Check if we can do 'todo'. */
3785 sd_iterator_def sd_it;
3786 dep_t dep;
3787 bool first_p = true;
3789 FOR_EACH_DEP (next, SD_LIST_BACK, sd_it, dep)
3791 ds_t ds = DEP_STATUS (dep) & SPECULATIVE;
3793 if (DEBUG_INSN_P (DEP_PRO (dep))
3794 && !DEBUG_INSN_P (next))
3795 continue;
3797 if (first_p)
3799 first_p = false;
3801 *ts = ds;
3803 else
3804 *ts = ds_merge (*ts, ds);
3807 if (ds_weak (*ts) < spec_info->data_weakness_cutoff)
3808 /* Too few points. */
3809 *ts = (*ts & ~SPECULATIVE) | HARD_DEP;
3811 else
3812 *ts |= HARD_DEP;
3815 if (*ts & HARD_DEP)
3816 gcc_assert (*ts == old_ts
3817 && QUEUE_INDEX (next) == QUEUE_NOWHERE);
3818 else if (current_sched_info->new_ready)
3819 *ts = current_sched_info->new_ready (next, *ts);
3821 /* * if !(old_ts & SPECULATIVE) (e.g. HARD_DEP or 0), then insn might
3822 have its original pattern or changed (speculative) one. This is due
3823 to changing ebb in region scheduling.
3824 * But if (old_ts & SPECULATIVE), then we are pretty sure that insn
3825 has speculative pattern.
3827 We can't assert (!(*ts & HARD_DEP) || *ts == old_ts) here because
3828 control-speculative NEXT could have been discarded by sched-rgn.c
3829 (the same case as when discarded by can_schedule_ready_p ()). */
3831 if ((*ts & SPECULATIVE)
3832 /* If (old_ts == *ts), then (old_ts & SPECULATIVE) and we don't
3833 need to change anything. */
3834 && *ts != old_ts)
3836 int res;
3837 rtx new_pat;
3839 gcc_assert ((*ts & SPECULATIVE) && !(*ts & ~SPECULATIVE));
3841 res = haifa_speculate_insn (next, *ts, &new_pat);
3843 switch (res)
3845 case -1:
3846 /* It would be nice to change DEP_STATUS of all dependences,
3847 which have ((DEP_STATUS & SPECULATIVE) == *ts) to HARD_DEP,
3848 so we won't reanalyze anything. */
3849 *ts = (*ts & ~SPECULATIVE) | HARD_DEP;
3850 break;
3852 case 0:
3853 /* We follow the rule, that every speculative insn
3854 has non-null ORIG_PAT. */
3855 if (!ORIG_PAT (next))
3856 ORIG_PAT (next) = PATTERN (next);
3857 break;
3859 case 1:
3860 if (!ORIG_PAT (next))
3861 /* If we gonna to overwrite the original pattern of insn,
3862 save it. */
3863 ORIG_PAT (next) = PATTERN (next);
3865 haifa_change_pattern (next, new_pat);
3866 break;
3868 default:
3869 gcc_unreachable ();
3873 /* We need to restore pattern only if (*ts == 0), because otherwise it is
3874 either correct (*ts & SPECULATIVE),
3875 or we simply don't care (*ts & HARD_DEP). */
3877 gcc_assert (!ORIG_PAT (next)
3878 || !IS_SPECULATION_BRANCHY_CHECK_P (next));
3880 if (*ts & HARD_DEP)
3882 /* We can't assert (QUEUE_INDEX (next) == QUEUE_NOWHERE) here because
3883 control-speculative NEXT could have been discarded by sched-rgn.c
3884 (the same case as when discarded by can_schedule_ready_p ()). */
3885 /*gcc_assert (QUEUE_INDEX (next) == QUEUE_NOWHERE);*/
3887 change_queue_index (next, QUEUE_NOWHERE);
3888 return -1;
3890 else if (!(*ts & BEGIN_SPEC) && ORIG_PAT (next) && !IS_SPECULATION_CHECK_P (next))
3891 /* We should change pattern of every previously speculative
3892 instruction - and we determine if NEXT was speculative by using
3893 ORIG_PAT field. Except one case - speculation checks have ORIG_PAT
3894 pat too, so skip them. */
3896 haifa_change_pattern (next, ORIG_PAT (next));
3897 ORIG_PAT (next) = 0;
3900 if (sched_verbose >= 2)
3902 int s = TODO_SPEC (next);
3904 fprintf (sched_dump, ";;\t\tdependencies resolved: insn %s",
3905 (*current_sched_info->print_insn) (next, 0));
3907 if (spec_info && spec_info->dump)
3909 if (s & BEGIN_DATA)
3910 fprintf (spec_info->dump, "; data-spec;");
3911 if (s & BEGIN_CONTROL)
3912 fprintf (spec_info->dump, "; control-spec;");
3913 if (s & BE_IN_CONTROL)
3914 fprintf (spec_info->dump, "; in-control-spec;");
3917 fprintf (sched_dump, "\n");
3920 adjust_priority (next);
3922 return fix_tick_ready (next);
3925 /* Calculate INSN_TICK of NEXT and add it to either ready or queue list. */
3926 static int
3927 fix_tick_ready (rtx next)
3929 int tick, delay;
3931 if (!DEBUG_INSN_P (next) && !sd_lists_empty_p (next, SD_LIST_RES_BACK))
3933 int full_p;
3934 sd_iterator_def sd_it;
3935 dep_t dep;
3937 tick = INSN_TICK (next);
3938 /* if tick is not equal to INVALID_TICK, then update
3939 INSN_TICK of NEXT with the most recent resolved dependence
3940 cost. Otherwise, recalculate from scratch. */
3941 full_p = (tick == INVALID_TICK);
3943 FOR_EACH_DEP (next, SD_LIST_RES_BACK, sd_it, dep)
3945 rtx pro = DEP_PRO (dep);
3946 int tick1;
3948 gcc_assert (INSN_TICK (pro) >= MIN_TICK);
3950 tick1 = INSN_TICK (pro) + dep_cost (dep);
3951 if (tick1 > tick)
3952 tick = tick1;
3954 if (!full_p)
3955 break;
3958 else
3959 tick = -1;
3961 INSN_TICK (next) = tick;
3963 delay = tick - clock_var;
3964 if (delay <= 0 || sched_pressure_p)
3965 delay = QUEUE_READY;
3967 change_queue_index (next, delay);
3969 return delay;
3972 /* Move NEXT to the proper queue list with (DELAY >= 1),
3973 or add it to the ready list (DELAY == QUEUE_READY),
3974 or remove it from ready and queue lists at all (DELAY == QUEUE_NOWHERE). */
3975 static void
3976 change_queue_index (rtx next, int delay)
3978 int i = QUEUE_INDEX (next);
3980 gcc_assert (QUEUE_NOWHERE <= delay && delay <= max_insn_queue_index
3981 && delay != 0);
3982 gcc_assert (i != QUEUE_SCHEDULED);
3984 if ((delay > 0 && NEXT_Q_AFTER (q_ptr, delay) == i)
3985 || (delay < 0 && delay == i))
3986 /* We have nothing to do. */
3987 return;
3989 /* Remove NEXT from wherever it is now. */
3990 if (i == QUEUE_READY)
3991 ready_remove_insn (next);
3992 else if (i >= 0)
3993 queue_remove (next);
3995 /* Add it to the proper place. */
3996 if (delay == QUEUE_READY)
3997 ready_add (readyp, next, false);
3998 else if (delay >= 1)
3999 queue_insn (next, delay, "change queue index");
4001 if (sched_verbose >= 2)
4003 fprintf (sched_dump, ";;\t\ttick updated: insn %s",
4004 (*current_sched_info->print_insn) (next, 0));
4006 if (delay == QUEUE_READY)
4007 fprintf (sched_dump, " into ready\n");
4008 else if (delay >= 1)
4009 fprintf (sched_dump, " into queue with cost=%d\n", delay);
4010 else
4011 fprintf (sched_dump, " removed from ready or queue lists\n");
4015 static int sched_ready_n_insns = -1;
4017 /* Initialize per region data structures. */
4018 void
4019 sched_extend_ready_list (int new_sched_ready_n_insns)
4021 int i;
4023 if (sched_ready_n_insns == -1)
4024 /* At the first call we need to initialize one more choice_stack
4025 entry. */
4027 i = 0;
4028 sched_ready_n_insns = 0;
4029 VEC_reserve (rtx, heap, scheduled_insns, new_sched_ready_n_insns);
4031 else
4032 i = sched_ready_n_insns + 1;
4034 ready.veclen = new_sched_ready_n_insns + issue_rate;
4035 ready.vec = XRESIZEVEC (rtx, ready.vec, ready.veclen);
4037 gcc_assert (new_sched_ready_n_insns >= sched_ready_n_insns);
4039 ready_try = (char *) xrecalloc (ready_try, new_sched_ready_n_insns,
4040 sched_ready_n_insns, sizeof (*ready_try));
4042 /* We allocate +1 element to save initial state in the choice_stack[0]
4043 entry. */
4044 choice_stack = XRESIZEVEC (struct choice_entry, choice_stack,
4045 new_sched_ready_n_insns + 1);
4047 for (; i <= new_sched_ready_n_insns; i++)
4049 choice_stack[i].state = xmalloc (dfa_state_size);
4051 if (targetm.sched.first_cycle_multipass_init)
4052 targetm.sched.first_cycle_multipass_init (&(choice_stack[i]
4053 .target_data));
4056 sched_ready_n_insns = new_sched_ready_n_insns;
4059 /* Free per region data structures. */
4060 void
4061 sched_finish_ready_list (void)
4063 int i;
4065 free (ready.vec);
4066 ready.vec = NULL;
4067 ready.veclen = 0;
4069 free (ready_try);
4070 ready_try = NULL;
4072 for (i = 0; i <= sched_ready_n_insns; i++)
4074 if (targetm.sched.first_cycle_multipass_fini)
4075 targetm.sched.first_cycle_multipass_fini (&(choice_stack[i]
4076 .target_data));
4078 free (choice_stack [i].state);
4080 free (choice_stack);
4081 choice_stack = NULL;
4083 sched_ready_n_insns = -1;
4086 static int
4087 haifa_luid_for_non_insn (rtx x)
4089 gcc_assert (NOTE_P (x) || LABEL_P (x));
4091 return 0;
4094 /* Generates recovery code for INSN. */
4095 static void
4096 generate_recovery_code (rtx insn)
4098 if (TODO_SPEC (insn) & BEGIN_SPEC)
4099 begin_speculative_block (insn);
4101 /* Here we have insn with no dependencies to
4102 instructions other then CHECK_SPEC ones. */
4104 if (TODO_SPEC (insn) & BE_IN_SPEC)
4105 add_to_speculative_block (insn);
4108 /* Helper function.
4109 Tries to add speculative dependencies of type FS between instructions
4110 in deps_list L and TWIN. */
4111 static void
4112 process_insn_forw_deps_be_in_spec (rtx insn, rtx twin, ds_t fs)
4114 sd_iterator_def sd_it;
4115 dep_t dep;
4117 FOR_EACH_DEP (insn, SD_LIST_FORW, sd_it, dep)
4119 ds_t ds;
4120 rtx consumer;
4122 consumer = DEP_CON (dep);
4124 ds = DEP_STATUS (dep);
4126 if (/* If we want to create speculative dep. */
4128 /* And we can do that because this is a true dep. */
4129 && (ds & DEP_TYPES) == DEP_TRUE)
4131 gcc_assert (!(ds & BE_IN_SPEC));
4133 if (/* If this dep can be overcome with 'begin speculation'. */
4134 ds & BEGIN_SPEC)
4135 /* Then we have a choice: keep the dep 'begin speculative'
4136 or transform it into 'be in speculative'. */
4138 if (/* In try_ready we assert that if insn once became ready
4139 it can be removed from the ready (or queue) list only
4140 due to backend decision. Hence we can't let the
4141 probability of the speculative dep to decrease. */
4142 ds_weak (ds) <= ds_weak (fs))
4144 ds_t new_ds;
4146 new_ds = (ds & ~BEGIN_SPEC) | fs;
4148 if (/* consumer can 'be in speculative'. */
4149 sched_insn_is_legitimate_for_speculation_p (consumer,
4150 new_ds))
4151 /* Transform it to be in speculative. */
4152 ds = new_ds;
4155 else
4156 /* Mark the dep as 'be in speculative'. */
4157 ds |= fs;
4161 dep_def _new_dep, *new_dep = &_new_dep;
4163 init_dep_1 (new_dep, twin, consumer, DEP_TYPE (dep), ds);
4164 sd_add_dep (new_dep, false);
4169 /* Generates recovery code for BEGIN speculative INSN. */
4170 static void
4171 begin_speculative_block (rtx insn)
4173 if (TODO_SPEC (insn) & BEGIN_DATA)
4174 nr_begin_data++;
4175 if (TODO_SPEC (insn) & BEGIN_CONTROL)
4176 nr_begin_control++;
4178 create_check_block_twin (insn, false);
4180 TODO_SPEC (insn) &= ~BEGIN_SPEC;
4183 static void haifa_init_insn (rtx);
4185 /* Generates recovery code for BE_IN speculative INSN. */
4186 static void
4187 add_to_speculative_block (rtx insn)
4189 ds_t ts;
4190 sd_iterator_def sd_it;
4191 dep_t dep;
4192 rtx twins = NULL;
4193 rtx_vec_t priorities_roots;
4195 ts = TODO_SPEC (insn);
4196 gcc_assert (!(ts & ~BE_IN_SPEC));
4198 if (ts & BE_IN_DATA)
4199 nr_be_in_data++;
4200 if (ts & BE_IN_CONTROL)
4201 nr_be_in_control++;
4203 TODO_SPEC (insn) &= ~BE_IN_SPEC;
4204 gcc_assert (!TODO_SPEC (insn));
4206 DONE_SPEC (insn) |= ts;
4208 /* First we convert all simple checks to branchy. */
4209 for (sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
4210 sd_iterator_cond (&sd_it, &dep);)
4212 rtx check = DEP_PRO (dep);
4214 if (IS_SPECULATION_SIMPLE_CHECK_P (check))
4216 create_check_block_twin (check, true);
4218 /* Restart search. */
4219 sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
4221 else
4222 /* Continue search. */
4223 sd_iterator_next (&sd_it);
4226 priorities_roots = NULL;
4227 clear_priorities (insn, &priorities_roots);
4229 while (1)
4231 rtx check, twin;
4232 basic_block rec;
4234 /* Get the first backward dependency of INSN. */
4235 sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
4236 if (!sd_iterator_cond (&sd_it, &dep))
4237 /* INSN has no backward dependencies left. */
4238 break;
4240 gcc_assert ((DEP_STATUS (dep) & BEGIN_SPEC) == 0
4241 && (DEP_STATUS (dep) & BE_IN_SPEC) != 0
4242 && (DEP_STATUS (dep) & DEP_TYPES) == DEP_TRUE);
4244 check = DEP_PRO (dep);
4246 gcc_assert (!IS_SPECULATION_CHECK_P (check) && !ORIG_PAT (check)
4247 && QUEUE_INDEX (check) == QUEUE_NOWHERE);
4249 rec = BLOCK_FOR_INSN (check);
4251 twin = emit_insn_before (copy_insn (PATTERN (insn)), BB_END (rec));
4252 haifa_init_insn (twin);
4254 sd_copy_back_deps (twin, insn, true);
4256 if (sched_verbose && spec_info->dump)
4257 /* INSN_BB (insn) isn't determined for twin insns yet.
4258 So we can't use current_sched_info->print_insn. */
4259 fprintf (spec_info->dump, ";;\t\tGenerated twin insn : %d/rec%d\n",
4260 INSN_UID (twin), rec->index);
4262 twins = alloc_INSN_LIST (twin, twins);
4264 /* Add dependences between TWIN and all appropriate
4265 instructions from REC. */
4266 FOR_EACH_DEP (insn, SD_LIST_SPEC_BACK, sd_it, dep)
4268 rtx pro = DEP_PRO (dep);
4270 gcc_assert (DEP_TYPE (dep) == REG_DEP_TRUE);
4272 /* INSN might have dependencies from the instructions from
4273 several recovery blocks. At this iteration we process those
4274 producers that reside in REC. */
4275 if (BLOCK_FOR_INSN (pro) == rec)
4277 dep_def _new_dep, *new_dep = &_new_dep;
4279 init_dep (new_dep, pro, twin, REG_DEP_TRUE);
4280 sd_add_dep (new_dep, false);
4284 process_insn_forw_deps_be_in_spec (insn, twin, ts);
4286 /* Remove all dependencies between INSN and insns in REC. */
4287 for (sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
4288 sd_iterator_cond (&sd_it, &dep);)
4290 rtx pro = DEP_PRO (dep);
4292 if (BLOCK_FOR_INSN (pro) == rec)
4293 sd_delete_dep (sd_it);
4294 else
4295 sd_iterator_next (&sd_it);
4299 /* We couldn't have added the dependencies between INSN and TWINS earlier
4300 because that would make TWINS appear in the INSN_BACK_DEPS (INSN). */
4301 while (twins)
4303 rtx twin;
4305 twin = XEXP (twins, 0);
4308 dep_def _new_dep, *new_dep = &_new_dep;
4310 init_dep (new_dep, insn, twin, REG_DEP_OUTPUT);
4311 sd_add_dep (new_dep, false);
4314 twin = XEXP (twins, 1);
4315 free_INSN_LIST_node (twins);
4316 twins = twin;
4319 calc_priorities (priorities_roots);
4320 VEC_free (rtx, heap, priorities_roots);
4323 /* Extends and fills with zeros (only the new part) array pointed to by P. */
4324 void *
4325 xrecalloc (void *p, size_t new_nmemb, size_t old_nmemb, size_t size)
4327 gcc_assert (new_nmemb >= old_nmemb);
4328 p = XRESIZEVAR (void, p, new_nmemb * size);
4329 memset (((char *) p) + old_nmemb * size, 0, (new_nmemb - old_nmemb) * size);
4330 return p;
4333 /* Helper function.
4334 Find fallthru edge from PRED. */
4335 edge
4336 find_fallthru_edge_from (basic_block pred)
4338 edge e;
4339 basic_block succ;
4341 succ = pred->next_bb;
4342 gcc_assert (succ->prev_bb == pred);
4344 if (EDGE_COUNT (pred->succs) <= EDGE_COUNT (succ->preds))
4346 e = find_fallthru_edge (pred->succs);
4348 if (e)
4350 gcc_assert (e->dest == succ);
4351 return e;
4354 else
4356 e = find_fallthru_edge (succ->preds);
4358 if (e)
4360 gcc_assert (e->src == pred);
4361 return e;
4365 return NULL;
4368 /* Extend per basic block data structures. */
4369 static void
4370 sched_extend_bb (void)
4372 rtx insn;
4374 /* The following is done to keep current_sched_info->next_tail non null. */
4375 insn = BB_END (EXIT_BLOCK_PTR->prev_bb);
4376 if (NEXT_INSN (insn) == 0
4377 || (!NOTE_P (insn)
4378 && !LABEL_P (insn)
4379 /* Don't emit a NOTE if it would end up before a BARRIER. */
4380 && !BARRIER_P (NEXT_INSN (insn))))
4382 rtx note = emit_note_after (NOTE_INSN_DELETED, insn);
4383 /* Make insn appear outside BB. */
4384 set_block_for_insn (note, NULL);
4385 BB_END (EXIT_BLOCK_PTR->prev_bb) = insn;
4389 /* Init per basic block data structures. */
4390 void
4391 sched_init_bbs (void)
4393 sched_extend_bb ();
4396 /* Initialize BEFORE_RECOVERY variable. */
4397 static void
4398 init_before_recovery (basic_block *before_recovery_ptr)
4400 basic_block last;
4401 edge e;
4403 last = EXIT_BLOCK_PTR->prev_bb;
4404 e = find_fallthru_edge_from (last);
4406 if (e)
4408 /* We create two basic blocks:
4409 1. Single instruction block is inserted right after E->SRC
4410 and has jump to
4411 2. Empty block right before EXIT_BLOCK.
4412 Between these two blocks recovery blocks will be emitted. */
4414 basic_block single, empty;
4415 rtx x, label;
4417 /* If the fallthrough edge to exit we've found is from the block we've
4418 created before, don't do anything more. */
4419 if (last == after_recovery)
4420 return;
4422 adding_bb_to_current_region_p = false;
4424 single = sched_create_empty_bb (last);
4425 empty = sched_create_empty_bb (single);
4427 /* Add new blocks to the root loop. */
4428 if (current_loops != NULL)
4430 add_bb_to_loop (single, VEC_index (loop_p, current_loops->larray, 0));
4431 add_bb_to_loop (empty, VEC_index (loop_p, current_loops->larray, 0));
4434 single->count = last->count;
4435 empty->count = last->count;
4436 single->frequency = last->frequency;
4437 empty->frequency = last->frequency;
4438 BB_COPY_PARTITION (single, last);
4439 BB_COPY_PARTITION (empty, last);
4441 redirect_edge_succ (e, single);
4442 make_single_succ_edge (single, empty, 0);
4443 make_single_succ_edge (empty, EXIT_BLOCK_PTR,
4444 EDGE_FALLTHRU | EDGE_CAN_FALLTHRU);
4446 label = block_label (empty);
4447 x = emit_jump_insn_after (gen_jump (label), BB_END (single));
4448 JUMP_LABEL (x) = label;
4449 LABEL_NUSES (label)++;
4450 haifa_init_insn (x);
4452 emit_barrier_after (x);
4454 sched_init_only_bb (empty, NULL);
4455 sched_init_only_bb (single, NULL);
4456 sched_extend_bb ();
4458 adding_bb_to_current_region_p = true;
4459 before_recovery = single;
4460 after_recovery = empty;
4462 if (before_recovery_ptr)
4463 *before_recovery_ptr = before_recovery;
4465 if (sched_verbose >= 2 && spec_info->dump)
4466 fprintf (spec_info->dump,
4467 ";;\t\tFixed fallthru to EXIT : %d->>%d->%d->>EXIT\n",
4468 last->index, single->index, empty->index);
4470 else
4471 before_recovery = last;
4474 /* Returns new recovery block. */
4475 basic_block
4476 sched_create_recovery_block (basic_block *before_recovery_ptr)
4478 rtx label;
4479 rtx barrier;
4480 basic_block rec;
4482 haifa_recovery_bb_recently_added_p = true;
4483 haifa_recovery_bb_ever_added_p = true;
4485 init_before_recovery (before_recovery_ptr);
4487 barrier = get_last_bb_insn (before_recovery);
4488 gcc_assert (BARRIER_P (barrier));
4490 label = emit_label_after (gen_label_rtx (), barrier);
4492 rec = create_basic_block (label, label, before_recovery);
4494 /* A recovery block always ends with an unconditional jump. */
4495 emit_barrier_after (BB_END (rec));
4497 if (BB_PARTITION (before_recovery) != BB_UNPARTITIONED)
4498 BB_SET_PARTITION (rec, BB_COLD_PARTITION);
4500 if (sched_verbose && spec_info->dump)
4501 fprintf (spec_info->dump, ";;\t\tGenerated recovery block rec%d\n",
4502 rec->index);
4504 return rec;
4507 /* Create edges: FIRST_BB -> REC; FIRST_BB -> SECOND_BB; REC -> SECOND_BB
4508 and emit necessary jumps. */
4509 void
4510 sched_create_recovery_edges (basic_block first_bb, basic_block rec,
4511 basic_block second_bb)
4513 rtx label;
4514 rtx jump;
4515 int edge_flags;
4517 /* This is fixing of incoming edge. */
4518 /* ??? Which other flags should be specified? */
4519 if (BB_PARTITION (first_bb) != BB_PARTITION (rec))
4520 /* Partition type is the same, if it is "unpartitioned". */
4521 edge_flags = EDGE_CROSSING;
4522 else
4523 edge_flags = 0;
4525 make_edge (first_bb, rec, edge_flags);
4526 label = block_label (second_bb);
4527 jump = emit_jump_insn_after (gen_jump (label), BB_END (rec));
4528 JUMP_LABEL (jump) = label;
4529 LABEL_NUSES (label)++;
4531 if (BB_PARTITION (second_bb) != BB_PARTITION (rec))
4532 /* Partition type is the same, if it is "unpartitioned". */
4534 /* Rewritten from cfgrtl.c. */
4535 if (flag_reorder_blocks_and_partition
4536 && targetm.have_named_sections)
4538 /* We don't need the same note for the check because
4539 any_condjump_p (check) == true. */
4540 add_reg_note (jump, REG_CROSSING_JUMP, NULL_RTX);
4542 edge_flags = EDGE_CROSSING;
4544 else
4545 edge_flags = 0;
4547 make_single_succ_edge (rec, second_bb, edge_flags);
4548 if (dom_info_available_p (CDI_DOMINATORS))
4549 set_immediate_dominator (CDI_DOMINATORS, rec, first_bb);
4552 /* This function creates recovery code for INSN. If MUTATE_P is nonzero,
4553 INSN is a simple check, that should be converted to branchy one. */
4554 static void
4555 create_check_block_twin (rtx insn, bool mutate_p)
4557 basic_block rec;
4558 rtx label, check, twin;
4559 ds_t fs;
4560 sd_iterator_def sd_it;
4561 dep_t dep;
4562 dep_def _new_dep, *new_dep = &_new_dep;
4563 ds_t todo_spec;
4565 gcc_assert (ORIG_PAT (insn) != NULL_RTX);
4567 if (!mutate_p)
4568 todo_spec = TODO_SPEC (insn);
4569 else
4571 gcc_assert (IS_SPECULATION_SIMPLE_CHECK_P (insn)
4572 && (TODO_SPEC (insn) & SPECULATIVE) == 0);
4574 todo_spec = CHECK_SPEC (insn);
4577 todo_spec &= SPECULATIVE;
4579 /* Create recovery block. */
4580 if (mutate_p || targetm.sched.needs_block_p (todo_spec))
4582 rec = sched_create_recovery_block (NULL);
4583 label = BB_HEAD (rec);
4585 else
4587 rec = EXIT_BLOCK_PTR;
4588 label = NULL_RTX;
4591 /* Emit CHECK. */
4592 check = targetm.sched.gen_spec_check (insn, label, todo_spec);
4594 if (rec != EXIT_BLOCK_PTR)
4596 /* To have mem_reg alive at the beginning of second_bb,
4597 we emit check BEFORE insn, so insn after splitting
4598 insn will be at the beginning of second_bb, which will
4599 provide us with the correct life information. */
4600 check = emit_jump_insn_before (check, insn);
4601 JUMP_LABEL (check) = label;
4602 LABEL_NUSES (label)++;
4604 else
4605 check = emit_insn_before (check, insn);
4607 /* Extend data structures. */
4608 haifa_init_insn (check);
4610 /* CHECK is being added to current region. Extend ready list. */
4611 gcc_assert (sched_ready_n_insns != -1);
4612 sched_extend_ready_list (sched_ready_n_insns + 1);
4614 if (current_sched_info->add_remove_insn)
4615 current_sched_info->add_remove_insn (insn, 0);
4617 RECOVERY_BLOCK (check) = rec;
4619 if (sched_verbose && spec_info->dump)
4620 fprintf (spec_info->dump, ";;\t\tGenerated check insn : %s\n",
4621 (*current_sched_info->print_insn) (check, 0));
4623 gcc_assert (ORIG_PAT (insn));
4625 /* Initialize TWIN (twin is a duplicate of original instruction
4626 in the recovery block). */
4627 if (rec != EXIT_BLOCK_PTR)
4629 sd_iterator_def sd_it;
4630 dep_t dep;
4632 FOR_EACH_DEP (insn, SD_LIST_RES_BACK, sd_it, dep)
4633 if ((DEP_STATUS (dep) & DEP_OUTPUT) != 0)
4635 struct _dep _dep2, *dep2 = &_dep2;
4637 init_dep (dep2, DEP_PRO (dep), check, REG_DEP_TRUE);
4639 sd_add_dep (dep2, true);
4642 twin = emit_insn_after (ORIG_PAT (insn), BB_END (rec));
4643 haifa_init_insn (twin);
4645 if (sched_verbose && spec_info->dump)
4646 /* INSN_BB (insn) isn't determined for twin insns yet.
4647 So we can't use current_sched_info->print_insn. */
4648 fprintf (spec_info->dump, ";;\t\tGenerated twin insn : %d/rec%d\n",
4649 INSN_UID (twin), rec->index);
4651 else
4653 ORIG_PAT (check) = ORIG_PAT (insn);
4654 HAS_INTERNAL_DEP (check) = 1;
4655 twin = check;
4656 /* ??? We probably should change all OUTPUT dependencies to
4657 (TRUE | OUTPUT). */
4660 /* Copy all resolved back dependencies of INSN to TWIN. This will
4661 provide correct value for INSN_TICK (TWIN). */
4662 sd_copy_back_deps (twin, insn, true);
4664 if (rec != EXIT_BLOCK_PTR)
4665 /* In case of branchy check, fix CFG. */
4667 basic_block first_bb, second_bb;
4668 rtx jump;
4670 first_bb = BLOCK_FOR_INSN (check);
4671 second_bb = sched_split_block (first_bb, check);
4673 sched_create_recovery_edges (first_bb, rec, second_bb);
4675 sched_init_only_bb (second_bb, first_bb);
4676 sched_init_only_bb (rec, EXIT_BLOCK_PTR);
4678 jump = BB_END (rec);
4679 haifa_init_insn (jump);
4682 /* Move backward dependences from INSN to CHECK and
4683 move forward dependences from INSN to TWIN. */
4685 /* First, create dependencies between INSN's producers and CHECK & TWIN. */
4686 FOR_EACH_DEP (insn, SD_LIST_BACK, sd_it, dep)
4688 rtx pro = DEP_PRO (dep);
4689 ds_t ds;
4691 /* If BEGIN_DATA: [insn ~~TRUE~~> producer]:
4692 check --TRUE--> producer ??? or ANTI ???
4693 twin --TRUE--> producer
4694 twin --ANTI--> check
4696 If BEGIN_CONTROL: [insn ~~ANTI~~> producer]:
4697 check --ANTI--> producer
4698 twin --ANTI--> producer
4699 twin --ANTI--> check
4701 If BE_IN_SPEC: [insn ~~TRUE~~> producer]:
4702 check ~~TRUE~~> producer
4703 twin ~~TRUE~~> producer
4704 twin --ANTI--> check */
4706 ds = DEP_STATUS (dep);
4708 if (ds & BEGIN_SPEC)
4710 gcc_assert (!mutate_p);
4711 ds &= ~BEGIN_SPEC;
4714 init_dep_1 (new_dep, pro, check, DEP_TYPE (dep), ds);
4715 sd_add_dep (new_dep, false);
4717 if (rec != EXIT_BLOCK_PTR)
4719 DEP_CON (new_dep) = twin;
4720 sd_add_dep (new_dep, false);
4724 /* Second, remove backward dependencies of INSN. */
4725 for (sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
4726 sd_iterator_cond (&sd_it, &dep);)
4728 if ((DEP_STATUS (dep) & BEGIN_SPEC)
4729 || mutate_p)
4730 /* We can delete this dep because we overcome it with
4731 BEGIN_SPECULATION. */
4732 sd_delete_dep (sd_it);
4733 else
4734 sd_iterator_next (&sd_it);
4737 /* Future Speculations. Determine what BE_IN speculations will be like. */
4738 fs = 0;
4740 /* Fields (DONE_SPEC (x) & BEGIN_SPEC) and CHECK_SPEC (x) are set only
4741 here. */
4743 gcc_assert (!DONE_SPEC (insn));
4745 if (!mutate_p)
4747 ds_t ts = TODO_SPEC (insn);
4749 DONE_SPEC (insn) = ts & BEGIN_SPEC;
4750 CHECK_SPEC (check) = ts & BEGIN_SPEC;
4752 /* Luckiness of future speculations solely depends upon initial
4753 BEGIN speculation. */
4754 if (ts & BEGIN_DATA)
4755 fs = set_dep_weak (fs, BE_IN_DATA, get_dep_weak (ts, BEGIN_DATA));
4756 if (ts & BEGIN_CONTROL)
4757 fs = set_dep_weak (fs, BE_IN_CONTROL,
4758 get_dep_weak (ts, BEGIN_CONTROL));
4760 else
4761 CHECK_SPEC (check) = CHECK_SPEC (insn);
4763 /* Future speculations: call the helper. */
4764 process_insn_forw_deps_be_in_spec (insn, twin, fs);
4766 if (rec != EXIT_BLOCK_PTR)
4768 /* Which types of dependencies should we use here is,
4769 generally, machine-dependent question... But, for now,
4770 it is not. */
4772 if (!mutate_p)
4774 init_dep (new_dep, insn, check, REG_DEP_TRUE);
4775 sd_add_dep (new_dep, false);
4777 init_dep (new_dep, insn, twin, REG_DEP_OUTPUT);
4778 sd_add_dep (new_dep, false);
4780 else
4782 if (spec_info->dump)
4783 fprintf (spec_info->dump, ";;\t\tRemoved simple check : %s\n",
4784 (*current_sched_info->print_insn) (insn, 0));
4786 /* Remove all dependencies of the INSN. */
4788 sd_it = sd_iterator_start (insn, (SD_LIST_FORW
4789 | SD_LIST_BACK
4790 | SD_LIST_RES_BACK));
4791 while (sd_iterator_cond (&sd_it, &dep))
4792 sd_delete_dep (sd_it);
4795 /* If former check (INSN) already was moved to the ready (or queue)
4796 list, add new check (CHECK) there too. */
4797 if (QUEUE_INDEX (insn) != QUEUE_NOWHERE)
4798 try_ready (check);
4800 /* Remove old check from instruction stream and free its
4801 data. */
4802 sched_remove_insn (insn);
4805 init_dep (new_dep, check, twin, REG_DEP_ANTI);
4806 sd_add_dep (new_dep, false);
4808 else
4810 init_dep_1 (new_dep, insn, check, REG_DEP_TRUE, DEP_TRUE | DEP_OUTPUT);
4811 sd_add_dep (new_dep, false);
4814 if (!mutate_p)
4815 /* Fix priorities. If MUTATE_P is nonzero, this is not necessary,
4816 because it'll be done later in add_to_speculative_block. */
4818 rtx_vec_t priorities_roots = NULL;
4820 clear_priorities (twin, &priorities_roots);
4821 calc_priorities (priorities_roots);
4822 VEC_free (rtx, heap, priorities_roots);
4826 /* Removes dependency between instructions in the recovery block REC
4827 and usual region instructions. It keeps inner dependences so it
4828 won't be necessary to recompute them. */
4829 static void
4830 fix_recovery_deps (basic_block rec)
4832 rtx note, insn, jump, ready_list = 0;
4833 bitmap_head in_ready;
4834 rtx link;
4836 bitmap_initialize (&in_ready, 0);
4838 /* NOTE - a basic block note. */
4839 note = NEXT_INSN (BB_HEAD (rec));
4840 gcc_assert (NOTE_INSN_BASIC_BLOCK_P (note));
4841 insn = BB_END (rec);
4842 gcc_assert (JUMP_P (insn));
4843 insn = PREV_INSN (insn);
4847 sd_iterator_def sd_it;
4848 dep_t dep;
4850 for (sd_it = sd_iterator_start (insn, SD_LIST_FORW);
4851 sd_iterator_cond (&sd_it, &dep);)
4853 rtx consumer = DEP_CON (dep);
4855 if (BLOCK_FOR_INSN (consumer) != rec)
4857 sd_delete_dep (sd_it);
4859 if (bitmap_set_bit (&in_ready, INSN_LUID (consumer)))
4860 ready_list = alloc_INSN_LIST (consumer, ready_list);
4862 else
4864 gcc_assert ((DEP_STATUS (dep) & DEP_TYPES) == DEP_TRUE);
4866 sd_iterator_next (&sd_it);
4870 insn = PREV_INSN (insn);
4872 while (insn != note);
4874 bitmap_clear (&in_ready);
4876 /* Try to add instructions to the ready or queue list. */
4877 for (link = ready_list; link; link = XEXP (link, 1))
4878 try_ready (XEXP (link, 0));
4879 free_INSN_LIST_list (&ready_list);
4881 /* Fixing jump's dependences. */
4882 insn = BB_HEAD (rec);
4883 jump = BB_END (rec);
4885 gcc_assert (LABEL_P (insn));
4886 insn = NEXT_INSN (insn);
4888 gcc_assert (NOTE_INSN_BASIC_BLOCK_P (insn));
4889 add_jump_dependencies (insn, jump);
4892 /* Change pattern of INSN to NEW_PAT. */
4893 void
4894 sched_change_pattern (rtx insn, rtx new_pat)
4896 int t;
4898 t = validate_change (insn, &PATTERN (insn), new_pat, 0);
4899 gcc_assert (t);
4900 dfa_clear_single_insn_cache (insn);
4903 /* Change pattern of INSN to NEW_PAT. Invalidate cached haifa
4904 instruction data. */
4905 static void
4906 haifa_change_pattern (rtx insn, rtx new_pat)
4908 sched_change_pattern (insn, new_pat);
4910 /* Invalidate INSN_COST, so it'll be recalculated. */
4911 INSN_COST (insn) = -1;
4912 /* Invalidate INSN_TICK, so it'll be recalculated. */
4913 INSN_TICK (insn) = INVALID_TICK;
4916 /* -1 - can't speculate,
4917 0 - for speculation with REQUEST mode it is OK to use
4918 current instruction pattern,
4919 1 - need to change pattern for *NEW_PAT to be speculative. */
4921 sched_speculate_insn (rtx insn, ds_t request, rtx *new_pat)
4923 gcc_assert (current_sched_info->flags & DO_SPECULATION
4924 && (request & SPECULATIVE)
4925 && sched_insn_is_legitimate_for_speculation_p (insn, request));
4927 if ((request & spec_info->mask) != request)
4928 return -1;
4930 if (request & BE_IN_SPEC
4931 && !(request & BEGIN_SPEC))
4932 return 0;
4934 return targetm.sched.speculate_insn (insn, request, new_pat);
4937 static int
4938 haifa_speculate_insn (rtx insn, ds_t request, rtx *new_pat)
4940 gcc_assert (sched_deps_info->generate_spec_deps
4941 && !IS_SPECULATION_CHECK_P (insn));
4943 if (HAS_INTERNAL_DEP (insn)
4944 || SCHED_GROUP_P (insn))
4945 return -1;
4947 return sched_speculate_insn (insn, request, new_pat);
4950 /* Print some information about block BB, which starts with HEAD and
4951 ends with TAIL, before scheduling it.
4952 I is zero, if scheduler is about to start with the fresh ebb. */
4953 static void
4954 dump_new_block_header (int i, basic_block bb, rtx head, rtx tail)
4956 if (!i)
4957 fprintf (sched_dump,
4958 ";; ======================================================\n");
4959 else
4960 fprintf (sched_dump,
4961 ";; =====================ADVANCING TO=====================\n");
4962 fprintf (sched_dump,
4963 ";; -- basic block %d from %d to %d -- %s reload\n",
4964 bb->index, INSN_UID (head), INSN_UID (tail),
4965 (reload_completed ? "after" : "before"));
4966 fprintf (sched_dump,
4967 ";; ======================================================\n");
4968 fprintf (sched_dump, "\n");
4971 /* Unlink basic block notes and labels and saves them, so they
4972 can be easily restored. We unlink basic block notes in EBB to
4973 provide back-compatibility with the previous code, as target backends
4974 assume, that there'll be only instructions between
4975 current_sched_info->{head and tail}. We restore these notes as soon
4976 as we can.
4977 FIRST (LAST) is the first (last) basic block in the ebb.
4978 NB: In usual case (FIRST == LAST) nothing is really done. */
4979 void
4980 unlink_bb_notes (basic_block first, basic_block last)
4982 /* We DON'T unlink basic block notes of the first block in the ebb. */
4983 if (first == last)
4984 return;
4986 bb_header = XNEWVEC (rtx, last_basic_block);
4988 /* Make a sentinel. */
4989 if (last->next_bb != EXIT_BLOCK_PTR)
4990 bb_header[last->next_bb->index] = 0;
4992 first = first->next_bb;
4995 rtx prev, label, note, next;
4997 label = BB_HEAD (last);
4998 if (LABEL_P (label))
4999 note = NEXT_INSN (label);
5000 else
5001 note = label;
5002 gcc_assert (NOTE_INSN_BASIC_BLOCK_P (note));
5004 prev = PREV_INSN (label);
5005 next = NEXT_INSN (note);
5006 gcc_assert (prev && next);
5008 NEXT_INSN (prev) = next;
5009 PREV_INSN (next) = prev;
5011 bb_header[last->index] = label;
5013 if (last == first)
5014 break;
5016 last = last->prev_bb;
5018 while (1);
5021 /* Restore basic block notes.
5022 FIRST is the first basic block in the ebb. */
5023 static void
5024 restore_bb_notes (basic_block first)
5026 if (!bb_header)
5027 return;
5029 /* We DON'T unlink basic block notes of the first block in the ebb. */
5030 first = first->next_bb;
5031 /* Remember: FIRST is actually a second basic block in the ebb. */
5033 while (first != EXIT_BLOCK_PTR
5034 && bb_header[first->index])
5036 rtx prev, label, note, next;
5038 label = bb_header[first->index];
5039 prev = PREV_INSN (label);
5040 next = NEXT_INSN (prev);
5042 if (LABEL_P (label))
5043 note = NEXT_INSN (label);
5044 else
5045 note = label;
5046 gcc_assert (NOTE_INSN_BASIC_BLOCK_P (note));
5048 bb_header[first->index] = 0;
5050 NEXT_INSN (prev) = label;
5051 NEXT_INSN (note) = next;
5052 PREV_INSN (next) = note;
5054 first = first->next_bb;
5057 free (bb_header);
5058 bb_header = 0;
5061 /* Helper function.
5062 Fix CFG after both in- and inter-block movement of
5063 control_flow_insn_p JUMP. */
5064 static void
5065 fix_jump_move (rtx jump)
5067 basic_block bb, jump_bb, jump_bb_next;
5069 bb = BLOCK_FOR_INSN (PREV_INSN (jump));
5070 jump_bb = BLOCK_FOR_INSN (jump);
5071 jump_bb_next = jump_bb->next_bb;
5073 gcc_assert (common_sched_info->sched_pass_id == SCHED_EBB_PASS
5074 || IS_SPECULATION_BRANCHY_CHECK_P (jump));
5076 if (!NOTE_INSN_BASIC_BLOCK_P (BB_END (jump_bb_next)))
5077 /* if jump_bb_next is not empty. */
5078 BB_END (jump_bb) = BB_END (jump_bb_next);
5080 if (BB_END (bb) != PREV_INSN (jump))
5081 /* Then there are instruction after jump that should be placed
5082 to jump_bb_next. */
5083 BB_END (jump_bb_next) = BB_END (bb);
5084 else
5085 /* Otherwise jump_bb_next is empty. */
5086 BB_END (jump_bb_next) = NEXT_INSN (BB_HEAD (jump_bb_next));
5088 /* To make assertion in move_insn happy. */
5089 BB_END (bb) = PREV_INSN (jump);
5091 update_bb_for_insn (jump_bb_next);
5094 /* Fix CFG after interblock movement of control_flow_insn_p JUMP. */
5095 static void
5096 move_block_after_check (rtx jump)
5098 basic_block bb, jump_bb, jump_bb_next;
5099 VEC(edge,gc) *t;
5101 bb = BLOCK_FOR_INSN (PREV_INSN (jump));
5102 jump_bb = BLOCK_FOR_INSN (jump);
5103 jump_bb_next = jump_bb->next_bb;
5105 update_bb_for_insn (jump_bb);
5107 gcc_assert (IS_SPECULATION_CHECK_P (jump)
5108 || IS_SPECULATION_CHECK_P (BB_END (jump_bb_next)));
5110 unlink_block (jump_bb_next);
5111 link_block (jump_bb_next, bb);
5113 t = bb->succs;
5114 bb->succs = 0;
5115 move_succs (&(jump_bb->succs), bb);
5116 move_succs (&(jump_bb_next->succs), jump_bb);
5117 move_succs (&t, jump_bb_next);
5119 df_mark_solutions_dirty ();
5121 common_sched_info->fix_recovery_cfg
5122 (bb->index, jump_bb->index, jump_bb_next->index);
5125 /* Helper function for move_block_after_check.
5126 This functions attaches edge vector pointed to by SUCCSP to
5127 block TO. */
5128 static void
5129 move_succs (VEC(edge,gc) **succsp, basic_block to)
5131 edge e;
5132 edge_iterator ei;
5134 gcc_assert (to->succs == 0);
5136 to->succs = *succsp;
5138 FOR_EACH_EDGE (e, ei, to->succs)
5139 e->src = to;
5141 *succsp = 0;
5144 /* Remove INSN from the instruction stream.
5145 INSN should have any dependencies. */
5146 static void
5147 sched_remove_insn (rtx insn)
5149 sd_finish_insn (insn);
5151 change_queue_index (insn, QUEUE_NOWHERE);
5152 current_sched_info->add_remove_insn (insn, 1);
5153 remove_insn (insn);
5156 /* Clear priorities of all instructions, that are forward dependent on INSN.
5157 Store in vector pointed to by ROOTS_PTR insns on which priority () should
5158 be invoked to initialize all cleared priorities. */
5159 static void
5160 clear_priorities (rtx insn, rtx_vec_t *roots_ptr)
5162 sd_iterator_def sd_it;
5163 dep_t dep;
5164 bool insn_is_root_p = true;
5166 gcc_assert (QUEUE_INDEX (insn) != QUEUE_SCHEDULED);
5168 FOR_EACH_DEP (insn, SD_LIST_BACK, sd_it, dep)
5170 rtx pro = DEP_PRO (dep);
5172 if (INSN_PRIORITY_STATUS (pro) >= 0
5173 && QUEUE_INDEX (insn) != QUEUE_SCHEDULED)
5175 /* If DEP doesn't contribute to priority then INSN itself should
5176 be added to priority roots. */
5177 if (contributes_to_priority_p (dep))
5178 insn_is_root_p = false;
5180 INSN_PRIORITY_STATUS (pro) = -1;
5181 clear_priorities (pro, roots_ptr);
5185 if (insn_is_root_p)
5186 VEC_safe_push (rtx, heap, *roots_ptr, insn);
5189 /* Recompute priorities of instructions, whose priorities might have been
5190 changed. ROOTS is a vector of instructions whose priority computation will
5191 trigger initialization of all cleared priorities. */
5192 static void
5193 calc_priorities (rtx_vec_t roots)
5195 int i;
5196 rtx insn;
5198 FOR_EACH_VEC_ELT (rtx, roots, i, insn)
5199 priority (insn);
5203 /* Add dependences between JUMP and other instructions in the recovery
5204 block. INSN is the first insn the recovery block. */
5205 static void
5206 add_jump_dependencies (rtx insn, rtx jump)
5210 insn = NEXT_INSN (insn);
5211 if (insn == jump)
5212 break;
5214 if (dep_list_size (insn) == 0)
5216 dep_def _new_dep, *new_dep = &_new_dep;
5218 init_dep (new_dep, insn, jump, REG_DEP_ANTI);
5219 sd_add_dep (new_dep, false);
5222 while (1);
5224 gcc_assert (!sd_lists_empty_p (jump, SD_LIST_BACK));
5227 /* Return the NOTE_INSN_BASIC_BLOCK of BB. */
5229 bb_note (basic_block bb)
5231 rtx note;
5233 note = BB_HEAD (bb);
5234 if (LABEL_P (note))
5235 note = NEXT_INSN (note);
5237 gcc_assert (NOTE_INSN_BASIC_BLOCK_P (note));
5238 return note;
5241 #ifdef ENABLE_CHECKING
5242 /* Helper function for check_cfg.
5243 Return nonzero, if edge vector pointed to by EL has edge with TYPE in
5244 its flags. */
5245 static int
5246 has_edge_p (VEC(edge,gc) *el, int type)
5248 edge e;
5249 edge_iterator ei;
5251 FOR_EACH_EDGE (e, ei, el)
5252 if (e->flags & type)
5253 return 1;
5254 return 0;
5257 /* Search back, starting at INSN, for an insn that is not a
5258 NOTE_INSN_VAR_LOCATION. Don't search beyond HEAD, and return it if
5259 no such insn can be found. */
5260 static inline rtx
5261 prev_non_location_insn (rtx insn, rtx head)
5263 while (insn != head && NOTE_P (insn)
5264 && NOTE_KIND (insn) == NOTE_INSN_VAR_LOCATION)
5265 insn = PREV_INSN (insn);
5267 return insn;
5270 /* Check few properties of CFG between HEAD and TAIL.
5271 If HEAD (TAIL) is NULL check from the beginning (till the end) of the
5272 instruction stream. */
5273 static void
5274 check_cfg (rtx head, rtx tail)
5276 rtx next_tail;
5277 basic_block bb = 0;
5278 int not_first = 0, not_last;
5280 if (head == NULL)
5281 head = get_insns ();
5282 if (tail == NULL)
5283 tail = get_last_insn ();
5284 next_tail = NEXT_INSN (tail);
5288 not_last = head != tail;
5290 if (not_first)
5291 gcc_assert (NEXT_INSN (PREV_INSN (head)) == head);
5292 if (not_last)
5293 gcc_assert (PREV_INSN (NEXT_INSN (head)) == head);
5295 if (LABEL_P (head)
5296 || (NOTE_INSN_BASIC_BLOCK_P (head)
5297 && (!not_first
5298 || (not_first && !LABEL_P (PREV_INSN (head))))))
5300 gcc_assert (bb == 0);
5301 bb = BLOCK_FOR_INSN (head);
5302 if (bb != 0)
5303 gcc_assert (BB_HEAD (bb) == head);
5304 else
5305 /* This is the case of jump table. See inside_basic_block_p (). */
5306 gcc_assert (LABEL_P (head) && !inside_basic_block_p (head));
5309 if (bb == 0)
5311 gcc_assert (!inside_basic_block_p (head));
5312 head = NEXT_INSN (head);
5314 else
5316 gcc_assert (inside_basic_block_p (head)
5317 || NOTE_P (head));
5318 gcc_assert (BLOCK_FOR_INSN (head) == bb);
5320 if (LABEL_P (head))
5322 head = NEXT_INSN (head);
5323 gcc_assert (NOTE_INSN_BASIC_BLOCK_P (head));
5325 else
5327 if (control_flow_insn_p (head))
5329 gcc_assert (prev_non_location_insn (BB_END (bb), head)
5330 == head);
5332 if (any_uncondjump_p (head))
5333 gcc_assert (EDGE_COUNT (bb->succs) == 1
5334 && BARRIER_P (NEXT_INSN (head)));
5335 else if (any_condjump_p (head))
5336 gcc_assert (/* Usual case. */
5337 (EDGE_COUNT (bb->succs) > 1
5338 && !BARRIER_P (NEXT_INSN (head)))
5339 /* Or jump to the next instruction. */
5340 || (EDGE_COUNT (bb->succs) == 1
5341 && (BB_HEAD (EDGE_I (bb->succs, 0)->dest)
5342 == JUMP_LABEL (head))));
5344 if (BB_END (bb) == head)
5346 if (EDGE_COUNT (bb->succs) > 1)
5347 gcc_assert (control_flow_insn_p (prev_non_location_insn
5348 (head, BB_HEAD (bb)))
5349 || has_edge_p (bb->succs, EDGE_COMPLEX));
5350 bb = 0;
5353 head = NEXT_INSN (head);
5357 not_first = 1;
5359 while (head != next_tail);
5361 gcc_assert (bb == 0);
5364 #endif /* ENABLE_CHECKING */
5366 /* Extend per basic block data structures. */
5367 static void
5368 extend_bb (void)
5370 if (sched_scan_info->extend_bb)
5371 sched_scan_info->extend_bb ();
5374 /* Init data for BB. */
5375 static void
5376 init_bb (basic_block bb)
5378 if (sched_scan_info->init_bb)
5379 sched_scan_info->init_bb (bb);
5382 /* Extend per insn data structures. */
5383 static void
5384 extend_insn (void)
5386 if (sched_scan_info->extend_insn)
5387 sched_scan_info->extend_insn ();
5390 /* Init data structures for INSN. */
5391 static void
5392 init_insn (rtx insn)
5394 if (sched_scan_info->init_insn)
5395 sched_scan_info->init_insn (insn);
5398 /* Init all insns in BB. */
5399 static void
5400 init_insns_in_bb (basic_block bb)
5402 rtx insn;
5404 FOR_BB_INSNS (bb, insn)
5405 init_insn (insn);
5408 /* A driver function to add a set of basic blocks (BBS),
5409 a single basic block (BB), a set of insns (INSNS) or a single insn (INSN)
5410 to the scheduling region. */
5411 void
5412 sched_scan (const struct sched_scan_info_def *ssi,
5413 bb_vec_t bbs, basic_block bb, insn_vec_t insns, rtx insn)
5415 sched_scan_info = ssi;
5417 if (bbs != NULL || bb != NULL)
5419 extend_bb ();
5421 if (bbs != NULL)
5423 unsigned i;
5424 basic_block x;
5426 FOR_EACH_VEC_ELT (basic_block, bbs, i, x)
5427 init_bb (x);
5430 if (bb != NULL)
5431 init_bb (bb);
5434 extend_insn ();
5436 if (bbs != NULL)
5438 unsigned i;
5439 basic_block x;
5441 FOR_EACH_VEC_ELT (basic_block, bbs, i, x)
5442 init_insns_in_bb (x);
5445 if (bb != NULL)
5446 init_insns_in_bb (bb);
5448 if (insns != NULL)
5450 unsigned i;
5451 rtx x;
5453 FOR_EACH_VEC_ELT (rtx, insns, i, x)
5454 init_insn (x);
5457 if (insn != NULL)
5458 init_insn (insn);
5462 /* Extend data structures for logical insn UID. */
5463 static void
5464 luids_extend_insn (void)
5466 int new_luids_max_uid = get_max_uid () + 1;
5468 VEC_safe_grow_cleared (int, heap, sched_luids, new_luids_max_uid);
5471 /* Initialize LUID for INSN. */
5472 static void
5473 luids_init_insn (rtx insn)
5475 int i = INSN_P (insn) ? 1 : common_sched_info->luid_for_non_insn (insn);
5476 int luid;
5478 if (i >= 0)
5480 luid = sched_max_luid;
5481 sched_max_luid += i;
5483 else
5484 luid = -1;
5486 SET_INSN_LUID (insn, luid);
5489 /* Initialize luids for BBS, BB, INSNS and INSN.
5490 The hook common_sched_info->luid_for_non_insn () is used to determine
5491 if notes, labels, etc. need luids. */
5492 void
5493 sched_init_luids (bb_vec_t bbs, basic_block bb, insn_vec_t insns, rtx insn)
5495 const struct sched_scan_info_def ssi =
5497 NULL, /* extend_bb */
5498 NULL, /* init_bb */
5499 luids_extend_insn, /* extend_insn */
5500 luids_init_insn /* init_insn */
5503 sched_scan (&ssi, bbs, bb, insns, insn);
5506 /* Free LUIDs. */
5507 void
5508 sched_finish_luids (void)
5510 VEC_free (int, heap, sched_luids);
5511 sched_max_luid = 1;
5514 /* Return logical uid of INSN. Helpful while debugging. */
5516 insn_luid (rtx insn)
5518 return INSN_LUID (insn);
5521 /* Extend per insn data in the target. */
5522 void
5523 sched_extend_target (void)
5525 if (targetm.sched.h_i_d_extended)
5526 targetm.sched.h_i_d_extended ();
5529 /* Extend global scheduler structures (those, that live across calls to
5530 schedule_block) to include information about just emitted INSN. */
5531 static void
5532 extend_h_i_d (void)
5534 int reserve = (get_max_uid () + 1
5535 - VEC_length (haifa_insn_data_def, h_i_d));
5536 if (reserve > 0
5537 && ! VEC_space (haifa_insn_data_def, h_i_d, reserve))
5539 VEC_safe_grow_cleared (haifa_insn_data_def, heap, h_i_d,
5540 3 * get_max_uid () / 2);
5541 sched_extend_target ();
5545 /* Initialize h_i_d entry of the INSN with default values.
5546 Values, that are not explicitly initialized here, hold zero. */
5547 static void
5548 init_h_i_d (rtx insn)
5550 if (INSN_LUID (insn) > 0)
5552 INSN_COST (insn) = -1;
5553 QUEUE_INDEX (insn) = QUEUE_NOWHERE;
5554 INSN_TICK (insn) = INVALID_TICK;
5555 INTER_TICK (insn) = INVALID_TICK;
5556 TODO_SPEC (insn) = HARD_DEP;
5560 /* Initialize haifa_insn_data for BBS, BB, INSNS and INSN. */
5561 void
5562 haifa_init_h_i_d (bb_vec_t bbs, basic_block bb, insn_vec_t insns, rtx insn)
5564 const struct sched_scan_info_def ssi =
5566 NULL, /* extend_bb */
5567 NULL, /* init_bb */
5568 extend_h_i_d, /* extend_insn */
5569 init_h_i_d /* init_insn */
5572 sched_scan (&ssi, bbs, bb, insns, insn);
5575 /* Finalize haifa_insn_data. */
5576 void
5577 haifa_finish_h_i_d (void)
5579 int i;
5580 haifa_insn_data_t data;
5581 struct reg_use_data *use, *next;
5583 FOR_EACH_VEC_ELT (haifa_insn_data_def, h_i_d, i, data)
5585 if (data->reg_pressure != NULL)
5586 free (data->reg_pressure);
5587 for (use = data->reg_use_list; use != NULL; use = next)
5589 next = use->next_insn_use;
5590 free (use);
5593 VEC_free (haifa_insn_data_def, heap, h_i_d);
5596 /* Init data for the new insn INSN. */
5597 static void
5598 haifa_init_insn (rtx insn)
5600 gcc_assert (insn != NULL);
5602 sched_init_luids (NULL, NULL, NULL, insn);
5603 sched_extend_target ();
5604 sched_deps_init (false);
5605 haifa_init_h_i_d (NULL, NULL, NULL, insn);
5607 if (adding_bb_to_current_region_p)
5609 sd_init_insn (insn);
5611 /* Extend dependency caches by one element. */
5612 extend_dependency_caches (1, false);
5614 if (sched_pressure_p)
5615 init_insn_reg_pressure_info (insn);
5618 /* Init data for the new basic block BB which comes after AFTER. */
5619 static void
5620 haifa_init_only_bb (basic_block bb, basic_block after)
5622 gcc_assert (bb != NULL);
5624 sched_init_bbs ();
5626 if (common_sched_info->add_block)
5627 /* This changes only data structures of the front-end. */
5628 common_sched_info->add_block (bb, after);
5631 /* A generic version of sched_split_block (). */
5632 basic_block
5633 sched_split_block_1 (basic_block first_bb, rtx after)
5635 edge e;
5637 e = split_block (first_bb, after);
5638 gcc_assert (e->src == first_bb);
5640 /* sched_split_block emits note if *check == BB_END. Probably it
5641 is better to rip that note off. */
5643 return e->dest;
5646 /* A generic version of sched_create_empty_bb (). */
5647 basic_block
5648 sched_create_empty_bb_1 (basic_block after)
5650 return create_empty_bb (after);
5653 /* Insert PAT as an INSN into the schedule and update the necessary data
5654 structures to account for it. */
5656 sched_emit_insn (rtx pat)
5658 rtx insn = emit_insn_after (pat, last_scheduled_insn);
5659 last_scheduled_insn = insn;
5660 haifa_init_insn (insn);
5661 return insn;
5664 /* This function returns a candidate satisfying dispatch constraints from
5665 the ready list. */
5667 static rtx
5668 ready_remove_first_dispatch (struct ready_list *ready)
5670 int i;
5671 rtx insn = ready_element (ready, 0);
5673 if (ready->n_ready == 1
5674 || INSN_CODE (insn) < 0
5675 || !INSN_P (insn)
5676 || !active_insn_p (insn)
5677 || targetm.sched.dispatch (insn, FITS_DISPATCH_WINDOW))
5678 return ready_remove_first (ready);
5680 for (i = 1; i < ready->n_ready; i++)
5682 insn = ready_element (ready, i);
5684 if (INSN_CODE (insn) < 0
5685 || !INSN_P (insn)
5686 || !active_insn_p (insn))
5687 continue;
5689 if (targetm.sched.dispatch (insn, FITS_DISPATCH_WINDOW))
5691 /* Return ith element of ready. */
5692 insn = ready_remove (ready, i);
5693 return insn;
5697 if (targetm.sched.dispatch (NULL_RTX, DISPATCH_VIOLATION))
5698 return ready_remove_first (ready);
5700 for (i = 1; i < ready->n_ready; i++)
5702 insn = ready_element (ready, i);
5704 if (INSN_CODE (insn) < 0
5705 || !INSN_P (insn)
5706 || !active_insn_p (insn))
5707 continue;
5709 /* Return i-th element of ready. */
5710 if (targetm.sched.dispatch (insn, IS_CMP))
5711 return ready_remove (ready, i);
5714 return ready_remove_first (ready);
5717 /* Get number of ready insn in the ready list. */
5720 number_in_ready (void)
5722 return ready.n_ready;
5725 /* Get number of ready's in the ready list. */
5728 get_ready_element (int i)
5730 return ready_element (&ready, i);
5733 #endif /* INSN_SCHEDULING */