OSDN Git Service

* Makefile.in (c-decl.o): Depends on defaults.h.
[pf3gnuchains/gcc-fork.git] / gcc / haifa-sched.c
1 /* Instruction scheduling pass.
2    Copyright (C) 1992, 93-98, 1999 Free Software Foundation, Inc.
3    Contributed by Michael Tiemann (tiemann@cygnus.com) Enhanced by,
4    and currently maintained by, Jim Wilson (wilson@cygnus.com)
5
6    This file is part of GNU CC.
7
8    GNU CC is free software; you can redistribute it and/or modify it
9    under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2, or (at your option)
11    any later version.
12
13    GNU CC is distributed in the hope that it will be useful, but
14    WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16    General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with GNU CC; see the file COPYING.  If not, write to the Free
20    the Free Software Foundation, 59 Temple Place - Suite 330,
21    Boston, MA 02111-1307, USA.  */
22
23
24 /* Instruction scheduling pass.
25
26    This pass implements list scheduling within basic blocks.  It is
27    run twice: (1) after flow analysis, but before register allocation,
28    and (2) after register allocation.
29
30    The first run performs interblock scheduling, moving insns between
31    different blocks in the same "region", and the second runs only
32    basic block scheduling.
33
34    Interblock motions performed are useful motions and speculative
35    motions, including speculative loads.  Motions requiring code
36    duplication are not supported.  The identification of motion type
37    and the check for validity of speculative motions requires
38    construction and analysis of the function's control flow graph.
39    The scheduler works as follows:
40
41    We compute insn priorities based on data dependencies.  Flow
42    analysis only creates a fraction of the data-dependencies we must
43    observe: namely, only those dependencies which the combiner can be
44    expected to use.  For this pass, we must therefore create the
45    remaining dependencies we need to observe: register dependencies,
46    memory dependencies, dependencies to keep function calls in order,
47    and the dependence between a conditional branch and the setting of
48    condition codes are all dealt with here.
49
50    The scheduler first traverses the data flow graph, starting with
51    the last instruction, and proceeding to the first, assigning values
52    to insn_priority as it goes.  This sorts the instructions
53    topologically by data dependence.
54
55    Once priorities have been established, we order the insns using
56    list scheduling.  This works as follows: starting with a list of
57    all the ready insns, and sorted according to priority number, we
58    schedule the insn from the end of the list by placing its
59    predecessors in the list according to their priority order.  We
60    consider this insn scheduled by setting the pointer to the "end" of
61    the list to point to the previous insn.  When an insn has no
62    predecessors, we either queue it until sufficient time has elapsed
63    or add it to the ready list.  As the instructions are scheduled or
64    when stalls are introduced, the queue advances and dumps insns into
65    the ready list.  When all insns down to the lowest priority have
66    been scheduled, the critical path of the basic block has been made
67    as short as possible.  The remaining insns are then scheduled in
68    remaining slots.
69
70    Function unit conflicts are resolved during forward list scheduling
71    by tracking the time when each insn is committed to the schedule
72    and from that, the time the function units it uses must be free.
73    As insns on the ready list are considered for scheduling, those
74    that would result in a blockage of the already committed insns are
75    queued until no blockage will result.
76
77    The following list shows the order in which we want to break ties
78    among insns in the ready list:
79
80    1.  choose insn with the longest path to end of bb, ties
81    broken by
82    2.  choose insn with least contribution to register pressure,
83    ties broken by
84    3.  prefer in-block upon interblock motion, ties broken by
85    4.  prefer useful upon speculative motion, ties broken by
86    5.  choose insn with largest control flow probability, ties
87    broken by
88    6.  choose insn with the least dependences upon the previously
89    scheduled insn, or finally
90    7   choose the insn which has the most insns dependent on it.
91    8.  choose insn with lowest UID.
92
93    Memory references complicate matters.  Only if we can be certain
94    that memory references are not part of the data dependency graph
95    (via true, anti, or output dependence), can we move operations past
96    memory references.  To first approximation, reads can be done
97    independently, while writes introduce dependencies.  Better
98    approximations will yield fewer dependencies.
99
100    Before reload, an extended analysis of interblock data dependences
101    is required for interblock scheduling.  This is performed in
102    compute_block_backward_dependences ().
103
104    Dependencies set up by memory references are treated in exactly the
105    same way as other dependencies, by using LOG_LINKS backward
106    dependences.  LOG_LINKS are translated into INSN_DEPEND forward
107    dependences for the purpose of forward list scheduling.
108
109    Having optimized the critical path, we may have also unduly
110    extended the lifetimes of some registers.  If an operation requires
111    that constants be loaded into registers, it is certainly desirable
112    to load those constants as early as necessary, but no earlier.
113    I.e., it will not do to load up a bunch of registers at the
114    beginning of a basic block only to use them at the end, if they
115    could be loaded later, since this may result in excessive register
116    utilization.
117
118    Note that since branches are never in basic blocks, but only end
119    basic blocks, this pass will not move branches.  But that is ok,
120    since we can use GNU's delayed branch scheduling pass to take care
121    of this case.
122
123    Also note that no further optimizations based on algebraic
124    identities are performed, so this pass would be a good one to
125    perform instruction splitting, such as breaking up a multiply
126    instruction into shifts and adds where that is profitable.
127
128    Given the memory aliasing analysis that this pass should perform,
129    it should be possible to remove redundant stores to memory, and to
130    load values from registers instead of hitting memory.
131
132    Before reload, speculative insns are moved only if a 'proof' exists
133    that no exception will be caused by this, and if no live registers
134    exist that inhibit the motion (live registers constraints are not
135    represented by data dependence edges).
136
137    This pass must update information that subsequent passes expect to
138    be correct.  Namely: reg_n_refs, reg_n_sets, reg_n_deaths,
139    reg_n_calls_crossed, and reg_live_length.  Also, BLOCK_HEAD,
140    BLOCK_END.
141
142    The information in the line number notes is carefully retained by
143    this pass.  Notes that refer to the starting and ending of
144    exception regions are also carefully retained by this pass.  All
145    other NOTE insns are grouped in their same relative order at the
146    beginning of basic blocks and regions that have been scheduled.
147
148    The main entry point for this pass is schedule_insns(), called for
149    each function.  The work of the scheduler is organized in three
150    levels: (1) function level: insns are subject to splitting,
151    control-flow-graph is constructed, regions are computed (after
152    reload, each region is of one block), (2) region level: control
153    flow graph attributes required for interblock scheduling are
154    computed (dominators, reachability, etc.), data dependences and
155    priorities are computed, and (3) block level: insns in the block
156    are actually scheduled.  */
157 \f
158 #include "config.h"
159 #include "system.h"
160 #include "toplev.h"
161 #include "rtl.h"
162 #include "basic-block.h"
163 #include "regs.h"
164 #include "hard-reg-set.h"
165 #include "flags.h"
166 #include "insn-config.h"
167 #include "insn-attr.h"
168 #include "except.h"
169 #include "toplev.h"
170 #include "recog.h"
171
172 extern char *reg_known_equiv_p;
173 extern rtx *reg_known_value;
174
175 #ifdef INSN_SCHEDULING
176
177 /* target_units bitmask has 1 for each unit in the cpu.  It should be
178    possible to compute this variable from the machine description.
179    But currently it is computed by examinning the insn list.  Since
180    this is only needed for visualization, it seems an acceptable
181    solution.  (For understanding the mapping of bits to units, see
182    definition of function_units[] in "insn-attrtab.c") */
183
184 static int target_units = 0;
185
186 /* issue_rate is the number of insns that can be scheduled in the same
187    machine cycle.  It can be defined in the config/mach/mach.h file,
188    otherwise we set it to 1.  */
189
190 static int issue_rate;
191
192 #ifndef ISSUE_RATE
193 #define ISSUE_RATE 1
194 #endif
195
196 /* sched-verbose controls the amount of debugging output the
197    scheduler prints.  It is controlled by -fsched-verbose-N:
198    N>0 and no -DSR : the output is directed to stderr.
199    N>=10 will direct the printouts to stderr (regardless of -dSR).
200    N=1: same as -dSR.
201    N=2: bb's probabilities, detailed ready list info, unit/insn info.
202    N=3: rtl at abort point, control-flow, regions info.
203    N=5: dependences info.  */
204
205 #define MAX_RGN_BLOCKS 10
206 #define MAX_RGN_INSNS 100
207
208 static int sched_verbose_param = 0;
209 static int sched_verbose = 0;
210
211 /* nr_inter/spec counts interblock/speculative motion for the function */
212 static int nr_inter, nr_spec;
213
214
215 /* debugging file. all printouts are sent to dump, which is always set,
216    either to stderr, or to the dump listing file (-dRS).  */
217 static FILE *dump = 0;
218
219 /* fix_sched_param() is called from toplev.c upon detection
220    of the -fsched-***-N options.  */
221
222 void
223 fix_sched_param (param, val)
224      char *param, *val;
225 {
226   if (!strcmp (param, "verbose"))
227     sched_verbose_param = atoi (val);
228   else
229     warning ("fix_sched_param: unknown param: %s", param);
230 }
231
232
233 /* Arrays set up by scheduling for the same respective purposes as
234    similar-named arrays set up by flow analysis.  We work with these
235    arrays during the scheduling pass so we can compare values against
236    unscheduled code.
237
238    Values of these arrays are copied at the end of this pass into the
239    arrays set up by flow analysis.  */
240 static int *sched_reg_n_calls_crossed;
241 static int *sched_reg_live_length;
242 static int *sched_reg_basic_block;
243
244 /* We need to know the current block number during the post scheduling
245    update of live register information so that we can also update
246    REG_BASIC_BLOCK if a register changes blocks.  */
247 static int current_block_num;
248
249 /* Element N is the next insn that sets (hard or pseudo) register
250    N within the current basic block; or zero, if there is no
251    such insn.  Needed for new registers which may be introduced
252    by splitting insns.  */
253 static rtx *reg_last_uses;
254 static rtx *reg_last_sets;
255 static rtx *reg_last_clobbers;
256 static regset reg_pending_sets;
257 static regset reg_pending_clobbers;
258 static int reg_pending_sets_all;
259
260 /* Vector indexed by INSN_UID giving the original ordering of the insns.  */
261 static int *insn_luid;
262 #define INSN_LUID(INSN) (insn_luid[INSN_UID (INSN)])
263
264 /* Vector indexed by INSN_UID giving each instruction a priority.  */
265 static int *insn_priority;
266 #define INSN_PRIORITY(INSN) (insn_priority[INSN_UID (INSN)])
267
268 static short *insn_costs;
269 #define INSN_COST(INSN) insn_costs[INSN_UID (INSN)]
270
271 /* Vector indexed by INSN_UID giving an encoding of the function units
272    used.  */
273 static short *insn_units;
274 #define INSN_UNIT(INSN) insn_units[INSN_UID (INSN)]
275
276 /* Vector indexed by INSN_UID giving each instruction a register-weight.
277    This weight is an estimation of the insn contribution to registers pressure.  */
278 static int *insn_reg_weight;
279 #define INSN_REG_WEIGHT(INSN) (insn_reg_weight[INSN_UID (INSN)])
280
281 /* Vector indexed by INSN_UID giving list of insns which
282    depend upon INSN.  Unlike LOG_LINKS, it represents forward dependences.  */
283 static rtx *insn_depend;
284 #define INSN_DEPEND(INSN) insn_depend[INSN_UID (INSN)]
285
286 /* Vector indexed by INSN_UID. Initialized to the number of incoming
287    edges in forward dependence graph (= number of LOG_LINKS).  As
288    scheduling procedes, dependence counts are decreased.  An
289    instruction moves to the ready list when its counter is zero.  */
290 static int *insn_dep_count;
291 #define INSN_DEP_COUNT(INSN) (insn_dep_count[INSN_UID (INSN)])
292
293 /* Vector indexed by INSN_UID giving an encoding of the blockage range
294    function.  The unit and the range are encoded.  */
295 static unsigned int *insn_blockage;
296 #define INSN_BLOCKAGE(INSN) insn_blockage[INSN_UID (INSN)]
297 #define UNIT_BITS 5
298 #define BLOCKAGE_MASK ((1 << BLOCKAGE_BITS) - 1)
299 #define ENCODE_BLOCKAGE(U, R)                           \
300 (((U) << BLOCKAGE_BITS                                  \
301   | MIN_BLOCKAGE_COST (R)) << BLOCKAGE_BITS             \
302  | MAX_BLOCKAGE_COST (R))
303 #define UNIT_BLOCKED(B) ((B) >> (2 * BLOCKAGE_BITS))
304 #define BLOCKAGE_RANGE(B)                                                \
305   (((((B) >> BLOCKAGE_BITS) & BLOCKAGE_MASK) << (HOST_BITS_PER_INT / 2)) \
306    | ((B) & BLOCKAGE_MASK))
307
308 /* Encodings of the `<name>_unit_blockage_range' function.  */
309 #define MIN_BLOCKAGE_COST(R) ((R) >> (HOST_BITS_PER_INT / 2))
310 #define MAX_BLOCKAGE_COST(R) ((R) & ((1 << (HOST_BITS_PER_INT / 2)) - 1))
311
312 #define DONE_PRIORITY   -1
313 #define MAX_PRIORITY    0x7fffffff
314 #define TAIL_PRIORITY   0x7ffffffe
315 #define LAUNCH_PRIORITY 0x7f000001
316 #define DONE_PRIORITY_P(INSN) (INSN_PRIORITY (INSN) < 0)
317 #define LOW_PRIORITY_P(INSN) ((INSN_PRIORITY (INSN) & 0x7f000000) == 0)
318
319 /* Vector indexed by INSN_UID giving number of insns referring to this insn.  */
320 static int *insn_ref_count;
321 #define INSN_REF_COUNT(INSN) (insn_ref_count[INSN_UID (INSN)])
322
323 /* Vector indexed by INSN_UID giving line-number note in effect for each
324    insn.  For line-number notes, this indicates whether the note may be
325    reused.  */
326 static rtx *line_note;
327 #define LINE_NOTE(INSN) (line_note[INSN_UID (INSN)])
328
329 /* Vector indexed by basic block number giving the starting line-number
330    for each basic block.  */
331 static rtx *line_note_head;
332
333 /* List of important notes we must keep around.  This is a pointer to the
334    last element in the list.  */
335 static rtx note_list;
336
337 /* Regsets telling whether a given register is live or dead before the last
338    scheduled insn.  Must scan the instructions once before scheduling to
339    determine what registers are live or dead at the end of the block.  */
340 static regset bb_live_regs;
341
342 /* Regset telling whether a given register is live after the insn currently
343    being scheduled.  Before processing an insn, this is equal to bb_live_regs
344    above.  This is used so that we can find registers that are newly born/dead
345    after processing an insn.  */
346 static regset old_live_regs;
347
348 /* The chain of REG_DEAD notes.  REG_DEAD notes are removed from all insns
349    during the initial scan and reused later.  If there are not exactly as
350    many REG_DEAD notes in the post scheduled code as there were in the
351    prescheduled code then we trigger an abort because this indicates a bug.  */
352 static rtx dead_notes;
353
354 /* Queues, etc.  */
355
356 /* An instruction is ready to be scheduled when all insns preceding it
357    have already been scheduled.  It is important to ensure that all
358    insns which use its result will not be executed until its result
359    has been computed.  An insn is maintained in one of four structures:
360
361    (P) the "Pending" set of insns which cannot be scheduled until
362    their dependencies have been satisfied.
363    (Q) the "Queued" set of insns that can be scheduled when sufficient
364    time has passed.
365    (R) the "Ready" list of unscheduled, uncommitted insns.
366    (S) the "Scheduled" list of insns.
367
368    Initially, all insns are either "Pending" or "Ready" depending on
369    whether their dependencies are satisfied.
370
371    Insns move from the "Ready" list to the "Scheduled" list as they
372    are committed to the schedule.  As this occurs, the insns in the
373    "Pending" list have their dependencies satisfied and move to either
374    the "Ready" list or the "Queued" set depending on whether
375    sufficient time has passed to make them ready.  As time passes,
376    insns move from the "Queued" set to the "Ready" list.  Insns may
377    move from the "Ready" list to the "Queued" set if they are blocked
378    due to a function unit conflict.
379
380    The "Pending" list (P) are the insns in the INSN_DEPEND of the unscheduled
381    insns, i.e., those that are ready, queued, and pending.
382    The "Queued" set (Q) is implemented by the variable `insn_queue'.
383    The "Ready" list (R) is implemented by the variables `ready' and
384    `n_ready'.
385    The "Scheduled" list (S) is the new insn chain built by this pass.
386
387    The transition (R->S) is implemented in the scheduling loop in
388    `schedule_block' when the best insn to schedule is chosen.
389    The transition (R->Q) is implemented in `queue_insn' when an
390    insn is found to have a function unit conflict with the already
391    committed insns.
392    The transitions (P->R and P->Q) are implemented in `schedule_insn' as
393    insns move from the ready list to the scheduled list.
394    The transition (Q->R) is implemented in 'queue_to_insn' as time
395    passes or stalls are introduced.  */
396
397 /* Implement a circular buffer to delay instructions until sufficient
398    time has passed.  INSN_QUEUE_SIZE is a power of two larger than
399    MAX_BLOCKAGE and MAX_READY_COST computed by genattr.c.  This is the
400    longest time an isnsn may be queued.  */
401 static rtx insn_queue[INSN_QUEUE_SIZE];
402 static int q_ptr = 0;
403 static int q_size = 0;
404 #define NEXT_Q(X) (((X)+1) & (INSN_QUEUE_SIZE-1))
405 #define NEXT_Q_AFTER(X, C) (((X)+C) & (INSN_QUEUE_SIZE-1))
406
407 /* Vector indexed by INSN_UID giving the minimum clock tick at which
408    the insn becomes ready.  This is used to note timing constraints for
409    insns in the pending list.  */
410 static int *insn_tick;
411 #define INSN_TICK(INSN) (insn_tick[INSN_UID (INSN)])
412
413 /* Data structure for keeping track of register information
414    during that register's life.  */
415
416 struct sometimes
417   {
418     int regno;
419     int live_length;
420     int calls_crossed;
421   };
422
423 /* Forward declarations.  */
424 static void add_dependence PROTO ((rtx, rtx, enum reg_note));
425 static void remove_dependence PROTO ((rtx, rtx));
426 static rtx find_insn_list PROTO ((rtx, rtx));
427 static int insn_unit PROTO ((rtx));
428 static unsigned int blockage_range PROTO ((int, rtx));
429 static void clear_units PROTO ((void));
430 static int actual_hazard_this_instance PROTO ((int, int, rtx, int, int));
431 static void schedule_unit PROTO ((int, rtx, int));
432 static int actual_hazard PROTO ((int, rtx, int, int));
433 static int potential_hazard PROTO ((int, rtx, int));
434 static int insn_cost PROTO ((rtx, rtx, rtx));
435 static int priority PROTO ((rtx));
436 static void free_pending_lists PROTO ((void));
437 static void add_insn_mem_dependence PROTO ((rtx *, rtx *, rtx, rtx));
438 static void flush_pending_lists PROTO ((rtx, int));
439 static void sched_analyze_1 PROTO ((rtx, rtx));
440 static void sched_analyze_2 PROTO ((rtx, rtx));
441 static void sched_analyze_insn PROTO ((rtx, rtx, rtx));
442 static void sched_analyze PROTO ((rtx, rtx));
443 static void sched_note_set PROTO ((rtx, int));
444 static int rank_for_schedule PROTO ((const GENERIC_PTR, const GENERIC_PTR));
445 static void swap_sort PROTO ((rtx *, int));
446 static void queue_insn PROTO ((rtx, int));
447 static int schedule_insn PROTO ((rtx, rtx *, int, int));
448 static void create_reg_dead_note PROTO ((rtx, rtx));
449 static void attach_deaths PROTO ((rtx, rtx, int));
450 static void attach_deaths_insn PROTO ((rtx));
451 static int new_sometimes_live PROTO ((struct sometimes *, int, int));
452 static void finish_sometimes_live PROTO ((struct sometimes *, int));
453 static int schedule_block PROTO ((int, int));
454 static void split_hard_reg_notes PROTO ((rtx, rtx, rtx));
455 static void new_insn_dead_notes PROTO ((rtx, rtx, rtx, rtx));
456 static void update_n_sets PROTO ((rtx, int));
457 static char *safe_concat PROTO ((char *, char *, char *));
458 static int insn_issue_delay PROTO ((rtx));
459 static int birthing_insn_p PROTO ((rtx));
460 static void adjust_priority PROTO ((rtx));
461
462 /* Mapping of insns to their original block prior to scheduling.  */
463 static int *insn_orig_block;
464 #define INSN_BLOCK(insn) (insn_orig_block[INSN_UID (insn)])
465
466 /* Some insns (e.g. call) are not allowed to move across blocks.  */
467 static char *cant_move;
468 #define CANT_MOVE(insn) (cant_move[INSN_UID (insn)])
469
470 /* Control flow graph edges are kept in circular lists.  */
471 typedef struct
472   {
473     int from_block;
474     int to_block;
475     int next_in;
476     int next_out;
477   }
478 haifa_edge;
479 static haifa_edge *edge_table;
480
481 #define NEXT_IN(edge) (edge_table[edge].next_in)
482 #define NEXT_OUT(edge) (edge_table[edge].next_out)
483 #define FROM_BLOCK(edge) (edge_table[edge].from_block)
484 #define TO_BLOCK(edge) (edge_table[edge].to_block)
485
486 /* Number of edges in the control flow graph.  (in fact larger than
487    that by 1, since edge 0 is unused.) */
488 static int nr_edges;
489
490 /* Circular list of incoming/outgoing edges of a block */
491 static int *in_edges;
492 static int *out_edges;
493
494 #define IN_EDGES(block) (in_edges[block])
495 #define OUT_EDGES(block) (out_edges[block])
496
497 /* List of labels which cannot be deleted, needed for control
498    flow graph construction.  */
499 extern rtx forced_labels;
500
501
502 static int is_cfg_nonregular PROTO ((void));
503 static int build_control_flow PROTO ((int_list_ptr *, int_list_ptr *,
504                                       int *, int *));
505 static void new_edge PROTO ((int, int));
506
507
508 /* A region is the main entity for interblock scheduling: insns
509    are allowed to move between blocks in the same region, along
510    control flow graph edges, in the 'up' direction.  */
511 typedef struct
512   {
513     int rgn_nr_blocks;          /* number of blocks in region */
514     int rgn_blocks;             /* blocks in the region (actually index in rgn_bb_table) */
515   }
516 region;
517
518 /* Number of regions in the procedure */
519 static int nr_regions;
520
521 /* Table of region descriptions */
522 static region *rgn_table;
523
524 /* Array of lists of regions' blocks */
525 static int *rgn_bb_table;
526
527 /* Topological order of blocks in the region (if b2 is reachable from
528    b1, block_to_bb[b2] > block_to_bb[b1]).
529    Note: A basic block is always referred to by either block or b,
530    while its topological order name (in the region) is refered to by
531    bb.
532  */
533 static int *block_to_bb;
534
535 /* The number of the region containing a block.  */
536 static int *containing_rgn;
537
538 #define RGN_NR_BLOCKS(rgn) (rgn_table[rgn].rgn_nr_blocks)
539 #define RGN_BLOCKS(rgn) (rgn_table[rgn].rgn_blocks)
540 #define BLOCK_TO_BB(block) (block_to_bb[block])
541 #define CONTAINING_RGN(block) (containing_rgn[block])
542
543 void debug_regions PROTO ((void));
544 static void find_single_block_region PROTO ((void));
545 static void find_rgns PROTO ((int_list_ptr *, int_list_ptr *,
546                               int *, int *, sbitmap *));
547 static int too_large PROTO ((int, int *, int *));
548
549 extern void debug_live PROTO ((int, int));
550
551 /* Blocks of the current region being scheduled.  */
552 static int current_nr_blocks;
553 static int current_blocks;
554
555 /* The mapping from bb to block */
556 #define BB_TO_BLOCK(bb) (rgn_bb_table[current_blocks + (bb)])
557
558
559 /* Bit vectors and bitset operations are needed for computations on
560    the control flow graph.  */
561
562 typedef unsigned HOST_WIDE_INT *bitset;
563 typedef struct
564   {
565     int *first_member;          /* pointer to the list start in bitlst_table.  */
566     int nr_members;             /* the number of members of the bit list.     */
567   }
568 bitlst;
569
570 static int bitlst_table_last;
571 static int bitlst_table_size;
572 static int *bitlst_table;
573
574 static char bitset_member PROTO ((bitset, int, int));
575 static void extract_bitlst PROTO ((bitset, int, bitlst *));
576
577 /* target info declarations.
578
579    The block currently being scheduled is referred to as the "target" block,
580    while other blocks in the region from which insns can be moved to the
581    target are called "source" blocks.  The candidate structure holds info
582    about such sources: are they valid?  Speculative?  Etc.  */
583 typedef bitlst bblst;
584 typedef struct
585   {
586     char is_valid;
587     char is_speculative;
588     int src_prob;
589     bblst split_bbs;
590     bblst update_bbs;
591   }
592 candidate;
593
594 static candidate *candidate_table;
595
596 /* A speculative motion requires checking live information on the path
597    from 'source' to 'target'.  The split blocks are those to be checked.
598    After a speculative motion, live information should be modified in
599    the 'update' blocks.
600
601    Lists of split and update blocks for  each candidate of the current
602    target  are  in  array bblst_table */
603 static int *bblst_table, bblst_size, bblst_last;
604
605 #define IS_VALID(src) ( candidate_table[src].is_valid )
606 #define IS_SPECULATIVE(src) ( candidate_table[src].is_speculative )
607 #define SRC_PROB(src) ( candidate_table[src].src_prob )
608
609 /* The bb being currently scheduled.  */
610 static int target_bb;
611
612 /* List of edges.  */
613 typedef bitlst edgelst;
614
615 /* target info functions */
616 static void split_edges PROTO ((int, int, edgelst *));
617 static void compute_trg_info PROTO ((int));
618 void debug_candidate PROTO ((int));
619 void debug_candidates PROTO ((int));
620
621
622 /* Bit-set of bbs, where bit 'i' stands for bb 'i'.  */
623 typedef bitset bbset;
624
625 /* Number of words of the bbset.  */
626 static int bbset_size;
627
628 /* Dominators array: dom[i] contains the bbset of dominators of
629    bb i in the region.  */
630 static bbset *dom;
631
632 /* bb 0 is the only region entry */
633 #define IS_RGN_ENTRY(bb) (!bb)
634
635 /* Is bb_src dominated by bb_trg.  */
636 #define IS_DOMINATED(bb_src, bb_trg)                                 \
637 ( bitset_member (dom[bb_src], bb_trg, bbset_size) )
638
639 /* Probability: Prob[i] is a float in [0, 1] which is the probability
640    of bb i relative to the region entry.  */
641 static float *prob;
642
643 /*  The probability of bb_src, relative to bb_trg.  Note, that while the
644    'prob[bb]' is a float in [0, 1], this macro returns an integer
645    in [0, 100].  */
646 #define GET_SRC_PROB(bb_src, bb_trg) ((int) (100.0 * (prob[bb_src] / \
647                                                       prob[bb_trg])))
648
649 /* Bit-set of edges, where bit i stands for edge i.  */
650 typedef bitset edgeset;
651
652 /* Number of edges in the region.  */
653 static int rgn_nr_edges;
654
655 /* Array of size rgn_nr_edges.    */
656 static int *rgn_edges;
657
658 /* Number of words in an edgeset.    */
659 static int edgeset_size;
660
661 /* Mapping from each edge in the graph to its number in the rgn.  */
662 static int *edge_to_bit;
663 #define EDGE_TO_BIT(edge) (edge_to_bit[edge])
664
665 /* The split edges of a source bb is different for each target
666    bb.  In order to compute this efficiently, the 'potential-split edges'
667    are computed for each bb prior to scheduling a region.  This is actually
668    the split edges of each bb relative to the region entry.
669
670    pot_split[bb] is the set of potential split edges of bb.  */
671 static edgeset *pot_split;
672
673 /* For every bb, a set of its ancestor edges.  */
674 static edgeset *ancestor_edges;
675
676 static void compute_dom_prob_ps PROTO ((int));
677
678 #define ABS_VALUE(x) (((x)<0)?(-(x)):(x))
679 #define INSN_PROBABILITY(INSN) (SRC_PROB (BLOCK_TO_BB (INSN_BLOCK (INSN))))
680 #define IS_SPECULATIVE_INSN(INSN) (IS_SPECULATIVE (BLOCK_TO_BB (INSN_BLOCK (INSN))))
681 #define INSN_BB(INSN) (BLOCK_TO_BB (INSN_BLOCK (INSN)))
682
683 /* parameters affecting the decision of rank_for_schedule() */
684 #define MIN_DIFF_PRIORITY 2
685 #define MIN_PROBABILITY 40
686 #define MIN_PROB_DIFF 10
687
688 /* speculative scheduling functions */
689 static int check_live_1 PROTO ((int, rtx));
690 static void update_live_1 PROTO ((int, rtx));
691 static int check_live PROTO ((rtx, int));
692 static void update_live PROTO ((rtx, int));
693 static void set_spec_fed PROTO ((rtx));
694 static int is_pfree PROTO ((rtx, int, int));
695 static int find_conditional_protection PROTO ((rtx, int));
696 static int is_conditionally_protected PROTO ((rtx, int, int));
697 static int may_trap_exp PROTO ((rtx, int));
698 static int haifa_classify_insn PROTO ((rtx));
699 static int is_prisky PROTO ((rtx, int, int));
700 static int is_exception_free PROTO ((rtx, int, int));
701
702 static char find_insn_mem_list PROTO ((rtx, rtx, rtx, rtx));
703 static void compute_block_forward_dependences PROTO ((int));
704 static void init_rgn_data_dependences PROTO ((int));
705 static void add_branch_dependences PROTO ((rtx, rtx));
706 static void compute_block_backward_dependences PROTO ((int));
707 void debug_dependencies PROTO ((void));
708
709 /* Notes handling mechanism:
710    =========================
711    Generally, NOTES are saved before scheduling and restored after scheduling.
712    The scheduler distinguishes between three types of notes:
713
714    (1) LINE_NUMBER notes, generated and used for debugging.  Here,
715    before scheduling a region, a pointer to the LINE_NUMBER note is
716    added to the insn following it (in save_line_notes()), and the note
717    is removed (in rm_line_notes() and unlink_line_notes()).  After
718    scheduling the region, this pointer is used for regeneration of
719    the LINE_NUMBER note (in restore_line_notes()).
720
721    (2) LOOP_BEGIN, LOOP_END, SETJMP, EHREGION_BEG, EHREGION_END notes:
722    Before scheduling a region, a pointer to the note is added to the insn
723    that follows or precedes it.  (This happens as part of the data dependence
724    computation).  After scheduling an insn, the pointer contained in it is
725    used for regenerating the corresponding note (in reemit_notes).
726
727    (3) All other notes (e.g. INSN_DELETED):  Before scheduling a block,
728    these notes are put in a list (in rm_other_notes() and
729    unlink_other_notes ()).  After scheduling the block, these notes are
730    inserted at the beginning of the block (in schedule_block()).  */
731
732 static rtx unlink_other_notes PROTO ((rtx, rtx));
733 static rtx unlink_line_notes PROTO ((rtx, rtx));
734 static void rm_line_notes PROTO ((int));
735 static void save_line_notes PROTO ((int));
736 static void restore_line_notes PROTO ((int));
737 static void rm_redundant_line_notes PROTO ((void));
738 static void rm_other_notes PROTO ((rtx, rtx));
739 static rtx reemit_notes PROTO ((rtx, rtx));
740
741 static void get_block_head_tail PROTO ((int, rtx *, rtx *));
742
743 static void find_pre_sched_live PROTO ((int));
744 static void find_post_sched_live PROTO ((int));
745 static void update_reg_usage PROTO ((void));
746 static int queue_to_ready PROTO ((rtx [], int));
747
748 static void debug_ready_list PROTO ((rtx[], int));
749 static void init_target_units PROTO ((void));
750 static void insn_print_units PROTO ((rtx));
751 static int get_visual_tbl_length PROTO ((void));
752 static void init_block_visualization PROTO ((void));
753 static void print_block_visualization PROTO ((int, char *));
754 static void visualize_scheduled_insns PROTO ((int, int));
755 static void visualize_no_unit PROTO ((rtx));
756 static void visualize_stall_cycles PROTO ((int, int));
757 static void print_exp PROTO ((char *, rtx, int));
758 static void print_value PROTO ((char *, rtx, int));
759 static void print_pattern PROTO ((char *, rtx, int));
760 static void print_insn PROTO ((char *, rtx, int));
761 void debug_reg_vector PROTO ((regset));
762
763 static rtx move_insn1 PROTO ((rtx, rtx));
764 static rtx move_insn PROTO ((rtx, rtx));
765 static rtx group_leader PROTO ((rtx));
766 static int set_priorities PROTO ((int));
767 static void init_rtx_vector PROTO ((rtx **, rtx *, int, int));
768 static void schedule_region PROTO ((int));
769
770 #endif /* INSN_SCHEDULING */
771 \f
772 #define SIZE_FOR_MODE(X) (GET_MODE_SIZE (GET_MODE (X)))
773
774 /* Helper functions for instruction scheduling.  */
775
776 /* An INSN_LIST containing all INSN_LISTs allocated but currently unused.  */
777 static rtx unused_insn_list;
778
779 /* An EXPR_LIST containing all EXPR_LISTs allocated but currently unused.  */
780 static rtx unused_expr_list;
781
782 static void free_list PROTO ((rtx *, rtx *));
783 static rtx alloc_INSN_LIST PROTO ((rtx, rtx));
784 static rtx alloc_EXPR_LIST PROTO ((int, rtx, rtx));
785
786 static void
787 free_list (listp, unused_listp)
788      rtx *listp, *unused_listp;
789 {
790   register rtx link, prev_link;
791
792   if (*listp == 0)
793     return;
794
795   prev_link = *listp;
796   link = XEXP (prev_link, 1);
797
798   while (link)
799     {
800       prev_link = link;
801       link = XEXP (link, 1);
802     }
803
804   XEXP (prev_link, 1) = *unused_listp;
805   *unused_listp = *listp;
806   *listp = 0;
807 }
808
809 static rtx
810 alloc_INSN_LIST (val, next)
811      rtx val, next;
812 {
813   rtx r;
814
815   if (unused_insn_list)
816     {
817       r = unused_insn_list;
818       unused_insn_list = XEXP (r, 1);
819       XEXP (r, 0) = val;
820       XEXP (r, 1) = next;
821       PUT_REG_NOTE_KIND (r, VOIDmode);
822     }
823   else
824     r = gen_rtx_INSN_LIST (VOIDmode, val, next);
825
826   return r;
827 }
828
829 static rtx
830 alloc_EXPR_LIST (kind, val, next)
831      int kind;
832      rtx val, next;
833 {
834   rtx r;
835
836   if (unused_expr_list)
837     {
838       r = unused_expr_list;
839       unused_expr_list = XEXP (r, 1);
840       XEXP (r, 0) = val;
841       XEXP (r, 1) = next;
842       PUT_REG_NOTE_KIND (r, kind);
843     }
844   else
845     r = gen_rtx_EXPR_LIST (kind, val, next);
846
847   return r;
848 }
849
850 /* Add ELEM wrapped in an INSN_LIST with reg note kind DEP_TYPE to the
851    LOG_LINKS of INSN, if not already there.  DEP_TYPE indicates the type
852    of dependence that this link represents.  */
853
854 static void
855 add_dependence (insn, elem, dep_type)
856      rtx insn;
857      rtx elem;
858      enum reg_note dep_type;
859 {
860   rtx link, next;
861
862   /* Don't depend an insn on itself.  */
863   if (insn == elem)
864     return;
865
866   /* We can get a dependency on deleted insns due to optimizations in
867      the register allocation and reloading or due to splitting.  Any
868      such dependency is useless and can be ignored.  */
869   if (GET_CODE (elem) == NOTE)
870     return;
871         
872   /* If elem is part of a sequence that must be scheduled together, then
873      make the dependence point to the last insn of the sequence.
874      When HAVE_cc0, it is possible for NOTEs to exist between users and
875      setters of the condition codes, so we must skip past notes here.
876      Otherwise, NOTEs are impossible here.  */
877
878   next = NEXT_INSN (elem);
879
880 #ifdef HAVE_cc0
881   while (next && GET_CODE (next) == NOTE)
882     next = NEXT_INSN (next);
883 #endif
884
885   if (next && SCHED_GROUP_P (next)
886       && GET_CODE (next) != CODE_LABEL)
887     {
888       /* Notes will never intervene here though, so don't bother checking
889          for them.  */
890       /* We must reject CODE_LABELs, so that we don't get confused by one
891          that has LABEL_PRESERVE_P set, which is represented by the same
892          bit in the rtl as SCHED_GROUP_P.  A CODE_LABEL can never be
893          SCHED_GROUP_P.  */
894       while (NEXT_INSN (next) && SCHED_GROUP_P (NEXT_INSN (next))
895              && GET_CODE (NEXT_INSN (next)) != CODE_LABEL)
896         next = NEXT_INSN (next);
897
898       /* Again, don't depend an insn on itself.  */
899       if (insn == next)
900         return;
901
902       /* Make the dependence to NEXT, the last insn of the group, instead
903          of the original ELEM.  */
904       elem = next;
905     }
906
907 #ifdef INSN_SCHEDULING
908   /* (This code is guarded by INSN_SCHEDULING, otherwise INSN_BB is undefined.)
909      No need for interblock dependences with calls, since
910      calls are not moved between blocks.   Note: the edge where
911      elem is a CALL is still required.  */
912   if (GET_CODE (insn) == CALL_INSN
913       && (INSN_BB (elem) != INSN_BB (insn)))
914     return;
915
916 #endif
917
918   /* Check that we don't already have this dependence.  */
919   for (link = LOG_LINKS (insn); link; link = XEXP (link, 1))
920     if (XEXP (link, 0) == elem)
921       {
922         /* If this is a more restrictive type of dependence than the existing
923            one, then change the existing dependence to this type.  */
924         if ((int) dep_type < (int) REG_NOTE_KIND (link))
925           PUT_REG_NOTE_KIND (link, dep_type);
926         return;
927       }
928   /* Might want to check one level of transitivity to save conses.  */
929
930   link = alloc_INSN_LIST (elem, LOG_LINKS (insn));
931   LOG_LINKS (insn) = link;
932
933   /* Insn dependency, not data dependency.  */
934   PUT_REG_NOTE_KIND (link, dep_type);
935 }
936
937 /* Remove ELEM wrapped in an INSN_LIST from the LOG_LINKS
938    of INSN.  Abort if not found.  */
939
940 static void
941 remove_dependence (insn, elem)
942      rtx insn;
943      rtx elem;
944 {
945   rtx prev, link, next;
946   int found = 0;
947
948   for (prev = 0, link = LOG_LINKS (insn); link; link = next)
949     {
950       next = XEXP (link, 1);
951       if (XEXP (link, 0) == elem)
952         {
953           if (prev)
954             XEXP (prev, 1) = next;
955           else
956             LOG_LINKS (insn) = next;
957
958           XEXP (link, 1) = unused_insn_list;
959           unused_insn_list = link;
960
961           found = 1;
962         }
963       else
964         prev = link;
965     }
966
967   if (!found)
968     abort ();
969   return;
970 }
971 \f
972 #ifndef INSN_SCHEDULING
973 void
974 schedule_insns (dump_file)
975      FILE *dump_file;
976 {
977 }
978 #else
979 #ifndef __GNUC__
980 #define __inline
981 #endif
982
983 #ifndef HAIFA_INLINE
984 #define HAIFA_INLINE __inline
985 #endif
986
987 /* Computation of memory dependencies.  */
988
989 /* The *_insns and *_mems are paired lists.  Each pending memory operation
990    will have a pointer to the MEM rtx on one list and a pointer to the
991    containing insn on the other list in the same place in the list.  */
992
993 /* We can't use add_dependence like the old code did, because a single insn
994    may have multiple memory accesses, and hence needs to be on the list
995    once for each memory access.  Add_dependence won't let you add an insn
996    to a list more than once.  */
997
998 /* An INSN_LIST containing all insns with pending read operations.  */
999 static rtx pending_read_insns;
1000
1001 /* An EXPR_LIST containing all MEM rtx's which are pending reads.  */
1002 static rtx pending_read_mems;
1003
1004 /* An INSN_LIST containing all insns with pending write operations.  */
1005 static rtx pending_write_insns;
1006
1007 /* An EXPR_LIST containing all MEM rtx's which are pending writes.  */
1008 static rtx pending_write_mems;
1009
1010 /* Indicates the combined length of the two pending lists.  We must prevent
1011    these lists from ever growing too large since the number of dependencies
1012    produced is at least O(N*N), and execution time is at least O(4*N*N), as
1013    a function of the length of these pending lists.  */
1014
1015 static int pending_lists_length;
1016
1017 /* The last insn upon which all memory references must depend.
1018    This is an insn which flushed the pending lists, creating a dependency
1019    between it and all previously pending memory references.  This creates
1020    a barrier (or a checkpoint) which no memory reference is allowed to cross.
1021
1022    This includes all non constant CALL_INSNs.  When we do interprocedural
1023    alias analysis, this restriction can be relaxed.
1024    This may also be an INSN that writes memory if the pending lists grow
1025    too large.  */
1026
1027 static rtx last_pending_memory_flush;
1028
1029 /* The last function call we have seen.  All hard regs, and, of course,
1030    the last function call, must depend on this.  */
1031
1032 static rtx last_function_call;
1033
1034 /* The LOG_LINKS field of this is a list of insns which use a pseudo register
1035    that does not already cross a call.  We create dependencies between each
1036    of those insn and the next call insn, to ensure that they won't cross a call
1037    after scheduling is done.  */
1038
1039 static rtx sched_before_next_call;
1040
1041 /* Pointer to the last instruction scheduled.  Used by rank_for_schedule,
1042    so that insns independent of the last scheduled insn will be preferred
1043    over dependent instructions.  */
1044
1045 static rtx last_scheduled_insn;
1046
1047 /* Data structures for the computation of data dependences in a regions.  We
1048    keep one copy of each of the declared above variables for each bb in the
1049    region.  Before analyzing the data dependences for a bb, its variables
1050    are initialized as a function of the variables of its predecessors.  When
1051    the analysis for a bb completes, we save the contents of each variable X
1052    to a corresponding bb_X[bb] variable.  For example, pending_read_insns is
1053    copied to bb_pending_read_insns[bb].  Another change is that few
1054    variables are now a list of insns rather than a single insn:
1055    last_pending_memory_flash, last_function_call, reg_last_sets.  The
1056    manipulation of these variables was changed appropriately.  */
1057
1058 static rtx **bb_reg_last_uses;
1059 static rtx **bb_reg_last_sets;
1060 static rtx **bb_reg_last_clobbers;
1061
1062 static rtx *bb_pending_read_insns;
1063 static rtx *bb_pending_read_mems;
1064 static rtx *bb_pending_write_insns;
1065 static rtx *bb_pending_write_mems;
1066 static int *bb_pending_lists_length;
1067
1068 static rtx *bb_last_pending_memory_flush;
1069 static rtx *bb_last_function_call;
1070 static rtx *bb_sched_before_next_call;
1071
1072 /* functions for construction of the control flow graph.  */
1073
1074 /* Return 1 if control flow graph should not be constructed, 0 otherwise.
1075
1076    We decide not to build the control flow graph if there is possibly more
1077    than one entry to the function, if computed branches exist, of if we
1078    have nonlocal gotos.  */
1079
1080 static int
1081 is_cfg_nonregular ()
1082 {
1083   int b;
1084   rtx insn;
1085   RTX_CODE code;
1086
1087   /* If we have a label that could be the target of a nonlocal goto, then
1088      the cfg is not well structured.  */
1089   if (nonlocal_goto_handler_labels)
1090     return 1;
1091
1092   /* If we have any forced labels, then the cfg is not well structured.  */
1093   if (forced_labels)
1094     return 1;
1095
1096   /* If this function has a computed jump, then we consider the cfg
1097      not well structured.  */
1098   if (current_function_has_computed_jump)
1099     return 1;
1100
1101   /* If we have exception handlers, then we consider the cfg not well
1102      structured.  ?!?  We should be able to handle this now that flow.c
1103      computes an accurate cfg for EH.  */
1104   if (exception_handler_labels)
1105     return 1;
1106
1107   /* If we have non-jumping insns which refer to labels, then we consider
1108      the cfg not well structured.  */
1109   /* check for labels referred to other thn by jumps */
1110   for (b = 0; b < n_basic_blocks; b++)
1111     for (insn = BLOCK_HEAD (b);; insn = NEXT_INSN (insn))
1112       {
1113         code = GET_CODE (insn);
1114         if (GET_RTX_CLASS (code) == 'i')
1115           {
1116             rtx note;
1117
1118             for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
1119               if (REG_NOTE_KIND (note) == REG_LABEL)
1120                 return 1;
1121           }
1122
1123         if (insn == BLOCK_END (b))
1124           break;
1125       }
1126
1127   /* All the tests passed.  Consider the cfg well structured.  */
1128   return 0;
1129 }
1130
1131 /* Build the control flow graph and set nr_edges.
1132
1133    Instead of trying to build a cfg ourselves, we rely on flow to
1134    do it for us.  Stamp out useless code (and bug) duplication.
1135
1136    Return nonzero if an irregularity in the cfg is found which would
1137    prevent cross block scheduling.  */
1138
1139 static int
1140 build_control_flow (s_preds, s_succs, num_preds, num_succs)
1141      int_list_ptr *s_preds;
1142      int_list_ptr *s_succs;
1143      int *num_preds;
1144      int *num_succs;
1145 {
1146   int i;
1147   int_list_ptr succ;
1148   int unreachable;
1149
1150   /* Count the number of edges in the cfg.  */
1151   nr_edges = 0;
1152   unreachable = 0;
1153   for (i = 0; i < n_basic_blocks; i++)
1154     {
1155       nr_edges += num_succs[i];
1156
1157       /* Unreachable loops with more than one basic block are detected
1158          during the DFS traversal in find_rgns.
1159
1160          Unreachable loops with a single block are detected here.  This
1161          test is redundant with the one in find_rgns, but it's much
1162          cheaper to go ahead and catch the trivial case here.  */
1163       if (num_preds[i] == 0
1164           || (num_preds[i] == 1 && INT_LIST_VAL (s_preds[i]) == i))
1165         unreachable = 1;
1166     }
1167
1168   /* Account for entry/exit edges.  */
1169   nr_edges += 2;
1170
1171   in_edges = (int *) xmalloc (n_basic_blocks * sizeof (int));
1172   out_edges = (int *) xmalloc (n_basic_blocks * sizeof (int));
1173   bzero ((char *) in_edges, n_basic_blocks * sizeof (int));
1174   bzero ((char *) out_edges, n_basic_blocks * sizeof (int));
1175
1176   edge_table = (haifa_edge *) xmalloc ((nr_edges) * sizeof (haifa_edge));
1177   bzero ((char *) edge_table, ((nr_edges) * sizeof (haifa_edge)));
1178
1179   nr_edges = 0;
1180   for (i = 0; i < n_basic_blocks; i++)
1181     for (succ = s_succs[i]; succ; succ = succ->next)
1182       {
1183         if (INT_LIST_VAL (succ) != EXIT_BLOCK)
1184           new_edge (i, INT_LIST_VAL (succ));
1185       }
1186
1187   /* increment by 1, since edge 0 is unused.  */
1188   nr_edges++;
1189
1190   return unreachable;
1191 }
1192
1193
1194 /* Record an edge in the control flow graph from SOURCE to TARGET.
1195
1196    In theory, this is redundant with the s_succs computed above, but
1197    we have not converted all of haifa to use information from the
1198    integer lists.  */
1199
1200 static void
1201 new_edge (source, target)
1202      int source, target;
1203 {
1204   int e, next_edge;
1205   int curr_edge, fst_edge;
1206
1207   /* check for duplicates */
1208   fst_edge = curr_edge = OUT_EDGES (source);
1209   while (curr_edge)
1210     {
1211       if (FROM_BLOCK (curr_edge) == source
1212           && TO_BLOCK (curr_edge) == target)
1213         {
1214           return;
1215         }
1216
1217       curr_edge = NEXT_OUT (curr_edge);
1218
1219       if (fst_edge == curr_edge)
1220         break;
1221     }
1222
1223   e = ++nr_edges;
1224
1225   FROM_BLOCK (e) = source;
1226   TO_BLOCK (e) = target;
1227
1228   if (OUT_EDGES (source))
1229     {
1230       next_edge = NEXT_OUT (OUT_EDGES (source));
1231       NEXT_OUT (OUT_EDGES (source)) = e;
1232       NEXT_OUT (e) = next_edge;
1233     }
1234   else
1235     {
1236       OUT_EDGES (source) = e;
1237       NEXT_OUT (e) = e;
1238     }
1239
1240   if (IN_EDGES (target))
1241     {
1242       next_edge = NEXT_IN (IN_EDGES (target));
1243       NEXT_IN (IN_EDGES (target)) = e;
1244       NEXT_IN (e) = next_edge;
1245     }
1246   else
1247     {
1248       IN_EDGES (target) = e;
1249       NEXT_IN (e) = e;
1250     }
1251 }
1252
1253
1254 /* BITSET macros for operations on the control flow graph.  */
1255
1256 /* Compute  bitwise union  of two  bitsets.  */
1257 #define BITSET_UNION(set1, set2, len)                                \
1258 do { register bitset tp = set1, sp = set2;                           \
1259      register int i;                                                 \
1260      for (i = 0; i < len; i++)                                       \
1261        *(tp++) |= *(sp++); } while (0)
1262
1263 /* Compute  bitwise intersection  of two  bitsets.  */
1264 #define BITSET_INTER(set1, set2, len)                                \
1265 do { register bitset tp = set1, sp = set2;                           \
1266      register int i;                                                 \
1267      for (i = 0; i < len; i++)                                       \
1268        *(tp++) &= *(sp++); } while (0)
1269
1270 /* Compute bitwise   difference of  two bitsets.  */
1271 #define BITSET_DIFFER(set1, set2, len)                               \
1272 do { register bitset tp = set1, sp = set2;                           \
1273      register int i;                                                 \
1274      for (i = 0; i < len; i++)                                       \
1275        *(tp++) &= ~*(sp++); } while (0)
1276
1277 /* Inverts every bit of bitset 'set' */
1278 #define BITSET_INVERT(set, len)                                      \
1279 do { register bitset tmpset = set;                                   \
1280      register int i;                                                 \
1281      for (i = 0; i < len; i++, tmpset++)                             \
1282        *tmpset = ~*tmpset; } while (0)
1283
1284 /* Turn on the index'th bit in bitset set.  */
1285 #define BITSET_ADD(set, index, len)                                  \
1286 {                                                                    \
1287   if (index >= HOST_BITS_PER_WIDE_INT * len)                         \
1288     abort ();                                                        \
1289   else                                                               \
1290     set[index/HOST_BITS_PER_WIDE_INT] |=                             \
1291       1 << (index % HOST_BITS_PER_WIDE_INT);                         \
1292 }
1293
1294 /* Turn off the index'th bit in set.  */
1295 #define BITSET_REMOVE(set, index, len)                               \
1296 {                                                                    \
1297   if (index >= HOST_BITS_PER_WIDE_INT * len)                         \
1298     abort ();                                                        \
1299   else                                                               \
1300     set[index/HOST_BITS_PER_WIDE_INT] &=                             \
1301       ~(1 << (index%HOST_BITS_PER_WIDE_INT));                        \
1302 }
1303
1304
1305 /* Check if the index'th bit in bitset  set is on.  */
1306
1307 static char
1308 bitset_member (set, index, len)
1309      bitset set;
1310      int index, len;
1311 {
1312   if (index >= HOST_BITS_PER_WIDE_INT * len)
1313     abort ();
1314   return (set[index / HOST_BITS_PER_WIDE_INT] &
1315           1 << (index % HOST_BITS_PER_WIDE_INT)) ? 1 : 0;
1316 }
1317
1318
1319 /* Translate a bit-set SET to a list BL of the bit-set members.  */
1320
1321 static void
1322 extract_bitlst (set, len, bl)
1323      bitset set;
1324      int len;
1325      bitlst *bl;
1326 {
1327   int i, j, offset;
1328   unsigned HOST_WIDE_INT word;
1329
1330   /* bblst table space is reused in each call to extract_bitlst */
1331   bitlst_table_last = 0;
1332
1333   bl->first_member = &bitlst_table[bitlst_table_last];
1334   bl->nr_members = 0;
1335
1336   for (i = 0; i < len; i++)
1337     {
1338       word = set[i];
1339       offset = i * HOST_BITS_PER_WIDE_INT;
1340       for (j = 0; word; j++)
1341         {
1342           if (word & 1)
1343             {
1344               bitlst_table[bitlst_table_last++] = offset;
1345               (bl->nr_members)++;
1346             }
1347           word >>= 1;
1348           ++offset;
1349         }
1350     }
1351
1352 }
1353
1354
1355 /* functions for the construction of regions */
1356
1357 /* Print the regions, for debugging purposes.  Callable from debugger.  */
1358
1359 void
1360 debug_regions ()
1361 {
1362   int rgn, bb;
1363
1364   fprintf (dump, "\n;;   ------------ REGIONS ----------\n\n");
1365   for (rgn = 0; rgn < nr_regions; rgn++)
1366     {
1367       fprintf (dump, ";;\trgn %d nr_blocks %d:\n", rgn,
1368                rgn_table[rgn].rgn_nr_blocks);
1369       fprintf (dump, ";;\tbb/block: ");
1370
1371       for (bb = 0; bb < rgn_table[rgn].rgn_nr_blocks; bb++)
1372         {
1373           current_blocks = RGN_BLOCKS (rgn);
1374
1375           if (bb != BLOCK_TO_BB (BB_TO_BLOCK (bb)))
1376             abort ();
1377
1378           fprintf (dump, " %d/%d ", bb, BB_TO_BLOCK (bb));
1379         }
1380
1381       fprintf (dump, "\n\n");
1382     }
1383 }
1384
1385
1386 /* Build a single block region for each basic block in the function.
1387    This allows for using the same code for interblock and basic block
1388    scheduling.  */
1389
1390 static void
1391 find_single_block_region ()
1392 {
1393   int i;
1394
1395   for (i = 0; i < n_basic_blocks; i++)
1396     {
1397       rgn_bb_table[i] = i;
1398       RGN_NR_BLOCKS (i) = 1;
1399       RGN_BLOCKS (i) = i;
1400       CONTAINING_RGN (i) = i;
1401       BLOCK_TO_BB (i) = 0;
1402     }
1403   nr_regions = n_basic_blocks;
1404 }
1405
1406
1407 /* Update number of blocks and the estimate for number of insns
1408    in the region.  Return 1 if the region is "too large" for interblock
1409    scheduling (compile time considerations), otherwise return 0.  */
1410
1411 static int
1412 too_large (block, num_bbs, num_insns)
1413      int block, *num_bbs, *num_insns;
1414 {
1415   (*num_bbs)++;
1416   (*num_insns) += (INSN_LUID (BLOCK_END (block)) -
1417                    INSN_LUID (BLOCK_HEAD (block)));
1418   if ((*num_bbs > MAX_RGN_BLOCKS) || (*num_insns > MAX_RGN_INSNS))
1419     return 1;
1420   else
1421     return 0;
1422 }
1423
1424
1425 /* Update_loop_relations(blk, hdr): Check if the loop headed by max_hdr[blk]
1426    is still an inner loop.  Put in max_hdr[blk] the header of the most inner
1427    loop containing blk.  */
1428 #define UPDATE_LOOP_RELATIONS(blk, hdr)                              \
1429 {                                                                    \
1430   if (max_hdr[blk] == -1)                                            \
1431     max_hdr[blk] = hdr;                                              \
1432   else if (dfs_nr[max_hdr[blk]] > dfs_nr[hdr])                       \
1433          RESET_BIT (inner, hdr);                                     \
1434   else if (dfs_nr[max_hdr[blk]] < dfs_nr[hdr])                       \
1435          {                                                           \
1436             RESET_BIT (inner,max_hdr[blk]);                          \
1437             max_hdr[blk] = hdr;                                      \
1438          }                                                           \
1439 }
1440
1441
1442 /* Find regions for interblock scheduling.
1443
1444    A region for scheduling can be:
1445
1446      * A loop-free procedure, or
1447
1448      * A reducible inner loop, or
1449
1450      * A basic block not contained in any other region.
1451
1452
1453    ?!? In theory we could build other regions based on extended basic
1454    blocks or reverse extended basic blocks.  Is it worth the trouble?
1455
1456    Loop blocks that form a region are put into the region's block list
1457    in topological order.
1458
1459    This procedure stores its results into the following global (ick) variables
1460
1461      * rgn_nr
1462      * rgn_table
1463      * rgn_bb_table
1464      * block_to_bb
1465      * containing region
1466
1467
1468    We use dominator relationships to avoid making regions out of non-reducible
1469    loops.
1470
1471    This procedure needs to be converted to work on pred/succ lists instead
1472    of edge tables.  That would simplify it somewhat.  */
1473
1474 static void
1475 find_rgns (s_preds, s_succs, num_preds, num_succs, dom)
1476      int_list_ptr *s_preds;
1477      int_list_ptr *s_succs;
1478      int *num_preds;
1479      int *num_succs;
1480      sbitmap *dom;
1481 {
1482   int *max_hdr, *dfs_nr, *stack, *queue, *degree;
1483   char no_loops = 1;
1484   int node, child, loop_head, i, head, tail;
1485   int count = 0, sp, idx = 0, current_edge = out_edges[0];
1486   int num_bbs, num_insns, unreachable;
1487   int too_large_failure;
1488
1489   /* Note if an edge has been passed.  */
1490   sbitmap passed;
1491
1492   /* Note if a block is a natural loop header.  */
1493   sbitmap header;
1494
1495   /* Note if a block is an natural inner loop header.  */
1496   sbitmap inner;
1497
1498   /* Note if a block is in the block queue. */
1499   sbitmap in_queue;
1500
1501   /* Note if a block is in the block queue. */
1502   sbitmap in_stack;
1503
1504   /* Perform a DFS traversal of the cfg.  Identify loop headers, inner loops
1505      and a mapping from block to its loop header (if the block is contained
1506      in a loop, else -1).
1507
1508      Store results in HEADER, INNER, and MAX_HDR respectively, these will
1509      be used as inputs to the second traversal.
1510
1511      STACK, SP and DFS_NR are only used during the first traversal.  */
1512
1513   /* Allocate and initialize variables for the first traversal.  */
1514   max_hdr = (int *) alloca (n_basic_blocks * sizeof (int));
1515   dfs_nr = (int *) alloca (n_basic_blocks * sizeof (int));
1516   bzero ((char *) dfs_nr, n_basic_blocks * sizeof (int));
1517   stack = (int *) alloca (nr_edges * sizeof (int));
1518
1519   inner = sbitmap_alloc (n_basic_blocks);
1520   sbitmap_ones (inner);
1521
1522   header = sbitmap_alloc (n_basic_blocks);
1523   sbitmap_zero (header);
1524
1525   passed = sbitmap_alloc (nr_edges);
1526   sbitmap_zero (passed);
1527
1528   in_queue = sbitmap_alloc (n_basic_blocks);
1529   sbitmap_zero (in_queue);
1530
1531   in_stack = sbitmap_alloc (n_basic_blocks);
1532   sbitmap_zero (in_stack);
1533
1534   for (i = 0; i < n_basic_blocks; i++)
1535     max_hdr[i] = -1;
1536
1537   /* DFS traversal to find inner loops in the cfg.  */
1538
1539   sp = -1;
1540   while (1)
1541     {
1542       if (current_edge == 0 || TEST_BIT (passed, current_edge))
1543         {
1544           /* We have reached a leaf node or a node that was already
1545              processed.  Pop edges off the stack until we find
1546              an edge that has not yet been processed.  */
1547           while (sp >= 0
1548                  && (current_edge == 0 || TEST_BIT (passed, current_edge)))
1549             {
1550               /* Pop entry off the stack.  */
1551               current_edge = stack[sp--];
1552               node = FROM_BLOCK (current_edge);
1553               child = TO_BLOCK (current_edge);
1554               RESET_BIT (in_stack, child);
1555               if (max_hdr[child] >= 0 && TEST_BIT (in_stack, max_hdr[child]))
1556                 UPDATE_LOOP_RELATIONS (node, max_hdr[child]);
1557               current_edge = NEXT_OUT (current_edge);
1558             }
1559
1560           /* See if have finished the DFS tree traversal.  */
1561           if (sp < 0 && TEST_BIT (passed, current_edge))
1562             break;
1563
1564           /* Nope, continue the traversal with the popped node.  */
1565           continue;
1566         }
1567
1568       /* Process a node.  */
1569       node = FROM_BLOCK (current_edge);
1570       child = TO_BLOCK (current_edge);
1571       SET_BIT (in_stack, node);
1572       dfs_nr[node] = ++count;
1573
1574       /* If the successor is in the stack, then we've found a loop.
1575          Mark the loop, if it is not a natural loop, then it will
1576          be rejected during the second traversal.  */
1577       if (TEST_BIT (in_stack, child))
1578         {
1579           no_loops = 0;
1580           SET_BIT (header, child);
1581           UPDATE_LOOP_RELATIONS (node, child);
1582           SET_BIT (passed, current_edge);
1583           current_edge = NEXT_OUT (current_edge);
1584           continue;
1585         }
1586
1587       /* If the child was already visited, then there is no need to visit
1588          it again.  Just update the loop relationships and restart
1589          with a new edge.  */
1590       if (dfs_nr[child])
1591         {
1592           if (max_hdr[child] >= 0 && TEST_BIT (in_stack, max_hdr[child]))
1593             UPDATE_LOOP_RELATIONS (node, max_hdr[child]);
1594           SET_BIT (passed, current_edge);
1595           current_edge = NEXT_OUT (current_edge);
1596           continue;
1597         }
1598
1599       /* Push an entry on the stack and continue DFS traversal.  */
1600       stack[++sp] = current_edge;
1601       SET_BIT (passed, current_edge);
1602       current_edge = OUT_EDGES (child);
1603     }
1604
1605   /* Another check for unreachable blocks.  The earlier test in
1606      is_cfg_nonregular only finds unreachable blocks that do not
1607      form a loop.
1608
1609      The DFS traversal will mark every block that is reachable from
1610      the entry node by placing a nonzero value in dfs_nr.  Thus if
1611      dfs_nr is zero for any block, then it must be unreachable.  */
1612   unreachable = 0;
1613   for (i = 0; i < n_basic_blocks; i++)
1614     if (dfs_nr[i] == 0)
1615       {
1616         unreachable = 1;
1617         break;
1618       }
1619
1620   /* Gross.  To avoid wasting memory, the second pass uses the dfs_nr array
1621      to hold degree counts.  */
1622   degree = dfs_nr;
1623
1624   /* Compute the in-degree of every block in the graph */
1625   for (i = 0; i < n_basic_blocks; i++)
1626     degree[i] = num_preds[i];
1627
1628   /* Do not perform region scheduling if there are any unreachable
1629      blocks.  */
1630   if (!unreachable)
1631     {
1632       if (no_loops)
1633         SET_BIT (header, 0);
1634
1635       /* Second travsersal:find reducible inner loops and topologically sort
1636          block of each region.  */
1637
1638       queue = (int *) alloca (n_basic_blocks * sizeof (int));
1639
1640       /* Find blocks which are inner loop headers.  We still have non-reducible
1641          loops to consider at this point.  */
1642       for (i = 0; i < n_basic_blocks; i++)
1643         {
1644           if (TEST_BIT (header, i) && TEST_BIT (inner, i))
1645             {
1646               int_list_ptr ps;
1647               int j;
1648
1649               /* Now check that the loop is reducible.  We do this separate
1650                  from finding inner loops so that we do not find a reducible
1651                  loop which contains an inner  non-reducible loop.
1652
1653                  A simple way to find reducible/natrual loops is to verify
1654                  that each block in the loop is dominated by the loop
1655                  header.
1656
1657                  If there exists a block that is not dominated by the loop
1658                  header, then the block is reachable from outside the loop
1659                  and thus the loop is not a natural loop.  */
1660               for (j = 0; j < n_basic_blocks; j++)      
1661                 {
1662                   /* First identify blocks in the loop, except for the loop
1663                      entry block.  */
1664                   if (i == max_hdr[j] && i != j)
1665                     {
1666                       /* Now verify that the block is dominated by the loop
1667                          header.  */
1668                       if (!TEST_BIT (dom[j], i))
1669                         break;
1670                     }
1671                 }
1672
1673               /* If we exited the loop early, then I is the header of a non
1674                  reducible loop and we should quit processing it now.  */
1675               if (j != n_basic_blocks)
1676                 continue;
1677
1678               /* I is a header of an inner loop, or block 0 in a subroutine
1679                  with no loops at all.  */
1680               head = tail = -1;
1681               too_large_failure = 0;
1682               loop_head = max_hdr[i];
1683
1684               /* Decrease degree of all I's successors for topological
1685                  ordering.  */
1686               for (ps = s_succs[i]; ps; ps = ps->next)
1687                 if (INT_LIST_VAL (ps) != EXIT_BLOCK
1688                     && INT_LIST_VAL (ps) != ENTRY_BLOCK)
1689                   --degree[INT_LIST_VAL(ps)];
1690
1691               /* Estimate # insns, and count # blocks in the region.  */
1692               num_bbs = 1;
1693               num_insns = (INSN_LUID (BLOCK_END (i))
1694                            - INSN_LUID (BLOCK_HEAD (i)));
1695
1696
1697               /* Find all loop latches (blocks which back edges to the loop
1698                  header) or all the leaf blocks in the cfg has no loops.
1699
1700                  Place those blocks into the queue.  */
1701               if (no_loops)
1702                 {
1703                   for (j = 0; j < n_basic_blocks; j++)
1704                     /* Leaf nodes have only a single successor which must
1705                        be EXIT_BLOCK.  */
1706                     if (num_succs[j] == 1
1707                         && INT_LIST_VAL (s_succs[j]) == EXIT_BLOCK)
1708                       {
1709                         queue[++tail] = j;
1710                         SET_BIT (in_queue, j);
1711
1712                         if (too_large (j, &num_bbs, &num_insns))
1713                           {
1714                             too_large_failure = 1;
1715                             break;
1716                           }
1717                       }
1718                 }
1719               else
1720                 {
1721                   int_list_ptr ps;
1722
1723                   for (ps = s_preds[i]; ps; ps = ps->next)
1724                     {
1725                       node = INT_LIST_VAL (ps);
1726
1727                       if (node == ENTRY_BLOCK || node == EXIT_BLOCK)
1728                         continue;
1729  
1730                       if (max_hdr[node] == loop_head && node != i)
1731                         {
1732                           /* This is a loop latch.  */
1733                           queue[++tail] = node;
1734                           SET_BIT (in_queue, node);
1735
1736                           if (too_large (node, &num_bbs, &num_insns))
1737                             {
1738                               too_large_failure = 1;
1739                               break;
1740                             }
1741                         }
1742                       
1743                     }
1744                 }
1745
1746               /* Now add all the blocks in the loop to the queue.
1747
1748              We know the loop is a natural loop; however the algorithm
1749              above will not always mark certain blocks as being in the
1750              loop.  Consider:
1751                 node   children
1752                  a        b,c
1753                  b        c
1754                  c        a,d
1755                  d        b
1756
1757
1758              The algorithm in the DFS traversal may not mark B & D as part
1759              of the loop (ie they will not have max_hdr set to A).
1760
1761              We know they can not be loop latches (else they would have
1762              had max_hdr set since they'd have a backedge to a dominator
1763              block).  So we don't need them on the initial queue.
1764
1765              We know they are part of the loop because they are dominated
1766              by the loop header and can be reached by a backwards walk of
1767              the edges starting with nodes on the initial queue.
1768
1769              It is safe and desirable to include those nodes in the
1770              loop/scheduling region.  To do so we would need to decrease
1771              the degree of a node if it is the target of a backedge
1772              within the loop itself as the node is placed in the queue.
1773
1774              We do not do this because I'm not sure that the actual
1775              scheduling code will properly handle this case. ?!? */
1776         
1777               while (head < tail && !too_large_failure)
1778                 {
1779                   int_list_ptr ps;
1780                   child = queue[++head];
1781
1782                   for (ps = s_preds[child]; ps; ps = ps->next)
1783                     {
1784                       node = INT_LIST_VAL (ps);
1785
1786                       /* See discussion above about nodes not marked as in
1787                          this loop during the initial DFS traversal.  */
1788                       if (node == ENTRY_BLOCK || node == EXIT_BLOCK
1789                           || max_hdr[node] != loop_head)
1790                         {
1791                           tail = -1;
1792                           break;
1793                         }
1794                       else if (!TEST_BIT (in_queue, node) && node != i)
1795                         {
1796                           queue[++tail] = node;
1797                           SET_BIT (in_queue, node);
1798
1799                           if (too_large (node, &num_bbs, &num_insns))
1800                             {
1801                               too_large_failure = 1;
1802                               break;
1803                             }
1804                         }
1805                     }
1806                 }
1807
1808               if (tail >= 0 && !too_large_failure)
1809                 {
1810                   /* Place the loop header into list of region blocks.  */
1811                   degree[i] = -1;
1812                   rgn_bb_table[idx] = i;
1813                   RGN_NR_BLOCKS (nr_regions) = num_bbs;
1814                   RGN_BLOCKS (nr_regions) = idx++;
1815                   CONTAINING_RGN (i) = nr_regions;
1816                   BLOCK_TO_BB (i) = count = 0;
1817
1818                   /* Remove blocks from queue[] when their in degree becomes
1819                  zero.  Repeat until no blocks are left on the list.  This
1820                  produces a topological list of blocks in the region.  */
1821                   while (tail >= 0)
1822                     {
1823                       int_list_ptr ps;
1824
1825                       if (head < 0)
1826                         head = tail;
1827                       child = queue[head];
1828                       if (degree[child] == 0)
1829                         {
1830                           degree[child] = -1;
1831                           rgn_bb_table[idx++] = child;
1832                           BLOCK_TO_BB (child) = ++count;
1833                           CONTAINING_RGN (child) = nr_regions;
1834                           queue[head] = queue[tail--];
1835
1836                           for (ps = s_succs[child]; ps; ps = ps->next)
1837                             if (INT_LIST_VAL (ps) != ENTRY_BLOCK
1838                                 && INT_LIST_VAL (ps) != EXIT_BLOCK)
1839                               --degree[INT_LIST_VAL (ps)];
1840                         }
1841                       else
1842                         --head;
1843                     }
1844                   ++nr_regions;
1845                 }
1846             }
1847         }
1848     }
1849
1850   /* Any block that did not end up in a region is placed into a region
1851      by itself.  */
1852   for (i = 0; i < n_basic_blocks; i++)
1853     if (degree[i] >= 0)
1854       {
1855         rgn_bb_table[idx] = i;
1856         RGN_NR_BLOCKS (nr_regions) = 1;
1857         RGN_BLOCKS (nr_regions) = idx++;
1858         CONTAINING_RGN (i) = nr_regions++;
1859         BLOCK_TO_BB (i) = 0;
1860       }
1861
1862   free (passed);
1863   free (header);
1864   free (inner);
1865   free (in_queue);
1866   free (in_stack);
1867 }
1868
1869
1870 /* functions for regions scheduling information */
1871
1872 /* Compute dominators, probability, and potential-split-edges of bb.
1873    Assume that these values were already computed for bb's predecessors.  */
1874
1875 static void
1876 compute_dom_prob_ps (bb)
1877      int bb;
1878 {
1879   int nxt_in_edge, fst_in_edge, pred;
1880   int fst_out_edge, nxt_out_edge, nr_out_edges, nr_rgn_out_edges;
1881
1882   prob[bb] = 0.0;
1883   if (IS_RGN_ENTRY (bb))
1884     {
1885       BITSET_ADD (dom[bb], 0, bbset_size);
1886       prob[bb] = 1.0;
1887       return;
1888     }
1889
1890   fst_in_edge = nxt_in_edge = IN_EDGES (BB_TO_BLOCK (bb));
1891
1892   /* intialize dom[bb] to '111..1' */
1893   BITSET_INVERT (dom[bb], bbset_size);
1894
1895   do
1896     {
1897       pred = FROM_BLOCK (nxt_in_edge);
1898       BITSET_INTER (dom[bb], dom[BLOCK_TO_BB (pred)], bbset_size);
1899
1900       BITSET_UNION (ancestor_edges[bb], ancestor_edges[BLOCK_TO_BB (pred)],
1901                     edgeset_size);
1902
1903       BITSET_ADD (ancestor_edges[bb], EDGE_TO_BIT (nxt_in_edge), edgeset_size);
1904
1905       nr_out_edges = 1;
1906       nr_rgn_out_edges = 0;
1907       fst_out_edge = OUT_EDGES (pred);
1908       nxt_out_edge = NEXT_OUT (fst_out_edge);
1909       BITSET_UNION (pot_split[bb], pot_split[BLOCK_TO_BB (pred)],
1910                     edgeset_size);
1911
1912       BITSET_ADD (pot_split[bb], EDGE_TO_BIT (fst_out_edge), edgeset_size);
1913
1914       /* the successor doesn't belong the region? */
1915       if (CONTAINING_RGN (TO_BLOCK (fst_out_edge)) !=
1916           CONTAINING_RGN (BB_TO_BLOCK (bb)))
1917         ++nr_rgn_out_edges;
1918
1919       while (fst_out_edge != nxt_out_edge)
1920         {
1921           ++nr_out_edges;
1922           /* the successor doesn't belong the region? */
1923           if (CONTAINING_RGN (TO_BLOCK (nxt_out_edge)) !=
1924               CONTAINING_RGN (BB_TO_BLOCK (bb)))
1925             ++nr_rgn_out_edges;
1926           BITSET_ADD (pot_split[bb], EDGE_TO_BIT (nxt_out_edge), edgeset_size);
1927           nxt_out_edge = NEXT_OUT (nxt_out_edge);
1928
1929         }
1930
1931       /* now nr_rgn_out_edges is the number of region-exit edges from pred,
1932          and nr_out_edges will be the number of pred out edges not leaving
1933          the region.  */
1934       nr_out_edges -= nr_rgn_out_edges;
1935       if (nr_rgn_out_edges > 0)
1936         prob[bb] += 0.9 * prob[BLOCK_TO_BB (pred)] / nr_out_edges;
1937       else
1938         prob[bb] += prob[BLOCK_TO_BB (pred)] / nr_out_edges;
1939       nxt_in_edge = NEXT_IN (nxt_in_edge);
1940     }
1941   while (fst_in_edge != nxt_in_edge);
1942
1943   BITSET_ADD (dom[bb], bb, bbset_size);
1944   BITSET_DIFFER (pot_split[bb], ancestor_edges[bb], edgeset_size);
1945
1946   if (sched_verbose >= 2)
1947     fprintf (dump, ";;  bb_prob(%d, %d) = %3d\n", bb, BB_TO_BLOCK (bb), (int) (100.0 * prob[bb]));
1948 }                               /* compute_dom_prob_ps */
1949
1950 /* functions for target info */
1951
1952 /* Compute in BL the list of split-edges of bb_src relatively to bb_trg.
1953    Note that bb_trg dominates bb_src.  */
1954
1955 static void
1956 split_edges (bb_src, bb_trg, bl)
1957      int bb_src;
1958      int bb_trg;
1959      edgelst *bl;
1960 {
1961   int es = edgeset_size;
1962   edgeset src = (edgeset) alloca (es * sizeof (HOST_WIDE_INT));
1963
1964   while (es--)
1965     src[es] = (pot_split[bb_src])[es];
1966   BITSET_DIFFER (src, pot_split[bb_trg], edgeset_size);
1967   extract_bitlst (src, edgeset_size, bl);
1968 }
1969
1970
1971 /* Find the valid candidate-source-blocks for the target block TRG, compute
1972    their probability, and check if they are speculative or not.
1973    For speculative sources, compute their update-blocks and split-blocks.  */
1974
1975 static void
1976 compute_trg_info (trg)
1977      int trg;
1978 {
1979   register candidate *sp;
1980   edgelst el;
1981   int check_block, update_idx;
1982   int i, j, k, fst_edge, nxt_edge;
1983
1984   /* define some of the fields for the target bb as well */
1985   sp = candidate_table + trg;
1986   sp->is_valid = 1;
1987   sp->is_speculative = 0;
1988   sp->src_prob = 100;
1989
1990   for (i = trg + 1; i < current_nr_blocks; i++)
1991     {
1992       sp = candidate_table + i;
1993
1994       sp->is_valid = IS_DOMINATED (i, trg);
1995       if (sp->is_valid)
1996         {
1997           sp->src_prob = GET_SRC_PROB (i, trg);
1998           sp->is_valid = (sp->src_prob >= MIN_PROBABILITY);
1999         }
2000
2001       if (sp->is_valid)
2002         {
2003           split_edges (i, trg, &el);
2004           sp->is_speculative = (el.nr_members) ? 1 : 0;
2005           if (sp->is_speculative && !flag_schedule_speculative)
2006             sp->is_valid = 0;
2007         }
2008
2009       if (sp->is_valid)
2010         {
2011           sp->split_bbs.first_member = &bblst_table[bblst_last];
2012           sp->split_bbs.nr_members = el.nr_members;
2013           for (j = 0; j < el.nr_members; bblst_last++, j++)
2014             bblst_table[bblst_last] =
2015               TO_BLOCK (rgn_edges[el.first_member[j]]);
2016           sp->update_bbs.first_member = &bblst_table[bblst_last];
2017           update_idx = 0;
2018           for (j = 0; j < el.nr_members; j++)
2019             {
2020               check_block = FROM_BLOCK (rgn_edges[el.first_member[j]]);
2021               fst_edge = nxt_edge = OUT_EDGES (check_block);
2022               do
2023                 {
2024                   for (k = 0; k < el.nr_members; k++)
2025                     if (EDGE_TO_BIT (nxt_edge) == el.first_member[k])
2026                       break;
2027
2028                   if (k >= el.nr_members)
2029                     {
2030                       bblst_table[bblst_last++] = TO_BLOCK (nxt_edge);
2031                       update_idx++;
2032                     }
2033
2034                   nxt_edge = NEXT_OUT (nxt_edge);
2035                 }
2036               while (fst_edge != nxt_edge);
2037             }
2038           sp->update_bbs.nr_members = update_idx;
2039
2040         }
2041       else
2042         {
2043           sp->split_bbs.nr_members = sp->update_bbs.nr_members = 0;
2044
2045           sp->is_speculative = 0;
2046           sp->src_prob = 0;
2047         }
2048     }
2049 }                               /* compute_trg_info */
2050
2051
2052 /* Print candidates info, for debugging purposes.  Callable from debugger.  */
2053
2054 void
2055 debug_candidate (i)
2056      int i;
2057 {
2058   if (!candidate_table[i].is_valid)
2059     return;
2060
2061   if (candidate_table[i].is_speculative)
2062     {
2063       int j;
2064       fprintf (dump, "src b %d bb %d speculative \n", BB_TO_BLOCK (i), i);
2065
2066       fprintf (dump, "split path: ");
2067       for (j = 0; j < candidate_table[i].split_bbs.nr_members; j++)
2068         {
2069           int b = candidate_table[i].split_bbs.first_member[j];
2070
2071           fprintf (dump, " %d ", b);
2072         }
2073       fprintf (dump, "\n");
2074
2075       fprintf (dump, "update path: ");
2076       for (j = 0; j < candidate_table[i].update_bbs.nr_members; j++)
2077         {
2078           int b = candidate_table[i].update_bbs.first_member[j];
2079
2080           fprintf (dump, " %d ", b);
2081         }
2082       fprintf (dump, "\n");
2083     }
2084   else
2085     {
2086       fprintf (dump, " src %d equivalent\n", BB_TO_BLOCK (i));
2087     }
2088 }
2089
2090
2091 /* Print candidates info, for debugging purposes.  Callable from debugger.  */
2092
2093 void
2094 debug_candidates (trg)
2095      int trg;
2096 {
2097   int i;
2098
2099   fprintf (dump, "----------- candidate table: target: b=%d bb=%d ---\n",
2100            BB_TO_BLOCK (trg), trg);
2101   for (i = trg + 1; i < current_nr_blocks; i++)
2102     debug_candidate (i);
2103 }
2104
2105
2106 /* functions for speculative scheduing */
2107
2108 /* Return 0 if x is a set of a register alive in the beginning of one
2109    of the split-blocks of src, otherwise return 1.  */
2110
2111 static int
2112 check_live_1 (src, x)
2113      int src;
2114      rtx x;
2115 {
2116   register int i;
2117   register int regno;
2118   register rtx reg = SET_DEST (x);
2119
2120   if (reg == 0)
2121     return 1;
2122
2123   while (GET_CODE (reg) == SUBREG || GET_CODE (reg) == ZERO_EXTRACT
2124          || GET_CODE (reg) == SIGN_EXTRACT
2125          || GET_CODE (reg) == STRICT_LOW_PART)
2126     reg = XEXP (reg, 0);
2127
2128   if (GET_CODE (reg) == PARALLEL
2129       && GET_MODE (reg) == BLKmode)
2130     {
2131       register int i;
2132       for (i = XVECLEN (reg, 0) - 1; i >= 0; i--)
2133         if (check_live_1 (src, XVECEXP (reg, 0, i)))
2134           return 1;
2135       return 0;
2136     }
2137
2138   if (GET_CODE (reg) != REG)
2139     return 1;
2140
2141   regno = REGNO (reg);
2142
2143   if (regno < FIRST_PSEUDO_REGISTER && global_regs[regno])
2144     {
2145       /* Global registers are assumed live */
2146       return 0;
2147     }
2148   else
2149     {
2150       if (regno < FIRST_PSEUDO_REGISTER)
2151         {
2152           /* check for hard registers */
2153           int j = HARD_REGNO_NREGS (regno, GET_MODE (reg));
2154           while (--j >= 0)
2155             {
2156               for (i = 0; i < candidate_table[src].split_bbs.nr_members; i++)
2157                 {
2158                   int b = candidate_table[src].split_bbs.first_member[i];
2159
2160                   if (REGNO_REG_SET_P (BASIC_BLOCK (b)->global_live_at_start,
2161                                        regno + j))
2162                     {
2163                       return 0;
2164                     }
2165                 }
2166             }
2167         }
2168       else
2169         {
2170           /* check for psuedo registers */
2171           for (i = 0; i < candidate_table[src].split_bbs.nr_members; i++)
2172             {
2173               int b = candidate_table[src].split_bbs.first_member[i];
2174
2175               if (REGNO_REG_SET_P (BASIC_BLOCK (b)->global_live_at_start, regno))
2176                 {
2177                   return 0;
2178                 }
2179             }
2180         }
2181     }
2182
2183   return 1;
2184 }
2185
2186
2187 /* If x is a set of a register R, mark that R is alive in the beginning
2188    of every update-block of src.  */
2189
2190 static void
2191 update_live_1 (src, x)
2192      int src;
2193      rtx x;
2194 {
2195   register int i;
2196   register int regno;
2197   register rtx reg = SET_DEST (x);
2198
2199   if (reg == 0)
2200     return;
2201
2202   while (GET_CODE (reg) == SUBREG || GET_CODE (reg) == ZERO_EXTRACT
2203          || GET_CODE (reg) == SIGN_EXTRACT
2204          || GET_CODE (reg) == STRICT_LOW_PART)
2205     reg = XEXP (reg, 0);
2206
2207   if (GET_CODE (reg) == PARALLEL
2208       && GET_MODE (reg) == BLKmode)
2209     {
2210       register int i;
2211       for (i = XVECLEN (reg, 0) - 1; i >= 0; i--)
2212         update_live_1 (src, XVECEXP (reg, 0, i));
2213       return;
2214     }
2215
2216   if (GET_CODE (reg) != REG)
2217     return;
2218
2219   /* Global registers are always live, so the code below does not apply
2220      to them.  */
2221
2222   regno = REGNO (reg);
2223
2224   if (regno >= FIRST_PSEUDO_REGISTER || !global_regs[regno])
2225     {
2226       if (regno < FIRST_PSEUDO_REGISTER)
2227         {
2228           int j = HARD_REGNO_NREGS (regno, GET_MODE (reg));
2229           while (--j >= 0)
2230             {
2231               for (i = 0; i < candidate_table[src].update_bbs.nr_members; i++)
2232                 {
2233                   int b = candidate_table[src].update_bbs.first_member[i];
2234
2235                   SET_REGNO_REG_SET (BASIC_BLOCK (b)->global_live_at_start,
2236                                      regno + j);
2237                 }
2238             }
2239         }
2240       else
2241         {
2242           for (i = 0; i < candidate_table[src].update_bbs.nr_members; i++)
2243             {
2244               int b = candidate_table[src].update_bbs.first_member[i];
2245
2246               SET_REGNO_REG_SET (BASIC_BLOCK (b)->global_live_at_start, regno);
2247             }
2248         }
2249     }
2250 }
2251
2252
2253 /* Return 1 if insn can be speculatively moved from block src to trg,
2254    otherwise return 0.  Called before first insertion of insn to
2255    ready-list or before the scheduling.  */
2256
2257 static int
2258 check_live (insn, src)
2259      rtx insn;
2260      int src;
2261 {
2262   /* find the registers set by instruction */
2263   if (GET_CODE (PATTERN (insn)) == SET
2264       || GET_CODE (PATTERN (insn)) == CLOBBER)
2265     return check_live_1 (src, PATTERN (insn));
2266   else if (GET_CODE (PATTERN (insn)) == PARALLEL)
2267     {
2268       int j;
2269       for (j = XVECLEN (PATTERN (insn), 0) - 1; j >= 0; j--)
2270         if ((GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == SET
2271              || GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == CLOBBER)
2272             && !check_live_1 (src, XVECEXP (PATTERN (insn), 0, j)))
2273           return 0;
2274
2275       return 1;
2276     }
2277
2278   return 1;
2279 }
2280
2281
2282 /* Update the live registers info after insn was moved speculatively from
2283    block src to trg.  */
2284
2285 static void
2286 update_live (insn, src)
2287      rtx insn;
2288      int src;
2289 {
2290   /* find the registers set by instruction */
2291   if (GET_CODE (PATTERN (insn)) == SET
2292       || GET_CODE (PATTERN (insn)) == CLOBBER)
2293     update_live_1 (src, PATTERN (insn));
2294   else if (GET_CODE (PATTERN (insn)) == PARALLEL)
2295     {
2296       int j;
2297       for (j = XVECLEN (PATTERN (insn), 0) - 1; j >= 0; j--)
2298         if (GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == SET
2299             || GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == CLOBBER)
2300           update_live_1 (src, XVECEXP (PATTERN (insn), 0, j));
2301     }
2302 }
2303
2304 /* Exception Free Loads:
2305
2306    We define five classes of speculative loads: IFREE, IRISKY,
2307    PFREE, PRISKY, and MFREE.
2308
2309    IFREE loads are loads that are proved to be exception-free, just
2310    by examining the load insn.  Examples for such loads are loads
2311    from TOC and loads of global data.
2312
2313    IRISKY loads are loads that are proved to be exception-risky,
2314    just by examining the load insn.  Examples for such loads are
2315    volatile loads and loads from shared memory.
2316
2317    PFREE loads are loads for which we can prove, by examining other
2318    insns, that they are exception-free.  Currently, this class consists
2319    of loads for which we are able to find a "similar load", either in
2320    the target block, or, if only one split-block exists, in that split
2321    block.  Load2 is similar to load1 if both have same single base
2322    register.  We identify only part of the similar loads, by finding
2323    an insn upon which both load1 and load2 have a DEF-USE dependence.
2324
2325    PRISKY loads are loads for which we can prove, by examining other
2326    insns, that they are exception-risky.  Currently we have two proofs for
2327    such loads.  The first proof detects loads that are probably guarded by a
2328    test on the memory address.  This proof is based on the
2329    backward and forward data dependence information for the region.
2330    Let load-insn be the examined load.
2331    Load-insn is PRISKY iff ALL the following hold:
2332
2333    - insn1 is not in the same block as load-insn
2334    - there is a DEF-USE dependence chain (insn1, ..., load-insn)
2335    - test-insn is either a compare or a branch, not in the same block as load-insn
2336    - load-insn is reachable from test-insn
2337    - there is a DEF-USE dependence chain (insn1, ..., test-insn)
2338
2339    This proof might fail when the compare and the load are fed
2340    by an insn not in the region.  To solve this, we will add to this
2341    group all loads that have no input DEF-USE dependence.
2342
2343    The second proof detects loads that are directly or indirectly
2344    fed by a speculative load.  This proof is affected by the
2345    scheduling process.  We will use the flag  fed_by_spec_load.
2346    Initially, all insns have this flag reset.  After a speculative
2347    motion of an insn, if insn is either a load, or marked as
2348    fed_by_spec_load, we will also mark as fed_by_spec_load every
2349    insn1 for which a DEF-USE dependence (insn, insn1) exists.  A
2350    load which is fed_by_spec_load is also PRISKY.
2351
2352    MFREE (maybe-free) loads are all the remaining loads. They may be
2353    exception-free, but we cannot prove it.
2354
2355    Now, all loads in IFREE and PFREE classes are considered
2356    exception-free, while all loads in IRISKY and PRISKY classes are
2357    considered exception-risky.  As for loads in the MFREE class,
2358    these are considered either exception-free or exception-risky,
2359    depending on whether we are pessimistic or optimistic.  We have
2360    to take the pessimistic approach to assure the safety of
2361    speculative scheduling, but we can take the optimistic approach
2362    by invoking the -fsched_spec_load_dangerous option.  */
2363
2364 enum INSN_TRAP_CLASS
2365 {
2366   TRAP_FREE = 0, IFREE = 1, PFREE_CANDIDATE = 2,
2367   PRISKY_CANDIDATE = 3, IRISKY = 4, TRAP_RISKY = 5
2368 };
2369
2370 #define WORST_CLASS(class1, class2) \
2371 ((class1 > class2) ? class1 : class2)
2372
2373 /* Indexed by INSN_UID, and set if there's DEF-USE dependence between */
2374 /* some speculatively moved load insn and this one.  */
2375 char *fed_by_spec_load;
2376 char *is_load_insn;
2377
2378 /* Non-zero if block bb_to is equal to, or reachable from block bb_from.  */
2379 #define IS_REACHABLE(bb_from, bb_to)                                    \
2380 (bb_from == bb_to                                                       \
2381    || IS_RGN_ENTRY (bb_from)                                            \
2382    || (bitset_member (ancestor_edges[bb_to],                            \
2383                       EDGE_TO_BIT (IN_EDGES (BB_TO_BLOCK (bb_from))),   \
2384                       edgeset_size)))
2385 #define FED_BY_SPEC_LOAD(insn) (fed_by_spec_load[INSN_UID (insn)])
2386 #define IS_LOAD_INSN(insn) (is_load_insn[INSN_UID (insn)])
2387
2388 /* Non-zero iff the address is comprised from at most 1 register */
2389 #define CONST_BASED_ADDRESS_P(x)                        \
2390   (GET_CODE (x) == REG                                  \
2391    || ((GET_CODE (x) == PLUS || GET_CODE (x) == MINUS   \
2392         || (GET_CODE (x) == LO_SUM))                    \
2393        && (GET_CODE (XEXP (x, 0)) == CONST_INT          \
2394            || GET_CODE (XEXP (x, 1)) == CONST_INT)))
2395
2396 /* Turns on the fed_by_spec_load flag for insns fed by load_insn.  */
2397
2398 static void
2399 set_spec_fed (load_insn)
2400      rtx load_insn;
2401 {
2402   rtx link;
2403
2404   for (link = INSN_DEPEND (load_insn); link; link = XEXP (link, 1))
2405     if (GET_MODE (link) == VOIDmode)
2406       FED_BY_SPEC_LOAD (XEXP (link, 0)) = 1;
2407 }                               /* set_spec_fed */
2408
2409 /* On the path from the insn to load_insn_bb, find a conditional branch */
2410 /* depending on insn, that guards the speculative load.  */
2411
2412 static int
2413 find_conditional_protection (insn, load_insn_bb)
2414      rtx insn;
2415      int load_insn_bb;
2416 {
2417   rtx link;
2418
2419   /* iterate through DEF-USE forward dependences */
2420   for (link = INSN_DEPEND (insn); link; link = XEXP (link, 1))
2421     {
2422       rtx next = XEXP (link, 0);
2423       if ((CONTAINING_RGN (INSN_BLOCK (next)) ==
2424            CONTAINING_RGN (BB_TO_BLOCK (load_insn_bb)))
2425           && IS_REACHABLE (INSN_BB (next), load_insn_bb)
2426           && load_insn_bb != INSN_BB (next)
2427           && GET_MODE (link) == VOIDmode
2428           && (GET_CODE (next) == JUMP_INSN
2429               || find_conditional_protection (next, load_insn_bb)))
2430         return 1;
2431     }
2432   return 0;
2433 }                               /* find_conditional_protection */
2434
2435 /* Returns 1 if the same insn1 that participates in the computation
2436    of load_insn's address is feeding a conditional branch that is
2437    guarding on load_insn. This is true if we find a the two DEF-USE
2438    chains:
2439    insn1 -> ... -> conditional-branch
2440    insn1 -> ... -> load_insn,
2441    and if a flow path exist:
2442    insn1 -> ... -> conditional-branch -> ... -> load_insn,
2443    and if insn1 is on the path
2444    region-entry -> ... -> bb_trg -> ... load_insn.
2445
2446    Locate insn1 by climbing on LOG_LINKS from load_insn.
2447    Locate the branch by following INSN_DEPEND from insn1.  */
2448
2449 static int
2450 is_conditionally_protected (load_insn, bb_src, bb_trg)
2451      rtx load_insn;
2452      int bb_src, bb_trg;
2453 {
2454   rtx link;
2455
2456   for (link = LOG_LINKS (load_insn); link; link = XEXP (link, 1))
2457     {
2458       rtx insn1 = XEXP (link, 0);
2459
2460       /* must be a DEF-USE dependence upon non-branch */
2461       if (GET_MODE (link) != VOIDmode
2462           || GET_CODE (insn1) == JUMP_INSN)
2463         continue;
2464
2465       /* must exist a path: region-entry -> ... -> bb_trg -> ... load_insn */
2466       if (INSN_BB (insn1) == bb_src
2467           || (CONTAINING_RGN (INSN_BLOCK (insn1))
2468               != CONTAINING_RGN (BB_TO_BLOCK (bb_src)))
2469           || (!IS_REACHABLE (bb_trg, INSN_BB (insn1))
2470               && !IS_REACHABLE (INSN_BB (insn1), bb_trg)))
2471         continue;
2472
2473       /* now search for the conditional-branch */
2474       if (find_conditional_protection (insn1, bb_src))
2475         return 1;
2476
2477       /* recursive step: search another insn1, "above" current insn1.  */
2478       return is_conditionally_protected (insn1, bb_src, bb_trg);
2479     }
2480
2481   /* the chain does not exsist */
2482   return 0;
2483 }                               /* is_conditionally_protected */
2484
2485 /* Returns 1 if a clue for "similar load" 'insn2' is found, and hence
2486    load_insn can move speculatively from bb_src to bb_trg.  All the
2487    following must hold:
2488
2489    (1) both loads have 1 base register (PFREE_CANDIDATEs).
2490    (2) load_insn and load1 have a def-use dependence upon
2491    the same insn 'insn1'.
2492    (3) either load2 is in bb_trg, or:
2493    - there's only one split-block, and
2494    - load1 is on the escape path, and
2495
2496    From all these we can conclude that the two loads access memory
2497    addresses that differ at most by a constant, and hence if moving
2498    load_insn would cause an exception, it would have been caused by
2499    load2 anyhow.  */
2500
2501 static int
2502 is_pfree (load_insn, bb_src, bb_trg)
2503      rtx load_insn;
2504      int bb_src, bb_trg;
2505 {
2506   rtx back_link;
2507   register candidate *candp = candidate_table + bb_src;
2508
2509   if (candp->split_bbs.nr_members != 1)
2510     /* must have exactly one escape block */
2511     return 0;
2512
2513   for (back_link = LOG_LINKS (load_insn);
2514        back_link; back_link = XEXP (back_link, 1))
2515     {
2516       rtx insn1 = XEXP (back_link, 0);
2517
2518       if (GET_MODE (back_link) == VOIDmode)
2519         {
2520           /* found a DEF-USE dependence (insn1, load_insn) */
2521           rtx fore_link;
2522
2523           for (fore_link = INSN_DEPEND (insn1);
2524                fore_link; fore_link = XEXP (fore_link, 1))
2525             {
2526               rtx insn2 = XEXP (fore_link, 0);
2527               if (GET_MODE (fore_link) == VOIDmode)
2528                 {
2529                   /* found a DEF-USE dependence (insn1, insn2) */
2530                   if (haifa_classify_insn (insn2) != PFREE_CANDIDATE)
2531                     /* insn2 not guaranteed to be a 1 base reg load */
2532                     continue;
2533
2534                   if (INSN_BB (insn2) == bb_trg)
2535                     /* insn2 is the similar load, in the target block */
2536                     return 1;
2537
2538                   if (*(candp->split_bbs.first_member) == INSN_BLOCK (insn2))
2539                     /* insn2 is a similar load, in a split-block */
2540                     return 1;
2541                 }
2542             }
2543         }
2544     }
2545
2546   /* couldn't find a similar load */
2547   return 0;
2548 }                               /* is_pfree */
2549
2550 /* Returns a class that insn with GET_DEST(insn)=x may belong to,
2551    as found by analyzing insn's expression.  */
2552
2553 static int
2554 may_trap_exp (x, is_store)
2555      rtx x;
2556      int is_store;
2557 {
2558   enum rtx_code code;
2559
2560   if (x == 0)
2561     return TRAP_FREE;
2562   code = GET_CODE (x);
2563   if (is_store)
2564     {
2565       if (code == MEM)
2566         return TRAP_RISKY;
2567       else
2568         return TRAP_FREE;
2569     }
2570   if (code == MEM)
2571     {
2572       /* The insn uses memory */
2573       /* a volatile load */
2574       if (MEM_VOLATILE_P (x))
2575         return IRISKY;
2576       /* an exception-free load */
2577       if (!may_trap_p (x))
2578         return IFREE;
2579       /* a load with 1 base register, to be further checked */
2580       if (CONST_BASED_ADDRESS_P (XEXP (x, 0)))
2581         return PFREE_CANDIDATE;
2582       /* no info on the load, to be further checked */
2583       return PRISKY_CANDIDATE;
2584     }
2585   else
2586     {
2587       char *fmt;
2588       int i, insn_class = TRAP_FREE;
2589
2590       /* neither store nor load, check if it may cause a trap */
2591       if (may_trap_p (x))
2592         return TRAP_RISKY;
2593       /* recursive step: walk the insn...  */
2594       fmt = GET_RTX_FORMAT (code);
2595       for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2596         {
2597           if (fmt[i] == 'e')
2598             {
2599               int tmp_class = may_trap_exp (XEXP (x, i), is_store);
2600               insn_class = WORST_CLASS (insn_class, tmp_class);
2601             }
2602           else if (fmt[i] == 'E')
2603             {
2604               int j;
2605               for (j = 0; j < XVECLEN (x, i); j++)
2606                 {
2607                   int tmp_class = may_trap_exp (XVECEXP (x, i, j), is_store);
2608                   insn_class = WORST_CLASS (insn_class, tmp_class);
2609                   if (insn_class == TRAP_RISKY || insn_class == IRISKY)
2610                     break;
2611                 }
2612             }
2613           if (insn_class == TRAP_RISKY || insn_class == IRISKY)
2614             break;
2615         }
2616       return insn_class;
2617     }
2618 }                               /* may_trap_exp */
2619
2620
2621 /* Classifies insn for the purpose of verifying that it can be
2622    moved speculatively, by examining it's patterns, returning:
2623    TRAP_RISKY: store, or risky non-load insn (e.g. division by variable).
2624    TRAP_FREE: non-load insn.
2625    IFREE: load from a globaly safe location.
2626    IRISKY: volatile load.
2627    PFREE_CANDIDATE, PRISKY_CANDIDATE: load that need to be checked for
2628    being either PFREE or PRISKY.  */
2629
2630 static int
2631 haifa_classify_insn (insn)
2632      rtx insn;
2633 {
2634   rtx pat = PATTERN (insn);
2635   int tmp_class = TRAP_FREE;
2636   int insn_class = TRAP_FREE;
2637   enum rtx_code code;
2638
2639   if (GET_CODE (pat) == PARALLEL)
2640     {
2641       int i, len = XVECLEN (pat, 0);
2642
2643       for (i = len - 1; i >= 0; i--)
2644         {
2645           code = GET_CODE (XVECEXP (pat, 0, i));
2646           switch (code)
2647             {
2648             case CLOBBER:
2649               /* test if it is a 'store' */
2650               tmp_class = may_trap_exp (XEXP (XVECEXP (pat, 0, i), 0), 1);
2651               break;
2652             case SET:
2653               /* test if it is a store */
2654               tmp_class = may_trap_exp (SET_DEST (XVECEXP (pat, 0, i)), 1);
2655               if (tmp_class == TRAP_RISKY)
2656                 break;
2657               /* test if it is a load  */
2658               tmp_class =
2659                 WORST_CLASS (tmp_class,
2660                            may_trap_exp (SET_SRC (XVECEXP (pat, 0, i)), 0));
2661               break;
2662             case TRAP_IF:
2663               tmp_class = TRAP_RISKY;
2664               break;
2665             default:;
2666             }
2667           insn_class = WORST_CLASS (insn_class, tmp_class);
2668           if (insn_class == TRAP_RISKY || insn_class == IRISKY)
2669             break;
2670         }
2671     }
2672   else
2673     {
2674       code = GET_CODE (pat);
2675       switch (code)
2676         {
2677         case CLOBBER:
2678           /* test if it is a 'store' */
2679           tmp_class = may_trap_exp (XEXP (pat, 0), 1);
2680           break;
2681         case SET:
2682           /* test if it is a store */
2683           tmp_class = may_trap_exp (SET_DEST (pat), 1);
2684           if (tmp_class == TRAP_RISKY)
2685             break;
2686           /* test if it is a load  */
2687           tmp_class =
2688             WORST_CLASS (tmp_class,
2689                          may_trap_exp (SET_SRC (pat), 0));
2690           break;
2691         case TRAP_IF:
2692           tmp_class = TRAP_RISKY;
2693           break;
2694         default:;
2695         }
2696       insn_class = tmp_class;
2697     }
2698
2699   return insn_class;
2700
2701 }                               /* haifa_classify_insn */
2702
2703 /* Return 1 if load_insn is prisky (i.e. if load_insn is fed by
2704    a load moved speculatively, or if load_insn is protected by
2705    a compare on load_insn's address).  */
2706
2707 static int
2708 is_prisky (load_insn, bb_src, bb_trg)
2709      rtx load_insn;
2710      int bb_src, bb_trg;
2711 {
2712   if (FED_BY_SPEC_LOAD (load_insn))
2713     return 1;
2714
2715   if (LOG_LINKS (load_insn) == NULL)
2716     /* dependence may 'hide' out of the region.  */
2717     return 1;
2718
2719   if (is_conditionally_protected (load_insn, bb_src, bb_trg))
2720     return 1;
2721
2722   return 0;
2723 }                               /* is_prisky */
2724
2725 /* Insn is a candidate to be moved speculatively from bb_src to bb_trg.
2726    Return 1 if insn is exception-free (and the motion is valid)
2727    and 0 otherwise.  */
2728
2729 static int
2730 is_exception_free (insn, bb_src, bb_trg)
2731      rtx insn;
2732      int bb_src, bb_trg;
2733 {
2734   int insn_class = haifa_classify_insn (insn);
2735
2736   /* handle non-load insns */
2737   switch (insn_class)
2738     {
2739     case TRAP_FREE:
2740       return 1;
2741     case TRAP_RISKY:
2742       return 0;
2743     default:;
2744     }
2745
2746   /* handle loads */
2747   if (!flag_schedule_speculative_load)
2748     return 0;
2749   IS_LOAD_INSN (insn) = 1;
2750   switch (insn_class)
2751     {
2752     case IFREE:
2753       return (1);
2754     case IRISKY:
2755       return 0;
2756     case PFREE_CANDIDATE:
2757       if (is_pfree (insn, bb_src, bb_trg))
2758         return 1;
2759       /* don't 'break' here: PFREE-candidate is also PRISKY-candidate */
2760     case PRISKY_CANDIDATE:
2761       if (!flag_schedule_speculative_load_dangerous
2762           || is_prisky (insn, bb_src, bb_trg))
2763         return 0;
2764       break;
2765     default:;
2766     }
2767
2768   return flag_schedule_speculative_load_dangerous;
2769 }                               /* is_exception_free */
2770
2771
2772 /* Process an insn's memory dependencies.  There are four kinds of
2773    dependencies:
2774
2775    (0) read dependence: read follows read
2776    (1) true dependence: read follows write
2777    (2) anti dependence: write follows read
2778    (3) output dependence: write follows write
2779
2780    We are careful to build only dependencies which actually exist, and
2781    use transitivity to avoid building too many links.  */
2782 \f
2783 /* Return the INSN_LIST containing INSN in LIST, or NULL
2784    if LIST does not contain INSN.  */
2785
2786 HAIFA_INLINE static rtx
2787 find_insn_list (insn, list)
2788      rtx insn;
2789      rtx list;
2790 {
2791   while (list)
2792     {
2793       if (XEXP (list, 0) == insn)
2794         return list;
2795       list = XEXP (list, 1);
2796     }
2797   return 0;
2798 }
2799
2800
2801 /* Return 1 if the pair (insn, x) is found in (LIST, LIST1), or 0 otherwise.  */
2802
2803 HAIFA_INLINE static char
2804 find_insn_mem_list (insn, x, list, list1)
2805      rtx insn, x;
2806      rtx list, list1;
2807 {
2808   while (list)
2809     {
2810       if (XEXP (list, 0) == insn
2811           && XEXP (list1, 0) == x)
2812         return 1;
2813       list = XEXP (list, 1);
2814       list1 = XEXP (list1, 1);
2815     }
2816   return 0;
2817 }
2818
2819
2820 /* Compute the function units used by INSN.  This caches the value
2821    returned by function_units_used.  A function unit is encoded as the
2822    unit number if the value is non-negative and the compliment of a
2823    mask if the value is negative.  A function unit index is the
2824    non-negative encoding.  */
2825
2826 HAIFA_INLINE static int
2827 insn_unit (insn)
2828      rtx insn;
2829 {
2830   register int unit = INSN_UNIT (insn);
2831
2832   if (unit == 0)
2833     {
2834       recog_memoized (insn);
2835
2836       /* A USE insn, or something else we don't need to understand.
2837          We can't pass these directly to function_units_used because it will
2838          trigger a fatal error for unrecognizable insns.  */
2839       if (INSN_CODE (insn) < 0)
2840         unit = -1;
2841       else
2842         {
2843           unit = function_units_used (insn);
2844           /* Increment non-negative values so we can cache zero.  */
2845           if (unit >= 0)
2846             unit++;
2847         }
2848       /* We only cache 16 bits of the result, so if the value is out of
2849          range, don't cache it.  */
2850       if (FUNCTION_UNITS_SIZE < HOST_BITS_PER_SHORT
2851           || unit >= 0
2852           || (~unit & ((1 << (HOST_BITS_PER_SHORT - 1)) - 1)) == 0)
2853         INSN_UNIT (insn) = unit;
2854     }
2855   return (unit > 0 ? unit - 1 : unit);
2856 }
2857
2858 /* Compute the blockage range for executing INSN on UNIT.  This caches
2859    the value returned by the blockage_range_function for the unit.
2860    These values are encoded in an int where the upper half gives the
2861    minimum value and the lower half gives the maximum value.  */
2862
2863 HAIFA_INLINE static unsigned int
2864 blockage_range (unit, insn)
2865      int unit;
2866      rtx insn;
2867 {
2868   unsigned int blockage = INSN_BLOCKAGE (insn);
2869   unsigned int range;
2870
2871   if ((int) UNIT_BLOCKED (blockage) != unit + 1)
2872     {
2873       range = function_units[unit].blockage_range_function (insn);
2874       /* We only cache the blockage range for one unit and then only if
2875          the values fit.  */
2876       if (HOST_BITS_PER_INT >= UNIT_BITS + 2 * BLOCKAGE_BITS)
2877         INSN_BLOCKAGE (insn) = ENCODE_BLOCKAGE (unit + 1, range);
2878     }
2879   else
2880     range = BLOCKAGE_RANGE (blockage);
2881
2882   return range;
2883 }
2884
2885 /* A vector indexed by function unit instance giving the last insn to use
2886    the unit.  The value of the function unit instance index for unit U
2887    instance I is (U + I * FUNCTION_UNITS_SIZE).  */
2888 static rtx unit_last_insn[FUNCTION_UNITS_SIZE * MAX_MULTIPLICITY];
2889
2890 /* A vector indexed by function unit instance giving the minimum time when
2891    the unit will unblock based on the maximum blockage cost.  */
2892 static int unit_tick[FUNCTION_UNITS_SIZE * MAX_MULTIPLICITY];
2893
2894 /* A vector indexed by function unit number giving the number of insns
2895    that remain to use the unit.  */
2896 static int unit_n_insns[FUNCTION_UNITS_SIZE];
2897
2898 /* Reset the function unit state to the null state.  */
2899
2900 static void
2901 clear_units ()
2902 {
2903   bzero ((char *) unit_last_insn, sizeof (unit_last_insn));
2904   bzero ((char *) unit_tick, sizeof (unit_tick));
2905   bzero ((char *) unit_n_insns, sizeof (unit_n_insns));
2906 }
2907
2908 /* Return the issue-delay of an insn */
2909
2910 HAIFA_INLINE static int
2911 insn_issue_delay (insn)
2912      rtx insn;
2913 {
2914   int i, delay = 0;
2915   int unit = insn_unit (insn);
2916
2917   /* efficiency note: in fact, we are working 'hard' to compute a
2918      value that was available in md file, and is not available in
2919      function_units[] structure.  It would be nice to have this
2920      value there, too.  */
2921   if (unit >= 0)
2922     {
2923       if (function_units[unit].blockage_range_function &&
2924           function_units[unit].blockage_function)
2925         delay = function_units[unit].blockage_function (insn, insn);
2926     }
2927   else
2928     for (i = 0, unit = ~unit; unit; i++, unit >>= 1)
2929       if ((unit & 1) != 0 && function_units[i].blockage_range_function
2930           && function_units[i].blockage_function)
2931         delay = MAX (delay, function_units[i].blockage_function (insn, insn));
2932
2933   return delay;
2934 }
2935
2936 /* Return the actual hazard cost of executing INSN on the unit UNIT,
2937    instance INSTANCE at time CLOCK if the previous actual hazard cost
2938    was COST.  */
2939
2940 HAIFA_INLINE static int
2941 actual_hazard_this_instance (unit, instance, insn, clock, cost)
2942      int unit, instance, clock, cost;
2943      rtx insn;
2944 {
2945   int tick = unit_tick[instance];       /* issue time of the last issued insn */
2946
2947   if (tick - clock > cost)
2948     {
2949       /* The scheduler is operating forward, so unit's last insn is the
2950          executing insn and INSN is the candidate insn.  We want a
2951          more exact measure of the blockage if we execute INSN at CLOCK
2952          given when we committed the execution of the unit's last insn.
2953
2954          The blockage value is given by either the unit's max blockage
2955          constant, blockage range function, or blockage function.  Use
2956          the most exact form for the given unit.  */
2957
2958       if (function_units[unit].blockage_range_function)
2959         {
2960           if (function_units[unit].blockage_function)
2961             tick += (function_units[unit].blockage_function
2962                      (unit_last_insn[instance], insn)
2963                      - function_units[unit].max_blockage);
2964           else
2965             tick += ((int) MAX_BLOCKAGE_COST (blockage_range (unit, insn))
2966                      - function_units[unit].max_blockage);
2967         }
2968       if (tick - clock > cost)
2969         cost = tick - clock;
2970     }
2971   return cost;
2972 }
2973
2974 /* Record INSN as having begun execution on the units encoded by UNIT at
2975    time CLOCK.  */
2976
2977 HAIFA_INLINE static void
2978 schedule_unit (unit, insn, clock)
2979      int unit, clock;
2980      rtx insn;
2981 {
2982   int i;
2983
2984   if (unit >= 0)
2985     {
2986       int instance = unit;
2987 #if MAX_MULTIPLICITY > 1
2988       /* Find the first free instance of the function unit and use that
2989          one.  We assume that one is free.  */
2990       for (i = function_units[unit].multiplicity - 1; i > 0; i--)
2991         {
2992           if (!actual_hazard_this_instance (unit, instance, insn, clock, 0))
2993             break;
2994           instance += FUNCTION_UNITS_SIZE;
2995         }
2996 #endif
2997       unit_last_insn[instance] = insn;
2998       unit_tick[instance] = (clock + function_units[unit].max_blockage);
2999     }
3000   else
3001     for (i = 0, unit = ~unit; unit; i++, unit >>= 1)
3002       if ((unit & 1) != 0)
3003         schedule_unit (i, insn, clock);
3004 }
3005
3006 /* Return the actual hazard cost of executing INSN on the units encoded by
3007    UNIT at time CLOCK if the previous actual hazard cost was COST.  */
3008
3009 HAIFA_INLINE static int
3010 actual_hazard (unit, insn, clock, cost)
3011      int unit, clock, cost;
3012      rtx insn;
3013 {
3014   int i;
3015
3016   if (unit >= 0)
3017     {
3018       /* Find the instance of the function unit with the minimum hazard.  */
3019       int instance = unit;
3020       int best_cost = actual_hazard_this_instance (unit, instance, insn,
3021                                                    clock, cost);
3022       int this_cost;
3023
3024 #if MAX_MULTIPLICITY > 1
3025       if (best_cost > cost)
3026         {
3027           for (i = function_units[unit].multiplicity - 1; i > 0; i--)
3028             {
3029               instance += FUNCTION_UNITS_SIZE;
3030               this_cost = actual_hazard_this_instance (unit, instance, insn,
3031                                                        clock, cost);
3032               if (this_cost < best_cost)
3033                 {
3034                   best_cost = this_cost;
3035                   if (this_cost <= cost)
3036                     break;
3037                 }
3038             }
3039         }
3040 #endif
3041       cost = MAX (cost, best_cost);
3042     }
3043   else
3044     for (i = 0, unit = ~unit; unit; i++, unit >>= 1)
3045       if ((unit & 1) != 0)
3046         cost = actual_hazard (i, insn, clock, cost);
3047
3048   return cost;
3049 }
3050
3051 /* Return the potential hazard cost of executing an instruction on the
3052    units encoded by UNIT if the previous potential hazard cost was COST.
3053    An insn with a large blockage time is chosen in preference to one
3054    with a smaller time; an insn that uses a unit that is more likely
3055    to be used is chosen in preference to one with a unit that is less
3056    used.  We are trying to minimize a subsequent actual hazard.  */
3057
3058 HAIFA_INLINE static int
3059 potential_hazard (unit, insn, cost)
3060      int unit, cost;
3061      rtx insn;
3062 {
3063   int i, ncost;
3064   unsigned int minb, maxb;
3065
3066   if (unit >= 0)
3067     {
3068       minb = maxb = function_units[unit].max_blockage;
3069       if (maxb > 1)
3070         {
3071           if (function_units[unit].blockage_range_function)
3072             {
3073               maxb = minb = blockage_range (unit, insn);
3074               maxb = MAX_BLOCKAGE_COST (maxb);
3075               minb = MIN_BLOCKAGE_COST (minb);
3076             }
3077
3078           if (maxb > 1)
3079             {
3080               /* Make the number of instructions left dominate.  Make the
3081                  minimum delay dominate the maximum delay.  If all these
3082                  are the same, use the unit number to add an arbitrary
3083                  ordering.  Other terms can be added.  */
3084               ncost = minb * 0x40 + maxb;
3085               ncost *= (unit_n_insns[unit] - 1) * 0x1000 + unit;
3086               if (ncost > cost)
3087                 cost = ncost;
3088             }
3089         }
3090     }
3091   else
3092     for (i = 0, unit = ~unit; unit; i++, unit >>= 1)
3093       if ((unit & 1) != 0)
3094         cost = potential_hazard (i, insn, cost);
3095
3096   return cost;
3097 }
3098
3099 /* Compute cost of executing INSN given the dependence LINK on the insn USED.
3100    This is the number of cycles between instruction issue and
3101    instruction results.  */
3102
3103 HAIFA_INLINE static int
3104 insn_cost (insn, link, used)
3105      rtx insn, link, used;
3106 {
3107   register int cost = INSN_COST (insn);
3108
3109   if (cost == 0)
3110     {
3111       recog_memoized (insn);
3112
3113       /* A USE insn, or something else we don't need to understand.
3114          We can't pass these directly to result_ready_cost because it will
3115          trigger a fatal error for unrecognizable insns.  */
3116       if (INSN_CODE (insn) < 0)
3117         {
3118           INSN_COST (insn) = 1;
3119           return 1;
3120         }
3121       else
3122         {
3123           cost = result_ready_cost (insn);
3124
3125           if (cost < 1)
3126             cost = 1;
3127
3128           INSN_COST (insn) = cost;
3129         }
3130     }
3131
3132   /* in this case estimate cost without caring how insn is used.  */
3133   if (link == 0 && used == 0)
3134     return cost;
3135
3136   /* A USE insn should never require the value used to be computed.  This
3137      allows the computation of a function's result and parameter values to
3138      overlap the return and call.  */
3139   recog_memoized (used);
3140   if (INSN_CODE (used) < 0)
3141     LINK_COST_FREE (link) = 1;
3142
3143   /* If some dependencies vary the cost, compute the adjustment.  Most
3144      commonly, the adjustment is complete: either the cost is ignored
3145      (in the case of an output- or anti-dependence), or the cost is
3146      unchanged.  These values are cached in the link as LINK_COST_FREE
3147      and LINK_COST_ZERO.  */
3148
3149   if (LINK_COST_FREE (link))
3150     cost = 0;
3151 #ifdef ADJUST_COST
3152   else if (!LINK_COST_ZERO (link))
3153     {
3154       int ncost = cost;
3155
3156       ADJUST_COST (used, link, insn, ncost);
3157       if (ncost < 1)
3158         {
3159           LINK_COST_FREE (link) = 1;
3160           ncost = 0;
3161         }
3162       if (cost == ncost)
3163         LINK_COST_ZERO (link) = 1;
3164       cost = ncost;
3165     }
3166 #endif
3167   return cost;
3168 }
3169
3170 /* Compute the priority number for INSN.  */
3171
3172 static int
3173 priority (insn)
3174      rtx insn;
3175 {
3176   int this_priority;
3177   rtx link;
3178
3179   if (GET_RTX_CLASS (GET_CODE (insn)) != 'i')
3180     return 0;
3181
3182   if ((this_priority = INSN_PRIORITY (insn)) == 0)
3183     {
3184       if (INSN_DEPEND (insn) == 0)
3185         this_priority = insn_cost (insn, 0, 0);
3186       else
3187         for (link = INSN_DEPEND (insn); link; link = XEXP (link, 1))
3188           {
3189             rtx next;
3190             int next_priority;
3191
3192             if (RTX_INTEGRATED_P (link))
3193               continue;
3194
3195             next = XEXP (link, 0);
3196
3197             /* critical path is meaningful in block boundaries only */
3198             if (INSN_BLOCK (next) != INSN_BLOCK (insn))
3199               continue;
3200
3201             next_priority = insn_cost (insn, link, next) + priority (next);
3202             if (next_priority > this_priority)
3203               this_priority = next_priority;
3204           }
3205       INSN_PRIORITY (insn) = this_priority;
3206     }
3207   return this_priority;
3208 }
3209 \f
3210
3211 /* Remove all INSN_LISTs and EXPR_LISTs from the pending lists and add
3212    them to the unused_*_list variables, so that they can be reused.  */
3213
3214 static void
3215 free_pending_lists ()
3216 {
3217   if (current_nr_blocks <= 1)
3218     {
3219       free_list (&pending_read_insns, &unused_insn_list);
3220       free_list (&pending_write_insns, &unused_insn_list);
3221       free_list (&pending_read_mems, &unused_expr_list);
3222       free_list (&pending_write_mems, &unused_expr_list);
3223     }
3224   else
3225     {
3226       /* interblock scheduling */
3227       int bb;
3228
3229       for (bb = 0; bb < current_nr_blocks; bb++)
3230         {
3231           free_list (&bb_pending_read_insns[bb], &unused_insn_list);
3232           free_list (&bb_pending_write_insns[bb], &unused_insn_list);
3233           free_list (&bb_pending_read_mems[bb], &unused_expr_list);
3234           free_list (&bb_pending_write_mems[bb], &unused_expr_list);
3235         }
3236     }
3237 }
3238
3239 /* Add an INSN and MEM reference pair to a pending INSN_LIST and MEM_LIST.
3240    The MEM is a memory reference contained within INSN, which we are saving
3241    so that we can do memory aliasing on it.  */
3242
3243 static void
3244 add_insn_mem_dependence (insn_list, mem_list, insn, mem)
3245      rtx *insn_list, *mem_list, insn, mem;
3246 {
3247   register rtx link;
3248
3249   link = alloc_INSN_LIST (insn, *insn_list);
3250   *insn_list = link;
3251
3252   link = alloc_EXPR_LIST (VOIDmode, mem, *mem_list);
3253   *mem_list = link;
3254
3255   pending_lists_length++;
3256 }
3257 \f
3258
3259 /* Make a dependency between every memory reference on the pending lists
3260    and INSN, thus flushing the pending lists.  If ONLY_WRITE, don't flush
3261    the read list.  */
3262
3263 static void
3264 flush_pending_lists (insn, only_write)
3265      rtx insn;
3266      int only_write;
3267 {
3268   rtx u;
3269   rtx link;
3270
3271   while (pending_read_insns && ! only_write)
3272     {
3273       add_dependence (insn, XEXP (pending_read_insns, 0), REG_DEP_ANTI);
3274
3275       link = pending_read_insns;
3276       pending_read_insns = XEXP (pending_read_insns, 1);
3277       XEXP (link, 1) = unused_insn_list;
3278       unused_insn_list = link;
3279
3280       link = pending_read_mems;
3281       pending_read_mems = XEXP (pending_read_mems, 1);
3282       XEXP (link, 1) = unused_expr_list;
3283       unused_expr_list = link;
3284     }
3285   while (pending_write_insns)
3286     {
3287       add_dependence (insn, XEXP (pending_write_insns, 0), REG_DEP_ANTI);
3288
3289       link = pending_write_insns;
3290       pending_write_insns = XEXP (pending_write_insns, 1);
3291       XEXP (link, 1) = unused_insn_list;
3292       unused_insn_list = link;
3293
3294       link = pending_write_mems;
3295       pending_write_mems = XEXP (pending_write_mems, 1);
3296       XEXP (link, 1) = unused_expr_list;
3297       unused_expr_list = link;
3298     }
3299   pending_lists_length = 0;
3300
3301   /* last_pending_memory_flush is now a list of insns */
3302   for (u = last_pending_memory_flush; u; u = XEXP (u, 1))
3303     add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
3304
3305   free_list (&last_pending_memory_flush, &unused_insn_list);
3306   last_pending_memory_flush = alloc_INSN_LIST (insn, NULL_RTX);
3307 }
3308
3309 /* Analyze a single SET or CLOBBER rtx, X, creating all dependencies generated
3310    by the write to the destination of X, and reads of everything mentioned.  */
3311
3312 static void
3313 sched_analyze_1 (x, insn)
3314      rtx x;
3315      rtx insn;
3316 {
3317   register int regno;
3318   register rtx dest = SET_DEST (x);
3319   enum rtx_code code = GET_CODE (x);
3320
3321   if (dest == 0)
3322     return;
3323
3324   if (GET_CODE (dest) == PARALLEL
3325       && GET_MODE (dest) == BLKmode)
3326     {
3327       register int i;
3328       for (i = XVECLEN (dest, 0) - 1; i >= 0; i--)
3329         sched_analyze_1 (XVECEXP (dest, 0, i), insn);
3330       if (GET_CODE (x) == SET)
3331         sched_analyze_2 (SET_SRC (x), insn);
3332       return;
3333     }
3334
3335   while (GET_CODE (dest) == STRICT_LOW_PART || GET_CODE (dest) == SUBREG
3336       || GET_CODE (dest) == ZERO_EXTRACT || GET_CODE (dest) == SIGN_EXTRACT)
3337     {
3338       if (GET_CODE (dest) == ZERO_EXTRACT || GET_CODE (dest) == SIGN_EXTRACT)
3339         {
3340           /* The second and third arguments are values read by this insn.  */
3341           sched_analyze_2 (XEXP (dest, 1), insn);
3342           sched_analyze_2 (XEXP (dest, 2), insn);
3343         }
3344       dest = SUBREG_REG (dest);
3345     }
3346
3347   if (GET_CODE (dest) == REG)
3348     {
3349       register int i;
3350
3351       regno = REGNO (dest);
3352
3353       /* A hard reg in a wide mode may really be multiple registers.
3354          If so, mark all of them just like the first.  */
3355       if (regno < FIRST_PSEUDO_REGISTER)
3356         {
3357           i = HARD_REGNO_NREGS (regno, GET_MODE (dest));
3358           while (--i >= 0)
3359             {
3360               rtx u;
3361
3362               for (u = reg_last_uses[regno + i]; u; u = XEXP (u, 1))
3363                 add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
3364
3365               for (u = reg_last_sets[regno + i]; u; u = XEXP (u, 1))
3366                 add_dependence (insn, XEXP (u, 0), REG_DEP_OUTPUT);
3367
3368               /* Clobbers need not be ordered with respect to one another,
3369                  but sets must be ordered with respect to a pending clobber. */
3370               if (code == SET)
3371                 {
3372                   free_list (&reg_last_uses[regno + i], &unused_insn_list);
3373                   for (u = reg_last_clobbers[regno + i]; u; u = XEXP (u, 1))
3374                     add_dependence (insn, XEXP (u, 0), REG_DEP_OUTPUT);
3375                   SET_REGNO_REG_SET (reg_pending_sets, regno + i);
3376                 }
3377               else
3378                 SET_REGNO_REG_SET (reg_pending_clobbers, regno + i);
3379
3380               /* Function calls clobber all call_used regs.  */
3381               if (global_regs[regno + i]
3382                   || (code == SET && call_used_regs[regno + i]))
3383                 for (u = last_function_call; u; u = XEXP (u, 1))
3384                   add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
3385             }
3386         }
3387       else
3388         {
3389           rtx u;
3390
3391           for (u = reg_last_uses[regno]; u; u = XEXP (u, 1))
3392             add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
3393
3394           for (u = reg_last_sets[regno]; u; u = XEXP (u, 1))
3395             add_dependence (insn, XEXP (u, 0), REG_DEP_OUTPUT);
3396
3397           if (code == SET)
3398             {
3399               free_list (&reg_last_uses[regno], &unused_insn_list);
3400               for (u = reg_last_clobbers[regno]; u; u = XEXP (u, 1))
3401                 add_dependence (insn, XEXP (u, 0), REG_DEP_OUTPUT);
3402               SET_REGNO_REG_SET (reg_pending_sets, regno);
3403             }
3404           else
3405             SET_REGNO_REG_SET (reg_pending_clobbers, regno);
3406
3407           /* Pseudos that are REG_EQUIV to something may be replaced
3408              by that during reloading.  We need only add dependencies for
3409              the address in the REG_EQUIV note.  */
3410           if (!reload_completed
3411               && reg_known_equiv_p[regno]
3412               && GET_CODE (reg_known_value[regno]) == MEM)
3413             sched_analyze_2 (XEXP (reg_known_value[regno], 0), insn);
3414
3415           /* Don't let it cross a call after scheduling if it doesn't
3416              already cross one.  */
3417
3418           if (REG_N_CALLS_CROSSED (regno) == 0)
3419             for (u = last_function_call; u; u = XEXP (u, 1))
3420               add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
3421         }
3422     }
3423   else if (GET_CODE (dest) == MEM)
3424     {
3425       /* Writing memory.  */
3426
3427       if (pending_lists_length > 32)
3428         {
3429           /* Flush all pending reads and writes to prevent the pending lists
3430              from getting any larger.  Insn scheduling runs too slowly when
3431              these lists get long.  The number 32 was chosen because it
3432              seems like a reasonable number.  When compiling GCC with itself,
3433              this flush occurs 8 times for sparc, and 10 times for m88k using
3434              the number 32.  */
3435           flush_pending_lists (insn, 0);
3436         }
3437       else
3438         {
3439           rtx u;
3440           rtx pending, pending_mem;
3441
3442           pending = pending_read_insns;
3443           pending_mem = pending_read_mems;
3444           while (pending)
3445             {
3446               /* If a dependency already exists, don't create a new one.  */
3447               if (!find_insn_list (XEXP (pending, 0), LOG_LINKS (insn)))
3448                 if (anti_dependence (XEXP (pending_mem, 0), dest))
3449                   add_dependence (insn, XEXP (pending, 0), REG_DEP_ANTI);
3450
3451               pending = XEXP (pending, 1);
3452               pending_mem = XEXP (pending_mem, 1);
3453             }
3454
3455           pending = pending_write_insns;
3456           pending_mem = pending_write_mems;
3457           while (pending)
3458             {
3459               /* If a dependency already exists, don't create a new one.  */
3460               if (!find_insn_list (XEXP (pending, 0), LOG_LINKS (insn)))
3461                 if (output_dependence (XEXP (pending_mem, 0), dest))
3462                   add_dependence (insn, XEXP (pending, 0), REG_DEP_OUTPUT);
3463
3464               pending = XEXP (pending, 1);
3465               pending_mem = XEXP (pending_mem, 1);
3466             }
3467
3468           for (u = last_pending_memory_flush; u; u = XEXP (u, 1))
3469             add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
3470
3471           add_insn_mem_dependence (&pending_write_insns, &pending_write_mems,
3472                                    insn, dest);
3473         }
3474       sched_analyze_2 (XEXP (dest, 0), insn);
3475     }
3476
3477   /* Analyze reads.  */
3478   if (GET_CODE (x) == SET)
3479     sched_analyze_2 (SET_SRC (x), insn);
3480 }
3481
3482 /* Analyze the uses of memory and registers in rtx X in INSN.  */
3483
3484 static void
3485 sched_analyze_2 (x, insn)
3486      rtx x;
3487      rtx insn;
3488 {
3489   register int i;
3490   register int j;
3491   register enum rtx_code code;
3492   register char *fmt;
3493
3494   if (x == 0)
3495     return;
3496
3497   code = GET_CODE (x);
3498
3499   switch (code)
3500     {
3501     case CONST_INT:
3502     case CONST_DOUBLE:
3503     case SYMBOL_REF:
3504     case CONST:
3505     case LABEL_REF:
3506       /* Ignore constants.  Note that we must handle CONST_DOUBLE here
3507          because it may have a cc0_rtx in its CONST_DOUBLE_CHAIN field, but
3508          this does not mean that this insn is using cc0.  */
3509       return;
3510
3511 #ifdef HAVE_cc0
3512     case CC0:
3513       {
3514         rtx link, prev;
3515
3516         /* User of CC0 depends on immediately preceding insn.  */
3517         SCHED_GROUP_P (insn) = 1;
3518
3519         /* There may be a note before this insn now, but all notes will
3520            be removed before we actually try to schedule the insns, so
3521            it won't cause a problem later.  We must avoid it here though.  */
3522         prev = prev_nonnote_insn (insn);
3523
3524         /* Make a copy of all dependencies on the immediately previous insn,
3525            and add to this insn.  This is so that all the dependencies will
3526            apply to the group.  Remove an explicit dependence on this insn
3527            as SCHED_GROUP_P now represents it.  */
3528
3529         if (find_insn_list (prev, LOG_LINKS (insn)))
3530           remove_dependence (insn, prev);
3531
3532         for (link = LOG_LINKS (prev); link; link = XEXP (link, 1))
3533           add_dependence (insn, XEXP (link, 0), REG_NOTE_KIND (link));
3534
3535         return;
3536       }
3537 #endif
3538
3539     case REG:
3540       {
3541         rtx u;
3542         int regno = REGNO (x);
3543         if (regno < FIRST_PSEUDO_REGISTER)
3544           {
3545             int i;
3546
3547             i = HARD_REGNO_NREGS (regno, GET_MODE (x));
3548             while (--i >= 0)
3549               {
3550                 reg_last_uses[regno + i]
3551                   = alloc_INSN_LIST (insn, reg_last_uses[regno + i]);
3552
3553                 for (u = reg_last_sets[regno + i]; u; u = XEXP (u, 1))
3554                   add_dependence (insn, XEXP (u, 0), 0);
3555
3556                 /* ??? This should never happen.  */
3557                 for (u = reg_last_clobbers[regno + i]; u; u = XEXP (u, 1))
3558                   add_dependence (insn, XEXP (u, 0), 0);
3559
3560                 if ((call_used_regs[regno + i] || global_regs[regno + i]))
3561                   /* Function calls clobber all call_used regs.  */
3562                   for (u = last_function_call; u; u = XEXP (u, 1))
3563                     add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
3564               }
3565           }
3566         else
3567           {
3568             reg_last_uses[regno] = alloc_INSN_LIST (insn, reg_last_uses[regno]);
3569
3570             for (u = reg_last_sets[regno]; u; u = XEXP (u, 1))
3571               add_dependence (insn, XEXP (u, 0), 0);
3572
3573             /* ??? This should never happen.  */
3574             for (u = reg_last_clobbers[regno]; u; u = XEXP (u, 1))
3575               add_dependence (insn, XEXP (u, 0), 0);
3576
3577             /* Pseudos that are REG_EQUIV to something may be replaced
3578                by that during reloading.  We need only add dependencies for
3579                the address in the REG_EQUIV note.  */
3580             if (!reload_completed
3581                 && reg_known_equiv_p[regno]
3582                 && GET_CODE (reg_known_value[regno]) == MEM)
3583               sched_analyze_2 (XEXP (reg_known_value[regno], 0), insn);
3584
3585             /* If the register does not already cross any calls, then add this
3586                insn to the sched_before_next_call list so that it will still
3587                not cross calls after scheduling.  */
3588             if (REG_N_CALLS_CROSSED (regno) == 0)
3589               add_dependence (sched_before_next_call, insn, REG_DEP_ANTI);
3590           }
3591         return;
3592       }
3593
3594     case MEM:
3595       {
3596         /* Reading memory.  */
3597         rtx u;
3598         rtx pending, pending_mem;
3599
3600         pending = pending_read_insns;
3601         pending_mem = pending_read_mems;
3602         while (pending)
3603           {
3604             /* If a dependency already exists, don't create a new one.  */
3605             if (!find_insn_list (XEXP (pending, 0), LOG_LINKS (insn)))
3606               if (read_dependence (XEXP (pending_mem, 0), x))
3607                 add_dependence (insn, XEXP (pending, 0), REG_DEP_ANTI);
3608
3609             pending = XEXP (pending, 1);
3610             pending_mem = XEXP (pending_mem, 1);
3611           }
3612
3613         pending = pending_write_insns;
3614         pending_mem = pending_write_mems;
3615         while (pending)
3616           {
3617             /* If a dependency already exists, don't create a new one.  */
3618             if (!find_insn_list (XEXP (pending, 0), LOG_LINKS (insn)))
3619               if (true_dependence (XEXP (pending_mem, 0), VOIDmode,
3620                   x, rtx_varies_p))
3621                 add_dependence (insn, XEXP (pending, 0), 0);
3622
3623             pending = XEXP (pending, 1);
3624             pending_mem = XEXP (pending_mem, 1);
3625           }
3626
3627         for (u = last_pending_memory_flush; u; u = XEXP (u, 1))
3628           add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
3629
3630         /* Always add these dependencies to pending_reads, since
3631            this insn may be followed by a write.  */
3632         add_insn_mem_dependence (&pending_read_insns, &pending_read_mems,
3633                                  insn, x);
3634
3635         /* Take advantage of tail recursion here.  */
3636         sched_analyze_2 (XEXP (x, 0), insn);
3637         return;
3638       }
3639
3640     /* Force pending stores to memory in case a trap handler needs them.  */
3641     case TRAP_IF:
3642       flush_pending_lists (insn, 1);
3643       break;
3644
3645     case ASM_OPERANDS:
3646     case ASM_INPUT:
3647     case UNSPEC_VOLATILE:
3648       {
3649         rtx u;
3650
3651         /* Traditional and volatile asm instructions must be considered to use
3652            and clobber all hard registers, all pseudo-registers and all of
3653            memory.  So must TRAP_IF and UNSPEC_VOLATILE operations.
3654
3655            Consider for instance a volatile asm that changes the fpu rounding
3656            mode.  An insn should not be moved across this even if it only uses
3657            pseudo-regs because it might give an incorrectly rounded result.  */
3658         if (code != ASM_OPERANDS || MEM_VOLATILE_P (x))
3659           {
3660             int max_reg = max_reg_num ();
3661             for (i = 0; i < max_reg; i++)
3662               {
3663                 for (u = reg_last_uses[i]; u; u = XEXP (u, 1))
3664                   add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
3665                 free_list (&reg_last_uses[i], &unused_insn_list);
3666
3667                 for (u = reg_last_sets[i]; u; u = XEXP (u, 1))
3668                   add_dependence (insn, XEXP (u, 0), 0);
3669
3670                 for (u = reg_last_clobbers[i]; u; u = XEXP (u, 1))
3671                   add_dependence (insn, XEXP (u, 0), 0);
3672               }
3673             reg_pending_sets_all = 1;
3674
3675             flush_pending_lists (insn, 0);
3676           }
3677
3678         /* For all ASM_OPERANDS, we must traverse the vector of input operands.
3679            We can not just fall through here since then we would be confused
3680            by the ASM_INPUT rtx inside ASM_OPERANDS, which do not indicate
3681            traditional asms unlike their normal usage.  */
3682
3683         if (code == ASM_OPERANDS)
3684           {
3685             for (j = 0; j < ASM_OPERANDS_INPUT_LENGTH (x); j++)
3686               sched_analyze_2 (ASM_OPERANDS_INPUT (x, j), insn);
3687             return;
3688           }
3689         break;
3690       }
3691
3692     case PRE_DEC:
3693     case POST_DEC:
3694     case PRE_INC:
3695     case POST_INC:
3696       /* These both read and modify the result.  We must handle them as writes
3697          to get proper dependencies for following instructions.  We must handle
3698          them as reads to get proper dependencies from this to previous
3699          instructions.  Thus we need to pass them to both sched_analyze_1
3700          and sched_analyze_2.  We must call sched_analyze_2 first in order
3701          to get the proper antecedent for the read.  */
3702       sched_analyze_2 (XEXP (x, 0), insn);
3703       sched_analyze_1 (x, insn);
3704       return;
3705
3706     default:
3707       break;
3708     }
3709
3710   /* Other cases: walk the insn.  */
3711   fmt = GET_RTX_FORMAT (code);
3712   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
3713     {
3714       if (fmt[i] == 'e')
3715         sched_analyze_2 (XEXP (x, i), insn);
3716       else if (fmt[i] == 'E')
3717         for (j = 0; j < XVECLEN (x, i); j++)
3718           sched_analyze_2 (XVECEXP (x, i, j), insn);
3719     }
3720 }
3721
3722 /* Analyze an INSN with pattern X to find all dependencies.  */
3723
3724 static void
3725 sched_analyze_insn (x, insn, loop_notes)
3726      rtx x, insn;
3727      rtx loop_notes;
3728 {
3729   register RTX_CODE code = GET_CODE (x);
3730   rtx link;
3731   int maxreg = max_reg_num ();
3732   int i;
3733
3734   if (code == SET || code == CLOBBER)
3735     sched_analyze_1 (x, insn);
3736   else if (code == PARALLEL)
3737     {
3738       register int i;
3739       for (i = XVECLEN (x, 0) - 1; i >= 0; i--)
3740         {
3741           code = GET_CODE (XVECEXP (x, 0, i));
3742           if (code == SET || code == CLOBBER)
3743             sched_analyze_1 (XVECEXP (x, 0, i), insn);
3744           else
3745             sched_analyze_2 (XVECEXP (x, 0, i), insn);
3746         }
3747     }
3748   else
3749     sched_analyze_2 (x, insn);
3750
3751   /* Mark registers CLOBBERED or used by called function.  */
3752   if (GET_CODE (insn) == CALL_INSN)
3753     for (link = CALL_INSN_FUNCTION_USAGE (insn); link; link = XEXP (link, 1))
3754       {
3755         if (GET_CODE (XEXP (link, 0)) == CLOBBER)
3756           sched_analyze_1 (XEXP (link, 0), insn);
3757         else
3758           sched_analyze_2 (XEXP (link, 0), insn);
3759       }
3760
3761   /* If there is a {LOOP,EHREGION}_{BEG,END} note in the middle of a basic
3762      block, then we must be sure that no instructions are scheduled across it.
3763      Otherwise, the reg_n_refs info (which depends on loop_depth) would
3764      become incorrect.  */
3765
3766   if (loop_notes)
3767     {
3768       int max_reg = max_reg_num ();
3769       int schedule_barrier_found = 0;
3770       rtx link;
3771
3772       /* Update loop_notes with any notes from this insn.  Also determine
3773          if any of the notes on the list correspond to instruction scheduling
3774          barriers (loop, eh & setjmp notes, but not range notes.  */
3775       link = loop_notes;
3776       while (XEXP (link, 1))
3777         {
3778           if (INTVAL (XEXP (link, 0)) == NOTE_INSN_LOOP_BEG
3779               || INTVAL (XEXP (link, 0)) == NOTE_INSN_LOOP_END
3780               || INTVAL (XEXP (link, 0)) == NOTE_INSN_EH_REGION_BEG
3781               || INTVAL (XEXP (link, 0)) == NOTE_INSN_EH_REGION_END
3782               || INTVAL (XEXP (link, 0)) == NOTE_INSN_SETJMP)
3783             schedule_barrier_found = 1;
3784
3785           link = XEXP (link, 1);
3786         }
3787       XEXP (link, 1) = REG_NOTES (insn);
3788       REG_NOTES (insn) = loop_notes;
3789
3790       /* Add dependencies if a scheduling barrier was found.  */
3791       if (schedule_barrier_found)
3792         {
3793           for (i = 0; i < max_reg; i++)
3794             {
3795               rtx u;
3796               for (u = reg_last_uses[i]; u; u = XEXP (u, 1))
3797                 add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
3798               free_list (&reg_last_uses[i], &unused_insn_list);
3799
3800               for (u = reg_last_sets[i]; u; u = XEXP (u, 1))
3801                 add_dependence (insn, XEXP (u, 0), 0);
3802
3803               for (u = reg_last_clobbers[i]; u; u = XEXP (u, 1))
3804                 add_dependence (insn, XEXP (u, 0), 0);
3805             }
3806           reg_pending_sets_all = 1;
3807
3808           flush_pending_lists (insn, 0);
3809         }
3810
3811     }
3812
3813   /* Accumulate clobbers until the next set so that it will be output dependant
3814      on all of them.  At the next set we can clear the clobber list, since
3815      subsequent sets will be output dependant on it.  */
3816   EXECUTE_IF_SET_IN_REG_SET (reg_pending_sets, 0, i,
3817                              {
3818                                free_list (&reg_last_sets[i], &unused_insn_list);
3819                                free_list (&reg_last_clobbers[i],
3820                                           &unused_insn_list);
3821                                reg_last_sets[i]
3822                                  = alloc_INSN_LIST (insn, NULL_RTX);
3823                              });
3824   EXECUTE_IF_SET_IN_REG_SET (reg_pending_clobbers, 0, i,
3825                              {
3826                                reg_last_clobbers[i]
3827                                  = alloc_INSN_LIST (insn, reg_last_clobbers[i]);
3828                              });
3829   CLEAR_REG_SET (reg_pending_sets);
3830   CLEAR_REG_SET (reg_pending_clobbers);
3831
3832   if (reg_pending_sets_all)
3833     {
3834       for (i = 0; i < maxreg; i++)
3835         {
3836           free_list (&reg_last_sets[i], &unused_insn_list);
3837           reg_last_sets[i] = alloc_INSN_LIST (insn, NULL_RTX);
3838         }
3839
3840       reg_pending_sets_all = 0;
3841     }
3842
3843   /* Handle function calls and function returns created by the epilogue
3844      threading code.  */
3845   if (GET_CODE (insn) == CALL_INSN || GET_CODE (insn) == JUMP_INSN)
3846     {
3847       rtx dep_insn;
3848       rtx prev_dep_insn;
3849
3850       /* When scheduling instructions, we make sure calls don't lose their
3851          accompanying USE insns by depending them one on another in order.
3852
3853          Also, we must do the same thing for returns created by the epilogue
3854          threading code.  Note this code works only in this special case,
3855          because other passes make no guarantee that they will never emit
3856          an instruction between a USE and a RETURN.  There is such a guarantee
3857          for USE instructions immediately before a call.  */
3858
3859       prev_dep_insn = insn;
3860       dep_insn = PREV_INSN (insn);
3861       while (GET_CODE (dep_insn) == INSN
3862              && GET_CODE (PATTERN (dep_insn)) == USE
3863              && GET_CODE (XEXP (PATTERN (dep_insn), 0)) == REG)
3864         {
3865           SCHED_GROUP_P (prev_dep_insn) = 1;
3866
3867           /* Make a copy of all dependencies on dep_insn, and add to insn.
3868              This is so that all of the dependencies will apply to the
3869              group.  */
3870
3871           for (link = LOG_LINKS (dep_insn); link; link = XEXP (link, 1))
3872             add_dependence (insn, XEXP (link, 0), REG_NOTE_KIND (link));
3873
3874           prev_dep_insn = dep_insn;
3875           dep_insn = PREV_INSN (dep_insn);
3876         }
3877     }
3878 }
3879
3880 /* Analyze every insn between HEAD and TAIL inclusive, creating LOG_LINKS
3881    for every dependency.  */
3882
3883 static void
3884 sched_analyze (head, tail)
3885      rtx head, tail;
3886 {
3887   register rtx insn;
3888   register rtx u;
3889   rtx loop_notes = 0;
3890
3891   for (insn = head;; insn = NEXT_INSN (insn))
3892     {
3893       if (GET_CODE (insn) == INSN || GET_CODE (insn) == JUMP_INSN)
3894         {
3895           /* Make each JUMP_INSN a scheduling barrier for memory references.  */
3896           if (GET_CODE (insn) == JUMP_INSN)
3897             last_pending_memory_flush
3898               = alloc_INSN_LIST (insn, last_pending_memory_flush);
3899           sched_analyze_insn (PATTERN (insn), insn, loop_notes);
3900           loop_notes = 0;
3901         }
3902       else if (GET_CODE (insn) == CALL_INSN)
3903         {
3904           rtx x;
3905           register int i;
3906
3907           CANT_MOVE (insn) = 1;
3908
3909           /* Any instruction using a hard register which may get clobbered
3910              by a call needs to be marked as dependent on this call.
3911              This prevents a use of a hard return reg from being moved
3912              past a void call (i.e. it does not explicitly set the hard
3913              return reg).  */
3914
3915           /* If this call is followed by a NOTE_INSN_SETJMP, then assume that
3916              all registers, not just hard registers, may be clobbered by this
3917              call.  */
3918
3919           /* Insn, being a CALL_INSN, magically depends on
3920              `last_function_call' already.  */
3921
3922           if (NEXT_INSN (insn) && GET_CODE (NEXT_INSN (insn)) == NOTE
3923               && NOTE_LINE_NUMBER (NEXT_INSN (insn)) == NOTE_INSN_SETJMP)
3924             {
3925               int max_reg = max_reg_num ();
3926               for (i = 0; i < max_reg; i++)
3927                 {
3928                   for (u = reg_last_uses[i]; u; u = XEXP (u, 1))
3929                     add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
3930                   free_list (&reg_last_uses[i], &unused_insn_list);
3931
3932                   for (u = reg_last_sets[i]; u; u = XEXP (u, 1))
3933                     add_dependence (insn, XEXP (u, 0), 0);
3934
3935                   for (u = reg_last_clobbers[i]; u; u = XEXP (u, 1))
3936                     add_dependence (insn, XEXP (u, 0), 0);
3937                 }
3938               reg_pending_sets_all = 1;
3939
3940               /* Add a pair of fake REG_NOTE which we will later
3941                  convert back into a NOTE_INSN_SETJMP note.  See
3942                  reemit_notes for why we use a pair of NOTEs.  */
3943               REG_NOTES (insn) = alloc_EXPR_LIST (REG_DEAD,
3944                                                   GEN_INT (0),
3945                                                   REG_NOTES (insn));
3946               REG_NOTES (insn) = alloc_EXPR_LIST (REG_DEAD,
3947                                                   GEN_INT (NOTE_INSN_SETJMP),
3948                                                   REG_NOTES (insn));
3949             }
3950           else
3951             {
3952               for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
3953                 if (call_used_regs[i] || global_regs[i])
3954                   {
3955                     for (u = reg_last_uses[i]; u; u = XEXP (u, 1))
3956                       add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
3957
3958                     for (u = reg_last_sets[i]; u; u = XEXP (u, 1))
3959                       add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
3960
3961                     SET_REGNO_REG_SET (reg_pending_clobbers, i);
3962                   }
3963             }
3964
3965           /* For each insn which shouldn't cross a call, add a dependence
3966              between that insn and this call insn.  */
3967           x = LOG_LINKS (sched_before_next_call);
3968           while (x)
3969             {
3970               add_dependence (insn, XEXP (x, 0), REG_DEP_ANTI);
3971               x = XEXP (x, 1);
3972             }
3973           LOG_LINKS (sched_before_next_call) = 0;
3974
3975           sched_analyze_insn (PATTERN (insn), insn, loop_notes);
3976           loop_notes = 0;
3977
3978           /* In the absence of interprocedural alias analysis, we must flush
3979              all pending reads and writes, and start new dependencies starting
3980              from here.  But only flush writes for constant calls (which may
3981              be passed a pointer to something we haven't written yet).  */
3982           flush_pending_lists (insn, CONST_CALL_P (insn));
3983
3984           /* Depend this function call (actually, the user of this
3985              function call) on all hard register clobberage.  */
3986
3987           /* last_function_call is now a list of insns */
3988           free_list(&last_function_call, &unused_insn_list);
3989           last_function_call = alloc_INSN_LIST (insn, NULL_RTX);
3990         }
3991
3992       /* See comments on reemit_notes as to why we do this.  */
3993       /* ??? Actually, the reemit_notes just say what is done, not why.  */
3994
3995       else if (GET_CODE (insn) == NOTE
3996                && (NOTE_LINE_NUMBER (insn) == NOTE_INSN_RANGE_START
3997                    || NOTE_LINE_NUMBER (insn) == NOTE_INSN_RANGE_END))
3998         {
3999           loop_notes = alloc_EXPR_LIST (REG_DEAD, NOTE_RANGE_INFO (insn),
4000                                         loop_notes);
4001           loop_notes = alloc_EXPR_LIST (REG_DEAD,
4002                                         GEN_INT (NOTE_LINE_NUMBER (insn)),
4003                                         loop_notes);
4004         }
4005       else if (GET_CODE (insn) == NOTE
4006                && (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_BEG
4007                    || NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_END
4008                    || NOTE_LINE_NUMBER (insn) == NOTE_INSN_EH_REGION_BEG
4009                    || NOTE_LINE_NUMBER (insn) == NOTE_INSN_EH_REGION_END
4010                    || (NOTE_LINE_NUMBER (insn) == NOTE_INSN_SETJMP
4011                        && GET_CODE (PREV_INSN (insn)) != CALL_INSN)))
4012         {
4013           loop_notes = alloc_EXPR_LIST (REG_DEAD,
4014                                         GEN_INT (NOTE_BLOCK_NUMBER (insn)),
4015                                         loop_notes);
4016           loop_notes = alloc_EXPR_LIST (REG_DEAD,
4017                                         GEN_INT (NOTE_LINE_NUMBER (insn)),
4018                                         loop_notes);
4019           CONST_CALL_P (loop_notes) = CONST_CALL_P (insn);
4020         }
4021
4022       if (insn == tail)
4023         return;
4024     }
4025   abort ();
4026 }
4027 \f
4028 /* Called when we see a set of a register.  If death is true, then we are
4029    scanning backwards.  Mark that register as unborn.  If nobody says
4030    otherwise, that is how things will remain.  If death is false, then we
4031    are scanning forwards.  Mark that register as being born.  */
4032
4033 static void
4034 sched_note_set (x, death)
4035      rtx x;
4036      int death;
4037 {
4038   register int regno;
4039   register rtx reg = SET_DEST (x);
4040   int subreg_p = 0;
4041
4042   if (reg == 0)
4043     return;
4044
4045   if (GET_CODE (reg) == PARALLEL
4046       && GET_MODE (reg) == BLKmode)
4047     {
4048       register int i;
4049       for (i = XVECLEN (reg, 0) - 1; i >= 0; i--)
4050         sched_note_set (XVECEXP (reg, 0, i), death);
4051       return;
4052     }
4053
4054   while (GET_CODE (reg) == SUBREG || GET_CODE (reg) == STRICT_LOW_PART
4055          || GET_CODE (reg) == SIGN_EXTRACT || GET_CODE (reg) == ZERO_EXTRACT)
4056     {
4057       /* Must treat modification of just one hardware register of a multi-reg
4058          value or just a byte field of a register exactly the same way that
4059          mark_set_1 in flow.c does, i.e. anything except a paradoxical subreg
4060          does not kill the entire register.  */
4061       if (GET_CODE (reg) != SUBREG
4062           || REG_SIZE (SUBREG_REG (reg)) > REG_SIZE (reg))
4063         subreg_p = 1;
4064
4065       reg = SUBREG_REG (reg);
4066     }
4067
4068   if (GET_CODE (reg) != REG)
4069     return;
4070
4071   /* Global registers are always live, so the code below does not apply
4072      to them.  */
4073
4074   regno = REGNO (reg);
4075   if (regno >= FIRST_PSEUDO_REGISTER || !global_regs[regno])
4076     {
4077       if (death)
4078         {
4079           /* If we only set part of the register, then this set does not
4080              kill it.  */
4081           if (subreg_p)
4082             return;
4083
4084           /* Try killing this register.  */
4085           if (regno < FIRST_PSEUDO_REGISTER)
4086             {
4087               int j = HARD_REGNO_NREGS (regno, GET_MODE (reg));
4088               while (--j >= 0)
4089                 {
4090                   CLEAR_REGNO_REG_SET (bb_live_regs, regno + j);
4091                 }
4092             }
4093           else
4094             {
4095               /* Recompute REG_BASIC_BLOCK as we update all the other
4096                  dataflow information.  */
4097               if (sched_reg_basic_block[regno] == REG_BLOCK_UNKNOWN)
4098                 sched_reg_basic_block[regno] = current_block_num;
4099               else if (sched_reg_basic_block[regno] != current_block_num)
4100                 sched_reg_basic_block[regno] = REG_BLOCK_GLOBAL;
4101
4102               CLEAR_REGNO_REG_SET (bb_live_regs, regno);
4103             }
4104         }
4105       else
4106         {
4107           /* Make the register live again.  */
4108           if (regno < FIRST_PSEUDO_REGISTER)
4109             {
4110               int j = HARD_REGNO_NREGS (regno, GET_MODE (reg));
4111               while (--j >= 0)
4112                 {
4113                   SET_REGNO_REG_SET (bb_live_regs, regno + j);
4114                 }
4115             }
4116           else
4117             {
4118               SET_REGNO_REG_SET (bb_live_regs, regno);
4119             }
4120         }
4121     }
4122 }
4123 \f
4124 /* Macros and functions for keeping the priority queue sorted, and
4125    dealing with queueing and dequeueing of instructions.  */
4126
4127 #define SCHED_SORT(READY, N_READY)                                   \
4128 do { if ((N_READY) == 2)                                             \
4129        swap_sort (READY, N_READY);                                   \
4130      else if ((N_READY) > 2)                                         \
4131          qsort (READY, N_READY, sizeof (rtx), rank_for_schedule); }  \
4132 while (0)
4133
4134 /* Returns a positive value if x is preferred; returns a negative value if
4135    y is preferred.  Should never return 0, since that will make the sort
4136    unstable.  */
4137
4138 static int
4139 rank_for_schedule (x, y)
4140      const GENERIC_PTR x;
4141      const GENERIC_PTR y;
4142 {
4143   rtx tmp = *(rtx *)y;
4144   rtx tmp2 = *(rtx *)x;
4145   rtx link;
4146   int tmp_class, tmp2_class, depend_count1, depend_count2;
4147   int val, priority_val, spec_val, prob_val, weight_val;
4148
4149
4150   /* prefer insn with higher priority */
4151   priority_val = INSN_PRIORITY (tmp2) - INSN_PRIORITY (tmp);
4152   if (priority_val)
4153     return priority_val;
4154
4155   /* prefer an insn with smaller contribution to registers-pressure */
4156   if (!reload_completed &&
4157       (weight_val = INSN_REG_WEIGHT (tmp) - INSN_REG_WEIGHT (tmp2)))
4158     return (weight_val);
4159
4160   /* some comparison make sense in interblock scheduling only */
4161   if (INSN_BB (tmp) != INSN_BB (tmp2))
4162     {
4163       /* prefer an inblock motion on an interblock motion */
4164       if ((INSN_BB (tmp2) == target_bb) && (INSN_BB (tmp) != target_bb))
4165         return 1;
4166       if ((INSN_BB (tmp) == target_bb) && (INSN_BB (tmp2) != target_bb))
4167         return -1;
4168
4169       /* prefer a useful motion on a speculative one */
4170       if ((spec_val = IS_SPECULATIVE_INSN (tmp) - IS_SPECULATIVE_INSN (tmp2)))
4171         return (spec_val);
4172
4173       /* prefer a more probable (speculative) insn */
4174       prob_val = INSN_PROBABILITY (tmp2) - INSN_PROBABILITY (tmp);
4175       if (prob_val)
4176         return (prob_val);
4177     }
4178
4179   /* compare insns based on their relation to the last-scheduled-insn */
4180   if (last_scheduled_insn)
4181     {
4182       /* Classify the instructions into three classes:
4183          1) Data dependent on last schedule insn.
4184          2) Anti/Output dependent on last scheduled insn.
4185          3) Independent of last scheduled insn, or has latency of one.
4186          Choose the insn from the highest numbered class if different.  */
4187       link = find_insn_list (tmp, INSN_DEPEND (last_scheduled_insn));
4188       if (link == 0 || insn_cost (last_scheduled_insn, link, tmp) == 1)
4189         tmp_class = 3;
4190       else if (REG_NOTE_KIND (link) == 0)       /* Data dependence.  */
4191         tmp_class = 1;
4192       else
4193         tmp_class = 2;
4194
4195       link = find_insn_list (tmp2, INSN_DEPEND (last_scheduled_insn));
4196       if (link == 0 || insn_cost (last_scheduled_insn, link, tmp2) == 1)
4197         tmp2_class = 3;
4198       else if (REG_NOTE_KIND (link) == 0)       /* Data dependence.  */
4199         tmp2_class = 1;
4200       else
4201         tmp2_class = 2;
4202
4203       if ((val = tmp2_class - tmp_class))
4204         return val;
4205     }
4206
4207   /* Prefer the insn which has more later insns that depend on it. 
4208      This gives the scheduler more freedom when scheduling later
4209      instructions at the expense of added register pressure.  */
4210   depend_count1 = 0;
4211   for (link = INSN_DEPEND (tmp); link; link = XEXP (link, 1))
4212     depend_count1++;
4213
4214   depend_count2 = 0;
4215   for (link = INSN_DEPEND (tmp2); link; link = XEXP (link, 1))
4216     depend_count2++;
4217
4218   val = depend_count2 - depend_count1;
4219   if (val)
4220     return val;
4221   
4222   /* If insns are equally good, sort by INSN_LUID (original insn order),
4223      so that we make the sort stable.  This minimizes instruction movement,
4224      thus minimizing sched's effect on debugging and cross-jumping.  */
4225   return INSN_LUID (tmp) - INSN_LUID (tmp2);
4226 }
4227
4228 /* Resort the array A in which only element at index N may be out of order.  */
4229
4230 HAIFA_INLINE static void
4231 swap_sort (a, n)
4232      rtx *a;
4233      int n;
4234 {
4235   rtx insn = a[n - 1];
4236   int i = n - 2;
4237
4238   while (i >= 0 && rank_for_schedule (a + i, &insn) >= 0)
4239     {
4240       a[i + 1] = a[i];
4241       i -= 1;
4242     }
4243   a[i + 1] = insn;
4244 }
4245
4246 static int max_priority;
4247
4248 /* Add INSN to the insn queue so that it can be executed at least
4249    N_CYCLES after the currently executing insn.  Preserve insns
4250    chain for debugging purposes.  */
4251
4252 HAIFA_INLINE static void
4253 queue_insn (insn, n_cycles)
4254      rtx insn;
4255      int n_cycles;
4256 {
4257   int next_q = NEXT_Q_AFTER (q_ptr, n_cycles);
4258   rtx link = alloc_INSN_LIST (insn, insn_queue[next_q]);
4259   insn_queue[next_q] = link;
4260   q_size += 1;
4261
4262   if (sched_verbose >= 2)
4263     {
4264       fprintf (dump, ";;\t\tReady-->Q: insn %d: ", INSN_UID (insn));
4265
4266       if (INSN_BB (insn) != target_bb)
4267         fprintf (dump, "(b%d) ", INSN_BLOCK (insn));
4268
4269       fprintf (dump, "queued for %d cycles.\n", n_cycles);
4270     }
4271
4272 }
4273
4274 /* Return nonzero if PAT is the pattern of an insn which makes a
4275    register live.  */
4276
4277 HAIFA_INLINE static int
4278 birthing_insn_p (pat)
4279      rtx pat;
4280 {
4281   int j;
4282
4283   if (reload_completed == 1)
4284     return 0;
4285
4286   if (GET_CODE (pat) == SET
4287       && (GET_CODE (SET_DEST (pat)) == REG
4288           || (GET_CODE (SET_DEST (pat)) == PARALLEL
4289               && GET_MODE (SET_DEST (pat)) == BLKmode)))
4290     {
4291       rtx dest = SET_DEST (pat);
4292       int i;
4293
4294       /* It would be more accurate to use refers_to_regno_p or
4295          reg_mentioned_p to determine when the dest is not live before this
4296          insn.  */
4297       if (GET_CODE (dest) == REG)
4298         {
4299           i = REGNO (dest);
4300           if (REGNO_REG_SET_P (bb_live_regs, i))
4301             return (REG_N_SETS (i) == 1);
4302         }
4303       else
4304         {
4305           for (i = XVECLEN (dest, 0) - 1; i >= 0; i--)
4306             {
4307               int regno = REGNO (SET_DEST (XVECEXP (dest, 0, i)));
4308               if (REGNO_REG_SET_P (bb_live_regs, regno))
4309                 return (REG_N_SETS (regno) == 1);
4310             }
4311         }
4312       return 0;
4313     }
4314   if (GET_CODE (pat) == PARALLEL)
4315     {
4316       for (j = 0; j < XVECLEN (pat, 0); j++)
4317         if (birthing_insn_p (XVECEXP (pat, 0, j)))
4318           return 1;
4319     }
4320   return 0;
4321 }
4322
4323 /* PREV is an insn that is ready to execute.  Adjust its priority if that
4324    will help shorten register lifetimes.  */
4325
4326 HAIFA_INLINE static void
4327 adjust_priority (prev)
4328      rtx prev;
4329 {
4330   /* Trying to shorten register lives after reload has completed
4331      is useless and wrong.  It gives inaccurate schedules.  */
4332   if (reload_completed == 0)
4333     {
4334       rtx note;
4335       int n_deaths = 0;
4336
4337       /* ??? This code has no effect, because REG_DEAD notes are removed
4338          before we ever get here.  */
4339       for (note = REG_NOTES (prev); note; note = XEXP (note, 1))
4340         if (REG_NOTE_KIND (note) == REG_DEAD)
4341           n_deaths += 1;
4342
4343       /* Defer scheduling insns which kill registers, since that
4344          shortens register lives.  Prefer scheduling insns which
4345          make registers live for the same reason.  */
4346       switch (n_deaths)
4347         {
4348         default:
4349           INSN_PRIORITY (prev) >>= 3;
4350           break;
4351         case 3:
4352           INSN_PRIORITY (prev) >>= 2;
4353           break;
4354         case 2:
4355         case 1:
4356           INSN_PRIORITY (prev) >>= 1;
4357           break;
4358         case 0:
4359           if (birthing_insn_p (PATTERN (prev)))
4360             {
4361               int max = max_priority;
4362
4363               if (max > INSN_PRIORITY (prev))
4364                 INSN_PRIORITY (prev) = max;
4365             }
4366           break;
4367         }
4368     }
4369
4370   /* That said, a target might have it's own reasons for adjusting
4371      priority after reload.  */
4372 #ifdef ADJUST_PRIORITY
4373   ADJUST_PRIORITY (prev);
4374 #endif
4375 }
4376
4377 /* Clock at which the previous instruction was issued.  */
4378 static int last_clock_var;
4379
4380 /* INSN is the "currently executing insn".  Launch each insn which was
4381    waiting on INSN.  READY is a vector of insns which are ready to fire.
4382    N_READY is the number of elements in READY.  CLOCK is the current
4383    cycle.  */
4384
4385 static int
4386 schedule_insn (insn, ready, n_ready, clock)
4387      rtx insn;
4388      rtx *ready;
4389      int n_ready;
4390      int clock;
4391 {
4392   rtx link;
4393   int unit;
4394
4395   unit = insn_unit (insn);
4396
4397   if (sched_verbose >= 2)
4398     {
4399       fprintf (dump, ";;\t\t--> scheduling insn <<<%d>>> on unit ", INSN_UID (insn));
4400       insn_print_units (insn);
4401       fprintf (dump, "\n");
4402     }
4403
4404   if (sched_verbose && unit == -1)
4405     visualize_no_unit (insn);
4406
4407   if (MAX_BLOCKAGE > 1 || issue_rate > 1 || sched_verbose)
4408     schedule_unit (unit, insn, clock);
4409
4410   if (INSN_DEPEND (insn) == 0)
4411     return n_ready;
4412
4413   /* This is used by the function adjust_priority above.  */
4414   if (n_ready > 0)
4415     max_priority = MAX (INSN_PRIORITY (ready[0]), INSN_PRIORITY (insn));
4416   else
4417     max_priority = INSN_PRIORITY (insn);
4418
4419   for (link = INSN_DEPEND (insn); link != 0; link = XEXP (link, 1))
4420     {
4421       rtx next = XEXP (link, 0);
4422       int cost = insn_cost (insn, link, next);
4423
4424       INSN_TICK (next) = MAX (INSN_TICK (next), clock + cost);
4425
4426       if ((INSN_DEP_COUNT (next) -= 1) == 0)
4427         {
4428           int effective_cost = INSN_TICK (next) - clock;
4429
4430           /* For speculative insns, before inserting to ready/queue,
4431              check live, exception-free, and issue-delay */
4432           if (INSN_BB (next) != target_bb
4433               && (!IS_VALID (INSN_BB (next))
4434                   || CANT_MOVE (next)
4435                   || (IS_SPECULATIVE_INSN (next)
4436                       && (insn_issue_delay (next) > 3
4437                           || !check_live (next, INSN_BB (next))
4438                  || !is_exception_free (next, INSN_BB (next), target_bb)))))
4439             continue;
4440
4441           if (sched_verbose >= 2)
4442             {
4443               fprintf (dump, ";;\t\tdependences resolved: insn %d ", INSN_UID (next));
4444
4445               if (current_nr_blocks > 1 && INSN_BB (next) != target_bb)
4446                 fprintf (dump, "/b%d ", INSN_BLOCK (next));
4447
4448               if (effective_cost < 1)
4449                 fprintf (dump, "into ready\n");
4450               else
4451                 fprintf (dump, "into queue with cost=%d\n", effective_cost);
4452             }
4453
4454           /* Adjust the priority of NEXT and either put it on the ready
4455              list or queue it.  */
4456           adjust_priority (next);
4457           if (effective_cost < 1)
4458             ready[n_ready++] = next;
4459           else
4460             queue_insn (next, effective_cost);
4461         }
4462     }
4463
4464   /* Annotate the instruction with issue information -- TImode 
4465      indicates that the instruction is expected not to be able
4466      to issue on the same cycle as the previous insn.  A machine
4467      may use this information to decide how the instruction should
4468      be aligned.  */
4469   if (reload_completed && issue_rate > 1)
4470     {
4471       PUT_MODE (insn, clock > last_clock_var ? TImode : VOIDmode);
4472       last_clock_var = clock;
4473     }
4474
4475   return n_ready;
4476 }
4477
4478
4479 /* Add a REG_DEAD note for REG to INSN, reusing a REG_DEAD note from the
4480    dead_notes list.  */
4481
4482 static void
4483 create_reg_dead_note (reg, insn)
4484      rtx reg, insn;
4485 {
4486   rtx link;
4487
4488   /* The number of registers killed after scheduling must be the same as the
4489      number of registers killed before scheduling.  The number of REG_DEAD
4490      notes may not be conserved, i.e. two SImode hard register REG_DEAD notes
4491      might become one DImode hard register REG_DEAD note, but the number of
4492      registers killed will be conserved.
4493
4494      We carefully remove REG_DEAD notes from the dead_notes list, so that
4495      there will be none left at the end.  If we run out early, then there
4496      is a bug somewhere in flow, combine and/or sched.  */
4497
4498   if (dead_notes == 0)
4499     {
4500       if (current_nr_blocks <= 1)
4501         abort ();
4502       else
4503         link = alloc_EXPR_LIST (REG_DEAD, NULL_RTX, NULL_RTX);
4504     }
4505   else
4506     {
4507       /* Number of regs killed by REG.  */
4508       int regs_killed = (REGNO (reg) >= FIRST_PSEUDO_REGISTER ? 1
4509                          : HARD_REGNO_NREGS (REGNO (reg), GET_MODE (reg)));
4510       /* Number of regs killed by REG_DEAD notes taken off the list.  */
4511       int reg_note_regs;
4512
4513       link = dead_notes;
4514       reg_note_regs = (REGNO (XEXP (link, 0)) >= FIRST_PSEUDO_REGISTER ? 1
4515                        : HARD_REGNO_NREGS (REGNO (XEXP (link, 0)),
4516                                            GET_MODE (XEXP (link, 0))));
4517       while (reg_note_regs < regs_killed)
4518         {
4519           link = XEXP (link, 1);
4520
4521           /* LINK might be zero if we killed more registers after scheduling
4522              than before, and the last hard register we kill is actually
4523              multiple hard regs. 
4524
4525              This is normal for interblock scheduling, so deal with it in
4526              that case, else abort.  */
4527           if (link == NULL_RTX && current_nr_blocks <= 1)
4528             abort ();
4529           else if (link == NULL_RTX)
4530             link = alloc_EXPR_LIST (REG_DEAD, gen_rtx_REG (word_mode, 0),
4531                                     NULL_RTX);
4532              
4533           reg_note_regs += (REGNO (XEXP (link, 0)) >= FIRST_PSEUDO_REGISTER ? 1
4534                             : HARD_REGNO_NREGS (REGNO (XEXP (link, 0)),
4535                                                 GET_MODE (XEXP (link, 0))));
4536         }
4537       dead_notes = XEXP (link, 1);
4538
4539       /* If we took too many regs kills off, put the extra ones back.  */
4540       while (reg_note_regs > regs_killed)
4541         {
4542           rtx temp_reg, temp_link;
4543
4544           temp_reg = gen_rtx_REG (word_mode, 0);
4545           temp_link = alloc_EXPR_LIST (REG_DEAD, temp_reg, dead_notes);
4546           dead_notes = temp_link;
4547           reg_note_regs--;
4548         }
4549     }
4550
4551   XEXP (link, 0) = reg;
4552   XEXP (link, 1) = REG_NOTES (insn);
4553   REG_NOTES (insn) = link;
4554 }
4555
4556 /* Subroutine on attach_deaths_insn--handles the recursive search
4557    through INSN.  If SET_P is true, then x is being modified by the insn.  */
4558
4559 static void
4560 attach_deaths (x, insn, set_p)
4561      rtx x;
4562      rtx insn;
4563      int set_p;
4564 {
4565   register int i;
4566   register int j;
4567   register enum rtx_code code;
4568   register char *fmt;
4569
4570   if (x == 0)
4571     return;
4572
4573   code = GET_CODE (x);
4574
4575   switch (code)
4576     {
4577     case CONST_INT:
4578     case CONST_DOUBLE:
4579     case LABEL_REF:
4580     case SYMBOL_REF:
4581     case CONST:
4582     case CODE_LABEL:
4583     case PC:
4584     case CC0:
4585       /* Get rid of the easy cases first.  */
4586       return;
4587
4588     case REG:
4589       {
4590         /* If the register dies in this insn, queue that note, and mark
4591            this register as needing to die.  */
4592         /* This code is very similar to mark_used_1 (if set_p is false)
4593            and mark_set_1 (if set_p is true) in flow.c.  */
4594
4595         register int regno;
4596         int some_needed;
4597         int all_needed;
4598
4599         if (set_p)
4600           return;
4601
4602         regno = REGNO (x);
4603         all_needed = some_needed = REGNO_REG_SET_P (old_live_regs, regno);
4604         if (regno < FIRST_PSEUDO_REGISTER)
4605           {
4606             int n;
4607
4608             n = HARD_REGNO_NREGS (regno, GET_MODE (x));
4609             while (--n > 0)
4610               {
4611                 int needed = (REGNO_REG_SET_P (old_live_regs, regno + n));
4612                 some_needed |= needed;
4613                 all_needed &= needed;
4614               }
4615           }
4616
4617         /* If it wasn't live before we started, then add a REG_DEAD note.
4618            We must check the previous lifetime info not the current info,
4619            because we may have to execute this code several times, e.g.
4620            once for a clobber (which doesn't add a note) and later
4621            for a use (which does add a note).
4622
4623            Always make the register live.  We must do this even if it was
4624            live before, because this may be an insn which sets and uses
4625            the same register, in which case the register has already been
4626            killed, so we must make it live again.
4627
4628            Global registers are always live, and should never have a REG_DEAD
4629            note added for them, so none of the code below applies to them.  */
4630
4631         if (regno >= FIRST_PSEUDO_REGISTER || ! global_regs[regno])
4632           {
4633             /* Never add REG_DEAD notes for STACK_POINTER_REGNUM
4634                since it's always considered to be live.  Similarly
4635                for FRAME_POINTER_REGNUM if a frame pointer is needed
4636                and for ARG_POINTER_REGNUM if it is fixed.  */
4637             if (! (regno == FRAME_POINTER_REGNUM
4638                    && (! reload_completed || frame_pointer_needed))
4639 #if HARD_FRAME_POINTER_REGNUM != FRAME_POINTER_REGNUM
4640                 && ! (regno == HARD_FRAME_POINTER_REGNUM
4641                       && (! reload_completed || frame_pointer_needed))
4642 #endif
4643 #if ARG_POINTER_REGNUM != FRAME_POINTER_REGNUM
4644                 && ! (regno == ARG_POINTER_REGNUM && fixed_regs[regno])
4645 #endif
4646                 && regno != STACK_POINTER_REGNUM)
4647               {
4648                 if (! all_needed && ! dead_or_set_p (insn, x))
4649                   {
4650                     /* Check for the case where the register dying partially
4651                        overlaps the register set by this insn.  */
4652                     if (regno < FIRST_PSEUDO_REGISTER
4653                         && HARD_REGNO_NREGS (regno, GET_MODE (x)) > 1)
4654                       {
4655                         int n = HARD_REGNO_NREGS (regno, GET_MODE (x));
4656                         while (--n >= 0)
4657                           some_needed |= dead_or_set_regno_p (insn, regno + n);
4658                       }
4659
4660                     /* If none of the words in X is needed, make a REG_DEAD
4661                        note.  Otherwise, we must make partial REG_DEAD
4662                        notes.  */
4663                     if (! some_needed)
4664                       create_reg_dead_note (x, insn);
4665                     else
4666                       {
4667                         int i;
4668
4669                         /* Don't make a REG_DEAD note for a part of a
4670                            register that is set in the insn.  */
4671                         for (i = HARD_REGNO_NREGS (regno, GET_MODE (x)) - 1;
4672                              i >= 0; i--)
4673                           if (! REGNO_REG_SET_P (old_live_regs, regno+i)
4674                               && ! dead_or_set_regno_p (insn, regno + i))
4675                             create_reg_dead_note (gen_rtx_REG (reg_raw_mode[regno + i],
4676                                                                regno + i),
4677                                                   insn);
4678                       }
4679                   }
4680               }
4681
4682             if (regno < FIRST_PSEUDO_REGISTER)
4683               {
4684                 int j = HARD_REGNO_NREGS (regno, GET_MODE (x));
4685                 while (--j >= 0)
4686                   {
4687                     SET_REGNO_REG_SET (bb_live_regs, regno + j);
4688                   }
4689               }
4690             else
4691               {
4692                 /* Recompute REG_BASIC_BLOCK as we update all the other
4693                    dataflow information.  */
4694                 if (sched_reg_basic_block[regno] == REG_BLOCK_UNKNOWN)
4695                   sched_reg_basic_block[regno] = current_block_num;
4696                 else if (sched_reg_basic_block[regno] != current_block_num)
4697                   sched_reg_basic_block[regno] = REG_BLOCK_GLOBAL;
4698
4699                 SET_REGNO_REG_SET (bb_live_regs, regno);
4700               }
4701           }
4702         return;
4703       }
4704
4705     case MEM:
4706       /* Handle tail-recursive case.  */
4707       attach_deaths (XEXP (x, 0), insn, 0);
4708       return;
4709
4710     case SUBREG:
4711       attach_deaths (SUBREG_REG (x), insn,
4712                      set_p && ((GET_MODE_SIZE (GET_MODE (SUBREG_REG (x)))
4713                                 <= UNITS_PER_WORD)
4714                                || (GET_MODE_SIZE (GET_MODE (SUBREG_REG (x)))
4715                                    == GET_MODE_SIZE (GET_MODE ((x))))));
4716       return;
4717
4718     case STRICT_LOW_PART:
4719       attach_deaths (XEXP (x, 0), insn, 0);
4720       return;
4721
4722     case ZERO_EXTRACT:
4723     case SIGN_EXTRACT:
4724       attach_deaths (XEXP (x, 0), insn, 0);
4725       attach_deaths (XEXP (x, 1), insn, 0);
4726       attach_deaths (XEXP (x, 2), insn, 0);
4727       return;
4728
4729     case PARALLEL:
4730       if (set_p
4731           && GET_MODE (x) == BLKmode)
4732         {
4733           for (i = XVECLEN (x, 0) - 1; i >= 0; i--)
4734             attach_deaths (SET_DEST (XVECEXP (x, 0, i)), insn, 1);
4735           return;
4736         }
4737
4738       /* fallthrough */
4739     default:
4740       /* Other cases: walk the insn.  */
4741       fmt = GET_RTX_FORMAT (code);
4742       for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
4743         {
4744           if (fmt[i] == 'e')
4745             attach_deaths (XEXP (x, i), insn, 0);
4746           else if (fmt[i] == 'E')
4747             for (j = 0; j < XVECLEN (x, i); j++)
4748               attach_deaths (XVECEXP (x, i, j), insn, 0);
4749         }
4750     }
4751 }
4752
4753 /* After INSN has executed, add register death notes for each register
4754    that is dead after INSN.  */
4755
4756 static void
4757 attach_deaths_insn (insn)
4758      rtx insn;
4759 {
4760   rtx x = PATTERN (insn);
4761   register RTX_CODE code = GET_CODE (x);
4762   rtx link;
4763
4764   if (code == SET)
4765     {
4766       attach_deaths (SET_SRC (x), insn, 0);
4767
4768       /* A register might die here even if it is the destination, e.g.
4769          it is the target of a volatile read and is otherwise unused.
4770          Hence we must always call attach_deaths for the SET_DEST.  */
4771       attach_deaths (SET_DEST (x), insn, 1);
4772     }
4773   else if (code == PARALLEL)
4774     {
4775       register int i;
4776       for (i = XVECLEN (x, 0) - 1; i >= 0; i--)
4777         {
4778           code = GET_CODE (XVECEXP (x, 0, i));
4779           if (code == SET)
4780             {
4781               attach_deaths (SET_SRC (XVECEXP (x, 0, i)), insn, 0);
4782
4783               attach_deaths (SET_DEST (XVECEXP (x, 0, i)), insn, 1);
4784             }
4785           /* Flow does not add REG_DEAD notes to registers that die in
4786              clobbers, so we can't either.  */
4787           else if (code != CLOBBER)
4788             attach_deaths (XVECEXP (x, 0, i), insn, 0);
4789         }
4790     }
4791   /* If this is a CLOBBER, only add REG_DEAD notes to registers inside a
4792      MEM being clobbered, just like flow.  */
4793   else if (code == CLOBBER && GET_CODE (XEXP (x, 0)) == MEM)
4794     attach_deaths (XEXP (XEXP (x, 0), 0), insn, 0);
4795   /* Otherwise don't add a death note to things being clobbered.  */
4796   else if (code != CLOBBER)
4797     attach_deaths (x, insn, 0);
4798
4799   /* Make death notes for things used in the called function.  */
4800   if (GET_CODE (insn) == CALL_INSN)
4801     for (link = CALL_INSN_FUNCTION_USAGE (insn); link; link = XEXP (link, 1))
4802       attach_deaths (XEXP (XEXP (link, 0), 0), insn,
4803                      GET_CODE (XEXP (link, 0)) == CLOBBER);
4804 }
4805
4806 /* functions for handlnig of notes */
4807
4808 /* Delete notes beginning with INSN and put them in the chain
4809    of notes ended by NOTE_LIST.
4810    Returns the insn following the notes.  */
4811
4812 static rtx
4813 unlink_other_notes (insn, tail)
4814      rtx insn, tail;
4815 {
4816   rtx prev = PREV_INSN (insn);
4817
4818   while (insn != tail && GET_CODE (insn) == NOTE)
4819     {
4820       rtx next = NEXT_INSN (insn);
4821       /* Delete the note from its current position.  */
4822       if (prev)
4823         NEXT_INSN (prev) = next;
4824       if (next)
4825         PREV_INSN (next) = prev;
4826
4827       /* Don't save away NOTE_INSN_SETJMPs, because they must remain
4828          immediately after the call they follow.  We use a fake
4829          (REG_DEAD (const_int -1)) note to remember them.
4830          Likewise with NOTE_INSN_{LOOP,EHREGION}_{BEG, END}.  */
4831       if (NOTE_LINE_NUMBER (insn) != NOTE_INSN_SETJMP
4832           && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_BEG
4833           && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_END
4834           && NOTE_LINE_NUMBER (insn) != NOTE_INSN_RANGE_START
4835           && NOTE_LINE_NUMBER (insn) != NOTE_INSN_RANGE_END
4836           && NOTE_LINE_NUMBER (insn) != NOTE_INSN_EH_REGION_BEG
4837           && NOTE_LINE_NUMBER (insn) != NOTE_INSN_EH_REGION_END)
4838         {
4839           /* Insert the note at the end of the notes list.  */
4840           PREV_INSN (insn) = note_list;
4841           if (note_list)
4842             NEXT_INSN (note_list) = insn;
4843           note_list = insn;
4844         }
4845
4846       insn = next;
4847     }
4848   return insn;
4849 }
4850
4851 /* Delete line notes beginning with INSN. Record line-number notes so
4852    they can be reused.  Returns the insn following the notes.  */
4853
4854 static rtx
4855 unlink_line_notes (insn, tail)
4856      rtx insn, tail;
4857 {
4858   rtx prev = PREV_INSN (insn);
4859
4860   while (insn != tail && GET_CODE (insn) == NOTE)
4861     {
4862       rtx next = NEXT_INSN (insn);
4863
4864       if (write_symbols != NO_DEBUG && NOTE_LINE_NUMBER (insn) > 0)
4865         {
4866           /* Delete the note from its current position.  */
4867           if (prev)
4868             NEXT_INSN (prev) = next;
4869           if (next)
4870             PREV_INSN (next) = prev;
4871
4872           /* Record line-number notes so they can be reused.  */
4873           LINE_NOTE (insn) = insn;
4874         }
4875       else
4876         prev = insn;
4877
4878       insn = next;
4879     }
4880   return insn;
4881 }
4882
4883 /* Return the head and tail pointers of BB.  */
4884
4885 HAIFA_INLINE static void
4886 get_block_head_tail (bb, headp, tailp)
4887      int bb;
4888      rtx *headp;
4889      rtx *tailp;
4890 {
4891
4892   rtx head;
4893   rtx tail;
4894   int b;
4895
4896   b = BB_TO_BLOCK (bb);
4897
4898   /* HEAD and TAIL delimit the basic block being scheduled.  */
4899   head = BLOCK_HEAD (b);
4900   tail = BLOCK_END (b);
4901
4902   /* Don't include any notes or labels at the beginning of the
4903      basic block, or notes at the ends of basic blocks.  */
4904   while (head != tail)
4905     {
4906       if (GET_CODE (head) == NOTE)
4907         head = NEXT_INSN (head);
4908       else if (GET_CODE (tail) == NOTE)
4909         tail = PREV_INSN (tail);
4910       else if (GET_CODE (head) == CODE_LABEL)
4911         head = NEXT_INSN (head);
4912       else
4913         break;
4914     }
4915
4916   *headp = head;
4917   *tailp = tail;
4918 }
4919
4920 /* Delete line notes from bb. Save them so they can be later restored
4921    (in restore_line_notes ()).  */
4922
4923 static void
4924 rm_line_notes (bb)
4925      int bb;
4926 {
4927   rtx next_tail;
4928   rtx tail;
4929   rtx head;
4930   rtx insn;
4931
4932   get_block_head_tail (bb, &head, &tail);
4933
4934   if (head == tail
4935       && (GET_RTX_CLASS (GET_CODE (head)) != 'i'))
4936     return;
4937
4938   next_tail = NEXT_INSN (tail);
4939   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
4940     {
4941       rtx prev;
4942
4943       /* Farm out notes, and maybe save them in NOTE_LIST.
4944          This is needed to keep the debugger from
4945          getting completely deranged.  */
4946       if (GET_CODE (insn) == NOTE)
4947         {
4948           prev = insn;
4949           insn = unlink_line_notes (insn, next_tail);
4950
4951           if (prev == tail)
4952             abort ();
4953           if (prev == head)
4954             abort ();
4955           if (insn == next_tail)
4956             abort ();
4957         }
4958     }
4959 }
4960
4961 /* Save line number notes for each insn in bb.  */
4962
4963 static void
4964 save_line_notes (bb)
4965      int bb;
4966 {
4967   rtx head, tail;
4968   rtx next_tail;
4969
4970   /* We must use the true line number for the first insn in the block
4971      that was computed and saved at the start of this pass.  We can't
4972      use the current line number, because scheduling of the previous
4973      block may have changed the current line number.  */
4974
4975   rtx line = line_note_head[BB_TO_BLOCK (bb)];
4976   rtx insn;
4977
4978   get_block_head_tail (bb, &head, &tail);
4979   next_tail = NEXT_INSN (tail);
4980
4981   for (insn = BLOCK_HEAD (BB_TO_BLOCK (bb));
4982        insn != next_tail;
4983        insn = NEXT_INSN (insn))
4984     if (GET_CODE (insn) == NOTE && NOTE_LINE_NUMBER (insn) > 0)
4985       line = insn;
4986     else
4987       LINE_NOTE (insn) = line;
4988 }
4989
4990
4991 /* After bb was scheduled, insert line notes into the insns list.  */
4992
4993 static void
4994 restore_line_notes (bb)
4995      int bb;
4996 {
4997   rtx line, note, prev, new;
4998   int added_notes = 0;
4999   int b;
5000   rtx head, next_tail, insn;
5001
5002   b = BB_TO_BLOCK (bb);
5003
5004   head = BLOCK_HEAD (b);
5005   next_tail = NEXT_INSN (BLOCK_END (b));
5006
5007   /* Determine the current line-number.  We want to know the current
5008      line number of the first insn of the block here, in case it is
5009      different from the true line number that was saved earlier.  If
5010      different, then we need a line number note before the first insn
5011      of this block.  If it happens to be the same, then we don't want to
5012      emit another line number note here.  */
5013   for (line = head; line; line = PREV_INSN (line))
5014     if (GET_CODE (line) == NOTE && NOTE_LINE_NUMBER (line) > 0)
5015       break;
5016
5017   /* Walk the insns keeping track of the current line-number and inserting
5018      the line-number notes as needed.  */
5019   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
5020     if (GET_CODE (insn) == NOTE && NOTE_LINE_NUMBER (insn) > 0)
5021       line = insn;
5022   /* This used to emit line number notes before every non-deleted note.
5023      However, this confuses a debugger, because line notes not separated
5024      by real instructions all end up at the same address.  I can find no
5025      use for line number notes before other notes, so none are emitted.  */
5026     else if (GET_CODE (insn) != NOTE
5027              && (note = LINE_NOTE (insn)) != 0
5028              && note != line
5029              && (line == 0
5030                  || NOTE_LINE_NUMBER (note) != NOTE_LINE_NUMBER (line)
5031                  || NOTE_SOURCE_FILE (note) != NOTE_SOURCE_FILE (line)))
5032       {
5033         line = note;
5034         prev = PREV_INSN (insn);
5035         if (LINE_NOTE (note))
5036           {
5037             /* Re-use the original line-number note.  */
5038             LINE_NOTE (note) = 0;
5039             PREV_INSN (note) = prev;
5040             NEXT_INSN (prev) = note;
5041             PREV_INSN (insn) = note;
5042             NEXT_INSN (note) = insn;
5043           }
5044         else
5045           {
5046             added_notes++;
5047             new = emit_note_after (NOTE_LINE_NUMBER (note), prev);
5048             NOTE_SOURCE_FILE (new) = NOTE_SOURCE_FILE (note);
5049             RTX_INTEGRATED_P (new) = RTX_INTEGRATED_P (note);
5050           }
5051       }
5052   if (sched_verbose && added_notes)
5053     fprintf (dump, ";; added %d line-number notes\n", added_notes);
5054 }
5055
5056 /* After scheduling the function, delete redundant line notes from the
5057    insns list.  */
5058
5059 static void
5060 rm_redundant_line_notes ()
5061 {
5062   rtx line = 0;
5063   rtx insn = get_insns ();
5064   int active_insn = 0;
5065   int notes = 0;
5066
5067   /* Walk the insns deleting redundant line-number notes.  Many of these
5068      are already present.  The remainder tend to occur at basic
5069      block boundaries.  */
5070   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
5071     if (GET_CODE (insn) == NOTE && NOTE_LINE_NUMBER (insn) > 0)
5072       {
5073         /* If there are no active insns following, INSN is redundant.  */
5074         if (active_insn == 0)
5075           {
5076             notes++;
5077             NOTE_SOURCE_FILE (insn) = 0;
5078             NOTE_LINE_NUMBER (insn) = NOTE_INSN_DELETED;
5079           }
5080         /* If the line number is unchanged, LINE is redundant.  */
5081         else if (line
5082                  && NOTE_LINE_NUMBER (line) == NOTE_LINE_NUMBER (insn)
5083                  && NOTE_SOURCE_FILE (line) == NOTE_SOURCE_FILE (insn))
5084           {
5085             notes++;
5086             NOTE_SOURCE_FILE (line) = 0;
5087             NOTE_LINE_NUMBER (line) = NOTE_INSN_DELETED;
5088             line = insn;
5089           }
5090         else
5091           line = insn;
5092         active_insn = 0;
5093       }
5094     else if (!((GET_CODE (insn) == NOTE
5095                 && NOTE_LINE_NUMBER (insn) == NOTE_INSN_DELETED)
5096                || (GET_CODE (insn) == INSN
5097                    && (GET_CODE (PATTERN (insn)) == USE
5098                        || GET_CODE (PATTERN (insn)) == CLOBBER))))
5099       active_insn++;
5100
5101   if (sched_verbose && notes)
5102     fprintf (dump, ";; deleted %d line-number notes\n", notes);
5103 }
5104
5105 /* Delete notes between head and tail and put them in the chain
5106    of notes ended by NOTE_LIST.  */
5107
5108 static void
5109 rm_other_notes (head, tail)
5110      rtx head;
5111      rtx tail;
5112 {
5113   rtx next_tail;
5114   rtx insn;
5115
5116   if (head == tail
5117       && (GET_RTX_CLASS (GET_CODE (head)) != 'i'))
5118     return;
5119
5120   next_tail = NEXT_INSN (tail);
5121   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
5122     {
5123       rtx prev;
5124
5125       /* Farm out notes, and maybe save them in NOTE_LIST.
5126          This is needed to keep the debugger from
5127          getting completely deranged.  */
5128       if (GET_CODE (insn) == NOTE)
5129         {
5130           prev = insn;
5131
5132           insn = unlink_other_notes (insn, next_tail);
5133
5134           if (prev == tail)
5135             abort ();
5136           if (prev == head)
5137             abort ();
5138           if (insn == next_tail)
5139             abort ();
5140         }
5141     }
5142 }
5143
5144 /* Constructor for `sometimes' data structure.  */
5145
5146 static int
5147 new_sometimes_live (regs_sometimes_live, regno, sometimes_max)
5148      struct sometimes *regs_sometimes_live;
5149      int regno;
5150      int sometimes_max;
5151 {
5152   register struct sometimes *p;
5153
5154   /* There should never be a register greater than max_regno here.  If there
5155      is, it means that a define_split has created a new pseudo reg.  This
5156      is not allowed, since there will not be flow info available for any
5157      new register, so catch the error here.  */
5158   if (regno >= max_regno)
5159     abort ();
5160
5161   p = &regs_sometimes_live[sometimes_max];
5162   p->regno = regno;
5163   p->live_length = 0;
5164   p->calls_crossed = 0;
5165   sometimes_max++;
5166   return sometimes_max;
5167 }
5168
5169 /* Count lengths of all regs we are currently tracking,
5170    and find new registers no longer live.  */
5171
5172 static void
5173 finish_sometimes_live (regs_sometimes_live, sometimes_max)
5174      struct sometimes *regs_sometimes_live;
5175      int sometimes_max;
5176 {
5177   int i;
5178
5179   for (i = 0; i < sometimes_max; i++)
5180     {
5181       register struct sometimes *p = &regs_sometimes_live[i];
5182       int regno = p->regno;
5183
5184       sched_reg_live_length[regno] += p->live_length;
5185       sched_reg_n_calls_crossed[regno] += p->calls_crossed;
5186     }
5187 }
5188
5189 /* functions for computation of registers live/usage info */
5190
5191 /* It is assumed that prior to scheduling BASIC_BLOCK (b)->global_live_at_start
5192    contains the registers that are alive at the entry to b.
5193
5194    Two passes follow: The first pass is performed before the scheduling
5195    of a region. It scans each block of the region forward, computing
5196    the set of registers alive at the end of the basic block and
5197    discard REG_DEAD notes (done by find_pre_sched_live ()).
5198
5199    The second path is invoked after scheduling all region blocks.
5200    It scans each block of the region backward, a block being traversed
5201    only after its succesors in the region. When the set of registers
5202    live at the end of a basic block may be changed by the scheduling
5203    (this may happen for multiple blocks region), it is computed as
5204    the union of the registers live at the start of its succesors.
5205    The last-use information is updated by inserting REG_DEAD notes.
5206    (done by find_post_sched_live ()) */
5207
5208 /* Scan all the insns to be scheduled, removing register death notes.
5209    Register death notes end up in DEAD_NOTES.
5210    Recreate the register life information for the end of this basic
5211    block.  */
5212
5213 static void
5214 find_pre_sched_live (bb)
5215      int bb;
5216 {
5217   rtx insn, next_tail, head, tail;
5218   int b = BB_TO_BLOCK (bb);
5219
5220   get_block_head_tail (bb, &head, &tail);
5221   COPY_REG_SET (bb_live_regs, BASIC_BLOCK (b)->global_live_at_start);
5222   next_tail = NEXT_INSN (tail);
5223
5224   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
5225     {
5226       rtx prev, next, link;
5227       int reg_weight = 0;
5228
5229       /* Handle register life information.  */
5230       if (GET_RTX_CLASS (GET_CODE (insn)) == 'i')
5231         {
5232           /* See if the register gets born here.  */
5233           /* We must check for registers being born before we check for
5234              registers dying.  It is possible for a register to be born and
5235              die in the same insn, e.g. reading from a volatile memory
5236              location into an otherwise unused register.  Such a register
5237              must be marked as dead after this insn.  */
5238           if (GET_CODE (PATTERN (insn)) == SET
5239               || GET_CODE (PATTERN (insn)) == CLOBBER)
5240             {
5241               sched_note_set (PATTERN (insn), 0);
5242               reg_weight++;
5243             }
5244
5245           else if (GET_CODE (PATTERN (insn)) == PARALLEL)
5246             {
5247               int j;
5248               for (j = XVECLEN (PATTERN (insn), 0) - 1; j >= 0; j--)
5249                 if (GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == SET
5250                     || GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == CLOBBER)
5251                   {
5252                     sched_note_set (XVECEXP (PATTERN (insn), 0, j), 0);
5253                     reg_weight++;
5254                   }
5255
5256               /* ??? This code is obsolete and should be deleted.  It
5257                  is harmless though, so we will leave it in for now.  */
5258               for (j = XVECLEN (PATTERN (insn), 0) - 1; j >= 0; j--)
5259                 if (GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == USE)
5260                   sched_note_set (XVECEXP (PATTERN (insn), 0, j), 0);
5261             }
5262
5263           /* Each call cobbers (makes live) all call-clobbered regs
5264              that are not global or fixed.  Note that the function-value
5265              reg is a call_clobbered reg.  */
5266           if (GET_CODE (insn) == CALL_INSN)
5267             {
5268               int j;
5269               for (j = 0; j < FIRST_PSEUDO_REGISTER; j++)
5270                 if (call_used_regs[j] && !global_regs[j]
5271                     && ! fixed_regs[j])
5272                   {
5273                     SET_REGNO_REG_SET (bb_live_regs, j);
5274                   }
5275             }
5276
5277           /* Need to know what registers this insn kills.  */
5278           for (prev = 0, link = REG_NOTES (insn); link; link = next)
5279             {
5280               next = XEXP (link, 1);
5281               if ((REG_NOTE_KIND (link) == REG_DEAD
5282                    || REG_NOTE_KIND (link) == REG_UNUSED)
5283               /* Verify that the REG_NOTE has a valid value.  */
5284                   && GET_CODE (XEXP (link, 0)) == REG)
5285                 {
5286                   register int regno = REGNO (XEXP (link, 0));
5287
5288                   reg_weight--;
5289
5290                   /* Only unlink REG_DEAD notes; leave REG_UNUSED notes
5291                      alone.  */
5292                   if (REG_NOTE_KIND (link) == REG_DEAD)
5293                     {
5294                       if (prev)
5295                         XEXP (prev, 1) = next;
5296                       else
5297                         REG_NOTES (insn) = next;
5298                       XEXP (link, 1) = dead_notes;
5299                       dead_notes = link;
5300                     }
5301                   else
5302                     prev = link;
5303
5304                   if (regno < FIRST_PSEUDO_REGISTER)
5305                     {
5306                       int j = HARD_REGNO_NREGS (regno,
5307                                                 GET_MODE (XEXP (link, 0)));
5308                       while (--j >= 0)
5309                         {
5310                           CLEAR_REGNO_REG_SET (bb_live_regs, regno+j);
5311                         }
5312                     }
5313                   else
5314                     {
5315                       CLEAR_REGNO_REG_SET (bb_live_regs, regno);
5316                     }
5317                 }
5318               else
5319                 prev = link;
5320             }
5321         }
5322
5323       INSN_REG_WEIGHT (insn) = reg_weight;
5324     }
5325 }
5326
5327 /* Update register life and usage information for block bb
5328    after scheduling.  Put register dead notes back in the code.  */
5329
5330 static void
5331 find_post_sched_live (bb)
5332      int bb;
5333 {
5334   int sometimes_max;
5335   int j, i;
5336   int b;
5337   rtx insn;
5338   rtx head, tail, prev_head, next_tail;
5339
5340   register struct sometimes *regs_sometimes_live;
5341
5342   b = BB_TO_BLOCK (bb);
5343
5344   /* compute live regs at the end of bb as a function of its successors.  */
5345   if (current_nr_blocks > 1)
5346     {
5347       int e;
5348       int first_edge;
5349
5350       first_edge = e = OUT_EDGES (b);
5351       CLEAR_REG_SET (bb_live_regs);
5352
5353       if (e)
5354         do
5355           {
5356             int b_succ;
5357
5358             b_succ = TO_BLOCK (e);
5359             IOR_REG_SET (bb_live_regs,
5360                          BASIC_BLOCK (b_succ)->global_live_at_start);
5361             e = NEXT_OUT (e);
5362           }
5363         while (e != first_edge);
5364     }
5365
5366   get_block_head_tail (bb, &head, &tail);
5367   next_tail = NEXT_INSN (tail);
5368   prev_head = PREV_INSN (head);
5369
5370   EXECUTE_IF_SET_IN_REG_SET (bb_live_regs, FIRST_PSEUDO_REGISTER, i,
5371                              {
5372                                sched_reg_basic_block[i] = REG_BLOCK_GLOBAL;
5373                              });
5374
5375   /* if the block is empty, same regs are alive at its end and its start.
5376      since this is not guaranteed after interblock scheduling, make sure they
5377      are truly identical.  */
5378   if (NEXT_INSN (prev_head) == tail
5379       && (GET_RTX_CLASS (GET_CODE (tail)) != 'i'))
5380     {
5381       if (current_nr_blocks > 1)
5382         COPY_REG_SET (BASIC_BLOCK (b)->global_live_at_start, bb_live_regs);
5383
5384       return;
5385     }
5386
5387   b = BB_TO_BLOCK (bb);
5388   current_block_num = b;
5389
5390   /* Keep track of register lives.  */
5391   old_live_regs = ALLOCA_REG_SET ();
5392   regs_sometimes_live
5393     = (struct sometimes *) alloca (max_regno * sizeof (struct sometimes));
5394   sometimes_max = 0;
5395
5396   /* initiate "sometimes" data, starting with registers live at end */
5397   sometimes_max = 0;
5398   COPY_REG_SET (old_live_regs, bb_live_regs);
5399   EXECUTE_IF_SET_IN_REG_SET (bb_live_regs, 0, j,
5400                              {
5401                                sometimes_max
5402                                  = new_sometimes_live (regs_sometimes_live,
5403                                                        j, sometimes_max);
5404                              });
5405
5406   /* scan insns back, computing regs live info */
5407   for (insn = tail; insn != prev_head; insn = PREV_INSN (insn))
5408     {
5409       /* First we kill registers set by this insn, and then we
5410          make registers used by this insn live.  This is the opposite
5411          order used above because we are traversing the instructions
5412          backwards.  */
5413
5414       /* Strictly speaking, we should scan REG_UNUSED notes and make
5415          every register mentioned there live, however, we will just
5416          kill them again immediately below, so there doesn't seem to
5417          be any reason why we bother to do this.  */
5418
5419       /* See if this is the last notice we must take of a register.  */
5420       if (GET_RTX_CLASS (GET_CODE (insn)) != 'i')
5421         continue;
5422
5423       if (GET_CODE (PATTERN (insn)) == SET
5424           || GET_CODE (PATTERN (insn)) == CLOBBER)
5425         sched_note_set (PATTERN (insn), 1);
5426       else if (GET_CODE (PATTERN (insn)) == PARALLEL)
5427         {
5428           for (j = XVECLEN (PATTERN (insn), 0) - 1; j >= 0; j--)
5429             if (GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == SET
5430                 || GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == CLOBBER)
5431               sched_note_set (XVECEXP (PATTERN (insn), 0, j), 1);
5432         }
5433
5434       /* This code keeps life analysis information up to date.  */
5435       if (GET_CODE (insn) == CALL_INSN)
5436         {
5437           register struct sometimes *p;
5438
5439           /* A call kills all call used registers that are not
5440              global or fixed, except for those mentioned in the call
5441              pattern which will be made live again later.  */
5442           for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
5443             if (call_used_regs[i] && ! global_regs[i]
5444                 && ! fixed_regs[i])
5445               {
5446                 CLEAR_REGNO_REG_SET (bb_live_regs, i);
5447               }
5448
5449           /* Regs live at the time of a call instruction must not
5450              go in a register clobbered by calls.  Record this for
5451              all regs now live.  Note that insns which are born or
5452              die in a call do not cross a call, so this must be done
5453              after the killings (above) and before the births
5454              (below).  */
5455           p = regs_sometimes_live;
5456           for (i = 0; i < sometimes_max; i++, p++)
5457             if (REGNO_REG_SET_P (bb_live_regs, p->regno))
5458               p->calls_crossed += 1;
5459         }
5460
5461       /* Make every register used live, and add REG_DEAD notes for
5462          registers which were not live before we started.  */
5463       attach_deaths_insn (insn);
5464
5465       /* Find registers now made live by that instruction.  */
5466       EXECUTE_IF_AND_COMPL_IN_REG_SET (bb_live_regs, old_live_regs, 0, j,
5467                                  {
5468                                    sometimes_max
5469                                      = new_sometimes_live (regs_sometimes_live,
5470                                                            j, sometimes_max);
5471                                  });
5472       IOR_REG_SET (old_live_regs, bb_live_regs);
5473
5474       /* Count lengths of all regs we are worrying about now,
5475          and handle registers no longer live.  */
5476
5477       for (i = 0; i < sometimes_max; i++)
5478         {
5479           register struct sometimes *p = &regs_sometimes_live[i];
5480           int regno = p->regno;
5481
5482           p->live_length += 1;
5483
5484           if (!REGNO_REG_SET_P (bb_live_regs, regno))
5485             {
5486               /* This is the end of one of this register's lifetime
5487                  segments.  Save the lifetime info collected so far,
5488                  and clear its bit in the old_live_regs entry.  */
5489               sched_reg_live_length[regno] += p->live_length;
5490               sched_reg_n_calls_crossed[regno] += p->calls_crossed;
5491               CLEAR_REGNO_REG_SET (old_live_regs, p->regno);
5492
5493               /* Delete the reg_sometimes_live entry for this reg by
5494                  copying the last entry over top of it.  */
5495               *p = regs_sometimes_live[--sometimes_max];
5496               /* ...and decrement i so that this newly copied entry
5497                  will be processed.  */
5498               i--;
5499             }
5500         }
5501     }
5502
5503   finish_sometimes_live (regs_sometimes_live, sometimes_max);
5504
5505   /* In interblock scheduling, global_live_at_start may have changed.  */
5506   if (current_nr_blocks > 1)
5507     COPY_REG_SET (BASIC_BLOCK (b)->global_live_at_start, bb_live_regs);
5508
5509
5510   FREE_REG_SET (old_live_regs);
5511 }                               /* find_post_sched_live */
5512
5513 /* After scheduling the subroutine, restore information about uses of
5514    registers.  */
5515
5516 static void
5517 update_reg_usage ()
5518 {
5519   int regno;
5520
5521   if (n_basic_blocks > 0)
5522     EXECUTE_IF_SET_IN_REG_SET (bb_live_regs, FIRST_PSEUDO_REGISTER, regno,
5523                                {
5524                                  sched_reg_basic_block[regno]
5525                                    = REG_BLOCK_GLOBAL;
5526                                });
5527
5528   for (regno = 0; regno < max_regno; regno++)
5529     if (sched_reg_live_length[regno])
5530       {
5531         if (sched_verbose)
5532           {
5533             if (REG_LIVE_LENGTH (regno) > sched_reg_live_length[regno])
5534               fprintf (dump,
5535                        ";; register %d life shortened from %d to %d\n",
5536                        regno, REG_LIVE_LENGTH (regno),
5537                        sched_reg_live_length[regno]);
5538             /* Negative values are special; don't overwrite the current
5539                reg_live_length value if it is negative.  */
5540             else if (REG_LIVE_LENGTH (regno) < sched_reg_live_length[regno]
5541                      && REG_LIVE_LENGTH (regno) >= 0)
5542               fprintf (dump,
5543                        ";; register %d life extended from %d to %d\n",
5544                        regno, REG_LIVE_LENGTH (regno),
5545                        sched_reg_live_length[regno]);
5546
5547             if (!REG_N_CALLS_CROSSED (regno)
5548                 && sched_reg_n_calls_crossed[regno])
5549               fprintf (dump,
5550                        ";; register %d now crosses calls\n", regno);
5551             else if (REG_N_CALLS_CROSSED (regno)
5552                      && !sched_reg_n_calls_crossed[regno]
5553                      && REG_BASIC_BLOCK (regno) != REG_BLOCK_GLOBAL)
5554               fprintf (dump,
5555                        ";; register %d no longer crosses calls\n", regno);
5556
5557             if (REG_BASIC_BLOCK (regno) != sched_reg_basic_block[regno]
5558                 && sched_reg_basic_block[regno] != REG_BLOCK_UNKNOWN
5559                 && REG_BASIC_BLOCK(regno) != REG_BLOCK_UNKNOWN)
5560               fprintf (dump,
5561                        ";; register %d changed basic block from %d to %d\n",
5562                         regno, REG_BASIC_BLOCK(regno),
5563                         sched_reg_basic_block[regno]);
5564
5565           }
5566         /* Negative values are special; don't overwrite the current
5567            reg_live_length value if it is negative.  */
5568         if (REG_LIVE_LENGTH (regno) >= 0)
5569           REG_LIVE_LENGTH (regno) = sched_reg_live_length[regno];
5570
5571         if (sched_reg_basic_block[regno] != REG_BLOCK_UNKNOWN
5572             && REG_BASIC_BLOCK(regno) != REG_BLOCK_UNKNOWN)
5573           REG_BASIC_BLOCK(regno) = sched_reg_basic_block[regno];
5574
5575         /* We can't change the value of reg_n_calls_crossed to zero for
5576            pseudos which are live in more than one block.
5577
5578            This is because combine might have made an optimization which
5579            invalidated global_live_at_start and reg_n_calls_crossed,
5580            but it does not update them.  If we update reg_n_calls_crossed
5581            here, the two variables are now inconsistent, and this might
5582            confuse the caller-save code into saving a register that doesn't
5583            need to be saved.  This is only a problem when we zero calls
5584            crossed for a pseudo live in multiple basic blocks.
5585
5586            Alternatively, we could try to correctly update basic block live
5587            at start here in sched, but that seems complicated.
5588
5589            Note: it is possible that a global register became local, as result
5590            of interblock motion, but will remain marked as a global register.  */
5591         if (sched_reg_n_calls_crossed[regno]
5592             || REG_BASIC_BLOCK (regno) != REG_BLOCK_GLOBAL)
5593           REG_N_CALLS_CROSSED (regno) = sched_reg_n_calls_crossed[regno];
5594
5595       }
5596 }
5597
5598 /* Scheduling clock, modified in schedule_block() and queue_to_ready () */
5599 static int clock_var;
5600
5601 /* Move insns that became ready to fire from queue to ready list.  */
5602
5603 static int
5604 queue_to_ready (ready, n_ready)
5605      rtx ready[];
5606      int n_ready;
5607 {
5608   rtx insn;
5609   rtx link;
5610
5611   q_ptr = NEXT_Q (q_ptr);
5612
5613   /* Add all pending insns that can be scheduled without stalls to the
5614      ready list.  */
5615   for (link = insn_queue[q_ptr]; link; link = XEXP (link, 1))
5616     {
5617
5618       insn = XEXP (link, 0);
5619       q_size -= 1;
5620
5621       if (sched_verbose >= 2)
5622         fprintf (dump, ";;\t\tQ-->Ready: insn %d: ", INSN_UID (insn));
5623
5624       if (sched_verbose >= 2 && INSN_BB (insn) != target_bb)
5625         fprintf (dump, "(b%d) ", INSN_BLOCK (insn));
5626
5627       ready[n_ready++] = insn;
5628       if (sched_verbose >= 2)
5629         fprintf (dump, "moving to ready without stalls\n");
5630     }
5631   insn_queue[q_ptr] = 0;
5632
5633   /* If there are no ready insns, stall until one is ready and add all
5634      of the pending insns at that point to the ready list.  */
5635   if (n_ready == 0)
5636     {
5637       register int stalls;
5638
5639       for (stalls = 1; stalls < INSN_QUEUE_SIZE; stalls++)
5640         {
5641           if ((link = insn_queue[NEXT_Q_AFTER (q_ptr, stalls)]))
5642             {
5643               for (; link; link = XEXP (link, 1))
5644                 {
5645                   insn = XEXP (link, 0);
5646                   q_size -= 1;
5647
5648                   if (sched_verbose >= 2)
5649                     fprintf (dump, ";;\t\tQ-->Ready: insn %d: ", INSN_UID (insn));
5650
5651                   if (sched_verbose >= 2 && INSN_BB (insn) != target_bb)
5652                     fprintf (dump, "(b%d) ", INSN_BLOCK (insn));
5653
5654                   ready[n_ready++] = insn;
5655                   if (sched_verbose >= 2)
5656                     fprintf (dump, "moving to ready with %d stalls\n", stalls);
5657                 }
5658               insn_queue[NEXT_Q_AFTER (q_ptr, stalls)] = 0;
5659
5660               if (n_ready)
5661                 break;
5662             }
5663         }
5664
5665       if (sched_verbose && stalls)
5666         visualize_stall_cycles (BB_TO_BLOCK (target_bb), stalls);
5667       q_ptr = NEXT_Q_AFTER (q_ptr, stalls);
5668       clock_var += stalls;
5669     }
5670   return n_ready;
5671 }
5672
5673 /* Print the ready list for debugging purposes. Callable from debugger.  */
5674
5675 static void
5676 debug_ready_list (ready, n_ready)
5677      rtx ready[];
5678      int n_ready;
5679 {
5680   int i;
5681
5682   for (i = 0; i < n_ready; i++)
5683     {
5684       fprintf (dump, "  %d", INSN_UID (ready[i]));
5685       if (current_nr_blocks > 1 && INSN_BB (ready[i]) != target_bb)
5686         fprintf (dump, "/b%d", INSN_BLOCK (ready[i]));
5687     }
5688   fprintf (dump, "\n");
5689 }
5690
5691 /* Print names of units on which insn can/should execute, for debugging.  */
5692
5693 static void
5694 insn_print_units (insn)
5695      rtx insn;
5696 {
5697   int i;
5698   int unit = insn_unit (insn);
5699
5700   if (unit == -1)
5701     fprintf (dump, "none");
5702   else if (unit >= 0)
5703     fprintf (dump, "%s", function_units[unit].name);
5704   else
5705     {
5706       fprintf (dump, "[");
5707       for (i = 0, unit = ~unit; unit; i++, unit >>= 1)
5708         if (unit & 1)
5709           {
5710             fprintf (dump, "%s", function_units[i].name);
5711             if (unit != 1)
5712               fprintf (dump, " ");
5713           }
5714       fprintf (dump, "]");
5715     }
5716 }
5717
5718 /* MAX_VISUAL_LINES is the maximum number of lines in visualization table
5719    of a basic block.  If more lines are needed, table is splitted to two.
5720    n_visual_lines is the number of lines printed so far for a block.
5721    visual_tbl contains the block visualization info.
5722    vis_no_unit holds insns in a cycle that are not mapped to any unit.  */
5723 #define MAX_VISUAL_LINES 100
5724 #define INSN_LEN 30
5725 int n_visual_lines;
5726 char *visual_tbl;
5727 int n_vis_no_unit;
5728 rtx vis_no_unit[10];
5729
5730 /* Finds units that are in use in this fuction. Required only
5731    for visualization.  */
5732
5733 static void
5734 init_target_units ()
5735 {
5736   rtx insn;
5737   int unit;
5738
5739   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
5740     {
5741       if (GET_RTX_CLASS (GET_CODE (insn)) != 'i')
5742         continue;
5743
5744       unit = insn_unit (insn);
5745
5746       if (unit < 0)
5747         target_units |= ~unit;
5748       else
5749         target_units |= (1 << unit);
5750     }
5751 }
5752
5753 /* Return the length of the visualization table */
5754
5755 static int
5756 get_visual_tbl_length ()
5757 {
5758   int unit, i;
5759   int n, n1;
5760   char *s;
5761
5762   /* compute length of one field in line */
5763   s = (char *) alloca (INSN_LEN + 5);
5764   sprintf (s, "  %33s", "uname");
5765   n1 = strlen (s);
5766
5767   /* compute length of one line */
5768   n = strlen (";; ");
5769   n += n1;
5770   for (unit = 0; unit < FUNCTION_UNITS_SIZE; unit++)
5771     if (function_units[unit].bitmask & target_units)
5772       for (i = 0; i < function_units[unit].multiplicity; i++)
5773         n += n1;
5774   n += n1;
5775   n += strlen ("\n") + 2;
5776
5777   /* compute length of visualization string */
5778   return (MAX_VISUAL_LINES * n);
5779 }
5780
5781 /* Init block visualization debugging info */
5782
5783 static void
5784 init_block_visualization ()
5785 {
5786   strcpy (visual_tbl, "");
5787   n_visual_lines = 0;
5788   n_vis_no_unit = 0;
5789 }
5790
5791 #define BUF_LEN 256
5792
5793 static char *
5794 safe_concat (buf, cur, str)
5795      char *buf;
5796      char *cur;
5797      char *str;
5798 {
5799   char *end = buf + BUF_LEN - 2;        /* leave room for null */
5800   int c;
5801
5802   if (cur > end)
5803     {
5804       *end = '\0';
5805       return end;
5806     }
5807
5808   while (cur < end && (c = *str++) != '\0')
5809     *cur++ = c;
5810
5811   *cur = '\0';
5812   return cur;
5813 }
5814
5815 /* This recognizes rtx, I classified as expressions. These are always */
5816 /* represent some action on values or results of other expression, */
5817 /* that may be stored in objects representing values.  */
5818
5819 static void
5820 print_exp (buf, x, verbose)
5821      char *buf;
5822      rtx x;
5823      int verbose;
5824 {
5825   char tmp[BUF_LEN];
5826   char *st[4];
5827   char *cur = buf;
5828   char *fun = (char *)0;
5829   char *sep;
5830   rtx op[4];
5831   int i;
5832
5833   for (i = 0; i < 4; i++)
5834     {
5835       st[i] = (char *)0;
5836       op[i] = NULL_RTX;
5837     }
5838
5839   switch (GET_CODE (x))
5840     {
5841     case PLUS:
5842       op[0] = XEXP (x, 0);
5843       if (GET_CODE (XEXP (x, 1)) == CONST_INT
5844           && INTVAL (XEXP (x, 1)) < 0)
5845         {
5846           st[1] = "-";
5847           op[1] = GEN_INT (-INTVAL (XEXP (x, 1)));
5848         }
5849       else
5850         {
5851           st[1] = "+";
5852           op[1] = XEXP (x, 1);
5853         }
5854       break;
5855     case LO_SUM:
5856       op[0] = XEXP (x, 0);
5857       st[1] = "+low(";
5858       op[1] = XEXP (x, 1);
5859       st[2] = ")";
5860       break;
5861     case MINUS:
5862       op[0] = XEXP (x, 0);
5863       st[1] = "-";
5864       op[1] = XEXP (x, 1);
5865       break;
5866     case COMPARE:
5867       fun = "cmp";
5868       op[0] = XEXP (x, 0);
5869       op[1] = XEXP (x, 1);
5870       break;
5871     case NEG:
5872       st[0] = "-";
5873       op[0] = XEXP (x, 0);
5874       break;
5875     case MULT:
5876       op[0] = XEXP (x, 0);
5877       st[1] = "*";
5878       op[1] = XEXP (x, 1);
5879       break;
5880     case DIV:
5881       op[0] = XEXP (x, 0);
5882       st[1] = "/";
5883       op[1] = XEXP (x, 1);
5884       break;
5885     case UDIV:
5886       fun = "udiv";
5887       op[0] = XEXP (x, 0);
5888       op[1] = XEXP (x, 1);
5889       break;
5890     case MOD:
5891       op[0] = XEXP (x, 0);
5892       st[1] = "%";
5893       op[1] = XEXP (x, 1);
5894       break;
5895     case UMOD:
5896       fun = "umod";
5897       op[0] = XEXP (x, 0);
5898       op[1] = XEXP (x, 1);
5899       break;
5900     case SMIN:
5901       fun = "smin";
5902       op[0] = XEXP (x, 0);
5903       op[1] = XEXP (x, 1);
5904       break;
5905     case SMAX:
5906       fun = "smax";
5907       op[0] = XEXP (x, 0);
5908       op[1] = XEXP (x, 1);
5909       break;
5910     case UMIN:
5911       fun = "umin";
5912       op[0] = XEXP (x, 0);
5913       op[1] = XEXP (x, 1);
5914       break;
5915     case UMAX:
5916       fun = "umax";
5917       op[0] = XEXP (x, 0);
5918       op[1] = XEXP (x, 1);
5919       break;
5920     case NOT:
5921       st[0] = "!";
5922       op[0] = XEXP (x, 0);
5923       break;
5924     case AND:
5925       op[0] = XEXP (x, 0);
5926       st[1] = "&";
5927       op[1] = XEXP (x, 1);
5928       break;
5929     case IOR:
5930       op[0] = XEXP (x, 0);
5931       st[1] = "|";
5932       op[1] = XEXP (x, 1);
5933       break;
5934     case XOR:
5935       op[0] = XEXP (x, 0);
5936       st[1] = "^";
5937       op[1] = XEXP (x, 1);
5938       break;
5939     case ASHIFT:
5940       op[0] = XEXP (x, 0);
5941       st[1] = "<<";
5942       op[1] = XEXP (x, 1);
5943       break;
5944     case LSHIFTRT:
5945       op[0] = XEXP (x, 0);
5946       st[1] = " 0>>";
5947       op[1] = XEXP (x, 1);
5948       break;
5949     case ASHIFTRT:
5950       op[0] = XEXP (x, 0);
5951       st[1] = ">>";
5952       op[1] = XEXP (x, 1);
5953       break;
5954     case ROTATE:
5955       op[0] = XEXP (x, 0);
5956       st[1] = "<-<";
5957       op[1] = XEXP (x, 1);
5958       break;
5959     case ROTATERT:
5960       op[0] = XEXP (x, 0);
5961       st[1] = ">->";
5962       op[1] = XEXP (x, 1);
5963       break;
5964     case ABS:
5965       fun = "abs";
5966       op[0] = XEXP (x, 0);
5967       break;
5968     case SQRT:
5969       fun = "sqrt";
5970       op[0] = XEXP (x, 0);
5971       break;
5972     case FFS:
5973       fun = "ffs";
5974       op[0] = XEXP (x, 0);
5975       break;
5976     case EQ:
5977       op[0] = XEXP (x, 0);
5978       st[1] = "==";
5979       op[1] = XEXP (x, 1);
5980       break;
5981     case NE:
5982       op[0] = XEXP (x, 0);
5983       st[1] = "!=";
5984       op[1] = XEXP (x, 1);
5985       break;
5986     case GT:
5987       op[0] = XEXP (x, 0);
5988       st[1] = ">";
5989       op[1] = XEXP (x, 1);
5990       break;
5991     case GTU:
5992       fun = "gtu";
5993       op[0] = XEXP (x, 0);
5994       op[1] = XEXP (x, 1);
5995       break;
5996     case LT:
5997       op[0] = XEXP (x, 0);
5998       st[1] = "<";
5999       op[1] = XEXP (x, 1);
6000       break;
6001     case LTU:
6002       fun = "ltu";
6003       op[0] = XEXP (x, 0);
6004       op[1] = XEXP (x, 1);
6005       break;
6006     case GE:
6007       op[0] = XEXP (x, 0);
6008       st[1] = ">=";
6009       op[1] = XEXP (x, 1);
6010       break;
6011     case GEU:
6012       fun = "geu";
6013       op[0] = XEXP (x, 0);
6014       op[1] = XEXP (x, 1);
6015       break;
6016     case LE:
6017       op[0] = XEXP (x, 0);
6018       st[1] = "<=";
6019       op[1] = XEXP (x, 1);
6020       break;
6021     case LEU:
6022       fun = "leu";
6023       op[0] = XEXP (x, 0);
6024       op[1] = XEXP (x, 1);
6025       break;
6026     case SIGN_EXTRACT:
6027       fun = (verbose) ? "sign_extract" : "sxt";
6028       op[0] = XEXP (x, 0);
6029       op[1] = XEXP (x, 1);
6030       op[2] = XEXP (x, 2);
6031       break;
6032     case ZERO_EXTRACT:
6033       fun = (verbose) ? "zero_extract" : "zxt";
6034       op[0] = XEXP (x, 0);
6035       op[1] = XEXP (x, 1);
6036       op[2] = XEXP (x, 2);
6037       break;
6038     case SIGN_EXTEND:
6039       fun = (verbose) ? "sign_extend" : "sxn";
6040       op[0] = XEXP (x, 0);
6041       break;
6042     case ZERO_EXTEND:
6043       fun = (verbose) ? "zero_extend" : "zxn";
6044       op[0] = XEXP (x, 0);
6045       break;
6046     case FLOAT_EXTEND:
6047       fun = (verbose) ? "float_extend" : "fxn";
6048       op[0] = XEXP (x, 0);
6049       break;
6050     case TRUNCATE:
6051       fun = (verbose) ? "trunc" : "trn";
6052       op[0] = XEXP (x, 0);
6053       break;
6054     case FLOAT_TRUNCATE:
6055       fun = (verbose) ? "float_trunc" : "ftr";
6056       op[0] = XEXP (x, 0);
6057       break;
6058     case FLOAT:
6059       fun = (verbose) ? "float" : "flt";
6060       op[0] = XEXP (x, 0);
6061       break;
6062     case UNSIGNED_FLOAT:
6063       fun = (verbose) ? "uns_float" : "ufl";
6064       op[0] = XEXP (x, 0);
6065       break;
6066     case FIX:
6067       fun = "fix";
6068       op[0] = XEXP (x, 0);
6069       break;
6070     case UNSIGNED_FIX:
6071       fun = (verbose) ? "uns_fix" : "ufx";
6072       op[0] = XEXP (x, 0);
6073       break;
6074     case PRE_DEC:
6075       st[0] = "--";
6076       op[0] = XEXP (x, 0);
6077       break;
6078     case PRE_INC:
6079       st[0] = "++";
6080       op[0] = XEXP (x, 0);
6081       break;
6082     case POST_DEC:
6083       op[0] = XEXP (x, 0);
6084       st[1] = "--";
6085       break;
6086     case POST_INC:
6087       op[0] = XEXP (x, 0);
6088       st[1] = "++";
6089       break;
6090     case CALL:
6091       st[0] = "call ";
6092       op[0] = XEXP (x, 0);
6093       if (verbose)
6094         {
6095           st[1] = " argc:";
6096           op[1] = XEXP (x, 1);
6097         }
6098       break;
6099     case IF_THEN_ELSE:
6100       st[0] = "{(";
6101       op[0] = XEXP (x, 0);
6102       st[1] = ")?";
6103       op[1] = XEXP (x, 1);
6104       st[2] = ":";
6105       op[2] = XEXP (x, 2);
6106       st[3] = "}";
6107       break;
6108     case TRAP_IF:
6109       fun = "trap_if";
6110       op[0] = TRAP_CONDITION (x);
6111       break;
6112     case UNSPEC:
6113     case UNSPEC_VOLATILE:
6114       {
6115         cur = safe_concat (buf, cur, "unspec");
6116         if (GET_CODE (x) == UNSPEC_VOLATILE)
6117           cur = safe_concat (buf, cur, "/v");
6118         cur = safe_concat (buf, cur, "[");
6119         sep = "";
6120         for (i = 0; i < XVECLEN (x, 0); i++)
6121           {
6122             print_pattern (tmp, XVECEXP (x, 0, i), verbose);
6123             cur = safe_concat (buf, cur, sep);
6124             cur = safe_concat (buf, cur, tmp);
6125             sep = ",";
6126           }
6127         cur = safe_concat (buf, cur, "] ");
6128         sprintf (tmp, "%d", XINT (x, 1));
6129         cur = safe_concat (buf, cur, tmp);
6130       }
6131       break;
6132     default:
6133       /* if (verbose) debug_rtx (x); */
6134       st[0] = GET_RTX_NAME (GET_CODE (x));
6135       break;
6136     }
6137
6138   /* Print this as a function? */
6139   if (fun)
6140     {
6141       cur = safe_concat (buf, cur, fun);
6142       cur = safe_concat (buf, cur, "(");
6143     }
6144
6145   for (i = 0; i < 4; i++)
6146     {
6147       if (st[i])
6148         cur = safe_concat (buf, cur, st[i]);
6149
6150       if (op[i])
6151         {
6152           if (fun && i != 0)
6153             cur = safe_concat (buf, cur, ",");
6154
6155           print_value (tmp, op[i], verbose);
6156           cur = safe_concat (buf, cur, tmp);
6157         }
6158     }
6159
6160   if (fun)
6161     cur = safe_concat (buf, cur, ")");
6162 }               /* print_exp */
6163
6164 /* Prints rtxes, i customly classified as values. They're constants, */
6165 /* registers, labels, symbols and memory accesses.  */
6166
6167 static void
6168 print_value (buf, x, verbose)
6169      char *buf;
6170      rtx x;
6171      int verbose;
6172 {
6173   char t[BUF_LEN];
6174   char *cur = buf;
6175
6176   switch (GET_CODE (x))
6177     {
6178     case CONST_INT:
6179       sprintf (t, HOST_WIDE_INT_PRINT_HEX, INTVAL (x));
6180       cur = safe_concat (buf, cur, t);
6181       break;
6182     case CONST_DOUBLE:
6183       sprintf (t, "<0x%lx,0x%lx>", (long)XWINT (x, 2), (long)XWINT (x, 3));
6184       cur = safe_concat (buf, cur, t);
6185       break;
6186     case CONST_STRING:
6187       cur = safe_concat (buf, cur, "\"");
6188       cur = safe_concat (buf, cur, XSTR (x, 0));
6189       cur = safe_concat (buf, cur, "\"");
6190       break;
6191     case SYMBOL_REF:
6192       cur = safe_concat (buf, cur, "`");
6193       cur = safe_concat (buf, cur, XSTR (x, 0));
6194       cur = safe_concat (buf, cur, "'");
6195       break;
6196     case LABEL_REF:
6197       sprintf (t, "L%d", INSN_UID (XEXP (x, 0)));
6198       cur = safe_concat (buf, cur, t);
6199       break;
6200     case CONST:
6201       print_value (t, XEXP (x, 0), verbose);
6202       cur = safe_concat (buf, cur, "const(");
6203       cur = safe_concat (buf, cur, t);
6204       cur = safe_concat (buf, cur, ")");
6205       break;
6206     case HIGH:
6207       print_value (t, XEXP (x, 0), verbose);
6208       cur = safe_concat (buf, cur, "high(");
6209       cur = safe_concat (buf, cur, t);
6210       cur = safe_concat (buf, cur, ")");
6211       break;
6212     case REG:
6213       if (REGNO (x) < FIRST_PSEUDO_REGISTER)
6214         {
6215           int c = reg_names[ REGNO (x) ][0];
6216           if (c >= '0' && c <= '9')
6217             cur = safe_concat (buf, cur, "%");
6218
6219           cur = safe_concat (buf, cur, reg_names[ REGNO (x) ]);
6220         }
6221       else
6222         {
6223           sprintf (t, "r%d", REGNO (x));
6224           cur = safe_concat (buf, cur, t);
6225         }
6226       break;
6227     case SUBREG:
6228       print_value (t, SUBREG_REG (x), verbose);
6229       cur = safe_concat (buf, cur, t);
6230       sprintf (t, "#%d", SUBREG_WORD (x));
6231       cur = safe_concat (buf, cur, t);
6232       break;
6233     case SCRATCH:
6234       cur = safe_concat (buf, cur, "scratch");
6235       break;
6236     case CC0:
6237       cur = safe_concat (buf, cur, "cc0");
6238       break;
6239     case PC:
6240       cur = safe_concat (buf, cur, "pc");
6241       break;
6242     case MEM:
6243       print_value (t, XEXP (x, 0), verbose);
6244       cur = safe_concat (buf, cur, "[");
6245       cur = safe_concat (buf, cur, t);
6246       cur = safe_concat (buf, cur, "]");
6247       break;
6248     default:
6249       print_exp (t, x, verbose);
6250       cur = safe_concat (buf, cur, t);
6251       break;
6252     }
6253 }                               /* print_value */
6254
6255 /* The next step in insn detalization, its pattern recognition */
6256
6257 static void
6258 print_pattern (buf, x, verbose)
6259      char *buf;
6260      rtx x;
6261      int verbose;
6262 {
6263   char t1[BUF_LEN], t2[BUF_LEN], t3[BUF_LEN];
6264
6265   switch (GET_CODE (x))
6266     {
6267     case SET:
6268       print_value (t1, SET_DEST (x), verbose);
6269       print_value (t2, SET_SRC (x), verbose);
6270       sprintf (buf, "%s=%s", t1, t2);
6271       break;
6272     case RETURN:
6273       sprintf (buf, "return");
6274       break;
6275     case CALL:
6276       print_exp (buf, x, verbose);
6277       break;
6278     case CLOBBER:
6279       print_value (t1, XEXP (x, 0), verbose);
6280       sprintf (buf, "clobber %s", t1);
6281       break;
6282     case USE:
6283       print_value (t1, XEXP (x, 0), verbose);
6284       sprintf (buf, "use %s", t1);
6285       break;
6286     case PARALLEL:
6287       {
6288         int i;
6289
6290         sprintf (t1, "{");
6291         for (i = 0; i < XVECLEN (x, 0); i++)
6292           {
6293             print_pattern (t2, XVECEXP (x, 0, i), verbose);
6294             sprintf (t3, "%s%s;", t1, t2);
6295             strcpy (t1, t3);
6296           }
6297         sprintf (buf, "%s}", t1);
6298       }
6299       break;
6300     case SEQUENCE:
6301       {
6302         int i;
6303
6304         sprintf (t1, "%%{");
6305         for (i = 0; i < XVECLEN (x, 0); i++)
6306           {
6307             print_insn (t2, XVECEXP (x, 0, i), verbose);
6308             sprintf (t3, "%s%s;", t1, t2);
6309             strcpy (t1, t3);
6310           }
6311         sprintf (buf, "%s%%}", t1);
6312       }
6313       break;
6314     case ASM_INPUT:
6315       sprintf (buf, "asm {%s}", XSTR (x, 0));
6316       break;
6317     case ADDR_VEC:
6318       break;
6319     case ADDR_DIFF_VEC:
6320       print_value (buf, XEXP (x, 0), verbose);
6321       break;
6322     case TRAP_IF:
6323       print_value (t1, TRAP_CONDITION (x), verbose);
6324       sprintf (buf, "trap_if %s", t1);
6325       break;
6326     case UNSPEC:
6327       {
6328         int i;
6329
6330         sprintf (t1, "unspec{");
6331         for (i = 0; i < XVECLEN (x, 0); i++)
6332           {
6333             print_pattern (t2, XVECEXP (x, 0, i), verbose);
6334             sprintf (t3, "%s%s;", t1, t2);
6335             strcpy (t1, t3);
6336           }
6337         sprintf (buf, "%s}", t1);
6338       }
6339       break;
6340     case UNSPEC_VOLATILE:
6341       {
6342         int i;
6343
6344         sprintf (t1, "unspec/v{");
6345         for (i = 0; i < XVECLEN (x, 0); i++)
6346           {
6347             print_pattern (t2, XVECEXP (x, 0, i), verbose);
6348             sprintf (t3, "%s%s;", t1, t2);
6349             strcpy (t1, t3);
6350           }
6351         sprintf (buf, "%s}", t1);
6352       }
6353       break;
6354     default:
6355       print_value (buf, x, verbose);
6356     }
6357 }                               /* print_pattern */
6358
6359 /* This is the main function in rtl visualization mechanism. It
6360    accepts an rtx and tries to recognize it as an insn, then prints it
6361    properly in human readable form, resembling assembler mnemonics.  */
6362 /* For every insn it prints its UID and BB the insn belongs */
6363 /* too. (probably the last "option" should be extended somehow, since */
6364 /* it depends now on sched.c inner variables ...) */
6365
6366 static void
6367 print_insn (buf, x, verbose)
6368      char *buf;
6369      rtx x;
6370      int verbose;
6371 {
6372   char t[BUF_LEN];
6373   rtx insn = x;
6374
6375   switch (GET_CODE (x))
6376     {
6377     case INSN:
6378       print_pattern (t, PATTERN (x), verbose);
6379       if (verbose)
6380         sprintf (buf, "b%d: i% 4d: %s", INSN_BB (x),
6381                  INSN_UID (x), t);
6382       else
6383         sprintf (buf, "%-4d %s", INSN_UID (x), t);
6384       break;
6385     case JUMP_INSN:
6386       print_pattern (t, PATTERN (x), verbose);
6387       if (verbose)
6388         sprintf (buf, "b%d: i% 4d: jump %s", INSN_BB (x),
6389                  INSN_UID (x), t);
6390       else
6391         sprintf (buf, "%-4d %s", INSN_UID (x), t);
6392       break;
6393     case CALL_INSN:
6394       x = PATTERN (insn);
6395       if (GET_CODE (x) == PARALLEL)
6396         {
6397           x = XVECEXP (x, 0, 0);
6398           print_pattern (t, x, verbose);
6399         }
6400       else
6401         strcpy (t, "call <...>");
6402       if (verbose)
6403         sprintf (buf, "b%d: i% 4d: %s", INSN_BB (insn),
6404                  INSN_UID (insn), t);
6405       else
6406         sprintf (buf, "%-4d %s", INSN_UID (insn), t);
6407       break;
6408     case CODE_LABEL:
6409       sprintf (buf, "L%d:", INSN_UID (x));
6410       break;
6411     case BARRIER:
6412       sprintf (buf, "i% 4d: barrier", INSN_UID (x));
6413       break;
6414     case NOTE:
6415       if (NOTE_LINE_NUMBER (x) > 0)
6416         sprintf (buf, "%4d note \"%s\" %d", INSN_UID (x),
6417                  NOTE_SOURCE_FILE (x), NOTE_LINE_NUMBER (x));
6418       else
6419         sprintf (buf, "%4d %s", INSN_UID (x),
6420                  GET_NOTE_INSN_NAME (NOTE_LINE_NUMBER (x)));
6421       break;
6422     default:
6423       if (verbose)
6424         {
6425           sprintf (buf, "Not an INSN at all\n");
6426           debug_rtx (x);
6427         }
6428       else
6429         sprintf (buf, "i%-4d  <What?>", INSN_UID (x));
6430     }
6431 }                               /* print_insn */
6432
6433 /* Print visualization debugging info */
6434
6435 static void
6436 print_block_visualization (b, s)
6437      int b;
6438      char *s;
6439 {
6440   int unit, i;
6441
6442   /* print header */
6443   fprintf (dump, "\n;;   ==================== scheduling visualization for block %d %s \n", b, s);
6444
6445   /* Print names of units */
6446   fprintf (dump, ";;   %-8s", "clock");
6447   for (unit = 0; unit < FUNCTION_UNITS_SIZE; unit++)
6448     if (function_units[unit].bitmask & target_units)
6449       for (i = 0; i < function_units[unit].multiplicity; i++)
6450         fprintf (dump, "  %-33s", function_units[unit].name);
6451   fprintf (dump, "  %-8s\n", "no-unit");
6452
6453   fprintf (dump, ";;   %-8s", "=====");
6454   for (unit = 0; unit < FUNCTION_UNITS_SIZE; unit++)
6455     if (function_units[unit].bitmask & target_units)
6456       for (i = 0; i < function_units[unit].multiplicity; i++)
6457         fprintf (dump, "  %-33s", "==============================");
6458   fprintf (dump, "  %-8s\n", "=======");
6459
6460   /* Print insns in each cycle */
6461   fprintf (dump, "%s\n", visual_tbl);
6462 }
6463
6464 /* Print insns in the 'no_unit' column of visualization */
6465
6466 static void
6467 visualize_no_unit (insn)
6468      rtx insn;
6469 {
6470   vis_no_unit[n_vis_no_unit] = insn;
6471   n_vis_no_unit++;
6472 }
6473
6474 /* Print insns scheduled in clock, for visualization.  */
6475
6476 static void
6477 visualize_scheduled_insns (b, clock)
6478      int b, clock;
6479 {
6480   int i, unit;
6481
6482   /* if no more room, split table into two */
6483   if (n_visual_lines >= MAX_VISUAL_LINES)
6484     {
6485       print_block_visualization (b, "(incomplete)");
6486       init_block_visualization ();
6487     }
6488
6489   n_visual_lines++;
6490
6491   sprintf (visual_tbl + strlen (visual_tbl), ";;   %-8d", clock);
6492   for (unit = 0; unit < FUNCTION_UNITS_SIZE; unit++)
6493     if (function_units[unit].bitmask & target_units)
6494       for (i = 0; i < function_units[unit].multiplicity; i++)
6495         {
6496           int instance = unit + i * FUNCTION_UNITS_SIZE;
6497           rtx insn = unit_last_insn[instance];
6498
6499           /* print insns that still keep the unit busy */
6500           if (insn &&
6501               actual_hazard_this_instance (unit, instance, insn, clock, 0))
6502             {
6503               char str[BUF_LEN];
6504               print_insn (str, insn, 0);
6505               str[INSN_LEN] = '\0';
6506               sprintf (visual_tbl + strlen (visual_tbl), "  %-33s", str);
6507             }
6508           else
6509             sprintf (visual_tbl + strlen (visual_tbl), "  %-33s", "------------------------------");
6510         }
6511
6512   /* print insns that are not assigned to any unit */
6513   for (i = 0; i < n_vis_no_unit; i++)
6514     sprintf (visual_tbl + strlen (visual_tbl), "  %-8d",
6515              INSN_UID (vis_no_unit[i]));
6516   n_vis_no_unit = 0;
6517
6518   sprintf (visual_tbl + strlen (visual_tbl), "\n");
6519 }
6520
6521 /* Print stalled cycles */
6522
6523 static void
6524 visualize_stall_cycles (b, stalls)
6525      int b, stalls;
6526 {
6527   int i;
6528
6529   /* if no more room, split table into two */
6530   if (n_visual_lines >= MAX_VISUAL_LINES)
6531     {
6532       print_block_visualization (b, "(incomplete)");
6533       init_block_visualization ();
6534     }
6535
6536   n_visual_lines++;
6537
6538   sprintf (visual_tbl + strlen (visual_tbl), ";;       ");
6539   for (i = 0; i < stalls; i++)
6540     sprintf (visual_tbl + strlen (visual_tbl), ".");
6541   sprintf (visual_tbl + strlen (visual_tbl), "\n");
6542 }
6543
6544 /* move_insn1: Remove INSN from insn chain, and link it after LAST insn */
6545
6546 static rtx
6547 move_insn1 (insn, last)
6548      rtx insn, last;
6549 {
6550   NEXT_INSN (PREV_INSN (insn)) = NEXT_INSN (insn);
6551   PREV_INSN (NEXT_INSN (insn)) = PREV_INSN (insn);
6552
6553   NEXT_INSN (insn) = NEXT_INSN (last);
6554   PREV_INSN (NEXT_INSN (last)) = insn;
6555
6556   NEXT_INSN (last) = insn;
6557   PREV_INSN (insn) = last;
6558
6559   return insn;
6560 }
6561
6562 /* Search INSN for fake REG_DEAD note pairs for NOTE_INSN_SETJMP,
6563    NOTE_INSN_{LOOP,EHREGION}_{BEG,END}; and convert them back into
6564    NOTEs.  The REG_DEAD note following first one is contains the saved
6565    value for NOTE_BLOCK_NUMBER which is useful for
6566    NOTE_INSN_EH_REGION_{BEG,END} NOTEs.  LAST is the last instruction
6567    output by the instruction scheduler.  Return the new value of LAST.  */
6568
6569 static rtx
6570 reemit_notes (insn, last)
6571      rtx insn;
6572      rtx last;
6573 {
6574   rtx note, retval;
6575
6576   retval = last;
6577   for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
6578     {
6579       if (REG_NOTE_KIND (note) == REG_DEAD
6580           && GET_CODE (XEXP (note, 0)) == CONST_INT)
6581         {
6582           int note_type = INTVAL (XEXP (note, 0));
6583           if (note_type == NOTE_INSN_SETJMP)
6584             {
6585               retval = emit_note_after (NOTE_INSN_SETJMP, insn);
6586               CONST_CALL_P (retval) = CONST_CALL_P (note);
6587               remove_note (insn, note);
6588               note = XEXP (note, 1);
6589             }
6590           else if (note_type == NOTE_INSN_RANGE_START
6591                    || note_type == NOTE_INSN_RANGE_END)
6592             {
6593               last = emit_note_before (note_type, last);
6594               remove_note (insn, note);
6595               note = XEXP (note, 1);
6596               NOTE_RANGE_INFO (last) = XEXP (note, 0);
6597             }
6598           else
6599             {
6600               last = emit_note_before (note_type, last);
6601               remove_note (insn, note);
6602               note = XEXP (note, 1);
6603               NOTE_BLOCK_NUMBER (last) = INTVAL (XEXP (note, 0));
6604             }
6605           remove_note (insn, note);
6606         }
6607     }
6608   return retval;
6609 }
6610
6611 /* Move INSN, and all insns which should be issued before it,
6612    due to SCHED_GROUP_P flag.  Reemit notes if needed.
6613
6614    Return the last insn emitted by the scheduler, which is the
6615    return value from the first call to reemit_notes.  */
6616
6617 static rtx
6618 move_insn (insn, last)
6619      rtx insn, last;
6620 {
6621   rtx retval = NULL;
6622
6623   /* If INSN has SCHED_GROUP_P set, then issue it and any other
6624      insns with SCHED_GROUP_P set first.  */
6625   while (SCHED_GROUP_P (insn))
6626     {
6627       rtx prev = PREV_INSN (insn);
6628
6629       /* Move a SCHED_GROUP_P insn.  */
6630       move_insn1 (insn, last);
6631       /* If this is the first call to reemit_notes, then record
6632          its return value.  */
6633       if (retval == NULL_RTX)
6634         retval = reemit_notes (insn, insn);
6635       else
6636         reemit_notes (insn, insn);
6637       insn = prev;
6638     }
6639
6640   /* Now move the first non SCHED_GROUP_P insn.  */
6641   move_insn1 (insn, last);
6642
6643   /* If this is the first call to reemit_notes, then record
6644      its return value.  */
6645   if (retval == NULL_RTX)
6646     retval = reemit_notes (insn, insn);
6647   else
6648     reemit_notes (insn, insn);
6649
6650   return retval;
6651 }
6652
6653 /* Return an insn which represents a SCHED_GROUP, which is
6654    the last insn in the group.  */
6655
6656 static rtx
6657 group_leader (insn)
6658      rtx insn;
6659 {
6660   rtx prev;
6661
6662   do
6663     {
6664       prev = insn;
6665       insn = next_nonnote_insn (insn);
6666     }
6667   while (insn && SCHED_GROUP_P (insn) && (GET_CODE (insn) != CODE_LABEL));
6668
6669   return prev;
6670 }
6671
6672 /* Use forward list scheduling to rearrange insns of block BB in region RGN,
6673    possibly bringing insns from subsequent blocks in the same region.
6674    Return number of insns scheduled.  */
6675
6676 static int
6677 schedule_block (bb, rgn_n_insns)
6678      int bb;
6679      int rgn_n_insns;
6680 {
6681   /* Local variables.  */
6682   rtx insn, last;
6683   rtx *ready;
6684   int n_ready = 0;
6685   int can_issue_more;
6686
6687   /* flow block of this bb */
6688   int b = BB_TO_BLOCK (bb);
6689
6690   /* target_n_insns == number of insns in b before scheduling starts.
6691      sched_target_n_insns == how many of b's insns were scheduled.
6692      sched_n_insns == how many insns were scheduled in b */
6693   int target_n_insns = 0;
6694   int sched_target_n_insns = 0;
6695   int sched_n_insns = 0;
6696
6697 #define NEED_NOTHING    0
6698 #define NEED_HEAD       1
6699 #define NEED_TAIL       2
6700   int new_needs;
6701
6702   /* head/tail info for this block */
6703   rtx prev_head;
6704   rtx next_tail;
6705   rtx head;
6706   rtx tail;
6707   int bb_src;
6708
6709   /* We used to have code to avoid getting parameters moved from hard
6710      argument registers into pseudos.
6711
6712      However, it was removed when it proved to be of marginal benefit
6713      and caused problems because schedule_block and compute_forward_dependences
6714      had different notions of what the "head" insn was.  */
6715   get_block_head_tail (bb, &head, &tail);
6716
6717   /* Interblock scheduling could have moved the original head insn from this
6718      block into a proceeding block.  This may also cause schedule_block and
6719      compute_forward_dependences to have different notions of what the
6720      "head" insn was.
6721
6722      If the interblock movement happened to make this block start with
6723      some notes (LOOP, EH or SETJMP) before the first real insn, then
6724      HEAD will have various special notes attached to it which must be
6725      removed so that we don't end up with extra copies of the notes.  */
6726   if (GET_RTX_CLASS (GET_CODE (head)) == 'i')
6727     {
6728       rtx note;
6729
6730       for (note = REG_NOTES (head); note; note = XEXP (note, 1))
6731         if (REG_NOTE_KIND (note) == REG_DEAD
6732             && GET_CODE (XEXP (note, 0)) == CONST_INT)
6733           remove_note (head, note);
6734     }
6735
6736   next_tail = NEXT_INSN (tail);
6737   prev_head = PREV_INSN (head);
6738
6739   /* If the only insn left is a NOTE or a CODE_LABEL, then there is no need
6740      to schedule this block.  */
6741   if (head == tail
6742       && (GET_RTX_CLASS (GET_CODE (head)) != 'i'))
6743     return (sched_n_insns);
6744
6745   /* debug info */
6746   if (sched_verbose)
6747     {
6748       fprintf (dump, ";;   ======================================================\n");
6749       fprintf (dump,
6750                ";;   -- basic block %d from %d to %d -- %s reload\n",
6751                b, INSN_UID (BLOCK_HEAD (b)), INSN_UID (BLOCK_END (b)),
6752                (reload_completed ? "after" : "before"));
6753       fprintf (dump, ";;   ======================================================\n");
6754       fprintf (dump, "\n");
6755
6756       visual_tbl = (char *) alloca (get_visual_tbl_length ());
6757       init_block_visualization ();
6758     }
6759
6760   /* remove remaining note insns from the block, save them in
6761      note_list.  These notes are restored at the end of
6762      schedule_block ().  */
6763   note_list = 0;
6764   rm_other_notes (head, tail);
6765
6766   target_bb = bb;
6767
6768   /* prepare current target block info */
6769   if (current_nr_blocks > 1)
6770     {
6771       candidate_table = (candidate *) alloca (current_nr_blocks * sizeof (candidate));
6772
6773       bblst_last = 0;
6774       /* ??? It is not clear why bblst_size is computed this way.  The original
6775          number was clearly too small as it resulted in compiler failures.
6776          Multiplying by the original number by 2 (to account for update_bbs
6777          members) seems to be a reasonable solution.  */
6778       /* ??? Or perhaps there is a bug somewhere else in this file?  */
6779       bblst_size = (current_nr_blocks - bb) * rgn_nr_edges * 2;
6780       bblst_table = (int *) alloca (bblst_size * sizeof (int));
6781
6782       bitlst_table_last = 0;
6783       bitlst_table_size = rgn_nr_edges;
6784       bitlst_table = (int *) alloca (rgn_nr_edges * sizeof (int));
6785
6786       compute_trg_info (bb);
6787     }
6788
6789   clear_units ();
6790
6791   /* Allocate the ready list */
6792   ready = (rtx *) alloca ((rgn_n_insns + 1) * sizeof (rtx));
6793
6794   /* Print debugging information.  */
6795   if (sched_verbose >= 5)
6796     debug_dependencies ();
6797
6798
6799   /* Initialize ready list with all 'ready' insns in target block.
6800      Count number of insns in the target block being scheduled.  */
6801   n_ready = 0;
6802   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
6803     {
6804       rtx next;
6805
6806       if (GET_RTX_CLASS (GET_CODE (insn)) != 'i')
6807         continue;
6808       next = NEXT_INSN (insn);
6809
6810       if (INSN_DEP_COUNT (insn) == 0
6811           && (SCHED_GROUP_P (next) == 0 || GET_RTX_CLASS (GET_CODE (next)) != 'i'))
6812         ready[n_ready++] = insn;
6813       if (!(SCHED_GROUP_P (insn)))
6814         target_n_insns++;
6815     }
6816
6817   /* Add to ready list all 'ready' insns in valid source blocks.
6818      For speculative insns, check-live, exception-free, and
6819      issue-delay.  */
6820   for (bb_src = bb + 1; bb_src < current_nr_blocks; bb_src++)
6821     if (IS_VALID (bb_src))
6822       {
6823         rtx src_head;
6824         rtx src_next_tail;
6825         rtx tail, head;
6826
6827         get_block_head_tail (bb_src, &head, &tail);
6828         src_next_tail = NEXT_INSN (tail);
6829         src_head = head;
6830
6831         if (head == tail
6832             && (GET_RTX_CLASS (GET_CODE (head)) != 'i'))
6833           continue;
6834
6835         for (insn = src_head; insn != src_next_tail; insn = NEXT_INSN (insn))
6836           {
6837             if (GET_RTX_CLASS (GET_CODE (insn)) != 'i')
6838               continue;
6839
6840             if (!CANT_MOVE (insn)
6841                 && (!IS_SPECULATIVE_INSN (insn)
6842                     || (insn_issue_delay (insn) <= 3
6843                         && check_live (insn, bb_src)
6844                         && is_exception_free (insn, bb_src, target_bb))))
6845
6846               {
6847                 rtx next;
6848
6849                 next = NEXT_INSN (insn);
6850                 if (INSN_DEP_COUNT (insn) == 0
6851                     && (SCHED_GROUP_P (next) == 0
6852                         || GET_RTX_CLASS (GET_CODE (next)) != 'i'))
6853                   ready[n_ready++] = insn;
6854               }
6855           }
6856       }
6857
6858 #ifdef MD_SCHED_INIT
6859   MD_SCHED_INIT (dump, sched_verbose);
6860 #endif
6861
6862   /* no insns scheduled in this block yet */
6863   last_scheduled_insn = 0;
6864
6865   /* Q_SIZE is the total number of insns in the queue.  */
6866   q_ptr = 0;
6867   q_size = 0;
6868   last_clock_var = 0;
6869   bzero ((char *) insn_queue, sizeof (insn_queue));
6870
6871   /* Start just before the beginning of time.  */
6872   clock_var = -1;
6873
6874   /* We start inserting insns after PREV_HEAD.  */
6875   last = prev_head;
6876
6877   /* Initialize INSN_QUEUE, LIST and NEW_NEEDS.  */
6878   new_needs = (NEXT_INSN (prev_head) == BLOCK_HEAD (b)
6879                ? NEED_HEAD : NEED_NOTHING);
6880   if (PREV_INSN (next_tail) == BLOCK_END (b))
6881     new_needs |= NEED_TAIL;
6882
6883   /* loop until all the insns in BB are scheduled.  */
6884   while (sched_target_n_insns < target_n_insns)
6885     {
6886       int b1;
6887
6888       clock_var++;
6889
6890       /* Add to the ready list all pending insns that can be issued now.
6891          If there are no ready insns, increment clock until one
6892          is ready and add all pending insns at that point to the ready
6893          list.  */
6894       n_ready = queue_to_ready (ready, n_ready);
6895
6896       if (n_ready == 0)
6897         abort ();
6898
6899       if (sched_verbose >= 2)
6900         {
6901           fprintf (dump, ";;\t\tReady list after queue_to_ready:  ");
6902           debug_ready_list (ready, n_ready);
6903         }
6904
6905       /* Sort the ready list based on priority.  */
6906       SCHED_SORT (ready, n_ready);
6907
6908       /* Allow the target to reorder the list, typically for 
6909          better instruction bundling.  */
6910 #ifdef MD_SCHED_REORDER
6911       MD_SCHED_REORDER (dump, sched_verbose, ready, n_ready, clock_var,
6912                         can_issue_more);
6913 #else
6914       can_issue_more = issue_rate;
6915 #endif
6916
6917       if (sched_verbose)
6918         {
6919           fprintf (dump, "\n;;\tReady list (t =%3d):  ", clock_var);
6920           debug_ready_list (ready, n_ready);
6921         }
6922
6923       /* Issue insns from ready list.  */
6924       while (n_ready != 0 && can_issue_more)
6925         {
6926           /* Select and remove the insn from the ready list.  */
6927           rtx insn = ready[--n_ready];
6928           int cost = actual_hazard (insn_unit (insn), insn, clock_var, 0);
6929
6930           if (cost >= 1)
6931             {
6932               queue_insn (insn, cost);
6933               continue;
6934             }
6935
6936           /* An interblock motion?  */
6937           if (INSN_BB (insn) != target_bb)
6938             {
6939               rtx temp;
6940
6941               if (IS_SPECULATIVE_INSN (insn))
6942                 {
6943                   if (!check_live (insn, INSN_BB (insn)))
6944                     continue;
6945                   update_live (insn, INSN_BB (insn));
6946
6947                   /* For speculative load, mark insns fed by it.  */
6948                   if (IS_LOAD_INSN (insn) || FED_BY_SPEC_LOAD (insn))
6949                     set_spec_fed (insn);
6950
6951                   nr_spec++;
6952                 }
6953               nr_inter++;
6954
6955               temp = insn;
6956               while (SCHED_GROUP_P (temp))
6957                 temp = PREV_INSN (temp);
6958
6959               /* Update source block boundaries.   */
6960               b1 = INSN_BLOCK (temp);
6961               if (temp == BLOCK_HEAD (b1)
6962                   && insn == BLOCK_END (b1))
6963                 {
6964                   /* We moved all the insns in the basic block.
6965                      Emit a note after the last insn and update the
6966                      begin/end boundaries to point to the note.  */
6967                   emit_note_after (NOTE_INSN_DELETED, insn);
6968                   BLOCK_END (b1) = NEXT_INSN (insn);
6969                   BLOCK_HEAD (b1) = NEXT_INSN (insn);
6970                 }
6971               else if (insn == BLOCK_END (b1))
6972                 {
6973                   /* We took insns from the end of the basic block,
6974                      so update the end of block boundary so that it
6975                      points to the first insn we did not move.  */
6976                   BLOCK_END (b1) = PREV_INSN (temp);
6977                 }
6978               else if (temp == BLOCK_HEAD (b1))
6979                 {
6980                   /* We took insns from the start of the basic block,
6981                      so update the start of block boundary so that
6982                      it points to the first insn we did not move.  */
6983                   BLOCK_HEAD (b1) = NEXT_INSN (insn);
6984                 }
6985             }
6986           else
6987             {
6988               /* In block motion.  */
6989               sched_target_n_insns++;
6990             }
6991
6992           last_scheduled_insn = insn;
6993           last = move_insn (insn, last);
6994           sched_n_insns++;
6995
6996 #ifdef MD_SCHED_VARIABLE_ISSUE
6997           MD_SCHED_VARIABLE_ISSUE (dump, sched_verbose, insn,
6998                                    can_issue_more);
6999 #else
7000           can_issue_more--;
7001 #endif
7002
7003           n_ready = schedule_insn (insn, ready, n_ready, clock_var);
7004
7005           /* Close this block after scheduling its jump.  */
7006           if (GET_CODE (last_scheduled_insn) == JUMP_INSN)
7007             break;
7008         }
7009
7010       /* Debug info.  */
7011       if (sched_verbose)
7012         visualize_scheduled_insns (b, clock_var);
7013     }
7014
7015   /* debug info */
7016   if (sched_verbose)
7017     {
7018       fprintf (dump, ";;\tReady list (final):  ");
7019       debug_ready_list (ready, n_ready);
7020       print_block_visualization (b, "");
7021     }
7022
7023   /* Sanity check -- queue must be empty now.  Meaningless if region has
7024      multiple bbs.  */
7025   if (current_nr_blocks > 1)
7026     if (!flag_schedule_interblock && q_size != 0)
7027       abort ();
7028
7029   /* update head/tail boundaries.  */
7030   head = NEXT_INSN (prev_head);
7031   tail = last;
7032
7033   /* Restore-other-notes: NOTE_LIST is the end of a chain of notes
7034      previously found among the insns.  Insert them at the beginning
7035      of the insns.  */
7036   if (note_list != 0)
7037     {
7038       rtx note_head = note_list;
7039
7040       while (PREV_INSN (note_head))
7041         {
7042           note_head = PREV_INSN (note_head);
7043         }
7044
7045       PREV_INSN (note_head) = PREV_INSN (head);
7046       NEXT_INSN (PREV_INSN (head)) = note_head;
7047       PREV_INSN (head) = note_list;
7048       NEXT_INSN (note_list) = head;
7049       head = note_head;
7050     }
7051
7052   /* update target block boundaries.  */
7053   if (new_needs & NEED_HEAD)
7054     BLOCK_HEAD (b) = head;
7055
7056   if (new_needs & NEED_TAIL)
7057     BLOCK_END (b) = tail;
7058
7059   /* debugging */
7060   if (sched_verbose)
7061     {
7062       fprintf (dump, ";;   total time = %d\n;;   new basic block head = %d\n",
7063                clock_var, INSN_UID (BLOCK_HEAD (b)));
7064       fprintf (dump, ";;   new basic block end = %d\n\n",
7065                INSN_UID (BLOCK_END (b)));
7066     }
7067
7068   return (sched_n_insns);
7069 }                               /* schedule_block () */
7070 \f
7071
7072 /* print the bit-set of registers, S.  callable from debugger */
7073
7074 extern void
7075 debug_reg_vector (s)
7076      regset s;
7077 {
7078   int regno;
7079
7080   EXECUTE_IF_SET_IN_REG_SET (s, 0, regno,
7081                              {
7082                                fprintf (dump, " %d", regno);
7083                              });
7084
7085   fprintf (dump, "\n");
7086 }
7087
7088 /* Use the backward dependences from LOG_LINKS to build
7089    forward dependences in INSN_DEPEND.  */
7090
7091 static void
7092 compute_block_forward_dependences (bb)
7093      int bb;
7094 {
7095   rtx insn, link;
7096   rtx tail, head;
7097   rtx next_tail;
7098   enum reg_note dep_type;
7099
7100   get_block_head_tail (bb, &head, &tail);
7101   next_tail = NEXT_INSN (tail);
7102   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
7103     {
7104       if (GET_RTX_CLASS (GET_CODE (insn)) != 'i')
7105         continue;
7106
7107       insn = group_leader (insn);
7108
7109       for (link = LOG_LINKS (insn); link; link = XEXP (link, 1))
7110         {
7111           rtx x = group_leader (XEXP (link, 0));
7112           rtx new_link;
7113
7114           if (x != XEXP (link, 0))
7115             continue;
7116
7117           /* Ignore dependences upon deleted insn */
7118           if (GET_CODE (x) == NOTE || INSN_DELETED_P (x))
7119             continue;
7120           if (find_insn_list (insn, INSN_DEPEND (x)))
7121             continue;
7122
7123           new_link = alloc_INSN_LIST (insn, INSN_DEPEND (x));
7124
7125           dep_type = REG_NOTE_KIND (link);
7126           PUT_REG_NOTE_KIND (new_link, dep_type);
7127
7128           INSN_DEPEND (x) = new_link;
7129           INSN_DEP_COUNT (insn) += 1;
7130         }
7131     }
7132 }
7133
7134 /* Initialize variables for region data dependence analysis.
7135    n_bbs is the number of region blocks */
7136
7137 __inline static void
7138 init_rgn_data_dependences (n_bbs)
7139      int n_bbs;
7140 {
7141   int bb;
7142
7143   /* variables for which one copy exists for each block */
7144   bzero ((char *) bb_pending_read_insns, n_bbs * sizeof (rtx));
7145   bzero ((char *) bb_pending_read_mems, n_bbs * sizeof (rtx));
7146   bzero ((char *) bb_pending_write_insns, n_bbs * sizeof (rtx));
7147   bzero ((char *) bb_pending_write_mems, n_bbs * sizeof (rtx));
7148   bzero ((char *) bb_pending_lists_length, n_bbs * sizeof (rtx));
7149   bzero ((char *) bb_last_pending_memory_flush, n_bbs * sizeof (rtx));
7150   bzero ((char *) bb_last_function_call, n_bbs * sizeof (rtx));
7151   bzero ((char *) bb_sched_before_next_call, n_bbs * sizeof (rtx));
7152
7153   /* Create an insn here so that we can hang dependencies off of it later.  */
7154   for (bb = 0; bb < n_bbs; bb++)
7155     {
7156       bb_sched_before_next_call[bb] =
7157         gen_rtx_INSN (VOIDmode, 0, NULL_RTX, NULL_RTX,
7158                       NULL_RTX, 0, NULL_RTX, NULL_RTX);
7159       LOG_LINKS (bb_sched_before_next_call[bb]) = 0;
7160     }
7161 }
7162
7163 /* Add dependences so that branches are scheduled to run last in their block */
7164
7165 static void
7166 add_branch_dependences (head, tail)
7167      rtx head, tail;
7168 {
7169
7170   rtx insn, last;
7171
7172   /* For all branches, calls, uses, and cc0 setters, force them to remain
7173      in order at the end of the block by adding dependencies and giving
7174      the last a high priority.  There may be notes present, and prev_head
7175      may also be a note.
7176
7177      Branches must obviously remain at the end.  Calls should remain at the
7178      end since moving them results in worse register allocation.  Uses remain
7179      at the end to ensure proper register allocation.  cc0 setters remaim
7180      at the end because they can't be moved away from their cc0 user.  */
7181   insn = tail;
7182   last = 0;
7183   while (GET_CODE (insn) == CALL_INSN || GET_CODE (insn) == JUMP_INSN
7184          || (GET_CODE (insn) == INSN
7185              && (GET_CODE (PATTERN (insn)) == USE
7186 #ifdef HAVE_cc0
7187                  || sets_cc0_p (PATTERN (insn))
7188 #endif
7189              ))
7190          || GET_CODE (insn) == NOTE)
7191     {
7192       if (GET_CODE (insn) != NOTE)
7193         {
7194           if (last != 0
7195               && !find_insn_list (insn, LOG_LINKS (last)))
7196             {
7197               add_dependence (last, insn, REG_DEP_ANTI);
7198               INSN_REF_COUNT (insn)++;
7199             }
7200
7201           CANT_MOVE (insn) = 1;
7202
7203           last = insn;
7204           /* Skip over insns that are part of a group.
7205              Make each insn explicitly depend on the previous insn.
7206              This ensures that only the group header will ever enter
7207              the ready queue (and, when scheduled, will automatically
7208              schedule the SCHED_GROUP_P block).  */
7209           while (SCHED_GROUP_P (insn))
7210             {
7211               rtx temp = prev_nonnote_insn (insn);
7212               add_dependence (insn, temp, REG_DEP_ANTI);
7213               insn = temp;
7214             }
7215         }
7216
7217       /* Don't overrun the bounds of the basic block.  */
7218       if (insn == head)
7219         break;
7220
7221       insn = PREV_INSN (insn);
7222     }
7223
7224   /* make sure these insns are scheduled last in their block */
7225   insn = last;
7226   if (insn != 0)
7227     while (insn != head)
7228       {
7229         insn = prev_nonnote_insn (insn);
7230
7231         if (INSN_REF_COUNT (insn) != 0)
7232           continue;
7233
7234         if (!find_insn_list (last, LOG_LINKS (insn)))
7235           add_dependence (last, insn, REG_DEP_ANTI);
7236         INSN_REF_COUNT (insn) = 1;
7237
7238         /* Skip over insns that are part of a group.  */
7239         while (SCHED_GROUP_P (insn))
7240           insn = prev_nonnote_insn (insn);
7241       }
7242 }
7243
7244 /* Compute bacward dependences inside BB.  In a multiple blocks region:
7245    (1) a bb is analyzed after its predecessors, and (2) the lists in
7246    effect at the end of bb (after analyzing for bb) are inherited by
7247    bb's successrs.
7248
7249    Specifically for reg-reg data dependences, the block insns are
7250    scanned by sched_analyze () top-to-bottom.  Two lists are
7251    naintained by sched_analyze (): reg_last_defs[] for register DEFs,
7252    and reg_last_uses[] for register USEs.
7253
7254    When analysis is completed for bb, we update for its successors:
7255    ;  - DEFS[succ] = Union (DEFS [succ], DEFS [bb])
7256    ;  - USES[succ] = Union (USES [succ], DEFS [bb])
7257
7258    The mechanism for computing mem-mem data dependence is very
7259    similar, and the result is interblock dependences in the region.  */
7260
7261 static void
7262 compute_block_backward_dependences (bb)
7263      int bb;
7264 {
7265   int b;
7266   rtx x;
7267   rtx head, tail;
7268   int max_reg = max_reg_num ();
7269
7270   b = BB_TO_BLOCK (bb);
7271
7272   if (current_nr_blocks == 1)
7273     {
7274       reg_last_uses = (rtx *) alloca (max_reg * sizeof (rtx));
7275       reg_last_sets = (rtx *) alloca (max_reg * sizeof (rtx));
7276       reg_last_clobbers = (rtx *) alloca (max_reg * sizeof (rtx));
7277
7278       bzero ((char *) reg_last_uses, max_reg * sizeof (rtx));
7279       bzero ((char *) reg_last_sets, max_reg * sizeof (rtx));
7280       bzero ((char *) reg_last_clobbers, max_reg * sizeof (rtx));
7281
7282       pending_read_insns = 0;
7283       pending_read_mems = 0;
7284       pending_write_insns = 0;
7285       pending_write_mems = 0;
7286       pending_lists_length = 0;
7287       last_function_call = 0;
7288       last_pending_memory_flush = 0;
7289       sched_before_next_call
7290         = gen_rtx_INSN (VOIDmode, 0, NULL_RTX, NULL_RTX,
7291                         NULL_RTX, 0, NULL_RTX, NULL_RTX);
7292       LOG_LINKS (sched_before_next_call) = 0;
7293     }
7294   else
7295     {
7296       reg_last_uses = bb_reg_last_uses[bb];
7297       reg_last_sets = bb_reg_last_sets[bb];
7298       reg_last_clobbers = bb_reg_last_clobbers[bb];
7299
7300       pending_read_insns = bb_pending_read_insns[bb];
7301       pending_read_mems = bb_pending_read_mems[bb];
7302       pending_write_insns = bb_pending_write_insns[bb];
7303       pending_write_mems = bb_pending_write_mems[bb];
7304       pending_lists_length = bb_pending_lists_length[bb];
7305       last_function_call = bb_last_function_call[bb];
7306       last_pending_memory_flush = bb_last_pending_memory_flush[bb];
7307
7308       sched_before_next_call = bb_sched_before_next_call[bb];
7309     }
7310
7311   /* do the analysis for this block */
7312   get_block_head_tail (bb, &head, &tail);
7313   sched_analyze (head, tail);
7314   add_branch_dependences (head, tail);
7315
7316   if (current_nr_blocks > 1)
7317     {
7318       int e, first_edge;
7319       int b_succ, bb_succ;
7320       int reg;
7321       rtx link_insn, link_mem;
7322       rtx u;
7323
7324       /* these lists should point to the right place, for correct freeing later.  */
7325       bb_pending_read_insns[bb] = pending_read_insns;
7326       bb_pending_read_mems[bb] = pending_read_mems;
7327       bb_pending_write_insns[bb] = pending_write_insns;
7328       bb_pending_write_mems[bb] = pending_write_mems;
7329
7330       /* bb's structures are inherited by it's successors */
7331       first_edge = e = OUT_EDGES (b);
7332       if (e > 0)
7333         do
7334           {
7335             b_succ = TO_BLOCK (e);
7336             bb_succ = BLOCK_TO_BB (b_succ);
7337
7338             /* only bbs "below" bb, in the same region, are interesting */
7339             if (CONTAINING_RGN (b) != CONTAINING_RGN (b_succ)
7340                 || bb_succ <= bb)
7341               {
7342                 e = NEXT_OUT (e);
7343                 continue;
7344               }
7345
7346             for (reg = 0; reg < max_reg; reg++)
7347               {
7348
7349                 /* reg-last-uses lists are inherited by bb_succ */
7350                 for (u = reg_last_uses[reg]; u; u = XEXP (u, 1))
7351                   {
7352                     if (find_insn_list (XEXP (u, 0), (bb_reg_last_uses[bb_succ])[reg]))
7353                       continue;
7354
7355                     (bb_reg_last_uses[bb_succ])[reg]
7356                       = alloc_INSN_LIST (XEXP (u, 0),
7357                                          (bb_reg_last_uses[bb_succ])[reg]);
7358                   }
7359
7360                 /* reg-last-defs lists are inherited by bb_succ */
7361                 for (u = reg_last_sets[reg]; u; u = XEXP (u, 1))
7362                   {
7363                     if (find_insn_list (XEXP (u, 0), (bb_reg_last_sets[bb_succ])[reg]))
7364                       continue;
7365
7366                     (bb_reg_last_sets[bb_succ])[reg]
7367                       = alloc_INSN_LIST (XEXP (u, 0),
7368                                          (bb_reg_last_sets[bb_succ])[reg]);
7369                   }
7370
7371                 for (u = reg_last_clobbers[reg]; u; u = XEXP (u, 1))
7372                   {
7373                     if (find_insn_list (XEXP (u, 0), (bb_reg_last_clobbers[bb_succ])[reg]))
7374                       continue;
7375
7376                     (bb_reg_last_clobbers[bb_succ])[reg]
7377                       = alloc_INSN_LIST (XEXP (u, 0),
7378                                          (bb_reg_last_clobbers[bb_succ])[reg]);
7379                   }
7380               }
7381
7382             /* mem read/write lists are inherited by bb_succ */
7383             link_insn = pending_read_insns;
7384             link_mem = pending_read_mems;
7385             while (link_insn)
7386               {
7387                 if (!(find_insn_mem_list (XEXP (link_insn, 0), XEXP (link_mem, 0),
7388                                           bb_pending_read_insns[bb_succ],
7389                                           bb_pending_read_mems[bb_succ])))
7390                   add_insn_mem_dependence (&bb_pending_read_insns[bb_succ],
7391                                            &bb_pending_read_mems[bb_succ],
7392                                    XEXP (link_insn, 0), XEXP (link_mem, 0));
7393                 link_insn = XEXP (link_insn, 1);
7394                 link_mem = XEXP (link_mem, 1);
7395               }
7396
7397             link_insn = pending_write_insns;
7398             link_mem = pending_write_mems;
7399             while (link_insn)
7400               {
7401                 if (!(find_insn_mem_list (XEXP (link_insn, 0), XEXP (link_mem, 0),
7402                                           bb_pending_write_insns[bb_succ],
7403                                           bb_pending_write_mems[bb_succ])))
7404                   add_insn_mem_dependence (&bb_pending_write_insns[bb_succ],
7405                                            &bb_pending_write_mems[bb_succ],
7406                                    XEXP (link_insn, 0), XEXP (link_mem, 0));
7407
7408                 link_insn = XEXP (link_insn, 1);
7409                 link_mem = XEXP (link_mem, 1);
7410               }
7411
7412             /* last_function_call is inherited by bb_succ */
7413             for (u = last_function_call; u; u = XEXP (u, 1))
7414               {
7415                 if (find_insn_list (XEXP (u, 0), bb_last_function_call[bb_succ]))
7416                   continue;
7417
7418                 bb_last_function_call[bb_succ]
7419                   = alloc_INSN_LIST (XEXP (u, 0),
7420                                      bb_last_function_call[bb_succ]);
7421               }
7422
7423             /* last_pending_memory_flush is inherited by bb_succ */
7424             for (u = last_pending_memory_flush; u; u = XEXP (u, 1))
7425               {
7426                 if (find_insn_list (XEXP (u, 0), bb_last_pending_memory_flush[bb_succ]))
7427                   continue;
7428
7429                 bb_last_pending_memory_flush[bb_succ]
7430                   = alloc_INSN_LIST (XEXP (u, 0),
7431                                      bb_last_pending_memory_flush[bb_succ]);
7432               }
7433
7434             /* sched_before_next_call is inherited by bb_succ */
7435             x = LOG_LINKS (sched_before_next_call);
7436             for (; x; x = XEXP (x, 1))
7437               add_dependence (bb_sched_before_next_call[bb_succ],
7438                               XEXP (x, 0), REG_DEP_ANTI);
7439
7440             e = NEXT_OUT (e);
7441           }
7442         while (e != first_edge);
7443     }
7444
7445   /* Free up the INSN_LISTs 
7446
7447      Note this loop is executed max_reg * nr_regions times.  It's first 
7448      implementation accounted for over 90% of the calls to free_list.
7449      The list was empty for the vast majority of those calls.  On the PA,
7450      not calling free_list in those cases improves -O2 compile times by
7451      3-5% on average.  */
7452   for (b = 0; b < max_reg; ++b)
7453     {
7454       if (reg_last_clobbers[b])
7455         free_list (&reg_last_clobbers[b], &unused_insn_list);
7456       if (reg_last_sets[b])
7457         free_list (&reg_last_sets[b], &unused_insn_list);
7458       if (reg_last_uses[b])
7459         free_list (&reg_last_uses[b], &unused_insn_list);
7460     }
7461
7462   /* Assert that we won't need bb_reg_last_* for this block anymore.  */
7463   if (current_nr_blocks > 1)
7464     {
7465       bb_reg_last_uses[bb] = (rtx *) NULL_RTX;
7466       bb_reg_last_sets[bb] = (rtx *) NULL_RTX;
7467       bb_reg_last_clobbers[bb] = (rtx *) NULL_RTX;
7468     }
7469 }
7470
7471 /* Print dependences for debugging, callable from debugger */
7472
7473 void
7474 debug_dependencies ()
7475 {
7476   int bb;
7477
7478   fprintf (dump, ";;   --------------- forward dependences: ------------ \n");
7479   for (bb = 0; bb < current_nr_blocks; bb++)
7480     {
7481       if (1)
7482         {
7483           rtx head, tail;
7484           rtx next_tail;
7485           rtx insn;
7486
7487           get_block_head_tail (bb, &head, &tail);
7488           next_tail = NEXT_INSN (tail);
7489           fprintf (dump, "\n;;   --- Region Dependences --- b %d bb %d \n",
7490                    BB_TO_BLOCK (bb), bb);
7491
7492           fprintf (dump, ";;   %7s%6s%6s%6s%6s%6s%11s%6s\n",
7493           "insn", "code", "bb", "dep", "prio", "cost", "blockage", "units");
7494           fprintf (dump, ";;   %7s%6s%6s%6s%6s%6s%11s%6s\n",
7495           "----", "----", "--", "---", "----", "----", "--------", "-----");
7496           for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
7497             {
7498               rtx link;
7499               int unit, range;
7500
7501               if (GET_RTX_CLASS (GET_CODE (insn)) != 'i')
7502                 {
7503                   int n;
7504                   fprintf (dump, ";;   %6d ", INSN_UID (insn));
7505                   if (GET_CODE (insn) == NOTE)
7506                     {
7507                       n = NOTE_LINE_NUMBER (insn);
7508                       if (n < 0)
7509                         fprintf (dump, "%s\n", GET_NOTE_INSN_NAME (n));
7510                       else
7511                         fprintf (dump, "line %d, file %s\n", n,
7512                                  NOTE_SOURCE_FILE (insn));
7513                     }
7514                   else
7515                     fprintf (dump, " {%s}\n", GET_RTX_NAME (GET_CODE (insn)));
7516                   continue;
7517                 }
7518
7519               unit = insn_unit (insn);
7520               range = (unit < 0
7521                  || function_units[unit].blockage_range_function == 0) ? 0 :
7522                 function_units[unit].blockage_range_function (insn);
7523               fprintf (dump,
7524                        ";;   %s%5d%6d%6d%6d%6d%6d  %3d -%3d   ",
7525                        (SCHED_GROUP_P (insn) ? "+" : " "),
7526                        INSN_UID (insn),
7527                        INSN_CODE (insn),
7528                        INSN_BB (insn),
7529                        INSN_DEP_COUNT (insn),
7530                        INSN_PRIORITY (insn),
7531                        insn_cost (insn, 0, 0),
7532                        (int) MIN_BLOCKAGE_COST (range),
7533                        (int) MAX_BLOCKAGE_COST (range));
7534               insn_print_units (insn);
7535               fprintf (dump, "\t: ");
7536               for (link = INSN_DEPEND (insn); link; link = XEXP (link, 1))
7537                 fprintf (dump, "%d ", INSN_UID (XEXP (link, 0)));
7538               fprintf (dump, "\n");
7539             }
7540         }
7541     }
7542   fprintf (dump, "\n");
7543 }
7544
7545 /* Set_priorities: compute priority of each insn in the block */
7546
7547 static int
7548 set_priorities (bb)
7549      int bb;
7550 {
7551   rtx insn;
7552   int n_insn;
7553
7554   rtx tail;
7555   rtx prev_head;
7556   rtx head;
7557
7558   get_block_head_tail (bb, &head, &tail);
7559   prev_head = PREV_INSN (head);
7560
7561   if (head == tail
7562       && (GET_RTX_CLASS (GET_CODE (head)) != 'i'))
7563     return 0;
7564
7565   n_insn = 0;
7566   for (insn = tail; insn != prev_head; insn = PREV_INSN (insn))
7567     {
7568
7569       if (GET_CODE (insn) == NOTE)
7570         continue;
7571
7572       if (!(SCHED_GROUP_P (insn)))
7573         n_insn++;
7574       (void) priority (insn);
7575     }
7576
7577   return n_insn;
7578 }
7579
7580 /* Make each element of VECTOR point at an rtx-vector,
7581    taking the space for all those rtx-vectors from SPACE.
7582    SPACE is of type (rtx *), but it is really as long as NELTS rtx-vectors.
7583    BYTES_PER_ELT is the number of bytes in one rtx-vector.
7584    (this is the same as init_regset_vector () in flow.c) */
7585
7586 static void
7587 init_rtx_vector (vector, space, nelts, bytes_per_elt)
7588      rtx **vector;
7589      rtx *space;
7590      int nelts;
7591      int bytes_per_elt;
7592 {
7593   register int i;
7594   register rtx *p = space;
7595
7596   for (i = 0; i < nelts; i++)
7597     {
7598       vector[i] = p;
7599       p += bytes_per_elt / sizeof (*p);
7600     }
7601 }
7602
7603 /* Schedule a region.  A region is either an inner loop, a loop-free
7604    subroutine, or a single basic block.  Each bb in the region is
7605    scheduled after its flow predecessors.  */
7606
7607 static void
7608 schedule_region (rgn)
7609      int rgn;
7610 {
7611   int bb;
7612   int rgn_n_insns = 0;
7613   int sched_rgn_n_insns = 0;
7614
7615   /* set variables for the current region */
7616   current_nr_blocks = RGN_NR_BLOCKS (rgn);
7617   current_blocks = RGN_BLOCKS (rgn);
7618
7619   reg_pending_sets = ALLOCA_REG_SET ();
7620   reg_pending_clobbers = ALLOCA_REG_SET ();
7621   reg_pending_sets_all = 0;
7622
7623   /* initializations for region data dependence analyisis */
7624   if (current_nr_blocks > 1)
7625     {
7626       rtx *space;
7627       int maxreg = max_reg_num ();
7628
7629       bb_reg_last_uses = (rtx **) alloca (current_nr_blocks * sizeof (rtx *));
7630       space = (rtx *) alloca (current_nr_blocks * maxreg * sizeof (rtx));
7631       bzero ((char *) space, current_nr_blocks * maxreg * sizeof (rtx));
7632       init_rtx_vector (bb_reg_last_uses, space, current_nr_blocks,
7633                        maxreg * sizeof (rtx *));
7634
7635       bb_reg_last_sets = (rtx **) alloca (current_nr_blocks * sizeof (rtx *));
7636       space = (rtx *) alloca (current_nr_blocks * maxreg * sizeof (rtx));
7637       bzero ((char *) space, current_nr_blocks * maxreg * sizeof (rtx));
7638       init_rtx_vector (bb_reg_last_sets, space, current_nr_blocks,
7639                        maxreg * sizeof (rtx *));
7640
7641       bb_reg_last_clobbers =
7642         (rtx **) alloca (current_nr_blocks * sizeof (rtx *));
7643       space = (rtx *) alloca (current_nr_blocks * maxreg * sizeof (rtx));
7644       bzero ((char *) space, current_nr_blocks * maxreg * sizeof (rtx));
7645       init_rtx_vector (bb_reg_last_clobbers, space, current_nr_blocks,
7646                        maxreg * sizeof (rtx *));
7647
7648       bb_pending_read_insns = (rtx *) alloca (current_nr_blocks * sizeof (rtx));
7649       bb_pending_read_mems = (rtx *) alloca (current_nr_blocks * sizeof (rtx));
7650       bb_pending_write_insns =
7651         (rtx *) alloca (current_nr_blocks * sizeof (rtx));
7652       bb_pending_write_mems = (rtx *) alloca (current_nr_blocks * sizeof (rtx));
7653       bb_pending_lists_length =
7654         (int *) alloca (current_nr_blocks * sizeof (int));
7655       bb_last_pending_memory_flush =
7656         (rtx *) alloca (current_nr_blocks * sizeof (rtx));
7657       bb_last_function_call = (rtx *) alloca (current_nr_blocks * sizeof (rtx));
7658       bb_sched_before_next_call =
7659         (rtx *) alloca (current_nr_blocks * sizeof (rtx));
7660
7661       init_rgn_data_dependences (current_nr_blocks);
7662     }
7663
7664   /* compute LOG_LINKS */
7665   for (bb = 0; bb < current_nr_blocks; bb++)
7666     compute_block_backward_dependences (bb);
7667
7668   /* compute INSN_DEPEND */
7669   for (bb = current_nr_blocks - 1; bb >= 0; bb--)
7670     compute_block_forward_dependences (bb);
7671
7672   /* Delete line notes, compute live-regs at block end, and set priorities.  */
7673   dead_notes = 0;
7674   for (bb = 0; bb < current_nr_blocks; bb++)
7675     {
7676       if (reload_completed == 0)
7677         find_pre_sched_live (bb);
7678
7679       if (write_symbols != NO_DEBUG)
7680         {
7681           save_line_notes (bb);
7682           rm_line_notes (bb);
7683         }
7684
7685       rgn_n_insns += set_priorities (bb);
7686     }
7687
7688   /* compute interblock info: probabilities, split-edges, dominators, etc.  */
7689   if (current_nr_blocks > 1)
7690     {
7691       int i;
7692
7693       prob = (float *) alloca ((current_nr_blocks) * sizeof (float));
7694
7695       bbset_size = current_nr_blocks / HOST_BITS_PER_WIDE_INT + 1;
7696       dom = (bbset *) alloca (current_nr_blocks * sizeof (bbset));
7697       for (i = 0; i < current_nr_blocks; i++)
7698         {
7699           dom[i] = (bbset) alloca (bbset_size * sizeof (HOST_WIDE_INT));
7700           bzero ((char *) dom[i], bbset_size * sizeof (HOST_WIDE_INT));
7701         }
7702
7703       /* edge to bit */
7704       rgn_nr_edges = 0;
7705       edge_to_bit = (int *) alloca (nr_edges * sizeof (int));
7706       for (i = 1; i < nr_edges; i++)
7707         if (CONTAINING_RGN (FROM_BLOCK (i)) == rgn)
7708           EDGE_TO_BIT (i) = rgn_nr_edges++;
7709       rgn_edges = (int *) alloca (rgn_nr_edges * sizeof (int));
7710
7711       rgn_nr_edges = 0;
7712       for (i = 1; i < nr_edges; i++)
7713         if (CONTAINING_RGN (FROM_BLOCK (i)) == (rgn))
7714           rgn_edges[rgn_nr_edges++] = i;
7715
7716       /* split edges */
7717       edgeset_size = rgn_nr_edges / HOST_BITS_PER_WIDE_INT + 1;
7718       pot_split = (edgeset *) alloca (current_nr_blocks * sizeof (edgeset));
7719       ancestor_edges = (edgeset *) alloca (current_nr_blocks * sizeof (edgeset));
7720       for (i = 0; i < current_nr_blocks; i++)
7721         {
7722           pot_split[i] =
7723             (edgeset) alloca (edgeset_size * sizeof (HOST_WIDE_INT));
7724           bzero ((char *) pot_split[i],
7725                  edgeset_size * sizeof (HOST_WIDE_INT));
7726           ancestor_edges[i] =
7727             (edgeset) alloca (edgeset_size * sizeof (HOST_WIDE_INT));
7728           bzero ((char *) ancestor_edges[i],
7729                  edgeset_size * sizeof (HOST_WIDE_INT));
7730         }
7731
7732       /* compute probabilities, dominators, split_edges */
7733       for (bb = 0; bb < current_nr_blocks; bb++)
7734         compute_dom_prob_ps (bb);
7735     }
7736
7737   /* now we can schedule all blocks */
7738   for (bb = 0; bb < current_nr_blocks; bb++)
7739     {
7740       sched_rgn_n_insns += schedule_block (bb, rgn_n_insns);
7741
7742 #ifdef USE_C_ALLOCA
7743       alloca (0);
7744 #endif
7745     }
7746
7747   /* sanity check: verify that all region insns were scheduled */
7748   if (sched_rgn_n_insns != rgn_n_insns)
7749     abort ();
7750
7751   /* update register life and usage information */
7752   if (reload_completed == 0)
7753     {
7754       for (bb = current_nr_blocks - 1; bb >= 0; bb--)
7755         find_post_sched_live (bb);
7756
7757       if (current_nr_blocks <= 1)
7758         /* Sanity check.  There should be no REG_DEAD notes leftover at the end.
7759            In practice, this can occur as the result of bugs in flow, combine.c,
7760            and/or sched.c.  The values of the REG_DEAD notes remaining are
7761            meaningless, because dead_notes is just used as a free list.  */
7762         if (dead_notes != 0)
7763           abort ();
7764     }
7765
7766   /* restore line notes.  */
7767   if (write_symbols != NO_DEBUG)
7768     {
7769       for (bb = 0; bb < current_nr_blocks; bb++)
7770         restore_line_notes (bb);
7771     }
7772
7773   /* Done with this region */
7774   free_pending_lists ();
7775
7776   FREE_REG_SET (reg_pending_sets);
7777   FREE_REG_SET (reg_pending_clobbers);
7778 }
7779
7780 /* Subroutine of update_flow_info.  Determines whether any new REG_NOTEs are
7781    needed for the hard register mentioned in the note.  This can happen
7782    if the reference to the hard register in the original insn was split into
7783    several smaller hard register references in the split insns.  */
7784
7785 static void
7786 split_hard_reg_notes (note, first, last)
7787      rtx note, first, last;
7788 {
7789   rtx reg, temp, link;
7790   int n_regs, i, new_reg;
7791   rtx insn;
7792
7793   /* Assume that this is a REG_DEAD note.  */
7794   if (REG_NOTE_KIND (note) != REG_DEAD)
7795     abort ();
7796
7797   reg = XEXP (note, 0);
7798
7799   n_regs = HARD_REGNO_NREGS (REGNO (reg), GET_MODE (reg));
7800
7801   for (i = 0; i < n_regs; i++)
7802     {
7803       new_reg = REGNO (reg) + i;
7804
7805       /* Check for references to new_reg in the split insns.  */
7806       for (insn = last;; insn = PREV_INSN (insn))
7807         {
7808           if (GET_RTX_CLASS (GET_CODE (insn)) == 'i'
7809               && (temp = regno_use_in (new_reg, PATTERN (insn))))
7810             {
7811               /* Create a new reg dead note ere.  */
7812               link = alloc_EXPR_LIST (REG_DEAD, temp, REG_NOTES (insn));
7813               REG_NOTES (insn) = link;
7814
7815               /* If killed multiple registers here, then add in the excess.  */
7816               i += HARD_REGNO_NREGS (REGNO (temp), GET_MODE (temp)) - 1;
7817
7818               break;
7819             }
7820           /* It isn't mentioned anywhere, so no new reg note is needed for
7821              this register.  */
7822           if (insn == first)
7823             break;
7824         }
7825     }
7826 }
7827
7828 /* Subroutine of update_flow_info.  Determines whether a SET or CLOBBER in an
7829    insn created by splitting needs a REG_DEAD or REG_UNUSED note added.  */
7830
7831 static void
7832 new_insn_dead_notes (pat, insn, last, orig_insn)
7833      rtx pat, insn, last, orig_insn;
7834 {
7835   rtx dest, tem, set;
7836
7837   /* PAT is either a CLOBBER or a SET here.  */
7838   dest = XEXP (pat, 0);
7839
7840   while (GET_CODE (dest) == ZERO_EXTRACT || GET_CODE (dest) == SUBREG
7841          || GET_CODE (dest) == STRICT_LOW_PART
7842          || GET_CODE (dest) == SIGN_EXTRACT)
7843     dest = XEXP (dest, 0);
7844
7845   if (GET_CODE (dest) == REG)
7846     {
7847       /* If the original insn already used this register, we may not add new
7848          notes for it.  One example for a split that needs this test is
7849          when a multi-word memory access with register-indirect addressing
7850          is split into multiple memory accesses with auto-increment and
7851          one adjusting add instruction for the address register.  */
7852       if (reg_referenced_p (dest, PATTERN (orig_insn)))
7853         return;
7854       for (tem = last; tem != insn; tem = PREV_INSN (tem))
7855         {
7856           if (GET_RTX_CLASS (GET_CODE (tem)) == 'i'
7857               && reg_overlap_mentioned_p (dest, PATTERN (tem))
7858               && (set = single_set (tem)))
7859             {
7860               rtx tem_dest = SET_DEST (set);
7861
7862               while (GET_CODE (tem_dest) == ZERO_EXTRACT
7863                      || GET_CODE (tem_dest) == SUBREG
7864                      || GET_CODE (tem_dest) == STRICT_LOW_PART
7865                      || GET_CODE (tem_dest) == SIGN_EXTRACT)
7866                 tem_dest = XEXP (tem_dest, 0);
7867
7868               if (!rtx_equal_p (tem_dest, dest))
7869                 {
7870                   /* Use the same scheme as combine.c, don't put both REG_DEAD
7871                      and REG_UNUSED notes on the same insn.  */
7872                   if (!find_regno_note (tem, REG_UNUSED, REGNO (dest))
7873                       && !find_regno_note (tem, REG_DEAD, REGNO (dest)))
7874                     {
7875                       rtx note = alloc_EXPR_LIST (REG_DEAD, dest,
7876                                                   REG_NOTES (tem));
7877                       REG_NOTES (tem) = note;
7878                     }
7879                   /* The reg only dies in one insn, the last one that uses
7880                      it.  */
7881                   break;
7882                 }
7883               else if (reg_overlap_mentioned_p (dest, SET_SRC (set)))
7884                 /* We found an instruction that both uses the register,
7885                    and sets it, so no new REG_NOTE is needed for this set.  */
7886                 break;
7887             }
7888         }
7889       /* If this is a set, it must die somewhere, unless it is the dest of
7890          the original insn, and hence is live after the original insn.  Abort
7891          if it isn't supposed to be live after the original insn.
7892
7893          If this is a clobber, then just add a REG_UNUSED note.  */
7894       if (tem == insn)
7895         {
7896           int live_after_orig_insn = 0;
7897           rtx pattern = PATTERN (orig_insn);
7898           int i;
7899
7900           if (GET_CODE (pat) == CLOBBER)
7901             {
7902               rtx note = alloc_EXPR_LIST (REG_UNUSED, dest, REG_NOTES (insn));
7903               REG_NOTES (insn) = note;
7904               return;
7905             }
7906
7907           /* The original insn could have multiple sets, so search the
7908              insn for all sets.  */
7909           if (GET_CODE (pattern) == SET)
7910             {
7911               if (reg_overlap_mentioned_p (dest, SET_DEST (pattern)))
7912                 live_after_orig_insn = 1;
7913             }
7914           else if (GET_CODE (pattern) == PARALLEL)
7915             {
7916               for (i = 0; i < XVECLEN (pattern, 0); i++)
7917                 if (GET_CODE (XVECEXP (pattern, 0, i)) == SET
7918                     && reg_overlap_mentioned_p (dest,
7919                                                 SET_DEST (XVECEXP (pattern,
7920                                                                    0, i))))
7921                   live_after_orig_insn = 1;
7922             }
7923
7924           if (!live_after_orig_insn)
7925             abort ();
7926         }
7927     }
7928 }
7929
7930 /* Subroutine of update_flow_info.  Update the value of reg_n_sets for all
7931    registers modified by X.  INC is -1 if the containing insn is being deleted,
7932    and is 1 if the containing insn is a newly generated insn.  */
7933
7934 static void
7935 update_n_sets (x, inc)
7936      rtx x;
7937      int inc;
7938 {
7939   rtx dest = SET_DEST (x);
7940
7941   while (GET_CODE (dest) == STRICT_LOW_PART || GET_CODE (dest) == SUBREG
7942       || GET_CODE (dest) == ZERO_EXTRACT || GET_CODE (dest) == SIGN_EXTRACT)
7943     dest = SUBREG_REG (dest);
7944
7945   if (GET_CODE (dest) == REG)
7946     {
7947       int regno = REGNO (dest);
7948
7949       if (regno < FIRST_PSEUDO_REGISTER)
7950         {
7951           register int i;
7952           int endregno = regno + HARD_REGNO_NREGS (regno, GET_MODE (dest));
7953
7954           for (i = regno; i < endregno; i++)
7955             REG_N_SETS (i) += inc;
7956         }
7957       else
7958         REG_N_SETS (regno) += inc;
7959     }
7960 }
7961
7962 /* Updates all flow-analysis related quantities (including REG_NOTES) for
7963    the insns from FIRST to LAST inclusive that were created by splitting
7964    ORIG_INSN.  NOTES are the original REG_NOTES.  */
7965
7966 void
7967 update_flow_info (notes, first, last, orig_insn)
7968      rtx notes;
7969      rtx first, last;
7970      rtx orig_insn;
7971 {
7972   rtx insn, note;
7973   rtx next;
7974   rtx orig_dest, temp;
7975   rtx set;
7976
7977   /* Get and save the destination set by the original insn.  */
7978
7979   orig_dest = single_set (orig_insn);
7980   if (orig_dest)
7981     orig_dest = SET_DEST (orig_dest);
7982
7983   /* Move REG_NOTES from the original insn to where they now belong.  */
7984
7985   for (note = notes; note; note = next)
7986     {
7987       next = XEXP (note, 1);
7988       switch (REG_NOTE_KIND (note))
7989         {
7990         case REG_DEAD:
7991         case REG_UNUSED:
7992           /* Move these notes from the original insn to the last new insn where
7993              the register is now set.  */
7994
7995           for (insn = last;; insn = PREV_INSN (insn))
7996             {
7997               if (GET_RTX_CLASS (GET_CODE (insn)) == 'i'
7998                   && reg_mentioned_p (XEXP (note, 0), PATTERN (insn)))
7999                 {
8000                   /* If this note refers to a multiple word hard register, it
8001                      may have been split into several smaller hard register
8002                      references, so handle it specially.  */
8003                   temp = XEXP (note, 0);
8004                   if (REG_NOTE_KIND (note) == REG_DEAD
8005                       && GET_CODE (temp) == REG
8006                       && REGNO (temp) < FIRST_PSEUDO_REGISTER
8007                       && HARD_REGNO_NREGS (REGNO (temp), GET_MODE (temp)) > 1)
8008                     split_hard_reg_notes (note, first, last);
8009                   else
8010                     {
8011                       XEXP (note, 1) = REG_NOTES (insn);
8012                       REG_NOTES (insn) = note;
8013                     }
8014
8015                   /* Sometimes need to convert REG_UNUSED notes to REG_DEAD
8016                      notes.  */
8017                   /* ??? This won't handle multiple word registers correctly,
8018                      but should be good enough for now.  */
8019                   if (REG_NOTE_KIND (note) == REG_UNUSED
8020                       && GET_CODE (XEXP (note, 0)) != SCRATCH
8021                       && !dead_or_set_p (insn, XEXP (note, 0)))
8022                     PUT_REG_NOTE_KIND (note, REG_DEAD);
8023
8024                   /* The reg only dies in one insn, the last one that uses
8025                      it.  */
8026                   break;
8027                 }
8028               /* It must die somewhere, fail it we couldn't find where it died.
8029
8030                  If this is a REG_UNUSED note, then it must be a temporary
8031                  register that was not needed by this instantiation of the
8032                  pattern, so we can safely ignore it.  */
8033               if (insn == first)
8034                 {                       
8035                   if (REG_NOTE_KIND (note) != REG_UNUSED)
8036                     abort ();
8037
8038                   break;
8039                 }
8040             }
8041           break;
8042
8043         case REG_WAS_0:
8044           /* If the insn that set the register to 0 was deleted, this
8045              note cannot be relied on any longer.  The destination might
8046              even have been moved to memory.
8047              This was observed for SH4 with execute/920501-6.c compilation,
8048              -O2 -fomit-frame-pointer -finline-functions .  */
8049           if (GET_CODE (XEXP (note, 0)) == NOTE
8050               || INSN_DELETED_P (XEXP (note, 0)))
8051             break;
8052           /* This note applies to the dest of the original insn.  Find the
8053              first new insn that now has the same dest, and move the note
8054              there.  */
8055
8056           if (!orig_dest)
8057             abort ();
8058
8059           for (insn = first;; insn = NEXT_INSN (insn))
8060             {
8061               if (GET_RTX_CLASS (GET_CODE (insn)) == 'i'
8062                   && (temp = single_set (insn))
8063                   && rtx_equal_p (SET_DEST (temp), orig_dest))
8064                 {
8065                   XEXP (note, 1) = REG_NOTES (insn);
8066                   REG_NOTES (insn) = note;
8067                   /* The reg is only zero before one insn, the first that
8068                      uses it.  */
8069                   break;
8070                 }
8071               /* If this note refers to a multiple word hard
8072                  register, it may have been split into several smaller
8073                  hard register references.  We could split the notes,
8074                  but simply dropping them is good enough.  */
8075               if (GET_CODE (orig_dest) == REG
8076                   && REGNO (orig_dest) < FIRST_PSEUDO_REGISTER
8077                   && HARD_REGNO_NREGS (REGNO (orig_dest),
8078                                        GET_MODE (orig_dest)) > 1)
8079                     break;
8080               /* It must be set somewhere, fail if we couldn't find where it
8081                  was set.  */
8082               if (insn == last)
8083                 abort ();
8084             }
8085           break;
8086
8087         case REG_EQUAL:
8088         case REG_EQUIV:
8089           /* A REG_EQUIV or REG_EQUAL note on an insn with more than one
8090              set is meaningless.  Just drop the note.  */
8091           if (!orig_dest)
8092             break;
8093
8094         case REG_NO_CONFLICT:
8095           /* These notes apply to the dest of the original insn.  Find the last
8096              new insn that now has the same dest, and move the note there.  */
8097
8098           if (!orig_dest)
8099             abort ();
8100
8101           for (insn = last;; insn = PREV_INSN (insn))
8102             {
8103               if (GET_RTX_CLASS (GET_CODE (insn)) == 'i'
8104                   && (temp = single_set (insn))
8105                   && rtx_equal_p (SET_DEST (temp), orig_dest))
8106                 {
8107                   XEXP (note, 1) = REG_NOTES (insn);
8108                   REG_NOTES (insn) = note;
8109                   /* Only put this note on one of the new insns.  */
8110                   break;
8111                 }
8112
8113               /* The original dest must still be set someplace.  Abort if we
8114                  couldn't find it.  */
8115               if (insn == first)
8116                 {
8117                   /* However, if this note refers to a multiple word hard
8118                      register, it may have been split into several smaller
8119                      hard register references.  We could split the notes,
8120                      but simply dropping them is good enough.  */
8121                   if (GET_CODE (orig_dest) == REG
8122                       && REGNO (orig_dest) < FIRST_PSEUDO_REGISTER
8123                       && HARD_REGNO_NREGS (REGNO (orig_dest),
8124                                            GET_MODE (orig_dest)) > 1)
8125                     break;
8126                   /* Likewise for multi-word memory references.  */
8127                   if (GET_CODE (orig_dest) == MEM
8128                       && SIZE_FOR_MODE (orig_dest) > UNITS_PER_WORD)
8129                     break;
8130                   abort ();
8131                 }
8132             }
8133           break;
8134
8135         case REG_LIBCALL:
8136           /* Move a REG_LIBCALL note to the first insn created, and update
8137              the corresponding REG_RETVAL note.  */
8138           XEXP (note, 1) = REG_NOTES (first);
8139           REG_NOTES (first) = note;
8140
8141           insn = XEXP (note, 0);
8142           note = find_reg_note (insn, REG_RETVAL, NULL_RTX);
8143           if (note)
8144             XEXP (note, 0) = first;
8145           break;
8146
8147         case REG_EXEC_COUNT:
8148           /* Move a REG_EXEC_COUNT note to the first insn created.  */
8149           XEXP (note, 1) = REG_NOTES (first);
8150           REG_NOTES (first) = note;
8151           break;
8152
8153         case REG_RETVAL:
8154           /* Move a REG_RETVAL note to the last insn created, and update
8155              the corresponding REG_LIBCALL note.  */
8156           XEXP (note, 1) = REG_NOTES (last);
8157           REG_NOTES (last) = note;
8158
8159           insn = XEXP (note, 0);
8160           note = find_reg_note (insn, REG_LIBCALL, NULL_RTX);
8161           if (note)
8162             XEXP (note, 0) = last;
8163           break;
8164
8165         case REG_NONNEG:
8166         case REG_BR_PROB:
8167           /* This should be moved to whichever instruction is a JUMP_INSN.  */
8168
8169           for (insn = last;; insn = PREV_INSN (insn))
8170             {
8171               if (GET_CODE (insn) == JUMP_INSN)
8172                 {
8173                   XEXP (note, 1) = REG_NOTES (insn);
8174                   REG_NOTES (insn) = note;
8175                   /* Only put this note on one of the new insns.  */
8176                   break;
8177                 }
8178               /* Fail if we couldn't find a JUMP_INSN.  */
8179               if (insn == first)
8180                 abort ();
8181             }
8182           break;
8183
8184         case REG_INC:
8185           /* reload sometimes leaves obsolete REG_INC notes around.  */
8186           if (reload_completed)
8187             break;
8188           /* This should be moved to whichever instruction now has the
8189              increment operation.  */
8190           abort ();
8191
8192         case REG_LABEL:
8193           /* Should be moved to the new insn(s) which use the label.  */
8194           for (insn = first; insn != NEXT_INSN (last); insn = NEXT_INSN (insn))
8195             if (GET_RTX_CLASS (GET_CODE (insn)) == 'i'
8196                 && reg_mentioned_p (XEXP (note, 0), PATTERN (insn)))
8197               {
8198                 REG_NOTES (insn) = alloc_EXPR_LIST (REG_LABEL,
8199                                                     XEXP (note, 0),
8200                                                     REG_NOTES (insn));
8201               }
8202           break;
8203
8204         case REG_CC_SETTER:
8205         case REG_CC_USER:
8206           /* These two notes will never appear until after reorg, so we don't
8207              have to handle them here.  */
8208         default:
8209           abort ();
8210         }
8211     }
8212
8213   /* Each new insn created, except the last, has a new set.  If the destination
8214      is a register, then this reg is now live across several insns, whereas
8215      previously the dest reg was born and died within the same insn.  To
8216      reflect this, we now need a REG_DEAD note on the insn where this
8217      dest reg dies.
8218
8219      Similarly, the new insns may have clobbers that need REG_UNUSED notes.  */
8220
8221   for (insn = first; insn != last; insn = NEXT_INSN (insn))
8222     {
8223       rtx pat;
8224       int i;
8225
8226       pat = PATTERN (insn);
8227       if (GET_CODE (pat) == SET || GET_CODE (pat) == CLOBBER)
8228         new_insn_dead_notes (pat, insn, last, orig_insn);
8229       else if (GET_CODE (pat) == PARALLEL)
8230         {
8231           for (i = 0; i < XVECLEN (pat, 0); i++)
8232             if (GET_CODE (XVECEXP (pat, 0, i)) == SET
8233                 || GET_CODE (XVECEXP (pat, 0, i)) == CLOBBER)
8234               new_insn_dead_notes (XVECEXP (pat, 0, i), insn, last, orig_insn);
8235         }
8236     }
8237
8238   /* If any insn, except the last, uses the register set by the last insn,
8239      then we need a new REG_DEAD note on that insn.  In this case, there
8240      would not have been a REG_DEAD note for this register in the original
8241      insn because it was used and set within one insn.  */
8242
8243   set = single_set (last);
8244   if (set)
8245     {
8246       rtx dest = SET_DEST (set);
8247
8248       while (GET_CODE (dest) == ZERO_EXTRACT || GET_CODE (dest) == SUBREG
8249              || GET_CODE (dest) == STRICT_LOW_PART
8250              || GET_CODE (dest) == SIGN_EXTRACT)
8251         dest = XEXP (dest, 0);
8252
8253       if (GET_CODE (dest) == REG
8254           /* Global registers are always live, so the code below does not
8255              apply to them.  */
8256           && (REGNO (dest) >= FIRST_PSEUDO_REGISTER
8257               || ! global_regs[REGNO (dest)]))
8258         {
8259           rtx stop_insn = PREV_INSN (first);
8260
8261           /* If the last insn uses the register that it is setting, then
8262              we don't want to put a REG_DEAD note there.  Search backwards
8263              to find the first insn that sets but does not use DEST.  */
8264
8265           insn = last;
8266           if (reg_overlap_mentioned_p (dest, SET_SRC (set)))
8267             {
8268               for (insn = PREV_INSN (insn); insn != first;
8269                    insn = PREV_INSN (insn))
8270                 {
8271                   if ((set = single_set (insn))
8272                       && reg_mentioned_p (dest, SET_DEST (set))
8273                       && ! reg_overlap_mentioned_p (dest, SET_SRC (set)))
8274                     break;
8275                 }
8276             }
8277
8278           /* Now find the first insn that uses but does not set DEST.  */
8279
8280           for (insn = PREV_INSN (insn); insn != stop_insn;
8281                insn = PREV_INSN (insn))
8282             {
8283               if (GET_RTX_CLASS (GET_CODE (insn)) == 'i'
8284                   && reg_mentioned_p (dest, PATTERN (insn))
8285                   && (set = single_set (insn)))
8286                 {
8287                   rtx insn_dest = SET_DEST (set);
8288
8289                   while (GET_CODE (insn_dest) == ZERO_EXTRACT
8290                          || GET_CODE (insn_dest) == SUBREG
8291                          || GET_CODE (insn_dest) == STRICT_LOW_PART
8292                          || GET_CODE (insn_dest) == SIGN_EXTRACT)
8293                     insn_dest = XEXP (insn_dest, 0);
8294
8295                   if (insn_dest != dest)
8296                     {
8297                       note = alloc_EXPR_LIST (REG_DEAD, dest, REG_NOTES (insn));
8298                       REG_NOTES (insn) = note;
8299                       /* The reg only dies in one insn, the last one
8300                          that uses it.  */
8301                       break;
8302                     }
8303                 }
8304             }
8305         }
8306     }
8307
8308   /* If the original dest is modifying a multiple register target, and the
8309      original instruction was split such that the original dest is now set
8310      by two or more SUBREG sets, then the split insns no longer kill the
8311      destination of the original insn.
8312
8313      In this case, if there exists an instruction in the same basic block,
8314      before the split insn, which uses the original dest, and this use is
8315      killed by the original insn, then we must remove the REG_DEAD note on
8316      this insn, because it is now superfluous.
8317
8318      This does not apply when a hard register gets split, because the code
8319      knows how to handle overlapping hard registers properly.  */
8320   if (orig_dest && GET_CODE (orig_dest) == REG)
8321     {
8322       int found_orig_dest = 0;
8323       int found_split_dest = 0;
8324
8325       for (insn = first;; insn = NEXT_INSN (insn))
8326         {
8327           rtx pat;
8328           int i;
8329
8330           /* I'm not sure if this can happen, but let's be safe.  */
8331           if (GET_RTX_CLASS (GET_CODE (insn)) != 'i')
8332             continue;
8333
8334           pat = PATTERN (insn);
8335           i = GET_CODE (pat) == PARALLEL ? XVECLEN (pat, 0) : 0;
8336           set = pat;
8337
8338           for (;;)
8339             {
8340               if (GET_CODE (set) == SET)
8341                 {
8342                   if (GET_CODE (SET_DEST (set)) == REG
8343                       && REGNO (SET_DEST (set)) == REGNO (orig_dest))
8344                     {
8345                       found_orig_dest = 1;
8346                       break;
8347                     }
8348                   else if (GET_CODE (SET_DEST (set)) == SUBREG
8349                            && SUBREG_REG (SET_DEST (set)) == orig_dest)
8350                     {
8351                       found_split_dest = 1;
8352                       break;
8353                     }
8354                 }
8355               if (--i < 0)
8356                 break;
8357               set = XVECEXP (pat, 0, i);
8358             }
8359
8360           if (insn == last)
8361             break;
8362         }
8363
8364       if (found_split_dest)
8365         {
8366           /* Search backwards from FIRST, looking for the first insn that uses
8367              the original dest.  Stop if we pass a CODE_LABEL or a JUMP_INSN.
8368              If we find an insn, and it has a REG_DEAD note, then delete the
8369              note.  */
8370
8371           for (insn = first; insn; insn = PREV_INSN (insn))
8372             {
8373               if (GET_CODE (insn) == CODE_LABEL
8374                   || GET_CODE (insn) == JUMP_INSN)
8375                 break;
8376               else if (GET_RTX_CLASS (GET_CODE (insn)) == 'i'
8377                        && reg_mentioned_p (orig_dest, insn))
8378                 {
8379                   note = find_regno_note (insn, REG_DEAD, REGNO (orig_dest));
8380                   if (note)
8381                     remove_note (insn, note);
8382                 }
8383             }
8384         }
8385       else if (!found_orig_dest)
8386         {
8387           int i, regno;
8388
8389           /* Should never reach here for a pseudo reg.  */
8390           if (REGNO (orig_dest) >= FIRST_PSEUDO_REGISTER)
8391             abort ();
8392
8393           /* This can happen for a hard register, if the splitter
8394              does not bother to emit instructions which would be no-ops.
8395              We try to verify that this is the case by checking to see if
8396              the original instruction uses all of the registers that it
8397              set.  This case is OK, because deleting a no-op can not affect
8398              REG_DEAD notes on other insns.  If this is not the case, then
8399              abort.  */
8400           
8401           regno = REGNO (orig_dest);
8402           for (i = HARD_REGNO_NREGS (regno, GET_MODE (orig_dest)) - 1;
8403                i >= 0; i--)
8404             if (! refers_to_regno_p (regno + i, regno + i + 1, orig_insn,
8405                                      NULL_PTR))
8406               break;
8407           if (i >= 0)
8408             abort ();
8409         }
8410     }
8411
8412   /* Update reg_n_sets.  This is necessary to prevent local alloc from
8413      converting REG_EQUAL notes to REG_EQUIV when splitting has modified
8414      a reg from set once to set multiple times.  */
8415
8416   {
8417     rtx x = PATTERN (orig_insn);
8418     RTX_CODE code = GET_CODE (x);
8419
8420     if (code == SET || code == CLOBBER)
8421       update_n_sets (x, -1);
8422     else if (code == PARALLEL)
8423       {
8424         int i;
8425         for (i = XVECLEN (x, 0) - 1; i >= 0; i--)
8426           {
8427             code = GET_CODE (XVECEXP (x, 0, i));
8428             if (code == SET || code == CLOBBER)
8429               update_n_sets (XVECEXP (x, 0, i), -1);
8430           }
8431       }
8432
8433     for (insn = first;; insn = NEXT_INSN (insn))
8434       {
8435         x = PATTERN (insn);
8436         code = GET_CODE (x);
8437
8438         if (code == SET || code == CLOBBER)
8439           update_n_sets (x, 1);
8440         else if (code == PARALLEL)
8441           {
8442             int i;
8443             for (i = XVECLEN (x, 0) - 1; i >= 0; i--)
8444               {
8445                 code = GET_CODE (XVECEXP (x, 0, i));
8446                 if (code == SET || code == CLOBBER)
8447                   update_n_sets (XVECEXP (x, 0, i), 1);
8448               }
8449           }
8450
8451         if (insn == last)
8452           break;
8453       }
8454   }
8455 }
8456
8457 /* The one entry point in this file.  DUMP_FILE is the dump file for
8458    this pass.  */
8459
8460 void
8461 schedule_insns (dump_file)
8462      FILE *dump_file;
8463 {
8464
8465   int max_uid;
8466   int b;
8467   rtx insn;
8468   int rgn;
8469
8470   int luid;
8471
8472   /* disable speculative loads in their presence if cc0 defined */
8473 #ifdef HAVE_cc0
8474   flag_schedule_speculative_load = 0;
8475 #endif
8476
8477   /* Taking care of this degenerate case makes the rest of
8478      this code simpler.  */
8479   if (n_basic_blocks == 0)
8480     return;
8481
8482   /* set dump and sched_verbose for the desired debugging output.  If no
8483      dump-file was specified, but -fsched-verbose-N (any N), print to stderr.
8484      For -fsched-verbose-N, N>=10, print everything to stderr.  */
8485   sched_verbose = sched_verbose_param;
8486   if (sched_verbose_param == 0 && dump_file)
8487     sched_verbose = 1;
8488   dump = ((sched_verbose_param >= 10 || !dump_file) ? stderr : dump_file);
8489
8490   nr_inter = 0;
8491   nr_spec = 0;
8492
8493   /* Initialize the unused_*_lists.  We can't use the ones left over from
8494      the previous function, because gcc has freed that memory.  We can use
8495      the ones left over from the first sched pass in the second pass however,
8496      so only clear them on the first sched pass.  The first pass is before
8497      reload if flag_schedule_insns is set, otherwise it is afterwards.  */
8498
8499   if (reload_completed == 0 || !flag_schedule_insns)
8500     {
8501       unused_insn_list = 0;
8502       unused_expr_list = 0;
8503     }
8504
8505   /* initialize issue_rate */
8506   issue_rate = ISSUE_RATE;
8507
8508   /* do the splitting first for all blocks */
8509   for (b = 0; b < n_basic_blocks; b++)
8510     split_block_insns (b, 1);
8511
8512   max_uid = (get_max_uid () + 1);
8513
8514   cant_move = (char *) xmalloc (max_uid * sizeof (char));
8515   bzero ((char *) cant_move, max_uid * sizeof (char));
8516
8517   fed_by_spec_load = (char *) xmalloc (max_uid * sizeof (char));
8518   bzero ((char *) fed_by_spec_load, max_uid * sizeof (char));
8519
8520   is_load_insn = (char *) xmalloc (max_uid * sizeof (char));
8521   bzero ((char *) is_load_insn, max_uid * sizeof (char));
8522
8523   insn_orig_block = (int *) xmalloc (max_uid * sizeof (int));
8524   insn_luid = (int *) xmalloc (max_uid * sizeof (int));
8525
8526   luid = 0;
8527   for (b = 0; b < n_basic_blocks; b++)
8528     for (insn = BLOCK_HEAD (b);; insn = NEXT_INSN (insn))
8529       {
8530         INSN_BLOCK (insn) = b;
8531         INSN_LUID (insn) = luid++;
8532
8533         if (insn == BLOCK_END (b))
8534           break;
8535       }
8536
8537   /* after reload, remove inter-blocks dependences computed before reload.  */
8538   if (reload_completed)
8539     {
8540       int b;
8541       rtx insn;
8542
8543       for (b = 0; b < n_basic_blocks; b++)
8544         for (insn = BLOCK_HEAD (b);; insn = NEXT_INSN (insn))
8545           {
8546             rtx link, prev;
8547
8548             if (GET_RTX_CLASS (GET_CODE (insn)) == 'i')
8549               {
8550                 prev = NULL_RTX;
8551                 link = LOG_LINKS (insn);
8552                 while (link)
8553                   {
8554                     rtx x = XEXP (link, 0);
8555
8556                     if (INSN_BLOCK (x) != b)
8557                       {
8558                         remove_dependence (insn, x);
8559                         link = prev ? XEXP (prev, 1) : LOG_LINKS (insn);
8560                       }
8561                     else
8562                       prev = link, link = XEXP (prev, 1);
8563                   }
8564               }
8565
8566             if (insn == BLOCK_END (b))
8567               break;
8568           }
8569     }
8570
8571   nr_regions = 0;
8572   rgn_table = (region *) alloca ((n_basic_blocks) * sizeof (region));
8573   rgn_bb_table = (int *) alloca ((n_basic_blocks) * sizeof (int));
8574   block_to_bb = (int *) alloca ((n_basic_blocks) * sizeof (int));
8575   containing_rgn = (int *) alloca ((n_basic_blocks) * sizeof (int));
8576
8577   /* compute regions for scheduling */
8578   if (reload_completed
8579       || n_basic_blocks == 1
8580       || !flag_schedule_interblock)
8581     {
8582       find_single_block_region ();
8583     }
8584   else
8585     {
8586       /* verify that a 'good' control flow graph can be built */
8587       if (is_cfg_nonregular ())
8588         {
8589           find_single_block_region ();
8590         }
8591       else
8592         {
8593           int_list_ptr *s_preds, *s_succs;
8594           int *num_preds, *num_succs;
8595           sbitmap *dom, *pdom;
8596
8597           s_preds = (int_list_ptr *) alloca (n_basic_blocks
8598                                              * sizeof (int_list_ptr));
8599           s_succs = (int_list_ptr *) alloca (n_basic_blocks
8600                                              * sizeof (int_list_ptr));
8601           num_preds = (int *) alloca (n_basic_blocks * sizeof (int));
8602           num_succs = (int *) alloca (n_basic_blocks * sizeof (int));
8603           dom = sbitmap_vector_alloc (n_basic_blocks, n_basic_blocks);
8604           pdom = sbitmap_vector_alloc (n_basic_blocks, n_basic_blocks);
8605
8606           /* The scheduler runs after flow; therefore, we can't blindly call
8607              back into find_basic_blocks since doing so could invalidate the
8608              info in global_live_at_start.
8609
8610              Consider a block consisting entirely of dead stores; after life
8611              analysis it would be a block of NOTE_INSN_DELETED notes.  If
8612              we call find_basic_blocks again, then the block would be removed
8613              entirely and invalidate our the register live information.
8614
8615              We could (should?) recompute register live information.  Doing
8616              so may even be beneficial.  */
8617
8618           compute_preds_succs (s_preds, s_succs, num_preds, num_succs);
8619
8620           /* Compute the dominators and post dominators.  We don't currently use
8621              post dominators, but we should for speculative motion analysis.  */
8622           compute_dominators (dom, pdom, s_preds, s_succs);
8623
8624           /* build_control_flow will return nonzero if it detects unreachable
8625              blocks or any other irregularity with the cfg which prevents
8626              cross block scheduling.  */
8627           if (build_control_flow (s_preds, s_succs, num_preds, num_succs) != 0)
8628             find_single_block_region ();
8629           else
8630             find_rgns (s_preds, s_succs, num_preds, num_succs, dom);
8631
8632           if (sched_verbose >= 3)
8633             debug_regions ();
8634
8635           /* For now.  This will move as more and more of haifa is converted
8636              to using the cfg code in flow.c  */
8637           free_bb_mem ();
8638           free (dom);
8639           free (pdom);
8640         }
8641     }
8642
8643   /* Allocate data for this pass.  See comments, above,
8644      for what these vectors do.
8645
8646      We use xmalloc instead of alloca, because max_uid can be very large
8647      when there is a lot of function inlining.  If we used alloca, we could
8648      exceed stack limits on some hosts for some inputs.  */
8649   insn_priority = (int *) xmalloc (max_uid * sizeof (int));
8650   insn_reg_weight = (int *) xmalloc (max_uid * sizeof (int));
8651   insn_tick = (int *) xmalloc (max_uid * sizeof (int));
8652   insn_costs = (short *) xmalloc (max_uid * sizeof (short));
8653   insn_units = (short *) xmalloc (max_uid * sizeof (short));
8654   insn_blockage = (unsigned int *) xmalloc (max_uid * sizeof (unsigned int));
8655   insn_ref_count = (int *) xmalloc (max_uid * sizeof (int));
8656
8657   /* Allocate for forward dependencies */
8658   insn_dep_count = (int *) xmalloc (max_uid * sizeof (int));
8659   insn_depend = (rtx *) xmalloc (max_uid * sizeof (rtx));
8660
8661   if (reload_completed == 0)
8662     {
8663       int i;
8664
8665       sched_reg_n_calls_crossed = (int *) alloca (max_regno * sizeof (int));
8666       sched_reg_live_length = (int *) alloca (max_regno * sizeof (int));
8667       sched_reg_basic_block = (int *) alloca (max_regno * sizeof (int));
8668       bb_live_regs = ALLOCA_REG_SET ();
8669       bzero ((char *) sched_reg_n_calls_crossed, max_regno * sizeof (int));
8670       bzero ((char *) sched_reg_live_length, max_regno * sizeof (int));
8671
8672       for (i = 0; i < max_regno; i++)
8673         sched_reg_basic_block[i] = REG_BLOCK_UNKNOWN;
8674     }
8675   else
8676     {
8677       sched_reg_n_calls_crossed = 0;
8678       sched_reg_live_length = 0;
8679       bb_live_regs = 0;
8680     }
8681   init_alias_analysis ();
8682
8683   if (write_symbols != NO_DEBUG)
8684     {
8685       rtx line;
8686
8687       line_note = (rtx *) xmalloc (max_uid * sizeof (rtx));
8688       bzero ((char *) line_note, max_uid * sizeof (rtx));
8689       line_note_head = (rtx *) alloca (n_basic_blocks * sizeof (rtx));
8690       bzero ((char *) line_note_head, n_basic_blocks * sizeof (rtx));
8691
8692       /* Save-line-note-head:
8693          Determine the line-number at the start of each basic block.
8694          This must be computed and saved now, because after a basic block's
8695          predecessor has been scheduled, it is impossible to accurately
8696          determine the correct line number for the first insn of the block.  */
8697
8698       for (b = 0; b < n_basic_blocks; b++)
8699         for (line = BLOCK_HEAD (b); line; line = PREV_INSN (line))
8700           if (GET_CODE (line) == NOTE && NOTE_LINE_NUMBER (line) > 0)
8701             {
8702               line_note_head[b] = line;
8703               break;
8704             }
8705     }
8706
8707   bzero ((char *) insn_priority, max_uid * sizeof (int));
8708   bzero ((char *) insn_reg_weight, max_uid * sizeof (int));
8709   bzero ((char *) insn_tick, max_uid * sizeof (int));
8710   bzero ((char *) insn_costs, max_uid * sizeof (short));
8711   bzero ((char *) insn_units, max_uid * sizeof (short));
8712   bzero ((char *) insn_blockage, max_uid * sizeof (unsigned int));
8713   bzero ((char *) insn_ref_count, max_uid * sizeof (int));
8714
8715   /* Initialize for forward dependencies */
8716   bzero ((char *) insn_depend, max_uid * sizeof (rtx));
8717   bzero ((char *) insn_dep_count, max_uid * sizeof (int));
8718
8719   /* Find units used in this fuction, for visualization */
8720   if (sched_verbose)
8721     init_target_units ();
8722
8723   /* ??? Add a NOTE after the last insn of the last basic block.  It is not
8724      known why this is done.  */
8725
8726   insn = BLOCK_END (n_basic_blocks - 1);
8727   if (NEXT_INSN (insn) == 0
8728       || (GET_CODE (insn) != NOTE
8729           && GET_CODE (insn) != CODE_LABEL
8730           /* Don't emit a NOTE if it would end up between an unconditional
8731              jump and a BARRIER.  */
8732           && !(GET_CODE (insn) == JUMP_INSN
8733                && GET_CODE (NEXT_INSN (insn)) == BARRIER)))
8734     emit_note_after (NOTE_INSN_DELETED, BLOCK_END (n_basic_blocks - 1));
8735
8736   /* Schedule every region in the subroutine */
8737   for (rgn = 0; rgn < nr_regions; rgn++)
8738     {
8739       schedule_region (rgn);
8740
8741 #ifdef USE_C_ALLOCA
8742       alloca (0);
8743 #endif
8744     }
8745
8746   /* Reposition the prologue and epilogue notes in case we moved the
8747      prologue/epilogue insns.  */
8748   if (reload_completed)
8749     reposition_prologue_and_epilogue_notes (get_insns ());
8750
8751   /* delete redundant line notes.  */
8752   if (write_symbols != NO_DEBUG)
8753     rm_redundant_line_notes ();
8754
8755   /* Update information about uses of registers in the subroutine.  */
8756   if (reload_completed == 0)
8757     update_reg_usage ();
8758
8759   if (sched_verbose)
8760     {
8761       if (reload_completed == 0 && flag_schedule_interblock)
8762         {
8763           fprintf (dump, "\n;; Procedure interblock/speculative motions == %d/%d \n",
8764                    nr_inter, nr_spec);
8765         }
8766       else
8767         {
8768           if (nr_inter > 0)
8769             abort ();
8770         }
8771       fprintf (dump, "\n\n");
8772     }
8773
8774   free (cant_move);
8775   free (fed_by_spec_load);
8776   free (is_load_insn);
8777   free (insn_orig_block);
8778   free (insn_luid);
8779
8780   free (insn_priority);
8781   free (insn_reg_weight);
8782   free (insn_tick);
8783   free (insn_costs);
8784   free (insn_units);
8785   free (insn_blockage);
8786   free (insn_ref_count);
8787
8788   free (insn_dep_count);
8789   free (insn_depend);
8790
8791   if (write_symbols != NO_DEBUG)
8792     free (line_note);
8793
8794   if (bb_live_regs)
8795     FREE_REG_SET (bb_live_regs);
8796
8797   if (edge_table)
8798     {
8799       free (edge_table);
8800       edge_table = NULL;
8801     }
8802
8803   if (in_edges)
8804     {
8805       free (in_edges);
8806       in_edges = NULL;
8807     }
8808   if (out_edges)
8809     {
8810       free (out_edges);
8811       out_edges = NULL;
8812     }
8813 }
8814 #endif /* INSN_SCHEDULING */