cfgrtl.h: New.
[platform/upstream/gcc.git] / gcc / sched-rgn.c
1 /* Instruction scheduling pass.
2    Copyright (C) 1992-2014 Free Software Foundation, Inc.
3    Contributed by Michael Tiemann (tiemann@cygnus.com) Enhanced by,
4    and currently maintained by, Jim Wilson (wilson@cygnus.com)
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22 /* This pass implements list scheduling within basic blocks.  It is
23    run twice: (1) after flow analysis, but before register allocation,
24    and (2) after register allocation.
25
26    The first run performs interblock scheduling, moving insns between
27    different blocks in the same "region", and the second runs only
28    basic block scheduling.
29
30    Interblock motions performed are useful motions and speculative
31    motions, including speculative loads.  Motions requiring code
32    duplication are not supported.  The identification of motion type
33    and the check for validity of speculative motions requires
34    construction and analysis of the function's control flow graph.
35
36    The main entry point for this pass is schedule_insns(), called for
37    each function.  The work of the scheduler is organized in three
38    levels: (1) function level: insns are subject to splitting,
39    control-flow-graph is constructed, regions are computed (after
40    reload, each region is of one block), (2) region level: control
41    flow graph attributes required for interblock scheduling are
42    computed (dominators, reachability, etc.), data dependences and
43    priorities are computed, and (3) block level: insns in the block
44    are actually scheduled.  */
45 \f
46 #include "config.h"
47 #include "system.h"
48 #include "coretypes.h"
49 #include "tm.h"
50 #include "diagnostic-core.h"
51 #include "rtl.h"
52 #include "tm_p.h"
53 #include "hard-reg-set.h"
54 #include "regs.h"
55 #include "hashtab.h"
56 #include "hash-set.h"
57 #include "vec.h"
58 #include "machmode.h"
59 #include "input.h"
60 #include "function.h"
61 #include "profile.h"
62 #include "flags.h"
63 #include "insn-config.h"
64 #include "insn-attr.h"
65 #include "except.h"
66 #include "recog.h"
67 #include "params.h"
68 #include "sched-int.h"
69 #include "sel-sched.h"
70 #include "target.h"
71 #include "tree-pass.h"
72 #include "dbgcnt.h"
73
74 #ifdef INSN_SCHEDULING
75
76 /* Some accessor macros for h_i_d members only used within this file.  */
77 #define FED_BY_SPEC_LOAD(INSN) (HID (INSN)->fed_by_spec_load)
78 #define IS_LOAD_INSN(INSN) (HID (insn)->is_load_insn)
79
80 /* nr_inter/spec counts interblock/speculative motion for the function.  */
81 static int nr_inter, nr_spec;
82
83 static int is_cfg_nonregular (void);
84
85 /* Number of regions in the procedure.  */
86 int nr_regions = 0;
87
88 /* Same as above before adding any new regions.  */
89 static int nr_regions_initial = 0;
90
91 /* Table of region descriptions.  */
92 region *rgn_table = NULL;
93
94 /* Array of lists of regions' blocks.  */
95 int *rgn_bb_table = NULL;
96
97 /* Topological order of blocks in the region (if b2 is reachable from
98    b1, block_to_bb[b2] > block_to_bb[b1]).  Note: A basic block is
99    always referred to by either block or b, while its topological
100    order name (in the region) is referred to by bb.  */
101 int *block_to_bb = NULL;
102
103 /* The number of the region containing a block.  */
104 int *containing_rgn = NULL;
105
106 /* ebb_head [i] - is index in rgn_bb_table of the head basic block of i'th ebb.
107    Currently we can get a ebb only through splitting of currently
108    scheduling block, therefore, we don't need ebb_head array for every region,
109    hence, its sufficient to hold it for current one only.  */
110 int *ebb_head = NULL;
111
112 /* The minimum probability of reaching a source block so that it will be
113    considered for speculative scheduling.  */
114 static int min_spec_prob;
115
116 static void find_single_block_region (bool);
117 static void find_rgns (void);
118 static bool too_large (int, int *, int *);
119
120 /* Blocks of the current region being scheduled.  */
121 int current_nr_blocks;
122 int current_blocks;
123
124 /* A speculative motion requires checking live information on the path
125    from 'source' to 'target'.  The split blocks are those to be checked.
126    After a speculative motion, live information should be modified in
127    the 'update' blocks.
128
129    Lists of split and update blocks for each candidate of the current
130    target are in array bblst_table.  */
131 static basic_block *bblst_table;
132 static int bblst_size, bblst_last;
133
134 /* Arrays that hold the DFA state at the end of a basic block, to re-use
135    as the initial state at the start of successor blocks.  The BB_STATE
136    array holds the actual DFA state, and BB_STATE_ARRAY[I] is a pointer
137    into BB_STATE for basic block I.  FIXME: This should be a vec.  */
138 static char *bb_state_array = NULL;
139 static state_t *bb_state = NULL;
140
141 /* Target info declarations.
142
143    The block currently being scheduled is referred to as the "target" block,
144    while other blocks in the region from which insns can be moved to the
145    target are called "source" blocks.  The candidate structure holds info
146    about such sources: are they valid?  Speculative?  Etc.  */
147 typedef struct
148 {
149   basic_block *first_member;
150   int nr_members;
151 }
152 bblst;
153
154 typedef struct
155 {
156   char is_valid;
157   char is_speculative;
158   int src_prob;
159   bblst split_bbs;
160   bblst update_bbs;
161 }
162 candidate;
163
164 static candidate *candidate_table;
165 #define IS_VALID(src) (candidate_table[src].is_valid)
166 #define IS_SPECULATIVE(src) (candidate_table[src].is_speculative)
167 #define IS_SPECULATIVE_INSN(INSN)                       \
168   (IS_SPECULATIVE (BLOCK_TO_BB (BLOCK_NUM (INSN))))
169 #define SRC_PROB(src) ( candidate_table[src].src_prob )
170
171 /* The bb being currently scheduled.  */
172 int target_bb;
173
174 /* List of edges.  */
175 typedef struct
176 {
177   edge *first_member;
178   int nr_members;
179 }
180 edgelst;
181
182 static edge *edgelst_table;
183 static int edgelst_last;
184
185 static void extract_edgelst (sbitmap, edgelst *);
186
187 /* Target info functions.  */
188 static void split_edges (int, int, edgelst *);
189 static void compute_trg_info (int);
190 void debug_candidate (int);
191 void debug_candidates (int);
192
193 /* Dominators array: dom[i] contains the sbitmap of dominators of
194    bb i in the region.  */
195 static sbitmap *dom;
196
197 /* bb 0 is the only region entry.  */
198 #define IS_RGN_ENTRY(bb) (!bb)
199
200 /* Is bb_src dominated by bb_trg.  */
201 #define IS_DOMINATED(bb_src, bb_trg)                                 \
202 ( bitmap_bit_p (dom[bb_src], bb_trg) )
203
204 /* Probability: Prob[i] is an int in [0, REG_BR_PROB_BASE] which is
205    the probability of bb i relative to the region entry.  */
206 static int *prob;
207
208 /* Bit-set of edges, where bit i stands for edge i.  */
209 typedef sbitmap edgeset;
210
211 /* Number of edges in the region.  */
212 static int rgn_nr_edges;
213
214 /* Array of size rgn_nr_edges.  */
215 static edge *rgn_edges;
216
217 /* Mapping from each edge in the graph to its number in the rgn.  */
218 #define EDGE_TO_BIT(edge) ((int)(size_t)(edge)->aux)
219 #define SET_EDGE_TO_BIT(edge,nr) ((edge)->aux = (void *)(size_t)(nr))
220
221 /* The split edges of a source bb is different for each target
222    bb.  In order to compute this efficiently, the 'potential-split edges'
223    are computed for each bb prior to scheduling a region.  This is actually
224    the split edges of each bb relative to the region entry.
225
226    pot_split[bb] is the set of potential split edges of bb.  */
227 static edgeset *pot_split;
228
229 /* For every bb, a set of its ancestor edges.  */
230 static edgeset *ancestor_edges;
231
232 #define INSN_PROBABILITY(INSN) (SRC_PROB (BLOCK_TO_BB (BLOCK_NUM (INSN))))
233
234 /* Speculative scheduling functions.  */
235 static int check_live_1 (int, rtx);
236 static void update_live_1 (int, rtx);
237 static int is_pfree (rtx, int, int);
238 static int find_conditional_protection (rtx, int);
239 static int is_conditionally_protected (rtx, int, int);
240 static int is_prisky (rtx, int, int);
241 static int is_exception_free (rtx, int, int);
242
243 static bool sets_likely_spilled (rtx);
244 static void sets_likely_spilled_1 (rtx, const_rtx, void *);
245 static void add_branch_dependences (rtx_insn *, rtx_insn *);
246 static void compute_block_dependences (int);
247
248 static void schedule_region (int);
249 static void concat_insn_mem_list (rtx_insn_list *, rtx_expr_list *,
250                                   rtx_insn_list **, rtx_expr_list **);
251 static void propagate_deps (int, struct deps_desc *);
252 static void free_pending_lists (void);
253
254 /* Functions for construction of the control flow graph.  */
255
256 /* Return 1 if control flow graph should not be constructed, 0 otherwise.
257
258    We decide not to build the control flow graph if there is possibly more
259    than one entry to the function, if computed branches exist, if we
260    have nonlocal gotos, or if we have an unreachable loop.  */
261
262 static int
263 is_cfg_nonregular (void)
264 {
265   basic_block b;
266   rtx_insn *insn;
267
268   /* If we have a label that could be the target of a nonlocal goto, then
269      the cfg is not well structured.  */
270   if (nonlocal_goto_handler_labels)
271     return 1;
272
273   /* If we have any forced labels, then the cfg is not well structured.  */
274   if (forced_labels)
275     return 1;
276
277   /* If we have exception handlers, then we consider the cfg not well
278      structured.  ?!?  We should be able to handle this now that we
279      compute an accurate cfg for EH.  */
280   if (current_function_has_exception_handlers ())
281     return 1;
282
283   /* If we have insns which refer to labels as non-jumped-to operands,
284      then we consider the cfg not well structured.  */
285   FOR_EACH_BB_FN (b, cfun)
286     FOR_BB_INSNS (b, insn)
287       {
288         rtx note, set, dest;
289         rtx_insn *next;
290
291         /* If this function has a computed jump, then we consider the cfg
292            not well structured.  */
293         if (JUMP_P (insn) && computed_jump_p (insn))
294           return 1;
295
296         if (!INSN_P (insn))
297           continue;
298
299         note = find_reg_note (insn, REG_LABEL_OPERAND, NULL_RTX);
300         if (note == NULL_RTX)
301           continue;
302
303         /* For that label not to be seen as a referred-to label, this
304            must be a single-set which is feeding a jump *only*.  This
305            could be a conditional jump with the label split off for
306            machine-specific reasons or a casesi/tablejump.  */
307         next = next_nonnote_insn (insn);
308         if (next == NULL_RTX
309             || !JUMP_P (next)
310             || (JUMP_LABEL (next) != XEXP (note, 0)
311                 && find_reg_note (next, REG_LABEL_TARGET,
312                                   XEXP (note, 0)) == NULL_RTX)
313             || BLOCK_FOR_INSN (insn) != BLOCK_FOR_INSN (next))
314           return 1;
315
316         set = single_set (insn);
317         if (set == NULL_RTX)
318           return 1;
319
320         dest = SET_DEST (set);
321         if (!REG_P (dest) || !dead_or_set_p (next, dest))
322           return 1;
323       }
324
325   /* Unreachable loops with more than one basic block are detected
326      during the DFS traversal in find_rgns.
327
328      Unreachable loops with a single block are detected here.  This
329      test is redundant with the one in find_rgns, but it's much
330      cheaper to go ahead and catch the trivial case here.  */
331   FOR_EACH_BB_FN (b, cfun)
332     {
333       if (EDGE_COUNT (b->preds) == 0
334           || (single_pred_p (b)
335               && single_pred (b) == b))
336         return 1;
337     }
338
339   /* All the tests passed.  Consider the cfg well structured.  */
340   return 0;
341 }
342
343 /* Extract list of edges from a bitmap containing EDGE_TO_BIT bits.  */
344
345 static void
346 extract_edgelst (sbitmap set, edgelst *el)
347 {
348   unsigned int i = 0;
349   sbitmap_iterator sbi;
350
351   /* edgelst table space is reused in each call to extract_edgelst.  */
352   edgelst_last = 0;
353
354   el->first_member = &edgelst_table[edgelst_last];
355   el->nr_members = 0;
356
357   /* Iterate over each word in the bitset.  */
358   EXECUTE_IF_SET_IN_BITMAP (set, 0, i, sbi)
359     {
360       edgelst_table[edgelst_last++] = rgn_edges[i];
361       el->nr_members++;
362     }
363 }
364
365 /* Functions for the construction of regions.  */
366
367 /* Print the regions, for debugging purposes.  Callable from debugger.  */
368
369 DEBUG_FUNCTION void
370 debug_regions (void)
371 {
372   int rgn, bb;
373
374   fprintf (sched_dump, "\n;;   ------------ REGIONS ----------\n\n");
375   for (rgn = 0; rgn < nr_regions; rgn++)
376     {
377       fprintf (sched_dump, ";;\trgn %d nr_blocks %d:\n", rgn,
378                rgn_table[rgn].rgn_nr_blocks);
379       fprintf (sched_dump, ";;\tbb/block: ");
380
381       /* We don't have ebb_head initialized yet, so we can't use
382          BB_TO_BLOCK ().  */
383       current_blocks = RGN_BLOCKS (rgn);
384
385       for (bb = 0; bb < rgn_table[rgn].rgn_nr_blocks; bb++)
386         fprintf (sched_dump, " %d/%d ", bb, rgn_bb_table[current_blocks + bb]);
387
388       fprintf (sched_dump, "\n\n");
389     }
390 }
391
392 /* Print the region's basic blocks.  */
393
394 DEBUG_FUNCTION void
395 debug_region (int rgn)
396 {
397   int bb;
398
399   fprintf (stderr, "\n;;   ------------ REGION %d ----------\n\n", rgn);
400   fprintf (stderr, ";;\trgn %d nr_blocks %d:\n", rgn,
401            rgn_table[rgn].rgn_nr_blocks);
402   fprintf (stderr, ";;\tbb/block: ");
403
404   /* We don't have ebb_head initialized yet, so we can't use
405      BB_TO_BLOCK ().  */
406   current_blocks = RGN_BLOCKS (rgn);
407
408   for (bb = 0; bb < rgn_table[rgn].rgn_nr_blocks; bb++)
409     fprintf (stderr, " %d/%d ", bb, rgn_bb_table[current_blocks + bb]);
410
411   fprintf (stderr, "\n\n");
412
413   for (bb = 0; bb < rgn_table[rgn].rgn_nr_blocks; bb++)
414     {
415       dump_bb (stderr,
416                BASIC_BLOCK_FOR_FN (cfun, rgn_bb_table[current_blocks + bb]),
417                0, TDF_SLIM | TDF_BLOCKS);
418       fprintf (stderr, "\n");
419     }
420
421   fprintf (stderr, "\n");
422
423 }
424
425 /* True when a bb with index BB_INDEX contained in region RGN.  */
426 static bool
427 bb_in_region_p (int bb_index, int rgn)
428 {
429   int i;
430
431   for (i = 0; i < rgn_table[rgn].rgn_nr_blocks; i++)
432     if (rgn_bb_table[current_blocks + i] == bb_index)
433       return true;
434
435   return false;
436 }
437
438 /* Dump region RGN to file F using dot syntax.  */
439 void
440 dump_region_dot (FILE *f, int rgn)
441 {
442   int i;
443
444   fprintf (f, "digraph Region_%d {\n", rgn);
445
446   /* We don't have ebb_head initialized yet, so we can't use
447      BB_TO_BLOCK ().  */
448   current_blocks = RGN_BLOCKS (rgn);
449
450   for (i = 0; i < rgn_table[rgn].rgn_nr_blocks; i++)
451     {
452       edge e;
453       edge_iterator ei;
454       int src_bb_num = rgn_bb_table[current_blocks + i];
455       basic_block bb = BASIC_BLOCK_FOR_FN (cfun, src_bb_num);
456
457       FOR_EACH_EDGE (e, ei, bb->succs)
458         if (bb_in_region_p (e->dest->index, rgn))
459           fprintf (f, "\t%d -> %d\n", src_bb_num, e->dest->index);
460     }
461   fprintf (f, "}\n");
462 }
463
464 /* The same, but first open a file specified by FNAME.  */
465 void
466 dump_region_dot_file (const char *fname, int rgn)
467 {
468   FILE *f = fopen (fname, "wt");
469   dump_region_dot (f, rgn);
470   fclose (f);
471 }
472
473 /* Build a single block region for each basic block in the function.
474    This allows for using the same code for interblock and basic block
475    scheduling.  */
476
477 static void
478 find_single_block_region (bool ebbs_p)
479 {
480   basic_block bb, ebb_start;
481   int i = 0;
482
483   nr_regions = 0;
484
485   if (ebbs_p) {
486     int probability_cutoff;
487     if (profile_info && flag_branch_probabilities)
488       probability_cutoff = PARAM_VALUE (TRACER_MIN_BRANCH_PROBABILITY_FEEDBACK);
489     else
490       probability_cutoff = PARAM_VALUE (TRACER_MIN_BRANCH_PROBABILITY);
491     probability_cutoff = REG_BR_PROB_BASE / 100 * probability_cutoff;
492
493     FOR_EACH_BB_FN (ebb_start, cfun)
494       {
495         RGN_NR_BLOCKS (nr_regions) = 0;
496         RGN_BLOCKS (nr_regions) = i;
497         RGN_DONT_CALC_DEPS (nr_regions) = 0;
498         RGN_HAS_REAL_EBB (nr_regions) = 0;
499
500         for (bb = ebb_start; ; bb = bb->next_bb)
501           {
502             edge e;
503
504             rgn_bb_table[i] = bb->index;
505             RGN_NR_BLOCKS (nr_regions)++;
506             CONTAINING_RGN (bb->index) = nr_regions;
507             BLOCK_TO_BB (bb->index) = i - RGN_BLOCKS (nr_regions);
508             i++;
509
510             if (bb->next_bb == EXIT_BLOCK_PTR_FOR_FN (cfun)
511                 || LABEL_P (BB_HEAD (bb->next_bb)))
512               break;
513
514             e = find_fallthru_edge (bb->succs);
515             if (! e)
516               break;
517             if (e->probability <= probability_cutoff)
518               break;
519           }
520
521         ebb_start = bb;
522         nr_regions++;
523       }
524   }
525   else
526     FOR_EACH_BB_FN (bb, cfun)
527       {
528         rgn_bb_table[nr_regions] = bb->index;
529         RGN_NR_BLOCKS (nr_regions) = 1;
530         RGN_BLOCKS (nr_regions) = nr_regions;
531         RGN_DONT_CALC_DEPS (nr_regions) = 0;
532         RGN_HAS_REAL_EBB (nr_regions) = 0;
533
534         CONTAINING_RGN (bb->index) = nr_regions;
535         BLOCK_TO_BB (bb->index) = 0;
536         nr_regions++;
537       }
538 }
539
540 /* Estimate number of the insns in the BB.  */
541 static int
542 rgn_estimate_number_of_insns (basic_block bb)
543 {
544   int count;
545
546   count = INSN_LUID (BB_END (bb)) - INSN_LUID (BB_HEAD (bb));
547
548   if (MAY_HAVE_DEBUG_INSNS)
549     {
550       rtx_insn *insn;
551
552       FOR_BB_INSNS (bb, insn)
553         if (DEBUG_INSN_P (insn))
554           count--;
555     }
556
557   return count;
558 }
559
560 /* Update number of blocks and the estimate for number of insns
561    in the region.  Return true if the region is "too large" for interblock
562    scheduling (compile time considerations).  */
563
564 static bool
565 too_large (int block, int *num_bbs, int *num_insns)
566 {
567   (*num_bbs)++;
568   (*num_insns) += (common_sched_info->estimate_number_of_insns
569                    (BASIC_BLOCK_FOR_FN (cfun, block)));
570
571   return ((*num_bbs > PARAM_VALUE (PARAM_MAX_SCHED_REGION_BLOCKS))
572           || (*num_insns > PARAM_VALUE (PARAM_MAX_SCHED_REGION_INSNS)));
573 }
574
575 /* Update_loop_relations(blk, hdr): Check if the loop headed by max_hdr[blk]
576    is still an inner loop.  Put in max_hdr[blk] the header of the most inner
577    loop containing blk.  */
578 #define UPDATE_LOOP_RELATIONS(blk, hdr)         \
579 {                                               \
580   if (max_hdr[blk] == -1)                       \
581     max_hdr[blk] = hdr;                         \
582   else if (dfs_nr[max_hdr[blk]] > dfs_nr[hdr])  \
583     bitmap_clear_bit (inner, hdr);                      \
584   else if (dfs_nr[max_hdr[blk]] < dfs_nr[hdr])  \
585     {                                           \
586       bitmap_clear_bit (inner,max_hdr[blk]);            \
587       max_hdr[blk] = hdr;                       \
588     }                                           \
589 }
590
591 /* Find regions for interblock scheduling.
592
593    A region for scheduling can be:
594
595      * A loop-free procedure, or
596
597      * A reducible inner loop, or
598
599      * A basic block not contained in any other region.
600
601    ?!? In theory we could build other regions based on extended basic
602    blocks or reverse extended basic blocks.  Is it worth the trouble?
603
604    Loop blocks that form a region are put into the region's block list
605    in topological order.
606
607    This procedure stores its results into the following global (ick) variables
608
609      * rgn_nr
610      * rgn_table
611      * rgn_bb_table
612      * block_to_bb
613      * containing region
614
615    We use dominator relationships to avoid making regions out of non-reducible
616    loops.
617
618    This procedure needs to be converted to work on pred/succ lists instead
619    of edge tables.  That would simplify it somewhat.  */
620
621 static void
622 haifa_find_rgns (void)
623 {
624   int *max_hdr, *dfs_nr, *degree;
625   char no_loops = 1;
626   int node, child, loop_head, i, head, tail;
627   int count = 0, sp, idx = 0;
628   edge_iterator current_edge;
629   edge_iterator *stack;
630   int num_bbs, num_insns, unreachable;
631   int too_large_failure;
632   basic_block bb;
633
634   /* Note if a block is a natural loop header.  */
635   sbitmap header;
636
637   /* Note if a block is a natural inner loop header.  */
638   sbitmap inner;
639
640   /* Note if a block is in the block queue.  */
641   sbitmap in_queue;
642
643   /* Note if a block is in the block queue.  */
644   sbitmap in_stack;
645
646   /* Perform a DFS traversal of the cfg.  Identify loop headers, inner loops
647      and a mapping from block to its loop header (if the block is contained
648      in a loop, else -1).
649
650      Store results in HEADER, INNER, and MAX_HDR respectively, these will
651      be used as inputs to the second traversal.
652
653      STACK, SP and DFS_NR are only used during the first traversal.  */
654
655   /* Allocate and initialize variables for the first traversal.  */
656   max_hdr = XNEWVEC (int, last_basic_block_for_fn (cfun));
657   dfs_nr = XCNEWVEC (int, last_basic_block_for_fn (cfun));
658   stack = XNEWVEC (edge_iterator, n_edges_for_fn (cfun));
659
660   inner = sbitmap_alloc (last_basic_block_for_fn (cfun));
661   bitmap_ones (inner);
662
663   header = sbitmap_alloc (last_basic_block_for_fn (cfun));
664   bitmap_clear (header);
665
666   in_queue = sbitmap_alloc (last_basic_block_for_fn (cfun));
667   bitmap_clear (in_queue);
668
669   in_stack = sbitmap_alloc (last_basic_block_for_fn (cfun));
670   bitmap_clear (in_stack);
671
672   for (i = 0; i < last_basic_block_for_fn (cfun); i++)
673     max_hdr[i] = -1;
674
675   #define EDGE_PASSED(E) (ei_end_p ((E)) || ei_edge ((E))->aux)
676   #define SET_EDGE_PASSED(E) (ei_edge ((E))->aux = ei_edge ((E)))
677
678   /* DFS traversal to find inner loops in the cfg.  */
679
680   current_edge = ei_start (single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun))->succs);
681   sp = -1;
682
683   while (1)
684     {
685       if (EDGE_PASSED (current_edge))
686         {
687           /* We have reached a leaf node or a node that was already
688              processed.  Pop edges off the stack until we find
689              an edge that has not yet been processed.  */
690           while (sp >= 0 && EDGE_PASSED (current_edge))
691             {
692               /* Pop entry off the stack.  */
693               current_edge = stack[sp--];
694               node = ei_edge (current_edge)->src->index;
695               gcc_assert (node != ENTRY_BLOCK);
696               child = ei_edge (current_edge)->dest->index;
697               gcc_assert (child != EXIT_BLOCK);
698               bitmap_clear_bit (in_stack, child);
699               if (max_hdr[child] >= 0 && bitmap_bit_p (in_stack, max_hdr[child]))
700                 UPDATE_LOOP_RELATIONS (node, max_hdr[child]);
701               ei_next (&current_edge);
702             }
703
704           /* See if have finished the DFS tree traversal.  */
705           if (sp < 0 && EDGE_PASSED (current_edge))
706             break;
707
708           /* Nope, continue the traversal with the popped node.  */
709           continue;
710         }
711
712       /* Process a node.  */
713       node = ei_edge (current_edge)->src->index;
714       gcc_assert (node != ENTRY_BLOCK);
715       bitmap_set_bit (in_stack, node);
716       dfs_nr[node] = ++count;
717
718       /* We don't traverse to the exit block.  */
719       child = ei_edge (current_edge)->dest->index;
720       if (child == EXIT_BLOCK)
721         {
722           SET_EDGE_PASSED (current_edge);
723           ei_next (&current_edge);
724           continue;
725         }
726
727       /* If the successor is in the stack, then we've found a loop.
728          Mark the loop, if it is not a natural loop, then it will
729          be rejected during the second traversal.  */
730       if (bitmap_bit_p (in_stack, child))
731         {
732           no_loops = 0;
733           bitmap_set_bit (header, child);
734           UPDATE_LOOP_RELATIONS (node, child);
735           SET_EDGE_PASSED (current_edge);
736           ei_next (&current_edge);
737           continue;
738         }
739
740       /* If the child was already visited, then there is no need to visit
741          it again.  Just update the loop relationships and restart
742          with a new edge.  */
743       if (dfs_nr[child])
744         {
745           if (max_hdr[child] >= 0 && bitmap_bit_p (in_stack, max_hdr[child]))
746             UPDATE_LOOP_RELATIONS (node, max_hdr[child]);
747           SET_EDGE_PASSED (current_edge);
748           ei_next (&current_edge);
749           continue;
750         }
751
752       /* Push an entry on the stack and continue DFS traversal.  */
753       stack[++sp] = current_edge;
754       SET_EDGE_PASSED (current_edge);
755       current_edge = ei_start (ei_edge (current_edge)->dest->succs);
756     }
757
758   /* Reset ->aux field used by EDGE_PASSED.  */
759   FOR_ALL_BB_FN (bb, cfun)
760     {
761       edge_iterator ei;
762       edge e;
763       FOR_EACH_EDGE (e, ei, bb->succs)
764         e->aux = NULL;
765     }
766
767
768   /* Another check for unreachable blocks.  The earlier test in
769      is_cfg_nonregular only finds unreachable blocks that do not
770      form a loop.
771
772      The DFS traversal will mark every block that is reachable from
773      the entry node by placing a nonzero value in dfs_nr.  Thus if
774      dfs_nr is zero for any block, then it must be unreachable.  */
775   unreachable = 0;
776   FOR_EACH_BB_FN (bb, cfun)
777     if (dfs_nr[bb->index] == 0)
778       {
779         unreachable = 1;
780         break;
781       }
782
783   /* Gross.  To avoid wasting memory, the second pass uses the dfs_nr array
784      to hold degree counts.  */
785   degree = dfs_nr;
786
787   FOR_EACH_BB_FN (bb, cfun)
788     degree[bb->index] = EDGE_COUNT (bb->preds);
789
790   /* Do not perform region scheduling if there are any unreachable
791      blocks.  */
792   if (!unreachable)
793     {
794       int *queue, *degree1 = NULL;
795       /* We use EXTENDED_RGN_HEADER as an addition to HEADER and put
796          there basic blocks, which are forced to be region heads.
797          This is done to try to assemble few smaller regions
798          from a too_large region.  */
799       sbitmap extended_rgn_header = NULL;
800       bool extend_regions_p;
801
802       if (no_loops)
803         bitmap_set_bit (header, 0);
804
805       /* Second traversal:find reducible inner loops and topologically sort
806          block of each region.  */
807
808       queue = XNEWVEC (int, n_basic_blocks_for_fn (cfun));
809
810       extend_regions_p = PARAM_VALUE (PARAM_MAX_SCHED_EXTEND_REGIONS_ITERS) > 0;
811       if (extend_regions_p)
812         {
813           degree1 = XNEWVEC (int, last_basic_block_for_fn (cfun));
814           extended_rgn_header =
815             sbitmap_alloc (last_basic_block_for_fn (cfun));
816           bitmap_clear (extended_rgn_header);
817         }
818
819       /* Find blocks which are inner loop headers.  We still have non-reducible
820          loops to consider at this point.  */
821       FOR_EACH_BB_FN (bb, cfun)
822         {
823           if (bitmap_bit_p (header, bb->index) && bitmap_bit_p (inner, bb->index))
824             {
825               edge e;
826               edge_iterator ei;
827               basic_block jbb;
828
829               /* Now check that the loop is reducible.  We do this separate
830                  from finding inner loops so that we do not find a reducible
831                  loop which contains an inner non-reducible loop.
832
833                  A simple way to find reducible/natural loops is to verify
834                  that each block in the loop is dominated by the loop
835                  header.
836
837                  If there exists a block that is not dominated by the loop
838                  header, then the block is reachable from outside the loop
839                  and thus the loop is not a natural loop.  */
840               FOR_EACH_BB_FN (jbb, cfun)
841                 {
842                   /* First identify blocks in the loop, except for the loop
843                      entry block.  */
844                   if (bb->index == max_hdr[jbb->index] && bb != jbb)
845                     {
846                       /* Now verify that the block is dominated by the loop
847                          header.  */
848                       if (!dominated_by_p (CDI_DOMINATORS, jbb, bb))
849                         break;
850                     }
851                 }
852
853               /* If we exited the loop early, then I is the header of
854                  a non-reducible loop and we should quit processing it
855                  now.  */
856               if (jbb != EXIT_BLOCK_PTR_FOR_FN (cfun))
857                 continue;
858
859               /* I is a header of an inner loop, or block 0 in a subroutine
860                  with no loops at all.  */
861               head = tail = -1;
862               too_large_failure = 0;
863               loop_head = max_hdr[bb->index];
864
865               if (extend_regions_p)
866                 /* We save degree in case when we meet a too_large region
867                    and cancel it.  We need a correct degree later when
868                    calling extend_rgns.  */
869                 memcpy (degree1, degree,
870                         last_basic_block_for_fn (cfun) * sizeof (int));
871
872               /* Decrease degree of all I's successors for topological
873                  ordering.  */
874               FOR_EACH_EDGE (e, ei, bb->succs)
875                 if (e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun))
876                   --degree[e->dest->index];
877
878               /* Estimate # insns, and count # blocks in the region.  */
879               num_bbs = 1;
880               num_insns = common_sched_info->estimate_number_of_insns (bb);
881
882               /* Find all loop latches (blocks with back edges to the loop
883                  header) or all the leaf blocks in the cfg has no loops.
884
885                  Place those blocks into the queue.  */
886               if (no_loops)
887                 {
888                   FOR_EACH_BB_FN (jbb, cfun)
889                     /* Leaf nodes have only a single successor which must
890                        be EXIT_BLOCK.  */
891                     if (single_succ_p (jbb)
892                         && single_succ (jbb) == EXIT_BLOCK_PTR_FOR_FN (cfun))
893                       {
894                         queue[++tail] = jbb->index;
895                         bitmap_set_bit (in_queue, jbb->index);
896
897                         if (too_large (jbb->index, &num_bbs, &num_insns))
898                           {
899                             too_large_failure = 1;
900                             break;
901                           }
902                       }
903                 }
904               else
905                 {
906                   edge e;
907
908                   FOR_EACH_EDGE (e, ei, bb->preds)
909                     {
910                       if (e->src == ENTRY_BLOCK_PTR_FOR_FN (cfun))
911                         continue;
912
913                       node = e->src->index;
914
915                       if (max_hdr[node] == loop_head && node != bb->index)
916                         {
917                           /* This is a loop latch.  */
918                           queue[++tail] = node;
919                           bitmap_set_bit (in_queue, node);
920
921                           if (too_large (node, &num_bbs, &num_insns))
922                             {
923                               too_large_failure = 1;
924                               break;
925                             }
926                         }
927                     }
928                 }
929
930               /* Now add all the blocks in the loop to the queue.
931
932              We know the loop is a natural loop; however the algorithm
933              above will not always mark certain blocks as being in the
934              loop.  Consider:
935                 node   children
936                  a        b,c
937                  b        c
938                  c        a,d
939                  d        b
940
941              The algorithm in the DFS traversal may not mark B & D as part
942              of the loop (i.e. they will not have max_hdr set to A).
943
944              We know they can not be loop latches (else they would have
945              had max_hdr set since they'd have a backedge to a dominator
946              block).  So we don't need them on the initial queue.
947
948              We know they are part of the loop because they are dominated
949              by the loop header and can be reached by a backwards walk of
950              the edges starting with nodes on the initial queue.
951
952              It is safe and desirable to include those nodes in the
953              loop/scheduling region.  To do so we would need to decrease
954              the degree of a node if it is the target of a backedge
955              within the loop itself as the node is placed in the queue.
956
957              We do not do this because I'm not sure that the actual
958              scheduling code will properly handle this case. ?!? */
959
960               while (head < tail && !too_large_failure)
961                 {
962                   edge e;
963                   child = queue[++head];
964
965                   FOR_EACH_EDGE (e, ei,
966                                  BASIC_BLOCK_FOR_FN (cfun, child)->preds)
967                     {
968                       node = e->src->index;
969
970                       /* See discussion above about nodes not marked as in
971                          this loop during the initial DFS traversal.  */
972                       if (e->src == ENTRY_BLOCK_PTR_FOR_FN (cfun)
973                           || max_hdr[node] != loop_head)
974                         {
975                           tail = -1;
976                           break;
977                         }
978                       else if (!bitmap_bit_p (in_queue, node) && node != bb->index)
979                         {
980                           queue[++tail] = node;
981                           bitmap_set_bit (in_queue, node);
982
983                           if (too_large (node, &num_bbs, &num_insns))
984                             {
985                               too_large_failure = 1;
986                               break;
987                             }
988                         }
989                     }
990                 }
991
992               if (tail >= 0 && !too_large_failure)
993                 {
994                   /* Place the loop header into list of region blocks.  */
995                   degree[bb->index] = -1;
996                   rgn_bb_table[idx] = bb->index;
997                   RGN_NR_BLOCKS (nr_regions) = num_bbs;
998                   RGN_BLOCKS (nr_regions) = idx++;
999                   RGN_DONT_CALC_DEPS (nr_regions) = 0;
1000                   RGN_HAS_REAL_EBB (nr_regions) = 0;
1001                   CONTAINING_RGN (bb->index) = nr_regions;
1002                   BLOCK_TO_BB (bb->index) = count = 0;
1003
1004                   /* Remove blocks from queue[] when their in degree
1005                      becomes zero.  Repeat until no blocks are left on the
1006                      list.  This produces a topological list of blocks in
1007                      the region.  */
1008                   while (tail >= 0)
1009                     {
1010                       if (head < 0)
1011                         head = tail;
1012                       child = queue[head];
1013                       if (degree[child] == 0)
1014                         {
1015                           edge e;
1016
1017                           degree[child] = -1;
1018                           rgn_bb_table[idx++] = child;
1019                           BLOCK_TO_BB (child) = ++count;
1020                           CONTAINING_RGN (child) = nr_regions;
1021                           queue[head] = queue[tail--];
1022
1023                           FOR_EACH_EDGE (e, ei,
1024                                          BASIC_BLOCK_FOR_FN (cfun,
1025                                                              child)->succs)
1026                             if (e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun))
1027                               --degree[e->dest->index];
1028                         }
1029                       else
1030                         --head;
1031                     }
1032                   ++nr_regions;
1033                 }
1034               else if (extend_regions_p)
1035                 {
1036                   /* Restore DEGREE.  */
1037                   int *t = degree;
1038
1039                   degree = degree1;
1040                   degree1 = t;
1041
1042                   /* And force successors of BB to be region heads.
1043                      This may provide several smaller regions instead
1044                      of one too_large region.  */
1045                   FOR_EACH_EDGE (e, ei, bb->succs)
1046                     if (e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun))
1047                       bitmap_set_bit (extended_rgn_header, e->dest->index);
1048                 }
1049             }
1050         }
1051       free (queue);
1052
1053       if (extend_regions_p)
1054         {
1055           free (degree1);
1056
1057           bitmap_ior (header, header, extended_rgn_header);
1058           sbitmap_free (extended_rgn_header);
1059
1060           extend_rgns (degree, &idx, header, max_hdr);
1061         }
1062     }
1063
1064   /* Any block that did not end up in a region is placed into a region
1065      by itself.  */
1066   FOR_EACH_BB_FN (bb, cfun)
1067     if (degree[bb->index] >= 0)
1068       {
1069         rgn_bb_table[idx] = bb->index;
1070         RGN_NR_BLOCKS (nr_regions) = 1;
1071         RGN_BLOCKS (nr_regions) = idx++;
1072         RGN_DONT_CALC_DEPS (nr_regions) = 0;
1073         RGN_HAS_REAL_EBB (nr_regions) = 0;
1074         CONTAINING_RGN (bb->index) = nr_regions++;
1075         BLOCK_TO_BB (bb->index) = 0;
1076       }
1077
1078   free (max_hdr);
1079   free (degree);
1080   free (stack);
1081   sbitmap_free (header);
1082   sbitmap_free (inner);
1083   sbitmap_free (in_queue);
1084   sbitmap_free (in_stack);
1085 }
1086
1087
1088 /* Wrapper function.
1089    If FLAG_SEL_SCHED_PIPELINING is set, then use custom function to form
1090    regions.  Otherwise just call find_rgns_haifa.  */
1091 static void
1092 find_rgns (void)
1093 {
1094   if (sel_sched_p () && flag_sel_sched_pipelining)
1095     sel_find_rgns ();
1096   else
1097     haifa_find_rgns ();
1098 }
1099
1100 static int gather_region_statistics (int **);
1101 static void print_region_statistics (int *, int, int *, int);
1102
1103 /* Calculate the histogram that shows the number of regions having the
1104    given number of basic blocks, and store it in the RSP array.  Return
1105    the size of this array.  */
1106 static int
1107 gather_region_statistics (int **rsp)
1108 {
1109   int i, *a = 0, a_sz = 0;
1110
1111   /* a[i] is the number of regions that have (i + 1) basic blocks.  */
1112   for (i = 0; i < nr_regions; i++)
1113     {
1114       int nr_blocks = RGN_NR_BLOCKS (i);
1115
1116       gcc_assert (nr_blocks >= 1);
1117
1118       if (nr_blocks > a_sz)
1119         {
1120           a = XRESIZEVEC (int, a, nr_blocks);
1121           do
1122             a[a_sz++] = 0;
1123           while (a_sz != nr_blocks);
1124         }
1125
1126       a[nr_blocks - 1]++;
1127     }
1128
1129   *rsp = a;
1130   return a_sz;
1131 }
1132
1133 /* Print regions statistics.  S1 and S2 denote the data before and after
1134    calling extend_rgns, respectively.  */
1135 static void
1136 print_region_statistics (int *s1, int s1_sz, int *s2, int s2_sz)
1137 {
1138   int i;
1139
1140   /* We iterate until s2_sz because extend_rgns does not decrease
1141      the maximal region size.  */
1142   for (i = 1; i < s2_sz; i++)
1143     {
1144       int n1, n2;
1145
1146       n2 = s2[i];
1147
1148       if (n2 == 0)
1149         continue;
1150
1151       if (i >= s1_sz)
1152         n1 = 0;
1153       else
1154         n1 = s1[i];
1155
1156       fprintf (sched_dump, ";; Region extension statistics: size %d: " \
1157                "was %d + %d more\n", i + 1, n1, n2 - n1);
1158     }
1159 }
1160
1161 /* Extend regions.
1162    DEGREE - Array of incoming edge count, considering only
1163    the edges, that don't have their sources in formed regions yet.
1164    IDXP - pointer to the next available index in rgn_bb_table.
1165    HEADER - set of all region heads.
1166    LOOP_HDR - mapping from block to the containing loop
1167    (two blocks can reside within one region if they have
1168    the same loop header).  */
1169 void
1170 extend_rgns (int *degree, int *idxp, sbitmap header, int *loop_hdr)
1171 {
1172   int *order, i, rescan = 0, idx = *idxp, iter = 0, max_iter, *max_hdr;
1173   int nblocks = n_basic_blocks_for_fn (cfun) - NUM_FIXED_BLOCKS;
1174
1175   max_iter = PARAM_VALUE (PARAM_MAX_SCHED_EXTEND_REGIONS_ITERS);
1176
1177   max_hdr = XNEWVEC (int, last_basic_block_for_fn (cfun));
1178
1179   order = XNEWVEC (int, last_basic_block_for_fn (cfun));
1180   post_order_compute (order, false, false);
1181
1182   for (i = nblocks - 1; i >= 0; i--)
1183     {
1184       int bbn = order[i];
1185       if (degree[bbn] >= 0)
1186         {
1187           max_hdr[bbn] = bbn;
1188           rescan = 1;
1189         }
1190       else
1191         /* This block already was processed in find_rgns.  */
1192         max_hdr[bbn] = -1;
1193     }
1194
1195   /* The idea is to topologically walk through CFG in top-down order.
1196      During the traversal, if all the predecessors of a node are
1197      marked to be in the same region (they all have the same max_hdr),
1198      then current node is also marked to be a part of that region.
1199      Otherwise the node starts its own region.
1200      CFG should be traversed until no further changes are made.  On each
1201      iteration the set of the region heads is extended (the set of those
1202      blocks that have max_hdr[bbi] == bbi).  This set is upper bounded by the
1203      set of all basic blocks, thus the algorithm is guaranteed to
1204      terminate.  */
1205
1206   while (rescan && iter < max_iter)
1207     {
1208       rescan = 0;
1209
1210       for (i = nblocks - 1; i >= 0; i--)
1211         {
1212           edge e;
1213           edge_iterator ei;
1214           int bbn = order[i];
1215
1216           if (max_hdr[bbn] != -1 && !bitmap_bit_p (header, bbn))
1217             {
1218               int hdr = -1;
1219
1220               FOR_EACH_EDGE (e, ei, BASIC_BLOCK_FOR_FN (cfun, bbn)->preds)
1221                 {
1222                   int predn = e->src->index;
1223
1224                   if (predn != ENTRY_BLOCK
1225                       /* If pred wasn't processed in find_rgns.  */
1226                       && max_hdr[predn] != -1
1227                       /* And pred and bb reside in the same loop.
1228                          (Or out of any loop).  */
1229                       && loop_hdr[bbn] == loop_hdr[predn])
1230                     {
1231                       if (hdr == -1)
1232                         /* Then bb extends the containing region of pred.  */
1233                         hdr = max_hdr[predn];
1234                       else if (hdr != max_hdr[predn])
1235                         /* Too bad, there are at least two predecessors
1236                            that reside in different regions.  Thus, BB should
1237                            begin its own region.  */
1238                         {
1239                           hdr = bbn;
1240                           break;
1241                         }
1242                     }
1243                   else
1244                     /* BB starts its own region.  */
1245                     {
1246                       hdr = bbn;
1247                       break;
1248                     }
1249                 }
1250
1251               if (hdr == bbn)
1252                 {
1253                   /* If BB start its own region,
1254                      update set of headers with BB.  */
1255                   bitmap_set_bit (header, bbn);
1256                   rescan = 1;
1257                 }
1258               else
1259                 gcc_assert (hdr != -1);
1260
1261               max_hdr[bbn] = hdr;
1262             }
1263         }
1264
1265       iter++;
1266     }
1267
1268   /* Statistics were gathered on the SPEC2000 package of tests with
1269      mainline weekly snapshot gcc-4.1-20051015 on ia64.
1270
1271      Statistics for SPECint:
1272      1 iteration : 1751 cases (38.7%)
1273      2 iterations: 2770 cases (61.3%)
1274      Blocks wrapped in regions by find_rgns without extension: 18295 blocks
1275      Blocks wrapped in regions by 2 iterations in extend_rgns: 23821 blocks
1276      (We don't count single block regions here).
1277
1278      Statistics for SPECfp:
1279      1 iteration : 621 cases (35.9%)
1280      2 iterations: 1110 cases (64.1%)
1281      Blocks wrapped in regions by find_rgns without extension: 6476 blocks
1282      Blocks wrapped in regions by 2 iterations in extend_rgns: 11155 blocks
1283      (We don't count single block regions here).
1284
1285      By default we do at most 2 iterations.
1286      This can be overridden with max-sched-extend-regions-iters parameter:
1287      0 - disable region extension,
1288      N > 0 - do at most N iterations.  */
1289
1290   if (sched_verbose && iter != 0)
1291     fprintf (sched_dump, ";; Region extension iterations: %d%s\n", iter,
1292              rescan ? "... failed" : "");
1293
1294   if (!rescan && iter != 0)
1295     {
1296       int *s1 = NULL, s1_sz = 0;
1297
1298       /* Save the old statistics for later printout.  */
1299       if (sched_verbose >= 6)
1300         s1_sz = gather_region_statistics (&s1);
1301
1302       /* We have succeeded.  Now assemble the regions.  */
1303       for (i = nblocks - 1; i >= 0; i--)
1304         {
1305           int bbn = order[i];
1306
1307           if (max_hdr[bbn] == bbn)
1308             /* BBN is a region head.  */
1309             {
1310               edge e;
1311               edge_iterator ei;
1312               int num_bbs = 0, j, num_insns = 0, large;
1313
1314               large = too_large (bbn, &num_bbs, &num_insns);
1315
1316               degree[bbn] = -1;
1317               rgn_bb_table[idx] = bbn;
1318               RGN_BLOCKS (nr_regions) = idx++;
1319               RGN_DONT_CALC_DEPS (nr_regions) = 0;
1320               RGN_HAS_REAL_EBB (nr_regions) = 0;
1321               CONTAINING_RGN (bbn) = nr_regions;
1322               BLOCK_TO_BB (bbn) = 0;
1323
1324               FOR_EACH_EDGE (e, ei, BASIC_BLOCK_FOR_FN (cfun, bbn)->succs)
1325                 if (e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun))
1326                   degree[e->dest->index]--;
1327
1328               if (!large)
1329                 /* Here we check whether the region is too_large.  */
1330                 for (j = i - 1; j >= 0; j--)
1331                   {
1332                     int succn = order[j];
1333                     if (max_hdr[succn] == bbn)
1334                       {
1335                         if ((large = too_large (succn, &num_bbs, &num_insns)))
1336                           break;
1337                       }
1338                   }
1339
1340               if (large)
1341                 /* If the region is too_large, then wrap every block of
1342                    the region into single block region.
1343                    Here we wrap region head only.  Other blocks are
1344                    processed in the below cycle.  */
1345                 {
1346                   RGN_NR_BLOCKS (nr_regions) = 1;
1347                   nr_regions++;
1348                 }
1349
1350               num_bbs = 1;
1351
1352               for (j = i - 1; j >= 0; j--)
1353                 {
1354                   int succn = order[j];
1355
1356                   if (max_hdr[succn] == bbn)
1357                     /* This cycle iterates over all basic blocks, that
1358                        are supposed to be in the region with head BBN,
1359                        and wraps them into that region (or in single
1360                        block region).  */
1361                     {
1362                       gcc_assert (degree[succn] == 0);
1363
1364                       degree[succn] = -1;
1365                       rgn_bb_table[idx] = succn;
1366                       BLOCK_TO_BB (succn) = large ? 0 : num_bbs++;
1367                       CONTAINING_RGN (succn) = nr_regions;
1368
1369                       if (large)
1370                         /* Wrap SUCCN into single block region.  */
1371                         {
1372                           RGN_BLOCKS (nr_regions) = idx;
1373                           RGN_NR_BLOCKS (nr_regions) = 1;
1374                           RGN_DONT_CALC_DEPS (nr_regions) = 0;
1375                           RGN_HAS_REAL_EBB (nr_regions) = 0;
1376                           nr_regions++;
1377                         }
1378
1379                       idx++;
1380
1381                       FOR_EACH_EDGE (e, ei,
1382                                      BASIC_BLOCK_FOR_FN (cfun, succn)->succs)
1383                         if (e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun))
1384                           degree[e->dest->index]--;
1385                     }
1386                 }
1387
1388               if (!large)
1389                 {
1390                   RGN_NR_BLOCKS (nr_regions) = num_bbs;
1391                   nr_regions++;
1392                 }
1393             }
1394         }
1395
1396       if (sched_verbose >= 6)
1397         {
1398           int *s2, s2_sz;
1399
1400           /* Get the new statistics and print the comparison with the
1401              one before calling this function.  */
1402           s2_sz = gather_region_statistics (&s2);
1403           print_region_statistics (s1, s1_sz, s2, s2_sz);
1404           free (s1);
1405           free (s2);
1406         }
1407     }
1408
1409   free (order);
1410   free (max_hdr);
1411
1412   *idxp = idx;
1413 }
1414
1415 /* Functions for regions scheduling information.  */
1416
1417 /* Compute dominators, probability, and potential-split-edges of bb.
1418    Assume that these values were already computed for bb's predecessors.  */
1419
1420 static void
1421 compute_dom_prob_ps (int bb)
1422 {
1423   edge_iterator in_ei;
1424   edge in_edge;
1425
1426   /* We shouldn't have any real ebbs yet.  */
1427   gcc_assert (ebb_head [bb] == bb + current_blocks);
1428
1429   if (IS_RGN_ENTRY (bb))
1430     {
1431       bitmap_set_bit (dom[bb], 0);
1432       prob[bb] = REG_BR_PROB_BASE;
1433       return;
1434     }
1435
1436   prob[bb] = 0;
1437
1438   /* Initialize dom[bb] to '111..1'.  */
1439   bitmap_ones (dom[bb]);
1440
1441   FOR_EACH_EDGE (in_edge, in_ei,
1442                  BASIC_BLOCK_FOR_FN (cfun, BB_TO_BLOCK (bb))->preds)
1443     {
1444       int pred_bb;
1445       edge out_edge;
1446       edge_iterator out_ei;
1447
1448       if (in_edge->src == ENTRY_BLOCK_PTR_FOR_FN (cfun))
1449         continue;
1450
1451       pred_bb = BLOCK_TO_BB (in_edge->src->index);
1452       bitmap_and (dom[bb], dom[bb], dom[pred_bb]);
1453       bitmap_ior (ancestor_edges[bb],
1454                       ancestor_edges[bb], ancestor_edges[pred_bb]);
1455
1456       bitmap_set_bit (ancestor_edges[bb], EDGE_TO_BIT (in_edge));
1457
1458       bitmap_ior (pot_split[bb], pot_split[bb], pot_split[pred_bb]);
1459
1460       FOR_EACH_EDGE (out_edge, out_ei, in_edge->src->succs)
1461         bitmap_set_bit (pot_split[bb], EDGE_TO_BIT (out_edge));
1462
1463       prob[bb] += combine_probabilities (prob[pred_bb], in_edge->probability);
1464       // The rounding divide in combine_probabilities can result in an extra
1465       // probability increment propagating along 50-50 edges. Eventually when
1466       // the edges re-merge, the accumulated probability can go slightly above
1467       // REG_BR_PROB_BASE.
1468       if (prob[bb] > REG_BR_PROB_BASE)
1469         prob[bb] = REG_BR_PROB_BASE;
1470     }
1471
1472   bitmap_set_bit (dom[bb], bb);
1473   bitmap_and_compl (pot_split[bb], pot_split[bb], ancestor_edges[bb]);
1474
1475   if (sched_verbose >= 2)
1476     fprintf (sched_dump, ";;  bb_prob(%d, %d) = %3d\n", bb, BB_TO_BLOCK (bb),
1477              (100 * prob[bb]) / REG_BR_PROB_BASE);
1478 }
1479
1480 /* Functions for target info.  */
1481
1482 /* Compute in BL the list of split-edges of bb_src relatively to bb_trg.
1483    Note that bb_trg dominates bb_src.  */
1484
1485 static void
1486 split_edges (int bb_src, int bb_trg, edgelst *bl)
1487 {
1488   sbitmap src = sbitmap_alloc (SBITMAP_SIZE (pot_split[bb_src]));
1489   bitmap_copy (src, pot_split[bb_src]);
1490
1491   bitmap_and_compl (src, src, pot_split[bb_trg]);
1492   extract_edgelst (src, bl);
1493   sbitmap_free (src);
1494 }
1495
1496 /* Find the valid candidate-source-blocks for the target block TRG, compute
1497    their probability, and check if they are speculative or not.
1498    For speculative sources, compute their update-blocks and split-blocks.  */
1499
1500 static void
1501 compute_trg_info (int trg)
1502 {
1503   candidate *sp;
1504   edgelst el = { NULL, 0 };
1505   int i, j, k, update_idx;
1506   basic_block block;
1507   sbitmap visited;
1508   edge_iterator ei;
1509   edge e;
1510
1511   candidate_table = XNEWVEC (candidate, current_nr_blocks);
1512
1513   bblst_last = 0;
1514   /* bblst_table holds split blocks and update blocks for each block after
1515      the current one in the region.  split blocks and update blocks are
1516      the TO blocks of region edges, so there can be at most rgn_nr_edges
1517      of them.  */
1518   bblst_size = (current_nr_blocks - target_bb) * rgn_nr_edges;
1519   bblst_table = XNEWVEC (basic_block, bblst_size);
1520
1521   edgelst_last = 0;
1522   edgelst_table = XNEWVEC (edge, rgn_nr_edges);
1523
1524   /* Define some of the fields for the target bb as well.  */
1525   sp = candidate_table + trg;
1526   sp->is_valid = 1;
1527   sp->is_speculative = 0;
1528   sp->src_prob = REG_BR_PROB_BASE;
1529
1530   visited = sbitmap_alloc (last_basic_block_for_fn (cfun));
1531
1532   for (i = trg + 1; i < current_nr_blocks; i++)
1533     {
1534       sp = candidate_table + i;
1535
1536       sp->is_valid = IS_DOMINATED (i, trg);
1537       if (sp->is_valid)
1538         {
1539           int tf = prob[trg], cf = prob[i];
1540
1541           /* In CFGs with low probability edges TF can possibly be zero.  */
1542           sp->src_prob = (tf ? GCOV_COMPUTE_SCALE (cf, tf) : 0);
1543           sp->is_valid = (sp->src_prob >= min_spec_prob);
1544         }
1545
1546       if (sp->is_valid)
1547         {
1548           split_edges (i, trg, &el);
1549           sp->is_speculative = (el.nr_members) ? 1 : 0;
1550           if (sp->is_speculative && !flag_schedule_speculative)
1551             sp->is_valid = 0;
1552         }
1553
1554       if (sp->is_valid)
1555         {
1556           /* Compute split blocks and store them in bblst_table.
1557              The TO block of every split edge is a split block.  */
1558           sp->split_bbs.first_member = &bblst_table[bblst_last];
1559           sp->split_bbs.nr_members = el.nr_members;
1560           for (j = 0; j < el.nr_members; bblst_last++, j++)
1561             bblst_table[bblst_last] = el.first_member[j]->dest;
1562           sp->update_bbs.first_member = &bblst_table[bblst_last];
1563
1564           /* Compute update blocks and store them in bblst_table.
1565              For every split edge, look at the FROM block, and check
1566              all out edges.  For each out edge that is not a split edge,
1567              add the TO block to the update block list.  This list can end
1568              up with a lot of duplicates.  We need to weed them out to avoid
1569              overrunning the end of the bblst_table.  */
1570
1571           update_idx = 0;
1572           bitmap_clear (visited);
1573           for (j = 0; j < el.nr_members; j++)
1574             {
1575               block = el.first_member[j]->src;
1576               FOR_EACH_EDGE (e, ei, block->succs)
1577                 {
1578                   if (!bitmap_bit_p (visited, e->dest->index))
1579                     {
1580                       for (k = 0; k < el.nr_members; k++)
1581                         if (e == el.first_member[k])
1582                           break;
1583
1584                       if (k >= el.nr_members)
1585                         {
1586                           bblst_table[bblst_last++] = e->dest;
1587                           bitmap_set_bit (visited, e->dest->index);
1588                           update_idx++;
1589                         }
1590                     }
1591                 }
1592             }
1593           sp->update_bbs.nr_members = update_idx;
1594
1595           /* Make sure we didn't overrun the end of bblst_table.  */
1596           gcc_assert (bblst_last <= bblst_size);
1597         }
1598       else
1599         {
1600           sp->split_bbs.nr_members = sp->update_bbs.nr_members = 0;
1601
1602           sp->is_speculative = 0;
1603           sp->src_prob = 0;
1604         }
1605     }
1606
1607   sbitmap_free (visited);
1608 }
1609
1610 /* Free the computed target info.  */
1611 static void
1612 free_trg_info (void)
1613 {
1614   free (candidate_table);
1615   free (bblst_table);
1616   free (edgelst_table);
1617 }
1618
1619 /* Print candidates info, for debugging purposes.  Callable from debugger.  */
1620
1621 DEBUG_FUNCTION void
1622 debug_candidate (int i)
1623 {
1624   if (!candidate_table[i].is_valid)
1625     return;
1626
1627   if (candidate_table[i].is_speculative)
1628     {
1629       int j;
1630       fprintf (sched_dump, "src b %d bb %d speculative \n", BB_TO_BLOCK (i), i);
1631
1632       fprintf (sched_dump, "split path: ");
1633       for (j = 0; j < candidate_table[i].split_bbs.nr_members; j++)
1634         {
1635           int b = candidate_table[i].split_bbs.first_member[j]->index;
1636
1637           fprintf (sched_dump, " %d ", b);
1638         }
1639       fprintf (sched_dump, "\n");
1640
1641       fprintf (sched_dump, "update path: ");
1642       for (j = 0; j < candidate_table[i].update_bbs.nr_members; j++)
1643         {
1644           int b = candidate_table[i].update_bbs.first_member[j]->index;
1645
1646           fprintf (sched_dump, " %d ", b);
1647         }
1648       fprintf (sched_dump, "\n");
1649     }
1650   else
1651     {
1652       fprintf (sched_dump, " src %d equivalent\n", BB_TO_BLOCK (i));
1653     }
1654 }
1655
1656 /* Print candidates info, for debugging purposes.  Callable from debugger.  */
1657
1658 DEBUG_FUNCTION void
1659 debug_candidates (int trg)
1660 {
1661   int i;
1662
1663   fprintf (sched_dump, "----------- candidate table: target: b=%d bb=%d ---\n",
1664            BB_TO_BLOCK (trg), trg);
1665   for (i = trg + 1; i < current_nr_blocks; i++)
1666     debug_candidate (i);
1667 }
1668
1669 /* Functions for speculative scheduling.  */
1670
1671 static bitmap_head not_in_df;
1672
1673 /* Return 0 if x is a set of a register alive in the beginning of one
1674    of the split-blocks of src, otherwise return 1.  */
1675
1676 static int
1677 check_live_1 (int src, rtx x)
1678 {
1679   int i;
1680   int regno;
1681   rtx reg = SET_DEST (x);
1682
1683   if (reg == 0)
1684     return 1;
1685
1686   while (GET_CODE (reg) == SUBREG
1687          || GET_CODE (reg) == ZERO_EXTRACT
1688          || GET_CODE (reg) == STRICT_LOW_PART)
1689     reg = XEXP (reg, 0);
1690
1691   if (GET_CODE (reg) == PARALLEL)
1692     {
1693       int i;
1694
1695       for (i = XVECLEN (reg, 0) - 1; i >= 0; i--)
1696         if (XEXP (XVECEXP (reg, 0, i), 0) != 0)
1697           if (check_live_1 (src, XEXP (XVECEXP (reg, 0, i), 0)))
1698             return 1;
1699
1700       return 0;
1701     }
1702
1703   if (!REG_P (reg))
1704     return 1;
1705
1706   regno = REGNO (reg);
1707
1708   if (regno < FIRST_PSEUDO_REGISTER && global_regs[regno])
1709     {
1710       /* Global registers are assumed live.  */
1711       return 0;
1712     }
1713   else
1714     {
1715       if (regno < FIRST_PSEUDO_REGISTER)
1716         {
1717           /* Check for hard registers.  */
1718           int j = hard_regno_nregs[regno][GET_MODE (reg)];
1719           while (--j >= 0)
1720             {
1721               for (i = 0; i < candidate_table[src].split_bbs.nr_members; i++)
1722                 {
1723                   basic_block b = candidate_table[src].split_bbs.first_member[i];
1724                   int t = bitmap_bit_p (&not_in_df, b->index);
1725
1726                   /* We can have split blocks, that were recently generated.
1727                      Such blocks are always outside current region.  */
1728                   gcc_assert (!t || (CONTAINING_RGN (b->index)
1729                                      != CONTAINING_RGN (BB_TO_BLOCK (src))));
1730
1731                   if (t || REGNO_REG_SET_P (df_get_live_in (b), regno + j))
1732                     return 0;
1733                 }
1734             }
1735         }
1736       else
1737         {
1738           /* Check for pseudo registers.  */
1739           for (i = 0; i < candidate_table[src].split_bbs.nr_members; i++)
1740             {
1741               basic_block b = candidate_table[src].split_bbs.first_member[i];
1742               int t = bitmap_bit_p (&not_in_df, b->index);
1743
1744               gcc_assert (!t || (CONTAINING_RGN (b->index)
1745                                  != CONTAINING_RGN (BB_TO_BLOCK (src))));
1746
1747               if (t || REGNO_REG_SET_P (df_get_live_in (b), regno))
1748                 return 0;
1749             }
1750         }
1751     }
1752
1753   return 1;
1754 }
1755
1756 /* If x is a set of a register R, mark that R is alive in the beginning
1757    of every update-block of src.  */
1758
1759 static void
1760 update_live_1 (int src, rtx x)
1761 {
1762   int i;
1763   int regno;
1764   rtx reg = SET_DEST (x);
1765
1766   if (reg == 0)
1767     return;
1768
1769   while (GET_CODE (reg) == SUBREG
1770          || GET_CODE (reg) == ZERO_EXTRACT
1771          || GET_CODE (reg) == STRICT_LOW_PART)
1772     reg = XEXP (reg, 0);
1773
1774   if (GET_CODE (reg) == PARALLEL)
1775     {
1776       int i;
1777
1778       for (i = XVECLEN (reg, 0) - 1; i >= 0; i--)
1779         if (XEXP (XVECEXP (reg, 0, i), 0) != 0)
1780           update_live_1 (src, XEXP (XVECEXP (reg, 0, i), 0));
1781
1782       return;
1783     }
1784
1785   if (!REG_P (reg))
1786     return;
1787
1788   /* Global registers are always live, so the code below does not apply
1789      to them.  */
1790
1791   regno = REGNO (reg);
1792
1793   if (! HARD_REGISTER_NUM_P (regno)
1794       || !global_regs[regno])
1795     {
1796       for (i = 0; i < candidate_table[src].update_bbs.nr_members; i++)
1797         {
1798           basic_block b = candidate_table[src].update_bbs.first_member[i];
1799
1800           if (HARD_REGISTER_NUM_P (regno))
1801             bitmap_set_range (df_get_live_in (b), regno,
1802                               hard_regno_nregs[regno][GET_MODE (reg)]);
1803           else
1804             bitmap_set_bit (df_get_live_in (b), regno);
1805         }
1806     }
1807 }
1808
1809 /* Return 1 if insn can be speculatively moved from block src to trg,
1810    otherwise return 0.  Called before first insertion of insn to
1811    ready-list or before the scheduling.  */
1812
1813 static int
1814 check_live (rtx_insn *insn, int src)
1815 {
1816   /* Find the registers set by instruction.  */
1817   if (GET_CODE (PATTERN (insn)) == SET
1818       || GET_CODE (PATTERN (insn)) == CLOBBER)
1819     return check_live_1 (src, PATTERN (insn));
1820   else if (GET_CODE (PATTERN (insn)) == PARALLEL)
1821     {
1822       int j;
1823       for (j = XVECLEN (PATTERN (insn), 0) - 1; j >= 0; j--)
1824         if ((GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == SET
1825              || GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == CLOBBER)
1826             && !check_live_1 (src, XVECEXP (PATTERN (insn), 0, j)))
1827           return 0;
1828
1829       return 1;
1830     }
1831
1832   return 1;
1833 }
1834
1835 /* Update the live registers info after insn was moved speculatively from
1836    block src to trg.  */
1837
1838 static void
1839 update_live (rtx insn, int src)
1840 {
1841   /* Find the registers set by instruction.  */
1842   if (GET_CODE (PATTERN (insn)) == SET
1843       || GET_CODE (PATTERN (insn)) == CLOBBER)
1844     update_live_1 (src, PATTERN (insn));
1845   else if (GET_CODE (PATTERN (insn)) == PARALLEL)
1846     {
1847       int j;
1848       for (j = XVECLEN (PATTERN (insn), 0) - 1; j >= 0; j--)
1849         if (GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == SET
1850             || GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == CLOBBER)
1851           update_live_1 (src, XVECEXP (PATTERN (insn), 0, j));
1852     }
1853 }
1854
1855 /* Nonzero if block bb_to is equal to, or reachable from block bb_from.  */
1856 #define IS_REACHABLE(bb_from, bb_to)                                    \
1857   (bb_from == bb_to                                                     \
1858    || IS_RGN_ENTRY (bb_from)                                            \
1859    || (bitmap_bit_p (ancestor_edges[bb_to],                                     \
1860          EDGE_TO_BIT (single_pred_edge (BASIC_BLOCK_FOR_FN (cfun, \
1861                                                             BB_TO_BLOCK (bb_from)))))))
1862
1863 /* Turns on the fed_by_spec_load flag for insns fed by load_insn.  */
1864
1865 static void
1866 set_spec_fed (rtx load_insn)
1867 {
1868   sd_iterator_def sd_it;
1869   dep_t dep;
1870
1871   FOR_EACH_DEP (load_insn, SD_LIST_FORW, sd_it, dep)
1872     if (DEP_TYPE (dep) == REG_DEP_TRUE)
1873       FED_BY_SPEC_LOAD (DEP_CON (dep)) = 1;
1874 }
1875
1876 /* On the path from the insn to load_insn_bb, find a conditional
1877 branch depending on insn, that guards the speculative load.  */
1878
1879 static int
1880 find_conditional_protection (rtx insn, int load_insn_bb)
1881 {
1882   sd_iterator_def sd_it;
1883   dep_t dep;
1884
1885   /* Iterate through DEF-USE forward dependences.  */
1886   FOR_EACH_DEP (insn, SD_LIST_FORW, sd_it, dep)
1887     {
1888       rtx_insn *next = DEP_CON (dep);
1889
1890       if ((CONTAINING_RGN (BLOCK_NUM (next)) ==
1891            CONTAINING_RGN (BB_TO_BLOCK (load_insn_bb)))
1892           && IS_REACHABLE (INSN_BB (next), load_insn_bb)
1893           && load_insn_bb != INSN_BB (next)
1894           && DEP_TYPE (dep) == REG_DEP_TRUE
1895           && (JUMP_P (next)
1896               || find_conditional_protection (next, load_insn_bb)))
1897         return 1;
1898     }
1899   return 0;
1900 }                               /* find_conditional_protection */
1901
1902 /* Returns 1 if the same insn1 that participates in the computation
1903    of load_insn's address is feeding a conditional branch that is
1904    guarding on load_insn. This is true if we find two DEF-USE
1905    chains:
1906    insn1 -> ... -> conditional-branch
1907    insn1 -> ... -> load_insn,
1908    and if a flow path exists:
1909    insn1 -> ... -> conditional-branch -> ... -> load_insn,
1910    and if insn1 is on the path
1911    region-entry -> ... -> bb_trg -> ... load_insn.
1912
1913    Locate insn1 by climbing on INSN_BACK_DEPS from load_insn.
1914    Locate the branch by following INSN_FORW_DEPS from insn1.  */
1915
1916 static int
1917 is_conditionally_protected (rtx load_insn, int bb_src, int bb_trg)
1918 {
1919   sd_iterator_def sd_it;
1920   dep_t dep;
1921
1922   FOR_EACH_DEP (load_insn, SD_LIST_BACK, sd_it, dep)
1923     {
1924       rtx_insn *insn1 = DEP_PRO (dep);
1925
1926       /* Must be a DEF-USE dependence upon non-branch.  */
1927       if (DEP_TYPE (dep) != REG_DEP_TRUE
1928           || JUMP_P (insn1))
1929         continue;
1930
1931       /* Must exist a path: region-entry -> ... -> bb_trg -> ... load_insn.  */
1932       if (INSN_BB (insn1) == bb_src
1933           || (CONTAINING_RGN (BLOCK_NUM (insn1))
1934               != CONTAINING_RGN (BB_TO_BLOCK (bb_src)))
1935           || (!IS_REACHABLE (bb_trg, INSN_BB (insn1))
1936               && !IS_REACHABLE (INSN_BB (insn1), bb_trg)))
1937         continue;
1938
1939       /* Now search for the conditional-branch.  */
1940       if (find_conditional_protection (insn1, bb_src))
1941         return 1;
1942
1943       /* Recursive step: search another insn1, "above" current insn1.  */
1944       return is_conditionally_protected (insn1, bb_src, bb_trg);
1945     }
1946
1947   /* The chain does not exist.  */
1948   return 0;
1949 }                               /* is_conditionally_protected */
1950
1951 /* Returns 1 if a clue for "similar load" 'insn2' is found, and hence
1952    load_insn can move speculatively from bb_src to bb_trg.  All the
1953    following must hold:
1954
1955    (1) both loads have 1 base register (PFREE_CANDIDATEs).
1956    (2) load_insn and load1 have a def-use dependence upon
1957    the same insn 'insn1'.
1958    (3) either load2 is in bb_trg, or:
1959    - there's only one split-block, and
1960    - load1 is on the escape path, and
1961
1962    From all these we can conclude that the two loads access memory
1963    addresses that differ at most by a constant, and hence if moving
1964    load_insn would cause an exception, it would have been caused by
1965    load2 anyhow.  */
1966
1967 static int
1968 is_pfree (rtx load_insn, int bb_src, int bb_trg)
1969 {
1970   sd_iterator_def back_sd_it;
1971   dep_t back_dep;
1972   candidate *candp = candidate_table + bb_src;
1973
1974   if (candp->split_bbs.nr_members != 1)
1975     /* Must have exactly one escape block.  */
1976     return 0;
1977
1978   FOR_EACH_DEP (load_insn, SD_LIST_BACK, back_sd_it, back_dep)
1979     {
1980       rtx_insn *insn1 = DEP_PRO (back_dep);
1981
1982       if (DEP_TYPE (back_dep) == REG_DEP_TRUE)
1983         /* Found a DEF-USE dependence (insn1, load_insn).  */
1984         {
1985           sd_iterator_def fore_sd_it;
1986           dep_t fore_dep;
1987
1988           FOR_EACH_DEP (insn1, SD_LIST_FORW, fore_sd_it, fore_dep)
1989             {
1990               rtx_insn *insn2 = DEP_CON (fore_dep);
1991
1992               if (DEP_TYPE (fore_dep) == REG_DEP_TRUE)
1993                 {
1994                   /* Found a DEF-USE dependence (insn1, insn2).  */
1995                   if (haifa_classify_insn (insn2) != PFREE_CANDIDATE)
1996                     /* insn2 not guaranteed to be a 1 base reg load.  */
1997                     continue;
1998
1999                   if (INSN_BB (insn2) == bb_trg)
2000                     /* insn2 is the similar load, in the target block.  */
2001                     return 1;
2002
2003                   if (*(candp->split_bbs.first_member) == BLOCK_FOR_INSN (insn2))
2004                     /* insn2 is a similar load, in a split-block.  */
2005                     return 1;
2006                 }
2007             }
2008         }
2009     }
2010
2011   /* Couldn't find a similar load.  */
2012   return 0;
2013 }                               /* is_pfree */
2014
2015 /* Return 1 if load_insn is prisky (i.e. if load_insn is fed by
2016    a load moved speculatively, or if load_insn is protected by
2017    a compare on load_insn's address).  */
2018
2019 static int
2020 is_prisky (rtx load_insn, int bb_src, int bb_trg)
2021 {
2022   if (FED_BY_SPEC_LOAD (load_insn))
2023     return 1;
2024
2025   if (sd_lists_empty_p (load_insn, SD_LIST_BACK))
2026     /* Dependence may 'hide' out of the region.  */
2027     return 1;
2028
2029   if (is_conditionally_protected (load_insn, bb_src, bb_trg))
2030     return 1;
2031
2032   return 0;
2033 }
2034
2035 /* Insn is a candidate to be moved speculatively from bb_src to bb_trg.
2036    Return 1 if insn is exception-free (and the motion is valid)
2037    and 0 otherwise.  */
2038
2039 static int
2040 is_exception_free (rtx insn, int bb_src, int bb_trg)
2041 {
2042   int insn_class = haifa_classify_insn (insn);
2043
2044   /* Handle non-load insns.  */
2045   switch (insn_class)
2046     {
2047     case TRAP_FREE:
2048       return 1;
2049     case TRAP_RISKY:
2050       return 0;
2051     default:;
2052     }
2053
2054   /* Handle loads.  */
2055   if (!flag_schedule_speculative_load)
2056     return 0;
2057   IS_LOAD_INSN (insn) = 1;
2058   switch (insn_class)
2059     {
2060     case IFREE:
2061       return (1);
2062     case IRISKY:
2063       return 0;
2064     case PFREE_CANDIDATE:
2065       if (is_pfree (insn, bb_src, bb_trg))
2066         return 1;
2067       /* Don't 'break' here: PFREE-candidate is also PRISKY-candidate.  */
2068     case PRISKY_CANDIDATE:
2069       if (!flag_schedule_speculative_load_dangerous
2070           || is_prisky (insn, bb_src, bb_trg))
2071         return 0;
2072       break;
2073     default:;
2074     }
2075
2076   return flag_schedule_speculative_load_dangerous;
2077 }
2078 \f
2079 /* The number of insns from the current block scheduled so far.  */
2080 static int sched_target_n_insns;
2081 /* The number of insns from the current block to be scheduled in total.  */
2082 static int target_n_insns;
2083 /* The number of insns from the entire region scheduled so far.  */
2084 static int sched_n_insns;
2085
2086 /* Implementations of the sched_info functions for region scheduling.  */
2087 static void init_ready_list (void);
2088 static int can_schedule_ready_p (rtx_insn *);
2089 static void begin_schedule_ready (rtx_insn *);
2090 static ds_t new_ready (rtx_insn *, ds_t);
2091 static int schedule_more_p (void);
2092 static const char *rgn_print_insn (const rtx_insn *, int);
2093 static int rgn_rank (rtx_insn *, rtx_insn *);
2094 static void compute_jump_reg_dependencies (rtx, regset);
2095
2096 /* Functions for speculative scheduling.  */
2097 static void rgn_add_remove_insn (rtx_insn *, int);
2098 static void rgn_add_block (basic_block, basic_block);
2099 static void rgn_fix_recovery_cfg (int, int, int);
2100 static basic_block advance_target_bb (basic_block, rtx_insn *);
2101
2102 /* Return nonzero if there are more insns that should be scheduled.  */
2103
2104 static int
2105 schedule_more_p (void)
2106 {
2107   return sched_target_n_insns < target_n_insns;
2108 }
2109
2110 /* Add all insns that are initially ready to the ready list READY.  Called
2111    once before scheduling a set of insns.  */
2112
2113 static void
2114 init_ready_list (void)
2115 {
2116   rtx_insn *prev_head = current_sched_info->prev_head;
2117   rtx_insn *next_tail = current_sched_info->next_tail;
2118   int bb_src;
2119   rtx_insn *insn;
2120
2121   target_n_insns = 0;
2122   sched_target_n_insns = 0;
2123   sched_n_insns = 0;
2124
2125   /* Print debugging information.  */
2126   if (sched_verbose >= 5)
2127     debug_rgn_dependencies (target_bb);
2128
2129   /* Prepare current target block info.  */
2130   if (current_nr_blocks > 1)
2131     compute_trg_info (target_bb);
2132
2133   /* Initialize ready list with all 'ready' insns in target block.
2134      Count number of insns in the target block being scheduled.  */
2135   for (insn = NEXT_INSN (prev_head); insn != next_tail; insn = NEXT_INSN (insn))
2136     {
2137       gcc_assert (TODO_SPEC (insn) == HARD_DEP || TODO_SPEC (insn) == DEP_POSTPONED);
2138       TODO_SPEC (insn) = HARD_DEP;
2139       try_ready (insn);
2140       target_n_insns++;
2141
2142       gcc_assert (!(TODO_SPEC (insn) & BEGIN_CONTROL));
2143     }
2144
2145   /* Add to ready list all 'ready' insns in valid source blocks.
2146      For speculative insns, check-live, exception-free, and
2147      issue-delay.  */
2148   for (bb_src = target_bb + 1; bb_src < current_nr_blocks; bb_src++)
2149     if (IS_VALID (bb_src))
2150       {
2151         rtx_insn *src_head;
2152         rtx_insn *src_next_tail;
2153         rtx_insn *tail, *head;
2154
2155         get_ebb_head_tail (EBB_FIRST_BB (bb_src), EBB_LAST_BB (bb_src),
2156                            &head, &tail);
2157         src_next_tail = NEXT_INSN (tail);
2158         src_head = head;
2159
2160         for (insn = src_head; insn != src_next_tail; insn = NEXT_INSN (insn))
2161           if (INSN_P (insn))
2162             {
2163               gcc_assert (TODO_SPEC (insn) == HARD_DEP || TODO_SPEC (insn) == DEP_POSTPONED);
2164               TODO_SPEC (insn) = HARD_DEP;
2165               try_ready (insn);
2166             }
2167       }
2168 }
2169
2170 /* Called after taking INSN from the ready list.  Returns nonzero if this
2171    insn can be scheduled, nonzero if we should silently discard it.  */
2172
2173 static int
2174 can_schedule_ready_p (rtx_insn *insn)
2175 {
2176   /* An interblock motion?  */
2177   if (INSN_BB (insn) != target_bb
2178       && IS_SPECULATIVE_INSN (insn)
2179       && !check_live (insn, INSN_BB (insn)))
2180     return 0;
2181   else
2182     return 1;
2183 }
2184
2185 /* Updates counter and other information.  Split from can_schedule_ready_p ()
2186    because when we schedule insn speculatively then insn passed to
2187    can_schedule_ready_p () differs from the one passed to
2188    begin_schedule_ready ().  */
2189 static void
2190 begin_schedule_ready (rtx_insn *insn)
2191 {
2192   /* An interblock motion?  */
2193   if (INSN_BB (insn) != target_bb)
2194     {
2195       if (IS_SPECULATIVE_INSN (insn))
2196         {
2197           gcc_assert (check_live (insn, INSN_BB (insn)));
2198
2199           update_live (insn, INSN_BB (insn));
2200
2201           /* For speculative load, mark insns fed by it.  */
2202           if (IS_LOAD_INSN (insn) || FED_BY_SPEC_LOAD (insn))
2203             set_spec_fed (insn);
2204
2205           nr_spec++;
2206         }
2207       nr_inter++;
2208     }
2209   else
2210     {
2211       /* In block motion.  */
2212       sched_target_n_insns++;
2213     }
2214   sched_n_insns++;
2215 }
2216
2217 /* Called after INSN has all its hard dependencies resolved and the speculation
2218    of type TS is enough to overcome them all.
2219    Return nonzero if it should be moved to the ready list or the queue, or zero
2220    if we should silently discard it.  */
2221 static ds_t
2222 new_ready (rtx_insn *next, ds_t ts)
2223 {
2224   if (INSN_BB (next) != target_bb)
2225     {
2226       int not_ex_free = 0;
2227
2228       /* For speculative insns, before inserting to ready/queue,
2229          check live, exception-free, and issue-delay.  */
2230       if (!IS_VALID (INSN_BB (next))
2231           || CANT_MOVE (next)
2232           || (IS_SPECULATIVE_INSN (next)
2233               && ((recog_memoized (next) >= 0
2234                    && min_insn_conflict_delay (curr_state, next, next)
2235                    > PARAM_VALUE (PARAM_MAX_SCHED_INSN_CONFLICT_DELAY))
2236                   || IS_SPECULATION_CHECK_P (next)
2237                   || !check_live (next, INSN_BB (next))
2238                   || (not_ex_free = !is_exception_free (next, INSN_BB (next),
2239                                                         target_bb)))))
2240         {
2241           if (not_ex_free
2242               /* We are here because is_exception_free () == false.
2243                  But we possibly can handle that with control speculation.  */
2244               && sched_deps_info->generate_spec_deps
2245               && spec_info->mask & BEGIN_CONTROL)
2246             {
2247               ds_t new_ds;
2248
2249               /* Add control speculation to NEXT's dependency type.  */
2250               new_ds = set_dep_weak (ts, BEGIN_CONTROL, MAX_DEP_WEAK);
2251
2252               /* Check if NEXT can be speculated with new dependency type.  */
2253               if (sched_insn_is_legitimate_for_speculation_p (next, new_ds))
2254                 /* Here we got new control-speculative instruction.  */
2255                 ts = new_ds;
2256               else
2257                 /* NEXT isn't ready yet.  */
2258                 ts = DEP_POSTPONED;
2259             }
2260           else
2261             /* NEXT isn't ready yet.  */
2262             ts = DEP_POSTPONED;
2263         }
2264     }
2265
2266   return ts;
2267 }
2268
2269 /* Return a string that contains the insn uid and optionally anything else
2270    necessary to identify this insn in an output.  It's valid to use a
2271    static buffer for this.  The ALIGNED parameter should cause the string
2272    to be formatted so that multiple output lines will line up nicely.  */
2273
2274 static const char *
2275 rgn_print_insn (const rtx_insn *insn, int aligned)
2276 {
2277   static char tmp[80];
2278
2279   if (aligned)
2280     sprintf (tmp, "b%3d: i%4d", INSN_BB (insn), INSN_UID (insn));
2281   else
2282     {
2283       if (current_nr_blocks > 1 && INSN_BB (insn) != target_bb)
2284         sprintf (tmp, "%d/b%d", INSN_UID (insn), INSN_BB (insn));
2285       else
2286         sprintf (tmp, "%d", INSN_UID (insn));
2287     }
2288   return tmp;
2289 }
2290
2291 /* Compare priority of two insns.  Return a positive number if the second
2292    insn is to be preferred for scheduling, and a negative one if the first
2293    is to be preferred.  Zero if they are equally good.  */
2294
2295 static int
2296 rgn_rank (rtx_insn *insn1, rtx_insn *insn2)
2297 {
2298   /* Some comparison make sense in interblock scheduling only.  */
2299   if (INSN_BB (insn1) != INSN_BB (insn2))
2300     {
2301       int spec_val, prob_val;
2302
2303       /* Prefer an inblock motion on an interblock motion.  */
2304       if ((INSN_BB (insn2) == target_bb) && (INSN_BB (insn1) != target_bb))
2305         return 1;
2306       if ((INSN_BB (insn1) == target_bb) && (INSN_BB (insn2) != target_bb))
2307         return -1;
2308
2309       /* Prefer a useful motion on a speculative one.  */
2310       spec_val = IS_SPECULATIVE_INSN (insn1) - IS_SPECULATIVE_INSN (insn2);
2311       if (spec_val)
2312         return spec_val;
2313
2314       /* Prefer a more probable (speculative) insn.  */
2315       prob_val = INSN_PROBABILITY (insn2) - INSN_PROBABILITY (insn1);
2316       if (prob_val)
2317         return prob_val;
2318     }
2319   return 0;
2320 }
2321
2322 /* NEXT is an instruction that depends on INSN (a backward dependence);
2323    return nonzero if we should include this dependence in priority
2324    calculations.  */
2325
2326 int
2327 contributes_to_priority (rtx_insn *next, rtx_insn *insn)
2328 {
2329   /* NEXT and INSN reside in one ebb.  */
2330   return BLOCK_TO_BB (BLOCK_NUM (next)) == BLOCK_TO_BB (BLOCK_NUM (insn));
2331 }
2332
2333 /* INSN is a JUMP_INSN.  Store the set of registers that must be
2334    considered as used by this jump in USED.  */
2335
2336 static void
2337 compute_jump_reg_dependencies (rtx insn ATTRIBUTE_UNUSED,
2338                                regset used ATTRIBUTE_UNUSED)
2339 {
2340   /* Nothing to do here, since we postprocess jumps in
2341      add_branch_dependences.  */
2342 }
2343
2344 /* This variable holds common_sched_info hooks and data relevant to
2345    the interblock scheduler.  */
2346 static struct common_sched_info_def rgn_common_sched_info;
2347
2348
2349 /* This holds data for the dependence analysis relevant to
2350    the interblock scheduler.  */
2351 static struct sched_deps_info_def rgn_sched_deps_info;
2352
2353 /* This holds constant data used for initializing the above structure
2354    for the Haifa scheduler.  */
2355 static const struct sched_deps_info_def rgn_const_sched_deps_info =
2356   {
2357     compute_jump_reg_dependencies,
2358     NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2359     0, 0, 0
2360   };
2361
2362 /* Same as above, but for the selective scheduler.  */
2363 static const struct sched_deps_info_def rgn_const_sel_sched_deps_info =
2364   {
2365     compute_jump_reg_dependencies,
2366     NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2367     0, 0, 0
2368   };
2369
2370 /* Return true if scheduling INSN will trigger finish of scheduling
2371    current block.  */
2372 static bool
2373 rgn_insn_finishes_block_p (rtx_insn *insn)
2374 {
2375   if (INSN_BB (insn) == target_bb
2376       && sched_target_n_insns + 1 == target_n_insns)
2377     /* INSN is the last not-scheduled instruction in the current block.  */
2378     return true;
2379
2380   return false;
2381 }
2382
2383 /* Used in schedule_insns to initialize current_sched_info for scheduling
2384    regions (or single basic blocks).  */
2385
2386 static const struct haifa_sched_info rgn_const_sched_info =
2387 {
2388   init_ready_list,
2389   can_schedule_ready_p,
2390   schedule_more_p,
2391   new_ready,
2392   rgn_rank,
2393   rgn_print_insn,
2394   contributes_to_priority,
2395   rgn_insn_finishes_block_p,
2396
2397   NULL, NULL,
2398   NULL, NULL,
2399   0, 0,
2400
2401   rgn_add_remove_insn,
2402   begin_schedule_ready,
2403   NULL,
2404   advance_target_bb,
2405   NULL, NULL,
2406   SCHED_RGN
2407 };
2408
2409 /* This variable holds the data and hooks needed to the Haifa scheduler backend
2410    for the interblock scheduler frontend.  */
2411 static struct haifa_sched_info rgn_sched_info;
2412
2413 /* Returns maximum priority that an insn was assigned to.  */
2414
2415 int
2416 get_rgn_sched_max_insns_priority (void)
2417 {
2418   return rgn_sched_info.sched_max_insns_priority;
2419 }
2420
2421 /* Determine if PAT sets a TARGET_CLASS_LIKELY_SPILLED_P register.  */
2422
2423 static bool
2424 sets_likely_spilled (rtx pat)
2425 {
2426   bool ret = false;
2427   note_stores (pat, sets_likely_spilled_1, &ret);
2428   return ret;
2429 }
2430
2431 static void
2432 sets_likely_spilled_1 (rtx x, const_rtx pat, void *data)
2433 {
2434   bool *ret = (bool *) data;
2435
2436   if (GET_CODE (pat) == SET
2437       && REG_P (x)
2438       && HARD_REGISTER_P (x)
2439       && targetm.class_likely_spilled_p (REGNO_REG_CLASS (REGNO (x))))
2440     *ret = true;
2441 }
2442
2443 /* A bitmap to note insns that participate in any dependency.  Used in
2444    add_branch_dependences.  */
2445 static sbitmap insn_referenced;
2446
2447 /* Add dependences so that branches are scheduled to run last in their
2448    block.  */
2449 static void
2450 add_branch_dependences (rtx_insn *head, rtx_insn *tail)
2451 {
2452   rtx_insn *insn, *last;
2453
2454   /* For all branches, calls, uses, clobbers, cc0 setters, and instructions
2455      that can throw exceptions, force them to remain in order at the end of
2456      the block by adding dependencies and giving the last a high priority.
2457      There may be notes present, and prev_head may also be a note.
2458
2459      Branches must obviously remain at the end.  Calls should remain at the
2460      end since moving them results in worse register allocation.  Uses remain
2461      at the end to ensure proper register allocation.
2462
2463      cc0 setters remain at the end because they can't be moved away from
2464      their cc0 user.
2465
2466      Predecessors of SCHED_GROUP_P instructions at the end remain at the end.
2467
2468      COND_EXEC insns cannot be moved past a branch (see e.g. PR17808).
2469
2470      Insns setting TARGET_CLASS_LIKELY_SPILLED_P registers (usually return
2471      values) are not moved before reload because we can wind up with register
2472      allocation failures.  */
2473
2474   while (tail != head && DEBUG_INSN_P (tail))
2475     tail = PREV_INSN (tail);
2476
2477   insn = tail;
2478   last = 0;
2479   while (CALL_P (insn)
2480          || JUMP_P (insn) || JUMP_TABLE_DATA_P (insn)
2481          || (NONJUMP_INSN_P (insn)
2482              && (GET_CODE (PATTERN (insn)) == USE
2483                  || GET_CODE (PATTERN (insn)) == CLOBBER
2484                  || can_throw_internal (insn)
2485 #ifdef HAVE_cc0
2486                  || sets_cc0_p (PATTERN (insn))
2487 #endif
2488                  || (!reload_completed
2489                      && sets_likely_spilled (PATTERN (insn)))))
2490          || NOTE_P (insn)
2491          || (last != 0 && SCHED_GROUP_P (last)))
2492     {
2493       if (!NOTE_P (insn))
2494         {
2495           if (last != 0
2496               && sd_find_dep_between (insn, last, false) == NULL)
2497             {
2498               if (! sched_insns_conditions_mutex_p (last, insn))
2499                 add_dependence (last, insn, REG_DEP_ANTI);
2500               bitmap_set_bit (insn_referenced, INSN_LUID (insn));
2501             }
2502
2503           CANT_MOVE (insn) = 1;
2504
2505           last = insn;
2506         }
2507
2508       /* Don't overrun the bounds of the basic block.  */
2509       if (insn == head)
2510         break;
2511
2512       do
2513         insn = PREV_INSN (insn);
2514       while (insn != head && DEBUG_INSN_P (insn));
2515     }
2516
2517   /* Make sure these insns are scheduled last in their block.  */
2518   insn = last;
2519   if (insn != 0)
2520     while (insn != head)
2521       {
2522         insn = prev_nonnote_insn (insn);
2523
2524         if (bitmap_bit_p (insn_referenced, INSN_LUID (insn))
2525             || DEBUG_INSN_P (insn))
2526           continue;
2527
2528         if (! sched_insns_conditions_mutex_p (last, insn))
2529           add_dependence (last, insn, REG_DEP_ANTI);
2530       }
2531
2532   if (!targetm.have_conditional_execution ())
2533     return;
2534
2535   /* Finally, if the block ends in a jump, and we are doing intra-block
2536      scheduling, make sure that the branch depends on any COND_EXEC insns
2537      inside the block to avoid moving the COND_EXECs past the branch insn.
2538
2539      We only have to do this after reload, because (1) before reload there
2540      are no COND_EXEC insns, and (2) the region scheduler is an intra-block
2541      scheduler after reload.
2542
2543      FIXME: We could in some cases move COND_EXEC insns past the branch if
2544      this scheduler would be a little smarter.  Consider this code:
2545
2546                 T = [addr]
2547         C  ?    addr += 4
2548         !C ?    X += 12
2549         C  ?    T += 1
2550         C  ?    jump foo
2551
2552      On a target with a one cycle stall on a memory access the optimal
2553      sequence would be:
2554
2555                 T = [addr]
2556         C  ?    addr += 4
2557         C  ?    T += 1
2558         C  ?    jump foo
2559         !C ?    X += 12
2560
2561      We don't want to put the 'X += 12' before the branch because it just
2562      wastes a cycle of execution time when the branch is taken.
2563
2564      Note that in the example "!C" will always be true.  That is another
2565      possible improvement for handling COND_EXECs in this scheduler: it
2566      could remove always-true predicates.  */
2567
2568   if (!reload_completed || ! (JUMP_P (tail) || JUMP_TABLE_DATA_P (tail)))
2569     return;
2570
2571   insn = tail;
2572   while (insn != head)
2573     {
2574       insn = PREV_INSN (insn);
2575
2576       /* Note that we want to add this dependency even when
2577          sched_insns_conditions_mutex_p returns true.  The whole point
2578          is that we _want_ this dependency, even if these insns really
2579          are independent.  */
2580       if (INSN_P (insn) && GET_CODE (PATTERN (insn)) == COND_EXEC)
2581         add_dependence (tail, insn, REG_DEP_ANTI);
2582     }
2583 }
2584
2585 /* Data structures for the computation of data dependences in a regions.  We
2586    keep one `deps' structure for every basic block.  Before analyzing the
2587    data dependences for a bb, its variables are initialized as a function of
2588    the variables of its predecessors.  When the analysis for a bb completes,
2589    we save the contents to the corresponding bb_deps[bb] variable.  */
2590
2591 static struct deps_desc *bb_deps;
2592
2593 static void
2594 concat_insn_mem_list (rtx_insn_list *copy_insns,
2595                       rtx_expr_list *copy_mems,
2596                       rtx_insn_list **old_insns_p,
2597                       rtx_expr_list **old_mems_p)
2598 {
2599   rtx_insn_list *new_insns = *old_insns_p;
2600   rtx_expr_list *new_mems = *old_mems_p;
2601
2602   while (copy_insns)
2603     {
2604       new_insns = alloc_INSN_LIST (copy_insns->insn (), new_insns);
2605       new_mems = alloc_EXPR_LIST (VOIDmode, copy_mems->element (), new_mems);
2606       copy_insns = copy_insns->next ();
2607       copy_mems = copy_mems->next ();
2608     }
2609
2610   *old_insns_p = new_insns;
2611   *old_mems_p = new_mems;
2612 }
2613
2614 /* Join PRED_DEPS to the SUCC_DEPS.  */
2615 void
2616 deps_join (struct deps_desc *succ_deps, struct deps_desc *pred_deps)
2617 {
2618   unsigned reg;
2619   reg_set_iterator rsi;
2620
2621   /* The reg_last lists are inherited by successor.  */
2622   EXECUTE_IF_SET_IN_REG_SET (&pred_deps->reg_last_in_use, 0, reg, rsi)
2623     {
2624       struct deps_reg *pred_rl = &pred_deps->reg_last[reg];
2625       struct deps_reg *succ_rl = &succ_deps->reg_last[reg];
2626
2627       succ_rl->uses = concat_INSN_LIST (pred_rl->uses, succ_rl->uses);
2628       succ_rl->sets = concat_INSN_LIST (pred_rl->sets, succ_rl->sets);
2629       succ_rl->implicit_sets
2630         = concat_INSN_LIST (pred_rl->implicit_sets, succ_rl->implicit_sets);
2631       succ_rl->clobbers = concat_INSN_LIST (pred_rl->clobbers,
2632                                             succ_rl->clobbers);
2633       succ_rl->uses_length += pred_rl->uses_length;
2634       succ_rl->clobbers_length += pred_rl->clobbers_length;
2635     }
2636   IOR_REG_SET (&succ_deps->reg_last_in_use, &pred_deps->reg_last_in_use);
2637
2638   /* Mem read/write lists are inherited by successor.  */
2639   concat_insn_mem_list (pred_deps->pending_read_insns,
2640                         pred_deps->pending_read_mems,
2641                         &succ_deps->pending_read_insns,
2642                         &succ_deps->pending_read_mems);
2643   concat_insn_mem_list (pred_deps->pending_write_insns,
2644                         pred_deps->pending_write_mems,
2645                         &succ_deps->pending_write_insns,
2646                         &succ_deps->pending_write_mems);
2647
2648   succ_deps->pending_jump_insns
2649     = concat_INSN_LIST (pred_deps->pending_jump_insns,
2650                         succ_deps->pending_jump_insns);
2651   succ_deps->last_pending_memory_flush
2652     = concat_INSN_LIST (pred_deps->last_pending_memory_flush,
2653                         succ_deps->last_pending_memory_flush);
2654
2655   succ_deps->pending_read_list_length += pred_deps->pending_read_list_length;
2656   succ_deps->pending_write_list_length += pred_deps->pending_write_list_length;
2657   succ_deps->pending_flush_length += pred_deps->pending_flush_length;
2658
2659   /* last_function_call is inherited by successor.  */
2660   succ_deps->last_function_call
2661     = concat_INSN_LIST (pred_deps->last_function_call,
2662                         succ_deps->last_function_call);
2663
2664   /* last_function_call_may_noreturn is inherited by successor.  */
2665   succ_deps->last_function_call_may_noreturn
2666     = concat_INSN_LIST (pred_deps->last_function_call_may_noreturn,
2667                         succ_deps->last_function_call_may_noreturn);
2668
2669   /* sched_before_next_call is inherited by successor.  */
2670   succ_deps->sched_before_next_call
2671     = concat_INSN_LIST (pred_deps->sched_before_next_call,
2672                         succ_deps->sched_before_next_call);
2673 }
2674
2675 /* After computing the dependencies for block BB, propagate the dependencies
2676    found in TMP_DEPS to the successors of the block.  */
2677 static void
2678 propagate_deps (int bb, struct deps_desc *pred_deps)
2679 {
2680   basic_block block = BASIC_BLOCK_FOR_FN (cfun, BB_TO_BLOCK (bb));
2681   edge_iterator ei;
2682   edge e;
2683
2684   /* bb's structures are inherited by its successors.  */
2685   FOR_EACH_EDGE (e, ei, block->succs)
2686     {
2687       /* Only bbs "below" bb, in the same region, are interesting.  */
2688       if (e->dest == EXIT_BLOCK_PTR_FOR_FN (cfun)
2689           || CONTAINING_RGN (block->index) != CONTAINING_RGN (e->dest->index)
2690           || BLOCK_TO_BB (e->dest->index) <= bb)
2691         continue;
2692
2693       deps_join (bb_deps + BLOCK_TO_BB (e->dest->index), pred_deps);
2694     }
2695
2696   /* These lists should point to the right place, for correct
2697      freeing later.  */
2698   bb_deps[bb].pending_read_insns = pred_deps->pending_read_insns;
2699   bb_deps[bb].pending_read_mems = pred_deps->pending_read_mems;
2700   bb_deps[bb].pending_write_insns = pred_deps->pending_write_insns;
2701   bb_deps[bb].pending_write_mems = pred_deps->pending_write_mems;
2702   bb_deps[bb].pending_jump_insns = pred_deps->pending_jump_insns;
2703
2704   /* Can't allow these to be freed twice.  */
2705   pred_deps->pending_read_insns = 0;
2706   pred_deps->pending_read_mems = 0;
2707   pred_deps->pending_write_insns = 0;
2708   pred_deps->pending_write_mems = 0;
2709   pred_deps->pending_jump_insns = 0;
2710 }
2711
2712 /* Compute dependences inside bb.  In a multiple blocks region:
2713    (1) a bb is analyzed after its predecessors, and (2) the lists in
2714    effect at the end of bb (after analyzing for bb) are inherited by
2715    bb's successors.
2716
2717    Specifically for reg-reg data dependences, the block insns are
2718    scanned by sched_analyze () top-to-bottom.  Three lists are
2719    maintained by sched_analyze (): reg_last[].sets for register DEFs,
2720    reg_last[].implicit_sets for implicit hard register DEFs, and
2721    reg_last[].uses for register USEs.
2722
2723    When analysis is completed for bb, we update for its successors:
2724    ;  - DEFS[succ] = Union (DEFS [succ], DEFS [bb])
2725    ;  - IMPLICIT_DEFS[succ] = Union (IMPLICIT_DEFS [succ], IMPLICIT_DEFS [bb])
2726    ;  - USES[succ] = Union (USES [succ], DEFS [bb])
2727
2728    The mechanism for computing mem-mem data dependence is very
2729    similar, and the result is interblock dependences in the region.  */
2730
2731 static void
2732 compute_block_dependences (int bb)
2733 {
2734   rtx_insn *head, *tail;
2735   struct deps_desc tmp_deps;
2736
2737   tmp_deps = bb_deps[bb];
2738
2739   /* Do the analysis for this block.  */
2740   gcc_assert (EBB_FIRST_BB (bb) == EBB_LAST_BB (bb));
2741   get_ebb_head_tail (EBB_FIRST_BB (bb), EBB_LAST_BB (bb), &head, &tail);
2742
2743   sched_analyze (&tmp_deps, head, tail);
2744
2745   /* Selective scheduling handles control dependencies by itself.  */
2746   if (!sel_sched_p ())
2747     add_branch_dependences (head, tail);
2748
2749   if (current_nr_blocks > 1)
2750     propagate_deps (bb, &tmp_deps);
2751
2752   /* Free up the INSN_LISTs.  */
2753   free_deps (&tmp_deps);
2754
2755   if (targetm.sched.dependencies_evaluation_hook)
2756     targetm.sched.dependencies_evaluation_hook (head, tail);
2757 }
2758
2759 /* Free dependencies of instructions inside BB.  */
2760 static void
2761 free_block_dependencies (int bb)
2762 {
2763   rtx_insn *head;
2764   rtx_insn *tail;
2765
2766   get_ebb_head_tail (EBB_FIRST_BB (bb), EBB_LAST_BB (bb), &head, &tail);
2767
2768   if (no_real_insns_p (head, tail))
2769     return;
2770
2771   sched_free_deps (head, tail, true);
2772 }
2773
2774 /* Remove all INSN_LISTs and EXPR_LISTs from the pending lists and add
2775    them to the unused_*_list variables, so that they can be reused.  */
2776
2777 static void
2778 free_pending_lists (void)
2779 {
2780   int bb;
2781
2782   for (bb = 0; bb < current_nr_blocks; bb++)
2783     {
2784       free_INSN_LIST_list (&bb_deps[bb].pending_read_insns);
2785       free_INSN_LIST_list (&bb_deps[bb].pending_write_insns);
2786       free_EXPR_LIST_list (&bb_deps[bb].pending_read_mems);
2787       free_EXPR_LIST_list (&bb_deps[bb].pending_write_mems);
2788       free_INSN_LIST_list (&bb_deps[bb].pending_jump_insns);
2789     }
2790 }
2791 \f
2792 /* Print dependences for debugging starting from FROM_BB.
2793    Callable from debugger.  */
2794 /* Print dependences for debugging starting from FROM_BB.
2795    Callable from debugger.  */
2796 DEBUG_FUNCTION void
2797 debug_rgn_dependencies (int from_bb)
2798 {
2799   int bb;
2800
2801   fprintf (sched_dump,
2802            ";;   --------------- forward dependences: ------------ \n");
2803
2804   for (bb = from_bb; bb < current_nr_blocks; bb++)
2805     {
2806       rtx_insn *head, *tail;
2807
2808       get_ebb_head_tail (EBB_FIRST_BB (bb), EBB_LAST_BB (bb), &head, &tail);
2809       fprintf (sched_dump, "\n;;   --- Region Dependences --- b %d bb %d \n",
2810                BB_TO_BLOCK (bb), bb);
2811
2812       debug_dependencies (head, tail);
2813     }
2814 }
2815
2816 /* Print dependencies information for instructions between HEAD and TAIL.
2817    ??? This function would probably fit best in haifa-sched.c.  */
2818 void debug_dependencies (rtx_insn *head, rtx_insn *tail)
2819 {
2820   rtx_insn *insn;
2821   rtx_insn *next_tail = NEXT_INSN (tail);
2822
2823   fprintf (sched_dump, ";;   %7s%6s%6s%6s%6s%6s%14s\n",
2824            "insn", "code", "bb", "dep", "prio", "cost",
2825            "reservation");
2826   fprintf (sched_dump, ";;   %7s%6s%6s%6s%6s%6s%14s\n",
2827            "----", "----", "--", "---", "----", "----",
2828            "-----------");
2829
2830   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
2831     {
2832       if (! INSN_P (insn))
2833         {
2834           int n;
2835           fprintf (sched_dump, ";;   %6d ", INSN_UID (insn));
2836           if (NOTE_P (insn))
2837             {
2838               n = NOTE_KIND (insn);
2839               fprintf (sched_dump, "%s\n", GET_NOTE_INSN_NAME (n));
2840             }
2841           else
2842             fprintf (sched_dump, " {%s}\n", GET_RTX_NAME (GET_CODE (insn)));
2843           continue;
2844         }
2845
2846       fprintf (sched_dump,
2847                ";;   %s%5d%6d%6d%6d%6d%6d   ",
2848                (SCHED_GROUP_P (insn) ? "+" : " "),
2849                INSN_UID (insn),
2850                INSN_CODE (insn),
2851                BLOCK_NUM (insn),
2852                sched_emulate_haifa_p ? -1 : sd_lists_size (insn, SD_LIST_BACK),
2853                (sel_sched_p () ? (sched_emulate_haifa_p ? -1
2854                                : INSN_PRIORITY (insn))
2855                 : INSN_PRIORITY (insn)),
2856                (sel_sched_p () ? (sched_emulate_haifa_p ? -1
2857                                : insn_cost (insn))
2858                 : insn_cost (insn)));
2859
2860       if (recog_memoized (insn) < 0)
2861         fprintf (sched_dump, "nothing");
2862       else
2863         print_reservation (sched_dump, insn);
2864
2865       fprintf (sched_dump, "\t: ");
2866       {
2867         sd_iterator_def sd_it;
2868         dep_t dep;
2869
2870         FOR_EACH_DEP (insn, SD_LIST_FORW, sd_it, dep)
2871           fprintf (sched_dump, "%d%s%s ", INSN_UID (DEP_CON (dep)),
2872                    DEP_NONREG (dep) ? "n" : "",
2873                    DEP_MULTIPLE (dep) ? "m" : "");
2874       }
2875       fprintf (sched_dump, "\n");
2876     }
2877
2878   fprintf (sched_dump, "\n");
2879 }
2880 \f
2881 /* Returns true if all the basic blocks of the current region have
2882    NOTE_DISABLE_SCHED_OF_BLOCK which means not to schedule that region.  */
2883 bool
2884 sched_is_disabled_for_current_region_p (void)
2885 {
2886   int bb;
2887
2888   for (bb = 0; bb < current_nr_blocks; bb++)
2889     if (!(BASIC_BLOCK_FOR_FN (cfun,
2890                               BB_TO_BLOCK (bb))->flags & BB_DISABLE_SCHEDULE))
2891       return false;
2892
2893   return true;
2894 }
2895
2896 /* Free all region dependencies saved in INSN_BACK_DEPS and
2897    INSN_RESOLVED_BACK_DEPS.  The Haifa scheduler does this on the fly
2898    when scheduling, so this function is supposed to be called from
2899    the selective scheduling only.  */
2900 void
2901 free_rgn_deps (void)
2902 {
2903   int bb;
2904
2905   for (bb = 0; bb < current_nr_blocks; bb++)
2906     {
2907       rtx_insn *head, *tail;
2908
2909       gcc_assert (EBB_FIRST_BB (bb) == EBB_LAST_BB (bb));
2910       get_ebb_head_tail (EBB_FIRST_BB (bb), EBB_LAST_BB (bb), &head, &tail);
2911
2912       sched_free_deps (head, tail, false);
2913     }
2914 }
2915
2916 static int rgn_n_insns;
2917
2918 /* Compute insn priority for a current region.  */
2919 void
2920 compute_priorities (void)
2921 {
2922   int bb;
2923
2924   current_sched_info->sched_max_insns_priority = 0;
2925   for (bb = 0; bb < current_nr_blocks; bb++)
2926     {
2927       rtx_insn *head, *tail;
2928
2929       gcc_assert (EBB_FIRST_BB (bb) == EBB_LAST_BB (bb));
2930       get_ebb_head_tail (EBB_FIRST_BB (bb), EBB_LAST_BB (bb), &head, &tail);
2931
2932       if (no_real_insns_p (head, tail))
2933         continue;
2934
2935       rgn_n_insns += set_priorities (head, tail);
2936     }
2937   current_sched_info->sched_max_insns_priority++;
2938 }
2939
2940 /* (Re-)initialize the arrays of DFA states at the end of each basic block.
2941
2942    SAVED_LAST_BASIC_BLOCK is the previous length of the arrays.  It must be
2943    zero for the first call to this function, to allocate the arrays for the
2944    first time.
2945
2946    This function is called once during initialization of the scheduler, and
2947    called again to resize the arrays if new basic blocks have been created,
2948    for example for speculation recovery code.  */
2949
2950 static void
2951 realloc_bb_state_array (int saved_last_basic_block)
2952 {
2953   char *old_bb_state_array = bb_state_array;
2954   size_t lbb = (size_t) last_basic_block_for_fn (cfun);
2955   size_t slbb = (size_t) saved_last_basic_block;
2956
2957   /* Nothing to do if nothing changed since the last time this was called.  */
2958   if (saved_last_basic_block == last_basic_block_for_fn (cfun))
2959     return;
2960
2961   /* The selective scheduler doesn't use the state arrays.  */
2962   if (sel_sched_p ())
2963     {
2964       gcc_assert (bb_state_array == NULL && bb_state == NULL);
2965       return;
2966     }
2967
2968   gcc_checking_assert (saved_last_basic_block == 0
2969                        || (bb_state_array != NULL && bb_state != NULL));
2970
2971   bb_state_array = XRESIZEVEC (char, bb_state_array, lbb * dfa_state_size);
2972   bb_state = XRESIZEVEC (state_t, bb_state, lbb);
2973
2974   /* If BB_STATE_ARRAY has moved, fixup all the state pointers array.
2975      Otherwise only fixup the newly allocated ones.  For the state
2976      array itself, only initialize the new entries.  */
2977   bool bb_state_array_moved = (bb_state_array != old_bb_state_array);
2978   for (size_t i = bb_state_array_moved ? 0 : slbb; i < lbb; i++)
2979     bb_state[i] = (state_t) (bb_state_array + i * dfa_state_size);
2980   for (size_t i = slbb; i < lbb; i++)
2981     state_reset (bb_state[i]);
2982 }
2983
2984 /* Free the arrays of DFA states at the end of each basic block.  */
2985
2986 static void
2987 free_bb_state_array (void)
2988 {
2989   free (bb_state_array);
2990   free (bb_state);
2991   bb_state_array = NULL;
2992   bb_state = NULL;
2993 }
2994
2995 /* Schedule a region.  A region is either an inner loop, a loop-free
2996    subroutine, or a single basic block.  Each bb in the region is
2997    scheduled after its flow predecessors.  */
2998
2999 static void
3000 schedule_region (int rgn)
3001 {
3002   int bb;
3003   int sched_rgn_n_insns = 0;
3004
3005   rgn_n_insns = 0;
3006
3007   /* Do not support register pressure sensitive scheduling for the new regions
3008      as we don't update the liveness info for them.  */
3009   if (sched_pressure != SCHED_PRESSURE_NONE
3010       && rgn >= nr_regions_initial)
3011     {
3012       free_global_sched_pressure_data ();
3013       sched_pressure = SCHED_PRESSURE_NONE;
3014     }
3015
3016   rgn_setup_region (rgn);
3017
3018   /* Don't schedule region that is marked by
3019      NOTE_DISABLE_SCHED_OF_BLOCK.  */
3020   if (sched_is_disabled_for_current_region_p ())
3021     return;
3022
3023   sched_rgn_compute_dependencies (rgn);
3024
3025   sched_rgn_local_init (rgn);
3026
3027   /* Set priorities.  */
3028   compute_priorities ();
3029
3030   sched_extend_ready_list (rgn_n_insns);
3031
3032   if (sched_pressure == SCHED_PRESSURE_WEIGHTED)
3033     {
3034       sched_init_region_reg_pressure_info ();
3035       for (bb = 0; bb < current_nr_blocks; bb++)
3036         {
3037           basic_block first_bb, last_bb;
3038           rtx_insn *head, *tail;
3039
3040           first_bb = EBB_FIRST_BB (bb);
3041           last_bb = EBB_LAST_BB (bb);
3042
3043           get_ebb_head_tail (first_bb, last_bb, &head, &tail);
3044
3045           if (no_real_insns_p (head, tail))
3046             {
3047               gcc_assert (first_bb == last_bb);
3048               continue;
3049             }
3050           sched_setup_bb_reg_pressure_info (first_bb, PREV_INSN (head));
3051         }
3052     }
3053
3054   /* Now we can schedule all blocks.  */
3055   for (bb = 0; bb < current_nr_blocks; bb++)
3056     {
3057       basic_block first_bb, last_bb, curr_bb;
3058       rtx_insn *head, *tail;
3059
3060       first_bb = EBB_FIRST_BB (bb);
3061       last_bb = EBB_LAST_BB (bb);
3062
3063       get_ebb_head_tail (first_bb, last_bb, &head, &tail);
3064
3065       if (no_real_insns_p (head, tail))
3066         {
3067           gcc_assert (first_bb == last_bb);
3068           continue;
3069         }
3070
3071       current_sched_info->prev_head = PREV_INSN (head);
3072       current_sched_info->next_tail = NEXT_INSN (tail);
3073
3074       remove_notes (head, tail);
3075
3076       unlink_bb_notes (first_bb, last_bb);
3077
3078       target_bb = bb;
3079
3080       gcc_assert (flag_schedule_interblock || current_nr_blocks == 1);
3081       current_sched_info->queue_must_finish_empty = current_nr_blocks == 1;
3082
3083       curr_bb = first_bb;
3084       if (dbg_cnt (sched_block))
3085         {
3086           edge f;
3087           int saved_last_basic_block = last_basic_block_for_fn (cfun);
3088
3089           schedule_block (&curr_bb, bb_state[first_bb->index]);
3090           gcc_assert (EBB_FIRST_BB (bb) == first_bb);
3091           sched_rgn_n_insns += sched_n_insns;
3092           realloc_bb_state_array (saved_last_basic_block);
3093           f = find_fallthru_edge (last_bb->succs);
3094           if (f && f->probability * 100 / REG_BR_PROB_BASE >=
3095               PARAM_VALUE (PARAM_SCHED_STATE_EDGE_PROB_CUTOFF))
3096             {
3097               memcpy (bb_state[f->dest->index], curr_state,
3098                       dfa_state_size);
3099               if (sched_verbose >= 5)
3100                 fprintf (sched_dump, "saving state for edge %d->%d\n",
3101                          f->src->index, f->dest->index);
3102             }
3103         }
3104       else
3105         {
3106           sched_rgn_n_insns += rgn_n_insns;
3107         }
3108
3109       /* Clean up.  */
3110       if (current_nr_blocks > 1)
3111         free_trg_info ();
3112     }
3113
3114   /* Sanity check: verify that all region insns were scheduled.  */
3115   gcc_assert (sched_rgn_n_insns == rgn_n_insns);
3116
3117   sched_finish_ready_list ();
3118
3119   /* Done with this region.  */
3120   sched_rgn_local_finish ();
3121
3122   /* Free dependencies.  */
3123   for (bb = 0; bb < current_nr_blocks; ++bb)
3124     free_block_dependencies (bb);
3125
3126   gcc_assert (haifa_recovery_bb_ever_added_p
3127               || deps_pools_are_empty_p ());
3128 }
3129
3130 /* Initialize data structures for region scheduling.  */
3131
3132 void
3133 sched_rgn_init (bool single_blocks_p)
3134 {
3135   min_spec_prob = ((PARAM_VALUE (PARAM_MIN_SPEC_PROB) * REG_BR_PROB_BASE)
3136                     / 100);
3137
3138   nr_inter = 0;
3139   nr_spec = 0;
3140
3141   extend_regions ();
3142
3143   CONTAINING_RGN (ENTRY_BLOCK) = -1;
3144   CONTAINING_RGN (EXIT_BLOCK) = -1;
3145
3146   realloc_bb_state_array (0);
3147
3148   /* Compute regions for scheduling.  */
3149   if (single_blocks_p
3150       || n_basic_blocks_for_fn (cfun) == NUM_FIXED_BLOCKS + 1
3151       || !flag_schedule_interblock
3152       || is_cfg_nonregular ())
3153     {
3154       find_single_block_region (sel_sched_p ());
3155     }
3156   else
3157     {
3158       /* Compute the dominators and post dominators.  */
3159       if (!sel_sched_p ())
3160         calculate_dominance_info (CDI_DOMINATORS);
3161
3162       /* Find regions.  */
3163       find_rgns ();
3164
3165       if (sched_verbose >= 3)
3166         debug_regions ();
3167
3168       /* For now.  This will move as more and more of haifa is converted
3169          to using the cfg code.  */
3170       if (!sel_sched_p ())
3171         free_dominance_info (CDI_DOMINATORS);
3172     }
3173
3174   gcc_assert (0 < nr_regions && nr_regions <= n_basic_blocks_for_fn (cfun));
3175
3176   RGN_BLOCKS (nr_regions) = (RGN_BLOCKS (nr_regions - 1) +
3177                              RGN_NR_BLOCKS (nr_regions - 1));
3178   nr_regions_initial = nr_regions;
3179 }
3180
3181 /* Free data structures for region scheduling.  */
3182 void
3183 sched_rgn_finish (void)
3184 {
3185   free_bb_state_array ();
3186
3187   /* Reposition the prologue and epilogue notes in case we moved the
3188      prologue/epilogue insns.  */
3189   if (reload_completed)
3190     reposition_prologue_and_epilogue_notes ();
3191
3192   if (sched_verbose)
3193     {
3194       if (reload_completed == 0
3195           && flag_schedule_interblock)
3196         {
3197           fprintf (sched_dump,
3198                    "\n;; Procedure interblock/speculative motions == %d/%d \n",
3199                    nr_inter, nr_spec);
3200         }
3201       else
3202         gcc_assert (nr_inter <= 0);
3203       fprintf (sched_dump, "\n\n");
3204     }
3205
3206   nr_regions = 0;
3207
3208   free (rgn_table);
3209   rgn_table = NULL;
3210
3211   free (rgn_bb_table);
3212   rgn_bb_table = NULL;
3213
3214   free (block_to_bb);
3215   block_to_bb = NULL;
3216
3217   free (containing_rgn);
3218   containing_rgn = NULL;
3219
3220   free (ebb_head);
3221   ebb_head = NULL;
3222 }
3223
3224 /* Setup global variables like CURRENT_BLOCKS and CURRENT_NR_BLOCK to
3225    point to the region RGN.  */
3226 void
3227 rgn_setup_region (int rgn)
3228 {
3229   int bb;
3230
3231   /* Set variables for the current region.  */
3232   current_nr_blocks = RGN_NR_BLOCKS (rgn);
3233   current_blocks = RGN_BLOCKS (rgn);
3234
3235   /* EBB_HEAD is a region-scope structure.  But we realloc it for
3236      each region to save time/memory/something else.
3237      See comments in add_block1, for what reasons we allocate +1 element.  */
3238   ebb_head = XRESIZEVEC (int, ebb_head, current_nr_blocks + 1);
3239   for (bb = 0; bb <= current_nr_blocks; bb++)
3240     ebb_head[bb] = current_blocks + bb;
3241 }
3242
3243 /* Compute instruction dependencies in region RGN.  */
3244 void
3245 sched_rgn_compute_dependencies (int rgn)
3246 {
3247   if (!RGN_DONT_CALC_DEPS (rgn))
3248     {
3249       int bb;
3250
3251       if (sel_sched_p ())
3252         sched_emulate_haifa_p = 1;
3253
3254       init_deps_global ();
3255
3256       /* Initializations for region data dependence analysis.  */
3257       bb_deps = XNEWVEC (struct deps_desc, current_nr_blocks);
3258       for (bb = 0; bb < current_nr_blocks; bb++)
3259         init_deps (bb_deps + bb, false);
3260
3261       /* Initialize bitmap used in add_branch_dependences.  */
3262       insn_referenced = sbitmap_alloc (sched_max_luid);
3263       bitmap_clear (insn_referenced);
3264
3265       /* Compute backward dependencies.  */
3266       for (bb = 0; bb < current_nr_blocks; bb++)
3267         compute_block_dependences (bb);
3268
3269       sbitmap_free (insn_referenced);
3270       free_pending_lists ();
3271       finish_deps_global ();
3272       free (bb_deps);
3273
3274       /* We don't want to recalculate this twice.  */
3275       RGN_DONT_CALC_DEPS (rgn) = 1;
3276
3277       if (sel_sched_p ())
3278         sched_emulate_haifa_p = 0;
3279     }
3280   else
3281     /* (This is a recovery block.  It is always a single block region.)
3282        OR (We use selective scheduling.)  */
3283     gcc_assert (current_nr_blocks == 1 || sel_sched_p ());
3284 }
3285
3286 /* Init region data structures.  Returns true if this region should
3287    not be scheduled.  */
3288 void
3289 sched_rgn_local_init (int rgn)
3290 {
3291   int bb;
3292
3293   /* Compute interblock info: probabilities, split-edges, dominators, etc.  */
3294   if (current_nr_blocks > 1)
3295     {
3296       basic_block block;
3297       edge e;
3298       edge_iterator ei;
3299
3300       prob = XNEWVEC (int, current_nr_blocks);
3301
3302       dom = sbitmap_vector_alloc (current_nr_blocks, current_nr_blocks);
3303       bitmap_vector_clear (dom, current_nr_blocks);
3304
3305       /* Use ->aux to implement EDGE_TO_BIT mapping.  */
3306       rgn_nr_edges = 0;
3307       FOR_EACH_BB_FN (block, cfun)
3308         {
3309           if (CONTAINING_RGN (block->index) != rgn)
3310             continue;
3311           FOR_EACH_EDGE (e, ei, block->succs)
3312             SET_EDGE_TO_BIT (e, rgn_nr_edges++);
3313         }
3314
3315       rgn_edges = XNEWVEC (edge, rgn_nr_edges);
3316       rgn_nr_edges = 0;
3317       FOR_EACH_BB_FN (block, cfun)
3318         {
3319           if (CONTAINING_RGN (block->index) != rgn)
3320             continue;
3321           FOR_EACH_EDGE (e, ei, block->succs)
3322             rgn_edges[rgn_nr_edges++] = e;
3323         }
3324
3325       /* Split edges.  */
3326       pot_split = sbitmap_vector_alloc (current_nr_blocks, rgn_nr_edges);
3327       bitmap_vector_clear (pot_split, current_nr_blocks);
3328       ancestor_edges = sbitmap_vector_alloc (current_nr_blocks, rgn_nr_edges);
3329       bitmap_vector_clear (ancestor_edges, current_nr_blocks);
3330
3331       /* Compute probabilities, dominators, split_edges.  */
3332       for (bb = 0; bb < current_nr_blocks; bb++)
3333         compute_dom_prob_ps (bb);
3334
3335       /* Cleanup ->aux used for EDGE_TO_BIT mapping.  */
3336       /* We don't need them anymore.  But we want to avoid duplication of
3337          aux fields in the newly created edges.  */
3338       FOR_EACH_BB_FN (block, cfun)
3339         {
3340           if (CONTAINING_RGN (block->index) != rgn)
3341             continue;
3342           FOR_EACH_EDGE (e, ei, block->succs)
3343             e->aux = NULL;
3344         }
3345     }
3346 }
3347
3348 /* Free data computed for the finished region.  */
3349 void
3350 sched_rgn_local_free (void)
3351 {
3352   free (prob);
3353   sbitmap_vector_free (dom);
3354   sbitmap_vector_free (pot_split);
3355   sbitmap_vector_free (ancestor_edges);
3356   free (rgn_edges);
3357 }
3358
3359 /* Free data computed for the finished region.  */
3360 void
3361 sched_rgn_local_finish (void)
3362 {
3363   if (current_nr_blocks > 1 && !sel_sched_p ())
3364     {
3365       sched_rgn_local_free ();
3366     }
3367 }
3368
3369 /* Setup scheduler infos.  */
3370 void
3371 rgn_setup_common_sched_info (void)
3372 {
3373   memcpy (&rgn_common_sched_info, &haifa_common_sched_info,
3374           sizeof (rgn_common_sched_info));
3375
3376   rgn_common_sched_info.fix_recovery_cfg = rgn_fix_recovery_cfg;
3377   rgn_common_sched_info.add_block = rgn_add_block;
3378   rgn_common_sched_info.estimate_number_of_insns
3379     = rgn_estimate_number_of_insns;
3380   rgn_common_sched_info.sched_pass_id = SCHED_RGN_PASS;
3381
3382   common_sched_info = &rgn_common_sched_info;
3383 }
3384
3385 /* Setup all *_sched_info structures (for the Haifa frontend
3386    and for the dependence analysis) in the interblock scheduler.  */
3387 void
3388 rgn_setup_sched_infos (void)
3389 {
3390   if (!sel_sched_p ())
3391     memcpy (&rgn_sched_deps_info, &rgn_const_sched_deps_info,
3392             sizeof (rgn_sched_deps_info));
3393   else
3394     memcpy (&rgn_sched_deps_info, &rgn_const_sel_sched_deps_info,
3395             sizeof (rgn_sched_deps_info));
3396
3397   sched_deps_info = &rgn_sched_deps_info;
3398
3399   memcpy (&rgn_sched_info, &rgn_const_sched_info, sizeof (rgn_sched_info));
3400   current_sched_info = &rgn_sched_info;
3401 }
3402
3403 /* The one entry point in this file.  */
3404 void
3405 schedule_insns (void)
3406 {
3407   int rgn;
3408
3409   /* Taking care of this degenerate case makes the rest of
3410      this code simpler.  */
3411   if (n_basic_blocks_for_fn (cfun) == NUM_FIXED_BLOCKS)
3412     return;
3413
3414   rgn_setup_common_sched_info ();
3415   rgn_setup_sched_infos ();
3416
3417   haifa_sched_init ();
3418   sched_rgn_init (reload_completed);
3419
3420   bitmap_initialize (&not_in_df, 0);
3421   bitmap_clear (&not_in_df);
3422
3423   /* Schedule every region in the subroutine.  */
3424   for (rgn = 0; rgn < nr_regions; rgn++)
3425     if (dbg_cnt (sched_region))
3426       schedule_region (rgn);
3427
3428   /* Clean up.  */
3429   sched_rgn_finish ();
3430   bitmap_clear (&not_in_df);
3431
3432   haifa_sched_finish ();
3433 }
3434
3435 /* INSN has been added to/removed from current region.  */
3436 static void
3437 rgn_add_remove_insn (rtx_insn *insn, int remove_p)
3438 {
3439   if (!remove_p)
3440     rgn_n_insns++;
3441   else
3442     rgn_n_insns--;
3443
3444   if (INSN_BB (insn) == target_bb)
3445     {
3446       if (!remove_p)
3447         target_n_insns++;
3448       else
3449         target_n_insns--;
3450     }
3451 }
3452
3453 /* Extend internal data structures.  */
3454 void
3455 extend_regions (void)
3456 {
3457   rgn_table = XRESIZEVEC (region, rgn_table, n_basic_blocks_for_fn (cfun));
3458   rgn_bb_table = XRESIZEVEC (int, rgn_bb_table,
3459                              n_basic_blocks_for_fn (cfun));
3460   block_to_bb = XRESIZEVEC (int, block_to_bb,
3461                             last_basic_block_for_fn (cfun));
3462   containing_rgn = XRESIZEVEC (int, containing_rgn,
3463                                last_basic_block_for_fn (cfun));
3464 }
3465
3466 void
3467 rgn_make_new_region_out_of_new_block (basic_block bb)
3468 {
3469   int i;
3470
3471   i = RGN_BLOCKS (nr_regions);
3472   /* I - first free position in rgn_bb_table.  */
3473
3474   rgn_bb_table[i] = bb->index;
3475   RGN_NR_BLOCKS (nr_regions) = 1;
3476   RGN_HAS_REAL_EBB (nr_regions) = 0;
3477   RGN_DONT_CALC_DEPS (nr_regions) = 0;
3478   CONTAINING_RGN (bb->index) = nr_regions;
3479   BLOCK_TO_BB (bb->index) = 0;
3480
3481   nr_regions++;
3482
3483   RGN_BLOCKS (nr_regions) = i + 1;
3484 }
3485
3486 /* BB was added to ebb after AFTER.  */
3487 static void
3488 rgn_add_block (basic_block bb, basic_block after)
3489 {
3490   extend_regions ();
3491   bitmap_set_bit (&not_in_df, bb->index);
3492
3493   if (after == 0 || after == EXIT_BLOCK_PTR_FOR_FN (cfun))
3494     {
3495       rgn_make_new_region_out_of_new_block (bb);
3496       RGN_DONT_CALC_DEPS (nr_regions - 1) = (after
3497                                              == EXIT_BLOCK_PTR_FOR_FN (cfun));
3498     }
3499   else
3500     {
3501       int i, pos;
3502
3503       /* We need to fix rgn_table, block_to_bb, containing_rgn
3504          and ebb_head.  */
3505
3506       BLOCK_TO_BB (bb->index) = BLOCK_TO_BB (after->index);
3507
3508       /* We extend ebb_head to one more position to
3509          easily find the last position of the last ebb in
3510          the current region.  Thus, ebb_head[BLOCK_TO_BB (after) + 1]
3511          is _always_ valid for access.  */
3512
3513       i = BLOCK_TO_BB (after->index) + 1;
3514       pos = ebb_head[i] - 1;
3515       /* Now POS is the index of the last block in the region.  */
3516
3517       /* Find index of basic block AFTER.  */
3518       for (; rgn_bb_table[pos] != after->index; pos--)
3519         ;
3520
3521       pos++;
3522       gcc_assert (pos > ebb_head[i - 1]);
3523
3524       /* i - ebb right after "AFTER".  */
3525       /* ebb_head[i] - VALID.  */
3526
3527       /* Source position: ebb_head[i]
3528          Destination position: ebb_head[i] + 1
3529          Last position:
3530            RGN_BLOCKS (nr_regions) - 1
3531          Number of elements to copy: (last_position) - (source_position) + 1
3532        */
3533
3534       memmove (rgn_bb_table + pos + 1,
3535                rgn_bb_table + pos,
3536                ((RGN_BLOCKS (nr_regions) - 1) - (pos) + 1)
3537                * sizeof (*rgn_bb_table));
3538
3539       rgn_bb_table[pos] = bb->index;
3540
3541       for (; i <= current_nr_blocks; i++)
3542         ebb_head [i]++;
3543
3544       i = CONTAINING_RGN (after->index);
3545       CONTAINING_RGN (bb->index) = i;
3546
3547       RGN_HAS_REAL_EBB (i) = 1;
3548
3549       for (++i; i <= nr_regions; i++)
3550         RGN_BLOCKS (i)++;
3551     }
3552 }
3553
3554 /* Fix internal data after interblock movement of jump instruction.
3555    For parameter meaning please refer to
3556    sched-int.h: struct sched_info: fix_recovery_cfg.  */
3557 static void
3558 rgn_fix_recovery_cfg (int bbi, int check_bbi, int check_bb_nexti)
3559 {
3560   int old_pos, new_pos, i;
3561
3562   BLOCK_TO_BB (check_bb_nexti) = BLOCK_TO_BB (bbi);
3563
3564   for (old_pos = ebb_head[BLOCK_TO_BB (check_bbi) + 1] - 1;
3565        rgn_bb_table[old_pos] != check_bb_nexti;
3566        old_pos--)
3567     ;
3568   gcc_assert (old_pos > ebb_head[BLOCK_TO_BB (check_bbi)]);
3569
3570   for (new_pos = ebb_head[BLOCK_TO_BB (bbi) + 1] - 1;
3571        rgn_bb_table[new_pos] != bbi;
3572        new_pos--)
3573     ;
3574   new_pos++;
3575   gcc_assert (new_pos > ebb_head[BLOCK_TO_BB (bbi)]);
3576
3577   gcc_assert (new_pos < old_pos);
3578
3579   memmove (rgn_bb_table + new_pos + 1,
3580            rgn_bb_table + new_pos,
3581            (old_pos - new_pos) * sizeof (*rgn_bb_table));
3582
3583   rgn_bb_table[new_pos] = check_bb_nexti;
3584
3585   for (i = BLOCK_TO_BB (bbi) + 1; i <= BLOCK_TO_BB (check_bbi); i++)
3586     ebb_head[i]++;
3587 }
3588
3589 /* Return next block in ebb chain.  For parameter meaning please refer to
3590    sched-int.h: struct sched_info: advance_target_bb.  */
3591 static basic_block
3592 advance_target_bb (basic_block bb, rtx_insn *insn)
3593 {
3594   if (insn)
3595     return 0;
3596
3597   gcc_assert (BLOCK_TO_BB (bb->index) == target_bb
3598               && BLOCK_TO_BB (bb->next_bb->index) == target_bb);
3599   return bb->next_bb;
3600 }
3601
3602 #endif
3603 \f
3604 /* Run instruction scheduler.  */
3605 static unsigned int
3606 rest_of_handle_live_range_shrinkage (void)
3607 {
3608 #ifdef INSN_SCHEDULING
3609   int saved;
3610
3611   initialize_live_range_shrinkage ();
3612   saved = flag_schedule_interblock;
3613   flag_schedule_interblock = false;
3614   schedule_insns ();
3615   flag_schedule_interblock = saved;
3616   finish_live_range_shrinkage ();
3617 #endif
3618   return 0;
3619 }
3620
3621 /* Run instruction scheduler.  */
3622 static unsigned int
3623 rest_of_handle_sched (void)
3624 {
3625 #ifdef INSN_SCHEDULING
3626   if (flag_selective_scheduling
3627       && ! maybe_skip_selective_scheduling ())
3628     run_selective_scheduling ();
3629   else
3630     schedule_insns ();
3631 #endif
3632   return 0;
3633 }
3634
3635 /* Run second scheduling pass after reload.  */
3636 static unsigned int
3637 rest_of_handle_sched2 (void)
3638 {
3639 #ifdef INSN_SCHEDULING
3640   if (flag_selective_scheduling2
3641       && ! maybe_skip_selective_scheduling ())
3642     run_selective_scheduling ();
3643   else
3644     {
3645       /* Do control and data sched analysis again,
3646          and write some more of the results to dump file.  */
3647       if (flag_sched2_use_superblocks)
3648         schedule_ebbs ();
3649       else
3650         schedule_insns ();
3651     }
3652 #endif
3653   return 0;
3654 }
3655
3656 namespace {
3657
3658 const pass_data pass_data_live_range_shrinkage =
3659 {
3660   RTL_PASS, /* type */
3661   "lr_shrinkage", /* name */
3662   OPTGROUP_NONE, /* optinfo_flags */
3663   TV_LIVE_RANGE_SHRINKAGE, /* tv_id */
3664   0, /* properties_required */
3665   0, /* properties_provided */
3666   0, /* properties_destroyed */
3667   0, /* todo_flags_start */
3668   TODO_df_finish, /* todo_flags_finish */
3669 };
3670
3671 class pass_live_range_shrinkage : public rtl_opt_pass
3672 {
3673 public:
3674   pass_live_range_shrinkage(gcc::context *ctxt)
3675     : rtl_opt_pass(pass_data_live_range_shrinkage, ctxt)
3676   {}
3677
3678   /* opt_pass methods: */
3679   virtual bool gate (function *)
3680     {
3681 #ifdef INSN_SCHEDULING
3682       return flag_live_range_shrinkage;
3683 #else
3684       return 0;
3685 #endif
3686     }
3687
3688   virtual unsigned int execute (function *)
3689     {
3690       return rest_of_handle_live_range_shrinkage ();
3691     }
3692
3693 }; // class pass_live_range_shrinkage
3694
3695 } // anon namespace
3696
3697 rtl_opt_pass *
3698 make_pass_live_range_shrinkage (gcc::context *ctxt)
3699 {
3700   return new pass_live_range_shrinkage (ctxt);
3701 }
3702
3703 namespace {
3704
3705 const pass_data pass_data_sched =
3706 {
3707   RTL_PASS, /* type */
3708   "sched1", /* name */
3709   OPTGROUP_NONE, /* optinfo_flags */
3710   TV_SCHED, /* tv_id */
3711   0, /* properties_required */
3712   0, /* properties_provided */
3713   0, /* properties_destroyed */
3714   0, /* todo_flags_start */
3715   TODO_df_finish, /* todo_flags_finish */
3716 };
3717
3718 class pass_sched : public rtl_opt_pass
3719 {
3720 public:
3721   pass_sched (gcc::context *ctxt)
3722     : rtl_opt_pass (pass_data_sched, ctxt)
3723   {}
3724
3725   /* opt_pass methods: */
3726   virtual bool gate (function *);
3727   virtual unsigned int execute (function *) { return rest_of_handle_sched (); }
3728
3729 }; // class pass_sched
3730
3731 bool
3732 pass_sched::gate (function *)
3733 {
3734 #ifdef INSN_SCHEDULING
3735   return optimize > 0 && flag_schedule_insns && dbg_cnt (sched_func);
3736 #else
3737   return 0;
3738 #endif
3739 }
3740
3741 } // anon namespace
3742
3743 rtl_opt_pass *
3744 make_pass_sched (gcc::context *ctxt)
3745 {
3746   return new pass_sched (ctxt);
3747 }
3748
3749 namespace {
3750
3751 const pass_data pass_data_sched2 =
3752 {
3753   RTL_PASS, /* type */
3754   "sched2", /* name */
3755   OPTGROUP_NONE, /* optinfo_flags */
3756   TV_SCHED2, /* tv_id */
3757   0, /* properties_required */
3758   0, /* properties_provided */
3759   0, /* properties_destroyed */
3760   0, /* todo_flags_start */
3761   TODO_df_finish, /* todo_flags_finish */
3762 };
3763
3764 class pass_sched2 : public rtl_opt_pass
3765 {
3766 public:
3767   pass_sched2 (gcc::context *ctxt)
3768     : rtl_opt_pass (pass_data_sched2, ctxt)
3769   {}
3770
3771   /* opt_pass methods: */
3772   virtual bool gate (function *);
3773   virtual unsigned int execute (function *)
3774     {
3775       return rest_of_handle_sched2 ();
3776     }
3777
3778 }; // class pass_sched2
3779
3780 bool
3781 pass_sched2::gate (function *)
3782 {
3783 #ifdef INSN_SCHEDULING
3784   return optimize > 0 && flag_schedule_insns_after_reload
3785     && !targetm.delay_sched2 && dbg_cnt (sched2_func);
3786 #else
3787   return 0;
3788 #endif
3789 }
3790
3791 } // anon namespace
3792
3793 rtl_opt_pass *
3794 make_pass_sched2 (gcc::context *ctxt)
3795 {
3796   return new pass_sched2 (ctxt);
3797 }