OSDN Git Service

2010-11-13 Tobias Burnus <burnus@net-b.de>
[pf3gnuchains/gcc-fork.git] / gcc / sel-sched-ir.c
1 /* Instruction scheduling pass.  Selective scheduler and pipeliner.
2    Copyright (C) 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
10
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3.  If not see
18 <http://www.gnu.org/licenses/>.  */
19
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "tm.h"
24 #include "diagnostic-core.h"
25 #include "toplev.h"
26 #include "rtl.h"
27 #include "tm_p.h"
28 #include "hard-reg-set.h"
29 #include "regs.h"
30 #include "function.h"
31 #include "flags.h"
32 #include "insn-config.h"
33 #include "insn-attr.h"
34 #include "except.h"
35 #include "toplev.h"
36 #include "recog.h"
37 #include "params.h"
38 #include "target.h"
39 #include "timevar.h"
40 #include "tree-pass.h"
41 #include "sched-int.h"
42 #include "ggc.h"
43 #include "tree.h"
44 #include "vec.h"
45 #include "langhooks.h"
46 #include "rtlhooks-def.h"
47 #include "emit-rtl.h"  /* FIXME: Can go away once crtl is moved to rtl.h.  */
48
49 #ifdef INSN_SCHEDULING
50 #include "sel-sched-ir.h"
51 /* We don't have to use it except for sel_print_insn.  */
52 #include "sel-sched-dump.h"
53
54 /* A vector holding bb info for whole scheduling pass.  */
55 VEC(sel_global_bb_info_def, heap) *sel_global_bb_info = NULL;
56
57 /* A vector holding bb info.  */
58 VEC(sel_region_bb_info_def, heap) *sel_region_bb_info = NULL;
59
60 /* A pool for allocating all lists.  */
61 alloc_pool sched_lists_pool;
62
63 /* This contains information about successors for compute_av_set.  */
64 struct succs_info current_succs;
65
66 /* Data structure to describe interaction with the generic scheduler utils.  */
67 static struct common_sched_info_def sel_common_sched_info;
68
69 /* The loop nest being pipelined.  */
70 struct loop *current_loop_nest;
71
72 /* LOOP_NESTS is a vector containing the corresponding loop nest for
73    each region.  */
74 static VEC(loop_p, heap) *loop_nests = NULL;
75
76 /* Saves blocks already in loop regions, indexed by bb->index.  */
77 static sbitmap bbs_in_loop_rgns = NULL;
78
79 /* CFG hooks that are saved before changing create_basic_block hook.  */
80 static struct cfg_hooks orig_cfg_hooks;
81 \f
82
83 /* Array containing reverse topological index of function basic blocks,
84    indexed by BB->INDEX.  */
85 static int *rev_top_order_index = NULL;
86
87 /* Length of the above array.  */
88 static int rev_top_order_index_len = -1;
89
90 /* A regset pool structure.  */
91 static struct
92 {
93   /* The stack to which regsets are returned.  */
94   regset *v;
95
96   /* Its pointer.  */
97   int n;
98
99   /* Its size.  */
100   int s;
101
102   /* In VV we save all generated regsets so that, when destructing the
103      pool, we can compare it with V and check that every regset was returned
104      back to pool.  */
105   regset *vv;
106
107   /* The pointer of VV stack.  */
108   int nn;
109
110   /* Its size.  */
111   int ss;
112
113   /* The difference between allocated and returned regsets.  */
114   int diff;
115 } regset_pool = { NULL, 0, 0, NULL, 0, 0, 0 };
116
117 /* This represents the nop pool.  */
118 static struct
119 {
120   /* The vector which holds previously emitted nops.  */
121   insn_t *v;
122
123   /* Its pointer.  */
124   int n;
125
126   /* Its size.  */
127   int s;
128 } nop_pool = { NULL, 0, 0 };
129
130 /* The pool for basic block notes.  */
131 static rtx_vec_t bb_note_pool;
132
133 /* A NOP pattern used to emit placeholder insns.  */
134 rtx nop_pattern = NULL_RTX;
135 /* A special instruction that resides in EXIT_BLOCK.
136    EXIT_INSN is successor of the insns that lead to EXIT_BLOCK.  */
137 rtx exit_insn = NULL_RTX;
138
139 /* TRUE if while scheduling current region, which is loop, its preheader
140    was removed.  */
141 bool preheader_removed = false;
142 \f
143
144 /* Forward static declarations.  */
145 static void fence_clear (fence_t);
146
147 static void deps_init_id (idata_t, insn_t, bool);
148 static void init_id_from_df (idata_t, insn_t, bool);
149 static expr_t set_insn_init (expr_t, vinsn_t, int);
150
151 static void cfg_preds (basic_block, insn_t **, int *);
152 static void prepare_insn_expr (insn_t, int);
153 static void free_history_vect (VEC (expr_history_def, heap) **);
154
155 static void move_bb_info (basic_block, basic_block);
156 static void remove_empty_bb (basic_block, bool);
157 static void sel_merge_blocks (basic_block, basic_block);
158 static void sel_remove_loop_preheader (void);
159
160 static bool insn_is_the_only_one_in_bb_p (insn_t);
161 static void create_initial_data_sets (basic_block);
162
163 static void free_av_set (basic_block);
164 static void invalidate_av_set (basic_block);
165 static void extend_insn_data (void);
166 static void sel_init_new_insn (insn_t, int);
167 static void finish_insns (void);
168 \f
169 /* Various list functions.  */
170
171 /* Copy an instruction list L.  */
172 ilist_t
173 ilist_copy (ilist_t l)
174 {
175   ilist_t head = NULL, *tailp = &head;
176
177   while (l)
178     {
179       ilist_add (tailp, ILIST_INSN (l));
180       tailp = &ILIST_NEXT (*tailp);
181       l = ILIST_NEXT (l);
182     }
183
184   return head;
185 }
186
187 /* Invert an instruction list L.  */
188 ilist_t
189 ilist_invert (ilist_t l)
190 {
191   ilist_t res = NULL;
192
193   while (l)
194     {
195       ilist_add (&res, ILIST_INSN (l));
196       l = ILIST_NEXT (l);
197     }
198
199   return res;
200 }
201
202 /* Add a new boundary to the LP list with parameters TO, PTR, and DC.  */
203 void
204 blist_add (blist_t *lp, insn_t to, ilist_t ptr, deps_t dc)
205 {
206   bnd_t bnd;
207
208   _list_add (lp);
209   bnd = BLIST_BND (*lp);
210
211   BND_TO (bnd) = to;
212   BND_PTR (bnd) = ptr;
213   BND_AV (bnd) = NULL;
214   BND_AV1 (bnd) = NULL;
215   BND_DC (bnd) = dc;
216 }
217
218 /* Remove the list note pointed to by LP.  */
219 void
220 blist_remove (blist_t *lp)
221 {
222   bnd_t b = BLIST_BND (*lp);
223
224   av_set_clear (&BND_AV (b));
225   av_set_clear (&BND_AV1 (b));
226   ilist_clear (&BND_PTR (b));
227
228   _list_remove (lp);
229 }
230
231 /* Init a fence tail L.  */
232 void
233 flist_tail_init (flist_tail_t l)
234 {
235   FLIST_TAIL_HEAD (l) = NULL;
236   FLIST_TAIL_TAILP (l) = &FLIST_TAIL_HEAD (l);
237 }
238
239 /* Try to find fence corresponding to INSN in L.  */
240 fence_t
241 flist_lookup (flist_t l, insn_t insn)
242 {
243   while (l)
244     {
245       if (FENCE_INSN (FLIST_FENCE (l)) == insn)
246         return FLIST_FENCE (l);
247
248       l = FLIST_NEXT (l);
249     }
250
251   return NULL;
252 }
253
254 /* Init the fields of F before running fill_insns.  */
255 static void
256 init_fence_for_scheduling (fence_t f)
257 {
258   FENCE_BNDS (f) = NULL;
259   FENCE_PROCESSED_P (f) = false;
260   FENCE_SCHEDULED_P (f) = false;
261 }
262
263 /* Add new fence consisting of INSN and STATE to the list pointed to by LP.  */
264 static void
265 flist_add (flist_t *lp, insn_t insn, state_t state, deps_t dc, void *tc,
266            insn_t last_scheduled_insn, VEC(rtx,gc) *executing_insns,
267            int *ready_ticks, int ready_ticks_size, insn_t sched_next,
268            int cycle, int cycle_issued_insns, int issue_more,
269            bool starts_cycle_p, bool after_stall_p)
270 {
271   fence_t f;
272
273   _list_add (lp);
274   f = FLIST_FENCE (*lp);
275
276   FENCE_INSN (f) = insn;
277
278   gcc_assert (state != NULL);
279   FENCE_STATE (f) = state;
280
281   FENCE_CYCLE (f) = cycle;
282   FENCE_ISSUED_INSNS (f) = cycle_issued_insns;
283   FENCE_STARTS_CYCLE_P (f) = starts_cycle_p;
284   FENCE_AFTER_STALL_P (f) = after_stall_p;
285
286   gcc_assert (dc != NULL);
287   FENCE_DC (f) = dc;
288
289   gcc_assert (tc != NULL || targetm.sched.alloc_sched_context == NULL);
290   FENCE_TC (f) = tc;
291
292   FENCE_LAST_SCHEDULED_INSN (f) = last_scheduled_insn;
293   FENCE_ISSUE_MORE (f) = issue_more;
294   FENCE_EXECUTING_INSNS (f) = executing_insns;
295   FENCE_READY_TICKS (f) = ready_ticks;
296   FENCE_READY_TICKS_SIZE (f) = ready_ticks_size;
297   FENCE_SCHED_NEXT (f) = sched_next;
298
299   init_fence_for_scheduling (f);
300 }
301
302 /* Remove the head node of the list pointed to by LP.  */
303 static void
304 flist_remove (flist_t *lp)
305 {
306   if (FENCE_INSN (FLIST_FENCE (*lp)))
307     fence_clear (FLIST_FENCE (*lp));
308   _list_remove (lp);
309 }
310
311 /* Clear the fence list pointed to by LP.  */
312 void
313 flist_clear (flist_t *lp)
314 {
315   while (*lp)
316     flist_remove (lp);
317 }
318
319 /* Add ORIGINAL_INSN the def list DL honoring CROSSES_CALL.  */
320 void
321 def_list_add (def_list_t *dl, insn_t original_insn, bool crosses_call)
322 {
323   def_t d;
324
325   _list_add (dl);
326   d = DEF_LIST_DEF (*dl);
327
328   d->orig_insn = original_insn;
329   d->crosses_call = crosses_call;
330 }
331 \f
332
333 /* Functions to work with target contexts.  */
334
335 /* Bulk target context.  It is convenient for debugging purposes to ensure
336    that there are no uninitialized (null) target contexts.  */
337 static tc_t bulk_tc = (tc_t) 1;
338
339 /* Target hooks wrappers.  In the future we can provide some default
340    implementations for them.  */
341
342 /* Allocate a store for the target context.  */
343 static tc_t
344 alloc_target_context (void)
345 {
346   return (targetm.sched.alloc_sched_context
347           ? targetm.sched.alloc_sched_context () : bulk_tc);
348 }
349
350 /* Init target context TC.
351    If CLEAN_P is true, then make TC as it is beginning of the scheduler.
352    Overwise, copy current backend context to TC.  */
353 static void
354 init_target_context (tc_t tc, bool clean_p)
355 {
356   if (targetm.sched.init_sched_context)
357     targetm.sched.init_sched_context (tc, clean_p);
358 }
359
360 /* Allocate and initialize a target context.  Meaning of CLEAN_P is the same as
361    int init_target_context ().  */
362 tc_t
363 create_target_context (bool clean_p)
364 {
365   tc_t tc = alloc_target_context ();
366
367   init_target_context (tc, clean_p);
368   return tc;
369 }
370
371 /* Copy TC to the current backend context.  */
372 void
373 set_target_context (tc_t tc)
374 {
375   if (targetm.sched.set_sched_context)
376     targetm.sched.set_sched_context (tc);
377 }
378
379 /* TC is about to be destroyed.  Free any internal data.  */
380 static void
381 clear_target_context (tc_t tc)
382 {
383   if (targetm.sched.clear_sched_context)
384     targetm.sched.clear_sched_context (tc);
385 }
386
387 /*  Clear and free it.  */
388 static void
389 delete_target_context (tc_t tc)
390 {
391   clear_target_context (tc);
392
393   if (targetm.sched.free_sched_context)
394     targetm.sched.free_sched_context (tc);
395 }
396
397 /* Make a copy of FROM in TO.
398    NB: May be this should be a hook.  */
399 static void
400 copy_target_context (tc_t to, tc_t from)
401 {
402   tc_t tmp = create_target_context (false);
403
404   set_target_context (from);
405   init_target_context (to, false);
406
407   set_target_context (tmp);
408   delete_target_context (tmp);
409 }
410
411 /* Create a copy of TC.  */
412 static tc_t
413 create_copy_of_target_context (tc_t tc)
414 {
415   tc_t copy = alloc_target_context ();
416
417   copy_target_context (copy, tc);
418
419   return copy;
420 }
421
422 /* Clear TC and initialize it according to CLEAN_P.  The meaning of CLEAN_P
423    is the same as in init_target_context ().  */
424 void
425 reset_target_context (tc_t tc, bool clean_p)
426 {
427   clear_target_context (tc);
428   init_target_context (tc, clean_p);
429 }
430 \f
431 /* Functions to work with dependence contexts.
432    Dc (aka deps context, aka deps_t, aka struct deps_desc *) is short for dependence
433    context.  It accumulates information about processed insns to decide if
434    current insn is dependent on the processed ones.  */
435
436 /* Make a copy of FROM in TO.  */
437 static void
438 copy_deps_context (deps_t to, deps_t from)
439 {
440   init_deps (to, false);
441   deps_join (to, from);
442 }
443
444 /* Allocate store for dep context.  */
445 static deps_t
446 alloc_deps_context (void)
447 {
448   return XNEW (struct deps_desc);
449 }
450
451 /* Allocate and initialize dep context.  */
452 static deps_t
453 create_deps_context (void)
454 {
455   deps_t dc = alloc_deps_context ();
456
457   init_deps (dc, false);
458   return dc;
459 }
460
461 /* Create a copy of FROM.  */
462 static deps_t
463 create_copy_of_deps_context (deps_t from)
464 {
465   deps_t to = alloc_deps_context ();
466
467   copy_deps_context (to, from);
468   return to;
469 }
470
471 /* Clean up internal data of DC.  */
472 static void
473 clear_deps_context (deps_t dc)
474 {
475   free_deps (dc);
476 }
477
478 /* Clear and free DC.  */
479 static void
480 delete_deps_context (deps_t dc)
481 {
482   clear_deps_context (dc);
483   free (dc);
484 }
485
486 /* Clear and init DC.  */
487 static void
488 reset_deps_context (deps_t dc)
489 {
490   clear_deps_context (dc);
491   init_deps (dc, false);
492 }
493
494 /* This structure describes the dependence analysis hooks for advancing
495    dependence context.  */
496 static struct sched_deps_info_def advance_deps_context_sched_deps_info =
497   {
498     NULL,
499
500     NULL, /* start_insn */
501     NULL, /* finish_insn */
502     NULL, /* start_lhs */
503     NULL, /* finish_lhs */
504     NULL, /* start_rhs */
505     NULL, /* finish_rhs */
506     haifa_note_reg_set,
507     haifa_note_reg_clobber,
508     haifa_note_reg_use,
509     NULL, /* note_mem_dep */
510     NULL, /* note_dep */
511
512     0, 0, 0
513   };
514
515 /* Process INSN and add its impact on DC.  */
516 void
517 advance_deps_context (deps_t dc, insn_t insn)
518 {
519   sched_deps_info = &advance_deps_context_sched_deps_info;
520   deps_analyze_insn (dc, insn);
521 }
522 \f
523
524 /* Functions to work with DFA states.  */
525
526 /* Allocate store for a DFA state.  */
527 static state_t
528 state_alloc (void)
529 {
530   return xmalloc (dfa_state_size);
531 }
532
533 /* Allocate and initialize DFA state.  */
534 static state_t
535 state_create (void)
536 {
537   state_t state = state_alloc ();
538
539   state_reset (state);
540   advance_state (state);
541   return state;
542 }
543
544 /* Free DFA state.  */
545 static void
546 state_free (state_t state)
547 {
548   free (state);
549 }
550
551 /* Make a copy of FROM in TO.  */
552 static void
553 state_copy (state_t to, state_t from)
554 {
555   memcpy (to, from, dfa_state_size);
556 }
557
558 /* Create a copy of FROM.  */
559 static state_t
560 state_create_copy (state_t from)
561 {
562   state_t to = state_alloc ();
563
564   state_copy (to, from);
565   return to;
566 }
567 \f
568
569 /* Functions to work with fences.  */
570
571 /* Clear the fence.  */
572 static void
573 fence_clear (fence_t f)
574 {
575   state_t s = FENCE_STATE (f);
576   deps_t dc = FENCE_DC (f);
577   void *tc = FENCE_TC (f);
578
579   ilist_clear (&FENCE_BNDS (f));
580
581   gcc_assert ((s != NULL && dc != NULL && tc != NULL)
582               || (s == NULL && dc == NULL && tc == NULL));
583
584   if (s != NULL)
585     free (s);
586
587   if (dc != NULL)
588     delete_deps_context (dc);
589
590   if (tc != NULL)
591     delete_target_context (tc);
592   VEC_free (rtx, gc, FENCE_EXECUTING_INSNS (f));
593   free (FENCE_READY_TICKS (f));
594   FENCE_READY_TICKS (f) = NULL;
595 }
596
597 /* Init a list of fences with successors of OLD_FENCE.  */
598 void
599 init_fences (insn_t old_fence)
600 {
601   insn_t succ;
602   succ_iterator si;
603   bool first = true;
604   int ready_ticks_size = get_max_uid () + 1;
605
606   FOR_EACH_SUCC_1 (succ, si, old_fence,
607                    SUCCS_NORMAL | SUCCS_SKIP_TO_LOOP_EXITS)
608     {
609
610       if (first)
611         first = false;
612       else
613         gcc_assert (flag_sel_sched_pipelining_outer_loops);
614
615       flist_add (&fences, succ,
616                  state_create (),
617                  create_deps_context () /* dc */,
618                  create_target_context (true) /* tc */,
619                  NULL_RTX /* last_scheduled_insn */,
620                  NULL, /* executing_insns */
621                  XCNEWVEC (int, ready_ticks_size), /* ready_ticks */
622                  ready_ticks_size,
623                  NULL_RTX /* sched_next */,
624                  1 /* cycle */, 0 /* cycle_issued_insns */,
625                  issue_rate, /* issue_more */
626                  1 /* starts_cycle_p */, 0 /* after_stall_p */);
627     }
628 }
629
630 /* Merges two fences (filling fields of fence F with resulting values) by
631    following rules: 1) state, target context and last scheduled insn are
632    propagated from fallthrough edge if it is available;
633    2) deps context and cycle is propagated from more probable edge;
634    3) all other fields are set to corresponding constant values.
635
636    INSN, STATE, DC, TC, LAST_SCHEDULED_INSN, EXECUTING_INSNS,
637    READY_TICKS, READY_TICKS_SIZE, SCHED_NEXT, CYCLE, ISSUE_MORE
638    and AFTER_STALL_P are the corresponding fields of the second fence.  */
639 static void
640 merge_fences (fence_t f, insn_t insn,
641               state_t state, deps_t dc, void *tc,
642               rtx last_scheduled_insn, VEC(rtx, gc) *executing_insns,
643               int *ready_ticks, int ready_ticks_size,
644               rtx sched_next, int cycle, int issue_more, bool after_stall_p)
645 {
646   insn_t last_scheduled_insn_old = FENCE_LAST_SCHEDULED_INSN (f);
647
648   gcc_assert (sel_bb_head_p (FENCE_INSN (f))
649               && !sched_next && !FENCE_SCHED_NEXT (f));
650
651   /* Check if we can decide which path fences came.
652      If we can't (or don't want to) - reset all.  */
653   if (last_scheduled_insn == NULL
654       || last_scheduled_insn_old == NULL
655       /* This is a case when INSN is reachable on several paths from
656          one insn (this can happen when pipelining of outer loops is on and
657          there are two edges: one going around of inner loop and the other -
658          right through it; in such case just reset everything).  */
659       || last_scheduled_insn == last_scheduled_insn_old)
660     {
661       state_reset (FENCE_STATE (f));
662       state_free (state);
663
664       reset_deps_context (FENCE_DC (f));
665       delete_deps_context (dc);
666
667       reset_target_context (FENCE_TC (f), true);
668       delete_target_context (tc);
669
670       if (cycle > FENCE_CYCLE (f))
671         FENCE_CYCLE (f) = cycle;
672
673       FENCE_LAST_SCHEDULED_INSN (f) = NULL;
674       FENCE_ISSUE_MORE (f) = issue_rate;
675       VEC_free (rtx, gc, executing_insns);
676       free (ready_ticks);
677       if (FENCE_EXECUTING_INSNS (f))
678         VEC_block_remove (rtx, FENCE_EXECUTING_INSNS (f), 0,
679                           VEC_length (rtx, FENCE_EXECUTING_INSNS (f)));
680       if (FENCE_READY_TICKS (f))
681         memset (FENCE_READY_TICKS (f), 0, FENCE_READY_TICKS_SIZE (f));
682     }
683   else
684     {
685       edge edge_old = NULL, edge_new = NULL;
686       edge candidate;
687       succ_iterator si;
688       insn_t succ;
689
690       /* Find fallthrough edge.  */
691       gcc_assert (BLOCK_FOR_INSN (insn)->prev_bb);
692       candidate = find_fallthru_edge_from (BLOCK_FOR_INSN (insn)->prev_bb);
693
694       if (!candidate
695           || (candidate->src != BLOCK_FOR_INSN (last_scheduled_insn)
696               && candidate->src != BLOCK_FOR_INSN (last_scheduled_insn_old)))
697         {
698           /* No fallthrough edge leading to basic block of INSN.  */
699           state_reset (FENCE_STATE (f));
700           state_free (state);
701
702           reset_target_context (FENCE_TC (f), true);
703           delete_target_context (tc);
704
705           FENCE_LAST_SCHEDULED_INSN (f) = NULL;
706           FENCE_ISSUE_MORE (f) = issue_rate;
707         }
708       else
709         if (candidate->src == BLOCK_FOR_INSN (last_scheduled_insn))
710           {
711             /* Would be weird if same insn is successor of several fallthrough
712                edges.  */
713             gcc_assert (BLOCK_FOR_INSN (insn)->prev_bb
714                         != BLOCK_FOR_INSN (last_scheduled_insn_old));
715
716             state_free (FENCE_STATE (f));
717             FENCE_STATE (f) = state;
718
719             delete_target_context (FENCE_TC (f));
720             FENCE_TC (f) = tc;
721
722             FENCE_LAST_SCHEDULED_INSN (f) = last_scheduled_insn;
723             FENCE_ISSUE_MORE (f) = issue_more;
724           }
725         else
726           {
727             /* Leave STATE, TC and LAST_SCHEDULED_INSN fields untouched.  */
728             state_free (state);
729             delete_target_context (tc);
730
731             gcc_assert (BLOCK_FOR_INSN (insn)->prev_bb
732                         != BLOCK_FOR_INSN (last_scheduled_insn));
733           }
734
735         /* Find edge of first predecessor (last_scheduled_insn_old->insn).  */
736         FOR_EACH_SUCC_1 (succ, si, last_scheduled_insn_old,
737                          SUCCS_NORMAL | SUCCS_SKIP_TO_LOOP_EXITS)
738           {
739             if (succ == insn)
740               {
741                 /* No same successor allowed from several edges.  */
742                 gcc_assert (!edge_old);
743                 edge_old = si.e1;
744               }
745           }
746         /* Find edge of second predecessor (last_scheduled_insn->insn).  */
747         FOR_EACH_SUCC_1 (succ, si, last_scheduled_insn,
748                          SUCCS_NORMAL | SUCCS_SKIP_TO_LOOP_EXITS)
749           {
750             if (succ == insn)
751               {
752                 /* No same successor allowed from several edges.  */
753                 gcc_assert (!edge_new);
754                 edge_new = si.e1;
755               }
756           }
757
758         /* Check if we can choose most probable predecessor.  */
759         if (edge_old == NULL || edge_new == NULL)
760           {
761             reset_deps_context (FENCE_DC (f));
762             delete_deps_context (dc);
763             VEC_free (rtx, gc, executing_insns);
764             free (ready_ticks);
765
766             FENCE_CYCLE (f) = MAX (FENCE_CYCLE (f), cycle);
767             if (FENCE_EXECUTING_INSNS (f))
768               VEC_block_remove (rtx, FENCE_EXECUTING_INSNS (f), 0,
769                                 VEC_length (rtx, FENCE_EXECUTING_INSNS (f)));
770             if (FENCE_READY_TICKS (f))
771               memset (FENCE_READY_TICKS (f), 0, FENCE_READY_TICKS_SIZE (f));
772           }
773         else
774           if (edge_new->probability > edge_old->probability)
775             {
776               delete_deps_context (FENCE_DC (f));
777               FENCE_DC (f) = dc;
778               VEC_free (rtx, gc, FENCE_EXECUTING_INSNS (f));
779               FENCE_EXECUTING_INSNS (f) = executing_insns;
780               free (FENCE_READY_TICKS (f));
781               FENCE_READY_TICKS (f) = ready_ticks;
782               FENCE_READY_TICKS_SIZE (f) = ready_ticks_size;
783               FENCE_CYCLE (f) = cycle;
784             }
785           else
786             {
787               /* Leave DC and CYCLE untouched.  */
788               delete_deps_context (dc);
789               VEC_free (rtx, gc, executing_insns);
790               free (ready_ticks);
791             }
792     }
793
794   /* Fill remaining invariant fields.  */
795   if (after_stall_p)
796     FENCE_AFTER_STALL_P (f) = 1;
797
798   FENCE_ISSUED_INSNS (f) = 0;
799   FENCE_STARTS_CYCLE_P (f) = 1;
800   FENCE_SCHED_NEXT (f) = NULL;
801 }
802
803 /* Add a new fence to NEW_FENCES list, initializing it from all
804    other parameters.  */
805 static void
806 add_to_fences (flist_tail_t new_fences, insn_t insn,
807                state_t state, deps_t dc, void *tc, rtx last_scheduled_insn,
808                VEC(rtx, gc) *executing_insns, int *ready_ticks,
809                int ready_ticks_size, rtx sched_next, int cycle,
810                int cycle_issued_insns, int issue_rate,
811                bool starts_cycle_p, bool after_stall_p)
812 {
813   fence_t f = flist_lookup (FLIST_TAIL_HEAD (new_fences), insn);
814
815   if (! f)
816     {
817       flist_add (FLIST_TAIL_TAILP (new_fences), insn, state, dc, tc,
818                  last_scheduled_insn, executing_insns, ready_ticks,
819                  ready_ticks_size, sched_next, cycle, cycle_issued_insns,
820                  issue_rate, starts_cycle_p, after_stall_p);
821
822       FLIST_TAIL_TAILP (new_fences)
823         = &FLIST_NEXT (*FLIST_TAIL_TAILP (new_fences));
824     }
825   else
826     {
827       merge_fences (f, insn, state, dc, tc, last_scheduled_insn,
828                     executing_insns, ready_ticks, ready_ticks_size,
829                     sched_next, cycle, issue_rate, after_stall_p);
830     }
831 }
832
833 /* Move the first fence in the OLD_FENCES list to NEW_FENCES.  */
834 void
835 move_fence_to_fences (flist_t old_fences, flist_tail_t new_fences)
836 {
837   fence_t f, old;
838   flist_t *tailp = FLIST_TAIL_TAILP (new_fences);
839
840   old = FLIST_FENCE (old_fences);
841   f = flist_lookup (FLIST_TAIL_HEAD (new_fences),
842                     FENCE_INSN (FLIST_FENCE (old_fences)));
843   if (f)
844     {
845       merge_fences (f, old->insn, old->state, old->dc, old->tc,
846                     old->last_scheduled_insn, old->executing_insns,
847                     old->ready_ticks, old->ready_ticks_size,
848                     old->sched_next, old->cycle, old->issue_more,
849                     old->after_stall_p);
850     }
851   else
852     {
853       _list_add (tailp);
854       FLIST_TAIL_TAILP (new_fences) = &FLIST_NEXT (*tailp);
855       *FLIST_FENCE (*tailp) = *old;
856       init_fence_for_scheduling (FLIST_FENCE (*tailp));
857     }
858   FENCE_INSN (old) = NULL;
859 }
860
861 /* Add a new fence to NEW_FENCES list and initialize most of its data
862    as a clean one.  */
863 void
864 add_clean_fence_to_fences (flist_tail_t new_fences, insn_t succ, fence_t fence)
865 {
866   int ready_ticks_size = get_max_uid () + 1;
867
868   add_to_fences (new_fences,
869                  succ, state_create (), create_deps_context (),
870                  create_target_context (true),
871                  NULL_RTX, NULL,
872                  XCNEWVEC (int, ready_ticks_size), ready_ticks_size,
873                  NULL_RTX, FENCE_CYCLE (fence) + 1,
874                  0, issue_rate, 1, FENCE_AFTER_STALL_P (fence));
875 }
876
877 /* Add a new fence to NEW_FENCES list and initialize all of its data
878    from FENCE and SUCC.  */
879 void
880 add_dirty_fence_to_fences (flist_tail_t new_fences, insn_t succ, fence_t fence)
881 {
882   int * new_ready_ticks
883     = XNEWVEC (int, FENCE_READY_TICKS_SIZE (fence));
884
885   memcpy (new_ready_ticks, FENCE_READY_TICKS (fence),
886           FENCE_READY_TICKS_SIZE (fence) * sizeof (int));
887   add_to_fences (new_fences,
888                  succ, state_create_copy (FENCE_STATE (fence)),
889                  create_copy_of_deps_context (FENCE_DC (fence)),
890                  create_copy_of_target_context (FENCE_TC (fence)),
891                  FENCE_LAST_SCHEDULED_INSN (fence),
892                  VEC_copy (rtx, gc, FENCE_EXECUTING_INSNS (fence)),
893                  new_ready_ticks,
894                  FENCE_READY_TICKS_SIZE (fence),
895                  FENCE_SCHED_NEXT (fence),
896                  FENCE_CYCLE (fence),
897                  FENCE_ISSUED_INSNS (fence),
898                  FENCE_ISSUE_MORE (fence),
899                  FENCE_STARTS_CYCLE_P (fence),
900                  FENCE_AFTER_STALL_P (fence));
901 }
902 \f
903
904 /* Functions to work with regset and nop pools.  */
905
906 /* Returns the new regset from pool.  It might have some of the bits set
907    from the previous usage.  */
908 regset
909 get_regset_from_pool (void)
910 {
911   regset rs;
912
913   if (regset_pool.n != 0)
914     rs = regset_pool.v[--regset_pool.n];
915   else
916     /* We need to create the regset.  */
917     {
918       rs = ALLOC_REG_SET (&reg_obstack);
919
920       if (regset_pool.nn == regset_pool.ss)
921         regset_pool.vv = XRESIZEVEC (regset, regset_pool.vv,
922                                      (regset_pool.ss = 2 * regset_pool.ss + 1));
923       regset_pool.vv[regset_pool.nn++] = rs;
924     }
925
926   regset_pool.diff++;
927
928   return rs;
929 }
930
931 /* Same as above, but returns the empty regset.  */
932 regset
933 get_clear_regset_from_pool (void)
934 {
935   regset rs = get_regset_from_pool ();
936
937   CLEAR_REG_SET (rs);
938   return rs;
939 }
940
941 /* Return regset RS to the pool for future use.  */
942 void
943 return_regset_to_pool (regset rs)
944 {
945   regset_pool.diff--;
946
947   if (regset_pool.n == regset_pool.s)
948     regset_pool.v = XRESIZEVEC (regset, regset_pool.v,
949                                 (regset_pool.s = 2 * regset_pool.s + 1));
950   regset_pool.v[regset_pool.n++] = rs;
951 }
952
953 #ifdef ENABLE_CHECKING
954 /* This is used as a qsort callback for sorting regset pool stacks.
955    X and XX are addresses of two regsets.  They are never equal.  */
956 static int
957 cmp_v_in_regset_pool (const void *x, const void *xx)
958 {
959   return *((const regset *) x) - *((const regset *) xx);
960 }
961 #endif
962
963 /*  Free the regset pool possibly checking for memory leaks.  */
964 void
965 free_regset_pool (void)
966 {
967 #ifdef ENABLE_CHECKING
968   {
969     regset *v = regset_pool.v;
970     int i = 0;
971     int n = regset_pool.n;
972
973     regset *vv = regset_pool.vv;
974     int ii = 0;
975     int nn = regset_pool.nn;
976
977     int diff = 0;
978
979     gcc_assert (n <= nn);
980
981     /* Sort both vectors so it will be possible to compare them.  */
982     qsort (v, n, sizeof (*v), cmp_v_in_regset_pool);
983     qsort (vv, nn, sizeof (*vv), cmp_v_in_regset_pool);
984
985     while (ii < nn)
986       {
987         if (v[i] == vv[ii])
988           i++;
989         else
990           /* VV[II] was lost.  */
991           diff++;
992
993         ii++;
994       }
995
996     gcc_assert (diff == regset_pool.diff);
997   }
998 #endif
999
1000   /* If not true - we have a memory leak.  */
1001   gcc_assert (regset_pool.diff == 0);
1002
1003   while (regset_pool.n)
1004     {
1005       --regset_pool.n;
1006       FREE_REG_SET (regset_pool.v[regset_pool.n]);
1007     }
1008
1009   free (regset_pool.v);
1010   regset_pool.v = NULL;
1011   regset_pool.s = 0;
1012
1013   free (regset_pool.vv);
1014   regset_pool.vv = NULL;
1015   regset_pool.nn = 0;
1016   regset_pool.ss = 0;
1017
1018   regset_pool.diff = 0;
1019 }
1020 \f
1021
1022 /* Functions to work with nop pools.  NOP insns are used as temporary
1023    placeholders of the insns being scheduled to allow correct update of
1024    the data sets.  When update is finished, NOPs are deleted.  */
1025
1026 /* A vinsn that is used to represent a nop.  This vinsn is shared among all
1027    nops sel-sched generates.  */
1028 static vinsn_t nop_vinsn = NULL;
1029
1030 /* Emit a nop before INSN, taking it from pool.  */
1031 insn_t
1032 get_nop_from_pool (insn_t insn)
1033 {
1034   insn_t nop;
1035   bool old_p = nop_pool.n != 0;
1036   int flags;
1037
1038   if (old_p)
1039     nop = nop_pool.v[--nop_pool.n];
1040   else
1041     nop = nop_pattern;
1042
1043   nop = emit_insn_before (nop, insn);
1044
1045   if (old_p)
1046     flags = INSN_INIT_TODO_SSID;
1047   else
1048     flags = INSN_INIT_TODO_LUID | INSN_INIT_TODO_SSID;
1049
1050   set_insn_init (INSN_EXPR (insn), nop_vinsn, INSN_SEQNO (insn));
1051   sel_init_new_insn (nop, flags);
1052
1053   return nop;
1054 }
1055
1056 /* Remove NOP from the instruction stream and return it to the pool.  */
1057 void
1058 return_nop_to_pool (insn_t nop, bool full_tidying)
1059 {
1060   gcc_assert (INSN_IN_STREAM_P (nop));
1061   sel_remove_insn (nop, false, full_tidying);
1062
1063   if (nop_pool.n == nop_pool.s)
1064     nop_pool.v = XRESIZEVEC (rtx, nop_pool.v,
1065                              (nop_pool.s = 2 * nop_pool.s + 1));
1066   nop_pool.v[nop_pool.n++] = nop;
1067 }
1068
1069 /* Free the nop pool.  */
1070 void
1071 free_nop_pool (void)
1072 {
1073   nop_pool.n = 0;
1074   nop_pool.s = 0;
1075   free (nop_pool.v);
1076   nop_pool.v = NULL;
1077 }
1078 \f
1079
1080 /* Skip unspec to support ia64 speculation. Called from rtx_equal_p_cb.
1081    The callback is given two rtxes XX and YY and writes the new rtxes
1082    to NX and NY in case some needs to be skipped.  */
1083 static int
1084 skip_unspecs_callback (const_rtx *xx, const_rtx *yy, rtx *nx, rtx* ny)
1085 {
1086   const_rtx x = *xx;
1087   const_rtx y = *yy;
1088
1089   if (GET_CODE (x) == UNSPEC
1090       && (targetm.sched.skip_rtx_p == NULL
1091           || targetm.sched.skip_rtx_p (x)))
1092     {
1093       *nx = XVECEXP (x, 0, 0);
1094       *ny = CONST_CAST_RTX (y);
1095       return 1;
1096     }
1097
1098   if (GET_CODE (y) == UNSPEC
1099       && (targetm.sched.skip_rtx_p == NULL
1100           || targetm.sched.skip_rtx_p (y)))
1101     {
1102       *nx = CONST_CAST_RTX (x);
1103       *ny = XVECEXP (y, 0, 0);
1104       return 1;
1105     }
1106
1107   return 0;
1108 }
1109
1110 /* Callback, called from hash_rtx_cb.  Helps to hash UNSPEC rtx X in a correct way
1111    to support ia64 speculation.  When changes are needed, new rtx X and new mode
1112    NMODE are written, and the callback returns true.  */
1113 static int
1114 hash_with_unspec_callback (const_rtx x, enum machine_mode mode ATTRIBUTE_UNUSED,
1115                            rtx *nx, enum machine_mode* nmode)
1116 {
1117   if (GET_CODE (x) == UNSPEC
1118       && targetm.sched.skip_rtx_p
1119       && targetm.sched.skip_rtx_p (x))
1120     {
1121       *nx = XVECEXP (x, 0 ,0);
1122       *nmode = VOIDmode;
1123       return 1;
1124     }
1125
1126   return 0;
1127 }
1128
1129 /* Returns LHS and RHS are ok to be scheduled separately.  */
1130 static bool
1131 lhs_and_rhs_separable_p (rtx lhs, rtx rhs)
1132 {
1133   if (lhs == NULL || rhs == NULL)
1134     return false;
1135
1136   /* Do not schedule CONST, CONST_INT and CONST_DOUBLE etc as rhs: no point
1137      to use reg, if const can be used.  Moreover, scheduling const as rhs may
1138      lead to mode mismatch cause consts don't have modes but they could be
1139      merged from branches where the same const used in different modes.  */
1140   if (CONSTANT_P (rhs))
1141     return false;
1142
1143   /* ??? Do not rename predicate registers to avoid ICEs in bundling.  */
1144   if (COMPARISON_P (rhs))
1145       return false;
1146
1147   /* Do not allow single REG to be an rhs.  */
1148   if (REG_P (rhs))
1149     return false;
1150
1151   /* See comment at find_used_regs_1 (*1) for explanation of this
1152      restriction.  */
1153   /* FIXME: remove this later.  */
1154   if (MEM_P (lhs))
1155     return false;
1156
1157   /* This will filter all tricky things like ZERO_EXTRACT etc.
1158      For now we don't handle it.  */
1159   if (!REG_P (lhs) && !MEM_P (lhs))
1160     return false;
1161
1162   return true;
1163 }
1164
1165 /* Initialize vinsn VI for INSN.  Only for use from vinsn_create ().  When
1166    FORCE_UNIQUE_P is true, the resulting vinsn will not be clonable.  This is
1167    used e.g. for insns from recovery blocks.  */
1168 static void
1169 vinsn_init (vinsn_t vi, insn_t insn, bool force_unique_p)
1170 {
1171   hash_rtx_callback_function hrcf;
1172   int insn_class;
1173
1174   VINSN_INSN_RTX (vi) = insn;
1175   VINSN_COUNT (vi) = 0;
1176   vi->cost = -1;
1177
1178   if (DF_INSN_UID_SAFE_GET (INSN_UID (insn)) != NULL)
1179     init_id_from_df (VINSN_ID (vi), insn, force_unique_p);
1180   else
1181     deps_init_id (VINSN_ID (vi), insn, force_unique_p);
1182
1183   /* Hash vinsn depending on whether it is separable or not.  */
1184   hrcf = targetm.sched.skip_rtx_p ? hash_with_unspec_callback : NULL;
1185   if (VINSN_SEPARABLE_P (vi))
1186     {
1187       rtx rhs = VINSN_RHS (vi);
1188
1189       VINSN_HASH (vi) = hash_rtx_cb (rhs, GET_MODE (rhs),
1190                                      NULL, NULL, false, hrcf);
1191       VINSN_HASH_RTX (vi) = hash_rtx_cb (VINSN_PATTERN (vi),
1192                                          VOIDmode, NULL, NULL,
1193                                          false, hrcf);
1194     }
1195   else
1196     {
1197       VINSN_HASH (vi) = hash_rtx_cb (VINSN_PATTERN (vi), VOIDmode,
1198                                      NULL, NULL, false, hrcf);
1199       VINSN_HASH_RTX (vi) = VINSN_HASH (vi);
1200     }
1201
1202   insn_class = haifa_classify_insn (insn);
1203   if (insn_class >= 2
1204       && (!targetm.sched.get_insn_spec_ds
1205           || ((targetm.sched.get_insn_spec_ds (insn) & BEGIN_CONTROL)
1206               == 0)))
1207     VINSN_MAY_TRAP_P (vi) = true;
1208   else
1209     VINSN_MAY_TRAP_P (vi) = false;
1210 }
1211
1212 /* Indicate that VI has become the part of an rtx object.  */
1213 void
1214 vinsn_attach (vinsn_t vi)
1215 {
1216   /* Assert that VI is not pending for deletion.  */
1217   gcc_assert (VINSN_INSN_RTX (vi));
1218
1219   VINSN_COUNT (vi)++;
1220 }
1221
1222 /* Create and init VI from the INSN.  Use UNIQUE_P for determining the correct
1223    VINSN_TYPE (VI).  */
1224 static vinsn_t
1225 vinsn_create (insn_t insn, bool force_unique_p)
1226 {
1227   vinsn_t vi = XCNEW (struct vinsn_def);
1228
1229   vinsn_init (vi, insn, force_unique_p);
1230   return vi;
1231 }
1232
1233 /* Return a copy of VI.  When REATTACH_P is true, detach VI and attach
1234    the copy.  */
1235 vinsn_t
1236 vinsn_copy (vinsn_t vi, bool reattach_p)
1237 {
1238   rtx copy;
1239   bool unique = VINSN_UNIQUE_P (vi);
1240   vinsn_t new_vi;
1241
1242   copy = create_copy_of_insn_rtx (VINSN_INSN_RTX (vi));
1243   new_vi = create_vinsn_from_insn_rtx (copy, unique);
1244   if (reattach_p)
1245     {
1246       vinsn_detach (vi);
1247       vinsn_attach (new_vi);
1248     }
1249
1250   return new_vi;
1251 }
1252
1253 /* Delete the VI vinsn and free its data.  */
1254 static void
1255 vinsn_delete (vinsn_t vi)
1256 {
1257   gcc_assert (VINSN_COUNT (vi) == 0);
1258
1259   return_regset_to_pool (VINSN_REG_SETS (vi));
1260   return_regset_to_pool (VINSN_REG_USES (vi));
1261   return_regset_to_pool (VINSN_REG_CLOBBERS (vi));
1262
1263   free (vi);
1264 }
1265
1266 /* Indicate that VI is no longer a part of some rtx object.
1267    Remove VI if it is no longer needed.  */
1268 void
1269 vinsn_detach (vinsn_t vi)
1270 {
1271   gcc_assert (VINSN_COUNT (vi) > 0);
1272
1273   if (--VINSN_COUNT (vi) == 0)
1274     vinsn_delete (vi);
1275 }
1276
1277 /* Returns TRUE if VI is a branch.  */
1278 bool
1279 vinsn_cond_branch_p (vinsn_t vi)
1280 {
1281   insn_t insn;
1282
1283   if (!VINSN_UNIQUE_P (vi))
1284     return false;
1285
1286   insn = VINSN_INSN_RTX (vi);
1287   if (BB_END (BLOCK_FOR_INSN (insn)) != insn)
1288     return false;
1289
1290   return control_flow_insn_p (insn);
1291 }
1292
1293 /* Return latency of INSN.  */
1294 static int
1295 sel_insn_rtx_cost (rtx insn)
1296 {
1297   int cost;
1298
1299   /* A USE insn, or something else we don't need to
1300      understand.  We can't pass these directly to
1301      result_ready_cost or insn_default_latency because it will
1302      trigger a fatal error for unrecognizable insns.  */
1303   if (recog_memoized (insn) < 0)
1304     cost = 0;
1305   else
1306     {
1307       cost = insn_default_latency (insn);
1308
1309       if (cost < 0)
1310         cost = 0;
1311     }
1312
1313   return cost;
1314 }
1315
1316 /* Return the cost of the VI.
1317    !!! FIXME: Unify with haifa-sched.c: insn_cost ().  */
1318 int
1319 sel_vinsn_cost (vinsn_t vi)
1320 {
1321   int cost = vi->cost;
1322
1323   if (cost < 0)
1324     {
1325       cost = sel_insn_rtx_cost (VINSN_INSN_RTX (vi));
1326       vi->cost = cost;
1327     }
1328
1329   return cost;
1330 }
1331 \f
1332
1333 /* Functions for insn emitting.  */
1334
1335 /* Emit new insn after AFTER based on PATTERN and initialize its data from
1336    EXPR and SEQNO.  */
1337 insn_t
1338 sel_gen_insn_from_rtx_after (rtx pattern, expr_t expr, int seqno, insn_t after)
1339 {
1340   insn_t new_insn;
1341
1342   gcc_assert (EXPR_TARGET_AVAILABLE (expr) == true);
1343
1344   new_insn = emit_insn_after (pattern, after);
1345   set_insn_init (expr, NULL, seqno);
1346   sel_init_new_insn (new_insn, INSN_INIT_TODO_LUID | INSN_INIT_TODO_SSID);
1347
1348   return new_insn;
1349 }
1350
1351 /* Force newly generated vinsns to be unique.  */
1352 static bool init_insn_force_unique_p = false;
1353
1354 /* Emit new speculation recovery insn after AFTER based on PATTERN and
1355    initialize its data from EXPR and SEQNO.  */
1356 insn_t
1357 sel_gen_recovery_insn_from_rtx_after (rtx pattern, expr_t expr, int seqno,
1358                                       insn_t after)
1359 {
1360   insn_t insn;
1361
1362   gcc_assert (!init_insn_force_unique_p);
1363
1364   init_insn_force_unique_p = true;
1365   insn = sel_gen_insn_from_rtx_after (pattern, expr, seqno, after);
1366   CANT_MOVE (insn) = 1;
1367   init_insn_force_unique_p = false;
1368
1369   return insn;
1370 }
1371
1372 /* Emit new insn after AFTER based on EXPR and SEQNO.  If VINSN is not NULL,
1373    take it as a new vinsn instead of EXPR's vinsn.
1374    We simplify insns later, after scheduling region in
1375    simplify_changed_insns.  */
1376 insn_t
1377 sel_gen_insn_from_expr_after (expr_t expr, vinsn_t vinsn, int seqno,
1378                               insn_t after)
1379 {
1380   expr_t emit_expr;
1381   insn_t insn;
1382   int flags;
1383
1384   emit_expr = set_insn_init (expr, vinsn ? vinsn : EXPR_VINSN (expr),
1385                              seqno);
1386   insn = EXPR_INSN_RTX (emit_expr);
1387   add_insn_after (insn, after, BLOCK_FOR_INSN (insn));
1388
1389   flags = INSN_INIT_TODO_SSID;
1390   if (INSN_LUID (insn) == 0)
1391     flags |= INSN_INIT_TODO_LUID;
1392   sel_init_new_insn (insn, flags);
1393
1394   return insn;
1395 }
1396
1397 /* Move insn from EXPR after AFTER.  */
1398 insn_t
1399 sel_move_insn (expr_t expr, int seqno, insn_t after)
1400 {
1401   insn_t insn = EXPR_INSN_RTX (expr);
1402   basic_block bb = BLOCK_FOR_INSN (after);
1403   insn_t next = NEXT_INSN (after);
1404
1405   /* Assert that in move_op we disconnected this insn properly.  */
1406   gcc_assert (EXPR_VINSN (INSN_EXPR (insn)) != NULL);
1407   PREV_INSN (insn) = after;
1408   NEXT_INSN (insn) = next;
1409
1410   NEXT_INSN (after) = insn;
1411   PREV_INSN (next) = insn;
1412
1413   /* Update links from insn to bb and vice versa.  */
1414   df_insn_change_bb (insn, bb);
1415   if (BB_END (bb) == after)
1416     BB_END (bb) = insn;
1417
1418   prepare_insn_expr (insn, seqno);
1419   return insn;
1420 }
1421
1422 \f
1423 /* Functions to work with right-hand sides.  */
1424
1425 /* Search for a hash value determined by UID/NEW_VINSN in a sorted vector
1426    VECT and return true when found.  Use NEW_VINSN for comparison only when
1427    COMPARE_VINSNS is true.  Write to INDP the index on which
1428    the search has stopped, such that inserting the new element at INDP will
1429    retain VECT's sort order.  */
1430 static bool
1431 find_in_history_vect_1 (VEC(expr_history_def, heap) *vect,
1432                         unsigned uid, vinsn_t new_vinsn,
1433                         bool compare_vinsns, int *indp)
1434 {
1435   expr_history_def *arr;
1436   int i, j, len = VEC_length (expr_history_def, vect);
1437
1438   if (len == 0)
1439     {
1440       *indp = 0;
1441       return false;
1442     }
1443
1444   arr = VEC_address (expr_history_def, vect);
1445   i = 0, j = len - 1;
1446
1447   while (i <= j)
1448     {
1449       unsigned auid = arr[i].uid;
1450       vinsn_t avinsn = arr[i].new_expr_vinsn;
1451
1452       if (auid == uid
1453           /* When undoing transformation on a bookkeeping copy, the new vinsn
1454              may not be exactly equal to the one that is saved in the vector.
1455              This is because the insn whose copy we're checking was possibly
1456              substituted itself.  */
1457           && (! compare_vinsns
1458               || vinsn_equal_p (avinsn, new_vinsn)))
1459         {
1460           *indp = i;
1461           return true;
1462         }
1463       else if (auid > uid)
1464         break;
1465       i++;
1466     }
1467
1468   *indp = i;
1469   return false;
1470 }
1471
1472 /* Search for a uid of INSN and NEW_VINSN in a sorted vector VECT.  Return
1473    the position found or -1, if no such value is in vector.
1474    Search also for UIDs of insn's originators, if ORIGINATORS_P is true.  */
1475 int
1476 find_in_history_vect (VEC(expr_history_def, heap) *vect, rtx insn,
1477                       vinsn_t new_vinsn, bool originators_p)
1478 {
1479   int ind;
1480
1481   if (find_in_history_vect_1 (vect, INSN_UID (insn), new_vinsn,
1482                               false, &ind))
1483     return ind;
1484
1485   if (INSN_ORIGINATORS (insn) && originators_p)
1486     {
1487       unsigned uid;
1488       bitmap_iterator bi;
1489
1490       EXECUTE_IF_SET_IN_BITMAP (INSN_ORIGINATORS (insn), 0, uid, bi)
1491         if (find_in_history_vect_1 (vect, uid, new_vinsn, false, &ind))
1492           return ind;
1493     }
1494
1495   return -1;
1496 }
1497
1498 /* Insert new element in a sorted history vector pointed to by PVECT,
1499    if it is not there already.  The element is searched using
1500    UID/NEW_EXPR_VINSN pair.  TYPE, OLD_EXPR_VINSN and SPEC_DS save
1501    the history of a transformation.  */
1502 void
1503 insert_in_history_vect (VEC (expr_history_def, heap) **pvect,
1504                         unsigned uid, enum local_trans_type type,
1505                         vinsn_t old_expr_vinsn, vinsn_t new_expr_vinsn,
1506                         ds_t spec_ds)
1507 {
1508   VEC(expr_history_def, heap) *vect = *pvect;
1509   expr_history_def temp;
1510   bool res;
1511   int ind;
1512
1513   res = find_in_history_vect_1 (vect, uid, new_expr_vinsn, true, &ind);
1514
1515   if (res)
1516     {
1517       expr_history_def *phist = VEC_index (expr_history_def, vect, ind);
1518
1519       /* It is possible that speculation types of expressions that were
1520          propagated through different paths will be different here.  In this
1521          case, merge the status to get the correct check later.  */
1522       if (phist->spec_ds != spec_ds)
1523         phist->spec_ds = ds_max_merge (phist->spec_ds, spec_ds);
1524       return;
1525     }
1526
1527   temp.uid = uid;
1528   temp.old_expr_vinsn = old_expr_vinsn;
1529   temp.new_expr_vinsn = new_expr_vinsn;
1530   temp.spec_ds = spec_ds;
1531   temp.type = type;
1532
1533   vinsn_attach (old_expr_vinsn);
1534   vinsn_attach (new_expr_vinsn);
1535   VEC_safe_insert (expr_history_def, heap, vect, ind, &temp);
1536   *pvect = vect;
1537 }
1538
1539 /* Free history vector PVECT.  */
1540 static void
1541 free_history_vect (VEC (expr_history_def, heap) **pvect)
1542 {
1543   unsigned i;
1544   expr_history_def *phist;
1545
1546   if (! *pvect)
1547     return;
1548
1549   for (i = 0;
1550        VEC_iterate (expr_history_def, *pvect, i, phist);
1551        i++)
1552     {
1553       vinsn_detach (phist->old_expr_vinsn);
1554       vinsn_detach (phist->new_expr_vinsn);
1555     }
1556
1557   VEC_free (expr_history_def, heap, *pvect);
1558   *pvect = NULL;
1559 }
1560
1561
1562 /* Compare two vinsns as rhses if possible and as vinsns otherwise.  */
1563 bool
1564 vinsn_equal_p (vinsn_t x, vinsn_t y)
1565 {
1566   rtx_equal_p_callback_function repcf;
1567
1568   if (x == y)
1569     return true;
1570
1571   if (VINSN_TYPE (x) != VINSN_TYPE (y))
1572     return false;
1573
1574   if (VINSN_HASH (x) != VINSN_HASH (y))
1575     return false;
1576
1577   repcf = targetm.sched.skip_rtx_p ? skip_unspecs_callback : NULL;
1578   if (VINSN_SEPARABLE_P (x))
1579     {
1580       /* Compare RHSes of VINSNs.  */
1581       gcc_assert (VINSN_RHS (x));
1582       gcc_assert (VINSN_RHS (y));
1583
1584       return rtx_equal_p_cb (VINSN_RHS (x), VINSN_RHS (y), repcf);
1585     }
1586
1587   return rtx_equal_p_cb (VINSN_PATTERN (x), VINSN_PATTERN (y), repcf);
1588 }
1589 \f
1590
1591 /* Functions for working with expressions.  */
1592
1593 /* Initialize EXPR.  */
1594 static void
1595 init_expr (expr_t expr, vinsn_t vi, int spec, int use, int priority,
1596            int sched_times, int orig_bb_index, ds_t spec_done_ds,
1597            ds_t spec_to_check_ds, int orig_sched_cycle,
1598            VEC(expr_history_def, heap) *history, bool target_available,
1599            bool was_substituted, bool was_renamed, bool needs_spec_check_p,
1600            bool cant_move)
1601 {
1602   vinsn_attach (vi);
1603
1604   EXPR_VINSN (expr) = vi;
1605   EXPR_SPEC (expr) = spec;
1606   EXPR_USEFULNESS (expr) = use;
1607   EXPR_PRIORITY (expr) = priority;
1608   EXPR_PRIORITY_ADJ (expr) = 0;
1609   EXPR_SCHED_TIMES (expr) = sched_times;
1610   EXPR_ORIG_BB_INDEX (expr) = orig_bb_index;
1611   EXPR_ORIG_SCHED_CYCLE (expr) = orig_sched_cycle;
1612   EXPR_SPEC_DONE_DS (expr) = spec_done_ds;
1613   EXPR_SPEC_TO_CHECK_DS (expr) = spec_to_check_ds;
1614
1615   if (history)
1616     EXPR_HISTORY_OF_CHANGES (expr) = history;
1617   else
1618     EXPR_HISTORY_OF_CHANGES (expr) = NULL;
1619
1620   EXPR_TARGET_AVAILABLE (expr) = target_available;
1621   EXPR_WAS_SUBSTITUTED (expr) = was_substituted;
1622   EXPR_WAS_RENAMED (expr) = was_renamed;
1623   EXPR_NEEDS_SPEC_CHECK_P (expr) = needs_spec_check_p;
1624   EXPR_CANT_MOVE (expr) = cant_move;
1625 }
1626
1627 /* Make a copy of the expr FROM into the expr TO.  */
1628 void
1629 copy_expr (expr_t to, expr_t from)
1630 {
1631   VEC(expr_history_def, heap) *temp = NULL;
1632
1633   if (EXPR_HISTORY_OF_CHANGES (from))
1634     {
1635       unsigned i;
1636       expr_history_def *phist;
1637
1638       temp = VEC_copy (expr_history_def, heap, EXPR_HISTORY_OF_CHANGES (from));
1639       for (i = 0;
1640            VEC_iterate (expr_history_def, temp, i, phist);
1641            i++)
1642         {
1643           vinsn_attach (phist->old_expr_vinsn);
1644           vinsn_attach (phist->new_expr_vinsn);
1645         }
1646     }
1647
1648   init_expr (to, EXPR_VINSN (from), EXPR_SPEC (from),
1649              EXPR_USEFULNESS (from), EXPR_PRIORITY (from),
1650              EXPR_SCHED_TIMES (from), EXPR_ORIG_BB_INDEX (from),
1651              EXPR_SPEC_DONE_DS (from), EXPR_SPEC_TO_CHECK_DS (from),
1652              EXPR_ORIG_SCHED_CYCLE (from), temp,
1653              EXPR_TARGET_AVAILABLE (from), EXPR_WAS_SUBSTITUTED (from),
1654              EXPR_WAS_RENAMED (from), EXPR_NEEDS_SPEC_CHECK_P (from),
1655              EXPR_CANT_MOVE (from));
1656 }
1657
1658 /* Same, but the final expr will not ever be in av sets, so don't copy
1659    "uninteresting" data such as bitmap cache.  */
1660 void
1661 copy_expr_onside (expr_t to, expr_t from)
1662 {
1663   init_expr (to, EXPR_VINSN (from), EXPR_SPEC (from), EXPR_USEFULNESS (from),
1664              EXPR_PRIORITY (from), EXPR_SCHED_TIMES (from), 0,
1665              EXPR_SPEC_DONE_DS (from), EXPR_SPEC_TO_CHECK_DS (from), 0, NULL,
1666              EXPR_TARGET_AVAILABLE (from), EXPR_WAS_SUBSTITUTED (from),
1667              EXPR_WAS_RENAMED (from), EXPR_NEEDS_SPEC_CHECK_P (from),
1668              EXPR_CANT_MOVE (from));
1669 }
1670
1671 /* Prepare the expr of INSN for scheduling.  Used when moving insn and when
1672    initializing new insns.  */
1673 static void
1674 prepare_insn_expr (insn_t insn, int seqno)
1675 {
1676   expr_t expr = INSN_EXPR (insn);
1677   ds_t ds;
1678
1679   INSN_SEQNO (insn) = seqno;
1680   EXPR_ORIG_BB_INDEX (expr) = BLOCK_NUM (insn);
1681   EXPR_SPEC (expr) = 0;
1682   EXPR_ORIG_SCHED_CYCLE (expr) = 0;
1683   EXPR_WAS_SUBSTITUTED (expr) = 0;
1684   EXPR_WAS_RENAMED (expr) = 0;
1685   EXPR_TARGET_AVAILABLE (expr) = 1;
1686   INSN_LIVE_VALID_P (insn) = false;
1687
1688   /* ??? If this expression is speculative, make its dependence
1689      as weak as possible.  We can filter this expression later
1690      in process_spec_exprs, because we do not distinguish
1691      between the status we got during compute_av_set and the
1692      existing status.  To be fixed.  */
1693   ds = EXPR_SPEC_DONE_DS (expr);
1694   if (ds)
1695     EXPR_SPEC_DONE_DS (expr) = ds_get_max_dep_weak (ds);
1696
1697   free_history_vect (&EXPR_HISTORY_OF_CHANGES (expr));
1698 }
1699
1700 /* Update target_available bits when merging exprs TO and FROM.  SPLIT_POINT
1701    is non-null when expressions are merged from different successors at
1702    a split point.  */
1703 static void
1704 update_target_availability (expr_t to, expr_t from, insn_t split_point)
1705 {
1706   if (EXPR_TARGET_AVAILABLE (to) < 0
1707       || EXPR_TARGET_AVAILABLE (from) < 0)
1708     EXPR_TARGET_AVAILABLE (to) = -1;
1709   else
1710     {
1711       /* We try to detect the case when one of the expressions
1712          can only be reached through another one.  In this case,
1713          we can do better.  */
1714       if (split_point == NULL)
1715         {
1716           int toind, fromind;
1717
1718           toind = EXPR_ORIG_BB_INDEX (to);
1719           fromind = EXPR_ORIG_BB_INDEX (from);
1720
1721           if (toind && toind == fromind)
1722             /* Do nothing -- everything is done in
1723                merge_with_other_exprs.  */
1724             ;
1725           else
1726             EXPR_TARGET_AVAILABLE (to) = -1;
1727         }
1728       else
1729         EXPR_TARGET_AVAILABLE (to) &= EXPR_TARGET_AVAILABLE (from);
1730     }
1731 }
1732
1733 /* Update speculation bits when merging exprs TO and FROM.  SPLIT_POINT
1734    is non-null when expressions are merged from different successors at
1735    a split point.  */
1736 static void
1737 update_speculative_bits (expr_t to, expr_t from, insn_t split_point)
1738 {
1739   ds_t old_to_ds, old_from_ds;
1740
1741   old_to_ds = EXPR_SPEC_DONE_DS (to);
1742   old_from_ds = EXPR_SPEC_DONE_DS (from);
1743
1744   EXPR_SPEC_DONE_DS (to) = ds_max_merge (old_to_ds, old_from_ds);
1745   EXPR_SPEC_TO_CHECK_DS (to) |= EXPR_SPEC_TO_CHECK_DS (from);
1746   EXPR_NEEDS_SPEC_CHECK_P (to) |= EXPR_NEEDS_SPEC_CHECK_P (from);
1747
1748   /* When merging e.g. control & data speculative exprs, or a control
1749      speculative with a control&data speculative one, we really have
1750      to change vinsn too.  Also, when speculative status is changed,
1751      we also need to record this as a transformation in expr's history.  */
1752   if ((old_to_ds & SPECULATIVE) || (old_from_ds & SPECULATIVE))
1753     {
1754       old_to_ds = ds_get_speculation_types (old_to_ds);
1755       old_from_ds = ds_get_speculation_types (old_from_ds);
1756
1757       if (old_to_ds != old_from_ds)
1758         {
1759           ds_t record_ds;
1760
1761           /* When both expressions are speculative, we need to change
1762              the vinsn first.  */
1763           if ((old_to_ds & SPECULATIVE) && (old_from_ds & SPECULATIVE))
1764             {
1765               int res;
1766
1767               res = speculate_expr (to, EXPR_SPEC_DONE_DS (to));
1768               gcc_assert (res >= 0);
1769             }
1770
1771           if (split_point != NULL)
1772             {
1773               /* Record the change with proper status.  */
1774               record_ds = EXPR_SPEC_DONE_DS (to) & SPECULATIVE;
1775               record_ds &= ~(old_to_ds & SPECULATIVE);
1776               record_ds &= ~(old_from_ds & SPECULATIVE);
1777
1778               insert_in_history_vect (&EXPR_HISTORY_OF_CHANGES (to),
1779                                       INSN_UID (split_point), TRANS_SPECULATION,
1780                                       EXPR_VINSN (from), EXPR_VINSN (to),
1781                                       record_ds);
1782             }
1783         }
1784     }
1785 }
1786
1787
1788 /* Merge bits of FROM expr to TO expr.  When SPLIT_POINT is not NULL,
1789    this is done along different paths.  */
1790 void
1791 merge_expr_data (expr_t to, expr_t from, insn_t split_point)
1792 {
1793   int i;
1794   expr_history_def *phist;
1795
1796   /* For now, we just set the spec of resulting expr to be minimum of the specs
1797      of merged exprs.  */
1798   if (EXPR_SPEC (to) > EXPR_SPEC (from))
1799     EXPR_SPEC (to) = EXPR_SPEC (from);
1800
1801   if (split_point)
1802     EXPR_USEFULNESS (to) += EXPR_USEFULNESS (from);
1803   else
1804     EXPR_USEFULNESS (to) = MAX (EXPR_USEFULNESS (to),
1805                                 EXPR_USEFULNESS (from));
1806
1807   if (EXPR_PRIORITY (to) < EXPR_PRIORITY (from))
1808     EXPR_PRIORITY (to) = EXPR_PRIORITY (from);
1809
1810   if (EXPR_SCHED_TIMES (to) > EXPR_SCHED_TIMES (from))
1811     EXPR_SCHED_TIMES (to) = EXPR_SCHED_TIMES (from);
1812
1813   if (EXPR_ORIG_BB_INDEX (to) != EXPR_ORIG_BB_INDEX (from))
1814     EXPR_ORIG_BB_INDEX (to) = 0;
1815
1816   EXPR_ORIG_SCHED_CYCLE (to) = MIN (EXPR_ORIG_SCHED_CYCLE (to),
1817                                     EXPR_ORIG_SCHED_CYCLE (from));
1818
1819   /* We keep this vector sorted.  */
1820   for (i = 0;
1821        VEC_iterate (expr_history_def, EXPR_HISTORY_OF_CHANGES (from),
1822                     i, phist);
1823        i++)
1824     insert_in_history_vect (&EXPR_HISTORY_OF_CHANGES (to),
1825                             phist->uid, phist->type,
1826                             phist->old_expr_vinsn, phist->new_expr_vinsn,
1827                             phist->spec_ds);
1828
1829   EXPR_WAS_SUBSTITUTED (to) |= EXPR_WAS_SUBSTITUTED (from);
1830   EXPR_WAS_RENAMED (to) |= EXPR_WAS_RENAMED (from);
1831   EXPR_CANT_MOVE (to) |= EXPR_CANT_MOVE (from);
1832
1833   update_target_availability (to, from, split_point);
1834   update_speculative_bits (to, from, split_point);
1835 }
1836
1837 /* Merge bits of FROM expr to TO expr.  Vinsns in the exprs should be equal
1838    in terms of vinsn_equal_p.  SPLIT_POINT is non-null when expressions
1839    are merged from different successors at a split point.  */
1840 void
1841 merge_expr (expr_t to, expr_t from, insn_t split_point)
1842 {
1843   vinsn_t to_vi = EXPR_VINSN (to);
1844   vinsn_t from_vi = EXPR_VINSN (from);
1845
1846   gcc_assert (vinsn_equal_p (to_vi, from_vi));
1847
1848   /* Make sure that speculative pattern is propagated into exprs that
1849      have non-speculative one.  This will provide us with consistent
1850      speculative bits and speculative patterns inside expr.  */
1851   if (EXPR_SPEC_DONE_DS (to) == 0
1852       && EXPR_SPEC_DONE_DS (from) != 0)
1853     change_vinsn_in_expr (to, EXPR_VINSN (from));
1854
1855   merge_expr_data (to, from, split_point);
1856   gcc_assert (EXPR_USEFULNESS (to) <= REG_BR_PROB_BASE);
1857 }
1858
1859 /* Clear the information of this EXPR.  */
1860 void
1861 clear_expr (expr_t expr)
1862 {
1863
1864   vinsn_detach (EXPR_VINSN (expr));
1865   EXPR_VINSN (expr) = NULL;
1866
1867   free_history_vect (&EXPR_HISTORY_OF_CHANGES (expr));
1868 }
1869
1870 /* For a given LV_SET, mark EXPR having unavailable target register.  */
1871 static void
1872 set_unavailable_target_for_expr (expr_t expr, regset lv_set)
1873 {
1874   if (EXPR_SEPARABLE_P (expr))
1875     {
1876       if (REG_P (EXPR_LHS (expr))
1877           && bitmap_bit_p (lv_set, REGNO (EXPR_LHS (expr))))
1878         {
1879           /* If it's an insn like r1 = use (r1, ...), and it exists in
1880              different forms in each of the av_sets being merged, we can't say
1881              whether original destination register is available or not.
1882              However, this still works if destination register is not used
1883              in the original expression: if the branch at which LV_SET we're
1884              looking here is not actually 'other branch' in sense that same
1885              expression is available through it (but it can't be determined
1886              at computation stage because of transformations on one of the
1887              branches), it still won't affect the availability.
1888              Liveness of a register somewhere on a code motion path means
1889              it's either read somewhere on a codemotion path, live on
1890              'other' branch, live at the point immediately following
1891              the original operation, or is read by the original operation.
1892              The latter case is filtered out in the condition below.
1893              It still doesn't cover the case when register is defined and used
1894              somewhere within the code motion path, and in this case we could
1895              miss a unifying code motion along both branches using a renamed
1896              register, but it won't affect a code correctness since upon
1897              an actual code motion a bookkeeping code would be generated.  */
1898           if (bitmap_bit_p (VINSN_REG_USES (EXPR_VINSN (expr)),
1899                             REGNO (EXPR_LHS (expr))))
1900             EXPR_TARGET_AVAILABLE (expr) = -1;
1901           else
1902             EXPR_TARGET_AVAILABLE (expr) = false;
1903         }
1904     }
1905   else
1906     {
1907       unsigned regno;
1908       reg_set_iterator rsi;
1909
1910       EXECUTE_IF_SET_IN_REG_SET (VINSN_REG_SETS (EXPR_VINSN (expr)),
1911                                  0, regno, rsi)
1912         if (bitmap_bit_p (lv_set, regno))
1913           {
1914             EXPR_TARGET_AVAILABLE (expr) = false;
1915             break;
1916           }
1917
1918       EXECUTE_IF_SET_IN_REG_SET (VINSN_REG_CLOBBERS (EXPR_VINSN (expr)),
1919                                  0, regno, rsi)
1920         if (bitmap_bit_p (lv_set, regno))
1921           {
1922             EXPR_TARGET_AVAILABLE (expr) = false;
1923             break;
1924           }
1925     }
1926 }
1927
1928 /* Try to make EXPR speculative.  Return 1 when EXPR's pattern
1929    or dependence status have changed, 2 when also the target register
1930    became unavailable, 0 if nothing had to be changed.  */
1931 int
1932 speculate_expr (expr_t expr, ds_t ds)
1933 {
1934   int res;
1935   rtx orig_insn_rtx;
1936   rtx spec_pat;
1937   ds_t target_ds, current_ds;
1938
1939   /* Obtain the status we need to put on EXPR.   */
1940   target_ds = (ds & SPECULATIVE);
1941   current_ds = EXPR_SPEC_DONE_DS (expr);
1942   ds = ds_full_merge (current_ds, target_ds, NULL_RTX, NULL_RTX);
1943
1944   orig_insn_rtx = EXPR_INSN_RTX (expr);
1945
1946   res = sched_speculate_insn (orig_insn_rtx, ds, &spec_pat);
1947
1948   switch (res)
1949     {
1950     case 0:
1951       EXPR_SPEC_DONE_DS (expr) = ds;
1952       return current_ds != ds ? 1 : 0;
1953
1954     case 1:
1955       {
1956         rtx spec_insn_rtx = create_insn_rtx_from_pattern (spec_pat, NULL_RTX);
1957         vinsn_t spec_vinsn = create_vinsn_from_insn_rtx (spec_insn_rtx, false);
1958
1959         change_vinsn_in_expr (expr, spec_vinsn);
1960         EXPR_SPEC_DONE_DS (expr) = ds;
1961         EXPR_NEEDS_SPEC_CHECK_P (expr) = true;
1962
1963         /* Do not allow clobbering the address register of speculative
1964            insns.  */
1965         if (bitmap_bit_p (VINSN_REG_USES (EXPR_VINSN (expr)),
1966                           expr_dest_regno (expr)))
1967           {
1968             EXPR_TARGET_AVAILABLE (expr) = false;
1969             return 2;
1970           }
1971
1972         return 1;
1973       }
1974
1975     case -1:
1976       return -1;
1977
1978     default:
1979       gcc_unreachable ();
1980       return -1;
1981     }
1982 }
1983
1984 /* Return a destination register, if any, of EXPR.  */
1985 rtx
1986 expr_dest_reg (expr_t expr)
1987 {
1988   rtx dest = VINSN_LHS (EXPR_VINSN (expr));
1989
1990   if (dest != NULL_RTX && REG_P (dest))
1991     return dest;
1992
1993   return NULL_RTX;
1994 }
1995
1996 /* Returns the REGNO of the R's destination.  */
1997 unsigned
1998 expr_dest_regno (expr_t expr)
1999 {
2000   rtx dest = expr_dest_reg (expr);
2001
2002   gcc_assert (dest != NULL_RTX);
2003   return REGNO (dest);
2004 }
2005
2006 /* For a given LV_SET, mark all expressions in JOIN_SET, but not present in
2007    AV_SET having unavailable target register.  */
2008 void
2009 mark_unavailable_targets (av_set_t join_set, av_set_t av_set, regset lv_set)
2010 {
2011   expr_t expr;
2012   av_set_iterator avi;
2013
2014   FOR_EACH_EXPR (expr, avi, join_set)
2015     if (av_set_lookup (av_set, EXPR_VINSN (expr)) == NULL)
2016       set_unavailable_target_for_expr (expr, lv_set);
2017 }
2018 \f
2019
2020 /* Av set functions.  */
2021
2022 /* Add a new element to av set SETP.
2023    Return the element added.  */
2024 static av_set_t
2025 av_set_add_element (av_set_t *setp)
2026 {
2027   /* Insert at the beginning of the list.  */
2028   _list_add (setp);
2029   return *setp;
2030 }
2031
2032 /* Add EXPR to SETP.  */
2033 void
2034 av_set_add (av_set_t *setp, expr_t expr)
2035 {
2036   av_set_t elem;
2037
2038   gcc_assert (!INSN_NOP_P (EXPR_INSN_RTX (expr)));
2039   elem = av_set_add_element (setp);
2040   copy_expr (_AV_SET_EXPR (elem), expr);
2041 }
2042
2043 /* Same, but do not copy EXPR.  */
2044 static void
2045 av_set_add_nocopy (av_set_t *setp, expr_t expr)
2046 {
2047   av_set_t elem;
2048
2049   elem = av_set_add_element (setp);
2050   *_AV_SET_EXPR (elem) = *expr;
2051 }
2052
2053 /* Remove expr pointed to by IP from the av_set.  */
2054 void
2055 av_set_iter_remove (av_set_iterator *ip)
2056 {
2057   clear_expr (_AV_SET_EXPR (*ip->lp));
2058   _list_iter_remove (ip);
2059 }
2060
2061 /* Search for an expr in SET, such that it's equivalent to SOUGHT_VINSN in the
2062    sense of vinsn_equal_p function. Return NULL if no such expr is
2063    in SET was found.  */
2064 expr_t
2065 av_set_lookup (av_set_t set, vinsn_t sought_vinsn)
2066 {
2067   expr_t expr;
2068   av_set_iterator i;
2069
2070   FOR_EACH_EXPR (expr, i, set)
2071     if (vinsn_equal_p (EXPR_VINSN (expr), sought_vinsn))
2072       return expr;
2073   return NULL;
2074 }
2075
2076 /* Same, but also remove the EXPR found.   */
2077 static expr_t
2078 av_set_lookup_and_remove (av_set_t *setp, vinsn_t sought_vinsn)
2079 {
2080   expr_t expr;
2081   av_set_iterator i;
2082
2083   FOR_EACH_EXPR_1 (expr, i, setp)
2084     if (vinsn_equal_p (EXPR_VINSN (expr), sought_vinsn))
2085       {
2086         _list_iter_remove_nofree (&i);
2087         return expr;
2088       }
2089   return NULL;
2090 }
2091
2092 /* Search for an expr in SET, such that it's equivalent to EXPR in the
2093    sense of vinsn_equal_p function of their vinsns, but not EXPR itself.
2094    Returns NULL if no such expr is in SET was found.  */
2095 static expr_t
2096 av_set_lookup_other_equiv_expr (av_set_t set, expr_t expr)
2097 {
2098   expr_t cur_expr;
2099   av_set_iterator i;
2100
2101   FOR_EACH_EXPR (cur_expr, i, set)
2102     {
2103       if (cur_expr == expr)
2104         continue;
2105       if (vinsn_equal_p (EXPR_VINSN (cur_expr), EXPR_VINSN (expr)))
2106         return cur_expr;
2107     }
2108
2109   return NULL;
2110 }
2111
2112 /* If other expression is already in AVP, remove one of them.  */
2113 expr_t
2114 merge_with_other_exprs (av_set_t *avp, av_set_iterator *ip, expr_t expr)
2115 {
2116   expr_t expr2;
2117
2118   expr2 = av_set_lookup_other_equiv_expr (*avp, expr);
2119   if (expr2 != NULL)
2120     {
2121       /* Reset target availability on merge, since taking it only from one
2122          of the exprs would be controversial for different code.  */
2123       EXPR_TARGET_AVAILABLE (expr2) = -1;
2124       EXPR_USEFULNESS (expr2) = 0;
2125
2126       merge_expr (expr2, expr, NULL);
2127
2128       /* Fix usefulness as it should be now REG_BR_PROB_BASE.  */
2129       EXPR_USEFULNESS (expr2) = REG_BR_PROB_BASE;
2130
2131       av_set_iter_remove (ip);
2132       return expr2;
2133     }
2134
2135   return expr;
2136 }
2137
2138 /* Return true if there is an expr that correlates to VI in SET.  */
2139 bool
2140 av_set_is_in_p (av_set_t set, vinsn_t vi)
2141 {
2142   return av_set_lookup (set, vi) != NULL;
2143 }
2144
2145 /* Return a copy of SET.  */
2146 av_set_t
2147 av_set_copy (av_set_t set)
2148 {
2149   expr_t expr;
2150   av_set_iterator i;
2151   av_set_t res = NULL;
2152
2153   FOR_EACH_EXPR (expr, i, set)
2154     av_set_add (&res, expr);
2155
2156   return res;
2157 }
2158
2159 /* Join two av sets that do not have common elements by attaching second set
2160    (pointed to by FROMP) to the end of first set (TO_TAILP must point to
2161    _AV_SET_NEXT of first set's last element).  */
2162 static void
2163 join_distinct_sets (av_set_t *to_tailp, av_set_t *fromp)
2164 {
2165   gcc_assert (*to_tailp == NULL);
2166   *to_tailp = *fromp;
2167   *fromp = NULL;
2168 }
2169
2170 /* Makes set pointed to by TO to be the union of TO and FROM.  Clear av_set
2171    pointed to by FROMP afterwards.  */
2172 void
2173 av_set_union_and_clear (av_set_t *top, av_set_t *fromp, insn_t insn)
2174 {
2175   expr_t expr1;
2176   av_set_iterator i;
2177
2178   /* Delete from TOP all exprs, that present in FROMP.  */
2179   FOR_EACH_EXPR_1 (expr1, i, top)
2180     {
2181       expr_t expr2 = av_set_lookup (*fromp, EXPR_VINSN (expr1));
2182
2183       if (expr2)
2184         {
2185           merge_expr (expr2, expr1, insn);
2186           av_set_iter_remove (&i);
2187         }
2188     }
2189
2190   join_distinct_sets (i.lp, fromp);
2191 }
2192
2193 /* Same as above, but also update availability of target register in
2194    TOP judging by TO_LV_SET and FROM_LV_SET.  */
2195 void
2196 av_set_union_and_live (av_set_t *top, av_set_t *fromp, regset to_lv_set,
2197                        regset from_lv_set, insn_t insn)
2198 {
2199   expr_t expr1;
2200   av_set_iterator i;
2201   av_set_t *to_tailp, in_both_set = NULL;
2202
2203   /* Delete from TOP all expres, that present in FROMP.  */
2204   FOR_EACH_EXPR_1 (expr1, i, top)
2205     {
2206       expr_t expr2 = av_set_lookup_and_remove (fromp, EXPR_VINSN (expr1));
2207
2208       if (expr2)
2209         {
2210           /* It may be that the expressions have different destination
2211              registers, in which case we need to check liveness here.  */
2212           if (EXPR_SEPARABLE_P (expr1))
2213             {
2214               int regno1 = (REG_P (EXPR_LHS (expr1))
2215                             ? (int) expr_dest_regno (expr1) : -1);
2216               int regno2 = (REG_P (EXPR_LHS (expr2))
2217                             ? (int) expr_dest_regno (expr2) : -1);
2218
2219               /* ??? We don't have a way to check restrictions for
2220                *other* register on the current path, we did it only
2221                for the current target register.  Give up.  */
2222               if (regno1 != regno2)
2223                 EXPR_TARGET_AVAILABLE (expr2) = -1;
2224             }
2225           else if (EXPR_INSN_RTX (expr1) != EXPR_INSN_RTX (expr2))
2226             EXPR_TARGET_AVAILABLE (expr2) = -1;
2227
2228           merge_expr (expr2, expr1, insn);
2229           av_set_add_nocopy (&in_both_set, expr2);
2230           av_set_iter_remove (&i);
2231         }
2232       else
2233         /* EXPR1 is present in TOP, but not in FROMP.  Check it on
2234            FROM_LV_SET.  */
2235         set_unavailable_target_for_expr (expr1, from_lv_set);
2236     }
2237   to_tailp = i.lp;
2238
2239   /* These expressions are not present in TOP.  Check liveness
2240      restrictions on TO_LV_SET.  */
2241   FOR_EACH_EXPR (expr1, i, *fromp)
2242     set_unavailable_target_for_expr (expr1, to_lv_set);
2243
2244   join_distinct_sets (i.lp, &in_both_set);
2245   join_distinct_sets (to_tailp, fromp);
2246 }
2247
2248 /* Clear av_set pointed to by SETP.  */
2249 void
2250 av_set_clear (av_set_t *setp)
2251 {
2252   expr_t expr;
2253   av_set_iterator i;
2254
2255   FOR_EACH_EXPR_1 (expr, i, setp)
2256     av_set_iter_remove (&i);
2257
2258   gcc_assert (*setp == NULL);
2259 }
2260
2261 /* Leave only one non-speculative element in the SETP.  */
2262 void
2263 av_set_leave_one_nonspec (av_set_t *setp)
2264 {
2265   expr_t expr;
2266   av_set_iterator i;
2267   bool has_one_nonspec = false;
2268
2269   /* Keep all speculative exprs, and leave one non-speculative
2270      (the first one).  */
2271   FOR_EACH_EXPR_1 (expr, i, setp)
2272     {
2273       if (!EXPR_SPEC_DONE_DS (expr))
2274         {
2275           if (has_one_nonspec)
2276             av_set_iter_remove (&i);
2277           else
2278             has_one_nonspec = true;
2279         }
2280     }
2281 }
2282
2283 /* Return the N'th element of the SET.  */
2284 expr_t
2285 av_set_element (av_set_t set, int n)
2286 {
2287   expr_t expr;
2288   av_set_iterator i;
2289
2290   FOR_EACH_EXPR (expr, i, set)
2291     if (n-- == 0)
2292       return expr;
2293
2294   gcc_unreachable ();
2295   return NULL;
2296 }
2297
2298 /* Deletes all expressions from AVP that are conditional branches (IFs).  */
2299 void
2300 av_set_substract_cond_branches (av_set_t *avp)
2301 {
2302   av_set_iterator i;
2303   expr_t expr;
2304
2305   FOR_EACH_EXPR_1 (expr, i, avp)
2306     if (vinsn_cond_branch_p (EXPR_VINSN (expr)))
2307       av_set_iter_remove (&i);
2308 }
2309
2310 /* Multiplies usefulness attribute of each member of av-set *AVP by
2311    value PROB / ALL_PROB.  */
2312 void
2313 av_set_split_usefulness (av_set_t av, int prob, int all_prob)
2314 {
2315   av_set_iterator i;
2316   expr_t expr;
2317
2318   FOR_EACH_EXPR (expr, i, av)
2319     EXPR_USEFULNESS (expr) = (all_prob
2320                               ? (EXPR_USEFULNESS (expr) * prob) / all_prob
2321                               : 0);
2322 }
2323
2324 /* Leave in AVP only those expressions, which are present in AV,
2325    and return it.  */
2326 void
2327 av_set_intersect (av_set_t *avp, av_set_t av)
2328 {
2329   av_set_iterator i;
2330   expr_t expr;
2331
2332   FOR_EACH_EXPR_1 (expr, i, avp)
2333     if (av_set_lookup (av, EXPR_VINSN (expr)) == NULL)
2334       av_set_iter_remove (&i);
2335 }
2336
2337 \f
2338
2339 /* Dependence hooks to initialize insn data.  */
2340
2341 /* This is used in hooks callable from dependence analysis when initializing
2342    instruction's data.  */
2343 static struct
2344 {
2345   /* Where the dependence was found (lhs/rhs).  */
2346   deps_where_t where;
2347
2348   /* The actual data object to initialize.  */
2349   idata_t id;
2350
2351   /* True when the insn should not be made clonable.  */
2352   bool force_unique_p;
2353
2354   /* True when insn should be treated as of type USE, i.e. never renamed.  */
2355   bool force_use_p;
2356 } deps_init_id_data;
2357
2358
2359 /* Setup ID for INSN.  FORCE_UNIQUE_P is true when INSN should not be
2360    clonable.  */
2361 static void
2362 setup_id_for_insn (idata_t id, insn_t insn, bool force_unique_p)
2363 {
2364   int type;
2365
2366   /* Determine whether INSN could be cloned and return appropriate vinsn type.
2367      That clonable insns which can be separated into lhs and rhs have type SET.
2368      Other clonable insns have type USE.  */
2369   type = GET_CODE (insn);
2370
2371   /* Only regular insns could be cloned.  */
2372   if (type == INSN && !force_unique_p)
2373     type = SET;
2374   else if (type == JUMP_INSN && simplejump_p (insn))
2375     type = PC;
2376   else if (type == DEBUG_INSN)
2377     type = !force_unique_p ? USE : INSN;
2378
2379   IDATA_TYPE (id) = type;
2380   IDATA_REG_SETS (id) = get_clear_regset_from_pool ();
2381   IDATA_REG_USES (id) = get_clear_regset_from_pool ();
2382   IDATA_REG_CLOBBERS (id) = get_clear_regset_from_pool ();
2383 }
2384
2385 /* Start initializing insn data.  */
2386 static void
2387 deps_init_id_start_insn (insn_t insn)
2388 {
2389   gcc_assert (deps_init_id_data.where == DEPS_IN_NOWHERE);
2390
2391   setup_id_for_insn (deps_init_id_data.id, insn,
2392                      deps_init_id_data.force_unique_p);
2393   deps_init_id_data.where = DEPS_IN_INSN;
2394 }
2395
2396 /* Start initializing lhs data.  */
2397 static void
2398 deps_init_id_start_lhs (rtx lhs)
2399 {
2400   gcc_assert (deps_init_id_data.where == DEPS_IN_INSN);
2401   gcc_assert (IDATA_LHS (deps_init_id_data.id) == NULL);
2402
2403   if (IDATA_TYPE (deps_init_id_data.id) == SET)
2404     {
2405       IDATA_LHS (deps_init_id_data.id) = lhs;
2406       deps_init_id_data.where = DEPS_IN_LHS;
2407     }
2408 }
2409
2410 /* Finish initializing lhs data.  */
2411 static void
2412 deps_init_id_finish_lhs (void)
2413 {
2414   deps_init_id_data.where = DEPS_IN_INSN;
2415 }
2416
2417 /* Note a set of REGNO.  */
2418 static void
2419 deps_init_id_note_reg_set (int regno)
2420 {
2421   haifa_note_reg_set (regno);
2422
2423   if (deps_init_id_data.where == DEPS_IN_RHS)
2424     deps_init_id_data.force_use_p = true;
2425
2426   if (IDATA_TYPE (deps_init_id_data.id) != PC)
2427     SET_REGNO_REG_SET (IDATA_REG_SETS (deps_init_id_data.id), regno);
2428
2429 #ifdef STACK_REGS
2430   /* Make instructions that set stack registers to be ineligible for
2431      renaming to avoid issues with find_used_regs.  */
2432   if (IN_RANGE (regno, FIRST_STACK_REG, LAST_STACK_REG))
2433     deps_init_id_data.force_use_p = true;
2434 #endif
2435 }
2436
2437 /* Note a clobber of REGNO.  */
2438 static void
2439 deps_init_id_note_reg_clobber (int regno)
2440 {
2441   haifa_note_reg_clobber (regno);
2442
2443   if (deps_init_id_data.where == DEPS_IN_RHS)
2444     deps_init_id_data.force_use_p = true;
2445
2446   if (IDATA_TYPE (deps_init_id_data.id) != PC)
2447     SET_REGNO_REG_SET (IDATA_REG_CLOBBERS (deps_init_id_data.id), regno);
2448 }
2449
2450 /* Note a use of REGNO.  */
2451 static void
2452 deps_init_id_note_reg_use (int regno)
2453 {
2454   haifa_note_reg_use (regno);
2455
2456   if (IDATA_TYPE (deps_init_id_data.id) != PC)
2457     SET_REGNO_REG_SET (IDATA_REG_USES (deps_init_id_data.id), regno);
2458 }
2459
2460 /* Start initializing rhs data.  */
2461 static void
2462 deps_init_id_start_rhs (rtx rhs)
2463 {
2464   gcc_assert (deps_init_id_data.where == DEPS_IN_INSN);
2465
2466   /* And there was no sel_deps_reset_to_insn ().  */
2467   if (IDATA_LHS (deps_init_id_data.id) != NULL)
2468     {
2469       IDATA_RHS (deps_init_id_data.id) = rhs;
2470       deps_init_id_data.where = DEPS_IN_RHS;
2471     }
2472 }
2473
2474 /* Finish initializing rhs data.  */
2475 static void
2476 deps_init_id_finish_rhs (void)
2477 {
2478   gcc_assert (deps_init_id_data.where == DEPS_IN_RHS
2479               || deps_init_id_data.where == DEPS_IN_INSN);
2480   deps_init_id_data.where = DEPS_IN_INSN;
2481 }
2482
2483 /* Finish initializing insn data.  */
2484 static void
2485 deps_init_id_finish_insn (void)
2486 {
2487   gcc_assert (deps_init_id_data.where == DEPS_IN_INSN);
2488
2489   if (IDATA_TYPE (deps_init_id_data.id) == SET)
2490     {
2491       rtx lhs = IDATA_LHS (deps_init_id_data.id);
2492       rtx rhs = IDATA_RHS (deps_init_id_data.id);
2493
2494       if (lhs == NULL || rhs == NULL || !lhs_and_rhs_separable_p (lhs, rhs)
2495           || deps_init_id_data.force_use_p)
2496         {
2497           /* This should be a USE, as we don't want to schedule its RHS
2498              separately.  However, we still want to have them recorded
2499              for the purposes of substitution.  That's why we don't
2500              simply call downgrade_to_use () here.  */
2501           gcc_assert (IDATA_TYPE (deps_init_id_data.id) == SET);
2502           gcc_assert (!lhs == !rhs);
2503
2504           IDATA_TYPE (deps_init_id_data.id) = USE;
2505         }
2506     }
2507
2508   deps_init_id_data.where = DEPS_IN_NOWHERE;
2509 }
2510
2511 /* This is dependence info used for initializing insn's data.  */
2512 static struct sched_deps_info_def deps_init_id_sched_deps_info;
2513
2514 /* This initializes most of the static part of the above structure.  */
2515 static const struct sched_deps_info_def const_deps_init_id_sched_deps_info =
2516   {
2517     NULL,
2518
2519     deps_init_id_start_insn,
2520     deps_init_id_finish_insn,
2521     deps_init_id_start_lhs,
2522     deps_init_id_finish_lhs,
2523     deps_init_id_start_rhs,
2524     deps_init_id_finish_rhs,
2525     deps_init_id_note_reg_set,
2526     deps_init_id_note_reg_clobber,
2527     deps_init_id_note_reg_use,
2528     NULL, /* note_mem_dep */
2529     NULL, /* note_dep */
2530
2531     0, /* use_cselib */
2532     0, /* use_deps_list */
2533     0 /* generate_spec_deps */
2534   };
2535
2536 /* Initialize INSN's lhs and rhs in ID.  When FORCE_UNIQUE_P is true,
2537    we don't actually need information about lhs and rhs.  */
2538 static void
2539 setup_id_lhs_rhs (idata_t id, insn_t insn, bool force_unique_p)
2540 {
2541   rtx pat = PATTERN (insn);
2542
2543   if (NONJUMP_INSN_P (insn)
2544       && GET_CODE (pat) == SET
2545       && !force_unique_p)
2546     {
2547       IDATA_RHS (id) = SET_SRC (pat);
2548       IDATA_LHS (id) = SET_DEST (pat);
2549     }
2550   else
2551     IDATA_LHS (id) = IDATA_RHS (id) = NULL;
2552 }
2553
2554 /* Possibly downgrade INSN to USE.  */
2555 static void
2556 maybe_downgrade_id_to_use (idata_t id, insn_t insn)
2557 {
2558   bool must_be_use = false;
2559   unsigned uid = INSN_UID (insn);
2560   df_ref *rec;
2561   rtx lhs = IDATA_LHS (id);
2562   rtx rhs = IDATA_RHS (id);
2563
2564   /* We downgrade only SETs.  */
2565   if (IDATA_TYPE (id) != SET)
2566     return;
2567
2568   if (!lhs || !lhs_and_rhs_separable_p (lhs, rhs))
2569     {
2570       IDATA_TYPE (id) = USE;
2571       return;
2572     }
2573
2574   for (rec = DF_INSN_UID_DEFS (uid); *rec; rec++)
2575     {
2576       df_ref def = *rec;
2577
2578       if (DF_REF_INSN (def)
2579           && DF_REF_FLAGS_IS_SET (def, DF_REF_PRE_POST_MODIFY)
2580           && loc_mentioned_in_p (DF_REF_LOC (def), IDATA_RHS (id)))
2581         {
2582           must_be_use = true;
2583           break;
2584         }
2585
2586 #ifdef STACK_REGS
2587       /* Make instructions that set stack registers to be ineligible for
2588          renaming to avoid issues with find_used_regs.  */
2589       if (IN_RANGE (DF_REF_REGNO (def), FIRST_STACK_REG, LAST_STACK_REG))
2590         {
2591           must_be_use = true;
2592           break;
2593         }
2594 #endif
2595     }
2596
2597   if (must_be_use)
2598     IDATA_TYPE (id) = USE;
2599 }
2600
2601 /* Setup register sets describing INSN in ID.  */
2602 static void
2603 setup_id_reg_sets (idata_t id, insn_t insn)
2604 {
2605   unsigned uid = INSN_UID (insn);
2606   df_ref *rec;
2607   regset tmp = get_clear_regset_from_pool ();
2608
2609   for (rec = DF_INSN_UID_DEFS (uid); *rec; rec++)
2610     {
2611       df_ref def = *rec;
2612       unsigned int regno = DF_REF_REGNO (def);
2613
2614       /* Post modifies are treated like clobbers by sched-deps.c.  */
2615       if (DF_REF_FLAGS_IS_SET (def, (DF_REF_MUST_CLOBBER
2616                                      | DF_REF_PRE_POST_MODIFY)))
2617         SET_REGNO_REG_SET (IDATA_REG_CLOBBERS (id), regno);
2618       else if (! DF_REF_FLAGS_IS_SET (def, DF_REF_MAY_CLOBBER))
2619         {
2620           SET_REGNO_REG_SET (IDATA_REG_SETS (id), regno);
2621
2622 #ifdef STACK_REGS
2623           /* For stack registers, treat writes to them as writes
2624              to the first one to be consistent with sched-deps.c.  */
2625           if (IN_RANGE (regno, FIRST_STACK_REG, LAST_STACK_REG))
2626             SET_REGNO_REG_SET (IDATA_REG_SETS (id), FIRST_STACK_REG);
2627 #endif
2628         }
2629       /* Mark special refs that generate read/write def pair.  */
2630       if (DF_REF_FLAGS_IS_SET (def, DF_REF_CONDITIONAL)
2631           || regno == STACK_POINTER_REGNUM)
2632         bitmap_set_bit (tmp, regno);
2633     }
2634
2635   for (rec = DF_INSN_UID_USES (uid); *rec; rec++)
2636     {
2637       df_ref use = *rec;
2638       unsigned int regno = DF_REF_REGNO (use);
2639
2640       /* When these refs are met for the first time, skip them, as
2641          these uses are just counterparts of some defs.  */
2642       if (bitmap_bit_p (tmp, regno))
2643         bitmap_clear_bit (tmp, regno);
2644       else if (! DF_REF_FLAGS_IS_SET (use, DF_REF_CALL_STACK_USAGE))
2645         {
2646           SET_REGNO_REG_SET (IDATA_REG_USES (id), regno);
2647
2648 #ifdef STACK_REGS
2649           /* For stack registers, treat reads from them as reads from
2650              the first one to be consistent with sched-deps.c.  */
2651           if (IN_RANGE (regno, FIRST_STACK_REG, LAST_STACK_REG))
2652             SET_REGNO_REG_SET (IDATA_REG_USES (id), FIRST_STACK_REG);
2653 #endif
2654         }
2655     }
2656
2657   return_regset_to_pool (tmp);
2658 }
2659
2660 /* Initialize instruction data for INSN in ID using DF's data.  */
2661 static void
2662 init_id_from_df (idata_t id, insn_t insn, bool force_unique_p)
2663 {
2664   gcc_assert (DF_INSN_UID_SAFE_GET (INSN_UID (insn)) != NULL);
2665
2666   setup_id_for_insn (id, insn, force_unique_p);
2667   setup_id_lhs_rhs (id, insn, force_unique_p);
2668
2669   if (INSN_NOP_P (insn))
2670     return;
2671
2672   maybe_downgrade_id_to_use (id, insn);
2673   setup_id_reg_sets (id, insn);
2674 }
2675
2676 /* Initialize instruction data for INSN in ID.  */
2677 static void
2678 deps_init_id (idata_t id, insn_t insn, bool force_unique_p)
2679 {
2680   struct deps_desc _dc, *dc = &_dc;
2681
2682   deps_init_id_data.where = DEPS_IN_NOWHERE;
2683   deps_init_id_data.id = id;
2684   deps_init_id_data.force_unique_p = force_unique_p;
2685   deps_init_id_data.force_use_p = false;
2686
2687   init_deps (dc, false);
2688
2689   memcpy (&deps_init_id_sched_deps_info,
2690           &const_deps_init_id_sched_deps_info,
2691           sizeof (deps_init_id_sched_deps_info));
2692
2693   if (spec_info != NULL)
2694     deps_init_id_sched_deps_info.generate_spec_deps = 1;
2695
2696   sched_deps_info = &deps_init_id_sched_deps_info;
2697
2698   deps_analyze_insn (dc, insn);
2699
2700   free_deps (dc);
2701
2702   deps_init_id_data.id = NULL;
2703 }
2704
2705 \f
2706
2707 /* Implement hooks for collecting fundamental insn properties like if insn is
2708    an ASM or is within a SCHED_GROUP.  */
2709
2710 /* True when a "one-time init" data for INSN was already inited.  */
2711 static bool
2712 first_time_insn_init (insn_t insn)
2713 {
2714   return INSN_LIVE (insn) == NULL;
2715 }
2716
2717 /* Hash an entry in a transformed_insns hashtable.  */
2718 static hashval_t
2719 hash_transformed_insns (const void *p)
2720 {
2721   return VINSN_HASH_RTX (((const struct transformed_insns *) p)->vinsn_old);
2722 }
2723
2724 /* Compare the entries in a transformed_insns hashtable.  */
2725 static int
2726 eq_transformed_insns (const void *p, const void *q)
2727 {
2728   rtx i1 = VINSN_INSN_RTX (((const struct transformed_insns *) p)->vinsn_old);
2729   rtx i2 = VINSN_INSN_RTX (((const struct transformed_insns *) q)->vinsn_old);
2730
2731   if (INSN_UID (i1) == INSN_UID (i2))
2732     return 1;
2733   return rtx_equal_p (PATTERN (i1), PATTERN (i2));
2734 }
2735
2736 /* Free an entry in a transformed_insns hashtable.  */
2737 static void
2738 free_transformed_insns (void *p)
2739 {
2740   struct transformed_insns *pti = (struct transformed_insns *) p;
2741
2742   vinsn_detach (pti->vinsn_old);
2743   vinsn_detach (pti->vinsn_new);
2744   free (pti);
2745 }
2746
2747 /* Init the s_i_d data for INSN which should be inited just once, when
2748    we first see the insn.  */
2749 static void
2750 init_first_time_insn_data (insn_t insn)
2751 {
2752   /* This should not be set if this is the first time we init data for
2753      insn.  */
2754   gcc_assert (first_time_insn_init (insn));
2755
2756   /* These are needed for nops too.  */
2757   INSN_LIVE (insn) = get_regset_from_pool ();
2758   INSN_LIVE_VALID_P (insn) = false;
2759
2760   if (!INSN_NOP_P (insn))
2761     {
2762       INSN_ANALYZED_DEPS (insn) = BITMAP_ALLOC (NULL);
2763       INSN_FOUND_DEPS (insn) = BITMAP_ALLOC (NULL);
2764       INSN_TRANSFORMED_INSNS (insn)
2765         = htab_create (16, hash_transformed_insns,
2766                        eq_transformed_insns, free_transformed_insns);
2767       init_deps (&INSN_DEPS_CONTEXT (insn), true);
2768     }
2769 }
2770
2771 /* Free almost all above data for INSN that is scheduled already.
2772    Used for extra-large basic blocks.  */
2773 void
2774 free_data_for_scheduled_insn (insn_t insn)
2775 {
2776   gcc_assert (! first_time_insn_init (insn));
2777
2778   if (! INSN_ANALYZED_DEPS (insn))
2779     return;
2780
2781   BITMAP_FREE (INSN_ANALYZED_DEPS (insn));
2782   BITMAP_FREE (INSN_FOUND_DEPS (insn));
2783   htab_delete (INSN_TRANSFORMED_INSNS (insn));
2784
2785   /* This is allocated only for bookkeeping insns.  */
2786   if (INSN_ORIGINATORS (insn))
2787     BITMAP_FREE (INSN_ORIGINATORS (insn));
2788   free_deps (&INSN_DEPS_CONTEXT (insn));
2789
2790   INSN_ANALYZED_DEPS (insn) = NULL;
2791
2792   /* Clear the readonly flag so we would ICE when trying to recalculate
2793      the deps context (as we believe that it should not happen).  */
2794   (&INSN_DEPS_CONTEXT (insn))->readonly = 0;
2795 }
2796
2797 /* Free the same data as above for INSN.  */
2798 static void
2799 free_first_time_insn_data (insn_t insn)
2800 {
2801   gcc_assert (! first_time_insn_init (insn));
2802
2803   free_data_for_scheduled_insn (insn);
2804   return_regset_to_pool (INSN_LIVE (insn));
2805   INSN_LIVE (insn) = NULL;
2806   INSN_LIVE_VALID_P (insn) = false;
2807 }
2808
2809 /* Initialize region-scope data structures for basic blocks.  */
2810 static void
2811 init_global_and_expr_for_bb (basic_block bb)
2812 {
2813   if (sel_bb_empty_p (bb))
2814     return;
2815
2816   invalidate_av_set (bb);
2817 }
2818
2819 /* Data for global dependency analysis (to initialize CANT_MOVE and
2820    SCHED_GROUP_P).  */
2821 static struct
2822 {
2823   /* Previous insn.  */
2824   insn_t prev_insn;
2825 } init_global_data;
2826
2827 /* Determine if INSN is in the sched_group, is an asm or should not be
2828    cloned.  After that initialize its expr.  */
2829 static void
2830 init_global_and_expr_for_insn (insn_t insn)
2831 {
2832   if (LABEL_P (insn))
2833     return;
2834
2835   if (NOTE_INSN_BASIC_BLOCK_P (insn))
2836     {
2837       init_global_data.prev_insn = NULL_RTX;
2838       return;
2839     }
2840
2841   gcc_assert (INSN_P (insn));
2842
2843   if (SCHED_GROUP_P (insn))
2844     /* Setup a sched_group.  */
2845     {
2846       insn_t prev_insn = init_global_data.prev_insn;
2847
2848       if (prev_insn)
2849         INSN_SCHED_NEXT (prev_insn) = insn;
2850
2851       init_global_data.prev_insn = insn;
2852     }
2853   else
2854     init_global_data.prev_insn = NULL_RTX;
2855
2856   if (GET_CODE (PATTERN (insn)) == ASM_INPUT
2857       || asm_noperands (PATTERN (insn)) >= 0)
2858     /* Mark INSN as an asm.  */
2859     INSN_ASM_P (insn) = true;
2860
2861   {
2862     bool force_unique_p;
2863     ds_t spec_done_ds;
2864
2865     /* Certain instructions cannot be cloned, and frame related insns and
2866        the insn adjacent to NOTE_INSN_EPILOGUE_BEG cannot be moved out of
2867        their block.  */
2868     if (prologue_epilogue_contains (insn))
2869       {
2870         if (RTX_FRAME_RELATED_P (insn))
2871           CANT_MOVE (insn) = 1;
2872         else
2873           {
2874             rtx note;
2875             for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
2876               if (REG_NOTE_KIND (note) == REG_SAVE_NOTE
2877                   && ((enum insn_note) INTVAL (XEXP (note, 0))
2878                       == NOTE_INSN_EPILOGUE_BEG))
2879                 {
2880                   CANT_MOVE (insn) = 1;
2881                   break;
2882                 }
2883           }
2884         force_unique_p = true;
2885       }
2886     else
2887       if (CANT_MOVE (insn)
2888           || INSN_ASM_P (insn)
2889           || SCHED_GROUP_P (insn)
2890           /* Exception handling insns are always unique.  */
2891           || (cfun->can_throw_non_call_exceptions && can_throw_internal (insn))
2892           /* TRAP_IF though have an INSN code is control_flow_insn_p ().  */
2893           || control_flow_insn_p (insn))
2894         force_unique_p = true;
2895       else
2896         force_unique_p = false;
2897
2898     if (targetm.sched.get_insn_spec_ds)
2899       {
2900         spec_done_ds = targetm.sched.get_insn_spec_ds (insn);
2901         spec_done_ds = ds_get_max_dep_weak (spec_done_ds);
2902       }
2903     else
2904       spec_done_ds = 0;
2905
2906     /* Initialize INSN's expr.  */
2907     init_expr (INSN_EXPR (insn), vinsn_create (insn, force_unique_p), 0,
2908                REG_BR_PROB_BASE, INSN_PRIORITY (insn), 0, BLOCK_NUM (insn),
2909                spec_done_ds, 0, 0, NULL, true, false, false, false,
2910                CANT_MOVE (insn));
2911   }
2912
2913   init_first_time_insn_data (insn);
2914 }
2915
2916 /* Scan the region and initialize instruction data for basic blocks BBS.  */
2917 void
2918 sel_init_global_and_expr (bb_vec_t bbs)
2919 {
2920   /* ??? It would be nice to implement push / pop scheme for sched_infos.  */
2921   const struct sched_scan_info_def ssi =
2922     {
2923       NULL, /* extend_bb */
2924       init_global_and_expr_for_bb, /* init_bb */
2925       extend_insn_data, /* extend_insn */
2926       init_global_and_expr_for_insn /* init_insn */
2927     };
2928
2929   sched_scan (&ssi, bbs, NULL, NULL, NULL);
2930 }
2931
2932 /* Finalize region-scope data structures for basic blocks.  */
2933 static void
2934 finish_global_and_expr_for_bb (basic_block bb)
2935 {
2936   av_set_clear (&BB_AV_SET (bb));
2937   BB_AV_LEVEL (bb) = 0;
2938 }
2939
2940 /* Finalize INSN's data.  */
2941 static void
2942 finish_global_and_expr_insn (insn_t insn)
2943 {
2944   if (LABEL_P (insn) || NOTE_INSN_BASIC_BLOCK_P (insn))
2945     return;
2946
2947   gcc_assert (INSN_P (insn));
2948
2949   if (INSN_LUID (insn) > 0)
2950     {
2951       free_first_time_insn_data (insn);
2952       INSN_WS_LEVEL (insn) = 0;
2953       CANT_MOVE (insn) = 0;
2954
2955       /* We can no longer assert this, as vinsns of this insn could be
2956          easily live in other insn's caches.  This should be changed to
2957          a counter-like approach among all vinsns.  */
2958       gcc_assert (true || VINSN_COUNT (INSN_VINSN (insn)) == 1);
2959       clear_expr (INSN_EXPR (insn));
2960     }
2961 }
2962
2963 /* Finalize per instruction data for the whole region.  */
2964 void
2965 sel_finish_global_and_expr (void)
2966 {
2967   {
2968     bb_vec_t bbs;
2969     int i;
2970
2971     bbs = VEC_alloc (basic_block, heap, current_nr_blocks);
2972
2973     for (i = 0; i < current_nr_blocks; i++)
2974       VEC_quick_push (basic_block, bbs, BASIC_BLOCK (BB_TO_BLOCK (i)));
2975
2976     /* Clear AV_SETs and INSN_EXPRs.  */
2977     {
2978       const struct sched_scan_info_def ssi =
2979         {
2980           NULL, /* extend_bb */
2981           finish_global_and_expr_for_bb, /* init_bb */
2982           NULL, /* extend_insn */
2983           finish_global_and_expr_insn /* init_insn */
2984         };
2985
2986       sched_scan (&ssi, bbs, NULL, NULL, NULL);
2987     }
2988
2989     VEC_free (basic_block, heap, bbs);
2990   }
2991
2992   finish_insns ();
2993 }
2994 \f
2995
2996 /* In the below hooks, we merely calculate whether or not a dependence
2997    exists, and in what part of insn.  However, we will need more data
2998    when we'll start caching dependence requests.  */
2999
3000 /* Container to hold information for dependency analysis.  */
3001 static struct
3002 {
3003   deps_t dc;
3004
3005   /* A variable to track which part of rtx we are scanning in
3006      sched-deps.c: sched_analyze_insn ().  */
3007   deps_where_t where;
3008
3009   /* Current producer.  */
3010   insn_t pro;
3011
3012   /* Current consumer.  */
3013   vinsn_t con;
3014
3015   /* Is SEL_DEPS_HAS_DEP_P[DEPS_IN_X] is true, then X has a dependence.
3016      X is from { INSN, LHS, RHS }.  */
3017   ds_t has_dep_p[DEPS_IN_NOWHERE];
3018 } has_dependence_data;
3019
3020 /* Start analyzing dependencies of INSN.  */
3021 static void
3022 has_dependence_start_insn (insn_t insn ATTRIBUTE_UNUSED)
3023 {
3024   gcc_assert (has_dependence_data.where == DEPS_IN_NOWHERE);
3025
3026   has_dependence_data.where = DEPS_IN_INSN;
3027 }
3028
3029 /* Finish analyzing dependencies of an insn.  */
3030 static void
3031 has_dependence_finish_insn (void)
3032 {
3033   gcc_assert (has_dependence_data.where == DEPS_IN_INSN);
3034
3035   has_dependence_data.where = DEPS_IN_NOWHERE;
3036 }
3037
3038 /* Start analyzing dependencies of LHS.  */
3039 static void
3040 has_dependence_start_lhs (rtx lhs ATTRIBUTE_UNUSED)
3041 {
3042   gcc_assert (has_dependence_data.where == DEPS_IN_INSN);
3043
3044   if (VINSN_LHS (has_dependence_data.con) != NULL)
3045     has_dependence_data.where = DEPS_IN_LHS;
3046 }
3047
3048 /* Finish analyzing dependencies of an lhs.  */
3049 static void
3050 has_dependence_finish_lhs (void)
3051 {
3052   has_dependence_data.where = DEPS_IN_INSN;
3053 }
3054
3055 /* Start analyzing dependencies of RHS.  */
3056 static void
3057 has_dependence_start_rhs (rtx rhs ATTRIBUTE_UNUSED)
3058 {
3059   gcc_assert (has_dependence_data.where == DEPS_IN_INSN);
3060
3061   if (VINSN_RHS (has_dependence_data.con) != NULL)
3062     has_dependence_data.where = DEPS_IN_RHS;
3063 }
3064
3065 /* Start analyzing dependencies of an rhs.  */
3066 static void
3067 has_dependence_finish_rhs (void)
3068 {
3069   gcc_assert (has_dependence_data.where == DEPS_IN_RHS
3070               || has_dependence_data.where == DEPS_IN_INSN);
3071
3072   has_dependence_data.where = DEPS_IN_INSN;
3073 }
3074
3075 /* Note a set of REGNO.  */
3076 static void
3077 has_dependence_note_reg_set (int regno)
3078 {
3079   struct deps_reg *reg_last = &has_dependence_data.dc->reg_last[regno];
3080
3081   if (!sched_insns_conditions_mutex_p (has_dependence_data.pro,
3082                                        VINSN_INSN_RTX
3083                                        (has_dependence_data.con)))
3084     {
3085       ds_t *dsp = &has_dependence_data.has_dep_p[has_dependence_data.where];
3086
3087       if (reg_last->sets != NULL
3088           || reg_last->clobbers != NULL)
3089         *dsp = (*dsp & ~SPECULATIVE) | DEP_OUTPUT;
3090
3091       if (reg_last->uses)
3092         *dsp = (*dsp & ~SPECULATIVE) | DEP_ANTI;
3093     }
3094 }
3095
3096 /* Note a clobber of REGNO.  */
3097 static void
3098 has_dependence_note_reg_clobber (int regno)
3099 {
3100   struct deps_reg *reg_last = &has_dependence_data.dc->reg_last[regno];
3101
3102   if (!sched_insns_conditions_mutex_p (has_dependence_data.pro,
3103                                        VINSN_INSN_RTX
3104                                        (has_dependence_data.con)))
3105     {
3106       ds_t *dsp = &has_dependence_data.has_dep_p[has_dependence_data.where];
3107
3108       if (reg_last->sets)
3109         *dsp = (*dsp & ~SPECULATIVE) | DEP_OUTPUT;
3110
3111       if (reg_last->uses)
3112         *dsp = (*dsp & ~SPECULATIVE) | DEP_ANTI;
3113     }
3114 }
3115
3116 /* Note a use of REGNO.  */
3117 static void
3118 has_dependence_note_reg_use (int regno)
3119 {
3120   struct deps_reg *reg_last = &has_dependence_data.dc->reg_last[regno];
3121
3122   if (!sched_insns_conditions_mutex_p (has_dependence_data.pro,
3123                                        VINSN_INSN_RTX
3124                                        (has_dependence_data.con)))
3125     {
3126       ds_t *dsp = &has_dependence_data.has_dep_p[has_dependence_data.where];
3127
3128       if (reg_last->sets)
3129         *dsp = (*dsp & ~SPECULATIVE) | DEP_TRUE;
3130
3131       if (reg_last->clobbers)
3132         *dsp = (*dsp & ~SPECULATIVE) | DEP_ANTI;
3133
3134       /* Handle BE_IN_SPEC.  */
3135       if (reg_last->uses)
3136         {
3137           ds_t pro_spec_checked_ds;
3138
3139           pro_spec_checked_ds = INSN_SPEC_CHECKED_DS (has_dependence_data.pro);
3140           pro_spec_checked_ds = ds_get_max_dep_weak (pro_spec_checked_ds);
3141
3142           if (pro_spec_checked_ds != 0)
3143             /* Merge BE_IN_SPEC bits into *DSP.  */
3144             *dsp = ds_full_merge (*dsp, pro_spec_checked_ds,
3145                                   NULL_RTX, NULL_RTX);
3146         }
3147     }
3148 }
3149
3150 /* Note a memory dependence.  */
3151 static void
3152 has_dependence_note_mem_dep (rtx mem ATTRIBUTE_UNUSED,
3153                              rtx pending_mem ATTRIBUTE_UNUSED,
3154                              insn_t pending_insn ATTRIBUTE_UNUSED,
3155                              ds_t ds ATTRIBUTE_UNUSED)
3156 {
3157   if (!sched_insns_conditions_mutex_p (has_dependence_data.pro,
3158                                        VINSN_INSN_RTX (has_dependence_data.con)))
3159     {
3160       ds_t *dsp = &has_dependence_data.has_dep_p[has_dependence_data.where];
3161
3162       *dsp = ds_full_merge (ds, *dsp, pending_mem, mem);
3163     }
3164 }
3165
3166 /* Note a dependence.  */
3167 static void
3168 has_dependence_note_dep (insn_t pro ATTRIBUTE_UNUSED,
3169                          ds_t ds ATTRIBUTE_UNUSED)
3170 {
3171   if (!sched_insns_conditions_mutex_p (has_dependence_data.pro,
3172                                        VINSN_INSN_RTX (has_dependence_data.con)))
3173     {
3174       ds_t *dsp = &has_dependence_data.has_dep_p[has_dependence_data.where];
3175
3176       *dsp = ds_full_merge (ds, *dsp, NULL_RTX, NULL_RTX);
3177     }
3178 }
3179
3180 /* Mark the insn as having a hard dependence that prevents speculation.  */
3181 void
3182 sel_mark_hard_insn (rtx insn)
3183 {
3184   int i;
3185
3186   /* Only work when we're in has_dependence_p mode.
3187      ??? This is a hack, this should actually be a hook.  */
3188   if (!has_dependence_data.dc || !has_dependence_data.pro)
3189     return;
3190
3191   gcc_assert (insn == VINSN_INSN_RTX (has_dependence_data.con));
3192   gcc_assert (has_dependence_data.where == DEPS_IN_INSN);
3193
3194   for (i = 0; i < DEPS_IN_NOWHERE; i++)
3195     has_dependence_data.has_dep_p[i] &= ~SPECULATIVE;
3196 }
3197
3198 /* This structure holds the hooks for the dependency analysis used when
3199    actually processing dependencies in the scheduler.  */
3200 static struct sched_deps_info_def has_dependence_sched_deps_info;
3201
3202 /* This initializes most of the fields of the above structure.  */
3203 static const struct sched_deps_info_def const_has_dependence_sched_deps_info =
3204   {
3205     NULL,
3206
3207     has_dependence_start_insn,
3208     has_dependence_finish_insn,
3209     has_dependence_start_lhs,
3210     has_dependence_finish_lhs,
3211     has_dependence_start_rhs,
3212     has_dependence_finish_rhs,
3213     has_dependence_note_reg_set,
3214     has_dependence_note_reg_clobber,
3215     has_dependence_note_reg_use,
3216     has_dependence_note_mem_dep,
3217     has_dependence_note_dep,
3218
3219     0, /* use_cselib */
3220     0, /* use_deps_list */
3221     0 /* generate_spec_deps */
3222   };
3223
3224 /* Initialize has_dependence_sched_deps_info with extra spec field.  */
3225 static void
3226 setup_has_dependence_sched_deps_info (void)
3227 {
3228   memcpy (&has_dependence_sched_deps_info,
3229           &const_has_dependence_sched_deps_info,
3230           sizeof (has_dependence_sched_deps_info));
3231
3232   if (spec_info != NULL)
3233     has_dependence_sched_deps_info.generate_spec_deps = 1;
3234
3235   sched_deps_info = &has_dependence_sched_deps_info;
3236 }
3237
3238 /* Remove all dependences found and recorded in has_dependence_data array.  */
3239 void
3240 sel_clear_has_dependence (void)
3241 {
3242   int i;
3243
3244   for (i = 0; i < DEPS_IN_NOWHERE; i++)
3245     has_dependence_data.has_dep_p[i] = 0;
3246 }
3247
3248 /* Return nonzero if EXPR has is dependent upon PRED.  Return the pointer
3249    to the dependence information array in HAS_DEP_PP.  */
3250 ds_t
3251 has_dependence_p (expr_t expr, insn_t pred, ds_t **has_dep_pp)
3252 {
3253   int i;
3254   ds_t ds;
3255   struct deps_desc *dc;
3256
3257   if (INSN_SIMPLEJUMP_P (pred))
3258     /* Unconditional jump is just a transfer of control flow.
3259        Ignore it.  */
3260     return false;
3261
3262   dc = &INSN_DEPS_CONTEXT (pred);
3263
3264   /* We init this field lazily.  */
3265   if (dc->reg_last == NULL)
3266     init_deps_reg_last (dc);
3267
3268   if (!dc->readonly)
3269     {
3270       has_dependence_data.pro = NULL;
3271       /* Initialize empty dep context with information about PRED.  */
3272       advance_deps_context (dc, pred);
3273       dc->readonly = 1;
3274     }
3275
3276   has_dependence_data.where = DEPS_IN_NOWHERE;
3277   has_dependence_data.pro = pred;
3278   has_dependence_data.con = EXPR_VINSN (expr);
3279   has_dependence_data.dc = dc;
3280
3281   sel_clear_has_dependence ();
3282
3283   /* Now catch all dependencies that would be generated between PRED and
3284      INSN.  */
3285   setup_has_dependence_sched_deps_info ();
3286   deps_analyze_insn (dc, EXPR_INSN_RTX (expr));
3287   has_dependence_data.dc = NULL;
3288
3289   /* When a barrier was found, set DEPS_IN_INSN bits.  */
3290   if (dc->last_reg_pending_barrier == TRUE_BARRIER)
3291     has_dependence_data.has_dep_p[DEPS_IN_INSN] = DEP_TRUE;
3292   else if (dc->last_reg_pending_barrier == MOVE_BARRIER)
3293     has_dependence_data.has_dep_p[DEPS_IN_INSN] = DEP_ANTI;
3294
3295   /* Do not allow stores to memory to move through checks.  Currently
3296      we don't move this to sched-deps.c as the check doesn't have
3297      obvious places to which this dependence can be attached.
3298      FIMXE: this should go to a hook.  */
3299   if (EXPR_LHS (expr)
3300       && MEM_P (EXPR_LHS (expr))
3301       && sel_insn_is_speculation_check (pred))
3302     has_dependence_data.has_dep_p[DEPS_IN_INSN] = DEP_ANTI;
3303
3304   *has_dep_pp = has_dependence_data.has_dep_p;
3305   ds = 0;
3306   for (i = 0; i < DEPS_IN_NOWHERE; i++)
3307     ds = ds_full_merge (ds, has_dependence_data.has_dep_p[i],
3308                         NULL_RTX, NULL_RTX);
3309
3310   return ds;
3311 }
3312 \f
3313
3314 /* Dependence hooks implementation that checks dependence latency constraints
3315    on the insns being scheduled.  The entry point for these routines is
3316    tick_check_p predicate.  */
3317
3318 static struct
3319 {
3320   /* An expr we are currently checking.  */
3321   expr_t expr;
3322
3323   /* A minimal cycle for its scheduling.  */
3324   int cycle;
3325
3326   /* Whether we have seen a true dependence while checking.  */
3327   bool seen_true_dep_p;
3328 } tick_check_data;
3329
3330 /* Update minimal scheduling cycle for tick_check_insn given that it depends
3331    on PRO with status DS and weight DW.  */
3332 static void
3333 tick_check_dep_with_dw (insn_t pro_insn, ds_t ds, dw_t dw)
3334 {
3335   expr_t con_expr = tick_check_data.expr;
3336   insn_t con_insn = EXPR_INSN_RTX (con_expr);
3337
3338   if (con_insn != pro_insn)
3339     {
3340       enum reg_note dt;
3341       int tick;
3342
3343       if (/* PROducer was removed from above due to pipelining.  */
3344           !INSN_IN_STREAM_P (pro_insn)
3345           /* Or PROducer was originally on the next iteration regarding the
3346              CONsumer.  */
3347           || (INSN_SCHED_TIMES (pro_insn)
3348               - EXPR_SCHED_TIMES (con_expr)) > 1)
3349         /* Don't count this dependence.  */
3350         return;
3351
3352       dt = ds_to_dt (ds);
3353       if (dt == REG_DEP_TRUE)
3354         tick_check_data.seen_true_dep_p = true;
3355
3356       gcc_assert (INSN_SCHED_CYCLE (pro_insn) > 0);
3357
3358       {
3359         dep_def _dep, *dep = &_dep;
3360
3361         init_dep (dep, pro_insn, con_insn, dt);
3362
3363         tick = INSN_SCHED_CYCLE (pro_insn) + dep_cost_1 (dep, dw);
3364       }
3365
3366       /* When there are several kinds of dependencies between pro and con,
3367          only REG_DEP_TRUE should be taken into account.  */
3368       if (tick > tick_check_data.cycle
3369           && (dt == REG_DEP_TRUE || !tick_check_data.seen_true_dep_p))
3370         tick_check_data.cycle = tick;
3371     }
3372 }
3373
3374 /* An implementation of note_dep hook.  */
3375 static void
3376 tick_check_note_dep (insn_t pro, ds_t ds)
3377 {
3378   tick_check_dep_with_dw (pro, ds, 0);
3379 }
3380
3381 /* An implementation of note_mem_dep hook.  */
3382 static void
3383 tick_check_note_mem_dep (rtx mem1, rtx mem2, insn_t pro, ds_t ds)
3384 {
3385   dw_t dw;
3386
3387   dw = (ds_to_dt (ds) == REG_DEP_TRUE
3388         ? estimate_dep_weak (mem1, mem2)
3389         : 0);
3390
3391   tick_check_dep_with_dw (pro, ds, dw);
3392 }
3393
3394 /* This structure contains hooks for dependence analysis used when determining
3395    whether an insn is ready for scheduling.  */
3396 static struct sched_deps_info_def tick_check_sched_deps_info =
3397   {
3398     NULL,
3399
3400     NULL,
3401     NULL,
3402     NULL,
3403     NULL,
3404     NULL,
3405     NULL,
3406     haifa_note_reg_set,
3407     haifa_note_reg_clobber,
3408     haifa_note_reg_use,
3409     tick_check_note_mem_dep,
3410     tick_check_note_dep,
3411
3412     0, 0, 0
3413   };
3414
3415 /* Estimate number of cycles from the current cycle of FENCE until EXPR can be
3416    scheduled.  Return 0 if all data from producers in DC is ready.  */
3417 int
3418 tick_check_p (expr_t expr, deps_t dc, fence_t fence)
3419 {
3420   int cycles_left;
3421   /* Initialize variables.  */
3422   tick_check_data.expr = expr;
3423   tick_check_data.cycle = 0;
3424   tick_check_data.seen_true_dep_p = false;
3425   sched_deps_info = &tick_check_sched_deps_info;
3426
3427   gcc_assert (!dc->readonly);
3428   dc->readonly = 1;
3429   deps_analyze_insn (dc, EXPR_INSN_RTX (expr));
3430   dc->readonly = 0;
3431
3432   cycles_left = tick_check_data.cycle - FENCE_CYCLE (fence);
3433
3434   return cycles_left >= 0 ? cycles_left : 0;
3435 }
3436 \f
3437
3438 /* Functions to work with insns.  */
3439
3440 /* Returns true if LHS of INSN is the same as DEST of an insn
3441    being moved.  */
3442 bool
3443 lhs_of_insn_equals_to_dest_p (insn_t insn, rtx dest)
3444 {
3445   rtx lhs = INSN_LHS (insn);
3446
3447   if (lhs == NULL || dest == NULL)
3448     return false;
3449
3450   return rtx_equal_p (lhs, dest);
3451 }
3452
3453 /* Return s_i_d entry of INSN.  Callable from debugger.  */
3454 sel_insn_data_def
3455 insn_sid (insn_t insn)
3456 {
3457   return *SID (insn);
3458 }
3459
3460 /* True when INSN is a speculative check.  We can tell this by looking
3461    at the data structures of the selective scheduler, not by examining
3462    the pattern.  */
3463 bool
3464 sel_insn_is_speculation_check (rtx insn)
3465 {
3466   return s_i_d && !! INSN_SPEC_CHECKED_DS (insn);
3467 }
3468
3469 /* Extracts machine mode MODE and destination location DST_LOC
3470    for given INSN.  */
3471 void
3472 get_dest_and_mode (rtx insn, rtx *dst_loc, enum machine_mode *mode)
3473 {
3474   rtx pat = PATTERN (insn);
3475
3476   gcc_assert (dst_loc);
3477   gcc_assert (GET_CODE (pat) == SET);
3478
3479   *dst_loc = SET_DEST (pat);
3480
3481   gcc_assert (*dst_loc);
3482   gcc_assert (MEM_P (*dst_loc) || REG_P (*dst_loc));
3483
3484   if (mode)
3485     *mode = GET_MODE (*dst_loc);
3486 }
3487
3488 /* Returns true when moving through JUMP will result in bookkeeping
3489    creation.  */
3490 bool
3491 bookkeeping_can_be_created_if_moved_through_p (insn_t jump)
3492 {
3493   insn_t succ;
3494   succ_iterator si;
3495
3496   FOR_EACH_SUCC (succ, si, jump)
3497     if (sel_num_cfg_preds_gt_1 (succ))
3498       return true;
3499
3500   return false;
3501 }
3502
3503 /* Return 'true' if INSN is the only one in its basic block.  */
3504 static bool
3505 insn_is_the_only_one_in_bb_p (insn_t insn)
3506 {
3507   return sel_bb_head_p (insn) && sel_bb_end_p (insn);
3508 }
3509
3510 #ifdef ENABLE_CHECKING
3511 /* Check that the region we're scheduling still has at most one
3512    backedge.  */
3513 static void
3514 verify_backedges (void)
3515 {
3516   if (pipelining_p)
3517     {
3518       int i, n = 0;
3519       edge e;
3520       edge_iterator ei;
3521
3522       for (i = 0; i < current_nr_blocks; i++)
3523         FOR_EACH_EDGE (e, ei, BASIC_BLOCK (BB_TO_BLOCK (i))->succs)
3524           if (in_current_region_p (e->dest)
3525               && BLOCK_TO_BB (e->dest->index) < i)
3526             n++;
3527
3528       gcc_assert (n <= 1);
3529     }
3530 }
3531 #endif
3532 \f
3533
3534 /* Functions to work with control flow.  */
3535
3536 /* Recompute BLOCK_TO_BB and BB_FOR_BLOCK for current region so that blocks
3537    are sorted in topological order (it might have been invalidated by
3538    redirecting an edge).  */
3539 static void
3540 sel_recompute_toporder (void)
3541 {
3542   int i, n, rgn;
3543   int *postorder, n_blocks;
3544
3545   postorder = XALLOCAVEC (int, n_basic_blocks);
3546   n_blocks = post_order_compute (postorder, false, false);
3547
3548   rgn = CONTAINING_RGN (BB_TO_BLOCK (0));
3549   for (n = 0, i = n_blocks - 1; i >= 0; i--)
3550     if (CONTAINING_RGN (postorder[i]) == rgn)
3551       {
3552         BLOCK_TO_BB (postorder[i]) = n;
3553         BB_TO_BLOCK (n) = postorder[i];
3554         n++;
3555       }
3556
3557   /* Assert that we updated info for all blocks.  We may miss some blocks if
3558      this function is called when redirecting an edge made a block
3559      unreachable, but that block is not deleted yet.  */
3560   gcc_assert (n == RGN_NR_BLOCKS (rgn));
3561 }
3562
3563 /* Tidy the possibly empty block BB.  */
3564 static bool
3565 maybe_tidy_empty_bb (basic_block bb)
3566 {
3567   basic_block succ_bb, pred_bb;
3568   edge e;
3569   edge_iterator ei;
3570   bool rescan_p;
3571
3572   /* Keep empty bb only if this block immediately precedes EXIT and
3573      has incoming non-fallthrough edge, or it has no predecessors or
3574      successors.  Otherwise remove it.  */
3575   if (!sel_bb_empty_p (bb)
3576       || (single_succ_p (bb)
3577           && single_succ (bb) == EXIT_BLOCK_PTR
3578           && (!single_pred_p (bb)
3579               || !(single_pred_edge (bb)->flags & EDGE_FALLTHRU)))
3580       || EDGE_COUNT (bb->preds) == 0
3581       || EDGE_COUNT (bb->succs) == 0)
3582     return false;
3583
3584   /* Do not attempt to redirect complex edges.  */
3585   FOR_EACH_EDGE (e, ei, bb->preds)
3586     if (e->flags & EDGE_COMPLEX)
3587       return false;
3588
3589   free_data_sets (bb);
3590
3591   /* Do not delete BB if it has more than one successor.
3592      That can occur when we moving a jump.  */
3593   if (!single_succ_p (bb))
3594     {
3595       gcc_assert (can_merge_blocks_p (bb->prev_bb, bb));
3596       sel_merge_blocks (bb->prev_bb, bb);
3597       return true;
3598     }
3599
3600   succ_bb = single_succ (bb);
3601   rescan_p = true;
3602   pred_bb = NULL;
3603
3604   /* Redirect all non-fallthru edges to the next bb.  */
3605   while (rescan_p)
3606     {
3607       rescan_p = false;
3608
3609       FOR_EACH_EDGE (e, ei, bb->preds)
3610         {
3611           pred_bb = e->src;
3612
3613           if (!(e->flags & EDGE_FALLTHRU))
3614             {
3615               /* We can not invalidate computed topological order by moving
3616                  the edge destination block (E->SUCC) along a fallthru edge.  */
3617               sel_redirect_edge_and_branch (e, succ_bb);
3618               rescan_p = true;
3619               break;
3620             }
3621           /* If the edge is fallthru, but PRED_BB ends in a conditional jump
3622              to BB (so there is no non-fallthru edge from PRED_BB to BB), we
3623              still have to adjust it.  */
3624           else if (single_succ_p (pred_bb) && any_condjump_p (BB_END (pred_bb)))
3625             {
3626               /* If possible, try to remove the unneeded conditional jump.  */
3627               if (INSN_SCHED_TIMES (BB_END (pred_bb)) == 0
3628                   && !IN_CURRENT_FENCE_P (BB_END (pred_bb)))
3629                 {
3630                   if (!sel_remove_insn (BB_END (pred_bb), false, false))
3631                     tidy_fallthru_edge (e);
3632                 }
3633               else
3634                 sel_redirect_edge_and_branch (e, succ_bb);
3635               rescan_p = true;
3636               break;
3637             }
3638         }
3639     }
3640
3641   if (can_merge_blocks_p (bb->prev_bb, bb))
3642     sel_merge_blocks (bb->prev_bb, bb);
3643   else
3644     {
3645       /* This is a block without fallthru predecessor.  Just delete it.  */
3646       gcc_assert (pred_bb != NULL);
3647
3648       if (in_current_region_p (pred_bb))
3649         move_bb_info (pred_bb, bb);
3650       remove_empty_bb (bb, true);
3651     }
3652
3653 #ifdef ENABLE_CHECKING
3654   verify_backedges ();
3655 #endif
3656
3657   return true;
3658 }
3659
3660 /* Tidy the control flow after we have removed original insn from
3661    XBB.  Return true if we have removed some blocks.  When FULL_TIDYING
3662    is true, also try to optimize control flow on non-empty blocks.  */
3663 bool
3664 tidy_control_flow (basic_block xbb, bool full_tidying)
3665 {
3666   bool changed = true;
3667   insn_t first, last;
3668
3669   /* First check whether XBB is empty.  */
3670   changed = maybe_tidy_empty_bb (xbb);
3671   if (changed || !full_tidying)
3672     return changed;
3673
3674   /* Check if there is a unnecessary jump after insn left.  */
3675   if (jump_leads_only_to_bb_p (BB_END (xbb), xbb->next_bb)
3676       && INSN_SCHED_TIMES (BB_END (xbb)) == 0
3677       && !IN_CURRENT_FENCE_P (BB_END (xbb)))
3678     {
3679       if (sel_remove_insn (BB_END (xbb), false, false))
3680         return true;
3681       tidy_fallthru_edge (EDGE_SUCC (xbb, 0));
3682     }
3683
3684   first = sel_bb_head (xbb);
3685   last = sel_bb_end (xbb);
3686   if (MAY_HAVE_DEBUG_INSNS)
3687     {
3688       if (first != last && DEBUG_INSN_P (first))
3689         do
3690           first = NEXT_INSN (first);
3691         while (first != last && (DEBUG_INSN_P (first) || NOTE_P (first)));
3692
3693       if (first != last && DEBUG_INSN_P (last))
3694         do
3695           last = PREV_INSN (last);
3696         while (first != last && (DEBUG_INSN_P (last) || NOTE_P (last)));
3697     }
3698   /* Check if there is an unnecessary jump in previous basic block leading
3699      to next basic block left after removing INSN from stream.
3700      If it is so, remove that jump and redirect edge to current
3701      basic block (where there was INSN before deletion).  This way
3702      when NOP will be deleted several instructions later with its
3703      basic block we will not get a jump to next instruction, which
3704      can be harmful.  */
3705   if (first == last
3706       && !sel_bb_empty_p (xbb)
3707       && INSN_NOP_P (last)
3708       /* Flow goes fallthru from current block to the next.  */
3709       && EDGE_COUNT (xbb->succs) == 1
3710       && (EDGE_SUCC (xbb, 0)->flags & EDGE_FALLTHRU)
3711       /* When successor is an EXIT block, it may not be the next block.  */
3712       && single_succ (xbb) != EXIT_BLOCK_PTR
3713       /* And unconditional jump in previous basic block leads to
3714          next basic block of XBB and this jump can be safely removed.  */
3715       && in_current_region_p (xbb->prev_bb)
3716       && jump_leads_only_to_bb_p (BB_END (xbb->prev_bb), xbb->next_bb)
3717       && INSN_SCHED_TIMES (BB_END (xbb->prev_bb)) == 0
3718       /* Also this jump is not at the scheduling boundary.  */
3719       && !IN_CURRENT_FENCE_P (BB_END (xbb->prev_bb)))
3720     {
3721       bool recompute_toporder_p;
3722       /* Clear data structures of jump - jump itself will be removed
3723          by sel_redirect_edge_and_branch.  */
3724       clear_expr (INSN_EXPR (BB_END (xbb->prev_bb)));
3725       recompute_toporder_p
3726         = sel_redirect_edge_and_branch (EDGE_SUCC (xbb->prev_bb, 0), xbb);
3727
3728       gcc_assert (EDGE_SUCC (xbb->prev_bb, 0)->flags & EDGE_FALLTHRU);
3729
3730       /* It can turn out that after removing unused jump, basic block
3731          that contained that jump, becomes empty too.  In such case
3732          remove it too.  */
3733       if (sel_bb_empty_p (xbb->prev_bb))
3734         changed = maybe_tidy_empty_bb (xbb->prev_bb);
3735       if (recompute_toporder_p)
3736         sel_recompute_toporder ();
3737     }
3738   return changed;
3739 }
3740
3741 /* Purge meaningless empty blocks in the middle of a region.  */
3742 void
3743 purge_empty_blocks (void)
3744 {
3745   /* Do not attempt to delete preheader.  */
3746   int i = sel_is_loop_preheader_p (BASIC_BLOCK (BB_TO_BLOCK (0))) ? 1 : 0;
3747
3748   while (i < current_nr_blocks)
3749     {
3750       basic_block b = BASIC_BLOCK (BB_TO_BLOCK (i));
3751
3752       if (maybe_tidy_empty_bb (b))
3753         continue;
3754
3755       i++;
3756     }
3757 }
3758
3759 /* Rip-off INSN from the insn stream.  When ONLY_DISCONNECT is true,
3760    do not delete insn's data, because it will be later re-emitted.
3761    Return true if we have removed some blocks afterwards.  */
3762 bool
3763 sel_remove_insn (insn_t insn, bool only_disconnect, bool full_tidying)
3764 {
3765   basic_block bb = BLOCK_FOR_INSN (insn);
3766
3767   gcc_assert (INSN_IN_STREAM_P (insn));
3768
3769   if (DEBUG_INSN_P (insn) && BB_AV_SET_VALID_P (bb))
3770     {
3771       expr_t expr;
3772       av_set_iterator i;
3773
3774       /* When we remove a debug insn that is head of a BB, it remains
3775          in the AV_SET of the block, but it shouldn't.  */
3776       FOR_EACH_EXPR_1 (expr, i, &BB_AV_SET (bb))
3777         if (EXPR_INSN_RTX (expr) == insn)
3778           {
3779             av_set_iter_remove (&i);
3780             break;
3781           }
3782     }
3783
3784   if (only_disconnect)
3785     {
3786       insn_t prev = PREV_INSN (insn);
3787       insn_t next = NEXT_INSN (insn);
3788       basic_block bb = BLOCK_FOR_INSN (insn);
3789
3790       NEXT_INSN (prev) = next;
3791       PREV_INSN (next) = prev;
3792
3793       if (BB_HEAD (bb) == insn)
3794         {
3795           gcc_assert (BLOCK_FOR_INSN (prev) == bb);
3796           BB_HEAD (bb) = prev;
3797         }
3798       if (BB_END (bb) == insn)
3799         BB_END (bb) = prev;
3800     }
3801   else
3802     {
3803       remove_insn (insn);
3804       clear_expr (INSN_EXPR (insn));
3805     }
3806
3807   /* It is necessary to null this fields before calling add_insn ().  */
3808   PREV_INSN (insn) = NULL_RTX;
3809   NEXT_INSN (insn) = NULL_RTX;
3810
3811   return tidy_control_flow (bb, full_tidying);
3812 }
3813
3814 /* Estimate number of the insns in BB.  */
3815 static int
3816 sel_estimate_number_of_insns (basic_block bb)
3817 {
3818   int res = 0;
3819   insn_t insn = NEXT_INSN (BB_HEAD (bb)), next_tail = NEXT_INSN (BB_END (bb));
3820
3821   for (; insn != next_tail; insn = NEXT_INSN (insn))
3822     if (NONDEBUG_INSN_P (insn))
3823       res++;
3824
3825   return res;
3826 }
3827
3828 /* We don't need separate luids for notes or labels.  */
3829 static int
3830 sel_luid_for_non_insn (rtx x)
3831 {
3832   gcc_assert (NOTE_P (x) || LABEL_P (x));
3833
3834   return -1;
3835 }
3836
3837 /* Return seqno of the only predecessor of INSN.  */
3838 static int
3839 get_seqno_of_a_pred (insn_t insn)
3840 {
3841   int seqno;
3842
3843   gcc_assert (INSN_SIMPLEJUMP_P (insn));
3844
3845   if (!sel_bb_head_p (insn))
3846     seqno = INSN_SEQNO (PREV_INSN (insn));
3847   else
3848     {
3849       basic_block bb = BLOCK_FOR_INSN (insn);
3850
3851       if (single_pred_p (bb)
3852           && !in_current_region_p (single_pred (bb)))
3853         {
3854           /* We can have preds outside a region when splitting edges
3855              for pipelining of an outer loop.  Use succ instead.
3856              There should be only one of them.  */
3857           insn_t succ = NULL;
3858           succ_iterator si;
3859           bool first = true;
3860
3861           gcc_assert (flag_sel_sched_pipelining_outer_loops
3862                       && current_loop_nest);
3863           FOR_EACH_SUCC_1 (succ, si, insn,
3864                            SUCCS_NORMAL | SUCCS_SKIP_TO_LOOP_EXITS)
3865             {
3866               gcc_assert (first);
3867               first = false;
3868             }
3869
3870           gcc_assert (succ != NULL);
3871           seqno = INSN_SEQNO (succ);
3872         }
3873       else
3874         {
3875           insn_t *preds;
3876           int n;
3877
3878           cfg_preds (BLOCK_FOR_INSN (insn), &preds, &n);
3879           gcc_assert (n == 1);
3880
3881           seqno = INSN_SEQNO (preds[0]);
3882
3883           free (preds);
3884         }
3885     }
3886
3887   return seqno;
3888 }
3889
3890 /*  Find the proper seqno for inserting at INSN.  Returns -1 if no predecessors
3891     with positive seqno exist.  */
3892 int
3893 get_seqno_by_preds (rtx insn)
3894 {
3895   basic_block bb = BLOCK_FOR_INSN (insn);
3896   rtx tmp = insn, head = BB_HEAD (bb);
3897   insn_t *preds;
3898   int n, i, seqno;
3899
3900   while (tmp != head)
3901     if (INSN_P (tmp))
3902       return INSN_SEQNO (tmp);
3903     else
3904       tmp = PREV_INSN (tmp);
3905
3906   cfg_preds (bb, &preds, &n);
3907   for (i = 0, seqno = -1; i < n; i++)
3908     seqno = MAX (seqno, INSN_SEQNO (preds[i]));
3909
3910   return seqno;
3911 }
3912
3913 \f
3914
3915 /* Extend pass-scope data structures for basic blocks.  */
3916 void
3917 sel_extend_global_bb_info (void)
3918 {
3919   VEC_safe_grow_cleared (sel_global_bb_info_def, heap, sel_global_bb_info,
3920                          last_basic_block);
3921 }
3922
3923 /* Extend region-scope data structures for basic blocks.  */
3924 static void
3925 extend_region_bb_info (void)
3926 {
3927   VEC_safe_grow_cleared (sel_region_bb_info_def, heap, sel_region_bb_info,
3928                          last_basic_block);
3929 }
3930
3931 /* Extend all data structures to fit for all basic blocks.  */
3932 static void
3933 extend_bb_info (void)
3934 {
3935   sel_extend_global_bb_info ();
3936   extend_region_bb_info ();
3937 }
3938
3939 /* Finalize pass-scope data structures for basic blocks.  */
3940 void
3941 sel_finish_global_bb_info (void)
3942 {
3943   VEC_free (sel_global_bb_info_def, heap, sel_global_bb_info);
3944 }
3945
3946 /* Finalize region-scope data structures for basic blocks.  */
3947 static void
3948 finish_region_bb_info (void)
3949 {
3950   VEC_free (sel_region_bb_info_def, heap, sel_region_bb_info);
3951 }
3952 \f
3953
3954 /* Data for each insn in current region.  */
3955 VEC (sel_insn_data_def, heap) *s_i_d = NULL;
3956
3957 /* A vector for the insns we've emitted.  */
3958 static insn_vec_t new_insns = NULL;
3959
3960 /* Extend data structures for insns from current region.  */
3961 static void
3962 extend_insn_data (void)
3963 {
3964   int reserve;
3965
3966   sched_extend_target ();
3967   sched_deps_init (false);
3968
3969   /* Extend data structures for insns from current region.  */
3970   reserve = (sched_max_luid + 1
3971              - VEC_length (sel_insn_data_def, s_i_d));
3972   if (reserve > 0
3973       && ! VEC_space (sel_insn_data_def, s_i_d, reserve))
3974     {
3975       int size;
3976
3977       if (sched_max_luid / 2 > 1024)
3978         size = sched_max_luid + 1024;
3979       else
3980         size = 3 * sched_max_luid / 2;
3981
3982
3983       VEC_safe_grow_cleared (sel_insn_data_def, heap, s_i_d, size);
3984     }
3985 }
3986
3987 /* Finalize data structures for insns from current region.  */
3988 static void
3989 finish_insns (void)
3990 {
3991   unsigned i;
3992
3993   /* Clear here all dependence contexts that may have left from insns that were
3994      removed during the scheduling.  */
3995   for (i = 0; i < VEC_length (sel_insn_data_def, s_i_d); i++)
3996     {
3997       sel_insn_data_def *sid_entry = VEC_index (sel_insn_data_def, s_i_d, i);
3998
3999       if (sid_entry->live)
4000         return_regset_to_pool (sid_entry->live);
4001       if (sid_entry->analyzed_deps)
4002         {
4003           BITMAP_FREE (sid_entry->analyzed_deps);
4004           BITMAP_FREE (sid_entry->found_deps);
4005           htab_delete (sid_entry->transformed_insns);
4006           free_deps (&sid_entry->deps_context);
4007         }
4008       if (EXPR_VINSN (&sid_entry->expr))
4009         {
4010           clear_expr (&sid_entry->expr);
4011
4012           /* Also, clear CANT_MOVE bit here, because we really don't want it
4013              to be passed to the next region.  */
4014           CANT_MOVE_BY_LUID (i) = 0;
4015         }
4016     }
4017
4018   VEC_free (sel_insn_data_def, heap, s_i_d);
4019 }
4020
4021 /* A proxy to pass initialization data to init_insn ().  */
4022 static sel_insn_data_def _insn_init_ssid;
4023 static sel_insn_data_t insn_init_ssid = &_insn_init_ssid;
4024
4025 /* If true create a new vinsn.  Otherwise use the one from EXPR.  */
4026 static bool insn_init_create_new_vinsn_p;
4027
4028 /* Set all necessary data for initialization of the new insn[s].  */
4029 static expr_t
4030 set_insn_init (expr_t expr, vinsn_t vi, int seqno)
4031 {
4032   expr_t x = &insn_init_ssid->expr;
4033
4034   copy_expr_onside (x, expr);
4035   if (vi != NULL)
4036     {
4037       insn_init_create_new_vinsn_p = false;
4038       change_vinsn_in_expr (x, vi);
4039     }
4040   else
4041     insn_init_create_new_vinsn_p = true;
4042
4043   insn_init_ssid->seqno = seqno;
4044   return x;
4045 }
4046
4047 /* Init data for INSN.  */
4048 static void
4049 init_insn_data (insn_t insn)
4050 {
4051   expr_t expr;
4052   sel_insn_data_t ssid = insn_init_ssid;
4053
4054   /* The fields mentioned below are special and hence are not being
4055      propagated to the new insns.  */
4056   gcc_assert (!ssid->asm_p && ssid->sched_next == NULL
4057               && !ssid->after_stall_p && ssid->sched_cycle == 0);
4058   gcc_assert (INSN_P (insn) && INSN_LUID (insn) > 0);
4059
4060   expr = INSN_EXPR (insn);
4061   copy_expr (expr, &ssid->expr);
4062   prepare_insn_expr (insn, ssid->seqno);
4063
4064   if (insn_init_create_new_vinsn_p)
4065     change_vinsn_in_expr (expr, vinsn_create (insn, init_insn_force_unique_p));
4066
4067   if (first_time_insn_init (insn))
4068     init_first_time_insn_data (insn);
4069 }
4070
4071 /* This is used to initialize spurious jumps generated by
4072    sel_redirect_edge ().  */
4073 static void
4074 init_simplejump_data (insn_t insn)
4075 {
4076   init_expr (INSN_EXPR (insn), vinsn_create (insn, false), 0,
4077              REG_BR_PROB_BASE, 0, 0, 0, 0, 0, 0, NULL, true, false, false,
4078              false, true);
4079   INSN_SEQNO (insn) = get_seqno_of_a_pred (insn);
4080   init_first_time_insn_data (insn);
4081 }
4082
4083 /* Perform deferred initialization of insns.  This is used to process
4084    a new jump that may be created by redirect_edge.  */
4085 void
4086 sel_init_new_insn (insn_t insn, int flags)
4087 {
4088   /* We create data structures for bb when the first insn is emitted in it.  */
4089   if (INSN_P (insn)
4090       && INSN_IN_STREAM_P (insn)
4091       && insn_is_the_only_one_in_bb_p (insn))
4092     {
4093       extend_bb_info ();
4094       create_initial_data_sets (BLOCK_FOR_INSN (insn));
4095     }
4096
4097   if (flags & INSN_INIT_TODO_LUID)
4098     sched_init_luids (NULL, NULL, NULL, insn);
4099
4100   if (flags & INSN_INIT_TODO_SSID)
4101     {
4102       extend_insn_data ();
4103       init_insn_data (insn);
4104       clear_expr (&insn_init_ssid->expr);
4105     }
4106
4107   if (flags & INSN_INIT_TODO_SIMPLEJUMP)
4108     {
4109       extend_insn_data ();
4110       init_simplejump_data (insn);
4111     }
4112
4113   gcc_assert (CONTAINING_RGN (BLOCK_NUM (insn))
4114               == CONTAINING_RGN (BB_TO_BLOCK (0)));
4115 }
4116 \f
4117
4118 /* Functions to init/finish work with lv sets.  */
4119
4120 /* Init BB_LV_SET of BB from DF_LR_IN set of BB.  */
4121 static void
4122 init_lv_set (basic_block bb)
4123 {
4124   gcc_assert (!BB_LV_SET_VALID_P (bb));
4125
4126   BB_LV_SET (bb) = get_regset_from_pool ();
4127   COPY_REG_SET (BB_LV_SET (bb), DF_LR_IN (bb));
4128   BB_LV_SET_VALID_P (bb) = true;
4129 }
4130
4131 /* Copy liveness information to BB from FROM_BB.  */
4132 static void
4133 copy_lv_set_from (basic_block bb, basic_block from_bb)
4134 {
4135   gcc_assert (!BB_LV_SET_VALID_P (bb));
4136
4137   COPY_REG_SET (BB_LV_SET (bb), BB_LV_SET (from_bb));
4138   BB_LV_SET_VALID_P (bb) = true;
4139 }
4140
4141 /* Initialize lv set of all bb headers.  */
4142 void
4143 init_lv_sets (void)
4144 {
4145   basic_block bb;
4146
4147   /* Initialize of LV sets.  */
4148   FOR_EACH_BB (bb)
4149     init_lv_set (bb);
4150
4151   /* Don't forget EXIT_BLOCK.  */
4152   init_lv_set (EXIT_BLOCK_PTR);
4153 }
4154
4155 /* Release lv set of HEAD.  */
4156 static void
4157 free_lv_set (basic_block bb)
4158 {
4159   gcc_assert (BB_LV_SET (bb) != NULL);
4160
4161   return_regset_to_pool (BB_LV_SET (bb));
4162   BB_LV_SET (bb) = NULL;
4163   BB_LV_SET_VALID_P (bb) = false;
4164 }
4165
4166 /* Finalize lv sets of all bb headers.  */
4167 void
4168 free_lv_sets (void)
4169 {
4170   basic_block bb;
4171
4172   /* Don't forget EXIT_BLOCK.  */
4173   free_lv_set (EXIT_BLOCK_PTR);
4174
4175   /* Free LV sets.  */
4176   FOR_EACH_BB (bb)
4177     if (BB_LV_SET (bb))
4178       free_lv_set (bb);
4179 }
4180
4181 /* Initialize an invalid AV_SET for BB.
4182    This set will be updated next time compute_av () process BB.  */
4183 static void
4184 invalidate_av_set (basic_block bb)
4185 {
4186   gcc_assert (BB_AV_LEVEL (bb) <= 0
4187               && BB_AV_SET (bb) == NULL);
4188
4189   BB_AV_LEVEL (bb) = -1;
4190 }
4191
4192 /* Create initial data sets for BB (they will be invalid).  */
4193 static void
4194 create_initial_data_sets (basic_block bb)
4195 {
4196   if (BB_LV_SET (bb))
4197     BB_LV_SET_VALID_P (bb) = false;
4198   else
4199     BB_LV_SET (bb) = get_regset_from_pool ();
4200   invalidate_av_set (bb);
4201 }
4202
4203 /* Free av set of BB.  */
4204 static void
4205 free_av_set (basic_block bb)
4206 {
4207   av_set_clear (&BB_AV_SET (bb));
4208   BB_AV_LEVEL (bb) = 0;
4209 }
4210
4211 /* Free data sets of BB.  */
4212 void
4213 free_data_sets (basic_block bb)
4214 {
4215   free_lv_set (bb);
4216   free_av_set (bb);
4217 }
4218
4219 /* Exchange lv sets of TO and FROM.  */
4220 static void
4221 exchange_lv_sets (basic_block to, basic_block from)
4222 {
4223   {
4224     regset to_lv_set = BB_LV_SET (to);
4225
4226     BB_LV_SET (to) = BB_LV_SET (from);
4227     BB_LV_SET (from) = to_lv_set;
4228   }
4229
4230   {
4231     bool to_lv_set_valid_p = BB_LV_SET_VALID_P (to);
4232
4233     BB_LV_SET_VALID_P (to) = BB_LV_SET_VALID_P (from);
4234     BB_LV_SET_VALID_P (from) = to_lv_set_valid_p;
4235   }
4236 }
4237
4238
4239 /* Exchange av sets of TO and FROM.  */
4240 static void
4241 exchange_av_sets (basic_block to, basic_block from)
4242 {
4243   {
4244     av_set_t to_av_set = BB_AV_SET (to);
4245
4246     BB_AV_SET (to) = BB_AV_SET (from);
4247     BB_AV_SET (from) = to_av_set;
4248   }
4249
4250   {
4251     int to_av_level = BB_AV_LEVEL (to);
4252
4253     BB_AV_LEVEL (to) = BB_AV_LEVEL (from);
4254     BB_AV_LEVEL (from) = to_av_level;
4255   }
4256 }
4257
4258 /* Exchange data sets of TO and FROM.  */
4259 void
4260 exchange_data_sets (basic_block to, basic_block from)
4261 {
4262   exchange_lv_sets (to, from);
4263   exchange_av_sets (to, from);
4264 }
4265
4266 /* Copy data sets of FROM to TO.  */
4267 void
4268 copy_data_sets (basic_block to, basic_block from)
4269 {
4270   gcc_assert (!BB_LV_SET_VALID_P (to) && !BB_AV_SET_VALID_P (to));
4271   gcc_assert (BB_AV_SET (to) == NULL);
4272
4273   BB_AV_LEVEL (to) = BB_AV_LEVEL (from);
4274   BB_LV_SET_VALID_P (to) = BB_LV_SET_VALID_P (from);
4275
4276   if (BB_AV_SET_VALID_P (from))
4277     {
4278       BB_AV_SET (to) = av_set_copy (BB_AV_SET (from));
4279     }
4280   if (BB_LV_SET_VALID_P (from))
4281     {
4282       gcc_assert (BB_LV_SET (to) != NULL);
4283       COPY_REG_SET (BB_LV_SET (to), BB_LV_SET (from));
4284     }
4285 }
4286
4287 /* Return an av set for INSN, if any.  */
4288 av_set_t
4289 get_av_set (insn_t insn)
4290 {
4291   av_set_t av_set;
4292
4293   gcc_assert (AV_SET_VALID_P (insn));
4294
4295   if (sel_bb_head_p (insn))
4296     av_set = BB_AV_SET (BLOCK_FOR_INSN (insn));
4297   else
4298     av_set = NULL;
4299
4300   return av_set;
4301 }
4302
4303 /* Implementation of AV_LEVEL () macro.  Return AV_LEVEL () of INSN.  */
4304 int
4305 get_av_level (insn_t insn)
4306 {
4307   int av_level;
4308
4309   gcc_assert (INSN_P (insn));
4310
4311   if (sel_bb_head_p (insn))
4312     av_level = BB_AV_LEVEL (BLOCK_FOR_INSN (insn));
4313   else
4314     av_level = INSN_WS_LEVEL (insn);
4315
4316   return av_level;
4317 }
4318
4319 \f
4320
4321 /* Variables to work with control-flow graph.  */
4322
4323 /* The basic block that already has been processed by the sched_data_update (),
4324    but hasn't been in sel_add_bb () yet.  */
4325 static VEC (basic_block, heap) *last_added_blocks = NULL;
4326
4327 /* A pool for allocating successor infos.  */
4328 static struct
4329 {
4330   /* A stack for saving succs_info structures.  */
4331   struct succs_info *stack;
4332
4333   /* Its size.  */
4334   int size;
4335
4336   /* Top of the stack.  */
4337   int top;
4338
4339   /* Maximal value of the top.  */
4340   int max_top;
4341 }  succs_info_pool;
4342
4343 /* Functions to work with control-flow graph.  */
4344
4345 /* Return basic block note of BB.  */
4346 insn_t
4347 sel_bb_head (basic_block bb)
4348 {
4349   insn_t head;
4350
4351   if (bb == EXIT_BLOCK_PTR)
4352     {
4353       gcc_assert (exit_insn != NULL_RTX);
4354       head = exit_insn;
4355     }
4356   else
4357     {
4358       insn_t note;
4359
4360       note = bb_note (bb);
4361       head = next_nonnote_insn (note);
4362
4363       if (head && (BARRIER_P (head) || BLOCK_FOR_INSN (head) != bb))
4364         head = NULL_RTX;
4365     }
4366
4367   return head;
4368 }
4369
4370 /* Return true if INSN is a basic block header.  */
4371 bool
4372 sel_bb_head_p (insn_t insn)
4373 {
4374   return sel_bb_head (BLOCK_FOR_INSN (insn)) == insn;
4375 }
4376
4377 /* Return last insn of BB.  */
4378 insn_t
4379 sel_bb_end (basic_block bb)
4380 {
4381   if (sel_bb_empty_p (bb))
4382     return NULL_RTX;
4383
4384   gcc_assert (bb != EXIT_BLOCK_PTR);
4385
4386   return BB_END (bb);
4387 }
4388
4389 /* Return true if INSN is the last insn in its basic block.  */
4390 bool
4391 sel_bb_end_p (insn_t insn)
4392 {
4393   return insn == sel_bb_end (BLOCK_FOR_INSN (insn));
4394 }
4395
4396 /* Return true if BB consist of single NOTE_INSN_BASIC_BLOCK.  */
4397 bool
4398 sel_bb_empty_p (basic_block bb)
4399 {
4400   return sel_bb_head (bb) == NULL;
4401 }
4402
4403 /* True when BB belongs to the current scheduling region.  */
4404 bool
4405 in_current_region_p (basic_block bb)
4406 {
4407   if (bb->index < NUM_FIXED_BLOCKS)
4408     return false;
4409
4410   return CONTAINING_RGN (bb->index) == CONTAINING_RGN (BB_TO_BLOCK (0));
4411 }
4412
4413 /* Return the block which is a fallthru bb of a conditional jump JUMP.  */
4414 basic_block
4415 fallthru_bb_of_jump (rtx jump)
4416 {
4417   if (!JUMP_P (jump))
4418     return NULL;
4419
4420   if (any_uncondjump_p (jump))
4421     return single_succ (BLOCK_FOR_INSN (jump));
4422
4423   if (!any_condjump_p (jump))
4424     return NULL;
4425
4426   /* A basic block that ends with a conditional jump may still have one successor
4427      (and be followed by a barrier), we are not interested.  */
4428   if (single_succ_p (BLOCK_FOR_INSN (jump)))
4429     return NULL;
4430
4431   return FALLTHRU_EDGE (BLOCK_FOR_INSN (jump))->dest;
4432 }
4433
4434 /* Remove all notes from BB.  */
4435 static void
4436 init_bb (basic_block bb)
4437 {
4438   remove_notes (bb_note (bb), BB_END (bb));
4439   BB_NOTE_LIST (bb) = note_list;
4440 }
4441
4442 void
4443 sel_init_bbs (bb_vec_t bbs, basic_block bb)
4444 {
4445   const struct sched_scan_info_def ssi =
4446     {
4447       extend_bb_info, /* extend_bb */
4448       init_bb, /* init_bb */
4449       NULL, /* extend_insn */
4450       NULL /* init_insn */
4451     };
4452
4453   sched_scan (&ssi, bbs, bb, new_insns, NULL);
4454 }
4455
4456 /* Restore notes for the whole region.  */
4457 static void
4458 sel_restore_notes (void)
4459 {
4460   int bb;
4461   insn_t insn;
4462
4463   for (bb = 0; bb < current_nr_blocks; bb++)
4464     {
4465       basic_block first, last;
4466
4467       first = EBB_FIRST_BB (bb);
4468       last = EBB_LAST_BB (bb)->next_bb;
4469
4470       do
4471         {
4472           note_list = BB_NOTE_LIST (first);
4473           restore_other_notes (NULL, first);
4474           BB_NOTE_LIST (first) = NULL_RTX;
4475
4476           FOR_BB_INSNS (first, insn)
4477             if (NONDEBUG_INSN_P (insn))
4478               reemit_notes (insn);
4479
4480           first = first->next_bb;
4481         }
4482       while (first != last);
4483     }
4484 }
4485
4486 /* Free per-bb data structures.  */
4487 void
4488 sel_finish_bbs (void)
4489 {
4490   sel_restore_notes ();
4491
4492   /* Remove current loop preheader from this loop.  */
4493   if (current_loop_nest)
4494     sel_remove_loop_preheader ();
4495
4496   finish_region_bb_info ();
4497 }
4498
4499 /* Return true if INSN has a single successor of type FLAGS.  */
4500 bool
4501 sel_insn_has_single_succ_p (insn_t insn, int flags)
4502 {
4503   insn_t succ;
4504   succ_iterator si;
4505   bool first_p = true;
4506
4507   FOR_EACH_SUCC_1 (succ, si, insn, flags)
4508     {
4509       if (first_p)
4510         first_p = false;
4511       else
4512         return false;
4513     }
4514
4515   return true;
4516 }
4517
4518 /* Allocate successor's info.  */
4519 static struct succs_info *
4520 alloc_succs_info (void)
4521 {
4522   if (succs_info_pool.top == succs_info_pool.max_top)
4523     {
4524       int i;
4525
4526       if (++succs_info_pool.max_top >= succs_info_pool.size)
4527         gcc_unreachable ();
4528
4529       i = ++succs_info_pool.top;
4530       succs_info_pool.stack[i].succs_ok = VEC_alloc (rtx, heap, 10);
4531       succs_info_pool.stack[i].succs_other = VEC_alloc (rtx, heap, 10);
4532       succs_info_pool.stack[i].probs_ok = VEC_alloc (int, heap, 10);
4533     }
4534   else
4535     succs_info_pool.top++;
4536
4537   return &succs_info_pool.stack[succs_info_pool.top];
4538 }
4539
4540 /* Free successor's info.  */
4541 void
4542 free_succs_info (struct succs_info * sinfo)
4543 {
4544   gcc_assert (succs_info_pool.top >= 0
4545               && &succs_info_pool.stack[succs_info_pool.top] == sinfo);
4546   succs_info_pool.top--;
4547
4548   /* Clear stale info.  */
4549   VEC_block_remove (rtx, sinfo->succs_ok,
4550                     0, VEC_length (rtx, sinfo->succs_ok));
4551   VEC_block_remove (rtx, sinfo->succs_other,
4552                     0, VEC_length (rtx, sinfo->succs_other));
4553   VEC_block_remove (int, sinfo->probs_ok,
4554                     0, VEC_length (int, sinfo->probs_ok));
4555   sinfo->all_prob = 0;
4556   sinfo->succs_ok_n = 0;
4557   sinfo->all_succs_n = 0;
4558 }
4559
4560 /* Compute successor info for INSN.  FLAGS are the flags passed
4561    to the FOR_EACH_SUCC_1 iterator.  */
4562 struct succs_info *
4563 compute_succs_info (insn_t insn, short flags)
4564 {
4565   succ_iterator si;
4566   insn_t succ;
4567   struct succs_info *sinfo = alloc_succs_info ();
4568
4569   /* Traverse *all* successors and decide what to do with each.  */
4570   FOR_EACH_SUCC_1 (succ, si, insn, SUCCS_ALL)
4571     {
4572       /* FIXME: this doesn't work for skipping to loop exits, as we don't
4573          perform code motion through inner loops.  */
4574       short current_flags = si.current_flags & ~SUCCS_SKIP_TO_LOOP_EXITS;
4575
4576       if (current_flags & flags)
4577         {
4578           VEC_safe_push (rtx, heap, sinfo->succs_ok, succ);
4579           VEC_safe_push (int, heap, sinfo->probs_ok,
4580                          /* FIXME: Improve calculation when skipping
4581                             inner loop to exits.  */
4582                          (si.bb_end
4583                           ? si.e1->probability
4584                           : REG_BR_PROB_BASE));
4585           sinfo->succs_ok_n++;
4586         }
4587       else
4588         VEC_safe_push (rtx, heap, sinfo->succs_other, succ);
4589
4590       /* Compute all_prob.  */
4591       if (!si.bb_end)
4592         sinfo->all_prob = REG_BR_PROB_BASE;
4593       else
4594         sinfo->all_prob += si.e1->probability;
4595
4596       sinfo->all_succs_n++;
4597     }
4598
4599   return sinfo;
4600 }
4601
4602 /* Return the predecessors of BB in PREDS and their number in N.
4603    Empty blocks are skipped.  SIZE is used to allocate PREDS.  */
4604 static void
4605 cfg_preds_1 (basic_block bb, insn_t **preds, int *n, int *size)
4606 {
4607   edge e;
4608   edge_iterator ei;
4609
4610   gcc_assert (BLOCK_TO_BB (bb->index) != 0);
4611
4612   FOR_EACH_EDGE (e, ei, bb->preds)
4613     {
4614       basic_block pred_bb = e->src;
4615       insn_t bb_end = BB_END (pred_bb);
4616
4617       if (!in_current_region_p (pred_bb))
4618         {
4619           gcc_assert (flag_sel_sched_pipelining_outer_loops
4620                       && current_loop_nest);
4621           continue;
4622         }
4623
4624       if (sel_bb_empty_p (pred_bb))
4625         cfg_preds_1 (pred_bb, preds, n, size);
4626       else
4627         {
4628           if (*n == *size)
4629             *preds = XRESIZEVEC (insn_t, *preds,
4630                                  (*size = 2 * *size + 1));
4631           (*preds)[(*n)++] = bb_end;
4632         }
4633     }
4634
4635   gcc_assert (*n != 0
4636               || (flag_sel_sched_pipelining_outer_loops
4637                   && current_loop_nest));
4638 }
4639
4640 /* Find all predecessors of BB and record them in PREDS and their number
4641    in N.  Empty blocks are skipped, and only normal (forward in-region)
4642    edges are processed.  */
4643 static void
4644 cfg_preds (basic_block bb, insn_t **preds, int *n)
4645 {
4646   int size = 0;
4647
4648   *preds = NULL;
4649   *n = 0;
4650   cfg_preds_1 (bb, preds, n, &size);
4651 }
4652
4653 /* Returns true if we are moving INSN through join point.  */
4654 bool
4655 sel_num_cfg_preds_gt_1 (insn_t insn)
4656 {
4657   basic_block bb;
4658
4659   if (!sel_bb_head_p (insn) || INSN_BB (insn) == 0)
4660     return false;
4661
4662   bb = BLOCK_FOR_INSN (insn);
4663
4664   while (1)
4665     {
4666       if (EDGE_COUNT (bb->preds) > 1)
4667         return true;
4668
4669       gcc_assert (EDGE_PRED (bb, 0)->dest == bb);
4670       bb = EDGE_PRED (bb, 0)->src;
4671
4672       if (!sel_bb_empty_p (bb))
4673         break;
4674     }
4675
4676   return false;
4677 }
4678
4679 /* Returns true when BB should be the end of an ebb.  Adapted from the
4680    code in sched-ebb.c.  */
4681 bool
4682 bb_ends_ebb_p (basic_block bb)
4683 {
4684   basic_block next_bb = bb_next_bb (bb);
4685   edge e;
4686
4687   if (next_bb == EXIT_BLOCK_PTR
4688       || bitmap_bit_p (forced_ebb_heads, next_bb->index)
4689       || (LABEL_P (BB_HEAD (next_bb))
4690           /* NB: LABEL_NUSES () is not maintained outside of jump.c.
4691              Work around that.  */
4692           && !single_pred_p (next_bb)))
4693     return true;
4694
4695   if (!in_current_region_p (next_bb))
4696     return true;
4697
4698   e = find_fallthru_edge (bb->succs);
4699   if (e)
4700     {
4701       gcc_assert (e->dest == next_bb);
4702       
4703       return false;
4704     }
4705
4706   return true;
4707 }
4708
4709 /* Returns true when INSN and SUCC are in the same EBB, given that SUCC is a
4710    successor of INSN.  */
4711 bool
4712 in_same_ebb_p (insn_t insn, insn_t succ)
4713 {
4714   basic_block ptr = BLOCK_FOR_INSN (insn);
4715
4716   for(;;)
4717     {
4718       if (ptr == BLOCK_FOR_INSN (succ))
4719         return true;
4720
4721       if (bb_ends_ebb_p (ptr))
4722         return false;
4723
4724       ptr = bb_next_bb (ptr);
4725     }
4726
4727   gcc_unreachable ();
4728   return false;
4729 }
4730
4731 /* Recomputes the reverse topological order for the function and
4732    saves it in REV_TOP_ORDER_INDEX.  REV_TOP_ORDER_INDEX_LEN is also
4733    modified appropriately.  */
4734 static void
4735 recompute_rev_top_order (void)
4736 {
4737   int *postorder;
4738   int n_blocks, i;
4739
4740   if (!rev_top_order_index || rev_top_order_index_len < last_basic_block)
4741     {
4742       rev_top_order_index_len = last_basic_block;
4743       rev_top_order_index = XRESIZEVEC (int, rev_top_order_index,
4744                                         rev_top_order_index_len);
4745     }
4746
4747   postorder = XNEWVEC (int, n_basic_blocks);
4748
4749   n_blocks = post_order_compute (postorder, true, false);
4750   gcc_assert (n_basic_blocks == n_blocks);
4751
4752   /* Build reverse function: for each basic block with BB->INDEX == K
4753      rev_top_order_index[K] is it's reverse topological sort number.  */
4754   for (i = 0; i < n_blocks; i++)
4755     {
4756       gcc_assert (postorder[i] < rev_top_order_index_len);
4757       rev_top_order_index[postorder[i]] = i;
4758     }
4759
4760   free (postorder);
4761 }
4762
4763 /* Clear all flags from insns in BB that could spoil its rescheduling.  */
4764 void
4765 clear_outdated_rtx_info (basic_block bb)
4766 {
4767   rtx insn;
4768
4769   FOR_BB_INSNS (bb, insn)
4770     if (INSN_P (insn))
4771       {
4772         SCHED_GROUP_P (insn) = 0;
4773         INSN_AFTER_STALL_P (insn) = 0;
4774         INSN_SCHED_TIMES (insn) = 0;
4775         EXPR_PRIORITY_ADJ (INSN_EXPR (insn)) = 0;
4776
4777         /* We cannot use the changed caches, as previously we could ignore
4778            the LHS dependence due to enabled renaming and transform
4779            the expression, and currently we'll be unable to do this.  */
4780         htab_empty (INSN_TRANSFORMED_INSNS (insn));
4781       }
4782 }
4783
4784 /* Add BB_NOTE to the pool of available basic block notes.  */
4785 static void
4786 return_bb_to_pool (basic_block bb)
4787 {
4788   rtx note = bb_note (bb);
4789
4790   gcc_assert (NOTE_BASIC_BLOCK (note) == bb
4791               && bb->aux == NULL);
4792
4793   /* It turns out that current cfg infrastructure does not support
4794      reuse of basic blocks.  Don't bother for now.  */
4795   /*VEC_safe_push (rtx, heap, bb_note_pool, note);*/
4796 }
4797
4798 /* Get a bb_note from pool or return NULL_RTX if pool is empty.  */
4799 static rtx
4800 get_bb_note_from_pool (void)
4801 {
4802   if (VEC_empty (rtx, bb_note_pool))
4803     return NULL_RTX;
4804   else
4805     {
4806       rtx note = VEC_pop (rtx, bb_note_pool);
4807
4808       PREV_INSN (note) = NULL_RTX;
4809       NEXT_INSN (note) = NULL_RTX;
4810
4811       return note;
4812     }
4813 }
4814
4815 /* Free bb_note_pool.  */
4816 void
4817 free_bb_note_pool (void)
4818 {
4819   VEC_free (rtx, heap, bb_note_pool);
4820 }
4821
4822 /* Setup scheduler pool and successor structure.  */
4823 void
4824 alloc_sched_pools (void)
4825 {
4826   int succs_size;
4827
4828   succs_size = MAX_WS + 1;
4829   succs_info_pool.stack = XCNEWVEC (struct succs_info, succs_size);
4830   succs_info_pool.size = succs_size;
4831   succs_info_pool.top = -1;
4832   succs_info_pool.max_top = -1;
4833
4834   sched_lists_pool = create_alloc_pool ("sel-sched-lists",
4835                                         sizeof (struct _list_node), 500);
4836 }
4837
4838 /* Free the pools.  */
4839 void
4840 free_sched_pools (void)
4841 {
4842   int i;
4843
4844   free_alloc_pool (sched_lists_pool);
4845   gcc_assert (succs_info_pool.top == -1);
4846   for (i = 0; i < succs_info_pool.max_top; i++)
4847     {
4848       VEC_free (rtx, heap, succs_info_pool.stack[i].succs_ok);
4849       VEC_free (rtx, heap, succs_info_pool.stack[i].succs_other);
4850       VEC_free (int, heap, succs_info_pool.stack[i].probs_ok);
4851     }
4852   free (succs_info_pool.stack);
4853 }
4854 \f
4855
4856 /* Returns a position in RGN where BB can be inserted retaining
4857    topological order.  */
4858 static int
4859 find_place_to_insert_bb (basic_block bb, int rgn)
4860 {
4861   bool has_preds_outside_rgn = false;
4862   edge e;
4863   edge_iterator ei;
4864
4865   /* Find whether we have preds outside the region.  */
4866   FOR_EACH_EDGE (e, ei, bb->preds)
4867     if (!in_current_region_p (e->src))
4868       {
4869         has_preds_outside_rgn = true;
4870         break;
4871       }
4872
4873   /* Recompute the top order -- needed when we have > 1 pred
4874      and in case we don't have preds outside.  */
4875   if (flag_sel_sched_pipelining_outer_loops
4876       && (has_preds_outside_rgn || EDGE_COUNT (bb->preds) > 1))
4877     {
4878       int i, bbi = bb->index, cur_bbi;
4879
4880       recompute_rev_top_order ();
4881       for (i = RGN_NR_BLOCKS (rgn) - 1; i >= 0; i--)
4882         {
4883           cur_bbi = BB_TO_BLOCK (i);
4884           if (rev_top_order_index[bbi]
4885               < rev_top_order_index[cur_bbi])
4886             break;
4887         }
4888
4889       /* We skipped the right block, so we increase i.  We accomodate
4890          it for increasing by step later, so we decrease i.  */
4891       return (i + 1) - 1;
4892     }
4893   else if (has_preds_outside_rgn)
4894     {
4895       /* This is the case when we generate an extra empty block
4896          to serve as region head during pipelining.  */
4897       e = EDGE_SUCC (bb, 0);
4898       gcc_assert (EDGE_COUNT (bb->succs) == 1
4899                   && in_current_region_p (EDGE_SUCC (bb, 0)->dest)
4900                   && (BLOCK_TO_BB (e->dest->index) == 0));
4901       return -1;
4902     }
4903
4904   /* We don't have preds outside the region.  We should have
4905      the only pred, because the multiple preds case comes from
4906      the pipelining of outer loops, and that is handled above.
4907      Just take the bbi of this single pred.  */
4908   if (EDGE_COUNT (bb->succs) > 0)
4909     {
4910       int pred_bbi;
4911
4912       gcc_assert (EDGE_COUNT (bb->preds) == 1);
4913
4914       pred_bbi = EDGE_PRED (bb, 0)->src->index;
4915       return BLOCK_TO_BB (pred_bbi);
4916     }
4917   else
4918     /* BB has no successors.  It is safe to put it in the end.  */
4919     return current_nr_blocks - 1;
4920 }
4921
4922 /* Deletes an empty basic block freeing its data.  */
4923 static void
4924 delete_and_free_basic_block (basic_block bb)
4925 {
4926   gcc_assert (sel_bb_empty_p (bb));
4927
4928   if (BB_LV_SET (bb))
4929     free_lv_set (bb);
4930
4931   bitmap_clear_bit (blocks_to_reschedule, bb->index);
4932
4933   /* Can't assert av_set properties because we use sel_aremove_bb
4934      when removing loop preheader from the region.  At the point of
4935      removing the preheader we already have deallocated sel_region_bb_info.  */
4936   gcc_assert (BB_LV_SET (bb) == NULL
4937               && !BB_LV_SET_VALID_P (bb)
4938               && BB_AV_LEVEL (bb) == 0
4939               && BB_AV_SET (bb) == NULL);
4940
4941   delete_basic_block (bb);
4942 }
4943
4944 /* Add BB to the current region and update the region data.  */
4945 static void
4946 add_block_to_current_region (basic_block bb)
4947 {
4948   int i, pos, bbi = -2, rgn;
4949
4950   rgn = CONTAINING_RGN (BB_TO_BLOCK (0));
4951   bbi = find_place_to_insert_bb (bb, rgn);
4952   bbi += 1;
4953   pos = RGN_BLOCKS (rgn) + bbi;
4954
4955   gcc_assert (RGN_HAS_REAL_EBB (rgn) == 0
4956               && ebb_head[bbi] == pos);
4957
4958   /* Make a place for the new block.  */
4959   extend_regions ();
4960
4961   for (i = RGN_BLOCKS (rgn + 1) - 1; i >= pos; i--)
4962     BLOCK_TO_BB (rgn_bb_table[i])++;
4963
4964   memmove (rgn_bb_table + pos + 1,
4965            rgn_bb_table + pos,
4966            (RGN_BLOCKS (nr_regions) - pos) * sizeof (*rgn_bb_table));
4967
4968   /* Initialize data for BB.  */
4969   rgn_bb_table[pos] = bb->index;
4970   BLOCK_TO_BB (bb->index) = bbi;
4971   CONTAINING_RGN (bb->index) = rgn;
4972
4973   RGN_NR_BLOCKS (rgn)++;
4974
4975   for (i = rgn + 1; i <= nr_regions; i++)
4976     RGN_BLOCKS (i)++;
4977 }
4978
4979 /* Remove BB from the current region and update the region data.  */
4980 static void
4981 remove_bb_from_region (basic_block bb)
4982 {
4983   int i, pos, bbi = -2, rgn;
4984
4985   rgn = CONTAINING_RGN (BB_TO_BLOCK (0));
4986   bbi = BLOCK_TO_BB (bb->index);
4987   pos = RGN_BLOCKS (rgn) + bbi;
4988
4989   gcc_assert (RGN_HAS_REAL_EBB (rgn) == 0
4990               && ebb_head[bbi] == pos);
4991
4992   for (i = RGN_BLOCKS (rgn + 1) - 1; i >= pos; i--)
4993     BLOCK_TO_BB (rgn_bb_table[i])--;
4994
4995   memmove (rgn_bb_table + pos,
4996            rgn_bb_table + pos + 1,
4997            (RGN_BLOCKS (nr_regions) - pos) * sizeof (*rgn_bb_table));
4998
4999   RGN_NR_BLOCKS (rgn)--;
5000   for (i = rgn + 1; i <= nr_regions; i++)
5001     RGN_BLOCKS (i)--;
5002 }
5003
5004 /* Add BB to the current region  and update all data.  If BB is NULL, add all
5005    blocks from last_added_blocks vector.  */
5006 static void
5007 sel_add_bb (basic_block bb)
5008 {
5009   /* Extend luids so that new notes will receive zero luids.  */
5010   sched_init_luids (NULL, NULL, NULL, NULL);
5011   sched_init_bbs ();
5012   sel_init_bbs (last_added_blocks, NULL);
5013
5014   /* When bb is passed explicitly, the vector should contain
5015      the only element that equals to bb; otherwise, the vector
5016      should not be NULL.  */
5017   gcc_assert (last_added_blocks != NULL);
5018
5019   if (bb != NULL)
5020     {
5021       gcc_assert (VEC_length (basic_block, last_added_blocks) == 1
5022                   && VEC_index (basic_block,
5023                                 last_added_blocks, 0) == bb);
5024       add_block_to_current_region (bb);
5025
5026       /* We associate creating/deleting data sets with the first insn
5027          appearing / disappearing in the bb.  */
5028       if (!sel_bb_empty_p (bb) && BB_LV_SET (bb) == NULL)
5029         create_initial_data_sets (bb);
5030
5031       VEC_free (basic_block, heap, last_added_blocks);
5032     }
5033   else
5034     /* BB is NULL - process LAST_ADDED_BLOCKS instead.  */
5035     {
5036       int i;
5037       basic_block temp_bb = NULL;
5038
5039       for (i = 0;
5040            VEC_iterate (basic_block, last_added_blocks, i, bb); i++)
5041         {
5042           add_block_to_current_region (bb);
5043           temp_bb = bb;
5044         }
5045
5046       /* We need to fetch at least one bb so we know the region
5047          to update.  */
5048       gcc_assert (temp_bb != NULL);
5049       bb = temp_bb;
5050
5051       VEC_free (basic_block, heap, last_added_blocks);
5052     }
5053
5054   rgn_setup_region (CONTAINING_RGN (bb->index));
5055 }
5056
5057 /* Remove BB from the current region and update all data.
5058    If REMOVE_FROM_CFG_PBB is true, also remove the block cfom cfg.  */
5059 static void
5060 sel_remove_bb (basic_block bb, bool remove_from_cfg_p)
5061 {
5062   unsigned idx = bb->index;
5063
5064   gcc_assert (bb != NULL && BB_NOTE_LIST (bb) == NULL_RTX);
5065
5066   remove_bb_from_region (bb);
5067   return_bb_to_pool (bb);
5068   bitmap_clear_bit (blocks_to_reschedule, idx);
5069
5070   if (remove_from_cfg_p)
5071     delete_and_free_basic_block (bb);
5072
5073   rgn_setup_region (CONTAINING_RGN (idx));
5074 }
5075
5076 /* Concatenate info of EMPTY_BB to info of MERGE_BB.  */
5077 static void
5078 move_bb_info (basic_block merge_bb, basic_block empty_bb)
5079 {
5080   gcc_assert (in_current_region_p (merge_bb));
5081
5082   concat_note_lists (BB_NOTE_LIST (empty_bb),
5083                      &BB_NOTE_LIST (merge_bb));
5084   BB_NOTE_LIST (empty_bb) = NULL_RTX;
5085
5086 }
5087
5088 /* Remove EMPTY_BB.  If REMOVE_FROM_CFG_P is false, remove EMPTY_BB from
5089    region, but keep it in CFG.  */
5090 static void
5091 remove_empty_bb (basic_block empty_bb, bool remove_from_cfg_p)
5092 {
5093   /* The block should contain just a note or a label.
5094      We try to check whether it is unused below.  */
5095   gcc_assert (BB_HEAD (empty_bb) == BB_END (empty_bb)
5096               || LABEL_P (BB_HEAD (empty_bb)));
5097
5098   /* If basic block has predecessors or successors, redirect them.  */
5099   if (remove_from_cfg_p
5100       && (EDGE_COUNT (empty_bb->preds) > 0
5101           || EDGE_COUNT (empty_bb->succs) > 0))
5102     {
5103       basic_block pred;
5104       basic_block succ;
5105
5106       /* We need to init PRED and SUCC before redirecting edges.  */
5107       if (EDGE_COUNT (empty_bb->preds) > 0)
5108         {
5109           edge e;
5110
5111           gcc_assert (EDGE_COUNT (empty_bb->preds) == 1);
5112
5113           e = EDGE_PRED (empty_bb, 0);
5114           gcc_assert (e->src == empty_bb->prev_bb
5115                       && (e->flags & EDGE_FALLTHRU));
5116
5117           pred = empty_bb->prev_bb;
5118         }
5119       else
5120         pred = NULL;
5121
5122       if (EDGE_COUNT (empty_bb->succs) > 0)
5123         {
5124           /* We do not check fallthruness here as above, because
5125              after removing a jump the edge may actually be not fallthru.  */
5126           gcc_assert (EDGE_COUNT (empty_bb->succs) == 1);
5127           succ = EDGE_SUCC (empty_bb, 0)->dest;
5128         }
5129       else
5130         succ = NULL;
5131
5132       if (EDGE_COUNT (empty_bb->preds) > 0 && succ != NULL)
5133         {
5134           edge e = EDGE_PRED (empty_bb, 0);
5135
5136           if (e->flags & EDGE_FALLTHRU)
5137             redirect_edge_succ_nodup (e, succ);
5138           else
5139             sel_redirect_edge_and_branch (EDGE_PRED (empty_bb, 0), succ);
5140         }
5141
5142       if (EDGE_COUNT (empty_bb->succs) > 0 && pred != NULL)
5143         {
5144           edge e = EDGE_SUCC (empty_bb, 0);
5145
5146           if (find_edge (pred, e->dest) == NULL)
5147             redirect_edge_pred (e, pred);
5148         }
5149     }
5150
5151   /* Finish removing.  */
5152   sel_remove_bb (empty_bb, remove_from_cfg_p);
5153 }
5154
5155 /* An implementation of create_basic_block hook, which additionally updates
5156    per-bb data structures.  */
5157 static basic_block
5158 sel_create_basic_block (void *headp, void *endp, basic_block after)
5159 {
5160   basic_block new_bb;
5161   insn_t new_bb_note;
5162
5163   gcc_assert (flag_sel_sched_pipelining_outer_loops
5164               || last_added_blocks == NULL);
5165
5166   new_bb_note = get_bb_note_from_pool ();
5167
5168   if (new_bb_note == NULL_RTX)
5169     new_bb = orig_cfg_hooks.create_basic_block (headp, endp, after);
5170   else
5171     {
5172       new_bb = create_basic_block_structure ((rtx) headp, (rtx) endp,
5173                                              new_bb_note, after);
5174       new_bb->aux = NULL;
5175     }
5176
5177   VEC_safe_push (basic_block, heap, last_added_blocks, new_bb);
5178
5179   return new_bb;
5180 }
5181
5182 /* Implement sched_init_only_bb ().  */
5183 static void
5184 sel_init_only_bb (basic_block bb, basic_block after)
5185 {
5186   gcc_assert (after == NULL);
5187
5188   extend_regions ();
5189   rgn_make_new_region_out_of_new_block (bb);
5190 }
5191
5192 /* Update the latch when we've splitted or merged it from FROM block to TO.
5193    This should be checked for all outer loops, too.  */
5194 static void
5195 change_loops_latches (basic_block from, basic_block to)
5196 {
5197   gcc_assert (from != to);
5198
5199   if (current_loop_nest)
5200     {
5201       struct loop *loop;
5202
5203       for (loop = current_loop_nest; loop; loop = loop_outer (loop))
5204         if (considered_for_pipelining_p (loop) && loop->latch == from)
5205           {
5206             gcc_assert (loop == current_loop_nest);
5207             loop->latch = to;
5208             gcc_assert (loop_latch_edge (loop));
5209           }
5210     }
5211 }
5212
5213 /* Splits BB on two basic blocks, adding it to the region and extending
5214    per-bb data structures.  Returns the newly created bb.  */
5215 static basic_block
5216 sel_split_block (basic_block bb, rtx after)
5217 {
5218   basic_block new_bb;
5219   insn_t insn;
5220
5221   new_bb = sched_split_block_1 (bb, after);
5222   sel_add_bb (new_bb);
5223
5224   /* This should be called after sel_add_bb, because this uses
5225      CONTAINING_RGN for the new block, which is not yet initialized.
5226      FIXME: this function may be a no-op now.  */
5227   change_loops_latches (bb, new_bb);
5228
5229   /* Update ORIG_BB_INDEX for insns moved into the new block.  */
5230   FOR_BB_INSNS (new_bb, insn)
5231    if (INSN_P (insn))
5232      EXPR_ORIG_BB_INDEX (INSN_EXPR (insn)) = new_bb->index;
5233
5234   if (sel_bb_empty_p (bb))
5235     {
5236       gcc_assert (!sel_bb_empty_p (new_bb));
5237
5238       /* NEW_BB has data sets that need to be updated and BB holds
5239          data sets that should be removed.  Exchange these data sets
5240          so that we won't lose BB's valid data sets.  */
5241       exchange_data_sets (new_bb, bb);
5242       free_data_sets (bb);
5243     }
5244
5245   if (!sel_bb_empty_p (new_bb)
5246       && bitmap_bit_p (blocks_to_reschedule, bb->index))
5247     bitmap_set_bit (blocks_to_reschedule, new_bb->index);
5248
5249   return new_bb;
5250 }
5251
5252 /* If BB ends with a jump insn whose ID is bigger then PREV_MAX_UID, return it.
5253    Otherwise returns NULL.  */
5254 static rtx
5255 check_for_new_jump (basic_block bb, int prev_max_uid)
5256 {
5257   rtx end;
5258
5259   end = sel_bb_end (bb);
5260   if (end && INSN_UID (end) >= prev_max_uid)
5261     return end;
5262   return NULL;
5263 }
5264
5265 /* Look for a new jump either in FROM_BB block or in newly created JUMP_BB block.
5266    New means having UID at least equal to PREV_MAX_UID.  */
5267 static rtx
5268 find_new_jump (basic_block from, basic_block jump_bb, int prev_max_uid)
5269 {
5270   rtx jump;
5271
5272   /* Return immediately if no new insns were emitted.  */
5273   if (get_max_uid () == prev_max_uid)
5274     return NULL;
5275
5276   /* Now check both blocks for new jumps.  It will ever be only one.  */
5277   if ((jump = check_for_new_jump (from, prev_max_uid)))
5278     return jump;
5279
5280   if (jump_bb != NULL
5281       && (jump = check_for_new_jump (jump_bb, prev_max_uid)))
5282     return jump;
5283   return NULL;
5284 }
5285
5286 /* Splits E and adds the newly created basic block to the current region.
5287    Returns this basic block.  */
5288 basic_block
5289 sel_split_edge (edge e)
5290 {
5291   basic_block new_bb, src, other_bb = NULL;
5292   int prev_max_uid;
5293   rtx jump;
5294
5295   src = e->src;
5296   prev_max_uid = get_max_uid ();
5297   new_bb = split_edge (e);
5298
5299   if (flag_sel_sched_pipelining_outer_loops
5300       && current_loop_nest)
5301     {
5302       int i;
5303       basic_block bb;
5304
5305       /* Some of the basic blocks might not have been added to the loop.
5306          Add them here, until this is fixed in force_fallthru.  */
5307       for (i = 0;
5308            VEC_iterate (basic_block, last_added_blocks, i, bb); i++)
5309         if (!bb->loop_father)
5310           {
5311             add_bb_to_loop (bb, e->dest->loop_father);
5312
5313             gcc_assert (!other_bb && (new_bb->index != bb->index));
5314             other_bb = bb;
5315           }
5316     }
5317
5318   /* Add all last_added_blocks to the region.  */
5319   sel_add_bb (NULL);
5320
5321   jump = find_new_jump (src, new_bb, prev_max_uid);
5322   if (jump)
5323     sel_init_new_insn (jump, INSN_INIT_TODO_LUID | INSN_INIT_TODO_SIMPLEJUMP);
5324
5325   /* Put the correct lv set on this block.  */
5326   if (other_bb && !sel_bb_empty_p (other_bb))
5327     compute_live (sel_bb_head (other_bb));
5328
5329   return new_bb;
5330 }
5331
5332 /* Implement sched_create_empty_bb ().  */
5333 static basic_block
5334 sel_create_empty_bb (basic_block after)
5335 {
5336   basic_block new_bb;
5337
5338   new_bb = sched_create_empty_bb_1 (after);
5339
5340   /* We'll explicitly initialize NEW_BB via sel_init_only_bb () a bit
5341      later.  */
5342   gcc_assert (VEC_length (basic_block, last_added_blocks) == 1
5343               && VEC_index (basic_block, last_added_blocks, 0) == new_bb);
5344
5345   VEC_free (basic_block, heap, last_added_blocks);
5346   return new_bb;
5347 }
5348
5349 /* Implement sched_create_recovery_block.  ORIG_INSN is where block
5350    will be splitted to insert a check.  */
5351 basic_block
5352 sel_create_recovery_block (insn_t orig_insn)
5353 {
5354   basic_block first_bb, second_bb, recovery_block;
5355   basic_block before_recovery = NULL;
5356   rtx jump;
5357
5358   first_bb = BLOCK_FOR_INSN (orig_insn);
5359   if (sel_bb_end_p (orig_insn))
5360     {
5361       /* Avoid introducing an empty block while splitting.  */
5362       gcc_assert (single_succ_p (first_bb));
5363       second_bb = single_succ (first_bb);
5364     }
5365   else
5366     second_bb = sched_split_block (first_bb, orig_insn);
5367
5368   recovery_block = sched_create_recovery_block (&before_recovery);
5369   if (before_recovery)
5370     copy_lv_set_from (before_recovery, EXIT_BLOCK_PTR);
5371
5372   gcc_assert (sel_bb_empty_p (recovery_block));
5373   sched_create_recovery_edges (first_bb, recovery_block, second_bb);
5374   if (current_loops != NULL)
5375     add_bb_to_loop (recovery_block, first_bb->loop_father);
5376
5377   sel_add_bb (recovery_block);
5378
5379   jump = BB_END (recovery_block);
5380   gcc_assert (sel_bb_head (recovery_block) == jump);
5381   sel_init_new_insn (jump, INSN_INIT_TODO_LUID | INSN_INIT_TODO_SIMPLEJUMP);
5382
5383   return recovery_block;
5384 }
5385
5386 /* Merge basic block B into basic block A.  */
5387 static void
5388 sel_merge_blocks (basic_block a, basic_block b)
5389 {
5390   gcc_assert (sel_bb_empty_p (b)
5391               && EDGE_COUNT (b->preds) == 1
5392               && EDGE_PRED (b, 0)->src == b->prev_bb);
5393
5394   move_bb_info (b->prev_bb, b);
5395   remove_empty_bb (b, false);
5396   merge_blocks (a, b);
5397   change_loops_latches (b, a);
5398 }
5399
5400 /* A wrapper for redirect_edge_and_branch_force, which also initializes
5401    data structures for possibly created bb and insns.  Returns the newly
5402    added bb or NULL, when a bb was not needed.  */
5403 void
5404 sel_redirect_edge_and_branch_force (edge e, basic_block to)
5405 {
5406   basic_block jump_bb, src;
5407   int prev_max_uid;
5408   rtx jump;
5409
5410   gcc_assert (!sel_bb_empty_p (e->src));
5411
5412   src = e->src;
5413   prev_max_uid = get_max_uid ();
5414   jump_bb = redirect_edge_and_branch_force (e, to);
5415
5416   if (jump_bb != NULL)
5417     sel_add_bb (jump_bb);
5418
5419   /* This function could not be used to spoil the loop structure by now,
5420      thus we don't care to update anything.  But check it to be sure.  */
5421   if (current_loop_nest
5422       && pipelining_p)
5423     gcc_assert (loop_latch_edge (current_loop_nest));
5424
5425   jump = find_new_jump (src, jump_bb, prev_max_uid);
5426   if (jump)
5427     sel_init_new_insn (jump, INSN_INIT_TODO_LUID | INSN_INIT_TODO_SIMPLEJUMP);
5428 }
5429
5430 /* A wrapper for redirect_edge_and_branch.  Return TRUE if blocks connected by
5431    redirected edge are in reverse topological order.  */
5432 bool
5433 sel_redirect_edge_and_branch (edge e, basic_block to)
5434 {
5435   bool latch_edge_p;
5436   basic_block src;
5437   int prev_max_uid;
5438   rtx jump;
5439   edge redirected;
5440   bool recompute_toporder_p = false;
5441
5442   latch_edge_p = (pipelining_p
5443                   && current_loop_nest
5444                   && e == loop_latch_edge (current_loop_nest));
5445
5446   src = e->src;
5447   prev_max_uid = get_max_uid ();
5448
5449   redirected = redirect_edge_and_branch (e, to);
5450
5451   gcc_assert (redirected && last_added_blocks == NULL);
5452
5453   /* When we've redirected a latch edge, update the header.  */
5454   if (latch_edge_p)
5455     {
5456       current_loop_nest->header = to;
5457       gcc_assert (loop_latch_edge (current_loop_nest));
5458     }
5459
5460   /* In rare situations, the topological relation between the blocks connected
5461      by the redirected edge can change (see PR42245 for an example).  Update
5462      block_to_bb/bb_to_block.  */
5463   if (CONTAINING_RGN (e->src->index) == CONTAINING_RGN (to->index)
5464       && BLOCK_TO_BB (e->src->index) > BLOCK_TO_BB (to->index))
5465     recompute_toporder_p = true;
5466
5467   jump = find_new_jump (src, NULL, prev_max_uid);
5468   if (jump)
5469     sel_init_new_insn (jump, INSN_INIT_TODO_LUID | INSN_INIT_TODO_SIMPLEJUMP);
5470
5471   return recompute_toporder_p;
5472 }
5473
5474 /* This variable holds the cfg hooks used by the selective scheduler.  */
5475 static struct cfg_hooks sel_cfg_hooks;
5476
5477 /* Register sel-sched cfg hooks.  */
5478 void
5479 sel_register_cfg_hooks (void)
5480 {
5481   sched_split_block = sel_split_block;
5482
5483   orig_cfg_hooks = get_cfg_hooks ();
5484   sel_cfg_hooks = orig_cfg_hooks;
5485
5486   sel_cfg_hooks.create_basic_block = sel_create_basic_block;
5487
5488   set_cfg_hooks (sel_cfg_hooks);
5489
5490   sched_init_only_bb = sel_init_only_bb;
5491   sched_split_block = sel_split_block;
5492   sched_create_empty_bb = sel_create_empty_bb;
5493 }
5494
5495 /* Unregister sel-sched cfg hooks.  */
5496 void
5497 sel_unregister_cfg_hooks (void)
5498 {
5499   sched_create_empty_bb = NULL;
5500   sched_split_block = NULL;
5501   sched_init_only_bb = NULL;
5502
5503   set_cfg_hooks (orig_cfg_hooks);
5504 }
5505 \f
5506
5507 /* Emit an insn rtx based on PATTERN.  If a jump insn is wanted,
5508    LABEL is where this jump should be directed.  */
5509 rtx
5510 create_insn_rtx_from_pattern (rtx pattern, rtx label)
5511 {
5512   rtx insn_rtx;
5513
5514   gcc_assert (!INSN_P (pattern));
5515
5516   start_sequence ();
5517
5518   if (label == NULL_RTX)
5519     insn_rtx = emit_insn (pattern);
5520   else if (DEBUG_INSN_P (label))
5521     insn_rtx = emit_debug_insn (pattern);
5522   else
5523     {
5524       insn_rtx = emit_jump_insn (pattern);
5525       JUMP_LABEL (insn_rtx) = label;
5526       ++LABEL_NUSES (label);
5527     }
5528
5529   end_sequence ();
5530
5531   sched_init_luids (NULL, NULL, NULL, NULL);
5532   sched_extend_target ();
5533   sched_deps_init (false);
5534
5535   /* Initialize INSN_CODE now.  */
5536   recog_memoized (insn_rtx);
5537   return insn_rtx;
5538 }
5539
5540 /* Create a new vinsn for INSN_RTX.  FORCE_UNIQUE_P is true when the vinsn
5541    must not be clonable.  */
5542 vinsn_t
5543 create_vinsn_from_insn_rtx (rtx insn_rtx, bool force_unique_p)
5544 {
5545   gcc_assert (INSN_P (insn_rtx) && !INSN_IN_STREAM_P (insn_rtx));
5546
5547   /* If VINSN_TYPE is not USE, retain its uniqueness.  */
5548   return vinsn_create (insn_rtx, force_unique_p);
5549 }
5550
5551 /* Create a copy of INSN_RTX.  */
5552 rtx
5553 create_copy_of_insn_rtx (rtx insn_rtx)
5554 {
5555   rtx res;
5556
5557   if (DEBUG_INSN_P (insn_rtx))
5558     return create_insn_rtx_from_pattern (copy_rtx (PATTERN (insn_rtx)),
5559                                          insn_rtx);
5560
5561   gcc_assert (NONJUMP_INSN_P (insn_rtx));
5562
5563   res = create_insn_rtx_from_pattern (copy_rtx (PATTERN (insn_rtx)),
5564                                       NULL_RTX);
5565   return res;
5566 }
5567
5568 /* Change vinsn field of EXPR to hold NEW_VINSN.  */
5569 void
5570 change_vinsn_in_expr (expr_t expr, vinsn_t new_vinsn)
5571 {
5572   vinsn_detach (EXPR_VINSN (expr));
5573
5574   EXPR_VINSN (expr) = new_vinsn;
5575   vinsn_attach (new_vinsn);
5576 }
5577
5578 /* Helpers for global init.  */
5579 /* This structure is used to be able to call existing bundling mechanism
5580    and calculate insn priorities.  */
5581 static struct haifa_sched_info sched_sel_haifa_sched_info =
5582 {
5583   NULL, /* init_ready_list */
5584   NULL, /* can_schedule_ready_p */
5585   NULL, /* schedule_more_p */
5586   NULL, /* new_ready */
5587   NULL, /* rgn_rank */
5588   sel_print_insn, /* rgn_print_insn */
5589   contributes_to_priority,
5590   NULL, /* insn_finishes_block_p */
5591
5592   NULL, NULL,
5593   NULL, NULL,
5594   0, 0,
5595
5596   NULL, /* add_remove_insn */
5597   NULL, /* begin_schedule_ready */
5598   NULL, /* advance_target_bb */
5599   SEL_SCHED | NEW_BBS
5600 };
5601
5602 /* Setup special insns used in the scheduler.  */
5603 void
5604 setup_nop_and_exit_insns (void)
5605 {
5606   gcc_assert (nop_pattern == NULL_RTX
5607               && exit_insn == NULL_RTX);
5608
5609   nop_pattern = gen_nop ();
5610
5611   start_sequence ();
5612   emit_insn (nop_pattern);
5613   exit_insn = get_insns ();
5614   end_sequence ();
5615   set_block_for_insn (exit_insn, EXIT_BLOCK_PTR);
5616 }
5617
5618 /* Free special insns used in the scheduler.  */
5619 void
5620 free_nop_and_exit_insns (void)
5621 {
5622   exit_insn = NULL_RTX;
5623   nop_pattern = NULL_RTX;
5624 }
5625
5626 /* Setup a special vinsn used in new insns initialization.  */
5627 void
5628 setup_nop_vinsn (void)
5629 {
5630   nop_vinsn = vinsn_create (exit_insn, false);
5631   vinsn_attach (nop_vinsn);
5632 }
5633
5634 /* Free a special vinsn used in new insns initialization.  */
5635 void
5636 free_nop_vinsn (void)
5637 {
5638   gcc_assert (VINSN_COUNT (nop_vinsn) == 1);
5639   vinsn_detach (nop_vinsn);
5640   nop_vinsn = NULL;
5641 }
5642
5643 /* Call a set_sched_flags hook.  */
5644 void
5645 sel_set_sched_flags (void)
5646 {
5647   /* ??? This means that set_sched_flags were called, and we decided to
5648      support speculation.  However, set_sched_flags also modifies flags
5649      on current_sched_info, doing this only at global init.  And we
5650      sometimes change c_s_i later.  So put the correct flags again.  */
5651   if (spec_info && targetm.sched.set_sched_flags)
5652     targetm.sched.set_sched_flags (spec_info);
5653 }
5654
5655 /* Setup pointers to global sched info structures.  */
5656 void
5657 sel_setup_sched_infos (void)
5658 {
5659   rgn_setup_common_sched_info ();
5660
5661   memcpy (&sel_common_sched_info, common_sched_info,
5662           sizeof (sel_common_sched_info));
5663
5664   sel_common_sched_info.fix_recovery_cfg = NULL;
5665   sel_common_sched_info.add_block = NULL;
5666   sel_common_sched_info.estimate_number_of_insns
5667     = sel_estimate_number_of_insns;
5668   sel_common_sched_info.luid_for_non_insn = sel_luid_for_non_insn;
5669   sel_common_sched_info.sched_pass_id = SCHED_SEL_PASS;
5670
5671   common_sched_info = &sel_common_sched_info;
5672
5673   current_sched_info = &sched_sel_haifa_sched_info;
5674   current_sched_info->sched_max_insns_priority =
5675     get_rgn_sched_max_insns_priority ();
5676
5677   sel_set_sched_flags ();
5678 }
5679 \f
5680
5681 /* Adds basic block BB to region RGN at the position *BB_ORD_INDEX,
5682    *BB_ORD_INDEX after that is increased.  */
5683 static void
5684 sel_add_block_to_region (basic_block bb, int *bb_ord_index, int rgn)
5685 {
5686   RGN_NR_BLOCKS (rgn) += 1;
5687   RGN_DONT_CALC_DEPS (rgn) = 0;
5688   RGN_HAS_REAL_EBB (rgn) = 0;
5689   CONTAINING_RGN (bb->index) = rgn;
5690   BLOCK_TO_BB (bb->index) = *bb_ord_index;
5691   rgn_bb_table[RGN_BLOCKS (rgn) + *bb_ord_index] = bb->index;
5692   (*bb_ord_index)++;
5693
5694   /* FIXME: it is true only when not scheduling ebbs.  */
5695   RGN_BLOCKS (rgn + 1) = RGN_BLOCKS (rgn) + RGN_NR_BLOCKS (rgn);
5696 }
5697
5698 /* Functions to support pipelining of outer loops.  */
5699
5700 /* Creates a new empty region and returns it's number.  */
5701 static int
5702 sel_create_new_region (void)
5703 {
5704   int new_rgn_number = nr_regions;
5705
5706   RGN_NR_BLOCKS (new_rgn_number) = 0;
5707
5708   /* FIXME: This will work only when EBBs are not created.  */
5709   if (new_rgn_number != 0)
5710     RGN_BLOCKS (new_rgn_number) = RGN_BLOCKS (new_rgn_number - 1) +
5711       RGN_NR_BLOCKS (new_rgn_number - 1);
5712   else
5713     RGN_BLOCKS (new_rgn_number) = 0;
5714
5715   /* Set the blocks of the next region so the other functions may
5716      calculate the number of blocks in the region.  */
5717   RGN_BLOCKS (new_rgn_number + 1) = RGN_BLOCKS (new_rgn_number) +
5718     RGN_NR_BLOCKS (new_rgn_number);
5719
5720   nr_regions++;
5721
5722   return new_rgn_number;
5723 }
5724
5725 /* If X has a smaller topological sort number than Y, returns -1;
5726    if greater, returns 1.  */
5727 static int
5728 bb_top_order_comparator (const void *x, const void *y)
5729 {
5730   basic_block bb1 = *(const basic_block *) x;
5731   basic_block bb2 = *(const basic_block *) y;
5732
5733   gcc_assert (bb1 == bb2
5734               || rev_top_order_index[bb1->index]
5735                  != rev_top_order_index[bb2->index]);
5736
5737   /* It's a reverse topological order in REV_TOP_ORDER_INDEX, so
5738      bbs with greater number should go earlier.  */
5739   if (rev_top_order_index[bb1->index] > rev_top_order_index[bb2->index])
5740     return -1;
5741   else
5742     return 1;
5743 }
5744
5745 /* Create a region for LOOP and return its number.  If we don't want
5746    to pipeline LOOP, return -1.  */
5747 static int
5748 make_region_from_loop (struct loop *loop)
5749 {
5750   unsigned int i;
5751   int new_rgn_number = -1;
5752   struct loop *inner;
5753
5754   /* Basic block index, to be assigned to BLOCK_TO_BB.  */
5755   int bb_ord_index = 0;
5756   basic_block *loop_blocks;
5757   basic_block preheader_block;
5758
5759   if (loop->num_nodes
5760       > (unsigned) PARAM_VALUE (PARAM_MAX_PIPELINE_REGION_BLOCKS))
5761     return -1;
5762
5763   /* Don't pipeline loops whose latch belongs to some of its inner loops.  */
5764   for (inner = loop->inner; inner; inner = inner->inner)
5765     if (flow_bb_inside_loop_p (inner, loop->latch))
5766       return -1;
5767
5768   loop->ninsns = num_loop_insns (loop);
5769   if ((int) loop->ninsns > PARAM_VALUE (PARAM_MAX_PIPELINE_REGION_INSNS))
5770     return -1;
5771
5772   loop_blocks = get_loop_body_in_custom_order (loop, bb_top_order_comparator);
5773
5774   for (i = 0; i < loop->num_nodes; i++)
5775     if (loop_blocks[i]->flags & BB_IRREDUCIBLE_LOOP)
5776       {
5777         free (loop_blocks);
5778         return -1;
5779       }
5780
5781   preheader_block = loop_preheader_edge (loop)->src;
5782   gcc_assert (preheader_block);
5783   gcc_assert (loop_blocks[0] == loop->header);
5784
5785   new_rgn_number = sel_create_new_region ();
5786
5787   sel_add_block_to_region (preheader_block, &bb_ord_index, new_rgn_number);
5788   SET_BIT (bbs_in_loop_rgns, preheader_block->index);
5789
5790   for (i = 0; i < loop->num_nodes; i++)
5791     {
5792       /* Add only those blocks that haven't been scheduled in the inner loop.
5793          The exception is the basic blocks with bookkeeping code - they should
5794          be added to the region (and they actually don't belong to the loop
5795          body, but to the region containing that loop body).  */
5796
5797       gcc_assert (new_rgn_number >= 0);
5798
5799       if (! TEST_BIT (bbs_in_loop_rgns, loop_blocks[i]->index))
5800         {
5801           sel_add_block_to_region (loop_blocks[i], &bb_ord_index,
5802                                    new_rgn_number);
5803           SET_BIT (bbs_in_loop_rgns, loop_blocks[i]->index);
5804         }
5805     }
5806
5807   free (loop_blocks);
5808   MARK_LOOP_FOR_PIPELINING (loop);
5809
5810   return new_rgn_number;
5811 }
5812
5813 /* Create a new region from preheader blocks LOOP_BLOCKS.  */
5814 void
5815 make_region_from_loop_preheader (VEC(basic_block, heap) **loop_blocks)
5816 {
5817   unsigned int i;
5818   int new_rgn_number = -1;
5819   basic_block bb;
5820
5821   /* Basic block index, to be assigned to BLOCK_TO_BB.  */
5822   int bb_ord_index = 0;
5823
5824   new_rgn_number = sel_create_new_region ();
5825
5826   FOR_EACH_VEC_ELT (basic_block, *loop_blocks, i, bb)
5827     {
5828       gcc_assert (new_rgn_number >= 0);
5829
5830       sel_add_block_to_region (bb, &bb_ord_index, new_rgn_number);
5831     }
5832
5833   VEC_free (basic_block, heap, *loop_blocks);
5834   gcc_assert (*loop_blocks == NULL);
5835 }
5836
5837
5838 /* Create region(s) from loop nest LOOP, such that inner loops will be
5839    pipelined before outer loops.  Returns true when a region for LOOP
5840    is created.  */
5841 static bool
5842 make_regions_from_loop_nest (struct loop *loop)
5843 {
5844   struct loop *cur_loop;
5845   int rgn_number;
5846
5847   /* Traverse all inner nodes of the loop.  */
5848   for (cur_loop = loop->inner; cur_loop; cur_loop = cur_loop->next)
5849     if (! TEST_BIT (bbs_in_loop_rgns, cur_loop->header->index))
5850       return false;
5851
5852   /* At this moment all regular inner loops should have been pipelined.
5853      Try to create a region from this loop.  */
5854   rgn_number = make_region_from_loop (loop);
5855
5856   if (rgn_number < 0)
5857     return false;
5858
5859   VEC_safe_push (loop_p, heap, loop_nests, loop);
5860   return true;
5861 }
5862
5863 /* Initalize data structures needed.  */
5864 void
5865 sel_init_pipelining (void)
5866 {
5867   /* Collect loop information to be used in outer loops pipelining.  */
5868   loop_optimizer_init (LOOPS_HAVE_PREHEADERS
5869                        | LOOPS_HAVE_FALLTHRU_PREHEADERS
5870                        | LOOPS_HAVE_RECORDED_EXITS
5871                        | LOOPS_HAVE_MARKED_IRREDUCIBLE_REGIONS);
5872   current_loop_nest = NULL;
5873
5874   bbs_in_loop_rgns = sbitmap_alloc (last_basic_block);
5875   sbitmap_zero (bbs_in_loop_rgns);
5876
5877   recompute_rev_top_order ();
5878 }
5879
5880 /* Returns a struct loop for region RGN.  */
5881 loop_p
5882 get_loop_nest_for_rgn (unsigned int rgn)
5883 {
5884   /* Regions created with extend_rgns don't have corresponding loop nests,
5885      because they don't represent loops.  */
5886   if (rgn < VEC_length (loop_p, loop_nests))
5887     return VEC_index (loop_p, loop_nests, rgn);
5888   else
5889     return NULL;
5890 }
5891
5892 /* True when LOOP was included into pipelining regions.   */
5893 bool
5894 considered_for_pipelining_p (struct loop *loop)
5895 {
5896   if (loop_depth (loop) == 0)
5897     return false;
5898
5899   /* Now, the loop could be too large or irreducible.  Check whether its
5900      region is in LOOP_NESTS.
5901      We determine the region number of LOOP as the region number of its
5902      latch.  We can't use header here, because this header could be
5903      just removed preheader and it will give us the wrong region number.
5904      Latch can't be used because it could be in the inner loop too.  */
5905   if (LOOP_MARKED_FOR_PIPELINING_P (loop))
5906     {
5907       int rgn = CONTAINING_RGN (loop->latch->index);
5908
5909       gcc_assert ((unsigned) rgn < VEC_length (loop_p, loop_nests));
5910       return true;
5911     }
5912
5913   return false;
5914 }
5915
5916 /* Makes regions from the rest of the blocks, after loops are chosen
5917    for pipelining.  */
5918 static void
5919 make_regions_from_the_rest (void)
5920 {
5921   int cur_rgn_blocks;
5922   int *loop_hdr;
5923   int i;
5924
5925   basic_block bb;
5926   edge e;
5927   edge_iterator ei;
5928   int *degree;
5929
5930   /* Index in rgn_bb_table where to start allocating new regions.  */
5931   cur_rgn_blocks = nr_regions ? RGN_BLOCKS (nr_regions) : 0;
5932
5933   /* Make regions from all the rest basic blocks - those that don't belong to
5934      any loop or belong to irreducible loops.  Prepare the data structures
5935      for extend_rgns.  */
5936
5937   /* LOOP_HDR[I] == -1 if I-th bb doesn't belong to any loop,
5938      LOOP_HDR[I] == LOOP_HDR[J] iff basic blocks I and J reside within the same
5939      loop.  */
5940   loop_hdr = XNEWVEC (int, last_basic_block);
5941   degree = XCNEWVEC (int, last_basic_block);
5942
5943
5944   /* For each basic block that belongs to some loop assign the number
5945      of innermost loop it belongs to.  */
5946   for (i = 0; i < last_basic_block; i++)
5947     loop_hdr[i] = -1;
5948
5949   FOR_EACH_BB (bb)
5950     {
5951       if (bb->loop_father && !bb->loop_father->num == 0
5952           && !(bb->flags & BB_IRREDUCIBLE_LOOP))
5953         loop_hdr[bb->index] = bb->loop_father->num;
5954     }
5955
5956   /* For each basic block degree is calculated as the number of incoming
5957      edges, that are going out of bbs that are not yet scheduled.
5958      The basic blocks that are scheduled have degree value of zero.  */
5959   FOR_EACH_BB (bb)
5960     {
5961       degree[bb->index] = 0;
5962
5963       if (!TEST_BIT (bbs_in_loop_rgns, bb->index))
5964         {
5965           FOR_EACH_EDGE (e, ei, bb->preds)
5966             if (!TEST_BIT (bbs_in_loop_rgns, e->src->index))
5967               degree[bb->index]++;
5968         }
5969       else
5970         degree[bb->index] = -1;
5971     }
5972
5973   extend_rgns (degree, &cur_rgn_blocks, bbs_in_loop_rgns, loop_hdr);
5974
5975   /* Any block that did not end up in a region is placed into a region
5976      by itself.  */
5977   FOR_EACH_BB (bb)
5978     if (degree[bb->index] >= 0)
5979       {
5980         rgn_bb_table[cur_rgn_blocks] = bb->index;
5981         RGN_NR_BLOCKS (nr_regions) = 1;
5982         RGN_BLOCKS (nr_regions) = cur_rgn_blocks++;
5983         RGN_DONT_CALC_DEPS (nr_regions) = 0;
5984         RGN_HAS_REAL_EBB (nr_regions) = 0;
5985         CONTAINING_RGN (bb->index) = nr_regions++;
5986         BLOCK_TO_BB (bb->index) = 0;
5987       }
5988
5989   free (degree);
5990   free (loop_hdr);
5991 }
5992
5993 /* Free data structures used in pipelining of loops.  */
5994 void sel_finish_pipelining (void)
5995 {
5996   loop_iterator li;
5997   struct loop *loop;
5998
5999   /* Release aux fields so we don't free them later by mistake.  */
6000   FOR_EACH_LOOP (li, loop, 0)
6001     loop->aux = NULL;
6002
6003   loop_optimizer_finalize ();
6004
6005   VEC_free (loop_p, heap, loop_nests);
6006
6007   free (rev_top_order_index);
6008   rev_top_order_index = NULL;
6009 }
6010
6011 /* This function replaces the find_rgns when
6012    FLAG_SEL_SCHED_PIPELINING_OUTER_LOOPS is set.  */
6013 void
6014 sel_find_rgns (void)
6015 {
6016   sel_init_pipelining ();
6017   extend_regions ();
6018
6019   if (current_loops)
6020     {
6021       loop_p loop;
6022       loop_iterator li;
6023
6024       FOR_EACH_LOOP (li, loop, (flag_sel_sched_pipelining_outer_loops
6025                                 ? LI_FROM_INNERMOST
6026                                 : LI_ONLY_INNERMOST))
6027         make_regions_from_loop_nest (loop);
6028     }
6029
6030   /* Make regions from all the rest basic blocks and schedule them.
6031      These blocks include blocks that don't belong to any loop or belong
6032      to irreducible loops.  */
6033   make_regions_from_the_rest ();
6034
6035   /* We don't need bbs_in_loop_rgns anymore.  */
6036   sbitmap_free (bbs_in_loop_rgns);
6037   bbs_in_loop_rgns = NULL;
6038 }
6039
6040 /* Adds the preheader blocks from previous loop to current region taking
6041    it from LOOP_PREHEADER_BLOCKS (current_loop_nest).
6042    This function is only used with -fsel-sched-pipelining-outer-loops.  */
6043 void
6044 sel_add_loop_preheaders (void)
6045 {
6046   int i;
6047   basic_block bb;
6048   VEC(basic_block, heap) *preheader_blocks
6049     = LOOP_PREHEADER_BLOCKS (current_loop_nest);
6050
6051   for (i = 0;
6052        VEC_iterate (basic_block, preheader_blocks, i, bb);
6053        i++)
6054     {
6055       VEC_safe_push (basic_block, heap, last_added_blocks, bb);
6056       sel_add_bb (bb);
6057     }
6058
6059   VEC_free (basic_block, heap, preheader_blocks);
6060 }
6061
6062 /* While pipelining outer loops, returns TRUE if BB is a loop preheader.
6063    Please note that the function should also work when pipelining_p is
6064    false, because it is used when deciding whether we should or should
6065    not reschedule pipelined code.  */
6066 bool
6067 sel_is_loop_preheader_p (basic_block bb)
6068 {
6069   if (current_loop_nest)
6070     {
6071       struct loop *outer;
6072
6073       if (preheader_removed)
6074         return false;
6075
6076       /* Preheader is the first block in the region.  */
6077       if (BLOCK_TO_BB (bb->index) == 0)
6078         return true;
6079
6080       /* We used to find a preheader with the topological information.
6081          Check that the above code is equivalent to what we did before.  */
6082
6083       if (in_current_region_p (current_loop_nest->header))
6084         gcc_assert (!(BLOCK_TO_BB (bb->index)
6085                       < BLOCK_TO_BB (current_loop_nest->header->index)));
6086
6087       /* Support the situation when the latch block of outer loop
6088          could be from here.  */
6089       for (outer = loop_outer (current_loop_nest);
6090            outer;
6091            outer = loop_outer (outer))
6092         if (considered_for_pipelining_p (outer) && outer->latch == bb)
6093           gcc_unreachable ();
6094     }
6095
6096   return false;
6097 }
6098
6099 /* Checks whether JUMP leads to basic block DEST_BB and no other blocks.  */
6100 bool
6101 jump_leads_only_to_bb_p (insn_t jump, basic_block dest_bb)
6102 {
6103   basic_block jump_bb = BLOCK_FOR_INSN (jump);
6104
6105   /* It is not jump, jump with side-effects or jump can lead to several
6106      basic blocks.  */
6107   if (!onlyjump_p (jump)
6108       || !any_uncondjump_p (jump))
6109     return false;
6110
6111   /* Several outgoing edges, abnormal edge or destination of jump is
6112      not DEST_BB.  */
6113   if (EDGE_COUNT (jump_bb->succs) != 1
6114       || EDGE_SUCC (jump_bb, 0)->flags & EDGE_ABNORMAL
6115       || EDGE_SUCC (jump_bb, 0)->dest != dest_bb)
6116     return false;
6117
6118   /* If not anything of the upper.  */
6119   return true;
6120 }
6121
6122 /* Removes the loop preheader from the current region and saves it in
6123    PREHEADER_BLOCKS of the father loop, so they will be added later to
6124    region that represents an outer loop.  */
6125 static void
6126 sel_remove_loop_preheader (void)
6127 {
6128   int i, old_len;
6129   int cur_rgn = CONTAINING_RGN (BB_TO_BLOCK (0));
6130   basic_block bb;
6131   bool all_empty_p = true;
6132   VEC(basic_block, heap) *preheader_blocks
6133     = LOOP_PREHEADER_BLOCKS (loop_outer (current_loop_nest));
6134
6135   gcc_assert (current_loop_nest);
6136   old_len = VEC_length (basic_block, preheader_blocks);
6137
6138   /* Add blocks that aren't within the current loop to PREHEADER_BLOCKS.  */
6139   for (i = 0; i < RGN_NR_BLOCKS (cur_rgn); i++)
6140     {
6141       bb = BASIC_BLOCK (BB_TO_BLOCK (i));
6142
6143       /* If the basic block belongs to region, but doesn't belong to
6144          corresponding loop, then it should be a preheader.  */
6145       if (sel_is_loop_preheader_p (bb))
6146         {
6147           VEC_safe_push (basic_block, heap, preheader_blocks, bb);
6148           if (BB_END (bb) != bb_note (bb))
6149             all_empty_p = false;
6150         }
6151     }
6152
6153   /* Remove these blocks only after iterating over the whole region.  */
6154   for (i = VEC_length (basic_block, preheader_blocks) - 1;
6155        i >= old_len;
6156        i--)
6157     {
6158       bb =  VEC_index (basic_block, preheader_blocks, i);
6159       sel_remove_bb (bb, false);
6160     }
6161
6162   if (!considered_for_pipelining_p (loop_outer (current_loop_nest)))
6163     {
6164       if (!all_empty_p)
6165         /* Immediately create new region from preheader.  */
6166         make_region_from_loop_preheader (&preheader_blocks);
6167       else
6168         {
6169           /* If all preheader blocks are empty - dont create new empty region.
6170              Instead, remove them completely.  */
6171           FOR_EACH_VEC_ELT (basic_block, preheader_blocks, i, bb)
6172             {
6173               edge e;
6174               edge_iterator ei;
6175               basic_block prev_bb = bb->prev_bb, next_bb = bb->next_bb;
6176
6177               /* Redirect all incoming edges to next basic block.  */
6178               for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
6179                 {
6180                   if (! (e->flags & EDGE_FALLTHRU))
6181                     redirect_edge_and_branch (e, bb->next_bb);
6182                   else
6183                     redirect_edge_succ (e, bb->next_bb);
6184                 }
6185               gcc_assert (BB_NOTE_LIST (bb) == NULL);
6186               delete_and_free_basic_block (bb);
6187
6188               /* Check if after deleting preheader there is a nonconditional
6189                  jump in PREV_BB that leads to the next basic block NEXT_BB.
6190                  If it is so - delete this jump and clear data sets of its
6191                  basic block if it becomes empty.  */
6192               if (next_bb->prev_bb == prev_bb
6193                   && prev_bb != ENTRY_BLOCK_PTR
6194                   && jump_leads_only_to_bb_p (BB_END (prev_bb), next_bb))
6195                 {
6196                   redirect_edge_and_branch (EDGE_SUCC (prev_bb, 0), next_bb);
6197                   if (BB_END (prev_bb) == bb_note (prev_bb))
6198                     free_data_sets (prev_bb);
6199                 }
6200             }
6201         }
6202       VEC_free (basic_block, heap, preheader_blocks);
6203     }
6204   else
6205     /* Store preheader within the father's loop structure.  */
6206     SET_LOOP_PREHEADER_BLOCKS (loop_outer (current_loop_nest),
6207                                preheader_blocks);
6208 }
6209 #endif