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