2008-08-31 Andrey Belevantsev <abel@ispras.ru>
authorabel <abel@138bc75d-0d04-0410-961f-82ee72b054a4>
Mon, 1 Sep 2008 08:57:00 +0000 (08:57 +0000)
committerabel <abel@138bc75d-0d04-0410-961f-82ee72b054a4>
Mon, 1 Sep 2008 08:57:00 +0000 (08:57 +0000)
        Dmitry Melnik  <dm@ispras.ru>
        Dmitry Zhurikhin  <zhur@ispras.ru>
        Alexander Monakov  <amonakov@ispras.ru>
        Maxim Kuvyrkov  <maxim@codesourcery.com>

* sel-sched.h, sel-sched-dump.h, sel-sched-ir.h, sel-sched.c,
sel-sched-dump.c, sel-sched-ir.c: New files.
* Makefile.in (OBJS-common): Add selective scheduling object
files.
(sel-sched.o, sel-sched-dump.o, sel-sched-ir.o): New entries.
(SEL_SCHED_IR_H, SEL_SCHED_DUMP_H): New entries.
(sched-vis.o): Add dependency on $(INSN_ATTR_H).
* cfghooks.h (get_cfg_hooks, set_cfg_hooks): New prototypes.
* cfghooks.c (get_cfg_hooks, set_cfg_hooks): New functions.
(make_forwarder_block): Update loop latch if we have redirected
the loop latch edge.
* cfgloop.c (get_loop_body_in_custom_order): New function.
* cfgloop.h (LOOPS_HAVE_FALLTHRU_PREHEADERS): New enum field.
(CP_FALLTHRU_PREHEADERS): Likewise.
(get_loop_body_in_custom_order): Declare.
* cfgloopmanip.c (has_preds_from_loop): New.
(create_preheader): Honor CP_FALLTHRU_PREHEADERS.
Assert that the preheader edge will be fall thru when it is set.
* common.opt (fsel-sched-bookkeeping, fsel-sched-pipelining,
fsel-sched-pipelining-outer-loops, fsel-sched-renaming,
fsel-sched-substitution, fselective-scheduling): New flags.
     * cse.c (hash_rtx_cb): New.
(hash_rtx): Use it.
* dbgcnt.def (sel_sched_cnt, sel_sched_region_cnt,
sel_sched_insn_cnt): New counters.
* final.c (compute_alignments): Export.  Free dominance info after loop_optimizer_finalize.
* genattr.c (main): Output maximal_insn_latency prototype.
* genautomata.c (output_default_latencies): New. Factor its code from ...
(output_internal_insn_latency_func): ... here.
(output_internal_maximal_insn_latency_func): New.
(output_maximal_insn_latency_func): New.
* hard-reg-set.h (UHOST_BITS_PER_WIDE_INT): Define unconditionally.
(struct hard_reg_set_iterator): New.
(hard_reg_set_iter_init, hard_reg_set_iter_set,
hard_reg_set_iter_next): New functions.
(EXECUTE_IF_SET_IN_HARD_REG_SET): New macro.
* lists.c (remove_free_INSN_LIST_node,
remove_free_EXPR_LIST_node): New functions.
* loop-init.c (loop_optimizer_init): When LOOPS_HAVE_FALLTHRU_PREHEADERS,
set CP_FALLTHRU_PREHEADERS when calling create_preheaders.
(loop_optimizer_finalize): Do not verify flow info after reload.
* recog.c (validate_replace_rtx_1): New parameter simplify.
Default it to true.  Update all uses.  Factor out simplifying
code to ...
(simplify_while_replacing): ... this new function.
(validate_replace_rtx_part,
validate_replace_rtx_part_nosimplify): New.
* recog.h (validate_replace_rtx_part,
validate_replace_rtx_part_nosimplify): Declare.
* rtl.c (rtx_equal_p_cb): New.
(rtx_equal_p): Use it.
* rtl.h (rtx_equal_p_cb, hash_rtx_cb): Declare.
(remove_free_INSN_LIST_NODE, remove_free_EXPR_LIST_node,
debug_bb_n_slim, debug_bb_slim,    print_rtl_slim): Likewise.
* vecprim.h: Add a vector type for unsigned int.
* haifa-sched.c: Include vecprim.h and cfgloop.h.
(issue_rate, sched_verbose_param, note_list, dfa_state_size,
ready_try, cycle_issued_insns, spec_info): Make global.
(readyp): Initialize.
(dfa_lookahead): New global variable.
(old_max_uid, old_last_basic_block): Remove.
(h_i_d): Make it a vector.
(INSN_TICK, INTER_TICK, QUEUE_INDEX, INSN_COST): Make them work
through HID macro.
(after_recovery, adding_bb_to_current_region_p):
New variables to handle correct insertion of the recovery code.
(struct ready_list): Move declaration to sched-int.h.
(rgn_n_insns): Removed.
(rtx_vec_t): Move to sched-int.h.
(find_insn_reg_weight): Remove.
(find_insn_reg_weight1): Rename to find_insn_reg_weight.
(haifa_init_h_i_d, haifa_finish_h_i_d):
New functions to initialize / finalize haifa instruction data.
(extend_h_i_d, init_h_i_d): Rewrite.
(unlink_other_notes): Move logic to add_to_note_list.  Handle
selective scheduler.
(ready_lastpos, ready_element, ready_sort, reemit_notes,
find_fallthru_edge): Make global, remove static prototypes.
(max_issue): Make global.  Add privileged_n and state parameters.  Use
them.
(extend_global, extend_all): Removed.
(init_before_recovery): Add new param.  Fix the handling of the case
when we insert a recovery code before the EXIT which has a predecessor
with a fallthrough edge to it.
(create_recovery_block): Make global.  Rename to
sched_create_recovery_block.  Update.
(change_pattern): Rename to sched_change_pattern.  Make global.
(speculate_insn): Rename to sched_speculate_insn.  Make global.
Split haifa-specific functionality into ...
(haifa_change_pattern): New static function.
(sched_extend_bb): New static function.
(sched_init_bbs): New function.
(current_sched_info): Change type to struct haifa_sched_info.
(insn_cost): Adjust for selective scheduling.
(dep_cost_1): New function.  Move logic from ...
(dep_cost): ... here.
(dep_cost): Use dep_cost_1.
(contributes_to_priority_p): Use sched_deps_info instead of
current_sched_info.
(priority): Adjust to work with selective scheduling.  Process the
corner case when all dependencies don't contribute to priority.
(rank_for_schedule): Use ds_weak instead of dep_weak.
(advance_state): New function.  Move logic from ...
(advance_one_cycle): ... here.
(add_to_note_list, concat_note_lists): New functions.
(rm_other_notes): Make static.  Adjust for selective scheduling.
(remove_notes, restore_other_notes): New functions.
(move_insn): Add two arguments.  Update assert.  Don't call
reemit_notes.
(choose_ready): Remove lookahead variable, use dfa_lookahead.
Remove more_issue, max_points.  Move the code to initialize
max_lookahead_tries to max_issue.
(schedule_block): Remove rgn_n_insns1 parameter.  Don't allocate
ready.  Adjust use of move_insn.  Call restore_other_notes.
(luid): Remove.
(sched_init, sched_finish): Move Haifa-specific initialization/
finalization to ...
(haifa_sched_init, haifa_sched_finish): ... respectively.
New functions.
(setup_sched_dump): New function.
(haifa_init_only_bb): New static function.
(haifa_speculate_insn): New static function.
(try_ready): Use haifa_* instead of speculate_insn and
change_pattern.
(extend_ready, extend_all): Remove.
(sched_extend_ready_list, sched_finish_ready_list): New functions.
(create_check_block_twin, add_to_speculative_block): Use
haifa_insns_init instead of extend_global.  Update to use new
initialization functions.  Change parameter.  Factor out code from
create_check_block_twin to ...
(sched_create_recovery_edges) ... this new function.
(add_block): Remove.
(sched_scan_info): New.
(extend_bb): Use sched_scan_info.
(init_bb, extend_insn, init_insn, init_insns_in_bb, sched_scan): New
static functions for walking through scheduling region.
(sched_luids): New vector variable to replace uid_to_luid.
(luids_extend_insn): New function.
(sched_max_luid): New variable.
(luids_init_insn): New function.
(sched_init_luids, sched_finish_luids): New functions.
(insn_luid): New debug function.
(sched_extend_target): New function.
(haifa_init_insn): New static function.
(sched_init_only_bb): New hook.
(sched_split_block): New hook.
(sched_split_block_1): New function.
(sched_create_empty_bb): New hook.
(sched_create_empty_bb_1): New function.
(common_sched_info, ready): New global variables.
(current_sched_info_var): Remove.
(move_block_after_check): Use common_sched_info.
(haifa_luid_for_non_insn): New static function.
(init_before_recovery): Use haifa_init_only_bb instead of
add_block.
(increase_insn_priority): New.
* modulo-sched.c: (issue_rate): Remove static declaration.
(sms_sched_info): Change type to haifa_sched_info.
(sms_sched_deps_info, sms_common_sched_info): New variables.
(setup_sched_infos): New.
(sms_schedule): Initialize them.  Call haifa_sched_init/finish.
Do not call regstat_free_calls_crossed.
(sms_print_insn): Use const_rtx.
* params.def (PARAM_MAX_PIPELINE_REGION_BLOCKS,
PARAM_MAX_PIPELINE_REGION_INSNS, PARAM_SELSCHED_MAX_LOOKAHEAD,
PARAM_SELSCHED_MAX_SCHED_TIMES, PARAM_SELSCHED_INSNS_TO_RENAME,
PARAM_SCHED_MEM_TRUE_DEP_COST): New.
* sched-deps.c (sched_deps_info): New.  Update all relevant uses of
current_sched_info to use it.
(enum reg_pending_barrier_mode): Move to sched-int.h.
(h_d_i_d): New variable. Initialize to NULL.
({true, output, anti, spec, forward}_dependency_cache): Initialize
to NULL.
(estimate_dep_weak): Remove static declaration.
(sched_has_condition_p): New function.  Adjust users of
sched_get_condition to use it instead.
(conditions_mutex_p): Add arguments indicating which conditions are
reversed.  Use them.
(sched_get_condition_with_rev): Rename from sched_get_condition.  Add
argument to indicate whether returned condition is reversed.  Do not
generate new rtx when condition should be reversed; indicate it by
setting new argument instead.
(add_dependence_list_and_free): Add deps parameter.
Update all users.  Do not free dependence list when
deps context is readonly.
(add_insn_mem_dependence, flush_pending_lists): Adjust for readonly
contexts.
(remove_from_dependence_list, remove_from_both_dependence_lists): New.
(remove_from_deps): New. Use the above functions.
(cur_insn, can_start_lhs_rhs_p): New static variables.
(add_or_update_back_dep_1): Initialize present_dep_type.
(haifa_start_insn, haifa_finish_insn, haifa_note_reg_set,
haifa_note_reg_clobber, haifa_note_reg_use, haifa_note_mem_dep,
haifa_note_dep): New functions implementing dependence hooks for
the Haifa scheduler.
(note_reg_use, note_reg_set, note_reg_clobber, note_mem_dep,
note_dep): New functions.
(ds_to_dt, extend_deps_reg_info, maybe_extend_reg_info_p): New
functions.
(init_deps): Initialize last_reg_pending_barrier and deps->readonly.
(free_deps): Initialize deps->reg_last.
(sched_analyze_reg, sched_analyze_1, sched_analyze_2,
sched_analyze_insn): Update to use dependency hooks infrastructure
and readonly contexts.
(deps_analyze_insn): New function.  Move part of logic from ...
(sched_analyze): ... here.  Also move some logic to ...
(deps_start_bb): ... here.  New function.
(add_forw_dep, delete_forw_dep): Guard use of INSN_DEP_COUNT with
sel_sched_p.
(sched_deps_init): New function.  Move code from ...
(init_dependency_caches): ... here.  Remove.
(init_deps_data_vector): New.
(sched_deps_finish): New function.  Move code from ...
(free_dependency_caches): ... here.  Remove.
(init_deps_global, finish_deps_global): Adjust for use with
selective scheduling.
(get_dep_weak): Move logic to ...
(get_dep_weak_1): New function.
(ds_merge): Move logic to ...
(ds_merge_1): New static function.
(ds_full_merge, ds_max_merge, ds_get_speculation_types): New functions.
(ds_get_max_dep_weak): New function.
* sched-ebb.c (sched_n_insns): Rename to sched_rgn_n_insns.
(n_insns): Rename to rgn_n_insns.
(debug_ebb_dependencies): New function.
(init_ready_list): Use it.
(begin_schedule_ready): Use sched_init_only_bb.
(ebb_print_insn): Indicate when an insn starts a new cycle.
(contributes_to_priority, compute_jump_reg_dependencies,
add_remove_insn, fix_recovery_cfg): Add ebb_ prefix to function names.
(add_block1): Remove to ebb_add_block.
(ebb_sched_deps_info, ebb_common_sched_info): New variables.
(schedule_ebb): Initialize them.  Use remove_notes instead of
rm_other_notes.  Use haifa_local_init/finish.
(schedule_ebbs): Use haifa_sched_init/finish.
* sched-int.h: Include vecprim.h, remove rtl.h.
(struct ready_list): Delete declaration.
(sched_verbose_param, enum sched_pass_id_t,
bb_vec_t, insn_vec_t, rtx_vec_t): New.
(struct sched_scan_info_def): New structure.
(sched_scan_info, sched_scan, sched_init_bbs,
sched_init_luids, sched_finish_luids, sched_extend_target,
haifa_init_h_i_d, haifa_finish_h_i_d): Declare.
(struct common_sched_info_def): New.
(common_sched_info, haifa_common_sched_info,
sched_emulate_haifa_p): Declare.
(sel_sched_p): New.
(sched_luids): Declare.
(INSN_LUID, LUID_BY_UID, SET_INSN_LUID): Declare.
(sched_max_luid, insn_luid): Declare.
(note_list, remove_notes, restore_other_notes, bb_note): Declare.
(sched_insns_init, sched_insns_finish, xrecalloc, reemit_notes,
print_insn, print_pattern, print_value, haifa_classify_insn,
sel_find_rgns, sel_mark_hard_insn, dfa_state_size, advance_state,
setup_sched_dump, sched_init, sched_finish,
sel_insn_is_speculation_check): Export.
(struct ready_list): Move from haifa-sched.c.
(ready_try, ready, max_issue): Export.
(ebb_compute_jump_reg_dependencies, find_fallthru_edge,
sched_init_only_bb, sched_split_block, sched_split_block_1,
sched_create_empty_bb, sched_create_empty_bb_1,
sched_create_recovery_block, sched_create_recovery_edges): Export.
(enum reg_pending_barrier_mode): Export.
(struct deps): New fields `last_reg_pending_barrier' and `readonly'.
(deps_t): New.
(struct sched_info): Rename to haifa_sched_info.  Use const_rtx for
print_insn field.  Move add_block and fix_recovery_cfg to
common_sched_info_def.  Move compute_jump_reg_dependencies, use_cselib  ...
(struct sched_deps_info_def): ... this new structure.
(sched_deps_info): Declare.
(struct spec_info_def): Remove weakness_cutoff, add
data_weakness_cutoff and control_weakness_cutoff.
(spec_info): Declare.
(struct _haifa_deps_insn_data): Split from haifa_insn_data.  Add
dep_count field.
(struct haifa_insn_data): Rename to struct _haifa_insn_data.
(haifa_insn_data_def, haifa_insn_data_t): New typedefs.
(current_sched_info): Change type to struct haifa_sched_info.
(haifa_deps_insn_data_def, haifa_deps_insn_data_t): New typedefs.
(h_d_i_d): New variable.
(HDID): New accessor macro.
(h_i_d): Change type to VEC (haifa_insn_data_def, heap) *.
(HID): New accessor macro.  Rewrite h_i_d accessor macros through HID
and HDID.
(IS_SPECULATION_CHECK_P): Update for selective scheduler.
(enum SCHED_FLAGS): Update for selective scheduler.
(enum SPEC_SCHED_FLAGS): New flag SEL_SCHED_SPEC_DONT_CHECK_CONTROL.
(init_dependency_caches, free_dependency_caches): Delete declarations.
(deps_analyze_insn, remove_from_deps, get_dep_weak_1,
estimate_dep_weak, ds_full_merge, ds_max_merge, ds_weak,
ds_get_speculation_types, ds_get_max_dep_weak, sched_deps_init,
sched_deps_finish, haifa_note_reg_set, haifa_note_reg_use,
haifa_note_reg_clobber, maybe_extend_reg_info_p, deps_start_bb,
ds_to_dt): Export.
(rm_other_notes): Delete declaration.
(schedule_block): Remove one argument.
(cycle_issued_insns, issue_rate, dfa_lookahead, ready_sort,
ready_element, ready_lastpos, sched_extend_ready_list,
sched_finish_ready_list, sched_change_pattern, sched_speculate_insn,
concat_note_lists): Export.
(struct region): Move from sched-rgn.h.
(nr_regions, rgn_table, rgn_bb_table, block_to_bb, containing_rgn,
RGN_NR_BLOCKS, RGN_BLOCKS, RGN_DONT_CALC_DEPS, RGN_HAS_REAL_EBB,
BLOCK_TO_BB, CONTAINING_RGN): Export.
(ebb_head, BB_TO_BLOCK, EBB_FIRST_BB, EBB_LAST_BB, INSN_BB): Likewise.
(current_nr_blocks, current_blocks, target_bb): Likewise.
(dep_cost_1, sched_is_disabled_for_current_region_p, sched_rgn_init,
sched_rgn_finish, rgn_setup_region, sched_rgn_compute_dependencies,
sched_rgn_local_init, extend_regions,
rgn_make_new_region_out_of_new_block, compute_priorities,
debug_rgn_dependencies, free_rgn_deps, contributes_to_priority,
extend_rgns, deps_join rgn_setup_common_sched_info,
rgn_setup_sched_infos, debug_regions, debug_region, dump_region_dot,
dump_region_dot_file, haifa_sched_init, haifa_sched_finish): Export.
(get_rgn_sched_max_insns_priority, sel_add_to_insn_priority,
increase_insn_priority): Likewise.
* sched-rgn.c: Include sel-sched.h.
(ref_counts): New static variable.  Use it ...
(INSN_REF_COUNT): ... here.  Rewrite and move closer to uses.
(FED_BY_SPEC_LOAD, IS_LOAD_INSN): Rewrite to use HID accessor macro.
(sched_is_disabled_for_current_region_p): Delete static declaration.
(struct region): Move to sched-int.h.
(nr_regions, rgn_table, rgn_bb_table, block_to_bb, containing_rgn,
ebb_head): Define and initialize.
(RGN_NR_BLOCKS, RGN_BLOCKS, RGN_DONT_CALC_DEPS, RGN_HAS_REAL_EBB,
BLOCK_TO_BB, CONTAINING_RGN, debug_regions, extend_regions,
BB_TO_BLOCK, EBB_FIRST_BB, EBB_LAST_BB): Move to
sched-int.h.
(find_single_block_region): Add new argument to indicate that EBB
regions should be constructed.
(debug_live): Delete declaration.
(current_nr_blocks, current_blocks, target_bb): Remove static qualifiers.
(compute_dom_prob_ps, check_live, update_live, set_spec_fed): Delete
declaration.
(init_regions): Delete declaration.
(debug_region, bb_in_region_p, dump_region_dot_file, dump_region_dot,
rgn_estimate_number_of_insns): New.
(too_large): Use estimate_number_of_insns.
(haifa_find_rgns): New. Move the code from ...
(find_rgns): ... here.  Call either sel_find_rgns or haifa_find_rgns.
(free_trg_info): New.
(compute_trg_info): Allocate candidate tables here instead of ...
(init_ready_list): ... here.
(rgn_print_insn): Use const_rtx.
(contributes_to_priority, extend_regions): Delete static declaration.
(add_remove_insn, fix_recovery_cfg): Add rgn_ to function names.
(add_block1): Rename to rgn_add_block.
(debug_rgn_dependencies): Delete static qualifier.
(new_ready): Use sched_deps_info.  Simplify.
(rgn_common_sched_info, rgn_const_sched_deps_info,
rgn_const_sel_sched_deps_info, rgn_sched_deps_info, rgn_sched_info): New.
(region_sched_info): Rename to rgn_const_sched_info.
(deps_join): New, extracted from ...
(propagate_deps): ... here.
(compute_block_dependences, debug_dependencies): Update for selective
scheduling.
(free_rgn_deps, compute_priorities): New functions.
(sched_rgn_init, sched_rgn_finish, rgn_setup_region,
sched_rgn_compute_dependencies): New functions.
(schedule_region): Use them.
(sched_rgn_local_init, sched_rgn_local_free, sched_rgn_local_finish,
rgn_setup_common_sched_info, rgn_setup_sched_infos):
New functions.
(schedule_insns): Call new functions that were split out.
(rgn_make_new_region_out_of_new_block): New.
(get_rgn_sched_max_insns_priority): New.
(rest_of_handle_sched, rest_of_handle_sched2): Call selective
scheduling when appropriate.
* sched-vis.c: Include insn-attr.h.
(print_value, print_pattern): Make global.
(print_rtl_slim, debug_bb_slim, debug_bb_n_slim): New functions.
* target-def.h (TARGET_SCHED_ADJUST_COST_2,
TARGET_SCHED_ALLOC_SCHED_CONTEXT, TARGET_SCHED_INIT_SCHED_CONTEXT,
TARGET_SCHED_SET_SCHED_CONTEXT, TARGET_SCHED_CLEAR_SCHED_CONTEXT,
TARGET_SCHED_FREE_SCHED_CONTEXT, TARGET_SCHED_GET_INSN_CHECKED_DS,
TARGET_SCHED_GET_INSN_SPEC_DS, TARGET_SCHED_SKIP_RTX_P): New target
hooks.  Initialize them to 0.
(TARGET_SCHED_GEN_CHECK): Rename to TARGET_SCHED_GEN_SPEC_CHECK.
* target.h (struct gcc_target): Add them.  Rename gen_check field to
gen_spec_check.
* flags.h (sel_sched_switch_set): Declare.
* opts.c (sel_sched_switch_set): New variable.
(decode_options): Unset flag_sel_sched_pipelining_outer_loops if
pipelining is disabled from command line.
(common_handle_option): Record whether selective scheduling is
requested from command line.
* doc/invoke.texi: Document new flags and parameters.
* doc/tm.texi: Document new target hooks.
* config/ia64/ia64.c (TARGET_SCHED_GEN_SPEC_CHECK): Define to ia64_gen_check.
(dfa_state_size): Do not declare locally.
* config/ia64/ia64.opt (msched-ar-data-spec): Default to 0.
* config/rs6000/rs6000.c (rs6000_init_sched_context,
rs6000_alloc_sched_context, rs6000_set_sched_context,
rs6000_free_sched_context): New functions.
(struct _rs6000_sched_context): New.
(rs6000_sched_reorder2): Do not modify INSN_PRIORITY for selective
scheduling.
(rs6000_sched_finish): Do not run for selective scheduling.

git-svn-id: svn+ssh://gcc.gnu.org/svn/gcc/trunk@139854 138bc75d-0d04-0410-961f-82ee72b054a4

46 files changed:
gcc/ChangeLog
gcc/Makefile.in
gcc/cfghooks.c
gcc/cfghooks.h
gcc/cfgloop.c
gcc/cfgloop.h
gcc/cfgloopmanip.c
gcc/common.opt
gcc/config/ia64/ia64.c
gcc/config/ia64/ia64.opt
gcc/config/rs6000/rs6000.c
gcc/cse.c
gcc/dbgcnt.def
gcc/doc/invoke.texi
gcc/doc/tm.texi
gcc/emit-rtl.c
gcc/final.c
gcc/flags.h
gcc/genattr.c
gcc/genautomata.c
gcc/haifa-sched.c
gcc/hard-reg-set.h
gcc/lists.c
gcc/loop-init.c
gcc/modulo-sched.c
gcc/opts.c
gcc/params.def
gcc/recog.c
gcc/recog.h
gcc/rtl.c
gcc/rtl.h
gcc/rtlhooks-def.h
gcc/sched-deps.c
gcc/sched-ebb.c
gcc/sched-int.h
gcc/sched-rgn.c
gcc/sched-vis.c
gcc/sel-sched-dump.c [new file with mode: 0644]
gcc/sel-sched-dump.h [new file with mode: 0644]
gcc/sel-sched-ir.c [new file with mode: 0644]
gcc/sel-sched-ir.h [new file with mode: 0644]
gcc/sel-sched.c [new file with mode: 0644]
gcc/sel-sched.h [new file with mode: 0644]
gcc/target-def.h
gcc/target.h
gcc/vecprim.h

index 2fc2fe7..768b296 100644 (file)
@@ -1,3 +1,408 @@
+2008-08-31  Andrey Belevantsev  <abel@ispras.ru>
+        Dmitry Melnik  <dm@ispras.ru>
+        Dmitry Zhurikhin  <zhur@ispras.ru>
+        Alexander Monakov  <amonakov@ispras.ru>
+        Maxim Kuvyrkov  <maxim@codesourcery.com>
+
+       * sel-sched.h, sel-sched-dump.h, sel-sched-ir.h, sel-sched.c,
+       sel-sched-dump.c, sel-sched-ir.c: New files.
+       * Makefile.in (OBJS-common): Add selective scheduling object
+       files.
+       (sel-sched.o, sel-sched-dump.o, sel-sched-ir.o): New entries.
+       (SEL_SCHED_IR_H, SEL_SCHED_DUMP_H): New entries.
+       (sched-vis.o): Add dependency on $(INSN_ATTR_H).
+       * cfghooks.h (get_cfg_hooks, set_cfg_hooks): New prototypes.
+       * cfghooks.c (get_cfg_hooks, set_cfg_hooks): New functions.
+       (make_forwarder_block): Update loop latch if we have redirected
+       the loop latch edge.
+       * cfgloop.c (get_loop_body_in_custom_order): New function.
+       * cfgloop.h (LOOPS_HAVE_FALLTHRU_PREHEADERS): New enum field.
+       (CP_FALLTHRU_PREHEADERS): Likewise.
+       (get_loop_body_in_custom_order): Declare.
+       * cfgloopmanip.c (has_preds_from_loop): New.
+       (create_preheader): Honor CP_FALLTHRU_PREHEADERS.
+       Assert that the preheader edge will be fall thru when it is set.
+       * common.opt (fsel-sched-bookkeeping, fsel-sched-pipelining,
+       fsel-sched-pipelining-outer-loops, fsel-sched-renaming,
+       fsel-sched-substitution, fselective-scheduling): New flags.
+       * cse.c (hash_rtx_cb): New.
+       (hash_rtx): Use it.
+       * dbgcnt.def (sel_sched_cnt, sel_sched_region_cnt,
+       sel_sched_insn_cnt): New counters. 
+       * final.c (compute_alignments): Export.  Free dominance info after loop_optimizer_finalize.
+       * genattr.c (main): Output maximal_insn_latency prototype.
+       * genautomata.c (output_default_latencies): New. Factor its code from ...
+       (output_internal_insn_latency_func): ... here.
+       (output_internal_maximal_insn_latency_func): New.
+       (output_maximal_insn_latency_func): New.
+       * hard-reg-set.h (UHOST_BITS_PER_WIDE_INT): Define unconditionally.
+       (struct hard_reg_set_iterator): New.
+       (hard_reg_set_iter_init, hard_reg_set_iter_set,
+       hard_reg_set_iter_next): New functions.
+       (EXECUTE_IF_SET_IN_HARD_REG_SET): New macro.
+       * lists.c (remove_free_INSN_LIST_node,
+       remove_free_EXPR_LIST_node): New functions.
+       * loop-init.c (loop_optimizer_init): When LOOPS_HAVE_FALLTHRU_PREHEADERS,
+       set CP_FALLTHRU_PREHEADERS when calling create_preheaders.
+       (loop_optimizer_finalize): Do not verify flow info after reload.
+       * recog.c (validate_replace_rtx_1): New parameter simplify.
+       Default it to true.  Update all uses.  Factor out simplifying
+       code to ...
+       (simplify_while_replacing): ... this new function.
+       (validate_replace_rtx_part,
+       validate_replace_rtx_part_nosimplify): New.
+       * recog.h (validate_replace_rtx_part,
+       validate_replace_rtx_part_nosimplify): Declare.
+       * rtl.c (rtx_equal_p_cb): New.
+       (rtx_equal_p): Use it.
+       * rtl.h (rtx_equal_p_cb, hash_rtx_cb): Declare.
+       (remove_free_INSN_LIST_NODE, remove_free_EXPR_LIST_node,
+       debug_bb_n_slim, debug_bb_slim,    print_rtl_slim): Likewise.
+       * vecprim.h: Add a vector type for unsigned int. 
+       * haifa-sched.c: Include vecprim.h and cfgloop.h.
+       (issue_rate, sched_verbose_param, note_list, dfa_state_size,
+       ready_try, cycle_issued_insns, spec_info): Make global.
+       (readyp): Initialize.
+       (dfa_lookahead): New global variable.
+       (old_max_uid, old_last_basic_block): Remove.
+       (h_i_d): Make it a vector.
+       (INSN_TICK, INTER_TICK, QUEUE_INDEX, INSN_COST): Make them work
+       through HID macro.
+       (after_recovery, adding_bb_to_current_region_p):
+       New variables to handle correct insertion of the recovery code.
+       (struct ready_list): Move declaration to sched-int.h.
+       (rgn_n_insns): Removed.
+       (rtx_vec_t): Move to sched-int.h.
+       (find_insn_reg_weight): Remove.
+       (find_insn_reg_weight1): Rename to find_insn_reg_weight.
+       (haifa_init_h_i_d, haifa_finish_h_i_d):
+       New functions to initialize / finalize haifa instruction data.
+       (extend_h_i_d, init_h_i_d): Rewrite.
+       (unlink_other_notes): Move logic to add_to_note_list.  Handle
+       selective scheduler.
+       (ready_lastpos, ready_element, ready_sort, reemit_notes,
+       find_fallthru_edge): Make global, remove static prototypes.
+       (max_issue): Make global.  Add privileged_n and state parameters.  Use
+       them.  
+       (extend_global, extend_all): Removed.
+       (init_before_recovery): Add new param.  Fix the handling of the case
+       when we insert a recovery code before the EXIT which has a predecessor
+       with a fallthrough edge to it.
+       (create_recovery_block): Make global.  Rename to
+       sched_create_recovery_block.  Update.
+       (change_pattern): Rename to sched_change_pattern.  Make global.
+       (speculate_insn): Rename to sched_speculate_insn.  Make global.
+       Split haifa-specific functionality into ...
+       (haifa_change_pattern): New static function.
+       (sched_extend_bb): New static function.
+       (sched_init_bbs): New function.
+       (current_sched_info): Change type to struct haifa_sched_info.
+       (insn_cost): Adjust for selective scheduling.
+       (dep_cost_1): New function.  Move logic from ...
+       (dep_cost): ... here.
+       (dep_cost): Use dep_cost_1.
+       (contributes_to_priority_p): Use sched_deps_info instead of
+       current_sched_info.
+       (priority): Adjust to work with selective scheduling.  Process the
+       corner case when all dependencies don't contribute to priority.
+       (rank_for_schedule): Use ds_weak instead of dep_weak.
+       (advance_state): New function.  Move logic from ...
+       (advance_one_cycle): ... here.
+       (add_to_note_list, concat_note_lists): New functions.
+       (rm_other_notes): Make static.  Adjust for selective scheduling.
+       (remove_notes, restore_other_notes): New functions.
+       (move_insn): Add two arguments.  Update assert.  Don't call
+       reemit_notes.
+       (choose_ready): Remove lookahead variable, use dfa_lookahead.
+       Remove more_issue, max_points.  Move the code to initialize
+       max_lookahead_tries to max_issue.
+       (schedule_block): Remove rgn_n_insns1 parameter.  Don't allocate
+       ready.  Adjust use of move_insn.  Call restore_other_notes.
+       (luid): Remove.
+       (sched_init, sched_finish): Move Haifa-specific initialization/
+       finalization to ...
+       (haifa_sched_init, haifa_sched_finish): ... respectively.
+       New functions.
+       (setup_sched_dump): New function.
+       (haifa_init_only_bb): New static function.
+       (haifa_speculate_insn): New static function.
+       (try_ready): Use haifa_* instead of speculate_insn and
+       change_pattern.
+       (extend_ready, extend_all): Remove.
+       (sched_extend_ready_list, sched_finish_ready_list): New functions.
+       (create_check_block_twin, add_to_speculative_block): Use
+       haifa_insns_init instead of extend_global.  Update to use new
+       initialization functions.  Change parameter.  Factor out code from
+       create_check_block_twin to ...
+       (sched_create_recovery_edges) ... this new function.
+       (add_block): Remove.
+       (sched_scan_info): New.
+       (extend_bb): Use sched_scan_info.
+       (init_bb, extend_insn, init_insn, init_insns_in_bb, sched_scan): New
+       static functions for walking through scheduling region.
+       (sched_luids): New vector variable to replace uid_to_luid.
+       (luids_extend_insn): New function.
+       (sched_max_luid): New variable.
+       (luids_init_insn): New function.
+       (sched_init_luids, sched_finish_luids): New functions.
+       (insn_luid): New debug function.
+       (sched_extend_target): New function.
+       (haifa_init_insn): New static function.
+       (sched_init_only_bb): New hook.
+       (sched_split_block): New hook.
+       (sched_split_block_1): New function.
+       (sched_create_empty_bb): New hook.
+       (sched_create_empty_bb_1): New function.        
+       (common_sched_info, ready): New global variables.
+       (current_sched_info_var): Remove.
+       (move_block_after_check): Use common_sched_info.                
+       (haifa_luid_for_non_insn): New static function. 
+       (init_before_recovery): Use haifa_init_only_bb instead of
+       add_block.
+       (increase_insn_priority): New.
+       * modulo-sched.c: (issue_rate): Remove static declaration.
+       (sms_sched_info): Change type to haifa_sched_info.
+       (sms_sched_deps_info, sms_common_sched_info): New variables.
+       (setup_sched_infos): New.
+       (sms_schedule): Initialize them.  Call haifa_sched_init/finish.
+       Do not call regstat_free_calls_crossed.
+       (sms_print_insn): Use const_rtx.
+       * params.def (PARAM_MAX_PIPELINE_REGION_BLOCKS,
+       PARAM_MAX_PIPELINE_REGION_INSNS, PARAM_SELSCHED_MAX_LOOKAHEAD,
+       PARAM_SELSCHED_MAX_SCHED_TIMES, PARAM_SELSCHED_INSNS_TO_RENAME,
+       PARAM_SCHED_MEM_TRUE_DEP_COST): New.
+       * sched-deps.c (sched_deps_info): New.  Update all relevant uses of
+       current_sched_info to use it.
+       (enum reg_pending_barrier_mode): Move to sched-int.h.
+       (h_d_i_d): New variable. Initialize to NULL.
+       ({true, output, anti, spec, forward}_dependency_cache): Initialize
+       to NULL.
+       (estimate_dep_weak): Remove static declaration.
+       (sched_has_condition_p): New function.  Adjust users of
+       sched_get_condition to use it instead.
+       (conditions_mutex_p): Add arguments indicating which conditions are
+       reversed.  Use them.
+       (sched_get_condition_with_rev): Rename from sched_get_condition.  Add
+       argument to indicate whether returned condition is reversed.  Do not
+       generate new rtx when condition should be reversed; indicate it by
+       setting new argument instead.
+       (add_dependence_list_and_free): Add deps parameter.
+       Update all users.  Do not free dependence list when
+       deps context is readonly.
+       (add_insn_mem_dependence, flush_pending_lists): Adjust for readonly
+       contexts.
+       (remove_from_dependence_list, remove_from_both_dependence_lists): New.
+       (remove_from_deps): New. Use the above functions.       
+       (cur_insn, can_start_lhs_rhs_p): New static variables.
+       (add_or_update_back_dep_1): Initialize present_dep_type.
+       (haifa_start_insn, haifa_finish_insn, haifa_note_reg_set,
+       haifa_note_reg_clobber, haifa_note_reg_use, haifa_note_mem_dep,
+       haifa_note_dep): New functions implementing dependence hooks for
+       the Haifa scheduler.
+       (note_reg_use, note_reg_set, note_reg_clobber, note_mem_dep,
+       note_dep): New functions.
+       (ds_to_dt, extend_deps_reg_info, maybe_extend_reg_info_p): New
+       functions.
+       (init_deps): Initialize last_reg_pending_barrier and deps->readonly.
+       (free_deps): Initialize deps->reg_last.
+       (sched_analyze_reg, sched_analyze_1, sched_analyze_2,
+       sched_analyze_insn): Update to use dependency hooks infrastructure
+       and readonly contexts.
+       (deps_analyze_insn): New function.  Move part of logic from ...
+       (sched_analyze): ... here.  Also move some logic to ...
+       (deps_start_bb): ... here.  New function.
+       (add_forw_dep, delete_forw_dep): Guard use of INSN_DEP_COUNT with
+       sel_sched_p.
+       (sched_deps_init): New function.  Move code from ...
+       (init_dependency_caches): ... here.  Remove.
+       (init_deps_data_vector): New.
+       (sched_deps_finish): New function.  Move code from ...
+       (free_dependency_caches): ... here.  Remove.
+       (init_deps_global, finish_deps_global): Adjust for use with
+       selective scheduling.
+       (get_dep_weak): Move logic to ...
+       (get_dep_weak_1): New function.
+       (ds_merge): Move logic to ...
+       (ds_merge_1): New static function.
+       (ds_full_merge, ds_max_merge, ds_get_speculation_types): New functions.
+       (ds_get_max_dep_weak): New function.
+       * sched-ebb.c (sched_n_insns): Rename to sched_rgn_n_insns.
+       (n_insns): Rename to rgn_n_insns.
+       (debug_ebb_dependencies): New function.
+       (init_ready_list): Use it.
+       (begin_schedule_ready): Use sched_init_only_bb.
+       (ebb_print_insn): Indicate when an insn starts a new cycle.
+       (contributes_to_priority, compute_jump_reg_dependencies,
+       add_remove_insn, fix_recovery_cfg): Add ebb_ prefix to function names.
+       (add_block1): Remove to ebb_add_block.
+       (ebb_sched_deps_info, ebb_common_sched_info): New variables.
+       (schedule_ebb): Initialize them.  Use remove_notes instead of
+       rm_other_notes.  Use haifa_local_init/finish.
+       (schedule_ebbs): Use haifa_sched_init/finish.
+       * sched-int.h: Include vecprim.h, remove rtl.h.
+       (struct ready_list): Delete declaration.
+       (sched_verbose_param, enum sched_pass_id_t,
+       bb_vec_t, insn_vec_t, rtx_vec_t): New.
+       (struct sched_scan_info_def): New structure.
+       (sched_scan_info, sched_scan, sched_init_bbs,
+       sched_init_luids, sched_finish_luids, sched_extend_target,
+       haifa_init_h_i_d, haifa_finish_h_i_d): Declare.
+       (struct common_sched_info_def): New.
+       (common_sched_info, haifa_common_sched_info,
+       sched_emulate_haifa_p): Declare.
+       (sel_sched_p): New.
+       (sched_luids): Declare.
+       (INSN_LUID, LUID_BY_UID, SET_INSN_LUID): Declare.
+       (sched_max_luid, insn_luid): Declare.
+       (note_list, remove_notes, restore_other_notes, bb_note): Declare.
+       (sched_insns_init, sched_insns_finish, xrecalloc, reemit_notes,
+       print_insn, print_pattern, print_value, haifa_classify_insn,
+       sel_find_rgns, sel_mark_hard_insn, dfa_state_size, advance_state,
+       setup_sched_dump, sched_init, sched_finish,
+       sel_insn_is_speculation_check): Export.
+       (struct ready_list): Move from haifa-sched.c.
+       (ready_try, ready, max_issue): Export.
+       (ebb_compute_jump_reg_dependencies, find_fallthru_edge,
+       sched_init_only_bb, sched_split_block, sched_split_block_1,
+       sched_create_empty_bb, sched_create_empty_bb_1,
+       sched_create_recovery_block, sched_create_recovery_edges): Export.
+       (enum reg_pending_barrier_mode): Export.
+       (struct deps): New fields `last_reg_pending_barrier' and `readonly'.
+       (deps_t): New.
+       (struct sched_info): Rename to haifa_sched_info.  Use const_rtx for
+       print_insn field.  Move add_block and fix_recovery_cfg to
+       common_sched_info_def.  Move compute_jump_reg_dependencies, use_cselib  ...
+       (struct sched_deps_info_def): ... this new structure.
+       (sched_deps_info): Declare.
+       (struct spec_info_def): Remove weakness_cutoff, add
+       data_weakness_cutoff and control_weakness_cutoff.
+       (spec_info): Declare.
+       (struct _haifa_deps_insn_data): Split from haifa_insn_data.  Add
+       dep_count field.
+       (struct haifa_insn_data): Rename to struct _haifa_insn_data.
+       (haifa_insn_data_def, haifa_insn_data_t): New typedefs.
+       (current_sched_info): Change type to struct haifa_sched_info.
+       (haifa_deps_insn_data_def, haifa_deps_insn_data_t): New typedefs.
+       (h_d_i_d): New variable.
+       (HDID): New accessor macro.
+       (h_i_d): Change type to VEC (haifa_insn_data_def, heap) *.
+       (HID): New accessor macro.  Rewrite h_i_d accessor macros through HID
+       and HDID.
+       (IS_SPECULATION_CHECK_P): Update for selective scheduler.
+       (enum SCHED_FLAGS): Update for selective scheduler.
+       (enum SPEC_SCHED_FLAGS): New flag SEL_SCHED_SPEC_DONT_CHECK_CONTROL.
+       (init_dependency_caches, free_dependency_caches): Delete declarations.
+       (deps_analyze_insn, remove_from_deps, get_dep_weak_1,
+       estimate_dep_weak, ds_full_merge, ds_max_merge, ds_weak,
+       ds_get_speculation_types, ds_get_max_dep_weak, sched_deps_init,
+       sched_deps_finish, haifa_note_reg_set, haifa_note_reg_use,
+       haifa_note_reg_clobber, maybe_extend_reg_info_p, deps_start_bb,
+       ds_to_dt): Export.
+       (rm_other_notes): Delete declaration.
+       (schedule_block): Remove one argument.
+       (cycle_issued_insns, issue_rate, dfa_lookahead, ready_sort,
+       ready_element, ready_lastpos, sched_extend_ready_list,
+       sched_finish_ready_list, sched_change_pattern, sched_speculate_insn,
+       concat_note_lists): Export.
+       (struct region): Move from sched-rgn.h.
+       (nr_regions, rgn_table, rgn_bb_table, block_to_bb, containing_rgn,
+       RGN_NR_BLOCKS, RGN_BLOCKS, RGN_DONT_CALC_DEPS, RGN_HAS_REAL_EBB,
+       BLOCK_TO_BB, CONTAINING_RGN): Export.
+       (ebb_head, BB_TO_BLOCK, EBB_FIRST_BB, EBB_LAST_BB, INSN_BB): Likewise.
+       (current_nr_blocks, current_blocks, target_bb): Likewise.
+       (dep_cost_1, sched_is_disabled_for_current_region_p, sched_rgn_init,
+       sched_rgn_finish, rgn_setup_region, sched_rgn_compute_dependencies,
+       sched_rgn_local_init, extend_regions,
+       rgn_make_new_region_out_of_new_block, compute_priorities,
+       debug_rgn_dependencies, free_rgn_deps, contributes_to_priority,
+       extend_rgns, deps_join rgn_setup_common_sched_info,
+       rgn_setup_sched_infos, debug_regions, debug_region, dump_region_dot,
+       dump_region_dot_file, haifa_sched_init, haifa_sched_finish): Export.
+       (get_rgn_sched_max_insns_priority, sel_add_to_insn_priority, 
+       increase_insn_priority): Likewise.
+       * sched-rgn.c: Include sel-sched.h.
+       (ref_counts): New static variable.  Use it ...
+       (INSN_REF_COUNT): ... here.  Rewrite and move closer to uses.
+       (FED_BY_SPEC_LOAD, IS_LOAD_INSN): Rewrite to use HID accessor macro.
+       (sched_is_disabled_for_current_region_p): Delete static declaration.
+       (struct region): Move to sched-int.h.
+       (nr_regions, rgn_table, rgn_bb_table, block_to_bb, containing_rgn,
+       ebb_head): Define and initialize.
+       (RGN_NR_BLOCKS, RGN_BLOCKS, RGN_DONT_CALC_DEPS, RGN_HAS_REAL_EBB,
+       BLOCK_TO_BB, CONTAINING_RGN, debug_regions, extend_regions,
+       BB_TO_BLOCK, EBB_FIRST_BB, EBB_LAST_BB): Move to
+       sched-int.h.
+       (find_single_block_region): Add new argument to indicate that EBB
+       regions should be constructed.
+       (debug_live): Delete declaration.
+       (current_nr_blocks, current_blocks, target_bb): Remove static qualifiers.
+       (compute_dom_prob_ps, check_live, update_live, set_spec_fed): Delete
+       declaration.
+       (init_regions): Delete declaration.
+       (debug_region, bb_in_region_p, dump_region_dot_file, dump_region_dot,
+       rgn_estimate_number_of_insns): New.
+       (too_large): Use estimate_number_of_insns.
+       (haifa_find_rgns): New. Move the code from ...
+       (find_rgns): ... here.  Call either sel_find_rgns or haifa_find_rgns.
+       (free_trg_info): New.
+       (compute_trg_info): Allocate candidate tables here instead of ...
+       (init_ready_list): ... here.
+       (rgn_print_insn): Use const_rtx.
+       (contributes_to_priority, extend_regions): Delete static declaration.
+       (add_remove_insn, fix_recovery_cfg): Add rgn_ to function names.
+       (add_block1): Rename to rgn_add_block.
+       (debug_rgn_dependencies): Delete static qualifier.
+       (new_ready): Use sched_deps_info.  Simplify.
+       (rgn_common_sched_info, rgn_const_sched_deps_info,
+       rgn_const_sel_sched_deps_info, rgn_sched_deps_info, rgn_sched_info): New.
+       (region_sched_info): Rename to rgn_const_sched_info.
+       (deps_join): New, extracted from ...
+       (propagate_deps): ... here.
+       (compute_block_dependences, debug_dependencies): Update for selective
+       scheduling.
+       (free_rgn_deps, compute_priorities): New functions.
+       (sched_rgn_init, sched_rgn_finish, rgn_setup_region,
+       sched_rgn_compute_dependencies): New functions.
+       (schedule_region): Use them.
+       (sched_rgn_local_init, sched_rgn_local_free, sched_rgn_local_finish,
+       rgn_setup_common_sched_info, rgn_setup_sched_infos):
+       New functions.
+       (schedule_insns): Call new functions that were split out.
+       (rgn_make_new_region_out_of_new_block): New.
+       (get_rgn_sched_max_insns_priority): New.
+       (rest_of_handle_sched, rest_of_handle_sched2): Call selective
+       scheduling when appropriate.
+       * sched-vis.c: Include insn-attr.h.
+       (print_value, print_pattern): Make global.
+       (print_rtl_slim, debug_bb_slim, debug_bb_n_slim): New functions.
+       * target-def.h (TARGET_SCHED_ADJUST_COST_2,
+       TARGET_SCHED_ALLOC_SCHED_CONTEXT, TARGET_SCHED_INIT_SCHED_CONTEXT,
+       TARGET_SCHED_SET_SCHED_CONTEXT, TARGET_SCHED_CLEAR_SCHED_CONTEXT,
+       TARGET_SCHED_FREE_SCHED_CONTEXT, TARGET_SCHED_GET_INSN_CHECKED_DS,
+       TARGET_SCHED_GET_INSN_SPEC_DS, TARGET_SCHED_SKIP_RTX_P): New target
+       hooks.  Initialize them to 0.
+       (TARGET_SCHED_GEN_CHECK): Rename to TARGET_SCHED_GEN_SPEC_CHECK.
+       * target.h (struct gcc_target): Add them.  Rename gen_check field to
+       gen_spec_check.
+       * flags.h (sel_sched_switch_set): Declare.
+       * opts.c (sel_sched_switch_set): New variable.
+       (decode_options): Unset flag_sel_sched_pipelining_outer_loops if
+       pipelining is disabled from command line.
+       (common_handle_option): Record whether selective scheduling is
+       requested from command line.
+       * doc/invoke.texi: Document new flags and parameters.
+       * doc/tm.texi: Document new target hooks.
+       * config/ia64/ia64.c (TARGET_SCHED_GEN_SPEC_CHECK): Define to ia64_gen_check.
+       (dfa_state_size): Do not declare locally.
+       * config/ia64/ia64.opt (msched-ar-data-spec): Default to 0.
+       * config/rs6000/rs6000.c (rs6000_init_sched_context,
+       rs6000_alloc_sched_context, rs6000_set_sched_context,
+       rs6000_free_sched_context): New functions.
+       (struct _rs6000_sched_context): New.
+       (rs6000_sched_reorder2): Do not modify INSN_PRIORITY for selective
+       scheduling.
+       (rs6000_sched_finish): Do not run for selective scheduling. 
+
 2008-08-31  Jan Hubicka  <jh@suse.cz>
 
        * frv.c (frv_rtx_costs): Update forward declaration.
index e27d04c..f5ee1e3 100644 (file)
@@ -803,7 +803,10 @@ OPTABS_H = optabs.h insn-codes.h
 REGS_H = regs.h varray.h $(MACHMODE_H) $(OBSTACK_H) $(BASIC_BLOCK_H) $(FUNCTION_H)
 RA_H = ra.h $(REGS_H)
 RESOURCE_H = resource.h hard-reg-set.h
-SCHED_INT_H = sched-int.h $(INSN_ATTR_H) $(BASIC_BLOCK_H) $(RTL_H) $(DF_H)
+SCHED_INT_H = sched-int.h $(INSN_ATTR_H) $(BASIC_BLOCK_H) $(RTL_H) $(DF_H) vecprim.h
+SEL_SCHED_IR_H = sel-sched-ir.h $(INSN_ATTR_H) $(BASIC_BLOCK_H) $(RTL_H) \
+       $(GGC_H) $(SCHED_INT_H)
+SEL_SCHED_DUMP_H = sel-sched-dump.h $(SEL_SCHED_IR_H)
 INTEGRATE_H = integrate.h $(VARRAY_H)
 CFGLAYOUT_H = cfglayout.h $(BASIC_BLOCK_H)
 CFGLOOP_H = cfgloop.h $(BASIC_BLOCK_H) $(RTL_H) vecprim.h double-int.h
@@ -1163,6 +1166,9 @@ OBJS-common = \
        sched-vis.o \
        sdbout.o \
        see.o \
+       sel-sched-ir.o \
+       sel-sched-dump.o \
+       sel-sched.o \
        simplify-rtx.o \
        sparseset.o \
        sreal.o \
@@ -2941,14 +2947,31 @@ sched-deps.o : sched-deps.c $(CONFIG_H) $(SYSTEM_H) coretypes.h $(TM_H) \
 sched-rgn.o : sched-rgn.c $(CONFIG_H) $(SYSTEM_H) coretypes.h $(TM_H) \
    $(RTL_H) $(SCHED_INT_H) $(REGS_H) hard-reg-set.h $(FLAGS_H) insn-config.h \
    $(FUNCTION_H) $(INSN_ATTR_H) $(TOPLEV_H) $(RECOG_H) except.h $(PARAMS_H) \
-   $(TM_P_H) $(TARGET_H) $(CFGLAYOUT_H) $(TIMEVAR_H) tree-pass.h $(DBGCNT_H)
+   $(TM_P_H) $(TARGET_H) $(CFGLAYOUT_H) $(TIMEVAR_H) tree-pass.h  \
+   $(DBGCNT_H)
 sched-ebb.o : sched-ebb.c $(CONFIG_H) $(SYSTEM_H) coretypes.h $(TM_H) \
    $(RTL_H) $(SCHED_INT_H) $(REGS_H) hard-reg-set.h $(FLAGS_H) insn-config.h \
    $(FUNCTION_H) $(INSN_ATTR_H) $(TOPLEV_H) $(RECOG_H) except.h $(TM_P_H) \
    $(PARAMS_H) $(CFGLAYOUT_H) $(TARGET_H) output.h
 sched-vis.o : sched-vis.c $(CONFIG_H) $(SYSTEM_H) coretypes.h $(TM_H) \
    $(RTL_H) $(SCHED_INT_H) hard-reg-set.h $(BASIC_BLOCK_H) $(OBSTACK_H) \
-   $(REAL_H) tree-pass.h
+   $(REAL_H) tree-pass.h $(INSN_ATTR_H)
+sel-sched.o : sel-sched.c $(CONFIG_H) $(SYSTEM_H) coretypes.h $(TM_H) \
+   $(RTL_H) $(REGS_H) hard-reg-set.h $(FLAGS_H) insn-config.h \
+   $(FUNCTION_H) $(INSN_ATTR_H) toplev.h $(RECOG_H) except.h $(PARAMS_H) \
+   $(TM_P_H) $(TARGET_H) $(CFGLAYOUT_H) $(TIMEVAR_H) tree-pass.h  \
+   $(SCHED_INT_H) $(GGC_H) $(TREE_H) $(LANGHOOKS_DEF_H) \
+   $(SEL_SCHED_IR_H) $(SEL_SCHED_DUMP_H) sel-sched.h
+sel-sched-dump.o : sel-sched-dump.c $(CONFIG_H) $(SYSTEM_H) coretypes.h $(TM_H) \
+   $(RTL_H) $(REGS_H) hard-reg-set.h $(FLAGS_H) insn-config.h \
+   $(FUNCTION_H) $(INSN_ATTR_H) toplev.h $(RECOG_H) except.h $(PARAMS_H) \
+   $(TM_P_H) $(TARGET_H) $(CFGLAYOUT_H) $(TIMEVAR_H) tree-pass.h \
+   $(SEL_SCHED_DUMP_H) $(GGC_H) $(TREE_H) $(LANGHOOKS_DEF_H) $(SEL_SCHED_IR_H)
+sel-sched-ir.o : sel-sched-ir.c $(CONFIG_H) $(SYSTEM_H) coretypes.h $(TM_H) \
+   $(RTL_H) $(REGS_H) hard-reg-set.h $(FLAGS_H) insn-config.h \
+   $(FUNCTION_H) $(INSN_ATTR_H) toplev.h $(RECOG_H) except.h $(PARAMS_H) \
+   $(TM_P_H) $(TARGET_H) $(CFGLAYOUT_H) $(TIMEVAR_H) tree-pass.h \
+   $(SCHED_INT_H) $(GGC_H) $(TREE_H) $(LANGHOOKS_DEF_H) $(SEL_SCHED_IR_H)
 final.o : final.c $(CONFIG_H) $(SYSTEM_H) coretypes.h $(TM_H) $(RTL_H) \
    $(TREE_H) $(FLAGS_H) intl.h $(REGS_H) $(RECOG_H) conditions.h \
    insn-config.h $(INSN_ATTR_H) $(FUNCTION_H) output.h hard-reg-set.h \
index 00d7151..0897b0d 100644 (file)
@@ -56,6 +56,18 @@ gimple_register_cfg_hooks (void)
   cfg_hooks = &gimple_cfg_hooks;
 }
 
+struct cfg_hooks
+get_cfg_hooks (void)
+{
+  return *cfg_hooks;
+}
+
+void
+set_cfg_hooks (struct cfg_hooks new_cfg_hooks)
+{
+  *cfg_hooks = new_cfg_hooks;
+}
+
 /* Returns current ir type.  */
 
 enum ir_type
@@ -719,6 +731,8 @@ make_forwarder_block (basic_block bb, bool (*redirect_edge_p) (edge),
   /* Redirect back edges we want to keep.  */
   for (ei = ei_start (dummy->preds); (e = ei_safe_edge (ei)); )
     {
+      basic_block e_src;
+
       if (redirect_edge_p (e))
        {
          ei_next (&ei);
@@ -735,10 +749,21 @@ make_forwarder_block (basic_block bb, bool (*redirect_edge_p) (edge),
       if (fallthru->count < 0)
        fallthru->count = 0;
 
+      e_src = e->src;
       jump = redirect_edge_and_branch_force (e, bb);
-      if (jump != NULL
-         && new_bb_cbk != NULL)
-       new_bb_cbk (jump);
+      if (jump != NULL)
+        {
+          /* If we redirected the loop latch edge, the JUMP block now acts like
+             the new latch of the loop.  */
+          if (current_loops != NULL
+              && dummy->loop_father != NULL
+              && dummy->loop_father->header == dummy
+              && dummy->loop_father->latch == e_src)
+            dummy->loop_father->latch = jump;
+          
+          if (new_bb_cbk != NULL)
+            new_bb_cbk (jump);
+        }
     }
 
   if (dom_info_available_p (CDI_DOMINATORS))
index 537c05f..cb4a536 100644 (file)
@@ -190,5 +190,7 @@ extern enum ir_type current_ir_type (void);
 extern void rtl_register_cfg_hooks (void);
 extern void cfg_layout_rtl_register_cfg_hooks (void);
 extern void gimple_register_cfg_hooks (void);
+extern struct cfg_hooks get_cfg_hooks (void);
+extern void set_cfg_hooks (struct cfg_hooks);
 
 #endif  /* GCC_CFGHOOKS_H */
index 4c9bbf0..0e95323 100644 (file)
@@ -887,6 +887,19 @@ get_loop_body_in_dom_order (const struct loop *loop)
   return tovisit;
 }
 
+/* Gets body of a LOOP sorted via provided BB_COMPARATOR.  */
+
+basic_block *
+get_loop_body_in_custom_order (const struct loop *loop, 
+                              int (*bb_comparator) (const void *, const void *))
+{
+  basic_block *bbs = get_loop_body (loop);
+
+  qsort (bbs, loop->num_nodes, sizeof (basic_block), bb_comparator);
+
+  return bbs;
+}
+
 /* Get body of a LOOP in breadth first sort order.  */
 
 basic_block *
index 842ebb5..aa3e611 100644 (file)
@@ -171,7 +171,8 @@ enum
   LOOPS_HAVE_RECORDED_EXITS = 8,
   LOOPS_MAY_HAVE_MULTIPLE_LATCHES = 16,
   LOOP_CLOSED_SSA = 32,
-  LOOPS_NEED_FIXUP = 64
+  LOOPS_NEED_FIXUP = 64,
+  LOOPS_HAVE_FALLTHRU_PREHEADERS = 128
 };
 
 #define LOOPS_NORMAL (LOOPS_HAVE_PREHEADERS | LOOPS_HAVE_SIMPLE_LATCHES \
@@ -235,6 +236,9 @@ extern unsigned get_loop_body_with_size (const struct loop *, basic_block *,
                                         unsigned);
 extern basic_block *get_loop_body_in_dom_order (const struct loop *);
 extern basic_block *get_loop_body_in_bfs_order (const struct loop *);
+extern basic_block *get_loop_body_in_custom_order (const struct loop *, 
+                              int (*) (const void *, const void *));
+
 extern VEC (edge, heap) *get_loop_exit_edges (const struct loop *);
 edge single_exit (const struct loop *);
 extern unsigned num_loop_branches (const struct loop *);
@@ -250,7 +254,8 @@ extern void delete_loop (struct loop *);
 
 enum
 {
-  CP_SIMPLE_PREHEADERS = 1
+  CP_SIMPLE_PREHEADERS = 1,
+  CP_FALLTHRU_PREHEADERS = 2
 };
 
 basic_block create_preheader (struct loop *, int);
index d5bd216..025b5be 100644 (file)
@@ -1102,9 +1102,26 @@ mfb_keep_just (edge e)
   return e != mfb_kj_edge;
 }
 
+/* True when a candidate preheader BLOCK has predecessors from LOOP.  */
+
+static bool
+has_preds_from_loop (basic_block block, struct loop *loop)
+{
+  edge e;
+  edge_iterator ei;
+  
+  FOR_EACH_EDGE (e, ei, block->preds)
+    if (e->src->loop_father == loop)
+      return true;
+  return false;
+}
+
 /* Creates a pre-header for a LOOP.  Returns newly created block.  Unless
    CP_SIMPLE_PREHEADERS is set in FLAGS, we only force LOOP to have single
    entry; otherwise we also force preheader block to have only one successor.
+   When CP_FALLTHRU_PREHEADERS is set in FLAGS, we force the preheader block
+   to be a fallthru predecessor to the loop header and to have only 
+   predecessors from outside of the loop.
    The function also updates dominators.  */
 
 basic_block
@@ -1131,13 +1148,27 @@ create_preheader (struct loop *loop, int flags)
   gcc_assert (nentry);
   if (nentry == 1)
     {
-      if (/* We do not allow entry block to be the loop preheader, since we
+      bool need_forwarder_block = false;
+      
+      /* We do not allow entry block to be the loop preheader, since we
             cannot emit code there.  */
-         single_entry->src != ENTRY_BLOCK_PTR
-         /* If we want simple preheaders, also force the preheader to have
-            just a single successor.  */
-         && !((flags & CP_SIMPLE_PREHEADERS)
-              && !single_succ_p (single_entry->src)))
+      if (single_entry->src == ENTRY_BLOCK_PTR)
+        need_forwarder_block = true;
+      else
+        {
+          /* If we want simple preheaders, also force the preheader to have
+             just a single successor.  */
+          if ((flags & CP_SIMPLE_PREHEADERS)
+              && !single_succ_p (single_entry->src))
+            need_forwarder_block = true;
+          /* If we want fallthru preheaders, also create forwarder block when
+             preheader ends with a jump or has predecessors from loop.  */
+          else if ((flags & CP_FALLTHRU_PREHEADERS)
+                   && (JUMP_P (BB_END (single_entry->src))
+                       || has_preds_from_loop (single_entry->src, loop)))
+            need_forwarder_block = true;
+        }
+      if (! need_forwarder_block)
        return NULL;
     }
 
@@ -1174,6 +1205,10 @@ create_preheader (struct loop *loop, int flags)
   if (dump_file)
     fprintf (dump_file, "Created preheader block for loop %i\n",
             loop->num);
+  
+  if (flags & CP_FALLTHRU_PREHEADERS)
+    gcc_assert ((single_succ_edge (dummy)->flags & EDGE_FALLTHRU)
+                && !JUMP_P (BB_END (dummy)));
 
   return dummy;
 }
index b2c6643..87824f5 100644 (file)
@@ -962,6 +962,29 @@ fschedule-insns2
 Common Report Var(flag_schedule_insns_after_reload) Optimization
 Reschedule instructions after register allocation
 
+; This flag should be on when a target implements non-trivial
+; scheduling hooks, maybe saving some information for its own sake.
+; On IA64, for example, this is used for correct bundling. 
+fselective-scheduling
+Common Report Var(flag_selective_scheduling) Optimization
+Schedule instructions using selective scheduling algorithm
+
+fselective-scheduling2
+Common Report Var(flag_selective_scheduling2) Optimization 
+Run selective scheduling after reload
+
+fsel-sched-pipelining
+Common Report Var(flag_sel_sched_pipelining) Init(0) Optimization
+Perform software pipelining of inner loops during selective scheduling
+
+fsel-sched-pipelining-outer-loops
+Common Report Var(flag_sel_sched_pipelining_outer_loops) Init(0) Optimization
+Perform software pipelining of outer loops during selective scheduling
+
+fsel-sched-reschedule-pipelined
+Common Report Var(flag_sel_sched_reschedule_pipelined) Init(0) Optimization
+Reschedule pipelined regions without pipelining
+
 ; sched_stalled_insns means that insns can be moved prematurely from the queue
 ; of stalled insns into the ready list.
 fsched-stalled-insns
index c16ecc7..1927011 100644 (file)
@@ -382,8 +382,8 @@ static const struct attribute_spec ia64_attribute_table[] =
 #undef TARGET_SCHED_NEEDS_BLOCK_P
 #define TARGET_SCHED_NEEDS_BLOCK_P ia64_needs_block_p
 
-#undef TARGET_SCHED_GEN_CHECK
-#define TARGET_SCHED_GEN_CHECK ia64_gen_check
+#undef TARGET_SCHED_GEN_SPEC_CHECK
+#define TARGET_SCHED_GEN_SPEC_CHECK ia64_gen_check
 
 #undef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD_SPEC
 #define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD_SPEC\
@@ -6278,10 +6278,6 @@ static rtx dfa_stop_insn;
 
 static rtx last_scheduled_insn;
 
-/* The following variable value is size of the DFA state.  */
-
-static size_t dfa_state_size;
-
 /* The following variable value is pointer to a DFA state used as
    temporary variable.  */
 
index 2ff3d59..5103f90 100644 (file)
@@ -101,7 +101,7 @@ Target Report Var(mflag_sched_br_data_spec) Init(0)
 Use data speculation before reload
 
 msched-ar-data-spec
-Target Report Var(mflag_sched_ar_data_spec) Init(1)
+Target Report Var(mflag_sched_ar_data_spec) Init(0)
 Use data speculation after reload
 
 msched-control-spec
index d3821a8..6ab3496 100644 (file)
@@ -857,6 +857,10 @@ static int rs6000_sched_reorder (FILE *, int, rtx *, int *, int);
 static int rs6000_sched_reorder2 (FILE *, int, rtx *, int *, int);
 static int rs6000_use_sched_lookahead (void);
 static int rs6000_use_sched_lookahead_guard (rtx);
+static void * rs6000_alloc_sched_context (void);
+static void rs6000_init_sched_context (void *, bool);
+static void rs6000_set_sched_context (void *);
+static void rs6000_free_sched_context (void *);
 static tree rs6000_builtin_reciprocal (unsigned int, bool, bool);
 static tree rs6000_builtin_mask_for_load (void);
 static tree rs6000_builtin_mul_widen_even (tree);
@@ -1131,6 +1135,15 @@ static const char alt_reg_names[][8] =
 #undef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD
 #define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD rs6000_use_sched_lookahead_guard
 
+#undef TARGET_SCHED_ALLOC_SCHED_CONTEXT
+#define TARGET_SCHED_ALLOC_SCHED_CONTEXT rs6000_alloc_sched_context
+#undef TARGET_SCHED_INIT_SCHED_CONTEXT
+#define TARGET_SCHED_INIT_SCHED_CONTEXT rs6000_init_sched_context
+#undef TARGET_SCHED_SET_SCHED_CONTEXT
+#define TARGET_SCHED_SET_SCHED_CONTEXT rs6000_set_sched_context
+#undef TARGET_SCHED_FREE_SCHED_CONTEXT
+#define TARGET_SCHED_FREE_SCHED_CONTEXT rs6000_free_sched_context
+
 #undef TARGET_VECTORIZE_BUILTIN_MASK_FOR_LOAD
 #define TARGET_VECTORIZE_BUILTIN_MASK_FOR_LOAD rs6000_builtin_mask_for_load
 #undef TARGET_VECTORIZE_BUILTIN_MUL_WIDEN_EVEN
@@ -19476,7 +19489,8 @@ rs6000_sched_reorder2 (FILE *dump, int sched_verbose, rtx *ready,
                   for (i=pos; i<*pn_ready-1; i++)
                     ready[i] = ready[i + 1];
                   ready[*pn_ready-1] = tmp;
-                  if INSN_PRIORITY_KNOWN (tmp)
+
+                  if (!sel_sched_p () && INSN_PRIORITY_KNOWN (tmp))
                     INSN_PRIORITY (tmp)++;
                   break;
                 }
@@ -19493,7 +19507,8 @@ rs6000_sched_reorder2 (FILE *dump, int sched_verbose, rtx *ready,
           while (pos >= 0)
             {
               if (is_load_insn (ready[pos])
-                  && INSN_PRIORITY_KNOWN (ready[pos]))
+                  && !sel_sched_p ()
+                 && INSN_PRIORITY_KNOWN (ready[pos]))
                 {
                   INSN_PRIORITY (ready[pos])++;
 
@@ -19535,8 +19550,10 @@ rs6000_sched_reorder2 (FILE *dump, int sched_verbose, rtx *ready,
                       for (i=pos; i<*pn_ready-1; i++)
                         ready[i] = ready[i + 1];
                       ready[*pn_ready-1] = tmp;
-                      if INSN_PRIORITY_KNOWN (tmp)
+
+                      if (!sel_sched_p () && INSN_PRIORITY_KNOWN (tmp))
                         INSN_PRIORITY (tmp)++;
+
                       first_store_pos = -1;
 
                       break;
@@ -19555,7 +19572,7 @@ rs6000_sched_reorder2 (FILE *dump, int sched_verbose, rtx *ready,
               for (i=first_store_pos; i<*pn_ready-1; i++)
                 ready[i] = ready[i + 1];
               ready[*pn_ready-1] = tmp;
-              if INSN_PRIORITY_KNOWN (tmp)
+              if (!sel_sched_p () && INSN_PRIORITY_KNOWN (tmp))
                 INSN_PRIORITY (tmp)++;
             }
         }
@@ -19569,7 +19586,8 @@ rs6000_sched_reorder2 (FILE *dump, int sched_verbose, rtx *ready,
           while (pos >= 0)
             {
               if (is_store_insn (ready[pos])
-                  && INSN_PRIORITY_KNOWN (ready[pos]))
+                  && !sel_sched_p ()
+                 && INSN_PRIORITY_KNOWN (ready[pos]))
                 {
                   INSN_PRIORITY (ready[pos])++;
 
@@ -20071,7 +20089,7 @@ pad_groups (FILE *dump, int sched_verbose, rtx prev_head_insn, rtx tail)
       if (group_end)
        {
          /* If the scheduler had marked group termination at this location
-            (between insn and next_indn), and neither insn nor next_insn will
+            (between insn and next_insn), and neither insn nor next_insn will
             force group termination, pad the group with nops to force group
             termination.  */
          if (can_issue_more
@@ -20125,6 +20143,10 @@ rs6000_sched_finish (FILE *dump, int sched_verbose)
 
   if (reload_completed && rs6000_sched_groups)
     {
+      /* Do not run sched_finish hook when selective scheduling enabled.  */
+      if (sel_sched_p ())
+       return;
+
       if (rs6000_sched_insert_nops == sched_finish_none)
        return;
 
@@ -20145,6 +20167,67 @@ rs6000_sched_finish (FILE *dump, int sched_verbose)
        }
     }
 }
+
+struct _rs6000_sched_context
+{
+  short cached_can_issue_more;
+  rtx last_scheduled_insn;
+  int load_store_pendulum;
+};
+
+typedef struct _rs6000_sched_context rs6000_sched_context_def;
+typedef rs6000_sched_context_def *rs6000_sched_context_t;
+
+/* Allocate store for new scheduling context.  */
+static void *
+rs6000_alloc_sched_context (void)
+{
+  return xmalloc (sizeof (rs6000_sched_context_def));
+}
+
+/* If CLEAN_P is true then initializes _SC with clean data,
+   and from the global context otherwise.  */
+static void
+rs6000_init_sched_context (void *_sc, bool clean_p)
+{
+  rs6000_sched_context_t sc = (rs6000_sched_context_t) _sc;
+
+  if (clean_p)
+    {
+      sc->cached_can_issue_more = 0;
+      sc->last_scheduled_insn = NULL_RTX;
+      sc->load_store_pendulum = 0;
+    }
+  else
+    {
+      sc->cached_can_issue_more = cached_can_issue_more;
+      sc->last_scheduled_insn = last_scheduled_insn;
+      sc->load_store_pendulum = load_store_pendulum;
+    }
+}
+
+/* Sets the global scheduling context to the one pointed to by _SC.  */
+static void
+rs6000_set_sched_context (void *_sc)
+{
+  rs6000_sched_context_t sc = (rs6000_sched_context_t) _sc;
+
+  gcc_assert (sc != NULL);
+
+  cached_can_issue_more = sc->cached_can_issue_more;
+  last_scheduled_insn = sc->last_scheduled_insn;
+  load_store_pendulum = sc->load_store_pendulum;
+}
+
+/* Free _SC.  */
+static void
+rs6000_free_sched_context (void *_sc)
+{
+  gcc_assert (_sc != NULL);
+
+  free (_sc);
+}
+
 \f
 /* Length in units of the trampoline for entering a nested function.  */
 
index d586c6c..c1effee 100644 (file)
--- a/gcc/cse.c
+++ b/gcc/cse.c
@@ -574,7 +574,7 @@ static rtx use_related_value (rtx, struct table_elt *);
 
 static inline unsigned canon_hash (rtx, enum machine_mode);
 static inline unsigned safe_hash (rtx, enum machine_mode);
-static unsigned hash_rtx_string (const char *);
+static inline unsigned hash_rtx_string (const char *);
 
 static rtx canon_reg (rtx, rtx);
 static enum rtx_code find_comparison_args (enum rtx_code, rtx *, rtx *,
@@ -2044,6 +2044,7 @@ use_related_value (rtx x, struct table_elt *elt)
   return plus_constant (q->exp, offset);
 }
 \f
+
 /* Hash a string.  Just add its bytes up.  */
 static inline unsigned
 hash_rtx_string (const char *ps)
@@ -2058,27 +2059,20 @@ hash_rtx_string (const char *ps)
   return hash;
 }
 
-/* Hash an rtx.  We are careful to make sure the value is never negative.
-   Equivalent registers hash identically.
-   MODE is used in hashing for CONST_INTs only;
-   otherwise the mode of X is used.
-
-   Store 1 in DO_NOT_RECORD_P if any subexpression is volatile.
-
-   If HASH_ARG_IN_MEMORY_P is not NULL, store 1 in it if X contains
-   a MEM rtx which does not have the RTX_UNCHANGING_P bit set.
-
-   Note that cse_insn knows that the hash code of a MEM expression
-   is just (int) MEM plus the hash code of the address.  */
+/* Same as hash_rtx, but call CB on each rtx if it is not NULL.  
+   When the callback returns true, we continue with the new rtx.  */
 
 unsigned
-hash_rtx (const_rtx x, enum machine_mode mode, int *do_not_record_p,
-         int *hash_arg_in_memory_p, bool have_reg_qty)
+hash_rtx_cb (const_rtx x, enum machine_mode mode,
+             int *do_not_record_p, int *hash_arg_in_memory_p,
+             bool have_reg_qty, hash_rtx_callback_function cb)
 {
   int i, j;
   unsigned hash = 0;
   enum rtx_code code;
   const char *fmt;
+  enum machine_mode newmode;
+  rtx newx;
 
   /* Used to turn recursion into iteration.  We can't rely on GCC's
      tail-recursion elimination since we need to keep accumulating values
@@ -2087,6 +2081,15 @@ hash_rtx (const_rtx x, enum machine_mode mode, int *do_not_record_p,
   if (x == 0)
     return hash;
 
+  /* Invoke the callback first.  */
+  if (cb != NULL 
+      && ((*cb) (x, mode, &newx, &newmode)))
+    {
+      hash += hash_rtx_cb (newx, newmode, do_not_record_p,
+                           hash_arg_in_memory_p, have_reg_qty, cb);
+      return hash;
+    }
+
   code = GET_CODE (x);
   switch (code)
     {
@@ -2094,7 +2097,7 @@ hash_rtx (const_rtx x, enum machine_mode mode, int *do_not_record_p,
       {
        unsigned int regno = REGNO (x);
 
-       if (!reload_completed)
+       if (do_not_record_p && !reload_completed)
          {
            /* On some machines, we can't record any non-fixed hard register,
               because extending its life will cause reload problems.  We
@@ -2188,8 +2191,9 @@ hash_rtx (const_rtx x, enum machine_mode mode, int *do_not_record_p,
        for (i = 0; i < units; ++i)
          {
            elt = CONST_VECTOR_ELT (x, i);
-           hash += hash_rtx (elt, GET_MODE (elt), do_not_record_p,
-                             hash_arg_in_memory_p, have_reg_qty);
+           hash += hash_rtx_cb (elt, GET_MODE (elt),
+                                 do_not_record_p, hash_arg_in_memory_p, 
+                                 have_reg_qty, cb);
          }
 
        return hash;
@@ -2223,7 +2227,7 @@ hash_rtx (const_rtx x, enum machine_mode mode, int *do_not_record_p,
     case MEM:
       /* We don't record if marked volatile or if BLKmode since we don't
         know the size of the move.  */
-      if (MEM_VOLATILE_P (x) || GET_MODE (x) == BLKmode)
+      if (do_not_record_p && (MEM_VOLATILE_P (x) || GET_MODE (x) == BLKmode))
        {
          *do_not_record_p = 1;
          return 0;
@@ -2270,11 +2274,16 @@ hash_rtx (const_rtx x, enum machine_mode mode, int *do_not_record_p,
     case CC0:
     case CALL:
     case UNSPEC_VOLATILE:
-      *do_not_record_p = 1;
-      return 0;
+      if (do_not_record_p) {
+        *do_not_record_p = 1;
+        return 0;
+      }
+      else
+        return hash;
+      break;
 
     case ASM_OPERANDS:
-      if (MEM_VOLATILE_P (x))
+      if (do_not_record_p && MEM_VOLATILE_P (x))
        {
          *do_not_record_p = 1;
          return 0;
@@ -2291,12 +2300,12 @@ hash_rtx (const_rtx x, enum machine_mode mode, int *do_not_record_p,
            {
              for (i = 1; i < ASM_OPERANDS_INPUT_LENGTH (x); i++)
                {
-                 hash += (hash_rtx (ASM_OPERANDS_INPUT (x, i),
-                                    GET_MODE (ASM_OPERANDS_INPUT (x, i)),
-                                    do_not_record_p, hash_arg_in_memory_p,
-                                    have_reg_qty)
+                 hash += (hash_rtx_cb (ASM_OPERANDS_INPUT (x, i),
+                                        GET_MODE (ASM_OPERANDS_INPUT (x, i)),
+                                        do_not_record_p, hash_arg_in_memory_p,
+                                        have_reg_qty, cb)
                           + hash_rtx_string
-                               (ASM_OPERANDS_INPUT_CONSTRAINT (x, i)));
+                           (ASM_OPERANDS_INPUT_CONSTRAINT (x, i)));
                }
 
              hash += hash_rtx_string (ASM_OPERANDS_INPUT_CONSTRAINT (x, 0));
@@ -2329,15 +2338,17 @@ hash_rtx (const_rtx x, enum machine_mode mode, int *do_not_record_p,
              x = XEXP (x, i);
              goto repeat;
            }
-
-         hash += hash_rtx (XEXP (x, i), 0, do_not_record_p,
-                           hash_arg_in_memory_p, have_reg_qty);
+          
+         hash += hash_rtx_cb (XEXP (x, i), 0, do_not_record_p,
+                               hash_arg_in_memory_p,
+                               have_reg_qty, cb);
          break;
 
        case 'E':
          for (j = 0; j < XVECLEN (x, i); j++)
-           hash += hash_rtx (XVECEXP (x, i, j), 0, do_not_record_p,
-                             hash_arg_in_memory_p, have_reg_qty);
+           hash += hash_rtx_cb (XVECEXP (x, i, j), 0, do_not_record_p,
+                                 hash_arg_in_memory_p,
+                                 have_reg_qty, cb);
          break;
 
        case 's':
@@ -2360,6 +2371,27 @@ hash_rtx (const_rtx x, enum machine_mode mode, int *do_not_record_p,
   return hash;
 }
 
+/* Hash an rtx.  We are careful to make sure the value is never negative.
+   Equivalent registers hash identically.
+   MODE is used in hashing for CONST_INTs only;
+   otherwise the mode of X is used.
+
+   Store 1 in DO_NOT_RECORD_P if any subexpression is volatile.
+
+   If HASH_ARG_IN_MEMORY_P is not NULL, store 1 in it if X contains
+   a MEM rtx which does not have the RTX_UNCHANGING_P bit set.
+
+   Note that cse_insn knows that the hash code of a MEM expression
+   is just (int) MEM plus the hash code of the address.  */
+
+unsigned
+hash_rtx (const_rtx x, enum machine_mode mode, int *do_not_record_p,
+         int *hash_arg_in_memory_p, bool have_reg_qty)
+{
+  return hash_rtx_cb (x, mode, do_not_record_p,
+                      hash_arg_in_memory_p, have_reg_qty, NULL);
+}
+
 /* Hash an rtx X for cse via hash_rtx.
    Stores 1 in do_not_record if any subexpression is volatile.
    Stores 1 in hash_arg_in_memory if X contains a mem rtx which
index fa75579..18e8bef 100644 (file)
@@ -172,6 +172,9 @@ DEBUG_COUNTER (sched_block)
 DEBUG_COUNTER (sched_func)
 DEBUG_COUNTER (sched_insn)
 DEBUG_COUNTER (sched_region)
+DEBUG_COUNTER (sel_sched_cnt)
+DEBUG_COUNTER (sel_sched_region_cnt)
+DEBUG_COUNTER (sel_sched_insn_cnt)
 DEBUG_COUNTER (sms_sched_loop)
 DEBUG_COUNTER (split_for_sched2)
 DEBUG_COUNTER (tail_call)
index 29b67c7..33070a0 100644 (file)
@@ -303,6 +303,7 @@ Objective-C and Objective-C++ Dialects}.
 -feliminate-unused-debug-symbols -femit-class-debug-always @gol
 -fmem-report -fpre-ipa-mem-report -fpost-ipa-mem-report -fprofile-arcs @gol
 -frandom-seed=@var{string} -fsched-verbose=@var{n} @gol
+-fsel-sched-verbose -fsel-sched-dump-cfg -fsel-sched-pipelining-verbose @gol
 -ftest-coverage  -ftime-report -fvar-tracking @gol
 -g  -g@var{level}  -gcoff -gdwarf-2 @gol
 -ggdb  -gstabs  -gstabs+  -gvms  -gxcoff  -gxcoff+ @gol
@@ -356,6 +357,8 @@ Objective-C and Objective-C++ Dialects}.
 -fsched2-use-traces -fsched-spec-load -fsched-spec-load-dangerous @gol
 -fsched-stalled-insns-dep[=@var{n}] -fsched-stalled-insns[=@var{n}] @gol
 -fschedule-insns -fschedule-insns2 -fsection-anchors -fsee @gol
+-fselective-scheduling -fselective-scheduling2 @gol
+-fsel-sched-pipelining -fsel-sched-pipelining-outer-loops @gol
 -fsignaling-nans -fsingle-precision-constant -fsplit-ivs-in-unroller @gol
 -fsplit-wide-types -fstack-protector -fstack-protector-all @gol
 -fstrict-aliasing -fstrict-overflow -fthread-jumps -ftracer @gol
@@ -5829,6 +5832,27 @@ The modulo scheduling comes before the traditional scheduling, if a loop
 was modulo scheduled we may want to prevent the later scheduling passes
 from changing its schedule, we use this option to control that.
 
+@item -fselective-scheduling
+@opindex fselective-scheduling
+Schedule instructions using selective scheduling algorithm.  Selective
+scheduling runs instead of the first scheduler pass.
+
+@item -fselective-scheduling2
+@opindex fselective-scheduling2
+Schedule instructions using selective scheduling algorithm.  Selective
+scheduling runs instead of the second scheduler pass.
+
+@item -fsel-sched-pipelining
+@opindex fsel-sched-pipelining
+Enable software pipelining of innermost loops during selective scheduling.  
+This option has no effect until one of @option{-fselective-scheduling} or 
+@option{-fselective-scheduling2} is turned on.
+
+@item -fsel-sched-pipelining-outer-loops
+@opindex fsel-sched-pipelining-outer-loops
+When pipelining loops during selective scheduling, also pipeline outer loops.
+This option has no effect until @option{-fsel-sched-pipelining} is turned on.
+
 @item -fcaller-saves
 @opindex fcaller-saves
 Enable values to be allocated in registers that will be clobbered by
@@ -7325,10 +7349,18 @@ with probably little benefit.  The default value is 100.
 The maximum number of blocks in a region to be considered for
 interblock scheduling.  The default value is 10.
 
+@item max-pipeline-region-blocks
+The maximum number of blocks in a region to be considered for
+pipelining in the selective scheduler.  The default value is 15.
+
 @item max-sched-region-insns
 The maximum number of insns in a region to be considered for
 interblock scheduling.  The default value is 100.
 
+@item max-pipeline-region-insns
+The maximum number of insns in a region to be considered for
+pipelining in the selective scheduler.  The default value is 200.
+
 @item min-spec-prob
 The minimum probability (in percents) of reaching a source block
 for interblock speculative scheduling.  The default value is 40.
@@ -7348,8 +7380,25 @@ The minimal probability of speculation success (in percents), so that
 speculative insn will be scheduled.
 The default value is 40.
 
-@item max-last-value-rtl
+@item sched-mem-true-dep-cost
+Minimal distance (in CPU cycles) between store and load targeting same
+memory locations.  The default value is 1.
+
+@item selsched-max-lookahead
+The maximum size of the lookahead window of selective scheduling.  It is a
+depth of search for available instructions.
+The default value is 50.
 
+@item selsched-max-sched-times
+The maximum number of times that an instruction will be scheduled during 
+selective scheduling.  This is the limit on the number of iterations 
+through which the instruction may be pipelined.  The default value is 2.
+
+@item selsched-max-insns-to-rename
+The maximum number of best instructions in the ready list that are considered
+for renaming in the selective scheduler.  The default value is 2.
+
+@item max-last-value-rtl
 The maximum size measured as number of RTLs that can be recorded in an expression
 in combiner for a pseudo register as last known value of that register.  The default
 is 10000.
index 2cd0877..d27dfbf 100644 (file)
@@ -6356,6 +6356,29 @@ the instruction stream.  The hook notifies a target backend to extend its
 per instruction data structures.
 @end deftypefn
 
+@deftypefn {Target Hook} void * TARGET_SCHED_ALLOC_SCHED_CONTEXT (void)
+Return a pointer to a store large enough to hold target scheduling context.
+@end deftypefn
+
+@deftypefn {Target Hook} void TARGET_SCHED_INIT_SCHED_CONTEXT (void *@var{tc}, bool @var{clean_p})
+Initialize store pointed to by @var{tc} to hold target scheduling context.
+It @var{clean_p} is true then initialize @var{tc} as if scheduler is at the
+beginning of the block.  Overwise, make a copy of the current context in
+@var{tc}.
+@end deftypefn
+
+@deftypefn {Target Hook} void TARGET_SCHED_SET_SCHED_CONTEXT (void *@var{tc})
+Copy target scheduling context pointer to by @var{tc} to the current context.
+@end deftypefn
+
+@deftypefn {Target Hook} void TARGET_SCHED_CLEAR_SCHED_CONTEXT (void *@var{tc})
+Deallocate internal data in target scheduling context pointed to by @var{tc}.
+@end deftypefn
+
+@deftypefn {Target Hook} void TARGET_SCHED_FREE_SCHED_CONTEXT (void *@var{tc})
+Deallocate a store for target scheduling context pointed to by @var{tc}.
+@end deftypefn
+
 @deftypefn {Target Hook} int TARGET_SCHED_SPECULATE_INSN (rtx @var{insn}, int @var{request}, rtx *@var{new_pat})
 This hook is called by the insn scheduler when @var{insn} has only
 speculative dependencies and therefore can be scheduled speculatively.
index a0af7b3..9a887f6 100644 (file)
@@ -3985,6 +3985,7 @@ emit_insn_after_1 (rtx first, rtx after, basic_block bb)
 
   if (after == last_insn)
     last_insn = last;
+
   return last;
 }
 
index c1359e8..a9b51ca 100644 (file)
@@ -664,7 +664,7 @@ insn_current_reference_address (rtx branch)
 /* Compute branch alignments based on frequency information in the
    CFG.  */
 
-static unsigned int
+unsigned int
 compute_alignments (void)
 {
   int log, max_skip, max_log;
@@ -784,7 +784,10 @@ compute_alignments (void)
     }
 
   if (dump_file)
-    loop_optimizer_finalize ();
+    {
+      loop_optimizer_finalize ();
+      free_dominance_info (CDI_DOMINATORS);
+    }
   return 0;
 }
 
index 1d645d9..4a209b3 100644 (file)
@@ -228,6 +228,9 @@ extern int flag_evaluation_order;
 extern unsigned HOST_WIDE_INT g_switch_value;
 extern bool g_switch_set;
 
+/* Same for selective scheduling.  */
+extern bool sel_sched_switch_set;
+
 /* Values of the -falign-* flags: how much to align labels in code. 
    0 means `use default', 1 means `don't align'.  
    For each variable, there is an _log variant which is the power
index 8ff3cd3..bef41cd 100644 (file)
@@ -184,6 +184,10 @@ main (int argc, char **argv)
       printf ("   Use the function if bypass_p returns nonzero for\n");
       printf ("   the 1st insn. */\n");
       printf ("extern int insn_latency (rtx, rtx);\n\n");
+      printf ("/* Maximal insn latency time possible of all bypasses for this insn.\n");
+      printf ("   Use the function if bypass_p returns nonzero for\n");
+      printf ("   the 1st insn. */\n");
+      printf ("extern int maximal_insn_latency (rtx);\n\n");
       printf ("\n#if AUTOMATON_ALTS\n");
       printf ("/* The following function returns number of alternative\n");
       printf ("   reservations of given insn.  It may be used for better\n");
index 3709c55..d314b8f 100644 (file)
@@ -8076,13 +8076,13 @@ output_min_insn_conflict_delay_func (void)
   fprintf (output_file, "}\n\n");
 }
 
-/* Output function `internal_insn_latency'.  */
+/* Output the array holding default latency values.  These are used in 
+   insn_latency and maximal_insn_latency function implementations.  */
 static void
-output_internal_insn_latency_func (void)
+output_default_latencies (void)
 {
-  decl_t decl;
-  struct bypass_decl *bypass;
   int i, j, col;
+  decl_t decl;
   const char *tabletype = "unsigned char";
 
   /* Find the smallest integer type that can hold all the default
@@ -8098,18 +8098,6 @@ output_internal_insn_latency_func (void)
          tabletype = "int";
       }
 
-  fprintf (output_file, "static int\n%s (int %s ATTRIBUTE_UNUSED,\n\tint %s ATTRIBUTE_UNUSED,\n\trtx %s ATTRIBUTE_UNUSED,\n\trtx %s ATTRIBUTE_UNUSED)\n",
-          INTERNAL_INSN_LATENCY_FUNC_NAME, INTERNAL_INSN_CODE_NAME,
-          INTERNAL_INSN2_CODE_NAME, INSN_PARAMETER_NAME,
-          INSN2_PARAMETER_NAME);
-  fprintf (output_file, "{\n");
-
-  if (DECL_INSN_RESERV (advance_cycle_insn_decl)->insn_num == 0)
-    {
-      fputs ("  return 0;\n}\n\n", output_file);
-      return;
-    }
-
   fprintf (output_file, "  static const %s default_latencies[] =\n    {",
           tabletype);
 
@@ -8126,6 +8114,27 @@ output_internal_insn_latency_func (void)
       }
   gcc_assert (j == DECL_INSN_RESERV (advance_cycle_insn_decl)->insn_num);
   fputs ("\n    };\n", output_file);
+}
+
+/* Output function `internal_insn_latency'.  */
+static void
+output_internal_insn_latency_func (void)
+{
+  int i;
+  decl_t decl;
+  struct bypass_decl *bypass;
+
+  fprintf (output_file, "static int\n%s (int %s ATTRIBUTE_UNUSED,\n\tint %s ATTRIBUTE_UNUSED,\n\trtx %s ATTRIBUTE_UNUSED,\n\trtx %s ATTRIBUTE_UNUSED)\n",
+          INTERNAL_INSN_LATENCY_FUNC_NAME, INTERNAL_INSN_CODE_NAME,
+          INTERNAL_INSN2_CODE_NAME, INSN_PARAMETER_NAME,
+          INSN2_PARAMETER_NAME);
+  fprintf (output_file, "{\n");
+
+  if (DECL_INSN_RESERV (advance_cycle_insn_decl)->insn_num == 0)
+    {
+      fputs ("  return 0;\n}\n\n", output_file);
+      return;
+    }
 
   fprintf (output_file, "  if (%s >= %s || %s >= %s)\n    return 0;\n",
           INTERNAL_INSN_CODE_NAME, ADVANCE_CYCLE_VALUE_NAME,
@@ -8171,6 +8180,50 @@ output_internal_insn_latency_func (void)
           INTERNAL_INSN_CODE_NAME);
 }
 
+/* Output function `internal_maximum_insn_latency'.  */
+static void
+output_internal_maximal_insn_latency_func (void)
+{
+  decl_t decl;
+  struct bypass_decl *bypass;
+  int i;
+  int max;
+
+  fprintf (output_file, "static int\n%s (int %s ATTRIBUTE_UNUSED,\n\trtx %s ATTRIBUTE_UNUSED)\n",
+          "internal_maximal_insn_latency", INTERNAL_INSN_CODE_NAME,
+          INSN_PARAMETER_NAME);
+  fprintf (output_file, "{\n");
+
+  if (DECL_INSN_RESERV (advance_cycle_insn_decl)->insn_num == 0)
+    {
+      fputs ("  return 0;\n}\n\n", output_file);
+      return;
+    }
+
+  fprintf (output_file, "  switch (%s)\n    {\n", INTERNAL_INSN_CODE_NAME);
+  for (i = 0; i < description->decls_num; i++)
+    if (description->decls[i]->mode == dm_insn_reserv
+       && DECL_INSN_RESERV (description->decls[i])->bypass_list)
+      {
+       decl = description->decls [i];
+        max = DECL_INSN_RESERV (decl)->default_latency;
+       fprintf (output_file,
+                "    case %d: {",
+                DECL_INSN_RESERV (decl)->insn_num);
+       for (bypass = DECL_INSN_RESERV (decl)->bypass_list;
+            bypass != NULL;
+            bypass = bypass->next)
+         {
+           if (bypass->latency > max)
+              max = bypass->latency;
+         }
+       fprintf (output_file, " return %d; }\n      break;\n", max);
+      }
+
+  fprintf (output_file, "    }\n  return default_latencies[%s];\n}\n\n",
+          INTERNAL_INSN_CODE_NAME);
+}
+
 /* The function outputs PHR interface function `insn_latency'.  */
 static void
 output_insn_latency_func (void)
@@ -8189,6 +8242,21 @@ output_insn_latency_func (void)
           INSN_PARAMETER_NAME, INSN2_PARAMETER_NAME);
 }
 
+/* The function outputs PHR interface function `maximal_insn_latency'.  */
+static void
+output_maximal_insn_latency_func (void)
+{
+  fprintf (output_file, "int\n%s (rtx %s)\n",
+          "maximal_insn_latency", INSN_PARAMETER_NAME);
+  fprintf (output_file, "{\n  int %s;\n",
+          INTERNAL_INSN_CODE_NAME);
+  output_internal_insn_code_evaluation (INSN_PARAMETER_NAME,
+                                       INTERNAL_INSN_CODE_NAME, 0);
+  fprintf (output_file, "  return %s (%s, %s);\n}\n\n",
+          "internal_maximal_insn_latency",
+          INTERNAL_INSN_CODE_NAME, INSN_PARAMETER_NAME);
+}
+
 /* The function outputs PHR interface function `print_reservation'.  */
 static void
 output_print_reservation_func (void)
@@ -9179,8 +9247,11 @@ write_automata (void)
   output_internal_reset_func ();
   output_reset_func ();
   output_min_insn_conflict_delay_func ();
+  output_default_latencies ();
   output_internal_insn_latency_func ();
   output_insn_latency_func ();
+  output_internal_maximal_insn_latency_func ();
+  output_maximal_insn_latency_func ();
   output_print_reservation_func ();
   /* Output function get_cpu_unit_code.  */
   fprintf (output_file, "\n#if %s\n\n", CPU_UNITS_QUERY_MACRO_NAME);
index 76282bd..2b5130c 100644 (file)
@@ -144,7 +144,9 @@ along with GCC; see the file COPYING3.  If not see
 #include "target.h"
 #include "output.h"
 #include "params.h"
+#include "vecprim.h"
 #include "dbgcnt.h"
+#include "cfgloop.h"
 
 #ifdef INSN_SCHEDULING
 
@@ -152,7 +154,7 @@ along with GCC; see the file COPYING3.  If not see
    machine cycle.  It can be defined in the config/mach/mach.h file,
    otherwise we set it to 1.  */
 
-static int issue_rate;
+int issue_rate;
 
 /* sched-verbose controls the amount of debugging output the
    scheduler prints.  It is controlled by -fsched-verbose=N:
@@ -170,9 +172,6 @@ int sched_verbose = 0;
    either to stderr, or to the dump listing file (-dRS).  */
 FILE *sched_dump = 0;
 
-/* Highest uid before scheduling.  */
-static int old_max_uid;
-
 /* fix_sched_param() is called from toplev.c upon detection
    of the -fsched-verbose=N option.  */
 
@@ -185,10 +184,12 @@ fix_sched_param (const char *param, const char *val)
     warning (0, "fix_sched_param: unknown param: %s", param);
 }
 
-struct haifa_insn_data *h_i_d;
+/* This is a placeholder for the scheduler parameters common 
+   to all schedulers.  */
+struct common_sched_info_def *common_sched_info;
 
-#define INSN_TICK(INSN)                (h_i_d[INSN_UID (INSN)].tick)
-#define INTER_TICK(INSN)        (h_i_d[INSN_UID (INSN)].inter_tick)
+#define INSN_TICK(INSN)        (HID (INSN)->tick)
+#define INTER_TICK(INSN) (HID (INSN)->inter_tick)
 
 /* If INSN_TICK of an instruction is equal to INVALID_TICK,
    then it should be recalculated from scratch.  */
@@ -202,12 +203,12 @@ struct haifa_insn_data *h_i_d;
 
 /* List of important notes we must keep around.  This is a pointer to the
    last element in the list.  */
-static rtx note_list;
+rtx note_list;
 
 static struct spec_info_def spec_info_var;
 /* Description of the speculative part of the scheduling.
    If NULL - no speculation.  */
-spec_info_t spec_info;
+spec_info_t spec_info = NULL;
 
 /* True, if recovery block was added during scheduling of current block.
    Used to determine, if we need to fix INSN_TICKs.  */
@@ -224,12 +225,16 @@ static int nr_begin_data, nr_be_in_data, nr_begin_control, nr_be_in_control;
 /* Array used in {unlink, restore}_bb_notes.  */
 static rtx *bb_header = 0;
 
-/* Number of basic_blocks.  */
-static int old_last_basic_block;
-
 /* Basic block after which recovery blocks will be created.  */
 static basic_block before_recovery;
 
+/* Basic block just before the EXIT_BLOCK and after recovery, if we have
+   created it.  */
+basic_block after_recovery;
+
+/* FALSE if we add bb to another region, so we don't need to initialize it.  */
+bool adding_bb_to_current_region_p = true;
+
 /* Queues, etc.  */
 
 /* An instruction is ready to be scheduled when all insns preceding it
@@ -290,7 +295,7 @@ static int q_size = 0;
    QUEUE_READY     - INSN is in ready list.
    N >= 0 - INSN queued for X [where NEXT_Q_AFTER (q_ptr, X) == N] cycles.  */
    
-#define QUEUE_INDEX(INSN) (h_i_d[INSN_UID (INSN)].queue_index)
+#define QUEUE_INDEX(INSN) (HID (INSN)->queue_index)
 
 /* The following variable value refers for all current and future
    reservations of the processor units.  */
@@ -298,37 +303,21 @@ state_t curr_state;
 
 /* The following variable value is size of memory representing all
    current and future reservations of the processor units.  */
-static size_t dfa_state_size;
+size_t dfa_state_size;
 
 /* The following array is used to find the best insn from ready when
    the automaton pipeline interface is used.  */
-static char *ready_try;
+char *ready_try = NULL;
 
-/* Describe the ready list of the scheduler.
-   VEC holds space enough for all insns in the current region.  VECLEN
-   says how many exactly.
-   FIRST is the index of the element with the highest priority; i.e. the
-   last one in the ready list, since elements are ordered by ascending
-   priority.
-   N_READY determines how many insns are on the ready list.  */
+/* The ready list.  */
+struct ready_list ready = {NULL, 0, 0, 0};
 
-struct ready_list
-{
-  rtx *vec;
-  int veclen;
-  int first;
-  int n_ready;
-};
-
-/* The pointer to the ready list.  */
-static struct ready_list *readyp;
+/* The pointer to the ready list (to be removed).  */
+static struct ready_list *readyp = &ready;
 
 /* Scheduling clock.  */
 static int clock_var;
 
-/* Number of instructions in current scheduling region.  */
-static int rgn_n_insns;
-
 static int may_trap_exp (const_rtx, int);
 
 /* Nonzero iff the address is comprised from at most 1 register.  */
@@ -342,6 +331,39 @@ static int may_trap_exp (const_rtx, int);
 /* Returns a class that insn with GET_DEST(insn)=x may belong to,
    as found by analyzing insn's expression.  */
 
+\f
+static int haifa_luid_for_non_insn (rtx x);
+
+/* Haifa version of sched_info hooks common to all headers.  */
+const struct common_sched_info_def haifa_common_sched_info = 
+  {
+    NULL, /* fix_recovery_cfg */
+    NULL, /* add_block */
+    NULL, /* estimate_number_of_insns */
+    haifa_luid_for_non_insn, /* luid_for_non_insn */
+    SCHED_PASS_UNKNOWN /* sched_pass_id */
+  };
+
+const struct sched_scan_info_def *sched_scan_info;
+
+/* Mapping from instruction UID to its Logical UID.  */
+VEC (int, heap) *sched_luids = NULL;
+
+/* Next LUID to assign to an instruction.  */
+int sched_max_luid = 1;
+
+/* Haifa Instruction Data.  */
+VEC (haifa_insn_data_def, heap) *h_i_d = NULL;
+
+void (* sched_init_only_bb) (basic_block, basic_block);
+
+/* Split block function.  Different schedulers might use different functions
+   to handle their internal data consistent.  */
+basic_block (* sched_split_block) (basic_block, rtx);
+
+/* Create empty basic block after the specified block.  */
+basic_block (* sched_create_empty_bb) (basic_block);
+
 static int
 may_trap_exp (const_rtx x, int is_store)
 {
@@ -478,10 +500,6 @@ haifa_classify_insn (const_rtx insn)
   return haifa_classify_rtx (PATTERN (insn));
 }
 
-
-/* A typedef for rtx vector.  */
-typedef VEC(rtx, heap) *rtx_vec_t;
-
 /* Forward declarations.  */
 
 static int priority (rtx);
@@ -490,10 +508,11 @@ static void swap_sort (rtx *, int);
 static void queue_insn (rtx, int);
 static int schedule_insn (rtx);
 static int find_set_reg_weight (const_rtx);
-static void find_insn_reg_weight (basic_block);
-static void find_insn_reg_weight1 (rtx);
+static void find_insn_reg_weight (const_rtx);
 static void adjust_priority (rtx);
 static void advance_one_cycle (void);
+static void extend_h_i_d (void);
+
 
 /* Notes handling mechanism:
    =========================
@@ -511,12 +530,7 @@ static void advance_one_cycle (void);
    unlink_other_notes ()).  After scheduling the block, these notes are
    inserted at the beginning of the block (in schedule_block()).  */
 
-static rtx unlink_other_notes (rtx, rtx);
-static void reemit_notes (rtx);
-
-static rtx *ready_lastpos (struct ready_list *);
 static void ready_add (struct ready_list *, rtx, bool);
-static void ready_sort (struct ready_list *);
 static rtx ready_remove_first (struct ready_list *);
 
 static void queue_to_ready (struct ready_list *);
@@ -524,14 +538,10 @@ static int early_queue_to_ready (state_t, struct ready_list *);
 
 static void debug_ready_list (struct ready_list *);
 
-static void move_insn (rtx);
-
 /* The following functions are used to implement multi-pass scheduling
    on the first cycle.  */
-static rtx ready_element (struct ready_list *, int);
 static rtx ready_remove (struct ready_list *, int);
 static void ready_remove_insn (rtx);
-static int max_issue (struct ready_list *, int *, int);
 
 static int choose_ready (struct ready_list *, rtx *);
 
@@ -543,23 +553,17 @@ static void change_queue_index (rtx, int);
    speculative instructions.  */
 
 static void extend_h_i_d (void);
-static void extend_ready (int);
 static void init_h_i_d (rtx);
 static void generate_recovery_code (rtx);
 static void process_insn_forw_deps_be_in_spec (rtx, rtx, ds_t);
 static void begin_speculative_block (rtx);
 static void add_to_speculative_block (rtx);
-static dw_t dep_weak (ds_t);
-static edge find_fallthru_edge (basic_block);
-static void init_before_recovery (void);
-static basic_block create_recovery_block (void);
+static void init_before_recovery (basic_block *);
 static void create_check_block_twin (rtx, bool);
 static void fix_recovery_deps (basic_block);
-static void change_pattern (rtx, rtx);
-static int speculate_insn (rtx, ds_t, rtx *);
+static void haifa_change_pattern (rtx, rtx);
 static void dump_new_block_header (int, basic_block, rtx, rtx);
 static void restore_bb_notes (basic_block);
-static void extend_bb (void);
 static void fix_jump_move (rtx);
 static void move_block_after_check (rtx);
 static void move_succs (VEC(edge,gc) **, basic_block);
@@ -575,7 +579,7 @@ static void check_cfg (rtx, rtx);
 #endif /* INSN_SCHEDULING */
 \f
 /* Point to state used for the current scheduling pass.  */
-struct sched_info *current_sched_info;
+struct haifa_sched_info *current_sched_info;
 \f
 #ifndef INSN_SCHEDULING
 void
@@ -584,9 +588,6 @@ schedule_insns (void)
 }
 #else
 
-/* Working copy of frontend's sched_info variable.  */
-static struct sched_info current_sched_info_var;
-
 /* Pointer to the last instruction scheduled.  Used by rank_for_schedule,
    so that insns independent of the last scheduled insn will be preferred
    over dependent instructions.  */
@@ -595,7 +596,7 @@ static rtx last_scheduled_insn;
 
 /* Cached cost of the instruction.  Use below function to get cost of the
    insn.  -1 here means that the field is not initialized.  */
-#define INSN_COST(INSN)                (h_i_d[INSN_UID (INSN)].cost)
+#define INSN_COST(INSN)        (HID (INSN)->cost)
 
 /* Compute cost of executing INSN.
    This is the number of cycles between instruction issue and
@@ -603,7 +604,21 @@ static rtx last_scheduled_insn;
 HAIFA_INLINE int
 insn_cost (rtx insn)
 {
-  int cost = INSN_COST (insn);
+  int cost;
+
+  if (sel_sched_p ())
+    {
+      if (recog_memoized (insn) < 0)
+       return 0;
+
+      cost = insn_default_latency (insn);
+      if (cost < 0)
+       cost = 0;
+
+      return cost;
+    }
+
+  cost = INSN_COST (insn);
 
   if (cost < 0)
     {
@@ -633,7 +648,7 @@ insn_cost (rtx insn)
    This is the number of cycles between instruction issue and
    instruction results.  */
 int
-dep_cost (dep_t link)
+dep_cost_1 (dep_t link, dw_t dw)
 {
   rtx used = DEP_CON (link);
   int cost;
@@ -664,8 +679,14 @@ dep_cost (dep_t link)
          else if (bypass_p (insn))
            cost = insn_latency (insn, used);
        }
+       
 
-      if (targetm.sched.adjust_cost != NULL)
+      if (targetm.sched.adjust_cost_2)
+       {
+         cost = targetm.sched.adjust_cost_2 (used, (int) dep_type, insn, cost,
+                                             dw);
+       }
+      else if (targetm.sched.adjust_cost != NULL)
        {
          /* This variable is used for backward compatibility with the
             targets.  */
@@ -691,6 +712,34 @@ dep_cost (dep_t link)
   return cost;
 }
 
+/* Compute cost of dependence LINK.
+   This is the number of cycles between instruction issue and
+   instruction results.  */
+int
+dep_cost (dep_t link)
+{
+  return dep_cost_1 (link, 0);
+}
+
+/* Use this sel-sched.c friendly function in reorder2 instead of increasing
+   INSN_PRIORITY explicitly.  */
+void
+increase_insn_priority (rtx insn, int amount)
+{
+  if (!sel_sched_p ())
+    {
+      /* We're dealing with haifa-sched.c INSN_PRIORITY.  */
+      if (INSN_PRIORITY_KNOWN (insn))
+         INSN_PRIORITY (insn) += amount;
+    }
+  else
+    {
+      /* In sel-sched.c INSN_PRIORITY is not kept up to date.  
+        Use EXPR_PRIORITY instead. */
+      sel_add_to_insn_priority (insn, amount);
+    }
+}
+
 /* Return 'true' if DEP should be included in priority calculations.  */
 static bool
 contributes_to_priority_p (dep_t dep)
@@ -706,7 +755,7 @@ contributes_to_priority_p (dep_t dep)
      their producers will increase, and, thus, the
      producers will more likely be scheduled, thus,
      resolving the dependence.  */
-  if ((current_sched_info->flags & DO_SPECULATION)
+  if (sched_deps_info->generate_spec_deps
       && !(spec_info->flags & COUNT_SPEC_IN_CRITICAL_PATH)
       && (DEP_STATUS (dep) & SPECULATIVE))
     return false;
@@ -726,7 +775,7 @@ priority (rtx insn)
 
   if (!INSN_PRIORITY_KNOWN (insn))
     {
-      int this_priority = 0;
+      int this_priority = -1;
 
       if (sd_lists_empty_p (insn, SD_LIST_FORW))
        /* ??? We should set INSN_PRIORITY to insn_cost when and insn has
@@ -745,7 +794,8 @@ priority (rtx insn)
             INSN_FORW_DEPS list of each instruction in the corresponding
             recovery block.  */ 
 
-         rec = RECOVERY_BLOCK (insn);
+          /* Selective scheduling does not define RECOVERY_BLOCK macro.  */
+         rec = sel_sched_p () ? NULL : RECOVERY_BLOCK (insn);
          if (!rec || rec == EXIT_BLOCK_PTR)
            {
              prev_first = PREV_INSN (insn);
@@ -798,6 +848,14 @@ priority (rtx insn)
            }
          while (twin != prev_first);
        }
+
+      if (this_priority < 0)
+       {
+         gcc_assert (this_priority == -1);
+
+         this_priority = insn_cost (insn);
+       }
+
       INSN_PRIORITY (insn) = this_priority;
       INSN_PRIORITY_STATUS (insn) = 1;
     }
@@ -849,13 +907,13 @@ rank_for_schedule (const void *x, const void *y)
 
       ds1 = TODO_SPEC (tmp) & SPECULATIVE;
       if (ds1)
-       dw1 = dep_weak (ds1);
+       dw1 = ds_weak (ds1);
       else
        dw1 = NO_DEP_WEAK;
       
       ds2 = TODO_SPEC (tmp2) & SPECULATIVE;
       if (ds2)
-       dw2 = dep_weak (ds2);
+       dw2 = ds_weak (ds2);
       else
        dw2 = NO_DEP_WEAK;
 
@@ -962,7 +1020,7 @@ queue_insn (rtx insn, int n_cycles)
 
       fprintf (sched_dump, "queued for %d cycles.\n", n_cycles);
     }
-  
+
   QUEUE_INDEX (insn) = next_q;
 }
 
@@ -979,7 +1037,7 @@ queue_remove (rtx insn)
 /* Return a pointer to the bottom of the ready list, i.e. the insn
    with the lowest priority.  */
 
-HAIFA_INLINE static rtx *
+rtx *
 ready_lastpos (struct ready_list *ready)
 {
   gcc_assert (ready->n_ready >= 1);
@@ -1052,7 +1110,7 @@ ready_remove_first (struct ready_list *ready)
    insn with the highest priority is 0, and the lowest priority has
    N_READY - 1.  */
 
-HAIFA_INLINE static rtx
+rtx
 ready_element (struct ready_list *ready, int index)
 {
   gcc_assert (ready->n_ready && index < ready->n_ready);
@@ -1099,7 +1157,7 @@ ready_remove_insn (rtx insn)
 /* Sort the ready list READY by ascending priority, using the SCHED_SORT
    macro.  */
 
-HAIFA_INLINE static void
+void
 ready_sort (struct ready_list *ready)
 {
   rtx *first = ready_lastpos (ready);
@@ -1125,27 +1183,36 @@ adjust_priority (rtx prev)
       targetm.sched.adjust_priority (prev, INSN_PRIORITY (prev));
 }
 
-/* Advance time on one cycle.  */
-HAIFA_INLINE static void
-advance_one_cycle (void)
+/* Advance DFA state STATE on one cycle.  */
+void
+advance_state (state_t state)
 {
   if (targetm.sched.dfa_pre_advance_cycle)
     targetm.sched.dfa_pre_advance_cycle ();
 
   if (targetm.sched.dfa_pre_cycle_insn)
-    state_transition (curr_state,
+    state_transition (state,
                      targetm.sched.dfa_pre_cycle_insn ());
 
-  state_transition (curr_state, NULL);
+  state_transition (state, NULL);
   
   if (targetm.sched.dfa_post_cycle_insn)
-    state_transition (curr_state,
+    state_transition (state,
                      targetm.sched.dfa_post_cycle_insn ());
 
   if (targetm.sched.dfa_post_advance_cycle)
     targetm.sched.dfa_post_advance_cycle ();
 }
 
+/* Advance time on one cycle.  */
+HAIFA_INLINE static void
+advance_one_cycle (void)
+{
+  advance_state (curr_state);
+  if (sched_verbose >= 6)
+    fprintf (sched_dump, "\n;;\tAdvanced a state.\n");
+}
+
 /* Clock at which the previous instruction was issued.  */
 static int last_clock_var;
 
@@ -1256,10 +1323,45 @@ schedule_insn (rtx insn)
 
 /* Functions for handling of notes.  */
 
+/* Insert the INSN note at the end of the notes list.  */
+static void 
+add_to_note_list (rtx insn, rtx *note_list_end_p)
+{
+  PREV_INSN (insn) = *note_list_end_p;
+  if (*note_list_end_p)
+    NEXT_INSN (*note_list_end_p) = insn;
+  *note_list_end_p = insn;
+}
+
+/* Add note list that ends on FROM_END to the end of TO_ENDP.  */
+void
+concat_note_lists (rtx from_end, rtx *to_endp)
+{
+  rtx from_start;
+
+  if (from_end == NULL)
+    /* It's easy when have nothing to concat.  */
+    return;
+
+  if (*to_endp == NULL)
+    /* It's also easy when destination is empty.  */
+    {
+      *to_endp = from_end;
+      return;
+    }
+
+  from_start = from_end;
+  /* A note list should be traversed via PREV_INSN.  */
+  while (PREV_INSN (from_start) != NULL) 
+    from_start = PREV_INSN (from_start);
+
+  add_to_note_list (from_start, to_endp);
+  *to_endp = from_end;
+}
+
 /* Delete notes beginning with INSN and put them in the chain
    of notes ended by NOTE_LIST.
    Returns the insn following the notes.  */
-
 static rtx
 unlink_other_notes (rtx insn, rtx tail)
 {
@@ -1290,22 +1392,22 @@ unlink_other_notes (rtx insn, rtx tail)
       /* See sched_analyze to see how these are handled.  */
       if (NOTE_KIND (insn) != NOTE_INSN_EH_REGION_BEG
          && NOTE_KIND (insn) != NOTE_INSN_EH_REGION_END)
-       {
-         /* Insert the note at the end of the notes list.  */
-         PREV_INSN (insn) = note_list;
-         if (note_list)
-           NEXT_INSN (note_list) = insn;
-         note_list = insn;
-       }
+        add_to_note_list (insn, &note_list);
 
       insn = next;
     }
+
+  if (insn == tail)
+    {
+      gcc_assert (sel_sched_p ());
+      return prev;
+    }
+
   return insn;
 }
 
 /* Return the head and tail pointers of ebb starting at BEG and ending
    at END.  */
-
 void
 get_ebb_head_tail (basic_block beg, basic_block end, rtx *headp, rtx *tailp)
 {
@@ -1358,8 +1460,7 @@ no_real_insns_p (const_rtx head, const_rtx tail)
 
 /* Delete notes between HEAD and TAIL and put them in the chain
    of notes ended by NOTE_LIST.  */
-
-void
+static void
 rm_other_notes (rtx head, rtx tail)
 {
   rtx next_tail;
@@ -1380,12 +1481,73 @@ rm_other_notes (rtx head, rtx tail)
       if (NOTE_NOT_BB_P (insn))
        {
          prev = insn;
-
          insn = unlink_other_notes (insn, next_tail);
 
-         gcc_assert (prev != tail && prev != head && insn != next_tail);
+         gcc_assert ((sel_sched_p ()
+                      || prev != tail) && prev != head && insn != next_tail);
+       }
+    }
+}
+
+/* Same as above, but also process REG_SAVE_NOTEs of HEAD.  */
+void
+remove_notes (rtx head, rtx tail)
+{
+  /* rm_other_notes only removes notes which are _inside_ the
+     block---that is, it won't remove notes before the first real insn
+     or after the last real insn of the block.  So if the first insn
+     has a REG_SAVE_NOTE which would otherwise be emitted before the
+     insn, it is redundant with the note before the start of the
+     block, and so we have to take it out.  */
+  if (INSN_P (head))
+    {
+      rtx note;
+
+      for (note = REG_NOTES (head); note; note = XEXP (note, 1))
+       if (REG_NOTE_KIND (note) == REG_SAVE_NOTE)
+         remove_note (head, note);
+    }
+
+  /* Remove remaining note insns from the block, save them in
+     note_list.  These notes are restored at the end of
+     schedule_block ().  */
+  rm_other_notes (head, tail);
+}
+
+/* Restore-other-notes: NOTE_LIST is the end of a chain of notes
+   previously found among the insns.  Insert them just before HEAD.  */
+rtx
+restore_other_notes (rtx head, basic_block head_bb)
+{
+  if (note_list != 0)
+    {
+      rtx note_head = note_list;
+
+      if (head)
+       head_bb = BLOCK_FOR_INSN (head);
+      else
+       head = NEXT_INSN (bb_note (head_bb));
+
+      while (PREV_INSN (note_head))
+       {
+         set_block_for_insn (note_head, head_bb);
+         note_head = PREV_INSN (note_head);
        }
+      /* In the above cycle we've missed this note.  */
+      set_block_for_insn (note_head, head_bb);
+
+      PREV_INSN (note_head) = PREV_INSN (head);
+      NEXT_INSN (PREV_INSN (head)) = note_head;
+      PREV_INSN (head) = note_list;
+      NEXT_INSN (note_list) = head;
+
+      if (BLOCK_FOR_INSN (head) != head_bb)
+       BB_END (head_bb) = note_list;
+
+      head = note_head;
     }
+
+  return head;
 }
 
 /* Functions for computation of registers live/usage info.  */
@@ -1393,7 +1555,6 @@ rm_other_notes (rtx head, rtx tail)
 /* This function looks for a new register being defined.
    If the destination register is already used by the source,
    a new register is not needed.  */
-
 static int
 find_set_reg_weight (const_rtx x)
 {
@@ -1415,25 +1576,9 @@ find_set_reg_weight (const_rtx x)
   return 0;
 }
 
-/* Calculate INSN_REG_WEIGHT for all insns of a block.  */
-
-static void
-find_insn_reg_weight (basic_block bb)
-{
-  rtx insn, next_tail, head, tail;
-
-  get_ebb_head_tail (bb, bb, &head, &tail);
-  next_tail = NEXT_INSN (tail);
-
-  for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
-    find_insn_reg_weight1 (insn);    
-}
-
-/* Calculate INSN_REG_WEIGHT for single instruction.
-   Separated from find_insn_reg_weight because of need
-   to initialize new instruction in generate_recovery_code.  */
+/* Calculate INSN_REG_WEIGHT for INSN.  */
 static void
-find_insn_reg_weight1 (rtx insn)
+find_insn_reg_weight (const_rtx insn)
 {
   int reg_weight = 0;
   rtx x;
@@ -1739,8 +1884,7 @@ debug_ready_list (struct ready_list *ready)
    NOTEs.  The REG_SAVE_NOTE note following first one is contains the
    saved value for NOTE_BLOCK_NUMBER which is useful for
    NOTE_INSN_EH_REGION_{BEG,END} NOTEs.  */
-
-static void
+void
 reemit_notes (rtx insn)
 {
   rtx note, last = insn;
@@ -1759,10 +1903,8 @@ reemit_notes (rtx insn)
 
 /* Move INSN.  Reemit notes if needed.  Update CFG, if needed.  */
 static void
-move_insn (rtx insn)
+move_insn (rtx insn, rtx last, rtx nt)
 {
-  rtx last = last_scheduled_insn;
-
   if (PREV_INSN (insn) != last)
     {
       basic_block bb;
@@ -1782,9 +1924,10 @@ move_insn (rtx insn)
          jump_p = control_flow_insn_p (insn);
 
          gcc_assert (!jump_p
-                     || ((current_sched_info->flags & SCHED_RGN)
+                     || ((common_sched_info->sched_pass_id == SCHED_RGN_PASS)
                          && IS_SPECULATION_BRANCHY_CHECK_P (insn))
-                     || (current_sched_info->flags & SCHED_EBB));
+                     || (common_sched_info->sched_pass_id
+                         == SCHED_EBB_PASS));
          
          gcc_assert (BLOCK_FOR_INSN (PREV_INSN (insn)) == bb);
 
@@ -1796,8 +1939,7 @@ move_insn (rtx insn)
       if (jump_p)
        /* We move the block note along with jump.  */
        {
-         /* NT is needed for assertion below.  */
-         rtx nt = current_sched_info->next_tail;
+         gcc_assert (nt);
 
          note = NEXT_INSN (insn);
          while (NOTE_NOT_BB_P (note) && note != nt)
@@ -1840,8 +1982,6 @@ move_insn (rtx insn)
       if (BB_END (bb) == last)
        BB_END (bb) = insn;  
     }
-  
-  reemit_notes (insn);
 
   SCHED_GROUP_P (insn) = 0;  
 }
@@ -1866,7 +2006,10 @@ static struct choice_entry *choice_stack;
 /* The following variable value is number of essential insns issued on
    the current cycle.  An insn is essential one if it changes the
    processors state.  */
-static int cycle_issued_insns;
+int cycle_issued_insns;
+
+/* This holds the value of the target dfa_lookahead hook.  */
+int dfa_lookahead;
 
 /* The following variable value is maximal number of tries of issuing
    insns for the first cycle multipass insn scheduling.  We define
@@ -1897,43 +2040,113 @@ static int cached_issue_rate = 0;
    of all instructions in READY.  The function stops immediately,
    if it reached the such a solution, that all instruction can be issued.
    INDEX will contain index of the best insn in READY.  The following
-   function is used only for first cycle multipass scheduling.  */
-static int
-max_issue (struct ready_list *ready, int *index, int max_points)
+   function is used only for first cycle multipass scheduling.
+
+   PRIVILEGED_N >= 0
+
+   This function expects recognized insns only.  All USEs,
+   CLOBBERs, etc must be filtered elsewhere.  */
+int
+max_issue (struct ready_list *ready, int privileged_n, state_t state,
+          int *index)
 {
-  int n, i, all, n_ready, best, delay, tries_num, points = -1;
+  int n, i, all, n_ready, best, delay, tries_num, points = -1, max_points;
+  int more_issue;
   struct choice_entry *top;
   rtx insn;
 
+  n_ready = ready->n_ready;
+  gcc_assert (dfa_lookahead >= 1 && privileged_n >= 0
+             && privileged_n <= n_ready);
+
+  /* Init MAX_LOOKAHEAD_TRIES.  */
+  if (cached_first_cycle_multipass_dfa_lookahead != dfa_lookahead)
+    {
+      cached_first_cycle_multipass_dfa_lookahead = dfa_lookahead;
+      max_lookahead_tries = 100;
+      for (i = 0; i < issue_rate; i++)
+       max_lookahead_tries *= dfa_lookahead;
+    }
+
+  /* Init max_points.  */
+  max_points = 0;
+  more_issue = issue_rate - cycle_issued_insns;
+  gcc_assert (more_issue >= 0);
+
+  for (i = 0; i < n_ready; i++)
+    if (!ready_try [i])
+      {
+       if (more_issue-- > 0)
+         max_points += ISSUE_POINTS (ready_element (ready, i));
+       else
+         break;
+      }
+
+  /* The number of the issued insns in the best solution.  */
   best = 0;
-  memcpy (choice_stack->state, curr_state, dfa_state_size);
+
   top = choice_stack;
-  top->rest = cached_first_cycle_multipass_dfa_lookahead;
+
+  /* Set initial state of the search.  */
+  memcpy (top->state, state, dfa_state_size);
+  top->rest = dfa_lookahead;
   top->n = 0;
-  n_ready = ready->n_ready;
+
+  /* Count the number of the insns to search among.  */
   for (all = i = 0; i < n_ready; i++)
     if (!ready_try [i])
       all++;
+
+  /* I is the index of the insn to try next.  */
   i = 0;
   tries_num = 0;
   for (;;)
     {
-      if (top->rest == 0 || i >= n_ready)
+      if (/* If we've reached a dead end or searched enough of what we have
+            been asked...  */
+         top->rest == 0
+         /* Or have nothing else to try.  */
+         || i >= n_ready)
        {
+         /* ??? (... || i == n_ready).  */
+         gcc_assert (i <= n_ready);
+
          if (top == choice_stack)
            break;
-         if (best < top - choice_stack && ready_try [0])
+
+         if (best < top - choice_stack)
            {
-             best = top - choice_stack;
-             *index = choice_stack [1].index;
-             points = top->n;
-             if (top->n == max_points || best == all)
-               break;
+             if (privileged_n)
+               {
+                 n = privileged_n;
+                 /* Try to find issued privileged insn.  */
+                 while (n && !ready_try[--n]);
+               }
+
+             if (/* If all insns are equally good...  */
+                 privileged_n == 0
+                 /* Or a privileged insn will be issued.  */
+                 || ready_try[n])
+               /* Then we have a solution.  */
+               {
+                 best = top - choice_stack;
+                 /* This is the index of the insn issued first in this
+                    solution.  */
+                 *index = choice_stack [1].index;
+                 points = top->n;
+                 if (top->n == max_points || best == all)
+                   break;
+               }
            }
+
+         /* Set ready-list index to point to the last insn
+            ('i++' below will advance it to the next insn).  */
          i = top->index;
+
+         /* Backtrack.  */
          ready_try [i] = 0;
          top--;
-         memcpy (curr_state, top->state, dfa_state_size);
+         memcpy (state, top->state, dfa_state_size);
        }
       else if (!ready_try [i])
        {
@@ -1941,45 +2154,43 @@ max_issue (struct ready_list *ready, int *index, int max_points)
          if (tries_num > max_lookahead_tries)
            break;
          insn = ready_element (ready, i);
-         delay = state_transition (curr_state, insn);
+         delay = state_transition (state, insn);
          if (delay < 0)
            {
-             if (state_dead_lock_p (curr_state))
+             if (state_dead_lock_p (state))
                top->rest = 0;
              else
                top->rest--;
+
              n = top->n;
-             if (memcmp (top->state, curr_state, dfa_state_size) != 0)
+             if (memcmp (top->state, state, dfa_state_size) != 0)
                n += ISSUE_POINTS (insn);
+
+             /* Advance to the next choice_entry.  */
              top++;
-             top->rest = cached_first_cycle_multipass_dfa_lookahead;
+             /* Initialize it.  */
+             top->rest = dfa_lookahead;
              top->index = i;
              top->n = n;
-             memcpy (top->state, curr_state, dfa_state_size);
+             memcpy (top->state, state, dfa_state_size);
+
              ready_try [i] = 1;
              i = -1;
            }
        }
+
+      /* Increase ready-list index.  */
       i++;
     }
-  while (top != choice_stack)
-    {
-      ready_try [top->index] = 0;
-      top--;
-    }
-  memcpy (curr_state, choice_stack->state, dfa_state_size);  
 
-  if (sched_verbose >= 4)    
-    fprintf (sched_dump, ";;\t\tChoosed insn : %s; points: %d/%d\n",
-            (*current_sched_info->print_insn) (ready_element (ready, *index),
-                                               0), 
-            points, max_points);
-  
+  /* Restore the original state of the DFA.  */
+  memcpy (state, choice_stack->state, dfa_state_size);  
+
   return best;
 }
 
 /* The following function chooses insn from READY and modifies
-   *N_READY and READY.  The following function is used only for first
+   READY.  The following function is used only for first
    cycle multipass scheduling.
    Return:
    -1 if cycle should be advanced,
@@ -2022,15 +2233,9 @@ choose_ready (struct ready_list *ready, rtx *insn_ptr)
       /* Try to choose the better insn.  */
       int index = 0, i, n;
       rtx insn;
-      int more_issue, max_points, try_data = 1, try_control = 1;
+      int try_data = 1, try_control = 1;
+      ds_t ts;
       
-      if (cached_first_cycle_multipass_dfa_lookahead != lookahead)
-       {
-         cached_first_cycle_multipass_dfa_lookahead = lookahead;
-         max_lookahead_tries = 100;
-         for (i = 0; i < issue_rate; i++)
-           max_lookahead_tries *= lookahead;
-       }
       insn = ready_element (ready, 0);
       if (INSN_CODE (insn) < 0)
        {
@@ -2069,11 +2274,13 @@ choose_ready (struct ready_list *ready, rtx *insn_ptr)
            }
        }
 
-      if ((!try_data && (TODO_SPEC (insn) & DATA_SPEC))
-         || (!try_control && (TODO_SPEC (insn) & CONTROL_SPEC))
-         || (targetm.sched.first_cycle_multipass_dfa_lookahead_guard_spec
-             && !targetm.sched.first_cycle_multipass_dfa_lookahead_guard_spec
-             (insn)))
+      ts = TODO_SPEC (insn);
+      if ((ts & SPECULATIVE)
+         && (((!try_data && (ts & DATA_SPEC))
+              || (!try_control && (ts & CONTROL_SPEC)))
+             || (targetm.sched.first_cycle_multipass_dfa_lookahead_guard_spec
+                 && !targetm.sched
+                 .first_cycle_multipass_dfa_lookahead_guard_spec (insn))))
        /* Discard speculative instruction that stands first in the ready
           list.  */
        {
@@ -2081,31 +2288,49 @@ choose_ready (struct ready_list *ready, rtx *insn_ptr)
          return 1;
        }
 
-      max_points = ISSUE_POINTS (insn);
-      more_issue = issue_rate - cycle_issued_insns - 1;
+      ready_try[0] = 0;
 
       for (i = 1; i < ready->n_ready; i++)
        {
          insn = ready_element (ready, i);
+
          ready_try [i]
-           = (INSN_CODE (insn) < 0
-               || (!try_data && (TODO_SPEC (insn) & DATA_SPEC))
-               || (!try_control && (TODO_SPEC (insn) & CONTROL_SPEC))
-              || (targetm.sched.first_cycle_multipass_dfa_lookahead_guard
-                  && !targetm.sched.first_cycle_multipass_dfa_lookahead_guard
-                  (insn)));
-
-         if (!ready_try [i] && more_issue-- > 0)
-           max_points += ISSUE_POINTS (insn);
+           = ((!try_data && (TODO_SPEC (insn) & DATA_SPEC))
+               || (!try_control && (TODO_SPEC (insn) & CONTROL_SPEC)));
        }
 
-      if (max_issue (ready, &index, max_points) == 0)
+      /* Let the target filter the search space.  */
+      for (i = 1; i < ready->n_ready; i++)
+       if (!ready_try[i])
+         {
+           insn = ready_element (ready, i);
+
+           gcc_assert (INSN_CODE (insn) >= 0
+                       || recog_memoized (insn) < 0);
+
+           ready_try [i]
+             = (/* INSN_CODE check can be omitted here as it is also done later
+                   in max_issue ().  */
+                INSN_CODE (insn) < 0
+                || (targetm.sched.first_cycle_multipass_dfa_lookahead_guard
+                    && !targetm.sched.first_cycle_multipass_dfa_lookahead_guard
+                    (insn)));
+         }
+
+      if (max_issue (ready, 1, curr_state, &index) == 0)
        {
+         if (sched_verbose >= 4)
+           fprintf (sched_dump, ";;\t\tChosen none\n");
          *insn_ptr = ready_remove_first (ready);
          return 0;
        }
       else
        {
+         if (sched_verbose >= 4)    
+           fprintf (sched_dump, ";;\t\tChosen insn : %s\n",
+                    (*current_sched_info->print_insn)
+                    (ready_element (ready, index), 0));
+          
          *insn_ptr = ready_remove (ready, index);
          return 0;
        }
@@ -2117,9 +2342,8 @@ choose_ready (struct ready_list *ready, rtx *insn_ptr)
    region.  */
 
 void
-schedule_block (basic_block *target_bb, int rgn_n_insns1)
+schedule_block (basic_block *target_bb)
 {
-  struct ready_list ready;
   int i, first_cycle_insn_p;
   int can_issue_more;
   state_t temp_state = NULL;  /* It is used for multipass scheduling.  */
@@ -2148,15 +2372,7 @@ schedule_block (basic_block *target_bb, int rgn_n_insns1)
 
   state_reset (curr_state);
 
-  /* Allocate the ready list.  */
-  readyp = &ready;
-  ready.vec = NULL;
-  ready_try = NULL;
-  choice_stack = NULL;
-
-  rgn_n_insns = -1;
-  extend_ready (rgn_n_insns1 + 1);
-
+  /* Clear the ready list.  */
   ready.first = ready.veclen - 1;
   ready.n_ready = 0;
 
@@ -2443,7 +2659,8 @@ schedule_block (basic_block *target_bb, int rgn_n_insns1)
          (*current_sched_info->begin_schedule_ready) (insn,
                                                       last_scheduled_insn);
  
-         move_insn (insn);
+         move_insn (insn, last_scheduled_insn, current_sched_info->next_tail);
+         reemit_notes (insn);
          last_scheduled_insn = insn;
          
          if (memcmp (curr_state, temp_state, dfa_state_size) != 0)
@@ -2530,6 +2747,9 @@ schedule_block (basic_block *target_bb, int rgn_n_insns1)
          }
     }
 
+  if (sched_verbose)
+    fprintf (sched_dump, ";;   total time = %d\n", clock_var);
+
   if (!current_sched_info->queue_must_finish_empty
       || haifa_recovery_bb_recently_added_p)
     {
@@ -2545,59 +2765,25 @@ schedule_block (basic_block *target_bb, int rgn_n_insns1)
   if (targetm.sched.md_finish)
     {
       targetm.sched.md_finish (sched_dump, sched_verbose);
-
       /* Target might have added some instructions to the scheduled block
         in its md_finish () hook.  These new insns don't have any data
         initialized and to identify them we extend h_i_d so that they'll
-        get zero luids.*/
-      extend_h_i_d ();
+        get zero luids.  */
+      sched_init_luids (NULL, NULL, NULL, NULL);
     }
 
+  if (sched_verbose)
+    fprintf (sched_dump, ";;   new head = %d\n;;   new tail = %d\n\n",
+            INSN_UID (head), INSN_UID (tail));
+
   /* Update head/tail boundaries.  */
   head = NEXT_INSN (prev_head);
   tail = last_scheduled_insn;
 
-  /* Restore-other-notes: NOTE_LIST is the end of a chain of notes
-     previously found among the insns.  Insert them at the beginning
-     of the insns.  */
-  if (note_list != 0)
-    {
-      basic_block head_bb = BLOCK_FOR_INSN (head);
-      rtx note_head = note_list;
-
-      while (PREV_INSN (note_head))
-       {
-         set_block_for_insn (note_head, head_bb);
-         note_head = PREV_INSN (note_head);
-       }
-      /* In the above cycle we've missed this note:  */
-      set_block_for_insn (note_head, head_bb);
-
-      PREV_INSN (note_head) = PREV_INSN (head);
-      NEXT_INSN (PREV_INSN (head)) = note_head;
-      PREV_INSN (head) = note_list;
-      NEXT_INSN (note_list) = head;
-      head = note_head;
-    }
-
-  /* Debugging.  */
-  if (sched_verbose)
-    {
-      fprintf (sched_dump, ";;   total time = %d\n;;   new head = %d\n",
-              clock_var, INSN_UID (head));
-      fprintf (sched_dump, ";;   new tail = %d\n\n",
-              INSN_UID (tail));
-    }
+  head = restore_other_notes (head, NULL);
 
   current_sched_info->head = head;
   current_sched_info->tail = tail;
-
-  free (ready.vec);
-
-  free (ready_try);
-  for (i = 0; i <= rgn_n_insns; i++)
-    free (choice_stack [i].state);
-  free (choice_stack);
 }
 \f
 /* Set_priorities: compute priority of each insn in the block.  */
@@ -2636,48 +2822,49 @@ set_priorities (rtx head, rtx tail)
   return n_insn;
 }
 
-/* Next LUID to assign to an instruction.  */
-static int luid;
+/* Set dump and sched_verbose for the desired debugging output.  If no
+   dump-file was specified, but -fsched-verbose=N (any N), print to stderr.
+   For -fsched-verbose=N, N>=10, print everything to stderr.  */
+void
+setup_sched_dump (void)
+{
+  sched_verbose = sched_verbose_param;
+  if (sched_verbose_param == 0 && dump_file)
+    sched_verbose = 1;
+  sched_dump = ((sched_verbose_param >= 10 || !dump_file)
+               ? stderr : dump_file);
+}
 
-/* Initialize some global state for the scheduler.  */
+/* Initialize some global state for the scheduler.  This function works 
+   with the common data shared between all the schedulers.  It is called
+   from the scheduler specific initialization routine.  */
 
 void
 sched_init (void)
 {
-  basic_block b;
-  rtx insn;
-  int i;
-
-  /* Switch to working copy of sched_info.  */
-  memcpy (&current_sched_info_var, current_sched_info,
-         sizeof (current_sched_info_var));
-  current_sched_info = &current_sched_info_var;
-      
   /* Disable speculative loads in their presence if cc0 defined.  */
 #ifdef HAVE_cc0
   flag_schedule_speculative_load = 0;
 #endif
 
-  /* Set dump and sched_verbose for the desired debugging output.  If no
-     dump-file was specified, but -fsched-verbose=N (any N), print to stderr.
-     For -fsched-verbose=N, N>=10, print everything to stderr.  */
-  sched_verbose = sched_verbose_param;
-  if (sched_verbose_param == 0 && dump_file)
-    sched_verbose = 1;
-  sched_dump = ((sched_verbose_param >= 10 || !dump_file)
-               ? stderr : dump_file);
-
   /* Initialize SPEC_INFO.  */
   if (targetm.sched.set_sched_flags)
     {
       spec_info = &spec_info_var;
       targetm.sched.set_sched_flags (spec_info);
-      if (current_sched_info->flags & DO_SPECULATION)
-       spec_info->weakness_cutoff =
-         (PARAM_VALUE (PARAM_SCHED_SPEC_PROB_CUTOFF) * MAX_DEP_WEAK) / 100;
+
+      if (spec_info->mask != 0)
+        {
+          spec_info->data_weakness_cutoff =
+            (PARAM_VALUE (PARAM_SCHED_SPEC_PROB_CUTOFF) * MAX_DEP_WEAK) / 100;
+          spec_info->control_weakness_cutoff =
+            (PARAM_VALUE (PARAM_SCHED_SPEC_PROB_CUTOFF)
+             * REG_BR_PROB_BASE) / 100;
+        }
       else
        /* So we won't read anything accidentally.  */
-       spec_info = 0;
+       spec_info = NULL;
+
     }
   else
     /* So we won't read anything accidentally.  */
@@ -2696,18 +2883,10 @@ sched_init (void)
       cached_first_cycle_multipass_dfa_lookahead = 0;
     }
 
-  old_max_uid = 0;
-  h_i_d = 0;
-  extend_h_i_d ();
-
-  for (i = 0; i < old_max_uid; i++)
-    {
-      h_i_d[i].cost = -1;
-      h_i_d[i].todo_spec = HARD_DEP;
-      h_i_d[i].queue_index = QUEUE_NOWHERE;
-      h_i_d[i].tick = INVALID_TICK;
-      h_i_d[i].inter_tick = INVALID_TICK;
-    }
+  if (targetm.sched.first_cycle_multipass_dfa_lookahead)
+    dfa_lookahead = targetm.sched.first_cycle_multipass_dfa_lookahead ();
+  else
+    dfa_lookahead = 0;
 
   if (targetm.sched.init_dfa_pre_cycle_insn)
     targetm.sched.init_dfa_pre_cycle_insn ();
@@ -2717,67 +2896,93 @@ sched_init (void)
 
   dfa_start ();
   dfa_state_size = state_size ();
-  curr_state = xmalloc (dfa_state_size);
 
-  h_i_d[0].luid = 0;
-  luid = 1;
-  FOR_EACH_BB (b)
-    for (insn = BB_HEAD (b); ; insn = NEXT_INSN (insn))
-      {
-       INSN_LUID (insn) = luid;
+  init_alias_analysis ();
 
-       /* Increment the next luid, unless this is a note.  We don't
-          really need separate IDs for notes and we don't want to
-          schedule differently depending on whether or not there are
-          line-number notes, i.e., depending on whether or not we're
-          generating debugging information.  */
-       if (!NOTE_P (insn))
-         ++luid;
+  df_set_flags (DF_LR_RUN_DCE);
+  df_note_add_problem ();
 
-       if (insn == BB_END (b))
-         break;
-      }
+  /* More problems needed for interloop dep calculation in SMS.  */
+  if (common_sched_info->sched_pass_id == SCHED_SMS_PASS)
+    {
+      df_rd_add_problem ();
+      df_chain_add_problem (DF_DU_CHAIN + DF_UD_CHAIN);
+    }
 
-  init_dependency_caches (luid);
+  df_analyze ();
+  
+  /* Do not run DCE after reload, as this can kill nops inserted 
+     by bundling.  */
+  if (reload_completed)
+    df_clear_flags (DF_LR_RUN_DCE);
 
-  init_alias_analysis ();
+  regstat_compute_calls_crossed ();
 
-  old_last_basic_block = 0;
-  extend_bb ();
+  if (targetm.sched.md_init_global)
+    targetm.sched.md_init_global (sched_dump, sched_verbose,
+                                 get_max_uid () + 1);
 
-  /* Compute INSN_REG_WEIGHT for all blocks.  We must do this before
-     removing death notes.  */
-  FOR_EACH_BB_REVERSE (b)
-    find_insn_reg_weight (b);
+  curr_state = xmalloc (dfa_state_size);
+}
 
-  if (targetm.sched.md_init_global)
-      targetm.sched.md_init_global (sched_dump, sched_verbose, old_max_uid);
+static void haifa_init_only_bb (basic_block, basic_block);
 
-  nr_begin_data = nr_begin_control = nr_be_in_data = nr_be_in_control = 0;
-  before_recovery = 0;
+/* Initialize data structures specific to the Haifa scheduler.  */
+void
+haifa_sched_init (void)
+{
+  setup_sched_dump ();
+  sched_init ();
+
+  if (spec_info != NULL)
+    {
+      sched_deps_info->use_deps_list = 1;
+      sched_deps_info->generate_spec_deps = 1;
+    }
+
+  /* Initialize luids, dependency caches, target and h_i_d for the
+     whole function.  */
+  {
+    bb_vec_t bbs = VEC_alloc (basic_block, heap, n_basic_blocks);
+    basic_block bb;
 
+    sched_init_bbs ();
+
+    FOR_EACH_BB (bb)
+      VEC_quick_push (basic_block, bbs, bb);
+    sched_init_luids (bbs, NULL, NULL, NULL);
+    sched_deps_init (true);
+    sched_extend_target ();
+    haifa_init_h_i_d (bbs, NULL, NULL, NULL);
+
+    VEC_free (basic_block, heap, bbs);
+  }
+
+  sched_init_only_bb = haifa_init_only_bb;
+  sched_split_block = sched_split_block_1;
+  sched_create_empty_bb = sched_create_empty_bb_1;
   haifa_recovery_bb_ever_added_p = false;
 
 #ifdef ENABLE_CHECKING
-  /* This is used preferably for finding bugs in check_cfg () itself.  */
+  /* This is used preferably for finding bugs in check_cfg () itself.
+     We must call sched_bbs_init () before check_cfg () because check_cfg ()
+     assumes that the last insn in the last bb has a non-null successor.  */
   check_cfg (0, 0);
 #endif
-}
 
-/* Free global data used during insn scheduling.  */
+  nr_begin_data = nr_begin_control = nr_be_in_data = nr_be_in_control = 0;
+  before_recovery = 0;
+  after_recovery = 0;
+}
 
+/* Finish work with the data specific to the Haifa scheduler.  */
 void
-sched_finish (void)
+haifa_sched_finish (void)
 {
-  free (h_i_d);
-  free (curr_state);
-  dfa_finish ();
-  free_dependency_caches ();
-  end_alias_analysis ();
+  sched_create_empty_bb = NULL;
+  sched_split_block = NULL;
+  sched_init_only_bb = NULL;
 
-  if (targetm.sched.md_finish_global)
-    targetm.sched.md_finish_global (sched_dump, sched_verbose);
-  
   if (spec_info && spec_info->dump)
     {
       char c = reload_completed ? 'a' : 'b';
@@ -2799,13 +3004,37 @@ sched_finish (void)
                c, nr_be_in_control);
     }
 
+  /* Finalize h_i_d, dependency caches, and luids for the whole
+     function.  Target will be finalized in md_global_finish ().  */
+  sched_deps_finish ();
+  sched_finish_luids ();
+  current_sched_info = NULL;
+  sched_finish ();
+}
+
+/* Free global data used during insn scheduling.  This function works with 
+   the common data shared between the schedulers.  */
+
+void
+sched_finish (void)
+{
+  haifa_finish_h_i_d ();
+  free (curr_state);
+
+  if (targetm.sched.md_finish_global)
+    targetm.sched.md_finish_global (sched_dump, sched_verbose);
+
+  end_alias_analysis ();
+
+  regstat_free_calls_crossed ();
+
+  dfa_finish ();
+
 #ifdef ENABLE_CHECKING
   /* After reload ia64 backend clobbers CFG, so can't check anything.  */
   if (!reload_completed)
     check_cfg (0, 0);
 #endif
-
-  current_sched_info = NULL;
 }
 
 /* Fix INSN_TICKs of the instructions in the current block as well as
@@ -2881,6 +3110,8 @@ fix_inter_tick (rtx head, rtx tail)
     }
   bitmap_clear (&processed);
 }
+
+static int haifa_speculate_insn (rtx, ds_t, rtx *);
   
 /* Check if NEXT is ready to be added to the ready or queue list.
    If "yes", add it to the proper list.
@@ -2940,7 +3171,7 @@ try_ready (rtx next)
                *ts = ds_merge (*ts, ds);
            }
 
-         if (dep_weak (*ts) < spec_info->weakness_cutoff)
+         if (ds_weak (*ts) < spec_info->data_weakness_cutoff)
            /* Too few points.  */
            *ts = (*ts & ~SPECULATIVE) | HARD_DEP;
        }
@@ -2974,7 +3205,7 @@ try_ready (rtx next)
       
       gcc_assert ((*ts & SPECULATIVE) && !(*ts & ~SPECULATIVE));
       
-      res = speculate_insn (next, *ts, &new_pat);
+      res = haifa_speculate_insn (next, *ts, &new_pat);
        
       switch (res)
        {
@@ -2998,7 +3229,7 @@ try_ready (rtx next)
               save it.  */
            ORIG_PAT (next) = PATTERN (next);
          
-         change_pattern (next, new_pat);
+         haifa_change_pattern (next, new_pat);
          break;
          
        default:
@@ -3029,7 +3260,7 @@ try_ready (rtx next)
        ORIG_PAT field.  Except one case - speculation checks have ORIG_PAT
        pat too, so skip them.  */
     {
-      change_pattern (next, ORIG_PAT (next));
+      haifa_change_pattern (next, ORIG_PAT (next));
       ORIG_PAT (next) = 0;
     }
 
@@ -3148,98 +3379,70 @@ change_queue_index (rtx next, int delay)
     }
 }
 
-/* Extend H_I_D data.  */
-static void
-extend_h_i_d (void)
-{
-  /* We use LUID 0 for the fake insn (UID 0) which holds dependencies for
-     pseudos which do not cross calls.  */
-  int new_max_uid = get_max_uid () + 1;  
-
-  h_i_d = (struct haifa_insn_data *)
-    xrecalloc (h_i_d, new_max_uid, old_max_uid, sizeof (*h_i_d));
-  old_max_uid = new_max_uid;
-
-  if (targetm.sched.h_i_d_extended)
-    targetm.sched.h_i_d_extended ();
-}
+static int sched_ready_n_insns = -1;
 
-/* Extend READY, READY_TRY and CHOICE_STACK arrays.
-   N_NEW_INSNS is the number of additional elements to allocate.  */
-static void
-extend_ready (int n_new_insns)
+/* Initialize per region data structures.  */
+void
+sched_extend_ready_list (int new_sched_ready_n_insns)
 {
   int i;
 
-  readyp->veclen = rgn_n_insns + n_new_insns + 1 + issue_rate;
-  readyp->vec = XRESIZEVEC (rtx, readyp->vec, readyp->veclen);
-  ready_try = (char *) xrecalloc (ready_try, rgn_n_insns + n_new_insns + 1,
-                                 rgn_n_insns + 1, sizeof (char));
+  if (sched_ready_n_insns == -1)
+    /* At the first call we need to initialize one more choice_stack
+       entry.  */
+    {
+      i = 0;
+      sched_ready_n_insns = 0;
+    }
+  else
+    i = sched_ready_n_insns + 1;
 
-  rgn_n_insns += n_new_insns;
+  ready.veclen = new_sched_ready_n_insns + issue_rate;
+  ready.vec = XRESIZEVEC (rtx, ready.vec, ready.veclen);
 
-  choice_stack = XRESIZEVEC (struct choice_entry, choice_stack,
-                            rgn_n_insns + 1);
+  gcc_assert (new_sched_ready_n_insns >= sched_ready_n_insns);
 
-  for (i = rgn_n_insns; n_new_insns--; i--)
-    choice_stack[i].state = xmalloc (dfa_state_size);
-}
+  ready_try = (char *) xrecalloc (ready_try, new_sched_ready_n_insns,
+                                  sched_ready_n_insns, sizeof (*ready_try));
 
-/* Extend global-scope scheduler data structures
-   (those, that live within one call to schedule_insns)
-   to include information about just emitted INSN.  */
-static void
-extend_global_data (rtx insn)
-{
-  gcc_assert (INSN_P (insn));
+  /* We allocate +1 element to save initial state in the choice_stack[0]
+     entry.  */
+  choice_stack = XRESIZEVEC (struct choice_entry, choice_stack,
+                            new_sched_ready_n_insns + 1);
 
-  /* Init h_i_d.  */
-  extend_h_i_d ();
-  init_h_i_d (insn);
+  for (; i <= new_sched_ready_n_insns; i++)
+    choice_stack[i].state = xmalloc (dfa_state_size);
 
-  /* Extend dependency caches by one element.  */
-  extend_dependency_caches (1, false);
+  sched_ready_n_insns = new_sched_ready_n_insns;
 }
 
-/* Extend global- and region-scope scheduler data structures
-   (those, that live within one call to schedule_region)
-   to include information about just emitted INSN.  */
-static void
-extend_region_data (rtx insn)
+/* Free per region data structures.  */
+void
+sched_finish_ready_list (void)
 {
-  extend_global_data (insn);
+  int i;
 
-  /* Init dependency data.  */
-  sd_init_insn (insn);
-}
+  free (ready.vec);
+  ready.vec = NULL;
+  ready.veclen = 0;
 
-/* Extend global-, region- and block-scope scheduler data structures
-   (those, that live within one call to schedule_block)
-   to include information about just emitted INSN.  */
-static void
-extend_block_data (rtx insn)
-{
-  extend_region_data (insn);
+  free (ready_try);
+  ready_try = NULL;
 
-  /* These structures have block scope.  */
-  extend_ready (1);
+  for (i = 0; i <= sched_ready_n_insns; i++)
+    free (choice_stack [i].state);
+  free (choice_stack);
+  choice_stack = NULL;
 
-  (*current_sched_info->add_remove_insn) (insn, 0);
+  sched_ready_n_insns = -1;
 }
 
-/* Initialize h_i_d entry of the new INSN with default values.
-   Values, that are not explicitly initialized here, hold zero.  */
-static void
-init_h_i_d (rtx insn)
+static int
+haifa_luid_for_non_insn (rtx x)
 {
-  INSN_LUID (insn) = luid++;
-  INSN_COST (insn) = -1;
-  TODO_SPEC (insn) = HARD_DEP;
-  QUEUE_INDEX (insn) = QUEUE_NOWHERE;
-  INSN_TICK (insn) = INVALID_TICK;
-  INTER_TICK (insn) = INVALID_TICK;
-  find_insn_reg_weight1 (insn);
+  gcc_assert (NOTE_P (x) || LABEL_P (x));
+
+  return 0;
 }
 
 /* Generates recovery code for INSN.  */
@@ -3290,7 +3493,7 @@ process_insn_forw_deps_be_in_spec (rtx insn, rtx twin, ds_t fs)
                     it can be removed from the ready (or queue) list only
                     due to backend decision.  Hence we can't let the
                     probability of the speculative dep to decrease.  */
-                 dep_weak (ds) <= dep_weak (fs))
+                 ds_weak (ds) <= ds_weak (fs))
                {
                  ds_t new_ds;
 
@@ -3331,6 +3534,8 @@ begin_speculative_block (rtx insn)
   TODO_SPEC (insn) &= ~BEGIN_SPEC;
 }
 
+static void haifa_init_insn (rtx);
+
 /* Generates recovery code for BE_IN speculative INSN.  */
 static void
 add_to_speculative_block (rtx insn)
@@ -3398,7 +3603,7 @@ add_to_speculative_block (rtx insn)
       rec = BLOCK_FOR_INSN (check);
 
       twin = emit_insn_before (copy_insn (PATTERN (insn)), BB_END (rec));
-      extend_region_data (twin);
+      haifa_init_insn (twin);
 
       sd_copy_back_deps (twin, insn, true);
 
@@ -3479,44 +3684,9 @@ xrecalloc (void *p, size_t new_nmemb, size_t old_nmemb, size_t size)
   return p;
 }
 
-/* Return the probability of speculation success for the speculation
-   status DS.  */
-static dw_t
-dep_weak (ds_t ds)
-{
-  ds_t res = 1, dt;
-  int n = 0;
-
-  dt = FIRST_SPEC_TYPE;
-  do
-    {
-      if (ds & dt)
-       {
-         res *= (ds_t) get_dep_weak (ds, dt);
-         n++;
-       }
-
-      if (dt == LAST_SPEC_TYPE)
-       break;
-      dt <<= SPEC_TYPE_SHIFT;
-    }
-  while (1);
-
-  gcc_assert (n);
-  while (--n)
-    res /= MAX_DEP_WEAK;
-
-  if (res < MIN_DEP_WEAK)
-    res = MIN_DEP_WEAK;
-
-  gcc_assert (res <= MAX_DEP_WEAK);
-
-  return (dw_t) res;
-}
-
 /* Helper function.
    Find fallthru edge from PRED.  */
-static edge
+edge
 find_fallthru_edge (basic_block pred)
 {
   edge e;
@@ -3548,9 +3718,37 @@ find_fallthru_edge (basic_block pred)
   return NULL;
 }
 
+/* Extend per basic block data structures.  */
+static void
+sched_extend_bb (void)
+{
+  rtx insn;
+
+  /* The following is done to keep current_sched_info->next_tail non null.  */
+  insn = BB_END (EXIT_BLOCK_PTR->prev_bb);
+  if (NEXT_INSN (insn) == 0
+      || (!NOTE_P (insn)
+         && !LABEL_P (insn)
+         /* Don't emit a NOTE if it would end up before a BARRIER.  */
+         && !BARRIER_P (NEXT_INSN (insn))))
+    {
+      rtx note = emit_note_after (NOTE_INSN_DELETED, insn);
+      /* Make insn appear outside BB.  */
+      set_block_for_insn (note, NULL);
+      BB_END (EXIT_BLOCK_PTR->prev_bb) = insn;
+    }
+}
+
+/* Init per basic block data structures.  */
+void
+sched_init_bbs (void)
+{
+  sched_extend_bb ();
+}
+
 /* Initialize BEFORE_RECOVERY variable.  */
 static void
-init_before_recovery (void)
+init_before_recovery (basic_block *before_recovery_ptr)
 {
   basic_block last;
   edge e;
@@ -3569,10 +3767,24 @@ init_before_recovery (void)
       basic_block single, empty;
       rtx x, label;
 
-      single = create_empty_bb (last);
-      empty = create_empty_bb (single);            
+      /* If the fallthrough edge to exit we've found is from the block we've 
+        created before, don't do anything more.  */
+      if (last == after_recovery)
+       return;
 
-      single->count = last->count;     
+      adding_bb_to_current_region_p = false;
+
+      single = sched_create_empty_bb (last);
+      empty = sched_create_empty_bb (single);
+
+      /* Add new blocks to the root loop.  */
+      if (current_loops != NULL)
+       {
+         add_bb_to_loop (single, VEC_index (loop_p, current_loops->larray, 0));
+         add_bb_to_loop (empty, VEC_index (loop_p, current_loops->larray, 0));
+       }
+
+      single->count = last->count;
       empty->count = last->count;
       single->frequency = last->frequency;
       empty->frequency = last->frequency;
@@ -3588,14 +3800,20 @@ init_before_recovery (void)
       x = emit_jump_insn_after (gen_jump (label), BB_END (single));
       JUMP_LABEL (x) = label;
       LABEL_NUSES (label)++;
-      extend_global_data (x);
+      haifa_init_insn (x);
           
       emit_barrier_after (x);
 
-      add_block (empty, 0);
-      add_block (single, 0);
+      sched_init_only_bb (empty, NULL);
+      sched_init_only_bb (single, NULL);
+      sched_extend_bb ();
 
+      adding_bb_to_current_region_p = true;
       before_recovery = single;
+      after_recovery = empty;
+
+      if (before_recovery_ptr)
+        *before_recovery_ptr = before_recovery;
 
       if (sched_verbose >= 2 && spec_info->dump)
         fprintf (spec_info->dump,
@@ -3607,8 +3825,8 @@ init_before_recovery (void)
 }
 
 /* Returns new recovery block.  */
-static basic_block
-create_recovery_block (void)
+basic_block
+sched_create_recovery_block (basic_block *before_recovery_ptr)
 {
   rtx label;
   rtx barrier;
@@ -3617,8 +3835,7 @@ create_recovery_block (void)
   haifa_recovery_bb_recently_added_p = true;
   haifa_recovery_bb_ever_added_p = true;
 
-  if (!before_recovery)
-    init_before_recovery ();
+  init_before_recovery (before_recovery_ptr);
 
   barrier = get_last_bb_insn (before_recovery);
   gcc_assert (BARRIER_P (barrier));
@@ -3627,7 +3844,7 @@ create_recovery_block (void)
 
   rec = create_basic_block (label, label, before_recovery);
 
-  /* Recovery block always end with an unconditional jump.  */
+  /* A recovery block always ends with an unconditional jump.  */
   emit_barrier_after (BB_END (rec));
 
   if (BB_PARTITION (before_recovery) != BB_UNPARTITIONED)
@@ -3637,11 +3854,55 @@ create_recovery_block (void)
     fprintf (spec_info->dump, ";;\t\tGenerated recovery block rec%d\n",
              rec->index);
 
-  before_recovery = rec;
-
   return rec;
 }
 
+/* Create edges: FIRST_BB -> REC; FIRST_BB -> SECOND_BB; REC -> SECOND_BB
+   and emit necessary jumps.  */
+void
+sched_create_recovery_edges (basic_block first_bb, basic_block rec,
+                            basic_block second_bb)
+{
+  rtx label;
+  rtx jump;
+  edge e;
+  int edge_flags;
+
+  /* This is fixing of incoming edge.  */
+  /* ??? Which other flags should be specified?  */      
+  if (BB_PARTITION (first_bb) != BB_PARTITION (rec))
+    /* Partition type is the same, if it is "unpartitioned".  */
+    edge_flags = EDGE_CROSSING;
+  else
+    edge_flags = 0;
+      
+  e = make_edge (first_bb, rec, edge_flags);
+  label = block_label (second_bb);
+  jump = emit_jump_insn_after (gen_jump (label), BB_END (rec));
+  JUMP_LABEL (jump) = label;
+  LABEL_NUSES (label)++;
+
+  if (BB_PARTITION (second_bb) != BB_PARTITION (rec))
+    /* Partition type is the same, if it is "unpartitioned".  */
+    {
+      /* Rewritten from cfgrtl.c.  */
+      if (flag_reorder_blocks_and_partition
+         && targetm.have_named_sections)
+       /* We don't need the same note for the check because
+          any_condjump_p (check) == true.  */
+       {
+         REG_NOTES (jump) = gen_rtx_EXPR_LIST (REG_CROSSING_JUMP,
+                                               NULL_RTX,
+                                               REG_NOTES (jump));
+       }
+      edge_flags = EDGE_CROSSING;
+    }
+  else
+    edge_flags = 0;  
+
+  make_single_succ_edge (rec, second_bb, edge_flags);  
+}
+
 /* This function creates recovery code for INSN.  If MUTATE_P is nonzero,
    INSN is a simple check, that should be converted to branchy one.  */
 static void
@@ -3653,26 +3914,36 @@ create_check_block_twin (rtx insn, bool mutate_p)
   sd_iterator_def sd_it;
   dep_t dep;
   dep_def _new_dep, *new_dep = &_new_dep;
+  ds_t todo_spec;
 
-  gcc_assert (ORIG_PAT (insn)
-             && (!mutate_p 
-                 || (IS_SPECULATION_SIMPLE_CHECK_P (insn)
-                     && !(TODO_SPEC (insn) & SPECULATIVE))));
+  gcc_assert (ORIG_PAT (insn) != NULL_RTX);
+
+  if (!mutate_p)
+    todo_spec = TODO_SPEC (insn);
+  else
+    {
+      gcc_assert (IS_SPECULATION_SIMPLE_CHECK_P (insn)
+                 && (TODO_SPEC (insn) & SPECULATIVE) == 0);
+
+      todo_spec = CHECK_SPEC (insn);
+    }
+
+  todo_spec &= SPECULATIVE;
 
   /* Create recovery block.  */
   if (mutate_p || targetm.sched.needs_block_p (insn))
     {
-      rec = create_recovery_block ();
+      rec = sched_create_recovery_block (NULL);
       label = BB_HEAD (rec);
     }
   else
     {
       rec = EXIT_BLOCK_PTR;
-      label = 0;
+      label = NULL_RTX;
     }
 
   /* Emit CHECK.  */
-  check = targetm.sched.gen_check (insn, label, mutate_p);
+  check = targetm.sched.gen_spec_check (insn, label, mutate_p);
 
   if (rec != EXIT_BLOCK_PTR)
     {
@@ -3688,7 +3959,15 @@ create_check_block_twin (rtx insn, bool mutate_p)
     check = emit_insn_before (check, insn);
 
   /* Extend data structures.  */
-  extend_block_data (check);
+  haifa_init_insn (check);
+
+  /* CHECK is being added to current region.  Extend ready list.  */
+  gcc_assert (sched_ready_n_insns != -1);
+  sched_extend_ready_list (sched_ready_n_insns + 1);
+
+  if (current_sched_info->add_remove_insn)
+    current_sched_info->add_remove_insn (insn, 0);
+
   RECOVERY_BLOCK (check) = rec;
 
   if (sched_verbose && spec_info->dump)
@@ -3715,7 +3994,7 @@ create_check_block_twin (rtx insn, bool mutate_p)
          }
 
       twin = emit_insn_after (ORIG_PAT (insn), BB_END (rec));
-      extend_region_data (twin);
+      haifa_init_insn (twin);
 
       if (sched_verbose && spec_info->dump)
        /* INSN_BB (insn) isn't determined for twin insns yet.
@@ -3741,54 +4020,17 @@ create_check_block_twin (rtx insn, bool mutate_p)
     {
       basic_block first_bb, second_bb;
       rtx jump;
-      edge e;
-      int edge_flags;
 
       first_bb = BLOCK_FOR_INSN (check);
-      e = split_block (first_bb, check);
-      /* split_block emits note if *check == BB_END.  Probably it 
-        is better to rip that note off.  */
-      gcc_assert (e->src == first_bb);
-      second_bb = e->dest;
-
-      /* This is fixing of incoming edge.  */
-      /* ??? Which other flags should be specified?  */      
-      if (BB_PARTITION (first_bb) != BB_PARTITION (rec))
-       /* Partition type is the same, if it is "unpartitioned".  */
-       edge_flags = EDGE_CROSSING;
-      else
-       edge_flags = 0;
-      
-      e = make_edge (first_bb, rec, edge_flags);
+      second_bb = sched_split_block (first_bb, check);
 
-      add_block (second_bb, first_bb);
-      
-      gcc_assert (NOTE_INSN_BASIC_BLOCK_P (BB_HEAD (second_bb)));
-      label = block_label (second_bb);
-      jump = emit_jump_insn_after (gen_jump (label), BB_END (rec));
-      JUMP_LABEL (jump) = label;
-      LABEL_NUSES (label)++;
-      extend_region_data (jump);
+      sched_create_recovery_edges (first_bb, rec, second_bb);
 
-      if (BB_PARTITION (second_bb) != BB_PARTITION (rec))
-       /* Partition type is the same, if it is "unpartitioned".  */
-       {
-         /* Rewritten from cfgrtl.c.  */
-         if (flag_reorder_blocks_and_partition
-             && targetm.have_named_sections
-             /*&& !any_condjump_p (jump)*/)
-           /* any_condjump_p (jump) == false.
-              We don't need the same note for the check because
-              any_condjump_p (check) == true.  */
-           add_reg_note (jump, REG_CROSSING_JUMP, NULL_RTX);
-         edge_flags = EDGE_CROSSING;
-       }
-      else
-       edge_flags = 0;  
-      
-      make_single_succ_edge (rec, second_bb, edge_flags);  
-      
-      add_block (rec, EXIT_BLOCK_PTR);
+      sched_init_only_bb (second_bb, first_bb);      
+      sched_init_only_bb (rec, EXIT_BLOCK_PTR);
+
+      jump = BB_END (rec);
+      haifa_init_insn (jump);
     }
 
   /* Move backward dependences from INSN to CHECK and 
@@ -4004,27 +4246,36 @@ fix_recovery_deps (basic_block rec)
   add_jump_dependencies (insn, jump);
 }
 
-/* Changes pattern of the INSN to NEW_PAT.  */
-static void
-change_pattern (rtx insn, rtx new_pat)
+/* Change pattern of INSN to NEW_PAT.  */
+void
+sched_change_pattern (rtx insn, rtx new_pat)
 {
   int t;
 
   t = validate_change (insn, &PATTERN (insn), new_pat, 0);
   gcc_assert (t);
+  dfa_clear_single_insn_cache (insn);
+}
+
+/* Change pattern of INSN to NEW_PAT.  Invalidate cached haifa
+   instruction data.  */
+static void
+haifa_change_pattern (rtx insn, rtx new_pat)
+{
+  sched_change_pattern (insn, new_pat);
+
   /* Invalidate INSN_COST, so it'll be recalculated.  */
   INSN_COST (insn) = -1;
   /* Invalidate INSN_TICK, so it'll be recalculated.  */
   INSN_TICK (insn) = INVALID_TICK;
-  dfa_clear_single_insn_cache (insn);
 }
 
 /* -1 - can't speculate,
    0 - for speculation with REQUEST mode it is OK to use
    current instruction pattern,
    1 - need to change pattern for *NEW_PAT to be speculative.  */
-static int
-speculate_insn (rtx insn, ds_t request, rtx *new_pat)
+int
+sched_speculate_insn (rtx insn, ds_t request, rtx *new_pat)
 {
   gcc_assert (current_sched_info->flags & DO_SPECULATION
               && (request & SPECULATIVE)
@@ -4037,7 +4288,20 @@ speculate_insn (rtx insn, ds_t request, rtx *new_pat)
       && !(request & BEGIN_SPEC))
     return 0;
 
-  return targetm.sched.speculate_insn (insn, request & BEGIN_SPEC, new_pat);
+  return targetm.sched.speculate_insn (insn, request, new_pat);
+}
+
+static int
+haifa_speculate_insn (rtx insn, ds_t request, rtx *new_pat)
+{
+  gcc_assert (sched_deps_info->generate_spec_deps
+             && !IS_SPECULATION_CHECK_P (insn));
+
+  if (HAS_INTERNAL_DEP (insn)
+      || SCHED_GROUP_P (insn))
+    return -1;
+
+  return sched_speculate_insn (insn, request, new_pat);
 }
 
 /* Print some information about block BB, which starts with HEAD and
@@ -4151,47 +4415,6 @@ restore_bb_notes (basic_block first)
   bb_header = 0;
 }
 
-/* Extend per basic block data structures of the scheduler.
-   If BB is NULL, initialize structures for the whole CFG.
-   Otherwise, initialize them for the just created BB.  */
-static void
-extend_bb (void)
-{
-  rtx insn;
-
-  old_last_basic_block = last_basic_block;
-
-  /* The following is done to keep current_sched_info->next_tail non null.  */
-
-  insn = BB_END (EXIT_BLOCK_PTR->prev_bb);
-  if (NEXT_INSN (insn) == 0
-      || (!NOTE_P (insn)
-         && !LABEL_P (insn)
-         /* Don't emit a NOTE if it would end up before a BARRIER.  */
-         && !BARRIER_P (NEXT_INSN (insn))))
-    {
-      rtx note = emit_note_after (NOTE_INSN_DELETED, insn);
-      /* Make insn appear outside BB.  */
-      set_block_for_insn (note, NULL);
-      BB_END (EXIT_BLOCK_PTR->prev_bb) = insn;
-    }
-}
-
-/* Add a basic block BB to extended basic block EBB.
-   If EBB is EXIT_BLOCK_PTR, then BB is recovery block.
-   If EBB is NULL, then BB should be a new region.  */
-void
-add_block (basic_block bb, basic_block ebb)
-{
-  gcc_assert (current_sched_info->flags & NEW_BBS);
-
-  extend_bb ();
-
-  if (current_sched_info->add_block)
-    /* This changes only data structures of the front-end.  */
-    current_sched_info->add_block (bb, ebb);
-}
-
 /* Helper function.
    Fix CFG after both in- and inter-block movement of
    control_flow_insn_p JUMP.  */
@@ -4204,7 +4427,7 @@ fix_jump_move (rtx jump)
   jump_bb = BLOCK_FOR_INSN (jump);
   jump_bb_next = jump_bb->next_bb;
 
-  gcc_assert (current_sched_info->flags & SCHED_EBB
+  gcc_assert (common_sched_info->sched_pass_id == SCHED_EBB_PASS
              || IS_SPECULATION_BRANCHY_CHECK_P (jump));
   
   if (!NOTE_INSN_BASIC_BLOCK_P (BB_END (jump_bb_next)))
@@ -4252,9 +4475,8 @@ move_block_after_check (rtx jump)
 
   df_mark_solutions_dirty ();
   
-  if (current_sched_info->fix_recovery_cfg)
-    current_sched_info->fix_recovery_cfg 
-      (bb->index, jump_bb->index, jump_bb_next->index);
+  common_sched_info->fix_recovery_cfg
+    (bb->index, jump_bb->index, jump_bb_next->index);
 }
 
 /* Helper function for move_block_after_check.
@@ -4480,6 +4702,281 @@ check_cfg (rtx head, rtx tail)
 
   gcc_assert (bb == 0);
 }
+
 #endif /* ENABLE_CHECKING */
 
+const struct sched_scan_info_def *sched_scan_info;
+
+/* Extend per basic block data structures.  */
+static void
+extend_bb (void)
+{
+  if (sched_scan_info->extend_bb)
+    sched_scan_info->extend_bb ();
+}
+
+/* Init data for BB.  */
+static void
+init_bb (basic_block bb)
+{
+  if (sched_scan_info->init_bb)
+    sched_scan_info->init_bb (bb);
+}
+
+/* Extend per insn data structures.  */
+static void
+extend_insn (void)
+{
+  if (sched_scan_info->extend_insn)
+    sched_scan_info->extend_insn ();
+}
+
+/* Init data structures for INSN.  */
+static void
+init_insn (rtx insn)
+{
+  if (sched_scan_info->init_insn)
+    sched_scan_info->init_insn (insn);
+}
+
+/* Init all insns in BB.  */
+static void
+init_insns_in_bb (basic_block bb)
+{
+  rtx insn;
+
+  FOR_BB_INSNS (bb, insn)
+    init_insn (insn);
+}
+
+/* A driver function to add a set of basic blocks (BBS),
+   a single basic block (BB), a set of insns (INSNS) or a single insn (INSN)
+   to the scheduling region.  */
+void
+sched_scan (const struct sched_scan_info_def *ssi,
+           bb_vec_t bbs, basic_block bb, insn_vec_t insns, rtx insn)
+{
+  sched_scan_info = ssi;
+
+  if (bbs != NULL || bb != NULL)
+    {
+      extend_bb ();
+
+      if (bbs != NULL)
+       {
+         unsigned i;
+         basic_block x;
+
+         for (i = 0; VEC_iterate (basic_block, bbs, i, x); i++)
+           init_bb (x);
+       }
+
+      if (bb != NULL)
+       init_bb (bb);
+    }
+
+  extend_insn ();
+
+  if (bbs != NULL)
+    {      
+      unsigned i;
+      basic_block x;
+
+      for (i = 0; VEC_iterate (basic_block, bbs, i, x); i++)
+       init_insns_in_bb (x);
+    }
+
+  if (bb != NULL)
+    init_insns_in_bb (bb);
+
+  if (insns != NULL)
+    {
+      unsigned i;
+      rtx x;
+
+      for (i = 0; VEC_iterate (rtx, insns, i, x); i++)
+       init_insn (x);
+    }
+
+  if (insn != NULL)
+    init_insn (insn);
+}
+
+
+/* Extend data structures for logical insn UID.  */
+static void
+luids_extend_insn (void)
+{
+  int new_luids_max_uid = get_max_uid () + 1;
+
+  VEC_safe_grow_cleared (int, heap, sched_luids, new_luids_max_uid);
+}
+
+/* Initialize LUID for INSN.  */
+static void
+luids_init_insn (rtx insn)
+{
+  int i = INSN_P (insn) ? 1 : common_sched_info->luid_for_non_insn (insn);
+  int luid;
+
+  if (i >= 0)
+    {
+      luid = sched_max_luid;
+      sched_max_luid += i;
+    }
+  else
+    luid = -1;
+
+  SET_INSN_LUID (insn, luid);
+}
+
+/* Initialize luids for BBS, BB, INSNS and INSN.
+   The hook common_sched_info->luid_for_non_insn () is used to determine
+   if notes, labels, etc. need luids.  */
+void
+sched_init_luids (bb_vec_t bbs, basic_block bb, insn_vec_t insns, rtx insn)
+{
+  const struct sched_scan_info_def ssi =
+    {
+      NULL, /* extend_bb */
+      NULL, /* init_bb */
+      luids_extend_insn, /* extend_insn */
+      luids_init_insn /* init_insn */
+    };
+
+  sched_scan (&ssi, bbs, bb, insns, insn);
+}
+
+/* Free LUIDs.  */
+void
+sched_finish_luids (void)
+{
+  VEC_free (int, heap, sched_luids);
+  sched_max_luid = 1;
+}
+
+/* Return logical uid of INSN.  Helpful while debugging.  */
+int
+insn_luid (rtx insn)
+{
+  return INSN_LUID (insn);
+}
+
+/* Extend per insn data in the target.  */
+void
+sched_extend_target (void)
+{
+  if (targetm.sched.h_i_d_extended)
+    targetm.sched.h_i_d_extended ();
+}
+
+/* Extend global scheduler structures (those, that live across calls to
+   schedule_block) to include information about just emitted INSN.  */
+static void
+extend_h_i_d (void)
+{
+  int reserve = (get_max_uid () + 1 
+                 - VEC_length (haifa_insn_data_def, h_i_d));
+  if (reserve > 0 
+      && ! VEC_space (haifa_insn_data_def, h_i_d, reserve))
+    {
+      VEC_safe_grow_cleared (haifa_insn_data_def, heap, h_i_d, 
+                             3 * get_max_uid () / 2);
+      sched_extend_target ();
+    }
+}
+
+/* Initialize h_i_d entry of the INSN with default values.
+   Values, that are not explicitly initialized here, hold zero.  */
+static void
+init_h_i_d (rtx insn)
+{
+  if (INSN_LUID (insn) > 0)
+    {
+      INSN_COST (insn) = -1;
+      find_insn_reg_weight (insn);
+      QUEUE_INDEX (insn) = QUEUE_NOWHERE;
+      INSN_TICK (insn) = INVALID_TICK;
+      INTER_TICK (insn) = INVALID_TICK;
+      TODO_SPEC (insn) = HARD_DEP;
+    }
+}
+
+/* Initialize haifa_insn_data for BBS, BB, INSNS and INSN.  */
+void
+haifa_init_h_i_d (bb_vec_t bbs, basic_block bb, insn_vec_t insns, rtx insn)
+{
+  const struct sched_scan_info_def ssi =
+    {
+      NULL, /* extend_bb */
+      NULL, /* init_bb */
+      extend_h_i_d, /* extend_insn */
+      init_h_i_d /* init_insn */
+    };
+
+  sched_scan (&ssi, bbs, bb, insns, insn);
+}
+
+/* Finalize haifa_insn_data.  */
+void
+haifa_finish_h_i_d (void)
+{
+  VEC_free (haifa_insn_data_def, heap, h_i_d);
+}
+
+/* Init data for the new insn INSN.  */
+static void
+haifa_init_insn (rtx insn)
+{
+  gcc_assert (insn != NULL);
+
+  sched_init_luids (NULL, NULL, NULL, insn);
+  sched_extend_target ();
+  sched_deps_init (false);
+  haifa_init_h_i_d (NULL, NULL, NULL, insn);
+
+  if (adding_bb_to_current_region_p)
+    {
+      sd_init_insn (insn);
+
+      /* Extend dependency caches by one element.  */
+      extend_dependency_caches (1, false);
+    }
+}
+
+/* Init data for the new basic block BB which comes after AFTER.  */
+static void
+haifa_init_only_bb (basic_block bb, basic_block after)
+{
+  gcc_assert (bb != NULL);
+
+  sched_init_bbs ();
+
+  if (common_sched_info->add_block)
+    /* This changes only data structures of the front-end.  */
+    common_sched_info->add_block (bb, after);
+}
+
+/* A generic version of sched_split_block ().  */
+basic_block
+sched_split_block_1 (basic_block first_bb, rtx after)
+{
+  edge e;
+
+  e = split_block (first_bb, after);
+  gcc_assert (e->src == first_bb);
+
+  /* sched_split_block emits note if *check == BB_END.  Probably it 
+     is better to rip that note off.  */
+
+  return e->dest;
+}
+
+/* A generic version of sched_create_empty_bb ().  */
+basic_block
+sched_create_empty_bb_1 (basic_block after)
+{
+  return create_empty_bb (after);
+}
+
 #endif /* INSN_SCHEDULING */
index c4f74a2..7e17cab 100644 (file)
@@ -89,6 +89,8 @@ typedef HARD_REG_ELT_TYPE HARD_REG_SET[HARD_REG_SET_LONGS];
    hard_reg_set_intersect_p (X, Y), which returns true if X and Y intersect.
    hard_reg_set_empty_p (X), which returns true if X is empty.  */
 
+#define UHOST_BITS_PER_WIDE_INT ((unsigned) HOST_BITS_PER_WIDEST_FAST_INT)
+
 #ifdef HARD_REG_SET
 
 #define SET_HARD_REG_BIT(SET, BIT)  \
@@ -135,8 +137,6 @@ hard_reg_set_empty_p (const HARD_REG_SET x)
 
 #else
 
-#define UHOST_BITS_PER_WIDE_INT ((unsigned) HOST_BITS_PER_WIDEST_FAST_INT)
-
 #define SET_HARD_REG_BIT(SET, BIT)             \
   ((SET)[(BIT) / UHOST_BITS_PER_WIDE_INT]      \
    |= HARD_CONST (1) << ((BIT) % UHOST_BITS_PER_WIDE_INT))
@@ -479,6 +479,100 @@ hard_reg_set_empty_p (const HARD_REG_SET x)
 #endif
 #endif
 
+/* Iterator for hard register sets.  */
+
+typedef struct
+{
+  /* Pointer to the current element.  */
+  HARD_REG_ELT_TYPE *pelt;
+
+  /* The length of the set.  */
+  unsigned short length;
+
+  /* Word within the current element.  */
+  unsigned short word_no;
+
+  /* Contents of the actually processed word.  When finding next bit
+     it is shifted right, so that the actual bit is always the least
+     significant bit of ACTUAL.  */
+  HARD_REG_ELT_TYPE bits;
+} hard_reg_set_iterator;
+
+#define HARD_REG_ELT_BITS UHOST_BITS_PER_WIDE_INT
+
+/* The implementation of the iterator functions is fully analogous to 
+   the bitmap iterators.  */
+static inline void
+hard_reg_set_iter_init (hard_reg_set_iterator *iter, HARD_REG_SET set, 
+                        unsigned min, unsigned *regno)
+{
+#ifdef HARD_REG_SET_LONGS
+  iter->pelt = set;
+  iter->length = HARD_REG_SET_LONGS;
+#else
+  iter->pelt = &set;
+  iter->length = 1;
+#endif
+  iter->word_no = min / HARD_REG_ELT_BITS;
+  if (iter->word_no < iter->length)
+    {
+      iter->bits = iter->pelt[iter->word_no];
+      iter->bits >>= min % HARD_REG_ELT_BITS;
+
+      /* This is required for correct search of the next bit.  */
+      min += !iter->bits;
+    }
+  *regno = min;
+}
+
+static inline bool 
+hard_reg_set_iter_set (hard_reg_set_iterator *iter, unsigned *regno)
+{
+  while (1)
+    {
+      /* Return false when we're advanced past the end of the set.  */
+      if (iter->word_no >= iter->length)
+        return false;
+
+      if (iter->bits)
+        {
+          /* Find the correct bit and return it.  */
+          while (!(iter->bits & 1))
+            {
+              iter->bits >>= 1;
+              *regno += 1;
+            }
+          return (*regno < FIRST_PSEUDO_REGISTER);
+        }
+  
+      /* Round to the beginning of the next word.  */
+      *regno = (*regno + HARD_REG_ELT_BITS - 1);
+      *regno -= *regno % HARD_REG_ELT_BITS;
+
+      /* Find the next non-zero word.  */
+      while (++iter->word_no < iter->length)
+        {
+          iter->bits = iter->pelt[iter->word_no];
+          if (iter->bits)
+            break;
+          *regno += HARD_REG_ELT_BITS;
+        }
+    }
+}
+
+static inline void
+hard_reg_set_iter_next (hard_reg_set_iterator *iter, unsigned *regno)
+{
+  iter->bits >>= 1;
+  *regno += 1;
+}
+
+#define EXECUTE_IF_SET_IN_HARD_REG_SET(SET, MIN, REGNUM, ITER)          \
+  for (hard_reg_set_iter_init (&(ITER), (SET), (MIN), &(REGNUM));       \
+       hard_reg_set_iter_set (&(ITER), &(REGNUM));                      \
+       hard_reg_set_iter_next (&(ITER), &(REGNUM)))
+
+
 /* Define some standard sets of registers.  */
 
 /* Indexed by hard register number, contains 1 for registers
index f917523..77aeac3 100644 (file)
@@ -188,4 +188,30 @@ remove_free_INSN_LIST_elem (rtx elem, rtx *listp)
   free_INSN_LIST_node (remove_list_elem (elem, listp));
 }
 
+/* Remove and free the first node in the INSN_LIST pointed to by LISTP.  */
+rtx
+remove_free_INSN_LIST_node (rtx *listp)
+{
+  rtx node = *listp;
+  rtx elem = XEXP (node, 0);
+
+  remove_list_node (listp);
+  free_INSN_LIST_node (node);
+
+  return elem;
+}
+
+/* Remove and free the first node in the EXPR_LIST pointed to by LISTP.  */
+rtx
+remove_free_EXPR_LIST_node (rtx *listp)
+{
+  rtx node = *listp;
+  rtx elem = XEXP (node, 0);
+
+  remove_list_node (listp);
+  free_EXPR_LIST_node (node);
+
+  return elem;
+}
+
 #include "gt-lists.h"
index 8337571..cb93eca 100644 (file)
@@ -66,7 +66,14 @@ loop_optimizer_init (unsigned flags)
 
   /* Create pre-headers.  */
   if (flags & LOOPS_HAVE_PREHEADERS)
-    create_preheaders (CP_SIMPLE_PREHEADERS);
+    {
+      int cp_flags = CP_SIMPLE_PREHEADERS;
+
+      if (flags & LOOPS_HAVE_FALLTHRU_PREHEADERS)
+        cp_flags |= CP_FALLTHRU_PREHEADERS;
+      
+      create_preheaders (cp_flags);
+    }
 
   /* Force all latches to have only single successor.  */
   if (flags & LOOPS_HAVE_SIMPLE_LATCHES)
@@ -118,7 +125,10 @@ loop_optimizer_finalize (void)
 
   /* Checking.  */
 #ifdef ENABLE_CHECKING
-  verify_flow_info ();
+  /* FIXME: no point to verify flow info after bundling on ia64.  Use this 
+     hack for achieving this.  */
+  if (!reload_completed)
+    verify_flow_info ();
 #endif
 }
 
index f11bc1c..7134bfc 100644 (file)
@@ -187,13 +187,6 @@ static int compute_split_row (sbitmap, int, int, int, ddg_node_ptr);
 /* This page defines constants and structures for the modulo scheduling
    driver.  */
 
-/* As in haifa-sched.c:  */
-/* issue_rate is the number of insns that can be scheduled in the same
-   machine cycle.  It can be defined in the config/mach/mach.h file,
-   otherwise we set it to 1.  */
-
-static int issue_rate;
-
 static int sms_order_nodes (ddg_ptr, int, int *, int *);
 static void set_node_sched_params (ddg_ptr);
 static partial_schedule_ptr sms_schedule_by_order (ddg_ptr, int, int, int *);
@@ -242,7 +235,7 @@ typedef struct node_sched_params
    code in order to use sched_analyze() for computing the dependencies.
    They are used when initializing the sched_info structure.  */
 static const char *
-sms_print_insn (rtx insn, int aligned ATTRIBUTE_UNUSED)
+sms_print_insn (const_rtx insn, int aligned ATTRIBUTE_UNUSED)
 {
   static char tmp[80];
 
@@ -258,7 +251,17 @@ compute_jump_reg_dependencies (rtx insn ATTRIBUTE_UNUSED,
 {
 }
 
-static struct sched_info sms_sched_info =
+static struct common_sched_info_def sms_common_sched_info;
+
+static struct sched_deps_info_def sms_sched_deps_info =
+  {
+    compute_jump_reg_dependencies,
+    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
+    NULL,
+    0, 0, 0
+  };
+
+static struct haifa_sched_info sms_sched_info =
 {
   NULL,
   NULL,
@@ -267,16 +270,14 @@ static struct sched_info sms_sched_info =
   NULL,
   sms_print_insn,
   NULL,
-  compute_jump_reg_dependencies,
   NULL, NULL,
   NULL, NULL,
-  0, 0, 0,
+  0, 0,
 
-  NULL, NULL, NULL, NULL, NULL,
+  NULL, NULL, NULL, 
   0
 };
 
-
 /* Given HEAD and TAIL which are the first and last insns in a loop;
    return the register which controls the loop.  Return zero if it has
    more than one occurrence in the loop besides the control part or the
@@ -856,6 +857,19 @@ canon_loop (struct loop *loop)
     }
 }
 
+/* Setup infos.  */
+static void
+setup_sched_infos (void)
+{
+  memcpy (&sms_common_sched_info, &haifa_common_sched_info,
+         sizeof (sms_common_sched_info));
+  sms_common_sched_info.sched_pass_id = SCHED_SMS_PASS;
+  common_sched_info = &sms_common_sched_info;
+
+  sched_deps_info = &sms_sched_deps_info;
+  current_sched_info = &sms_sched_info;
+}
+
 /* Probability in % that the sms-ed loop rolls enough so that optimized
    version may be entered.  Just a guess.  */
 #define PROB_SMS_ENOUGH_ITERATIONS 80
@@ -901,16 +915,8 @@ sms_schedule (void)
     issue_rate = 1;
 
   /* Initialize the scheduler.  */
-  current_sched_info = &sms_sched_info;
-
-  /* Init Data Flow analysis, to be used in interloop dep calculation.  */
-  df_set_flags (DF_LR_RUN_DCE);
-  df_rd_add_problem ();
-  df_note_add_problem ();
-  df_chain_add_problem (DF_DU_CHAIN + DF_UD_CHAIN);
-  df_analyze ();
-  regstat_compute_calls_crossed ();
-  sched_init ();
+  setup_sched_infos ();
+  haifa_sched_init ();
 
   /* Allocate memory to hold the DDG array one entry for each loop.
      We use loop->num as index into this array.  */
@@ -1242,11 +1248,10 @@ sms_schedule (void)
       free_ddg (g);
     }
 
-  regstat_free_calls_crossed ();
   free (g_arr);
 
   /* Release scheduler data, needed until now because of DFA.  */
-  sched_finish ();
+  haifa_sched_finish ();
   loop_optimizer_finalize ();
 }
 
index 621f6b3..0c0f0a3 100644 (file)
@@ -47,6 +47,9 @@ along with GCC; see the file COPYING3.  If not see
 unsigned HOST_WIDE_INT g_switch_value;
 bool g_switch_set;
 
+/* Same for selective scheduling.  */
+bool sel_sched_switch_set;
+
 /* True if we should exit after parsing options.  */
 bool exit_after_options;
 
@@ -1087,6 +1090,11 @@ decode_options (unsigned int argc, const char **argv)
       flag_reorder_blocks = 1;
     }
 
+  /* Pipelining of outer loops is only possible when general pipelining
+     capabilities are requested.  */
+  if (!flag_sel_sched_pipelining)
+    flag_sel_sched_pipelining_outer_loops = 0;
+
 #ifndef IRA_COVER_CLASSES
   if (flag_ira)
     {
@@ -1870,6 +1878,11 @@ common_handle_option (size_t scode, const char *arg, int value,
       set_random_seed (arg);
       break;
 
+    case OPT_fselective_scheduling:
+    case OPT_fselective_scheduling2:
+      sel_sched_switch_set = true;
+      break;
+
     case OPT_fsched_verbose_:
 #ifdef INSN_SCHEDULING
       fix_sched_param ("verbose", arg);
index 5e9a664..8d30a24 100644 (file)
@@ -557,6 +557,16 @@ DEFPARAM(PARAM_MAX_SCHED_REGION_INSNS,
         "The maximum number of insns in a region to be considered for interblock scheduling",
         100, 0, 0)
 
+DEFPARAM(PARAM_MAX_PIPELINE_REGION_BLOCKS,
+        "max-pipeline-region-blocks",
+        "The maximum number of blocks in a region to be considered for interblock scheduling",
+        15, 0, 0)
+
+DEFPARAM(PARAM_MAX_PIPELINE_REGION_INSNS,
+        "max-pipeline-region-insns",
+        "The maximum number of insns in a region to be considered for interblock scheduling",
+        200, 0, 0)
+
 DEFPARAM(PARAM_MIN_SPEC_PROB,
          "min-spec-prob",
          "The minimum probability of reaching a source block for interblock speculative scheduling",
@@ -577,6 +587,26 @@ DEFPARAM(PARAM_SCHED_SPEC_PROB_CUTOFF,
          "The minimal probability of speculation success (in percents), so that speculative insn will be scheduled.",
          40, 0, 100)
 
+DEFPARAM(PARAM_SELSCHED_MAX_LOOKAHEAD,
+         "selsched-max-lookahead",
+         "The maximum size of the lookahead window of selective scheduling",
+         50, 0, 0)
+
+DEFPARAM(PARAM_SELSCHED_MAX_SCHED_TIMES,
+         "selsched-max-sched-times",
+         "Maximum number of times that an insn could be scheduled",
+         2, 0, 0)
+
+DEFPARAM(PARAM_SELSCHED_INSNS_TO_RENAME,
+         "selsched-insns-to-rename",
+         "Maximum number of instructions in the ready list that are considered eligible for renaming",
+         2, 0, 0)
+
+DEFPARAM (PARAM_SCHED_MEM_TRUE_DEP_COST,
+         "sched-mem-true-dep-cost",
+         "Minimal distance between possibly conflicting store and load",
+         1, 0, 0)
+
 DEFPARAM(PARAM_MAX_LAST_VALUE_RTL,
         "max-last-value-rtl",
         "The maximum number of RTL nodes that can be recorded as combiner's last value",
index 8da4e20..7ab6a1d 100644 (file)
@@ -69,7 +69,7 @@ get_attr_enabled (rtx insn ATTRIBUTE_UNUSED)
 }
 #endif
 
-static void validate_replace_rtx_1 (rtx *, rtx, rtx, rtx);
+static void validate_replace_rtx_1 (rtx *, rtx, rtx, rtx, bool);
 static void validate_replace_src_1 (rtx *, void *);
 static rtx split_insn (rtx);
 
@@ -513,88 +513,17 @@ cancel_changes (int num)
   num_changes = num;
 }
 
-/* Replace every occurrence of FROM in X with TO.  Mark each change with
-   validate_change passing OBJECT.  */
+/* A subroutine of validate_replace_rtx_1 that tries to simplify the resulting
+   rtx.  */
 
 static void
-validate_replace_rtx_1 (rtx *loc, rtx from, rtx to, rtx object)
+simplify_while_replacing (rtx *loc, rtx to, rtx object, 
+                          enum machine_mode op0_mode)
 {
-  int i, j;
-  const char *fmt;
   rtx x = *loc;
-  enum rtx_code code;
-  enum machine_mode op0_mode = VOIDmode;
-  int prev_changes = num_changes;
+  enum rtx_code code = GET_CODE (x);
   rtx new_rtx;
 
-  if (!x)
-    return;
-
-  code = GET_CODE (x);
-  fmt = GET_RTX_FORMAT (code);
-  if (fmt[0] == 'e')
-    op0_mode = GET_MODE (XEXP (x, 0));
-
-  /* X matches FROM if it is the same rtx or they are both referring to the
-     same register in the same mode.  Avoid calling rtx_equal_p unless the
-     operands look similar.  */
-
-  if (x == from
-      || (REG_P (x) && REG_P (from)
-         && GET_MODE (x) == GET_MODE (from)
-         && REGNO (x) == REGNO (from))
-      || (GET_CODE (x) == GET_CODE (from) && GET_MODE (x) == GET_MODE (from)
-         && rtx_equal_p (x, from)))
-    {
-      validate_unshare_change (object, loc, to, 1);
-      return;
-    }
-
-  /* Call ourself recursively to perform the replacements.
-     We must not replace inside already replaced expression, otherwise we
-     get infinite recursion for replacements like (reg X)->(subreg (reg X))
-     done by regmove, so we must special case shared ASM_OPERANDS.  */
-
-  if (GET_CODE (x) == PARALLEL)
-    {
-      for (j = XVECLEN (x, 0) - 1; j >= 0; j--)
-       {
-         if (j && GET_CODE (XVECEXP (x, 0, j)) == SET
-             && GET_CODE (SET_SRC (XVECEXP (x, 0, j))) == ASM_OPERANDS)
-           {
-             /* Verify that operands are really shared.  */
-             gcc_assert (ASM_OPERANDS_INPUT_VEC (SET_SRC (XVECEXP (x, 0, 0)))
-                         == ASM_OPERANDS_INPUT_VEC (SET_SRC (XVECEXP
-                                                             (x, 0, j))));
-             validate_replace_rtx_1 (&SET_DEST (XVECEXP (x, 0, j)),
-                                     from, to, object);
-           }
-         else
-           validate_replace_rtx_1 (&XVECEXP (x, 0, j), from, to, object);
-       }
-    }
-  else
-    for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
-      {
-       if (fmt[i] == 'e')
-         validate_replace_rtx_1 (&XEXP (x, i), from, to, object);
-       else if (fmt[i] == 'E')
-         for (j = XVECLEN (x, i) - 1; j >= 0; j--)
-           validate_replace_rtx_1 (&XVECEXP (x, i, j), from, to, object);
-      }
-
-  /* If we didn't substitute, there is nothing more to do.  */
-  if (num_changes == prev_changes)
-    return;
-
-  /* Allow substituted expression to have different mode.  This is used by
-     regmove to change mode of pseudo register.  */
-  if (fmt[0] == 'e' && GET_MODE (XEXP (x, 0)) != VOIDmode)
-    op0_mode = GET_MODE (XEXP (x, 0));
-
-  /* Do changes needed to keep rtx consistent.  Don't do any other
-     simplifications, as it is not our job.  */
-
   if (SWAPPABLE_OPERANDS_P (x)
       && swap_commutative_operands_p (XEXP (x, 0), XEXP (x, 1)))
     {
@@ -715,22 +644,132 @@ validate_replace_rtx_1 (rtx *loc, rtx from, rtx to, rtx object)
     }
 }
 
+/* Replace every occurrence of FROM in X with TO.  Mark each change with
+   validate_change passing OBJECT.  */
+
+static void
+validate_replace_rtx_1 (rtx *loc, rtx from, rtx to, rtx object, 
+                        bool simplify)
+{
+  int i, j;
+  const char *fmt;
+  rtx x = *loc;
+  enum rtx_code code;
+  enum machine_mode op0_mode = VOIDmode;
+  int prev_changes = num_changes;
+
+  if (!x)
+    return;
+
+  code = GET_CODE (x);
+  fmt = GET_RTX_FORMAT (code);
+  if (fmt[0] == 'e')
+    op0_mode = GET_MODE (XEXP (x, 0));
+
+  /* X matches FROM if it is the same rtx or they are both referring to the
+     same register in the same mode.  Avoid calling rtx_equal_p unless the
+     operands look similar.  */
+
+  if (x == from
+      || (REG_P (x) && REG_P (from)
+         && GET_MODE (x) == GET_MODE (from)
+         && REGNO (x) == REGNO (from))
+      || (GET_CODE (x) == GET_CODE (from) && GET_MODE (x) == GET_MODE (from)
+         && rtx_equal_p (x, from)))
+    {
+      validate_unshare_change (object, loc, to, 1);
+      return;
+    }
+
+  /* Call ourself recursively to perform the replacements.
+     We must not replace inside already replaced expression, otherwise we
+     get infinite recursion for replacements like (reg X)->(subreg (reg X))
+     done by regmove, so we must special case shared ASM_OPERANDS.  */
+
+  if (GET_CODE (x) == PARALLEL)
+    {
+      for (j = XVECLEN (x, 0) - 1; j >= 0; j--)
+       {
+         if (j && GET_CODE (XVECEXP (x, 0, j)) == SET
+             && GET_CODE (SET_SRC (XVECEXP (x, 0, j))) == ASM_OPERANDS)
+           {
+             /* Verify that operands are really shared.  */
+             gcc_assert (ASM_OPERANDS_INPUT_VEC (SET_SRC (XVECEXP (x, 0, 0)))
+                         == ASM_OPERANDS_INPUT_VEC (SET_SRC (XVECEXP
+                                                             (x, 0, j))));
+             validate_replace_rtx_1 (&SET_DEST (XVECEXP (x, 0, j)),
+                                     from, to, object, simplify);
+           }
+         else
+           validate_replace_rtx_1 (&XVECEXP (x, 0, j), from, to, object, 
+                                    simplify);
+       }
+    }
+  else
+    for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
+      {
+       if (fmt[i] == 'e')
+         validate_replace_rtx_1 (&XEXP (x, i), from, to, object, simplify);
+       else if (fmt[i] == 'E')
+         for (j = XVECLEN (x, i) - 1; j >= 0; j--)
+           validate_replace_rtx_1 (&XVECEXP (x, i, j), from, to, object, 
+                                    simplify);
+      }
+
+  /* If we didn't substitute, there is nothing more to do.  */
+  if (num_changes == prev_changes)
+    return;
+
+  /* Allow substituted expression to have different mode.  This is used by
+     regmove to change mode of pseudo register.  */
+  if (fmt[0] == 'e' && GET_MODE (XEXP (x, 0)) != VOIDmode)
+    op0_mode = GET_MODE (XEXP (x, 0));
+
+  /* Do changes needed to keep rtx consistent.  Don't do any other
+     simplifications, as it is not our job.  */
+  if (simplify)
+    simplify_while_replacing (loc, to, object, op0_mode);
+}
+
 /* Try replacing every occurrence of FROM in INSN with TO.  After all
    changes have been made, validate by seeing if INSN is still valid.  */
 
 int
 validate_replace_rtx (rtx from, rtx to, rtx insn)
 {
-  validate_replace_rtx_1 (&PATTERN (insn), from, to, insn);
+  validate_replace_rtx_1 (&PATTERN (insn), from, to, insn, true);
   return apply_change_group ();
 }
 
+/* Try replacing every occurrence of FROM in WHERE with TO.  Assume that WHERE
+   is a part of INSN.  After all changes have been made, validate by seeing if 
+   INSN is still valid.  
+   validate_replace_rtx (from, to, insn) is equivalent to 
+   validate_replace_rtx_part (from, to, &PATTERN (insn), insn).  */
+
+int
+validate_replace_rtx_part (rtx from, rtx to, rtx *where, rtx insn)
+{
+  validate_replace_rtx_1 (where, from, to, insn, true);
+  return apply_change_group ();
+}
+
+/* Same as above, but do not simplify rtx afterwards.  */
+int 
+validate_replace_rtx_part_nosimplify (rtx from, rtx to, rtx *where, 
+                                      rtx insn)
+{
+  validate_replace_rtx_1 (where, from, to, insn, false);
+  return apply_change_group ();
+
+}
+
 /* Try replacing every occurrence of FROM in INSN with TO.  */
 
 void
 validate_replace_rtx_group (rtx from, rtx to, rtx insn)
 {
-  validate_replace_rtx_1 (&PATTERN (insn), from, to, insn);
+  validate_replace_rtx_1 (&PATTERN (insn), from, to, insn, true);
 }
 
 /* Function called by note_uses to replace used subexpressions.  */
@@ -747,7 +786,7 @@ validate_replace_src_1 (rtx *x, void *data)
   struct validate_replace_src_data *d
     = (struct validate_replace_src_data *) data;
 
-  validate_replace_rtx_1 (x, d->from, d->to, d->insn);
+  validate_replace_rtx_1 (x, d->from, d->to, d->insn, true);
 }
 
 /* Try replacing every occurrence of FROM in INSN with TO, avoiding
index 6a2a2ca..9b73211 100644 (file)
@@ -87,6 +87,8 @@ extern int constrain_operands_cached (int);
 extern int memory_address_p (enum machine_mode, rtx);
 extern int strict_memory_address_p (enum machine_mode, rtx);
 extern int validate_replace_rtx (rtx, rtx, rtx);
+extern int validate_replace_rtx_part (rtx, rtx, rtx *, rtx);
+extern int validate_replace_rtx_part_nosimplify (rtx, rtx, rtx *, rtx);
 extern void validate_replace_rtx_group (rtx, rtx, rtx);
 extern void validate_replace_src_group (rtx, rtx, rtx);
 extern bool validate_simplify_insn (rtx insn);
index 6d53a78..97debd3 100644 (file)
--- a/gcc/rtl.c
+++ b/gcc/rtl.c
@@ -333,22 +333,29 @@ int generating_concat_p;
 int currently_expanding_to_rtl;
 
 \f
-/* Return 1 if X and Y are identical-looking rtx's.
-   This is the Lisp function EQUAL for rtx arguments.  */
+
+/* Same as rtx_equal_p, but call CB on each pair of rtx if CB is not NULL.  
+   When the callback returns true, we continue with the new pair.  */
 
 int
-rtx_equal_p (const_rtx x, const_rtx y)
+rtx_equal_p_cb (const_rtx x, const_rtx y, rtx_equal_p_callback_function cb)
 {
   int i;
   int j;
   enum rtx_code code;
   const char *fmt;
+  rtx nx, ny;
 
   if (x == y)
     return 1;
   if (x == 0 || y == 0)
     return 0;
 
+  /* Invoke the callback first.  */
+  if (cb != NULL
+      && ((*cb) (&x, &y, &nx, &ny)))
+    return rtx_equal_p_cb (nx, ny, cb);
+
   code = GET_CODE (x);
   /* Rtx's of different codes cannot be equal.  */
   if (code != GET_CODE (y))
@@ -409,12 +416,13 @@ rtx_equal_p (const_rtx x, const_rtx y)
 
          /* And the corresponding elements must match.  */
          for (j = 0; j < XVECLEN (x, i); j++)
-           if (rtx_equal_p (XVECEXP (x, i, j), XVECEXP (y, i, j)) == 0)
+           if (rtx_equal_p_cb (XVECEXP (x, i, j), 
+                                XVECEXP (y, i, j), cb) == 0)
              return 0;
          break;
 
        case 'e':
-         if (rtx_equal_p (XEXP (x, i), XEXP (y, i)) == 0)
+         if (rtx_equal_p_cb (XEXP (x, i), XEXP (y, i), cb) == 0)
            return 0;
          break;
 
@@ -444,6 +452,15 @@ rtx_equal_p (const_rtx x, const_rtx y)
   return 1;
 }
 
+/* Return 1 if X and Y are identical-looking rtx's.
+   This is the Lisp function EQUAL for rtx arguments.  */
+
+int
+rtx_equal_p (const_rtx x, const_rtx y)
+{
+  return rtx_equal_p_cb (x, y, NULL);
+}
+
 void
 dump_rtx_statistics (void)
 {
index 8b64789..4b04d28 100644 (file)
--- a/gcc/rtl.h
+++ b/gcc/rtl.h
@@ -1774,8 +1774,20 @@ extern int replace_label (rtx *, void *);
 extern int rtx_referenced_p (rtx, rtx);
 extern bool tablejump_p (const_rtx, rtx *, rtx *);
 extern int computed_jump_p (const_rtx);
+
 typedef int (*rtx_function) (rtx *, void *);
 extern int for_each_rtx (rtx *, rtx_function, void *);
+
+typedef int (*rtx_equal_p_callback_function) (const_rtx *, const_rtx *,
+                                              rtx *, rtx *);
+extern int rtx_equal_p_cb (const_rtx, const_rtx,
+                           rtx_equal_p_callback_function);
+
+typedef int (*hash_rtx_callback_function) (const_rtx, enum machine_mode, rtx *,
+                                           enum machine_mode *);
+extern unsigned hash_rtx_cb (const_rtx, enum machine_mode, int *, int *,
+                             bool, hash_rtx_callback_function);
+
 extern rtx regno_use_in (unsigned int, rtx);
 extern int auto_inc_p (const_rtx);
 extern int in_expr_list_p (const_rtx, const_rtx);
@@ -1796,14 +1808,17 @@ extern rtx get_condition (rtx, rtx *, int, int);
 
 /* lists.c */
 
-void free_EXPR_LIST_list               (rtx *);
-void free_INSN_LIST_list               (rtx *);
-void free_EXPR_LIST_node               (rtx);
-void free_INSN_LIST_node               (rtx);
-rtx alloc_INSN_LIST                    (rtx, rtx);
-rtx alloc_EXPR_LIST                    (int, rtx, rtx);
-void remove_free_INSN_LIST_elem (rtx, rtx *);
-rtx remove_list_elem (rtx, rtx *);
+extern void free_EXPR_LIST_list                (rtx *);
+extern void free_INSN_LIST_list                (rtx *);
+extern void free_EXPR_LIST_node                (rtx);
+extern void free_INSN_LIST_node                (rtx);
+extern rtx alloc_INSN_LIST                     (rtx, rtx);
+extern rtx alloc_EXPR_LIST                     (int, rtx, rtx);
+extern void remove_free_INSN_LIST_elem (rtx, rtx *);
+extern rtx remove_list_elem (rtx, rtx *);
+extern rtx remove_free_INSN_LIST_node (rtx *);
+extern rtx remove_free_EXPR_LIST_node (rtx *);
+
 
 /* regclass.c */
 
@@ -2133,7 +2148,9 @@ extern void dump_combine_total_stats (FILE *);
 extern void delete_dead_jumptables (void);
 
 /* In sched-vis.c.  */
-extern void print_insn (char *, rtx, int);
+extern void debug_bb_n_slim (int);
+extern void debug_bb_slim (struct basic_block_def *);
+extern void print_rtl_slim (FILE *, rtx, rtx, int, int);
 extern void print_rtl_slim_with_bb (FILE *, rtx, int);
 extern void dump_insn_slim (FILE *f, rtx x);
 extern void debug_insn_slim (rtx x);
@@ -2147,6 +2164,9 @@ extern void schedule_ebbs (void);
 /* In haifa-sched.c.  */
 extern void fix_sched_param (const char *, const char *);
 
+/* In sel-sched-dump.c.  */
+extern void sel_sched_fix_param (const char *param, const char *val);
+
 /* In print-rtl.c */
 extern const char *print_rtx_head;
 extern void debug_rtx (const_rtx);
@@ -2311,6 +2331,9 @@ extern rtx compare_and_jump_seq (rtx, rtx, enum rtx_code, rtx, int, rtx);
 /* In loop-iv.c  */
 extern rtx canon_condition (rtx);
 extern void simplify_using_condition (rtx, rtx *, struct bitmap_head_def *);
+
+/* In final.c  */
+extern unsigned int compute_alignments (void);
 \f
 struct rtl_hooks
 {
index a3bc52d..623d6ab 100644 (file)
@@ -34,7 +34,7 @@ along with GCC; see the file COPYING3.  If not see
   RTL_HOOKS_GEN_LOWPART_NO_EMIT,               \
   RTL_HOOKS_REG_NONZERO_REG_BITS,              \
   RTL_HOOKS_REG_NUM_SIGN_BIT_COPIES,           \
-  RTL_HOOKS_REG_TRUNCATED_TO_MODE,             \
+  RTL_HOOKS_REG_TRUNCATED_TO_MODE              \
 }
 
 extern rtx gen_lowpart_general (enum machine_mode, rtx);
index bbd7a36..b7aa6b4 100644 (file)
@@ -50,6 +50,12 @@ along with GCC; see the file COPYING3.  If not see
 #define CHECK (false)
 #endif
 
+/* Holds current parameters for the dependency analyzer.  */
+struct sched_deps_info_def *sched_deps_info;
+
+/* The data is specific to the Haifa scheduler.  */
+VEC(haifa_deps_insn_data_def, heap) *h_d_i_d = NULL;
+
 /* Return the major type present in the DS.  */
 enum reg_note
 ds_to_dk (ds_t ds)
@@ -388,17 +394,6 @@ clear_deps_list (deps_list_t l)
 static regset reg_pending_sets;
 static regset reg_pending_clobbers;
 static regset reg_pending_uses;
-
-/* The following enumeration values tell us what dependencies we
-   should use to implement the barrier.  We use true-dependencies for
-   TRUE_BARRIER and anti-dependencies for MOVE_BARRIER.  */
-enum reg_pending_barrier_mode
-{
-  NOT_A_BARRIER = 0,
-  MOVE_BARRIER,
-  TRUE_BARRIER
-};
-
 static enum reg_pending_barrier_mode reg_pending_barrier;
 
 /* To speed up the test for duplicate dependency links we keep a
@@ -414,15 +409,16 @@ static enum reg_pending_barrier_mode reg_pending_barrier;
    has enough entries to represent a dependency on any other insn in
    the insn chain.  All bitmap for true dependencies cache is
    allocated then the rest two ones are also allocated.  */
-static bitmap_head *true_dependency_cache;
-static bitmap_head *output_dependency_cache;
-static bitmap_head *anti_dependency_cache;
-static bitmap_head *spec_dependency_cache;
+static bitmap_head *true_dependency_cache = NULL;
+static bitmap_head *output_dependency_cache = NULL;
+static bitmap_head *anti_dependency_cache = NULL;
+static bitmap_head *spec_dependency_cache = NULL;
 static int cache_size;
 
 static int deps_may_trap_p (const_rtx);
 static void add_dependence_list (rtx, rtx, int, enum reg_note);
-static void add_dependence_list_and_free (rtx, rtx *, int, enum reg_note);
+static void add_dependence_list_and_free (struct deps *, rtx, 
+                                          rtx *, int, enum reg_note);
 static void delete_all_dependences (rtx);
 static void fixup_sched_groups (rtx);
 
@@ -431,14 +427,13 @@ static void sched_analyze_1 (struct deps *, rtx, rtx);
 static void sched_analyze_2 (struct deps *, rtx, rtx);
 static void sched_analyze_insn (struct deps *, rtx, rtx);
 
-static rtx sched_get_condition (const_rtx);
-static int conditions_mutex_p (const_rtx, const_rtx);
+static bool sched_has_condition_p (const_rtx);
+static int conditions_mutex_p (const_rtx, const_rtx, bool, bool);
 
 static enum DEPS_ADJUST_RESULT maybe_add_or_update_dep_1 (dep_t, bool,
                                                          rtx, rtx);
 static enum DEPS_ADJUST_RESULT add_or_update_dep_1 (dep_t, bool, rtx, rtx);
 
-static dw_t estimate_dep_weak (rtx, rtx);
 #ifdef ENABLE_CHECKING
 static void check_dep (dep_t, bool);
 #endif
@@ -459,10 +454,12 @@ deps_may_trap_p (const_rtx mem)
   return rtx_addr_can_trap_p (addr);
 }
 \f
-/* Find the condition under which INSN is executed.  */
 
+/* Find the condition under which INSN is executed.  If REV is not NULL,
+   it is set to TRUE when the returned comparison should be reversed
+   to get the actual condition.  */
 static rtx
-sched_get_condition (const_rtx insn)
+sched_get_condition_with_rev (const_rtx insn, bool *rev)
 {
   rtx pat = PATTERN (insn);
   rtx src;
@@ -470,6 +467,9 @@ sched_get_condition (const_rtx insn)
   if (pat == 0)
     return 0;
 
+  if (rev)
+    *rev = false;
+
   if (GET_CODE (pat) == COND_EXEC)
     return COND_EXEC_TEST (pat);
 
@@ -487,22 +487,34 @@ sched_get_condition (const_rtx insn)
 
       if (revcode == UNKNOWN)
        return 0;
-      return gen_rtx_fmt_ee (revcode, GET_MODE (cond), XEXP (cond, 0),
-                            XEXP (cond, 1));
+
+      if (rev)
+       *rev = true;
+      return cond;
     }
 
   return 0;
 }
 
+/* True when we can find a condition under which INSN is executed.  */
+static bool
+sched_has_condition_p (const_rtx insn)
+{
+  return !! sched_get_condition_with_rev (insn, NULL);
+}
+
 \f
-/* Return nonzero if conditions COND1 and COND2 can never be both true.  */
 
+/* Return nonzero if conditions COND1 and COND2 can never be both true.  */
 static int
-conditions_mutex_p (const_rtx cond1, const_rtx cond2)
+conditions_mutex_p (const_rtx cond1, const_rtx cond2, bool rev1, bool rev2)
 {
   if (COMPARISON_P (cond1)
       && COMPARISON_P (cond2)
-      && GET_CODE (cond1) == reversed_comparison_code (cond2, NULL)
+      && GET_CODE (cond1) ==
+         (rev1==rev2
+         ? reversed_comparison_code (cond2, NULL)
+         : GET_CODE (cond2))
       && XEXP (cond1, 0) == XEXP (cond2, 0)
       && XEXP (cond1, 1) == XEXP (cond2, 1))
     return 1;
@@ -515,15 +527,16 @@ bool
 sched_insns_conditions_mutex_p (const_rtx insn1, const_rtx insn2)
 {
   rtx cond1, cond2;
+  bool rev1, rev2;
 
   /* df doesn't handle conditional lifetimes entirely correctly;
      calls mess up the conditional lifetimes.  */
   if (!CALL_P (insn1) && !CALL_P (insn2))
     {
-      cond1 = sched_get_condition (insn1);
-      cond2 = sched_get_condition (insn2);
+      cond1 = sched_get_condition_with_rev (insn1, &rev1);
+      cond2 = sched_get_condition_with_rev (insn2, &rev2);
       if (cond1 && cond2
-         && conditions_mutex_p (cond1, cond2)
+         && conditions_mutex_p (cond1, cond2, rev1, rev2)
          /* Make sure first instruction doesn't affect condition of second
             instruction if switched.  */
          && !modified_in_p (cond1, insn2)
@@ -549,7 +562,7 @@ sched_insn_is_legitimate_for_speculation_p (const_rtx insn, ds_t ds)
   if (SCHED_GROUP_P (insn))
     return false;
 
-  if (IS_SPECULATION_CHECK_P (insn))
+  if (IS_SPECULATION_CHECK_P (CONST_CAST_RTX (insn)))
     return false;
 
   if (side_effects_p (PATTERN (insn)))
@@ -567,7 +580,7 @@ sched_insn_is_legitimate_for_speculation_p (const_rtx insn, ds_t ds)
        return false;
 
       if ((ds & BE_IN_DATA)
-         && sched_get_condition (insn) != NULL_RTX)
+         && sched_has_condition_p (insn))
        /* If this is a predicated instruction, then it cannot be
           speculatively scheduled.  See PR35659.  */
        return false;
@@ -792,7 +805,7 @@ maybe_add_or_update_dep_1 (dep_t dep, bool resolved_p, rtx mem1, rtx mem2)
   /* Don't depend an insn on itself.  */
   if (insn == elem)
     {
-      if (current_sched_info->flags & DO_SPECULATION)
+      if (sched_deps_info->generate_spec_deps)
         /* INSN has an internal dependence, which we can't overcome.  */
         HAS_INTERNAL_DEP (insn) = 1;
 
@@ -1119,7 +1132,7 @@ add_or_update_dep_1 (dep_t new_dep, bool resolved_p,
 
   if (mem1 != NULL_RTX)
     {
-      gcc_assert (current_sched_info->flags & DO_SPECULATION);
+      gcc_assert (sched_deps_info->generate_spec_deps);
       DEP_STATUS (new_dep) = set_dep_weak (DEP_STATUS (new_dep), BEGIN_DATA,
                                           estimate_dep_weak (mem1, mem2));
     }
@@ -1339,13 +1352,21 @@ add_dependence_list (rtx insn, rtx list, int uncond, enum reg_note dep_type)
     }
 }
 
-/* Similar, but free *LISTP at the same time.  */
+/* Similar, but free *LISTP at the same time, when the context 
+   is not readonly.  */
 
 static void
-add_dependence_list_and_free (rtx insn, rtx *listp, int uncond,
-                             enum reg_note dep_type)
+add_dependence_list_and_free (struct deps *deps, rtx insn, rtx *listp, 
+                              int uncond, enum reg_note dep_type)
 {
   rtx list, next;
+
+  if (deps->readonly)
+    {
+      add_dependence_list (insn, *listp, uncond, dep_type);
+      return;
+    }
+
   for (list = *listp, *listp = NULL; list ; list = next)
     {
       next = XEXP (list, 1);
@@ -1355,6 +1376,52 @@ add_dependence_list_and_free (rtx insn, rtx *listp, int uncond,
     }
 }
 
+/* Remove all occurences of INSN from LIST.  Return the number of 
+   occurences removed.  */
+
+static int
+remove_from_dependence_list (rtx insn, rtx* listp)
+{
+  int removed = 0;
+  
+  while (*listp)
+    {
+      if (XEXP (*listp, 0) == insn)
+        {
+          remove_free_INSN_LIST_node (listp);
+          removed++;
+          continue;
+        }
+      
+      listp = &XEXP (*listp, 1);
+    }
+  
+  return removed;
+}
+
+/* Same as above, but process two lists at once.  */
+static int 
+remove_from_both_dependence_lists (rtx insn, rtx *listp, rtx *exprp)
+{
+  int removed = 0;
+  
+  while (*listp)
+    {
+      if (XEXP (*listp, 0) == insn)
+        {
+          remove_free_INSN_LIST_node (listp);
+          remove_free_EXPR_LIST_node (exprp);
+          removed++;
+          continue;
+        }
+      
+      listp = &XEXP (*listp, 1);
+      exprp = &XEXP (*exprp, 1);
+    }
+  
+  return removed;
+}
+
 /* Clear all dependencies for an insn.  */
 static void
 delete_all_dependences (rtx insn)
@@ -1433,6 +1500,7 @@ add_insn_mem_dependence (struct deps *deps, bool read_p,
   rtx *mem_list;
   rtx link;
 
+  gcc_assert (!deps->readonly);
   if (read_p)
     {
       insn_list = &deps->pending_read_insns;
@@ -1449,7 +1517,7 @@ add_insn_mem_dependence (struct deps *deps, bool read_p,
   link = alloc_INSN_LIST (insn, *insn_list);
   *insn_list = link;
 
-  if (current_sched_info->use_cselib)
+  if (sched_deps_info->use_cselib)
     {
       mem = shallow_copy_rtx (mem);
       XEXP (mem, 0) = cselib_subst_to_values (XEXP (mem, 0));
@@ -1468,23 +1536,202 @@ flush_pending_lists (struct deps *deps, rtx insn, int for_read,
 {
   if (for_write)
     {
-      add_dependence_list_and_free (insn, &deps->pending_read_insns, 1,
-                                   REG_DEP_ANTI);
-      free_EXPR_LIST_list (&deps->pending_read_mems);
-      deps->pending_read_list_length = 0;
+      add_dependence_list_and_free (deps, insn, &deps->pending_read_insns, 
+                                    1, REG_DEP_ANTI);
+      if (!deps->readonly)
+        {
+          free_EXPR_LIST_list (&deps->pending_read_mems);
+          deps->pending_read_list_length = 0;
+        }
     }
 
-  add_dependence_list_and_free (insn, &deps->pending_write_insns, 1,
+  add_dependence_list_and_free (deps, insn, &deps->pending_write_insns, 1,
                                for_read ? REG_DEP_ANTI : REG_DEP_OUTPUT);
-  free_EXPR_LIST_list (&deps->pending_write_mems);
-  deps->pending_write_list_length = 0;
 
-  add_dependence_list_and_free (insn, &deps->last_pending_memory_flush, 1,
-                               for_read ? REG_DEP_ANTI : REG_DEP_OUTPUT);
-  deps->last_pending_memory_flush = alloc_INSN_LIST (insn, NULL_RTX);
-  deps->pending_flush_length = 1;
+  add_dependence_list_and_free (deps, insn, 
+                                &deps->last_pending_memory_flush, 1,
+                                for_read ? REG_DEP_ANTI : REG_DEP_OUTPUT);
+  if (!deps->readonly)
+    {
+      free_EXPR_LIST_list (&deps->pending_write_mems);
+      deps->pending_write_list_length = 0;
+
+      deps->last_pending_memory_flush = alloc_INSN_LIST (insn, NULL_RTX);
+      deps->pending_flush_length = 1;
+    }
+}
+\f
+/* Instruction which dependencies we are analyzing.  */
+static rtx cur_insn = NULL_RTX;
+
+/* Implement hooks for haifa scheduler.  */
+
+static void
+haifa_start_insn (rtx insn)
+{
+  gcc_assert (insn && !cur_insn);
+
+  cur_insn = insn;
+}
+
+static void
+haifa_finish_insn (void)
+{
+  cur_insn = NULL;
+}
+
+void
+haifa_note_reg_set (int regno)
+{
+  SET_REGNO_REG_SET (reg_pending_sets, regno);
+}
+
+void
+haifa_note_reg_clobber (int regno)
+{
+  SET_REGNO_REG_SET (reg_pending_clobbers, regno);
+}
+
+void
+haifa_note_reg_use (int regno)
+{
+  SET_REGNO_REG_SET (reg_pending_uses, regno);
+}
+
+static void
+haifa_note_mem_dep (rtx mem, rtx pending_mem, rtx pending_insn, ds_t ds)
+{
+  if (!(ds & SPECULATIVE))
+    {
+      mem = NULL_RTX;
+      pending_mem = NULL_RTX;
+    }
+  else
+    gcc_assert (ds & BEGIN_DATA);
+
+  {
+    dep_def _dep, *dep = &_dep;
+    
+    init_dep_1 (dep, pending_insn, cur_insn, ds_to_dt (ds), 
+                current_sched_info->flags & USE_DEPS_LIST ? ds : -1);
+    maybe_add_or_update_dep_1 (dep, false, pending_mem, mem);
+  }
+
+}
+
+static void
+haifa_note_dep (rtx elem, ds_t ds)
+{
+  dep_def _dep;
+  dep_t dep = &_dep;
+
+  init_dep (dep, elem, cur_insn, ds_to_dt (ds));
+  maybe_add_or_update_dep_1 (dep, false, NULL_RTX, NULL_RTX);
+}
+
+static void
+note_reg_use (int r)
+{
+  if (sched_deps_info->note_reg_use)
+    sched_deps_info->note_reg_use (r);
+}
+
+static void
+note_reg_set (int r)
+{
+  if (sched_deps_info->note_reg_set)
+    sched_deps_info->note_reg_set (r);
+}
+
+static void
+note_reg_clobber (int r)
+{
+  if (sched_deps_info->note_reg_clobber)
+    sched_deps_info->note_reg_clobber (r);
+}
+
+static void
+note_mem_dep (rtx m1, rtx m2, rtx e, ds_t ds)
+{
+  if (sched_deps_info->note_mem_dep)
+    sched_deps_info->note_mem_dep (m1, m2, e, ds);
+}
+
+static void
+note_dep (rtx e, ds_t ds)
+{
+  if (sched_deps_info->note_dep)
+    sched_deps_info->note_dep (e, ds);
+}
+
+/* Return corresponding to DS reg_note.  */
+enum reg_note
+ds_to_dt (ds_t ds)
+{
+  if (ds & DEP_TRUE)
+    return REG_DEP_TRUE;
+  else if (ds & DEP_OUTPUT)
+    return REG_DEP_OUTPUT;
+  else
+    {
+      gcc_assert (ds & DEP_ANTI);
+      return REG_DEP_ANTI;
+    }
 }
 \f
+
+/* Internal variable for sched_analyze_[12] () functions.
+   If it is nonzero, this means that sched_analyze_[12] looks
+   at the most toplevel SET.  */
+static bool can_start_lhs_rhs_p;
+
+/* Extend reg info for the deps context DEPS given that 
+   we have just generated a register numbered REGNO.  */
+static void
+extend_deps_reg_info (struct deps *deps, int regno)
+{
+  int max_regno = regno + 1;
+
+  gcc_assert (!reload_completed);
+
+  /* In a readonly context, it would not hurt to extend info,
+     but it should not be needed.  */
+  if (reload_completed && deps->readonly)
+    {
+      deps->max_reg = max_regno;
+      return;
+    }
+
+  if (max_regno > deps->max_reg)
+    {
+      deps->reg_last = XRESIZEVEC (struct deps_reg, deps->reg_last, 
+                                   max_regno);
+      memset (&deps->reg_last[deps->max_reg],
+              0, (max_regno - deps->max_reg) 
+              * sizeof (struct deps_reg));
+      deps->max_reg = max_regno;
+    }
+}
+
+/* Extends REG_INFO_P if needed.  */
+void
+maybe_extend_reg_info_p (void)
+{
+  /* Extend REG_INFO_P, if needed.  */
+  if ((unsigned int)max_regno - 1 >= reg_info_p_size)
+    {
+      size_t new_reg_info_p_size = max_regno + 128;
+
+      gcc_assert (!reload_completed && sel_sched_p ());
+
+      reg_info_p = (struct reg_info_t *) xrecalloc (reg_info_p,
+                                                    new_reg_info_p_size,
+                                                    reg_info_p_size,
+                                                    sizeof (*reg_info_p));
+      reg_info_p_size = new_reg_info_p_size;
+    }
+}
+
 /* Analyze a single reference to register (reg:MODE REGNO) in INSN.
    The type of the reference is specified by REF and can be SET,
    CLOBBER, PRE_DEC, POST_DEC, PRE_INC, POST_INC or USE.  */
@@ -1493,6 +1740,13 @@ static void
 sched_analyze_reg (struct deps *deps, int regno, enum machine_mode mode,
                   enum rtx_code ref, rtx insn)
 {
+  /* We could emit new pseudos in renaming.  Extend the reg structures.  */
+  if (!reload_completed && sel_sched_p ()
+      && (regno >= max_reg_num () - 1 || regno >= deps->max_reg))
+    extend_deps_reg_info (deps, regno);
+
+  maybe_extend_reg_info_p ();
+
   /* A hard reg in a wide mode may really be multiple registers.
      If so, mark all of them just like the first.  */
   if (regno < FIRST_PSEUDO_REGISTER)
@@ -1501,17 +1755,17 @@ sched_analyze_reg (struct deps *deps, int regno, enum machine_mode mode,
       if (ref == SET)
        {
          while (--i >= 0)
-           SET_REGNO_REG_SET (reg_pending_sets, regno + i);
+           note_reg_set (regno + i);
        }
       else if (ref == USE)
        {
          while (--i >= 0)
-           SET_REGNO_REG_SET (reg_pending_uses, regno + i);
+           note_reg_use (regno + i);
        }
       else
        {
          while (--i >= 0)
-           SET_REGNO_REG_SET (reg_pending_clobbers, regno + i);
+           note_reg_clobber (regno + i);
        }
     }
 
@@ -1527,11 +1781,11 @@ sched_analyze_reg (struct deps *deps, int regno, enum machine_mode mode,
   else
     {
       if (ref == SET)
-       SET_REGNO_REG_SET (reg_pending_sets, regno);
+       note_reg_set (regno);
       else if (ref == USE)
-       SET_REGNO_REG_SET (reg_pending_uses, regno);
+       note_reg_use (regno);
       else
-       SET_REGNO_REG_SET (reg_pending_clobbers, regno);
+       note_reg_clobber (regno);
 
       /* Pseudos that are REG_EQUIV to something may be replaced
         by that during reloading.  We need only add dependencies for
@@ -1547,7 +1801,8 @@ sched_analyze_reg (struct deps *deps, int regno, enum machine_mode mode,
         already cross one.  */
       if (REG_N_CALLS_CROSSED (regno) == 0)
        {
-         if (ref == USE)
+         if (!deps->readonly 
+              && ref == USE)
            deps->sched_before_next_call
              = alloc_INSN_LIST (insn, deps->sched_before_next_call);
          else
@@ -1566,10 +1821,17 @@ sched_analyze_1 (struct deps *deps, rtx x, rtx insn)
 {
   rtx dest = XEXP (x, 0);
   enum rtx_code code = GET_CODE (x);
+  bool cslr_p = can_start_lhs_rhs_p;
 
+  can_start_lhs_rhs_p = false;
+
+  gcc_assert (dest);
   if (dest == 0)
     return;
 
+  if (cslr_p && sched_deps_info->start_lhs)
+    sched_deps_info->start_lhs (dest);
+
   if (GET_CODE (dest) == PARALLEL)
     {
       int i;
@@ -1581,8 +1843,18 @@ sched_analyze_1 (struct deps *deps, rtx x, rtx insn)
                                            XEXP (XVECEXP (dest, 0, i), 0)),
                           insn);
 
-      if (GET_CODE (x) == SET)
-       sched_analyze_2 (deps, SET_SRC (x), insn);
+      if (cslr_p && sched_deps_info->finish_lhs)
+       sched_deps_info->finish_lhs ();
+
+      if (code == SET)
+       {
+         can_start_lhs_rhs_p = cslr_p;
+
+         sched_analyze_2 (deps, SET_SRC (x), insn);
+
+         can_start_lhs_rhs_p = false;
+       }
+
       return;
     }
 
@@ -1633,7 +1905,7 @@ sched_analyze_1 (struct deps *deps, rtx x, rtx insn)
       /* Writing memory.  */
       rtx t = dest;
 
-      if (current_sched_info->use_cselib)
+      if (sched_deps_info->use_cselib)
        {
          t = shallow_copy_rtx (dest);
          cselib_lookup (XEXP (t, 0), Pmode, 1);
@@ -1641,8 +1913,10 @@ sched_analyze_1 (struct deps *deps, rtx x, rtx insn)
        }
       t = canon_rtx (t);
 
-      if ((deps->pending_read_list_length + deps->pending_write_list_length)
-         > MAX_PENDING_LIST_LENGTH)
+      /* Pending lists can't get larger with a readonly context.  */
+      if (!deps->readonly
+          && ((deps->pending_read_list_length + deps->pending_write_list_length)
+              > MAX_PENDING_LIST_LENGTH))
        {
          /* Flush all pending reads and writes to prevent the pending lists
             from getting any larger.  Insn scheduling runs too slowly when
@@ -1661,7 +1935,8 @@ sched_analyze_1 (struct deps *deps, rtx x, rtx insn)
            {
              if (anti_dependence (XEXP (pending_mem, 0), t)
                  && ! sched_insns_conditions_mutex_p (insn, XEXP (pending, 0)))
-               add_dependence (insn, XEXP (pending, 0), REG_DEP_ANTI);
+               note_mem_dep (t, XEXP (pending_mem, 0), XEXP (pending, 0),
+                             DEP_ANTI);
 
              pending = XEXP (pending, 1);
              pending_mem = XEXP (pending_mem, 1);
@@ -1673,7 +1948,8 @@ sched_analyze_1 (struct deps *deps, rtx x, rtx insn)
            {
              if (output_dependence (XEXP (pending_mem, 0), t)
                  && ! sched_insns_conditions_mutex_p (insn, XEXP (pending, 0)))
-               add_dependence (insn, XEXP (pending, 0), REG_DEP_OUTPUT);
+               note_mem_dep (t, XEXP (pending_mem, 0), XEXP (pending, 0),
+                             DEP_OUTPUT);
 
              pending = XEXP (pending, 1);
              pending_mem = XEXP (pending_mem, 1);
@@ -1682,18 +1958,27 @@ sched_analyze_1 (struct deps *deps, rtx x, rtx insn)
          add_dependence_list (insn, deps->last_pending_memory_flush, 1,
                               REG_DEP_ANTI);
 
-         add_insn_mem_dependence (deps, false, insn, dest);
+          if (!deps->readonly)
+            add_insn_mem_dependence (deps, false, insn, dest);
        }
       sched_analyze_2 (deps, XEXP (dest, 0), insn);
     }
 
+  if (cslr_p && sched_deps_info->finish_lhs)
+    sched_deps_info->finish_lhs ();
+
   /* Analyze reads.  */
   if (GET_CODE (x) == SET)
-    sched_analyze_2 (deps, SET_SRC (x), insn);
+    {
+      can_start_lhs_rhs_p = cslr_p;
+
+      sched_analyze_2 (deps, SET_SRC (x), insn);
+
+      can_start_lhs_rhs_p = false;
+    }
 }
 
 /* Analyze the uses of memory and registers in rtx X in INSN.  */
-
 static void
 sched_analyze_2 (struct deps *deps, rtx x, rtx insn)
 {
@@ -1701,10 +1986,17 @@ sched_analyze_2 (struct deps *deps, rtx x, rtx insn)
   int j;
   enum rtx_code code;
   const char *fmt;
+  bool cslr_p = can_start_lhs_rhs_p;
+
+  can_start_lhs_rhs_p = false;
 
+  gcc_assert (x);
   if (x == 0)
     return;
 
+  if (cslr_p && sched_deps_info->start_rhs)
+    sched_deps_info->start_rhs (x);
+
   code = GET_CODE (x);
 
   switch (code)
@@ -1719,6 +2011,10 @@ sched_analyze_2 (struct deps *deps, rtx x, rtx insn)
       /* Ignore constants.  Note that we must handle CONST_DOUBLE here
          because it may have a cc0_rtx in its CONST_DOUBLE_CHAIN field, but
          this does not mean that this insn is using cc0.  */
+
+      if (cslr_p && sched_deps_info->finish_rhs)
+       sched_deps_info->finish_rhs ();
+
       return;
 
 #ifdef HAVE_cc0
@@ -1728,6 +2024,10 @@ sched_analyze_2 (struct deps *deps, rtx x, rtx insn)
        /* Don't move CC0 setter to another block (it can set up the
         same flag for previous CC0 users which is safe).  */
       CANT_MOVE (prev_nonnote_insn (insn)) = 1;
+
+      if (cslr_p && sched_deps_info->finish_rhs)
+       sched_deps_info->finish_rhs ();
+
       return;
 #endif
 
@@ -1748,6 +2048,10 @@ sched_analyze_2 (struct deps *deps, rtx x, rtx insn)
          sched_analyze_reg (deps, FIRST_STACK_REG, mode, SET, insn);
        }
 #endif
+
+       if (cslr_p && sched_deps_info->finish_rhs)
+         sched_deps_info->finish_rhs ();
+
        return;
       }
 
@@ -1758,7 +2062,7 @@ sched_analyze_2 (struct deps *deps, rtx x, rtx insn)
        rtx pending, pending_mem;
        rtx t = x;
 
-       if (current_sched_info->use_cselib)
+       if (sched_deps_info->use_cselib)
          {
            t = shallow_copy_rtx (t);
            cselib_lookup (XEXP (t, 0), Pmode, 1);
@@ -1771,7 +2075,8 @@ sched_analyze_2 (struct deps *deps, rtx x, rtx insn)
          {
            if (read_dependence (XEXP (pending_mem, 0), t)
                && ! sched_insns_conditions_mutex_p (insn, XEXP (pending, 0)))
-             add_dependence (insn, XEXP (pending, 0), REG_DEP_ANTI);
+             note_mem_dep (t, XEXP (pending_mem, 0), XEXP (pending, 0),
+                           DEP_ANTI);
 
            pending = XEXP (pending, 1);
            pending_mem = XEXP (pending_mem, 1);
@@ -1784,38 +2089,44 @@ sched_analyze_2 (struct deps *deps, rtx x, rtx insn)
            if (true_dependence (XEXP (pending_mem, 0), VOIDmode,
                                 t, rtx_varies_p)
                && ! sched_insns_conditions_mutex_p (insn, XEXP (pending, 0)))
-              {
-                if ((current_sched_info->flags & DO_SPECULATION)
-                   && (spec_info->mask & BEGIN_DATA))
-                 /* Create a data-speculative dependence between producer
-                    and consumer.  */
-                 {
-                   dep_def _dep, *dep = &_dep;
-
-                   init_dep_1 (dep, XEXP (pending, 0), insn, REG_DEP_TRUE,
-                               BEGIN_DATA | DEP_TRUE);
-
-                   maybe_add_or_update_dep_1 (dep, false,
-                                              XEXP (pending_mem, 0), t);
-                 }
-                else
-                  add_dependence (insn, XEXP (pending, 0), REG_DEP_TRUE);
-              }
+             note_mem_dep (t, XEXP (pending_mem, 0), XEXP (pending, 0),
+                           sched_deps_info->generate_spec_deps
+                           ? BEGIN_DATA | DEP_TRUE : DEP_TRUE);
 
            pending = XEXP (pending, 1);
            pending_mem = XEXP (pending_mem, 1);
          }
 
        for (u = deps->last_pending_memory_flush; u; u = XEXP (u, 1))
-         if (! JUMP_P (XEXP (u, 0)) || deps_may_trap_p (x))
-           add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
+         {
+           if (! JUMP_P (XEXP (u, 0)))
+             add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
+           else if (deps_may_trap_p (x))
+             {
+               if ((sched_deps_info->generate_spec_deps)
+                   && sel_sched_p () && (spec_info->mask & BEGIN_CONTROL))
+                 {
+                   ds_t ds = set_dep_weak (DEP_ANTI, BEGIN_CONTROL,
+                                           MAX_DEP_WEAK);
+
+                   note_dep (XEXP (u, 0), ds);
+                 }
+               else
+                 add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
+             }
+         }
 
        /* Always add these dependencies to pending_reads, since
           this insn may be followed by a write.  */
-       add_insn_mem_dependence (deps, true, insn, x);
+        if (!deps->readonly)
+          add_insn_mem_dependence (deps, true, insn, x);
 
        /* Take advantage of tail recursion here.  */
        sched_analyze_2 (deps, XEXP (x, 0), insn);
+
+       if (cslr_p && sched_deps_info->finish_rhs)
+         sched_deps_info->finish_rhs ();
+
        return;
       }
 
@@ -1847,6 +2158,10 @@ sched_analyze_2 (struct deps *deps, rtx x, rtx insn)
          {
            for (j = 0; j < ASM_OPERANDS_INPUT_LENGTH (x); j++)
              sched_analyze_2 (deps, ASM_OPERANDS_INPUT (x, j), insn);
+
+           if (cslr_p && sched_deps_info->finish_rhs)
+             sched_deps_info->finish_rhs ();
+
            return;
          }
        break;
@@ -1864,6 +2179,10 @@ sched_analyze_2 (struct deps *deps, rtx x, rtx insn)
          to get the proper antecedent for the read.  */
       sched_analyze_2 (deps, XEXP (x, 0), insn);
       sched_analyze_1 (deps, x, insn);
+
+      if (cslr_p && sched_deps_info->finish_rhs)
+       sched_deps_info->finish_rhs ();
+
       return;
 
     case POST_MODIFY:
@@ -1872,6 +2191,10 @@ sched_analyze_2 (struct deps *deps, rtx x, rtx insn)
       sched_analyze_2 (deps, XEXP (x, 0), insn);
       sched_analyze_2 (deps, XEXP (x, 1), insn);
       sched_analyze_1 (deps, x, insn);
+
+      if (cslr_p && sched_deps_info->finish_rhs)
+       sched_deps_info->finish_rhs ();
+
       return;
 
     default:
@@ -1888,10 +2211,12 @@ sched_analyze_2 (struct deps *deps, rtx x, rtx insn)
        for (j = 0; j < XVECLEN (x, i); j++)
          sched_analyze_2 (deps, XVECEXP (x, i, j), insn);
     }
+
+  if (cslr_p && sched_deps_info->finish_rhs)
+    sched_deps_info->finish_rhs ();
 }
 
 /* Analyze an INSN with pattern X to find all dependencies.  */
-
 static void
 sched_analyze_insn (struct deps *deps, rtx x, rtx insn)
 {
@@ -1900,6 +2225,9 @@ sched_analyze_insn (struct deps *deps, rtx x, rtx insn)
   unsigned i;
   reg_set_iterator rsi;
 
+  can_start_lhs_rhs_p = (NONJUMP_INSN_P (insn)
+                        && code == SET);
+
   if (code == COND_EXEC)
     {
       sched_analyze_2 (deps, COND_EXEC_TEST (x), insn);
@@ -1964,25 +2292,34 @@ sched_analyze_insn (struct deps *deps, rtx x, rtx insn)
       else
        {
          rtx pending, pending_mem;
-         regset_head tmp_uses, tmp_sets;
-         INIT_REG_SET (&tmp_uses);
-         INIT_REG_SET (&tmp_sets);
-
-         (*current_sched_info->compute_jump_reg_dependencies)
-           (insn, &deps->reg_conditional_sets, &tmp_uses, &tmp_sets);
-         /* Make latency of jump equal to 0 by using anti-dependence.  */
-         EXECUTE_IF_SET_IN_REG_SET (&tmp_uses, 0, i, rsi)
-           {
-             struct deps_reg *reg_last = &deps->reg_last[i];
-             add_dependence_list (insn, reg_last->sets, 0, REG_DEP_ANTI);
-             add_dependence_list (insn, reg_last->clobbers, 0, REG_DEP_ANTI);
-             reg_last->uses_length++;
-             reg_last->uses = alloc_INSN_LIST (insn, reg_last->uses);
-           }
-         IOR_REG_SET (reg_pending_sets, &tmp_sets);
 
-         CLEAR_REG_SET (&tmp_uses);
-         CLEAR_REG_SET (&tmp_sets);
+          if (sched_deps_info->compute_jump_reg_dependencies)
+            {
+              regset_head tmp_uses, tmp_sets;
+              INIT_REG_SET (&tmp_uses);
+              INIT_REG_SET (&tmp_sets);
+
+              (*sched_deps_info->compute_jump_reg_dependencies)
+                (insn, &deps->reg_conditional_sets, &tmp_uses, &tmp_sets);
+              /* Make latency of jump equal to 0 by using anti-dependence.  */
+              EXECUTE_IF_SET_IN_REG_SET (&tmp_uses, 0, i, rsi)
+                {
+                  struct deps_reg *reg_last = &deps->reg_last[i];
+                  add_dependence_list (insn, reg_last->sets, 0, REG_DEP_ANTI);
+                  add_dependence_list (insn, reg_last->clobbers, 0,
+                                      REG_DEP_ANTI);
+
+                  if (!deps->readonly)
+                    {
+                      reg_last->uses_length++;
+                      reg_last->uses = alloc_INSN_LIST (insn, reg_last->uses);
+                    }
+                }
+              IOR_REG_SET (reg_pending_sets, &tmp_sets);
+
+              CLEAR_REG_SET (&tmp_uses);
+              CLEAR_REG_SET (&tmp_sets);
+            }
 
          /* All memory writes and volatile reads must happen before the
             jump.  Non-volatile reads must happen before the jump iff
@@ -2024,89 +2361,123 @@ sched_analyze_insn (struct deps *deps, rtx x, rtx insn)
       || (NONJUMP_INSN_P (insn) && control_flow_insn_p (insn)))
     reg_pending_barrier = MOVE_BARRIER;
 
-  /* Add register dependencies for insn.
-     If the current insn is conditional, we can't free any of the lists.  */
-  if (sched_get_condition (insn))
+  /* If the current insn is conditional, we can't free any
+     of the lists.  */
+  if (sched_has_condition_p (insn))
     {
       EXECUTE_IF_SET_IN_REG_SET (reg_pending_uses, 0, i, rsi)
-       {
-         struct deps_reg *reg_last = &deps->reg_last[i];
-         add_dependence_list (insn, reg_last->sets, 0, REG_DEP_TRUE);
-         add_dependence_list (insn, reg_last->clobbers, 0, REG_DEP_TRUE);
-         reg_last->uses = alloc_INSN_LIST (insn, reg_last->uses);
-         reg_last->uses_length++;
-       }
+        {
+          struct deps_reg *reg_last = &deps->reg_last[i];
+          add_dependence_list (insn, reg_last->sets, 0, REG_DEP_TRUE);
+          add_dependence_list (insn, reg_last->clobbers, 0, REG_DEP_TRUE);
+              
+          if (!deps->readonly)
+            {
+              reg_last->uses = alloc_INSN_LIST (insn, reg_last->uses);
+              reg_last->uses_length++;
+            }
+        }
       EXECUTE_IF_SET_IN_REG_SET (reg_pending_clobbers, 0, i, rsi)
-       {
-         struct deps_reg *reg_last = &deps->reg_last[i];
-         add_dependence_list (insn, reg_last->sets, 0, REG_DEP_OUTPUT);
-         add_dependence_list (insn, reg_last->uses, 0, REG_DEP_ANTI);
-         reg_last->clobbers = alloc_INSN_LIST (insn, reg_last->clobbers);
-         reg_last->clobbers_length++;
-       }
+        {
+          struct deps_reg *reg_last = &deps->reg_last[i];
+          add_dependence_list (insn, reg_last->sets, 0, REG_DEP_OUTPUT);
+          add_dependence_list (insn, reg_last->uses, 0, REG_DEP_ANTI);
+
+          if (!deps->readonly)
+            {
+              reg_last->clobbers = alloc_INSN_LIST (insn, reg_last->clobbers);
+              reg_last->clobbers_length++;
+            }
+        }
       EXECUTE_IF_SET_IN_REG_SET (reg_pending_sets, 0, i, rsi)
-       {
-         struct deps_reg *reg_last = &deps->reg_last[i];
-         add_dependence_list (insn, reg_last->sets, 0, REG_DEP_OUTPUT);
-         add_dependence_list (insn, reg_last->clobbers, 0, REG_DEP_OUTPUT);
-         add_dependence_list (insn, reg_last->uses, 0, REG_DEP_ANTI);
-         reg_last->sets = alloc_INSN_LIST (insn, reg_last->sets);
-         SET_REGNO_REG_SET (&deps->reg_conditional_sets, i);
-       }
+        {
+          struct deps_reg *reg_last = &deps->reg_last[i];
+          add_dependence_list (insn, reg_last->sets, 0, REG_DEP_OUTPUT);
+          add_dependence_list (insn, reg_last->clobbers, 0, REG_DEP_OUTPUT);
+          add_dependence_list (insn, reg_last->uses, 0, REG_DEP_ANTI);
+
+          if (!deps->readonly)
+            {
+              reg_last->sets = alloc_INSN_LIST (insn, reg_last->sets);
+              SET_REGNO_REG_SET (&deps->reg_conditional_sets, i);
+            }
+        }
     }
   else
     {
       EXECUTE_IF_SET_IN_REG_SET (reg_pending_uses, 0, i, rsi)
-       {
-         struct deps_reg *reg_last = &deps->reg_last[i];
-         add_dependence_list (insn, reg_last->sets, 0, REG_DEP_TRUE);
-         add_dependence_list (insn, reg_last->clobbers, 0, REG_DEP_TRUE);
-         reg_last->uses_length++;
-         reg_last->uses = alloc_INSN_LIST (insn, reg_last->uses);
-       }
+        {
+          struct deps_reg *reg_last = &deps->reg_last[i];
+          add_dependence_list (insn, reg_last->sets, 0, REG_DEP_TRUE);
+          add_dependence_list (insn, reg_last->clobbers, 0, REG_DEP_TRUE);
+
+          if (!deps->readonly)
+            {
+              reg_last->uses_length++;
+              reg_last->uses = alloc_INSN_LIST (insn, reg_last->uses);
+            }
+        }
       EXECUTE_IF_SET_IN_REG_SET (reg_pending_clobbers, 0, i, rsi)
-       {
-         struct deps_reg *reg_last = &deps->reg_last[i];
-         if (reg_last->uses_length > MAX_PENDING_LIST_LENGTH
-             || reg_last->clobbers_length > MAX_PENDING_LIST_LENGTH)
-           {
-             add_dependence_list_and_free (insn, &reg_last->sets, 0,
-                                           REG_DEP_OUTPUT);
-             add_dependence_list_and_free (insn, &reg_last->uses, 0,
-                                           REG_DEP_ANTI);
-             add_dependence_list_and_free (insn, &reg_last->clobbers, 0,
-                                           REG_DEP_OUTPUT);
-             reg_last->sets = alloc_INSN_LIST (insn, reg_last->sets);
-             reg_last->clobbers_length = 0;
-             reg_last->uses_length = 0;
-           }
-         else
-           {
-             add_dependence_list (insn, reg_last->sets, 0, REG_DEP_OUTPUT);
-             add_dependence_list (insn, reg_last->uses, 0, REG_DEP_ANTI);
-           }
-         reg_last->clobbers_length++;
-         reg_last->clobbers = alloc_INSN_LIST (insn, reg_last->clobbers);
-       }
+        {
+          struct deps_reg *reg_last = &deps->reg_last[i];
+          if (reg_last->uses_length > MAX_PENDING_LIST_LENGTH
+              || reg_last->clobbers_length > MAX_PENDING_LIST_LENGTH)
+            {
+              add_dependence_list_and_free (deps, insn, &reg_last->sets, 0,
+                                            REG_DEP_OUTPUT);
+              add_dependence_list_and_free (deps, insn, &reg_last->uses, 0,
+                                            REG_DEP_ANTI);
+              add_dependence_list_and_free (deps, insn, &reg_last->clobbers, 0,
+                                            REG_DEP_OUTPUT);
+
+              if (!deps->readonly)
+                {
+                  reg_last->sets = alloc_INSN_LIST (insn, reg_last->sets);
+                  reg_last->clobbers_length = 0;
+                  reg_last->uses_length = 0;
+                }
+            }
+          else
+            {
+              add_dependence_list (insn, reg_last->sets, 0, REG_DEP_OUTPUT);
+              add_dependence_list (insn, reg_last->uses, 0, REG_DEP_ANTI);
+            }
+
+          if (!deps->readonly)
+            {
+              reg_last->clobbers_length++;
+              reg_last->clobbers = alloc_INSN_LIST (insn, reg_last->clobbers);
+            }
+        }
       EXECUTE_IF_SET_IN_REG_SET (reg_pending_sets, 0, i, rsi)
-       {
-         struct deps_reg *reg_last = &deps->reg_last[i];
-         add_dependence_list_and_free (insn, &reg_last->sets, 0,
-                                       REG_DEP_OUTPUT);
-         add_dependence_list_and_free (insn, &reg_last->clobbers, 0,
-                                       REG_DEP_OUTPUT);
-         add_dependence_list_and_free (insn, &reg_last->uses, 0,
-                                       REG_DEP_ANTI);
-         reg_last->sets = alloc_INSN_LIST (insn, reg_last->sets);
-         reg_last->uses_length = 0;
-         reg_last->clobbers_length = 0;
-         CLEAR_REGNO_REG_SET (&deps->reg_conditional_sets, i);
-       }
+        {
+          struct deps_reg *reg_last = &deps->reg_last[i];
+          add_dependence_list_and_free (deps, insn, &reg_last->sets, 0,
+                                        REG_DEP_OUTPUT);
+          add_dependence_list_and_free (deps, insn, &reg_last->clobbers, 0,
+                                        REG_DEP_OUTPUT);
+          add_dependence_list_and_free (deps, insn, &reg_last->uses, 0,
+                                        REG_DEP_ANTI);
+
+          if (!deps->readonly)
+            {
+              reg_last->sets = alloc_INSN_LIST (insn, reg_last->sets);
+              reg_last->uses_length = 0;
+              reg_last->clobbers_length = 0;
+              CLEAR_REGNO_REG_SET (&deps->reg_conditional_sets, i);
+            }
+        }
     }
 
-  IOR_REG_SET (&deps->reg_last_in_use, reg_pending_uses);
-  IOR_REG_SET (&deps->reg_last_in_use, reg_pending_clobbers);
-  IOR_REG_SET (&deps->reg_last_in_use, reg_pending_sets);
+  if (!deps->readonly)
+    {
+      IOR_REG_SET (&deps->reg_last_in_use, reg_pending_uses);
+      IOR_REG_SET (&deps->reg_last_in_use, reg_pending_clobbers);
+      IOR_REG_SET (&deps->reg_last_in_use, reg_pending_sets);
+
+      /* Set up the pending barrier found.  */
+      deps->last_reg_pending_barrier = reg_pending_barrier;
+    }
 
   CLEAR_REG_SET (reg_pending_uses);
   CLEAR_REG_SET (reg_pending_clobbers);
@@ -2117,7 +2488,7 @@ sched_analyze_insn (struct deps *deps, rtx x, rtx insn)
     {
       /* In the case of barrier the most added dependencies are not
          real, so we use anti-dependence here.  */
-      if (sched_get_condition (insn))
+      if (sched_has_condition_p (insn))
        {
          EXECUTE_IF_SET_IN_REG_SET (&deps->reg_last_in_use, 0, i, rsi)
            {
@@ -2136,28 +2507,38 @@ sched_analyze_insn (struct deps *deps, rtx x, rtx insn)
          EXECUTE_IF_SET_IN_REG_SET (&deps->reg_last_in_use, 0, i, rsi)
            {
              struct deps_reg *reg_last = &deps->reg_last[i];
-             add_dependence_list_and_free (insn, &reg_last->uses, 0,
+             add_dependence_list_and_free (deps, insn, &reg_last->uses, 0,
                                            REG_DEP_ANTI);
              add_dependence_list_and_free
-               (insn, &reg_last->sets, 0,
+               (deps, insn, &reg_last->sets, 0,
                 reg_pending_barrier == TRUE_BARRIER ? REG_DEP_TRUE : REG_DEP_ANTI);
              add_dependence_list_and_free
-               (insn, &reg_last->clobbers, 0,
+               (deps, insn, &reg_last->clobbers, 0,
                 reg_pending_barrier == TRUE_BARRIER ? REG_DEP_TRUE : REG_DEP_ANTI);
-             reg_last->uses_length = 0;
-             reg_last->clobbers_length = 0;
-           }
-       }
 
-      for (i = 0; i < (unsigned)deps->max_reg; i++)
-       {
-         struct deps_reg *reg_last = &deps->reg_last[i];
-         reg_last->sets = alloc_INSN_LIST (insn, reg_last->sets);
-         SET_REGNO_REG_SET (&deps->reg_last_in_use, i);
+              if (!deps->readonly)
+                {
+                  reg_last->uses_length = 0;
+                  reg_last->clobbers_length = 0;
+                }
+           }
        }
 
-      flush_pending_lists (deps, insn, true, true);
-      CLEAR_REG_SET (&deps->reg_conditional_sets);
+      if (!deps->readonly)
+        for (i = 0; i < (unsigned)deps->max_reg; i++)
+          {
+            struct deps_reg *reg_last = &deps->reg_last[i];
+            reg_last->sets = alloc_INSN_LIST (insn, reg_last->sets);
+            SET_REGNO_REG_SET (&deps->reg_last_in_use, i);
+          }
+
+      /* Flush pending lists on jumps, but not on speculative checks.  */
+      if (JUMP_P (insn) && !(sel_sched_p () 
+                             && sel_insn_is_speculation_check (insn)))
+       flush_pending_lists (deps, insn, true, true);
+      
+      if (!deps->readonly)
+        CLEAR_REG_SET (&deps->reg_conditional_sets);
       reg_pending_barrier = NOT_A_BARRIER;
     }
 
@@ -2203,160 +2584,211 @@ sched_analyze_insn (struct deps *deps, rtx x, rtx insn)
       if (src_regno < FIRST_PSEUDO_REGISTER
          || dest_regno < FIRST_PSEUDO_REGISTER)
        {
-         if (deps->in_post_call_group_p == post_call_initial)
+         if (!deps->readonly
+              && deps->in_post_call_group_p == post_call_initial)
            deps->in_post_call_group_p = post_call;
 
-         SCHED_GROUP_P (insn) = 1;
-         CANT_MOVE (insn) = 1;
+          if (!sel_sched_p () || sched_emulate_haifa_p) 
+            {
+              SCHED_GROUP_P (insn) = 1;
+              CANT_MOVE (insn) = 1;
+            }
        }
       else
        {
        end_call_group:
-         deps->in_post_call_group_p = not_post_call;
+          if (!deps->readonly)
+            deps->in_post_call_group_p = not_post_call;
        }
     }
 
-  /* Fixup the dependencies in the sched group.  */
-  if (SCHED_GROUP_P (insn))
-    fixup_sched_groups (insn);
-
   if ((current_sched_info->flags & DO_SPECULATION)
       && !sched_insn_is_legitimate_for_speculation_p (insn, 0))
     /* INSN has an internal dependency (e.g. r14 = [r14]) and thus cannot
        be speculated.  */
     {
-      sd_iterator_def sd_it;
-      dep_t dep;
-
-      for (sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
-          sd_iterator_cond (&sd_it, &dep);)
-       change_spec_dep_to_hard (sd_it);
+      if (sel_sched_p ())
+        sel_mark_hard_insn (insn);
+      else
+        {
+          sd_iterator_def sd_it;
+          dep_t dep;
+          
+          for (sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
+               sd_iterator_cond (&sd_it, &dep);)
+            change_spec_dep_to_hard (sd_it);
+        }
     }
 }
 
-/* Analyze every insn between HEAD and TAIL inclusive, creating backward
-   dependencies for each insn.  */
-
+/* Analyze INSN with DEPS as a context.  */
 void
-sched_analyze (struct deps *deps, rtx head, rtx tail)
+deps_analyze_insn (struct deps *deps, rtx insn)
 {
-  rtx insn;
+  if (sched_deps_info->start_insn)
+    sched_deps_info->start_insn (insn);
 
-  if (current_sched_info->use_cselib)
-    cselib_init (true);
+  if (NONJUMP_INSN_P (insn) || JUMP_P (insn))
+    {
+      /* Make each JUMP_INSN (but not a speculative check) 
+         a scheduling barrier for memory references.  */
+      if (!deps->readonly
+          && JUMP_P (insn) 
+          && !(sel_sched_p () 
+               && sel_insn_is_speculation_check (insn)))
+        {
+          /* Keep the list a reasonable size.  */
+          if (deps->pending_flush_length++ > MAX_PENDING_LIST_LENGTH)
+            flush_pending_lists (deps, insn, true, true);
+          else
+            deps->last_pending_memory_flush
+              = alloc_INSN_LIST (insn, deps->last_pending_memory_flush);
+        }
+
+      sched_analyze_insn (deps, PATTERN (insn), insn);
+    }
+  else if (CALL_P (insn))
+    {
+      int i;
+
+      CANT_MOVE (insn) = 1;
+
+      if (find_reg_note (insn, REG_SETJMP, NULL))
+        {
+          /* This is setjmp.  Assume that all registers, not just
+             hard registers, may be clobbered by this call.  */
+          reg_pending_barrier = MOVE_BARRIER;
+        }
+      else
+        {
+          for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
+            /* A call may read and modify global register variables.  */
+            if (global_regs[i])
+              {
+                SET_REGNO_REG_SET (reg_pending_sets, i);
+                SET_REGNO_REG_SET (reg_pending_uses, i);
+              }
+          /* Other call-clobbered hard regs may be clobbered.
+             Since we only have a choice between 'might be clobbered'
+             and 'definitely not clobbered', we must include all
+             partly call-clobbered registers here.  */
+            else if (HARD_REGNO_CALL_PART_CLOBBERED (i, reg_raw_mode[i])
+                     || TEST_HARD_REG_BIT (regs_invalidated_by_call, i))
+              SET_REGNO_REG_SET (reg_pending_clobbers, i);
+          /* We don't know what set of fixed registers might be used
+             by the function, but it is certain that the stack pointer
+             is among them, but be conservative.  */
+            else if (fixed_regs[i])
+              SET_REGNO_REG_SET (reg_pending_uses, i);
+          /* The frame pointer is normally not used by the function
+             itself, but by the debugger.  */
+          /* ??? MIPS o32 is an exception.  It uses the frame pointer
+             in the macro expansion of jal but does not represent this
+             fact in the call_insn rtl.  */
+            else if (i == FRAME_POINTER_REGNUM
+                     || (i == HARD_FRAME_POINTER_REGNUM
+                         && (! reload_completed || frame_pointer_needed)))
+              SET_REGNO_REG_SET (reg_pending_uses, i);
+        }
+
+      /* For each insn which shouldn't cross a call, add a dependence
+         between that insn and this call insn.  */
+      add_dependence_list_and_free (deps, insn, 
+                                    &deps->sched_before_next_call, 1,
+                                    REG_DEP_ANTI);
+
+      sched_analyze_insn (deps, PATTERN (insn), insn);
+
+      /* If CALL would be in a sched group, then this will violate
+        convention that sched group insns have dependencies only on the
+        previous instruction.
+
+        Of course one can say: "Hey!  What about head of the sched group?"
+        And I will answer: "Basic principles (one dep per insn) are always
+        the same."  */
+      gcc_assert (!SCHED_GROUP_P (insn));
+
+      /* In the absence of interprocedural alias analysis, we must flush
+         all pending reads and writes, and start new dependencies starting
+         from here.  But only flush writes for constant calls (which may
+         be passed a pointer to something we haven't written yet).  */
+      flush_pending_lists (deps, insn, true, ! RTL_CONST_OR_PURE_CALL_P (insn));
+
+      if (!deps->readonly)
+        {
+          /* Remember the last function call for limiting lifetimes.  */
+          free_INSN_LIST_list (&deps->last_function_call);
+          deps->last_function_call = alloc_INSN_LIST (insn, NULL_RTX);
+          
+          /* Before reload, begin a post-call group, so as to keep the
+             lifetimes of hard registers correct.  */
+          if (! reload_completed)
+            deps->in_post_call_group_p = post_call;
+        }
+    }
+
+  if (sched_deps_info->use_cselib)
+    cselib_process_insn (insn);
+
+  /* EH_REGION insn notes can not appear until well after we complete
+     scheduling.  */
+  if (NOTE_P (insn))
+    gcc_assert (NOTE_KIND (insn) != NOTE_INSN_EH_REGION_BEG
+               && NOTE_KIND (insn) != NOTE_INSN_EH_REGION_END);
+
+  if (sched_deps_info->finish_insn)
+    sched_deps_info->finish_insn ();
+
+  /* Fixup the dependencies in the sched group.  */
+  if ((NONJUMP_INSN_P (insn) || JUMP_P (insn)) 
+      && SCHED_GROUP_P (insn) && !sel_sched_p ())
+    fixup_sched_groups (insn);
+}
+
+/* Initialize DEPS for the new block beginning with HEAD.  */
+void
+deps_start_bb (struct deps *deps, rtx head)
+{
+  gcc_assert (!deps->readonly);
 
   /* Before reload, if the previous block ended in a call, show that
      we are inside a post-call group, so as to keep the lifetimes of
      hard registers correct.  */
   if (! reload_completed && !LABEL_P (head))
     {
-      insn = prev_nonnote_insn (head);
+      rtx insn = prev_nonnote_insn (head);
+
       if (insn && CALL_P (insn))
        deps->in_post_call_group_p = post_call_initial;
     }
+}
+
+/* Analyze every insn between HEAD and TAIL inclusive, creating backward
+   dependencies for each insn.  */
+void
+sched_analyze (struct deps *deps, rtx head, rtx tail)
+{
+  rtx insn;
+
+  if (sched_deps_info->use_cselib)
+    cselib_init (true);
+
+  deps_start_bb (deps, head);
+
   for (insn = head;; insn = NEXT_INSN (insn))
     {
+
       if (INSN_P (insn))
        {
          /* And initialize deps_lists.  */
          sd_init_insn (insn);
        }
 
-      if (NONJUMP_INSN_P (insn) || JUMP_P (insn))
-       {
-         /* Make each JUMP_INSN a scheduling barrier for memory
-             references.  */
-         if (JUMP_P (insn))
-           {
-             /* Keep the list a reasonable size.  */
-             if (deps->pending_flush_length++ > MAX_PENDING_LIST_LENGTH)
-               flush_pending_lists (deps, insn, true, true);
-             else
-               deps->last_pending_memory_flush
-                 = alloc_INSN_LIST (insn, deps->last_pending_memory_flush);
-           }
-         sched_analyze_insn (deps, PATTERN (insn), insn);
-       }
-      else if (CALL_P (insn))
-       {
-         int i;
-
-         CANT_MOVE (insn) = 1;
-
-         if (find_reg_note (insn, REG_SETJMP, NULL))
-           {
-             /* This is setjmp.  Assume that all registers, not just
-                hard registers, may be clobbered by this call.  */
-             reg_pending_barrier = MOVE_BARRIER;
-           }
-         else
-           {
-             for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
-               /* A call may read and modify global register variables.  */
-               if (global_regs[i])
-                 {
-                   SET_REGNO_REG_SET (reg_pending_sets, i);
-                   SET_REGNO_REG_SET (reg_pending_uses, i);
-                 }
-               /* Other call-clobbered hard regs may be clobbered.
-                  Since we only have a choice between 'might be clobbered'
-                  and 'definitely not clobbered', we must include all
-                  partly call-clobbered registers here.  */
-               else if (HARD_REGNO_CALL_PART_CLOBBERED (i, reg_raw_mode[i])
-                        || TEST_HARD_REG_BIT (regs_invalidated_by_call, i))
-                 SET_REGNO_REG_SET (reg_pending_clobbers, i);
-               /* We don't know what set of fixed registers might be used
-                  by the function, but it is certain that the stack pointer
-                  is among them, but be conservative.  */
-               else if (fixed_regs[i])
-                 SET_REGNO_REG_SET (reg_pending_uses, i);
-               /* The frame pointer is normally not used by the function
-                  itself, but by the debugger.  */
-               /* ??? MIPS o32 is an exception.  It uses the frame pointer
-                  in the macro expansion of jal but does not represent this
-                  fact in the call_insn rtl.  */
-               else if (i == FRAME_POINTER_REGNUM
-                        || (i == HARD_FRAME_POINTER_REGNUM
-                            && (! reload_completed || frame_pointer_needed)))
-                 SET_REGNO_REG_SET (reg_pending_uses, i);
-           }
-
-         /* For each insn which shouldn't cross a call, add a dependence
-            between that insn and this call insn.  */
-         add_dependence_list_and_free (insn, &deps->sched_before_next_call, 1,
-                                       REG_DEP_ANTI);
-
-         sched_analyze_insn (deps, PATTERN (insn), insn);
-
-         /* In the absence of interprocedural alias analysis, we must flush
-            all pending reads and writes, and start new dependencies starting
-            from here.  But only flush writes for constant calls (which may
-            be passed a pointer to something we haven't written yet).  */
-         flush_pending_lists (deps, insn, true, 
-                              ! RTL_CONST_OR_PURE_CALL_P (insn));
-
-         /* Remember the last function call for limiting lifetimes.  */
-         free_INSN_LIST_list (&deps->last_function_call);
-         deps->last_function_call = alloc_INSN_LIST (insn, NULL_RTX);
-
-         /* Before reload, begin a post-call group, so as to keep the
-            lifetimes of hard registers correct.  */
-         if (! reload_completed)
-           deps->in_post_call_group_p = post_call;
-       }
-
-      /* EH_REGION insn notes can not appear until well after we complete
-        scheduling.  */
-      if (NOTE_P (insn))
-       gcc_assert (NOTE_KIND (insn) != NOTE_INSN_EH_REGION_BEG
-                   && NOTE_KIND (insn) != NOTE_INSN_EH_REGION_END);
-
-      if (current_sched_info->use_cselib)
-       cselib_process_insn (insn);
+      deps_analyze_insn (deps, insn);
 
       if (insn == tail)
        {
-         if (current_sched_info->use_cselib)
+         if (sched_deps_info->use_cselib)
            cselib_finish ();
          return;
        }
@@ -2441,6 +2873,8 @@ init_deps (struct deps *deps)
   deps->last_function_call = 0;
   deps->sched_before_next_call = 0;
   deps->in_post_call_group_p = not_post_call;
+  deps->last_reg_pending_barrier = NOT_A_BARRIER;
+  deps->readonly = 0;
 }
 
 /* Free insn lists found in DEPS.  */
@@ -2474,42 +2908,98 @@ free_deps (struct deps *deps)
   CLEAR_REG_SET (&deps->reg_conditional_sets);
 
   free (deps->reg_last);
+  deps->reg_last = NULL;
+
+  deps = NULL;
 }
 
-/* If it is profitable to use them, initialize caches for tracking
-   dependency information.  LUID is the number of insns to be scheduled,
-   it is used in the estimate of profitability.  */
+/* Remove INSN from dependence contexts DEPS.  Caution: reg_conditional_sets
+   is not handled.  */
+void
+remove_from_deps (struct deps *deps, rtx insn)
+{
+  int removed;
+  unsigned i;
+  reg_set_iterator rsi;
+  
+  removed = remove_from_both_dependence_lists (insn, &deps->pending_read_insns,
+                                               &deps->pending_read_mems);
+  deps->pending_read_list_length -= removed;
+  removed = remove_from_both_dependence_lists (insn, &deps->pending_write_insns,
+                                               &deps->pending_write_mems);
+  deps->pending_write_list_length -= removed;
+  removed = remove_from_dependence_list (insn, &deps->last_pending_memory_flush);
+  deps->pending_flush_length -= removed;
 
+  EXECUTE_IF_SET_IN_REG_SET (&deps->reg_last_in_use, 0, i, rsi)
+    {
+      struct deps_reg *reg_last = &deps->reg_last[i];
+      if (reg_last->uses)
+       remove_from_dependence_list (insn, &reg_last->uses);
+      if (reg_last->sets)
+       remove_from_dependence_list (insn, &reg_last->sets);
+      if (reg_last->clobbers)
+       remove_from_dependence_list (insn, &reg_last->clobbers);
+      if (!reg_last->uses && !reg_last->sets && !reg_last->clobbers)
+        CLEAR_REGNO_REG_SET (&deps->reg_last_in_use, i);
+    }
+
+  if (CALL_P (insn))
+    remove_from_dependence_list (insn, &deps->last_function_call);
+  remove_from_dependence_list (insn, &deps->sched_before_next_call);
+}
+
+/* Init deps data vector.  */
+static void
+init_deps_data_vector (void)
+{
+  int reserve = (sched_max_luid + 1 
+                 - VEC_length (haifa_deps_insn_data_def, h_d_i_d));
+  if (reserve > 0 
+      && ! VEC_space (haifa_deps_insn_data_def, h_d_i_d, reserve))
+    VEC_safe_grow_cleared (haifa_deps_insn_data_def, heap, h_d_i_d,
+                           3 * sched_max_luid / 2);
+}
+
+/* If it is profitable to use them, initialize or extend (depending on
+   GLOBAL_P) dependency data.  */
 void
-init_dependency_caches (int luid)
+sched_deps_init (bool global_p)
 {
   /* Average number of insns in the basic block.
      '+ 1' is used to make it nonzero.  */
-  int insns_in_block = luid / n_basic_blocks + 1;
+  int insns_in_block = sched_max_luid / n_basic_blocks + 1;
 
-  /* ?!? We could save some memory by computing a per-region luid mapping
-     which could reduce both the number of vectors in the cache and the size
-     of each vector.  Instead we just avoid the cache entirely unless the
-     average number of instructions in a basic block is very high.  See
-     the comment before the declaration of true_dependency_cache for
-     what we consider "very high".  */
-  if (insns_in_block > 100 * 5)
-    {
+  init_deps_data_vector ();
+  
+  /* We use another caching mechanism for selective scheduling, so 
+     we don't use this one.  */
+  if (!sel_sched_p () && global_p && insns_in_block > 100 * 5)
+    {
+      /* ?!? We could save some memory by computing a per-region luid mapping
+         which could reduce both the number of vectors in the cache and the
+         size of each vector.  Instead we just avoid the cache entirely unless
+         the average number of instructions in a basic block is very high.  See
+         the comment before the declaration of true_dependency_cache for
+         what we consider "very high".  */
       cache_size = 0;
-      extend_dependency_caches (luid, true);
+      extend_dependency_caches (sched_max_luid, true);
     }
 
-  dl_pool = create_alloc_pool ("deps_list", sizeof (struct _deps_list),
-                              /* Allocate lists for one block at a time.  */
-                              insns_in_block);
-
-  dn_pool = create_alloc_pool ("dep_node", sizeof (struct _dep_node),
-                              /* Allocate nodes for one block at a time.
-                                 We assume that average insn has
-                                 5 producers.  */
-                              5 * insns_in_block);
+  if (global_p) 
+    {
+      dl_pool = create_alloc_pool ("deps_list", sizeof (struct _deps_list),
+                                   /* Allocate lists for one block at a time.  */
+                                   insns_in_block);
+      dn_pool = create_alloc_pool ("dep_node", sizeof (struct _dep_node),
+                                   /* Allocate nodes for one block at a time.
+                                      We assume that average insn has
+                                      5 producers.  */
+                                   5 * insns_in_block);
+    }
 }
 
+
 /* Create or extend (depending on CREATE_P) dependency caches to
    size N.  */
 void
@@ -2543,16 +3033,18 @@ extend_dependency_caches (int n, bool create_p)
     }
 }
 
-/* Free the caches allocated in init_dependency_caches.  */
-
+/* Finalize dependency information for the whole function.  */
 void
-free_dependency_caches (void)
+sched_deps_finish (void)
 {
   gcc_assert (deps_pools_are_empty_p ());
   free_alloc_pool_if_empty (&dn_pool);
   free_alloc_pool_if_empty (&dl_pool);
   gcc_assert (dn_pool == NULL && dl_pool == NULL);
 
+  VEC_free (haifa_deps_insn_data_def, heap, h_d_i_d);
+  cache_size = 0;
+  
   if (true_dependency_cache)
     {
       int i;
@@ -2563,7 +3055,7 @@ free_dependency_caches (void)
          bitmap_clear (&output_dependency_cache[i]);
          bitmap_clear (&anti_dependency_cache[i]);
 
-          if (current_sched_info->flags & DO_SPECULATION)
+          if (sched_deps_info->generate_spec_deps)
             bitmap_clear (&spec_dependency_cache[i]);
        }
       free (true_dependency_cache);
@@ -2573,11 +3065,12 @@ free_dependency_caches (void)
       free (anti_dependency_cache);
       anti_dependency_cache = NULL;
 
-      if (current_sched_info->flags & DO_SPECULATION)
+      if (sched_deps_info->generate_spec_deps)
         {
           free (spec_dependency_cache);
           spec_dependency_cache = NULL;
         }
+
     }
 }
 
@@ -2591,6 +3084,19 @@ init_deps_global (void)
   reg_pending_clobbers = ALLOC_REG_SET (&reg_obstack);
   reg_pending_uses = ALLOC_REG_SET (&reg_obstack);
   reg_pending_barrier = NOT_A_BARRIER;
+
+  if (!sel_sched_p () || sched_emulate_haifa_p)
+    {
+      sched_deps_info->start_insn = haifa_start_insn;
+      sched_deps_info->finish_insn = haifa_finish_insn;
+
+      sched_deps_info->note_reg_set = haifa_note_reg_set;
+      sched_deps_info->note_reg_clobber = haifa_note_reg_clobber;
+      sched_deps_info->note_reg_use = haifa_note_reg_use;
+
+      sched_deps_info->note_mem_dep = haifa_note_mem_dep;
+      sched_deps_info->note_dep = haifa_note_dep;
+   }
 }
 
 /* Free everything used by the dependency analysis code.  */
@@ -2604,7 +3110,7 @@ finish_deps_global (void)
 }
 
 /* Estimate the weakness of dependence between MEM1 and MEM2.  */
-static dw_t
+dw_t
 estimate_dep_weak (rtx mem1, rtx mem2)
 {
   rtx r1, r2;
@@ -2637,17 +3143,38 @@ estimate_dep_weak (rtx mem1, rtx mem2)
 void
 add_dependence (rtx insn, rtx elem, enum reg_note dep_type)
 {
-  dep_def _dep, *dep = &_dep;
+  ds_t ds;
+  bool internal;
 
-  init_dep (dep, elem, insn, dep_type);
-  maybe_add_or_update_dep_1 (dep, false, NULL_RTX, NULL_RTX);
+  if (dep_type == REG_DEP_TRUE)
+    ds = DEP_TRUE;
+  else if (dep_type == REG_DEP_OUTPUT)
+    ds = DEP_OUTPUT;
+  else
+    {
+      gcc_assert (dep_type == REG_DEP_ANTI);
+      ds = DEP_ANTI;
+    }
+
+  /* When add_dependence is called from inside sched-deps.c, we expect
+     cur_insn to be non-null.  */
+  internal = cur_insn != NULL;
+  if (internal)
+    gcc_assert (insn == cur_insn);
+  else
+    cur_insn = insn;
+      
+  note_dep (elem, ds);
+  if (!internal)
+    cur_insn = NULL;
 }
 
 /* Return weakness of speculative type TYPE in the dep_status DS.  */
-static dw_t
+dw_t
 get_dep_weak_1 (ds_t ds, ds_t type)
 {
   ds = ds & type;
+
   switch (type)
     {
     case BEGIN_DATA: ds >>= BEGIN_DATA_BITS_OFFSET; break;
@@ -2660,14 +3187,12 @@ get_dep_weak_1 (ds_t ds, ds_t type)
   return (dw_t) ds;
 }
 
-/* Return weakness of speculative type TYPE in the dep_status DS.  */
 dw_t
 get_dep_weak (ds_t ds, ds_t type)
 {
   dw_t dw = get_dep_weak_1 (ds, type);
 
   gcc_assert (MIN_DEP_WEAK <= dw && dw <= MAX_DEP_WEAK);
-
   return dw;
 }
 
@@ -2690,9 +3215,12 @@ set_dep_weak (ds_t ds, ds_t type, dw_t dw)
   return ds;
 }
 
-/* Return the join of two dep_statuses DS1 and DS2.  */
-ds_t
-ds_merge (ds_t ds1, ds_t ds2)
+/* Return the join of two dep_statuses DS1 and DS2.
+   If MAX_P is true then choose the greater probability,
+   otherwise multiply probabilities.
+   This function assumes that both DS1 and DS2 contain speculative bits.  */
+static ds_t
+ds_merge_1 (ds_t ds1, ds_t ds2, bool max_p)
 {
   ds_t ds, t;
 
@@ -2709,12 +3237,24 @@ ds_merge (ds_t ds1, ds_t ds2)
        ds |= ds2 & t;
       else if ((ds1 & t) && (ds2 & t))
        {
+         dw_t dw1 = get_dep_weak (ds1, t);
+         dw_t dw2 = get_dep_weak (ds2, t);
          ds_t dw;
 
-         dw = ((ds_t) get_dep_weak (ds1, t)) * ((ds_t) get_dep_weak (ds2, t));
-         dw /= MAX_DEP_WEAK;
-         if (dw < MIN_DEP_WEAK)
-           dw = MIN_DEP_WEAK;
+         if (!max_p)
+           {
+             dw = ((ds_t) dw1) * ((ds_t) dw2);
+             dw /= MAX_DEP_WEAK;
+             if (dw < MIN_DEP_WEAK)
+               dw = MIN_DEP_WEAK;
+           }
+         else
+           {
+             if (dw1 >= dw2)
+               dw = dw1;
+             else
+               dw = dw2;
+           }
 
          ds = set_dep_weak (ds, t, (dw_t) dw);
        }
@@ -2728,6 +3268,134 @@ ds_merge (ds_t ds1, ds_t ds2)
   return ds;
 }
 
+/* Return the join of two dep_statuses DS1 and DS2.
+   This function assumes that both DS1 and DS2 contain speculative bits.  */
+ds_t
+ds_merge (ds_t ds1, ds_t ds2)
+{
+  return ds_merge_1 (ds1, ds2, false);
+}
+
+/* Return the join of two dep_statuses DS1 and DS2.  */
+ds_t
+ds_full_merge (ds_t ds, ds_t ds2, rtx mem1, rtx mem2)
+{
+  ds_t new_status = ds | ds2;
+
+  if (new_status & SPECULATIVE)
+    {
+      if ((ds && !(ds & SPECULATIVE))
+         || (ds2 && !(ds2 & SPECULATIVE)))
+       /* Then this dep can't be speculative.  */
+       new_status &= ~SPECULATIVE;
+      else
+       {
+         /* Both are speculative.  Merging probabilities.  */
+         if (mem1)
+           {
+             dw_t dw;
+
+             dw = estimate_dep_weak (mem1, mem2);
+             ds = set_dep_weak (ds, BEGIN_DATA, dw);
+           }
+
+         if (!ds)
+           new_status = ds2;
+         else if (!ds2)
+           new_status = ds;
+         else
+           new_status = ds_merge (ds2, ds);
+       }
+    }
+
+  return new_status;
+}
+
+/* Return the join of DS1 and DS2.  Use maximum instead of multiplying
+   probabilities.  */
+ds_t
+ds_max_merge (ds_t ds1, ds_t ds2)
+{
+  if (ds1 == 0 && ds2 == 0)
+    return 0;
+
+  if (ds1 == 0 && ds2 != 0)
+    return ds2;
+
+  if (ds1 != 0 && ds2 == 0)
+    return ds1;
+
+  return ds_merge_1 (ds1, ds2, true);
+}
+
+/* Return the probability of speculation success for the speculation
+   status DS.  */
+dw_t
+ds_weak (ds_t ds)
+{
+  ds_t res = 1, dt;
+  int n = 0;
+
+  dt = FIRST_SPEC_TYPE;
+  do
+    {
+      if (ds & dt)
+       {
+         res *= (ds_t) get_dep_weak (ds, dt);
+         n++;
+       }
+
+      if (dt == LAST_SPEC_TYPE)
+       break;
+      dt <<= SPEC_TYPE_SHIFT;
+    }
+  while (1);
+
+  gcc_assert (n);
+  while (--n)
+    res /= MAX_DEP_WEAK;
+
+  if (res < MIN_DEP_WEAK)
+    res = MIN_DEP_WEAK;
+
+  gcc_assert (res <= MAX_DEP_WEAK);
+
+  return (dw_t) res;
+}
+
+/* Return a dep status that contains all speculation types of DS.  */
+ds_t
+ds_get_speculation_types (ds_t ds)
+{
+  if (ds & BEGIN_DATA)
+    ds |= BEGIN_DATA;
+  if (ds & BE_IN_DATA)
+    ds |= BE_IN_DATA;
+  if (ds & BEGIN_CONTROL)
+    ds |= BEGIN_CONTROL;
+  if (ds & BE_IN_CONTROL)
+    ds |= BE_IN_CONTROL;
+
+  return ds & SPECULATIVE;
+}
+
+/* Return a dep status that contains maximal weakness for each speculation
+   type present in DS.  */
+ds_t
+ds_get_max_dep_weak (ds_t ds)
+{
+  if (ds & BEGIN_DATA)
+    ds = set_dep_weak (ds, BEGIN_DATA, MAX_DEP_WEAK);
+  if (ds & BE_IN_DATA)
+    ds = set_dep_weak (ds, BE_IN_DATA, MAX_DEP_WEAK);
+  if (ds & BEGIN_CONTROL)
+    ds = set_dep_weak (ds, BEGIN_CONTROL, MAX_DEP_WEAK);
+  if (ds & BE_IN_CONTROL)
+    ds = set_dep_weak (ds, BE_IN_CONTROL, MAX_DEP_WEAK);
+
+  return ds;
+}
+
 /* Dump information about the dependence status S.  */
 static void
 dump_ds (FILE *f, ds_t s)
@@ -2796,7 +3464,7 @@ check_dep (dep_t dep, bool relaxed_p)
 
   /* Check that dependence status is set correctly when speculation is not
      supported.  */
-  if (!(current_sched_info->flags & DO_SPECULATION))
+  if (!sched_deps_info->generate_spec_deps)
     gcc_assert (!(ds & SPECULATIVE));
   else if (ds & SPECULATIVE)
     {
index 25b97c3..5c4d2df 100644 (file)
@@ -46,11 +46,11 @@ along with GCC; see the file COPYING3.  If not see
 \f
 #ifdef INSN_SCHEDULING
 
-/* The number of insns scheduled so far.  */
-static int sched_n_insns;
-
 /* The number of insns to be scheduled in total.  */
-static int n_insns;
+static int rgn_n_insns;
+
+/* The number of insns scheduled so far.  */
+static int sched_rgn_n_insns;
 
 /* Set of blocks, that already have their dependencies calculated.  */
 static bitmap_head dont_calc_deps;
@@ -62,25 +62,25 @@ static basic_block last_bb;
 static void init_ready_list (void);
 static void begin_schedule_ready (rtx, rtx);
 static int schedule_more_p (void);
-static const char *ebb_print_insn (rtx, int);
+static const char *ebb_print_insn (const_rtx, int);
 static int rank (rtx, rtx);
-static int contributes_to_priority (rtx, rtx);
-static void compute_jump_reg_dependencies (rtx, regset, regset, regset);
+static int ebb_contributes_to_priority (rtx, rtx);
 static basic_block earliest_block_with_similiar_load (basic_block, rtx);
 static void add_deps_for_risky_insns (rtx, rtx);
 static basic_block schedule_ebb (rtx, rtx);
+static void debug_ebb_dependencies (rtx, rtx);
 
-static void add_remove_insn (rtx, int);
-static void add_block1 (basic_block, basic_block);
+static void ebb_add_remove_insn (rtx, int);
+static void ebb_add_block (basic_block, basic_block);
 static basic_block advance_target_bb (basic_block, rtx);
-static void fix_recovery_cfg (int, int, int);
+static void ebb_fix_recovery_cfg (int, int, int);
 
 /* Return nonzero if there are more insns that should be scheduled.  */
 
 static int
 schedule_more_p (void)
 {
-  return sched_n_insns < n_insns;
+  return sched_rgn_n_insns < rgn_n_insns;
 }
 
 /* Print dependency information about ebb between HEAD and TAIL.  */
@@ -107,7 +107,7 @@ init_ready_list (void)
   rtx next_tail = current_sched_info->next_tail;
   rtx insn;
 
-  sched_n_insns = 0;
+  sched_rgn_n_insns = 0;
 
   /* Print debugging information.  */
   if (sched_verbose >= 5)
@@ -121,14 +121,14 @@ init_ready_list (void)
       n++;
     }
 
-  gcc_assert (n == n_insns);
+  gcc_assert (n == rgn_n_insns);
 }
 
 /* INSN is being scheduled after LAST.  Update counters.  */
 static void
 begin_schedule_ready (rtx insn, rtx last)
 {
-  sched_n_insns++;
+  sched_rgn_n_insns++;
 
   if (BLOCK_FOR_INSN (insn) == last_bb
       /* INSN is a jump in the last block, ...  */
@@ -184,7 +184,8 @@ begin_schedule_ready (rtx insn, rtx last)
       current_sched_info->next_tail = NEXT_INSN (BB_END (bb));
       gcc_assert (current_sched_info->next_tail);
 
-      add_block (bb, last_bb);
+      /* Append new basic block to the end of the ebb.  */
+      sched_init_only_bb (bb, last_bb);
       gcc_assert (last_bb == bb);
     }
 }
@@ -195,11 +196,16 @@ begin_schedule_ready (rtx insn, rtx last)
    to be formatted so that multiple output lines will line up nicely.  */
 
 static const char *
-ebb_print_insn (rtx insn, int aligned ATTRIBUTE_UNUSED)
+ebb_print_insn (const_rtx insn, int aligned ATTRIBUTE_UNUSED)
 {
   static char tmp[80];
 
-  sprintf (tmp, "%4d", INSN_UID (insn));
+  /* '+' before insn means it is a new cycle start.  */
+  if (GET_MODE (insn) == TImode)
+    sprintf (tmp, "+ %4d", INSN_UID (insn));
+  else
+    sprintf (tmp, "  %4d", INSN_UID (insn));
+
   return tmp;
 }
 
@@ -227,8 +233,8 @@ rank (rtx insn1, rtx insn2)
    calculations.  */
 
 static int
-contributes_to_priority (rtx next ATTRIBUTE_UNUSED,
-                        rtx insn ATTRIBUTE_UNUSED)
+ebb_contributes_to_priority (rtx next ATTRIBUTE_UNUSED,
+                             rtx insn ATTRIBUTE_UNUSED)
 {
   return 1;
 }
@@ -238,9 +244,9 @@ contributes_to_priority (rtx next ATTRIBUTE_UNUSED,
     must be considered as used by this jump in USED and that of
     registers that must be considered as set in SET.  */
 
-static void
-compute_jump_reg_dependencies (rtx insn, regset cond_set, regset used,
-                              regset set)
+void
+ebb_compute_jump_reg_dependencies (rtx insn, regset cond_set, regset used,
+                                  regset set)
 {
   basic_block b = BLOCK_FOR_INSN (insn);
   edge e;
@@ -261,7 +267,17 @@ compute_jump_reg_dependencies (rtx insn, regset cond_set, regset used,
 /* Used in schedule_insns to initialize current_sched_info for scheduling
    regions (or single basic blocks).  */
 
-static struct sched_info ebb_sched_info =
+static struct common_sched_info_def ebb_common_sched_info;
+
+static struct sched_deps_info_def ebb_sched_deps_info =
+  {
+    ebb_compute_jump_reg_dependencies,
+    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
+    NULL,
+    1, 0, 0
+  };
+
+static struct haifa_sched_info ebb_sched_info =
 {
   init_ready_list,
   NULL,
@@ -269,18 +285,15 @@ static struct sched_info ebb_sched_info =
   NULL,
   rank,
   ebb_print_insn,
-  contributes_to_priority,
-  compute_jump_reg_dependencies,
+  ebb_contributes_to_priority,
 
   NULL, NULL,
   NULL, NULL,
-  0, 1, 0,
+  1, 0,
 
-  add_remove_insn,
+  ebb_add_remove_insn,
   begin_schedule_ready,
-  add_block1,
   advance_target_bb,
-  fix_recovery_cfg,
   SCHED_EBB
   /* We can create new blocks in begin_schedule_ready ().  */
   | NEW_BBS
@@ -482,44 +495,29 @@ schedule_ebb (rtx head, rtx tail)
 
   /* Set priorities.  */
   current_sched_info->sched_max_insns_priority = 0;
-  n_insns = set_priorities (head, tail);
+  rgn_n_insns = set_priorities (head, tail);
   current_sched_info->sched_max_insns_priority++;
 
   current_sched_info->prev_head = PREV_INSN (head);
   current_sched_info->next_tail = NEXT_INSN (tail);
 
-  /* rm_other_notes only removes notes which are _inside_ the
-     block---that is, it won't remove notes before the first real insn
-     or after the last real insn of the block.  So if the first insn
-     has a REG_SAVE_NOTE which would otherwise be emitted before the
-     insn, it is redundant with the note before the start of the
-     block, and so we have to take it out.  */
-  if (INSN_P (head))
-    {
-      rtx note;
-
-      for (note = REG_NOTES (head); note; note = XEXP (note, 1))
-       if (REG_NOTE_KIND (note) == REG_SAVE_NOTE)
-         remove_note (head, note);
-    }
-
-  /* Remove remaining note insns from the block, save them in
-     note_list.  These notes are restored at the end of
-     schedule_block ().  */
-  rm_other_notes (head, tail);
+  remove_notes (head, tail);
 
   unlink_bb_notes (first_bb, last_bb);
 
-  current_sched_info->queue_must_finish_empty = 1;
-
   target_bb = first_bb;
-  schedule_block (&target_bb, n_insns);
+
+  /* Make ready list big enough to hold all the instructions from the ebb.  */
+  sched_extend_ready_list (rgn_n_insns);
+  schedule_block (&target_bb);
+  /* Free ready list.  */
+  sched_finish_ready_list ();
 
   /* We might pack all instructions into fewer blocks,
      so we may made some of them empty.  Can't assert (b == last_bb).  */
   
   /* Sanity check: verify that all region insns were scheduled.  */
-  gcc_assert (sched_n_insns == n_insns);
+  gcc_assert (sched_rgn_n_insns == rgn_n_insns);
 
   /* Free dependencies.  */
   sched_free_deps (current_sched_info->head, current_sched_info->tail, true);
@@ -559,16 +557,21 @@ schedule_ebbs (void)
   if (n_basic_blocks == NUM_FIXED_BLOCKS)
     return;
 
-  /* We need current_sched_info in init_dependency_caches, which is
-     invoked via sched_init.  */
-  current_sched_info = &ebb_sched_info;
+  /* Setup infos.  */
+  {
+    memcpy (&ebb_common_sched_info, &haifa_common_sched_info,
+           sizeof (ebb_common_sched_info));
+
+    ebb_common_sched_info.fix_recovery_cfg = ebb_fix_recovery_cfg;
+    ebb_common_sched_info.add_block = ebb_add_block;
+    ebb_common_sched_info.sched_pass_id = SCHED_EBB_PASS;
+
+    common_sched_info = &ebb_common_sched_info;
+    sched_deps_info = &ebb_sched_deps_info;
+    current_sched_info = &ebb_sched_info;
+  }
 
-  df_set_flags (DF_LR_RUN_DCE);
-  df_note_add_problem ();
-  df_analyze ();
-  df_clear_flags (DF_LR_RUN_DCE);
-  regstat_compute_calls_crossed ();
-  sched_init ();
+  haifa_sched_init ();
 
   compute_bb_for_insn ();
 
@@ -622,23 +625,22 @@ schedule_ebbs (void)
   if (reload_completed)
     reposition_prologue_and_epilogue_notes ();
 
-  sched_finish ();
-  regstat_free_calls_crossed ();
+  haifa_sched_finish ();
 }
 
 /* INSN has been added to/removed from current ebb.  */
 static void
-add_remove_insn (rtx insn ATTRIBUTE_UNUSED, int remove_p)
+ebb_add_remove_insn (rtx insn ATTRIBUTE_UNUSED, int remove_p)
 {
   if (!remove_p)
-    n_insns++;
+    rgn_n_insns++;
   else
-    n_insns--;
+    rgn_n_insns--;
 }
 
 /* BB was added to ebb after AFTER.  */
 static void
-add_block1 (basic_block bb, basic_block after)
+ebb_add_block (basic_block bb, basic_block after)
 {
   /* Recovery blocks are always bounded by BARRIERS, 
      therefore, they always form single block EBB,
@@ -691,7 +693,8 @@ advance_target_bb (basic_block bb, rtx insn)
    For parameter meaning please refer to
    sched-int.h: struct sched_info: fix_recovery_cfg.  */
 static void
-fix_recovery_cfg (int bbi ATTRIBUTE_UNUSED, int jump_bbi, int jump_bb_nexti)
+ebb_fix_recovery_cfg (int bbi ATTRIBUTE_UNUSED, int jump_bbi,
+                     int jump_bb_nexti)
 {
   gcc_assert (last_bb->index != bbi);
 
index bfbb861..2f9b781 100644 (file)
@@ -26,18 +26,196 @@ along with GCC; see the file COPYING3.  If not see
 
 /* For state_t.  */
 #include "insn-attr.h"
-/* For regset_head.  */
-#include "basic-block.h"
-/* For reg_note.  */
-#include "rtl.h"
 #include "df.h"
+#include "basic-block.h"
+
+/* For VEC (int, heap).  */
+#include "vecprim.h"
+
+/* Identificator of a scheduler pass.  */
+enum sched_pass_id_t { SCHED_PASS_UNKNOWN, SCHED_RGN_PASS, SCHED_EBB_PASS,
+                      SCHED_SMS_PASS, SCHED_SEL_PASS };
+
+typedef VEC (basic_block, heap) *bb_vec_t;
+typedef VEC (rtx, heap) *insn_vec_t;
+typedef VEC(rtx, heap) *rtx_vec_t;
+
+struct sched_scan_info_def
+{
+  /* This hook notifies scheduler frontend to extend its internal per basic
+     block data structures.  This hook should be called once before a series of
+     calls to bb_init ().  */
+  void (*extend_bb) (void);
+
+  /* This hook makes scheduler frontend to initialize its internal data
+     structures for the passed basic block.  */
+  void (*init_bb) (basic_block);
+
+  /* This hook notifies scheduler frontend to extend its internal per insn data
+     structures.  This hook should be called once before a series of calls to
+     insn_init ().  */
+  void (*extend_insn) (void);
+
+  /* This hook makes scheduler frontend to initialize its internal data
+     structures for the passed insn.  */
+  void (*init_insn) (rtx);
+};
+
+extern const struct sched_scan_info_def *sched_scan_info;
+
+extern void sched_scan (const struct sched_scan_info_def *,
+                       bb_vec_t, basic_block, insn_vec_t, rtx);
+
+extern void sched_init_bbs (void);
+
+extern void sched_init_luids (bb_vec_t, basic_block, insn_vec_t, rtx);
+extern void sched_finish_luids (void);
+
+extern void sched_extend_target (void);
+
+extern void haifa_init_h_i_d (bb_vec_t, basic_block, insn_vec_t, rtx);
+extern void haifa_finish_h_i_d (void);
+
+/* Hooks that are common to all the schedulers.  */
+struct common_sched_info_def
+{
+  /* Called after blocks were rearranged due to movement of jump instruction.
+     The first parameter - index of basic block, in which jump currently is.
+     The second parameter - index of basic block, in which jump used
+     to be.
+     The third parameter - index of basic block, that follows the second
+     parameter.  */
+  void (*fix_recovery_cfg) (int, int, int);
+
+  /* Called to notify frontend, that new basic block is being added.
+     The first parameter - new basic block.
+     The second parameter - block, after which new basic block is being added,
+     or EXIT_BLOCK_PTR, if recovery block is being added,
+     or NULL, if standalone block is being added.  */
+  void (*add_block) (basic_block, basic_block);
+
+  /* Estimate number of insns in the basic block.  */
+  int (*estimate_number_of_insns) (basic_block);
+
+  /* Given a non-insn (!INSN_P (x)) return
+     -1 - if this rtx don't need a luid.
+     0 - if it should have the same luid as the previous insn.
+     1 - if it needs a separate luid.  */
+  int (*luid_for_non_insn) (rtx);
+
+  /* Scheduler pass identifier.  It is preferably used in assertions.  */
+  enum sched_pass_id_t sched_pass_id;
+};
+
+extern struct common_sched_info_def *common_sched_info;
+
+extern const struct common_sched_info_def haifa_common_sched_info;
+
+/* Return true if selective scheduling pass is working.  */
+static inline bool
+sel_sched_p (void)
+{
+  return common_sched_info->sched_pass_id == SCHED_SEL_PASS;
+}
+
+/* Returns maximum priority that an insn was assigned to.  */
+extern int get_rgn_sched_max_insns_priority (void);
+
+/* Increases effective priority for INSN by AMOUNT.  */
+extern void sel_add_to_insn_priority (rtx, int);
+
+/* True if during selective scheduling we need to emulate some of haifa
+   scheduler behaviour.  */
+extern int sched_emulate_haifa_p;
+
+/* Mapping from INSN_UID to INSN_LUID.  In the end all other per insn data
+   structures should be indexed by luid.  */
+extern VEC (int, heap) *sched_luids;
+#define INSN_LUID(INSN) (VEC_index (int, sched_luids, INSN_UID (INSN)))
+#define LUID_BY_UID(UID) (VEC_index (int, sched_luids, UID))
+
+#define SET_INSN_LUID(INSN, LUID) \
+(VEC_replace (int, sched_luids, INSN_UID (INSN), (LUID)))
+
+/* The highest INSN_LUID.  */
+extern int sched_max_luid;
+
+extern int insn_luid (rtx);
+
+/* This list holds ripped off notes from the current block.  These notes will
+   be attached to the beginning of the block when its scheduling is
+   finished.  */
+extern rtx note_list;
+
+extern void remove_notes (rtx, rtx);
+extern rtx restore_other_notes (rtx, basic_block);
+extern void sched_insns_init (rtx);
+extern void sched_insns_finish (void);
+
+extern void *xrecalloc (void *, size_t, size_t, size_t);
+extern rtx bb_note (basic_block);
+
+extern void reemit_notes (rtx);
+
+/* Functions in sched-vis.c.  */
+extern void print_insn (char *, const_rtx, int);
+extern void print_pattern (char *, const_rtx, int);
+extern void print_value (char *, const_rtx, int);
+
+/* Functions in haifa-sched.c.  */
+extern int haifa_classify_insn (const_rtx);
+
+/* Functions in sel-sched-ir.c.  */
+extern void sel_find_rgns (void);
+extern void sel_mark_hard_insn (rtx);
+
+extern size_t dfa_state_size;
+
+extern void advance_state (state_t);
+
+extern void setup_sched_dump (void);
+extern void sched_init (void);
+extern void sched_finish (void);
+
+extern bool sel_insn_is_speculation_check (rtx);
+
+/* Describe the ready list of the scheduler.
+   VEC holds space enough for all insns in the current region.  VECLEN
+   says how many exactly.
+   FIRST is the index of the element with the highest priority; i.e. the
+   last one in the ready list, since elements are ordered by ascending
+   priority.
+   N_READY determines how many insns are on the ready list.  */
+struct ready_list
+{
+  rtx *vec;
+  int veclen;
+  int first;
+  int n_ready;
+};
+
+extern char *ready_try;
+extern struct ready_list ready;
+
+extern int max_issue (struct ready_list *, int, state_t, int *);
+
+extern void ebb_compute_jump_reg_dependencies (rtx, regset, regset, regset);
+
+extern edge find_fallthru_edge (basic_block);
+
+extern void (* sched_init_only_bb) (basic_block, basic_block);
+extern basic_block (* sched_split_block) (basic_block, rtx);
+extern basic_block sched_split_block_1 (basic_block, rtx);
+extern basic_block (* sched_create_empty_bb) (basic_block);
+extern basic_block sched_create_empty_bb_1 (basic_block);
+
+extern basic_block sched_create_recovery_block (basic_block *);
+extern void sched_create_recovery_edges (basic_block, basic_block,
+                                        basic_block);
 
 /* Pointer to data describing the current DFA state.  */
 extern state_t curr_state;
 
-/* Forward declaration.  */
-struct ready_list;
-
 /* Type to represent status of a dependence.  */
 typedef int ds_t;
 
@@ -242,6 +420,16 @@ struct _dep_node
 #define DEP_NODE_DEP(N) (&(N)->dep)
 #define DEP_NODE_FORW(N) (&(N)->forw)
 
+/* The following enumeration values tell us what dependencies we
+   should use to implement the barrier.  We use true-dependencies for
+   TRUE_BARRIER and anti-dependencies for MOVE_BARRIER.  */
+enum reg_pending_barrier_mode
+{
+  NOT_A_BARRIER = 0,
+  MOVE_BARRIER,
+  TRUE_BARRIER
+};
+
 /* Describe state of dependencies used during sched_analyze phase.  */
 struct deps
 {
@@ -330,14 +518,23 @@ struct deps
 
   /* Element N is set for each register that is conditionally set.  */
   regset_head reg_conditional_sets;
+
+  /* Shows the last value of reg_pending_barrier associated with the insn.  */
+  enum reg_pending_barrier_mode last_reg_pending_barrier;
+
+  /* True when this context should be treated as a readonly by 
+     the analysis.  */
+  BOOL_BITFIELD readonly : 1;
 };
 
+typedef struct deps *deps_t;
+
 /* This structure holds some state of the current scheduling pass, and
    contains some function pointers that abstract out some of the non-generic
    functionality from functions such as schedule_block or schedule_insn.
    There is one global variable, current_sched_info, which points to the
    sched_info structure currently in use.  */
-struct sched_info
+struct haifa_sched_info
 {
   /* Add all insns that are initially ready to the ready list.  Called once
      before scheduling a set of insns.  */
@@ -361,14 +558,10 @@ struct sched_info
      necessary to identify this insn in an output.  It's valid to use a
      static buffer for this.  The ALIGNED parameter should cause the string
      to be formatted so that multiple output lines will line up nicely.  */
-  const char *(*print_insn) (rtx, int);
+  const char *(*print_insn) (const_rtx, int);
   /* Return nonzero if an insn should be included in priority
      calculations.  */
   int (*contributes_to_priority) (rtx, rtx);
-  /* Called when computing dependencies for a JUMP_INSN.  This function
-     should store the set of registers that must be considered as set by
-     the jump in the regset.  */
-  void (*compute_jump_reg_dependencies) (rtx, regset, regset, regset);
 
   /* The boundaries of the set of insns to be scheduled.  */
   rtx prev_head, next_tail;
@@ -379,11 +572,6 @@ struct sched_info
 
   /* If nonzero, enables an additional sanity check in schedule_block.  */
   unsigned int queue_must_finish_empty:1;
-  /* Nonzero if we should use cselib for better alias analysis.  This
-     must be 0 if the dependency information is used after sched_analyze
-     has completed, e.g. if we're using it to initialize state for successor
-     blocks in region scheduling.  */
-  unsigned int use_cselib:1;
 
   /* Maximum priority that has been assigned to an insn.  */
   int sched_max_insns_priority;
@@ -399,27 +587,12 @@ struct sched_info
      last scheduled instruction.  */
   void (*begin_schedule_ready) (rtx, rtx);
 
-  /* Called to notify frontend, that new basic block is being added.
-     The first parameter - new basic block.
-     The second parameter - block, after which new basic block is being added,
-     or EXIT_BLOCK_PTR, if recovery block is being added,
-     or NULL, if standalone block is being added.  */
-  void (*add_block) (basic_block, basic_block);
-
   /* If the second parameter is not NULL, return nonnull value, if the
      basic block should be advanced.
      If the second parameter is NULL, return the next basic block in EBB.
      The first parameter is the current basic block in EBB.  */
   basic_block (*advance_target_bb) (basic_block, rtx);
 
-  /* Called after blocks were rearranged due to movement of jump instruction.
-     The first parameter - index of basic block, in which jump currently is.
-     The second parameter - index of basic block, in which jump used
-     to be.
-     The third parameter - index of basic block, that follows the second
-     parameter.  */
-  void (*fix_recovery_cfg) (int, int, int);
-
   /* ??? FIXME: should use straight bitfields inside sched_info instead of
      this flag field.  */
   unsigned int flags;
@@ -438,23 +611,40 @@ struct spec_info_def
 
   /* Minimal cumulative weakness of speculative instruction's
      dependencies, so that insn will be scheduled.  */
-  dw_t weakness_cutoff;
+  dw_t data_weakness_cutoff;
+
+  /* Minimal usefulness of speculative instruction to be considered for
+     scheduling.  */
+  int control_weakness_cutoff;
 
   /* Flags from the enum SPEC_SCHED_FLAGS.  */
   int flags;
 };
 typedef struct spec_info_def *spec_info_t;
 
-extern struct sched_info *current_sched_info;
+extern spec_info_t spec_info;
+
+extern struct haifa_sched_info *current_sched_info;
 
 /* Indexed by INSN_UID, the collection of all data associated with
    a single instruction.  */
 
-struct haifa_insn_data
+struct _haifa_deps_insn_data
 {
-  /* We can't place 'struct _deps_list' into h_i_d instead of deps_list_t
-     because when h_i_d extends, addresses of the deps_list->first
-     change without updating deps_list->first->next->prev_nextp.  */
+  /* The number of incoming edges in the forward dependency graph.
+     As scheduling proceeds, counts are decreased.  An insn moves to
+     the ready queue when its counter reaches zero.  */
+  int dep_count;
+
+  /* Nonzero if instruction has internal dependence
+     (e.g. add_dependence was invoked with (insn == elem)).  */
+  unsigned int has_internal_dep;
+
+  /* NB: We can't place 'struct _deps_list' here instead of deps_list_t into
+     h_i_d because when h_i_d extends, addresses of the deps_list->first
+     change without updating deps_list->first->next->prev_nextp.  Thus
+     BACK_DEPS and RESOLVED_BACK_DEPS are allocated on the heap and FORW_DEPS
+     list is allocated on the obstack.  */
 
   /* A list of hard backward dependencies.  The insn is a consumer of all the
      deps mentioned here.  */
@@ -476,7 +666,17 @@ struct haifa_insn_data
      from 'forw_deps' to 'resolved_forw_deps' while scheduling to fasten the
      search in 'forw_deps'.  */
   deps_list_t resolved_forw_deps;
+
+  /* Some insns (e.g. call) are not allowed to move across blocks.  */
+  unsigned int cant_move : 1;
+};
+
+struct _haifa_insn_data
+{
+  /* We can't place 'struct _deps_list' into h_i_d instead of deps_list_t
+     because when h_i_d extends, addresses of the deps_list->first
+     change without updating deps_list->first->next->prev_nextp.  */
+
   /* Logical uid gives the original ordering of the insns.  */
   int luid;
 
@@ -503,9 +703,6 @@ struct haifa_insn_data
      register pressure.  */
   short reg_weight;
 
-  /* Some insns (e.g. call) are not allowed to move across blocks.  */
-  unsigned int cant_move : 1;
-
   /* Set if there's DEF-USE dependence between some speculatively
      moved load insn and this one.  */
   unsigned int fed_by_spec_load : 1;
@@ -516,14 +713,12 @@ struct haifa_insn_data
      '< 0' if priority in invalid and should be recomputed.  */
   signed char priority_status;
 
-  /* Nonzero if instruction has internal dependence
-     (e.g. add_dependence was invoked with (insn == elem)).  */
-  unsigned int has_internal_dep : 1;
-  
   /* What speculations are necessary to apply to schedule the instruction.  */
   ds_t todo_spec;
+
   /* What speculations were already applied.  */
   ds_t done_spec; 
+
   /* What speculations are checked by this instruction.  */
   ds_t check_spec;
 
@@ -534,33 +729,56 @@ struct haifa_insn_data
   rtx orig_pat;
 };
 
-extern struct haifa_insn_data *h_i_d;
+typedef struct _haifa_insn_data haifa_insn_data_def;
+typedef haifa_insn_data_def *haifa_insn_data_t;
+
+DEF_VEC_O (haifa_insn_data_def);
+DEF_VEC_ALLOC_O (haifa_insn_data_def, heap);
+
+extern VEC(haifa_insn_data_def, heap) *h_i_d;
+
+#define HID(INSN) (VEC_index (haifa_insn_data_def, h_i_d, INSN_UID (INSN)))
 
 /* Accessor macros for h_i_d.  There are more in haifa-sched.c and
    sched-rgn.c.  */
-
-#define INSN_HARD_BACK_DEPS(INSN) (h_i_d[INSN_UID (INSN)].hard_back_deps)
-#define INSN_SPEC_BACK_DEPS(INSN) (h_i_d[INSN_UID (INSN)].spec_back_deps)
-#define INSN_FORW_DEPS(INSN) (h_i_d[INSN_UID (INSN)].forw_deps)
-#define INSN_RESOLVED_BACK_DEPS(INSN) \
-  (h_i_d[INSN_UID (INSN)].resolved_back_deps)
-#define INSN_RESOLVED_FORW_DEPS(INSN) \
-  (h_i_d[INSN_UID (INSN)].resolved_forw_deps)
-#define INSN_LUID(INSN)                (h_i_d[INSN_UID (INSN)].luid)
-#define CANT_MOVE(insn)                (h_i_d[INSN_UID (insn)].cant_move)
-#define INSN_PRIORITY(INSN)    (h_i_d[INSN_UID (INSN)].priority)
-#define INSN_PRIORITY_STATUS(INSN) (h_i_d[INSN_UID (INSN)].priority_status)
+#define INSN_PRIORITY(INSN) (HID (INSN)->priority)
+#define INSN_REG_WEIGHT(INSN) (HID (INSN)->reg_weight)
+#define INSN_PRIORITY_STATUS(INSN) (HID (INSN)->priority_status)
+
+typedef struct _haifa_deps_insn_data haifa_deps_insn_data_def;
+typedef haifa_deps_insn_data_def *haifa_deps_insn_data_t;
+
+DEF_VEC_O (haifa_deps_insn_data_def);
+DEF_VEC_ALLOC_O (haifa_deps_insn_data_def, heap);
+
+extern VEC(haifa_deps_insn_data_def, heap) *h_d_i_d;
+
+#define HDID(INSN) (VEC_index (haifa_deps_insn_data_def, h_d_i_d,      \
+                              INSN_LUID (INSN)))
+#define INSN_DEP_COUNT(INSN)   (HDID (INSN)->dep_count)
+#define HAS_INTERNAL_DEP(INSN)  (HDID (INSN)->has_internal_dep)
+#define INSN_FORW_DEPS(INSN) (HDID (INSN)->forw_deps)
+#define INSN_RESOLVED_BACK_DEPS(INSN) (HDID (INSN)->resolved_back_deps)
+#define INSN_RESOLVED_FORW_DEPS(INSN) (HDID (INSN)->resolved_forw_deps)
+#define INSN_HARD_BACK_DEPS(INSN) (HDID (INSN)->hard_back_deps)
+#define INSN_SPEC_BACK_DEPS(INSN) (HDID (INSN)->spec_back_deps)
+#define CANT_MOVE(INSN)        (HDID (INSN)->cant_move)
+#define CANT_MOVE_BY_LUID(LUID)        (VEC_index (haifa_deps_insn_data_def, h_d_i_d, \
+                                            LUID)->cant_move)
+
+
+#define INSN_PRIORITY(INSN)    (HID (INSN)->priority)
+#define INSN_PRIORITY_STATUS(INSN) (HID (INSN)->priority_status)
 #define INSN_PRIORITY_KNOWN(INSN) (INSN_PRIORITY_STATUS (INSN) > 0)
-#define INSN_REG_WEIGHT(INSN)  (h_i_d[INSN_UID (INSN)].reg_weight)
-#define HAS_INTERNAL_DEP(INSN)  (h_i_d[INSN_UID (INSN)].has_internal_dep)
-#define TODO_SPEC(INSN)         (h_i_d[INSN_UID (INSN)].todo_spec)
-#define DONE_SPEC(INSN)         (h_i_d[INSN_UID (INSN)].done_spec)
-#define CHECK_SPEC(INSN)        (h_i_d[INSN_UID (INSN)].check_spec)
-#define RECOVERY_BLOCK(INSN)    (h_i_d[INSN_UID (INSN)].recovery_block)
-#define ORIG_PAT(INSN)          (h_i_d[INSN_UID (INSN)].orig_pat)
+#define TODO_SPEC(INSN) (HID (INSN)->todo_spec)
+#define DONE_SPEC(INSN) (HID (INSN)->done_spec)
+#define CHECK_SPEC(INSN) (HID (INSN)->check_spec)
+#define RECOVERY_BLOCK(INSN) (HID (INSN)->recovery_block)
+#define ORIG_PAT(INSN) (HID (INSN)->orig_pat)
 
 /* INSN is either a simple or a branchy speculation check.  */
-#define IS_SPECULATION_CHECK_P(INSN) (RECOVERY_BLOCK (INSN) != NULL)
+#define IS_SPECULATION_CHECK_P(INSN) \
+  (sel_sched_p () ? sel_insn_is_speculation_check (INSN) : RECOVERY_BLOCK (INSN) != NULL)
 
 /* INSN is a speculation check that will simply reexecute the speculatively
    scheduled instruction if the speculation fails.  */
@@ -706,14 +924,16 @@ enum SCHED_FLAGS {
   DO_SPECULATION = USE_DEPS_LIST << 1,
   SCHED_RGN = DO_SPECULATION << 1,
   SCHED_EBB = SCHED_RGN << 1,
-  /* Scheduler can possible create new basic blocks.  Used for assertions.  */
-  NEW_BBS = SCHED_EBB << 1
+  /* Scheduler can possibly create new basic blocks.  Used for assertions.  */
+  NEW_BBS = SCHED_EBB << 1,
+  SEL_SCHED = NEW_BBS << 1
 };
 
 enum SPEC_SCHED_FLAGS {
   COUNT_SPEC_IN_CRITICAL_PATH = 1,
   PREFER_NON_DATA_SPEC = COUNT_SPEC_IN_CRITICAL_PATH << 1,
-  PREFER_NON_CONTROL_SPEC = PREFER_NON_DATA_SPEC << 1
+  PREFER_NON_CONTROL_SPEC = PREFER_NON_DATA_SPEC << 1,
+  SEL_SCHED_SPEC_DONT_CHECK_CONTROL = PREFER_NON_CONTROL_SPEC << 1
 };
 
 #define NOTE_NOT_BB_P(NOTE) (NOTE_P (NOTE) && (NOTE_KIND (NOTE)        \
@@ -803,23 +1023,104 @@ enum INSN_TRAP_CLASS
 #define HAIFA_INLINE __inline
 #endif
 
+struct sched_deps_info_def
+{
+  /* Called when computing dependencies for a JUMP_INSN.  This function
+     should store the set of registers that must be considered as set by
+     the jump in the regset.  */
+  void (*compute_jump_reg_dependencies) (rtx, regset, regset, regset);
+
+  /* Start analyzing insn.  */
+  void (*start_insn) (rtx);
+
+  /* Finish analyzing insn.  */
+  void (*finish_insn) (void);
+
+  /* Start analyzing insn LHS (Left Hand Side).  */
+  void (*start_lhs) (rtx);
+
+  /* Finish analyzing insn LHS.  */
+  void (*finish_lhs) (void);
+
+  /* Start analyzing insn RHS (Right Hand Side).  */
+  void (*start_rhs) (rtx);
+
+  /* Finish analyzing insn RHS.  */
+  void (*finish_rhs) (void);
+
+  /* Note set of the register.  */
+  void (*note_reg_set) (int);
+
+  /* Note clobber of the register.  */
+  void (*note_reg_clobber) (int);
+
+  /* Note use of the register.  */
+  void (*note_reg_use) (int);
+
+  /* Note memory dependence of type DS between MEM1 and MEM2 (which is
+     in the INSN2).  */
+  void (*note_mem_dep) (rtx mem1, rtx mem2, rtx insn2, ds_t ds);
+
+  /* Note a dependence of type DS from the INSN.  */
+  void (*note_dep) (rtx insn, ds_t ds);
+
+  /* Nonzero if we should use cselib for better alias analysis.  This
+     must be 0 if the dependency information is used after sched_analyze
+     has completed, e.g. if we're using it to initialize state for successor
+     blocks in region scheduling.  */
+  unsigned int use_cselib : 1;
+
+  /* If set, generate links between instruction as DEPS_LIST.
+     Otherwise, generate usual INSN_LIST links.  */
+  unsigned int use_deps_list : 1;
+
+  /* Generate data and control speculative dependencies.
+     Requires USE_DEPS_LIST set.  */
+  unsigned int generate_spec_deps : 1;
+};
+
+extern struct sched_deps_info_def *sched_deps_info;
+
+
 /* Functions in sched-deps.c.  */
 extern bool sched_insns_conditions_mutex_p (const_rtx, const_rtx);
 extern bool sched_insn_is_legitimate_for_speculation_p (const_rtx, ds_t);
 extern void add_dependence (rtx, rtx, enum reg_note);
 extern void sched_analyze (struct deps *, rtx, rtx);
-extern bool deps_pools_are_empty_p (void);
-extern void sched_free_deps (rtx, rtx, bool);
 extern void init_deps (struct deps *);
 extern void free_deps (struct deps *);
 extern void init_deps_global (void);
 extern void finish_deps_global (void);
-extern void init_dependency_caches (int);
-extern void free_dependency_caches (void);
-extern void extend_dependency_caches (int, bool);
+extern void deps_analyze_insn (struct deps *, rtx);
+extern void remove_from_deps (struct deps *, rtx);
+
+extern dw_t get_dep_weak_1 (ds_t, ds_t);
 extern dw_t get_dep_weak (ds_t, ds_t);
 extern ds_t set_dep_weak (ds_t, ds_t, dw_t);
+extern dw_t estimate_dep_weak (rtx, rtx);
 extern ds_t ds_merge (ds_t, ds_t);
+extern ds_t ds_full_merge (ds_t, ds_t, rtx, rtx);
+extern ds_t ds_max_merge (ds_t, ds_t);
+extern dw_t ds_weak (ds_t);
+extern ds_t ds_get_speculation_types (ds_t);
+extern ds_t ds_get_max_dep_weak (ds_t);
+
+extern void sched_deps_init (bool);
+extern void sched_deps_finish (void);
+
+extern void haifa_note_reg_set (int);
+extern void haifa_note_reg_clobber (int);
+extern void haifa_note_reg_use (int);
+
+extern void maybe_extend_reg_info_p (void);
+
+extern void deps_start_bb (struct deps *, rtx);
+extern enum reg_note ds_to_dt (ds_t);
+
+extern bool deps_pools_are_empty_p (void);
+extern void sched_free_deps (rtx, rtx, bool);
+extern void extend_dependency_caches (int, bool);
+
 extern void debug_ds (ds_t);
 
 /* Functions in haifa-sched.c.  */
@@ -827,25 +1128,105 @@ extern int haifa_classify_insn (const_rtx);
 extern void get_ebb_head_tail (basic_block, basic_block, rtx *, rtx *);
 extern int no_real_insns_p (const_rtx, const_rtx);
 
-extern void rm_other_notes (rtx, rtx);
-
 extern int insn_cost (rtx);
+extern int dep_cost_1 (dep_t, dw_t);
 extern int dep_cost (dep_t);
 extern int set_priorities (rtx, rtx);
 
-extern void schedule_block (basic_block *, int);
-extern void sched_init (void);
-extern void sched_finish (void);
+extern void schedule_block (basic_block *);
+
+extern int cycle_issued_insns;
+extern int issue_rate;
+extern int dfa_lookahead;
+
+extern void ready_sort (struct ready_list *);
+extern rtx ready_element (struct ready_list *, int);
+extern rtx *ready_lastpos (struct ready_list *);
 
 extern int try_ready (rtx);
-extern void * xrecalloc (void *, size_t, size_t, size_t);
+extern void sched_extend_ready_list (int);
+extern void sched_finish_ready_list (void);
+extern void sched_change_pattern (rtx, rtx);
+extern int sched_speculate_insn (rtx, ds_t, rtx *);
 extern void unlink_bb_notes (basic_block, basic_block);
 extern void add_block (basic_block, basic_block);
 extern rtx bb_note (basic_block);
+extern void concat_note_lists (rtx, rtx *);
+\f
 
-/* Functions in sched-rgn.c.  */
+/* Types and functions in sched-rgn.c.  */
 
+/* A region is the main entity for interblock scheduling: insns
+   are allowed to move between blocks in the same region, along
+   control flow graph edges, in the 'up' direction.  */
+typedef struct
+{
+  /* Number of extended basic blocks in region.  */
+  int rgn_nr_blocks;
+  /* cblocks in the region (actually index in rgn_bb_table).  */
+  int rgn_blocks;
+  /* Dependencies for this region are already computed.  Basically, indicates,
+     that this is a recovery block.  */
+  unsigned int dont_calc_deps : 1;
+  /* This region has at least one non-trivial ebb.  */
+  unsigned int has_real_ebb : 1;
+}
+region;
+
+extern int nr_regions;
+extern region *rgn_table;
+extern int *rgn_bb_table;
+extern int *block_to_bb;
+extern int *containing_rgn;
+
+#define RGN_NR_BLOCKS(rgn) (rgn_table[rgn].rgn_nr_blocks)
+#define RGN_BLOCKS(rgn) (rgn_table[rgn].rgn_blocks)
+#define RGN_DONT_CALC_DEPS(rgn) (rgn_table[rgn].dont_calc_deps)
+#define RGN_HAS_REAL_EBB(rgn) (rgn_table[rgn].has_real_ebb)
+#define BLOCK_TO_BB(block) (block_to_bb[block])
+#define CONTAINING_RGN(block) (containing_rgn[block])
+
+/* The mapping from ebb to block.  */
+extern int *ebb_head;
+#define BB_TO_BLOCK(ebb) (rgn_bb_table[ebb_head[ebb]])
+#define EBB_FIRST_BB(ebb) BASIC_BLOCK (BB_TO_BLOCK (ebb))
+#define EBB_LAST_BB(ebb) BASIC_BLOCK (rgn_bb_table[ebb_head[ebb + 1] - 1])
+#define INSN_BB(INSN) (BLOCK_TO_BB (BLOCK_NUM (INSN)))
+
+extern int current_nr_blocks;
+extern int current_blocks;
+extern int target_bb;
+
+extern bool sched_is_disabled_for_current_region_p (void);
+extern void sched_rgn_init (bool);
+extern void sched_rgn_finish (void);
+extern void rgn_setup_region (int);
+extern void sched_rgn_compute_dependencies (int);
+extern void sched_rgn_local_init (int);
+extern void sched_rgn_local_finish (void);
+extern void sched_rgn_local_free (void);
+extern void extend_regions (void);
+extern void rgn_make_new_region_out_of_new_block (basic_block);
+
+extern void compute_priorities (void);
+extern void increase_insn_priority (rtx, int);
+extern void debug_rgn_dependencies (int);
 extern void debug_dependencies (rtx, rtx);
+extern void free_rgn_deps (void);          
+extern int contributes_to_priority (rtx, rtx);
+extern void extend_rgns (int *, int *, sbitmap, int *);
+extern void deps_join (struct deps *, struct deps *);
+
+extern void rgn_setup_common_sched_info (void);
+extern void rgn_setup_sched_infos (void);
+
+extern void debug_regions (void);
+extern void debug_region (int);
+extern void dump_region_dot (FILE *, int);
+extern void dump_region_dot_file (const char *, int);
+
+extern void haifa_sched_init (void);
+extern void haifa_sched_finish (void);
 
 /* sched-deps.c interface to walk, add, search, update, resolve, delete
    and debug instruction dependencies.  */
index 9304536..8ea3d09 100644 (file)
@@ -64,90 +64,68 @@ along with GCC; see the file COPYING3.  If not see
 #include "cfglayout.h"
 #include "params.h"
 #include "sched-int.h"
+#include "sel-sched.h"
 #include "target.h"
 #include "timevar.h"
 #include "tree-pass.h"
 #include "dbgcnt.h"
 
 #ifdef INSN_SCHEDULING
+
 /* Some accessor macros for h_i_d members only used within this file.  */
-#define INSN_REF_COUNT(INSN)   (h_i_d[INSN_UID (INSN)].ref_count)
-#define FED_BY_SPEC_LOAD(insn) (h_i_d[INSN_UID (insn)].fed_by_spec_load)
-#define IS_LOAD_INSN(insn)     (h_i_d[INSN_UID (insn)].is_load_insn)
+#define FED_BY_SPEC_LOAD(INSN) (HID (INSN)->fed_by_spec_load)
+#define IS_LOAD_INSN(INSN) (HID (insn)->is_load_insn)
 
 /* nr_inter/spec counts interblock/speculative motion for the function.  */
 static int nr_inter, nr_spec;
 
 static int is_cfg_nonregular (void);
-static bool sched_is_disabled_for_current_region_p (void);
-
-/* A region is the main entity for interblock scheduling: insns
-   are allowed to move between blocks in the same region, along
-   control flow graph edges, in the 'up' direction.  */
-typedef struct
-{
-  /* Number of extended basic blocks in region.  */
-  int rgn_nr_blocks;
-  /* cblocks in the region (actually index in rgn_bb_table).  */
-  int rgn_blocks;
-  /* Dependencies for this region are already computed.  Basically, indicates,
-     that this is a recovery block.  */
-  unsigned int dont_calc_deps : 1;
-  /* This region has at least one non-trivial ebb.  */
-  unsigned int has_real_ebb : 1;
-}
-region;
 
 /* Number of regions in the procedure.  */
-static int nr_regions;
+int nr_regions = 0;
 
 /* Table of region descriptions.  */
-static region *rgn_table;
+region *rgn_table = NULL;
 
 /* Array of lists of regions' blocks.  */
-static int *rgn_bb_table;
+int *rgn_bb_table = NULL;
 
 /* Topological order of blocks in the region (if b2 is reachable from
    b1, block_to_bb[b2] > block_to_bb[b1]).  Note: A basic block is
    always referred to by either block or b, while its topological
    order name (in the region) is referred to by bb.  */
-static int *block_to_bb;
+int *block_to_bb = NULL;
 
 /* The number of the region containing a block.  */
-static int *containing_rgn;
+int *containing_rgn = NULL;
+
+/* ebb_head [i] - is index in rgn_bb_table of the head basic block of i'th ebb.
+   Currently we can get a ebb only through splitting of currently
+   scheduling block, therefore, we don't need ebb_head array for every region,
+   hence, its sufficient to hold it for current one only.  */
+int *ebb_head = NULL;
 
 /* The minimum probability of reaching a source block so that it will be
    considered for speculative scheduling.  */
 static int min_spec_prob;
 
-#define RGN_NR_BLOCKS(rgn) (rgn_table[rgn].rgn_nr_blocks)
-#define RGN_BLOCKS(rgn) (rgn_table[rgn].rgn_blocks)
-#define RGN_DONT_CALC_DEPS(rgn) (rgn_table[rgn].dont_calc_deps)
-#define RGN_HAS_REAL_EBB(rgn) (rgn_table[rgn].has_real_ebb)
-#define BLOCK_TO_BB(block) (block_to_bb[block])
-#define CONTAINING_RGN(block) (containing_rgn[block])
-
-void debug_regions (void);
-static void find_single_block_region (void);
+static void find_single_block_region (bool);
 static void find_rgns (void);
-static void extend_rgns (int *, int *, sbitmap, int *);
 static bool too_large (int, int *, int *);
 
-extern void debug_live (int, int);
-
 /* Blocks of the current region being scheduled.  */
-static int current_nr_blocks;
-static int current_blocks;
+int current_nr_blocks;
+int current_blocks;
 
-static int rgn_n_insns;
+/* A speculative motion requires checking live information on the path
+   from 'source' to 'target'.  The split blocks are those to be checked.
+   After a speculative motion, live information should be modified in
+   the 'update' blocks.
 
-/* The mapping from ebb to block.  */
-/* ebb_head [i] - is index in rgn_bb_table, while
-   EBB_HEAD (i) - is basic block index.
-   BASIC_BLOCK (EBB_HEAD (i)) - head of ebb.  */
-#define BB_TO_BLOCK(ebb) (rgn_bb_table[ebb_head[ebb]])
-#define EBB_FIRST_BB(ebb) BASIC_BLOCK (BB_TO_BLOCK (ebb))
-#define EBB_LAST_BB(ebb) BASIC_BLOCK (rgn_bb_table[ebb_head[ebb + 1] - 1])
+   Lists of split and update blocks for each candidate of the current
+   target are in array bblst_table.  */
+static basic_block *bblst_table;
+static int bblst_size, bblst_last;
 
 /* Target info declarations.
 
@@ -173,23 +151,14 @@ typedef struct
 candidate;
 
 static candidate *candidate_table;
-
-/* A speculative motion requires checking live information on the path
-   from 'source' to 'target'.  The split blocks are those to be checked.
-   After a speculative motion, live information should be modified in
-   the 'update' blocks.
-
-   Lists of split and update blocks for each candidate of the current
-   target are in array bblst_table.  */
-static basic_block *bblst_table;
-static int bblst_size, bblst_last;
-
-#define IS_VALID(src) ( candidate_table[src].is_valid )
-#define IS_SPECULATIVE(src) ( candidate_table[src].is_speculative )
+#define IS_VALID(src) (candidate_table[src].is_valid)
+#define IS_SPECULATIVE(src) (candidate_table[src].is_speculative)
+#define IS_SPECULATIVE_INSN(INSN)                      \
+  (IS_SPECULATIVE (BLOCK_TO_BB (BLOCK_NUM (INSN))))
 #define SRC_PROB(src) ( candidate_table[src].src_prob )
 
 /* The bb being currently scheduled.  */
-static int target_bb;
+int target_bb;
 
 /* List of edges.  */
 typedef struct
@@ -204,7 +173,6 @@ static int edgelst_last;
 
 static void extract_edgelst (sbitmap, edgelst *);
 
-
 /* Target info functions.  */
 static void split_edges (int, int, edgelst *);
 static void compute_trg_info (int);
@@ -250,24 +218,11 @@ static edgeset *pot_split;
 /* For every bb, a set of its ancestor edges.  */
 static edgeset *ancestor_edges;
 
-/* Array of EBBs sizes.  Currently we can get a ebb only through 
-   splitting of currently scheduling block, therefore, we don't need
-   ebb_head array for every region, its sufficient to hold it only
-   for current one.  */
-static int *ebb_head;
-
-static void compute_dom_prob_ps (int);
-
 #define INSN_PROBABILITY(INSN) (SRC_PROB (BLOCK_TO_BB (BLOCK_NUM (INSN))))
-#define IS_SPECULATIVE_INSN(INSN) (IS_SPECULATIVE (BLOCK_TO_BB (BLOCK_NUM (INSN))))
-#define INSN_BB(INSN) (BLOCK_TO_BB (BLOCK_NUM (INSN)))
 
 /* Speculative scheduling functions.  */
 static int check_live_1 (int, rtx);
 static void update_live_1 (int, rtx);
-static int check_live (rtx, int);
-static void update_live (rtx, int);
-static void set_spec_fed (rtx);
 static int is_pfree (rtx, int, int);
 static int find_conditional_protection (rtx, int);
 static int is_conditionally_protected (rtx, int, int);
@@ -279,7 +234,6 @@ static void sets_likely_spilled_1 (rtx, const_rtx, void *);
 static void add_branch_dependences (rtx, rtx);
 static void compute_block_dependences (int);
 
-static void init_regions (void);
 static void schedule_region (int);
 static rtx concat_INSN_LIST (rtx, rtx);
 static void concat_insn_mem_list (rtx, rtx, rtx *, rtx *);
@@ -423,28 +377,160 @@ debug_regions (void)
     }
 }
 
+/* Print the region's basic blocks.  */
+
+void
+debug_region (int rgn)
+{
+  int bb;
+
+  fprintf (stderr, "\n;;   ------------ REGION %d ----------\n\n", rgn);
+  fprintf (stderr, ";;\trgn %d nr_blocks %d:\n", rgn,
+          rgn_table[rgn].rgn_nr_blocks);
+  fprintf (stderr, ";;\tbb/block: ");
+
+  /* We don't have ebb_head initialized yet, so we can't use
+     BB_TO_BLOCK ().  */
+  current_blocks = RGN_BLOCKS (rgn);
+
+  for (bb = 0; bb < rgn_table[rgn].rgn_nr_blocks; bb++)
+    fprintf (stderr, " %d/%d ", bb, rgn_bb_table[current_blocks + bb]);
+
+  fprintf (stderr, "\n\n");
+
+  for (bb = 0; bb < rgn_table[rgn].rgn_nr_blocks; bb++)
+    {
+      debug_bb_n_slim (rgn_bb_table[current_blocks + bb]);
+      fprintf (stderr, "\n");
+    }
+
+  fprintf (stderr, "\n");
+
+}
+
+/* True when a bb with index BB_INDEX contained in region RGN.  */
+static bool
+bb_in_region_p (int bb_index, int rgn)
+{
+  int i;
+
+  for (i = 0; i < rgn_table[rgn].rgn_nr_blocks; i++)
+    if (rgn_bb_table[current_blocks + i] == bb_index)
+      return true;
+
+  return false;
+}
+
+/* Dump region RGN to file F using dot syntax.  */
+void
+dump_region_dot (FILE *f, int rgn)
+{
+  int i;
+
+  fprintf (f, "digraph Region_%d {\n", rgn);
+
+  /* We don't have ebb_head initialized yet, so we can't use
+     BB_TO_BLOCK ().  */
+  current_blocks = RGN_BLOCKS (rgn);
+
+  for (i = 0; i < rgn_table[rgn].rgn_nr_blocks; i++)
+    {
+      edge e;
+      edge_iterator ei;
+      int src_bb_num = rgn_bb_table[current_blocks + i];
+      struct basic_block_def *bb = BASIC_BLOCK (src_bb_num);
+
+      FOR_EACH_EDGE (e, ei, bb->succs)
+        if (bb_in_region_p (e->dest->index, rgn))
+         fprintf (f, "\t%d -> %d\n", src_bb_num, e->dest->index);
+    }
+  fprintf (f, "}\n");
+}
+
+/* The same, but first open a file specified by FNAME.  */
+void 
+dump_region_dot_file (const char *fname, int rgn)
+{
+  FILE *f = fopen (fname, "wt");
+  dump_region_dot (f, rgn);
+  fclose (f);
+}
+
 /* Build a single block region for each basic block in the function.
    This allows for using the same code for interblock and basic block
    scheduling.  */
 
 static void
-find_single_block_region (void)
+find_single_block_region (bool ebbs_p)
 {
-  basic_block bb;
+  basic_block bb, ebb_start;
+  int i = 0;
 
   nr_regions = 0;
 
-  FOR_EACH_BB (bb)
-    {
-      rgn_bb_table[nr_regions] = bb->index;
-      RGN_NR_BLOCKS (nr_regions) = 1;
-      RGN_BLOCKS (nr_regions) = nr_regions;
-      RGN_DONT_CALC_DEPS (nr_regions) = 0;
-      RGN_HAS_REAL_EBB (nr_regions) = 0;
-      CONTAINING_RGN (bb->index) = nr_regions;
-      BLOCK_TO_BB (bb->index) = 0;
-      nr_regions++;
-    }
+  if (ebbs_p) {
+    int probability_cutoff;
+    if (profile_info && flag_branch_probabilities)
+      probability_cutoff = PARAM_VALUE (TRACER_MIN_BRANCH_PROBABILITY_FEEDBACK);
+    else
+      probability_cutoff = PARAM_VALUE (TRACER_MIN_BRANCH_PROBABILITY);
+    probability_cutoff = REG_BR_PROB_BASE / 100 * probability_cutoff;
+
+    FOR_EACH_BB (ebb_start)
+      {
+        RGN_NR_BLOCKS (nr_regions) = 0;
+        RGN_BLOCKS (nr_regions) = i;
+        RGN_DONT_CALC_DEPS (nr_regions) = 0;
+        RGN_HAS_REAL_EBB (nr_regions) = 0;
+
+        for (bb = ebb_start; ; bb = bb->next_bb)
+          {
+            edge e;
+            edge_iterator ei;
+
+            rgn_bb_table[i] = bb->index;
+            RGN_NR_BLOCKS (nr_regions)++;
+            CONTAINING_RGN (bb->index) = nr_regions;
+            BLOCK_TO_BB (bb->index) = i - RGN_BLOCKS (nr_regions);
+            i++;
+
+            if (bb->next_bb == EXIT_BLOCK_PTR
+                || LABEL_P (BB_HEAD (bb->next_bb)))
+              break;
+            
+            FOR_EACH_EDGE (e, ei, bb->succs)
+             if ((e->flags & EDGE_FALLTHRU) != 0)
+               break;
+            if (! e)
+              break;
+            if (e->probability <= probability_cutoff)
+              break;
+          }
+
+        ebb_start = bb;
+        nr_regions++;
+      }
+  }
+  else
+    FOR_EACH_BB (bb)
+      {
+        rgn_bb_table[nr_regions] = bb->index;
+        RGN_NR_BLOCKS (nr_regions) = 1;
+        RGN_BLOCKS (nr_regions) = nr_regions;
+        RGN_DONT_CALC_DEPS (nr_regions) = 0;
+        RGN_HAS_REAL_EBB (nr_regions) = 0;
+
+        CONTAINING_RGN (bb->index) = nr_regions;
+        BLOCK_TO_BB (bb->index) = 0;
+        nr_regions++;
+      }
+}
+
+/* Estimate number of the insns in the BB.  */
+static int
+rgn_estimate_number_of_insns (basic_block bb)
+{
+  return INSN_LUID (BB_END (bb)) - INSN_LUID (BB_HEAD (bb));
 }
 
 /* Update number of blocks and the estimate for number of insns
@@ -455,8 +541,8 @@ static bool
 too_large (int block, int *num_bbs, int *num_insns)
 {
   (*num_bbs)++;
-  (*num_insns) += (INSN_LUID (BB_END (BASIC_BLOCK (block)))
-                  - INSN_LUID (BB_HEAD (BASIC_BLOCK (block))));
+  (*num_insns) += (common_sched_info->estimate_number_of_insns
+                   (BASIC_BLOCK (block)));
 
   return ((*num_bbs > PARAM_VALUE (PARAM_MAX_SCHED_REGION_BLOCKS))
          || (*num_insns > PARAM_VALUE (PARAM_MAX_SCHED_REGION_INSNS)));
@@ -509,7 +595,7 @@ too_large (int block, int *num_bbs, int *num_insns)
    of edge tables.  That would simplify it somewhat.  */
 
 static void
-find_rgns (void)
+haifa_find_rgns (void)
 {
   int *max_hdr, *dfs_nr, *degree;
   char no_loops = 1;
@@ -765,8 +851,7 @@ find_rgns (void)
 
              /* Estimate # insns, and count # blocks in the region.  */
              num_bbs = 1;
-             num_insns = (INSN_LUID (BB_END (bb))
-                          - INSN_LUID (BB_HEAD (bb)));
+             num_insns = common_sched_info->estimate_number_of_insns (bb);
 
              /* Find all loop latches (blocks with back edges to the loop
                 header) or all the leaf blocks in the cfg has no loops.
@@ -970,6 +1055,19 @@ find_rgns (void)
   sbitmap_free (in_stack);
 }
 
+
+/* Wrapper function.
+   If FLAG_SEL_SCHED_PIPELINING is set, then use custom function to form
+   regions.  Otherwise just call find_rgns_haifa.  */
+static void
+find_rgns (void)
+{
+  if (sel_sched_p () && flag_sel_sched_pipelining)
+    sel_find_rgns ();
+  else
+    haifa_find_rgns ();
+}
+
 static int gather_region_statistics (int **);
 static void print_region_statistics (int *, int, int *, int);
 
@@ -1039,7 +1137,7 @@ print_region_statistics (int *s1, int s1_sz, int *s2, int s2_sz)
    LOOP_HDR - mapping from block to the containing loop
    (two blocks can reside within one region if they have
    the same loop header).  */
-static void
+void
 extend_rgns (int *degree, int *idxp, sbitmap header, int *loop_hdr)
 {
   int *order, i, rescan = 0, idx = *idxp, iter = 0, max_iter, *max_hdr;
@@ -1073,7 +1171,8 @@ extend_rgns (int *degree, int *idxp, sbitmap header, int *loop_hdr)
      CFG should be traversed until no further changes are made.  On each 
      iteration the set of the region heads is extended (the set of those 
      blocks that have max_hdr[bbi] == bbi).  This set is upper bounded by the 
-     set of all basic blocks, thus the algorithm is guaranteed to terminate.  */
+     set of all basic blocks, thus the algorithm is guaranteed to
+     terminate.  */
 
   while (rescan && iter < max_iter)
     {
@@ -1372,6 +1471,19 @@ compute_trg_info (int trg)
   edge_iterator ei;
   edge e;
 
+  candidate_table = XNEWVEC (candidate, current_nr_blocks);
+
+  bblst_last = 0;
+  /* bblst_table holds split blocks and update blocks for each block after
+     the current one in the region.  split blocks and update blocks are
+     the TO blocks of region edges, so there can be at most rgn_nr_edges
+     of them.  */
+  bblst_size = (current_nr_blocks - target_bb) * rgn_nr_edges;
+  bblst_table = XNEWVEC (basic_block, bblst_size);
+
+  edgelst_last = 0;
+  edgelst_table = XNEWVEC (edge, rgn_nr_edges);
+
   /* Define some of the fields for the target bb as well.  */
   sp = candidate_table + trg;
   sp->is_valid = 1;
@@ -1458,6 +1570,15 @@ compute_trg_info (int trg)
   sbitmap_free (visited);
 }
 
+/* Free the computed target info.  */
+static void
+free_trg_info (void)
+{
+  free (candidate_table);
+  free (bblst_table);
+  free (edgelst_table);
+}
+
 /* Print candidates info, for debugging purposes.  Callable from debugger.  */
 
 void
@@ -1941,20 +2062,16 @@ static int can_schedule_ready_p (rtx);
 static void begin_schedule_ready (rtx, rtx);
 static ds_t new_ready (rtx, ds_t);
 static int schedule_more_p (void);
-static const char *rgn_print_insn (rtx, int);
+static const char *rgn_print_insn (const_rtx, int);
 static int rgn_rank (rtx, rtx);
-static int contributes_to_priority (rtx, rtx);
 static void compute_jump_reg_dependencies (rtx, regset, regset, regset);
 
 /* Functions for speculative scheduling.  */
-static void add_remove_insn (rtx, int);
-static void extend_regions (void);
-static void add_block1 (basic_block, basic_block);
-static void fix_recovery_cfg (int, int, int);
+static void rgn_add_remove_insn (rtx, int);
+static void rgn_add_block (basic_block, basic_block);
+static void rgn_fix_recovery_cfg (int, int, int);
 static basic_block advance_target_bb (basic_block, rtx);
 
-static void debug_rgn_dependencies (int);
-
 /* Return nonzero if there are more insns that should be scheduled.  */
 
 static int
@@ -1984,22 +2101,7 @@ init_ready_list (void)
 
   /* Prepare current target block info.  */
   if (current_nr_blocks > 1)
-    {
-      candidate_table = XNEWVEC (candidate, current_nr_blocks);
-
-      bblst_last = 0;
-      /* bblst_table holds split blocks and update blocks for each block after
-        the current one in the region.  split blocks and update blocks are
-        the TO blocks of region edges, so there can be at most rgn_nr_edges
-        of them.  */
-      bblst_size = (current_nr_blocks - target_bb) * rgn_nr_edges;
-      bblst_table = XNEWVEC (basic_block, bblst_size);
-
-      edgelst_last = 0;
-      edgelst_table = XNEWVEC (edge, rgn_nr_edges);
-
-      compute_trg_info (target_bb);
-    }
+    compute_trg_info (target_bb);
 
   /* Initialize ready list with all 'ready' insns in target block.
      Count number of insns in the target block being scheduled.  */
@@ -2106,8 +2208,8 @@ new_ready (rtx next, ds_t ts)
          if (not_ex_free
              /* We are here because is_exception_free () == false.
                 But we possibly can handle that with control speculation.  */
-             && (current_sched_info->flags & DO_SPECULATION)
-             && (spec_info->mask & BEGIN_CONTROL))
+             && sched_deps_info->generate_spec_deps
+             && spec_info->mask & BEGIN_CONTROL)
            {
              ds_t new_ds;
 
@@ -2137,7 +2239,7 @@ new_ready (rtx next, ds_t ts)
    to be formatted so that multiple output lines will line up nicely.  */
 
 static const char *
-rgn_print_insn (rtx insn, int aligned)
+rgn_print_insn (const_rtx insn, int aligned)
 {
   static char tmp[80];
 
@@ -2188,7 +2290,7 @@ rgn_rank (rtx insn1, rtx insn2)
    return nonzero if we should include this dependence in priority
    calculations.  */
 
-static int
+int
 contributes_to_priority (rtx next, rtx insn)
 {
   /* NEXT and INSN reside in one ebb.  */
@@ -2210,10 +2312,36 @@ compute_jump_reg_dependencies (rtx insn ATTRIBUTE_UNUSED,
      add_branch_dependences.  */
 }
 
+/* This variable holds common_sched_info hooks and data relevant to 
+   the interblock scheduler.  */
+static struct common_sched_info_def rgn_common_sched_info;
+
+
+/* This holds data for the dependence analysis relevant to
+   the interblock scheduler.  */
+static struct sched_deps_info_def rgn_sched_deps_info;
+
+/* This holds constant data used for initializing the above structure
+   for the Haifa scheduler.  */
+static const struct sched_deps_info_def rgn_const_sched_deps_info =
+  {
+    compute_jump_reg_dependencies,
+    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
+    0, 0, 0
+  };
+
+/* Same as above, but for the selective scheduler.  */
+static const struct sched_deps_info_def rgn_const_sel_sched_deps_info =
+  {
+    compute_jump_reg_dependencies,
+    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
+    0, 0, 0
+  };
+
 /* Used in schedule_insns to initialize current_sched_info for scheduling
    regions (or single basic blocks).  */
 
-static struct sched_info region_sched_info =
+static const struct haifa_sched_info rgn_const_sched_info =
 {
   init_ready_list,
   can_schedule_ready_p,
@@ -2222,20 +2350,29 @@ static struct sched_info region_sched_info =
   rgn_rank,
   rgn_print_insn,
   contributes_to_priority,
-  compute_jump_reg_dependencies,
 
   NULL, NULL,
   NULL, NULL,
-  0, 0, 0,
+  0, 0,
 
-  add_remove_insn,
+  rgn_add_remove_insn,
   begin_schedule_ready,
-  add_block1,
   advance_target_bb,
-  fix_recovery_cfg,
   SCHED_RGN
 };
 
+/* This variable holds the data and hooks needed to the Haifa scheduler backend
+   for the interblock scheduler frontend.  */
+static struct haifa_sched_info rgn_sched_info;
+
+/* Returns maximum priority that an insn was assigned to.  */
+
+int
+get_rgn_sched_max_insns_priority (void)
+{
+  return rgn_sched_info.sched_max_insns_priority;
+}
+
 /* Determine if PAT sets a CLASS_LIKELY_SPILLED_P register.  */
 
 static bool
@@ -2258,9 +2395,12 @@ sets_likely_spilled_1 (rtx x, const_rtx pat, void *data)
     *ret = true;
 }
 
+/* An array used to hold the number of dependencies in which insn 
+   participates.  Used in add_branch_dependences.  */
+static int *ref_counts;
+
 /* Add dependences so that branches are scheduled to run last in their
    block.  */
-
 static void
 add_branch_dependences (rtx head, rtx tail)
 {
@@ -2284,6 +2424,8 @@ add_branch_dependences (rtx head, rtx tail)
      are not moved before reload because we can wind up with register
      allocation failures.  */
 
+#define INSN_REF_COUNT(INSN) (ref_counts[INSN_UID (INSN)])
+
   insn = tail;
   last = 0;
   while (CALL_P (insn)
@@ -2426,6 +2568,57 @@ concat_insn_mem_list (rtx copy_insns, rtx copy_mems, rtx *old_insns_p,
   *old_mems_p = new_mems;
 }
 
+/* Join PRED_DEPS to the SUCC_DEPS.  */
+void
+deps_join (struct deps *succ_deps, struct deps *pred_deps)
+{
+  unsigned reg;
+  reg_set_iterator rsi;
+
+  /* The reg_last lists are inherited by successor.  */
+  EXECUTE_IF_SET_IN_REG_SET (&pred_deps->reg_last_in_use, 0, reg, rsi)
+    {
+      struct deps_reg *pred_rl = &pred_deps->reg_last[reg];
+      struct deps_reg *succ_rl = &succ_deps->reg_last[reg];
+
+      succ_rl->uses = concat_INSN_LIST (pred_rl->uses, succ_rl->uses);
+      succ_rl->sets = concat_INSN_LIST (pred_rl->sets, succ_rl->sets);
+      succ_rl->clobbers = concat_INSN_LIST (pred_rl->clobbers,
+                                            succ_rl->clobbers);
+      succ_rl->uses_length += pred_rl->uses_length;
+      succ_rl->clobbers_length += pred_rl->clobbers_length;
+    }
+  IOR_REG_SET (&succ_deps->reg_last_in_use, &pred_deps->reg_last_in_use);
+
+  /* Mem read/write lists are inherited by successor.  */
+  concat_insn_mem_list (pred_deps->pending_read_insns,
+                        pred_deps->pending_read_mems,
+                        &succ_deps->pending_read_insns,
+                        &succ_deps->pending_read_mems);
+  concat_insn_mem_list (pred_deps->pending_write_insns,
+                        pred_deps->pending_write_mems,
+                        &succ_deps->pending_write_insns,
+                        &succ_deps->pending_write_mems);
+
+  succ_deps->last_pending_memory_flush
+    = concat_INSN_LIST (pred_deps->last_pending_memory_flush,
+                        succ_deps->last_pending_memory_flush);
+
+  succ_deps->pending_read_list_length += pred_deps->pending_read_list_length;
+  succ_deps->pending_write_list_length += pred_deps->pending_write_list_length;
+  succ_deps->pending_flush_length += pred_deps->pending_flush_length;
+
+  /* last_function_call is inherited by successor.  */
+  succ_deps->last_function_call
+    = concat_INSN_LIST (pred_deps->last_function_call,
+                        succ_deps->last_function_call);
+
+  /* sched_before_next_call is inherited by successor.  */
+  succ_deps->sched_before_next_call
+    = concat_INSN_LIST (pred_deps->sched_before_next_call,
+                        succ_deps->sched_before_next_call);
+}
+
 /* After computing the dependencies for block BB, propagate the dependencies
    found in TMP_DEPS to the successors of the block.  */
 static void
@@ -2438,62 +2631,13 @@ propagate_deps (int bb, struct deps *pred_deps)
   /* bb's structures are inherited by its successors.  */
   FOR_EACH_EDGE (e, ei, block->succs)
     {
-      struct deps *succ_deps;
-      unsigned reg;
-      reg_set_iterator rsi;
-
       /* Only bbs "below" bb, in the same region, are interesting.  */
       if (e->dest == EXIT_BLOCK_PTR
          || CONTAINING_RGN (block->index) != CONTAINING_RGN (e->dest->index)
          || BLOCK_TO_BB (e->dest->index) <= bb)
        continue;
 
-      succ_deps = bb_deps + BLOCK_TO_BB (e->dest->index);
-
-      /* The reg_last lists are inherited by successor.  */
-      EXECUTE_IF_SET_IN_REG_SET (&pred_deps->reg_last_in_use, 0, reg, rsi)
-       {
-         struct deps_reg *pred_rl = &pred_deps->reg_last[reg];
-         struct deps_reg *succ_rl = &succ_deps->reg_last[reg];
-
-         succ_rl->uses = concat_INSN_LIST (pred_rl->uses, succ_rl->uses);
-         succ_rl->sets = concat_INSN_LIST (pred_rl->sets, succ_rl->sets);
-         succ_rl->clobbers = concat_INSN_LIST (pred_rl->clobbers,
-                                               succ_rl->clobbers);
-         succ_rl->uses_length += pred_rl->uses_length;
-         succ_rl->clobbers_length += pred_rl->clobbers_length;
-       }
-      IOR_REG_SET (&succ_deps->reg_last_in_use, &pred_deps->reg_last_in_use);
-
-      /* Mem read/write lists are inherited by successor.  */
-      concat_insn_mem_list (pred_deps->pending_read_insns,
-                           pred_deps->pending_read_mems,
-                           &succ_deps->pending_read_insns,
-                           &succ_deps->pending_read_mems);
-      concat_insn_mem_list (pred_deps->pending_write_insns,
-                           pred_deps->pending_write_mems,
-                           &succ_deps->pending_write_insns,
-                           &succ_deps->pending_write_mems);
-
-      succ_deps->last_pending_memory_flush
-       = concat_INSN_LIST (pred_deps->last_pending_memory_flush,
-                           succ_deps->last_pending_memory_flush);
-
-      succ_deps->pending_read_list_length
-       += pred_deps->pending_read_list_length;
-      succ_deps->pending_write_list_length
-       += pred_deps->pending_write_list_length;
-      succ_deps->pending_flush_length += pred_deps->pending_flush_length;
-
-      /* last_function_call is inherited by successor.  */
-      succ_deps->last_function_call
-       = concat_INSN_LIST (pred_deps->last_function_call,
-                             succ_deps->last_function_call);
-
-      /* sched_before_next_call is inherited by successor.  */
-      succ_deps->sched_before_next_call
-       = concat_INSN_LIST (pred_deps->sched_before_next_call,
-                           succ_deps->sched_before_next_call);
+      deps_join (bb_deps + BLOCK_TO_BB (e->dest->index), pred_deps);
     }
 
   /* These lists should point to the right place, for correct
@@ -2540,7 +2684,10 @@ compute_block_dependences (int bb)
   get_ebb_head_tail (EBB_FIRST_BB (bb), EBB_LAST_BB (bb), &head, &tail);
 
   sched_analyze (&tmp_deps, head, tail);
-  add_branch_dependences (head, tail);
+
+  /* Selective scheduling handles control dependencies by itself.  */
+  if (!sel_sched_p ())
+    add_branch_dependences (head, tail);
 
   if (current_nr_blocks > 1)
     propagate_deps (bb, &tmp_deps);
@@ -2641,9 +2788,13 @@ void debug_dependencies (rtx head, rtx tail)
               INSN_UID (insn),
               INSN_CODE (insn),
               BLOCK_NUM (insn),
-              sd_lists_size (insn, SD_LIST_BACK),
-              INSN_PRIORITY (insn),
-              insn_cost (insn));
+              sched_emulate_haifa_p ? -1 : sd_lists_size (insn, SD_LIST_BACK),
+              (sel_sched_p () ? (sched_emulate_haifa_p ? -1
+                              : INSN_PRIORITY (insn))
+               : INSN_PRIORITY (insn)),
+              (sel_sched_p () ? (sched_emulate_haifa_p ? -1
+                              : insn_cost (insn))
+               : insn_cost (insn)));
 
       if (recog_memoized (insn) < 0)
        fprintf (sched_dump, "nothing");
@@ -2666,7 +2817,7 @@ void debug_dependencies (rtx head, rtx tail)
 \f
 /* Returns true if all the basic blocks of the current region have
    NOTE_DISABLE_SCHED_OF_BLOCK which means not to schedule that region.  */
-static bool
+bool
 sched_is_disabled_for_current_region_p (void)
 {
   int bb;
@@ -2678,58 +2829,34 @@ sched_is_disabled_for_current_region_p (void)
   return true;
 }
 
-/* Schedule a region.  A region is either an inner loop, a loop-free
-   subroutine, or a single basic block.  Each bb in the region is
-   scheduled after its flow predecessors.  */
-
-static void
-schedule_region (int rgn)
+/* Free all region dependencies saved in INSN_BACK_DEPS and 
+   INSN_RESOLVED_BACK_DEPS.  The Haifa scheduler does this on the fly
+   when scheduling, so this function is supposed to be called from 
+   the selective scheduling only.  */
+void
+free_rgn_deps (void)
 {
-  basic_block block;
-  edge_iterator ei;
-  edge e;
   int bb;
-  int sched_rgn_n_insns = 0;
-
-  rgn_n_insns = 0;
-  /* Set variables for the current region.  */
-  current_nr_blocks = RGN_NR_BLOCKS (rgn);
-  current_blocks = RGN_BLOCKS (rgn);
-  
-  /* See comments in add_block1, for what reasons we allocate +1 element.  */ 
-  ebb_head = XRESIZEVEC (int, ebb_head, current_nr_blocks + 1);
-  for (bb = 0; bb <= current_nr_blocks; bb++)
-    ebb_head[bb] = current_blocks + bb;
-
-  /* Don't schedule region that is marked by
-     NOTE_DISABLE_SCHED_OF_BLOCK.  */
-  if (sched_is_disabled_for_current_region_p ())
-    return;
 
-  if (!RGN_DONT_CALC_DEPS (rgn))
+  for (bb = 0; bb < current_nr_blocks; bb++)
     {
-      init_deps_global ();
-
-      /* Initializations for region data dependence analysis.  */
-      bb_deps = XNEWVEC (struct deps, current_nr_blocks);
-      for (bb = 0; bb < current_nr_blocks; bb++)
-       init_deps (bb_deps + bb);
+      rtx head, tail;
+      
+      gcc_assert (EBB_FIRST_BB (bb) == EBB_LAST_BB (bb));
+      get_ebb_head_tail (EBB_FIRST_BB (bb), EBB_LAST_BB (bb), &head, &tail);
 
-      /* Compute dependencies.  */
-      for (bb = 0; bb < current_nr_blocks; bb++)
-       compute_block_dependences (bb);
+      sched_free_deps (head, tail, false);
+    }
+}
 
-      free_pending_lists ();
+static int rgn_n_insns;
 
-      finish_deps_global ();
+/* Compute insn priority for a current region.  */
+void
+compute_priorities (void) 
+{
+  int bb;
 
-      free (bb_deps);
-    }
-  else
-    /* This is a recovery block.  It is always a single block region.  */
-    gcc_assert (current_nr_blocks == 1);
-      
-  /* Set priorities.  */
   current_sched_info->sched_max_insns_priority = 0;
   for (bb = 0; bb < current_nr_blocks; bb++)
     {
@@ -2741,56 +2868,35 @@ schedule_region (int rgn)
       rgn_n_insns += set_priorities (head, tail);
     }
   current_sched_info->sched_max_insns_priority++;
+}
 
-  /* Compute interblock info: probabilities, split-edges, dominators, etc.  */
-  if (current_nr_blocks > 1)
-    {
-      prob = XNEWVEC (int, current_nr_blocks);
+/* Schedule a region.  A region is either an inner loop, a loop-free
+   subroutine, or a single basic block.  Each bb in the region is
+   scheduled after its flow predecessors.  */
 
-      dom = sbitmap_vector_alloc (current_nr_blocks, current_nr_blocks);
-      sbitmap_vector_zero (dom, current_nr_blocks);
+static void
+schedule_region (int rgn)
+{
+  int bb;
+  int sched_rgn_n_insns = 0;
 
-      /* Use ->aux to implement EDGE_TO_BIT mapping.  */
-      rgn_nr_edges = 0;
-      FOR_EACH_BB (block)
-       {
-         if (CONTAINING_RGN (block->index) != rgn)
-           continue;
-         FOR_EACH_EDGE (e, ei, block->succs)
-           SET_EDGE_TO_BIT (e, rgn_nr_edges++);
-       }
+  rgn_n_insns = 0;
 
-      rgn_edges = XNEWVEC (edge, rgn_nr_edges);
-      rgn_nr_edges = 0;
-      FOR_EACH_BB (block)
-       {
-         if (CONTAINING_RGN (block->index) != rgn)
-           continue;
-         FOR_EACH_EDGE (e, ei, block->succs)
-           rgn_edges[rgn_nr_edges++] = e;
-       }
+  rgn_setup_region (rgn);
 
-      /* Split edges.  */
-      pot_split = sbitmap_vector_alloc (current_nr_blocks, rgn_nr_edges);
-      sbitmap_vector_zero (pot_split, current_nr_blocks);
-      ancestor_edges = sbitmap_vector_alloc (current_nr_blocks, rgn_nr_edges);
-      sbitmap_vector_zero (ancestor_edges, current_nr_blocks);
+  /* Don't schedule region that is marked by
+     NOTE_DISABLE_SCHED_OF_BLOCK.  */
+  if (sched_is_disabled_for_current_region_p ())
+    return;
 
-      /* Compute probabilities, dominators, split_edges.  */
-      for (bb = 0; bb < current_nr_blocks; bb++)
-       compute_dom_prob_ps (bb);
+  sched_rgn_compute_dependencies (rgn);
 
-      /* Cleanup ->aux used for EDGE_TO_BIT mapping.  */
-      /* We don't need them anymore.  But we want to avoid duplication of
-        aux fields in the newly created edges.  */
-      FOR_EACH_BB (block)
-       {
-         if (CONTAINING_RGN (block->index) != rgn)
-           continue;
-         FOR_EACH_EDGE (e, ei, block->succs)
-           e->aux = NULL;
-        }
-    }
+  sched_rgn_local_init (rgn);
+
+  /* Set priorities.  */
+  compute_priorities ();
+
+  sched_extend_ready_list (rgn_n_insns);
 
   /* Now we can schedule all blocks.  */
   for (bb = 0; bb < current_nr_blocks; bb++)
@@ -2812,31 +2918,7 @@ schedule_region (int rgn)
       current_sched_info->prev_head = PREV_INSN (head);
       current_sched_info->next_tail = NEXT_INSN (tail);
 
-
-      /* rm_other_notes only removes notes which are _inside_ the
-        block---that is, it won't remove notes before the first real insn
-        or after the last real insn of the block.  So if the first insn
-        has a REG_SAVE_NOTE which would otherwise be emitted before the
-        insn, it is redundant with the note before the start of the
-        block, and so we have to take it out.  */
-      if (INSN_P (head))
-       {
-         rtx note;
-
-         for (note = REG_NOTES (head); note; note = XEXP (note, 1))
-           if (REG_NOTE_KIND (note) == REG_SAVE_NOTE)
-             remove_note (head, note);
-       }
-      else
-       /* This means that first block in ebb is empty.
-          It looks to me as an impossible thing.  There at least should be
-          a recovery check, that caused the splitting.  */
-       gcc_unreachable ();
-
-      /* Remove remaining note insns from the block, save them in
-        note_list.  These notes are restored at the end of
-        schedule_block ().  */
-      rm_other_notes (head, tail);
+      remove_notes (head, tail);
 
       unlink_bb_notes (first_bb, last_bb);
 
@@ -2848,7 +2930,7 @@ schedule_region (int rgn)
       curr_bb = first_bb;
       if (dbg_cnt (sched_block))
         {
-          schedule_block (&curr_bb, rgn_n_insns);
+          schedule_block (&curr_bb);
           gcc_assert (EBB_FIRST_BB (bb) == first_bb);
           sched_rgn_n_insns += sched_n_insns;
         }
@@ -2859,26 +2941,16 @@ schedule_region (int rgn)
 
       /* Clean up.  */
       if (current_nr_blocks > 1)
-       {
-         free (candidate_table);
-         free (bblst_table);
-         free (edgelst_table);
-       }
+       free_trg_info ();
     }
 
   /* Sanity check: verify that all region insns were scheduled.  */
   gcc_assert (sched_rgn_n_insns == rgn_n_insns);
 
-  /* Done with this region.  */
+  sched_finish_ready_list ();
 
-  if (current_nr_blocks > 1)
-    {
-      free (prob);
-      sbitmap_vector_free (dom);
-      sbitmap_vector_free (pot_split);
-      sbitmap_vector_free (ancestor_edges);
-      free (rgn_edges);
-    }
+  /* Done with this region.  */
+  sched_rgn_local_finish ();
 
   /* Free dependencies.  */
   for (bb = 0; bb < current_nr_blocks; ++bb)
@@ -2890,28 +2962,33 @@ schedule_region (int rgn)
 
 /* Initialize data structures for region scheduling.  */
 
-static void
-init_regions (void)
+void
+sched_rgn_init (bool single_blocks_p)
 {
-  nr_regions = 0;
-  rgn_table = 0;
-  rgn_bb_table = 0;
-  block_to_bb = 0;
-  containing_rgn = 0;
+  min_spec_prob = ((PARAM_VALUE (PARAM_MIN_SPEC_PROB) * REG_BR_PROB_BASE)
+                   / 100);
+
+  nr_inter = 0;
+  nr_spec = 0;
+
   extend_regions ();
 
+  CONTAINING_RGN (ENTRY_BLOCK) = -1;
+  CONTAINING_RGN (EXIT_BLOCK) = -1;
+
   /* Compute regions for scheduling.  */
-  if (reload_completed
+  if (single_blocks_p
       || n_basic_blocks == NUM_FIXED_BLOCKS + 1
       || !flag_schedule_interblock
       || is_cfg_nonregular ())
     {
-      find_single_block_region ();
+      find_single_block_region (sel_sched_p ());
     }
   else
     {
       /* Compute the dominators and post dominators.  */
-      calculate_dominance_info (CDI_DOMINATORS);
+      if (!sel_sched_p ())
+       calculate_dominance_info (CDI_DOMINATORS);
 
       /* Find regions.  */
       find_rgns ();
@@ -2921,56 +2998,20 @@ init_regions (void)
 
       /* For now.  This will move as more and more of haifa is converted
         to using the cfg code.  */
-      free_dominance_info (CDI_DOMINATORS);
+      if (!sel_sched_p ())
+       free_dominance_info (CDI_DOMINATORS);
     }
-  RGN_BLOCKS (nr_regions) = RGN_BLOCKS (nr_regions - 1) +
-    RGN_NR_BLOCKS (nr_regions - 1);
-}
 
-/* The one entry point in this file.  */
+  gcc_assert (0 < nr_regions && nr_regions <= n_basic_blocks);
 
+  RGN_BLOCKS (nr_regions) = (RGN_BLOCKS (nr_regions - 1) +
+                            RGN_NR_BLOCKS (nr_regions - 1));
+}
+
+/* Free data structures for region scheduling.  */
 void
-schedule_insns (void)
+sched_rgn_finish (void)
 {
-  int rgn;
-
-  /* Taking care of this degenerate case makes the rest of
-     this code simpler.  */
-  if (n_basic_blocks == NUM_FIXED_BLOCKS)
-    return;
-
-  nr_inter = 0;
-  nr_spec = 0;
-
-  /* We need current_sched_info in init_dependency_caches, which is
-     invoked via sched_init.  */
-  current_sched_info = &region_sched_info;
-
-  df_set_flags (DF_LR_RUN_DCE);
-  df_note_add_problem ();
-  df_analyze ();
-  regstat_compute_calls_crossed ();
-
-  sched_init ();
-
-  bitmap_initialize (&not_in_df, 0);
-  bitmap_clear (&not_in_df);
-
-  min_spec_prob = ((PARAM_VALUE (PARAM_MIN_SPEC_PROB) * REG_BR_PROB_BASE)
-                   / 100);
-
-  init_regions ();
-
-  /* EBB_HEAD is a region-scope structure.  But we realloc it for
-     each region to save time/memory/something else.  */
-  ebb_head = 0;
-  
-  /* Schedule every region in the subroutine.  */
-  for (rgn = 0; rgn < nr_regions; rgn++)
-    if (dbg_cnt (sched_region))
-      schedule_region (rgn);
-  
-  free(ebb_head);
   /* Reposition the prologue and epilogue notes in case we moved the
      prologue/epilogue insns.  */
   if (reload_completed)
@@ -2978,7 +3019,8 @@ schedule_insns (void)
 
   if (sched_verbose)
     {
-      if (reload_completed == 0 && flag_schedule_interblock)
+      if (reload_completed == 0
+         && flag_schedule_interblock)
        {
          fprintf (sched_dump,
                   "\n;; Procedure interblock/speculative motions == %d/%d \n",
@@ -2989,22 +3031,237 @@ schedule_insns (void)
       fprintf (sched_dump, "\n\n");
     }
 
-  /* Clean up.  */
+  nr_regions = 0;
+
   free (rgn_table);
+  rgn_table = NULL;
+
   free (rgn_bb_table);
+  rgn_bb_table = NULL;
+
   free (block_to_bb);
+  block_to_bb = NULL;
+
   free (containing_rgn);
+  containing_rgn = NULL;
+
+  free (ebb_head);
+  ebb_head = NULL;
+}
+
+/* Setup global variables like CURRENT_BLOCKS and CURRENT_NR_BLOCK to
+   point to the region RGN.  */
+void
+rgn_setup_region (int rgn)
+{
+  int bb;
+
+  /* Set variables for the current region.  */
+  current_nr_blocks = RGN_NR_BLOCKS (rgn);
+  current_blocks = RGN_BLOCKS (rgn);
+  
+  /* EBB_HEAD is a region-scope structure.  But we realloc it for
+     each region to save time/memory/something else.
+     See comments in add_block1, for what reasons we allocate +1 element.  */
+  ebb_head = XRESIZEVEC (int, ebb_head, current_nr_blocks + 1);
+  for (bb = 0; bb <= current_nr_blocks; bb++)
+    ebb_head[bb] = current_blocks + bb;
+}
+
+/* Compute instruction dependencies in region RGN.  */
+void
+sched_rgn_compute_dependencies (int rgn)
+{
+  if (!RGN_DONT_CALC_DEPS (rgn))
+    {
+      int bb;
+
+      if (sel_sched_p ())
+       sched_emulate_haifa_p = 1;
+
+      init_deps_global ();
+
+      /* Initializations for region data dependence analysis.  */
+      bb_deps = XNEWVEC (struct deps, current_nr_blocks);
+      for (bb = 0; bb < current_nr_blocks; bb++)
+       init_deps (bb_deps + bb);
+
+      /* Initialize array used in add_branch_dependencies ().  */
+      ref_counts = XCNEWVEC (int, get_max_uid () + 1);
+      
+      /* Compute backward dependencies.  */
+      for (bb = 0; bb < current_nr_blocks; bb++)
+       compute_block_dependences (bb);
+      
+      free (ref_counts);
+      free_pending_lists ();
+      finish_deps_global ();
+      free (bb_deps);
 
-  regstat_free_calls_crossed ();
+      /* We don't want to recalculate this twice.  */
+      RGN_DONT_CALC_DEPS (rgn) = 1;
 
+      if (sel_sched_p ())
+       sched_emulate_haifa_p = 0;
+    }
+  else
+    /* (This is a recovery block.  It is always a single block region.)
+       OR (We use selective scheduling.)  */
+    gcc_assert (current_nr_blocks == 1 || sel_sched_p ());
+}
+
+/* Init region data structures.  Returns true if this region should
+   not be scheduled.  */
+void
+sched_rgn_local_init (int rgn)
+{
+  int bb;
+      
+  /* Compute interblock info: probabilities, split-edges, dominators, etc.  */
+  if (current_nr_blocks > 1)
+    {
+      basic_block block;
+      edge e;
+      edge_iterator ei;
+
+      prob = XNEWVEC (int, current_nr_blocks);
+
+      dom = sbitmap_vector_alloc (current_nr_blocks, current_nr_blocks);
+      sbitmap_vector_zero (dom, current_nr_blocks);
+
+      /* Use ->aux to implement EDGE_TO_BIT mapping.  */
+      rgn_nr_edges = 0;
+      FOR_EACH_BB (block)
+       {
+         if (CONTAINING_RGN (block->index) != rgn)
+           continue;
+         FOR_EACH_EDGE (e, ei, block->succs)
+           SET_EDGE_TO_BIT (e, rgn_nr_edges++);
+       }
+
+      rgn_edges = XNEWVEC (edge, rgn_nr_edges);
+      rgn_nr_edges = 0;
+      FOR_EACH_BB (block)
+       {
+         if (CONTAINING_RGN (block->index) != rgn)
+           continue;
+         FOR_EACH_EDGE (e, ei, block->succs)
+           rgn_edges[rgn_nr_edges++] = e;
+       }
+
+      /* Split edges.  */
+      pot_split = sbitmap_vector_alloc (current_nr_blocks, rgn_nr_edges);
+      sbitmap_vector_zero (pot_split, current_nr_blocks);
+      ancestor_edges = sbitmap_vector_alloc (current_nr_blocks, rgn_nr_edges);
+      sbitmap_vector_zero (ancestor_edges, current_nr_blocks);
+
+      /* Compute probabilities, dominators, split_edges.  */
+      for (bb = 0; bb < current_nr_blocks; bb++)
+       compute_dom_prob_ps (bb);
+
+      /* Cleanup ->aux used for EDGE_TO_BIT mapping.  */
+      /* We don't need them anymore.  But we want to avoid duplication of
+        aux fields in the newly created edges.  */
+      FOR_EACH_BB (block)
+       {
+         if (CONTAINING_RGN (block->index) != rgn)
+           continue;
+         FOR_EACH_EDGE (e, ei, block->succs)
+           e->aux = NULL;
+        }
+    }
+}
+
+/* Free data computed for the finished region.  */
+void 
+sched_rgn_local_free (void)
+{
+  free (prob);
+  sbitmap_vector_free (dom);
+  sbitmap_vector_free (pot_split);
+  sbitmap_vector_free (ancestor_edges);
+  free (rgn_edges);
+}
+
+/* Free data computed for the finished region.  */
+void
+sched_rgn_local_finish (void)
+{
+  if (current_nr_blocks > 1 && !sel_sched_p ())
+    {
+      sched_rgn_local_free ();
+    }
+}
+
+/* Setup scheduler infos.  */
+void
+rgn_setup_common_sched_info (void)
+{
+  memcpy (&rgn_common_sched_info, &haifa_common_sched_info,
+         sizeof (rgn_common_sched_info));
+
+  rgn_common_sched_info.fix_recovery_cfg = rgn_fix_recovery_cfg;
+  rgn_common_sched_info.add_block = rgn_add_block;
+  rgn_common_sched_info.estimate_number_of_insns
+    = rgn_estimate_number_of_insns;
+  rgn_common_sched_info.sched_pass_id = SCHED_RGN_PASS;
+
+  common_sched_info = &rgn_common_sched_info;
+}
+
+/* Setup all *_sched_info structures (for the Haifa frontend
+   and for the dependence analysis) in the interblock scheduler.  */
+void
+rgn_setup_sched_infos (void)
+{
+  if (!sel_sched_p ())
+    memcpy (&rgn_sched_deps_info, &rgn_const_sched_deps_info,
+           sizeof (rgn_sched_deps_info));
+  else
+    memcpy (&rgn_sched_deps_info, &rgn_const_sel_sched_deps_info,
+           sizeof (rgn_sched_deps_info));
+
+  sched_deps_info = &rgn_sched_deps_info;
+
+  memcpy (&rgn_sched_info, &rgn_const_sched_info, sizeof (rgn_sched_info));
+  current_sched_info = &rgn_sched_info;
+}
+
+/* The one entry point in this file.  */
+void
+schedule_insns (void)
+{
+  int rgn;
+
+  /* Taking care of this degenerate case makes the rest of
+     this code simpler.  */
+  if (n_basic_blocks == NUM_FIXED_BLOCKS)
+    return;
+
+  rgn_setup_common_sched_info ();
+  rgn_setup_sched_infos ();
+
+  haifa_sched_init ();
+  sched_rgn_init (reload_completed);
+
+  bitmap_initialize (&not_in_df, 0);
   bitmap_clear (&not_in_df);
 
-  sched_finish ();
+  /* Schedule every region in the subroutine.  */
+  for (rgn = 0; rgn < nr_regions; rgn++)
+    if (dbg_cnt (sched_region))
+      schedule_region (rgn);
+
+  /* Clean up.  */
+  sched_rgn_finish ();
+  bitmap_clear (&not_in_df);
+
+  haifa_sched_finish ();
 }
 
 /* INSN has been added to/removed from current region.  */
 static void
-add_remove_insn (rtx insn, int remove_p)
+rgn_add_remove_insn (rtx insn, int remove_p)
 {
   if (!remove_p)
     rgn_n_insns++;
@@ -3021,7 +3278,7 @@ add_remove_insn (rtx insn, int remove_p)
 }
 
 /* Extend internal data structures.  */
-static void
+void
 extend_regions (void)
 {
   rgn_table = XRESIZEVEC (region, rgn_table, n_basic_blocks);
@@ -3030,31 +3287,37 @@ extend_regions (void)
   containing_rgn = XRESIZEVEC (int, containing_rgn, last_basic_block);
 }
 
+void
+rgn_make_new_region_out_of_new_block (basic_block bb)
+{
+  int i;
+
+  i = RGN_BLOCKS (nr_regions);
+  /* I - first free position in rgn_bb_table.  */
+
+  rgn_bb_table[i] = bb->index;
+  RGN_NR_BLOCKS (nr_regions) = 1;
+  RGN_HAS_REAL_EBB (nr_regions) = 0;
+  RGN_DONT_CALC_DEPS (nr_regions) = 0;
+  CONTAINING_RGN (bb->index) = nr_regions;
+  BLOCK_TO_BB (bb->index) = 0;
+
+  nr_regions++;
+      
+  RGN_BLOCKS (nr_regions) = i + 1;
+}
+
 /* BB was added to ebb after AFTER.  */
 static void
-add_block1 (basic_block bb, basic_block after)
+rgn_add_block (basic_block bb, basic_block after)
 {
   extend_regions ();
-
   bitmap_set_bit (&not_in_df, bb->index);
 
   if (after == 0 || after == EXIT_BLOCK_PTR)
     {
-      int i;
-      
-      i = RGN_BLOCKS (nr_regions);
-      /* I - first free position in rgn_bb_table.  */
-
-      rgn_bb_table[i] = bb->index;
-      RGN_NR_BLOCKS (nr_regions) = 1;
-      RGN_DONT_CALC_DEPS (nr_regions) = after == EXIT_BLOCK_PTR;
-      RGN_HAS_REAL_EBB (nr_regions) = 0;
-      CONTAINING_RGN (bb->index) = nr_regions;
-      BLOCK_TO_BB (bb->index) = 0;
-
-      nr_regions++;
-      
-      RGN_BLOCKS (nr_regions) = i + 1;
+      rgn_make_new_region_out_of_new_block (bb);
+      RGN_DONT_CALC_DEPS (nr_regions - 1) = (after == EXIT_BLOCK_PTR);
     }
   else
     { 
@@ -3114,7 +3377,7 @@ add_block1 (basic_block bb, basic_block after)
    For parameter meaning please refer to
    sched-int.h: struct sched_info: fix_recovery_cfg.  */
 static void
-fix_recovery_cfg (int bbi, int check_bbi, int check_bb_nexti)
+rgn_fix_recovery_cfg (int bbi, int check_bbi, int check_bb_nexti)
 {
   int old_pos, new_pos, i;
 
@@ -3173,7 +3436,11 @@ static unsigned int
 rest_of_handle_sched (void)
 {
 #ifdef INSN_SCHEDULING
-  schedule_insns ();
+  if (flag_selective_scheduling
+      && ! maybe_skip_selective_scheduling ())
+    run_selective_scheduling ();
+  else
+    schedule_insns ();
 #endif
   return 0;
 }
@@ -3194,12 +3461,18 @@ static unsigned int
 rest_of_handle_sched2 (void)
 {
 #ifdef INSN_SCHEDULING
-  /* Do control and data sched analysis again,
-     and write some more of the results to dump file.  */
-  if (flag_sched2_use_superblocks || flag_sched2_use_traces)
-    schedule_ebbs ();
+  if (flag_selective_scheduling2
+      && ! maybe_skip_selective_scheduling ())
+    run_selective_scheduling ();
   else
-    schedule_insns ();
+    {
+      /* Do control and data sched analysis again,
+        and write some more of the results to dump file.  */
+      if (flag_sched2_use_superblocks || flag_sched2_use_traces)
+       schedule_ebbs ();
+      else
+       schedule_insns ();
+    }
 #endif
   return 0;
 }
index 242791b..2544338 100644 (file)
@@ -29,13 +29,11 @@ along with GCC; see the file COPYING3.  If not see
 #include "hard-reg-set.h"
 #include "basic-block.h"
 #include "real.h"
+#include "insn-attr.h"
 #include "sched-int.h"
 #include "tree-pass.h"
 
 static char *safe_concat (char *, char *, const char *);
-static void print_exp (char *, const_rtx, int);
-static void print_value (char *, const_rtx, int);
-static void print_pattern (char *, const_rtx, int);
 
 #define BUF_LEN 2048
 
@@ -425,7 +423,7 @@ print_exp (char *buf, const_rtx x, int verbose)
 /* Prints rtxes, I customarily classified as values.  They're constants,
    registers, labels, symbols and memory accesses.  */
 
-static void
+void
 print_value (char *buf, const_rtx x, int verbose)
 {
   char t[BUF_LEN];
@@ -532,7 +530,7 @@ print_value (char *buf, const_rtx x, int verbose)
 
 /* The next step in insn detalization, its pattern recognition.  */
 
-static void
+void
 print_pattern (char *buf, const_rtx x, int verbose)
 {
   char t1[BUF_LEN], t2[BUF_LEN], t3[BUF_LEN];
@@ -643,10 +641,10 @@ print_pattern (char *buf, const_rtx x, int verbose)
    depends now on sched.c inner variables ...)  */
 
 void
-print_insn (char *buf, rtx x, int verbose)
+print_insn (char *buf, const_rtx x, int verbose)
 {
   char t[BUF_LEN];
-  rtx insn = x;
+  const_rtx insn = x;
 
   switch (GET_CODE (x))
     {
@@ -681,7 +679,7 @@ print_insn (char *buf, rtx x, int verbose)
        strcpy (t, "call <...>");
 #ifdef INSN_SCHEDULING
       if (verbose && current_sched_info)
-       sprintf (buf, "%s: %s", (*current_sched_info->print_insn) (x, 1), t);
+       sprintf (buf, "%s: %s", (*current_sched_info->print_insn) (insn, 1), t);
       else
 #endif
        sprintf (buf, " %4d %s", INSN_UID (insn), t);
@@ -702,7 +700,6 @@ print_insn (char *buf, rtx x, int verbose)
     }
 }                              /* print_insn */
 
-
 /* Emit a slim dump of X (an insn) to the file F, including any register
    note attached to the instruction.  */
 void
@@ -736,10 +733,21 @@ debug_insn_slim (rtx x)
 void
 print_rtl_slim_with_bb (FILE *f, rtx first, int flags)
 {
+  print_rtl_slim (f, first, NULL, -1, flags);
+}
+
+/* Same as above, but stop at LAST or when COUNT == 0.  
+   If COUNT < 0 it will stop only at LAST or NULL rtx.  */
+void
+print_rtl_slim (FILE *f, rtx first, rtx last, int count, int flags)
+{
   basic_block current_bb = NULL;
-  rtx insn;
+  rtx insn, tail;
 
-  for (insn = first; NULL != insn; insn = NEXT_INSN (insn))
+  tail = last ? NEXT_INSN (last) : NULL_RTX;
+  for (insn = first; 
+       (insn != NULL) && (insn != tail) && (count != 0); 
+       insn = NEXT_INSN (insn))
     {
       if ((flags & TDF_BLOCKS)
          && (INSN_P (insn) || GET_CODE (insn) == NOTE)
@@ -759,6 +767,21 @@ print_rtl_slim_with_bb (FILE *f, rtx first, int flags)
          dump_bb_info (current_bb, false, true, flags, ";; ", f);
          current_bb = NULL;
        }
+      if (count > 0)
+        count--;
     }
 }
 
+void 
+debug_bb_slim (struct basic_block_def *bb)
+{
+  print_rtl_slim (stderr, BB_HEAD (bb), BB_END (bb), -1, 32);
+}
+
+void
+debug_bb_n_slim (int n)
+{
+  struct basic_block_def *bb = BASIC_BLOCK (n);
+  debug_bb_slim (bb);
+}
+
diff --git a/gcc/sel-sched-dump.c b/gcc/sel-sched-dump.c
new file mode 100644 (file)
index 0000000..7d56d3b
--- /dev/null
@@ -0,0 +1,945 @@
+/* Instruction scheduling pass.   Log dumping infrastructure.
+   Copyright (C) 2006, 2007, 2008 Free Software Foundation, Inc.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free
+Software Foundation; either version 3, or (at your option) any later
+version.
+
+GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or
+FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3.  If not see
+<http://www.gnu.org/licenses/>.  */
+
+#include "config.h"
+#include "system.h"
+#include "coretypes.h"
+#include "tm.h"
+#include "toplev.h"
+#include "rtl.h"
+#include "tm_p.h"
+#include "hard-reg-set.h"
+#include "regs.h"
+#include "function.h"
+#include "flags.h"
+#include "insn-config.h"
+#include "insn-attr.h"
+#include "params.h"
+#include "output.h"
+#include "basic-block.h"
+#include "cselib.h"
+#include "sel-sched-ir.h"
+#include "sel-sched-dump.h"
+\f
+
+/* These variables control high-level pretty printing.  */
+static int sel_dump_cfg_flags = SEL_DUMP_CFG_FLAGS;
+static int sel_debug_cfg_flags = SEL_DUMP_CFG_FLAGS;
+
+/* True when a cfg should be dumped.  */
+static bool sel_dump_cfg_p;
+
+/* Variables that are used to build the cfg dump file name.  */
+static const char * const sel_debug_cfg_root = "./";
+static const char * const sel_debug_cfg_root_postfix_default = "";
+static const char *sel_debug_cfg_root_postfix = "";
+static int sel_dump_cfg_fileno = -1;
+static int sel_debug_cfg_fileno = -1;
+
+/* When this flag is on, we are dumping to the .dot file.
+   When it is off, we are dumping to log.
+   This is useful to differentiate formatting between log and .dot
+   files.  */
+bool sched_dump_to_dot_p = false;
+
+/* Controls how insns from a fence list should be dumped.  */
+static int dump_flist_insn_flags = (DUMP_INSN_UID | DUMP_INSN_BBN
+                                    | DUMP_INSN_SEQNO);
+\f
+
+/* The variable used to hold the value of sched_dump when temporarily
+   switching dump output to the other source, e.g. the .dot file.  */
+static FILE *saved_sched_dump = NULL;
+
+/* Switch sched_dump to TO.  It must not be called twice.  */
+static void
+switch_dump (FILE *to)
+{
+  gcc_assert (saved_sched_dump == NULL);
+  
+  saved_sched_dump = sched_dump;
+  sched_dump = to;
+}
+
+/* Restore previously switched dump.  */
+static void
+restore_dump (void)
+{
+  sched_dump = saved_sched_dump;
+  saved_sched_dump = NULL;
+}
+\f
+
+/* Functions for dumping instructions, av sets, and exprs.  */ 
+
+/* Default flags for dumping insns.  */
+static int dump_insn_rtx_flags = DUMP_INSN_RTX_PATTERN;
+
+/* Default flags for dumping vinsns.  */
+static int dump_vinsn_flags = (DUMP_VINSN_INSN_RTX | DUMP_VINSN_TYPE
+                              | DUMP_VINSN_COUNT);
+
+/* Default flags for dumping expressions.  */
+static int dump_expr_flags = DUMP_EXPR_ALL;
+
+/* Default flags for dumping insns when debugging.  */
+static int debug_insn_rtx_flags = DUMP_INSN_RTX_ALL;
+
+/* Default flags for dumping vinsns when debugging.  */
+static int debug_vinsn_flags = DUMP_VINSN_ALL;
+
+/* Default flags for dumping expressions when debugging.  */
+static int debug_expr_flags = DUMP_EXPR_ALL;
+
+/* Controls how an insn from stream should be dumped when debugging.  */
+static int debug_insn_flags = DUMP_INSN_ALL;
+
+/* Print an rtx X.  */
+void
+sel_print_rtl (rtx x)
+{
+  print_rtl_single (sched_dump, x);
+}
+
+/* Dump insn INSN honoring FLAGS.  */
+void
+dump_insn_rtx_1 (rtx insn, int flags)
+{
+  int all;
+
+  /* flags == -1 also means dumping all.  */
+  all = (flags & 1);;
+  if (all)
+    flags |= DUMP_INSN_RTX_ALL;
+
+  sel_print ("(");
+
+  if (flags & DUMP_INSN_RTX_UID)
+    sel_print ("%d;", INSN_UID (insn));
+
+  if (flags & DUMP_INSN_RTX_PATTERN)
+    {
+      char buf[2048];
+
+      print_insn (buf, insn, 0);
+      sel_print ("%s;", buf);
+    }
+
+  if (flags & DUMP_INSN_RTX_BBN)
+    {
+      basic_block bb = BLOCK_FOR_INSN (insn);
+
+      sel_print ("bb:%d;", bb != NULL ? bb->index : -1);
+    }
+
+  sel_print (")");
+}
+
+
+/* Dump INSN with default flags.  */
+void
+dump_insn_rtx (rtx insn)
+{
+  dump_insn_rtx_1 (insn, dump_insn_rtx_flags);
+}
+
+
+/* Dump INSN to stderr.  */
+void
+debug_insn_rtx (rtx insn)
+{
+  switch_dump (stderr);
+  dump_insn_rtx_1 (insn, debug_insn_rtx_flags);
+  sel_print ("\n");
+  restore_dump ();
+}
+
+/* Dump vinsn VI honoring flags.  */
+void
+dump_vinsn_1 (vinsn_t vi, int flags)
+{
+  int all;
+
+  /* flags == -1 also means dumping all.  */
+  all = flags & 1;
+  if (all)
+    flags |= DUMP_VINSN_ALL;
+
+  sel_print ("(");
+
+  if (flags & DUMP_VINSN_INSN_RTX)
+    dump_insn_rtx_1 (VINSN_INSN_RTX (vi), dump_insn_rtx_flags | all);
+
+  if (flags & DUMP_VINSN_TYPE)
+    sel_print ("type:%s;", GET_RTX_NAME (VINSN_TYPE (vi)));
+
+  if (flags & DUMP_VINSN_COUNT)
+    sel_print ("count:%d;", VINSN_COUNT (vi));
+
+  if (flags & DUMP_VINSN_COST)
+    {
+      int cost = vi->cost;
+
+      if (cost != -1)
+       sel_print ("cost:%d;", cost);
+    }
+
+  sel_print (")");
+}
+
+/* Dump vinsn VI with default flags.  */
+void
+dump_vinsn (vinsn_t vi)
+{
+  dump_vinsn_1 (vi, dump_vinsn_flags);
+}
+
+/* Dump vinsn VI to stderr.  */
+void
+debug_vinsn (vinsn_t vi)
+{
+  switch_dump (stderr);
+  dump_vinsn_1 (vi, debug_vinsn_flags);
+  sel_print ("\n"); 
+  restore_dump ();
+}
+
+/* Dump EXPR honoring flags.  */
+void
+dump_expr_1 (expr_t expr, int flags)
+{
+  int all;
+
+  /* flags == -1 also means dumping all.  */
+  all = flags & 1;
+  if (all)
+    flags |= DUMP_EXPR_ALL;
+
+  sel_print ("[");
+
+  if (flags & DUMP_EXPR_VINSN)
+    dump_vinsn_1 (EXPR_VINSN (expr), dump_vinsn_flags | all);
+
+  if (flags & DUMP_EXPR_SPEC)
+    {
+      int spec = EXPR_SPEC (expr);
+
+      if (spec != 0)
+       sel_print ("spec:%d;", spec);
+    }
+
+  if (flags & DUMP_EXPR_USEFULNESS)
+    {
+      int use = EXPR_USEFULNESS (expr);
+
+      if (use != REG_BR_PROB_BASE)
+        sel_print ("use:%d;", use);
+    }
+
+  if (flags & DUMP_EXPR_PRIORITY)
+    sel_print ("prio:%d;", EXPR_PRIORITY (expr));
+
+  if (flags & DUMP_EXPR_SCHED_TIMES)
+    {
+      int times = EXPR_SCHED_TIMES (expr);
+
+      if (times != 0)
+       sel_print ("times:%d;", times);
+    }
+
+  if (flags & DUMP_EXPR_SPEC_DONE_DS)
+    {
+      ds_t spec_done_ds = EXPR_SPEC_DONE_DS (expr);
+
+      if (spec_done_ds != 0)
+       sel_print ("ds:%d;", spec_done_ds);
+    }
+
+  if (flags & DUMP_EXPR_ORIG_BB)
+    {
+      int orig_bb = EXPR_ORIG_BB_INDEX (expr);
+
+      if (orig_bb != 0)
+       sel_print ("orig_bb:%d;", orig_bb);
+    }
+  
+  if (EXPR_TARGET_AVAILABLE (expr) < 1)
+    sel_print ("target:%d;", EXPR_TARGET_AVAILABLE (expr));
+  sel_print ("]");
+}
+
+/* Dump expression EXPR with default flags.  */
+void
+dump_expr (expr_t expr)
+{
+  dump_expr_1 (expr, dump_expr_flags);
+}
+
+/* Dump expression EXPR to stderr.  */
+void
+debug_expr (expr_t expr)
+{
+  switch_dump (stderr);
+  dump_expr_1 (expr, debug_expr_flags);
+  sel_print ("\n");
+  restore_dump ();
+}
+
+/* Dump insn I honoring FLAGS.  */
+void
+dump_insn_1 (insn_t i, int flags)
+{
+  int all;
+
+  all = flags & 1;
+  if (all)
+    flags |= DUMP_INSN_ALL;
+
+  if (!sched_dump_to_dot_p)
+    sel_print ("(");
+
+  if (flags & DUMP_INSN_EXPR)
+    {
+      dump_expr_1 (INSN_EXPR (i), dump_expr_flags | all);
+      sel_print (";");
+    }
+  else if (flags & DUMP_INSN_PATTERN)
+    {
+      dump_insn_rtx_1 (i, DUMP_INSN_RTX_PATTERN | all);
+      sel_print (";");
+    }
+  else if (flags & DUMP_INSN_UID)
+    sel_print ("uid:%d;", INSN_UID (i));
+
+  if (flags & DUMP_INSN_SEQNO)
+    sel_print ("seqno:%d;", INSN_SEQNO (i));
+
+  if (flags & DUMP_INSN_SCHED_CYCLE)
+    {
+      int cycle = INSN_SCHED_CYCLE (i);
+
+      if (cycle != 0)
+       sel_print ("cycle:%d;", cycle);
+    }
+
+  if (!sched_dump_to_dot_p)
+    sel_print (")");
+}
+
+/* Dump insn I with default flags.  */
+void
+dump_insn (insn_t i)
+{
+  dump_insn_1 (i, DUMP_INSN_EXPR | DUMP_INSN_SCHED_CYCLE);
+}
+
+/* Dump INSN to stderr.  */
+void
+debug_insn (insn_t insn)
+{
+  switch_dump (stderr);
+  dump_insn_1 (insn, debug_insn_flags);
+  sel_print ("\n");
+  restore_dump ();
+}
+
+/* Dumps av_set AV.  */
+void
+dump_av_set (av_set_t av)
+{
+  av_set_iterator i;
+  expr_t expr;
+  
+  if (!sched_dump_to_dot_p)
+    sel_print ("{");
+  
+  FOR_EACH_EXPR (expr, i, av)
+    {
+      dump_expr (expr);
+      if (!sched_dump_to_dot_p)
+        sel_print (" ");
+      else
+        sel_print ("\n");
+    }
+  
+  if (!sched_dump_to_dot_p)
+    sel_print ("}");
+}
+
+/* Dumps lvset LV.  */
+void
+dump_lv_set (regset lv)
+{
+  sel_print ("{");
+
+  /* This code was adapted from flow.c: dump_regset ().  */
+  if (lv == NULL)
+    sel_print ("nil");
+  else
+    {
+      unsigned i;
+      reg_set_iterator rsi;
+      int count = 0;
+      
+      EXECUTE_IF_SET_IN_REG_SET (lv, 0, i, rsi)
+        {
+          sel_print (" %d", i);
+          if (i < FIRST_PSEUDO_REGISTER)
+            {
+              sel_print (" [%s]", reg_names[i]);
+              ++count;
+            }
+          
+          ++count;
+          
+          if (sched_dump_to_dot_p && count == 12)
+            {
+              count = 0;
+              sel_print ("\n");
+            }
+        }
+    }
+  
+  sel_print ("}\n");
+}
+
+/* Dumps a list of instructions pointed to by P.  */
+static void
+dump_ilist (ilist_t p)
+{
+  while (p)
+    {
+      dump_insn (ILIST_INSN (p));
+      p = ILIST_NEXT (p);
+    }
+}
+
+/* Dumps a list of boundaries pointed to by BNDS.  */
+void
+dump_blist (blist_t bnds)
+{
+  for (; bnds; bnds = BLIST_NEXT (bnds))
+    {
+      bnd_t bnd = BLIST_BND (bnds);
+      
+      sel_print ("[to: %d; ptr: ", INSN_UID (BND_TO (bnd)));
+      dump_ilist (BND_PTR (bnd));
+      sel_print ("] ");
+    }
+}
+
+/* Dumps a list of fences pointed to by L.  */
+void
+dump_flist (flist_t l)
+{
+  while (l)
+    {
+      dump_insn_1 (FENCE_INSN (FLIST_FENCE (l)), dump_flist_insn_flags);
+      sel_print (" ");
+      l = FLIST_NEXT (l);
+    }
+}
+
+/* Dumps an insn vector SUCCS.  */
+void
+dump_insn_vector (rtx_vec_t succs)
+{
+  int i;
+  rtx succ;
+  
+  for (i = 0; VEC_iterate (rtx, succs, i, succ); i++)
+    if (succ)
+      dump_insn (succ);
+    else
+      sel_print ("NULL ");
+}
+
+/* Dumps a hard reg set SET to FILE using PREFIX.  */
+static void
+print_hard_reg_set (FILE *file, const char *prefix, HARD_REG_SET set)
+{
+  int i;
+
+  fprintf (file, "%s{ ", prefix);
+  for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
+    {
+      if (TEST_HARD_REG_BIT (set, i))
+       fprintf (file, "%d ", i);
+    }
+  fprintf (file, "}\n");
+}
+
+/* Dumps a hard reg set SET using PREFIX.  */
+void
+dump_hard_reg_set (const char *prefix, HARD_REG_SET set)
+{
+  print_hard_reg_set (sched_dump, prefix, set);
+}
+
+/* Pretty print INSN.  This is used as a hook.  */
+const char *
+sel_print_insn (const_rtx insn, int aligned ATTRIBUTE_UNUSED)
+{
+  static char buf[80];
+
+  /* '+' before insn means it is a new cycle start and it's not been 
+     scheduled yet.  '>' - has been scheduled.  */
+  if (s_i_d && INSN_LUID (insn) > 0)
+    if (GET_MODE (insn) == TImode)
+      sprintf (buf, "%s %4d", 
+               INSN_SCHED_TIMES (insn) > 0 ? "> " : "< ", 
+               INSN_UID (insn));
+    else
+      sprintf (buf, "%s %4d", 
+               INSN_SCHED_TIMES (insn) > 0 ? "! " : "  ", 
+               INSN_UID (insn));
+  else
+    if (GET_MODE (insn) == TImode)
+      sprintf (buf, "+ %4d", INSN_UID (insn));
+    else
+      sprintf (buf, "  %4d", INSN_UID (insn));
+
+  return buf;
+}
+\f
+
+/* Functions for pretty printing of CFG.  */
+
+/* Replace all occurencies of STR1 to STR2 in BUF.
+   The BUF must be large enough to hold the result.  */
+static void
+replace_str_in_buf (char *buf, const char *str1, const char *str2)
+{
+  int buf_len = strlen (buf);
+  int str1_len = strlen (str1);
+  int str2_len = strlen (str2);
+  int diff = str2_len - str1_len;
+
+  char *p = buf;
+  do
+    {
+      p = strstr (p, str1);
+      if (p) 
+       {
+         char *p1 = p + str1_len;
+         /* Copy the rest of buf and '\0'.  */
+         int n = buf + buf_len - p1;
+         int i;
+
+         /* Shift str by DIFF chars.  */
+         if (diff > 0)
+            for (i = n; i >= 0; i--)
+              p1[i + diff] = p1[i];
+         else
+            for (i = 0; i <= n; i++)
+              p1[i + diff] = p1[i];
+
+         /* Copy str2.  */
+         for (i = 0; i < str2_len; i++)
+           p[i] = str2[i];
+           
+         p += str2_len;
+         buf_len += diff;
+       }
+
+    }
+  while (p);
+}
+
+/* Replace characters in BUF that have special meaning in .dot file.  */
+void
+sel_prepare_string_for_dot_label (char *buf)
+{
+  static char specials_from[7][2] = { "<", ">", "{", "|", "}", "\"",
+                                      "\n" };
+  static char specials_to[7][3] = { "\\<", "\\>", "\\{", "\\|", "\\}", 
+                                    "\\\"", "\\l" };
+  unsigned i;
+
+  for (i = 0; i < 7; i++)
+    replace_str_in_buf (buf, specials_from[i], specials_to[i]);
+}
+
+/* Dump INSN with FLAGS.  */
+static void
+sel_dump_cfg_insn (insn_t insn, int flags)
+{
+  int insn_flags = DUMP_INSN_UID | DUMP_INSN_PATTERN;
+
+  if (sched_luids != NULL && INSN_LUID (insn) > 0)
+    {
+      if (flags & SEL_DUMP_CFG_INSN_SEQNO)
+       insn_flags |= DUMP_INSN_SEQNO | DUMP_INSN_SCHED_CYCLE | DUMP_INSN_EXPR;
+    }
+
+  dump_insn_1 (insn, insn_flags);
+}
+
+/* Dump E to the dot file F.  */
+static void
+sel_dump_cfg_edge (FILE *f, edge e)
+{
+  int w;
+  const char *color;
+
+  if (e->flags & EDGE_FALLTHRU)
+    {
+      w = 10;
+      color = ", color = red";
+    }
+  else if (e->src->next_bb == e->dest)
+    {
+      w = 3;
+      color = ", color = blue";
+    }
+  else
+    {
+      w = 1;
+      color = "";
+    }
+
+  fprintf (f, "\tbb%d -> bb%d [weight = %d%s];\n",
+          e->src->index, e->dest->index, w, color);
+}
+
+
+/* Return true if BB has a predesessor from current region.
+   TODO: Either make this function to trace back through empty block
+   or just remove those empty blocks.  */
+static bool
+has_preds_in_current_region_p (basic_block bb)
+{
+  edge e;
+  edge_iterator ei;
+
+  gcc_assert (!in_current_region_p (bb));
+
+  FOR_EACH_EDGE (e, ei, bb->preds)
+    if (in_current_region_p (e->src))
+      return true;
+
+  return false;
+}
+
+/* Dump a cfg region to the dot file F honoring FLAGS.  */
+static void
+sel_dump_cfg_2 (FILE *f, int flags)
+{
+  basic_block bb;
+
+  sched_dump_to_dot_p = true;
+  switch_dump (f);
+
+  fprintf (f, "digraph G {\n"
+          "\tratio = 2.25;\n"
+          "\tnode [shape = record, fontsize = 9];\n");
+
+  if (flags & SEL_DUMP_CFG_FUNCTION_NAME)
+    fprintf (f, "function [label = \"%s\"];\n", current_function_name ());
+
+  FOR_EACH_BB (bb)
+    {
+      insn_t insn = BB_HEAD (bb);
+      insn_t next_tail = NEXT_INSN (BB_END (bb));
+      edge e;
+      edge_iterator ei;
+      bool in_region_p = ((flags & SEL_DUMP_CFG_CURRENT_REGION)
+                         && in_current_region_p (bb));
+      bool full_p = (!(flags & SEL_DUMP_CFG_CURRENT_REGION)
+                    || in_region_p);
+      bool some_p = full_p || has_preds_in_current_region_p (bb);
+      const char *color;
+      const char *style;
+
+      if (!some_p)
+       continue;
+
+      if ((flags & SEL_DUMP_CFG_CURRENT_REGION)
+         && in_current_region_p (bb)
+         && BLOCK_TO_BB (bb->index) == 0)
+       color = "color = green, ";
+      else
+       color = "";
+
+      if ((flags & SEL_DUMP_CFG_FENCES)
+         && in_region_p)
+       {
+         style = "";
+
+         if (!sel_bb_empty_p (bb))
+           {
+             bool first_p = true;
+             insn_t tail = BB_END (bb);
+             insn_t cur_insn;
+
+             cur_insn = bb_note (bb);
+
+             do
+               {
+                 fence_t fence;
+
+                 cur_insn = NEXT_INSN (cur_insn);
+                 fence = flist_lookup (fences, cur_insn);
+
+                 if (fence != NULL)
+                   {
+                     if (!FENCE_SCHEDULED_P (fence))
+                       {
+                         if (first_p)
+                           color = "color = red, ";
+                         else
+                           color = "color = yellow, ";
+                       }
+                     else
+                       color = "color = blue, ";
+                   }
+
+                 first_p = false;
+               }
+             while (cur_insn != tail);
+           }
+       }
+      else if (!full_p)
+       style = "style = dashed, ";
+      else
+       style = "";
+
+      fprintf (f, "\tbb%d [%s%slabel = \"{Basic block %d", bb->index,
+              style, color, bb->index);
+
+      if ((flags & SEL_DUMP_CFG_BB_LOOP)
+         && bb->loop_father != NULL)
+       fprintf (f, ", loop %d", bb->loop_father->num);
+
+      if (full_p
+         && (flags & SEL_DUMP_CFG_BB_NOTES_LIST))
+       {
+         insn_t notes = BB_NOTE_LIST (bb);
+
+         if (notes != NULL_RTX)
+           {
+             fprintf (f, "|");
+
+             /* For simplicity, we dump notes from note_list in reversed order
+                to that what they will appear in the code.  */
+             while (notes != NULL_RTX)
+               {
+                 sel_dump_cfg_insn (notes, flags);
+                 fprintf (f, "\\l");
+
+                 notes = PREV_INSN (notes);
+               }
+           }
+       }
+
+      if (full_p
+         && (flags & SEL_DUMP_CFG_AV_SET)
+         && in_current_region_p (bb)
+         && !sel_bb_empty_p (bb))
+       {
+         fprintf (f, "|");
+
+         if (BB_AV_SET_VALID_P (bb))
+           dump_av_set (BB_AV_SET (bb));
+         else if (BB_AV_LEVEL (bb) == -1)
+           fprintf (f, "AV_SET needs update");
+       }
+
+      if ((flags & SEL_DUMP_CFG_LV_SET)
+         && !sel_bb_empty_p (bb))
+       {
+         fprintf (f, "|");
+
+         if (BB_LV_SET_VALID_P (bb))
+           dump_lv_set (BB_LV_SET (bb));
+         else
+           fprintf (f, "LV_SET needs update");
+       }
+
+      if (full_p
+         && (flags & SEL_DUMP_CFG_BB_INSNS))
+       {
+         fprintf (f, "|");
+         while (insn != next_tail)
+           {
+             sel_dump_cfg_insn (insn, flags);
+             fprintf (f, "\\l");
+
+             insn = NEXT_INSN (insn);
+           }
+       }
+
+      fprintf (f, "}\"];\n");
+
+      FOR_EACH_EDGE (e, ei, bb->succs)
+       if (full_p || in_current_region_p (e->dest))
+         sel_dump_cfg_edge (f, e);
+    }
+
+  fprintf (f, "}");
+
+  restore_dump ();
+  sched_dump_to_dot_p = false;
+}
+
+/* Dump a cfg region to the file specified by TAG honoring flags.  
+   The file is created by the function.  */
+static void
+sel_dump_cfg_1 (const char *tag, int flags)
+{
+  char *buf;
+  int i;
+  FILE *f;
+
+  ++sel_dump_cfg_fileno;
+
+  if (!sel_dump_cfg_p)
+    return;
+
+  i = 1 + snprintf (NULL, 0, "%s/%s%05d-%s.dot", sel_debug_cfg_root,
+                   sel_debug_cfg_root_postfix, sel_dump_cfg_fileno, tag);
+  buf = XNEWVEC (char, i);
+  snprintf (buf, i, "%s/%s%05d-%s.dot", sel_debug_cfg_root,
+           sel_debug_cfg_root_postfix, sel_dump_cfg_fileno, tag);
+
+  f = fopen (buf, "w");
+
+  if (f == NULL)
+    fprintf (stderr, "Can't create file: %s.\n", buf);
+  else
+    {
+      sel_dump_cfg_2 (f, flags);
+
+      fclose (f);
+    }
+
+  free (buf);
+}
+
+/* Setup cfg dumping flags.  Used for debugging.  */
+void
+setup_dump_cfg_params (void)
+{
+  sel_dump_cfg_flags = SEL_DUMP_CFG_FLAGS;
+  sel_dump_cfg_p = 0;
+  sel_debug_cfg_root_postfix = sel_debug_cfg_root_postfix_default;
+}
+
+/* Debug a cfg region with FLAGS.  */
+void
+sel_debug_cfg_1 (int flags)
+{
+  bool t1 = sel_dump_cfg_p;
+  int t2 = sel_dump_cfg_fileno;
+
+  sel_dump_cfg_p = true;
+  sel_dump_cfg_fileno = ++sel_debug_cfg_fileno;
+
+  sel_dump_cfg_1 ("sel-debug-cfg", flags);
+
+  sel_dump_cfg_fileno = t2;
+  sel_dump_cfg_p = t1;
+}
+\f
+/* Dumps av_set AV to stderr.  */
+void
+debug_av_set (av_set_t av)
+{
+  switch_dump (stderr);
+  dump_av_set (av);
+  sel_print ("\n");
+  restore_dump ();
+}
+
+/* Dump LV to stderr.  */
+void
+debug_lv_set (regset lv)
+{
+  switch_dump (stderr);
+  dump_lv_set (lv);
+  sel_print ("\n");
+  restore_dump ();
+}
+
+/* Dump an instruction list P to stderr.  */
+void
+debug_ilist (ilist_t p)
+{
+  switch_dump (stderr);
+  dump_ilist (p);
+  sel_print ("\n");
+  restore_dump ();
+}
+
+/* Dump a boundary list BNDS to stderr.  */
+void
+debug_blist (blist_t bnds)
+{
+  switch_dump (stderr);
+  dump_blist (bnds);
+  sel_print ("\n");
+  restore_dump ();
+}
+
+/* Dump an insn vector SUCCS.  */
+void
+debug_insn_vector (rtx_vec_t succs)
+{
+  switch_dump (stderr);
+  dump_insn_vector (succs);
+  sel_print ("\n");
+  restore_dump ();
+}
+
+/* Dump a hard reg set SET to stderr.  */
+void
+debug_hard_reg_set (HARD_REG_SET set)
+{
+  switch_dump (stderr);
+  dump_hard_reg_set ("", set);
+  sel_print ("\n");
+  restore_dump ();
+}
+
+/* Debug a cfg region with default flags.  */
+void
+sel_debug_cfg (void)
+{
+  sel_debug_cfg_1 (sel_debug_cfg_flags);
+}
+
+/* Print a current cselib value for X's address to stderr.  */
+rtx
+debug_mem_addr_value (rtx x)
+{
+  rtx t, addr;
+
+  gcc_assert (MEM_P (x));
+  t = shallow_copy_rtx (x);
+  if (cselib_lookup (XEXP (t, 0), Pmode, 0))
+    XEXP (t, 0) = cselib_subst_to_values (XEXP (t, 0));
+
+  t = canon_rtx (t);
+  addr = get_addr (XEXP (t, 0));
+  debug_rtx (t);
+  debug_rtx (addr);
+  return t;
+}
+
+
diff --git a/gcc/sel-sched-dump.h b/gcc/sel-sched-dump.h
new file mode 100644 (file)
index 0000000..70750f9
--- /dev/null
@@ -0,0 +1,241 @@
+/* Instruction scheduling pass.  Log dumping infrastructure.  
+   Copyright (C) 2006, 2007, 2008 Free Software Foundation, Inc.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free
+Software Foundation; either version 3, or (at your option) any later
+version.
+
+GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or
+FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3.  If not see
+<http://www.gnu.org/licenses/>.  */
+
+
+#ifndef GCC_SEL_SCHED_DUMP_H
+#define GCC_SEL_SCHED_DUMP_H
+
+#include "sel-sched-ir.h"
+
+
+/* These values control the dumping of control flow graph to the .dot file.  */
+enum sel_dump_cfg_def
+  {
+    /* Dump only current region.  */
+    SEL_DUMP_CFG_CURRENT_REGION = 2,
+
+    /* Dump note_list for this bb.  */
+    SEL_DUMP_CFG_BB_NOTES_LIST = 4,
+
+    /* Dump availability set from the bb header.  */
+    SEL_DUMP_CFG_AV_SET = 8,
+
+    /* Dump liveness set from the bb header.  */
+    SEL_DUMP_CFG_LV_SET = 16,
+
+    /* Dump insns of the given block.  */
+    SEL_DUMP_CFG_BB_INSNS = 32,
+
+    /* Show current fences when dumping cfg.  */
+    SEL_DUMP_CFG_FENCES = 64,
+
+    /* Show insn's seqnos when dumping cfg.  */
+    SEL_DUMP_CFG_INSN_SEQNO = 128,
+
+    /* Dump function name when dumping cfg.  */
+    SEL_DUMP_CFG_FUNCTION_NAME = 256,
+
+    /* Dump loop father number of the given bb.  */
+    SEL_DUMP_CFG_BB_LOOP = 512,
+
+    /* The default flags for cfg dumping.  */
+    SEL_DUMP_CFG_FLAGS = (SEL_DUMP_CFG_CURRENT_REGION   
+                          | SEL_DUMP_CFG_BB_NOTES_LIST   
+                          | SEL_DUMP_CFG_AV_SET         
+                          | SEL_DUMP_CFG_LV_SET         
+                          | SEL_DUMP_CFG_BB_INSNS       
+                          | SEL_DUMP_CFG_FENCES         
+                          | SEL_DUMP_CFG_INSN_SEQNO     
+                          | SEL_DUMP_CFG_BB_LOOP)
+  };
+
+/* These values control the dumping of insns containing in expressions.  */
+enum dump_insn_rtx_def
+  {
+    /* Dump insn's UID.  */
+    DUMP_INSN_RTX_UID = 2,
+
+    /* Dump insn's pattern.  */
+    DUMP_INSN_RTX_PATTERN = 4,
+
+    /* Dump insn's basic block number.  */
+    DUMP_INSN_RTX_BBN = 8,
+
+    /* Dump all of the above.  */
+    DUMP_INSN_RTX_ALL = (DUMP_INSN_RTX_UID | DUMP_INSN_RTX_PATTERN
+                        | DUMP_INSN_RTX_BBN)
+  };
+
+extern void dump_insn_rtx_1 (rtx, int);
+extern void dump_insn_rtx (rtx);
+extern void debug_insn_rtx (rtx);
+
+/* These values control dumping of vinsns.  The meaning of different fields
+   of a vinsn is explained in sel-sched-ir.h.  */
+enum dump_vinsn_def
+  {
+    /* Dump the insn behind this vinsn.  */
+    DUMP_VINSN_INSN_RTX = 2,
+
+    /* Dump vinsn's type.  */
+    DUMP_VINSN_TYPE = 4,
+
+    /* Dump vinsn's count.  */
+    DUMP_VINSN_COUNT = 8,
+
+    /* Dump the cost (default latency) of the insn behind this vinsn.  */
+    DUMP_VINSN_COST = 16,
+
+    /* Dump all of the above.  */
+    DUMP_VINSN_ALL = (DUMP_VINSN_INSN_RTX | DUMP_VINSN_TYPE | DUMP_VINSN_COUNT
+                     | DUMP_VINSN_COST)
+  };
+
+extern void dump_vinsn_1 (vinsn_t, int);
+extern void dump_vinsn (vinsn_t);
+extern void debug_vinsn (vinsn_t);
+
+/* These values control dumping of expressions.  The meaning of the fields
+   is explained in sel-sched-ir.h.  */
+enum dump_expr_def
+  {
+    /* Dump the vinsn behind this expression.  */
+    DUMP_EXPR_VINSN = 2,
+    
+    /* Dump expression's SPEC parameter.  */
+    DUMP_EXPR_SPEC = 4,
+
+    /* Dump expression's priority.  */
+    DUMP_EXPR_PRIORITY = 8,
+
+    /* Dump the number of times this expression was scheduled.  */
+    DUMP_EXPR_SCHED_TIMES = 16,
+
+    /* Dump speculative status of the expression.  */
+    DUMP_EXPR_SPEC_DONE_DS = 32,
+
+    /* Dump the basic block number which originated this expression.  */
+    DUMP_EXPR_ORIG_BB = 64,
+
+    /* Dump expression's usefulness.  */
+    DUMP_EXPR_USEFULNESS = 128,
+
+    /* Dump all of the above.  */
+    DUMP_EXPR_ALL = (DUMP_EXPR_VINSN | DUMP_EXPR_SPEC | DUMP_EXPR_PRIORITY
+                    | DUMP_EXPR_SCHED_TIMES | DUMP_EXPR_SPEC_DONE_DS
+                    | DUMP_EXPR_ORIG_BB | DUMP_EXPR_USEFULNESS)
+  };
+
+extern void dump_expr_1 (expr_t, int);
+extern void dump_expr (expr_t);
+extern void debug_expr (expr_t);
+
+/* A enumeration for dumping flags of an insn.  The difference from 
+   dump_insn_rtx_def is that these fields are for insns in stream only.  */
+enum dump_insn_def
+{
+  /* Dump expression of this insn.  */
+  DUMP_INSN_EXPR = 2,
+
+  /* Dump insn's seqno.  */
+  DUMP_INSN_SEQNO = 4,
+
+  /* Dump the cycle on which insn was scheduled.  */
+  DUMP_INSN_SCHED_CYCLE = 8,
+
+  /* Dump insn's UID.  */
+  DUMP_INSN_UID = 16,
+
+  /* Dump insn's pattern.  */
+  DUMP_INSN_PATTERN = 32,
+
+  /* Dump insn's basic block number.  */
+  DUMP_INSN_BBN = 64,
+
+  /* Dump all of the above.  */
+  DUMP_INSN_ALL = (DUMP_INSN_EXPR | DUMP_INSN_SEQNO | DUMP_INSN_BBN
+                  | DUMP_INSN_SCHED_CYCLE | DUMP_INSN_UID | DUMP_INSN_PATTERN)
+};
+
+extern void dump_insn_1 (insn_t, int);
+extern void dump_insn (insn_t);
+extern void debug_insn (insn_t);
+
+extern void sel_prepare_string_for_dot_label (char *);
+
+/* When this flag is on, we are dumping to the .dot file.
+   When it is off, we are dumping to log.  */
+extern bool sched_dump_to_dot_p;
+
+/* This macro acts like printf but dumps information to the .dot file.  
+   Used when dumping control flow.  */
+#define sel_print_to_dot(...)                           \
+  do {                                                  \
+    int __j = 1 + 2 * snprintf (NULL, 0, __VA_ARGS__);  \
+    char *__s = XALLOCAVEC (char, __j);                 \
+    snprintf (__s, __j, __VA_ARGS__);                   \
+    sel_prepare_string_for_dot_label (__s);             \
+    fprintf (sched_dump, "%s", __s);                    \
+  } while (0)
+
+/* This macro acts like printf but dumps to the sched_dump file.  */
+#define sel_print(...)                                 \
+  do {                                                 \
+    if (sched_dump_to_dot_p)                            \
+      sel_print_to_dot (__VA_ARGS__);                   \
+    else                                                \
+      fprintf (sched_dump, __VA_ARGS__);                \
+  } while (0)
+\f
+
+/* Functions from sel-sched-dump.c.  */
+extern const char * sel_print_insn (const_rtx, int);
+extern void free_sel_dump_data (void);
+
+extern void block_start (void);
+extern void block_finish (void);
+extern int get_print_blocks_num (void);
+extern void line_start (void);
+extern void line_finish (void);
+
+extern void sel_print_rtl (rtx x);
+extern void dump_insn_1 (insn_t, int);
+extern void dump_insn (insn_t);
+extern void dump_insn_vector (rtx_vec_t);
+extern void dump_expr (expr_t);
+extern void dump_used_regs (bitmap);
+extern void dump_av_set (av_set_t);
+extern void dump_lv_set (regset);
+extern void dump_blist (blist_t);
+extern void dump_flist (flist_t);
+extern void dump_hard_reg_set (const char *, HARD_REG_SET);
+extern void sel_debug_cfg_1 (int);
+extern void sel_debug_cfg (void);
+extern void setup_dump_cfg_params (void);
+
+/* Debug functions.  */
+extern void debug_expr (expr_t);
+extern void debug_av_set (av_set_t);
+extern void debug_lv_set (regset);
+extern void debug_ilist (ilist_t);
+extern void debug_blist (blist_t);
+extern void debug_insn_vector (rtx_vec_t);
+extern void debug_hard_reg_set (HARD_REG_SET);
+extern rtx debug_mem_addr_value (rtx);
+#endif
diff --git a/gcc/sel-sched-ir.c b/gcc/sel-sched-ir.c
new file mode 100644 (file)
index 0000000..856fb42
--- /dev/null
@@ -0,0 +1,6049 @@
+/* Instruction scheduling pass.  Selective scheduler and pipeliner.
+   Copyright (C) 2006, 2007, 2008 Free Software Foundation, Inc.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free
+Software Foundation; either version 3, or (at your option) any later
+version.
+
+GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or
+FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3.  If not see
+<http://www.gnu.org/licenses/>.  */
+
+#include "config.h"
+#include "system.h"
+#include "coretypes.h"
+#include "tm.h"
+#include "toplev.h"
+#include "rtl.h"
+#include "tm_p.h"
+#include "hard-reg-set.h"
+#include "regs.h"
+#include "function.h"
+#include "flags.h"
+#include "insn-config.h"
+#include "insn-attr.h"
+#include "except.h"
+#include "toplev.h"
+#include "recog.h"
+#include "params.h"
+#include "target.h"
+#include "timevar.h"
+#include "tree-pass.h"
+#include "sched-int.h"
+#include "ggc.h"
+#include "tree.h"
+#include "vec.h"
+#include "langhooks.h"
+#include "rtlhooks-def.h"
+
+#ifdef INSN_SCHEDULING
+#include "sel-sched-ir.h"
+/* We don't have to use it except for sel_print_insn.  */
+#include "sel-sched-dump.h"
+
+/* A vector holding bb info for whole scheduling pass.  */
+VEC(sel_global_bb_info_def, heap) *sel_global_bb_info = NULL;
+
+/* A vector holding bb info.  */
+VEC(sel_region_bb_info_def, heap) *sel_region_bb_info = NULL;
+
+/* A pool for allocating all lists.  */
+alloc_pool sched_lists_pool;
+
+/* This contains information about successors for compute_av_set.  */
+struct succs_info current_succs;
+
+/* Data structure to describe interaction with the generic scheduler utils.  */
+static struct common_sched_info_def sel_common_sched_info;
+
+/* The loop nest being pipelined.  */
+struct loop *current_loop_nest;
+
+/* LOOP_NESTS is a vector containing the corresponding loop nest for
+   each region.  */
+static VEC(loop_p, heap) *loop_nests = NULL;
+
+/* Saves blocks already in loop regions, indexed by bb->index.  */
+static sbitmap bbs_in_loop_rgns = NULL;
+
+/* CFG hooks that are saved before changing create_basic_block hook.  */
+static struct cfg_hooks orig_cfg_hooks;
+\f
+
+/* Array containing reverse topological index of function basic blocks,
+   indexed by BB->INDEX.  */
+static int *rev_top_order_index = NULL;
+
+/* Length of the above array.  */
+static int rev_top_order_index_len = -1;
+
+/* A regset pool structure.  */
+static struct
+{
+  /* The stack to which regsets are returned.  */
+  regset *v;
+
+  /* Its pointer.  */
+  int n;
+
+  /* Its size.  */
+  int s;
+
+  /* In VV we save all generated regsets so that, when destructing the
+     pool, we can compare it with V and check that every regset was returned
+     back to pool.  */
+  regset *vv;
+
+  /* The pointer of VV stack.  */
+  int nn;
+
+  /* Its size.  */
+  int ss;
+
+  /* The difference between allocated and returned regsets.  */
+  int diff;
+} regset_pool = { NULL, 0, 0, NULL, 0, 0, 0 };
+
+/* This represents the nop pool.  */
+static struct
+{
+  /* The vector which holds previously emitted nops.  */
+  insn_t *v;
+
+  /* Its pointer.  */
+  int n;
+
+  /* Its size.  */
+  int s;  
+} nop_pool = { NULL, 0, 0 };
+
+/* The pool for basic block notes.  */
+static rtx_vec_t bb_note_pool;
+
+/* A NOP pattern used to emit placeholder insns.  */
+rtx nop_pattern = NULL_RTX;
+/* A special instruction that resides in EXIT_BLOCK.
+   EXIT_INSN is successor of the insns that lead to EXIT_BLOCK.  */
+rtx exit_insn = NULL_RTX;
+
+/* TRUE if while scheduling current region, which is loop, its preheader 
+   was removed.  */
+bool preheader_removed = false;
+\f
+
+/* Forward static declarations.  */
+static void fence_clear (fence_t);
+
+static void deps_init_id (idata_t, insn_t, bool);
+static void init_id_from_df (idata_t, insn_t, bool);
+static expr_t set_insn_init (expr_t, vinsn_t, int);
+
+static void cfg_preds (basic_block, insn_t **, int *);
+static void prepare_insn_expr (insn_t, int);
+static void free_history_vect (VEC (expr_history_def, heap) **);
+
+static void move_bb_info (basic_block, basic_block);
+static void remove_empty_bb (basic_block, bool);
+static void sel_remove_loop_preheader (void);
+
+static bool insn_is_the_only_one_in_bb_p (insn_t);
+static void create_initial_data_sets (basic_block);
+
+static void invalidate_av_set (basic_block);
+static void extend_insn_data (void);
+static void sel_init_new_insn (insn_t, int);
+static void finish_insns (void);
+\f
+/* Various list functions.  */
+
+/* Copy an instruction list L.  */
+ilist_t
+ilist_copy (ilist_t l)
+{
+  ilist_t head = NULL, *tailp = &head;
+
+  while (l)
+    {
+      ilist_add (tailp, ILIST_INSN (l));
+      tailp = &ILIST_NEXT (*tailp);
+      l = ILIST_NEXT (l);
+    }
+
+  return head;
+}
+
+/* Invert an instruction list L.  */
+ilist_t
+ilist_invert (ilist_t l)
+{
+  ilist_t res = NULL;
+
+  while (l)
+    {
+      ilist_add (&res, ILIST_INSN (l));
+      l = ILIST_NEXT (l);
+    }
+
+  return res;
+}
+
+/* Add a new boundary to the LP list with parameters TO, PTR, and DC.  */
+void
+blist_add (blist_t *lp, insn_t to, ilist_t ptr, deps_t dc)
+{
+  bnd_t bnd;
+
+  _list_add (lp);
+  bnd = BLIST_BND (*lp);
+
+  BND_TO (bnd) = to;
+  BND_PTR (bnd) = ptr;
+  BND_AV (bnd) = NULL;
+  BND_AV1 (bnd) = NULL;
+  BND_DC (bnd) = dc;
+}
+
+/* Remove the list note pointed to by LP.  */
+void
+blist_remove (blist_t *lp)
+{
+  bnd_t b = BLIST_BND (*lp);
+
+  av_set_clear (&BND_AV (b));
+  av_set_clear (&BND_AV1 (b));
+  ilist_clear (&BND_PTR (b));
+
+  _list_remove (lp);
+}
+
+/* Init a fence tail L.  */
+void
+flist_tail_init (flist_tail_t l)
+{
+  FLIST_TAIL_HEAD (l) = NULL;
+  FLIST_TAIL_TAILP (l) = &FLIST_TAIL_HEAD (l);
+}
+
+/* Try to find fence corresponding to INSN in L.  */
+fence_t
+flist_lookup (flist_t l, insn_t insn)
+{
+  while (l)
+    {
+      if (FENCE_INSN (FLIST_FENCE (l)) == insn)
+       return FLIST_FENCE (l);
+
+      l = FLIST_NEXT (l);
+    }
+
+  return NULL;
+}
+
+/* Init the fields of F before running fill_insns.  */
+static void
+init_fence_for_scheduling (fence_t f)
+{
+  FENCE_BNDS (f) = NULL;
+  FENCE_PROCESSED_P (f) = false;
+  FENCE_SCHEDULED_P (f) = false;
+}
+
+/* Add new fence consisting of INSN and STATE to the list pointed to by LP.  */
+static void
+flist_add (flist_t *lp, insn_t insn, state_t state, deps_t dc, void *tc, 
+           insn_t last_scheduled_insn, VEC(rtx,gc) *executing_insns, 
+           int *ready_ticks, int ready_ticks_size, insn_t sched_next, 
+           int cycle, int cycle_issued_insns, 
+           bool starts_cycle_p, bool after_stall_p)
+{
+  fence_t f;
+
+  _list_add (lp);
+  f = FLIST_FENCE (*lp);
+
+  FENCE_INSN (f) = insn;
+
+  gcc_assert (state != NULL);
+  FENCE_STATE (f) = state;
+
+  FENCE_CYCLE (f) = cycle;
+  FENCE_ISSUED_INSNS (f) = cycle_issued_insns;
+  FENCE_STARTS_CYCLE_P (f) = starts_cycle_p;
+  FENCE_AFTER_STALL_P (f) = after_stall_p;
+
+  gcc_assert (dc != NULL);
+  FENCE_DC (f) = dc;
+
+  gcc_assert (tc != NULL || targetm.sched.alloc_sched_context == NULL);
+  FENCE_TC (f) = tc;
+
+  FENCE_LAST_SCHEDULED_INSN (f) = last_scheduled_insn;
+  FENCE_EXECUTING_INSNS (f) = executing_insns;
+  FENCE_READY_TICKS (f) = ready_ticks;
+  FENCE_READY_TICKS_SIZE (f) = ready_ticks_size;
+  FENCE_SCHED_NEXT (f) = sched_next;
+
+  init_fence_for_scheduling (f);
+}
+
+/* Remove the head node of the list pointed to by LP.  */
+static void
+flist_remove (flist_t *lp)
+{
+  if (FENCE_INSN (FLIST_FENCE (*lp)))
+    fence_clear (FLIST_FENCE (*lp));
+  _list_remove (lp);
+}
+
+/* Clear the fence list pointed to by LP.  */
+void
+flist_clear (flist_t *lp)
+{
+  while (*lp)
+    flist_remove (lp);
+}
+
+/* Add ORIGINAL_INSN the def list DL honoring CROSSES_CALL.  */
+void
+def_list_add (def_list_t *dl, insn_t original_insn, bool crosses_call)
+{
+  def_t d;
+  
+  _list_add (dl);
+  d = DEF_LIST_DEF (*dl);
+
+  d->orig_insn = original_insn;
+  d->crosses_call = crosses_call;
+}
+\f
+
+/* Functions to work with target contexts.  */
+
+/* Bulk target context.  It is convenient for debugging purposes to ensure 
+   that there are no uninitialized (null) target contexts.  */
+static tc_t bulk_tc = (tc_t) 1;
+
+/* Target hooks wrappers.  In the future we can provide some default 
+   implementations for them.  */
+
+/* Allocate a store for the target context.  */
+static tc_t
+alloc_target_context (void)
+{
+  return (targetm.sched.alloc_sched_context
+         ? targetm.sched.alloc_sched_context () : bulk_tc);
+}
+
+/* Init target context TC.
+   If CLEAN_P is true, then make TC as it is beginning of the scheduler.
+   Overwise, copy current backend context to TC.  */
+static void
+init_target_context (tc_t tc, bool clean_p)
+{
+  if (targetm.sched.init_sched_context)
+    targetm.sched.init_sched_context (tc, clean_p);
+}
+
+/* Allocate and initialize a target context.  Meaning of CLEAN_P is the same as
+   int init_target_context ().  */
+tc_t
+create_target_context (bool clean_p)
+{
+  tc_t tc = alloc_target_context ();
+
+  init_target_context (tc, clean_p);
+  return tc;
+}
+
+/* Copy TC to the current backend context.  */
+void
+set_target_context (tc_t tc)
+{
+  if (targetm.sched.set_sched_context)
+    targetm.sched.set_sched_context (tc);
+}
+
+/* TC is about to be destroyed.  Free any internal data.  */
+static void
+clear_target_context (tc_t tc)
+{
+  if (targetm.sched.clear_sched_context)
+    targetm.sched.clear_sched_context (tc);
+}
+
+/*  Clear and free it.  */
+static void
+delete_target_context (tc_t tc)
+{
+  clear_target_context (tc);
+
+  if (targetm.sched.free_sched_context)
+    targetm.sched.free_sched_context (tc);
+}
+
+/* Make a copy of FROM in TO.
+   NB: May be this should be a hook.  */
+static void
+copy_target_context (tc_t to, tc_t from)
+{
+  tc_t tmp = create_target_context (false);
+
+  set_target_context (from);
+  init_target_context (to, false);
+
+  set_target_context (tmp);
+  delete_target_context (tmp);
+}
+
+/* Create a copy of TC.  */
+static tc_t
+create_copy_of_target_context (tc_t tc)
+{
+  tc_t copy = alloc_target_context ();
+
+  copy_target_context (copy, tc);
+
+  return copy;
+}
+
+/* Clear TC and initialize it according to CLEAN_P.  The meaning of CLEAN_P
+   is the same as in init_target_context ().  */
+void
+reset_target_context (tc_t tc, bool clean_p)
+{
+  clear_target_context (tc);
+  init_target_context (tc, clean_p);
+}
+\f
+/* Functions to work with dependence contexts. 
+   Dc (aka deps context, aka deps_t, aka struct deps *) is short for dependence
+   context.  It accumulates information about processed insns to decide if
+   current insn is dependent on the processed ones.  */
+
+/* Make a copy of FROM in TO.  */
+static void
+copy_deps_context (deps_t to, deps_t from)
+{
+  init_deps (to);
+  deps_join (to, from);
+}
+
+/* Allocate store for dep context.  */
+static deps_t
+alloc_deps_context (void)
+{
+  return XNEW (struct deps);
+}
+
+/* Allocate and initialize dep context.  */
+static deps_t
+create_deps_context (void)
+{
+  deps_t dc = alloc_deps_context ();
+
+  init_deps (dc);
+  return dc;
+}
+
+/* Create a copy of FROM.  */
+static deps_t
+create_copy_of_deps_context (deps_t from)
+{
+  deps_t to = alloc_deps_context ();
+
+  copy_deps_context (to, from);
+  return to;
+}
+
+/* Clean up internal data of DC.  */
+static void
+clear_deps_context (deps_t dc)
+{
+  free_deps (dc);
+}
+
+/* Clear and free DC.  */
+static void
+delete_deps_context (deps_t dc)
+{
+  clear_deps_context (dc);
+  free (dc);
+}
+
+/* Clear and init DC.  */
+static void
+reset_deps_context (deps_t dc)
+{
+  clear_deps_context (dc);
+  init_deps (dc);
+}
+
+/* This structure describes the dependence analysis hooks for advancing 
+   dependence context.  */
+static struct sched_deps_info_def advance_deps_context_sched_deps_info =
+  {
+    NULL,
+
+    NULL, /* start_insn */
+    NULL, /* finish_insn */
+    NULL, /* start_lhs */
+    NULL, /* finish_lhs */
+    NULL, /* start_rhs */
+    NULL, /* finish_rhs */
+    haifa_note_reg_set,
+    haifa_note_reg_clobber,
+    haifa_note_reg_use,
+    NULL, /* note_mem_dep */
+    NULL, /* note_dep */
+
+    0, 0, 0
+  };
+
+/* Process INSN and add its impact on DC.  */
+void
+advance_deps_context (deps_t dc, insn_t insn)
+{
+  sched_deps_info = &advance_deps_context_sched_deps_info;
+  deps_analyze_insn (dc, insn);
+}
+\f
+
+/* Functions to work with DFA states.  */
+
+/* Allocate store for a DFA state.  */
+static state_t
+state_alloc (void)
+{
+  return xmalloc (dfa_state_size);
+}
+
+/* Allocate and initialize DFA state.  */
+static state_t
+state_create (void)
+{
+  state_t state = state_alloc ();
+
+  state_reset (state);
+  advance_state (state);
+  return state;
+}
+
+/* Free DFA state.  */
+static void
+state_free (state_t state)
+{
+  free (state);
+}
+
+/* Make a copy of FROM in TO.  */
+static void
+state_copy (state_t to, state_t from)
+{
+  memcpy (to, from, dfa_state_size);
+}
+
+/* Create a copy of FROM.  */
+static state_t
+state_create_copy (state_t from)
+{
+  state_t to = state_alloc ();
+
+  state_copy (to, from);
+  return to;
+}
+\f
+
+/* Functions to work with fences.  */
+
+/* Clear the fence.  */
+static void
+fence_clear (fence_t f)
+{
+  state_t s = FENCE_STATE (f);
+  deps_t dc = FENCE_DC (f);
+  void *tc = FENCE_TC (f);
+
+  ilist_clear (&FENCE_BNDS (f));
+
+  gcc_assert ((s != NULL && dc != NULL && tc != NULL)
+             || (s == NULL && dc == NULL && tc == NULL));
+
+  if (s != NULL)
+    free (s);
+
+  if (dc != NULL)
+    delete_deps_context (dc);
+
+  if (tc != NULL)
+    delete_target_context (tc);
+  VEC_free (rtx, gc, FENCE_EXECUTING_INSNS (f));
+  free (FENCE_READY_TICKS (f));
+  FENCE_READY_TICKS (f) = NULL;
+}
+
+/* Init a list of fences with successors of OLD_FENCE.  */
+void
+init_fences (insn_t old_fence)
+{
+  insn_t succ;
+  succ_iterator si;
+  bool first = true;
+  int ready_ticks_size = get_max_uid () + 1;
+      
+  FOR_EACH_SUCC_1 (succ, si, old_fence, 
+                   SUCCS_NORMAL | SUCCS_SKIP_TO_LOOP_EXITS)
+    {
+      
+      if (first)
+        first = false;
+      else
+        gcc_assert (flag_sel_sched_pipelining_outer_loops);
+
+      flist_add (&fences, succ,
+                state_create (),
+                create_deps_context () /* dc */,
+                create_target_context (true) /* tc */,
+                NULL_RTX /* last_scheduled_insn */, 
+                 NULL, /* executing_insns */
+                 XCNEWVEC (int, ready_ticks_size), /* ready_ticks */
+                 ready_ticks_size,
+                 NULL_RTX /* sched_next */,
+                1 /* cycle */, 0 /* cycle_issued_insns */, 
+                1 /* starts_cycle_p */, 0 /* after_stall_p */);  
+    }
+}
+
+/* Merges two fences (filling fields of fence F with resulting values) by
+   following rules: 1) state, target context and last scheduled insn are
+   propagated from fallthrough edge if it is available; 
+   2) deps context and cycle is propagated from more probable edge;
+   3) all other fields are set to corresponding constant values.  
+
+   INSN, STATE, DC, TC, LAST_SCHEDULED_INSN, EXECUTING_INSNS, 
+   READY_TICKS, READY_TICKS_SIZE, SCHED_NEXT, CYCLE and AFTER_STALL_P
+   are the corresponding fields of the second fence.  */
+static void
+merge_fences (fence_t f, insn_t insn,
+             state_t state, deps_t dc, void *tc, 
+              rtx last_scheduled_insn, VEC(rtx, gc) *executing_insns,
+              int *ready_ticks, int ready_ticks_size,
+             rtx sched_next, int cycle, bool after_stall_p)
+{
+  insn_t last_scheduled_insn_old = FENCE_LAST_SCHEDULED_INSN (f);
+
+  gcc_assert (sel_bb_head_p (FENCE_INSN (f))
+              && !sched_next && !FENCE_SCHED_NEXT (f));
+
+  /* Check if we can decide which path fences came.  
+     If we can't (or don't want to) - reset all.  */
+  if (last_scheduled_insn == NULL
+      || last_scheduled_insn_old == NULL
+      /* This is a case when INSN is reachable on several paths from 
+         one insn (this can happen when pipelining of outer loops is on and 
+         there are two edges: one going around of inner loop and the other - 
+         right through it; in such case just reset everything).  */
+      || last_scheduled_insn == last_scheduled_insn_old)
+    {
+      state_reset (FENCE_STATE (f));
+      state_free (state);
+  
+      reset_deps_context (FENCE_DC (f));
+      delete_deps_context (dc);
+  
+      reset_target_context (FENCE_TC (f), true);
+      delete_target_context (tc);
+
+      if (cycle > FENCE_CYCLE (f))
+        FENCE_CYCLE (f) = cycle;
+
+      FENCE_LAST_SCHEDULED_INSN (f) = NULL;
+      VEC_free (rtx, gc, executing_insns);
+      free (ready_ticks);
+      if (FENCE_EXECUTING_INSNS (f))
+        VEC_block_remove (rtx, FENCE_EXECUTING_INSNS (f), 0, 
+                          VEC_length (rtx, FENCE_EXECUTING_INSNS (f)));
+      if (FENCE_READY_TICKS (f))
+        memset (FENCE_READY_TICKS (f), 0, FENCE_READY_TICKS_SIZE (f));
+    }
+  else
+    {
+      edge edge_old = NULL, edge_new = NULL;
+      edge candidate;
+      succ_iterator si;
+      insn_t succ;
+    
+      /* Find fallthrough edge.  */
+      gcc_assert (BLOCK_FOR_INSN (insn)->prev_bb);
+      candidate = find_fallthru_edge (BLOCK_FOR_INSN (insn)->prev_bb);
+
+      if (!candidate
+          || (candidate->src != BLOCK_FOR_INSN (last_scheduled_insn)
+              && candidate->src != BLOCK_FOR_INSN (last_scheduled_insn_old)))
+        {
+          /* No fallthrough edge leading to basic block of INSN.  */
+          state_reset (FENCE_STATE (f));
+          state_free (state);
+  
+          reset_target_context (FENCE_TC (f), true);
+          delete_target_context (tc);
+  
+          FENCE_LAST_SCHEDULED_INSN (f) = NULL;
+        }
+      else
+        if (candidate->src == BLOCK_FOR_INSN (last_scheduled_insn))
+          {
+            /* Would be weird if same insn is successor of several fallthrough 
+               edges.  */
+            gcc_assert (BLOCK_FOR_INSN (insn)->prev_bb
+                        != BLOCK_FOR_INSN (last_scheduled_insn_old));
+
+            state_free (FENCE_STATE (f));
+            FENCE_STATE (f) = state;
+
+            delete_target_context (FENCE_TC (f));
+            FENCE_TC (f) = tc;
+
+            FENCE_LAST_SCHEDULED_INSN (f) = last_scheduled_insn;
+          }
+        else
+          {
+            /* Leave STATE, TC and LAST_SCHEDULED_INSN fields untouched.  */
+            state_free (state);
+            delete_target_context (tc);
+
+            gcc_assert (BLOCK_FOR_INSN (insn)->prev_bb
+                        != BLOCK_FOR_INSN (last_scheduled_insn));
+          }
+
+        /* Find edge of first predecessor (last_scheduled_insn_old->insn).  */
+        FOR_EACH_SUCC_1 (succ, si, last_scheduled_insn_old,
+                         SUCCS_NORMAL | SUCCS_SKIP_TO_LOOP_EXITS)
+          {
+            if (succ == insn)
+              {
+                /* No same successor allowed from several edges.  */
+                gcc_assert (!edge_old);
+                edge_old = si.e1;
+              }
+          }
+        /* Find edge of second predecessor (last_scheduled_insn->insn).  */
+        FOR_EACH_SUCC_1 (succ, si, last_scheduled_insn,
+                         SUCCS_NORMAL | SUCCS_SKIP_TO_LOOP_EXITS)
+          {
+            if (succ == insn)
+              {
+                /* No same successor allowed from several edges.  */
+                gcc_assert (!edge_new);
+                edge_new = si.e1;
+              }
+          }
+
+        /* Check if we can choose most probable predecessor.  */
+        if (edge_old == NULL || edge_new == NULL)
+          {
+            reset_deps_context (FENCE_DC (f));
+            delete_deps_context (dc);
+            VEC_free (rtx, gc, executing_insns);
+            free (ready_ticks);
+  
+            FENCE_CYCLE (f) = MAX (FENCE_CYCLE (f), cycle);
+            if (FENCE_EXECUTING_INSNS (f))
+              VEC_block_remove (rtx, FENCE_EXECUTING_INSNS (f), 0, 
+                                VEC_length (rtx, FENCE_EXECUTING_INSNS (f)));
+            if (FENCE_READY_TICKS (f))
+              memset (FENCE_READY_TICKS (f), 0, FENCE_READY_TICKS_SIZE (f));
+          }
+        else
+          if (edge_new->probability > edge_old->probability)
+            {
+              delete_deps_context (FENCE_DC (f));
+              FENCE_DC (f) = dc;
+              VEC_free (rtx, gc, FENCE_EXECUTING_INSNS (f));
+              FENCE_EXECUTING_INSNS (f) = executing_insns;
+              free (FENCE_READY_TICKS (f));
+              FENCE_READY_TICKS (f) = ready_ticks;
+              FENCE_READY_TICKS_SIZE (f) = ready_ticks_size;
+              FENCE_CYCLE (f) = cycle;
+            }
+          else
+            {
+              /* Leave DC and CYCLE untouched.  */
+              delete_deps_context (dc);
+              VEC_free (rtx, gc, executing_insns);
+              free (ready_ticks);
+            }
+    }
+
+  /* Fill remaining invariant fields.  */
+  if (after_stall_p)
+    FENCE_AFTER_STALL_P (f) = 1;
+
+  FENCE_ISSUED_INSNS (f) = 0;
+  FENCE_STARTS_CYCLE_P (f) = 1;
+  FENCE_SCHED_NEXT (f) = NULL;
+}
+
+/* Add a new fence to NEW_FENCES list, initializing it from all 
+   other parameters.  */
+static void
+add_to_fences (flist_tail_t new_fences, insn_t insn,
+               state_t state, deps_t dc, void *tc, rtx last_scheduled_insn, 
+               VEC(rtx, gc) *executing_insns, int *ready_ticks, 
+               int ready_ticks_size, rtx sched_next, int cycle, 
+               int cycle_issued_insns, bool starts_cycle_p, bool after_stall_p)
+{
+  fence_t f = flist_lookup (FLIST_TAIL_HEAD (new_fences), insn);
+
+  if (! f)
+    {
+      flist_add (FLIST_TAIL_TAILP (new_fences), insn, state, dc, tc,
+                last_scheduled_insn, executing_insns, ready_ticks, 
+                 ready_ticks_size, sched_next, cycle, cycle_issued_insns,
+                starts_cycle_p, after_stall_p);
+
+      FLIST_TAIL_TAILP (new_fences)
+       = &FLIST_NEXT (*FLIST_TAIL_TAILP (new_fences));
+    }
+  else
+    {
+      merge_fences (f, insn, state, dc, tc, last_scheduled_insn, 
+                    executing_insns, ready_ticks, ready_ticks_size, 
+                    sched_next, cycle, after_stall_p);
+    }
+}
+
+/* Move the first fence in the OLD_FENCES list to NEW_FENCES.  */
+void
+move_fence_to_fences (flist_t old_fences, flist_tail_t new_fences)
+{
+  fence_t f, old;
+  flist_t *tailp = FLIST_TAIL_TAILP (new_fences);
+
+  old = FLIST_FENCE (old_fences);
+  f = flist_lookup (FLIST_TAIL_HEAD (new_fences), 
+                    FENCE_INSN (FLIST_FENCE (old_fences)));
+  if (f)
+    {
+      merge_fences (f, old->insn, old->state, old->dc, old->tc,
+                    old->last_scheduled_insn, old->executing_insns,
+                    old->ready_ticks, old->ready_ticks_size,
+                    old->sched_next, old->cycle, 
+                    old->after_stall_p);
+    }
+  else
+    {
+      _list_add (tailp);
+      FLIST_TAIL_TAILP (new_fences) = &FLIST_NEXT (*tailp);
+      *FLIST_FENCE (*tailp) = *old;
+      init_fence_for_scheduling (FLIST_FENCE (*tailp));
+    }
+  FENCE_INSN (old) = NULL;
+}
+
+/* Add a new fence to NEW_FENCES list and initialize most of its data 
+   as a clean one.  */
+void
+add_clean_fence_to_fences (flist_tail_t new_fences, insn_t succ, fence_t fence)
+{
+  int ready_ticks_size = get_max_uid () + 1;
+  
+  add_to_fences (new_fences,
+                 succ, state_create (), create_deps_context (),
+                 create_target_context (true),
+                 NULL_RTX, NULL, 
+                 XCNEWVEC (int, ready_ticks_size), ready_ticks_size,
+                 NULL_RTX, FENCE_CYCLE (fence) + 1,
+                 0, 1, FENCE_AFTER_STALL_P (fence));
+}
+
+/* Add a new fence to NEW_FENCES list and initialize all of its data 
+   from FENCE and SUCC.  */
+void
+add_dirty_fence_to_fences (flist_tail_t new_fences, insn_t succ, fence_t fence)
+{
+  int * new_ready_ticks 
+    = XNEWVEC (int, FENCE_READY_TICKS_SIZE (fence));
+  
+  memcpy (new_ready_ticks, FENCE_READY_TICKS (fence),
+          FENCE_READY_TICKS_SIZE (fence) * sizeof (int));
+  add_to_fences (new_fences,
+                 succ, state_create_copy (FENCE_STATE (fence)),
+                 create_copy_of_deps_context (FENCE_DC (fence)),
+                 create_copy_of_target_context (FENCE_TC (fence)),
+                 FENCE_LAST_SCHEDULED_INSN (fence), 
+                 VEC_copy (rtx, gc, FENCE_EXECUTING_INSNS (fence)),
+                 new_ready_ticks,
+                 FENCE_READY_TICKS_SIZE (fence),
+                 FENCE_SCHED_NEXT (fence),
+                 FENCE_CYCLE (fence),
+                 FENCE_ISSUED_INSNS (fence),
+                 FENCE_STARTS_CYCLE_P (fence),
+                 FENCE_AFTER_STALL_P (fence));
+}
+\f
+
+/* Functions to work with regset and nop pools.  */
+
+/* Returns the new regset from pool.  It might have some of the bits set
+   from the previous usage.  */
+regset
+get_regset_from_pool (void)
+{
+  regset rs;
+
+  if (regset_pool.n != 0)
+    rs = regset_pool.v[--regset_pool.n];
+  else
+    /* We need to create the regset.  */
+    {
+      rs = ALLOC_REG_SET (&reg_obstack);
+
+      if (regset_pool.nn == regset_pool.ss)
+       regset_pool.vv = XRESIZEVEC (regset, regset_pool.vv,
+                                     (regset_pool.ss = 2 * regset_pool.ss + 1));
+      regset_pool.vv[regset_pool.nn++] = rs;
+    }
+
+  regset_pool.diff++;
+
+  return rs;
+}
+
+/* Same as above, but returns the empty regset.  */
+regset
+get_clear_regset_from_pool (void)
+{
+  regset rs = get_regset_from_pool ();
+
+  CLEAR_REG_SET (rs);
+  return rs;
+}
+
+/* Return regset RS to the pool for future use.  */
+void
+return_regset_to_pool (regset rs)
+{
+  regset_pool.diff--;
+
+  if (regset_pool.n == regset_pool.s)
+    regset_pool.v = XRESIZEVEC (regset, regset_pool.v,
+                                (regset_pool.s = 2 * regset_pool.s + 1));
+  regset_pool.v[regset_pool.n++] = rs;
+}
+
+/* This is used as a qsort callback for sorting regset pool stacks.
+   X and XX are addresses of two regsets.  They are never equal.  */
+static int
+cmp_v_in_regset_pool (const void *x, const void *xx)
+{
+  return *((const regset *) x) - *((const regset *) xx);
+}
+
+/*  Free the regset pool possibly checking for memory leaks.  */
+void
+free_regset_pool (void)
+{
+#ifdef ENABLE_CHECKING
+  {
+    regset *v = regset_pool.v;
+    int i = 0;
+    int n = regset_pool.n;
+    
+    regset *vv = regset_pool.vv;
+    int ii = 0;
+    int nn = regset_pool.nn;
+    
+    int diff = 0;
+    
+    gcc_assert (n <= nn);
+    
+    /* Sort both vectors so it will be possible to compare them.  */
+    qsort (v, n, sizeof (*v), cmp_v_in_regset_pool);
+    qsort (vv, nn, sizeof (*vv), cmp_v_in_regset_pool);
+    
+    while (ii < nn)
+      {
+        if (v[i] == vv[ii])
+          i++;
+        else
+          /* VV[II] was lost.  */
+          diff++;
+        
+        ii++;
+      }
+    
+    gcc_assert (diff == regset_pool.diff);
+  }
+#endif
+  
+  /* If not true - we have a memory leak.  */
+  gcc_assert (regset_pool.diff == 0);
+  
+  while (regset_pool.n)
+    {
+      --regset_pool.n;
+      FREE_REG_SET (regset_pool.v[regset_pool.n]);
+    }
+
+  free (regset_pool.v);
+  regset_pool.v = NULL;
+  regset_pool.s = 0;
+  
+  free (regset_pool.vv);
+  regset_pool.vv = NULL;
+  regset_pool.nn = 0;
+  regset_pool.ss = 0;
+
+  regset_pool.diff = 0;
+}
+\f
+
+/* Functions to work with nop pools.  NOP insns are used as temporary 
+   placeholders of the insns being scheduled to allow correct update of 
+   the data sets.  When update is finished, NOPs are deleted.  */
+
+/* A vinsn that is used to represent a nop.  This vinsn is shared among all
+   nops sel-sched generates.  */
+static vinsn_t nop_vinsn = NULL;
+
+/* Emit a nop before INSN, taking it from pool.  */
+insn_t
+get_nop_from_pool (insn_t insn)
+{
+  insn_t nop;
+  bool old_p = nop_pool.n != 0;
+  int flags;
+
+  if (old_p)
+    nop = nop_pool.v[--nop_pool.n];
+  else
+    nop = nop_pattern;
+
+  nop = emit_insn_before (nop, insn);
+
+  if (old_p)
+    flags = INSN_INIT_TODO_SSID;
+  else
+    flags = INSN_INIT_TODO_LUID | INSN_INIT_TODO_SSID;
+
+  set_insn_init (INSN_EXPR (insn), nop_vinsn, INSN_SEQNO (insn));
+  sel_init_new_insn (nop, flags);
+
+  return nop;
+}
+
+/* Remove NOP from the instruction stream and return it to the pool.  */
+void
+return_nop_to_pool (insn_t nop)
+{
+  gcc_assert (INSN_IN_STREAM_P (nop));
+  sel_remove_insn (nop, false, true);
+
+  if (nop_pool.n == nop_pool.s)
+    nop_pool.v = XRESIZEVEC (rtx, nop_pool.v, 
+                             (nop_pool.s = 2 * nop_pool.s + 1));
+  nop_pool.v[nop_pool.n++] = nop;
+}
+
+/* Free the nop pool.  */
+void
+free_nop_pool (void)
+{
+  nop_pool.n = 0;
+  nop_pool.s = 0;
+  free (nop_pool.v);
+  nop_pool.v = NULL;
+}
+\f
+
+/* Skip unspec to support ia64 speculation. Called from rtx_equal_p_cb.  
+   The callback is given two rtxes XX and YY and writes the new rtxes
+   to NX and NY in case some needs to be skipped.  */
+static int
+skip_unspecs_callback (const_rtx *xx, const_rtx *yy, rtx *nx, rtx* ny)
+{
+  const_rtx x = *xx;
+  const_rtx y = *yy;
+  
+  if (GET_CODE (x) == UNSPEC
+      && (targetm.sched.skip_rtx_p == NULL
+          || targetm.sched.skip_rtx_p (x)))
+    {
+      *nx = XVECEXP (x, 0, 0);
+      *ny = CONST_CAST_RTX (y);
+      return 1;
+    }
+  
+  if (GET_CODE (y) == UNSPEC
+      && (targetm.sched.skip_rtx_p == NULL
+          || targetm.sched.skip_rtx_p (y)))
+    {
+      *nx = CONST_CAST_RTX (x);
+      *ny = XVECEXP (y, 0, 0);
+      return 1;
+    }
+  
+  return 0;
+}
+
+/* Callback, called from hash_rtx_cb.  Helps to hash UNSPEC rtx X in a correct way 
+   to support ia64 speculation.  When changes are needed, new rtx X and new mode
+   NMODE are written, and the callback returns true.  */
+static int
+hash_with_unspec_callback (const_rtx x, enum machine_mode mode ATTRIBUTE_UNUSED,
+                           rtx *nx, enum machine_mode* nmode)
+{
+  if (GET_CODE (x) == UNSPEC 
+      && targetm.sched.skip_rtx_p
+      && targetm.sched.skip_rtx_p (x))
+    {
+      *nx = XVECEXP (x, 0 ,0);
+      *nmode = 0;
+      return 1;
+    }
+  
+  return 0;
+}
+
+/* Returns LHS and RHS are ok to be scheduled separately.  */
+static bool
+lhs_and_rhs_separable_p (rtx lhs, rtx rhs)
+{
+  if (lhs == NULL || rhs == NULL)
+    return false;
+
+  /* Do not schedule CONST, CONST_INT and CONST_DOUBLE etc as rhs: no point 
+     to use reg, if const can be used.  Moreover, scheduling const as rhs may 
+     lead to mode mismatch cause consts don't have modes but they could be 
+     merged from branches where the same const used in different modes.  */
+  if (CONSTANT_P (rhs))
+    return false;
+
+  /* ??? Do not rename predicate registers to avoid ICEs in bundling.  */
+  if (COMPARISON_P (rhs))
+      return false;
+
+  /* Do not allow single REG to be an rhs.  */
+  if (REG_P (rhs))
+    return false;
+
+  /* See comment at find_used_regs_1 (*1) for explanation of this 
+     restriction.  */
+  /* FIXME: remove this later.  */
+  if (MEM_P (lhs))
+    return false;
+
+  /* This will filter all tricky things like ZERO_EXTRACT etc.
+     For now we don't handle it.  */
+  if (!REG_P (lhs) && !MEM_P (lhs))
+    return false;
+
+  return true;
+}
+
+/* Initialize vinsn VI for INSN.  Only for use from vinsn_create ().  When 
+   FORCE_UNIQUE_P is true, the resulting vinsn will not be clonable.  This is 
+   used e.g. for insns from recovery blocks.  */
+static void
+vinsn_init (vinsn_t vi, insn_t insn, bool force_unique_p)
+{
+  hash_rtx_callback_function hrcf;
+  int insn_class;
+
+  VINSN_INSN_RTX (vi) = insn;
+  VINSN_COUNT (vi) = 0;
+  vi->cost = -1;
+  
+  if (DF_INSN_UID_SAFE_GET (INSN_UID (insn)) != NULL)
+    init_id_from_df (VINSN_ID (vi), insn, force_unique_p);
+  else
+    deps_init_id (VINSN_ID (vi), insn, force_unique_p);
+  
+  /* Hash vinsn depending on whether it is separable or not.  */
+  hrcf = targetm.sched.skip_rtx_p ? hash_with_unspec_callback : NULL;
+  if (VINSN_SEPARABLE_P (vi))
+    {
+      rtx rhs = VINSN_RHS (vi);
+
+      VINSN_HASH (vi) = hash_rtx_cb (rhs, GET_MODE (rhs),
+                                     NULL, NULL, false, hrcf);
+      VINSN_HASH_RTX (vi) = hash_rtx_cb (VINSN_PATTERN (vi),
+                                         VOIDmode, NULL, NULL,
+                                         false, hrcf);
+    }
+  else
+    {
+      VINSN_HASH (vi) = hash_rtx_cb (VINSN_PATTERN (vi), VOIDmode,
+                                     NULL, NULL, false, hrcf);
+      VINSN_HASH_RTX (vi) = VINSN_HASH (vi);
+    }
+    
+  insn_class = haifa_classify_insn (insn);
+  if (insn_class >= 2
+      && (!targetm.sched.get_insn_spec_ds
+          || ((targetm.sched.get_insn_spec_ds (insn) & BEGIN_CONTROL)
+              == 0)))
+    VINSN_MAY_TRAP_P (vi) = true;
+  else
+    VINSN_MAY_TRAP_P (vi) = false;
+}
+
+/* Indicate that VI has become the part of an rtx object.  */
+void
+vinsn_attach (vinsn_t vi)
+{
+  /* Assert that VI is not pending for deletion.  */
+  gcc_assert (VINSN_INSN_RTX (vi));
+
+  VINSN_COUNT (vi)++;
+}
+
+/* Create and init VI from the INSN.  Use UNIQUE_P for determining the correct 
+   VINSN_TYPE (VI).  */
+static vinsn_t
+vinsn_create (insn_t insn, bool force_unique_p)
+{
+  vinsn_t vi = XCNEW (struct vinsn_def);
+
+  vinsn_init (vi, insn, force_unique_p);
+  return vi;
+}
+
+/* Return a copy of VI.  When REATTACH_P is true, detach VI and attach
+   the copy.  */
+vinsn_t 
+vinsn_copy (vinsn_t vi, bool reattach_p)
+{
+  rtx copy;
+  bool unique = VINSN_UNIQUE_P (vi);
+  vinsn_t new_vi;
+  
+  copy = create_copy_of_insn_rtx (VINSN_INSN_RTX (vi));
+  new_vi = create_vinsn_from_insn_rtx (copy, unique);
+  if (reattach_p)
+    {
+      vinsn_detach (vi);
+      vinsn_attach (new_vi);
+    }
+
+  return new_vi;
+}
+
+/* Delete the VI vinsn and free its data.  */
+static void
+vinsn_delete (vinsn_t vi)
+{
+  gcc_assert (VINSN_COUNT (vi) == 0);
+
+  return_regset_to_pool (VINSN_REG_SETS (vi));
+  return_regset_to_pool (VINSN_REG_USES (vi));
+  return_regset_to_pool (VINSN_REG_CLOBBERS (vi));
+
+  free (vi);
+}
+
+/* Indicate that VI is no longer a part of some rtx object.  
+   Remove VI if it is no longer needed.  */
+void
+vinsn_detach (vinsn_t vi)
+{
+  gcc_assert (VINSN_COUNT (vi) > 0);
+
+  if (--VINSN_COUNT (vi) == 0)
+    vinsn_delete (vi);
+}
+
+/* Returns TRUE if VI is a branch.  */
+bool
+vinsn_cond_branch_p (vinsn_t vi)
+{
+  insn_t insn;
+
+  if (!VINSN_UNIQUE_P (vi))
+    return false;
+
+  insn = VINSN_INSN_RTX (vi);
+  if (BB_END (BLOCK_FOR_INSN (insn)) != insn)
+    return false;
+
+  return control_flow_insn_p (insn);
+}
+
+/* Return latency of INSN.  */
+static int
+sel_insn_rtx_cost (rtx insn)
+{
+  int cost;
+
+  /* A USE insn, or something else we don't need to
+     understand.  We can't pass these directly to
+     result_ready_cost or insn_default_latency because it will
+     trigger a fatal error for unrecognizable insns.  */
+  if (recog_memoized (insn) < 0)
+    cost = 0;
+  else
+    {
+      cost = insn_default_latency (insn);
+
+      if (cost < 0)
+       cost = 0;
+    }
+
+  return cost;
+}
+
+/* Return the cost of the VI.
+   !!! FIXME: Unify with haifa-sched.c: insn_cost ().  */
+int
+sel_vinsn_cost (vinsn_t vi)
+{
+  int cost = vi->cost;
+
+  if (cost < 0)
+    {
+      cost = sel_insn_rtx_cost (VINSN_INSN_RTX (vi));
+      vi->cost = cost;
+    }
+
+  return cost;
+}
+\f
+
+/* Functions for insn emitting.  */
+
+/* Emit new insn after AFTER based on PATTERN and initialize its data from
+   EXPR and SEQNO.  */
+insn_t
+sel_gen_insn_from_rtx_after (rtx pattern, expr_t expr, int seqno, insn_t after)
+{
+  insn_t new_insn;
+
+  gcc_assert (EXPR_TARGET_AVAILABLE (expr) == true);
+
+  new_insn = emit_insn_after (pattern, after);
+  set_insn_init (expr, NULL, seqno);
+  sel_init_new_insn (new_insn, INSN_INIT_TODO_LUID | INSN_INIT_TODO_SSID);
+
+  return new_insn;
+}
+
+/* Force newly generated vinsns to be unique.  */
+static bool init_insn_force_unique_p = false;
+
+/* Emit new speculation recovery insn after AFTER based on PATTERN and
+   initialize its data from EXPR and SEQNO.  */
+insn_t
+sel_gen_recovery_insn_from_rtx_after (rtx pattern, expr_t expr, int seqno,
+                                     insn_t after)
+{
+  insn_t insn;
+
+  gcc_assert (!init_insn_force_unique_p);
+
+  init_insn_force_unique_p = true;
+  insn = sel_gen_insn_from_rtx_after (pattern, expr, seqno, after);
+  CANT_MOVE (insn) = 1;
+  init_insn_force_unique_p = false;
+
+  return insn;
+}
+
+/* Emit new insn after AFTER based on EXPR and SEQNO.  If VINSN is not NULL,
+   take it as a new vinsn instead of EXPR's vinsn.  
+   We simplify insns later, after scheduling region in 
+   simplify_changed_insns.  */
+insn_t
+sel_gen_insn_from_expr_after (expr_t expr, vinsn_t vinsn, int seqno, 
+                              insn_t after)
+{
+  expr_t emit_expr;
+  insn_t insn;
+  int flags;
+  
+  emit_expr = set_insn_init (expr, vinsn ? vinsn : EXPR_VINSN (expr), 
+                             seqno);
+  insn = EXPR_INSN_RTX (emit_expr);
+  add_insn_after (insn, after, BLOCK_FOR_INSN (insn));          
+
+  flags = INSN_INIT_TODO_SSID;
+  if (INSN_LUID (insn) == 0)
+    flags |= INSN_INIT_TODO_LUID;
+  sel_init_new_insn (insn, flags);
+
+  return insn;
+}
+
+/* Move insn from EXPR after AFTER.  */
+insn_t
+sel_move_insn (expr_t expr, int seqno, insn_t after)
+{
+  insn_t insn = EXPR_INSN_RTX (expr);
+  basic_block bb = BLOCK_FOR_INSN (after);
+  insn_t next = NEXT_INSN (after);
+
+  /* Assert that in move_op we disconnected this insn properly.  */
+  gcc_assert (EXPR_VINSN (INSN_EXPR (insn)) != NULL);
+  PREV_INSN (insn) = after;
+  NEXT_INSN (insn) = next;
+
+  NEXT_INSN (after) = insn;
+  PREV_INSN (next) = insn;
+
+  /* Update links from insn to bb and vice versa.  */
+  df_insn_change_bb (insn, bb);
+  if (BB_END (bb) == after)
+    BB_END (bb) = insn;
+      
+  prepare_insn_expr (insn, seqno);
+  return insn;
+}
+
+\f
+/* Functions to work with right-hand sides.  */
+
+/* Search for a hash value determined by UID/NEW_VINSN in a sorted vector 
+   VECT and return true when found.  Use NEW_VINSN for comparison only when
+   COMPARE_VINSNS is true.  Write to INDP the index on which 
+   the search has stopped, such that inserting the new element at INDP will 
+   retain VECT's sort order.  */
+static bool
+find_in_history_vect_1 (VEC(expr_history_def, heap) *vect, 
+                        unsigned uid, vinsn_t new_vinsn, 
+                        bool compare_vinsns, int *indp)
+{
+  expr_history_def *arr;
+  int i, j, len = VEC_length (expr_history_def, vect);
+
+  if (len == 0)
+    {
+      *indp = 0;
+      return false;
+    }
+
+  arr = VEC_address (expr_history_def, vect);
+  i = 0, j = len - 1;
+
+  while (i <= j)
+    {
+      unsigned auid = arr[i].uid;
+      vinsn_t avinsn = arr[i].new_expr_vinsn; 
+
+      if (auid == uid
+          /* When undoing transformation on a bookkeeping copy, the new vinsn 
+             may not be exactly equal to the one that is saved in the vector. 
+             This is because the insn whose copy we're checking was possibly
+             substituted itself.  */
+          && (! compare_vinsns 
+              || vinsn_equal_p (avinsn, new_vinsn)))
+        {
+          *indp = i;
+          return true;
+        }
+      else if (auid > uid)
+        break;
+      i++;
+    }
+
+  *indp = i;
+  return false;
+}
+
+/* Search for a uid of INSN and NEW_VINSN in a sorted vector VECT.  Return 
+   the position found or -1, if no such value is in vector.  
+   Search also for UIDs of insn's originators, if ORIGINATORS_P is true.  */
+int
+find_in_history_vect (VEC(expr_history_def, heap) *vect, rtx insn, 
+                      vinsn_t new_vinsn, bool originators_p)
+{
+  int ind;
+
+  if (find_in_history_vect_1 (vect, INSN_UID (insn), new_vinsn, 
+                              false, &ind))
+    return ind;
+
+  if (INSN_ORIGINATORS (insn) && originators_p)
+    {
+      unsigned uid;
+      bitmap_iterator bi;
+
+      EXECUTE_IF_SET_IN_BITMAP (INSN_ORIGINATORS (insn), 0, uid, bi)
+        if (find_in_history_vect_1 (vect, uid, new_vinsn, false, &ind))
+          return ind;
+    }
+  
+  return -1;
+}
+
+/* Insert new element in a sorted history vector pointed to by PVECT, 
+   if it is not there already.  The element is searched using 
+   UID/NEW_EXPR_VINSN pair.  TYPE, OLD_EXPR_VINSN and SPEC_DS save
+   the history of a transformation.  */
+void
+insert_in_history_vect (VEC (expr_history_def, heap) **pvect,
+                        unsigned uid, enum local_trans_type type,
+                        vinsn_t old_expr_vinsn, vinsn_t new_expr_vinsn, 
+                        ds_t spec_ds)
+{
+  VEC(expr_history_def, heap) *vect = *pvect;
+  expr_history_def temp;
+  bool res;
+  int ind;
+
+  res = find_in_history_vect_1 (vect, uid, new_expr_vinsn, true, &ind);
+
+  if (res)
+    {
+      expr_history_def *phist = VEC_index (expr_history_def, vect, ind);
+
+      /* When merging, either old vinsns are the *same* or, if not, both 
+         old and new vinsns are different pointers.  In the latter case, 
+         though, new vinsns should be equal.  */
+      gcc_assert (phist->old_expr_vinsn == old_expr_vinsn
+                  || (phist->new_expr_vinsn != new_expr_vinsn 
+                      && (vinsn_equal_p 
+                          (phist->old_expr_vinsn, old_expr_vinsn))));
+
+      /* It is possible that speculation types of expressions that were 
+         propagated through different paths will be different here.  In this
+         case, merge the status to get the correct check later.  */
+      if (phist->spec_ds != spec_ds)
+        phist->spec_ds = ds_max_merge (phist->spec_ds, spec_ds);
+      return;
+    }
+      
+  temp.uid = uid;
+  temp.old_expr_vinsn = old_expr_vinsn;
+  temp.new_expr_vinsn = new_expr_vinsn; 
+  temp.spec_ds = spec_ds;
+  temp.type = type;
+
+  vinsn_attach (old_expr_vinsn);
+  vinsn_attach (new_expr_vinsn);
+  VEC_safe_insert (expr_history_def, heap, vect, ind, &temp);
+  *pvect = vect;
+}
+
+/* Free history vector PVECT.  */
+static void
+free_history_vect (VEC (expr_history_def, heap) **pvect)
+{
+  unsigned i;
+  expr_history_def *phist;
+
+  if (! *pvect)
+    return;
+  
+  for (i = 0; 
+       VEC_iterate (expr_history_def, *pvect, i, phist);
+       i++)
+    {
+      vinsn_detach (phist->old_expr_vinsn);
+      vinsn_detach (phist->new_expr_vinsn);
+    }
+  
+  VEC_free (expr_history_def, heap, *pvect);
+  *pvect = NULL;
+}
+
+
+/* Compare two vinsns as rhses if possible and as vinsns otherwise.  */
+bool
+vinsn_equal_p (vinsn_t x, vinsn_t y)
+{
+  rtx_equal_p_callback_function repcf;
+
+  if (x == y)
+    return true;
+
+  if (VINSN_TYPE (x) != VINSN_TYPE (y))
+    return false;
+
+  if (VINSN_HASH (x) != VINSN_HASH (y))
+    return false;
+
+  repcf = targetm.sched.skip_rtx_p ? skip_unspecs_callback : NULL;
+  if (VINSN_SEPARABLE_P (x)) 
+    {
+      /* Compare RHSes of VINSNs.  */
+      gcc_assert (VINSN_RHS (x));
+      gcc_assert (VINSN_RHS (y));
+
+      return rtx_equal_p_cb (VINSN_RHS (x), VINSN_RHS (y), repcf);
+    }
+
+  return rtx_equal_p_cb (VINSN_PATTERN (x), VINSN_PATTERN (y), repcf);
+}
+\f
+
+/* Functions for working with expressions.  */
+
+/* Initialize EXPR.  */
+static void
+init_expr (expr_t expr, vinsn_t vi, int spec, int use, int priority,
+          int sched_times, int orig_bb_index, ds_t spec_done_ds,
+          ds_t spec_to_check_ds, int orig_sched_cycle,
+          VEC(expr_history_def, heap) *history, bool target_available, 
+           bool was_substituted, bool was_renamed, bool needs_spec_check_p,
+           bool cant_move)
+{
+  vinsn_attach (vi);
+
+  EXPR_VINSN (expr) = vi;
+  EXPR_SPEC (expr) = spec;
+  EXPR_USEFULNESS (expr) = use;
+  EXPR_PRIORITY (expr) = priority;
+  EXPR_PRIORITY_ADJ (expr) = 0;
+  EXPR_SCHED_TIMES (expr) = sched_times;
+  EXPR_ORIG_BB_INDEX (expr) = orig_bb_index;
+  EXPR_ORIG_SCHED_CYCLE (expr) = orig_sched_cycle;
+  EXPR_SPEC_DONE_DS (expr) = spec_done_ds;
+  EXPR_SPEC_TO_CHECK_DS (expr) = spec_to_check_ds;
+
+  if (history)
+    EXPR_HISTORY_OF_CHANGES (expr) = history;
+  else
+    EXPR_HISTORY_OF_CHANGES (expr) = NULL;
+
+  EXPR_TARGET_AVAILABLE (expr) = target_available;
+  EXPR_WAS_SUBSTITUTED (expr) = was_substituted;
+  EXPR_WAS_RENAMED (expr) = was_renamed;
+  EXPR_NEEDS_SPEC_CHECK_P (expr) = needs_spec_check_p;
+  EXPR_CANT_MOVE (expr) = cant_move;
+}
+
+/* Make a copy of the expr FROM into the expr TO.  */
+void
+copy_expr (expr_t to, expr_t from)
+{
+  VEC(expr_history_def, heap) *temp = NULL;
+
+  if (EXPR_HISTORY_OF_CHANGES (from))
+    {
+      unsigned i;
+      expr_history_def *phist;
+
+      temp = VEC_copy (expr_history_def, heap, EXPR_HISTORY_OF_CHANGES (from));
+      for (i = 0; 
+           VEC_iterate (expr_history_def, temp, i, phist);
+           i++)
+        {
+          vinsn_attach (phist->old_expr_vinsn);
+          vinsn_attach (phist->new_expr_vinsn);
+        }
+    }
+
+  init_expr (to, EXPR_VINSN (from), EXPR_SPEC (from), 
+             EXPR_USEFULNESS (from), EXPR_PRIORITY (from),
+            EXPR_SCHED_TIMES (from), EXPR_ORIG_BB_INDEX (from),
+            EXPR_SPEC_DONE_DS (from), EXPR_SPEC_TO_CHECK_DS (from), 
+            EXPR_ORIG_SCHED_CYCLE (from), temp,
+             EXPR_TARGET_AVAILABLE (from), EXPR_WAS_SUBSTITUTED (from), 
+             EXPR_WAS_RENAMED (from), EXPR_NEEDS_SPEC_CHECK_P (from),
+             EXPR_CANT_MOVE (from));
+}
+
+/* Same, but the final expr will not ever be in av sets, so don't copy 
+   "uninteresting" data such as bitmap cache.  */
+void
+copy_expr_onside (expr_t to, expr_t from)
+{
+  init_expr (to, EXPR_VINSN (from), EXPR_SPEC (from), EXPR_USEFULNESS (from),
+            EXPR_PRIORITY (from), EXPR_SCHED_TIMES (from), 0,
+            EXPR_SPEC_DONE_DS (from), EXPR_SPEC_TO_CHECK_DS (from), 0, NULL,
+            EXPR_TARGET_AVAILABLE (from), EXPR_WAS_SUBSTITUTED (from),
+            EXPR_WAS_RENAMED (from), EXPR_NEEDS_SPEC_CHECK_P (from),
+             EXPR_CANT_MOVE (from));
+}
+
+/* Prepare the expr of INSN for scheduling.  Used when moving insn and when
+   initializing new insns.  */
+static void
+prepare_insn_expr (insn_t insn, int seqno)
+{
+  expr_t expr = INSN_EXPR (insn);
+  ds_t ds;
+  
+  INSN_SEQNO (insn) = seqno;
+  EXPR_ORIG_BB_INDEX (expr) = BLOCK_NUM (insn);
+  EXPR_SPEC (expr) = 0;
+  EXPR_ORIG_SCHED_CYCLE (expr) = 0;
+  EXPR_WAS_SUBSTITUTED (expr) = 0;
+  EXPR_WAS_RENAMED (expr) = 0;
+  EXPR_TARGET_AVAILABLE (expr) = 1;
+  INSN_LIVE_VALID_P (insn) = false;
+
+  /* ??? If this expression is speculative, make its dependence
+     as weak as possible.  We can filter this expression later
+     in process_spec_exprs, because we do not distinguish
+     between the status we got during compute_av_set and the
+     existing status.  To be fixed.  */
+  ds = EXPR_SPEC_DONE_DS (expr);
+  if (ds)
+    EXPR_SPEC_DONE_DS (expr) = ds_get_max_dep_weak (ds);
+
+  free_history_vect (&EXPR_HISTORY_OF_CHANGES (expr));
+}
+
+/* Update target_available bits when merging exprs TO and FROM.  SPLIT_POINT
+   is non-null when expressions are merged from different successors at 
+   a split point.  */
+static void
+update_target_availability (expr_t to, expr_t from, insn_t split_point)
+{
+  if (EXPR_TARGET_AVAILABLE (to) < 0  
+      || EXPR_TARGET_AVAILABLE (from) < 0)
+    EXPR_TARGET_AVAILABLE (to) = -1;
+  else
+    {
+      /* We try to detect the case when one of the expressions
+         can only be reached through another one.  In this case,
+         we can do better.  */
+      if (split_point == NULL)
+        {
+          int toind, fromind;
+
+          toind = EXPR_ORIG_BB_INDEX (to);
+          fromind = EXPR_ORIG_BB_INDEX (from);
+          
+          if (toind && toind == fromind)
+            /* Do nothing -- everything is done in 
+               merge_with_other_exprs.  */
+            ;
+          else
+            EXPR_TARGET_AVAILABLE (to) = -1;
+        }
+      else
+        EXPR_TARGET_AVAILABLE (to) &= EXPR_TARGET_AVAILABLE (from);
+    }
+}
+
+/* Update speculation bits when merging exprs TO and FROM.  SPLIT_POINT
+   is non-null when expressions are merged from different successors at 
+   a split point.  */
+static void
+update_speculative_bits (expr_t to, expr_t from, insn_t split_point)
+{
+  ds_t old_to_ds, old_from_ds;
+
+  old_to_ds = EXPR_SPEC_DONE_DS (to);
+  old_from_ds = EXPR_SPEC_DONE_DS (from);
+    
+  EXPR_SPEC_DONE_DS (to) = ds_max_merge (old_to_ds, old_from_ds);
+  EXPR_SPEC_TO_CHECK_DS (to) |= EXPR_SPEC_TO_CHECK_DS (from);
+  EXPR_NEEDS_SPEC_CHECK_P (to) |= EXPR_NEEDS_SPEC_CHECK_P (from);
+
+  /* When merging e.g. control & data speculative exprs, or a control
+     speculative with a control&data speculative one, we really have 
+     to change vinsn too.  Also, when speculative status is changed,
+     we also need to record this as a transformation in expr's history.  */
+  if ((old_to_ds & SPECULATIVE) || (old_from_ds & SPECULATIVE))
+    {
+      old_to_ds = ds_get_speculation_types (old_to_ds);
+      old_from_ds = ds_get_speculation_types (old_from_ds);
+        
+      if (old_to_ds != old_from_ds)
+        {
+          ds_t record_ds;
+            
+          /* When both expressions are speculative, we need to change 
+             the vinsn first.  */
+          if ((old_to_ds & SPECULATIVE) && (old_from_ds & SPECULATIVE))
+            {
+              int res;
+                
+              res = speculate_expr (to, EXPR_SPEC_DONE_DS (to));
+              gcc_assert (res >= 0);
+            }
+
+          if (split_point != NULL)
+            {
+              /* Record the change with proper status.  */
+              record_ds = EXPR_SPEC_DONE_DS (to) & SPECULATIVE;
+              record_ds &= ~(old_to_ds & SPECULATIVE);
+              record_ds &= ~(old_from_ds & SPECULATIVE);
+                
+              insert_in_history_vect (&EXPR_HISTORY_OF_CHANGES (to), 
+                                      INSN_UID (split_point), TRANS_SPECULATION, 
+                                      EXPR_VINSN (from), EXPR_VINSN (to),
+                                      record_ds);
+            }
+        }
+    }
+}
+
+
+/* Merge bits of FROM expr to TO expr.  When SPLIT_POINT is not NULL,
+   this is done along different paths.  */
+void
+merge_expr_data (expr_t to, expr_t from, insn_t split_point)
+{
+  int i;
+  expr_history_def *phist;
+  
+  /* For now, we just set the spec of resulting expr to be minimum of the specs
+     of merged exprs.  */
+  if (EXPR_SPEC (to) > EXPR_SPEC (from))
+    EXPR_SPEC (to) = EXPR_SPEC (from);
+
+  if (split_point)
+    EXPR_USEFULNESS (to) += EXPR_USEFULNESS (from);
+  else
+    EXPR_USEFULNESS (to) = MAX (EXPR_USEFULNESS (to), 
+                                EXPR_USEFULNESS (from));
+
+  if (EXPR_PRIORITY (to) < EXPR_PRIORITY (from))
+    EXPR_PRIORITY (to) = EXPR_PRIORITY (from);
+
+  if (EXPR_SCHED_TIMES (to) > EXPR_SCHED_TIMES (from))
+    EXPR_SCHED_TIMES (to) = EXPR_SCHED_TIMES (from);
+
+  if (EXPR_ORIG_BB_INDEX (to) != EXPR_ORIG_BB_INDEX (from))
+    EXPR_ORIG_BB_INDEX (to) = 0;
+
+  EXPR_ORIG_SCHED_CYCLE (to) = MIN (EXPR_ORIG_SCHED_CYCLE (to), 
+                                    EXPR_ORIG_SCHED_CYCLE (from));
+
+  /* We keep this vector sorted.  */
+  for (i = 0; 
+       VEC_iterate (expr_history_def, EXPR_HISTORY_OF_CHANGES (from), 
+                    i, phist);
+       i++)
+    insert_in_history_vect (&EXPR_HISTORY_OF_CHANGES (to), 
+                            phist->uid, phist->type, 
+                            phist->old_expr_vinsn, phist->new_expr_vinsn, 
+                            phist->spec_ds);
+
+  EXPR_WAS_SUBSTITUTED (to) |= EXPR_WAS_SUBSTITUTED (from);
+  EXPR_WAS_RENAMED (to) |= EXPR_WAS_RENAMED (from);
+  EXPR_CANT_MOVE (to) |= EXPR_CANT_MOVE (from);
+
+  update_target_availability (to, from, split_point);
+  update_speculative_bits (to, from, split_point);
+}
+
+/* Merge bits of FROM expr to TO expr.  Vinsns in the exprs should be equal
+   in terms of vinsn_equal_p.  SPLIT_POINT is non-null when expressions 
+   are merged from different successors at a split point.  */
+void
+merge_expr (expr_t to, expr_t from, insn_t split_point)
+{
+  vinsn_t to_vi = EXPR_VINSN (to);
+  vinsn_t from_vi = EXPR_VINSN (from);
+
+  gcc_assert (vinsn_equal_p (to_vi, from_vi));
+
+  /* Make sure that speculative pattern is propagated into exprs that
+     have non-speculative one.  This will provide us with consistent
+     speculative bits and speculative patterns inside expr.  */
+  if (EXPR_SPEC_DONE_DS (to) == 0
+      && EXPR_SPEC_DONE_DS (from) != 0)
+    change_vinsn_in_expr (to, EXPR_VINSN (from));
+
+  merge_expr_data (to, from, split_point);
+  gcc_assert (EXPR_USEFULNESS (to) <= REG_BR_PROB_BASE);
+}
+
+/* Clear the information of this EXPR.  */
+void
+clear_expr (expr_t expr)
+{
+  vinsn_detach (EXPR_VINSN (expr));
+  EXPR_VINSN (expr) = NULL;
+
+  free_history_vect (&EXPR_HISTORY_OF_CHANGES (expr));
+}
+
+/* For a given LV_SET, mark EXPR having unavailable target register.  */
+static void
+set_unavailable_target_for_expr (expr_t expr, regset lv_set)
+{
+  if (EXPR_SEPARABLE_P (expr))
+    {
+      if (REG_P (EXPR_LHS (expr))
+          && bitmap_bit_p (lv_set, REGNO (EXPR_LHS (expr))))
+       {
+         /* If it's an insn like r1 = use (r1, ...), and it exists in 
+            different forms in each of the av_sets being merged, we can't say 
+            whether original destination register is available or not.  
+            However, this still works if destination register is not used 
+            in the original expression: if the branch at which LV_SET we're
+            looking here is not actually 'other branch' in sense that same
+            expression is available through it (but it can't be determined 
+            at computation stage because of transformations on one of the
+            branches), it still won't affect the availability.  
+            Liveness of a register somewhere on a code motion path means 
+            it's either read somewhere on a codemotion path, live on 
+            'other' branch, live at the point immediately following
+            the original operation, or is read by the original operation.
+            The latter case is filtered out in the condition below.
+            It still doesn't cover the case when register is defined and used
+            somewhere within the code motion path, and in this case we could
+            miss a unifying code motion along both branches using a renamed
+            register, but it won't affect a code correctness since upon
+            an actual code motion a bookkeeping code would be generated.  */
+         if (bitmap_bit_p (VINSN_REG_USES (EXPR_VINSN (expr)), 
+                           REGNO (EXPR_LHS (expr))))
+           EXPR_TARGET_AVAILABLE (expr) = -1;
+         else
+           EXPR_TARGET_AVAILABLE (expr) = false;
+       }
+    }
+  else
+    {
+      unsigned regno;
+      reg_set_iterator rsi;
+      
+      EXECUTE_IF_SET_IN_REG_SET (VINSN_REG_SETS (EXPR_VINSN (expr)), 
+                                 0, regno, rsi)
+        if (bitmap_bit_p (lv_set, regno))
+          {
+            EXPR_TARGET_AVAILABLE (expr) = false;
+            break;
+          }
+
+      EXECUTE_IF_SET_IN_REG_SET (VINSN_REG_CLOBBERS (EXPR_VINSN (expr)),
+                                 0, regno, rsi)
+        if (bitmap_bit_p (lv_set, regno))
+          {
+            EXPR_TARGET_AVAILABLE (expr) = false;
+            break;
+          }
+    }
+}
+
+/* Try to make EXPR speculative.  Return 1 when EXPR's pattern 
+   or dependence status have changed, 2 when also the target register
+   became unavailable, 0 if nothing had to be changed.  */
+int
+speculate_expr (expr_t expr, ds_t ds)
+{
+  int res;
+  rtx orig_insn_rtx;
+  rtx spec_pat;
+  ds_t target_ds, current_ds;
+
+  /* Obtain the status we need to put on EXPR.   */
+  target_ds = (ds & SPECULATIVE);
+  current_ds = EXPR_SPEC_DONE_DS (expr);
+  ds = ds_full_merge (current_ds, target_ds, NULL_RTX, NULL_RTX);
+
+  orig_insn_rtx = EXPR_INSN_RTX (expr);
+
+  res = sched_speculate_insn (orig_insn_rtx, ds, &spec_pat);
+
+  switch (res)
+    {
+    case 0:
+      EXPR_SPEC_DONE_DS (expr) = ds;
+      return current_ds != ds ? 1 : 0;
+      
+    case 1:
+      {
+       rtx spec_insn_rtx = create_insn_rtx_from_pattern (spec_pat, NULL_RTX);
+       vinsn_t spec_vinsn = create_vinsn_from_insn_rtx (spec_insn_rtx, false);
+
+       change_vinsn_in_expr (expr, spec_vinsn);
+       EXPR_SPEC_DONE_DS (expr) = ds;
+        EXPR_NEEDS_SPEC_CHECK_P (expr) = true;
+
+        /* Do not allow clobbering the address register of speculative 
+           insns.  */
+        if (bitmap_bit_p (VINSN_REG_USES (EXPR_VINSN (expr)), 
+                          expr_dest_regno (expr)))
+          {
+            EXPR_TARGET_AVAILABLE (expr) = false;
+            return 2;
+          }
+
+       return 1;
+      }
+
+    case -1:
+      return -1;
+
+    default:
+      gcc_unreachable ();
+      return -1;
+    }
+}
+
+/* Return a destination register, if any, of EXPR.  */
+rtx
+expr_dest_reg (expr_t expr)
+{
+  rtx dest = VINSN_LHS (EXPR_VINSN (expr));
+
+  if (dest != NULL_RTX && REG_P (dest))
+    return dest;
+
+  return NULL_RTX;
+}
+
+/* Returns the REGNO of the R's destination.  */
+unsigned
+expr_dest_regno (expr_t expr)
+{
+  rtx dest = expr_dest_reg (expr);
+
+  gcc_assert (dest != NULL_RTX);
+  return REGNO (dest);
+}
+
+/* For a given LV_SET, mark all expressions in JOIN_SET, but not present in 
+   AV_SET having unavailable target register.  */
+void
+mark_unavailable_targets (av_set_t join_set, av_set_t av_set, regset lv_set)
+{
+  expr_t expr;
+  av_set_iterator avi;
+
+  FOR_EACH_EXPR (expr, avi, join_set)
+    if (av_set_lookup (av_set, EXPR_VINSN (expr)) == NULL)
+      set_unavailable_target_for_expr (expr, lv_set);
+}
+\f
+
+/* Av set functions.  */
+
+/* Add a new element to av set SETP.
+   Return the element added.  */
+static av_set_t
+av_set_add_element (av_set_t *setp)
+{
+  /* Insert at the beginning of the list.  */
+  _list_add (setp);
+  return *setp;
+}
+
+/* Add EXPR to SETP.  */
+void
+av_set_add (av_set_t *setp, expr_t expr)
+{
+  av_set_t elem;
+  
+  gcc_assert (!INSN_NOP_P (EXPR_INSN_RTX (expr)));
+  elem = av_set_add_element (setp);
+  copy_expr (_AV_SET_EXPR (elem), expr);
+}
+
+/* Same, but do not copy EXPR.  */
+static void
+av_set_add_nocopy (av_set_t *setp, expr_t expr)
+{
+  av_set_t elem;
+
+  elem = av_set_add_element (setp);
+  *_AV_SET_EXPR (elem) = *expr;
+}
+
+/* Remove expr pointed to by IP from the av_set.  */
+void
+av_set_iter_remove (av_set_iterator *ip)
+{
+  clear_expr (_AV_SET_EXPR (*ip->lp));
+  _list_iter_remove (ip);
+}
+
+/* Search for an expr in SET, such that it's equivalent to SOUGHT_VINSN in the
+   sense of vinsn_equal_p function. Return NULL if no such expr is
+   in SET was found.  */
+expr_t
+av_set_lookup (av_set_t set, vinsn_t sought_vinsn)
+{
+  expr_t expr;
+  av_set_iterator i;
+
+  FOR_EACH_EXPR (expr, i, set)
+    if (vinsn_equal_p (EXPR_VINSN (expr), sought_vinsn))
+      return expr;
+  return NULL;
+}
+
+/* Same, but also remove the EXPR found.   */
+static expr_t
+av_set_lookup_and_remove (av_set_t *setp, vinsn_t sought_vinsn)
+{
+  expr_t expr;
+  av_set_iterator i;
+
+  FOR_EACH_EXPR_1 (expr, i, setp)
+    if (vinsn_equal_p (EXPR_VINSN (expr), sought_vinsn))
+      {
+        _list_iter_remove_nofree (&i);
+        return expr;
+      }
+  return NULL;
+}
+
+/* Search for an expr in SET, such that it's equivalent to EXPR in the
+   sense of vinsn_equal_p function of their vinsns, but not EXPR itself.
+   Returns NULL if no such expr is in SET was found.  */
+static expr_t
+av_set_lookup_other_equiv_expr (av_set_t set, expr_t expr)
+{
+  expr_t cur_expr;
+  av_set_iterator i;
+
+  FOR_EACH_EXPR (cur_expr, i, set)
+    {
+      if (cur_expr == expr)
+        continue;
+      if (vinsn_equal_p (EXPR_VINSN (cur_expr), EXPR_VINSN (expr)))
+        return cur_expr;
+    }
+
+  return NULL;
+}
+
+/* If other expression is already in AVP, remove one of them.  */
+expr_t
+merge_with_other_exprs (av_set_t *avp, av_set_iterator *ip, expr_t expr)
+{
+  expr_t expr2;
+
+  expr2 = av_set_lookup_other_equiv_expr (*avp, expr);
+  if (expr2 != NULL)
+    {
+      /* Reset target availability on merge, since taking it only from one
+        of the exprs would be controversial for different code.  */
+      EXPR_TARGET_AVAILABLE (expr2) = -1;
+      EXPR_USEFULNESS (expr2) = 0;
+
+      merge_expr (expr2, expr, NULL);
+      
+      /* Fix usefulness as it should be now REG_BR_PROB_BASE.  */
+      EXPR_USEFULNESS (expr2) = REG_BR_PROB_BASE;
+      
+      av_set_iter_remove (ip);
+      return expr2;
+    }
+
+  return expr;
+}
+
+/* Return true if there is an expr that correlates to VI in SET.  */
+bool
+av_set_is_in_p (av_set_t set, vinsn_t vi)
+{
+  return av_set_lookup (set, vi) != NULL;
+}
+
+/* Return a copy of SET.  */
+av_set_t
+av_set_copy (av_set_t set)
+{
+  expr_t expr;
+  av_set_iterator i;
+  av_set_t res = NULL;
+
+  FOR_EACH_EXPR (expr, i, set)
+    av_set_add (&res, expr);
+
+  return res;
+}
+
+/* Join two av sets that do not have common elements by attaching second set
+   (pointed to by FROMP) to the end of first set (TO_TAILP must point to
+   _AV_SET_NEXT of first set's last element).  */
+static void
+join_distinct_sets (av_set_t *to_tailp, av_set_t *fromp)
+{
+  gcc_assert (*to_tailp == NULL);
+  *to_tailp = *fromp;
+  *fromp = NULL;
+}
+
+/* Makes set pointed to by TO to be the union of TO and FROM.  Clear av_set
+   pointed to by FROMP afterwards.  */
+void
+av_set_union_and_clear (av_set_t *top, av_set_t *fromp, insn_t insn)
+{
+  expr_t expr1;
+  av_set_iterator i;
+
+  /* Delete from TOP all exprs, that present in FROMP.  */
+  FOR_EACH_EXPR_1 (expr1, i, top)
+    {
+      expr_t expr2 = av_set_lookup (*fromp, EXPR_VINSN (expr1));
+
+      if (expr2)
+       {
+          merge_expr (expr2, expr1, insn);
+         av_set_iter_remove (&i);
+       }
+    }
+
+  join_distinct_sets (i.lp, fromp);
+}
+
+/* Same as above, but also update availability of target register in 
+   TOP judging by TO_LV_SET and FROM_LV_SET.  */
+void
+av_set_union_and_live (av_set_t *top, av_set_t *fromp, regset to_lv_set,
+                       regset from_lv_set, insn_t insn)
+{
+  expr_t expr1;
+  av_set_iterator i;
+  av_set_t *to_tailp, in_both_set = NULL;
+
+  /* Delete from TOP all expres, that present in FROMP.  */
+  FOR_EACH_EXPR_1 (expr1, i, top)
+    {
+      expr_t expr2 = av_set_lookup_and_remove (fromp, EXPR_VINSN (expr1));
+
+      if (expr2)
+       {
+          /* It may be that the expressions have different destination 
+             registers, in which case we need to check liveness here.  */
+          if (EXPR_SEPARABLE_P (expr1))
+            {
+              int regno1 = (REG_P (EXPR_LHS (expr1)) 
+                            ? (int) expr_dest_regno (expr1) : -1);
+              int regno2 = (REG_P (EXPR_LHS (expr2)) 
+                            ? (int) expr_dest_regno (expr2) : -1);
+              
+              /* ??? We don't have a way to check restrictions for 
+               *other* register on the current path, we did it only
+               for the current target register.  Give up.  */
+              if (regno1 != regno2)
+                EXPR_TARGET_AVAILABLE (expr2) = -1;
+            }
+          else if (EXPR_INSN_RTX (expr1) != EXPR_INSN_RTX (expr2))
+            EXPR_TARGET_AVAILABLE (expr2) = -1;
+
+          merge_expr (expr2, expr1, insn);
+          av_set_add_nocopy (&in_both_set, expr2);
+         av_set_iter_remove (&i);
+       }
+      else
+        /* EXPR1 is present in TOP, but not in FROMP.  Check it on 
+           FROM_LV_SET.  */
+        set_unavailable_target_for_expr (expr1, from_lv_set);
+    }
+  to_tailp = i.lp;
+
+  /* These expressions are not present in TOP.  Check liveness
+     restrictions on TO_LV_SET.  */
+  FOR_EACH_EXPR (expr1, i, *fromp)
+    set_unavailable_target_for_expr (expr1, to_lv_set);
+
+  join_distinct_sets (i.lp, &in_both_set);
+  join_distinct_sets (to_tailp, fromp);
+}
+
+/* Clear av_set pointed to by SETP.  */
+void
+av_set_clear (av_set_t *setp)
+{
+  expr_t expr;
+  av_set_iterator i;
+
+  FOR_EACH_EXPR_1 (expr, i, setp)
+    av_set_iter_remove (&i);
+
+  gcc_assert (*setp == NULL);
+}
+
+/* Leave only one non-speculative element in the SETP.  */
+void
+av_set_leave_one_nonspec (av_set_t *setp)
+{
+  expr_t expr;
+  av_set_iterator i;
+  bool has_one_nonspec = false;
+
+  /* Keep all speculative exprs, and leave one non-speculative 
+     (the first one).  */
+  FOR_EACH_EXPR_1 (expr, i, setp)
+    {
+      if (!EXPR_SPEC_DONE_DS (expr))
+       {
+         if (has_one_nonspec)
+           av_set_iter_remove (&i);
+         else
+           has_one_nonspec = true;
+       }
+    }
+}
+
+/* Return the N'th element of the SET.  */
+expr_t
+av_set_element (av_set_t set, int n)
+{
+  expr_t expr;
+  av_set_iterator i;
+
+  FOR_EACH_EXPR (expr, i, set)
+    if (n-- == 0)
+      return expr;
+
+  gcc_unreachable ();
+  return NULL;
+}
+
+/* Deletes all expressions from AVP that are conditional branches (IFs).  */
+void
+av_set_substract_cond_branches (av_set_t *avp)
+{
+  av_set_iterator i;
+  expr_t expr;
+
+  FOR_EACH_EXPR_1 (expr, i, avp)
+    if (vinsn_cond_branch_p (EXPR_VINSN (expr)))
+      av_set_iter_remove (&i);
+}
+
+/* Multiplies usefulness attribute of each member of av-set *AVP by 
+   value PROB / ALL_PROB.  */
+void
+av_set_split_usefulness (av_set_t av, int prob, int all_prob)
+{
+  av_set_iterator i;
+  expr_t expr;
+
+  FOR_EACH_EXPR (expr, i, av)
+    EXPR_USEFULNESS (expr) = (all_prob 
+                              ? (EXPR_USEFULNESS (expr) * prob) / all_prob
+                              : 0);
+}
+
+/* Leave in AVP only those expressions, which are present in AV,
+   and return it.  */
+void
+av_set_intersect (av_set_t *avp, av_set_t av)
+{
+  av_set_iterator i;
+  expr_t expr;
+
+  FOR_EACH_EXPR_1 (expr, i, avp)
+    if (av_set_lookup (av, EXPR_VINSN (expr)) == NULL)
+      av_set_iter_remove (&i);
+}
+
+\f
+
+/* Dependence hooks to initialize insn data.  */
+
+/* This is used in hooks callable from dependence analysis when initializing
+   instruction's data.  */
+static struct
+{
+  /* Where the dependence was found (lhs/rhs).  */
+  deps_where_t where;
+
+  /* The actual data object to initialize.  */
+  idata_t id;
+
+  /* True when the insn should not be made clonable.  */
+  bool force_unique_p;
+
+  /* True when insn should be treated as of type USE, i.e. never renamed.  */
+  bool force_use_p;
+} deps_init_id_data;
+
+
+/* Setup ID for INSN.  FORCE_UNIQUE_P is true when INSN should not be 
+   clonable.  */
+static void
+setup_id_for_insn (idata_t id, insn_t insn, bool force_unique_p)
+{
+  int type;
+  
+  /* Determine whether INSN could be cloned and return appropriate vinsn type.
+     That clonable insns which can be separated into lhs and rhs have type SET.
+     Other clonable insns have type USE.  */
+  type = GET_CODE (insn);
+
+  /* Only regular insns could be cloned.  */
+  if (type == INSN && !force_unique_p)
+    type = SET;
+  else if (type == JUMP_INSN && simplejump_p (insn))
+    type = PC;
+  
+  IDATA_TYPE (id) = type;
+  IDATA_REG_SETS (id) = get_clear_regset_from_pool ();
+  IDATA_REG_USES (id) = get_clear_regset_from_pool ();
+  IDATA_REG_CLOBBERS (id) = get_clear_regset_from_pool ();
+}
+
+/* Start initializing insn data.  */
+static void
+deps_init_id_start_insn (insn_t insn)
+{
+  gcc_assert (deps_init_id_data.where == DEPS_IN_NOWHERE);
+
+  setup_id_for_insn (deps_init_id_data.id, insn,
+                     deps_init_id_data.force_unique_p);
+  deps_init_id_data.where = DEPS_IN_INSN;
+}
+
+/* Start initializing lhs data.  */
+static void
+deps_init_id_start_lhs (rtx lhs)
+{
+  gcc_assert (deps_init_id_data.where == DEPS_IN_INSN);
+  gcc_assert (IDATA_LHS (deps_init_id_data.id) == NULL);
+
+  if (IDATA_TYPE (deps_init_id_data.id) == SET)
+    {
+      IDATA_LHS (deps_init_id_data.id) = lhs;
+      deps_init_id_data.where = DEPS_IN_LHS;
+    }
+}
+
+/* Finish initializing lhs data.  */
+static void
+deps_init_id_finish_lhs (void)
+{
+  deps_init_id_data.where = DEPS_IN_INSN;
+}
+
+/* Note a set of REGNO.  */
+static void
+deps_init_id_note_reg_set (int regno)
+{
+  haifa_note_reg_set (regno);
+
+  if (deps_init_id_data.where == DEPS_IN_RHS)
+    deps_init_id_data.force_use_p = true;
+
+  if (IDATA_TYPE (deps_init_id_data.id) != PC)
+    SET_REGNO_REG_SET (IDATA_REG_SETS (deps_init_id_data.id), regno);
+
+#ifdef STACK_REGS
+  /* Make instructions that set stack registers to be ineligible for 
+     renaming to avoid issues with find_used_regs.  */
+  if (IN_RANGE (regno, FIRST_STACK_REG, LAST_STACK_REG))
+    deps_init_id_data.force_use_p = true;
+#endif
+}
+
+/* Note a clobber of REGNO.  */
+static void
+deps_init_id_note_reg_clobber (int regno)
+{
+  haifa_note_reg_clobber (regno);
+
+  if (deps_init_id_data.where == DEPS_IN_RHS)
+    deps_init_id_data.force_use_p = true;
+
+  if (IDATA_TYPE (deps_init_id_data.id) != PC)
+    SET_REGNO_REG_SET (IDATA_REG_CLOBBERS (deps_init_id_data.id), regno);
+}
+
+/* Note a use of REGNO.  */
+static void
+deps_init_id_note_reg_use (int regno)
+{
+  haifa_note_reg_use (regno);
+
+  if (IDATA_TYPE (deps_init_id_data.id) != PC)
+    SET_REGNO_REG_SET (IDATA_REG_USES (deps_init_id_data.id), regno);
+}
+
+/* Start initializing rhs data.  */
+static void
+deps_init_id_start_rhs (rtx rhs)
+{
+  gcc_assert (deps_init_id_data.where == DEPS_IN_INSN);
+
+  /* And there was no sel_deps_reset_to_insn ().  */
+  if (IDATA_LHS (deps_init_id_data.id) != NULL)
+    {
+      IDATA_RHS (deps_init_id_data.id) = rhs;
+      deps_init_id_data.where = DEPS_IN_RHS;
+    }
+}
+
+/* Finish initializing rhs data.  */
+static void
+deps_init_id_finish_rhs (void)
+{
+  gcc_assert (deps_init_id_data.where == DEPS_IN_RHS
+             || deps_init_id_data.where == DEPS_IN_INSN);
+  deps_init_id_data.where = DEPS_IN_INSN;
+}
+
+/* Finish initializing insn data.  */
+static void
+deps_init_id_finish_insn (void)
+{
+  gcc_assert (deps_init_id_data.where == DEPS_IN_INSN);
+
+  if (IDATA_TYPE (deps_init_id_data.id) == SET)
+    {
+      rtx lhs = IDATA_LHS (deps_init_id_data.id);
+      rtx rhs = IDATA_RHS (deps_init_id_data.id);
+
+      if (lhs == NULL || rhs == NULL || !lhs_and_rhs_separable_p (lhs, rhs)
+         || deps_init_id_data.force_use_p)
+       {
+          /* This should be a USE, as we don't want to schedule its RHS 
+             separately.  However, we still want to have them recorded
+             for the purposes of substitution.  That's why we don't 
+             simply call downgrade_to_use () here.  */
+         gcc_assert (IDATA_TYPE (deps_init_id_data.id) == SET);
+         gcc_assert (!lhs == !rhs);
+
+         IDATA_TYPE (deps_init_id_data.id) = USE;
+       }
+    }
+
+  deps_init_id_data.where = DEPS_IN_NOWHERE;
+}
+
+/* This is dependence info used for initializing insn's data.  */
+static struct sched_deps_info_def deps_init_id_sched_deps_info;
+
+/* This initializes most of the static part of the above structure.  */
+static const struct sched_deps_info_def const_deps_init_id_sched_deps_info =
+  {
+    NULL,
+
+    deps_init_id_start_insn,
+    deps_init_id_finish_insn,
+    deps_init_id_start_lhs,
+    deps_init_id_finish_lhs,
+    deps_init_id_start_rhs,
+    deps_init_id_finish_rhs,
+    deps_init_id_note_reg_set,
+    deps_init_id_note_reg_clobber,
+    deps_init_id_note_reg_use,
+    NULL, /* note_mem_dep */
+    NULL, /* note_dep */
+
+    0, /* use_cselib */
+    0, /* use_deps_list */
+    0 /* generate_spec_deps */
+  };
+
+/* Initialize INSN's lhs and rhs in ID.  When FORCE_UNIQUE_P is true,
+   we don't actually need information about lhs and rhs.  */
+static void
+setup_id_lhs_rhs (idata_t id, insn_t insn, bool force_unique_p)
+{
+  rtx pat = PATTERN (insn);
+  
+  if (GET_CODE (insn) == INSN
+      && GET_CODE (pat) == SET 
+      && !force_unique_p)
+    {
+      IDATA_RHS (id) = SET_SRC (pat);
+      IDATA_LHS (id) = SET_DEST (pat);
+    }
+  else
+    IDATA_LHS (id) = IDATA_RHS (id) = NULL;
+}
+
+/* Possibly downgrade INSN to USE.  */
+static void
+maybe_downgrade_id_to_use (idata_t id, insn_t insn)
+{
+  bool must_be_use = false;
+  unsigned uid = INSN_UID (insn);
+  struct df_ref **rec;
+  rtx lhs = IDATA_LHS (id);
+  rtx rhs = IDATA_RHS (id);
+  
+  /* We downgrade only SETs.  */
+  if (IDATA_TYPE (id) != SET)
+    return;
+
+  if (!lhs || !lhs_and_rhs_separable_p (lhs, rhs))
+    {
+      IDATA_TYPE (id) = USE;
+      return;
+    }
+  
+  for (rec = DF_INSN_UID_DEFS (uid); *rec; rec++)
+    {
+      struct df_ref *def = *rec;
+      
+      if (DF_REF_INSN (def)
+          && DF_REF_FLAGS_IS_SET (def, DF_REF_PRE_POST_MODIFY)
+          && loc_mentioned_in_p (DF_REF_LOC (def), IDATA_RHS (id)))
+        {
+          must_be_use = true;
+          break;
+        }
+
+#ifdef STACK_REGS
+      /* Make instructions that set stack registers to be ineligible for 
+        renaming to avoid issues with find_used_regs.  */
+      if (IN_RANGE (DF_REF_REGNO (def), FIRST_STACK_REG, LAST_STACK_REG))
+       {
+         must_be_use = true;
+         break;
+       }
+#endif
+    }    
+  
+  if (must_be_use)
+    IDATA_TYPE (id) = USE;
+}
+
+/* Setup register sets describing INSN in ID.  */
+static void
+setup_id_reg_sets (idata_t id, insn_t insn)
+{
+  unsigned uid = INSN_UID (insn);
+  struct df_ref **rec;
+  regset tmp = get_clear_regset_from_pool ();
+  
+  for (rec = DF_INSN_UID_DEFS (uid); *rec; rec++)
+    {
+      struct df_ref *def = *rec;
+      unsigned int regno = DF_REF_REGNO (def);
+      
+      /* Post modifies are treated like clobbers by sched-deps.c.  */
+      if (DF_REF_FLAGS_IS_SET (def, (DF_REF_MUST_CLOBBER
+                                     | DF_REF_PRE_POST_MODIFY)))
+        SET_REGNO_REG_SET (IDATA_REG_CLOBBERS (id), regno);
+      else if (! DF_REF_FLAGS_IS_SET (def, DF_REF_MAY_CLOBBER))
+        {
+         SET_REGNO_REG_SET (IDATA_REG_SETS (id), regno);
+
+#ifdef STACK_REGS
+         /* For stack registers, treat writes to them as writes 
+            to the first one to be consistent with sched-deps.c.  */
+         if (IN_RANGE (regno, FIRST_STACK_REG, LAST_STACK_REG))
+           SET_REGNO_REG_SET (IDATA_REG_SETS (id), FIRST_STACK_REG);
+#endif
+       }
+      /* Mark special refs that generate read/write def pair.  */
+      if (DF_REF_FLAGS_IS_SET (def, DF_REF_CONDITIONAL)
+          || regno == STACK_POINTER_REGNUM)
+        bitmap_set_bit (tmp, regno);
+    }
+      
+  for (rec = DF_INSN_UID_USES (uid); *rec; rec++)
+    {
+      struct df_ref *use = *rec;
+      unsigned int regno = DF_REF_REGNO (use);
+
+      /* When these refs are met for the first time, skip them, as
+         these uses are just counterparts of some defs.  */
+      if (bitmap_bit_p (tmp, regno))
+        bitmap_clear_bit (tmp, regno);
+      else if (! DF_REF_FLAGS_IS_SET (use, DF_REF_CALL_STACK_USAGE))
+       {
+         SET_REGNO_REG_SET (IDATA_REG_USES (id), regno);
+
+#ifdef STACK_REGS
+         /* For stack registers, treat reads from them as reads from 
+            the first one to be consistent with sched-deps.c.  */
+         if (IN_RANGE (regno, FIRST_STACK_REG, LAST_STACK_REG))
+           SET_REGNO_REG_SET (IDATA_REG_USES (id), FIRST_STACK_REG);
+#endif
+       }
+    }
+
+  return_regset_to_pool (tmp);
+}
+
+/* Initialize instruction data for INSN in ID using DF's data.  */
+static void
+init_id_from_df (idata_t id, insn_t insn, bool force_unique_p)
+{
+  gcc_assert (DF_INSN_UID_SAFE_GET (INSN_UID (insn)) != NULL);
+
+  setup_id_for_insn (id, insn, force_unique_p);
+  setup_id_lhs_rhs (id, insn, force_unique_p);
+
+  if (INSN_NOP_P (insn))
+    return;
+
+  maybe_downgrade_id_to_use (id, insn);
+  setup_id_reg_sets (id, insn);
+}
+
+/* Initialize instruction data for INSN in ID.  */
+static void
+deps_init_id (idata_t id, insn_t insn, bool force_unique_p)
+{
+  struct deps _dc, *dc = &_dc;
+
+  deps_init_id_data.where = DEPS_IN_NOWHERE;
+  deps_init_id_data.id = id;
+  deps_init_id_data.force_unique_p = force_unique_p;
+  deps_init_id_data.force_use_p = false;
+
+  init_deps (dc);
+
+  memcpy (&deps_init_id_sched_deps_info,
+         &const_deps_init_id_sched_deps_info,
+         sizeof (deps_init_id_sched_deps_info));
+
+  if (spec_info != NULL)
+    deps_init_id_sched_deps_info.generate_spec_deps = 1;
+
+  sched_deps_info = &deps_init_id_sched_deps_info;
+
+  deps_analyze_insn (dc, insn);
+
+  free_deps (dc);
+
+  deps_init_id_data.id = NULL;
+}
+
+\f
+
+/* Implement hooks for collecting fundamental insn properties like if insn is
+   an ASM or is within a SCHED_GROUP.  */
+
+/* True when a "one-time init" data for INSN was already inited.  */
+static bool
+first_time_insn_init (insn_t insn)
+{
+  return INSN_LIVE (insn) == NULL;
+}
+
+/* Hash an entry in a transformed_insns hashtable.  */
+static hashval_t
+hash_transformed_insns (const void *p)
+{
+  return VINSN_HASH_RTX (((const struct transformed_insns *) p)->vinsn_old);
+}
+
+/* Compare the entries in a transformed_insns hashtable.  */
+static int
+eq_transformed_insns (const void *p, const void *q)
+{
+  rtx i1 = VINSN_INSN_RTX (((const struct transformed_insns *) p)->vinsn_old);
+  rtx i2 = VINSN_INSN_RTX (((const struct transformed_insns *) q)->vinsn_old);
+
+  if (INSN_UID (i1) == INSN_UID (i2))
+    return 1;
+  return rtx_equal_p (PATTERN (i1), PATTERN (i2));
+}
+
+/* Free an entry in a transformed_insns hashtable.  */
+static void
+free_transformed_insns (void *p)
+{
+  struct transformed_insns *pti = (struct transformed_insns *) p;
+
+  vinsn_detach (pti->vinsn_old);
+  vinsn_detach (pti->vinsn_new);
+  free (pti);
+}
+
+/* Init the s_i_d data for INSN which should be inited just once, when 
+   we first see the insn.  */
+static void
+init_first_time_insn_data (insn_t insn)
+{
+  /* This should not be set if this is the first time we init data for
+     insn.  */
+  gcc_assert (first_time_insn_init (insn));
+  
+  /* These are needed for nops too.  */
+  INSN_LIVE (insn) = get_regset_from_pool ();
+  INSN_LIVE_VALID_P (insn) = false;
+  
+  if (!INSN_NOP_P (insn))
+    {
+      INSN_ANALYZED_DEPS (insn) = BITMAP_ALLOC (NULL);
+      INSN_FOUND_DEPS (insn) = BITMAP_ALLOC (NULL);
+      INSN_TRANSFORMED_INSNS (insn) 
+        = htab_create (16, hash_transformed_insns,
+                       eq_transformed_insns, free_transformed_insns);
+      init_deps (&INSN_DEPS_CONTEXT (insn));
+    }
+}
+
+/* Free the same data as above for INSN.  */
+static void
+free_first_time_insn_data (insn_t insn)
+{
+  gcc_assert (! first_time_insn_init (insn));
+
+  BITMAP_FREE (INSN_ANALYZED_DEPS (insn));
+  BITMAP_FREE (INSN_FOUND_DEPS (insn));
+  htab_delete (INSN_TRANSFORMED_INSNS (insn));
+  return_regset_to_pool (INSN_LIVE (insn));
+  INSN_LIVE (insn) = NULL;
+  INSN_LIVE_VALID_P (insn) = false;
+
+  /* This is allocated only for bookkeeping insns.  */
+  if (INSN_ORIGINATORS (insn))
+    BITMAP_FREE (INSN_ORIGINATORS (insn));
+  free_deps (&INSN_DEPS_CONTEXT (insn));
+}
+
+/* Initialize region-scope data structures for basic blocks.  */
+static void
+init_global_and_expr_for_bb (basic_block bb)
+{
+  if (sel_bb_empty_p (bb))
+    return;
+
+  invalidate_av_set (bb);
+}
+
+/* Data for global dependency analysis (to initialize CANT_MOVE and
+   SCHED_GROUP_P).  */
+static struct
+{
+  /* Previous insn.  */
+  insn_t prev_insn;
+} init_global_data;
+
+/* Determine if INSN is in the sched_group, is an asm or should not be
+   cloned.  After that initialize its expr.  */
+static void
+init_global_and_expr_for_insn (insn_t insn)
+{
+  if (LABEL_P (insn))
+    return;
+
+  if (NOTE_INSN_BASIC_BLOCK_P (insn))
+    {
+      init_global_data.prev_insn = NULL_RTX;
+      return;
+    }
+
+  gcc_assert (INSN_P (insn));
+
+  if (SCHED_GROUP_P (insn))
+    /* Setup a sched_group.  */
+    {
+      insn_t prev_insn = init_global_data.prev_insn;
+
+      if (prev_insn)
+       INSN_SCHED_NEXT (prev_insn) = insn;
+
+      init_global_data.prev_insn = insn;
+    }
+  else
+    init_global_data.prev_insn = NULL_RTX;
+
+  if (GET_CODE (PATTERN (insn)) == ASM_INPUT
+      || asm_noperands (PATTERN (insn)) >= 0)
+    /* Mark INSN as an asm.  */
+    INSN_ASM_P (insn) = true;
+
+  {
+    bool force_unique_p;
+    ds_t spec_done_ds;
+
+    /* Certain instructions cannot be cloned.  */
+    if (CANT_MOVE (insn)
+       || INSN_ASM_P (insn)
+       || SCHED_GROUP_P (insn)
+       || prologue_epilogue_contains (insn) 
+       /* Exception handling insns are always unique.  */
+       || (flag_non_call_exceptions && can_throw_internal (insn))
+       /* TRAP_IF though have an INSN code is control_flow_insn_p ().  */
+       || control_flow_insn_p (insn))
+      force_unique_p = true;
+    else
+      force_unique_p = false;
+
+    if (targetm.sched.get_insn_spec_ds)
+      {
+       spec_done_ds = targetm.sched.get_insn_spec_ds (insn);
+       spec_done_ds = ds_get_max_dep_weak (spec_done_ds);
+      }
+    else
+      spec_done_ds = 0;
+
+    /* Initialize INSN's expr.  */
+    init_expr (INSN_EXPR (insn), vinsn_create (insn, force_unique_p), 0,
+              REG_BR_PROB_BASE, INSN_PRIORITY (insn), 0, BLOCK_NUM (insn),
+              spec_done_ds, 0, 0, NULL, true, false, false, false, 
+               CANT_MOVE (insn));
+  }
+
+  init_first_time_insn_data (insn);
+}
+
+/* Scan the region and initialize instruction data for basic blocks BBS.  */
+void
+sel_init_global_and_expr (bb_vec_t bbs)
+{
+  /* ??? It would be nice to implement push / pop scheme for sched_infos.  */
+  const struct sched_scan_info_def ssi =
+    {
+      NULL, /* extend_bb */
+      init_global_and_expr_for_bb, /* init_bb */
+      extend_insn_data, /* extend_insn */
+      init_global_and_expr_for_insn /* init_insn */
+    };
+  
+  sched_scan (&ssi, bbs, NULL, NULL, NULL);
+}
+
+/* Finalize region-scope data structures for basic blocks.  */
+static void
+finish_global_and_expr_for_bb (basic_block bb)
+{
+  av_set_clear (&BB_AV_SET (bb));
+  BB_AV_LEVEL (bb) = 0;
+}
+
+/* Finalize INSN's data.  */
+static void
+finish_global_and_expr_insn (insn_t insn)
+{
+  if (LABEL_P (insn) || NOTE_INSN_BASIC_BLOCK_P (insn))
+    return;
+
+  gcc_assert (INSN_P (insn));
+
+  if (INSN_LUID (insn) > 0)
+    {
+      free_first_time_insn_data (insn);
+      INSN_WS_LEVEL (insn) = 0;
+      CANT_MOVE (insn) = 0;
+      
+      /* We can no longer assert this, as vinsns of this insn could be 
+         easily live in other insn's caches.  This should be changed to 
+         a counter-like approach among all vinsns.  */
+      gcc_assert (true || VINSN_COUNT (INSN_VINSN (insn)) == 1);
+      clear_expr (INSN_EXPR (insn));
+    }
+}
+
+/* Finalize per instruction data for the whole region.  */
+void
+sel_finish_global_and_expr (void)
+{
+  {
+    bb_vec_t bbs;
+    int i;
+
+    bbs = VEC_alloc (basic_block, heap, current_nr_blocks);
+
+    for (i = 0; i < current_nr_blocks; i++)
+      VEC_quick_push (basic_block, bbs, BASIC_BLOCK (BB_TO_BLOCK (i)));
+
+    /* Clear AV_SETs and INSN_EXPRs.  */
+    {
+      const struct sched_scan_info_def ssi =
+       {
+         NULL, /* extend_bb */
+         finish_global_and_expr_for_bb, /* init_bb */
+         NULL, /* extend_insn */
+         finish_global_and_expr_insn /* init_insn */
+       };
+
+      sched_scan (&ssi, bbs, NULL, NULL, NULL);
+    }
+
+    VEC_free (basic_block, heap, bbs);
+  }
+
+  finish_insns ();
+}
+\f
+
+/* In the below hooks, we merely calculate whether or not a dependence 
+   exists, and in what part of insn.  However, we will need more data 
+   when we'll start caching dependence requests.  */
+
+/* Container to hold information for dependency analysis.  */
+static struct
+{
+  deps_t dc;
+
+  /* A variable to track which part of rtx we are scanning in
+     sched-deps.c: sched_analyze_insn ().  */
+  deps_where_t where;
+
+  /* Current producer.  */
+  insn_t pro;
+
+  /* Current consumer.  */
+  vinsn_t con;
+
+  /* Is SEL_DEPS_HAS_DEP_P[DEPS_IN_X] is true, then X has a dependence.
+     X is from { INSN, LHS, RHS }.  */
+  ds_t has_dep_p[DEPS_IN_NOWHERE];
+} has_dependence_data;
+
+/* Start analyzing dependencies of INSN.  */
+static void
+has_dependence_start_insn (insn_t insn ATTRIBUTE_UNUSED)
+{
+  gcc_assert (has_dependence_data.where == DEPS_IN_NOWHERE);
+
+  has_dependence_data.where = DEPS_IN_INSN;
+}
+
+/* Finish analyzing dependencies of an insn.  */
+static void
+has_dependence_finish_insn (void)
+{
+  gcc_assert (has_dependence_data.where == DEPS_IN_INSN);
+
+  has_dependence_data.where = DEPS_IN_NOWHERE;
+}
+
+/* Start analyzing dependencies of LHS.  */
+static void
+has_dependence_start_lhs (rtx lhs ATTRIBUTE_UNUSED)
+{
+  gcc_assert (has_dependence_data.where == DEPS_IN_INSN);
+
+  if (VINSN_LHS (has_dependence_data.con) != NULL)
+    has_dependence_data.where = DEPS_IN_LHS;
+}
+
+/* Finish analyzing dependencies of an lhs.  */
+static void
+has_dependence_finish_lhs (void)
+{
+  has_dependence_data.where = DEPS_IN_INSN;
+}
+
+/* Start analyzing dependencies of RHS.  */
+static void
+has_dependence_start_rhs (rtx rhs ATTRIBUTE_UNUSED)
+{
+  gcc_assert (has_dependence_data.where == DEPS_IN_INSN);
+
+  if (VINSN_RHS (has_dependence_data.con) != NULL)
+    has_dependence_data.where = DEPS_IN_RHS;
+}
+
+/* Start analyzing dependencies of an rhs.  */
+static void
+has_dependence_finish_rhs (void)
+{
+  gcc_assert (has_dependence_data.where == DEPS_IN_RHS
+             || has_dependence_data.where == DEPS_IN_INSN);
+
+  has_dependence_data.where = DEPS_IN_INSN;
+}
+
+/* Note a set of REGNO.  */
+static void
+has_dependence_note_reg_set (int regno)
+{
+  struct deps_reg *reg_last = &has_dependence_data.dc->reg_last[regno];
+
+  if (!sched_insns_conditions_mutex_p (has_dependence_data.pro,
+                                      VINSN_INSN_RTX
+                                      (has_dependence_data.con)))
+    {
+      ds_t *dsp = &has_dependence_data.has_dep_p[has_dependence_data.where];
+
+      if (reg_last->sets != NULL
+         || reg_last->clobbers != NULL)
+       *dsp = (*dsp & ~SPECULATIVE) | DEP_OUTPUT;
+
+      if (reg_last->uses)
+       *dsp = (*dsp & ~SPECULATIVE) | DEP_ANTI;
+    }
+}
+
+/* Note a clobber of REGNO.  */
+static void
+has_dependence_note_reg_clobber (int regno)
+{
+  struct deps_reg *reg_last = &has_dependence_data.dc->reg_last[regno];
+
+  if (!sched_insns_conditions_mutex_p (has_dependence_data.pro,
+                                      VINSN_INSN_RTX
+                                      (has_dependence_data.con)))
+    {
+      ds_t *dsp = &has_dependence_data.has_dep_p[has_dependence_data.where];
+
+      if (reg_last->sets)
+       *dsp = (*dsp & ~SPECULATIVE) | DEP_OUTPUT;
+       
+      if (reg_last->uses)
+       *dsp = (*dsp & ~SPECULATIVE) | DEP_ANTI;
+    }
+}
+
+/* Note a use of REGNO.  */
+static void
+has_dependence_note_reg_use (int regno)
+{
+  struct deps_reg *reg_last = &has_dependence_data.dc->reg_last[regno];
+
+  if (!sched_insns_conditions_mutex_p (has_dependence_data.pro,
+                                      VINSN_INSN_RTX
+                                      (has_dependence_data.con)))
+    {
+      ds_t *dsp = &has_dependence_data.has_dep_p[has_dependence_data.where];
+
+      if (reg_last->sets)
+       *dsp = (*dsp & ~SPECULATIVE) | DEP_TRUE;
+
+      if (reg_last->clobbers)
+       *dsp = (*dsp & ~SPECULATIVE) | DEP_ANTI;
+
+      /* Handle BE_IN_SPEC.  */
+      if (reg_last->uses)
+       {
+         ds_t pro_spec_checked_ds;
+
+         pro_spec_checked_ds = INSN_SPEC_CHECKED_DS (has_dependence_data.pro);
+         pro_spec_checked_ds = ds_get_max_dep_weak (pro_spec_checked_ds);
+
+         if (pro_spec_checked_ds != 0)
+           /* Merge BE_IN_SPEC bits into *DSP.  */
+           *dsp = ds_full_merge (*dsp, pro_spec_checked_ds,
+                                 NULL_RTX, NULL_RTX);
+       }
+    }
+}
+
+/* Note a memory dependence.  */
+static void
+has_dependence_note_mem_dep (rtx mem ATTRIBUTE_UNUSED,
+                            rtx pending_mem ATTRIBUTE_UNUSED,
+                            insn_t pending_insn ATTRIBUTE_UNUSED,
+                            ds_t ds ATTRIBUTE_UNUSED)
+{
+  if (!sched_insns_conditions_mutex_p (has_dependence_data.pro,
+                                      VINSN_INSN_RTX (has_dependence_data.con)))
+    {
+      ds_t *dsp = &has_dependence_data.has_dep_p[has_dependence_data.where];
+
+      *dsp = ds_full_merge (ds, *dsp, pending_mem, mem);
+    }
+}
+
+/* Note a dependence.  */
+static void
+has_dependence_note_dep (insn_t pro ATTRIBUTE_UNUSED,
+                        ds_t ds ATTRIBUTE_UNUSED)
+{
+  if (!sched_insns_conditions_mutex_p (has_dependence_data.pro,
+                                      VINSN_INSN_RTX (has_dependence_data.con)))
+    {
+      ds_t *dsp = &has_dependence_data.has_dep_p[has_dependence_data.where];
+
+      *dsp = ds_full_merge (ds, *dsp, NULL_RTX, NULL_RTX);
+    }
+}
+
+/* Mark the insn as having a hard dependence that prevents speculation.  */
+void
+sel_mark_hard_insn (rtx insn)
+{
+  int i;
+
+  /* Only work when we're in has_dependence_p mode.
+     ??? This is a hack, this should actually be a hook.  */
+  if (!has_dependence_data.dc || !has_dependence_data.pro)
+    return;
+
+  gcc_assert (insn == VINSN_INSN_RTX (has_dependence_data.con));
+  gcc_assert (has_dependence_data.where == DEPS_IN_INSN);
+
+  for (i = 0; i < DEPS_IN_NOWHERE; i++)
+    has_dependence_data.has_dep_p[i] &= ~SPECULATIVE;
+}
+
+/* This structure holds the hooks for the dependency analysis used when
+   actually processing dependencies in the scheduler.  */
+static struct sched_deps_info_def has_dependence_sched_deps_info;
+
+/* This initializes most of the fields of the above structure.  */
+static const struct sched_deps_info_def const_has_dependence_sched_deps_info =
+  {
+    NULL,
+
+    has_dependence_start_insn,
+    has_dependence_finish_insn,
+    has_dependence_start_lhs,
+    has_dependence_finish_lhs,
+    has_dependence_start_rhs,
+    has_dependence_finish_rhs,
+    has_dependence_note_reg_set,
+    has_dependence_note_reg_clobber,
+    has_dependence_note_reg_use,
+    has_dependence_note_mem_dep,
+    has_dependence_note_dep,
+
+    0, /* use_cselib */
+    0, /* use_deps_list */
+    0 /* generate_spec_deps */
+  };
+
+/* Initialize has_dependence_sched_deps_info with extra spec field.  */
+static void
+setup_has_dependence_sched_deps_info (void)
+{
+  memcpy (&has_dependence_sched_deps_info,
+         &const_has_dependence_sched_deps_info,
+         sizeof (has_dependence_sched_deps_info));
+
+  if (spec_info != NULL)
+    has_dependence_sched_deps_info.generate_spec_deps = 1;
+
+  sched_deps_info = &has_dependence_sched_deps_info;
+}
+
+/* Remove all dependences found and recorded in has_dependence_data array.  */
+void
+sel_clear_has_dependence (void)
+{
+  int i;
+
+  for (i = 0; i < DEPS_IN_NOWHERE; i++)
+    has_dependence_data.has_dep_p[i] = 0;
+}
+
+/* Return nonzero if EXPR has is dependent upon PRED.  Return the pointer
+   to the dependence information array in HAS_DEP_PP.  */
+ds_t
+has_dependence_p (expr_t expr, insn_t pred, ds_t **has_dep_pp)
+{
+  int i;
+  ds_t ds;
+  struct deps *dc;
+
+  if (INSN_SIMPLEJUMP_P (pred))
+    /* Unconditional jump is just a transfer of control flow.
+       Ignore it.  */
+    return false;
+
+  dc = &INSN_DEPS_CONTEXT (pred);
+  if (!dc->readonly)
+    {
+      has_dependence_data.pro = NULL;
+      /* Initialize empty dep context with information about PRED.  */
+      advance_deps_context (dc, pred);
+      dc->readonly = 1;
+    }
+
+  has_dependence_data.where = DEPS_IN_NOWHERE;
+  has_dependence_data.pro = pred;
+  has_dependence_data.con = EXPR_VINSN (expr);
+  has_dependence_data.dc = dc;
+
+  sel_clear_has_dependence ();
+
+  /* Now catch all dependencies that would be generated between PRED and
+     INSN.  */
+  setup_has_dependence_sched_deps_info ();
+  deps_analyze_insn (dc, EXPR_INSN_RTX (expr));
+  has_dependence_data.dc = NULL;
+
+  /* When a barrier was found, set DEPS_IN_INSN bits.  */
+  if (dc->last_reg_pending_barrier == TRUE_BARRIER)
+    has_dependence_data.has_dep_p[DEPS_IN_INSN] = DEP_TRUE;
+  else if (dc->last_reg_pending_barrier == MOVE_BARRIER)
+    has_dependence_data.has_dep_p[DEPS_IN_INSN] = DEP_ANTI;
+
+  /* Do not allow stores to memory to move through checks.  Currently
+     we don't move this to sched-deps.c as the check doesn't have
+     obvious places to which this dependence can be attached.  
+     FIMXE: this should go to a hook.  */
+  if (EXPR_LHS (expr)
+      && MEM_P (EXPR_LHS (expr))
+      && sel_insn_is_speculation_check (pred))
+    has_dependence_data.has_dep_p[DEPS_IN_INSN] = DEP_ANTI;
+  
+  *has_dep_pp = has_dependence_data.has_dep_p;
+  ds = 0;
+  for (i = 0; i < DEPS_IN_NOWHERE; i++)
+    ds = ds_full_merge (ds, has_dependence_data.has_dep_p[i],
+                       NULL_RTX, NULL_RTX);
+
+  return ds;
+}
+\f
+
+/* Dependence hooks implementation that checks dependence latency constraints 
+   on the insns being scheduled.  The entry point for these routines is 
+   tick_check_p predicate.  */ 
+
+static struct
+{
+  /* An expr we are currently checking.  */
+  expr_t expr;
+
+  /* A minimal cycle for its scheduling.  */
+  int cycle;
+
+  /* Whether we have seen a true dependence while checking.  */
+  bool seen_true_dep_p;
+} tick_check_data;
+
+/* Update minimal scheduling cycle for tick_check_insn given that it depends
+   on PRO with status DS and weight DW.  */
+static void
+tick_check_dep_with_dw (insn_t pro_insn, ds_t ds, dw_t dw)
+{
+  expr_t con_expr = tick_check_data.expr;
+  insn_t con_insn = EXPR_INSN_RTX (con_expr);
+
+  if (con_insn != pro_insn)
+    {
+      enum reg_note dt;
+      int tick;
+
+      if (/* PROducer was removed from above due to pipelining.  */
+         !INSN_IN_STREAM_P (pro_insn)
+         /* Or PROducer was originally on the next iteration regarding the
+            CONsumer.  */
+         || (INSN_SCHED_TIMES (pro_insn)
+             - EXPR_SCHED_TIMES (con_expr)) > 1)
+       /* Don't count this dependence.  */
+        return;
+
+      dt = ds_to_dt (ds);
+      if (dt == REG_DEP_TRUE)
+        tick_check_data.seen_true_dep_p = true;
+
+      gcc_assert (INSN_SCHED_CYCLE (pro_insn) > 0);
+
+      {
+       dep_def _dep, *dep = &_dep;
+
+       init_dep (dep, pro_insn, con_insn, dt);
+
+       tick = INSN_SCHED_CYCLE (pro_insn) + dep_cost_1 (dep, dw);
+      }
+
+      /* When there are several kinds of dependencies between pro and con,
+         only REG_DEP_TRUE should be taken into account.  */
+      if (tick > tick_check_data.cycle
+         && (dt == REG_DEP_TRUE || !tick_check_data.seen_true_dep_p))
+       tick_check_data.cycle = tick;
+    }
+}
+
+/* An implementation of note_dep hook.  */
+static void
+tick_check_note_dep (insn_t pro, ds_t ds)
+{
+  tick_check_dep_with_dw (pro, ds, 0);
+}
+
+/* An implementation of note_mem_dep hook.  */
+static void
+tick_check_note_mem_dep (rtx mem1, rtx mem2, insn_t pro, ds_t ds)
+{
+  dw_t dw;
+
+  dw = (ds_to_dt (ds) == REG_DEP_TRUE
+        ? estimate_dep_weak (mem1, mem2)
+        : 0);
+
+  tick_check_dep_with_dw (pro, ds, dw);
+}
+
+/* This structure contains hooks for dependence analysis used when determining
+   whether an insn is ready for scheduling.  */
+static struct sched_deps_info_def tick_check_sched_deps_info =
+  {
+    NULL,
+
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    haifa_note_reg_set,
+    haifa_note_reg_clobber,
+    haifa_note_reg_use,
+    tick_check_note_mem_dep,
+    tick_check_note_dep,
+
+    0, 0, 0
+  };
+
+/* Estimate number of cycles from the current cycle of FENCE until EXPR can be
+   scheduled.  Return 0 if all data from producers in DC is ready.  */
+int
+tick_check_p (expr_t expr, deps_t dc, fence_t fence)
+{
+  int cycles_left;
+  /* Initialize variables.  */
+  tick_check_data.expr = expr;
+  tick_check_data.cycle = 0;
+  tick_check_data.seen_true_dep_p = false;
+  sched_deps_info = &tick_check_sched_deps_info;
+  
+  gcc_assert (!dc->readonly);
+  dc->readonly = 1;
+  deps_analyze_insn (dc, EXPR_INSN_RTX (expr));
+  dc->readonly = 0;
+
+  cycles_left = tick_check_data.cycle - FENCE_CYCLE (fence);
+
+  return cycles_left >= 0 ? cycles_left : 0;
+}
+\f
+
+/* Functions to work with insns.  */
+
+/* Returns true if LHS of INSN is the same as DEST of an insn
+   being moved.  */
+bool
+lhs_of_insn_equals_to_dest_p (insn_t insn, rtx dest)
+{
+  rtx lhs = INSN_LHS (insn);
+
+  if (lhs == NULL || dest == NULL)
+    return false;
+  
+  return rtx_equal_p (lhs, dest);
+}
+
+/* Return s_i_d entry of INSN.  Callable from debugger.  */
+sel_insn_data_def
+insn_sid (insn_t insn)
+{
+  return *SID (insn);
+}
+
+/* True when INSN is a speculative check.  We can tell this by looking
+   at the data structures of the selective scheduler, not by examining
+   the pattern.  */
+bool
+sel_insn_is_speculation_check (rtx insn)
+{
+  return s_i_d && !! INSN_SPEC_CHECKED_DS (insn);
+}
+
+/* Extracts machine mode MODE and destination location DST_LOC 
+   for given INSN.  */
+void
+get_dest_and_mode (rtx insn, rtx *dst_loc, enum machine_mode *mode)
+{
+  rtx pat = PATTERN (insn);
+
+  gcc_assert (dst_loc);
+  gcc_assert (GET_CODE (pat) == SET);
+
+  *dst_loc = SET_DEST (pat);
+
+  gcc_assert (*dst_loc);
+  gcc_assert (MEM_P (*dst_loc) || REG_P (*dst_loc));
+
+  if (mode)
+    *mode = GET_MODE (*dst_loc);
+}
+
+/* Returns true when moving through JUMP will result in bookkeeping 
+   creation.  */
+bool
+bookkeeping_can_be_created_if_moved_through_p (insn_t jump)
+{
+  insn_t succ;
+  succ_iterator si;
+
+  FOR_EACH_SUCC (succ, si, jump)
+    if (sel_num_cfg_preds_gt_1 (succ))
+      return true;
+
+  return false;
+}
+
+/* Return 'true' if INSN is the only one in its basic block.  */
+static bool
+insn_is_the_only_one_in_bb_p (insn_t insn)
+{
+  return sel_bb_head_p (insn) && sel_bb_end_p (insn);
+}
+
+#ifdef ENABLE_CHECKING
+/* Check that the region we're scheduling still has at most one 
+   backedge.  */
+static void
+verify_backedges (void)
+{
+  if (pipelining_p)
+    {
+      int i, n = 0;
+      edge e;
+      edge_iterator ei;
+          
+      for (i = 0; i < current_nr_blocks; i++)
+        FOR_EACH_EDGE (e, ei, BASIC_BLOCK (BB_TO_BLOCK (i))->succs)
+          if (in_current_region_p (e->dest)
+              && BLOCK_TO_BB (e->dest->index) < i)
+            n++;
+          
+      gcc_assert (n <= 1);
+    }
+}
+#endif
+\f
+
+/* Functions to work with control flow.  */
+
+/* Tidy the possibly empty block BB.  */
+bool
+maybe_tidy_empty_bb (basic_block bb)
+{
+  basic_block succ_bb, pred_bb;
+  bool rescan_p;
+
+  /* Keep empty bb only if this block immediately precedes EXIT and
+     has incoming non-fallthrough edge.  Otherwise remove it.  */
+  if (!sel_bb_empty_p (bb) 
+      || (single_succ_p (bb) 
+          && single_succ (bb) == EXIT_BLOCK_PTR
+          && (!single_pred_p (bb) 
+              || !(single_pred_edge (bb)->flags & EDGE_FALLTHRU))))
+    return false;
+
+  free_data_sets (bb);
+
+  /* Do not delete BB if it has more than one successor.
+     That can occur when we moving a jump.  */
+  if (!single_succ_p (bb))
+    {
+      gcc_assert (can_merge_blocks_p (bb->prev_bb, bb));
+      sel_merge_blocks (bb->prev_bb, bb);
+      return true;
+    }
+
+  succ_bb = single_succ (bb);
+  rescan_p = true;
+  pred_bb = NULL;
+
+  /* Redirect all non-fallthru edges to the next bb.  */
+  while (rescan_p)
+    {
+      edge e;
+      edge_iterator ei;
+
+      rescan_p = false;
+
+      FOR_EACH_EDGE (e, ei, bb->preds)
+        {
+          pred_bb = e->src;
+
+          if (!(e->flags & EDGE_FALLTHRU))
+            {
+              sel_redirect_edge_and_branch (e, succ_bb);
+              rescan_p = true;
+              break;
+            }
+        }
+    }
+
+  /* If it is possible - merge BB with its predecessor.  */
+  if (can_merge_blocks_p (bb->prev_bb, bb))
+    sel_merge_blocks (bb->prev_bb, bb);
+  else
+    /* Otherwise this is a block without fallthru predecessor.
+       Just delete it.  */
+    {
+      gcc_assert (pred_bb != NULL);
+
+      move_bb_info (pred_bb, bb);
+      remove_empty_bb (bb, true);
+    }
+
+#ifdef ENABLE_CHECKING
+  verify_backedges ();
+#endif
+
+  return true;
+}
+
+/* Tidy the control flow after we have removed original insn from 
+   XBB.  Return true if we have removed some blocks.  When FULL_TIDYING
+   is true, also try to optimize control flow on non-empty blocks.  */
+bool
+tidy_control_flow (basic_block xbb, bool full_tidying)
+{
+  bool changed = true;
+  
+  /* First check whether XBB is empty.  */
+  changed = maybe_tidy_empty_bb (xbb);
+  if (changed || !full_tidying)
+    return changed;
+  
+  /* Check if there is a unnecessary jump after insn left.  */
+  if (jump_leads_only_to_bb_p (BB_END (xbb), xbb->next_bb)
+      && INSN_SCHED_TIMES (BB_END (xbb)) == 0
+      && !IN_CURRENT_FENCE_P (BB_END (xbb)))
+    {
+      if (sel_remove_insn (BB_END (xbb), false, false))
+        return true;
+      tidy_fallthru_edge (EDGE_SUCC (xbb, 0));
+    }
+
+  /* Check if there is an unnecessary jump in previous basic block leading
+     to next basic block left after removing INSN from stream.  
+     If it is so, remove that jump and redirect edge to current 
+     basic block (where there was INSN before deletion).  This way 
+     when NOP will be deleted several instructions later with its 
+     basic block we will not get a jump to next instruction, which 
+     can be harmful.  */
+  if (sel_bb_head (xbb) == sel_bb_end (xbb) 
+      && !sel_bb_empty_p (xbb)
+      && INSN_NOP_P (sel_bb_end (xbb))
+      /* Flow goes fallthru from current block to the next.  */
+      && EDGE_COUNT (xbb->succs) == 1
+      && (EDGE_SUCC (xbb, 0)->flags & EDGE_FALLTHRU)
+      /* When successor is an EXIT block, it may not be the next block.  */
+      && single_succ (xbb) != EXIT_BLOCK_PTR
+      /* And unconditional jump in previous basic block leads to
+         next basic block of XBB and this jump can be safely removed.  */
+      && in_current_region_p (xbb->prev_bb)
+      && jump_leads_only_to_bb_p (BB_END (xbb->prev_bb), xbb->next_bb)
+      && INSN_SCHED_TIMES (BB_END (xbb->prev_bb)) == 0
+      /* Also this jump is not at the scheduling boundary.  */
+      && !IN_CURRENT_FENCE_P (BB_END (xbb->prev_bb)))
+    {
+      /* Clear data structures of jump - jump itself will be removed
+         by sel_redirect_edge_and_branch.  */
+      clear_expr (INSN_EXPR (BB_END (xbb->prev_bb)));
+      sel_redirect_edge_and_branch (EDGE_SUCC (xbb->prev_bb, 0), xbb);
+      gcc_assert (EDGE_SUCC (xbb->prev_bb, 0)->flags & EDGE_FALLTHRU);
+
+      /* It can turn out that after removing unused jump, basic block
+         that contained that jump, becomes empty too.  In such case
+         remove it too.  */
+      if (sel_bb_empty_p (xbb->prev_bb))
+        changed = maybe_tidy_empty_bb (xbb->prev_bb);
+    }
+
+  return changed;
+}
+
+/* Rip-off INSN from the insn stream.  When ONLY_DISCONNECT is true, 
+   do not delete insn's data, because it will be later re-emitted.  
+   Return true if we have removed some blocks afterwards.  */
+bool
+sel_remove_insn (insn_t insn, bool only_disconnect, bool full_tidying)
+{
+  basic_block bb = BLOCK_FOR_INSN (insn);
+
+  gcc_assert (INSN_IN_STREAM_P (insn));
+
+  if (only_disconnect)
+    {
+      insn_t prev = PREV_INSN (insn);
+      insn_t next = NEXT_INSN (insn);
+      basic_block bb = BLOCK_FOR_INSN (insn);
+
+      NEXT_INSN (prev) = next;
+      PREV_INSN (next) = prev;
+
+      if (BB_HEAD (bb) == insn)
+        {
+          gcc_assert (BLOCK_FOR_INSN (prev) == bb);
+          BB_HEAD (bb) = prev;
+        }
+      if (BB_END (bb) == insn)
+        BB_END (bb) = prev;
+    }
+  else
+    {
+      remove_insn (insn);
+      clear_expr (INSN_EXPR (insn));
+    }
+
+  /* It is necessary to null this fields before calling add_insn ().  */
+  PREV_INSN (insn) = NULL_RTX;
+  NEXT_INSN (insn) = NULL_RTX;
+
+  return tidy_control_flow (bb, full_tidying);
+}
+
+/* Estimate number of the insns in BB.  */
+static int
+sel_estimate_number_of_insns (basic_block bb)
+{
+  int res = 0;
+  insn_t insn = NEXT_INSN (BB_HEAD (bb)), next_tail = NEXT_INSN (BB_END (bb));
+
+  for (; insn != next_tail; insn = NEXT_INSN (insn))
+    if (INSN_P (insn))
+      res++;
+
+  return res;
+}
+
+/* We don't need separate luids for notes or labels.  */
+static int
+sel_luid_for_non_insn (rtx x)
+{
+  gcc_assert (NOTE_P (x) || LABEL_P (x));
+
+  return -1;
+}
+
+/* Return seqno of the only predecessor of INSN.  */
+static int
+get_seqno_of_a_pred (insn_t insn)
+{
+  int seqno;
+
+  gcc_assert (INSN_SIMPLEJUMP_P (insn));
+
+  if (!sel_bb_head_p (insn))
+    seqno = INSN_SEQNO (PREV_INSN (insn));
+  else
+    {
+      basic_block bb = BLOCK_FOR_INSN (insn);
+
+      if (single_pred_p (bb)
+         && !in_current_region_p (single_pred (bb)))
+       {
+          /* We can have preds outside a region when splitting edges
+             for pipelining of an outer loop.  Use succ instead.  
+             There should be only one of them.  */
+         insn_t succ = NULL;
+          succ_iterator si;
+          bool first = true;
+          
+         gcc_assert (flag_sel_sched_pipelining_outer_loops
+                     && current_loop_nest);
+          FOR_EACH_SUCC_1 (succ, si, insn, 
+                           SUCCS_NORMAL | SUCCS_SKIP_TO_LOOP_EXITS)
+            {
+              gcc_assert (first);
+              first = false;
+            }
+
+         gcc_assert (succ != NULL);
+         seqno = INSN_SEQNO (succ);
+       }
+      else
+       {
+         insn_t *preds;
+         int n;
+
+         cfg_preds (BLOCK_FOR_INSN (insn), &preds, &n);
+         gcc_assert (n == 1);
+
+         seqno = INSN_SEQNO (preds[0]);
+              
+         free (preds);
+       }
+    }
+
+  return seqno;
+}
+
+/*  Find the proper seqno for inserting at INSN.  */
+int
+get_seqno_by_preds (rtx insn)
+{
+  basic_block bb = BLOCK_FOR_INSN (insn);
+  rtx tmp = insn, head = BB_HEAD (bb);
+  insn_t *preds;
+  int n, i, seqno;
+
+  while (tmp != head)
+    if (INSN_P (tmp))
+      return INSN_SEQNO (tmp);
+    else
+      tmp = PREV_INSN (tmp);
+  
+  cfg_preds (bb, &preds, &n);
+  for (i = 0, seqno = -1; i < n; i++)
+    seqno = MAX (seqno, INSN_SEQNO (preds[i]));
+
+  gcc_assert (seqno > 0);
+  return seqno;
+}
+
+\f
+
+/* Extend pass-scope data structures for basic blocks.  */
+void
+sel_extend_global_bb_info (void)
+{
+  VEC_safe_grow_cleared (sel_global_bb_info_def, heap, sel_global_bb_info,
+                        last_basic_block);
+}
+
+/* Extend region-scope data structures for basic blocks.  */
+static void
+extend_region_bb_info (void)
+{
+  VEC_safe_grow_cleared (sel_region_bb_info_def, heap, sel_region_bb_info,
+                        last_basic_block);
+}
+
+/* Extend all data structures to fit for all basic blocks.  */
+static void
+extend_bb_info (void)
+{
+  sel_extend_global_bb_info ();
+  extend_region_bb_info ();
+}
+
+/* Finalize pass-scope data structures for basic blocks.  */
+void
+sel_finish_global_bb_info (void)
+{
+  VEC_free (sel_global_bb_info_def, heap, sel_global_bb_info);
+}
+
+/* Finalize region-scope data structures for basic blocks.  */
+static void
+finish_region_bb_info (void)
+{
+  VEC_free (sel_region_bb_info_def, heap, sel_region_bb_info);
+}
+\f
+
+/* Data for each insn in current region.  */
+VEC (sel_insn_data_def, heap) *s_i_d = NULL;
+
+/* A vector for the insns we've emitted.  */
+static insn_vec_t new_insns = NULL;
+
+/* Extend data structures for insns from current region.  */
+static void
+extend_insn_data (void)
+{
+  int reserve;
+  
+  sched_extend_target ();
+  sched_deps_init (false);
+
+  /* Extend data structures for insns from current region.  */
+  reserve = (sched_max_luid + 1 
+             - VEC_length (sel_insn_data_def, s_i_d));
+  if (reserve > 0 
+      && ! VEC_space (sel_insn_data_def, s_i_d, reserve))
+    VEC_safe_grow_cleared (sel_insn_data_def, heap, s_i_d,
+                           3 * sched_max_luid / 2);
+}
+
+/* Finalize data structures for insns from current region.  */
+static void
+finish_insns (void)
+{
+  unsigned i;
+
+  /* Clear here all dependence contexts that may have left from insns that were
+     removed during the scheduling.  */
+  for (i = 0; i < VEC_length (sel_insn_data_def, s_i_d); i++)
+    {
+      sel_insn_data_def *sid_entry = VEC_index (sel_insn_data_def, s_i_d, i);
+      
+      if (sid_entry->live)
+        return_regset_to_pool (sid_entry->live);
+      if (sid_entry->analyzed_deps)
+       {
+         BITMAP_FREE (sid_entry->analyzed_deps);
+         BITMAP_FREE (sid_entry->found_deps);
+          htab_delete (sid_entry->transformed_insns);
+         free_deps (&sid_entry->deps_context);
+       }
+      if (EXPR_VINSN (&sid_entry->expr))
+        {
+          clear_expr (&sid_entry->expr);
+          
+          /* Also, clear CANT_MOVE bit here, because we really don't want it
+             to be passed to the next region.  */
+          CANT_MOVE_BY_LUID (i) = 0;
+        }
+    }
+  
+  VEC_free (sel_insn_data_def, heap, s_i_d);
+}
+
+/* A proxy to pass initialization data to init_insn ().  */
+static sel_insn_data_def _insn_init_ssid;
+static sel_insn_data_t insn_init_ssid = &_insn_init_ssid;
+
+/* If true create a new vinsn.  Otherwise use the one from EXPR.  */
+static bool insn_init_create_new_vinsn_p;
+
+/* Set all necessary data for initialization of the new insn[s].  */
+static expr_t
+set_insn_init (expr_t expr, vinsn_t vi, int seqno)
+{
+  expr_t x = &insn_init_ssid->expr;
+
+  copy_expr_onside (x, expr);
+  if (vi != NULL)
+    {
+      insn_init_create_new_vinsn_p = false;
+      change_vinsn_in_expr (x, vi);
+    }
+  else
+    insn_init_create_new_vinsn_p = true;
+
+  insn_init_ssid->seqno = seqno;
+  return x;
+}
+
+/* Init data for INSN.  */
+static void
+init_insn_data (insn_t insn)
+{
+  expr_t expr;
+  sel_insn_data_t ssid = insn_init_ssid;
+
+  /* The fields mentioned below are special and hence are not being
+     propagated to the new insns.  */
+  gcc_assert (!ssid->asm_p && ssid->sched_next == NULL
+             && !ssid->after_stall_p && ssid->sched_cycle == 0);
+  gcc_assert (INSN_P (insn) && INSN_LUID (insn) > 0);
+
+  expr = INSN_EXPR (insn);
+  copy_expr (expr, &ssid->expr);
+  prepare_insn_expr (insn, ssid->seqno);
+
+  if (insn_init_create_new_vinsn_p)
+    change_vinsn_in_expr (expr, vinsn_create (insn, init_insn_force_unique_p));
+  
+  if (first_time_insn_init (insn))
+    init_first_time_insn_data (insn);
+}
+
+/* This is used to initialize spurious jumps generated by
+   sel_redirect_edge ().  */
+static void
+init_simplejump_data (insn_t insn)
+{
+  init_expr (INSN_EXPR (insn), vinsn_create (insn, false), 0,
+            REG_BR_PROB_BASE, 0, 0, 0, 0, 0, 0, NULL, true, false, false, 
+            false, true);
+  INSN_SEQNO (insn) = get_seqno_of_a_pred (insn);
+  init_first_time_insn_data (insn);
+}
+
+/* Perform deferred initialization of insns.  This is used to process 
+   a new jump that may be created by redirect_edge.  */
+void
+sel_init_new_insn (insn_t insn, int flags)
+{
+  /* We create data structures for bb when the first insn is emitted in it.  */
+  if (INSN_P (insn)
+      && INSN_IN_STREAM_P (insn)
+      && insn_is_the_only_one_in_bb_p (insn))
+    {
+      extend_bb_info ();
+      create_initial_data_sets (BLOCK_FOR_INSN (insn));
+    }
+  
+  if (flags & INSN_INIT_TODO_LUID)
+    sched_init_luids (NULL, NULL, NULL, insn);
+
+  if (flags & INSN_INIT_TODO_SSID)
+    {
+      extend_insn_data ();
+      init_insn_data (insn);
+      clear_expr (&insn_init_ssid->expr);
+    }
+
+  if (flags & INSN_INIT_TODO_SIMPLEJUMP)
+    {
+      extend_insn_data ();
+      init_simplejump_data (insn);
+    }
+  
+  gcc_assert (CONTAINING_RGN (BLOCK_NUM (insn))
+              == CONTAINING_RGN (BB_TO_BLOCK (0)));
+}
+\f
+
+/* Functions to init/finish work with lv sets.  */
+
+/* Init BB_LV_SET of BB from DF_LR_IN set of BB.  */
+static void
+init_lv_set (basic_block bb)
+{
+  gcc_assert (!BB_LV_SET_VALID_P (bb));
+
+  BB_LV_SET (bb) = get_regset_from_pool ();
+  COPY_REG_SET (BB_LV_SET (bb), DF_LR_IN (bb)); 
+  BB_LV_SET_VALID_P (bb) = true;
+}
+
+/* Copy liveness information to BB from FROM_BB.  */
+static void
+copy_lv_set_from (basic_block bb, basic_block from_bb)
+{
+  gcc_assert (!BB_LV_SET_VALID_P (bb));
+  
+  COPY_REG_SET (BB_LV_SET (bb), BB_LV_SET (from_bb));
+  BB_LV_SET_VALID_P (bb) = true;
+}                
+
+/* Initialize lv set of all bb headers.  */
+void
+init_lv_sets (void)
+{
+  basic_block bb;
+
+  /* Initialize of LV sets.  */
+  FOR_EACH_BB (bb)
+    init_lv_set (bb);
+
+  /* Don't forget EXIT_BLOCK.  */
+  init_lv_set (EXIT_BLOCK_PTR);
+}
+
+/* Release lv set of HEAD.  */
+static void
+free_lv_set (basic_block bb)
+{
+  gcc_assert (BB_LV_SET (bb) != NULL);
+
+  return_regset_to_pool (BB_LV_SET (bb));
+  BB_LV_SET (bb) = NULL;
+  BB_LV_SET_VALID_P (bb) = false;
+}
+
+/* Finalize lv sets of all bb headers.  */
+void
+free_lv_sets (void)
+{
+  basic_block bb;
+
+  /* Don't forget EXIT_BLOCK.  */
+  free_lv_set (EXIT_BLOCK_PTR);
+
+  /* Free LV sets.  */
+  FOR_EACH_BB (bb)
+    if (BB_LV_SET (bb))
+      free_lv_set (bb);
+}
+
+/* Initialize an invalid AV_SET for BB.
+   This set will be updated next time compute_av () process BB.  */
+static void
+invalidate_av_set (basic_block bb)
+{
+  gcc_assert (BB_AV_LEVEL (bb) <= 0
+             && BB_AV_SET (bb) == NULL);
+
+  BB_AV_LEVEL (bb) = -1;
+}
+
+/* Create initial data sets for BB (they will be invalid).  */
+static void
+create_initial_data_sets (basic_block bb)
+{
+  if (BB_LV_SET (bb))
+    BB_LV_SET_VALID_P (bb) = false;
+  else
+    BB_LV_SET (bb) = get_regset_from_pool ();
+  invalidate_av_set (bb);
+}
+
+/* Free av set of BB.  */
+static void
+free_av_set (basic_block bb)
+{
+  av_set_clear (&BB_AV_SET (bb));
+  BB_AV_LEVEL (bb) = 0;
+}
+
+/* Free data sets of BB.  */
+void
+free_data_sets (basic_block bb)
+{
+  free_lv_set (bb);
+  free_av_set (bb);
+}
+
+/* Exchange lv sets of TO and FROM.  */
+static void
+exchange_lv_sets (basic_block to, basic_block from)
+{
+  {
+    regset to_lv_set = BB_LV_SET (to);
+
+    BB_LV_SET (to) = BB_LV_SET (from);
+    BB_LV_SET (from) = to_lv_set;
+  }
+
+  {
+    bool to_lv_set_valid_p = BB_LV_SET_VALID_P (to);
+
+    BB_LV_SET_VALID_P (to) = BB_LV_SET_VALID_P (from);
+    BB_LV_SET_VALID_P (from) = to_lv_set_valid_p;
+  }
+}
+
+
+/* Exchange av sets of TO and FROM.  */
+static void
+exchange_av_sets (basic_block to, basic_block from)
+{
+  {
+    av_set_t to_av_set = BB_AV_SET (to);
+
+    BB_AV_SET (to) = BB_AV_SET (from);
+    BB_AV_SET (from) = to_av_set;
+  }
+
+  {
+    int to_av_level = BB_AV_LEVEL (to);
+
+    BB_AV_LEVEL (to) = BB_AV_LEVEL (from);
+    BB_AV_LEVEL (from) = to_av_level;
+  }
+}
+
+/* Exchange data sets of TO and FROM.  */
+void
+exchange_data_sets (basic_block to, basic_block from)
+{
+  exchange_lv_sets (to, from);
+  exchange_av_sets (to, from);
+}
+
+/* Copy data sets of FROM to TO.  */
+void
+copy_data_sets (basic_block to, basic_block from)
+{
+  gcc_assert (!BB_LV_SET_VALID_P (to) && !BB_AV_SET_VALID_P (to));
+  gcc_assert (BB_AV_SET (to) == NULL);
+
+  BB_AV_LEVEL (to) = BB_AV_LEVEL (from);
+  BB_LV_SET_VALID_P (to) = BB_LV_SET_VALID_P (from);
+
+  if (BB_AV_SET_VALID_P (from))
+    {
+      BB_AV_SET (to) = av_set_copy (BB_AV_SET (from));
+    }
+  if (BB_LV_SET_VALID_P (from))
+    {
+      gcc_assert (BB_LV_SET (to) != NULL);
+      COPY_REG_SET (BB_LV_SET (to), BB_LV_SET (from));
+    }
+}
+
+/* Return an av set for INSN, if any.  */
+av_set_t
+get_av_set (insn_t insn)
+{
+  av_set_t av_set;
+
+  gcc_assert (AV_SET_VALID_P (insn));
+
+  if (sel_bb_head_p (insn))
+    av_set = BB_AV_SET (BLOCK_FOR_INSN (insn));
+  else
+    av_set = NULL;
+
+  return av_set;
+}
+
+/* Implementation of AV_LEVEL () macro.  Return AV_LEVEL () of INSN.  */
+int
+get_av_level (insn_t insn)
+{
+  int av_level;
+
+  gcc_assert (INSN_P (insn));
+
+  if (sel_bb_head_p (insn))
+    av_level = BB_AV_LEVEL (BLOCK_FOR_INSN (insn));
+  else
+    av_level = INSN_WS_LEVEL (insn);
+
+  return av_level;
+}
+
+\f
+
+/* Variables to work with control-flow graph.  */
+
+/* The basic block that already has been processed by the sched_data_update (),
+   but hasn't been in sel_add_bb () yet.  */
+static VEC (basic_block, heap) *last_added_blocks = NULL;
+
+/* A pool for allocating successor infos.  */
+static struct
+{
+  /* A stack for saving succs_info structures.  */
+  struct succs_info *stack;
+
+  /* Its size.  */
+  int size;
+
+  /* Top of the stack.  */
+  int top;
+
+  /* Maximal value of the top.  */
+  int max_top;
+}  succs_info_pool;
+
+/* Functions to work with control-flow graph.  */
+
+/* Return basic block note of BB.  */
+insn_t
+sel_bb_head (basic_block bb)
+{
+  insn_t head;
+
+  if (bb == EXIT_BLOCK_PTR)
+    {
+      gcc_assert (exit_insn != NULL_RTX);
+      head = exit_insn;
+    }
+  else
+    {
+      insn_t note;
+
+      note = bb_note (bb);
+      head = next_nonnote_insn (note);
+
+      if (head && BLOCK_FOR_INSN (head) != bb)
+       head = NULL_RTX;
+    }
+
+  return head;
+}
+
+/* Return true if INSN is a basic block header.  */
+bool
+sel_bb_head_p (insn_t insn)
+{
+  return sel_bb_head (BLOCK_FOR_INSN (insn)) == insn;
+}
+
+/* Return last insn of BB.  */
+insn_t
+sel_bb_end (basic_block bb)
+{
+  if (sel_bb_empty_p (bb))
+    return NULL_RTX;
+
+  gcc_assert (bb != EXIT_BLOCK_PTR);
+
+  return BB_END (bb);
+}
+
+/* Return true if INSN is the last insn in its basic block.  */
+bool
+sel_bb_end_p (insn_t insn)
+{
+  return insn == sel_bb_end (BLOCK_FOR_INSN (insn));
+}
+
+/* Return true if BB consist of single NOTE_INSN_BASIC_BLOCK.  */
+bool
+sel_bb_empty_p (basic_block bb)
+{
+  return sel_bb_head (bb) == NULL;
+}
+
+/* True when BB belongs to the current scheduling region.  */
+bool
+in_current_region_p (basic_block bb)
+{
+  if (bb->index < NUM_FIXED_BLOCKS)
+    return false;
+
+  return CONTAINING_RGN (bb->index) == CONTAINING_RGN (BB_TO_BLOCK (0));
+}
+
+/* Return the block which is a fallthru bb of a conditional jump JUMP.  */
+basic_block
+fallthru_bb_of_jump (rtx jump)
+{
+  if (!JUMP_P (jump))
+    return NULL;
+
+  if (any_uncondjump_p (jump))
+    return single_succ (BLOCK_FOR_INSN (jump));
+
+  if (!any_condjump_p (jump))
+    return NULL;
+
+  return FALLTHRU_EDGE (BLOCK_FOR_INSN (jump))->dest;
+}
+
+/* Remove all notes from BB.  */
+static void
+init_bb (basic_block bb)
+{
+  remove_notes (bb_note (bb), BB_END (bb));
+  BB_NOTE_LIST (bb) = note_list;
+}
+
+void
+sel_init_bbs (bb_vec_t bbs, basic_block bb)
+{
+  const struct sched_scan_info_def ssi =
+    {
+      extend_bb_info, /* extend_bb */
+      init_bb, /* init_bb */
+      NULL, /* extend_insn */
+      NULL /* init_insn */
+    };
+
+  sched_scan (&ssi, bbs, bb, new_insns, NULL);
+}
+
+/* Restore other notes for the whole region.  */
+static void
+sel_restore_other_notes (void)
+{
+  int bb;
+
+  for (bb = 0; bb < current_nr_blocks; bb++)
+    {
+      basic_block first, last;
+
+      first = EBB_FIRST_BB (bb);
+      last = EBB_LAST_BB (bb)->next_bb;
+
+      do
+       {
+         note_list = BB_NOTE_LIST (first);
+         restore_other_notes (NULL, first);
+         BB_NOTE_LIST (first) = NULL_RTX;
+
+          first = first->next_bb;
+       }
+      while (first != last);
+    }
+}
+
+/* Free per-bb data structures.  */
+void
+sel_finish_bbs (void)
+{
+  sel_restore_other_notes ();
+
+  /* Remove current loop preheader from this loop.  */
+  if (current_loop_nest)
+    sel_remove_loop_preheader ();
+
+  finish_region_bb_info ();
+}
+
+/* Return true if INSN has a single successor of type FLAGS.  */
+bool
+sel_insn_has_single_succ_p (insn_t insn, int flags)
+{
+  insn_t succ;
+  succ_iterator si;
+  bool first_p = true;
+
+  FOR_EACH_SUCC_1 (succ, si, insn, flags)
+    {
+      if (first_p)
+       first_p = false;
+      else
+       return false;
+    }
+
+  return true;
+}
+
+/* Allocate successor's info.  */
+static struct succs_info *
+alloc_succs_info (void)
+{
+  if (succs_info_pool.top == succs_info_pool.max_top)
+    {
+      int i;
+      
+      if (++succs_info_pool.max_top >= succs_info_pool.size)
+        gcc_unreachable ();
+
+      i = ++succs_info_pool.top;
+      succs_info_pool.stack[i].succs_ok = VEC_alloc (rtx, heap, 10);
+      succs_info_pool.stack[i].succs_other = VEC_alloc (rtx, heap, 10);
+      succs_info_pool.stack[i].probs_ok = VEC_alloc (int, heap, 10);
+    }
+  else
+    succs_info_pool.top++;
+
+  return &succs_info_pool.stack[succs_info_pool.top];
+}
+
+/* Free successor's info.  */
+void
+free_succs_info (struct succs_info * sinfo)
+{
+  gcc_assert (succs_info_pool.top >= 0 
+              && &succs_info_pool.stack[succs_info_pool.top] == sinfo);
+  succs_info_pool.top--;
+
+  /* Clear stale info.  */
+  VEC_block_remove (rtx, sinfo->succs_ok, 
+                    0, VEC_length (rtx, sinfo->succs_ok));
+  VEC_block_remove (rtx, sinfo->succs_other, 
+                    0, VEC_length (rtx, sinfo->succs_other));
+  VEC_block_remove (int, sinfo->probs_ok, 
+                    0, VEC_length (int, sinfo->probs_ok));
+  sinfo->all_prob = 0;
+  sinfo->succs_ok_n = 0;
+  sinfo->all_succs_n = 0;
+}
+
+/* Compute successor info for INSN.  FLAGS are the flags passed 
+   to the FOR_EACH_SUCC_1 iterator.  */
+struct succs_info *
+compute_succs_info (insn_t insn, short flags)
+{
+  succ_iterator si;
+  insn_t succ;
+  struct succs_info *sinfo = alloc_succs_info ();
+
+  /* Traverse *all* successors and decide what to do with each.  */
+  FOR_EACH_SUCC_1 (succ, si, insn, SUCCS_ALL)
+    {
+      /* FIXME: this doesn't work for skipping to loop exits, as we don't
+         perform code motion through inner loops.  */
+      short current_flags = si.current_flags & ~SUCCS_SKIP_TO_LOOP_EXITS;
+
+      if (current_flags & flags)
+        {
+          VEC_safe_push (rtx, heap, sinfo->succs_ok, succ);
+          VEC_safe_push (int, heap, sinfo->probs_ok,
+                         /* FIXME: Improve calculation when skipping 
+                            inner loop to exits.  */
+                         (si.bb_end 
+                          ? si.e1->probability 
+                          : REG_BR_PROB_BASE));
+          sinfo->succs_ok_n++;
+        }
+      else
+        VEC_safe_push (rtx, heap, sinfo->succs_other, succ);
+
+      /* Compute all_prob.  */
+      if (!si.bb_end)
+        sinfo->all_prob = REG_BR_PROB_BASE;
+      else
+        sinfo->all_prob += si.e1->probability;
+
+      sinfo->all_succs_n++;
+    }
+
+  return sinfo;
+}
+
+/* Return the predecessors of BB in PREDS and their number in N. 
+   Empty blocks are skipped.  SIZE is used to allocate PREDS.  */
+static void
+cfg_preds_1 (basic_block bb, insn_t **preds, int *n, int *size)
+{
+  edge e;
+  edge_iterator ei;
+
+  gcc_assert (BLOCK_TO_BB (bb->index) != 0);
+
+  FOR_EACH_EDGE (e, ei, bb->preds)
+    {
+      basic_block pred_bb = e->src;
+      insn_t bb_end = BB_END (pred_bb);
+
+      /* ??? This code is not supposed to walk out of a region.  */
+      gcc_assert (in_current_region_p (pred_bb));
+
+      if (sel_bb_empty_p (pred_bb))
+       cfg_preds_1 (pred_bb, preds, n, size);
+      else
+       {
+         if (*n == *size)
+           *preds = XRESIZEVEC (insn_t, *preds, 
+                                 (*size = 2 * *size + 1));
+         (*preds)[(*n)++] = bb_end;
+       }
+    }
+
+  gcc_assert (*n != 0);
+}
+
+/* Find all predecessors of BB and record them in PREDS and their number 
+   in N.  Empty blocks are skipped, and only normal (forward in-region) 
+   edges are processed.  */
+static void
+cfg_preds (basic_block bb, insn_t **preds, int *n)
+{
+  int size = 0;
+
+  *preds = NULL;
+  *n = 0;
+  cfg_preds_1 (bb, preds, n, &size);
+}
+
+/* Returns true if we are moving INSN through join point.  */
+bool
+sel_num_cfg_preds_gt_1 (insn_t insn)
+{
+  basic_block bb;
+
+  if (!sel_bb_head_p (insn) || INSN_BB (insn) == 0)
+    return false;
+
+  bb = BLOCK_FOR_INSN (insn);
+
+  while (1)
+    {
+      if (EDGE_COUNT (bb->preds) > 1)
+       return true;
+
+      gcc_assert (EDGE_PRED (bb, 0)->dest == bb);
+      bb = EDGE_PRED (bb, 0)->src;
+
+      if (!sel_bb_empty_p (bb))
+       break;
+    }
+
+  return false;
+}
+
+/* Returns true when BB should be the end of an ebb.  Adapted from the 
+   code in sched-ebb.c.  */
+bool
+bb_ends_ebb_p (basic_block bb)
+{
+  basic_block next_bb = bb_next_bb (bb);
+  edge e;
+  edge_iterator ei;
+  
+  if (next_bb == EXIT_BLOCK_PTR
+      || bitmap_bit_p (forced_ebb_heads, next_bb->index)
+      || (LABEL_P (BB_HEAD (next_bb))
+         /* NB: LABEL_NUSES () is not maintained outside of jump.c.
+            Work around that.  */
+         && !single_pred_p (next_bb)))
+    return true;
+
+  if (!in_current_region_p (next_bb))
+    return true;
+
+  FOR_EACH_EDGE (e, ei, bb->succs)
+    if ((e->flags & EDGE_FALLTHRU) != 0)
+      {
+       gcc_assert (e->dest == next_bb);
+
+       return false;
+      }
+
+  return true;
+}
+
+/* Returns true when INSN and SUCC are in the same EBB, given that SUCC is a
+   successor of INSN.  */
+bool
+in_same_ebb_p (insn_t insn, insn_t succ)
+{
+  basic_block ptr = BLOCK_FOR_INSN (insn);
+
+  for(;;)
+    {
+      if (ptr == BLOCK_FOR_INSN (succ))
+        return true;
+    
+      if (bb_ends_ebb_p (ptr))
+        return false;
+
+      ptr = bb_next_bb (ptr);
+    }
+
+  gcc_unreachable ();
+  return false;
+}
+
+/* Recomputes the reverse topological order for the function and
+   saves it in REV_TOP_ORDER_INDEX.  REV_TOP_ORDER_INDEX_LEN is also
+   modified appropriately.  */
+static void
+recompute_rev_top_order (void)
+{
+  int *postorder;
+  int n_blocks, i;
+
+  if (!rev_top_order_index || rev_top_order_index_len < last_basic_block)
+    {
+      rev_top_order_index_len = last_basic_block; 
+      rev_top_order_index = XRESIZEVEC (int, rev_top_order_index,
+                                        rev_top_order_index_len);
+    }
+
+  postorder = XNEWVEC (int, n_basic_blocks);
+
+  n_blocks = post_order_compute (postorder, true, false);
+  gcc_assert (n_basic_blocks == n_blocks);
+
+  /* Build reverse function: for each basic block with BB->INDEX == K
+     rev_top_order_index[K] is it's reverse topological sort number.  */
+  for (i = 0; i < n_blocks; i++)
+    {
+      gcc_assert (postorder[i] < rev_top_order_index_len);
+      rev_top_order_index[postorder[i]] = i;
+    }
+
+  free (postorder);
+}
+
+/* Clear all flags from insns in BB that could spoil its rescheduling.  */
+void
+clear_outdated_rtx_info (basic_block bb)
+{
+  rtx insn;
+
+  FOR_BB_INSNS (bb, insn)
+    if (INSN_P (insn))
+      {
+       SCHED_GROUP_P (insn) = 0;
+       INSN_AFTER_STALL_P (insn) = 0;
+       INSN_SCHED_TIMES (insn) = 0;
+       EXPR_PRIORITY_ADJ (INSN_EXPR (insn)) = 0;
+
+        /* We cannot use the changed caches, as previously we could ignore
+           the LHS dependence due to enabled renaming and transform 
+           the expression, and currently we'll be unable to do this.  */
+        htab_empty (INSN_TRANSFORMED_INSNS (insn));
+      }
+}
+
+/* Add BB_NOTE to the pool of available basic block notes.  */
+static void
+return_bb_to_pool (basic_block bb)
+{
+  rtx note = bb_note (bb);
+
+  gcc_assert (NOTE_BASIC_BLOCK (note) == bb
+             && bb->aux == NULL);
+
+  /* It turns out that current cfg infrastructure does not support
+     reuse of basic blocks.  Don't bother for now.  */
+  /*VEC_safe_push (rtx, heap, bb_note_pool, note);*/
+}
+
+/* Get a bb_note from pool or return NULL_RTX if pool is empty.  */
+static rtx
+get_bb_note_from_pool (void)
+{
+  if (VEC_empty (rtx, bb_note_pool))
+    return NULL_RTX;
+  else
+    {
+      rtx note = VEC_pop (rtx, bb_note_pool);
+
+      PREV_INSN (note) = NULL_RTX;
+      NEXT_INSN (note) = NULL_RTX;
+
+      return note;
+    }
+}
+
+/* Free bb_note_pool.  */
+void
+free_bb_note_pool (void)
+{
+  VEC_free (rtx, heap, bb_note_pool);
+}
+
+/* Setup scheduler pool and successor structure.  */
+void
+alloc_sched_pools (void)
+{
+  int succs_size;
+
+  succs_size = MAX_WS + 1;
+  succs_info_pool.stack = XCNEWVEC (struct succs_info, succs_size); 
+  succs_info_pool.size = succs_size;
+  succs_info_pool.top = -1;
+  succs_info_pool.max_top = -1;
+
+  sched_lists_pool = create_alloc_pool ("sel-sched-lists", 
+                                        sizeof (struct _list_node), 500);
+}
+
+/* Free the pools.  */
+void
+free_sched_pools (void)
+{
+  int i;
+  
+  free_alloc_pool (sched_lists_pool);
+  gcc_assert (succs_info_pool.top == -1);
+  for (i = 0; i < succs_info_pool.max_top; i++)
+    {
+      VEC_free (rtx, heap, succs_info_pool.stack[i].succs_ok);
+      VEC_free (rtx, heap, succs_info_pool.stack[i].succs_other);
+      VEC_free (int, heap, succs_info_pool.stack[i].probs_ok);
+    }
+  free (succs_info_pool.stack);
+}
+\f
+
+/* Returns a position in RGN where BB can be inserted retaining 
+   topological order.  */
+static int
+find_place_to_insert_bb (basic_block bb, int rgn)
+{
+  bool has_preds_outside_rgn = false;
+  edge e;
+  edge_iterator ei;
+  
+  /* Find whether we have preds outside the region.  */
+  FOR_EACH_EDGE (e, ei, bb->preds)
+    if (!in_current_region_p (e->src))
+      {
+        has_preds_outside_rgn = true;
+        break;
+      }
+  
+  /* Recompute the top order -- needed when we have > 1 pred
+     and in case we don't have preds outside.  */
+  if (flag_sel_sched_pipelining_outer_loops
+      && (has_preds_outside_rgn || EDGE_COUNT (bb->preds) > 1))
+    {
+      int i, bbi = bb->index, cur_bbi;
+
+      recompute_rev_top_order ();
+      for (i = RGN_NR_BLOCKS (rgn) - 1; i >= 0; i--)
+        {
+          cur_bbi = BB_TO_BLOCK (i);
+          if (rev_top_order_index[bbi] 
+              < rev_top_order_index[cur_bbi])
+            break;
+        }
+              
+      /* We skipped the right block, so we increase i.  We accomodate
+         it for increasing by step later, so we decrease i.  */
+      return (i + 1) - 1;
+    }
+  else if (has_preds_outside_rgn)
+    {
+      /* This is the case when we generate an extra empty block
+         to serve as region head during pipelining.  */
+      e = EDGE_SUCC (bb, 0);
+      gcc_assert (EDGE_COUNT (bb->succs) == 1
+                  && in_current_region_p (EDGE_SUCC (bb, 0)->dest)
+                  && (BLOCK_TO_BB (e->dest->index) == 0));
+      return -1;
+    }
+
+  /* We don't have preds outside the region.  We should have
+     the only pred, because the multiple preds case comes from
+     the pipelining of outer loops, and that is handled above.
+     Just take the bbi of this single pred.  */
+  if (EDGE_COUNT (bb->succs) > 0)
+    {
+      int pred_bbi;
+          
+      gcc_assert (EDGE_COUNT (bb->preds) == 1);
+          
+      pred_bbi = EDGE_PRED (bb, 0)->src->index;
+      return BLOCK_TO_BB (pred_bbi);
+    }
+  else
+    /* BB has no successors.  It is safe to put it in the end.  */
+    return current_nr_blocks - 1;
+}
+
+/* Deletes an empty basic block freeing its data.  */
+static void
+delete_and_free_basic_block (basic_block bb)
+{
+  gcc_assert (sel_bb_empty_p (bb));
+
+  if (BB_LV_SET (bb))
+    free_lv_set (bb);
+
+  bitmap_clear_bit (blocks_to_reschedule, bb->index);
+
+  /* Can't assert av_set properties because we use sel_aremove_bb 
+     when removing loop preheader from the region.  At the point of 
+     removing the preheader we already have deallocated sel_region_bb_info.  */
+  gcc_assert (BB_LV_SET (bb) == NULL
+              && !BB_LV_SET_VALID_P (bb)
+              && BB_AV_LEVEL (bb) == 0
+              && BB_AV_SET (bb) == NULL);
+  
+  delete_basic_block (bb);
+}
+
+/* Add BB to the current region and update the region data.  */
+static void
+add_block_to_current_region (basic_block bb)
+{
+  int i, pos, bbi = -2, rgn;
+
+  rgn = CONTAINING_RGN (BB_TO_BLOCK (0));
+  bbi = find_place_to_insert_bb (bb, rgn);
+  bbi += 1;
+  pos = RGN_BLOCKS (rgn) + bbi;
+
+  gcc_assert (RGN_HAS_REAL_EBB (rgn) == 0
+              && ebb_head[bbi] == pos);
+  
+  /* Make a place for the new block.  */
+  extend_regions ();
+
+  for (i = RGN_BLOCKS (rgn + 1) - 1; i >= pos; i--)
+    BLOCK_TO_BB (rgn_bb_table[i])++;
+  
+  memmove (rgn_bb_table + pos + 1,
+           rgn_bb_table + pos,
+           (RGN_BLOCKS (nr_regions) - pos) * sizeof (*rgn_bb_table));
+
+  /* Initialize data for BB.  */
+  rgn_bb_table[pos] = bb->index;
+  BLOCK_TO_BB (bb->index) = bbi;
+  CONTAINING_RGN (bb->index) = rgn;
+
+  RGN_NR_BLOCKS (rgn)++;
+  
+  for (i = rgn + 1; i <= nr_regions; i++)
+    RGN_BLOCKS (i)++;
+}
+
+/* Remove BB from the current region and update the region data.  */
+static void
+remove_bb_from_region (basic_block bb)
+{
+  int i, pos, bbi = -2, rgn;
+
+  rgn = CONTAINING_RGN (BB_TO_BLOCK (0));
+  bbi = BLOCK_TO_BB (bb->index);
+  pos = RGN_BLOCKS (rgn) + bbi;
+
+  gcc_assert (RGN_HAS_REAL_EBB (rgn) == 0
+              && ebb_head[bbi] == pos);
+
+  for (i = RGN_BLOCKS (rgn + 1) - 1; i >= pos; i--)
+    BLOCK_TO_BB (rgn_bb_table[i])--;
+
+  memmove (rgn_bb_table + pos,
+           rgn_bb_table + pos + 1,
+           (RGN_BLOCKS (nr_regions) - pos) * sizeof (*rgn_bb_table));
+
+  RGN_NR_BLOCKS (rgn)--;
+  for (i = rgn + 1; i <= nr_regions; i++)
+    RGN_BLOCKS (i)--;
+}
+
+/* Add BB to the current region  and update all data.  If BB is NULL, add all 
+   blocks from last_added_blocks vector.  */
+static void
+sel_add_bb (basic_block bb)
+{
+  /* Extend luids so that new notes will receive zero luids.  */
+  sched_init_luids (NULL, NULL, NULL, NULL);
+  sched_init_bbs ();
+  sel_init_bbs (last_added_blocks, NULL);
+
+  /* When bb is passed explicitly, the vector should contain 
+     the only element that equals to bb; otherwise, the vector
+     should not be NULL.  */
+  gcc_assert (last_added_blocks != NULL);
+  
+  if (bb != NULL)
+    {
+      gcc_assert (VEC_length (basic_block, last_added_blocks) == 1
+                  && VEC_index (basic_block, 
+                                last_added_blocks, 0) == bb);     
+      add_block_to_current_region (bb);
+
+      /* We associate creating/deleting data sets with the first insn
+         appearing / disappearing in the bb.  */
+      if (!sel_bb_empty_p (bb) && BB_LV_SET (bb) == NULL)
+       create_initial_data_sets (bb);
+    
+      VEC_free (basic_block, heap, last_added_blocks);
+    }
+  else
+    /* BB is NULL - process LAST_ADDED_BLOCKS instead.  */
+    {
+      int i;
+      basic_block temp_bb = NULL;
+
+      for (i = 0; 
+           VEC_iterate (basic_block, last_added_blocks, i, bb); i++)
+        {
+          add_block_to_current_region (bb);
+          temp_bb = bb;
+        }
+
+      /* We need to fetch at least one bb so we know the region 
+         to update.  */
+      gcc_assert (temp_bb != NULL);
+      bb = temp_bb;
+
+      VEC_free (basic_block, heap, last_added_blocks);
+    }
+
+  rgn_setup_region (CONTAINING_RGN (bb->index));
+}
+
+/* Remove BB from the current region and update all data.  
+   If REMOVE_FROM_CFG_PBB is true, also remove the block cfom cfg.  */
+static void
+sel_remove_bb (basic_block bb, bool remove_from_cfg_p)
+{
+  gcc_assert (bb != NULL && BB_NOTE_LIST (bb) == NULL_RTX);
+  
+  remove_bb_from_region (bb);
+  return_bb_to_pool (bb);
+  bitmap_clear_bit (blocks_to_reschedule, bb->index);
+  
+  if (remove_from_cfg_p)
+    delete_and_free_basic_block (bb);
+
+  rgn_setup_region (CONTAINING_RGN (bb->index));
+}
+
+/* Concatenate info of EMPTY_BB to info of MERGE_BB.  */
+static void
+move_bb_info (basic_block merge_bb, basic_block empty_bb)
+{
+  gcc_assert (in_current_region_p (merge_bb));
+
+  concat_note_lists (BB_NOTE_LIST (empty_bb), 
+                    &BB_NOTE_LIST (merge_bb));
+  BB_NOTE_LIST (empty_bb) = NULL_RTX;
+
+}
+
+/* Remove an empty basic block EMPTY_BB.  When MERGE_UP_P is true, we put 
+   EMPTY_BB's note lists into its predecessor instead of putting them 
+   into the successor.  When REMOVE_FROM_CFG_P is true, also remove 
+   the empty block.  */
+void
+sel_remove_empty_bb (basic_block empty_bb, bool merge_up_p,
+                    bool remove_from_cfg_p)
+{
+  basic_block merge_bb;
+
+  gcc_assert (sel_bb_empty_p (empty_bb));
+
+  if (merge_up_p)
+    {
+      merge_bb = empty_bb->prev_bb;
+      gcc_assert (EDGE_COUNT (empty_bb->preds) == 1
+                 && EDGE_PRED (empty_bb, 0)->src == merge_bb);
+    }
+  else
+    {
+      edge e;
+      edge_iterator ei;
+
+      merge_bb = bb_next_bb (empty_bb);
+
+      /* Redirect incoming edges (except fallthrough one) of EMPTY_BB to its 
+         successor block.  */
+      for (ei = ei_start (empty_bb->preds);
+           (e = ei_safe_edge (ei)); )
+        {
+          if (! (e->flags & EDGE_FALLTHRU))
+            sel_redirect_edge_and_branch (e, merge_bb);
+          else
+            ei_next (&ei);
+        }
+
+      gcc_assert (EDGE_COUNT (empty_bb->succs) == 1
+                 && EDGE_SUCC (empty_bb, 0)->dest == merge_bb);
+    }
+
+  move_bb_info (merge_bb, empty_bb);
+  remove_empty_bb (empty_bb, remove_from_cfg_p);
+}
+
+/* Remove EMPTY_BB.  If REMOVE_FROM_CFG_P is false, remove EMPTY_BB from
+   region, but keep it in CFG.  */
+static void
+remove_empty_bb (basic_block empty_bb, bool remove_from_cfg_p)
+{
+  /* The block should contain just a note or a label.
+     We try to check whether it is unused below.  */
+  gcc_assert (BB_HEAD (empty_bb) == BB_END (empty_bb)
+              || LABEL_P (BB_HEAD (empty_bb)));
+
+  /* If basic block has predecessors or successors, redirect them.  */
+  if (remove_from_cfg_p
+      && (EDGE_COUNT (empty_bb->preds) > 0
+         || EDGE_COUNT (empty_bb->succs) > 0))
+    {
+      basic_block pred;
+      basic_block succ;
+
+      /* We need to init PRED and SUCC before redirecting edges.  */
+      if (EDGE_COUNT (empty_bb->preds) > 0)
+       {
+         edge e;
+
+         gcc_assert (EDGE_COUNT (empty_bb->preds) == 1);
+
+         e = EDGE_PRED (empty_bb, 0);
+          gcc_assert (e->src == empty_bb->prev_bb
+                     && (e->flags & EDGE_FALLTHRU));
+
+         pred = empty_bb->prev_bb;
+       }
+      else
+       pred = NULL;
+
+      if (EDGE_COUNT (empty_bb->succs) > 0)
+       {
+          /* We do not check fallthruness here as above, because
+             after removing a jump the edge may actually be not fallthru.  */
+         gcc_assert (EDGE_COUNT (empty_bb->succs) == 1);
+         succ = EDGE_SUCC (empty_bb, 0)->dest;
+       }
+      else
+       succ = NULL;
+
+      if (EDGE_COUNT (empty_bb->preds) > 0 && succ != NULL)
+        {
+          edge e = EDGE_PRED (empty_bb, 0);
+
+          if (e->flags & EDGE_FALLTHRU)
+            redirect_edge_succ_nodup (e, succ);
+          else
+            sel_redirect_edge_and_branch (EDGE_PRED (empty_bb, 0), succ);
+        }
+
+      if (EDGE_COUNT (empty_bb->succs) > 0 && pred != NULL)
+       {
+         edge e = EDGE_SUCC (empty_bb, 0);
+
+         if (find_edge (pred, e->dest) == NULL)
+           redirect_edge_pred (e, pred);
+       }
+    }
+
+  /* Finish removing.  */
+  sel_remove_bb (empty_bb, remove_from_cfg_p);
+}
+
+/* An implementation of create_basic_block hook, which additionally updates 
+   per-bb data structures.  */
+static basic_block
+sel_create_basic_block (void *headp, void *endp, basic_block after)
+{
+  basic_block new_bb;
+  insn_t new_bb_note;
+  
+  gcc_assert (flag_sel_sched_pipelining_outer_loops 
+              || last_added_blocks == NULL);
+
+  new_bb_note = get_bb_note_from_pool ();
+
+  if (new_bb_note == NULL_RTX)
+    new_bb = orig_cfg_hooks.create_basic_block (headp, endp, after);
+  else
+    {
+      new_bb = create_basic_block_structure ((rtx) headp, (rtx) endp,
+                                            new_bb_note, after);
+      new_bb->aux = NULL;
+    }
+
+  VEC_safe_push (basic_block, heap, last_added_blocks, new_bb);
+
+  return new_bb;
+}
+
+/* Implement sched_init_only_bb ().  */
+static void
+sel_init_only_bb (basic_block bb, basic_block after)
+{
+  gcc_assert (after == NULL);
+
+  extend_regions ();
+  rgn_make_new_region_out_of_new_block (bb);
+}
+
+/* Update the latch when we've splitted or merged it from FROM block to TO.
+   This should be checked for all outer loops, too.  */
+static void
+change_loops_latches (basic_block from, basic_block to)
+{
+  gcc_assert (from != to);
+
+  if (current_loop_nest)
+    {
+      struct loop *loop;
+
+      for (loop = current_loop_nest; loop; loop = loop_outer (loop))
+        if (considered_for_pipelining_p (loop) && loop->latch == from)
+          {
+            gcc_assert (loop == current_loop_nest);
+            loop->latch = to;
+            gcc_assert (loop_latch_edge (loop));
+          }
+    }
+}
+
+/* Splits BB on two basic blocks, adding it to the region and extending 
+   per-bb data structures.  Returns the newly created bb.  */
+static basic_block
+sel_split_block (basic_block bb, rtx after)
+{
+  basic_block new_bb;
+  insn_t insn;
+
+  new_bb = sched_split_block_1 (bb, after);
+  sel_add_bb (new_bb);
+
+  /* This should be called after sel_add_bb, because this uses
+     CONTAINING_RGN for the new block, which is not yet initialized.  
+     FIXME: this function may be a no-op now.  */
+  change_loops_latches (bb, new_bb);
+
+  /* Update ORIG_BB_INDEX for insns moved into the new block.  */
+  FOR_BB_INSNS (new_bb, insn)
+   if (INSN_P (insn))
+     EXPR_ORIG_BB_INDEX (INSN_EXPR (insn)) = new_bb->index;
+
+  if (sel_bb_empty_p (bb))
+    {
+      gcc_assert (!sel_bb_empty_p (new_bb));
+
+      /* NEW_BB has data sets that need to be updated and BB holds
+        data sets that should be removed.  Exchange these data sets
+        so that we won't lose BB's valid data sets.  */
+      exchange_data_sets (new_bb, bb);
+      free_data_sets (bb);
+    }
+
+  if (!sel_bb_empty_p (new_bb)
+      && bitmap_bit_p (blocks_to_reschedule, bb->index))
+    bitmap_set_bit (blocks_to_reschedule, new_bb->index);
+
+  return new_bb;
+}
+
+/* If BB ends with a jump insn whose ID is bigger then PREV_MAX_UID, return it.
+   Otherwise returns NULL.  */
+static rtx
+check_for_new_jump (basic_block bb, int prev_max_uid)
+{
+  rtx end;
+
+  end = sel_bb_end (bb);
+  if (end && INSN_UID (end) >= prev_max_uid)
+    return end;
+  return NULL;
+}
+
+/* Look for a new jump either in FROM_BB block or in newly created JUMP_BB block. 
+   New means having UID at least equal to PREV_MAX_UID.  */
+static rtx
+find_new_jump (basic_block from, basic_block jump_bb, int prev_max_uid)
+{
+  rtx jump;
+
+  /* Return immediately if no new insns were emitted.  */
+  if (get_max_uid () == prev_max_uid)
+    return NULL;
+  
+  /* Now check both blocks for new jumps.  It will ever be only one.  */
+  if ((jump = check_for_new_jump (from, prev_max_uid)))
+    return jump;
+
+  if (jump_bb != NULL
+      && (jump = check_for_new_jump (jump_bb, prev_max_uid)))
+    return jump;
+  return NULL;
+}
+
+/* Splits E and adds the newly created basic block to the current region.
+   Returns this basic block.  */
+basic_block
+sel_split_edge (edge e)
+{
+  basic_block new_bb, src, other_bb = NULL;
+  int prev_max_uid;
+  rtx jump;
+
+  src = e->src;
+  prev_max_uid = get_max_uid ();
+  new_bb = split_edge (e);
+
+  if (flag_sel_sched_pipelining_outer_loops 
+      && current_loop_nest)
+    {
+      int i;
+      basic_block bb;
+
+      /* Some of the basic blocks might not have been added to the loop.  
+         Add them here, until this is fixed in force_fallthru.  */
+      for (i = 0; 
+           VEC_iterate (basic_block, last_added_blocks, i, bb); i++)
+        if (!bb->loop_father)
+          {
+            add_bb_to_loop (bb, e->dest->loop_father);
+
+            gcc_assert (!other_bb && (new_bb->index != bb->index));
+            other_bb = bb;
+          }
+    }
+
+  /* Add all last_added_blocks to the region.  */
+  sel_add_bb (NULL);
+
+  jump = find_new_jump (src, new_bb, prev_max_uid);
+  if (jump)
+    sel_init_new_insn (jump, INSN_INIT_TODO_LUID | INSN_INIT_TODO_SIMPLEJUMP);
+
+  /* Put the correct lv set on this block.  */
+  if (other_bb && !sel_bb_empty_p (other_bb))
+    compute_live (sel_bb_head (other_bb));
+
+  return new_bb;
+}
+
+/* Implement sched_create_empty_bb ().  */
+static basic_block
+sel_create_empty_bb (basic_block after)
+{
+  basic_block new_bb;
+
+  new_bb = sched_create_empty_bb_1 (after);
+
+  /* We'll explicitly initialize NEW_BB via sel_init_only_bb () a bit
+     later.  */
+  gcc_assert (VEC_length (basic_block, last_added_blocks) == 1
+             && VEC_index (basic_block, last_added_blocks, 0) == new_bb);
+
+  VEC_free (basic_block, heap, last_added_blocks);
+  return new_bb;
+}
+
+/* Implement sched_create_recovery_block.  ORIG_INSN is where block
+   will be splitted to insert a check.  */
+basic_block
+sel_create_recovery_block (insn_t orig_insn)
+{
+  basic_block first_bb, second_bb, recovery_block;
+  basic_block before_recovery = NULL;
+  rtx jump;
+
+  first_bb = BLOCK_FOR_INSN (orig_insn);
+  if (sel_bb_end_p (orig_insn))
+    {
+      /* Avoid introducing an empty block while splitting.  */
+      gcc_assert (single_succ_p (first_bb));
+      second_bb = single_succ (first_bb);
+    }
+  else
+    second_bb = sched_split_block (first_bb, orig_insn);
+
+  recovery_block = sched_create_recovery_block (&before_recovery);
+  if (before_recovery)
+    copy_lv_set_from (before_recovery, EXIT_BLOCK_PTR);
+
+  gcc_assert (sel_bb_empty_p (recovery_block));
+  sched_create_recovery_edges (first_bb, recovery_block, second_bb);
+  if (current_loops != NULL)
+    add_bb_to_loop (recovery_block, first_bb->loop_father);
+  
+  sel_add_bb (recovery_block);
+    
+  jump = BB_END (recovery_block);
+  gcc_assert (sel_bb_head (recovery_block) == jump);
+  sel_init_new_insn (jump, INSN_INIT_TODO_LUID | INSN_INIT_TODO_SIMPLEJUMP);
+
+  return recovery_block;
+}
+
+/* Merge basic block B into basic block A.  */
+void
+sel_merge_blocks (basic_block a, basic_block b)
+{
+  gcc_assert (can_merge_blocks_p (a, b));
+
+  sel_remove_empty_bb (b, true, false);
+  merge_blocks (a, b);
+
+  change_loops_latches (b, a);
+}
+
+/* A wrapper for redirect_edge_and_branch_force, which also initializes
+   data structures for possibly created bb and insns.  Returns the newly
+   added bb or NULL, when a bb was not needed.  */
+void
+sel_redirect_edge_and_branch_force (edge e, basic_block to)
+{
+  basic_block jump_bb, src;
+  int prev_max_uid;
+  rtx jump;
+    
+  gcc_assert (!sel_bb_empty_p (e->src));
+  
+  src = e->src;
+  prev_max_uid = get_max_uid ();
+  jump_bb = redirect_edge_and_branch_force (e, to);
+
+  if (jump_bb != NULL)
+    sel_add_bb (jump_bb);
+
+  /* This function could not be used to spoil the loop structure by now,
+     thus we don't care to update anything.  But check it to be sure.  */
+  if (current_loop_nest
+      && pipelining_p)
+    gcc_assert (loop_latch_edge (current_loop_nest));
+  
+  jump = find_new_jump (src, jump_bb, prev_max_uid);
+  if (jump)
+    sel_init_new_insn (jump, INSN_INIT_TODO_LUID | INSN_INIT_TODO_SIMPLEJUMP);
+}
+
+/* A wrapper for redirect_edge_and_branch.  */
+void
+sel_redirect_edge_and_branch (edge e, basic_block to)
+{
+  bool latch_edge_p;
+  basic_block src;
+  int prev_max_uid;
+  rtx jump;
+
+  latch_edge_p = (pipelining_p
+                  && current_loop_nest
+                  && e == loop_latch_edge (current_loop_nest));
+
+  src = e->src;
+  prev_max_uid = get_max_uid ();
+  
+  redirect_edge_and_branch (e, to);
+  gcc_assert (last_added_blocks == NULL);
+
+  /* When we've redirected a latch edge, update the header.  */
+  if (latch_edge_p)
+    {
+      current_loop_nest->header = to;
+      gcc_assert (loop_latch_edge (current_loop_nest));
+    }
+
+  jump = find_new_jump (src, NULL, prev_max_uid);
+  if (jump)
+    sel_init_new_insn (jump, INSN_INIT_TODO_LUID | INSN_INIT_TODO_SIMPLEJUMP);
+}
+
+/* This variable holds the cfg hooks used by the selective scheduler.  */
+static struct cfg_hooks sel_cfg_hooks;
+
+/* Register sel-sched cfg hooks.  */
+void
+sel_register_cfg_hooks (void)
+{
+  sched_split_block = sel_split_block;
+
+  orig_cfg_hooks = get_cfg_hooks ();
+  sel_cfg_hooks = orig_cfg_hooks;
+
+  sel_cfg_hooks.create_basic_block = sel_create_basic_block;
+
+  set_cfg_hooks (sel_cfg_hooks);
+
+  sched_init_only_bb = sel_init_only_bb;
+  sched_split_block = sel_split_block;
+  sched_create_empty_bb = sel_create_empty_bb;
+}
+
+/* Unregister sel-sched cfg hooks.  */
+void
+sel_unregister_cfg_hooks (void)
+{
+  sched_create_empty_bb = NULL;
+  sched_split_block = NULL;
+  sched_init_only_bb = NULL;
+
+  set_cfg_hooks (orig_cfg_hooks);
+}
+\f
+
+/* Emit an insn rtx based on PATTERN.  If a jump insn is wanted,
+   LABEL is where this jump should be directed.  */
+rtx
+create_insn_rtx_from_pattern (rtx pattern, rtx label)
+{
+  rtx insn_rtx;
+
+  gcc_assert (!INSN_P (pattern));
+
+  start_sequence ();
+
+  if (label == NULL_RTX)
+    insn_rtx = emit_insn (pattern);
+  else
+    {
+      insn_rtx = emit_jump_insn (pattern);
+      JUMP_LABEL (insn_rtx) = label;
+      ++LABEL_NUSES (label);
+    }
+
+  end_sequence ();
+
+  sched_init_luids (NULL, NULL, NULL, NULL);
+  sched_extend_target ();
+  sched_deps_init (false);
+
+  /* Initialize INSN_CODE now.  */
+  recog_memoized (insn_rtx);
+  return insn_rtx;
+}
+
+/* Create a new vinsn for INSN_RTX.  FORCE_UNIQUE_P is true when the vinsn
+   must not be clonable.  */
+vinsn_t
+create_vinsn_from_insn_rtx (rtx insn_rtx, bool force_unique_p)
+{
+  gcc_assert (INSN_P (insn_rtx) && !INSN_IN_STREAM_P (insn_rtx));
+
+  /* If VINSN_TYPE is not USE, retain its uniqueness.  */
+  return vinsn_create (insn_rtx, force_unique_p);
+}
+
+/* Create a copy of INSN_RTX.  */
+rtx
+create_copy_of_insn_rtx (rtx insn_rtx)
+{
+  rtx res;
+
+  gcc_assert (NONJUMP_INSN_P (insn_rtx));
+
+  res = create_insn_rtx_from_pattern (copy_rtx (PATTERN (insn_rtx)),
+                                      NULL_RTX);
+  return res;
+}
+
+/* Change vinsn field of EXPR to hold NEW_VINSN.  */
+void
+change_vinsn_in_expr (expr_t expr, vinsn_t new_vinsn)
+{
+  vinsn_detach (EXPR_VINSN (expr));
+
+  EXPR_VINSN (expr) = new_vinsn;
+  vinsn_attach (new_vinsn);
+}
+
+/* Helpers for global init.  */
+/* This structure is used to be able to call existing bundling mechanism
+   and calculate insn priorities.  */
+static struct haifa_sched_info sched_sel_haifa_sched_info = 
+{
+  NULL, /* init_ready_list */
+  NULL, /* can_schedule_ready_p */
+  NULL, /* schedule_more_p */
+  NULL, /* new_ready */
+  NULL, /* rgn_rank */
+  sel_print_insn, /* rgn_print_insn */
+  contributes_to_priority,
+
+  NULL, NULL,
+  NULL, NULL,
+  0, 0,
+
+  NULL, /* add_remove_insn */
+  NULL, /* begin_schedule_ready */
+  NULL, /* advance_target_bb */
+  SEL_SCHED | NEW_BBS
+};
+
+/* Setup special insns used in the scheduler.  */
+void 
+setup_nop_and_exit_insns (void)
+{
+  gcc_assert (nop_pattern == NULL_RTX
+             && exit_insn == NULL_RTX);
+
+  nop_pattern = gen_nop ();
+
+  start_sequence ();
+  emit_insn (nop_pattern);
+  exit_insn = get_insns ();
+  end_sequence ();
+  set_block_for_insn (exit_insn, EXIT_BLOCK_PTR);
+}
+
+/* Free special insns used in the scheduler.  */
+void
+free_nop_and_exit_insns (void)
+{
+  exit_insn = NULL_RTX;
+  nop_pattern = NULL_RTX;
+}
+
+/* Setup a special vinsn used in new insns initialization.  */
+void
+setup_nop_vinsn (void)
+{
+  nop_vinsn = vinsn_create (exit_insn, false);
+  vinsn_attach (nop_vinsn);
+}
+
+/* Free a special vinsn used in new insns initialization.  */
+void
+free_nop_vinsn (void)
+{
+  gcc_assert (VINSN_COUNT (nop_vinsn) == 1);
+  vinsn_detach (nop_vinsn);
+  nop_vinsn = NULL;
+}
+
+/* Call a set_sched_flags hook.  */
+void
+sel_set_sched_flags (void)
+{
+  /* ??? This means that set_sched_flags were called, and we decided to 
+     support speculation.  However, set_sched_flags also modifies flags
+     on current_sched_info, doing this only at global init.  And we 
+     sometimes change c_s_i later.  So put the correct flags again.  */
+  if (spec_info && targetm.sched.set_sched_flags)
+    targetm.sched.set_sched_flags (spec_info);
+}
+
+/* Setup pointers to global sched info structures.  */
+void
+sel_setup_sched_infos (void)
+{
+  rgn_setup_common_sched_info ();
+
+  memcpy (&sel_common_sched_info, common_sched_info,
+         sizeof (sel_common_sched_info));
+
+  sel_common_sched_info.fix_recovery_cfg = NULL;
+  sel_common_sched_info.add_block = NULL;
+  sel_common_sched_info.estimate_number_of_insns
+    = sel_estimate_number_of_insns;
+  sel_common_sched_info.luid_for_non_insn = sel_luid_for_non_insn;
+  sel_common_sched_info.sched_pass_id = SCHED_SEL_PASS;
+
+  common_sched_info = &sel_common_sched_info;
+
+  current_sched_info = &sched_sel_haifa_sched_info;
+  current_sched_info->sched_max_insns_priority = 
+    get_rgn_sched_max_insns_priority ();
+  
+  sel_set_sched_flags ();
+}
+\f
+
+/* Adds basic block BB to region RGN at the position *BB_ORD_INDEX,
+   *BB_ORD_INDEX after that is increased.  */
+static void
+sel_add_block_to_region (basic_block bb, int *bb_ord_index, int rgn)
+{
+  RGN_NR_BLOCKS (rgn) += 1;
+  RGN_DONT_CALC_DEPS (rgn) = 0;
+  RGN_HAS_REAL_EBB (rgn) = 0;
+  CONTAINING_RGN (bb->index) = rgn;
+  BLOCK_TO_BB (bb->index) = *bb_ord_index;
+  rgn_bb_table[RGN_BLOCKS (rgn) + *bb_ord_index] = bb->index;
+  (*bb_ord_index)++;
+
+  /* FIXME: it is true only when not scheduling ebbs.  */
+  RGN_BLOCKS (rgn + 1) = RGN_BLOCKS (rgn) + RGN_NR_BLOCKS (rgn);
+}
+
+/* Functions to support pipelining of outer loops.  */
+
+/* Creates a new empty region and returns it's number.  */
+static int
+sel_create_new_region (void)
+{
+  int new_rgn_number = nr_regions;
+
+  RGN_NR_BLOCKS (new_rgn_number) = 0;
+
+  /* FIXME: This will work only when EBBs are not created.  */
+  if (new_rgn_number != 0)
+    RGN_BLOCKS (new_rgn_number) = RGN_BLOCKS (new_rgn_number - 1) + 
+      RGN_NR_BLOCKS (new_rgn_number - 1);
+  else
+    RGN_BLOCKS (new_rgn_number) = 0;
+
+  /* Set the blocks of the next region so the other functions may
+     calculate the number of blocks in the region.  */
+  RGN_BLOCKS (new_rgn_number + 1) = RGN_BLOCKS (new_rgn_number) + 
+    RGN_NR_BLOCKS (new_rgn_number);
+
+  nr_regions++;
+
+  return new_rgn_number;
+}
+
+/* If X has a smaller topological sort number than Y, returns -1;
+   if greater, returns 1.  */
+static int
+bb_top_order_comparator (const void *x, const void *y)
+{
+  basic_block bb1 = *(const basic_block *) x;
+  basic_block bb2 = *(const basic_block *) y;
+
+  gcc_assert (bb1 == bb2 
+             || rev_top_order_index[bb1->index] 
+                != rev_top_order_index[bb2->index]);
+
+  /* It's a reverse topological order in REV_TOP_ORDER_INDEX, so
+     bbs with greater number should go earlier.  */
+  if (rev_top_order_index[bb1->index] > rev_top_order_index[bb2->index])
+    return -1;
+  else
+    return 1;
+}
+
+/* Create a region for LOOP and return its number.  If we don't want 
+   to pipeline LOOP, return -1.  */
+static int
+make_region_from_loop (struct loop *loop)
+{
+  unsigned int i;
+  int new_rgn_number = -1;
+  struct loop *inner;
+
+  /* Basic block index, to be assigned to BLOCK_TO_BB.  */
+  int bb_ord_index = 0;
+  basic_block *loop_blocks;
+  basic_block preheader_block;
+
+  if (loop->num_nodes 
+      > (unsigned) PARAM_VALUE (PARAM_MAX_PIPELINE_REGION_BLOCKS))
+    return -1;
+  
+  /* Don't pipeline loops whose latch belongs to some of its inner loops.  */
+  for (inner = loop->inner; inner; inner = inner->inner)
+    if (flow_bb_inside_loop_p (inner, loop->latch))
+      return -1;
+
+  loop->ninsns = num_loop_insns (loop);
+  if ((int) loop->ninsns > PARAM_VALUE (PARAM_MAX_PIPELINE_REGION_INSNS))
+    return -1;
+
+  loop_blocks = get_loop_body_in_custom_order (loop, bb_top_order_comparator);
+
+  for (i = 0; i < loop->num_nodes; i++)
+    if (loop_blocks[i]->flags & BB_IRREDUCIBLE_LOOP)
+      {
+       free (loop_blocks);
+       return -1;
+      }
+
+  preheader_block = loop_preheader_edge (loop)->src;
+  gcc_assert (preheader_block);
+  gcc_assert (loop_blocks[0] == loop->header);
+
+  new_rgn_number = sel_create_new_region ();
+
+  sel_add_block_to_region (preheader_block, &bb_ord_index, new_rgn_number);
+  SET_BIT (bbs_in_loop_rgns, preheader_block->index);
+
+  for (i = 0; i < loop->num_nodes; i++)
+    {
+      /* Add only those blocks that haven't been scheduled in the inner loop.
+        The exception is the basic blocks with bookkeeping code - they should
+        be added to the region (and they actually don't belong to the loop 
+        body, but to the region containing that loop body).  */
+
+      gcc_assert (new_rgn_number >= 0);
+
+      if (! TEST_BIT (bbs_in_loop_rgns, loop_blocks[i]->index))
+       {
+         sel_add_block_to_region (loop_blocks[i], &bb_ord_index, 
+                                   new_rgn_number);
+         SET_BIT (bbs_in_loop_rgns, loop_blocks[i]->index);
+       }
+    }
+
+  free (loop_blocks);
+  MARK_LOOP_FOR_PIPELINING (loop);
+
+  return new_rgn_number;
+}
+
+/* Create a new region from preheader blocks LOOP_BLOCKS.  */
+void
+make_region_from_loop_preheader (VEC(basic_block, heap) **loop_blocks)
+{
+  unsigned int i;
+  int new_rgn_number = -1;
+  basic_block bb;
+
+  /* Basic block index, to be assigned to BLOCK_TO_BB.  */
+  int bb_ord_index = 0;
+
+  new_rgn_number = sel_create_new_region ();
+
+  for (i = 0; VEC_iterate (basic_block, *loop_blocks, i, bb); i++)
+    {
+      gcc_assert (new_rgn_number >= 0);
+
+      sel_add_block_to_region (bb, &bb_ord_index, new_rgn_number);
+    }
+
+  VEC_free (basic_block, heap, *loop_blocks);
+  gcc_assert (*loop_blocks == NULL);
+}
+
+
+/* Create region(s) from loop nest LOOP, such that inner loops will be
+   pipelined before outer loops.  Returns true when a region for LOOP 
+   is created.  */
+static bool
+make_regions_from_loop_nest (struct loop *loop)
+{   
+  struct loop *cur_loop;
+  int rgn_number;
+
+  /* Traverse all inner nodes of the loop.  */
+  for (cur_loop = loop->inner; cur_loop; cur_loop = cur_loop->next)
+    if (! TEST_BIT (bbs_in_loop_rgns, cur_loop->header->index))
+      return false;
+
+  /* At this moment all regular inner loops should have been pipelined.
+     Try to create a region from this loop.  */
+  rgn_number = make_region_from_loop (loop);
+
+  if (rgn_number < 0)
+    return false;
+
+  VEC_safe_push (loop_p, heap, loop_nests, loop);
+  return true;
+}
+
+/* Initalize data structures needed.  */
+void
+sel_init_pipelining (void)
+{
+  /* Collect loop information to be used in outer loops pipelining.  */
+  loop_optimizer_init (LOOPS_HAVE_PREHEADERS
+                       | LOOPS_HAVE_FALLTHRU_PREHEADERS
+                      | LOOPS_HAVE_RECORDED_EXITS
+                      | LOOPS_HAVE_MARKED_IRREDUCIBLE_REGIONS);
+  current_loop_nest = NULL;
+
+  bbs_in_loop_rgns = sbitmap_alloc (last_basic_block);
+  sbitmap_zero (bbs_in_loop_rgns);
+
+  recompute_rev_top_order ();
+}
+
+/* Returns a struct loop for region RGN.  */
+loop_p
+get_loop_nest_for_rgn (unsigned int rgn)
+{
+  /* Regions created with extend_rgns don't have corresponding loop nests,
+     because they don't represent loops.  */
+  if (rgn < VEC_length (loop_p, loop_nests))
+    return VEC_index (loop_p, loop_nests, rgn);
+  else
+    return NULL;
+}
+
+/* True when LOOP was included into pipelining regions.   */
+bool
+considered_for_pipelining_p (struct loop *loop)
+{
+  if (loop_depth (loop) == 0)
+    return false;
+
+  /* Now, the loop could be too large or irreducible.  Check whether its 
+     region is in LOOP_NESTS.  
+     We determine the region number of LOOP as the region number of its 
+     latch.  We can't use header here, because this header could be 
+     just removed preheader and it will give us the wrong region number.
+     Latch can't be used because it could be in the inner loop too.  */
+  if (LOOP_MARKED_FOR_PIPELINING_P (loop) && pipelining_p)
+    {
+      int rgn = CONTAINING_RGN (loop->latch->index);
+
+      gcc_assert ((unsigned) rgn < VEC_length (loop_p, loop_nests));
+      return true;
+    }
+  
+  return false;
+}
+
+/* Makes regions from the rest of the blocks, after loops are chosen 
+   for pipelining.  */
+static void
+make_regions_from_the_rest (void)
+{
+  int cur_rgn_blocks;
+  int *loop_hdr;
+  int i;
+
+  basic_block bb;
+  edge e;
+  edge_iterator ei;
+  int *degree;
+  int new_regions;
+
+  /* Index in rgn_bb_table where to start allocating new regions.  */
+  cur_rgn_blocks = nr_regions ? RGN_BLOCKS (nr_regions) : 0;
+  new_regions = nr_regions;
+
+  /* Make regions from all the rest basic blocks - those that don't belong to 
+     any loop or belong to irreducible loops.  Prepare the data structures
+     for extend_rgns.  */
+
+  /* LOOP_HDR[I] == -1 if I-th bb doesn't belong to any loop,
+     LOOP_HDR[I] == LOOP_HDR[J] iff basic blocks I and J reside within the same
+     loop.  */
+  loop_hdr = XNEWVEC (int, last_basic_block);
+  degree = XCNEWVEC (int, last_basic_block);
+
+
+  /* For each basic block that belongs to some loop assign the number
+     of innermost loop it belongs to.  */
+  for (i = 0; i < last_basic_block; i++)
+    loop_hdr[i] = -1;
+
+  FOR_EACH_BB (bb)
+    {
+      if (bb->loop_father && !bb->loop_father->num == 0
+         && !(bb->flags & BB_IRREDUCIBLE_LOOP))
+       loop_hdr[bb->index] = bb->loop_father->num;
+    }
+
+  /* For each basic block degree is calculated as the number of incoming 
+     edges, that are going out of bbs that are not yet scheduled.
+     The basic blocks that are scheduled have degree value of zero.  */
+  FOR_EACH_BB (bb) 
+    {
+      degree[bb->index] = 0;
+
+      if (!TEST_BIT (bbs_in_loop_rgns, bb->index))
+       {
+         FOR_EACH_EDGE (e, ei, bb->preds)
+           if (!TEST_BIT (bbs_in_loop_rgns, e->src->index))
+             degree[bb->index]++;
+       }
+      else
+       degree[bb->index] = -1;
+    }
+
+  extend_rgns (degree, &cur_rgn_blocks, bbs_in_loop_rgns, loop_hdr);
+
+  /* Any block that did not end up in a region is placed into a region
+     by itself.  */
+  FOR_EACH_BB (bb)
+    if (degree[bb->index] >= 0)
+      {
+       rgn_bb_table[cur_rgn_blocks] = bb->index;
+       RGN_NR_BLOCKS (nr_regions) = 1;
+       RGN_BLOCKS (nr_regions) = cur_rgn_blocks++;
+        RGN_DONT_CALC_DEPS (nr_regions) = 0;
+       RGN_HAS_REAL_EBB (nr_regions) = 0;
+       CONTAINING_RGN (bb->index) = nr_regions++;
+       BLOCK_TO_BB (bb->index) = 0;
+      }
+
+  free (degree);
+  free (loop_hdr);
+}
+
+/* Free data structures used in pipelining of loops.  */
+void sel_finish_pipelining (void)
+{
+  loop_iterator li;
+  struct loop *loop;
+
+  /* Release aux fields so we don't free them later by mistake.  */
+  FOR_EACH_LOOP (li, loop, 0)
+    loop->aux = NULL;
+
+  loop_optimizer_finalize ();
+
+  VEC_free (loop_p, heap, loop_nests);
+
+  free (rev_top_order_index);
+  rev_top_order_index = NULL;
+}
+
+/* This function replaces the find_rgns when 
+   FLAG_SEL_SCHED_PIPELINING_OUTER_LOOPS is set.  */
+void 
+sel_find_rgns (void)
+{
+  sel_init_pipelining ();
+  extend_regions ();
+
+  if (current_loops)
+    {
+      loop_p loop;
+      loop_iterator li;
+
+      FOR_EACH_LOOP (li, loop, (flag_sel_sched_pipelining_outer_loops
+                               ? LI_FROM_INNERMOST
+                               : LI_ONLY_INNERMOST))
+       make_regions_from_loop_nest (loop);
+    }
+
+  /* Make regions from all the rest basic blocks and schedule them.
+     These blocks include blocks that don't belong to any loop or belong  
+     to irreducible loops.  */
+  make_regions_from_the_rest ();
+
+  /* We don't need bbs_in_loop_rgns anymore.  */
+  sbitmap_free (bbs_in_loop_rgns);
+  bbs_in_loop_rgns = NULL;
+}
+
+/* Adds the preheader blocks from previous loop to current region taking 
+   it from LOOP_PREHEADER_BLOCKS (current_loop_nest).  
+   This function is only used with -fsel-sched-pipelining-outer-loops.  */
+void
+sel_add_loop_preheaders (void)
+{
+  int i;
+  basic_block bb;
+  VEC(basic_block, heap) *preheader_blocks 
+    = LOOP_PREHEADER_BLOCKS (current_loop_nest);
+
+  for (i = 0;
+       VEC_iterate (basic_block, preheader_blocks, i, bb);
+       i++)
+      sel_add_bb (bb);
+
+  VEC_free (basic_block, heap, preheader_blocks);
+}
+
+/* While pipelining outer loops, returns TRUE if BB is a loop preheader.  
+   Please note that the function should also work when pipelining_p is 
+   false, because it is used when deciding whether we should or should 
+   not reschedule pipelined code.  */
+bool
+sel_is_loop_preheader_p (basic_block bb)
+{
+  if (current_loop_nest)
+    {
+      struct loop *outer;
+
+      if (preheader_removed)
+        return false;
+
+      /* Preheader is the first block in the region.  */
+      if (BLOCK_TO_BB (bb->index) == 0)
+        return true;
+
+      /* We used to find a preheader with the topological information.
+         Check that the above code is equivalent to what we did before.  */
+
+      if (in_current_region_p (current_loop_nest->header))
+       gcc_assert (!(BLOCK_TO_BB (bb->index) 
+                     < BLOCK_TO_BB (current_loop_nest->header->index)));
+
+      /* Support the situation when the latch block of outer loop
+         could be from here.  */
+      for (outer = loop_outer (current_loop_nest);
+          outer;
+          outer = loop_outer (outer))
+        if (considered_for_pipelining_p (outer) && outer->latch == bb)
+          gcc_unreachable ();
+    }
+
+  return false;
+}
+
+/* Checks whether JUMP leads to basic block DEST_BB and no other blocks.  */
+bool
+jump_leads_only_to_bb_p (insn_t jump, basic_block dest_bb)
+{
+  basic_block jump_bb = BLOCK_FOR_INSN (jump);
+
+  /* It is not jump, jump with side-effects or jump can lead to several 
+     basic blocks.  */
+  if (!onlyjump_p (jump)
+      || !any_uncondjump_p (jump))
+    return false;
+
+  /* Several outgoing edges, abnormal edge or destination of jump is 
+     not DEST_BB.  */
+  if (EDGE_COUNT (jump_bb->succs) != 1
+      || EDGE_SUCC (jump_bb, 0)->flags & EDGE_ABNORMAL
+      || EDGE_SUCC (jump_bb, 0)->dest != dest_bb)
+    return false;
+
+  /* If not anything of the upper.  */
+  return true;
+}
+
+/* Removes the loop preheader from the current region and saves it in
+   PREHEADER_BLOCKS of the father loop, so they will be added later to 
+   region that represents an outer loop.  */
+static void
+sel_remove_loop_preheader (void)
+{
+  int i, old_len;
+  int cur_rgn = CONTAINING_RGN (BB_TO_BLOCK (0));
+  basic_block bb;
+  bool all_empty_p = true;
+  VEC(basic_block, heap) *preheader_blocks 
+    = LOOP_PREHEADER_BLOCKS (loop_outer (current_loop_nest));
+
+  gcc_assert (current_loop_nest);
+  old_len = VEC_length (basic_block, preheader_blocks);
+
+  /* Add blocks that aren't within the current loop to PREHEADER_BLOCKS.  */
+  for (i = 0; i < RGN_NR_BLOCKS (cur_rgn); i++)
+    {
+      bb = BASIC_BLOCK (BB_TO_BLOCK (i));
+
+      /* If the basic block belongs to region, but doesn't belong to 
+        corresponding loop, then it should be a preheader.  */
+      if (sel_is_loop_preheader_p (bb))
+        {
+          VEC_safe_push (basic_block, heap, preheader_blocks, bb);
+          if (BB_END (bb) != bb_note (bb))
+            all_empty_p = false;
+        }
+    }
+  
+  /* Remove these blocks only after iterating over the whole region.  */
+  for (i = VEC_length (basic_block, preheader_blocks) - 1;
+       i >= old_len;
+       i--)
+    {
+      bb =  VEC_index (basic_block, preheader_blocks, i); 
+      sel_remove_bb (bb, false);
+    }
+
+  if (!considered_for_pipelining_p (loop_outer (current_loop_nest)))
+    {
+      if (!all_empty_p)
+        /* Immediately create new region from preheader.  */
+        make_region_from_loop_preheader (&preheader_blocks);
+      else
+        {
+          /* If all preheader blocks are empty - dont create new empty region.
+             Instead, remove them completely.  */
+          for (i = 0; VEC_iterate (basic_block, preheader_blocks, i, bb); i++)
+            {
+              edge e;
+              edge_iterator ei;
+              basic_block prev_bb = bb->prev_bb, next_bb = bb->next_bb;
+
+              /* Redirect all incoming edges to next basic block.  */
+              for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
+                {
+                  if (! (e->flags & EDGE_FALLTHRU))
+                    redirect_edge_and_branch (e, bb->next_bb);
+                  else
+                    redirect_edge_succ (e, bb->next_bb);
+                }
+              gcc_assert (BB_NOTE_LIST (bb) == NULL);
+              delete_and_free_basic_block (bb);
+
+              /* Check if after deleting preheader there is a nonconditional 
+                 jump in PREV_BB that leads to the next basic block NEXT_BB.  
+                 If it is so - delete this jump and clear data sets of its 
+                 basic block if it becomes empty.  */
+             if (next_bb->prev_bb == prev_bb
+                  && prev_bb != ENTRY_BLOCK_PTR
+                  && jump_leads_only_to_bb_p (BB_END (prev_bb), next_bb))
+                {
+                  redirect_edge_and_branch (EDGE_SUCC (prev_bb, 0), next_bb);
+                  if (BB_END (prev_bb) == bb_note (prev_bb))
+                    free_data_sets (prev_bb);
+                }
+            }
+        }
+      VEC_free (basic_block, heap, preheader_blocks);
+    }
+  else
+    /* Store preheader within the father's loop structure.  */
+    SET_LOOP_PREHEADER_BLOCKS (loop_outer (current_loop_nest),
+                              preheader_blocks);
+}
+#endif
diff --git a/gcc/sel-sched-ir.h b/gcc/sel-sched-ir.h
new file mode 100644 (file)
index 0000000..4bf21b2
--- /dev/null
@@ -0,0 +1,1627 @@
+/* Instruction scheduling pass.  This file contains definitions used
+   internally in the scheduler.
+   Copyright (C) 2006, 2007, 2008 Free Software Foundation, Inc.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free
+Software Foundation; either version 3, or (at your option) any later
+version.
+
+GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or
+FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3.  If not see
+<http://www.gnu.org/licenses/>.  */
+
+#ifndef GCC_SEL_SCHED_IR_H
+#define GCC_SEL_SCHED_IR_H
+
+/* For state_t.  */
+#include "insn-attr.h"
+/* For regset_head.  */
+#include "basic-block.h"
+/* For reg_note.  */
+#include "rtl.h"
+#include "ggc.h"
+#include "bitmap.h"
+#include "vecprim.h"
+#include "sched-int.h"
+#include "cfgloop.h"
+
+/* tc_t is a short for target context.  This is a state of the target
+   backend.  */
+typedef void *tc_t;
+
+/* List data types used for av sets, fences, paths, and boundaries.  */
+
+/* Forward declarations for types that are part of some list nodes.  */
+struct _list_node;
+
+/* List backend.  */
+typedef struct _list_node *_list_t;
+#define _LIST_NEXT(L) ((L)->next)
+
+/* Instruction data that is part of vinsn type.  */
+struct idata_def;
+typedef struct idata_def *idata_t;
+
+/* A virtual instruction, i.e. an instruction as seen by the scheduler.  */
+struct vinsn_def;
+typedef struct vinsn_def *vinsn_t;
+
+/* RTX list.
+   This type is the backend for ilist.  */
+typedef _list_t _xlist_t;
+#define _XLIST_X(L) ((L)->u.x)
+#define _XLIST_NEXT(L) (_LIST_NEXT (L))
+
+/* Instruction.  */
+typedef rtx insn_t;
+
+/* List of insns.  */
+typedef _xlist_t ilist_t;
+#define ILIST_INSN(L) (_XLIST_X (L))
+#define ILIST_NEXT(L) (_XLIST_NEXT (L))
+
+/* This lists possible transformations that done locally, i.e. in 
+   moveup_expr.  */
+enum local_trans_type
+  {
+    TRANS_SUBSTITUTION,
+    TRANS_SPECULATION
+  };
+
+/* This struct is used to record the history of expression's 
+   transformations.  */
+struct expr_history_def_1
+{
+  /* UID of the insn.  */
+  unsigned uid;
+
+  /* How the expression looked like.  */
+  vinsn_t old_expr_vinsn;
+
+  /* How the expression looks after the transformation.  */
+  vinsn_t new_expr_vinsn;
+
+  /* And its speculative status.  */
+  ds_t spec_ds;
+
+  /* Type of the transformation.  */
+  enum local_trans_type type;
+};
+
+typedef struct expr_history_def_1 expr_history_def;
+
+DEF_VEC_O (expr_history_def);
+DEF_VEC_ALLOC_O (expr_history_def, heap);
+
+/* Expression information.  */
+struct _expr
+{
+  /* Insn description.  */
+  vinsn_t vinsn;
+
+  /* SPEC is the degree of speculativeness.
+     FIXME: now spec is increased when an rhs is moved through a
+     conditional, thus showing only control speculativeness.  In the
+     future we'd like to count data spec separately to allow a better
+     control on scheduling.  */
+  int spec;
+
+  /* Degree of speculativeness measured as probability of executing 
+     instruction's original basic block given relative to 
+     the current scheduling point.  */
+  int usefulness;
+
+  /* A priority of this expression.  */
+  int priority;
+
+  /* A priority adjustment of this expression.  */
+  int priority_adj;
+
+  /* Number of times the insn was scheduled.  */
+  int sched_times;
+
+  /* A basic block index this was originated from.  Zero when there is 
+     more than one originator.  */
+  int orig_bb_index;
+
+  /* Instruction should be of SPEC_DONE_DS type in order to be moved to this
+     point.  */
+  ds_t spec_done_ds;
+
+  /* SPEC_TO_CHECK_DS hold speculation types that should be checked
+     (used only during move_op ()).  */
+  ds_t spec_to_check_ds;
+
+  /* Cycle on which original insn was scheduled.  Zero when it has not yet 
+     been scheduled or more than one originator.  */
+  int orig_sched_cycle;
+
+  /* This vector contains the history of insn's transformations.  */
+  VEC(expr_history_def, heap) *history_of_changes;
+
+  /* True (1) when original target (register or memory) of this instruction 
+     is available for scheduling, false otherwise.  -1 means we're not sure;
+     please run find_used_regs to clarify.  */
+  signed char target_available;
+
+  /* True when this expression needs a speculation check to be scheduled.  
+     This is used during find_used_regs.  */
+  BOOL_BITFIELD needs_spec_check_p : 1;
+
+  /* True when the expression was substituted.  Used for statistical 
+     purposes.  */
+  BOOL_BITFIELD was_substituted : 1;
+
+  /* True when the expression was renamed.  */
+  BOOL_BITFIELD was_renamed : 1;
+
+  /* True when expression can't be moved.  */
+  BOOL_BITFIELD cant_move : 1;
+};
+
+typedef struct _expr expr_def;
+typedef expr_def *expr_t;
+
+#define EXPR_VINSN(EXPR) ((EXPR)->vinsn)
+#define EXPR_INSN_RTX(EXPR) (VINSN_INSN_RTX (EXPR_VINSN (EXPR)))
+#define EXPR_PATTERN(EXPR) (VINSN_PATTERN (EXPR_VINSN (EXPR)))
+#define EXPR_LHS(EXPR) (VINSN_LHS (EXPR_VINSN (EXPR)))
+#define EXPR_RHS(EXPR) (VINSN_RHS (EXPR_VINSN (EXPR)))
+#define EXPR_TYPE(EXPR) (VINSN_TYPE (EXPR_VINSN (EXPR)))
+#define EXPR_SEPARABLE_P(EXPR) (VINSN_SEPARABLE_P (EXPR_VINSN (EXPR)))
+
+#define EXPR_SPEC(EXPR) ((EXPR)->spec)
+#define EXPR_USEFULNESS(EXPR) ((EXPR)->usefulness)
+#define EXPR_PRIORITY(EXPR) ((EXPR)->priority)
+#define EXPR_PRIORITY_ADJ(EXPR) ((EXPR)->priority_adj)
+#define EXPR_SCHED_TIMES(EXPR) ((EXPR)->sched_times)
+#define EXPR_ORIG_BB_INDEX(EXPR) ((EXPR)->orig_bb_index)
+#define EXPR_ORIG_SCHED_CYCLE(EXPR) ((EXPR)->orig_sched_cycle)
+#define EXPR_SPEC_DONE_DS(EXPR) ((EXPR)->spec_done_ds)
+#define EXPR_SPEC_TO_CHECK_DS(EXPR) ((EXPR)->spec_to_check_ds)
+#define EXPR_HISTORY_OF_CHANGES(EXPR) ((EXPR)->history_of_changes)
+#define EXPR_TARGET_AVAILABLE(EXPR) ((EXPR)->target_available)
+#define EXPR_NEEDS_SPEC_CHECK_P(EXPR) ((EXPR)->needs_spec_check_p)
+#define EXPR_WAS_SUBSTITUTED(EXPR) ((EXPR)->was_substituted)
+#define EXPR_WAS_RENAMED(EXPR) ((EXPR)->was_renamed)
+#define EXPR_CANT_MOVE(EXPR) ((EXPR)->cant_move)
+
+#define EXPR_WAS_CHANGED(EXPR) (VEC_length (expr_history_def, \
+                                            EXPR_HISTORY_OF_CHANGES (EXPR)) > 0) 
+
+/* Insn definition for list of original insns in find_used_regs.  */
+struct _def
+{
+  insn_t orig_insn;
+
+  /* FIXME: Get rid of CROSSES_CALL in each def, since if we're moving up
+     rhs from two different places, but only one of the code motion paths
+     crosses a call, we can't use any of the call_used_regs, no matter which 
+     path or whether all paths crosses a call.  Thus we should move CROSSES_CALL
+     to static params.  */
+  bool crosses_call;
+};
+typedef struct _def *def_t;
+
+
+/* Availability sets are sets of expressions we're scheduling.  */
+typedef _list_t av_set_t;
+#define _AV_SET_EXPR(L) (&(L)->u.expr)
+#define _AV_SET_NEXT(L) (_LIST_NEXT (L))
+
+
+/* Boundary of the current fence group.  */
+struct _bnd
+{
+  /* The actual boundary instruction.  */
+  insn_t to;
+
+  /* Its path to the fence.  */
+  ilist_t ptr;
+
+  /* Availability set at the boundary.  */
+  av_set_t av;
+
+  /* This set moved to the fence.  */
+  av_set_t av1;
+  
+  /* Deps context at this boundary.  As long as we have one boundary per fence,
+     this is just a pointer to the same deps context as in the corresponding
+     fence.  */
+  deps_t dc;
+};
+typedef struct _bnd *bnd_t;
+#define BND_TO(B) ((B)->to)
+
+/* PTR stands not for pointer as you might think, but as a Path To Root of the
+   current instruction group from boundary B.  */
+#define BND_PTR(B) ((B)->ptr)
+#define BND_AV(B) ((B)->av)
+#define BND_AV1(B) ((B)->av1)
+#define BND_DC(B) ((B)->dc)
+
+/* List of boundaries.  */
+typedef _list_t blist_t;
+#define BLIST_BND(L) (&(L)->u.bnd)
+#define BLIST_NEXT(L) (_LIST_NEXT (L))
+
+
+/* Fence information.  A fence represents current scheduling point and also
+   blocks code motion through it when pipelining.  */
+struct _fence
+{
+  /* Insn before which we gather an instruction group.*/
+  insn_t insn;
+
+  /* Modeled state of the processor pipeline.  */
+  state_t state;
+
+  /* Current cycle that is being scheduled on this fence.  */
+  int cycle;
+
+  /* Number of insns that were scheduled on the current cycle.
+     This information has to be local to a fence.  */
+  int cycle_issued_insns;
+
+  /* At the end of fill_insns () this field holds the list of the instructions
+     that are inner boundaries of the scheduled parallel group.  */
+  ilist_t bnds;
+
+  /* Deps context at this fence.  It is used to model dependencies at the
+     fence so that insn ticks can be properly evaluated.  */
+  deps_t dc;
+
+  /* Target context at this fence.  Used to save and load any local target
+     scheduling information when changing fences.  */
+  tc_t tc;
+
+  /* A vector of insns that are scheduled but not yet completed.  */
+  VEC (rtx,gc) *executing_insns;
+
+  /* A vector indexed by UIDs that caches the earliest cycle on which 
+     an insn can be scheduled on this fence.  */
+  int *ready_ticks;
+
+  /* Its size.  */
+  int ready_ticks_size;
+
+  /* Insn, which has been scheduled last on this fence.  */
+  rtx last_scheduled_insn;
+
+  /* If non-NULL force the next scheduled insn to be SCHED_NEXT.  */
+  rtx sched_next;
+
+  /* True if fill_insns processed this fence.  */
+  BOOL_BITFIELD processed_p : 1;
+
+  /* True if fill_insns actually scheduled something on this fence.  */
+  BOOL_BITFIELD scheduled_p : 1;
+
+  /* True when the next insn scheduled here would start a cycle.  */
+  BOOL_BITFIELD starts_cycle_p : 1;
+
+  /* True when the next insn scheduled here would be scheduled after a stall.  */
+  BOOL_BITFIELD after_stall_p : 1;
+};
+typedef struct _fence *fence_t;
+
+#define FENCE_INSN(F) ((F)->insn)
+#define FENCE_STATE(F) ((F)->state)
+#define FENCE_BNDS(F) ((F)->bnds)
+#define FENCE_PROCESSED_P(F) ((F)->processed_p)
+#define FENCE_SCHEDULED_P(F) ((F)->scheduled_p)
+#define FENCE_ISSUED_INSNS(F) ((F)->cycle_issued_insns)
+#define FENCE_CYCLE(F) ((F)->cycle)
+#define FENCE_STARTS_CYCLE_P(F) ((F)->starts_cycle_p)
+#define FENCE_AFTER_STALL_P(F) ((F)->after_stall_p)
+#define FENCE_DC(F) ((F)->dc)
+#define FENCE_TC(F) ((F)->tc)
+#define FENCE_LAST_SCHEDULED_INSN(F) ((F)->last_scheduled_insn)
+#define FENCE_EXECUTING_INSNS(F) ((F)->executing_insns)
+#define FENCE_READY_TICKS(F) ((F)->ready_ticks)
+#define FENCE_READY_TICKS_SIZE(F) ((F)->ready_ticks_size)
+#define FENCE_SCHED_NEXT(F) ((F)->sched_next)
+
+/* List of fences.  */
+typedef _list_t flist_t;
+#define FLIST_FENCE(L) (&(L)->u.fence)
+#define FLIST_NEXT(L) (_LIST_NEXT (L))
+
+/* List of fences with pointer to the tail node.  */
+struct flist_tail_def
+{
+  flist_t head;
+  flist_t *tailp;
+};
+
+typedef struct flist_tail_def *flist_tail_t;
+#define FLIST_TAIL_HEAD(L) ((L)->head)
+#define FLIST_TAIL_TAILP(L) ((L)->tailp)
+
+/* List node information.  A list node can be any of the types above.  */
+struct _list_node
+{
+  _list_t next;
+
+  union
+  {
+    rtx x;
+    struct _bnd bnd;
+    expr_def expr;
+    struct _fence fence;
+    struct _def def;
+    void *data;
+  } u;
+};
+\f
+
+/* _list_t functions.
+   All of _*list_* functions are used through accessor macros, thus
+   we can't move them in sel-sched-ir.c.  */
+extern alloc_pool sched_lists_pool;
+
+static inline _list_t
+_list_alloc (void)
+{
+  return (_list_t) pool_alloc (sched_lists_pool);
+}
+
+static inline void
+_list_add (_list_t *lp)
+{
+  _list_t l = _list_alloc ();
+
+  _LIST_NEXT (l) = *lp;
+  *lp = l;
+}
+
+static inline void
+_list_remove_nofree (_list_t *lp)
+{
+  _list_t n = *lp;
+
+  *lp = _LIST_NEXT (n);
+}
+
+static inline void
+_list_remove (_list_t *lp)
+{
+  _list_t n = *lp;
+
+  *lp = _LIST_NEXT (n);
+  pool_free (sched_lists_pool, n);
+}
+
+static inline void
+_list_clear (_list_t *l)
+{
+  while (*l)
+    _list_remove (l);
+}
+\f
+
+/* List iterator backend.  */
+typedef struct
+{
+  /* The list we're iterating.  */
+  _list_t *lp;
+
+  /* True when this iterator supprts removing.  */
+  bool can_remove_p;
+
+  /* True when we've actually removed something.  */
+  bool removed_p;
+} _list_iterator;
+
+static inline void
+_list_iter_start (_list_iterator *ip, _list_t *lp, bool can_remove_p)
+{
+  ip->lp = lp;
+  ip->can_remove_p = can_remove_p;
+  ip->removed_p = false;
+}
+
+static inline void
+_list_iter_next (_list_iterator *ip)
+{
+  if (!ip->removed_p)
+    ip->lp = &_LIST_NEXT (*ip->lp);
+  else
+    ip->removed_p = false;
+}
+
+static inline void
+_list_iter_remove (_list_iterator *ip)
+{
+  gcc_assert (!ip->removed_p && ip->can_remove_p);
+  _list_remove (ip->lp);
+  ip->removed_p = true;
+}
+
+static inline void
+_list_iter_remove_nofree (_list_iterator *ip)
+{
+  gcc_assert (!ip->removed_p && ip->can_remove_p);
+  _list_remove_nofree (ip->lp);
+  ip->removed_p = true;
+}
+
+/* General macros to traverse a list.  FOR_EACH_* interfaces are
+   implemented using these.  */
+#define _FOR_EACH(TYPE, ELEM, I, L)                            \
+  for (_list_iter_start (&(I), &(L), false);                   \
+       _list_iter_cond_##TYPE (*(I).lp, &(ELEM));              \
+       _list_iter_next (&(I)))
+
+#define _FOR_EACH_1(TYPE, ELEM, I, LP)                              \
+  for (_list_iter_start (&(I), (LP), true);                         \
+       _list_iter_cond_##TYPE (*(I).lp, &(ELEM));                   \
+       _list_iter_next (&(I))) 
+\f
+
+/* _xlist_t functions.  */
+
+static inline void
+_xlist_add (_xlist_t *lp, rtx x)
+{
+  _list_add (lp);
+  _XLIST_X (*lp) = x;
+}
+
+#define _xlist_remove(LP) (_list_remove (LP))
+#define _xlist_clear(LP) (_list_clear (LP))
+
+static inline bool
+_xlist_is_in_p (_xlist_t l, rtx x)
+{
+  while (l)
+    {
+      if (_XLIST_X (l) == x)
+        return true;
+      l = _XLIST_NEXT (l);
+    }
+
+  return false;
+}
+
+/* Used through _FOR_EACH.  */
+static inline bool
+_list_iter_cond_x (_xlist_t l, rtx *xp)
+{
+  if (l)
+    {
+      *xp = _XLIST_X (l);
+      return true;
+    }
+
+  return false;
+}
+
+#define _xlist_iter_remove(IP) (_list_iter_remove (IP))
+
+typedef _list_iterator _xlist_iterator;
+#define _FOR_EACH_X(X, I, L) _FOR_EACH (x, (X), (I), (L))
+#define _FOR_EACH_X_1(X, I, LP) _FOR_EACH_1 (x, (X), (I), (LP))
+\f
+
+/* ilist_t functions.  Instruction lists are simply RTX lists.  */
+
+#define ilist_add(LP, INSN) (_xlist_add ((LP), (INSN)))
+#define ilist_remove(LP) (_xlist_remove (LP))
+#define ilist_clear(LP) (_xlist_clear (LP))
+#define ilist_is_in_p(L, INSN) (_xlist_is_in_p ((L), (INSN)))
+#define ilist_iter_remove(IP) (_xlist_iter_remove (IP))
+
+typedef _xlist_iterator ilist_iterator;
+#define FOR_EACH_INSN(INSN, I, L) _FOR_EACH_X (INSN, I, L)
+#define FOR_EACH_INSN_1(INSN, I, LP) _FOR_EACH_X_1 (INSN, I, LP)
+\f
+
+/* Av set iterators.  */
+typedef _list_iterator av_set_iterator;
+#define FOR_EACH_EXPR(EXPR, I, AV) _FOR_EACH (expr, (EXPR), (I), (AV))
+#define FOR_EACH_EXPR_1(EXPR, I, AV) _FOR_EACH_1 (expr, (EXPR), (I), (AV))
+
+static bool
+_list_iter_cond_expr (av_set_t av, expr_t *exprp)
+{
+  if (av)
+    {
+      *exprp = _AV_SET_EXPR (av);
+      return true;
+    }
+
+  return false;
+}
+\f
+
+/* Def list iterators.  */
+typedef _list_t def_list_t;
+typedef _list_iterator def_list_iterator;
+
+#define DEF_LIST_NEXT(L) (_LIST_NEXT (L))
+#define DEF_LIST_DEF(L) (&(L)->u.def)
+
+#define FOR_EACH_DEF(DEF, I, DEF_LIST) _FOR_EACH (def, (DEF), (I), (DEF_LIST))
+
+static inline bool
+_list_iter_cond_def (def_list_t def_list, def_t *def)
+{
+  if (def_list)
+    {
+      *def = DEF_LIST_DEF (def_list);
+      return true;
+    }
+
+  return false;
+}
+\f
+
+/* InstructionData.  Contains information about insn pattern.  */
+struct idata_def
+{
+  /* Type of the insn.
+     o CALL_INSN - Call insn
+     o JUMP_INSN - Jump insn
+     o INSN - INSN that cannot be cloned
+     o USE - INSN that can be cloned
+     o SET - INSN that can be cloned and separable into lhs and rhs
+     o PC - simplejump.  Insns that simply redirect control flow should not
+     have any dependencies.  Sched-deps.c, though, might consider them as
+     producers or consumers of certain registers.  To avoid that we handle
+     dependency for simple jumps ourselves.  */
+  int type;
+
+  /* If insn is a SET, this is its left hand side.  */
+  rtx lhs;
+
+  /* If insn is a SET, this is its right hand side.  */
+  rtx rhs;
+
+  /* Registers that are set/used by this insn.  This info is now gathered
+     via sched-deps.c.  The downside of this is that we also use live info
+     from flow that is accumulated in the basic blocks.  These two infos
+     can be slightly inconsistent, hence in the beginning we make a pass
+     through CFG and calculating the conservative solution for the info in
+     basic blocks.  When this scheduler will be switched to use dataflow,
+     this can be unified as df gives us both per basic block and per
+     instruction info.  Actually, we don't do that pass and just hope
+     for the best.  */
+  regset reg_sets;
+
+  regset reg_clobbers;
+
+  regset reg_uses;
+};
+
+#define IDATA_TYPE(ID) ((ID)->type)
+#define IDATA_LHS(ID) ((ID)->lhs)
+#define IDATA_RHS(ID) ((ID)->rhs)
+#define IDATA_REG_SETS(ID) ((ID)->reg_sets)
+#define IDATA_REG_USES(ID) ((ID)->reg_uses)
+#define IDATA_REG_CLOBBERS(ID) ((ID)->reg_clobbers)
+
+/* Type to represent all needed info to emit an insn.
+   This is a virtual equivalent of the insn.
+   Every insn in the stream has an associated vinsn.  This is used
+   to reduce memory consumption basing on the fact that many insns
+   don't change through the scheduler.
+
+   vinsn can be either normal or unique.
+   * Normal vinsn is the one, that can be cloned multiple times and typically
+   corresponds to normal instruction.
+
+   * Unique vinsn derivates from CALL, ASM, JUMP (for a while) and other
+   unusual stuff.  Such a vinsn is described by its INSN field, which is a
+   reference to the original instruction.  */
+struct vinsn_def
+{
+  /* Associated insn.  */
+  rtx insn_rtx;
+
+  /* Its description.  */
+  struct idata_def id;
+
+  /* Hash of vinsn.  It is computed either from pattern or from rhs using
+     hash_rtx.  It is not placed in ID for faster compares.  */
+  unsigned hash;
+
+  /* Hash of the insn_rtx pattern.  */
+  unsigned hash_rtx;
+
+  /* Smart pointer counter.  */
+  int count;
+
+  /* Cached cost of the vinsn.  To access it please use vinsn_cost ().  */
+  int cost;
+
+  /* Mark insns that may trap so we don't move them through jumps.  */
+  bool may_trap_p;
+};
+
+#define VINSN_INSN_RTX(VI) ((VI)->insn_rtx)
+#define VINSN_PATTERN(VI) (PATTERN (VINSN_INSN_RTX (VI)))
+
+#define VINSN_ID(VI) (&((VI)->id))
+#define VINSN_HASH(VI) ((VI)->hash)
+#define VINSN_HASH_RTX(VI) ((VI)->hash_rtx)
+#define VINSN_TYPE(VI) (IDATA_TYPE (VINSN_ID (VI)))
+#define VINSN_SEPARABLE_P(VI) (VINSN_TYPE (VI) == SET)
+#define VINSN_CLONABLE_P(VI) (VINSN_SEPARABLE_P (VI) || VINSN_TYPE (VI) == USE)
+#define VINSN_UNIQUE_P(VI) (!VINSN_CLONABLE_P (VI))
+#define VINSN_LHS(VI) (IDATA_LHS (VINSN_ID (VI)))
+#define VINSN_RHS(VI) (IDATA_RHS (VINSN_ID (VI)))
+#define VINSN_REG_SETS(VI) (IDATA_REG_SETS (VINSN_ID (VI)))
+#define VINSN_REG_USES(VI) (IDATA_REG_USES (VINSN_ID (VI)))
+#define VINSN_REG_CLOBBERS(VI) (IDATA_REG_CLOBBERS (VINSN_ID (VI)))
+#define VINSN_COUNT(VI) ((VI)->count)
+#define VINSN_MAY_TRAP_P(VI) ((VI)->may_trap_p)
+\f
+
+/* An entry of the hashtable describing transformations happened when 
+   moving up through an insn.  */
+struct transformed_insns
+{
+  /* Previous vinsn.  Used to find the proper element.  */
+  vinsn_t vinsn_old;
+
+  /* A new vinsn.  */
+  vinsn_t vinsn_new;
+
+  /* Speculative status.  */
+  ds_t ds;
+
+  /* Type of transformation happened.  */
+  enum local_trans_type type;
+
+  /* Whether a conflict on the target register happened.  */
+  BOOL_BITFIELD was_target_conflict : 1;
+
+  /* Whether a check was needed.  */
+  BOOL_BITFIELD needs_check : 1;
+};
+
+/* Indexed by INSN_LUID, the collection of all data associated with
+   a single instruction that is in the stream.  */
+struct _sel_insn_data
+{
+  /* The expression that contains vinsn for this insn and some
+     flow-sensitive data like priority.  */
+  expr_def expr;
+
+  /* If (WS_LEVEL == GLOBAL_LEVEL) then AV is empty.  */
+  int ws_level;
+
+  /* A number that helps in defining a traversing order for a region.  */
+  int seqno;
+
+  /* A liveness data computed above this insn.  */
+  regset live;
+
+  /* An INSN_UID bit is set when deps analysis result is already known.  */
+  bitmap analyzed_deps;
+
+  /* An INSN_UID bit is set when a hard dep was found, not set when 
+     no dependence is found.  This is meaningful only when the analyzed_deps
+     bitmap has its bit set.  */
+  bitmap found_deps;
+
+  /* An INSN_UID bit is set when this is a bookkeeping insn generated from 
+     a parent with this uid.  */
+  bitmap originators;
+
+  /* A hashtable caching the result of insn transformations through this one.  */
+  htab_t transformed_insns;
+  
+  /* A context incapsulating this insn.  */
+  struct deps deps_context;
+
+  /* This field is initialized at the beginning of scheduling and is used
+     to handle sched group instructions.  If it is non-null, then it points
+     to the instruction, which should be forced to schedule next.  Such
+     instructions are unique.  */
+  insn_t sched_next;
+
+  /* Cycle at which insn was scheduled.  It is greater than zero if insn was
+     scheduled.  This is used for bundling.  */
+  int sched_cycle;
+
+  /* Cycle at which insn's data will be fully ready.  */
+  int ready_cycle;
+
+  /* Speculations that are being checked by this insn.  */
+  ds_t spec_checked_ds;
+
+  /* Whether the live set valid or not.  */
+  BOOL_BITFIELD live_valid_p : 1;
+  /* Insn is an ASM.  */
+  BOOL_BITFIELD asm_p : 1;
+
+  /* True when an insn is scheduled after we've determined that a stall is
+     required.
+     This is used when emulating the Haifa scheduler for bundling.  */
+  BOOL_BITFIELD after_stall_p : 1;
+};
+
+typedef struct _sel_insn_data sel_insn_data_def;
+typedef sel_insn_data_def *sel_insn_data_t;
+
+DEF_VEC_O (sel_insn_data_def);
+DEF_VEC_ALLOC_O (sel_insn_data_def, heap);
+extern VEC (sel_insn_data_def, heap) *s_i_d;
+
+/* Accessor macros for s_i_d.  */
+#define SID(INSN) (VEC_index (sel_insn_data_def, s_i_d,        INSN_LUID (INSN)))
+#define SID_BY_UID(UID) (VEC_index (sel_insn_data_def, s_i_d,  LUID_BY_UID (UID)))
+
+extern sel_insn_data_def insn_sid (insn_t);
+
+#define INSN_ASM_P(INSN) (SID (INSN)->asm_p)
+#define INSN_SCHED_NEXT(INSN) (SID (INSN)->sched_next)
+#define INSN_ANALYZED_DEPS(INSN) (SID (INSN)->analyzed_deps)
+#define INSN_FOUND_DEPS(INSN) (SID (INSN)->found_deps) 
+#define INSN_DEPS_CONTEXT(INSN) (SID (INSN)->deps_context) 
+#define INSN_ORIGINATORS(INSN) (SID (INSN)->originators)
+#define INSN_ORIGINATORS_BY_UID(UID) (SID_BY_UID (UID)->originators)
+#define INSN_TRANSFORMED_INSNS(INSN) (SID (INSN)->transformed_insns)
+
+#define INSN_EXPR(INSN) (&SID (INSN)->expr)
+#define INSN_LIVE(INSN) (SID (INSN)->live)
+#define INSN_LIVE_VALID_P(INSN) (SID (INSN)->live_valid_p)
+#define INSN_VINSN(INSN) (EXPR_VINSN (INSN_EXPR (INSN)))
+#define INSN_TYPE(INSN) (VINSN_TYPE (INSN_VINSN (INSN)))
+#define INSN_SIMPLEJUMP_P(INSN) (INSN_TYPE (INSN) == PC)
+#define INSN_LHS(INSN) (VINSN_LHS (INSN_VINSN (INSN)))
+#define INSN_RHS(INSN) (VINSN_RHS (INSN_VINSN (INSN)))
+#define INSN_REG_SETS(INSN) (VINSN_REG_SETS (INSN_VINSN (INSN)))
+#define INSN_REG_CLOBBERS(INSN) (VINSN_REG_CLOBBERS (INSN_VINSN (INSN)))
+#define INSN_REG_USES(INSN) (VINSN_REG_USES (INSN_VINSN (INSN)))
+#define INSN_SCHED_TIMES(INSN) (EXPR_SCHED_TIMES (INSN_EXPR (INSN)))
+#define INSN_SEQNO(INSN) (SID (INSN)->seqno)
+#define INSN_AFTER_STALL_P(INSN) (SID (INSN)->after_stall_p)
+#define INSN_SCHED_CYCLE(INSN) (SID (INSN)->sched_cycle)
+#define INSN_READY_CYCLE(INSN) (SID (INSN)->ready_cycle)
+#define INSN_SPEC_CHECKED_DS(INSN) (SID (INSN)->spec_checked_ds)
+
+/* A global level shows whether an insn is valid or not.  */
+extern int global_level;
+
+#define INSN_WS_LEVEL(INSN) (SID (INSN)->ws_level)
+
+extern av_set_t get_av_set (insn_t);
+extern int get_av_level (insn_t);
+
+#define AV_SET(INSN) (get_av_set (INSN))
+#define AV_LEVEL(INSN) (get_av_level (INSN))
+#define AV_SET_VALID_P(INSN) (AV_LEVEL (INSN) == global_level)
+
+/* A list of fences currently in the works.  */
+extern flist_t fences;
+
+/* A NOP pattern used as a placeholder for real insns.  */
+extern rtx nop_pattern;
+
+/* An insn that 'contained' in EXIT block.  */
+extern rtx exit_insn;
+
+/* Provide a separate luid for the insn.  */
+#define INSN_INIT_TODO_LUID (1)
+
+/* Initialize s_s_i_d.  */
+#define INSN_INIT_TODO_SSID (2)
+
+/* Initialize data for simplejump.  */
+#define INSN_INIT_TODO_SIMPLEJUMP (4)
+
+/* Return true if INSN is a local NOP.  The nop is local in the sense that
+   it was emitted by the scheduler as a temporary insn and will soon be
+   deleted.  These nops are identified by their pattern.  */
+#define INSN_NOP_P(INSN) (PATTERN (INSN) == nop_pattern)
+
+/* Return true if INSN is linked into instruction stream.
+   NB: It is impossible for INSN to have one field null and the other not
+   null: gcc_assert ((PREV_INSN (INSN) == NULL_RTX)
+   == (NEXT_INSN (INSN) == NULL_RTX)) is valid.  */
+#define INSN_IN_STREAM_P(INSN) (PREV_INSN (INSN) && NEXT_INSN (INSN))
+
+/* Return true if INSN is in current fence.  */
+#define IN_CURRENT_FENCE_P(INSN) (flist_lookup (fences, INSN) != NULL)
+
+/* Marks loop as being considered for pipelining.  */
+#define MARK_LOOP_FOR_PIPELINING(LOOP) ((LOOP)->aux = (void *)(size_t)(1))
+#define LOOP_MARKED_FOR_PIPELINING_P(LOOP) ((size_t)((LOOP)->aux))
+
+/* Saved loop preheader to transfer when scheduling the loop.  */
+#define LOOP_PREHEADER_BLOCKS(LOOP) ((size_t)((LOOP)->aux) == 1         \
+                                     ? NULL                             \
+                                     : ((VEC(basic_block, heap) *) (LOOP)->aux))
+#define SET_LOOP_PREHEADER_BLOCKS(LOOP,BLOCKS) ((LOOP)->aux             \
+                                                = (BLOCKS != NULL       \
+                                                   ? BLOCKS             \
+                                                   : (LOOP)->aux))
+
+extern bitmap blocks_to_reschedule;
+\f
+
+/* A variable to track which part of rtx we are scanning in
+   sched-deps.c: sched_analyze_insn ().  */
+enum deps_where_def
+  {
+    DEPS_IN_INSN,
+    DEPS_IN_LHS,
+    DEPS_IN_RHS,
+    DEPS_IN_NOWHERE
+  };
+typedef enum deps_where_def deps_where_t;
+\f
+
+/* Per basic block data for the whole CFG.  */
+typedef struct
+{
+  /* For each bb header this field contains a set of live registers.
+     For all other insns this field has a NULL.
+     We also need to know LV sets for the instructions, that are immediatly
+     after the border of the region.  */
+  regset lv_set;
+
+  /* Status of LV_SET.
+     true - block has usable LV_SET.
+     false - block's LV_SET should be recomputed.  */
+  bool lv_set_valid_p;
+} sel_global_bb_info_def;
+
+typedef sel_global_bb_info_def *sel_global_bb_info_t;
+
+DEF_VEC_O (sel_global_bb_info_def);
+DEF_VEC_ALLOC_O (sel_global_bb_info_def, heap);
+
+/* Per basic block data.  This array is indexed by basic block index.  */
+extern VEC (sel_global_bb_info_def, heap) *sel_global_bb_info;
+
+extern void sel_extend_global_bb_info (void);
+extern void sel_finish_global_bb_info (void);
+
+/* Get data for BB.  */
+#define SEL_GLOBAL_BB_INFO(BB)                                 \
+  (VEC_index (sel_global_bb_info_def, sel_global_bb_info, (BB)->index))
+
+/* Access macros.  */
+#define BB_LV_SET(BB) (SEL_GLOBAL_BB_INFO (BB)->lv_set)
+#define BB_LV_SET_VALID_P(BB) (SEL_GLOBAL_BB_INFO (BB)->lv_set_valid_p)
+
+/* Per basic block data for the region.  */
+typedef struct 
+{
+  /* This insn stream is constructed in such a way that it should be
+     traversed by PREV_INSN field - (*not* NEXT_INSN).  */
+  rtx note_list;
+
+  /* Cached availability set at the beginning of a block.
+     See also AV_LEVEL () for conditions when this av_set can be used.  */
+  av_set_t av_set;
+
+  /* If (AV_LEVEL == GLOBAL_LEVEL) then AV is valid.  */
+  int av_level;
+} sel_region_bb_info_def;
+
+typedef sel_region_bb_info_def *sel_region_bb_info_t;
+
+DEF_VEC_O (sel_region_bb_info_def);
+DEF_VEC_ALLOC_O (sel_region_bb_info_def, heap);
+
+/* Per basic block data.  This array is indexed by basic block index.  */
+extern VEC (sel_region_bb_info_def, heap) *sel_region_bb_info;
+
+/* Get data for BB.  */
+#define SEL_REGION_BB_INFO(BB) (VEC_index (sel_region_bb_info_def,     \
+                                          sel_region_bb_info, (BB)->index))
+
+/* Get BB's note_list.
+   A note_list is a list of various notes that was scattered across BB
+   before scheduling, and will be appended at the beginning of BB after
+   scheduling is finished.  */
+#define BB_NOTE_LIST(BB) (SEL_REGION_BB_INFO (BB)->note_list)
+
+#define BB_AV_SET(BB) (SEL_REGION_BB_INFO (BB)->av_set)
+#define BB_AV_LEVEL(BB) (SEL_REGION_BB_INFO (BB)->av_level)
+#define BB_AV_SET_VALID_P(BB) (BB_AV_LEVEL (BB) == global_level)
+
+/* Used in bb_in_ebb_p.  */
+extern bitmap_head *forced_ebb_heads;
+
+/* The loop nest being pipelined.  */
+extern struct loop *current_loop_nest;
+
+/* Saves pipelined blocks.  Bitmap is indexed by bb->index.  */
+extern sbitmap bbs_pipelined;
+
+/* Various flags.  */
+extern bool enable_moveup_set_path_p;
+extern bool pipelining_p;
+extern bool bookkeeping_p;
+extern int max_insns_to_rename;  
+extern bool preheader_removed;
+
+/* Software lookahead window size.
+   According to the results in Nakatani and Ebcioglu [1993], window size of 16 
+   is enough to extract most ILP in integer code.  */
+#define MAX_WS (PARAM_VALUE (PARAM_SELSCHED_MAX_LOOKAHEAD))
+
+extern regset sel_all_regs;
+\f
+
+/* Successor iterator backend.  */
+typedef struct
+{
+  /* True if we're at BB end.  */
+  bool bb_end;
+
+  /* An edge on which we're iterating.  */
+  edge e1;
+
+  /* The previous edge saved after skipping empty blocks.  */
+  edge e2;
+  
+  /* Edge iterator used when there are successors in other basic blocks.  */
+  edge_iterator ei;
+
+  /* Successor block we're traversing.  */
+  basic_block bb;
+
+  /* Flags that are passed to the iterator.  We return only successors
+     that comply to these flags.  */
+  short flags;
+  
+  /* When flags include SUCCS_ALL, this will be set to the exact type 
+     of the sucessor we're traversing now.  */
+  short current_flags;
+
+  /* If skip to loop exits, save here information about loop exits.  */
+  int current_exit;
+  VEC (edge, heap) *loop_exits;
+} succ_iterator;
+
+/* A structure returning all successor's information.  */
+struct succs_info
+{
+  /* Flags that these succcessors were computed with.  */
+  short flags;
+
+  /* Successors that correspond to the flags.  */
+  insn_vec_t succs_ok;
+
+  /* Their probabilities.  As of now, we don't need this for other 
+     successors.  */
+  VEC(int,heap) *probs_ok;
+
+  /* Other successors.  */
+  insn_vec_t succs_other;
+
+  /* Probability of all successors.  */
+  int all_prob;
+
+  /* The number of all successors.  */
+  int all_succs_n;
+
+  /* The number of good successors.  */
+  int succs_ok_n;
+};
+
+/* Some needed definitions.  */
+extern basic_block after_recovery;
+
+extern insn_t sel_bb_head (basic_block);
+extern bool sel_bb_empty_p (basic_block);
+extern bool in_current_region_p (basic_block);
+
+/* True when BB is a header of the inner loop.  */
+static inline bool
+inner_loop_header_p (basic_block bb)
+{
+  struct loop *inner_loop; 
+
+  if (!current_loop_nest)
+    return false;
+
+  if (bb == EXIT_BLOCK_PTR)
+    return false;
+
+  inner_loop = bb->loop_father;
+  if (inner_loop == current_loop_nest)
+    return false;
+
+  /* If successor belongs to another loop.  */
+  if (bb == inner_loop->header
+      && flow_bb_inside_loop_p (current_loop_nest, bb))
+    {
+      /* Could be '=' here because of wrong loop depths.  */
+      gcc_assert (loop_depth (inner_loop) >= loop_depth (current_loop_nest));
+      return true;
+    }
+
+  return false;  
+}
+
+/* Return exit edges of LOOP, filtering out edges with the same dest bb.  */
+static inline VEC (edge, heap) *
+get_loop_exit_edges_unique_dests (const struct loop *loop)
+{
+  VEC (edge, heap) *edges = NULL;
+  struct loop_exit *exit;
+
+  gcc_assert (loop->latch != EXIT_BLOCK_PTR
+              && current_loops->state & LOOPS_HAVE_RECORDED_EXITS);
+
+  for (exit = loop->exits->next; exit->e; exit = exit->next)
+    {
+      int i;
+      edge e;
+      bool was_dest = false;
+      
+      for (i = 0; VEC_iterate (edge, edges, i, e); i++)
+        if (e->dest == exit->e->dest)
+          {
+            was_dest = true;
+            break;
+          }
+
+      if (!was_dest)
+        VEC_safe_push (edge, heap, edges, exit->e);
+    }
+  return edges;
+}
+
+/* Collect all loop exits recursively, skipping empty BBs between them.  
+   E.g. if BB is a loop header which has several loop exits,
+   traverse all of them and if any of them turns out to be another loop header
+   (after skipping empty BBs), add its loop exits to the resulting vector 
+   as well.  */
+static inline VEC(edge, heap) *
+get_all_loop_exits (basic_block bb)
+{
+  VEC(edge, heap) *exits = NULL;
+
+  /* If bb is empty, and we're skipping to loop exits, then
+     consider bb as a possible gate to the inner loop now.  */
+  while (sel_bb_empty_p (bb) 
+        && in_current_region_p (bb))
+    {
+      bb = single_succ (bb);
+
+      /* This empty block could only lead outside the region.  */
+      gcc_assert (! in_current_region_p (bb));
+    }
+
+  /* And now check whether we should skip over inner loop.  */
+  if (inner_loop_header_p (bb))
+    {
+      struct loop *this_loop;
+      struct loop *pred_loop = NULL;
+      int i;
+      edge e;
+      
+      for (this_loop = bb->loop_father;
+           this_loop && this_loop != current_loop_nest;
+           this_loop = loop_outer (this_loop))
+        pred_loop = this_loop;
+      
+      this_loop = pred_loop;
+      gcc_assert (this_loop != NULL);
+
+      exits = get_loop_exit_edges_unique_dests (this_loop);
+
+      /* Traverse all loop headers.  */
+      for (i = 0; VEC_iterate (edge, exits, i, e); i++)
+       if (in_current_region_p (e->dest))
+         {
+           VEC(edge, heap) *next_exits = get_all_loop_exits (e->dest);
+  
+           if (next_exits)
+             {
+               int j;
+               edge ne;
+  
+               /* Add all loop exits for the current edge into the
+                  resulting vector.  */
+               for (j = 0; VEC_iterate (edge, next_exits, j, ne); j++)
+                 VEC_safe_push (edge, heap, exits, ne);
+  
+               /* Remove the original edge.  */
+               VEC_ordered_remove (edge, exits, i);
+
+               /*  Decrease the loop counter so we won't skip anything.  */
+               i--;
+               continue;
+             }
+         }
+    }
+
+  return exits;
+}
+
+/* Flags to pass to compute_succs_info and FOR_EACH_SUCC.
+   Any successor will fall into exactly one category.   */
+
+/* Include normal successors.  */
+#define SUCCS_NORMAL (1)
+
+/* Include back-edge successors.  */
+#define SUCCS_BACK (2)
+
+/* Include successors that are outside of the current region.  */
+#define SUCCS_OUT (4)
+
+/* When pipelining of the outer loops is enabled, skip innermost loops 
+   to their exits.  */
+#define SUCCS_SKIP_TO_LOOP_EXITS (8)
+
+/* Include all successors.  */
+#define SUCCS_ALL (SUCCS_NORMAL | SUCCS_BACK | SUCCS_OUT)
+
+/* We need to return a succ_iterator to avoid 'unitialized' warning
+   during bootstrap.  */
+static inline succ_iterator
+_succ_iter_start (insn_t *succp, insn_t insn, int flags)
+{
+  succ_iterator i;
+
+  basic_block bb = BLOCK_FOR_INSN (insn);
+
+  gcc_assert (INSN_P (insn) || NOTE_INSN_BASIC_BLOCK_P (insn));
+
+  i.flags = flags;
+
+  /* Avoid 'uninitialized' warning.  */
+  *succp = NULL;
+  i.e1 = NULL;
+  i.e2 = NULL;
+  i.bb = bb;
+  i.current_flags = 0;
+  i.current_exit = -1;
+  i.loop_exits = NULL;
+
+  if (bb != EXIT_BLOCK_PTR && BB_END (bb) != insn)
+    {
+      i.bb_end = false;
+
+      /* Avoid 'uninitialized' warning.  */
+      i.ei.index = 0;
+      i.ei.container = NULL;
+    }
+  else
+    {
+      i.ei = ei_start (bb->succs);
+      i.bb_end = true;
+    }
+
+  return i;
+}
+
+static inline bool
+_succ_iter_cond (succ_iterator *ip, rtx *succp, rtx insn,
+                 bool check (edge, succ_iterator *))
+{
+  if (!ip->bb_end)
+    {
+      /* When we're in a middle of a basic block, return
+         the next insn immediately, but only when SUCCS_NORMAL is set.  */
+      if (*succp != NULL || (ip->flags & SUCCS_NORMAL) == 0)
+        return false;
+
+      *succp = NEXT_INSN (insn);
+      ip->current_flags = SUCCS_NORMAL;
+      return true;
+    }
+  else
+    {
+      while (1) 
+        {
+          edge e_tmp = NULL;
+
+          /* First, try loop exits, if we have them.  */
+          if (ip->loop_exits)
+            {
+              do
+                {
+                  VEC_iterate (edge, ip->loop_exits, 
+                               ip->current_exit, e_tmp);
+                  ip->current_exit++;
+                }
+             while (e_tmp && !check (e_tmp, ip));
+              
+              if (!e_tmp)
+                VEC_free (edge, heap, ip->loop_exits);
+            }
+
+          /* If we have found a successor, then great.  */
+          if (e_tmp)
+            {
+              ip->e1 = e_tmp;
+              break;
+            }
+
+          /* If not, then try the next edge.  */
+          while (ei_cond (ip->ei, &(ip->e1)))
+            {
+              basic_block bb = ip->e1->dest;
+
+              /* Consider bb as a possible loop header.  */
+              if ((ip->flags & SUCCS_SKIP_TO_LOOP_EXITS)
+                  && flag_sel_sched_pipelining_outer_loops
+                 && (!in_current_region_p (bb) 
+                     || BLOCK_TO_BB (ip->bb->index) 
+                        < BLOCK_TO_BB (bb->index)))
+                {
+                 /* Get all loop exits recursively.  */
+                 ip->loop_exits = get_all_loop_exits (bb);
+
+                 if (ip->loop_exits)
+                   {
+                     ip->current_exit = 0;
+                     /* Move the iterator now, because we won't do 
+                        succ_iter_next until loop exits will end.  */
+                     ei_next (&(ip->ei));
+                     break;
+                   }
+                }
+
+              /* bb is not a loop header, check as usual.  */
+              if (check (ip->e1, ip))
+                break;
+
+              ei_next (&(ip->ei));
+            }
+
+          /* If loop_exits are non null, we have found an inner loop;
+            do one more iteration to fetch an edge from these exits.  */
+          if (ip->loop_exits)
+            continue;
+
+          /* Otherwise, we've found an edge in a usual way.  Break now.  */
+          break;
+        }
+
+      if (ip->e1)
+       {
+         basic_block bb = ip->e2->dest;
+
+         if (bb == EXIT_BLOCK_PTR || bb == after_recovery)
+           *succp = exit_insn;
+         else
+           {
+              *succp = sel_bb_head (bb);
+
+              gcc_assert (ip->flags != SUCCS_NORMAL
+                          || *succp == NEXT_INSN (bb_note (bb)));
+             gcc_assert (BLOCK_FOR_INSN (*succp) == bb);
+           }
+
+         return true;
+       }
+      else
+       return false;
+    }
+}
+
+static inline void
+_succ_iter_next (succ_iterator *ip)
+{
+  gcc_assert (!ip->e2 || ip->e1);
+
+  if (ip->bb_end && ip->e1 && !ip->loop_exits)
+    ei_next (&(ip->ei));
+}
+
+/* Returns true when E1 is an eligible successor edge, possibly skipping
+   empty blocks.  When E2P is not null, the resulting edge is written there.
+   FLAGS are used to specify whether back edges and out-of-region edges
+   should be considered.  */
+static inline bool
+_eligible_successor_edge_p (edge e1, succ_iterator *ip)
+{
+  edge e2 = e1;
+  basic_block bb;
+  int flags = ip->flags;
+  bool src_outside_rgn = !in_current_region_p (e1->src);
+
+  gcc_assert (flags != 0);
+
+  if (src_outside_rgn)
+    {
+      /* Any successor of the block that is outside current region is
+         ineligible, except when we're skipping to loop exits.  */
+      gcc_assert (flags & (SUCCS_OUT | SUCCS_SKIP_TO_LOOP_EXITS));
+
+      if (flags & SUCCS_OUT)
+       return false;
+    }
+
+  bb = e2->dest;
+
+  /* Skip empty blocks, but be careful not to leave the region.  */
+  while (1)
+    {
+      if (!sel_bb_empty_p (bb))
+        break;
+        
+      if (!in_current_region_p (bb) 
+          && !(flags & SUCCS_OUT))
+        return false;
+
+      e2 = EDGE_SUCC (bb, 0);
+      bb = e2->dest;
+      
+      /* This couldn't happen inside a region.  */
+      gcc_assert (! in_current_region_p (bb)
+                  || (flags & SUCCS_OUT));
+    }
+  
+  /* Save the second edge for later checks.  */
+  ip->e2 = e2;
+
+  if (in_current_region_p (bb))
+    {
+      /* BLOCK_TO_BB sets topological order of the region here.  
+         It is important to use real predecessor here, which is ip->bb, 
+         as we may well have e1->src outside current region, 
+         when skipping to loop exits.  */
+      bool succeeds_in_top_order = (BLOCK_TO_BB (ip->bb->index)
+                                   < BLOCK_TO_BB (bb->index));
+
+      /* This is true for the all cases except the last one.  */
+      ip->current_flags = SUCCS_NORMAL;
+      
+      /* We are advancing forward in the region, as usual.  */
+      if (succeeds_in_top_order)
+        {
+          /* We are skipping to loop exits here.  */
+          gcc_assert (!src_outside_rgn
+                      || flag_sel_sched_pipelining_outer_loops);
+          return !!(flags & SUCCS_NORMAL);
+        }
+
+      /* This is a back edge.  During pipelining we ignore back edges, 
+         but only when it leads to the same loop.  It can lead to the header
+         of the outer loop, which will also be the preheader of 
+         the current loop.  */
+      if (pipelining_p
+           && e1->src->loop_father == bb->loop_father)
+        return !!(flags & SUCCS_NORMAL);
+
+      /* A back edge should be requested explicitly.  */
+      ip->current_flags = SUCCS_BACK;
+      return !!(flags & SUCCS_BACK);
+    }
+
+  ip->current_flags = SUCCS_OUT;
+  return !!(flags & SUCCS_OUT);
+}
+
+#define FOR_EACH_SUCC_1(SUCC, ITER, INSN, FLAGS)                        \
+  for ((ITER) = _succ_iter_start (&(SUCC), (INSN), (FLAGS));            \
+       _succ_iter_cond (&(ITER), &(SUCC), (INSN), _eligible_successor_edge_p); \
+       _succ_iter_next (&(ITER)))
+
+#define FOR_EACH_SUCC(SUCC, ITER, INSN)                 \
+  FOR_EACH_SUCC_1 (SUCC, ITER, INSN, SUCCS_NORMAL)
+
+/* Return the current edge along which a successor was built.  */
+#define SUCC_ITER_EDGE(ITER) ((ITER)->e1)
+
+/* Return the next block of BB not running into inconsistencies.  */
+static inline basic_block
+bb_next_bb (basic_block bb)
+{
+  switch (EDGE_COUNT (bb->succs))
+    {
+    case 0:
+      return bb->next_bb;
+
+    case 1: 
+      return single_succ (bb);
+
+    case 2:
+      return FALLTHRU_EDGE (bb)->dest;
+      
+    default:
+      return bb->next_bb;
+    }
+
+  gcc_unreachable ();
+}
+
+\f
+
+/* Functions that are used in sel-sched.c.  */
+
+/* List functions.  */
+extern ilist_t ilist_copy (ilist_t);
+extern ilist_t ilist_invert (ilist_t);
+extern void blist_add (blist_t *, insn_t, ilist_t, deps_t);
+extern void blist_remove (blist_t *);
+extern void flist_tail_init (flist_tail_t);
+
+extern fence_t flist_lookup (flist_t, insn_t);
+extern void flist_clear (flist_t *);
+extern void def_list_add (def_list_t *, insn_t, bool);
+
+/* Target context functions.  */
+extern tc_t create_target_context (bool);
+extern void set_target_context (tc_t);
+extern void reset_target_context (tc_t, bool);
+
+/* Deps context functions.  */
+extern void advance_deps_context (deps_t, insn_t);
+
+/* Fences functions.  */
+extern void init_fences (insn_t);
+extern void add_clean_fence_to_fences (flist_tail_t, insn_t, fence_t);
+extern void add_dirty_fence_to_fences (flist_tail_t, insn_t, fence_t);
+extern void move_fence_to_fences (flist_t, flist_tail_t);
+
+/* Pool functions.  */
+extern regset get_regset_from_pool (void);
+extern regset get_clear_regset_from_pool (void);
+extern void return_regset_to_pool (regset);
+extern void free_regset_pool (void);
+
+extern insn_t get_nop_from_pool (insn_t);
+extern void return_nop_to_pool (insn_t);
+extern void free_nop_pool (void);
+
+/* Vinsns functions.  */
+extern bool vinsn_separable_p (vinsn_t);
+extern bool vinsn_cond_branch_p (vinsn_t);
+extern void recompute_vinsn_lhs_rhs (vinsn_t);
+extern int sel_vinsn_cost (vinsn_t);
+extern insn_t sel_gen_insn_from_rtx_after (rtx, expr_t, int, insn_t);
+extern insn_t sel_gen_recovery_insn_from_rtx_after (rtx, expr_t, int, insn_t);
+extern insn_t sel_gen_insn_from_expr_after (expr_t, vinsn_t, int, insn_t);
+extern insn_t  sel_move_insn (expr_t, int, insn_t);
+extern void vinsn_attach (vinsn_t);
+extern void vinsn_detach (vinsn_t);
+extern vinsn_t vinsn_copy (vinsn_t, bool);
+extern bool vinsn_equal_p (vinsn_t, vinsn_t);
+
+/* EXPR functions.  */
+extern void copy_expr (expr_t, expr_t);
+extern void copy_expr_onside (expr_t, expr_t);
+extern void merge_expr_data (expr_t, expr_t, insn_t);
+extern void merge_expr (expr_t, expr_t, insn_t);
+extern void clear_expr (expr_t);
+extern unsigned expr_dest_regno (expr_t);
+extern rtx expr_dest_reg (expr_t); 
+extern int find_in_history_vect (VEC(expr_history_def, heap) *, 
+                                 rtx, vinsn_t, bool);
+extern void insert_in_history_vect (VEC(expr_history_def, heap) **, 
+                                    unsigned, enum local_trans_type, 
+                                    vinsn_t, vinsn_t, ds_t);
+extern void mark_unavailable_targets (av_set_t, av_set_t, regset);
+extern int speculate_expr (expr_t, ds_t);
+
+/* Av set functions.  */
+extern void av_set_add (av_set_t *, expr_t);
+extern void av_set_iter_remove (av_set_iterator *);
+extern expr_t av_set_lookup (av_set_t, vinsn_t);
+extern expr_t merge_with_other_exprs (av_set_t *, av_set_iterator *, expr_t);
+extern bool av_set_is_in_p (av_set_t, vinsn_t);
+extern av_set_t av_set_copy (av_set_t);
+extern void av_set_union_and_clear (av_set_t *, av_set_t *, insn_t);
+extern void av_set_union_and_live (av_set_t *, av_set_t *, regset, regset, insn_t);
+extern void av_set_clear (av_set_t *);
+extern void av_set_leave_one_nonspec (av_set_t *);
+extern expr_t av_set_element (av_set_t, int);
+extern void av_set_substract_cond_branches (av_set_t *);
+extern void av_set_split_usefulness (av_set_t, int, int);
+extern void av_set_intersect (av_set_t *, av_set_t);
+
+extern void sel_save_haifa_priorities (void);
+
+extern void sel_init_global_and_expr (bb_vec_t);
+extern void sel_finish_global_and_expr (void);
+
+extern regset compute_live (insn_t);
+
+/* Dependence analysis functions.  */
+extern void sel_clear_has_dependence (void);
+extern ds_t has_dependence_p (expr_t, insn_t, ds_t **);
+
+extern int tick_check_p (expr_t, deps_t, fence_t);
+
+/* Functions to work with insns.  */
+extern bool lhs_of_insn_equals_to_dest_p (insn_t, rtx);
+extern bool insn_eligible_for_subst_p (insn_t);
+extern void get_dest_and_mode (rtx, rtx *, enum machine_mode *);
+
+extern bool bookkeeping_can_be_created_if_moved_through_p (insn_t);
+extern bool sel_remove_insn (insn_t, bool, bool);
+extern bool bb_header_p (insn_t);
+extern void sel_init_invalid_data_sets (insn_t);
+extern bool insn_at_boundary_p (insn_t);
+extern bool jump_leads_only_to_bb_p (insn_t, basic_block);
+
+/* Basic block and CFG functions.  */
+
+extern insn_t sel_bb_head (basic_block);
+extern bool sel_bb_head_p (insn_t);
+extern insn_t sel_bb_end (basic_block);
+extern bool sel_bb_end_p (insn_t);
+extern bool sel_bb_empty_p (basic_block);
+
+extern bool in_current_region_p (basic_block);
+extern basic_block fallthru_bb_of_jump (rtx);
+
+extern void sel_init_bbs (bb_vec_t, basic_block);
+extern void sel_finish_bbs (void);
+
+extern struct succs_info * compute_succs_info (insn_t, short);
+extern void free_succs_info (struct succs_info *);
+extern bool sel_insn_has_single_succ_p (insn_t, int);
+extern bool sel_num_cfg_preds_gt_1 (insn_t);
+extern int get_seqno_by_preds (rtx);
+
+extern bool bb_ends_ebb_p (basic_block);
+extern bool in_same_ebb_p (insn_t, insn_t);
+
+extern bool tidy_control_flow (basic_block, bool);
+extern void free_bb_note_pool (void);
+
+extern void sel_remove_empty_bb (basic_block, bool, bool);
+extern bool maybe_tidy_empty_bb (basic_block bb);
+extern basic_block sel_split_edge (edge);
+extern basic_block sel_create_recovery_block (insn_t);
+extern void sel_merge_blocks (basic_block, basic_block);
+extern void sel_redirect_edge_and_branch (edge, basic_block);
+extern void sel_redirect_edge_and_branch_force (edge, basic_block);
+extern void sel_init_pipelining (void);
+extern void sel_finish_pipelining (void);
+extern void sel_sched_region (int);
+extern void sel_find_rgns (void);
+extern loop_p get_loop_nest_for_rgn (unsigned int);
+extern bool considered_for_pipelining_p (struct loop *);
+extern void make_region_from_loop_preheader (VEC(basic_block, heap) **);
+extern void sel_add_loop_preheaders (void);
+extern bool sel_is_loop_preheader_p (basic_block);
+extern void clear_outdated_rtx_info (basic_block);
+extern void free_data_sets (basic_block);
+extern void exchange_data_sets (basic_block, basic_block);
+extern void copy_data_sets (basic_block, basic_block);
+
+extern void sel_register_cfg_hooks (void);
+extern void sel_unregister_cfg_hooks (void);
+
+/* Expression transformation routines.  */
+extern rtx create_insn_rtx_from_pattern (rtx, rtx);
+extern vinsn_t create_vinsn_from_insn_rtx (rtx, bool);
+extern rtx create_copy_of_insn_rtx (rtx);
+extern void change_vinsn_in_expr (expr_t, vinsn_t);
+
+/* Various initialization functions.  */
+extern void init_lv_sets (void);
+extern void free_lv_sets (void);
+extern void setup_nop_and_exit_insns (void);
+extern void free_nop_and_exit_insns (void);
+extern void setup_nop_vinsn (void);
+extern void free_nop_vinsn (void);
+extern void sel_set_sched_flags (void);
+extern void sel_setup_sched_infos (void);
+extern void alloc_sched_pools (void);
+extern void free_sched_pools (void);
+
+#endif /* GCC_SEL_SCHED_IR_H */
+
+
+
+
+
+
+
+
diff --git a/gcc/sel-sched.c b/gcc/sel-sched.c
new file mode 100644 (file)
index 0000000..e2edb0a
--- /dev/null
@@ -0,0 +1,7327 @@
+/* Instruction scheduling pass.  Selective scheduler and pipeliner.
+   Copyright (C) 2006, 2007, 2008 Free Software Foundation, Inc.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free
+Software Foundation; either version 3, or (at your option) any later
+version.
+
+GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or
+FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3.  If not see
+<http://www.gnu.org/licenses/>.  */
+
+#include "config.h"
+#include "system.h"
+#include "coretypes.h"
+#include "tm.h"
+#include "toplev.h"
+#include "rtl.h"
+#include "tm_p.h"
+#include "hard-reg-set.h"
+#include "regs.h"
+#include "function.h"
+#include "flags.h"
+#include "insn-config.h"
+#include "insn-attr.h"
+#include "except.h"
+#include "toplev.h"
+#include "recog.h"
+#include "params.h"
+#include "target.h"
+#include "output.h"
+#include "timevar.h"
+#include "tree-pass.h"
+#include "sched-int.h"
+#include "ggc.h"
+#include "tree.h"
+#include "vec.h"
+#include "langhooks.h"
+#include "rtlhooks-def.h"
+#include "output.h"
+
+#ifdef INSN_SCHEDULING
+#include "sel-sched-ir.h"
+#include "sel-sched-dump.h"
+#include "sel-sched.h"
+#include "dbgcnt.h"
+
+/* Implementation of selective scheduling approach.
+   The below implementation follows the original approach with the following
+   changes:
+
+   o the scheduler works after register allocation (but can be also tuned 
+   to work before RA);
+   o some instructions are not copied or register renamed;
+   o conditional jumps are not moved with code duplication;
+   o several jumps in one parallel group are not supported;
+   o when pipelining outer loops, code motion through inner loops
+   is not supported;
+   o control and data speculation are supported;
+   o some improvements for better compile time/performance were made.
+
+   Terminology
+   ===========
+
+   A vinsn, or virtual insn, is an insn with additional data characterizing 
+   insn pattern, such as LHS, RHS, register sets used/set/clobbered, etc.  
+   Vinsns also act as smart pointers to save memory by reusing them in 
+   different expressions.  A vinsn is described by vinsn_t type.
+
+   An expression is a vinsn with additional data characterizing its properties
+   at some point in the control flow graph.  The data may be its usefulness, 
+   priority, speculative status, whether it was renamed/subsituted, etc.
+   An expression is described by expr_t type.
+
+   Availability set (av_set) is a set of expressions at a given control flow 
+   point. It is represented as av_set_t.  The expressions in av sets are kept
+   sorted in the terms of expr_greater_p function.  It allows to truncate 
+   the set while leaving the best expressions.
+   
+   A fence is a point through which code motion is prohibited.  On each step,
+   we gather a parallel group of insns at a fence.  It is possible to have
+   multiple fences. A fence is represented via fence_t.
+
+   A boundary is the border between the fence group and the rest of the code.
+   Currently, we never have more than one boundary per fence, as we finalize
+   the fence group when a jump is scheduled. A boundary is represented 
+   via bnd_t.
+
+   High-level overview
+   ===================
+
+   The scheduler finds regions to schedule, schedules each one, and finalizes.
+   The regions are formed starting from innermost loops, so that when the inner 
+   loop is pipelined, its prologue can be scheduled together with yet unprocessed
+   outer loop. The rest of acyclic regions are found using extend_rgns: 
+   the blocks that are not yet allocated to any regions are traversed in top-down
+   order, and a block is added to a region to which all its predecessors belong; 
+   otherwise, the block starts its own region.
+
+   The main scheduling loop (sel_sched_region_2) consists of just
+   scheduling on each fence and updating fences.  For each fence,
+   we fill a parallel group of insns (fill_insns) until some insns can be added.
+   First, we compute available exprs (av-set) at the boundary of the current 
+   group.  Second, we choose the best expression from it.  If the stall is 
+   required to schedule any of the expressions, we advance the current cycle
+   appropriately.  So, the final group does not exactly correspond to a VLIW 
+   word.  Third, we move the chosen expression to the boundary (move_op)
+   and update the intermediate av sets and liveness sets.  We quit fill_insns
+   when either no insns left for scheduling or we have scheduled enough insns
+   so we feel like advancing a scheduling point.  
+
+   Computing available expressions
+   ===============================
+
+   The computation (compute_av_set) is a bottom-up traversal.  At each insn,
+   we're moving the union of its successors' sets through it via 
+   moveup_expr_set.  The dependent expressions are removed.  Local 
+   transformations (substitution, speculation) are applied to move more 
+   exprs.  Then the expr corresponding to the current insn is added.
+   The result is saved on each basic block header.
+
+   When traversing the CFG, we're moving down for no more than max_ws insns.
+   Also, we do not move down to ineligible successors (is_ineligible_successor),
+   which include moving along a back-edge, moving to already scheduled code,
+   and moving to another fence.  The first two restrictions are lifted during 
+   pipelining, which allows us to move insns along a back-edge.  We always have
+   an acyclic region for scheduling because we forbid motion through fences.
+
+   Choosing the best expression
+   ============================
+
+   We sort the final availability set via sel_rank_for_schedule, then we remove
+   expressions which are not yet ready (tick_check_p) or which dest registers
+   cannot be used.  For some of them, we choose another register via 
+   find_best_reg.  To do this, we run find_used_regs to calculate the set of 
+   registers which cannot be used.  The find_used_regs function performs
+   a traversal of code motion paths for an expr.  We consider for renaming
+   only registers which are from the same regclass as the original one and 
+   using which does not interfere with any live ranges.  Finally, we convert
+   the resulting set to the ready list format and use max_issue and reorder*
+   hooks similarly to the Haifa scheduler.
+
+   Scheduling the best expression
+   ==============================
+
+   We run the move_op routine to perform the same type of code motion paths 
+   traversal as in find_used_regs.  (These are working via the same driver,
+   code_motion_path_driver.)  When moving down the CFG, we look for original
+   instruction that gave birth to a chosen expression.  We undo 
+   the transformations performed on an expression via the history saved in it.
+   When found, we remove the instruction or leave a reg-reg copy/speculation 
+   check if needed.  On a way up, we insert bookkeeping copies at each join 
+   point.  If a copy is not needed, it will be removed later during this 
+   traversal.  We update the saved av sets and liveness sets on the way up, too.
+
+   Finalizing the schedule
+   =======================
+
+   When pipelining, we reschedule the blocks from which insns were pipelined 
+   to get a tighter schedule.  On Itanium, we also perform bundling via 
+   the same routine from ia64.c.  
+
+   Dependence analysis changes
+   ===========================
+
+   We augmented the sched-deps.c with hooks that get called when a particular
+   dependence is found in a particular part of an insn.  Using these hooks, we
+   can do several actions such as: determine whether an insn can be moved through
+   another (has_dependence_p, moveup_expr); find out whether an insn can be 
+   scheduled on the current cycle (tick_check_p); find out registers that 
+   are set/used/clobbered by an insn and find out all the strange stuff that 
+   restrict its movement, like SCHED_GROUP_P or CANT_MOVE (done in 
+   init_global_and_expr_for_insn).
+
+   Initialization changes
+   ======================
+
+   There are parts of haifa-sched.c, sched-deps.c, and sched-rgn.c that are 
+   reused in all of the schedulers.  We have split up the initialization of data
+   of such parts into different functions prefixed with scheduler type and 
+   postfixed with the type of data initialized: {,sel_,haifa_}sched_{init,finish},
+   sched_rgn_init/finish, sched_deps_init/finish, sched_init_{luids/bbs}, etc.
+   The same splitting is done with current_sched_info structure: 
+   dependence-related parts are in sched_deps_info, common part is in 
+   common_sched_info, and haifa/sel/etc part is in current_sched_info.
+   
+   Target contexts
+   ===============
+
+   As we now have multiple-point scheduling, this would not work with backends
+   which save some of the scheduler state to use it in the target hooks.  
+   For this purpose, we introduce a concept of target contexts, which 
+   encapsulate such information.  The backend should implement simple routines
+   of allocating/freeing/setting such a context.  The scheduler calls these
+   as target hooks and handles the target context as an opaque pointer (similar
+   to the DFA state type, state_t).
+
+   Various speedups
+   ================
+
+   As the correct data dependence graph is not supported during scheduling (which
+   is to be changed in mid-term), we cache as much of the dependence analysis 
+   results as possible to avoid reanalyzing.  This includes: bitmap caches on 
+   each insn in stream of the region saying yes/no for a query with a pair of 
+   UIDs; hashtables with the previously done transformations on each insn in
+   stream; a vector keeping a history of transformations on each expr.
+
+   Also, we try to minimize the dependence context used on each fence to check
+   whether the given expression is ready for scheduling by removing from it
+   insns that are definitely completed the execution.  The results of 
+   tick_check_p checks are also cached in a vector on each fence.
+
+   We keep a valid liveness set on each insn in a region to avoid the high 
+   cost of recomputation on large basic blocks.
+
+   Finally, we try to minimize the number of needed updates to the availability
+   sets.  The updates happen in two cases: when fill_insns terminates, 
+   we advance all fences and increase the stage number to show that the region
+   has changed and the sets are to be recomputed; and when the next iteration
+   of a loop in fill_insns happens (but this one reuses the saved av sets
+   on bb headers.)  Thus, we try to break the fill_insns loop only when
+   "significant" number of insns from the current scheduling window was
+   scheduled.  This should be made a target param.
+   
+
+   TODO: correctly support the data dependence graph at all stages and get rid
+   of all caches.  This should speed up the scheduler.
+   TODO: implement moving cond jumps with bookkeeping copies on both targets.
+   TODO: tune the scheduler before RA so it does not create too much pseudos.
+
+
+   References:
+   S.-M. Moon and K. Ebcioglu. Parallelizing nonnumerical code with
+   selective scheduling and software pipelining. 
+   ACM TOPLAS, Vol 19, No. 6, pages 853--898, Nov. 1997.  
+
+   Andrey Belevantsev, Maxim Kuvyrkov, Vladimir Makarov, Dmitry Melnik, 
+   and Dmitry Zhurikhin.  An interblock VLIW-targeted instruction scheduler 
+   for GCC. In Proceedings of GCC Developers' Summit 2006.
+
+   Arutyun Avetisyan, Andrey Belevantsev, and Dmitry Melnik.  GCC Instruction 
+   Scheduler and Software Pipeliner on the Itanium Platform.   EPIC-7 Workshop.
+   http://rogue.colorado.edu/EPIC7/.
+   
+*/
+
+/* True when pipelining is enabled.  */
+bool pipelining_p;
+
+/* True if bookkeeping is enabled.  */
+bool bookkeeping_p;
+
+/* Maximum number of insns that are eligible for renaming.  */
+int max_insns_to_rename;
+\f
+
+/* Definitions of local types and macros.  */
+
+/* Represents possible outcomes of moving an expression through an insn.  */
+enum MOVEUP_EXPR_CODE 
+  { 
+    /* The expression is not changed.  */
+    MOVEUP_EXPR_SAME, 
+
+    /* Not changed, but requires a new destination register.  */
+    MOVEUP_EXPR_AS_RHS, 
+
+    /* Cannot be moved.  */
+    MOVEUP_EXPR_NULL, 
+
+    /* Changed (substituted or speculated).  */
+    MOVEUP_EXPR_CHANGED 
+  };
+
+/* The container to be passed into rtx search & replace functions.  */
+struct rtx_search_arg
+{
+  /* What we are searching for.  */
+  rtx x;
+
+  /* The occurence counter.  */
+  int n;
+};
+
+typedef struct rtx_search_arg *rtx_search_arg_p;
+
+/* This struct contains precomputed hard reg sets that are needed when 
+   computing registers available for renaming.  */
+struct hard_regs_data 
+{
+  /* For every mode, this stores registers available for use with 
+     that mode.  */
+  HARD_REG_SET regs_for_mode[NUM_MACHINE_MODES];
+
+  /* True when regs_for_mode[mode] is initialized.  */
+  bool regs_for_mode_ok[NUM_MACHINE_MODES];
+
+  /* For every register, it has regs that are ok to rename into it.
+     The register in question is always set.  If not, this means
+     that the whole set is not computed yet.  */
+  HARD_REG_SET regs_for_rename[FIRST_PSEUDO_REGISTER];
+
+  /* For every mode, this stores registers not available due to 
+     call clobbering.  */
+  HARD_REG_SET regs_for_call_clobbered[NUM_MACHINE_MODES];
+
+  /* All registers that are used or call used.  */
+  HARD_REG_SET regs_ever_used;
+
+#ifdef STACK_REGS
+  /* Stack registers.  */
+  HARD_REG_SET stack_regs;
+#endif
+};
+
+/* Holds the results of computation of available for renaming and
+   unavailable hard registers.  */
+struct reg_rename
+{
+  /* These are unavailable due to calls crossing, globalness, etc.  */
+  HARD_REG_SET unavailable_hard_regs;
+
+  /* These are *available* for renaming.  */
+  HARD_REG_SET available_for_renaming;
+
+  /* Whether this code motion path crosses a call.  */
+  bool crosses_call;
+};
+
+/* A global structure that contains the needed information about harg 
+   regs.  */
+static struct hard_regs_data sel_hrd;
+\f
+
+/* This structure holds local data used in code_motion_path_driver hooks on 
+   the same or adjacent levels of recursion.  Here we keep those parameters 
+   that are not used in code_motion_path_driver routine itself, but only in 
+   its hooks.  Moreover, all parameters that can be modified in hooks are 
+   in this structure, so all other parameters passed explicitly to hooks are 
+   read-only.  */
+struct cmpd_local_params
+{
+  /* Local params used in move_op_* functions.  */
+
+  /* Edges for bookkeeping generation.  */
+  edge e1, e2;
+
+  /* C_EXPR merged from all successors and locally allocated temporary C_EXPR.  */
+  expr_t c_expr_merged, c_expr_local;
+
+  /* Local params used in fur_* functions.  */
+  /* Copy of the ORIGINAL_INSN list, stores the original insns already
+     found before entering the current level of code_motion_path_driver.  */
+  def_list_t old_original_insns;
+
+  /* Local params used in move_op_* functions.  */
+  /* True when we have removed last insn in the block which was 
+     also a boundary.  Do not update anything or create bookkeeping copies.  */
+  BOOL_BITFIELD removed_last_insn : 1;
+};
+
+/* Stores the static parameters for move_op_* calls.  */
+struct moveop_static_params
+{
+  /* Destination register.  */
+  rtx dest;
+
+  /* Current C_EXPR.  */
+  expr_t c_expr;
+
+  /* An UID of expr_vliw which is to be moved up.  If we find other exprs,
+     they are to be removed.  */
+  int uid;
+
+#ifdef ENABLE_CHECKING
+  /* This is initialized to the insn on which the driver stopped its traversal.  */
+  insn_t failed_insn;
+#endif
+
+  /* True if we scheduled an insn with different register.  */
+  bool was_renamed;
+};
+
+/* Stores the static parameters for fur_* calls.  */
+struct fur_static_params
+{
+  /* Set of registers unavailable on the code motion path.  */
+  regset used_regs;
+
+  /* Pointer to the list of original insns definitions.  */
+  def_list_t *original_insns;
+
+  /* True if a code motion path contains a CALL insn.  */
+  bool crosses_call;
+};
+
+typedef struct fur_static_params *fur_static_params_p;
+typedef struct cmpd_local_params *cmpd_local_params_p;
+typedef struct moveop_static_params *moveop_static_params_p;
+
+/* Set of hooks and parameters that determine behaviour specific to
+   move_op or find_used_regs functions.  */
+struct code_motion_path_driver_info_def
+{
+  /* Called on enter to the basic block.  */
+  int (*on_enter) (insn_t, cmpd_local_params_p, void *, bool);
+
+  /* Called when original expr is found.  */
+  void (*orig_expr_found) (insn_t, expr_t, cmpd_local_params_p, void *);
+
+  /* Called while descending current basic block if current insn is not
+     the original EXPR we're searching for.  */
+  bool (*orig_expr_not_found) (insn_t, av_set_t, void *);
+
+  /* Function to merge C_EXPRes from different successors.  */
+  void (*merge_succs) (insn_t, insn_t, int, cmpd_local_params_p, void *);
+
+  /* Function to finalize merge from different successors and possibly
+     deallocate temporary data structures used for merging.  */
+  void (*after_merge_succs) (cmpd_local_params_p, void *);
+
+  /* Called on the backward stage of recursion to do moveup_expr.
+     Used only with move_op_*.  */
+  void (*ascend) (insn_t, void *);
+
+  /* Called on the ascending pass, before returning from the current basic 
+     block or from the whole traversal.  */
+  void (*at_first_insn) (insn_t, cmpd_local_params_p, void *);
+
+  /* When processing successors in move_op we need only descend into 
+     SUCCS_NORMAL successors, while in find_used_regs we need SUCCS_ALL.  */
+  int succ_flags;
+
+  /* The routine name to print in dumps ("move_op" of "find_used_regs").  */
+  const char *routine_name;
+};
+
+/* Global pointer to current hooks, either points to MOVE_OP_HOOKS or
+   FUR_HOOKS.  */
+struct code_motion_path_driver_info_def *code_motion_path_driver_info;
+
+/* Set of hooks for performing move_op and find_used_regs routines with
+   code_motion_path_driver.  */
+struct code_motion_path_driver_info_def move_op_hooks, fur_hooks;
+
+/* True if/when we want to emulate Haifa scheduler in the common code.  
+   This is used in sched_rgn_local_init and in various places in 
+   sched-deps.c.  */
+int sched_emulate_haifa_p;
+
+/* GLOBAL_LEVEL is used to discard information stored in basic block headers
+   av_sets.  Av_set of bb header is valid if its (bb header's) level is equal
+   to GLOBAL_LEVEL.  And invalid if lesser.  This is primarily used to advance
+   scheduling window.  */
+int global_level;
+
+/* Current fences.  */
+flist_t fences;
+
+/* True when separable insns should be scheduled as RHSes.  */
+static bool enable_schedule_as_rhs_p;
+
+/* Used in verify_target_availability to assert that target reg is reported
+   unavailabile by both TARGET_UNAVAILABLE and find_used_regs only if
+   we haven't scheduled anything on the previous fence.  
+   if scheduled_something_on_previous_fence is true, TARGET_UNAVAILABLE can
+   have more conservative value than the one returned by the 
+   find_used_regs, thus we shouldn't assert that these values are equal.  */
+static bool scheduled_something_on_previous_fence;
+
+/* All newly emitted insns will have their uids greater than this value.  */
+static int first_emitted_uid;
+
+/* Set of basic blocks that are forced to start new ebbs.  This is a subset
+   of all the ebb heads.  */
+static bitmap_head _forced_ebb_heads;
+bitmap_head *forced_ebb_heads = &_forced_ebb_heads;
+
+/* Blocks that need to be rescheduled after pipelining.  */
+bitmap blocks_to_reschedule = NULL;
+
+/* True when the first lv set should be ignored when updating liveness.  */
+static bool ignore_first = false;
+
+/* Number of insns max_issue has initialized data structures for.  */
+static int max_issue_size = 0;
+
+/* Whether we can issue more instructions.  */
+static int can_issue_more;
+
+/* Maximum software lookahead window size, reduced when rescheduling after
+   pipelining.  */
+static int max_ws;
+
+/* Number of insns scheduled in current region.  */
+static int num_insns_scheduled;
+
+/* A vector of expressions is used to be able to sort them.  */
+DEF_VEC_P(expr_t);
+DEF_VEC_ALLOC_P(expr_t,heap);
+static VEC(expr_t, heap) *vec_av_set = NULL;
+
+/* A vector of vinsns is used to hold temporary lists of vinsns.  */
+DEF_VEC_P(vinsn_t);
+DEF_VEC_ALLOC_P(vinsn_t,heap);
+typedef VEC(vinsn_t, heap) *vinsn_vec_t;
+
+/* This vector has the exprs which may still present in av_sets, but actually
+   can't be moved up due to bookkeeping created during code motion to another
+   fence.  See comment near the call to update_and_record_unavailable_insns
+   for the detailed explanations.  */
+static vinsn_vec_t vec_bookkeeping_blocked_vinsns = NULL;
+
+/* This vector has vinsns which are scheduled with renaming on the first fence 
+   and then seen on the second.  For expressions with such vinsns, target
+   availability information may be wrong.  */
+static vinsn_vec_t vec_target_unavailable_vinsns = NULL;
+
+/* Vector to store temporary nops inserted in move_op to prevent removal
+   of empty bbs.  */
+DEF_VEC_P(insn_t);
+DEF_VEC_ALLOC_P(insn_t,heap);
+static VEC(insn_t, heap) *vec_temp_moveop_nops = NULL;
+
+/* These bitmaps record original instructions scheduled on the current 
+   iteration and bookkeeping copies created by them.  */ 
+static bitmap current_originators = NULL;
+static bitmap current_copies = NULL;
+
+/* This bitmap marks the blocks visited by code_motion_path_driver so we don't
+   visit them afterwards.  */
+static bitmap code_motion_visited_blocks = NULL;
+
+/* Variables to accumulate different statistics.  */
+
+/* The number of bookkeeping copies created.  */
+static int stat_bookkeeping_copies;
+
+/* The number of insns that required bookkeeiping for their scheduling.  */
+static int stat_insns_needed_bookkeeping;
+
+/* The number of insns that got renamed.  */
+static int stat_renamed_scheduled;
+
+/* The number of substitutions made during scheduling.  */
+static int stat_substitutions_total;
+\f
+
+/* Forward declarations of static functions.  */
+static bool rtx_ok_for_substitution_p (rtx, rtx);
+static int sel_rank_for_schedule (const void *, const void *);
+static av_set_t find_sequential_best_exprs (bnd_t, expr_t, bool);
+
+static rtx get_dest_from_orig_ops (av_set_t);
+static basic_block generate_bookkeeping_insn (expr_t, edge, edge);
+static bool find_used_regs (insn_t, av_set_t, regset, struct reg_rename *, 
+                            def_list_t *);
+static bool move_op (insn_t, av_set_t, expr_t, rtx, expr_t);
+static bool code_motion_path_driver (insn_t, av_set_t, ilist_t,
+                                     cmpd_local_params_p, void *);
+static void sel_sched_region_1 (void);
+static void sel_sched_region_2 (int);
+static av_set_t compute_av_set_inside_bb (insn_t, ilist_t, int, bool);
+
+static void debug_state (state_t);
+\f
+
+/* Functions that work with fences.  */
+
+/* Advance one cycle on FENCE.  */
+static void
+advance_one_cycle (fence_t fence)
+{
+  unsigned i;
+  int cycle;
+  rtx insn;
+  
+  advance_state (FENCE_STATE (fence));
+  cycle = ++FENCE_CYCLE (fence);
+  FENCE_ISSUED_INSNS (fence) = 0;
+  FENCE_STARTS_CYCLE_P (fence) = 1;
+  can_issue_more = issue_rate;
+
+  for (i = 0; VEC_iterate (rtx, FENCE_EXECUTING_INSNS (fence), i, insn); )
+    {
+      if (INSN_READY_CYCLE (insn) < cycle)
+        {
+          remove_from_deps (FENCE_DC (fence), insn);
+          VEC_unordered_remove (rtx, FENCE_EXECUTING_INSNS (fence), i);
+          continue;
+        }
+      i++;
+    }
+  if (sched_verbose >= 2)
+    {
+      sel_print ("Finished a cycle.  Current cycle = %d\n", FENCE_CYCLE (fence));
+      debug_state (FENCE_STATE (fence));
+    }
+}
+
+/* Returns true when SUCC in a fallthru bb of INSN, possibly
+   skipping empty basic blocks.  */
+static bool
+in_fallthru_bb_p (rtx insn, rtx succ)
+{
+  basic_block bb = BLOCK_FOR_INSN (insn);
+
+  if (bb == BLOCK_FOR_INSN (succ))
+    return true;
+
+  if (find_fallthru_edge (bb))
+    bb = find_fallthru_edge (bb)->dest;
+  else
+    return false;
+
+  while (sel_bb_empty_p (bb))
+    bb = bb->next_bb;
+
+  return bb == BLOCK_FOR_INSN (succ);
+}
+
+/* Construct successor fences from OLD_FENCEs and put them in NEW_FENCES. 
+   When a successor will continue a ebb, transfer all parameters of a fence
+   to the new fence.  ORIG_MAX_SEQNO is the maximal seqno before this round
+   of scheduling helping to distinguish between the old and the new code.  */
+static void
+extract_new_fences_from (flist_t old_fences, flist_tail_t new_fences,
+                        int orig_max_seqno)
+{
+  bool was_here_p = false;
+  insn_t insn = NULL_RTX;
+  insn_t succ;
+  succ_iterator si;
+  ilist_iterator ii;
+  fence_t fence = FLIST_FENCE (old_fences);
+  basic_block bb;
+
+  /* Get the only element of FENCE_BNDS (fence).  */
+  FOR_EACH_INSN (insn, ii, FENCE_BNDS (fence))
+    {
+      gcc_assert (!was_here_p);
+      was_here_p = true;
+    }
+  gcc_assert (was_here_p && insn != NULL_RTX);
+
+  /* When in the "middle" of the block, just move this fence 
+     to the new list.  */
+  bb = BLOCK_FOR_INSN (insn);
+  if (! sel_bb_end_p (insn)
+      || (single_succ_p (bb) 
+          && single_pred_p (single_succ (bb))))
+    {
+      insn_t succ;
+
+      succ = (sel_bb_end_p (insn) 
+              ? sel_bb_head (single_succ (bb))
+              : NEXT_INSN (insn));
+
+      if (INSN_SEQNO (succ) > 0 
+          && INSN_SEQNO (succ) <= orig_max_seqno
+          && INSN_SCHED_TIMES (succ) <= 0)
+        {
+          FENCE_INSN (fence) = succ;
+          move_fence_to_fences (old_fences, new_fences);
+
+          if (sched_verbose >= 1)
+            sel_print ("Fence %d continues as %d[%d] (state continue)\n", 
+                       INSN_UID (insn), INSN_UID (succ), BLOCK_NUM (succ));
+        }
+      return;
+    }
+
+  /* Otherwise copy fence's structures to (possibly) multiple successors.  */
+  FOR_EACH_SUCC_1 (succ, si, insn, SUCCS_NORMAL | SUCCS_SKIP_TO_LOOP_EXITS)
+    {
+      int seqno = INSN_SEQNO (succ);
+
+      if (0 < seqno && seqno <= orig_max_seqno
+          && (pipelining_p || INSN_SCHED_TIMES (succ) <= 0))
+        {
+          bool b = (in_same_ebb_p (insn, succ)
+                    || in_fallthru_bb_p (insn, succ)); 
+
+          if (sched_verbose >= 1)
+            sel_print ("Fence %d continues as %d[%d] (state %s)\n", 
+                       INSN_UID (insn), INSN_UID (succ), 
+                       BLOCK_NUM (succ), b ? "continue" : "reset");
+
+          if (b)
+            add_dirty_fence_to_fences (new_fences, succ, fence);
+          else
+            {
+              /* Mark block of the SUCC as head of the new ebb.  */
+              bitmap_set_bit (forced_ebb_heads, BLOCK_NUM (succ));
+              add_clean_fence_to_fences (new_fences, succ, fence);
+            }
+        }
+    }
+}
+\f
+
+/* Functions to support substitution.  */
+
+/* Returns whether INSN with dependence status DS is eligible for 
+   substitution, i.e. it's a copy operation x := y, and RHS that is 
+   moved up through this insn should be substituted.  */
+static bool
+can_substitute_through_p (insn_t insn, ds_t ds)
+{
+  /* We can substitute only true dependencies.  */
+  if ((ds & DEP_OUTPUT)
+      || (ds & DEP_ANTI)
+      || ! INSN_RHS (insn)
+      || ! INSN_LHS (insn))
+    return false;
+
+  /* Now we just need to make sure the INSN_RHS consists of only one 
+     simple REG rtx.  */
+  if (REG_P (INSN_LHS (insn)) 
+      && REG_P (INSN_RHS (insn)))
+    return true;             
+  return false;
+}
+
+/* Substitute all occurences of INSN's destination in EXPR' vinsn with INSN's 
+   source (if INSN is eligible for substitution).  Returns TRUE if
+   substitution was actually performed, FALSE otherwise.  Substitution might
+   be not performed because it's either EXPR' vinsn doesn't contain INSN's
+   destination or the resulting insn is invalid for the target machine.  
+   When UNDO is true, perform unsubstitution instead (the difference is in
+   the part of rtx on which validate_replace_rtx is called).  */
+static bool
+substitute_reg_in_expr (expr_t expr, insn_t insn, bool undo)
+{
+  rtx *where;
+  bool new_insn_valid;
+  vinsn_t *vi = &EXPR_VINSN (expr);
+  bool has_rhs = VINSN_RHS (*vi) != NULL;
+  rtx old, new_rtx;
+
+  /* Do not try to replace in SET_DEST.  Although we'll choose new
+     register for the RHS, we don't want to change RHS' original reg.  
+     If the insn is not SET, we may still be able to substitute something
+     in it, and if we're here (don't have deps), it doesn't write INSN's 
+     dest.  */
+  where = (has_rhs
+          ? &VINSN_RHS (*vi)
+          : &PATTERN (VINSN_INSN_RTX (*vi)));
+  old = undo ? INSN_RHS (insn) : INSN_LHS (insn);
+
+  /* Substitute if INSN has a form of x:=y and LHS(INSN) occurs in *VI.  */
+  if (rtx_ok_for_substitution_p (old, *where))
+    {
+      rtx new_insn;
+      rtx *where_replace;
+
+      /* We should copy these rtxes before substitution.  */
+      new_rtx = copy_rtx (undo ? INSN_LHS (insn) : INSN_RHS (insn));
+      new_insn = create_copy_of_insn_rtx (VINSN_INSN_RTX (*vi));
+
+      /* Where we'll replace.  
+         WHERE_REPLACE should point inside NEW_INSN, so INSN_RHS couldn't be
+        used instead of SET_SRC.  */
+      where_replace = (has_rhs
+                      ? &SET_SRC (PATTERN (new_insn))
+                      : &PATTERN (new_insn));
+
+      new_insn_valid 
+        = validate_replace_rtx_part_nosimplify (old, new_rtx, where_replace, 
+                                                new_insn);
+
+      /* ??? Actually, constrain_operands result depends upon choice of
+         destination register.  E.g. if we allow single register to be an rhs,
+        and if we try to move dx=ax(as rhs) through ax=dx, we'll result 
+        in invalid insn dx=dx, so we'll loose this rhs here.
+        Just can't come up with significant testcase for this, so just
+        leaving it for now.  */
+      if (new_insn_valid)
+       {
+         change_vinsn_in_expr (expr, 
+                               create_vinsn_from_insn_rtx (new_insn, false));
+
+         /* Do not allow clobbering the address register of speculative 
+             insns.  */
+         if ((EXPR_SPEC_DONE_DS (expr) & SPECULATIVE)
+              && bitmap_bit_p (VINSN_REG_USES (EXPR_VINSN (expr)), 
+                              expr_dest_regno (expr)))
+           EXPR_TARGET_AVAILABLE (expr) = false;
+
+         return true;
+       }
+      else
+        return false;
+    }
+  else
+    return false;
+}
+
+/* Helper function for count_occurences_equiv.  */
+static int 
+count_occurrences_1 (rtx *cur_rtx, void *arg)
+{
+  rtx_search_arg_p p = (rtx_search_arg_p) arg;
+
+  /* The last param FOR_GCSE is true, because otherwise it performs excessive
+    substitutions like
+       r8 = r33
+       r16 = r33
+    for the last insn it presumes r33 equivalent to r8, so it changes it to
+    r33.  Actually, there's no change, but it spoils debugging.  */
+  if (exp_equiv_p (*cur_rtx, p->x, 0, true))
+    {
+      /* Bail out if we occupy more than one register.  */
+      if (REG_P (*cur_rtx)
+          && hard_regno_nregs[REGNO(*cur_rtx)][GET_MODE (*cur_rtx)] > 1)
+        {
+          p->n = 0;
+          return 1;
+        }
+
+      p->n++;
+
+      /* Do not traverse subexprs.  */
+      return -1;
+    }
+
+  if (GET_CODE (*cur_rtx) == SUBREG
+      && REG_P (p->x)
+      && REGNO (SUBREG_REG (*cur_rtx)) == REGNO (p->x))
+    {
+      /* ??? Do not support substituting regs inside subregs.  In that case,
+         simplify_subreg will be called by validate_replace_rtx, and 
+         unsubstitution will fail later.  */
+      p->n = 0;
+      return 1;
+    }
+
+  /* Continue search.  */
+  return 0;
+}
+
+/* Return the number of places WHAT appears within WHERE.  
+   Bail out when we found a reference occupying several hard registers.  */
+static int 
+count_occurrences_equiv (rtx what, rtx where)
+{
+  struct rtx_search_arg arg;
+
+  arg.x = what;
+  arg.n = 0;
+
+  for_each_rtx (&where, &count_occurrences_1, (void *) &arg);
+
+  return arg.n;
+}
+
+/* Returns TRUE if WHAT is found in WHERE rtx tree.  */
+static bool
+rtx_ok_for_substitution_p (rtx what, rtx where)
+{
+  return (count_occurrences_equiv (what, where) > 0);
+}
+\f
+
+/* Functions to support register renaming.  */
+
+/* Substitute VI's set source with REGNO.  Returns newly created pattern
+   that has REGNO as its source.  */
+static rtx
+create_insn_rtx_with_rhs (vinsn_t vi, rtx rhs_rtx)
+{
+  rtx lhs_rtx;
+  rtx pattern;
+  rtx insn_rtx;
+
+  lhs_rtx = copy_rtx (VINSN_LHS (vi));
+
+  pattern = gen_rtx_SET (VOIDmode, lhs_rtx, rhs_rtx);
+  insn_rtx = create_insn_rtx_from_pattern (pattern, NULL_RTX);
+
+  return insn_rtx;
+}
+
+/* Returns whether INSN's src can be replaced with register number 
+   NEW_SRC_REG. E.g. the following insn is valid for i386:
+
+    (insn:HI 2205 6585 2207 727 ../../gcc/libiberty/regex.c:3337 
+      (set (mem/s:QI (plus:SI (plus:SI (reg/f:SI 7 sp)
+                       (reg:SI 0 ax [orig:770 c1 ] [770]))
+                   (const_int 288 [0x120])) [0 str S1 A8])
+           (const_int 0 [0x0])) 43 {*movqi_1} (nil)
+       (nil))
+
+  But if we change (const_int 0 [0x0]) to (reg:QI 4 si), it will be invalid
+  because of operand constraints: 
+
+    (define_insn "*movqi_1"
+      [(set (match_operand:QI 0 "nonimmediate_operand" "=q,q ,q ,r,r ,?r,m")
+           (match_operand:QI 1 "general_operand"      " q,qn,qm,q,rn,qm,qn")
+           )]
+    
+  So do constrain_operands here, before choosing NEW_SRC_REG as best 
+  reg for rhs.  */
+
+static bool
+replace_src_with_reg_ok_p (insn_t insn, rtx new_src_reg)
+{
+  vinsn_t vi = INSN_VINSN (insn);
+  enum machine_mode mode;
+  rtx dst_loc;
+  bool res;
+
+  gcc_assert (VINSN_SEPARABLE_P (vi));
+
+  get_dest_and_mode (insn, &dst_loc, &mode);
+  gcc_assert (mode == GET_MODE (new_src_reg));
+
+  if (REG_P (dst_loc) && REGNO (new_src_reg) == REGNO (dst_loc))
+    return true;
+
+  /* See whether SET_SRC can be replaced with this register.  */
+  validate_change (insn, &SET_SRC (PATTERN (insn)), new_src_reg, 1);
+  res = verify_changes (0);
+  cancel_changes (0);
+
+  return res;
+}
+
+/* Returns whether INSN still be valid after replacing it's DEST with
+   register NEW_REG.  */
+static bool
+replace_dest_with_reg_ok_p (insn_t insn, rtx new_reg)
+{
+  vinsn_t vi = INSN_VINSN (insn);
+  bool res;
+
+  /* We should deal here only with separable insns.  */
+  gcc_assert (VINSN_SEPARABLE_P (vi));
+  gcc_assert (GET_MODE (VINSN_LHS (vi)) == GET_MODE (new_reg));
+
+  /* See whether SET_DEST can be replaced with this register.  */
+  validate_change (insn, &SET_DEST (PATTERN (insn)), new_reg, 1);
+  res = verify_changes (0);
+  cancel_changes (0);
+
+  return res;
+}
+
+/* Create a pattern with rhs of VI and lhs of LHS_RTX.  */
+static rtx
+create_insn_rtx_with_lhs (vinsn_t vi, rtx lhs_rtx)
+{
+  rtx rhs_rtx;
+  rtx pattern;
+  rtx insn_rtx;
+
+  rhs_rtx = copy_rtx (VINSN_RHS (vi));
+
+  pattern = gen_rtx_SET (VOIDmode, lhs_rtx, rhs_rtx);
+  insn_rtx = create_insn_rtx_from_pattern (pattern, NULL_RTX);
+
+  return insn_rtx;
+}
+
+/* Substitute lhs in the given expression EXPR for the register with number 
+   NEW_REGNO.  SET_DEST may be arbitrary rtx, not only register.  */
+static void
+replace_dest_with_reg_in_expr (expr_t expr, rtx new_reg)
+{
+  rtx insn_rtx;
+  vinsn_t vinsn;
+
+  insn_rtx = create_insn_rtx_with_lhs (EXPR_VINSN (expr), new_reg);
+  vinsn = create_vinsn_from_insn_rtx (insn_rtx, false);
+
+  change_vinsn_in_expr (expr, vinsn);
+  EXPR_WAS_RENAMED (expr) = 1;
+  EXPR_TARGET_AVAILABLE (expr) = 1;
+}
+
+/* Returns whether VI writes either one of the USED_REGS registers or,
+   if a register is a hard one, one of the UNAVAILABLE_HARD_REGS registers.  */
+static bool
+vinsn_writes_one_of_regs_p (vinsn_t vi, regset used_regs, 
+                            HARD_REG_SET unavailable_hard_regs)
+{
+  unsigned regno;
+  reg_set_iterator rsi;
+
+  EXECUTE_IF_SET_IN_REG_SET (VINSN_REG_SETS (vi), 0, regno, rsi)
+    {
+      if (REGNO_REG_SET_P (used_regs, regno))
+        return true;
+      if (HARD_REGISTER_NUM_P (regno)
+          && TEST_HARD_REG_BIT (unavailable_hard_regs, regno))
+       return true;
+    }
+
+  EXECUTE_IF_SET_IN_REG_SET (VINSN_REG_CLOBBERS (vi), 0, regno, rsi)
+    {
+      if (REGNO_REG_SET_P (used_regs, regno))
+        return true;
+      if (HARD_REGISTER_NUM_P (regno)
+          && TEST_HARD_REG_BIT (unavailable_hard_regs, regno))
+       return true;
+    }
+
+  return false;
+}
+
+/* Returns register class of the output register in INSN.  
+   Returns NO_REGS for call insns because some targets have constraints on
+   destination register of a call insn.
+   
+   Code adopted from regrename.c::build_def_use.  */
+static enum reg_class
+get_reg_class (rtx insn)
+{
+  int alt, i, n_ops;
+
+  extract_insn (insn);
+  if (! constrain_operands (1))
+    fatal_insn_not_found (insn);
+  preprocess_constraints ();
+  alt = which_alternative;
+  n_ops = recog_data.n_operands;
+
+  for (i = 0; i < n_ops; ++i)
+    {
+      int matches = recog_op_alt[i][alt].matches;
+      if (matches >= 0)
+       recog_op_alt[i][alt].cl = recog_op_alt[matches][alt].cl;
+    }
+
+  if (asm_noperands (PATTERN (insn)) > 0)
+    {
+      for (i = 0; i < n_ops; i++)
+       if (recog_data.operand_type[i] == OP_OUT)
+         {
+           rtx *loc = recog_data.operand_loc[i];
+           rtx op = *loc;
+           enum reg_class cl = recog_op_alt[i][alt].cl;
+
+           if (REG_P (op)
+               && REGNO (op) == ORIGINAL_REGNO (op))
+             continue;
+
+           return cl;
+         }
+    }
+  else if (!CALL_P (insn))
+    {
+      for (i = 0; i < n_ops + recog_data.n_dups; i++)
+       {
+        int opn = i < n_ops ? i : recog_data.dup_num[i - n_ops];
+        enum reg_class cl = recog_op_alt[opn][alt].cl;
+  
+        if (recog_data.operand_type[opn] == OP_OUT ||
+            recog_data.operand_type[opn] == OP_INOUT)
+          return cl;
+       }
+    }
+
+/*  Insns like
+    (insn (set (reg:CCZ 17 flags) (compare:CCZ ...)))
+    may result in returning NO_REGS, cause flags is written implicitly through
+    CMP insn, which has no OP_OUT | OP_INOUT operands.  */
+  return NO_REGS;
+}
+
+#ifdef HARD_REGNO_RENAME_OK
+/* Calculate HARD_REGNO_RENAME_OK data for REGNO.  */
+static void
+init_hard_regno_rename (int regno)
+{
+  int cur_reg;
+
+  SET_HARD_REG_BIT (sel_hrd.regs_for_rename[regno], regno);
+
+  for (cur_reg = 0; cur_reg < FIRST_PSEUDO_REGISTER; cur_reg++)
+    {
+      /* We are not interested in renaming in other regs.  */
+      if (!TEST_HARD_REG_BIT (sel_hrd.regs_ever_used, cur_reg))
+        continue;
+
+      if (HARD_REGNO_RENAME_OK (regno, cur_reg))
+        SET_HARD_REG_BIT (sel_hrd.regs_for_rename[regno], cur_reg);
+    }
+}
+#endif
+
+/* A wrapper around HARD_REGNO_RENAME_OK that will look into the hard regs 
+   data first.  */
+static inline bool
+sel_hard_regno_rename_ok (int from, int to)
+{
+#ifdef HARD_REGNO_RENAME_OK
+  /* Check whether this is all calculated.  */
+  if (TEST_HARD_REG_BIT (sel_hrd.regs_for_rename[from], from))
+    return TEST_HARD_REG_BIT (sel_hrd.regs_for_rename[from], to);
+
+  init_hard_regno_rename (from);
+
+  return TEST_HARD_REG_BIT (sel_hrd.regs_for_rename[from], to);
+#else
+  return true;
+#endif
+}
+
+/* Calculate set of registers that are capable of holding MODE.  */
+static void
+init_regs_for_mode (enum machine_mode mode)
+{
+  int cur_reg;
+  
+  CLEAR_HARD_REG_SET (sel_hrd.regs_for_mode[mode]);
+  CLEAR_HARD_REG_SET (sel_hrd.regs_for_call_clobbered[mode]);
+
+  for (cur_reg = 0; cur_reg < FIRST_PSEUDO_REGISTER; cur_reg++)
+    {
+      int nregs = hard_regno_nregs[cur_reg][mode];
+      int i;
+      
+      for (i = nregs - 1; i >= 0; --i)
+        if (fixed_regs[cur_reg + i]
+                || global_regs[cur_reg + i]
+            /* Can't use regs which aren't saved by 
+               the prologue.  */
+            || !TEST_HARD_REG_BIT (sel_hrd.regs_ever_used, cur_reg + i)
+#ifdef LEAF_REGISTERS
+            /* We can't use a non-leaf register if we're in a
+               leaf function.  */
+            || (current_function_is_leaf
+                && !LEAF_REGISTERS[cur_reg + i])
+#endif
+            )
+          break;
+      
+      if (i >= 0) 
+        continue;
+      
+      /* See whether it accepts all modes that occur in
+         original insns.  */
+      if (! HARD_REGNO_MODE_OK (cur_reg, mode))
+        continue;
+      
+      if (HARD_REGNO_CALL_PART_CLOBBERED (cur_reg, mode))
+        SET_HARD_REG_BIT (sel_hrd.regs_for_call_clobbered[mode], 
+                          cur_reg);
+      
+      /* If the CUR_REG passed all the checks above, 
+         then it's ok.  */
+      SET_HARD_REG_BIT (sel_hrd.regs_for_mode[mode], cur_reg);
+    }
+
+  sel_hrd.regs_for_mode_ok[mode] = true;
+}
+
+/* Init all register sets gathered in HRD.  */
+static void
+init_hard_regs_data (void)
+{
+  int cur_reg = 0;
+  enum machine_mode cur_mode = 0;
+
+  CLEAR_HARD_REG_SET (sel_hrd.regs_ever_used);
+  for (cur_reg = 0; cur_reg < FIRST_PSEUDO_REGISTER; cur_reg++)
+    if (df_regs_ever_live_p (cur_reg) || call_used_regs[cur_reg])
+      SET_HARD_REG_BIT (sel_hrd.regs_ever_used, cur_reg);
+  
+  /* Initialize registers that are valid based on mode when this is 
+     really needed.  */
+  for (cur_mode = 0; cur_mode < NUM_MACHINE_MODES; cur_mode++)
+    sel_hrd.regs_for_mode_ok[cur_mode] = false;
+  
+  /* Mark that all HARD_REGNO_RENAME_OK is not calculated.  */
+  for (cur_reg = 0; cur_reg < FIRST_PSEUDO_REGISTER; cur_reg++)
+    CLEAR_HARD_REG_SET (sel_hrd.regs_for_rename[cur_reg]);
+
+#ifdef STACK_REGS
+  CLEAR_HARD_REG_SET (sel_hrd.stack_regs);
+
+  for (cur_reg = FIRST_STACK_REG; cur_reg <= LAST_STACK_REG; cur_reg++)
+    SET_HARD_REG_BIT (sel_hrd.stack_regs, cur_reg);
+#endif
+} 
+
+/* Mark hardware regs in REG_RENAME_P that are not suitable 
+   for renaming rhs in INSN due to hardware restrictions (register class,
+   modes compatibility etc).  This doesn't affect original insn's dest reg,
+   if it isn't in USED_REGS.  DEF is a definition insn of rhs for which the
+   destination register is sought.  LHS (DEF->ORIG_INSN) may be REG or MEM.
+   Registers that are in used_regs are always marked in
+   unavailable_hard_regs as well.  */
+
+static void
+mark_unavailable_hard_regs (def_t def, struct reg_rename *reg_rename_p,
+                            regset used_regs ATTRIBUTE_UNUSED)
+{
+  enum machine_mode mode;
+  enum reg_class cl = NO_REGS;
+  rtx orig_dest;
+  unsigned cur_reg, regno;
+  hard_reg_set_iterator hrsi;
+
+  gcc_assert (GET_CODE (PATTERN (def->orig_insn)) == SET);
+  gcc_assert (reg_rename_p);
+
+  orig_dest = SET_DEST (PATTERN (def->orig_insn));
+  
+  /* We have decided not to rename 'mem = something;' insns, as 'something'
+     is usually a register.  */
+  if (!REG_P (orig_dest))
+    return;
+
+  regno = REGNO (orig_dest);
+
+  /* If before reload, don't try to work with pseudos.  */
+  if (!reload_completed && !HARD_REGISTER_NUM_P (regno))
+    return;
+
+  mode = GET_MODE (orig_dest);
+
+  /* Stop when mode is not supported for renaming.  Also can't proceed 
+     if the original register is one of the fixed_regs, global_regs or 
+     frame pointer.  */
+  if (fixed_regs[regno] 
+      || global_regs[regno]
+#if FRAME_POINTER_REGNUM != HARD_FRAME_POINTER_REGNUM
+       || (frame_pointer_needed && regno == HARD_FRAME_POINTER_REGNUM)
+#else
+       || (frame_pointer_needed && regno == FRAME_POINTER_REGNUM)
+#endif
+      )
+    {
+      SET_HARD_REG_SET (reg_rename_p->unavailable_hard_regs);
+
+      /* Give a chance for original register, if it isn't in used_regs.  */
+      if (!def->crosses_call)
+        CLEAR_HARD_REG_BIT (reg_rename_p->unavailable_hard_regs, regno);
+
+      return;
+    }
+
+  /* If something allocated on stack in this function, mark frame pointer
+     register unavailable, considering also modes.  
+     FIXME: it is enough to do this once per all original defs.  */
+  if (frame_pointer_needed)
+    {
+      int i;
+
+      for (i = hard_regno_nregs[FRAME_POINTER_REGNUM][Pmode]; i--;)
+       SET_HARD_REG_BIT (reg_rename_p->unavailable_hard_regs, 
+                          FRAME_POINTER_REGNUM + i);
+
+#if FRAME_POINTER_REGNUM != HARD_FRAME_POINTER_REGNUM
+      for (i = hard_regno_nregs[HARD_FRAME_POINTER_REGNUM][Pmode]; i--;)
+       SET_HARD_REG_BIT (reg_rename_p->unavailable_hard_regs, 
+                          HARD_FRAME_POINTER_REGNUM + i);
+#endif
+    }
+
+#ifdef STACK_REGS
+  /* For the stack registers the presence of FIRST_STACK_REG in USED_REGS
+     is equivalent to as if all stack regs were in this set.
+     I.e. no stack register can be renamed, and even if it's an original
+     register here we make sure it won't be lifted over it's previous def 
+     (it's previous def will appear as if it's a FIRST_STACK_REG def.  
+     The HARD_REGNO_RENAME_OK covers other cases in condition below.  */
+  if (IN_RANGE (REGNO (orig_dest), FIRST_STACK_REG, LAST_STACK_REG)
+      && REGNO_REG_SET_P (used_regs, FIRST_STACK_REG)) 
+    IOR_HARD_REG_SET (reg_rename_p->unavailable_hard_regs, 
+                      sel_hrd.stack_regs);
+#endif    
+
+  /* If there's a call on this path, make regs from call_used_reg_set 
+     unavailable.  */
+  if (def->crosses_call)
+    IOR_HARD_REG_SET (reg_rename_p->unavailable_hard_regs, 
+                      call_used_reg_set);
+
+  /* Stop here before reload: we need FRAME_REGS, STACK_REGS, and crosses_call, 
+     but not register classes.  */
+  if (!reload_completed)
+    return;
+
+  /* Leave regs as 'available' only from the current 
+     register class.  */
+  cl = get_reg_class (def->orig_insn);
+  gcc_assert (cl != NO_REGS);
+  COPY_HARD_REG_SET (reg_rename_p->available_for_renaming,
+                     reg_class_contents[cl]);
+
+  /* Leave only registers available for this mode.  */
+  if (!sel_hrd.regs_for_mode_ok[mode])
+    init_regs_for_mode (mode);
+  AND_HARD_REG_SET (reg_rename_p->available_for_renaming, 
+                    sel_hrd.regs_for_mode[mode]);
+
+  /* Exclude registers that are partially call clobbered.  */
+  if (def->crosses_call
+      && ! HARD_REGNO_CALL_PART_CLOBBERED (regno, mode))
+    AND_COMPL_HARD_REG_SET (reg_rename_p->available_for_renaming, 
+                            sel_hrd.regs_for_call_clobbered[mode]);
+
+  /* Leave only those that are ok to rename.  */
+  EXECUTE_IF_SET_IN_HARD_REG_SET (reg_rename_p->available_for_renaming,
+                                  0, cur_reg, hrsi)
+    {
+      int nregs;
+      int i;
+
+      nregs = hard_regno_nregs[cur_reg][mode];
+      gcc_assert (nregs > 0);
+
+      for (i = nregs - 1; i >= 0; --i)
+        if (! sel_hard_regno_rename_ok (regno + i, cur_reg + i))
+          break;
+
+      if (i >= 0) 
+        CLEAR_HARD_REG_BIT (reg_rename_p->available_for_renaming, 
+                            cur_reg);
+    }
+
+  AND_COMPL_HARD_REG_SET (reg_rename_p->available_for_renaming, 
+                          reg_rename_p->unavailable_hard_regs);
+
+  /* Regno is always ok from the renaming part of view, but it really
+     could be in *unavailable_hard_regs already, so set it here instead
+     of there.  */
+  SET_HARD_REG_BIT (reg_rename_p->available_for_renaming, regno);
+}
+
+/* reg_rename_tick[REG1] > reg_rename_tick[REG2] if REG1 was chosen as the
+   best register more recently than REG2.  */
+static int reg_rename_tick[FIRST_PSEUDO_REGISTER];
+
+/* Indicates the number of times renaming happened before the current one.  */
+static int reg_rename_this_tick;
+
+/* Choose the register among free, that is suitable for storing 
+   the rhs value.
+
+   ORIGINAL_INSNS is the list of insns where the operation (rhs)
+   originally appears.  There could be multiple original operations 
+   for single rhs since we moving it up and merging along different 
+   paths.
+
+   Some code is adapted from regrename.c (regrename_optimize).
+   If original register is available, function returns it.
+   Otherwise it performs the checks, so the new register should
+   comply with the following:
+    - it should not violate any live ranges (such registers are in 
+      REG_RENAME_P->available_for_renaming set);
+    - it should not be in the HARD_REGS_USED regset;
+    - it should be in the class compatible with original uses;
+    - it should not be clobbered through reference with different mode;
+    - if we're in the leaf function, then the new register should 
+      not be in the LEAF_REGISTERS;
+    - etc.
+
+   If several registers meet the conditions, the register with smallest
+   tick is returned to achieve more even register allocation.
+
+   If original register seems to be ok, we set *IS_ORIG_REG_P_PTR to true.
+
+   If no register satisfies the above conditions, NULL_RTX is returned.  */
+static rtx
+choose_best_reg_1 (HARD_REG_SET hard_regs_used, 
+                   struct reg_rename *reg_rename_p, 
+                   def_list_t original_insns, bool *is_orig_reg_p_ptr)
+{
+  int best_new_reg;
+  unsigned cur_reg;
+  enum machine_mode mode = VOIDmode;
+  unsigned regno, i, n;
+  hard_reg_set_iterator hrsi;
+  def_list_iterator di;
+  def_t def;
+
+  /* If original register is available, return it.  */
+  *is_orig_reg_p_ptr = true;
+
+  FOR_EACH_DEF (def, di, original_insns)
+    {
+      rtx orig_dest = SET_DEST (PATTERN (def->orig_insn));
+
+      gcc_assert (REG_P (orig_dest));
+
+      /* Check that all original operations have the same mode.  
+         This is done for the next loop; if we'd return from this
+         loop, we'd check only part of them, but in this case 
+         it doesn't matter.  */
+      if (mode == VOIDmode)
+        mode = GET_MODE (orig_dest);
+      gcc_assert (mode == GET_MODE (orig_dest));
+
+      regno = REGNO (orig_dest);
+      for (i = 0, n = hard_regno_nregs[regno][mode]; i < n; i++)
+        if (TEST_HARD_REG_BIT (hard_regs_used, regno + i))
+          break;
+
+      /* All hard registers are available.  */
+      if (i == n)
+        {
+          gcc_assert (mode != VOIDmode);
+          
+          /* Hard registers should not be shared.  */
+          return gen_rtx_REG (mode, regno);
+        }
+    }
+  
+  *is_orig_reg_p_ptr = false;
+  best_new_reg = -1;
+  
+  /* Among all available regs choose the register that was 
+     allocated earliest.  */
+  EXECUTE_IF_SET_IN_HARD_REG_SET (reg_rename_p->available_for_renaming,
+                                  0, cur_reg, hrsi)
+    if (! TEST_HARD_REG_BIT (hard_regs_used, cur_reg))
+      {
+        /* All hard registers are available.  */
+        if (best_new_reg < 0
+            || reg_rename_tick[cur_reg] < reg_rename_tick[best_new_reg])
+          {
+            best_new_reg = cur_reg;
+            
+            /* Return immediately when we know there's no better reg.  */
+            if (! reg_rename_tick[best_new_reg])
+              break;
+          }
+      }
+
+  if (best_new_reg >= 0)
+    {
+      /* Use the check from the above loop.  */
+      gcc_assert (mode != VOIDmode);
+      return gen_rtx_REG (mode, best_new_reg);
+    }
+
+  return NULL_RTX;
+}
+
+/* A wrapper around choose_best_reg_1 () to verify that we make correct
+   assumptions about available registers in the function.  */
+static rtx
+choose_best_reg (HARD_REG_SET hard_regs_used, struct reg_rename *reg_rename_p, 
+                 def_list_t original_insns, bool *is_orig_reg_p_ptr)
+{
+  rtx best_reg = choose_best_reg_1 (hard_regs_used, reg_rename_p, 
+                                    original_insns, is_orig_reg_p_ptr);
+
+  gcc_assert (best_reg == NULL_RTX
+             || TEST_HARD_REG_BIT (sel_hrd.regs_ever_used, REGNO (best_reg)));
+
+  return best_reg;
+}
+
+/* Choose the pseudo register for storing rhs value.  As this is supposed 
+   to work before reload, we return either the original register or make
+   the new one.  The parameters are the same that in choose_nest_reg_1 
+   functions, except that USED_REGS may contain pseudos.  
+   If we work with hard regs, check also REG_RENAME_P->UNAVAILABLE_HARD_REGS.
+
+   TODO: take into account register pressure while doing this.  Up to this 
+   moment, this function would never return NULL for pseudos, but we should 
+   not rely on this.  */
+static rtx
+choose_best_pseudo_reg (regset used_regs, 
+                        struct reg_rename *reg_rename_p, 
+                        def_list_t original_insns, bool *is_orig_reg_p_ptr)
+{
+  def_list_iterator i;
+  def_t def;
+  enum machine_mode mode = VOIDmode;
+  bool bad_hard_regs = false;
+  
+  /* We should not use this after reload.  */
+  gcc_assert (!reload_completed);
+
+  /* If original register is available, return it.  */
+  *is_orig_reg_p_ptr = true;
+
+  FOR_EACH_DEF (def, i, original_insns)
+    {
+      rtx dest = SET_DEST (PATTERN (def->orig_insn));
+      int orig_regno;
+      
+      gcc_assert (REG_P (dest));
+      
+      /* Check that all original operations have the same mode.  */
+      if (mode == VOIDmode)
+        mode = GET_MODE (dest);
+      else
+        gcc_assert (mode == GET_MODE (dest));
+      orig_regno = REGNO (dest);
+      
+      if (!REGNO_REG_SET_P (used_regs, orig_regno))
+        {
+          if (orig_regno < FIRST_PSEUDO_REGISTER)
+            {
+              gcc_assert (df_regs_ever_live_p (orig_regno));
+              
+              /* For hard registers, we have to check hardware imposed 
+                 limitations (frame/stack registers, calls crossed).  */
+              if (!TEST_HARD_REG_BIT (reg_rename_p->unavailable_hard_regs, 
+                                      orig_regno))
+               {
+                 /* Don't let register cross a call if it doesn't already 
+                    cross one.  This condition is written in accordance with 
+                    that in sched-deps.c sched_analyze_reg().  */
+                 if (!reg_rename_p->crosses_call 
+                     || REG_N_CALLS_CROSSED (orig_regno) > 0)
+                   return gen_rtx_REG (mode, orig_regno);                  
+               }
+              
+              bad_hard_regs = true;
+            }
+          else
+            return dest;
+        }
+     }
+
+  *is_orig_reg_p_ptr = false;
+  /* We had some original hard registers that couldn't be used.
+     Those were likely special.  Don't try to create a pseudo.  */
+  if (bad_hard_regs)
+    return NULL_RTX;
+  
+  /* We haven't found a register from original operations.  Get a new one.  
+     FIXME: control register pressure somehow.  */
+  {
+    rtx new_reg = gen_reg_rtx (mode);
+
+    gcc_assert (mode != VOIDmode);
+
+    max_regno = max_reg_num ();
+    maybe_extend_reg_info_p ();
+    REG_N_CALLS_CROSSED (REGNO (new_reg)) = reg_rename_p->crosses_call ? 1 : 0;
+
+    return new_reg;
+  }
+}
+
+/* True when target of EXPR is available due to EXPR_TARGET_AVAILABLE,
+   USED_REGS and REG_RENAME_P->UNAVAILABLE_HARD_REGS.  */
+static void
+verify_target_availability (expr_t expr, regset used_regs, 
+                           struct reg_rename *reg_rename_p)
+{
+  unsigned n, i, regno;
+  enum machine_mode mode;
+  bool target_available, live_available, hard_available;
+
+  if (!REG_P (EXPR_LHS (expr)) || EXPR_TARGET_AVAILABLE (expr) < 0)
+    return;
+  
+  regno = expr_dest_regno (expr);
+  mode = GET_MODE (EXPR_LHS (expr));
+  target_available = EXPR_TARGET_AVAILABLE (expr) == 1;
+  n = reload_completed ? hard_regno_nregs[regno][mode] : 1;
+
+  live_available = hard_available = true;
+  for (i = 0; i < n; i++)
+    {
+      if (bitmap_bit_p (used_regs, regno + i))
+        live_available = false;
+      if (TEST_HARD_REG_BIT (reg_rename_p->unavailable_hard_regs, regno + i))
+        hard_available = false;
+    }
+
+  /* When target is not available, it may be due to hard register 
+     restrictions, e.g. crosses calls, so we check hard_available too.  */
+  if (target_available)
+    gcc_assert (live_available);
+  else
+    /* Check only if we haven't scheduled something on the previous fence, 
+       cause due to MAX_SOFTWARE_LOOKAHEAD_WINDOW_SIZE issues
+       and having more than one fence, we may end having targ_un in a block
+       in which successors target register is actually available.  
+
+       The last condition handles the case when a dependence from a call insn
+       was created in sched-deps.c for insns with destination registers that 
+       never crossed a call before, but do cross one after our code motion.  
+
+       FIXME: in the latter case, we just uselessly called find_used_regs, 
+       because we can't move this expression with any other register 
+       as well.  */
+    gcc_assert (scheduled_something_on_previous_fence || !live_available 
+               || !hard_available 
+               || (!reload_completed && reg_rename_p->crosses_call 
+                   && REG_N_CALLS_CROSSED (regno) == 0));
+}
+
+/* Collect unavailable registers due to liveness for EXPR from BNDS 
+   into USED_REGS.  Save additional information about available 
+   registers and unavailable due to hardware restriction registers
+   into REG_RENAME_P structure.  Save original insns into ORIGINAL_INSNS
+   list.  */
+static void
+collect_unavailable_regs_from_bnds (expr_t expr, blist_t bnds, regset used_regs,
+                                   struct reg_rename *reg_rename_p,
+                                   def_list_t *original_insns)
+{
+  for (; bnds; bnds = BLIST_NEXT (bnds))
+    {
+      bool res;
+      av_set_t orig_ops = NULL;
+      bnd_t bnd = BLIST_BND (bnds);
+
+      /* If the chosen best expr doesn't belong to current boundary,
+        skip it.  */
+      if (!av_set_is_in_p (BND_AV1 (bnd), EXPR_VINSN (expr)))
+       continue;
+
+      /* Put in ORIG_OPS all exprs from this boundary that became
+        RES on top.  */
+      orig_ops = find_sequential_best_exprs (bnd, expr, false);
+
+      /* Compute used regs and OR it into the USED_REGS.  */
+      res = find_used_regs (BND_TO (bnd), orig_ops, used_regs,
+                           reg_rename_p, original_insns);
+
+      /* FIXME: the assert is true until we'd have several boundaries.  */
+      gcc_assert (res);
+      av_set_clear (&orig_ops);
+    }
+}
+
+/* Return TRUE if it is possible to replace LHSes of ORIG_INSNS with BEST_REG.
+   If BEST_REG is valid, replace LHS of EXPR with it.  */
+static bool
+try_replace_dest_reg (ilist_t orig_insns, rtx best_reg, expr_t expr)
+{
+  if (expr_dest_regno (expr) == REGNO (best_reg))
+    {
+      EXPR_TARGET_AVAILABLE (expr) = 1;
+      return true;
+    }
+
+  gcc_assert (orig_insns);
+
+  /* Try whether we'll be able to generate the insn
+     'dest := best_reg' at the place of the original operation.  */
+  for (; orig_insns; orig_insns = ILIST_NEXT (orig_insns))
+    {
+      insn_t orig_insn = DEF_LIST_DEF (orig_insns)->orig_insn;
+
+      gcc_assert (EXPR_SEPARABLE_P (INSN_EXPR (orig_insn)));
+
+      if (!replace_src_with_reg_ok_p (orig_insn, best_reg)
+         || !replace_dest_with_reg_ok_p (orig_insn, best_reg))
+       return false;
+    }
+
+  /* Make sure that EXPR has the right destination
+     register.  */
+  replace_dest_with_reg_in_expr (expr, best_reg);
+  return true;
+}
+
+/* Select and assign best register to EXPR searching from BNDS.  
+   Set *IS_ORIG_REG_P to TRUE if original register was selected.  
+   Return FALSE if no register can be chosen, which could happen when:
+   * EXPR_SEPARABLE_P is true but we were unable to find suitable register;
+   * EXPR_SEPARABLE_P is false but the insn sets/clobbers one of the registers
+     that are used on the moving path.  */
+static bool
+find_best_reg_for_expr (expr_t expr, blist_t bnds, bool *is_orig_reg_p)
+{
+  static struct reg_rename reg_rename_data;
+
+  regset used_regs;
+  def_list_t original_insns = NULL;
+  bool reg_ok;
+
+  *is_orig_reg_p = false;
+
+  /* Don't bother to do anything if this insn doesn't set any registers.  */
+  if (bitmap_empty_p (VINSN_REG_SETS (EXPR_VINSN (expr)))
+      && bitmap_empty_p (VINSN_REG_CLOBBERS (EXPR_VINSN (expr))))
+    return true;
+
+  used_regs = get_clear_regset_from_pool ();
+  CLEAR_HARD_REG_SET (reg_rename_data.unavailable_hard_regs);
+
+  collect_unavailable_regs_from_bnds (expr, bnds, used_regs, &reg_rename_data,
+                                     &original_insns);
+
+#ifdef ENABLE_CHECKING
+  /* If after reload, make sure we're working with hard regs here.  */
+  if (reload_completed) 
+    {
+      reg_set_iterator rsi;
+      unsigned i;
+      
+      EXECUTE_IF_SET_IN_REG_SET (used_regs, FIRST_PSEUDO_REGISTER, i, rsi)
+        gcc_unreachable ();
+    }
+#endif
+
+  if (EXPR_SEPARABLE_P (expr))
+    {
+      rtx best_reg = NULL_RTX;
+      /* Check that we have computed availability of a target register
+        correctly.  */
+      verify_target_availability (expr, used_regs, &reg_rename_data);
+
+      /* Turn everything in hard regs after reload.  */
+      if (reload_completed)
+       {
+         HARD_REG_SET hard_regs_used;
+         REG_SET_TO_HARD_REG_SET (hard_regs_used, used_regs);
+
+         /* Join hard registers unavailable due to register class
+            restrictions and live range intersection.  */
+         IOR_HARD_REG_SET (hard_regs_used,
+                           reg_rename_data.unavailable_hard_regs);
+
+         best_reg = choose_best_reg (hard_regs_used, &reg_rename_data,
+                                     original_insns, is_orig_reg_p);
+       }
+      else
+       best_reg = choose_best_pseudo_reg (used_regs, &reg_rename_data,
+                                          original_insns, is_orig_reg_p);
+
+      if (!best_reg)
+       reg_ok = false;
+      else if (*is_orig_reg_p)
+       {
+         /* In case of unification BEST_REG may be different from EXPR's LHS
+            when EXPR's LHS is unavailable, and there is another LHS among
+            ORIGINAL_INSNS.  */
+         reg_ok = try_replace_dest_reg (original_insns, best_reg, expr);
+       }
+      else
+       {
+         /* Forbid renaming of low-cost insns.  */
+         if (sel_vinsn_cost (EXPR_VINSN (expr)) < 2)
+           reg_ok = false;
+         else
+           reg_ok = try_replace_dest_reg (original_insns, best_reg, expr);
+       }
+    }
+  else
+    {
+      /* If !EXPR_SCHEDULE_AS_RHS (EXPR), just make sure INSN doesn't set
+        any of the HARD_REGS_USED set.  */
+      if (vinsn_writes_one_of_regs_p (EXPR_VINSN (expr), used_regs,
+                                     reg_rename_data.unavailable_hard_regs))
+       {
+         reg_ok = false;
+         gcc_assert (EXPR_TARGET_AVAILABLE (expr) <= 0);
+       }
+      else
+       {
+         reg_ok = true;
+         gcc_assert (EXPR_TARGET_AVAILABLE (expr) != 0);
+       }
+    }
+
+  ilist_clear (&original_insns);
+  return_regset_to_pool (used_regs);
+
+  return reg_ok;
+}
+\f
+
+/* Return true if dependence described by DS can be overcomed.  */
+static bool
+can_speculate_dep_p (ds_t ds)
+{
+  if (spec_info == NULL)
+    return false;
+
+  /* Leave only speculative data.  */
+  ds &= SPECULATIVE;
+
+  if (ds == 0)
+    return false;
+
+  {
+    /* FIXME: make sched-deps.c produce only those non-hard dependencies,
+       that we can overcome.  */
+    ds_t spec_mask = spec_info->mask;
+
+    if ((ds & spec_mask) != ds)
+      return false;
+  }
+
+  if (ds_weak (ds) < spec_info->data_weakness_cutoff)
+    return false;
+
+  return true;
+}
+
+/* Get a speculation check instruction.
+   C_EXPR is a speculative expression,
+   CHECK_DS describes speculations that should be checked,
+   ORIG_INSN is the original non-speculative insn in the stream.  */
+static insn_t
+create_speculation_check (expr_t c_expr, ds_t check_ds, insn_t orig_insn)
+{
+  rtx check_pattern;
+  rtx insn_rtx;
+  insn_t insn;
+  basic_block recovery_block;
+  rtx label;
+
+  /* Create a recovery block if target is going to emit branchy check, or if
+     ORIG_INSN was speculative already.  */
+  if (targetm.sched.needs_block_p (EXPR_INSN_RTX (c_expr))
+      || EXPR_SPEC_DONE_DS (INSN_EXPR (orig_insn)) != 0)
+    {
+      recovery_block = sel_create_recovery_block (orig_insn);
+      label = BB_HEAD (recovery_block);
+    }
+  else
+    {
+      recovery_block = NULL;
+      label = NULL_RTX;
+    }
+
+  /* Get pattern of the check.  */
+  check_pattern = targetm.sched.gen_spec_check (EXPR_INSN_RTX (c_expr), label,
+                                               check_ds);
+
+  gcc_assert (check_pattern != NULL);
+
+  /* Emit check.  */
+  insn_rtx = create_insn_rtx_from_pattern (check_pattern, label);
+
+  insn = sel_gen_insn_from_rtx_after (insn_rtx, INSN_EXPR (orig_insn),
+                                     INSN_SEQNO (orig_insn), orig_insn);
+
+  /* Make check to be non-speculative.  */
+  EXPR_SPEC_DONE_DS (INSN_EXPR (insn)) = 0;
+  INSN_SPEC_CHECKED_DS (insn) = check_ds;
+
+  /* Decrease priority of check by difference of load/check instruction
+     latencies.  */
+  EXPR_PRIORITY (INSN_EXPR (insn)) -= (sel_vinsn_cost (INSN_VINSN (orig_insn))
+                                      - sel_vinsn_cost (INSN_VINSN (insn)));
+
+  /* Emit copy of original insn (though with replaced target register,
+     if needed) to the recovery block.  */
+  if (recovery_block != NULL)
+    {
+      rtx twin_rtx;
+      insn_t twin;
+
+      twin_rtx = copy_rtx (PATTERN (EXPR_INSN_RTX (c_expr)));
+      twin_rtx = create_insn_rtx_from_pattern (twin_rtx, NULL_RTX);
+      twin = sel_gen_recovery_insn_from_rtx_after (twin_rtx,
+                                                  INSN_EXPR (orig_insn),
+                                                  INSN_SEQNO (insn),
+                                                  bb_note (recovery_block));
+    }
+
+  /* If we've generated a data speculation check, make sure
+     that all the bookkeeping instruction we'll create during
+     this move_op () will allocate an ALAT entry so that the
+     check won't fail.
+     In case of control speculation we must convert C_EXPR to control
+     speculative mode, because failing to do so will bring us an exception
+     thrown by the non-control-speculative load.  */
+  check_ds = ds_get_max_dep_weak (check_ds);
+  speculate_expr (c_expr, check_ds);
+    
+  return insn;
+}
+
+/* True when INSN is a "regN = regN" copy.  */
+static bool
+identical_copy_p (rtx insn)
+{
+  rtx lhs, rhs, pat;
+
+  pat = PATTERN (insn);
+
+  if (GET_CODE (pat) != SET)
+    return false;
+
+  lhs = SET_DEST (pat);
+  if (!REG_P (lhs))
+    return false;
+
+  rhs = SET_SRC (pat);
+  if (!REG_P (rhs))
+    return false;
+
+  return REGNO (lhs) == REGNO (rhs);
+}
+
+/* Undo all transformations on *AV_PTR that were done when 
+   moving through INSN.  */
+static void
+undo_transformations (av_set_t *av_ptr, rtx insn)
+{
+  av_set_iterator av_iter;
+  expr_t expr;
+  av_set_t new_set = NULL;
+
+  /* First, kill any EXPR that uses registers set by an insn.  This is 
+     required for correctness.  */
+  FOR_EACH_EXPR_1 (expr, av_iter, av_ptr)
+    if (!sched_insns_conditions_mutex_p (insn, EXPR_INSN_RTX (expr))
+        && bitmap_intersect_p (INSN_REG_SETS (insn), 
+                               VINSN_REG_USES (EXPR_VINSN (expr)))
+        /* When an insn looks like 'r1 = r1', we could substitute through
+           it, but the above condition will still hold.  This happened with
+           gcc.c-torture/execute/961125-1.c.  */ 
+        && !identical_copy_p (insn))
+      {
+        if (sched_verbose >= 6)
+          sel_print ("Expr %d removed due to use/set conflict\n", 
+                     INSN_UID (EXPR_INSN_RTX (expr)));
+        av_set_iter_remove (&av_iter);
+      }
+
+  /* Undo transformations looking at the history vector.  */
+  FOR_EACH_EXPR (expr, av_iter, *av_ptr)
+    {
+      int index = find_in_history_vect (EXPR_HISTORY_OF_CHANGES (expr),
+                                        insn, EXPR_VINSN (expr), true);
+
+      if (index >= 0)
+        {
+          expr_history_def *phist;
+
+          phist = VEC_index (expr_history_def, 
+                             EXPR_HISTORY_OF_CHANGES (expr),
+                             index);
+
+          switch (phist->type) 
+            {
+            case TRANS_SPECULATION:
+              {
+                ds_t old_ds, new_ds;
+                
+                /* Compute the difference between old and new speculative
+                   statuses: that's what we need to check.  
+                   Earlier we used to assert that the status will really
+                   change.  This no longer works because only the probability
+                   bits in the status may have changed during compute_av_set,
+                   and in the case of merging different probabilities of the 
+                   same speculative status along different paths we do not 
+                   record this in the history vector.  */
+                old_ds = phist->spec_ds;
+                new_ds = EXPR_SPEC_DONE_DS (expr);
+
+                old_ds &= SPECULATIVE;
+                new_ds &= SPECULATIVE;
+                new_ds &= ~old_ds;
+                
+                EXPR_SPEC_TO_CHECK_DS (expr) |= new_ds;
+                break;
+              }
+            case TRANS_SUBSTITUTION:
+              {
+                expr_def _tmp_expr, *tmp_expr = &_tmp_expr;
+                vinsn_t new_vi;
+                bool add = true;
+                
+                new_vi = phist->old_expr_vinsn;
+         
+                gcc_assert (VINSN_SEPARABLE_P (new_vi) 
+                            == EXPR_SEPARABLE_P (expr));
+                copy_expr (tmp_expr, expr);
+
+                if (vinsn_equal_p (phist->new_expr_vinsn, 
+                                   EXPR_VINSN (tmp_expr)))
+                  change_vinsn_in_expr (tmp_expr, new_vi);
+                else
+                  /* This happens when we're unsubstituting on a bookkeeping
+                     copy, which was in turn substituted.  The history is wrong
+                     in this case.  Do it the hard way.  */
+                  add = substitute_reg_in_expr (tmp_expr, insn, true);
+                if (add)
+                  av_set_add (&new_set, tmp_expr);
+                clear_expr (tmp_expr);
+                break;
+              }
+            default:
+              gcc_unreachable ();
+            }
+        }
+          
+    }
+
+  av_set_union_and_clear (av_ptr, &new_set, NULL);
+}
+\f
+
+/* Moveup_* helpers for code motion and computing av sets.  */
+
+/* Propagates EXPR inside an insn group through THROUGH_INSN.
+   The difference from the below function is that only substitution is 
+   performed.  */
+static enum MOVEUP_EXPR_CODE
+moveup_expr_inside_insn_group (expr_t expr, insn_t through_insn)
+{
+  vinsn_t vi = EXPR_VINSN (expr);
+  ds_t *has_dep_p;
+  ds_t full_ds;
+
+  /* Do this only inside insn group.  */
+  gcc_assert (INSN_SCHED_CYCLE (through_insn) > 0);
+
+  full_ds = has_dependence_p (expr, through_insn, &has_dep_p);
+  if (full_ds == 0)
+    return MOVEUP_EXPR_SAME;
+
+  /* Substitution is the possible choice in this case.  */
+  if (has_dep_p[DEPS_IN_RHS])
+    {
+      /* Can't substitute UNIQUE VINSNs.  */
+      gcc_assert (!VINSN_UNIQUE_P (vi));
+      
+      if (can_substitute_through_p (through_insn, 
+                                    has_dep_p[DEPS_IN_RHS])
+          && substitute_reg_in_expr (expr, through_insn, false))
+        {
+          EXPR_WAS_SUBSTITUTED (expr) = true;
+          return MOVEUP_EXPR_CHANGED;
+        }
+
+      /* Don't care about this, as even true dependencies may be allowed
+         in an insn group.  */
+      return MOVEUP_EXPR_SAME;
+    }
+
+  /* This can catch output dependencies in COND_EXECs.  */
+  if (has_dep_p[DEPS_IN_INSN])
+    return MOVEUP_EXPR_NULL;
+  
+  /* This is either an output or an anti dependence, which usually have
+     a zero latency.  Allow this here, if we'd be wrong, tick_check_p
+     will fix this.  */
+  gcc_assert (has_dep_p[DEPS_IN_LHS]);
+  return MOVEUP_EXPR_AS_RHS;
+}
+
+/* True when a trapping EXPR cannot be moved through THROUGH_INSN.  */
+#define CANT_MOVE_TRAPPING(expr, through_insn)                \
+  (VINSN_MAY_TRAP_P (EXPR_VINSN (expr))                       \
+   && !sel_insn_has_single_succ_p ((through_insn), SUCCS_ALL) \
+   && !sel_insn_is_speculation_check (through_insn))
+
+/* True when a conflict on a target register was found during moveup_expr.  */
+static bool was_target_conflict = false;
+
+/* Modifies EXPR so it can be moved through the THROUGH_INSN,
+   performing necessary transformations.  Record the type of transformation 
+   made in PTRANS_TYPE, when it is not NULL.  When INSIDE_INSN_GROUP, 
+   permit all dependencies except true ones, and try to remove those
+   too via forward substitution.  All cases when a non-eliminable 
+   non-zero cost dependency exists inside an insn group will be fixed 
+   in tick_check_p instead.  */
+static enum MOVEUP_EXPR_CODE
+moveup_expr (expr_t expr, insn_t through_insn, bool inside_insn_group,
+            enum local_trans_type *ptrans_type)
+{
+  vinsn_t vi = EXPR_VINSN (expr);
+  insn_t insn = VINSN_INSN_RTX (vi);
+  bool was_changed = false;
+  bool as_rhs = false;
+  ds_t *has_dep_p;
+  ds_t full_ds;
+
+  /* When inside_insn_group, delegate to the helper.  */
+  if (inside_insn_group)
+    return moveup_expr_inside_insn_group (expr, through_insn);
+
+  /* Deal with unique insns and control dependencies.  */
+  if (VINSN_UNIQUE_P (vi))
+    {
+      /* We can move jumps without side-effects or jumps that are
+        mutually exclusive with instruction THROUGH_INSN (all in cases
+        dependencies allow to do so and jump is not speculative).  */
+      if (control_flow_insn_p (insn))
+        {
+          basic_block fallthru_bb;
+
+          /* Do not move checks and do not move jumps through other 
+             jumps.  */
+          if (control_flow_insn_p (through_insn)
+              || sel_insn_is_speculation_check (insn))
+            return MOVEUP_EXPR_NULL;
+
+          /* Don't move jumps through CFG joins.  */
+          if (bookkeeping_can_be_created_if_moved_through_p (through_insn))
+            return MOVEUP_EXPR_NULL;
+
+          /* The jump should have a clear fallthru block, and 
+             this block should be in the current region.  */
+          if ((fallthru_bb = fallthru_bb_of_jump (insn)) == NULL
+              || ! in_current_region_p (fallthru_bb))
+            return MOVEUP_EXPR_NULL;
+          
+          /* And it should be mutually exclusive with through_insn, or 
+             be an unconditional jump.  */
+          if (! any_uncondjump_p (insn)
+              && ! sched_insns_conditions_mutex_p (insn, through_insn))
+            return MOVEUP_EXPR_NULL;
+        }
+
+      /* Don't move what we can't move.  */
+      if (EXPR_CANT_MOVE (expr)
+         && BLOCK_FOR_INSN (through_insn) != BLOCK_FOR_INSN (insn))
+       return MOVEUP_EXPR_NULL;
+
+      /* Don't move SCHED_GROUP instruction through anything.
+         If we don't force this, then it will be possible to start
+         scheduling a sched_group before all its dependencies are
+         resolved.
+         ??? Haifa deals with this issue by delaying the SCHED_GROUP
+         as late as possible through rank_for_schedule.  */
+      if (SCHED_GROUP_P (insn))
+       return MOVEUP_EXPR_NULL;
+    }
+  else
+    gcc_assert (!control_flow_insn_p (insn));
+
+  /* Deal with data dependencies.  */
+  was_target_conflict = false;
+  full_ds = has_dependence_p (expr, through_insn, &has_dep_p);
+  if (full_ds == 0)
+    {
+      if (!CANT_MOVE_TRAPPING (expr, through_insn))
+       return MOVEUP_EXPR_SAME;
+    }
+  else
+    {
+      /* We can move UNIQUE insn up only as a whole and unchanged, 
+         so it shouldn't have any dependencies.  */
+      if (VINSN_UNIQUE_P (vi))
+       return MOVEUP_EXPR_NULL;
+    }
+
+  if (full_ds != 0 && can_speculate_dep_p (full_ds))
+    {
+      int res;
+
+      res = speculate_expr (expr, full_ds);
+      if (res >= 0)
+       {
+          /* Speculation was successful.  */
+          full_ds = 0;
+          was_changed = (res > 0);
+          if (res == 2)
+            was_target_conflict = true;
+          if (ptrans_type)
+            *ptrans_type = TRANS_SPECULATION;
+         sel_clear_has_dependence ();
+       }
+    }
+
+  if (has_dep_p[DEPS_IN_INSN])
+    /* We have some dependency that cannot be discarded.  */
+    return MOVEUP_EXPR_NULL;
+
+  if (has_dep_p[DEPS_IN_LHS])
+    { 
+      /* Only separable insns can be moved up with the new register.
+         Anyways, we should mark that the original register is 
+         unavailable.  */
+      if (!enable_schedule_as_rhs_p || !EXPR_SEPARABLE_P (expr))
+        return MOVEUP_EXPR_NULL;
+
+      EXPR_TARGET_AVAILABLE (expr) = false;
+      was_target_conflict = true;
+      as_rhs = true;
+    }
+
+  /* At this point we have either separable insns, that will be lifted
+     up only as RHSes, or non-separable insns with no dependency in lhs.
+     If dependency is in RHS, then try to perform substitution and move up
+     substituted RHS:
+
+      Ex. 1:                             Ex.2
+       y = x;                              y = x;
+       z = y*2;                            y = y*2;
+
+    In Ex.1 y*2 can be substituted for x*2 and the whole operation can be 
+    moved above y=x assignment as z=x*2.
+
+    In Ex.2 y*2 also can be substituted for x*2, but only the right hand 
+    side can be moved because of the output dependency.  The operation was
+    cropped to its rhs above.  */
+  if (has_dep_p[DEPS_IN_RHS])
+    {
+      ds_t *rhs_dsp = &has_dep_p[DEPS_IN_RHS];
+
+      /* Can't substitute UNIQUE VINSNs.  */
+      gcc_assert (!VINSN_UNIQUE_P (vi));
+
+      if (can_speculate_dep_p (*rhs_dsp))
+       {
+          int res;
+          
+          res = speculate_expr (expr, *rhs_dsp);
+          if (res >= 0)
+            {
+              /* Speculation was successful.  */
+              *rhs_dsp = 0;
+              was_changed = (res > 0);
+              if (res == 2)
+                was_target_conflict = true;
+              if (ptrans_type)
+                *ptrans_type = TRANS_SPECULATION;
+            }
+         else
+           return MOVEUP_EXPR_NULL;
+       }
+      else if (can_substitute_through_p (through_insn,
+                                         *rhs_dsp)
+               && substitute_reg_in_expr (expr, through_insn, false))
+       {
+          /* ??? We cannot perform substitution AND speculation on the same
+             insn.  */
+          gcc_assert (!was_changed);
+          was_changed = true;
+          if (ptrans_type)
+            *ptrans_type = TRANS_SUBSTITUTION;
+          EXPR_WAS_SUBSTITUTED (expr) = true;
+       }
+      else
+       return MOVEUP_EXPR_NULL;
+    }
+
+  /* Don't move trapping insns through jumps.
+     This check should be at the end to give a chance to control speculation
+     to perform its duties.  */
+  if (CANT_MOVE_TRAPPING (expr, through_insn))
+    return MOVEUP_EXPR_NULL;
+
+  return (was_changed 
+          ? MOVEUP_EXPR_CHANGED 
+          : (as_rhs 
+             ? MOVEUP_EXPR_AS_RHS
+             : MOVEUP_EXPR_SAME));
+}
+
+/* Try to look at bitmap caches for EXPR and INSN pair, return true 
+   if successful.  When INSIDE_INSN_GROUP, also try ignore dependencies
+   that can exist within a parallel group.  Write to RES the resulting
+   code for moveup_expr.  */
+static bool 
+try_bitmap_cache (expr_t expr, insn_t insn,
+                  bool inside_insn_group,
+                  enum MOVEUP_EXPR_CODE *res)
+{
+  int expr_uid = INSN_UID (EXPR_INSN_RTX (expr));
+  
+  /* First check whether we've analyzed this situation already.  */
+  if (bitmap_bit_p (INSN_ANALYZED_DEPS (insn), expr_uid))
+    {
+      if (bitmap_bit_p (INSN_FOUND_DEPS (insn), expr_uid))
+        {
+          if (sched_verbose >= 6)
+            sel_print ("removed (cached)\n");
+          *res = MOVEUP_EXPR_NULL;
+          return true;
+        }
+      else
+        {
+          if (sched_verbose >= 6)
+            sel_print ("unchanged (cached)\n");
+          *res = MOVEUP_EXPR_SAME;
+          return true;
+        }
+    }
+  else if (bitmap_bit_p (INSN_FOUND_DEPS (insn), expr_uid))
+    {
+      if (inside_insn_group)
+        {
+          if (sched_verbose >= 6)
+            sel_print ("unchanged (as RHS, cached, inside insn group)\n");
+          *res = MOVEUP_EXPR_SAME;
+          return true;
+          
+        }
+      else
+        EXPR_TARGET_AVAILABLE (expr) = false;
+
+      /* This is the only case when propagation result can change over time, 
+         as we can dynamically switch off scheduling as RHS.  In this case, 
+         just check the flag to reach the correct decision.  */
+      if (enable_schedule_as_rhs_p)
+        {
+          if (sched_verbose >= 6)
+            sel_print ("unchanged (as RHS, cached)\n");
+          *res = MOVEUP_EXPR_AS_RHS;
+          return true;
+        }
+      else
+        {
+          if (sched_verbose >= 6)
+            sel_print ("removed (cached as RHS, but renaming"
+                       " is now disabled)\n");
+          *res = MOVEUP_EXPR_NULL;
+          return true;
+        }
+    }
+
+  return false;
+}
+
+/* Try to look at bitmap caches for EXPR and INSN pair, return true 
+   if successful.  Write to RES the resulting code for moveup_expr.  */
+static bool 
+try_transformation_cache (expr_t expr, insn_t insn,
+                          enum MOVEUP_EXPR_CODE *res)
+{
+  struct transformed_insns *pti 
+    = (struct transformed_insns *)
+    htab_find_with_hash (INSN_TRANSFORMED_INSNS (insn),
+                         &EXPR_VINSN (expr), 
+                         VINSN_HASH_RTX (EXPR_VINSN (expr)));
+  if (pti)
+    {
+      /* This EXPR was already moved through this insn and was 
+         changed as a result.  Fetch the proper data from 
+         the hashtable.  */
+      insert_in_history_vect (&EXPR_HISTORY_OF_CHANGES (expr), 
+                              INSN_UID (insn), pti->type, 
+                              pti->vinsn_old, pti->vinsn_new, 
+                              EXPR_SPEC_DONE_DS (expr));
+      
+      if (INSN_IN_STREAM_P (VINSN_INSN_RTX (pti->vinsn_new)))
+        pti->vinsn_new = vinsn_copy (pti->vinsn_new, true);
+      change_vinsn_in_expr (expr, pti->vinsn_new);
+      if (pti->was_target_conflict)
+        EXPR_TARGET_AVAILABLE (expr) = false;
+      if (pti->type == TRANS_SPECULATION)
+        {
+          ds_t ds;
+
+          ds = EXPR_SPEC_DONE_DS (expr);
+                  
+          EXPR_SPEC_DONE_DS (expr) = pti->ds;
+          EXPR_NEEDS_SPEC_CHECK_P (expr) |= pti->needs_check;
+        }
+
+      if (sched_verbose >= 6)
+        {
+          sel_print ("changed (cached): ");
+          dump_expr (expr);
+          sel_print ("\n");
+        }
+
+      *res = MOVEUP_EXPR_CHANGED;
+      return true;
+    }
+
+  return false;
+}
+
+/* Update bitmap caches on INSN with result RES of propagating EXPR.  */
+static void
+update_bitmap_cache (expr_t expr, insn_t insn, bool inside_insn_group, 
+                     enum MOVEUP_EXPR_CODE res)
+{
+  int expr_uid = INSN_UID (EXPR_INSN_RTX (expr));
+
+  /* Do not cache result of propagating jumps through an insn group, 
+     as it is always true, which is not useful outside the group.  */
+  if (inside_insn_group)
+    return;
+      
+  if (res == MOVEUP_EXPR_NULL)
+    {
+      bitmap_set_bit (INSN_ANALYZED_DEPS (insn), expr_uid);
+      bitmap_set_bit (INSN_FOUND_DEPS (insn), expr_uid);
+    }
+  else if (res == MOVEUP_EXPR_SAME)
+    {
+      bitmap_set_bit (INSN_ANALYZED_DEPS (insn), expr_uid);
+      bitmap_clear_bit (INSN_FOUND_DEPS (insn), expr_uid);
+    }
+  else if (res == MOVEUP_EXPR_AS_RHS)
+    {
+      bitmap_clear_bit (INSN_ANALYZED_DEPS (insn), expr_uid);
+      bitmap_set_bit (INSN_FOUND_DEPS (insn), expr_uid);
+    }
+  else
+    gcc_unreachable ();
+}
+
+/* Update hashtable on INSN with changed EXPR, old EXPR_OLD_VINSN
+   and transformation type TRANS_TYPE.  */
+static void
+update_transformation_cache (expr_t expr, insn_t insn, 
+                             bool inside_insn_group,
+                             enum local_trans_type trans_type, 
+                             vinsn_t expr_old_vinsn)
+{
+  struct transformed_insns *pti;
+
+  if (inside_insn_group)
+    return;
+  
+  pti = XNEW (struct transformed_insns);
+  pti->vinsn_old = expr_old_vinsn;
+  pti->vinsn_new = EXPR_VINSN (expr);
+  pti->type = trans_type;
+  pti->was_target_conflict = was_target_conflict;
+  pti->ds = EXPR_SPEC_DONE_DS (expr);
+  pti->needs_check = EXPR_NEEDS_SPEC_CHECK_P (expr);
+  vinsn_attach (pti->vinsn_old);
+  vinsn_attach (pti->vinsn_new);
+  *((struct transformed_insns **) 
+    htab_find_slot_with_hash (INSN_TRANSFORMED_INSNS (insn),
+                              pti, VINSN_HASH_RTX (expr_old_vinsn),
+                              INSERT)) = pti;
+}
+
+/* Same as moveup_expr, but first looks up the result of 
+   transformation in caches.  */
+static enum MOVEUP_EXPR_CODE
+moveup_expr_cached (expr_t expr, insn_t insn, bool inside_insn_group)
+{
+  enum MOVEUP_EXPR_CODE res;
+  bool got_answer = false;
+
+  if (sched_verbose >= 6)
+    {
+      sel_print ("Moving "); 
+      dump_expr (expr);
+      sel_print (" through %d: ", INSN_UID (insn));
+    }
+
+  if (try_bitmap_cache (expr, insn, inside_insn_group, &res))
+    /* When inside insn group, we do not want remove stores conflicting
+       with previosly issued loads.  */
+    got_answer = ! inside_insn_group || res != MOVEUP_EXPR_NULL;
+  else if (try_transformation_cache (expr, insn, &res))
+    got_answer = true;
+
+  if (! got_answer)
+    {
+      /* Invoke moveup_expr and record the results.  */
+      vinsn_t expr_old_vinsn = EXPR_VINSN (expr);
+      ds_t expr_old_spec_ds = EXPR_SPEC_DONE_DS (expr);
+      int expr_uid = INSN_UID (VINSN_INSN_RTX (expr_old_vinsn));
+      bool unique_p = VINSN_UNIQUE_P (expr_old_vinsn);
+      enum local_trans_type trans_type = TRANS_SUBSTITUTION;
+
+      /* ??? Invent something better than this.  We can't allow old_vinsn 
+         to go, we need it for the history vector.  */
+      vinsn_attach (expr_old_vinsn);
+
+      res = moveup_expr (expr, insn, inside_insn_group,
+                         &trans_type);
+      switch (res)
+        {
+        case MOVEUP_EXPR_NULL:
+          update_bitmap_cache (expr, insn, inside_insn_group, res);
+         if (sched_verbose >= 6)
+            sel_print ("removed\n");
+         break;
+
+       case MOVEUP_EXPR_SAME:
+          update_bitmap_cache (expr, insn, inside_insn_group, res);
+          if (sched_verbose >= 6)
+            sel_print ("unchanged\n");
+         break;
+
+        case MOVEUP_EXPR_AS_RHS:
+          gcc_assert (!unique_p || inside_insn_group);
+          update_bitmap_cache (expr, insn, inside_insn_group, res);
+         if (sched_verbose >= 6)
+            sel_print ("unchanged (as RHS)\n");
+         break;
+
+       case MOVEUP_EXPR_CHANGED:
+          gcc_assert (INSN_UID (EXPR_INSN_RTX (expr)) != expr_uid
+                      || EXPR_SPEC_DONE_DS (expr) != expr_old_spec_ds);
+          insert_in_history_vect (&EXPR_HISTORY_OF_CHANGES (expr), 
+                                  INSN_UID (insn), trans_type, 
+                                  expr_old_vinsn, EXPR_VINSN (expr), 
+                                  expr_old_spec_ds);
+          update_transformation_cache (expr, insn, inside_insn_group,
+                                       trans_type, expr_old_vinsn);
+          if (sched_verbose >= 6)
+            {
+              sel_print ("changed: ");
+              dump_expr (expr);
+              sel_print ("\n");
+            }
+         break;
+       default:
+         gcc_unreachable ();
+        }
+
+      vinsn_detach (expr_old_vinsn);
+    }
+
+  return res;
+}
+
+/* Moves an av set AVP up through INSN, performing necessary 
+   transformations.  */
+static void
+moveup_set_expr (av_set_t *avp, insn_t insn, bool inside_insn_group)
+{
+  av_set_iterator i;
+  expr_t expr;
+
+  FOR_EACH_EXPR_1 (expr, i, avp)    
+    { 
+      
+      switch (moveup_expr_cached (expr, insn, inside_insn_group))
+       {
+       case MOVEUP_EXPR_SAME:
+        case MOVEUP_EXPR_AS_RHS:
+         break;
+
+       case MOVEUP_EXPR_NULL:
+         av_set_iter_remove (&i);
+         break;
+
+       case MOVEUP_EXPR_CHANGED:
+          expr = merge_with_other_exprs (avp, &i, expr);
+         break;
+          
+       default:
+         gcc_unreachable ();
+       }
+    }
+}
+
+/* Moves AVP set along PATH.  */
+static void
+moveup_set_inside_insn_group (av_set_t *avp, ilist_t path)
+{
+  int last_cycle;
+  
+  if (sched_verbose >= 6)
+    sel_print ("Moving expressions up in the insn group...\n");
+  if (! path)
+    return;
+  last_cycle = INSN_SCHED_CYCLE (ILIST_INSN (path));
+  while (path 
+         && INSN_SCHED_CYCLE (ILIST_INSN (path)) == last_cycle)
+    {
+      moveup_set_expr (avp, ILIST_INSN (path), true);
+      path = ILIST_NEXT (path);
+    }
+}
+
+/* Returns true if after moving EXPR along PATH it equals to EXPR_VLIW.  */
+static bool
+equal_after_moveup_path_p (expr_t expr, ilist_t path, expr_t expr_vliw)
+{
+  expr_def _tmp, *tmp = &_tmp;
+  int last_cycle;
+  bool res = true;
+
+  copy_expr_onside (tmp, expr);
+  last_cycle = path ? INSN_SCHED_CYCLE (ILIST_INSN (path)) : 0;
+  while (path 
+         && res
+         && INSN_SCHED_CYCLE (ILIST_INSN (path)) == last_cycle)
+    {
+      res = (moveup_expr_cached (tmp, ILIST_INSN (path), true) 
+             != MOVEUP_EXPR_NULL);
+      path = ILIST_NEXT (path);
+    }
+
+  if (res)
+    {
+      vinsn_t tmp_vinsn = EXPR_VINSN (tmp);
+      vinsn_t expr_vliw_vinsn = EXPR_VINSN (expr_vliw);
+
+      if (tmp_vinsn != expr_vliw_vinsn)
+       res = vinsn_equal_p (tmp_vinsn, expr_vliw_vinsn);
+    }
+
+  clear_expr (tmp);
+  return res;
+}
+\f
+
+/* Functions that compute av and lv sets.  */
+
+/* Returns true if INSN is not a downward continuation of the given path P in 
+   the current stage.  */
+static bool
+is_ineligible_successor (insn_t insn, ilist_t p)
+{
+  insn_t prev_insn;
+
+  /* Check if insn is not deleted.  */
+  if (PREV_INSN (insn) && NEXT_INSN (PREV_INSN (insn)) != insn)
+    gcc_unreachable ();
+  else if (NEXT_INSN (insn) && PREV_INSN (NEXT_INSN (insn)) != insn)
+    gcc_unreachable ();
+
+  /* If it's the first insn visited, then the successor is ok.  */
+  if (!p)
+    return false;
+
+  prev_insn = ILIST_INSN (p);
+
+  if (/* a backward edge.  */
+      INSN_SEQNO (insn) < INSN_SEQNO (prev_insn)
+      /* is already visited.  */
+      || (INSN_SEQNO (insn) == INSN_SEQNO (prev_insn)
+         && (ilist_is_in_p (p, insn)
+              /* We can reach another fence here and still seqno of insn 
+                 would be equal to seqno of prev_insn.  This is possible 
+                 when prev_insn is a previously created bookkeeping copy.
+                 In that case it'd get a seqno of insn.  Thus, check here
+                 whether insn is in current fence too.  */
+              || IN_CURRENT_FENCE_P (insn)))
+      /* Was already scheduled on this round.  */
+      || (INSN_SEQNO (insn) > INSN_SEQNO (prev_insn)
+         && IN_CURRENT_FENCE_P (insn))
+      /* An insn from another fence could also be 
+        scheduled earlier even if this insn is not in 
+        a fence list right now.  Check INSN_SCHED_CYCLE instead.  */
+      || (!pipelining_p
+          && INSN_SCHED_TIMES (insn) > 0))
+    return true;
+  else
+    return false;
+}
+
+/* Computes the av_set below the last bb insn INSN, doing all the 'dirty work' 
+   of handling multiple successors and properly merging its av_sets.  P is 
+   the current path traversed.  WS is the size of lookahead window.  
+   Return the av set computed.  */
+static av_set_t
+compute_av_set_at_bb_end (insn_t insn, ilist_t p, int ws)
+{
+  struct succs_info *sinfo;
+  av_set_t expr_in_all_succ_branches = NULL;
+  int is;
+  insn_t succ, zero_succ = NULL;
+  av_set_t av1 = NULL;
+
+  gcc_assert (sel_bb_end_p (insn));
+
+  /* Find different kind of successors needed for correct computing of 
+     SPEC and TARGET_AVAILABLE attributes.  */
+  sinfo = compute_succs_info (insn, SUCCS_NORMAL);
+
+  /* Debug output.  */
+  if (sched_verbose >= 6)
+    {
+      sel_print ("successors of bb end (%d): ", INSN_UID (insn));
+      dump_insn_vector (sinfo->succs_ok);
+      sel_print ("\n");
+      if (sinfo->succs_ok_n != sinfo->all_succs_n)
+        sel_print ("real successors num: %d\n", sinfo->all_succs_n);
+    }
+
+  /* Add insn to to the tail of current path.  */
+  ilist_add (&p, insn);
+
+  for (is = 0; VEC_iterate (rtx, sinfo->succs_ok, is, succ); is++)
+    {
+      av_set_t succ_set;
+
+      /* We will edit SUCC_SET and EXPR_SPEC field of its elements.  */
+      succ_set = compute_av_set_inside_bb (succ, p, ws, true);
+
+      av_set_split_usefulness (succ_set, 
+                               VEC_index (int, sinfo->probs_ok, is), 
+                               sinfo->all_prob);
+
+      if (sinfo->all_succs_n > 1 
+          && sinfo->all_succs_n == sinfo->succs_ok_n)
+       {
+          /* Find EXPR'es that came from *all* successors and save them 
+             into expr_in_all_succ_branches.  This set will be used later
+             for calculating speculation attributes of EXPR'es.  */
+          if (is == 0)
+            {
+              expr_in_all_succ_branches = av_set_copy (succ_set);
+
+              /* Remember the first successor for later. */
+              zero_succ = succ;
+            }
+          else
+            {
+              av_set_iterator i;
+              expr_t expr;
+              
+              FOR_EACH_EXPR_1 (expr, i, &expr_in_all_succ_branches)
+                if (!av_set_is_in_p (succ_set, EXPR_VINSN (expr)))
+                  av_set_iter_remove (&i);
+            }
+       }
+
+      /* Union the av_sets.  Check liveness restrictions on target registers
+         in special case of two successors.  */
+      if (sinfo->succs_ok_n == 2 && is == 1)
+        {
+          basic_block bb0 = BLOCK_FOR_INSN (zero_succ);
+          basic_block bb1 = BLOCK_FOR_INSN (succ);
+
+          gcc_assert (BB_LV_SET_VALID_P (bb0) && BB_LV_SET_VALID_P (bb1));
+          av_set_union_and_live (&av1, &succ_set, 
+                                 BB_LV_SET (bb0),
+                                 BB_LV_SET (bb1),
+                                 insn);
+        }
+      else
+        av_set_union_and_clear (&av1, &succ_set, insn);
+    }
+
+  /* Check liveness restrictions via hard way when there are more than 
+     two successors.  */
+  if (sinfo->succs_ok_n > 2)
+    for (is = 0; VEC_iterate (rtx, sinfo->succs_ok, is, succ); is++)
+      {
+        basic_block succ_bb = BLOCK_FOR_INSN (succ);
+        
+        gcc_assert (BB_LV_SET_VALID_P (succ_bb));
+        mark_unavailable_targets (av1, BB_AV_SET (succ_bb), 
+                                  BB_LV_SET (succ_bb));
+      }
+  
+  /* Finally, check liveness restrictions on paths leaving the region.  */ 
+  if (sinfo->all_succs_n > sinfo->succs_ok_n)
+    for (is = 0; VEC_iterate (rtx, sinfo->succs_other, is, succ); is++)
+      mark_unavailable_targets 
+        (av1, NULL, BB_LV_SET (BLOCK_FOR_INSN (succ)));
+
+  if (sinfo->all_succs_n > 1)
+    {
+      av_set_iterator i;
+      expr_t expr;
+
+      /* Increase the spec attribute of all EXPR'es that didn't come 
+        from all successors.  */
+      FOR_EACH_EXPR (expr, i, av1)
+       if (!av_set_is_in_p (expr_in_all_succ_branches, EXPR_VINSN (expr)))
+         EXPR_SPEC (expr)++;
+
+      av_set_clear (&expr_in_all_succ_branches);
+      
+      /* Do not move conditional branches through other 
+        conditional branches.  So, remove all conditional 
+        branches from av_set if current operator is a conditional
+        branch.  */
+      av_set_substract_cond_branches (&av1);
+    }
+  
+  ilist_remove (&p);
+  free_succs_info (sinfo);
+
+  if (sched_verbose >= 6)
+    {
+      sel_print ("av_succs (%d): ", INSN_UID (insn));
+      dump_av_set (av1);
+      sel_print ("\n");
+    }
+
+  return av1;
+}
+
+/* This function computes av_set for the FIRST_INSN by dragging valid 
+   av_set through all basic block insns either from the end of basic block 
+   (computed using compute_av_set_at_bb_end) or from the insn on which 
+   MAX_WS was exceeded.  It uses compute_av_set_at_bb_end to compute av_set
+   below the basic block and handling conditional branches.
+   FIRST_INSN - the basic block head, P - path consisting of the insns
+   traversed on the way to the FIRST_INSN (the path is sparse, only bb heads
+   and bb ends are added to the path), WS - current window size,
+   NEED_COPY_P - true if we'll make a copy of av_set before returning it.  */
+static av_set_t
+compute_av_set_inside_bb (insn_t first_insn, ilist_t p, int ws, 
+                         bool need_copy_p)
+{
+  insn_t cur_insn;
+  int end_ws = ws;
+  insn_t bb_end = sel_bb_end (BLOCK_FOR_INSN (first_insn));
+  insn_t after_bb_end = NEXT_INSN (bb_end);
+  insn_t last_insn;
+  av_set_t av = NULL;
+  basic_block cur_bb = BLOCK_FOR_INSN (first_insn);
+
+  /* Return NULL if insn is not on the legitimate downward path.  */
+  if (is_ineligible_successor (first_insn, p))
+    {
+      if (sched_verbose >= 6)
+        sel_print ("Insn %d is ineligible_successor\n", INSN_UID (first_insn));
+
+      return NULL;
+    }
+
+  /* If insn already has valid av(insn) computed, just return it.  */ 
+  if (AV_SET_VALID_P (first_insn))
+    {
+      av_set_t av_set;
+
+      if (sel_bb_head_p (first_insn))
+       av_set = BB_AV_SET (BLOCK_FOR_INSN (first_insn));
+      else
+       av_set = NULL;
+
+      if (sched_verbose >= 6)
+        {
+          sel_print ("Insn %d has a valid av set: ", INSN_UID (first_insn));
+          dump_av_set (av_set);
+          sel_print ("\n");
+        }
+
+      return need_copy_p ? av_set_copy (av_set) : av_set;
+    }
+
+  ilist_add (&p, first_insn);
+
+  /* As the result after this loop have completed, in LAST_INSN we'll
+     have the insn which has valid av_set to start backward computation 
+     from: it either will be NULL because on it the window size was exceeded 
+     or other valid av_set as returned by compute_av_set for the last insn 
+     of the basic block.  */
+  for (last_insn = first_insn; last_insn != after_bb_end;
+       last_insn = NEXT_INSN (last_insn))
+    {
+      /* We may encounter valid av_set not only on bb_head, but also on
+        those insns on which previously MAX_WS was exceeded.  */
+      if (AV_SET_VALID_P (last_insn))
+       {
+          if (sched_verbose >= 6)
+            sel_print ("Insn %d has a valid empty av set\n", INSN_UID (last_insn));
+         break;
+       }
+
+      /* The special case: the last insn of the BB may be an
+         ineligible_successor due to its SEQ_NO that was set on
+        it as a bookkeeping.  */
+      if (last_insn != first_insn 
+          && is_ineligible_successor (last_insn, p))
+       {
+          if (sched_verbose >= 6)
+            sel_print ("Insn %d is ineligible_successor\n", INSN_UID (last_insn));
+         break;          
+       }
+
+      if (end_ws > max_ws)
+       {
+         /* We can reach max lookahead size at bb_header, so clean av_set 
+            first.  */
+         INSN_WS_LEVEL (last_insn) = global_level;
+
+         if (sched_verbose >= 6)
+            sel_print ("Insn %d is beyond the software lookahead window size\n",
+                       INSN_UID (last_insn));
+         break;
+       }
+
+      end_ws++;
+    }
+
+  /* Get the valid av_set into AV above the LAST_INSN to start backward
+     computation from.  It either will be empty av_set or av_set computed from
+     the successors on the last insn of the current bb.  */
+  if (last_insn != after_bb_end)
+    {
+      av = NULL;
+
+      /* This is needed only to obtain av_sets that are identical to 
+         those computed by the old compute_av_set version.  */
+      if (last_insn == first_insn && !INSN_NOP_P (last_insn))
+        av_set_add (&av, INSN_EXPR (last_insn));
+    }
+  else
+    /* END_WS is always already increased by 1 if LAST_INSN == AFTER_BB_END.  */
+    av = compute_av_set_at_bb_end (bb_end, p, end_ws);
+
+  /* Compute av_set in AV starting from below the LAST_INSN up to
+     location above the FIRST_INSN.  */
+  for (cur_insn = PREV_INSN (last_insn); cur_insn != PREV_INSN (first_insn);
+       cur_insn = PREV_INSN (cur_insn))    
+    if (!INSN_NOP_P (cur_insn))
+      {
+        expr_t expr;
+  
+        moveup_set_expr (&av, cur_insn, false);
+        
+        /* If the expression for CUR_INSN is already in the set, 
+           replace it by the new one.  */
+        expr = av_set_lookup (av, INSN_VINSN (cur_insn)); 
+        if (expr != NULL)
+          {
+            clear_expr (expr);
+            copy_expr (expr, INSN_EXPR (cur_insn));
+          }
+        else
+          av_set_add (&av, INSN_EXPR (cur_insn));
+      }
+
+  /* Clear stale bb_av_set.  */
+  if (sel_bb_head_p (first_insn))
+    {
+      av_set_clear (&BB_AV_SET (cur_bb));
+      BB_AV_SET (cur_bb) = need_copy_p ? av_set_copy (av) : av;
+      BB_AV_LEVEL (cur_bb) = global_level;
+    }
+
+  if (sched_verbose >= 6)
+    {
+      sel_print ("Computed av set for insn %d: ", INSN_UID (first_insn));
+      dump_av_set (av);
+      sel_print ("\n");
+    }
+
+  ilist_remove (&p);
+  return av;
+}
+
+/* Compute av set before INSN.
+   INSN - the current operation (actual rtx INSN)
+   P - the current path, which is list of insns visited so far
+   WS - software lookahead window size.
+   UNIQUE_P - TRUE, if returned av_set will be changed, hence
+   if we want to save computed av_set in s_i_d, we should make a copy of it.
+
+   In the resulting set we will have only expressions that don't have delay
+   stalls and nonsubstitutable dependences.  */
+static av_set_t
+compute_av_set (insn_t insn, ilist_t p, int ws, bool unique_p)
+{
+  return compute_av_set_inside_bb (insn, p, ws, unique_p);
+}
+
+/* Propagate a liveness set LV through INSN.  */
+static void
+propagate_lv_set (regset lv, insn_t insn)
+{
+  gcc_assert (INSN_P (insn));
+
+  if (INSN_NOP_P (insn))
+    return;
+
+  df_simulate_one_insn (BLOCK_FOR_INSN (insn), insn, lv);
+}
+
+/* Return livness set at the end of BB.  */
+static regset
+compute_live_after_bb (basic_block bb)
+{
+  edge e;
+  edge_iterator ei;
+  regset lv = get_clear_regset_from_pool ();
+
+  gcc_assert (!ignore_first);
+
+  FOR_EACH_EDGE (e, ei, bb->succs)
+    if (sel_bb_empty_p (e->dest))
+      {
+        if (! BB_LV_SET_VALID_P (e->dest))
+          {
+            gcc_unreachable ();
+            gcc_assert (BB_LV_SET (e->dest) == NULL);
+            BB_LV_SET (e->dest) = compute_live_after_bb (e->dest);
+            BB_LV_SET_VALID_P (e->dest) = true;
+          }
+        IOR_REG_SET (lv, BB_LV_SET (e->dest));
+      }
+    else
+      IOR_REG_SET (lv, compute_live (sel_bb_head (e->dest)));
+
+  return lv;
+}
+
+/* Compute the set of all live registers at the point before INSN and save
+   it at INSN if INSN is bb header.  */
+regset
+compute_live (insn_t insn)
+{
+  basic_block bb = BLOCK_FOR_INSN (insn);
+  insn_t final, temp;
+  regset lv;
+
+  /* Return the valid set if we're already on it.  */
+  if (!ignore_first)
+    {
+      regset src = NULL;
+      
+      if (sel_bb_head_p (insn) && BB_LV_SET_VALID_P (bb))
+        src = BB_LV_SET (bb);
+      else 
+        {
+          gcc_assert (in_current_region_p (bb));
+          if (INSN_LIVE_VALID_P (insn))
+            src = INSN_LIVE (insn);
+        }
+      
+      if (src)
+       {
+         lv = get_regset_from_pool ();
+         COPY_REG_SET (lv, src);
+
+          if (sel_bb_head_p (insn) && ! BB_LV_SET_VALID_P (bb))
+            {
+              COPY_REG_SET (BB_LV_SET (bb), lv);
+              BB_LV_SET_VALID_P (bb) = true;
+            }
+          
+         return_regset_to_pool (lv);
+         return lv;
+       }
+    }
+
+  /* We've skipped the wrong lv_set.  Don't skip the right one.  */
+  ignore_first = false;
+  gcc_assert (in_current_region_p (bb));
+
+  /* Find a valid LV set in this block or below, if needed.  
+     Start searching from the next insn: either ignore_first is true, or 
+     INSN doesn't have a correct live set.  */
+  temp = NEXT_INSN (insn);
+  final = NEXT_INSN (BB_END (bb));
+  while (temp != final && ! INSN_LIVE_VALID_P (temp))
+    temp = NEXT_INSN (temp);
+  if (temp == final)
+    {
+      lv = compute_live_after_bb (bb);
+      temp = PREV_INSN (temp);
+    }
+  else
+    {
+      lv = get_regset_from_pool ();
+      COPY_REG_SET (lv, INSN_LIVE (temp));
+    }
+
+  /* Put correct lv sets on the insns which have bad sets.  */
+  final = PREV_INSN (insn);
+  while (temp != final)
+    {
+      propagate_lv_set (lv, temp);
+      COPY_REG_SET (INSN_LIVE (temp), lv);
+      INSN_LIVE_VALID_P (temp) = true;
+      temp = PREV_INSN (temp);
+    }
+
+  /* Also put it in a BB.  */
+  if (sel_bb_head_p (insn))
+    {
+      basic_block bb = BLOCK_FOR_INSN (insn);
+      
+      COPY_REG_SET (BB_LV_SET (bb), lv);
+      BB_LV_SET_VALID_P (bb) = true;
+    }
+  
+  /* We return LV to the pool, but will not clear it there.  Thus we can
+     legimatelly use LV till the next use of regset_pool_get ().  */
+  return_regset_to_pool (lv);
+  return lv;
+}
+
+/* Update liveness sets for INSN.  */
+static inline void
+update_liveness_on_insn (rtx insn)
+{
+  ignore_first = true;
+  compute_live (insn);
+}
+
+/* Compute liveness below INSN and write it into REGS.  */
+static inline void
+compute_live_below_insn (rtx insn, regset regs)
+{
+  rtx succ;
+  succ_iterator si;
+  
+  FOR_EACH_SUCC_1 (succ, si, insn, SUCCS_ALL) 
+    IOR_REG_SET (regs, compute_live (succ));
+}
+
+/* Update the data gathered in av and lv sets starting from INSN.  */
+static void
+update_data_sets (rtx insn)
+{
+  update_liveness_on_insn (insn);
+  if (sel_bb_head_p (insn))
+    {
+      gcc_assert (AV_LEVEL (insn) != 0);
+      BB_AV_LEVEL (BLOCK_FOR_INSN (insn)) = -1;
+      compute_av_set (insn, NULL, 0, 0);
+    }
+}
+\f
+
+/* Helper for move_op () and find_used_regs ().
+   Return speculation type for which a check should be created on the place
+   of INSN.  EXPR is one of the original ops we are searching for.  */
+static ds_t
+get_spec_check_type_for_insn (insn_t insn, expr_t expr)
+{
+  ds_t to_check_ds;
+  ds_t already_checked_ds = EXPR_SPEC_DONE_DS (INSN_EXPR (insn));
+
+  to_check_ds = EXPR_SPEC_TO_CHECK_DS (expr);
+
+  if (targetm.sched.get_insn_checked_ds)
+    already_checked_ds |= targetm.sched.get_insn_checked_ds (insn);
+
+  if (spec_info != NULL
+      && (spec_info->flags & SEL_SCHED_SPEC_DONT_CHECK_CONTROL))
+    already_checked_ds |= BEGIN_CONTROL;
+
+  already_checked_ds = ds_get_speculation_types (already_checked_ds);
+
+  to_check_ds &= ~already_checked_ds;
+
+  return to_check_ds;
+}
+
+/* Find the set of registers that are unavailable for storing expres 
+   while moving ORIG_OPS up on the path starting from INSN due to
+   liveness (USED_REGS) or hardware restrictions (REG_RENAME_P).
+
+   All the original operations found during the traversal are saved in the
+   ORIGINAL_INSNS list.
+
+   REG_RENAME_P denotes the set of hardware registers that
+   can not be used with renaming due to the register class restrictions,
+   mode restrictions and other (the register we'll choose should be 
+   compatible class with the original uses, shouldn't be in call_used_regs,
+   should be HARD_REGNO_RENAME_OK etc).
+
+   Returns TRUE if we've found all original insns, FALSE otherwise.
+
+   This function utilizes code_motion_path_driver (formerly find_used_regs_1)
+   to traverse the code motion paths.  This helper function finds registers 
+   that are not available for storing expres while moving ORIG_OPS up on the 
+   path starting from INSN.  A register considered as used on the moving path,
+   if one of the following conditions is not satisfied:
+
+      (1) a register not set or read on any path from xi to an instance of 
+         the original operation, 
+      (2) not among the live registers of the point immediately following the 
+          first original operation on a given downward path, except for the
+         original target register of the operation,
+      (3) not live on the other path of any conditional branch that is passed 
+         by the operation, in case original operations are not present on
+         both paths of the conditional branch.
+
+   All the original operations found during the traversal are saved in the
+   ORIGINAL_INSNS list.
+
+   REG_RENAME_P->CROSSES_CALL is true, if there is a call insn on the path 
+   from INSN to original insn. In this case CALL_USED_REG_SET will be added 
+   to unavailable hard regs at the point original operation is found.  */
+
+static bool
+find_used_regs (insn_t insn, av_set_t orig_ops, regset used_regs,
+               struct reg_rename  *reg_rename_p, def_list_t *original_insns)
+{
+  def_list_iterator i;
+  def_t def;
+  int res;
+  bool needs_spec_check_p = false;
+  expr_t expr;
+  av_set_iterator expr_iter;
+  struct fur_static_params sparams;
+  struct cmpd_local_params lparams;
+
+  /* We haven't visited any blocks yet.  */
+  bitmap_clear (code_motion_visited_blocks);
+
+  /* Init parameters for code_motion_path_driver.  */
+  sparams.crosses_call = false;
+  sparams.original_insns = original_insns;
+  sparams.used_regs = used_regs;
+  
+  /* Set the appropriate hooks and data.  */
+  code_motion_path_driver_info = &fur_hooks;
+  
+  res = code_motion_path_driver (insn, orig_ops, NULL, &lparams, &sparams);
+
+  reg_rename_p->crosses_call |= sparams.crosses_call;
+
+  gcc_assert (res == 1);
+  gcc_assert (original_insns && *original_insns);
+
+  /* ??? We calculate whether an expression needs a check when computing
+     av sets.  This information is not as precise as it could be due to
+     merging this bit in merge_expr.  We can do better in find_used_regs,
+     but we want to avoid multiple traversals of the same code motion 
+     paths.  */
+  FOR_EACH_EXPR (expr, expr_iter, orig_ops)
+    needs_spec_check_p |= EXPR_NEEDS_SPEC_CHECK_P (expr);
+
+  /* Mark hardware regs in REG_RENAME_P that are not suitable 
+     for renaming expr in INSN due to hardware restrictions (register class,
+     modes compatibility etc).  */
+  FOR_EACH_DEF (def, i, *original_insns)
+    {
+      vinsn_t vinsn = INSN_VINSN (def->orig_insn);
+
+      if (VINSN_SEPARABLE_P (vinsn))
+       mark_unavailable_hard_regs (def, reg_rename_p, used_regs);
+
+      /* Do not allow clobbering of ld.[sa] address in case some of the 
+         original operations need a check.  */
+      if (needs_spec_check_p)
+       IOR_REG_SET (used_regs, VINSN_REG_USES (vinsn));
+    }
+
+  return true;
+}
+\f
+
+/* Functions to choose the best insn from available ones.  */
+
+/* Adjusts the priority for EXPR using the backend *_adjust_priority hook.  */
+static int
+sel_target_adjust_priority (expr_t expr)
+{
+  int priority = EXPR_PRIORITY (expr);
+  int new_priority;
+
+  if (targetm.sched.adjust_priority)
+    new_priority = targetm.sched.adjust_priority (EXPR_INSN_RTX (expr), priority);
+  else
+    new_priority = priority;
+
+  /* If the priority has changed, adjust EXPR_PRIORITY_ADJ accordingly.  */
+  EXPR_PRIORITY_ADJ (expr) = new_priority - EXPR_PRIORITY (expr);
+
+  gcc_assert (EXPR_PRIORITY_ADJ (expr) >= 0);
+
+  if (sched_verbose >= 2)
+    sel_print ("sel_target_adjust_priority: insn %d,  %d +%d = %d.\n", 
+              INSN_UID (EXPR_INSN_RTX (expr)), EXPR_PRIORITY (expr), 
+              EXPR_PRIORITY_ADJ (expr), new_priority);
+
+  return new_priority;
+}
+
+/* Rank two available exprs for schedule.  Never return 0 here.  */
+static int 
+sel_rank_for_schedule (const void *x, const void *y)
+{
+  expr_t tmp = *(const expr_t *) y;
+  expr_t tmp2 = *(const expr_t *) x;
+  insn_t tmp_insn, tmp2_insn;
+  vinsn_t tmp_vinsn, tmp2_vinsn;
+  int val;
+
+  tmp_vinsn = EXPR_VINSN (tmp);
+  tmp2_vinsn = EXPR_VINSN (tmp2);
+  tmp_insn = EXPR_INSN_RTX (tmp);
+  tmp2_insn = EXPR_INSN_RTX (tmp2);
+  
+  /* Prefer SCHED_GROUP_P insns to any others.  */
+  if (SCHED_GROUP_P (tmp_insn) != SCHED_GROUP_P (tmp2_insn))
+    {
+      if (VINSN_UNIQUE_P (tmp_vinsn) && VINSN_UNIQUE_P (tmp2_vinsn)) 
+        return SCHED_GROUP_P (tmp2_insn) ? 1 : -1;
+
+      /* Now uniqueness means SCHED_GROUP_P is set, because schedule groups
+         cannot be cloned.  */
+      if (VINSN_UNIQUE_P (tmp2_vinsn))
+        return 1;
+      return -1;
+    }
+
+  /* Discourage scheduling of speculative checks.  */
+  val = (sel_insn_is_speculation_check (tmp_insn)
+        - sel_insn_is_speculation_check (tmp2_insn));
+  if (val)
+    return val;
+
+  /* Prefer not scheduled insn over scheduled one.  */
+  if (EXPR_SCHED_TIMES (tmp) > 0 || EXPR_SCHED_TIMES (tmp2) > 0)
+    {
+      val = EXPR_SCHED_TIMES (tmp) - EXPR_SCHED_TIMES (tmp2);
+      if (val)
+       return val;
+    }
+
+  /* Prefer jump over non-jump instruction.  */
+  if (control_flow_insn_p (tmp_insn) && !control_flow_insn_p (tmp2_insn))
+    return -1;
+  else if (control_flow_insn_p (tmp2_insn) && !control_flow_insn_p (tmp_insn))
+    return 1;
+
+  /* Prefer an expr with greater priority.  */
+  if (EXPR_USEFULNESS (tmp) != 0 && EXPR_USEFULNESS (tmp2) != 0)
+    {
+      int p2 = EXPR_PRIORITY (tmp2) + EXPR_PRIORITY_ADJ (tmp2),
+          p1 = EXPR_PRIORITY (tmp) + EXPR_PRIORITY_ADJ (tmp);
+
+      val = p2 * EXPR_USEFULNESS (tmp2) - p1 * EXPR_USEFULNESS (tmp);
+    }
+  else
+    val = EXPR_PRIORITY (tmp2) - EXPR_PRIORITY (tmp) 
+         + EXPR_PRIORITY_ADJ (tmp2) - EXPR_PRIORITY_ADJ (tmp);
+  if (val)
+    return val;
+
+  if (spec_info != NULL && spec_info->mask != 0)
+    /* This code was taken from haifa-sched.c: rank_for_schedule ().  */
+    {
+      ds_t ds1, ds2;
+      dw_t dw1, dw2;
+      int dw;
+
+      ds1 = EXPR_SPEC_DONE_DS (tmp);
+      if (ds1)
+       dw1 = ds_weak (ds1);
+      else
+       dw1 = NO_DEP_WEAK;
+
+      ds2 = EXPR_SPEC_DONE_DS (tmp2);
+      if (ds2)
+       dw2 = ds_weak (ds2);
+      else
+       dw2 = NO_DEP_WEAK;
+
+      dw = dw2 - dw1;
+      if (dw > (NO_DEP_WEAK / 8) || dw < -(NO_DEP_WEAK / 8))
+       return dw;
+    }
+
+  tmp_insn = EXPR_INSN_RTX (tmp);
+  tmp2_insn = EXPR_INSN_RTX (tmp2);
+
+  /* Prefer an old insn to a bookkeeping insn.  */
+  if (INSN_UID (tmp_insn) < first_emitted_uid 
+      && INSN_UID (tmp2_insn) >= first_emitted_uid)
+    return -1;
+  if (INSN_UID (tmp_insn) >= first_emitted_uid 
+      && INSN_UID (tmp2_insn) < first_emitted_uid)
+    return 1;
+
+  /* Prefer an insn with smaller UID, as a last resort.  
+     We can't safely use INSN_LUID as it is defined only for those insns
+     that are in the stream.  */
+  return INSN_UID (tmp_insn) - INSN_UID (tmp2_insn);
+}
+
+/* Filter out expressions from av set pointed to by AV_PTR 
+   that are pipelined too many times.  */
+static void
+process_pipelined_exprs (av_set_t *av_ptr)
+{
+  expr_t expr;
+  av_set_iterator si;
+
+  /* Don't pipeline already pipelined code as that would increase
+     number of unnecessary register moves.  */  
+  FOR_EACH_EXPR_1 (expr, si, av_ptr)
+    {
+      if (EXPR_SCHED_TIMES (expr)
+         >= PARAM_VALUE (PARAM_SELSCHED_MAX_SCHED_TIMES))
+       av_set_iter_remove (&si);
+    }
+}
+
+/* Filter speculative insns from AV_PTR if we don't want them.  */
+static void
+process_spec_exprs (av_set_t *av_ptr)
+{
+  bool try_data_p = true;
+  bool try_control_p = true;
+  expr_t expr;
+  av_set_iterator si;
+
+  if (spec_info == NULL)
+    return;
+
+  /* Scan *AV_PTR to find out if we want to consider speculative
+     instructions for scheduling.  */
+  FOR_EACH_EXPR_1 (expr, si, av_ptr)
+    {
+      ds_t ds;
+
+      ds = EXPR_SPEC_DONE_DS (expr);
+
+      /* The probability of a success is too low - don't speculate.  */
+      if ((ds & SPECULATIVE)
+          && (ds_weak (ds) < spec_info->data_weakness_cutoff
+              || EXPR_USEFULNESS (expr) < spec_info->control_weakness_cutoff
+             || (pipelining_p && false
+                 && (ds & DATA_SPEC)
+                 && (ds & CONTROL_SPEC))))
+        {
+          av_set_iter_remove (&si);
+          continue;
+        }
+
+      if ((spec_info->flags & PREFER_NON_DATA_SPEC)
+          && !(ds & BEGIN_DATA))
+        try_data_p = false;
+
+      if ((spec_info->flags & PREFER_NON_CONTROL_SPEC)
+          && !(ds & BEGIN_CONTROL))
+        try_control_p = false;
+    }
+
+  FOR_EACH_EXPR_1 (expr, si, av_ptr)
+    {
+      ds_t ds;
+
+      ds = EXPR_SPEC_DONE_DS (expr);
+
+      if (ds & SPECULATIVE)
+        {
+          if ((ds & BEGIN_DATA) && !try_data_p)
+            /* We don't want any data speculative instructions right
+               now.  */
+            av_set_iter_remove (&si);
+
+          if ((ds & BEGIN_CONTROL) && !try_control_p)
+            /* We don't want any control speculative instructions right
+               now.  */
+            av_set_iter_remove (&si);
+        }
+    }
+}
+
+/* Search for any use-like insns in AV_PTR and decide on scheduling 
+   them.  Return one when found, and NULL otherwise.  
+   Note that we check here whether a USE could be scheduled to avoid
+   an infinite loop later.  */
+static expr_t
+process_use_exprs (av_set_t *av_ptr)
+{
+  expr_t expr;
+  av_set_iterator si;
+  bool uses_present_p = false;
+  bool try_uses_p = true;
+
+  FOR_EACH_EXPR_1 (expr, si, av_ptr)
+    {
+      /* This will also initialize INSN_CODE for later use.  */
+      if (recog_memoized (EXPR_INSN_RTX (expr)) < 0)
+        {
+          /* If we have a USE in *AV_PTR that was not scheduled yet,
+             do so because it will do good only.  */
+          if (EXPR_SCHED_TIMES (expr) <= 0)
+            {
+              if (EXPR_TARGET_AVAILABLE (expr) == 1)
+                return expr;
+
+              av_set_iter_remove (&si);
+            }
+          else
+            {
+              gcc_assert (pipelining_p);
+
+              uses_present_p = true;
+            }
+        }
+      else
+        try_uses_p = false;
+    }
+
+  if (uses_present_p)
+    {
+      /* If we don't want to schedule any USEs right now and we have some
+           in *AV_PTR, remove them, else just return the first one found.  */
+      if (!try_uses_p)
+        {
+          FOR_EACH_EXPR_1 (expr, si, av_ptr)
+            if (INSN_CODE (EXPR_INSN_RTX (expr)) < 0)
+              av_set_iter_remove (&si);
+        }
+      else
+        {
+          FOR_EACH_EXPR_1 (expr, si, av_ptr)
+            {
+              gcc_assert (INSN_CODE (EXPR_INSN_RTX (expr)) < 0);
+
+              if (EXPR_TARGET_AVAILABLE (expr) == 1)
+                return expr;
+
+              av_set_iter_remove (&si);
+            }
+        }
+    }
+
+  return NULL;
+}
+
+/* Lookup EXPR in VINSN_VEC and return TRUE if found.  */
+static bool
+vinsn_vec_has_expr_p (vinsn_vec_t vinsn_vec, expr_t expr)
+{
+  vinsn_t vinsn;
+  int n;
+
+  for (n = 0; VEC_iterate (vinsn_t, vinsn_vec, n, vinsn); n++)
+    if (VINSN_SEPARABLE_P (vinsn))
+      {
+        if (vinsn_equal_p (vinsn, EXPR_VINSN (expr)))
+          return true;
+      }
+    else
+      {
+        /* For non-separable instructions, the blocking insn can have
+           another pattern due to substitution, and we can't choose
+           different register as in the above case.  Check all registers
+           being written instead.  */
+        if (bitmap_intersect_p (VINSN_REG_SETS (vinsn), 
+                                VINSN_REG_SETS (EXPR_VINSN (expr))))
+          return true;
+      }
+
+  return false;
+}
+
+#ifdef ENABLE_CHECKING
+/* Return true if either of expressions from ORIG_OPS can be blocked
+   by previously created bookkeeping code.  STATIC_PARAMS points to static
+   parameters of move_op.  */
+static bool
+av_set_could_be_blocked_by_bookkeeping_p (av_set_t orig_ops, void *static_params)
+{
+  expr_t expr;
+  av_set_iterator iter;
+  moveop_static_params_p sparams;
+
+  /* This checks that expressions in ORIG_OPS are not blocked by bookkeeping
+     created while scheduling on another fence.  */
+  FOR_EACH_EXPR (expr, iter, orig_ops)
+    if (vinsn_vec_has_expr_p (vec_bookkeeping_blocked_vinsns, expr))
+      return true;
+
+  gcc_assert (code_motion_path_driver_info == &move_op_hooks);
+  sparams = (moveop_static_params_p) static_params;
+
+  /* Expressions can be also blocked by bookkeeping created during current
+     move_op.  */
+  if (bitmap_bit_p (current_copies, INSN_UID (sparams->failed_insn)))
+    FOR_EACH_EXPR (expr, iter, orig_ops)
+      if (moveup_expr_cached (expr, sparams->failed_insn, false) != MOVEUP_EXPR_NULL)
+        return true;
+
+  /* Expressions in ORIG_OPS may have wrong destination register due to
+     renaming.  Check with the right register instead.  */
+  if (sparams->dest && REG_P (sparams->dest))
+    {
+      unsigned regno = REGNO (sparams->dest);
+      vinsn_t failed_vinsn = INSN_VINSN (sparams->failed_insn);
+
+      if (bitmap_bit_p (VINSN_REG_SETS (failed_vinsn), regno)
+         || bitmap_bit_p (VINSN_REG_USES (failed_vinsn), regno)
+         || bitmap_bit_p (VINSN_REG_CLOBBERS (failed_vinsn), regno))
+       return true;
+    }
+
+  return false;
+}
+#endif
+
+/* Clear VINSN_VEC and detach vinsns.  */
+static void
+vinsn_vec_clear (vinsn_vec_t *vinsn_vec)
+{
+  unsigned len = VEC_length (vinsn_t, *vinsn_vec);
+  if (len > 0)
+    {
+      vinsn_t vinsn;
+      int n;
+      
+      for (n = 0; VEC_iterate (vinsn_t, *vinsn_vec, n, vinsn); n++)
+        vinsn_detach (vinsn);
+      VEC_block_remove (vinsn_t, *vinsn_vec, 0, len);
+    }
+}
+
+/* Add the vinsn of EXPR to the VINSN_VEC.  */
+static void
+vinsn_vec_add (vinsn_vec_t *vinsn_vec, expr_t expr)
+{
+  vinsn_attach (EXPR_VINSN (expr));
+  VEC_safe_push (vinsn_t, heap, *vinsn_vec, EXPR_VINSN (expr));
+}
+
+/* Free the vector representing blocked expressions.  */    
+static void
+vinsn_vec_free (vinsn_vec_t *vinsn_vec)
+{
+  if (*vinsn_vec)
+    VEC_free (vinsn_t, heap, *vinsn_vec);
+}
+
+/* Increase EXPR_PRIORITY_ADJ for INSN by AMOUNT.  */
+
+void sel_add_to_insn_priority (rtx insn, int amount)
+{
+  EXPR_PRIORITY_ADJ (INSN_EXPR (insn)) += amount;
+
+  if (sched_verbose >= 2)
+    sel_print ("sel_add_to_insn_priority: insn %d, by %d (now %d+%d).\n", 
+              INSN_UID (insn), amount, EXPR_PRIORITY (INSN_EXPR (insn)),
+              EXPR_PRIORITY_ADJ (INSN_EXPR (insn)));
+}
+
+/* Turn AV into a vector, filter inappropriate insns and sort it.  Return 
+   true if there is something to schedule.  BNDS and FENCE are current
+   boundaries and fence, respectively.  If we need to stall for some cycles
+   before an expr from AV would become available, write this number to 
+   *PNEED_STALL.  */
+static bool
+fill_vec_av_set (av_set_t av, blist_t bnds, fence_t fence,
+                 int *pneed_stall)
+{
+  av_set_iterator si;
+  expr_t expr;
+  int sched_next_worked = 0, stalled, n;
+  static int av_max_prio, est_ticks_till_branch;
+  int min_need_stall = -1;
+  deps_t dc = BND_DC (BLIST_BND (bnds));
+
+  /* Bail out early when the ready list contained only USEs/CLOBBERs that are
+     already scheduled.  */
+  if (av == NULL)
+    return false;
+
+  /* Empty vector from the previous stuff.  */
+  if (VEC_length (expr_t, vec_av_set) > 0)
+    VEC_block_remove (expr_t, vec_av_set, 0, VEC_length (expr_t, vec_av_set));
+
+  /* Turn the set into a vector for sorting and call sel_target_adjust_priority
+     for each insn.  */
+  gcc_assert (VEC_empty (expr_t, vec_av_set));
+  FOR_EACH_EXPR (expr, si, av)
+    {  
+      VEC_safe_push (expr_t, heap, vec_av_set, expr);
+
+      gcc_assert (EXPR_PRIORITY_ADJ (expr) == 0 || *pneed_stall);
+
+      /* Adjust priority using target backend hook.  */
+      sel_target_adjust_priority (expr);
+    }
+
+  /* Sort the vector.  */
+  qsort (VEC_address (expr_t, vec_av_set), VEC_length (expr_t, vec_av_set),
+         sizeof (expr_t), sel_rank_for_schedule);
+
+  /* We record maximal priority of insns in av set for current instruction
+     group.  */
+  if (FENCE_STARTS_CYCLE_P (fence))
+    av_max_prio = est_ticks_till_branch = INT_MIN;
+
+  /* Filter out inappropriate expressions.  Loop's direction is reversed to
+     visit "best" instructions first.  We assume that VEC_unordered_remove
+     moves last element in place of one being deleted.  */
+  for (n = VEC_length (expr_t, vec_av_set) - 1, stalled = 0; n >= 0; n--)
+    {
+      expr_t expr = VEC_index (expr_t, vec_av_set, n);
+      insn_t insn = EXPR_INSN_RTX (expr);
+      char target_available;
+      bool is_orig_reg_p = true;
+      int need_cycles, new_prio;
+
+      /* Don't allow any insns other than from SCHED_GROUP if we have one.  */
+      if (FENCE_SCHED_NEXT (fence) && insn != FENCE_SCHED_NEXT (fence))
+        {
+          VEC_unordered_remove (expr_t, vec_av_set, n);
+          continue;
+        }
+
+      /* Set number of sched_next insns (just in case there 
+         could be several).  */
+      if (FENCE_SCHED_NEXT (fence))
+        sched_next_worked++;
+      
+      /* Check all liveness requirements and try renaming.  
+         FIXME: try to minimize calls to this.  */
+      target_available = EXPR_TARGET_AVAILABLE (expr);
+
+      /* If insn was already scheduled on the current fence,
+        set TARGET_AVAILABLE to -1 no matter what expr's attribute says.  */
+      if (vinsn_vec_has_expr_p (vec_target_unavailable_vinsns, expr))
+       target_available = -1;
+
+      /* If the availability of the EXPR is invalidated by the insertion of
+        bookkeeping earlier, make sure that we won't choose this expr for
+        scheduling if it's not separable, and if it is separable, then
+        we have to recompute the set of available registers for it.  */
+      if (vinsn_vec_has_expr_p (vec_bookkeeping_blocked_vinsns, expr))
+       {
+          VEC_unordered_remove (expr_t, vec_av_set, n);
+          if (sched_verbose >= 4)
+            sel_print ("Expr %d is blocked by bookkeeping inserted earlier\n",
+                       INSN_UID (insn));
+          continue;
+        }
+      
+      if (target_available == true)
+       {
+          /* Do nothing -- we can use an existing register.  */
+         is_orig_reg_p = EXPR_SEPARABLE_P (expr);
+        }
+      else if (/* Non-separable instruction will never 
+                  get another register. */
+               (target_available == false
+                && !EXPR_SEPARABLE_P (expr))
+               /* Don't try to find a register for low-priority expression.  */
+               || (int) VEC_length (expr_t, vec_av_set) - 1 - n >= max_insns_to_rename
+               /* ??? FIXME: Don't try to rename data speculation.  */
+               || (EXPR_SPEC_DONE_DS (expr) & BEGIN_DATA)
+               || ! find_best_reg_for_expr (expr, bnds, &is_orig_reg_p))
+        {
+          VEC_unordered_remove (expr_t, vec_av_set, n);
+          if (sched_verbose >= 4)
+            sel_print ("Expr %d has no suitable target register\n", 
+                       INSN_UID (insn));
+          continue;
+        }
+
+      /* Filter expressions that need to be renamed or speculated when
+        pipelining, because compensating register copies or speculation
+        checks are likely to be placed near the beginning of the loop,
+        causing a stall.  */
+      if (pipelining_p && EXPR_ORIG_SCHED_CYCLE (expr) > 0
+         && (!is_orig_reg_p || EXPR_SPEC_DONE_DS (expr) != 0))
+       {
+         /* Estimation of number of cycles until loop branch for
+            renaming/speculation to be successful.  */
+         int need_n_ticks_till_branch = sel_vinsn_cost (EXPR_VINSN (expr));
+
+         if ((int) current_loop_nest->ninsns < 9)
+           {
+             VEC_unordered_remove (expr_t, vec_av_set, n);
+             if (sched_verbose >= 4)
+               sel_print ("Pipelining expr %d will likely cause stall\n",
+                          INSN_UID (insn));
+             continue;
+           }
+
+         if ((int) current_loop_nest->ninsns - num_insns_scheduled
+             < need_n_ticks_till_branch * issue_rate / 2
+             && est_ticks_till_branch < need_n_ticks_till_branch)
+            {
+              VEC_unordered_remove (expr_t, vec_av_set, n);
+              if (sched_verbose >= 4)
+                sel_print ("Pipelining expr %d will likely cause stall\n",
+                           INSN_UID (insn));
+              continue;
+            }
+       }
+
+      /* We want to schedule speculation checks as late as possible.  Discard
+        them from av set if there are instructions with higher priority.  */
+      if (sel_insn_is_speculation_check (insn)
+         && EXPR_PRIORITY (expr) < av_max_prio)
+       {
+          stalled++;
+          min_need_stall = min_need_stall < 0 ? 1 : MIN (min_need_stall, 1);
+          VEC_unordered_remove (expr_t, vec_av_set, n);
+         if (sched_verbose >= 4)
+           sel_print ("Delaying speculation check %d until its first use\n",
+                      INSN_UID (insn));
+         continue;
+       }
+
+      /* Ignore EXPRs available from pipelining to update AV_MAX_PRIO.  */
+      if (EXPR_ORIG_SCHED_CYCLE (expr) <= 0)
+       av_max_prio = MAX (av_max_prio, EXPR_PRIORITY (expr));
+
+      /* Don't allow any insns whose data is not yet ready.
+         Check first whether we've already tried them and failed.  */
+      if (INSN_UID (insn) < FENCE_READY_TICKS_SIZE (fence))
+       {
+          need_cycles = (FENCE_READY_TICKS (fence)[INSN_UID (insn)]
+                        - FENCE_CYCLE (fence));
+         if (EXPR_ORIG_SCHED_CYCLE (expr) <= 0)
+           est_ticks_till_branch = MAX (est_ticks_till_branch,
+                                        EXPR_PRIORITY (expr) + need_cycles);
+
+         if (need_cycles > 0)
+           {
+             stalled++;
+             min_need_stall = (min_need_stall < 0 
+                               ? need_cycles
+                               : MIN (min_need_stall, need_cycles));
+             VEC_unordered_remove (expr_t, vec_av_set, n);
+
+             if (sched_verbose >= 4)
+               sel_print ("Expr %d is not ready until cycle %d (cached)\n", 
+                          INSN_UID (insn),
+                          FENCE_READY_TICKS (fence)[INSN_UID (insn)]);
+             continue;
+           }
+       }
+
+      /* Now resort to dependence analysis to find whether EXPR might be 
+         stalled due to dependencies from FENCE's context.  */
+      need_cycles = tick_check_p (expr, dc, fence);
+      new_prio = EXPR_PRIORITY (expr) + EXPR_PRIORITY_ADJ (expr) + need_cycles;
+
+      if (EXPR_ORIG_SCHED_CYCLE (expr) <= 0)
+       est_ticks_till_branch = MAX (est_ticks_till_branch,
+                                    new_prio);
+
+      if (need_cycles > 0)
+        {
+          if (INSN_UID (insn) >= FENCE_READY_TICKS_SIZE (fence))
+            {
+              int new_size = INSN_UID (insn) * 3 / 2;
+              
+              FENCE_READY_TICKS (fence) 
+                = (int *) xrecalloc (FENCE_READY_TICKS (fence),
+                                     new_size, FENCE_READY_TICKS_SIZE (fence),
+                                     sizeof (int));
+            }
+          FENCE_READY_TICKS (fence)[INSN_UID (insn)] 
+            = FENCE_CYCLE (fence) + need_cycles; 
+          
+          stalled++;
+          min_need_stall = (min_need_stall < 0 
+                            ? need_cycles
+                            : MIN (min_need_stall, need_cycles));
+
+          VEC_unordered_remove (expr_t, vec_av_set, n);
+          
+          if (sched_verbose >= 4)
+            sel_print ("Expr %d is not ready yet until cycle %d\n", 
+                       INSN_UID (insn),
+                       FENCE_READY_TICKS (fence)[INSN_UID (insn)]);
+          continue;
+        }
+
+      if (sched_verbose >= 4)
+        sel_print ("Expr %d is ok\n", INSN_UID (insn));
+      min_need_stall = 0;
+    }
+
+  /* Clear SCHED_NEXT.  */
+  if (FENCE_SCHED_NEXT (fence))
+    {
+      gcc_assert (sched_next_worked == 1);
+      FENCE_SCHED_NEXT (fence) = NULL_RTX;
+    }
+
+  /* No need to stall if this variable was not initialized.  */
+  if (min_need_stall < 0)
+    min_need_stall = 0;
+
+  if (VEC_empty (expr_t, vec_av_set))
+    {
+      /* We need to set *pneed_stall here, because later we skip this code
+         when ready list is empty.  */
+      *pneed_stall = min_need_stall;
+      return false;
+    }
+  else
+    gcc_assert (min_need_stall == 0);
+
+  /* Sort the vector.  */
+  qsort (VEC_address (expr_t, vec_av_set), VEC_length (expr_t, vec_av_set),
+         sizeof (expr_t), sel_rank_for_schedule);
+  
+  if (sched_verbose >= 4)
+    {
+      sel_print ("Total ready exprs: %d, stalled: %d\n", 
+                 VEC_length (expr_t, vec_av_set), stalled);
+      sel_print ("Sorted av set (%d): ", VEC_length (expr_t, vec_av_set));
+      for (n = 0; VEC_iterate (expr_t, vec_av_set, n, expr); n++)
+        dump_expr (expr);
+      sel_print ("\n");
+    }
+
+  *pneed_stall = 0;
+  return true;
+}
+
+/* Convert a vectored and sorted av set to the ready list that
+   the rest of the backend wants to see.  */
+static void
+convert_vec_av_set_to_ready (void)
+{
+  int n;
+  expr_t expr;
+
+  /* Allocate and fill the ready list from the sorted vector.  */
+  ready.n_ready = VEC_length (expr_t, vec_av_set);
+  ready.first = ready.n_ready - 1;
+  
+  gcc_assert (ready.n_ready > 0);
+
+  if (ready.n_ready > max_issue_size)
+    {
+      max_issue_size = ready.n_ready;
+      sched_extend_ready_list (ready.n_ready);
+    }
+  
+  for (n = 0; VEC_iterate (expr_t, vec_av_set, n, expr); n++)
+    {
+      vinsn_t vi = EXPR_VINSN (expr);
+      insn_t insn = VINSN_INSN_RTX (vi);
+
+      ready_try[n] = 0;
+      ready.vec[n] = insn;
+    }
+}
+
+/* Initialize ready list from *AV_PTR for the max_issue () call.
+   If any unrecognizable insn found in *AV_PTR, return it (and skip
+   max_issue).  BND and FENCE are current boundary and fence, 
+   respectively.  If we need to stall for some cycles before an expr 
+   from *AV_PTR would become available, write this number to *PNEED_STALL.  */
+static expr_t
+fill_ready_list (av_set_t *av_ptr, blist_t bnds, fence_t fence,
+                 int *pneed_stall)
+{
+  expr_t expr;
+
+  /* We do not support multiple boundaries per fence.  */
+  gcc_assert (BLIST_NEXT (bnds) == NULL);
+
+  /* Process expressions required special handling, i.e.  pipelined, 
+     speculative and recog() < 0 expressions first.  */
+  process_pipelined_exprs (av_ptr);
+  process_spec_exprs (av_ptr);
+
+  /* A USE could be scheduled immediately.  */
+  expr = process_use_exprs (av_ptr);
+  if (expr)
+    {
+      *pneed_stall = 0;
+      return expr;
+    }
+
+  /* Turn the av set to a vector for sorting.  */
+  if (! fill_vec_av_set (*av_ptr, bnds, fence, pneed_stall))
+    {
+      ready.n_ready = 0;
+      return NULL;
+    }
+
+  /* Build the final ready list.  */
+  convert_vec_av_set_to_ready ();
+  return NULL;
+}
+
+/* Wrapper for dfa_new_cycle ().  Returns TRUE if cycle was advanced.  */
+static bool
+sel_dfa_new_cycle (insn_t insn, fence_t fence)
+{
+  int last_scheduled_cycle = FENCE_LAST_SCHEDULED_INSN (fence) 
+                             ? INSN_SCHED_CYCLE (FENCE_LAST_SCHEDULED_INSN (fence)) 
+                             : FENCE_CYCLE (fence) - 1;
+  bool res = false;
+  int sort_p = 0;
+
+  if (!targetm.sched.dfa_new_cycle)
+    return false;
+
+  memcpy (curr_state, FENCE_STATE (fence), dfa_state_size);
+
+  while (!sort_p && targetm.sched.dfa_new_cycle (sched_dump, sched_verbose,
+                                                 insn, last_scheduled_cycle,
+                                                 FENCE_CYCLE (fence), &sort_p))
+    {
+      memcpy (FENCE_STATE (fence), curr_state, dfa_state_size);
+      advance_one_cycle (fence);
+      memcpy (curr_state, FENCE_STATE (fence), dfa_state_size);
+      res = true;
+    }
+
+  return res;
+}
+
+/* Invoke reorder* target hooks on the ready list.  Return the number of insns
+   we can issue.  FENCE is the current fence.  */
+static int
+invoke_reorder_hooks (fence_t fence)
+{
+  int issue_more;
+  bool ran_hook = false;
+
+  /* Call the reorder hook at the beginning of the cycle, and call
+     the reorder2 hook in the middle of the cycle.  */
+  if (FENCE_ISSUED_INSNS (fence) == 0)
+    {
+      if (targetm.sched.reorder
+          && !SCHED_GROUP_P (ready_element (&ready, 0))
+          && ready.n_ready > 1)
+        {
+          /* Don't give reorder the most prioritized insn as it can break
+             pipelining.  */
+          if (pipelining_p)
+            --ready.n_ready;
+
+          issue_more
+            = targetm.sched.reorder (sched_dump, sched_verbose,
+                                     ready_lastpos (&ready),
+                                     &ready.n_ready, FENCE_CYCLE (fence));
+
+          if (pipelining_p)
+            ++ready.n_ready;
+
+          ran_hook = true;
+        }
+      else
+        /* Initialize can_issue_more for variable_issue.  */
+        issue_more = issue_rate;
+    }
+  else if (targetm.sched.reorder2
+           && !SCHED_GROUP_P (ready_element (&ready, 0)))
+    {
+      if (ready.n_ready == 1)
+        issue_more = 
+          targetm.sched.reorder2 (sched_dump, sched_verbose,
+                                  ready_lastpos (&ready),
+                                  &ready.n_ready, FENCE_CYCLE (fence));
+      else
+        {
+          if (pipelining_p)
+            --ready.n_ready;
+
+          issue_more =
+            targetm.sched.reorder2 (sched_dump, sched_verbose,
+                                    ready.n_ready
+                                    ? ready_lastpos (&ready) : NULL,
+                                    &ready.n_ready, FENCE_CYCLE (fence));
+
+          if (pipelining_p)
+            ++ready.n_ready;
+        }
+
+      ran_hook = true;
+    }
+  else 
+    issue_more = issue_rate;
+
+  /* Ensure that ready list and vec_av_set are in line with each other,
+     i.e. vec_av_set[i] == ready_element (&ready, i).  */
+  if (issue_more && ran_hook)
+    {
+      int i, j, n;
+      rtx *arr = ready.vec;
+      expr_t *vec = VEC_address (expr_t, vec_av_set);
+
+      for (i = 0, n = ready.n_ready; i < n; i++)
+        if (EXPR_INSN_RTX (vec[i]) != arr[i])
+          {
+            expr_t tmp;
+
+            for (j = i; j < n; j++)
+              if (EXPR_INSN_RTX (vec[j]) == arr[i])
+                break;
+            gcc_assert (j < n);
+
+            tmp = vec[i]; 
+            vec[i] = vec[j];
+            vec[j] = tmp;
+          }
+    }
+
+  return issue_more;
+}
+
+/* Return an EXPR correponding to INDEX element of ready list, if 
+   FOLLOW_READY_ELEMENT is true (i.e., an expr of 
+   ready_element (&ready, INDEX) will be returned), and to INDEX element of 
+   ready.vec otherwise.  */
+static inline expr_t
+find_expr_for_ready (int index, bool follow_ready_element)
+{
+  expr_t expr;
+  int real_index;
+
+  real_index = follow_ready_element ? ready.first - index : index;
+
+  expr = VEC_index (expr_t, vec_av_set, real_index);
+  gcc_assert (ready.vec[real_index] == EXPR_INSN_RTX (expr));
+
+  return expr;
+}
+
+/* Calculate insns worth trying via lookahead_guard hook.  Return a number
+   of such insns found.  */
+static int
+invoke_dfa_lookahead_guard (void)
+{
+  int i, n;
+  bool have_hook 
+    = targetm.sched.first_cycle_multipass_dfa_lookahead_guard != NULL;
+
+  if (sched_verbose >= 2)
+    sel_print ("ready after reorder: ");
+
+  for (i = 0, n = 0; i < ready.n_ready; i++)
+    {
+      expr_t expr;
+      insn_t insn;
+      int r;
+
+      /* In this loop insn is Ith element of the ready list given by 
+         ready_element, not Ith element of ready.vec.  */
+      insn = ready_element (&ready, i);
+      
+      if (! have_hook || i == 0)
+        r = 0;
+      else
+        r = !targetm.sched.first_cycle_multipass_dfa_lookahead_guard (insn);
+      
+      gcc_assert (INSN_CODE (insn) >= 0);
+        
+      /* Only insns with ready_try = 0 can get here 
+         from fill_ready_list.  */
+      gcc_assert (ready_try [i] == 0);
+      ready_try[i] = r;
+      if (!r)
+        n++;
+
+      expr = find_expr_for_ready (i, true);
+      
+      if (sched_verbose >= 2)
+        {
+          dump_vinsn (EXPR_VINSN (expr));
+          sel_print (":%d; ", ready_try[i]);
+        }
+    }
+
+  if (sched_verbose >= 2)
+    sel_print ("\n");
+  return n;
+}
+
+/* Calculate the number of privileged insns and return it.  */
+static int
+calculate_privileged_insns (void)
+{
+  expr_t cur_expr, min_spec_expr = NULL;
+  insn_t cur_insn, min_spec_insn;
+  int privileged_n = 0, i;
+
+  for (i = 0; i < ready.n_ready; i++)
+    {
+      if (ready_try[i])
+        continue;
+
+      if (! min_spec_expr)
+        {
+          min_spec_insn = ready_element (&ready, i);
+          min_spec_expr = find_expr_for_ready (i, true);
+        }
+      
+      cur_insn = ready_element (&ready, i);
+      cur_expr = find_expr_for_ready (i, true);
+
+      if (EXPR_SPEC (cur_expr) > EXPR_SPEC (min_spec_expr))
+        break;
+
+      ++privileged_n;
+    }
+
+  if (i == ready.n_ready)
+    privileged_n = 0;
+
+  if (sched_verbose >= 2)
+    sel_print ("privileged_n: %d insns with SPEC %d\n",
+               privileged_n, privileged_n ? EXPR_SPEC (min_spec_expr) : -1);
+  return privileged_n;
+}
+
+/* Call the rest of the hooks after the choice was made.  Return 
+   the number of insns that still can be issued given that the current
+   number is ISSUE_MORE.  FENCE and BEST_INSN are the current fence
+   and the insn chosen for scheduling, respectively.  */
+static int
+invoke_aftermath_hooks (fence_t fence, rtx best_insn, int issue_more)
+{
+  gcc_assert (INSN_P (best_insn));
+
+  /* First, call dfa_new_cycle, and then variable_issue, if available.  */
+  sel_dfa_new_cycle (best_insn, fence);
+  
+  if (targetm.sched.variable_issue)
+    {
+      memcpy (curr_state, FENCE_STATE (fence), dfa_state_size);
+      issue_more = 
+        targetm.sched.variable_issue (sched_dump, sched_verbose, best_insn,
+                                      issue_more);
+      memcpy (FENCE_STATE (fence), curr_state, dfa_state_size);
+    }
+  else if (GET_CODE (PATTERN (best_insn)) != USE
+           && GET_CODE (PATTERN (best_insn)) != CLOBBER)
+    issue_more--;
+
+  return issue_more;
+}
+
+/* Estimate the cost of issuing INSN on DFA state STATE.  */
+static int
+estimate_insn_cost (rtx insn, state_t state)
+{
+  static state_t temp = NULL;
+  int cost;
+
+  if (!temp)
+    temp = xmalloc (dfa_state_size);
+
+  memcpy (temp, state, dfa_state_size);
+  cost = state_transition (temp, insn);
+
+  if (cost < 0)
+    return 0;
+  else if (cost == 0)
+    return 1;
+  return cost;
+}
+
+/* Return the cost of issuing EXPR on the FENCE as estimated by DFA.  
+   This function properly handles ASMs, USEs etc.  */
+static int
+get_expr_cost (expr_t expr, fence_t fence)
+{
+  rtx insn = EXPR_INSN_RTX (expr);
+
+  if (recog_memoized (insn) < 0)
+    {
+      if (!FENCE_STARTS_CYCLE_P (fence) 
+          /* FIXME: Is this condition necessary?  */
+          && VINSN_UNIQUE_P (EXPR_VINSN (expr))
+         && INSN_ASM_P (insn))
+       /* This is asm insn which is tryed to be issued on the
+          cycle not first.  Issue it on the next cycle.  */
+       return 1;
+      else
+       /* A USE insn, or something else we don't need to
+          understand.  We can't pass these directly to
+          state_transition because it will trigger a
+          fatal error for unrecognizable insns.  */
+       return 0;
+    }
+  else
+    return estimate_insn_cost (insn, FENCE_STATE (fence));
+}
+
+/* Find the best insn for scheduling, either via max_issue or just take 
+   the most prioritized available.  */
+static int
+choose_best_insn (fence_t fence, int privileged_n, int *index)
+{
+  int can_issue = 0;
+
+  if (dfa_lookahead > 0)
+    {
+      cycle_issued_insns = FENCE_ISSUED_INSNS (fence);
+      can_issue = max_issue (&ready, privileged_n,
+                             FENCE_STATE (fence), index);
+      if (sched_verbose >= 2)
+        sel_print ("max_issue: we can issue %d insns, already did %d insns\n",
+                   can_issue, FENCE_ISSUED_INSNS (fence));
+    }
+  else
+    {
+      /* We can't use max_issue; just return the first available element.  */
+      int i;
+
+      for (i = 0; i < ready.n_ready; i++)
+       {
+         expr_t expr = find_expr_for_ready (i, true);
+
+         if (get_expr_cost (expr, fence) < 1)
+           {
+             can_issue = can_issue_more;
+             *index = i;
+
+             if (sched_verbose >= 2)
+               sel_print ("using %dth insn from the ready list\n", i + 1);
+
+             break;
+           }
+       }
+
+      if (i == ready.n_ready)
+       {
+         can_issue = 0;
+         *index = -1;
+       }
+    }
+
+  return can_issue;
+}
+
+/* Choose the best expr from *AV_VLIW_PTR and a suitable register for it.  
+   BNDS and FENCE are current boundaries and scheduling fence respectively.  
+   Return the expr found and NULL if nothing can be issued atm.  
+   Write to PNEED_STALL the number of cycles to stall if no expr was found.  */ 
+static expr_t
+find_best_expr (av_set_t *av_vliw_ptr, blist_t bnds, fence_t fence,
+                int *pneed_stall)
+{
+  expr_t best;
+  
+  /* Choose the best insn for scheduling via:
+     1) sorting the ready list based on priority;
+     2) calling the reorder hook;
+     3) calling max_issue.  */
+  best = fill_ready_list (av_vliw_ptr, bnds, fence, pneed_stall);
+  if (best == NULL && ready.n_ready > 0)
+    {
+      int privileged_n, index, avail_n;
+
+      can_issue_more = invoke_reorder_hooks (fence);
+      if (can_issue_more > 0)
+        {
+          /* Try choosing the best insn until we find one that is could be 
+             scheduled due to liveness restrictions on its destination register.
+             In the future, we'd like to choose once and then just probe insns
+             in the order of their priority.  */
+          avail_n = invoke_dfa_lookahead_guard ();
+          privileged_n = calculate_privileged_insns ();
+          can_issue_more = choose_best_insn (fence, privileged_n, &index);
+          if (can_issue_more)
+            best = find_expr_for_ready (index, true);
+        }
+      /* We had some available insns, so if we can't issue them, 
+         we have a stall.  */
+      if (can_issue_more == 0)
+        {
+          best = NULL;
+          *pneed_stall = 1;
+        }
+    }
+
+  if (best != NULL)
+    {
+      can_issue_more = invoke_aftermath_hooks (fence, EXPR_INSN_RTX (best),
+                                               can_issue_more);
+      if (can_issue_more == 0)
+        *pneed_stall = 1;
+    }
+  
+  if (sched_verbose >= 2)
+    {
+      if (best != NULL)
+        {
+          sel_print ("Best expression (vliw form): ");
+          dump_expr (best);
+          sel_print ("; cycle %d\n", FENCE_CYCLE (fence));
+        }
+      else
+        sel_print ("No best expr found!\n");
+    }
+
+  return best;
+}
+\f
+
+/* Functions that implement the core of the scheduler.  */
+
+
+/* Emit an instruction from EXPR with SEQNO and VINSN after 
+   PLACE_TO_INSERT.  */
+static insn_t
+emit_insn_from_expr_after (expr_t expr, vinsn_t vinsn, int seqno, 
+                           insn_t place_to_insert)
+{
+  /* This assert fails when we have identical instructions
+     one of which dominates the other.  In this case move_op ()
+     finds the first instruction and doesn't search for second one.
+     The solution would be to compute av_set after the first found
+     insn and, if insn present in that set, continue searching.
+     For now we workaround this issue in move_op.  */
+  gcc_assert (!INSN_IN_STREAM_P (EXPR_INSN_RTX (expr)));
+
+  if (EXPR_WAS_RENAMED (expr))
+    {
+      unsigned regno = expr_dest_regno (expr);
+      
+      if (HARD_REGISTER_NUM_P (regno))
+       {
+         df_set_regs_ever_live (regno, true);
+         reg_rename_tick[regno] = ++reg_rename_this_tick;
+       }
+    }
+  
+  return sel_gen_insn_from_expr_after (expr, vinsn, seqno, 
+                                       place_to_insert);
+}
+
+/* Return TRUE if BB can hold bookkeeping code.  */
+static bool
+block_valid_for_bookkeeping_p (basic_block bb)
+{
+  insn_t bb_end = BB_END (bb);
+
+  if (!in_current_region_p (bb) || EDGE_COUNT (bb->succs) > 1)
+    return false;
+
+  if (INSN_P (bb_end))
+    {
+      if (INSN_SCHED_TIMES (bb_end) > 0)
+       return false;
+    }
+  else
+    gcc_assert (NOTE_INSN_BASIC_BLOCK_P (bb_end));
+
+  return true;
+}
+
+/* Attempt to find a block that can hold bookkeeping code for path(s) incoming
+   into E2->dest, except from E1->src (there may be a sequence of empty basic
+   blocks between E1->src and E2->dest).  Return found block, or NULL if new
+   one must be created.  */
+static basic_block
+find_block_for_bookkeeping (edge e1, edge e2)
+{
+  basic_block candidate_block = NULL;
+  edge e;
+
+  /* Loop over edges from E1 to E2, inclusive.  */
+  for (e = e1; ; e = EDGE_SUCC (e->dest, 0))
+    {
+      if (EDGE_COUNT (e->dest->preds) == 2)
+       {
+         if (candidate_block == NULL)
+           candidate_block = (EDGE_PRED (e->dest, 0) == e
+                              ? EDGE_PRED (e->dest, 1)->src
+                              : EDGE_PRED (e->dest, 0)->src);
+         else
+           /* Found additional edge leading to path from e1 to e2
+              from aside.  */
+           return NULL;
+       }
+      else if (EDGE_COUNT (e->dest->preds) > 2)
+       /* Several edges leading to path from e1 to e2 from aside.  */
+       return NULL;
+
+      if (e == e2)
+       return (block_valid_for_bookkeeping_p (candidate_block)
+               ? candidate_block
+               : NULL);
+    }
+  gcc_unreachable ();
+}
+
+/* Create new basic block for bookkeeping code for path(s) incoming into
+   E2->dest, except from E1->src.  Return created block.  */
+static basic_block
+create_block_for_bookkeeping (edge e1, edge e2)
+{
+  basic_block new_bb, bb = e2->dest;
+
+  /* Check that we don't spoil the loop structure.  */
+  if (current_loop_nest)
+    {
+      basic_block latch = current_loop_nest->latch;
+
+      /* We do not split header.  */
+      gcc_assert (e2->dest != current_loop_nest->header);
+
+      /* We do not redirect the only edge to the latch block.  */
+      gcc_assert (e1->dest != latch
+                 || !single_pred_p (latch)
+                 || e1 != single_pred_edge (latch));
+    }
+
+  /* Split BB to insert BOOK_INSN there.  */
+  new_bb = sched_split_block (bb, NULL);
+
+  /* Move note_list from the upper bb.  */
+  gcc_assert (BB_NOTE_LIST (new_bb) == NULL_RTX);
+  BB_NOTE_LIST (new_bb) = BB_NOTE_LIST (bb);
+  BB_NOTE_LIST (bb) = NULL_RTX;
+
+  gcc_assert (e2->dest == bb);
+
+  /* Skip block for bookkeeping copy when leaving E1->src.  */
+  if (e1->flags & EDGE_FALLTHRU)
+    sel_redirect_edge_and_branch_force (e1, new_bb);
+  else
+    sel_redirect_edge_and_branch (e1, new_bb);
+
+  gcc_assert (e1->dest == new_bb);
+  gcc_assert (sel_bb_empty_p (bb));
+
+  return bb;
+}
+
+/* Return insn after which we must insert bookkeeping code for path(s) incoming
+   into E2->dest, except from E1->src.  */
+static insn_t
+find_place_for_bookkeeping (edge e1, edge e2)
+{
+  insn_t place_to_insert;
+  /* Find a basic block that can hold bookkeeping.  If it can be found, do not
+     create new basic block, but insert bookkeeping there.  */
+  basic_block book_block = find_block_for_bookkeeping (e1, e2);
+
+  if (!book_block)
+    book_block = create_block_for_bookkeeping (e1, e2);
+
+  place_to_insert = BB_END (book_block);
+
+  /* If basic block ends with a jump, insert bookkeeping code right before it.  */
+  if (INSN_P (place_to_insert) && control_flow_insn_p (place_to_insert))
+    place_to_insert = PREV_INSN (place_to_insert);
+
+  return place_to_insert;
+}
+
+/* Find a proper seqno for bookkeeing insn inserted at PLACE_TO_INSERT
+   for JOIN_POINT.   */
+static int
+find_seqno_for_bookkeeping (insn_t place_to_insert, insn_t join_point)
+{
+  int seqno;
+  rtx next;
+
+  /* Check if we are about to insert bookkeeping copy before a jump, and use
+     jump's seqno for the copy; otherwise, use JOIN_POINT's seqno.  */
+  next = NEXT_INSN (place_to_insert);
+  if (INSN_P (next) 
+      && JUMP_P (next)
+      && BLOCK_FOR_INSN (next) == BLOCK_FOR_INSN (place_to_insert))
+    seqno = INSN_SEQNO (next);
+  else if (INSN_SEQNO (join_point) > 0)
+    seqno = INSN_SEQNO (join_point);
+  else
+    seqno = get_seqno_by_preds (place_to_insert);
+  
+  gcc_assert (seqno > 0);
+  return seqno;
+}
+
+/* Insert bookkeeping copy of C_EXPS's insn after PLACE_TO_INSERT, assigning
+   NEW_SEQNO to it.  Return created insn.  */
+static insn_t
+emit_bookkeeping_insn (insn_t place_to_insert, expr_t c_expr, int new_seqno)
+{
+  rtx new_insn_rtx = create_copy_of_insn_rtx (EXPR_INSN_RTX (c_expr));
+
+  vinsn_t new_vinsn
+    = create_vinsn_from_insn_rtx (new_insn_rtx,
+                                 VINSN_UNIQUE_P (EXPR_VINSN (c_expr)));
+
+  insn_t new_insn = emit_insn_from_expr_after (c_expr, new_vinsn, new_seqno,
+                                              place_to_insert);
+
+  INSN_SCHED_TIMES (new_insn) = 0;
+  bitmap_set_bit (current_copies, INSN_UID (new_insn));
+
+  return new_insn;
+}
+
+/* Generate a bookkeeping copy of C_EXPR's insn for path(s) incoming into to
+   E2->dest, except from E1->src (there may be a sequence of empty blocks
+   between E1->src and E2->dest).  Return block containing the copy.
+   All scheduler data is initialized for the newly created insn.  */
+static basic_block
+generate_bookkeeping_insn (expr_t c_expr, edge e1, edge e2)
+{
+  insn_t join_point, place_to_insert, new_insn;
+  int new_seqno;
+  bool need_to_exchange_data_sets;
+
+  if (sched_verbose >= 4)
+    sel_print ("Generating bookkeeping insn (%d->%d)\n", e1->src->index,
+              e2->dest->index);
+
+  join_point = sel_bb_head (e2->dest);
+  place_to_insert = find_place_for_bookkeeping (e1, e2);
+  new_seqno = find_seqno_for_bookkeeping (place_to_insert, join_point);
+  need_to_exchange_data_sets
+    = sel_bb_empty_p (BLOCK_FOR_INSN (place_to_insert));
+
+  new_insn = emit_bookkeeping_insn (place_to_insert, c_expr, new_seqno);
+
+  /* When inserting bookkeeping insn in new block, av sets should be
+     following: old basic block (that now holds bookkeeping) data sets are
+     the same as was before generation of bookkeeping, and new basic block
+     (that now hold all other insns of old basic block) data sets are
+     invalid.  So exchange data sets for these basic blocks as sel_split_block
+     mistakenly exchanges them in this case.  Cannot do it earlier because
+     when single instruction is added to new basic block it should hold NULL
+     lv_set.  */
+  if (need_to_exchange_data_sets)
+    exchange_data_sets (BLOCK_FOR_INSN (new_insn),
+                       BLOCK_FOR_INSN (join_point));
+
+  stat_bookkeeping_copies++;
+  return BLOCK_FOR_INSN (new_insn);
+}
+
+/* Remove from AV_PTR all insns that may need bookkeeping when scheduling 
+   on FENCE, but we are unable to copy them.  */
+static void
+remove_insns_that_need_bookkeeping (fence_t fence, av_set_t *av_ptr)
+{
+  expr_t expr;
+  av_set_iterator i;
+
+  /*  An expression does not need bookkeeping if it is available on all paths 
+      from current block to original block and current block dominates 
+      original block.  We check availability on all paths by examining 
+      EXPR_SPEC; this is not equivalent, because it may be positive even 
+      if expr is available on all paths (but if expr is not available on 
+      any path, EXPR_SPEC will be positive).  */
+
+  FOR_EACH_EXPR_1 (expr, i, av_ptr)
+    {
+      if (!control_flow_insn_p (EXPR_INSN_RTX (expr))
+         && (!bookkeeping_p || VINSN_UNIQUE_P (EXPR_VINSN (expr)))
+         && (EXPR_SPEC (expr)
+             || !EXPR_ORIG_BB_INDEX (expr)
+             || !dominated_by_p (CDI_DOMINATORS,
+                                 BASIC_BLOCK (EXPR_ORIG_BB_INDEX (expr)),
+                                 BLOCK_FOR_INSN (FENCE_INSN (fence)))))
+       {
+          if (sched_verbose >= 4)
+            sel_print ("Expr %d removed because it would need bookkeeping, which "
+                       "cannot be created\n", INSN_UID (EXPR_INSN_RTX (expr)));
+         av_set_iter_remove (&i);
+       }
+    }
+}
+
+/* Moving conditional jump through some instructions.
+
+   Consider example:
+
+       ...                     <- current scheduling point
+       NOTE BASIC BLOCK:       <- bb header
+       (p8)  add r14=r14+0x9;;
+       (p8)  mov [r14]=r23
+       (!p8) jump L1;;
+       NOTE BASIC BLOCK:
+       ...
+
+   We can schedule jump one cycle earlier, than mov, because they cannot be 
+   executed together as their predicates are mutually exclusive.
+
+   This is done in this way: first, new fallthrough basic block is created 
+   after jump (it is always can be done, because there already should be a 
+   fallthrough block, where control flow goes in case of predicate being true -
+   in our example; otherwise there should be a dependence between those 
+   instructions and jump and we cannot schedule jump right now); 
+   next, all instructions between jump and current scheduling point are moved 
+   to this new block.  And the result is this:
+
+      NOTE BASIC BLOCK:
+      (!p8) jump L1           <- current scheduling point
+      NOTE BASIC BLOCK:       <- bb header
+      (p8)  add r14=r14+0x9;;
+      (p8)  mov [r14]=r23
+      NOTE BASIC BLOCK:
+      ...
+*/
+static void
+move_cond_jump (rtx insn, bnd_t bnd)
+{
+  edge ft_edge;
+  basic_block block_from, block_next, block_new;
+  rtx next, prev, link;
+
+  /* BLOCK_FROM holds basic block of the jump.  */
+  block_from = BLOCK_FOR_INSN (insn);
+
+  /* Moving of jump should not cross any other jumps or
+  beginnings of new basic blocks.  */
+  gcc_assert (block_from == BLOCK_FOR_INSN (BND_TO (bnd)));
+
+  /* Jump is moved to the boundary.  */
+  prev = BND_TO (bnd);
+  next = PREV_INSN (insn);
+  BND_TO (bnd) = insn;
+
+  ft_edge = find_fallthru_edge (block_from);
+  block_next = ft_edge->dest;
+  /* There must be a fallthrough block (or where should go
+  control flow in case of false jump predicate otherwise?).  */
+  gcc_assert (block_next);
+
+  /* Create new empty basic block after source block.  */
+  block_new = sel_split_edge (ft_edge);
+  gcc_assert (block_new->next_bb == block_next
+              && block_from->next_bb == block_new);
+
+  gcc_assert (BB_END (block_from) == insn);
+
+  /* Move all instructions except INSN from BLOCK_FROM to
+     BLOCK_NEW.  */
+  for (link = prev; link != insn; link = NEXT_INSN (link))
+    {
+      EXPR_ORIG_BB_INDEX (INSN_EXPR (link)) = block_new->index;
+      df_insn_change_bb (link, block_new);
+    }
+
+  /* Set correct basic block and instructions properties.  */
+  BB_END (block_new) = PREV_INSN (insn);
+
+  NEXT_INSN (PREV_INSN (prev)) = insn;
+  PREV_INSN (insn) = PREV_INSN (prev);
+
+  /* Assert there is no jump to BLOCK_NEW, only fallthrough edge.  */
+  gcc_assert (NOTE_INSN_BASIC_BLOCK_P (BB_HEAD (block_new)));
+  PREV_INSN (prev) = BB_HEAD (block_new);
+  NEXT_INSN (next) = NEXT_INSN (BB_HEAD (block_new));
+  NEXT_INSN (BB_HEAD (block_new)) = prev;
+  PREV_INSN (NEXT_INSN (next)) = next;
+
+  gcc_assert (!sel_bb_empty_p (block_from)
+              && !sel_bb_empty_p (block_new));
+
+  /* Update data sets for BLOCK_NEW to represent that INSN and
+     instructions from the other branch of INSN is no longer
+     available at BLOCK_NEW.  */
+  BB_AV_LEVEL (block_new) = global_level;
+  gcc_assert (BB_LV_SET (block_new) == NULL);
+  BB_LV_SET (block_new) = get_clear_regset_from_pool ();
+  update_data_sets (sel_bb_head (block_new));
+
+  /* INSN is a new basic block header - so prepare its data
+     structures and update availability and liveness sets.  */
+  update_data_sets (insn);
+
+  if (sched_verbose >= 4)
+    sel_print ("Moving jump %d\n", INSN_UID (insn));
+}
+
+/* Remove nops generated during move_op for preventing removal of empty
+   basic blocks.  */
+static void
+remove_temp_moveop_nops (void)
+{
+  int i;
+  insn_t insn;
+  
+  for (i = 0; VEC_iterate (insn_t, vec_temp_moveop_nops, i, insn); i++)
+    {
+      gcc_assert (INSN_NOP_P (insn));
+      return_nop_to_pool (insn);
+    }
+
+  /* Empty the vector.  */
+  if (VEC_length (insn_t, vec_temp_moveop_nops) > 0)
+    VEC_block_remove (insn_t, vec_temp_moveop_nops, 0, 
+                     VEC_length (insn_t, vec_temp_moveop_nops));
+}
+
+/* Records the maximal UID before moving up an instruction.  Used for
+   distinguishing between bookkeeping copies and original insns.  */
+static int max_uid_before_move_op = 0;
+
+/* Remove from AV_VLIW_P all instructions but next when debug counter
+   tells us so.  Next instruction is fetched from BNDS.  */
+static void
+remove_insns_for_debug (blist_t bnds, av_set_t *av_vliw_p)
+{
+  if (! dbg_cnt (sel_sched_insn_cnt))
+    /* Leave only the next insn in av_vliw.  */
+    {
+      av_set_iterator av_it;
+      expr_t expr;
+      bnd_t bnd = BLIST_BND (bnds);
+      insn_t next = BND_TO (bnd);
+
+      gcc_assert (BLIST_NEXT (bnds) == NULL);
+
+      FOR_EACH_EXPR_1 (expr, av_it, av_vliw_p)
+        if (EXPR_INSN_RTX (expr) != next)
+          av_set_iter_remove (&av_it);
+    }
+}
+
+/* Compute available instructions on BNDS.  FENCE is the current fence.  Write 
+   the computed set to *AV_VLIW_P.  */
+static void
+compute_av_set_on_boundaries (fence_t fence, blist_t bnds, av_set_t *av_vliw_p)
+{
+  if (sched_verbose >= 2)
+    {
+      sel_print ("Boundaries: ");
+      dump_blist (bnds);
+      sel_print ("\n");
+    }
+
+  for (; bnds; bnds = BLIST_NEXT (bnds))
+    {
+      bnd_t bnd = BLIST_BND (bnds);
+      av_set_t av1_copy;
+      insn_t bnd_to = BND_TO (bnd);
+
+      /* Rewind BND->TO to the basic block header in case some bookkeeping
+         instructions were inserted before BND->TO and it needs to be
+         adjusted.  */
+      if (sel_bb_head_p (bnd_to))
+        gcc_assert (INSN_SCHED_TIMES (bnd_to) == 0);
+      else
+        while (INSN_SCHED_TIMES (PREV_INSN (bnd_to)) == 0)
+          {
+            bnd_to = PREV_INSN (bnd_to);
+            if (sel_bb_head_p (bnd_to))
+              break;
+          }
+
+      if (BND_TO (bnd) != bnd_to)
+       {
+         gcc_assert (FENCE_INSN (fence) == BND_TO (bnd));
+         FENCE_INSN (fence) = bnd_to;
+         BND_TO (bnd) = bnd_to;
+       }
+
+      av_set_clear (&BND_AV (bnd));
+      BND_AV (bnd) = compute_av_set (BND_TO (bnd), NULL, 0, true);
+
+      av_set_clear (&BND_AV1 (bnd));
+      BND_AV1 (bnd) = av_set_copy (BND_AV (bnd));
+
+      moveup_set_inside_insn_group (&BND_AV1 (bnd), NULL);
+      
+      av1_copy = av_set_copy (BND_AV1 (bnd));
+      av_set_union_and_clear (av_vliw_p, &av1_copy, NULL);
+    }
+
+  if (sched_verbose >= 2)
+    {
+      sel_print ("Available exprs (vliw form): ");
+      dump_av_set (*av_vliw_p);
+      sel_print ("\n");
+    }
+}
+
+/* Calculate the sequential av set on BND corresponding to the EXPR_VLIW 
+   expression.  When FOR_MOVEOP is true, also replace the register of 
+   expressions found with the register from EXPR_VLIW.  */
+static av_set_t
+find_sequential_best_exprs (bnd_t bnd, expr_t expr_vliw, bool for_moveop)
+{
+  av_set_t expr_seq = NULL;
+  expr_t expr;
+  av_set_iterator i;
+  
+  FOR_EACH_EXPR (expr, i, BND_AV (bnd))
+    {
+      if (equal_after_moveup_path_p (expr, NULL, expr_vliw))
+        {
+          if (for_moveop)
+            {
+              /* The sequential expression has the right form to pass 
+                 to move_op except when renaming happened.  Put the 
+                 correct register in EXPR then.  */
+              if (EXPR_SEPARABLE_P (expr) && REG_P (EXPR_LHS (expr)))
+               {
+                  if (expr_dest_regno (expr) != expr_dest_regno (expr_vliw))
+                   {
+                     replace_dest_with_reg_in_expr (expr, EXPR_LHS (expr_vliw));
+                     stat_renamed_scheduled++;
+                   }
+                 /* Also put the correct TARGET_AVAILABLE bit on the expr.  
+                     This is needed when renaming came up with original 
+                     register.  */
+                  else if (EXPR_TARGET_AVAILABLE (expr) 
+                           != EXPR_TARGET_AVAILABLE (expr_vliw))
+                   {
+                     gcc_assert (EXPR_TARGET_AVAILABLE (expr_vliw) == 1);
+                     EXPR_TARGET_AVAILABLE (expr) = 1;
+                   }
+               }
+              if (EXPR_WAS_SUBSTITUTED (expr))
+                stat_substitutions_total++;
+            }
+
+          av_set_add (&expr_seq, expr);
+          
+          /* With substitution inside insn group, it is possible 
+             that more than one expression in expr_seq will correspond 
+             to expr_vliw.  In this case, choose one as the attempt to 
+             move both leads to miscompiles.  */
+          break;
+        }
+    }
+
+  if (for_moveop && sched_verbose >= 2)
+    {
+      sel_print ("Best expression(s) (sequential form): ");
+      dump_av_set (expr_seq);
+      sel_print ("\n");
+    }
+  
+  return expr_seq;
+}
+
+
+/* Move nop to previous block.  */
+static void ATTRIBUTE_UNUSED
+move_nop_to_previous_block (insn_t nop, basic_block prev_bb)
+{
+  insn_t prev_insn, next_insn, note;
+
+  gcc_assert (sel_bb_head_p (nop) 
+              && prev_bb == BLOCK_FOR_INSN (nop)->prev_bb);
+  note = bb_note (BLOCK_FOR_INSN (nop));
+  prev_insn = sel_bb_end (prev_bb);
+  next_insn = NEXT_INSN (nop);
+  gcc_assert (prev_insn != NULL_RTX
+              && PREV_INSN (note) == prev_insn);
+
+  NEXT_INSN (prev_insn) = nop;
+  PREV_INSN (nop) = prev_insn;
+
+  PREV_INSN (note) = nop;
+  NEXT_INSN (note) = next_insn;
+
+  NEXT_INSN (nop) = note;
+  PREV_INSN (next_insn) = note;
+
+  BB_END (prev_bb) = nop;
+  BLOCK_FOR_INSN (nop) = prev_bb;
+}
+
+/* Prepare a place to insert the chosen expression on BND.  */
+static insn_t
+prepare_place_to_insert (bnd_t bnd)
+{
+  insn_t place_to_insert;
+
+  /* Init place_to_insert before calling move_op, as the later
+     can possibly remove BND_TO (bnd).  */
+  if (/* If this is not the first insn scheduled.  */
+      BND_PTR (bnd))
+    {
+      /* Add it after last scheduled.  */
+      place_to_insert = ILIST_INSN (BND_PTR (bnd));
+    }
+  else
+    {
+      /* Add it before BND_TO.  The difference is in the
+         basic block, where INSN will be added.  */
+      place_to_insert = get_nop_from_pool (BND_TO (bnd));
+      gcc_assert (BLOCK_FOR_INSN (place_to_insert)
+                  == BLOCK_FOR_INSN (BND_TO (bnd)));
+    }
+
+  return place_to_insert;
+}
+
+/* Find original instructions for EXPR_SEQ and move it to BND boundary.  
+   Return the expression to emit in C_EXPR.  */
+static void
+move_exprs_to_boundary (bnd_t bnd, expr_t expr_vliw, 
+                        av_set_t expr_seq, expr_t c_expr)
+{
+  bool b;
+  unsigned book_uid;
+  bitmap_iterator bi;
+  int n_bookkeeping_copies_before_moveop;
+
+  /* Make a move.  This call will remove the original operation,
+     insert all necessary bookkeeping instructions and update the
+     data sets.  After that all we have to do is add the operation
+     at before BND_TO (BND).  */
+  n_bookkeeping_copies_before_moveop = stat_bookkeeping_copies;
+  max_uid_before_move_op = get_max_uid ();
+  bitmap_clear (current_copies);
+  bitmap_clear (current_originators);
+
+  b = move_op (BND_TO (bnd), expr_seq, expr_vliw, 
+               get_dest_from_orig_ops (expr_seq), c_expr);
+
+  /* We should be able to find the expression we've chosen for 
+     scheduling.  */
+  gcc_assert (b == 1);
+  
+  if (stat_bookkeeping_copies > n_bookkeeping_copies_before_moveop)
+    stat_insns_needed_bookkeeping++;
+  
+  EXECUTE_IF_SET_IN_BITMAP (current_copies, 0, book_uid, bi)
+    {
+      /* We allocate these bitmaps lazily.  */
+      if (! INSN_ORIGINATORS_BY_UID (book_uid))
+        INSN_ORIGINATORS_BY_UID (book_uid) = BITMAP_ALLOC (NULL);
+      
+      bitmap_copy (INSN_ORIGINATORS_BY_UID (book_uid), 
+                   current_originators);
+    }
+}
+
+
+/* Debug a DFA state as an array of bytes.  */
+static void
+debug_state (state_t state)
+{
+  unsigned char *p;
+  unsigned int i, size = dfa_state_size;
+
+  sel_print ("state (%u):", size);
+  for (i = 0, p = (unsigned char *) state; i < size; i++)
+    sel_print (" %d", p[i]);
+  sel_print ("\n");
+}
+
+/* Advance state on FENCE with INSN.  Return true if INSN is 
+   an ASM, and we should advance state once more.  */
+static bool
+advance_state_on_fence (fence_t fence, insn_t insn)
+{
+  bool asm_p;
+
+  if (recog_memoized (insn) >= 0)
+    {
+      int res;
+      state_t temp_state = alloca (dfa_state_size);
+              
+      gcc_assert (!INSN_ASM_P (insn));
+      asm_p = false;
+
+      memcpy (temp_state, FENCE_STATE (fence), dfa_state_size);
+      res = state_transition (FENCE_STATE (fence), insn);
+      gcc_assert (res < 0);
+
+      if (memcmp (temp_state, FENCE_STATE (fence), dfa_state_size))
+        {
+          FENCE_ISSUED_INSNS (fence)++;
+
+          /* We should never issue more than issue_rate insns.  */
+          if (FENCE_ISSUED_INSNS (fence) > issue_rate)
+            gcc_unreachable ();
+        }
+    } 
+  else
+    {
+      /* This could be an ASM insn which we'd like to schedule 
+         on the next cycle.  */
+      asm_p = INSN_ASM_P (insn);
+      if (!FENCE_STARTS_CYCLE_P (fence) && asm_p)
+        advance_one_cycle (fence);
+    }
+
+  if (sched_verbose >= 2)
+    debug_state (FENCE_STATE (fence));
+  FENCE_STARTS_CYCLE_P (fence) = 0;
+  return asm_p;
+}
+
+/* Update FENCE on which INSN was scheduled and this INSN, too.  NEED_STALL
+   is nonzero if we need to stall after issuing INSN.  */
+static void
+update_fence_and_insn (fence_t fence, insn_t insn, int need_stall)
+{
+  bool asm_p;
+  
+  /* First, reflect that something is scheduled on this fence.  */
+  asm_p = advance_state_on_fence (fence, insn);
+  FENCE_LAST_SCHEDULED_INSN (fence) = insn;
+  VEC_safe_push (rtx, gc, FENCE_EXECUTING_INSNS (fence), insn);
+  if (SCHED_GROUP_P (insn))
+    {
+      FENCE_SCHED_NEXT (fence) = INSN_SCHED_NEXT (insn);
+      SCHED_GROUP_P (insn) = 0;
+    }
+  else
+    FENCE_SCHED_NEXT (fence) = NULL_RTX;
+  if (INSN_UID (insn) < FENCE_READY_TICKS_SIZE (fence))
+    FENCE_READY_TICKS (fence) [INSN_UID (insn)] = 0;
+
+  /* Set instruction scheduling info.  This will be used in bundling,
+     pipelining, tick computations etc.  */
+  ++INSN_SCHED_TIMES (insn);
+  EXPR_TARGET_AVAILABLE (INSN_EXPR (insn)) = true;
+  EXPR_ORIG_SCHED_CYCLE (INSN_EXPR (insn)) = FENCE_CYCLE (fence);
+  INSN_AFTER_STALL_P (insn) = FENCE_AFTER_STALL_P (fence);
+  INSN_SCHED_CYCLE (insn) = FENCE_CYCLE (fence);
+
+  /* This does not account for adjust_cost hooks, just add the biggest
+     constant the hook may add to the latency.  TODO: make this 
+     a target dependent constant.  */
+  INSN_READY_CYCLE (insn) 
+    = INSN_SCHED_CYCLE (insn) + (INSN_CODE (insn) < 0 
+                                 ? 1
+                                 : maximal_insn_latency (insn) + 1);
+
+  /* Change these fields last, as they're used above.  */
+  FENCE_AFTER_STALL_P (fence) = 0;
+  if (asm_p || need_stall)
+    advance_one_cycle (fence);
+  
+  /* Indicate that we've scheduled something on this fence.  */
+  FENCE_SCHEDULED_P (fence) = true;
+  scheduled_something_on_previous_fence = true;
+
+  /* Print debug information when insn's fields are updated.  */
+  if (sched_verbose >= 2)
+    {
+      sel_print ("Scheduling insn: ");
+      dump_insn_1 (insn, 1);
+      sel_print ("\n");
+    }
+}
+
+/* Update boundary BND with INSN, remove the old boundary from
+   BNDSP, add new boundaries to BNDS_TAIL_P and return it.  */
+static blist_t *
+update_boundaries (bnd_t bnd, insn_t insn, blist_t *bndsp, 
+                   blist_t *bnds_tailp)
+{
+  succ_iterator si;
+  insn_t succ;
+
+  advance_deps_context (BND_DC (bnd), insn);
+  FOR_EACH_SUCC_1 (succ, si, insn, 
+                   SUCCS_NORMAL | SUCCS_SKIP_TO_LOOP_EXITS)
+    {
+      ilist_t ptr = ilist_copy (BND_PTR (bnd));
+      
+      ilist_add (&ptr, insn);
+      blist_add (bnds_tailp, succ, ptr, BND_DC (bnd));
+      bnds_tailp = &BLIST_NEXT (*bnds_tailp);
+    }
+  
+  blist_remove (bndsp);
+  return bnds_tailp;
+}
+
+/* Schedule EXPR_VLIW on BND.  Return the insn emitted.  */
+static insn_t
+schedule_expr_on_boundary (bnd_t bnd, expr_t expr_vliw, int seqno)
+{
+  av_set_t expr_seq;
+  expr_t c_expr = XALLOCA (expr_def);
+  insn_t place_to_insert;
+  insn_t insn;
+  bool cant_move;
+
+  expr_seq = find_sequential_best_exprs (bnd, expr_vliw, true);
+
+  /* In case of scheduling a jump skipping some other instructions,
+     prepare CFG.  After this, jump is at the boundary and can be 
+     scheduled as usual insn by MOVE_OP.  */
+  if (vinsn_cond_branch_p (EXPR_VINSN (expr_vliw)))
+    {
+      insn = EXPR_INSN_RTX (expr_vliw);
+              
+      /* Speculative jumps are not handled.  */
+      if (insn != BND_TO (bnd) 
+          && !sel_insn_is_speculation_check (insn))
+        move_cond_jump (insn, bnd);
+    }
+
+  /* Calculate cant_move now as EXPR_WAS_RENAMED can change after move_op 
+     meaning that there was *any* renaming somewhere.  */
+  cant_move = EXPR_WAS_CHANGED (expr_vliw) || EXPR_WAS_RENAMED (expr_vliw);
+
+  /* Find a place for C_EXPR to schedule.  */
+  place_to_insert = prepare_place_to_insert (bnd);
+  move_exprs_to_boundary (bnd, expr_vliw, expr_seq, c_expr);
+  clear_expr (c_expr);
+            
+  /* Add the instruction.  The corner case to care about is when 
+     the expr_seq set has more than one expr, and we chose the one that 
+     is not equal to expr_vliw.  Then expr_vliw may be insn in stream, and 
+     we can't use it.  Generate the new vinsn.  */
+  if (INSN_IN_STREAM_P (EXPR_INSN_RTX (expr_vliw)))
+    {
+      vinsn_t vinsn_new;
+      
+      vinsn_new = vinsn_copy (EXPR_VINSN (expr_vliw), false);
+      change_vinsn_in_expr (expr_vliw, vinsn_new);
+      cant_move = 1;
+    }
+  if (cant_move)
+    insn = emit_insn_from_expr_after (expr_vliw, NULL, seqno, 
+                                      place_to_insert);
+  else
+    insn = sel_move_insn (expr_vliw, seqno, place_to_insert);
+
+  /* Return the nops generated for preserving of data sets back
+     into pool.  */
+  if (INSN_NOP_P (place_to_insert))
+    return_nop_to_pool (place_to_insert);
+  remove_temp_moveop_nops ();
+
+  av_set_clear (&expr_seq);
+  /* Save the expression scheduled so to reset target availability if we'll 
+     meet it later on the same fence.  */
+  if (EXPR_WAS_RENAMED (expr_vliw))
+    vinsn_vec_add (&vec_target_unavailable_vinsns, INSN_EXPR (insn));
+
+  /* Check that the recent movement didn't destroyed loop
+     structure.  */
+  gcc_assert (!pipelining_p
+              || current_loop_nest == NULL
+              || loop_latch_edge (current_loop_nest));
+  return insn;
+}
+
+/* Stall for N cycles on FENCE.  */
+static void
+stall_for_cycles (fence_t fence, int n)
+{
+  int could_more;
+              
+  could_more = n > 1 || FENCE_ISSUED_INSNS (fence) < issue_rate;
+  while (n--)
+    advance_one_cycle (fence);
+  if (could_more)
+    FENCE_AFTER_STALL_P (fence) = 1;
+}
+
+/* Gather a parallel group of insns at FENCE and assign their seqno 
+   to SEQNO.  All scheduled insns are gathered in SCHEDULED_INSNS_TAILPP 
+   list for later recalculation of seqnos.  */
+static void
+fill_insns (fence_t fence, int seqno, ilist_t **scheduled_insns_tailpp)
+{
+  blist_t bnds = NULL, *bnds_tailp;
+  av_set_t av_vliw = NULL;
+  insn_t insn = FENCE_INSN (fence);
+
+  if (sched_verbose >= 2)
+    sel_print ("Starting fill_insns for insn %d, cycle %d\n", 
+               INSN_UID (insn), FENCE_CYCLE (fence));
+
+  blist_add (&bnds, insn, NULL, FENCE_DC (fence));
+  bnds_tailp = &BLIST_NEXT (bnds);
+  set_target_context (FENCE_TC (fence));
+  target_bb = INSN_BB (insn);
+
+  /* Do while we can add any operation to the current group.  */
+  do
+    {
+      blist_t *bnds_tailp1, *bndsp;
+      expr_t expr_vliw;
+      int need_stall;
+      int was_stall = 0, scheduled_insns = 0, stall_iterations = 0;
+      int max_insns = pipelining_p ? issue_rate : 2 * issue_rate;
+      int max_stall = pipelining_p ? 1 : 3;
+      
+      compute_av_set_on_boundaries (fence, bnds, &av_vliw);
+      remove_insns_that_need_bookkeeping (fence, &av_vliw);
+      remove_insns_for_debug (bnds, &av_vliw);
+
+      /* Return early if we have nothing to schedule.  */
+      if (av_vliw == NULL)
+        break;
+
+      /* Choose the best expression and, if needed, destination register
+        for it.  */
+      do
+        {
+          expr_vliw = find_best_expr (&av_vliw, bnds, fence, &need_stall);
+          if (!expr_vliw && need_stall)
+            {
+              /* All expressions required a stall.  Do not recompute av sets
+                 as we'll get the same answer (modulo the insns between
+                 the fence and its boundary, which will not be available for
+                 pipelining).  */
+              gcc_assert (! expr_vliw && stall_iterations < 2);
+              was_stall++;
+             /* If we are going to stall for too long, break to recompute av
+                sets and bring more insns for pipelining.  */
+             if (need_stall <= 3)
+               stall_for_cycles (fence, need_stall);
+             else
+               {
+                 stall_for_cycles (fence, 1);
+                 break;
+               }
+            }
+        }
+      while (! expr_vliw && need_stall);
+      
+      /* Now either we've selected expr_vliw or we have nothing to schedule.  */
+      if (!expr_vliw)
+        {
+         av_set_clear (&av_vliw);
+          break;
+        }
+
+      bndsp = &bnds;
+      bnds_tailp1 = bnds_tailp;
+
+      do
+       /* This code will be executed only once until we'd have several 
+           boundaries per fence.  */
+        {
+         bnd_t bnd = BLIST_BND (*bndsp);
+
+         if (!av_set_is_in_p (BND_AV1 (bnd), EXPR_VINSN (expr_vliw)))
+           {
+             bndsp = &BLIST_NEXT (*bndsp);
+             continue;
+           }
+          
+          insn = schedule_expr_on_boundary (bnd, expr_vliw, seqno);
+          update_fence_and_insn (fence, insn, need_stall);
+          bnds_tailp = update_boundaries (bnd, insn, bndsp, bnds_tailp);
+
+         /* Add insn to the list of scheduled on this cycle instructions.  */
+         ilist_add (*scheduled_insns_tailpp, insn);
+         *scheduled_insns_tailpp = &ILIST_NEXT (**scheduled_insns_tailpp);
+        }
+      while (*bndsp != *bnds_tailp1);
+
+      av_set_clear (&av_vliw);
+      scheduled_insns++;
+
+      /* We currently support information about candidate blocks only for
+        one 'target_bb' block.  Hence we can't schedule after jump insn,
+        as this will bring two boundaries and, hence, necessity to handle
+        information for two or more blocks concurrently.  */
+      if (sel_bb_end_p (insn)
+          || (was_stall 
+              && (was_stall >= max_stall 
+                  || scheduled_insns >= max_insns)))
+        break;
+    }
+  while (bnds);
+
+  gcc_assert (!FENCE_BNDS (fence));
+  
+  /* Update boundaries of the FENCE.  */
+  while (bnds)
+    {
+      ilist_t ptr = BND_PTR (BLIST_BND (bnds));
+
+      if (ptr)
+       {
+         insn = ILIST_INSN (ptr);
+
+         if (!ilist_is_in_p (FENCE_BNDS (fence), insn))
+           ilist_add (&FENCE_BNDS (fence), insn);
+       }
+      
+      blist_remove (&bnds);
+    }
+
+  /* Update target context on the fence.  */
+  reset_target_context (FENCE_TC (fence), false);
+}
+
+/* All exprs in ORIG_OPS must have the same destination register or memory.
+   Return that destination.  */
+static rtx
+get_dest_from_orig_ops (av_set_t orig_ops)
+{
+  rtx dest = NULL_RTX;
+  av_set_iterator av_it;
+  expr_t expr;
+  bool first_p = true;
+
+  FOR_EACH_EXPR (expr, av_it, orig_ops)
+    {
+      rtx x = EXPR_LHS (expr);
+
+      if (first_p)
+       {
+         first_p = false;
+         dest = x;
+       }
+      else
+       gcc_assert (dest == x
+                   || (dest != NULL_RTX && x != NULL_RTX
+                       && rtx_equal_p (dest, x)));
+    }
+
+  return dest;
+}
+
+/* Update data sets for the bookkeeping block and record those expressions
+   which become no longer available after inserting this bookkeeping.  */
+static void
+update_and_record_unavailable_insns (basic_block book_block)
+{
+  av_set_iterator i;
+  av_set_t old_av_set = NULL;
+  expr_t cur_expr;
+  rtx bb_end = sel_bb_end (book_block);
+
+  /* First, get correct liveness in the bookkeeping block.  The problem is 
+     the range between the bookeeping insn and the end of block.  */
+  update_liveness_on_insn (bb_end);
+  if (control_flow_insn_p (bb_end))
+    update_liveness_on_insn (PREV_INSN (bb_end));
+
+  /* If there's valid av_set on BOOK_BLOCK, then there might exist another
+     fence above, where we may choose to schedule an insn which is
+     actually blocked from moving up with the bookkeeping we create here.  */
+  if (AV_SET_VALID_P (sel_bb_head (book_block)))
+    {
+      old_av_set = av_set_copy (BB_AV_SET (book_block));
+      update_data_sets (sel_bb_head (book_block));
+    
+      /* Traverse all the expressions in the old av_set and check whether
+        CUR_EXPR is in new AV_SET.  */
+      FOR_EACH_EXPR (cur_expr, i, old_av_set)
+        {
+          expr_t new_expr = av_set_lookup (BB_AV_SET (book_block), 
+                                          EXPR_VINSN (cur_expr));
+
+          if (! new_expr 
+              /* In this case, we can just turn off the E_T_A bit, but we can't 
+                 represent this information with the current vector.  */
+              || EXPR_TARGET_AVAILABLE (new_expr) 
+                != EXPR_TARGET_AVAILABLE (cur_expr))
+           /* Unfortunately, the below code could be also fired up on
+              separable insns.
+              FIXME: add an example of how this could happen.  */
+            vinsn_vec_add (&vec_bookkeeping_blocked_vinsns, cur_expr);
+        }
+
+      av_set_clear (&old_av_set);
+    }
+}
+
+/* The main effect of this function is that sparams->c_expr is merged 
+   with (or copied to) lparams->c_expr_merged.  If there's only one successor,
+   we avoid merging anything by copying sparams->c_expr to lparams->c_expr_merged.
+   lparams->c_expr_merged is copied back to sparams->c_expr after all 
+   successors has been traversed.  lparams->c_expr_local is an expr allocated 
+   on stack in the caller function, and is used if there is more than one 
+   successor. 
+
+   SUCC is one of the SUCCS_NORMAL successors of INSN,
+   MOVEOP_DRV_CALL_RES is the result of call code_motion_path_driver on succ,
+   LPARAMS and STATIC_PARAMS contain the parameters described above.  */
+static void
+move_op_merge_succs (insn_t insn ATTRIBUTE_UNUSED, 
+                     insn_t succ ATTRIBUTE_UNUSED, 
+                    int moveop_drv_call_res, 
+                    cmpd_local_params_p lparams, void *static_params)
+{
+  moveop_static_params_p sparams = (moveop_static_params_p) static_params;
+
+  /* Nothing to do, if original expr wasn't found below.  */
+  if (moveop_drv_call_res != 1)
+    return;
+
+  /* If this is a first successor.  */
+  if (!lparams->c_expr_merged)
+    {
+      lparams->c_expr_merged = sparams->c_expr;
+      sparams->c_expr = lparams->c_expr_local;
+    }
+  else
+    {
+      /* We must merge all found expressions to get reasonable
+        EXPR_SPEC_DONE_DS for the resulting insn.  If we don't
+        do so then we can first find the expr with epsilon
+        speculation success probability and only then with the
+        good probability.  As a result the insn will get epsilon
+        probability and will never be scheduled because of
+        weakness_cutoff in find_best_expr.
+
+        We call merge_expr_data here instead of merge_expr 
+        because due to speculation C_EXPR and X may have the
+        same insns with different speculation types.  And as of
+        now such insns are considered non-equal.  
+
+        However, EXPR_SCHED_TIMES is different -- we must get 
+        SCHED_TIMES from a real insn, not a bookkeeping copy.  
+        We force this here.  Instead, we may consider merging
+        SCHED_TIMES to the maximum instead of minimum in the 
+        below function.  */
+      int old_times = EXPR_SCHED_TIMES (lparams->c_expr_merged);
+
+      merge_expr_data (lparams->c_expr_merged, sparams->c_expr, NULL);
+      if (EXPR_SCHED_TIMES (sparams->c_expr) == 0)
+       EXPR_SCHED_TIMES (lparams->c_expr_merged) = old_times;
+
+      clear_expr (sparams->c_expr);
+    }
+}
+
+/*  Add used regs for the successor SUCC into SPARAMS->USED_REGS.
+
+   SUCC is one of the SUCCS_NORMAL successors of INSN,
+   MOVEOP_DRV_CALL_RES is the result of call code_motion_path_driver on succ or 0,
+     if SUCC is one of SUCCS_BACK or SUCCS_OUT.
+   STATIC_PARAMS contain USED_REGS set.  */
+static void
+fur_merge_succs (insn_t insn ATTRIBUTE_UNUSED, insn_t succ, 
+                int moveop_drv_call_res, 
+                cmpd_local_params_p lparams ATTRIBUTE_UNUSED, 
+                void *static_params)
+{
+  regset succ_live;
+  fur_static_params_p sparams = (fur_static_params_p) static_params;
+
+  /* Here we compute live regsets only for branches that do not lie
+     on the code motion paths.  These branches correspond to value 
+     MOVEOP_DRV_CALL_RES==0 and include SUCCS_BACK and SUCCS_OUT, though
+     for such branches code_motion_path_driver is not called.  */
+  if (moveop_drv_call_res != 0)
+    return;
+
+  /* Mark all registers that do not meet the following condition:
+     (3) not live on the other path of any conditional branch
+     that is passed by the operation, in case original
+     operations are not present on both paths of the
+     conditional branch.  */
+  succ_live = compute_live (succ);
+  IOR_REG_SET (sparams->used_regs, succ_live);
+}
+
+/* This function is called after the last successor.  Copies LP->C_EXPR_MERGED
+   into SP->CEXPR.  */
+static void
+move_op_after_merge_succs (cmpd_local_params_p lp, void *sparams)
+{  
+  moveop_static_params_p sp = (moveop_static_params_p) sparams;
+
+  sp->c_expr = lp->c_expr_merged;
+}
+
+/* Track bookkeeping copies created, insns scheduled, and blocks for
+   rescheduling when INSN is found by move_op.  */
+static void
+track_scheduled_insns_and_blocks (rtx insn)
+{
+  /* Even if this insn can be a copy that will be removed during current move_op,
+     we still need to count it as an originator.  */
+  bitmap_set_bit (current_originators, INSN_UID (insn));
+
+  if (!bitmap_bit_p (current_copies, INSN_UID (insn)))
+    {
+      /* Note that original block needs to be rescheduled, as we pulled an
+        instruction out of it.  */
+      if (INSN_SCHED_TIMES (insn) > 0)
+       bitmap_set_bit (blocks_to_reschedule, BLOCK_FOR_INSN (insn)->index);
+      else if (INSN_UID (insn) < first_emitted_uid)
+       num_insns_scheduled++;
+    }
+  else
+    bitmap_clear_bit (current_copies, INSN_UID (insn));
+
+  /* For instructions we must immediately remove insn from the
+     stream, so subsequent update_data_sets () won't include this
+     insn into av_set.
+     For expr we must make insn look like "INSN_REG (insn) := c_expr".  */
+  if (INSN_UID (insn) > max_uid_before_move_op)
+    stat_bookkeeping_copies--;
+}
+
+/* Emit a register-register copy for INSN if needed.  Return true if 
+   emitted one.  PARAMS is the move_op static parameters.  */
+static bool
+maybe_emit_renaming_copy (rtx insn, 
+                          moveop_static_params_p params)
+{
+  bool insn_emitted  = false;
+  rtx cur_reg = expr_dest_reg (params->c_expr);
+
+  gcc_assert (!cur_reg || (params->dest && REG_P (params->dest)));
+
+  /* If original operation has expr and the register chosen for
+     that expr is not original operation's dest reg, substitute
+     operation's right hand side with the register chosen.  */
+  if (cur_reg != NULL_RTX && REGNO (params->dest) != REGNO (cur_reg))
+    {
+      insn_t reg_move_insn, reg_move_insn_rtx;
+      
+      reg_move_insn_rtx = create_insn_rtx_with_rhs (INSN_VINSN (insn), 
+                                                    params->dest);
+      reg_move_insn = sel_gen_insn_from_rtx_after (reg_move_insn_rtx, 
+                                                   INSN_EXPR (insn), 
+                                                   INSN_SEQNO (insn), 
+                                                   insn);
+      EXPR_SPEC_DONE_DS (INSN_EXPR (reg_move_insn)) = 0;
+      replace_dest_with_reg_in_expr (params->c_expr, params->dest);
+      
+      insn_emitted = true;
+      params->was_renamed = true;
+    }
+  
+  return insn_emitted;
+}
+
+/* Emit a speculative check for INSN speculated as EXPR if needed.  
+   Return true if we've  emitted one.  PARAMS is the move_op static 
+   parameters.  */
+static bool
+maybe_emit_speculative_check (rtx insn, expr_t expr,
+                              moveop_static_params_p params)
+{
+  bool insn_emitted = false;
+  insn_t x;
+  ds_t check_ds;
+
+  check_ds = get_spec_check_type_for_insn (insn, expr);
+  if (check_ds != 0)
+    {
+      /* A speculation check should be inserted.  */
+      x = create_speculation_check (params->c_expr, check_ds, insn);
+      insn_emitted = true;
+    }
+  else
+    {
+      EXPR_SPEC_DONE_DS (INSN_EXPR (insn)) = 0;
+      x = insn;
+    }
+  
+  gcc_assert (EXPR_SPEC_DONE_DS (INSN_EXPR (x)) == 0
+              && EXPR_SPEC_TO_CHECK_DS (INSN_EXPR (x)) == 0);
+  return insn_emitted;
+}
+
+/* Handle transformations that leave an insn in place of original 
+   insn such as renaming/speculation.  Return true if one of such 
+   transformations actually happened, and we have emitted this insn.  */
+static bool
+handle_emitting_transformations (rtx insn, expr_t expr, 
+                                 moveop_static_params_p params)
+{
+  bool insn_emitted = false;
+
+  insn_emitted = maybe_emit_renaming_copy (insn, params);
+  insn_emitted |= maybe_emit_speculative_check (insn, expr, params);
+
+  return insn_emitted;
+}  
+
+/* Remove INSN from stream.  When ONLY_DISCONNECT is true, its data 
+   is not removed but reused when INSN is re-emitted.  */
+static void
+remove_insn_from_stream (rtx insn, bool only_disconnect)
+{
+  insn_t nop, bb_head, bb_end;
+  bool need_nop_to_preserve_bb;
+  basic_block bb = BLOCK_FOR_INSN (insn);
+
+  /* If INSN is the only insn in the basic block (not counting JUMP,
+     which may be a jump to next insn), leave NOP there till the 
+     return to fill_insns.  */
+  bb_head = sel_bb_head (bb);
+  bb_end = sel_bb_end (bb);
+  need_nop_to_preserve_bb = ((bb_head == bb_end)
+                             || (NEXT_INSN (bb_head) == bb_end 
+                                 && JUMP_P (bb_end))
+                             || IN_CURRENT_FENCE_P (NEXT_INSN (insn)));
+
+  /* If there's only one insn in the BB, make sure that a nop is
+     inserted into it, so the basic block won't disappear when we'll
+     delete INSN below with sel_remove_insn. It should also survive
+     till the return to fill_insns.  */             
+  if (need_nop_to_preserve_bb)
+    {
+      nop = get_nop_from_pool (insn);
+      gcc_assert (INSN_NOP_P (nop));
+      VEC_safe_push (insn_t, heap, vec_temp_moveop_nops, nop);
+    }
+
+  sel_remove_insn (insn, only_disconnect, false);
+}
+
+/* This function is called when original expr is found.
+   INSN - current insn traversed, EXPR - the corresponding expr found.  
+   LPARAMS is the local parameters of code modion driver, STATIC_PARAMS
+   is static parameters of move_op.  */
+static void
+move_op_orig_expr_found (insn_t insn, expr_t expr, 
+                         cmpd_local_params_p lparams ATTRIBUTE_UNUSED, 
+                         void *static_params)
+{
+  bool only_disconnect, insn_emitted;
+  moveop_static_params_p params = (moveop_static_params_p) static_params;
+  
+  copy_expr_onside (params->c_expr, INSN_EXPR (insn));
+  track_scheduled_insns_and_blocks (insn);
+  insn_emitted = handle_emitting_transformations (insn, expr, params);
+  only_disconnect = (params->uid == INSN_UID (insn)
+                     && ! insn_emitted  && ! EXPR_WAS_CHANGED (expr));
+  remove_insn_from_stream (insn, only_disconnect);
+}
+
+/* The function is called when original expr is found.
+   INSN - current insn traversed, EXPR - the corresponding expr found,
+   crosses_call and original_insns in STATIC_PARAMS are updated.  */
+static void
+fur_orig_expr_found (insn_t insn, expr_t expr ATTRIBUTE_UNUSED,
+                     cmpd_local_params_p lparams ATTRIBUTE_UNUSED,
+                     void *static_params)
+{
+  fur_static_params_p params = (fur_static_params_p) static_params;
+  regset tmp;
+
+  if (CALL_P (insn))
+    params->crosses_call = true;
+
+  def_list_add (params->original_insns, insn, params->crosses_call);
+
+  /* Mark the registers that do not meet the following condition:
+    (2) not among the live registers of the point 
+       immediately following the first original operation on 
+       a given downward path, except for the original target
+       register of the operation.  */
+  tmp = get_clear_regset_from_pool ();
+  compute_live_below_insn (insn, tmp);
+  AND_COMPL_REG_SET (tmp, INSN_REG_SETS (insn));
+  AND_COMPL_REG_SET (tmp, INSN_REG_CLOBBERS (insn));
+  IOR_REG_SET (params->used_regs, tmp);
+  return_regset_to_pool (tmp);
+
+  /* (*1) We need to add to USED_REGS registers that are read by
+     INSN's lhs. This may lead to choosing wrong src register.
+     E.g. (scheduling const expr enabled):
+
+       429: ax=0x0     <- Can't use AX for this expr (0x0)
+       433: dx=[bp-0x18]
+       427: [ax+dx+0x1]=ax
+         REG_DEAD: ax
+       168: di=dx
+         REG_DEAD: dx
+     */
+  /* FIXME: see comment above and enable MEM_P 
+     in vinsn_separable_p.  */
+  gcc_assert (!VINSN_SEPARABLE_P (INSN_VINSN (insn))
+             || !MEM_P (INSN_LHS (insn)));
+}
+
+/* This function is called on the ascending pass, before returning from
+   current basic block.  */
+static void
+move_op_at_first_insn (insn_t insn, cmpd_local_params_p lparams, 
+                       void *static_params)
+{
+  moveop_static_params_p sparams = (moveop_static_params_p) static_params;
+  basic_block book_block = NULL;
+
+  /* When we have removed the boundary insn for scheduling, which also 
+     happened to be the end insn in its bb, we don't need to update sets.  */
+  if (!lparams->removed_last_insn 
+      && lparams->e1
+      && sel_bb_head_p (insn))
+    {
+      /* We should generate bookkeeping code only if we are not at the
+         top level of the move_op.  */
+      if (sel_num_cfg_preds_gt_1 (insn))
+        book_block = generate_bookkeeping_insn (sparams->c_expr,
+                                                lparams->e1, lparams->e2);
+      /* Update data sets for the current insn.  */
+      update_data_sets (insn);
+    }
+  
+  /* If bookkeeping code was inserted, we need to update av sets of basic
+     block that received bookkeeping.  After generation of bookkeeping insn, 
+     bookkeeping block does not contain valid av set because we are not following
+     the original algorithm in every detail with regards to e.g. renaming 
+     simple reg-reg copies.  Consider example:
+         
+     bookkeeping block           scheduling fence
+     \            /
+      \    join  /
+       ----------
+       |        |
+       ----------
+      /           \
+     /             \
+     r1 := r2          r1 := r3
+
+     We try to schedule insn "r1 := r3" on the current 
+     scheduling fence.  Also, note that av set of bookkeeping block
+     contain both insns "r1 := r2" and "r1 := r3".  When the insn has
+     been scheduled, the CFG is as follows:
+
+     r1 := r3               r1 := r3
+     bookkeeping block           scheduling fence
+     \            /
+      \    join  /
+       ----------
+       |        |
+       ----------
+      /          \
+     /            \
+     r1 := r2
+
+     Here, insn "r1 := r3" was scheduled at the current scheduling point
+     and bookkeeping code was generated at the bookeeping block.  This
+     way insn "r1 := r2" is no longer available as a whole instruction
+     (but only as expr) ahead of insn "r1 := r3" in bookkeeping block.
+     This situation is handled by calling update_data_sets.  
+
+     Since update_data_sets is called only on the bookkeeping block, and
+     it also may have predecessors with av_sets, containing instructions that 
+     are no longer available, we save all such expressions that become
+     unavailable during data sets update on the bookkeeping block in
+     VEC_BOOKKEEPING_BLOCKED_VINSNS.  Later we avoid selecting such 
+     expressions for scheduling.  This allows us to avoid recomputation of 
+     av_sets outside the code motion path.  */
+      
+  if (book_block)
+    update_and_record_unavailable_insns (book_block);
+
+  /* If INSN was previously marked for deletion, it's time to do it.  */
+  if (lparams->removed_last_insn)
+    insn = PREV_INSN (insn);
+  
+  /* Do not tidy control flow at the topmost moveop, as we can erroneously
+     kill a block with a single nop in which the insn should be emitted.  */
+  if (lparams->e1)
+    tidy_control_flow (BLOCK_FOR_INSN (insn), true);
+}
+
+/* This function is called on the ascending pass, before returning from the
+   current basic block.  */
+static void
+fur_at_first_insn (insn_t insn, 
+                   cmpd_local_params_p lparams ATTRIBUTE_UNUSED, 
+                   void *static_params ATTRIBUTE_UNUSED)
+{
+  gcc_assert (!sel_bb_head_p (insn) || AV_SET_VALID_P (insn)
+             || AV_LEVEL (insn) == -1);
+}
+
+/* Called on the backward stage of recursion to call moveup_expr for insn
+   and sparams->c_expr.  */
+static void
+move_op_ascend (insn_t insn, void *static_params)
+{
+  enum MOVEUP_EXPR_CODE res;
+  moveop_static_params_p sparams = (moveop_static_params_p) static_params;
+
+  if (! INSN_NOP_P (insn))
+    {
+      res = moveup_expr_cached (sparams->c_expr, insn, false);
+      gcc_assert (res != MOVEUP_EXPR_NULL);
+    }
+
+  /* Update liveness for this insn as it was invalidated.  */
+  update_liveness_on_insn (insn);
+}
+
+/* This function is called on enter to the basic block.  
+   Returns TRUE if this block already have been visited and 
+   code_motion_path_driver should return 1, FALSE otherwise.  */
+static int
+fur_on_enter (insn_t insn ATTRIBUTE_UNUSED, cmpd_local_params_p local_params, 
+             void *static_params, bool visited_p)
+{
+  fur_static_params_p sparams = (fur_static_params_p) static_params;
+
+  if (visited_p)
+    {
+      /* If we have found something below this block, there should be at
+        least one insn in ORIGINAL_INSNS.  */
+      gcc_assert (*sparams->original_insns);
+
+      /* Adjust CROSSES_CALL, since we may have come to this block along
+        different path.  */
+      DEF_LIST_DEF (*sparams->original_insns)->crosses_call
+         |= sparams->crosses_call;
+    }
+  else
+    local_params->old_original_insns = *sparams->original_insns;
+
+  return 1;
+}
+
+/* Same as above but for move_op.   */
+static int
+move_op_on_enter (insn_t insn ATTRIBUTE_UNUSED, 
+                  cmpd_local_params_p local_params ATTRIBUTE_UNUSED, 
+                  void *static_params ATTRIBUTE_UNUSED, bool visited_p)
+{
+  if (visited_p)
+    return -1;
+  return 1;
+}
+
+/* This function is called while descending current basic block if current 
+   insn is not the original EXPR we're searching for.
+
+   Return value: FALSE, if code_motion_path_driver should perform a local 
+                       cleanup and return 0 itself;
+                TRUE, if code_motion_path_driver should continue.  */
+static bool
+move_op_orig_expr_not_found (insn_t insn, av_set_t orig_ops ATTRIBUTE_UNUSED,
+                           void *static_params)
+{
+  moveop_static_params_p sparams = (moveop_static_params_p) static_params;
+
+#ifdef ENABLE_CHECKING
+  sparams->failed_insn = insn;
+#endif
+
+  /* If we're scheduling separate expr, in order to generate correct code
+     we need to stop the search at bookkeeping code generated with the 
+     same destination register or memory.  */
+  if (lhs_of_insn_equals_to_dest_p (insn, sparams->dest))
+    return false;
+  return true;
+}
+
+/* This function is called while descending current basic block if current 
+   insn is not the original EXPR we're searching for.
+
+   Return value: TRUE (code_motion_path_driver should continue).  */
+static bool
+fur_orig_expr_not_found (insn_t insn, av_set_t orig_ops, void *static_params)
+{
+  bool mutexed;
+  expr_t r;
+  av_set_iterator avi;
+  fur_static_params_p sparams = (fur_static_params_p) static_params;
+
+  if (CALL_P (insn))
+    sparams->crosses_call = true;
+
+  /* If current insn we are looking at cannot be executed together
+     with original insn, then we can skip it safely.
+
+     Example: ORIG_OPS = { (p6) r14 = sign_extend (r15); }
+             INSN = (!p6) r14 = r14 + 1;
+
+     Here we can schedule ORIG_OP with lhs = r14, though only
+     looking at the set of used and set registers of INSN we must
+     forbid it.  So, add set/used in INSN registers to the
+     untouchable set only if there is an insn in ORIG_OPS that can
+     affect INSN.  */
+  mutexed = true;
+  FOR_EACH_EXPR (r, avi, orig_ops)
+    if (!sched_insns_conditions_mutex_p (insn, EXPR_INSN_RTX (r)))
+      {
+       mutexed = false;
+       break;
+      }
+
+  /* Mark all registers that do not meet the following condition:
+     (1) Not set or read on any path from xi to an instance of the
+        original operation.  */
+  if (!mutexed)
+    {
+      IOR_REG_SET (sparams->used_regs, INSN_REG_SETS (insn));
+      IOR_REG_SET (sparams->used_regs, INSN_REG_USES (insn));
+      IOR_REG_SET (sparams->used_regs, INSN_REG_CLOBBERS (insn));
+    }
+
+  return true;
+}
+
+/* Hooks and data to perform move_op operations with code_motion_path_driver.  */
+struct code_motion_path_driver_info_def move_op_hooks = {
+  move_op_on_enter,
+  move_op_orig_expr_found,
+  move_op_orig_expr_not_found,
+  move_op_merge_succs,
+  move_op_after_merge_succs,
+  move_op_ascend,
+  move_op_at_first_insn,
+  SUCCS_NORMAL,
+  "move_op"
+};
+
+/* Hooks and data to perform find_used_regs operations 
+   with code_motion_path_driver.  */
+struct code_motion_path_driver_info_def fur_hooks = {
+  fur_on_enter,
+  fur_orig_expr_found,
+  fur_orig_expr_not_found,
+  fur_merge_succs,
+  NULL, /* fur_after_merge_succs */
+  NULL, /* fur_ascend */
+  fur_at_first_insn,
+  SUCCS_ALL,
+  "find_used_regs"
+};
+
+/* Traverse all successors of INSN.  For each successor that is SUCCS_NORMAL
+   code_motion_path_driver is called recursively.  Original operation 
+   was found at least on one path that is starting with one of INSN's 
+   successors (this fact is asserted).  ORIG_OPS is expressions we're looking
+   for, PATH is the path we've traversed, STATIC_PARAMS is the parameters
+   of either move_op or find_used_regs depending on the caller.  
+
+   Return 0 if we haven't found expression, 1 if we found it, -1 if we don't
+   know for sure at this point.  */
+static int
+code_motion_process_successors (insn_t insn, av_set_t orig_ops, 
+                                ilist_t path, void *static_params)
+{
+  int res = 0;
+  succ_iterator succ_i;
+  rtx succ;
+  basic_block bb;
+  int old_index;
+  unsigned old_succs;
+
+  struct cmpd_local_params lparams;
+  expr_def _x;
+
+  lparams.c_expr_local = &_x;
+  lparams.c_expr_merged = NULL;
+
+  /* We need to process only NORMAL succs for move_op, and collect live
+     registers from ALL branches (including those leading out of the 
+     region) for find_used_regs.  
+
+     In move_op, there can be a case when insn's bb number has changed
+     due to created bookkeeping.  This happens very rare, as we need to 
+     move expression from the beginning to the end of the same block.  
+     Rescan successors in this case.  */     
+
+ rescan:
+  bb = BLOCK_FOR_INSN (insn);
+  old_index = bb->index; 
+  old_succs = EDGE_COUNT (bb->succs);
+  
+  FOR_EACH_SUCC_1 (succ, succ_i, insn, code_motion_path_driver_info->succ_flags)
+    {
+      int b;
+
+      lparams.e1 = succ_i.e1;
+      lparams.e2 = succ_i.e2;
+
+      /* Go deep into recursion only for NORMAL edges (non-backedges within the
+        current region).  */
+      if (succ_i.current_flags == SUCCS_NORMAL)
+       b = code_motion_path_driver (succ, orig_ops, path, &lparams, 
+                                    static_params);
+      else
+       b = 0;
+
+      /* Merge c_expres found or unify live register sets from different
+        successors.  */
+      code_motion_path_driver_info->merge_succs (insn, succ, b, &lparams,
+                                                static_params);
+      if (b == 1)
+        res = b;
+      else if (b == -1 && res != 1)
+        res = b;
+
+      /* We have simplified the control flow below this point.  In this case,
+         the iterator becomes invalid.  We need to try again.  */
+      if (BLOCK_FOR_INSN (insn)->index != old_index
+          || EDGE_COUNT (bb->succs) != old_succs)
+        goto rescan;
+    }
+
+#ifdef ENABLE_CHECKING
+  /* Here, RES==1 if original expr was found at least for one of the 
+     successors.  After the loop, RES may happen to have zero value
+     only if at some point the expr searched is present in av_set, but is 
+     not found below.  In most cases, this situation is an error.  
+     The exception is when the original operation is blocked by
+     bookkeeping generated for another fence or for another path in current
+     move_op.  */
+  gcc_assert (res == 1 
+              || (res == 0 
+                  && av_set_could_be_blocked_by_bookkeeping_p (orig_ops,
+                                                              static_params))
+              || res == -1);
+#endif
+  
+  /* Merge data, clean up, etc.  */
+  if (code_motion_path_driver_info->after_merge_succs)
+    code_motion_path_driver_info->after_merge_succs (&lparams, static_params);
+
+  return res;
+}
+
+
+/* Perform a cleanup when the driver is about to terminate.  ORIG_OPS_P 
+   is the pointer to the av set with expressions we were looking for, 
+   PATH_P is the pointer to the traversed path.  */
+static inline void
+code_motion_path_driver_cleanup (av_set_t *orig_ops_p, ilist_t *path_p)
+{
+  ilist_remove (path_p);
+  av_set_clear (orig_ops_p);
+}
+
+/* The driver function that implements move_op or find_used_regs 
+   functionality dependent whether code_motion_path_driver_INFO is set to 
+   &MOVE_OP_HOOKS or &FUR_HOOKS.  This function implements the common parts 
+   of code (CFG traversal etc) that are shared among both functions.  INSN
+   is the insn we're starting the search from, ORIG_OPS are the expressions
+   we're searching for, PATH is traversed path, LOCAL_PARAMS_IN are local
+   parameters of the driver, and STATIC_PARAMS are static parameters of
+   the caller.  
+
+   Returns whether original instructions were found.  Note that top-level
+   code_motion_path_driver always returns true.  */
+static bool
+code_motion_path_driver (insn_t insn, av_set_t orig_ops, ilist_t path, 
+                        cmpd_local_params_p local_params_in, 
+                        void *static_params)
+{
+  expr_t expr = NULL;
+  basic_block bb = BLOCK_FOR_INSN (insn);
+  insn_t first_insn, bb_tail, before_first;
+  bool removed_last_insn = false;
+
+  if (sched_verbose >= 6)
+    {
+      sel_print ("%s (", code_motion_path_driver_info->routine_name);
+      dump_insn (insn);
+      sel_print (",");
+      dump_av_set (orig_ops);
+      sel_print (")\n");
+    }
+
+  gcc_assert (orig_ops);
+
+  /* If no original operations exist below this insn, return immediately.  */
+  if (is_ineligible_successor (insn, path))
+    {
+      if (sched_verbose >= 6)
+        sel_print ("Insn %d is ineligible successor\n", INSN_UID (insn));
+      return false;
+    }
+  
+  /* The block can have invalid av set, in which case it was created earlier
+     during move_op.  Return immediately.  */
+  if (sel_bb_head_p (insn))
+    {
+      if (! AV_SET_VALID_P (insn))
+        {
+          if (sched_verbose >= 6)
+            sel_print ("Returned from block %d as it had invalid av set\n",
+                       bb->index);
+          return false;
+        }
+
+      if (bitmap_bit_p (code_motion_visited_blocks, bb->index))
+        {
+          /* We have already found an original operation on this branch, do not
+             go any further and just return TRUE here.  If we don't stop here,
+             function can have exponential behaviour even on the small code 
+             with many different paths (e.g. with data speculation and
+             recovery blocks).  */
+          if (sched_verbose >= 6)
+            sel_print ("Block %d already visited in this traversal\n", bb->index);
+          if (code_motion_path_driver_info->on_enter)
+            return code_motion_path_driver_info->on_enter (insn, 
+                                                           local_params_in,
+                                                           static_params, 
+                                                           true);
+        }
+    }
+  
+  if (code_motion_path_driver_info->on_enter)
+    code_motion_path_driver_info->on_enter (insn, local_params_in,
+                                            static_params, false);
+  orig_ops = av_set_copy (orig_ops);
+
+  /* Filter the orig_ops set.  */
+  if (AV_SET_VALID_P (insn))
+    av_set_intersect (&orig_ops, AV_SET (insn));
+
+  /* If no more original ops, return immediately.  */
+  if (!orig_ops)
+    {
+      if (sched_verbose >= 6)
+        sel_print ("No intersection with av set of block %d\n", bb->index);
+      return false;
+    }
+
+  /* For non-speculative insns we have to leave only one form of the
+     original operation, because if we don't, we may end up with 
+     different C_EXPRes and, consequently, with bookkeepings for different
+     expression forms along the same code motion path.  That may lead to
+     generation of incorrect code.  So for each code motion we stick to 
+     the single form of the instruction,  except for speculative insns 
+     which we need to keep in different forms with all speculation 
+     types.  */
+  av_set_leave_one_nonspec (&orig_ops);
+
+  /* It is not possible that all ORIG_OPS are filtered out.  */
+  gcc_assert (orig_ops);
+
+  /* It is enough to place only heads and tails of visited basic blocks into
+     the PATH.  */
+  ilist_add (&path, insn);
+  first_insn = insn;
+  bb_tail = sel_bb_end (bb);
+
+  /* Descend the basic block in search of the original expr; this part
+     corresponds to the part of the original move_op procedure executed 
+     before the recursive call.  */
+  for (;;)
+    {
+      /* Look at the insn and decide if it could be an ancestor of currently
+        scheduling operation.  If it is so, then the insn "dest = op" could
+        either be replaced with "dest = reg", because REG now holds the result
+        of OP, or just removed, if we've scheduled the insn as a whole.
+
+        If this insn doesn't contain currently scheduling OP, then proceed
+        with searching and look at its successors.  Operations we're searching
+        for could have changed when moving up through this insn via 
+        substituting.  In this case, perform unsubstitution on them first.
+
+        When traversing the DAG below this insn is finished, insert
+        bookkeeping code, if the insn is a joint point, and remove
+        leftovers.  */
+
+      expr = av_set_lookup (orig_ops, INSN_VINSN (insn));
+      if (expr)
+       {
+         insn_t last_insn = PREV_INSN (insn);
+
+         /* We have found the original operation.   */
+          if (sched_verbose >= 6)
+            sel_print ("Found original operation at insn %d\n", INSN_UID (insn));
+
+         code_motion_path_driver_info->orig_expr_found 
+            (insn, expr, local_params_in, static_params);
+
+         /* Step back, so on the way back we'll start traversing from the
+            previous insn (or we'll see that it's bb_note and skip that 
+            loop).  */
+          if (insn == first_insn)
+            {
+              first_insn = NEXT_INSN (last_insn);
+              removed_last_insn = sel_bb_end_p (last_insn);
+            }
+         insn = last_insn;
+         break;
+       }
+      else
+       {
+         /* We haven't found the original expr, continue descending the basic
+            block.  */
+         if (code_motion_path_driver_info->orig_expr_not_found 
+              (insn, orig_ops, static_params))
+           {
+             /* Av set ops could have been changed when moving through this 
+                insn.  To find them below it, we have to un-substitute them.  */
+             undo_transformations (&orig_ops, insn);
+           }
+         else
+           {
+             /* Clean up and return, if the hook tells us to do so.  It may
+                happen if we've encountered the previously created 
+                bookkeeping.  */
+             code_motion_path_driver_cleanup (&orig_ops, &path);
+             return -1;
+           }
+
+         gcc_assert (orig_ops);
+        }
+
+      /* Stop at insn if we got to the end of BB.  */
+      if (insn == bb_tail)
+       break;
+
+      insn = NEXT_INSN (insn);
+    }
+
+  /* Here INSN either points to the insn before the original insn (may be 
+     bb_note, if original insn was a bb_head) or to the bb_end.  */
+  if (!expr)
+    {
+      int res;
+
+      gcc_assert (insn == sel_bb_end (bb));
+
+      /* Add bb tail to PATH (but it doesn't make any sense if it's a bb_head -
+        it's already in PATH then).  */
+      if (insn != first_insn)
+       ilist_add (&path, insn);
+
+      /* Process_successors should be able to find at least one 
+        successor for which code_motion_path_driver returns TRUE.  */ 
+      res = code_motion_process_successors (insn, orig_ops, 
+                                            path, static_params);
+
+      /* Remove bb tail from path.  */
+      if (insn != first_insn)
+       ilist_remove (&path);
+
+      if (res != 1)
+       {
+         /* This is the case when one of the original expr is no longer available
+            due to bookkeeping created on this branch with the same register.  
+            In the original algorithm, which doesn't have update_data_sets call
+            on a bookkeeping block, it would simply result in returning 
+            FALSE when we've encountered a previously generated bookkeeping 
+            insn in moveop_orig_expr_not_found.  */
+         code_motion_path_driver_cleanup (&orig_ops, &path);
+         return res;
+       }
+    }
+
+  /* Don't need it any more.  */
+  av_set_clear (&orig_ops);
+
+  /* Backward pass: now, when we have C_EXPR computed, we'll drag it to 
+     the beginning of the basic block.  */
+  before_first = PREV_INSN (first_insn);
+  while (insn != before_first)
+    { 
+      if (code_motion_path_driver_info->ascend)
+       code_motion_path_driver_info->ascend (insn, static_params);
+
+      insn = PREV_INSN (insn);
+    }
+  
+  /* Now we're at the bb head.  */
+  insn = first_insn;
+  ilist_remove (&path);
+  local_params_in->removed_last_insn = removed_last_insn;
+  code_motion_path_driver_info->at_first_insn (insn, local_params_in, static_params);
+  
+  /* This should be the very last operation as at bb head we could change
+     the numbering by creating bookkeeping blocks.  */
+  if (removed_last_insn)
+    insn = PREV_INSN (insn);
+  bitmap_set_bit (code_motion_visited_blocks, BLOCK_FOR_INSN (insn)->index);
+  return true;
+}
+
+/* Move up the operations from ORIG_OPS set traversing the dag starting 
+   from INSN.  PATH represents the edges traversed so far.
+   DEST is the register chosen for scheduling the current expr.  Insert
+   bookkeeping code in the join points.  EXPR_VLIW is the chosen expression,
+   C_EXPR is how it looks like at the given cfg point.  
+
+   Returns whether original instructions were found, which is asserted 
+   to be true in the caller.  */
+static bool
+move_op (insn_t insn, av_set_t orig_ops, expr_t expr_vliw,
+         rtx dest, expr_t c_expr)
+{
+  struct moveop_static_params sparams;
+  struct cmpd_local_params lparams;
+  bool res;
+
+  /* Init params for code_motion_path_driver.  */ 
+  sparams.dest = dest;
+  sparams.c_expr = c_expr;
+  sparams.uid = INSN_UID (EXPR_INSN_RTX (expr_vliw));
+#ifdef ENABLE_CHECKING
+  sparams.failed_insn = NULL;
+#endif
+  sparams.was_renamed = false;
+  lparams.e1 = NULL;
+
+  /* We haven't visited any blocks yet.  */
+  bitmap_clear (code_motion_visited_blocks);
+  
+  /* Set appropriate hooks and data.  */
+  code_motion_path_driver_info = &move_op_hooks;
+  res = code_motion_path_driver (insn, orig_ops, NULL, &lparams, &sparams);
+
+  if (sparams.was_renamed)
+    EXPR_WAS_RENAMED (expr_vliw) = true;
+
+  return res;
+}
+\f
+
+/* Functions that work with regions.  */
+
+/* Current number of seqno used in init_seqno and init_seqno_1.  */
+static int cur_seqno;
+
+/* A helper for init_seqno.  Traverse the region starting from BB and 
+   compute seqnos for visited insns, marking visited bbs in VISITED_BBS.  
+   Clear visited blocks from BLOCKS_TO_RESCHEDULE.  */
+static void
+init_seqno_1 (basic_block bb, sbitmap visited_bbs, bitmap blocks_to_reschedule)
+{
+  int bbi = BLOCK_TO_BB (bb->index);
+  insn_t insn, note = bb_note (bb);
+  insn_t succ_insn;
+  succ_iterator si;
+
+  SET_BIT (visited_bbs, bbi);
+  if (blocks_to_reschedule)
+    bitmap_clear_bit (blocks_to_reschedule, bb->index);
+
+  FOR_EACH_SUCC_1 (succ_insn, si, BB_END (bb), 
+                  SUCCS_NORMAL | SUCCS_SKIP_TO_LOOP_EXITS)
+    {
+      basic_block succ = BLOCK_FOR_INSN (succ_insn);
+      int succ_bbi = BLOCK_TO_BB (succ->index);
+
+      gcc_assert (in_current_region_p (succ));
+
+      if (!TEST_BIT (visited_bbs, succ_bbi))
+       {
+         gcc_assert (succ_bbi > bbi);
+
+         init_seqno_1 (succ, visited_bbs, blocks_to_reschedule);
+       }
+    }
+
+  for (insn = BB_END (bb); insn != note; insn = PREV_INSN (insn))
+    INSN_SEQNO (insn) = cur_seqno--;
+}
+
+/* Initialize seqnos for the current region.  NUMBER_OF_INSNS is the number
+   of instructions in the region, BLOCKS_TO_RESCHEDULE contains blocks on 
+   which we're rescheduling when pipelining, FROM is the block where
+   traversing region begins (it may not be the head of the region when
+   pipelining, but the head of the loop instead).  
+
+   Returns the maximal seqno found.  */
+static int
+init_seqno (int number_of_insns, bitmap blocks_to_reschedule, basic_block from)
+{
+  sbitmap visited_bbs;
+  bitmap_iterator bi;
+  unsigned bbi;
+
+  visited_bbs = sbitmap_alloc (current_nr_blocks);
+
+  if (blocks_to_reschedule)
+    {
+      sbitmap_ones (visited_bbs);
+      EXECUTE_IF_SET_IN_BITMAP (blocks_to_reschedule, 0, bbi, bi)
+        {
+         gcc_assert (BLOCK_TO_BB (bbi) < current_nr_blocks);
+          RESET_BIT (visited_bbs, BLOCK_TO_BB (bbi));
+       }
+    }
+  else
+    {
+      sbitmap_zero (visited_bbs);
+      from = EBB_FIRST_BB (0);
+    }
+
+  cur_seqno = number_of_insns > 0 ? number_of_insns : sched_max_luid - 1;
+  init_seqno_1 (from, visited_bbs, blocks_to_reschedule);
+  gcc_assert (cur_seqno == 0 || number_of_insns == 0);
+
+  sbitmap_free (visited_bbs);
+  return sched_max_luid - 1;
+}
+
+/* Initialize scheduling parameters for current region.  */
+static void
+sel_setup_region_sched_flags (void)
+{
+  enable_schedule_as_rhs_p = 1;
+  bookkeeping_p = 1;
+  pipelining_p = (bookkeeping_p 
+                  && (flag_sel_sched_pipelining != 0)
+                 && current_loop_nest != NULL);
+  max_insns_to_rename = PARAM_VALUE (PARAM_SELSCHED_INSNS_TO_RENAME);
+  max_ws = MAX_WS;
+}
+
+/* Return true if all basic blocks of current region are empty.  */
+static bool
+current_region_empty_p (void)
+{
+  int i;
+  for (i = 0; i < current_nr_blocks; i++)
+    if (! sel_bb_empty_p (BASIC_BLOCK (BB_TO_BLOCK (i))))
+      return false;
+
+  return true;
+}
+
+/* Prepare and verify loop nest for pipelining.  */
+static void
+setup_current_loop_nest (int rgn)
+{
+  current_loop_nest = get_loop_nest_for_rgn (rgn);
+
+  if (!current_loop_nest)
+    return;
+
+  /* If this loop has any saved loop preheaders from nested loops,
+     add these basic blocks to the current region.  */
+  sel_add_loop_preheaders ();
+
+  /* Check that we're starting with a valid information.  */
+  gcc_assert (loop_latch_edge (current_loop_nest));
+  gcc_assert (LOOP_MARKED_FOR_PIPELINING_P (current_loop_nest));
+}
+
+/* Purge meaningless empty blocks in the middle of a region.  */
+static void
+purge_empty_blocks (void)
+{
+  int i ;
+
+  for (i = 1; i < current_nr_blocks; )
+    {
+      basic_block b = BASIC_BLOCK (BB_TO_BLOCK (i));
+
+      if (maybe_tidy_empty_bb (b))
+       continue;
+
+      i++;
+    }
+}
+
+/* Compute instruction priorities for current region.  */
+static void
+sel_compute_priorities (int rgn)
+{
+  sched_rgn_compute_dependencies (rgn);
+
+  /* Compute insn priorities in haifa style.  Then free haifa style
+     dependencies that we've calculated for this.  */
+  compute_priorities ();
+
+  if (sched_verbose >= 5)
+    debug_rgn_dependencies (0);
+
+  free_rgn_deps ();
+}
+
+/* Init scheduling data for RGN.  Returns true when this region should not
+   be scheduled.  */
+static bool
+sel_region_init (int rgn)
+{
+  int i;
+  bb_vec_t bbs;
+
+  rgn_setup_region (rgn);
+
+  /* Even if sched_is_disabled_for_current_region_p() is true, we still 
+     do region initialization here so the region can be bundled correctly,
+     but we'll skip the scheduling in sel_sched_region ().  */
+  if (current_region_empty_p ())
+    return true;
+
+  if (flag_sel_sched_pipelining)
+    setup_current_loop_nest (rgn);
+
+  sel_setup_region_sched_flags ();
+
+  bbs = VEC_alloc (basic_block, heap, current_nr_blocks);
+
+  for (i = 0; i < current_nr_blocks; i++)
+    VEC_quick_push (basic_block, bbs, BASIC_BLOCK (BB_TO_BLOCK (i)));
+
+  sel_init_bbs (bbs, NULL);
+
+  /* Initialize luids and dependence analysis which both sel-sched and haifa
+     need.  */
+  sched_init_luids (bbs, NULL, NULL, NULL);
+  sched_deps_init (false);
+
+  /* Initialize haifa data.  */
+  rgn_setup_sched_infos ();
+  sel_set_sched_flags ();
+  haifa_init_h_i_d (bbs, NULL, NULL, NULL);
+
+  sel_compute_priorities (rgn);
+  init_deps_global ();
+
+  /* Main initialization.  */
+  sel_setup_sched_infos ();
+  sel_init_global_and_expr (bbs);
+
+  VEC_free (basic_block, heap, bbs);
+
+  blocks_to_reschedule = BITMAP_ALLOC (NULL);
+
+  /* Init correct liveness sets on each instruction of a single-block loop.
+     This is the only situation when we can't update liveness when calling
+     compute_live for the first insn of the loop.  */
+  if (current_loop_nest)
+    {
+      int header = (sel_is_loop_preheader_p (BASIC_BLOCK (BB_TO_BLOCK (0)))
+                    ? 1
+                    : 0);
+
+      if (current_nr_blocks == header + 1)
+        update_liveness_on_insn 
+          (sel_bb_head (BASIC_BLOCK (BB_TO_BLOCK (header))));
+    }
+      
+  /* Set hooks so that no newly generated insn will go out unnoticed.  */
+  sel_register_cfg_hooks ();
+
+  /* !!! We call target.sched.md_init () for the whole region, but we invoke
+     targetm.sched.md_finish () for every ebb.  */
+  if (targetm.sched.md_init)
+    /* None of the arguments are actually used in any target.  */
+    targetm.sched.md_init (sched_dump, sched_verbose, -1);
+
+  first_emitted_uid = get_max_uid () + 1;
+  preheader_removed = false;
+
+  /* Reset register allocation ticks array.  */
+  memset (reg_rename_tick, 0, sizeof reg_rename_tick);
+  reg_rename_this_tick = 0;
+
+  bitmap_initialize (forced_ebb_heads, 0);
+  bitmap_clear (forced_ebb_heads);
+
+  setup_nop_vinsn ();
+  current_copies = BITMAP_ALLOC (NULL);
+  current_originators = BITMAP_ALLOC (NULL);
+  code_motion_visited_blocks = BITMAP_ALLOC (NULL);
+
+  return false;
+}
+
+/* Simplify insns after the scheduling.  */
+static void
+simplify_changed_insns (void)
+{
+  int i;
+
+  for (i = 0; i < current_nr_blocks; i++)
+    {
+      basic_block bb = BASIC_BLOCK (BB_TO_BLOCK (i));
+      rtx insn;
+
+      FOR_BB_INSNS (bb, insn)
+       if (INSN_P (insn))
+         {
+           expr_t expr = INSN_EXPR (insn);
+
+           if (EXPR_WAS_SUBSTITUTED (expr)) 
+             validate_simplify_insn (insn);
+         }
+    }
+}
+
+/* Find boundaries of the EBB starting from basic block BB, marking blocks of
+   this EBB in SCHEDULED_BLOCKS and appropriately filling in HEAD, TAIL,
+   PREV_HEAD, and NEXT_TAIL fields of CURRENT_SCHED_INFO structure.  */
+static void
+find_ebb_boundaries (basic_block bb, bitmap scheduled_blocks)
+{
+  insn_t head, tail;
+  basic_block bb1 = bb;
+  if (sched_verbose >= 2)
+    sel_print ("Finishing schedule in bbs: ");
+
+  do
+    {
+      bitmap_set_bit (scheduled_blocks, BLOCK_TO_BB (bb1->index));
+
+      if (sched_verbose >= 2)
+       sel_print ("%d; ", bb1->index);
+    }
+  while (!bb_ends_ebb_p (bb1) && (bb1 = bb_next_bb (bb1)));
+
+  if (sched_verbose >= 2)
+    sel_print ("\n");
+
+  get_ebb_head_tail (bb, bb1, &head, &tail);
+
+  current_sched_info->head = head;
+  current_sched_info->tail = tail;
+  current_sched_info->prev_head = PREV_INSN (head);
+  current_sched_info->next_tail = NEXT_INSN (tail);
+}
+
+/* Regenerate INSN_SCHED_CYCLEs for insns of current EBB.  */
+static void
+reset_sched_cycles_in_current_ebb (void)
+{
+  int last_clock = 0;
+  int haifa_last_clock = -1;
+  int haifa_clock = 0;
+  insn_t insn;
+
+  if (targetm.sched.md_init)
+    {
+      /* None of the arguments are actually used in any target.
+        NB: We should have md_reset () hook for cases like this.  */
+      targetm.sched.md_init (sched_dump, sched_verbose, -1);
+    }
+
+  state_reset (curr_state);
+  advance_state (curr_state);
+  
+  for (insn = current_sched_info->head;
+       insn != current_sched_info->next_tail;
+       insn = NEXT_INSN (insn))
+    {
+      int cost, haifa_cost;
+      int sort_p;
+      bool asm_p, real_insn, after_stall;
+      int clock;
+
+      if (!INSN_P (insn))
+       continue;
+
+      asm_p = false;
+      real_insn = recog_memoized (insn) >= 0;
+      clock = INSN_SCHED_CYCLE (insn);
+
+      cost = clock - last_clock;
+
+      /* Initialize HAIFA_COST.  */
+      if (! real_insn)
+       {
+         asm_p = INSN_ASM_P (insn);
+
+         if (asm_p)
+           /* This is asm insn which *had* to be scheduled first
+              on the cycle.  */
+           haifa_cost = 1;
+         else
+           /* This is a use/clobber insn.  It should not change 
+              cost.  */
+           haifa_cost = 0;
+       }
+      else
+        haifa_cost = estimate_insn_cost (insn, curr_state);
+
+      /* Stall for whatever cycles we've stalled before.  */
+      after_stall = 0;
+      if (INSN_AFTER_STALL_P (insn) && cost > haifa_cost)
+        {
+          haifa_cost = cost;
+          after_stall = 1;
+        }
+
+      if (haifa_cost > 0)
+       {
+         int i = 0;
+
+         while (haifa_cost--)
+           {
+             advance_state (curr_state);
+              i++;
+
+             if (sched_verbose >= 2)
+                {
+                  sel_print ("advance_state (state_transition)\n");
+                  debug_state (curr_state);
+                }
+
+              /* The DFA may report that e.g. insn requires 2 cycles to be 
+                 issued, but on the next cycle it says that insn is ready 
+                 to go.  Check this here.  */
+              if (!after_stall
+                  && real_insn 
+                  && haifa_cost > 0
+                  && estimate_insn_cost (insn, curr_state) == 0)
+                break;
+           }
+
+         haifa_clock += i;
+       }
+      else
+       gcc_assert (haifa_cost == 0);
+
+      if (sched_verbose >= 2)
+       sel_print ("Haifa cost for insn %d: %d\n", INSN_UID (insn), haifa_cost);
+
+      if (targetm.sched.dfa_new_cycle)
+       while (targetm.sched.dfa_new_cycle (sched_dump, sched_verbose, insn,
+                                           haifa_last_clock, haifa_clock,
+                                           &sort_p))
+         {
+           advance_state (curr_state);
+           haifa_clock++;
+           if (sched_verbose >= 2)
+              {
+                sel_print ("advance_state (dfa_new_cycle)\n");
+                debug_state (curr_state);
+              }
+          }
+
+      if (real_insn)
+       {
+         cost = state_transition (curr_state, insn);
+
+          if (sched_verbose >= 2)
+            debug_state (curr_state);
+
+         gcc_assert (cost < 0);
+       }
+
+      if (targetm.sched.variable_issue)
+       targetm.sched.variable_issue (sched_dump, sched_verbose, insn, 0);
+
+      INSN_SCHED_CYCLE (insn) = haifa_clock;
+
+      last_clock = clock;
+      haifa_last_clock = haifa_clock;
+    }
+}
+
+/* Put TImode markers on insns starting a new issue group.  */
+static void
+put_TImodes (void)
+{
+  int last_clock = -1;
+  insn_t insn;
+
+  for (insn = current_sched_info->head; insn != current_sched_info->next_tail;
+       insn = NEXT_INSN (insn))
+    {
+      int cost, clock;
+
+      if (!INSN_P (insn))
+       continue;
+
+      clock = INSN_SCHED_CYCLE (insn);
+      cost = (last_clock == -1) ? 1 : clock - last_clock;
+
+      gcc_assert (cost >= 0);
+
+      if (issue_rate > 1
+         && GET_CODE (PATTERN (insn)) != USE
+         && GET_CODE (PATTERN (insn)) != CLOBBER)
+       {
+         if (reload_completed && cost > 0)
+           PUT_MODE (insn, TImode);
+
+         last_clock = clock;
+       }
+
+      if (sched_verbose >= 2)
+       sel_print ("Cost for insn %d is %d\n", INSN_UID (insn), cost);
+    }
+}
+
+/* Perform MD_FINISH on EBBs comprising current region.  When 
+   RESET_SCHED_CYCLES_P is true, run a pass emulating the scheduler
+   to produce correct sched cycles on insns.  */
+static void
+sel_region_target_finish (bool reset_sched_cycles_p)
+{
+  int i;
+  bitmap scheduled_blocks = BITMAP_ALLOC (NULL);
+
+  for (i = 0; i < current_nr_blocks; i++)
+    {
+      if (bitmap_bit_p (scheduled_blocks, i))
+       continue;
+
+      /* While pipelining outer loops, skip bundling for loop
+        preheaders.  Those will be rescheduled in the outer loop.  */
+      if (sel_is_loop_preheader_p (EBB_FIRST_BB (i)))
+       continue;
+
+      find_ebb_boundaries (EBB_FIRST_BB (i), scheduled_blocks);
+
+      if (no_real_insns_p (current_sched_info->head, current_sched_info->tail))
+       continue;
+
+      if (reset_sched_cycles_p)
+       reset_sched_cycles_in_current_ebb ();
+
+      if (targetm.sched.md_init)
+       targetm.sched.md_init (sched_dump, sched_verbose, -1);
+
+      put_TImodes ();
+
+      if (targetm.sched.md_finish)
+       {
+         targetm.sched.md_finish (sched_dump, sched_verbose);
+
+         /* Extend luids so that insns generated by the target will
+            get zero luid.  */
+         sched_init_luids (NULL, NULL, NULL, NULL);
+       }
+    }
+
+  BITMAP_FREE (scheduled_blocks);
+}
+
+/* Free the scheduling data for the current region.  When RESET_SCHED_CYCLES_P
+   is true, make an additional pass emulating scheduler to get correct insn 
+   cycles for md_finish calls.  */
+static void
+sel_region_finish (bool reset_sched_cycles_p)
+{
+  simplify_changed_insns ();
+  sched_finish_ready_list ();
+  free_nop_pool ();
+
+  /* Free the vectors.  */
+  if (vec_av_set)
+    VEC_free (expr_t, heap, vec_av_set);
+  BITMAP_FREE (current_copies);
+  BITMAP_FREE (current_originators);
+  BITMAP_FREE (code_motion_visited_blocks);
+  vinsn_vec_free (&vec_bookkeeping_blocked_vinsns);
+  vinsn_vec_free (&vec_target_unavailable_vinsns);
+
+  /* If LV_SET of the region head should be updated, do it now because
+     there will be no other chance.  */
+  {
+    succ_iterator si;
+    insn_t insn;
+
+    FOR_EACH_SUCC_1 (insn, si, bb_note (EBB_FIRST_BB (0)),
+                     SUCCS_NORMAL | SUCCS_SKIP_TO_LOOP_EXITS)
+      {
+       basic_block bb = BLOCK_FOR_INSN (insn);
+
+       if (!BB_LV_SET_VALID_P (bb))
+         compute_live (insn);
+      }
+  }
+
+  /* Emulate the Haifa scheduler for bundling.  */
+  if (reload_completed)
+    sel_region_target_finish (reset_sched_cycles_p);
+
+  sel_finish_global_and_expr ();
+
+  bitmap_clear (forced_ebb_heads);
+
+  free_nop_vinsn ();
+
+  finish_deps_global ();
+  sched_finish_luids ();
+
+  sel_finish_bbs ();
+  BITMAP_FREE (blocks_to_reschedule);
+
+  sel_unregister_cfg_hooks ();
+
+  max_issue_size = 0;
+}
+\f
+
+/* Functions that implement the scheduler driver.  */
+
+/* Schedule a parallel instruction group on each of FENCES.  MAX_SEQNO
+   is the current maximum seqno.  SCHEDULED_INSNS_TAILPP is the list
+   of insns scheduled -- these would be postprocessed later.  */
+static void
+schedule_on_fences (flist_t fences, int max_seqno,
+                    ilist_t **scheduled_insns_tailpp)
+{
+  flist_t old_fences = fences;
+
+  if (sched_verbose >= 1)
+    {
+      sel_print ("\nScheduling on fences: ");
+      dump_flist (fences);
+      sel_print ("\n");
+    }
+
+  scheduled_something_on_previous_fence = false;
+  for (; fences; fences = FLIST_NEXT (fences))
+    {
+      fence_t fence = NULL;
+      int seqno = 0;
+      flist_t fences2;
+      bool first_p = true;
+         
+      /* Choose the next fence group to schedule.
+         The fact that insn can be scheduled only once
+         on the cycle is guaranteed by two properties:
+         1. seqnos of parallel groups decrease with each iteration.
+         2. If is_ineligible_successor () sees the larger seqno, it
+         checks if candidate insn is_in_current_fence_p ().  */
+      for (fences2 = old_fences; fences2; fences2 = FLIST_NEXT (fences2))
+        {
+          fence_t f = FLIST_FENCE (fences2);
+
+          if (!FENCE_PROCESSED_P (f))
+            {
+              int i = INSN_SEQNO (FENCE_INSN (f));
+
+              if (first_p || i > seqno)
+                {
+                  seqno = i;
+                  fence = f;
+                  first_p = false;
+                }
+              else
+                /* ??? Seqnos of different groups should be different.  */
+                gcc_assert (1 || i != seqno);
+            }
+        }
+
+      gcc_assert (fence);
+
+      /* As FENCE is nonnull, SEQNO is initialized.  */
+      seqno -= max_seqno + 1;
+      fill_insns (fence, seqno, scheduled_insns_tailpp);
+      FENCE_PROCESSED_P (fence) = true;
+    }
+
+  /* All av_sets are invalidated by GLOBAL_LEVEL increase, thus we
+     don't need to keep bookkeeping-invalidated and target-unavailable 
+     vinsns any more.  */
+  vinsn_vec_clear (&vec_bookkeeping_blocked_vinsns);
+  vinsn_vec_clear (&vec_target_unavailable_vinsns);
+}
+
+/* Calculate MIN_SEQNO and MAX_SEQNO.  */
+static void
+find_min_max_seqno (flist_t fences, int *min_seqno, int *max_seqno)
+{
+  *min_seqno = *max_seqno = INSN_SEQNO (FENCE_INSN (FLIST_FENCE (fences)));
+
+  /* The first element is already processed.  */
+  while ((fences = FLIST_NEXT (fences)))
+    {
+      int seqno = INSN_SEQNO (FENCE_INSN (FLIST_FENCE (fences)));
+      
+      if (*min_seqno > seqno)
+        *min_seqno = seqno;
+      else if (*max_seqno < seqno)
+        *max_seqno = seqno;
+    }
+}
+
+/* Calculate new fences from FENCES.  */
+static flist_t 
+calculate_new_fences (flist_t fences, int orig_max_seqno)
+{
+  flist_t old_fences = fences;
+  struct flist_tail_def _new_fences, *new_fences = &_new_fences;
+
+  flist_tail_init (new_fences);
+  for (; fences; fences = FLIST_NEXT (fences))
+    {
+      fence_t fence = FLIST_FENCE (fences);
+      insn_t insn;
+      
+      if (!FENCE_BNDS (fence))
+        {
+          /* This fence doesn't have any successors.  */
+          if (!FENCE_SCHEDULED_P (fence))
+            {
+              /* Nothing was scheduled on this fence.  */
+              int seqno;
+
+              insn = FENCE_INSN (fence);
+              seqno = INSN_SEQNO (insn);
+              gcc_assert (seqno > 0 && seqno <= orig_max_seqno);
+
+              if (sched_verbose >= 1)
+                sel_print ("Fence %d[%d] has not changed\n", 
+                           INSN_UID (insn),
+                           BLOCK_NUM (insn));
+              move_fence_to_fences (fences, new_fences);
+            }
+        }
+      else
+        extract_new_fences_from (fences, new_fences, orig_max_seqno);
+    }
+
+  flist_clear (&old_fences);
+  return FLIST_TAIL_HEAD (new_fences);
+}
+
+/* Update seqnos of insns given by PSCHEDULED_INSNS.  MIN_SEQNO and MAX_SEQNO
+   are the miminum and maximum seqnos of the group, HIGHEST_SEQNO_IN_USE is
+   the highest seqno used in a region.  Return the updated highest seqno.  */
+static int
+update_seqnos_and_stage (int min_seqno, int max_seqno, 
+                         int highest_seqno_in_use, 
+                         ilist_t *pscheduled_insns)
+{
+  int new_hs;
+  ilist_iterator ii;
+  insn_t insn;
+  
+  /* Actually, new_hs is the seqno of the instruction, that was
+     scheduled first (i.e. it is the first one in SCHEDULED_INSNS).  */
+  if (*pscheduled_insns)
+    {
+      new_hs = (INSN_SEQNO (ILIST_INSN (*pscheduled_insns))
+                + highest_seqno_in_use + max_seqno - min_seqno + 2);
+      gcc_assert (new_hs > highest_seqno_in_use);
+    }
+  else
+    new_hs = highest_seqno_in_use;
+
+  FOR_EACH_INSN (insn, ii, *pscheduled_insns)
+    {
+      gcc_assert (INSN_SEQNO (insn) < 0);
+      INSN_SEQNO (insn) += highest_seqno_in_use + max_seqno - min_seqno + 2;
+      gcc_assert (INSN_SEQNO (insn) <= new_hs);
+    }
+
+  ilist_clear (pscheduled_insns);
+  global_level++;
+
+  return new_hs;
+}
+
+/* The main driver for scheduling a region.  This function is responsible 
+   for correct propagation of fences (i.e. scheduling points) and creating 
+   a group of parallel insns at each of them.  It also supports 
+   pipelining.  ORIG_MAX_SEQNO is the maximal seqno before this pass
+   of scheduling.  */
+static void
+sel_sched_region_2 (int orig_max_seqno)
+{
+  int highest_seqno_in_use = orig_max_seqno;
+
+  stat_bookkeeping_copies = 0;
+  stat_insns_needed_bookkeeping = 0;
+  stat_renamed_scheduled = 0;
+  stat_substitutions_total = 0;
+  num_insns_scheduled = 0;
+
+  while (fences)
+    {
+      int min_seqno, max_seqno;
+      ilist_t scheduled_insns = NULL;
+      ilist_t *scheduled_insns_tailp = &scheduled_insns;
+
+      find_min_max_seqno (fences, &min_seqno, &max_seqno);
+      schedule_on_fences (fences, max_seqno, &scheduled_insns_tailp);
+      fences = calculate_new_fences (fences, orig_max_seqno);
+      highest_seqno_in_use = update_seqnos_and_stage (min_seqno, max_seqno,
+                                                      highest_seqno_in_use,
+                                                      &scheduled_insns);
+    }
+
+  if (sched_verbose >= 1)
+    sel_print ("Scheduled %d bookkeeping copies, %d insns needed "
+               "bookkeeping, %d insns renamed, %d insns substituted\n",
+               stat_bookkeeping_copies,
+               stat_insns_needed_bookkeeping,
+               stat_renamed_scheduled,
+               stat_substitutions_total);
+}
+
+/* Schedule a region.  When pipelining, search for possibly never scheduled 
+   bookkeeping code and schedule it.  Reschedule pipelined code without 
+   pipelining after.  */
+static void
+sel_sched_region_1 (void)
+{
+  int number_of_insns;
+  int orig_max_seqno;
+
+  /* Remove empty blocks that might be in the region from the beginning.  
+     We need to do save sched_max_luid before that, as it actually shows
+     the number of insns in the region, and purge_empty_blocks can 
+     alter it.  */
+  number_of_insns = sched_max_luid - 1;
+  purge_empty_blocks ();
+
+  orig_max_seqno = init_seqno (number_of_insns, NULL, NULL);
+  gcc_assert (orig_max_seqno >= 1);
+
+  /* When pipelining outer loops, create fences on the loop header,
+     not preheader.  */
+  fences = NULL;
+  if (current_loop_nest)
+    init_fences (BB_END (EBB_FIRST_BB (0)));
+  else
+    init_fences (bb_note (EBB_FIRST_BB (0)));
+  global_level = 1;
+
+  sel_sched_region_2 (orig_max_seqno);
+
+  gcc_assert (fences == NULL);
+
+  if (pipelining_p)
+    {
+      int i;
+      basic_block bb;
+      struct flist_tail_def _new_fences;
+      flist_tail_t new_fences = &_new_fences;
+      bool do_p = true;
+
+      pipelining_p = false;
+      max_ws = MIN (max_ws, issue_rate * 3 / 2);
+      bookkeeping_p = false;
+      enable_schedule_as_rhs_p = false;
+
+      /* Schedule newly created code, that has not been scheduled yet.  */
+      do_p = true;
+
+      while (do_p)
+        {
+          do_p = false;
+
+          for (i = 0; i < current_nr_blocks; i++)
+            {
+              basic_block bb = EBB_FIRST_BB (i);
+
+              if (sel_bb_empty_p (bb))
+                {
+                  bitmap_clear_bit (blocks_to_reschedule, bb->index);
+                  continue;
+                }
+
+              if (bitmap_bit_p (blocks_to_reschedule, bb->index))
+                {
+                  clear_outdated_rtx_info (bb);
+                  if (sel_insn_is_speculation_check (BB_END (bb))
+                      && JUMP_P (BB_END (bb)))
+                    bitmap_set_bit (blocks_to_reschedule,
+                                    BRANCH_EDGE (bb)->dest->index);
+                }
+              else if (INSN_SCHED_TIMES (sel_bb_head (bb)) <= 0)
+                bitmap_set_bit (blocks_to_reschedule, bb->index);
+            }
+
+          for (i = 0; i < current_nr_blocks; i++)
+            {
+              bb = EBB_FIRST_BB (i);
+
+              /* While pipelining outer loops, skip bundling for loop 
+                 preheaders.  Those will be rescheduled in the outer
+                 loop.  */
+              if (sel_is_loop_preheader_p (bb))
+                {
+                  clear_outdated_rtx_info (bb);
+                  continue;
+                }
+                  
+              if (bitmap_bit_p (blocks_to_reschedule, bb->index))
+                {
+                  flist_tail_init (new_fences);
+
+                  orig_max_seqno = init_seqno (0, blocks_to_reschedule, bb);
+
+                  /* Mark BB as head of the new ebb.  */
+                  bitmap_set_bit (forced_ebb_heads, bb->index);
+
+                  bitmap_clear_bit (blocks_to_reschedule, bb->index);
+  
+                  gcc_assert (fences == NULL);
+
+                  init_fences (bb_note (bb));
+  
+                  sel_sched_region_2 (orig_max_seqno);
+  
+                  do_p = true;
+                  break;
+                }
+            }
+        }
+    }
+}
+
+/* Schedule the RGN region.  */
+void
+sel_sched_region (int rgn)
+{
+  bool schedule_p;
+  bool reset_sched_cycles_p;
+
+  if (sel_region_init (rgn))
+    return;
+
+  if (sched_verbose >= 1)
+    sel_print ("Scheduling region %d\n", rgn);
+
+  schedule_p = (!sched_is_disabled_for_current_region_p ()
+                && dbg_cnt (sel_sched_region_cnt));
+  reset_sched_cycles_p = pipelining_p;
+  if (schedule_p)
+    sel_sched_region_1 ();
+  else
+    /* Force initialization of INSN_SCHED_CYCLEs for correct bundling.  */
+    reset_sched_cycles_p = true;
+  
+  sel_region_finish (reset_sched_cycles_p);
+}
+
+/* Perform global init for the scheduler.  */
+static void
+sel_global_init (void)
+{
+  calculate_dominance_info (CDI_DOMINATORS);
+  alloc_sched_pools ();
+
+  /* Setup the infos for sched_init.  */
+  sel_setup_sched_infos ();
+  setup_sched_dump ();
+
+  sched_rgn_init (false);
+  sched_init ();
+
+  sched_init_bbs ();
+  /* Reset AFTER_RECOVERY if it has been set by the 1st scheduler pass.  */
+  after_recovery = 0;
+  can_issue_more = issue_rate; 
+
+  sched_extend_target ();
+  sched_deps_init (true);
+  setup_nop_and_exit_insns ();
+  sel_extend_global_bb_info ();
+  init_lv_sets ();
+  init_hard_regs_data ();
+}
+
+/* Free the global data of the scheduler.  */
+static void
+sel_global_finish (void)
+{
+  free_bb_note_pool ();
+  free_lv_sets ();
+  sel_finish_global_bb_info ();
+
+  free_regset_pool ();
+  free_nop_and_exit_insns ();
+
+  sched_rgn_finish ();
+  sched_deps_finish ();
+  sched_finish ();
+
+  if (current_loops)
+    sel_finish_pipelining ();
+
+  free_sched_pools ();
+  free_dominance_info (CDI_DOMINATORS);
+}
+
+/* Return true when we need to skip selective scheduling.  Used for debugging.  */
+bool
+maybe_skip_selective_scheduling (void)
+{
+  return ! dbg_cnt (sel_sched_cnt);
+}
+
+/* The entry point.  */
+void
+run_selective_scheduling (void)
+{
+  int rgn;
+
+  if (n_basic_blocks == NUM_FIXED_BLOCKS)
+    return;
+
+  sel_global_init ();
+
+  for (rgn = 0; rgn < nr_regions; rgn++)
+    sel_sched_region (rgn);
+
+  sel_global_finish ();
+}
+
+#endif
diff --git a/gcc/sel-sched.h b/gcc/sel-sched.h
new file mode 100644 (file)
index 0000000..8e0b5d5
--- /dev/null
@@ -0,0 +1,27 @@
+/* Instruction scheduling pass.  
+   Copyright (C) 2006, 2007, 2008 Free Software Foundation, Inc.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free
+Software Foundation; either version 3, or (at your option) any later
+version.
+
+GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or
+FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3.  If not see
+<http://www.gnu.org/licenses/>.  */
+
+#ifndef GCC_SEL_SCHED_H
+#define GCC_SEL_SCHED_H
+
+/* The main entry point.  */
+extern void run_selective_scheduling (void);
+extern bool maybe_skip_selective_scheduling (void);
+
+#endif /* GCC_SEL_SCHED_H */
index 740efc5..07b7f33 100644 (file)
 #define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD 0
 #define TARGET_SCHED_DFA_NEW_CYCLE 0
 #define TARGET_SCHED_IS_COSTLY_DEPENDENCE 0
+#define TARGET_SCHED_ADJUST_COST_2 0
 #define TARGET_SCHED_H_I_D_EXTENDED 0
+#define TARGET_SCHED_ALLOC_SCHED_CONTEXT 0
+#define TARGET_SCHED_INIT_SCHED_CONTEXT 0
+#define TARGET_SCHED_SET_SCHED_CONTEXT 0
+#define TARGET_SCHED_CLEAR_SCHED_CONTEXT 0
+#define TARGET_SCHED_FREE_SCHED_CONTEXT 0
 #define TARGET_SCHED_SPECULATE_INSN 0
 #define TARGET_SCHED_NEEDS_BLOCK_P 0
-#define TARGET_SCHED_GEN_CHECK 0
+#define TARGET_SCHED_GEN_SPEC_CHECK 0
 #define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD_SPEC 0
 #define TARGET_SCHED_SET_SCHED_FLAGS 0
+#define TARGET_SCHED_GET_INSN_SPEC_DS 0
+#define TARGET_SCHED_GET_INSN_CHECKED_DS 0
+#define TARGET_SCHED_SKIP_RTX_P 0
 #define TARGET_SCHED_SMS_RES_MII 0
 
 #define TARGET_SCHED                                           \
    TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD,     \
    TARGET_SCHED_DFA_NEW_CYCLE,                                 \
    TARGET_SCHED_IS_COSTLY_DEPENDENCE,                           \
+   TARGET_SCHED_ADJUST_COST_2,                                  \
    TARGET_SCHED_H_I_D_EXTENDED,                                        \
+   TARGET_SCHED_ALLOC_SCHED_CONTEXT,                            \
+   TARGET_SCHED_INIT_SCHED_CONTEXT,                             \
+   TARGET_SCHED_SET_SCHED_CONTEXT,                              \
+   TARGET_SCHED_CLEAR_SCHED_CONTEXT,                            \
+   TARGET_SCHED_FREE_SCHED_CONTEXT,                             \
    TARGET_SCHED_SPECULATE_INSN,                                 \
    TARGET_SCHED_NEEDS_BLOCK_P,                                  \
-   TARGET_SCHED_GEN_CHECK,                                      \
+   TARGET_SCHED_GEN_SPEC_CHECK,                                        \
    TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD_SPEC, \
    TARGET_SCHED_SET_SCHED_FLAGS,                                \
+   TARGET_SCHED_GET_INSN_SPEC_DS,                               \
+   TARGET_SCHED_GET_INSN_CHECKED_DS,                            \
+   TARGET_SCHED_SKIP_RTX_P,                                    \
    TARGET_SCHED_SMS_RES_MII}
 
 #define TARGET_VECTORIZE_BUILTIN_MASK_FOR_LOAD 0
index 69b270f..de8150e 100644 (file)
@@ -274,7 +274,7 @@ struct gcc_target
     /* Finalize machine-dependent scheduling code.  */
     void (* md_finish) (FILE *, int);
 
-    /* Initialize machine-dependent function while scheduling code.  */
+    /* Initialize machine-dependent function wide scheduling code.  */
     void (* md_init_global) (FILE *, int, int);
 
     /* Finalize machine-dependent function wide scheduling code.  */
@@ -354,11 +354,33 @@ struct gcc_target
        second insn (second parameter).  */
     bool (* is_costly_dependence) (struct _dep *_dep, int, int);
 
+    /* Given the current cost, COST, of an insn, INSN, calculate and
+       return a new cost based on its relationship to DEP_INSN through the
+       dependence of type DEP_TYPE.  The default is to make no adjustment.  */
+    int (* adjust_cost_2) (rtx insn, int, rtx dep_insn, int cost, int dw);
+
     /* The following member value is a pointer to a function called
        by the insn scheduler. This hook is called to notify the backend
        that new instructions were emitted.  */
     void (* h_i_d_extended) (void);
-    
+
+    /* Next 5 functions are for multi-point scheduling.  */
+
+    /* Allocate memory for scheduler context.  */
+    void *(* alloc_sched_context) (void);
+
+    /* Fills the context from the local machine scheduler context.  */
+    void (* init_sched_context) (void *, bool);
+
+    /* Sets local machine scheduler context to a saved value.  */
+    void (* set_sched_context) (void *);
+
+    /* Clears a scheduler context so it becomes like after init.  */
+    void (* clear_sched_context) (void *);
+
+    /* Frees the scheduler context.  */
+    void (* free_sched_context) (void *);
+
     /* The following member value is a pointer to a function called
        by the insn scheduler.
        The first parameter is an instruction, the second parameter is the type
@@ -374,8 +396,7 @@ struct gcc_target
 
     /* The following member value is a pointer to a function called
        by the insn scheduler.  It should return true if the check instruction
-       corresponding to the instruction passed as the parameter needs a
-       recovery block.  */
+       passed as the parameter needs a recovery block.  */
     bool (* needs_block_p) (const_rtx);
 
     /* The following member value is a pointer to a function called
@@ -386,7 +407,7 @@ struct gcc_target
        simple check).  If the mutation of the check is requested (e.g. from
        ld.c to chk.a), the third parameter is true - in this case the first
        parameter is the previous check.  */
-    rtx (* gen_check) (rtx, rtx, bool);
+    rtx (* gen_spec_check) (rtx, rtx, bool);
 
     /* The following member value is a pointer to a function controlling
        what insns from the ready insn queue will be considered for the
@@ -401,6 +422,17 @@ struct gcc_target
        The parameter is a pointer to spec_info variable.  */
     void (* set_sched_flags) (struct spec_info_def *);
 
+    /* Return speculation types of the instruction passed as the parameter.  */
+    int (* get_insn_spec_ds) (rtx);
+
+    /* Return speculation types that are checked for the instruction passed as
+       the parameter.  */
+    int (* get_insn_checked_ds) (rtx);
+
+    /* Return bool if rtx scanning should just skip current layer and
+       advance to the inner rtxes.  */
+    bool (* skip_rtx_p) (const_rtx);
+
     /* The following member value is a pointer to a function that provides
        information about the target resource-based lower bound which is
        used by the swing modulo scheduler.  The parameter is a pointer
index d4e5ffd..750dada 100644 (file)
@@ -26,4 +26,7 @@ DEF_VEC_ALLOC_I(char,heap);
 DEF_VEC_I(int);
 DEF_VEC_ALLOC_I(int,heap);
 
+DEF_VEC_I(unsigned);
+DEF_VEC_ALLOC_I(unsigned,heap);
+
 #endif /* GCC_VECPRIM_H */