OSDN Git Service

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