OSDN Git Service

* flow.c (split_block): Make sure bb_note is included in the
[pf3gnuchains/gcc-fork.git] / gcc / flow.c
1 /* Data flow analysis for GNU compiler.
2    Copyright (C) 1987, 1988, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3    1999, 2000, 2001 Free Software Foundation, Inc.
4
5 This file is part of GNU CC.
6
7 GNU CC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 GNU CC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU CC; see the file COPYING.  If not, write to
19 the Free Software Foundation, 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA.  */
21
22 /* This file contains the data flow analysis pass of the compiler.  It
23    computes data flow information which tells combine_instructions
24    which insns to consider combining and controls register allocation.
25
26    Additional data flow information that is too bulky to record is
27    generated during the analysis, and is used at that time to create
28    autoincrement and autodecrement addressing.
29
30    The first step is dividing the function into basic blocks.
31    find_basic_blocks does this.  Then life_analysis determines
32    where each register is live and where it is dead.
33
34    ** find_basic_blocks **
35
36    find_basic_blocks divides the current function's rtl into basic
37    blocks and constructs the CFG.  The blocks are recorded in the
38    basic_block_info array; the CFG exists in the edge structures
39    referenced by the blocks.
40
41    find_basic_blocks also finds any unreachable loops and deletes them.
42
43    ** life_analysis **
44
45    life_analysis is called immediately after find_basic_blocks.
46    It uses the basic block information to determine where each
47    hard or pseudo register is live.
48
49    ** live-register info **
50
51    The information about where each register is live is in two parts:
52    the REG_NOTES of insns, and the vector basic_block->global_live_at_start.
53
54    basic_block->global_live_at_start has an element for each basic
55    block, and the element is a bit-vector with a bit for each hard or
56    pseudo register.  The bit is 1 if the register is live at the
57    beginning of the basic block.
58
59    Two types of elements can be added to an insn's REG_NOTES.
60    A REG_DEAD note is added to an insn's REG_NOTES for any register
61    that meets both of two conditions:  The value in the register is not
62    needed in subsequent insns and the insn does not replace the value in
63    the register (in the case of multi-word hard registers, the value in
64    each register must be replaced by the insn to avoid a REG_DEAD note).
65
66    In the vast majority of cases, an object in a REG_DEAD note will be
67    used somewhere in the insn.  The (rare) exception to this is if an
68    insn uses a multi-word hard register and only some of the registers are
69    needed in subsequent insns.  In that case, REG_DEAD notes will be
70    provided for those hard registers that are not subsequently needed.
71    Partial REG_DEAD notes of this type do not occur when an insn sets
72    only some of the hard registers used in such a multi-word operand;
73    omitting REG_DEAD notes for objects stored in an insn is optional and
74    the desire to do so does not justify the complexity of the partial
75    REG_DEAD notes.
76
77    REG_UNUSED notes are added for each register that is set by the insn
78    but is unused subsequently (if every register set by the insn is unused
79    and the insn does not reference memory or have some other side-effect,
80    the insn is deleted instead).  If only part of a multi-word hard
81    register is used in a subsequent insn, REG_UNUSED notes are made for
82    the parts that will not be used.
83
84    To determine which registers are live after any insn, one can
85    start from the beginning of the basic block and scan insns, noting
86    which registers are set by each insn and which die there.
87
88    ** Other actions of life_analysis **
89
90    life_analysis sets up the LOG_LINKS fields of insns because the
91    information needed to do so is readily available.
92
93    life_analysis deletes insns whose only effect is to store a value
94    that is never used.
95
96    life_analysis notices cases where a reference to a register as
97    a memory address can be combined with a preceding or following
98    incrementation or decrementation of the register.  The separate
99    instruction to increment or decrement is deleted and the address
100    is changed to a POST_INC or similar rtx.
101
102    Each time an incrementing or decrementing address is created,
103    a REG_INC element is added to the insn's REG_NOTES list.
104
105    life_analysis fills in certain vectors containing information about
106    register usage: REG_N_REFS, REG_N_DEATHS, REG_N_SETS, REG_LIVE_LENGTH,
107    REG_N_CALLS_CROSSED and REG_BASIC_BLOCK.
108
109    life_analysis sets current_function_sp_is_unchanging if the function
110    doesn't modify the stack pointer.  */
111
112 /* TODO:
113
114    Split out from life_analysis:
115         - local property discovery (bb->local_live, bb->local_set)
116         - global property computation
117         - log links creation
118         - pre/post modify transformation
119 */
120 \f
121 #include "config.h"
122 #include "system.h"
123 #include "tree.h"
124 #include "rtl.h"
125 #include "tm_p.h"
126 #include "hard-reg-set.h"
127 #include "basic-block.h"
128 #include "insn-config.h"
129 #include "regs.h"
130 #include "flags.h"
131 #include "output.h"
132 #include "function.h"
133 #include "except.h"
134 #include "toplev.h"
135 #include "recog.h"
136 #include "expr.h"
137 #include "ssa.h"
138 #include "timevar.h"
139
140 #include "obstack.h"
141 #include "splay-tree.h"
142
143 #define obstack_chunk_alloc xmalloc
144 #define obstack_chunk_free free
145
146 /* EXIT_IGNORE_STACK should be nonzero if, when returning from a function,
147    the stack pointer does not matter.  The value is tested only in
148    functions that have frame pointers.
149    No definition is equivalent to always zero.  */
150 #ifndef EXIT_IGNORE_STACK
151 #define EXIT_IGNORE_STACK 0
152 #endif
153
154 #ifndef HAVE_epilogue
155 #define HAVE_epilogue 0
156 #endif
157 #ifndef HAVE_prologue
158 #define HAVE_prologue 0
159 #endif
160 #ifndef HAVE_sibcall_epilogue
161 #define HAVE_sibcall_epilogue 0
162 #endif
163
164 #ifndef LOCAL_REGNO
165 #define LOCAL_REGNO(REGNO)  0
166 #endif
167 #ifndef EPILOGUE_USES
168 #define EPILOGUE_USES(REGNO)  0
169 #endif
170
171 #ifdef HAVE_conditional_execution
172 #ifndef REVERSE_CONDEXEC_PREDICATES_P
173 #define REVERSE_CONDEXEC_PREDICATES_P(x, y) ((x) == reverse_condition (y))
174 #endif
175 #endif
176
177 /* The obstack on which the flow graph components are allocated.  */
178
179 struct obstack flow_obstack;
180 static char *flow_firstobj;
181
182 /* Number of basic blocks in the current function.  */
183
184 int n_basic_blocks;
185
186 /* Number of edges in the current function.  */
187
188 int n_edges;
189
190 /* The basic block array.  */
191
192 varray_type basic_block_info;
193
194 /* The special entry and exit blocks.  */
195
196 struct basic_block_def entry_exit_blocks[2]
197 = {{NULL,                       /* head */
198     NULL,                       /* end */
199     NULL,                       /* head_tree */
200     NULL,                       /* end_tree */
201     NULL,                       /* pred */
202     NULL,                       /* succ */
203     NULL,                       /* local_set */
204     NULL,                       /* cond_local_set */
205     NULL,                       /* global_live_at_start */
206     NULL,                       /* global_live_at_end */
207     NULL,                       /* aux */
208     ENTRY_BLOCK,                /* index */
209     0,                          /* loop_depth */
210     0,                          /* count */
211     0                           /* frequency */
212   },
213   {
214     NULL,                       /* head */
215     NULL,                       /* end */
216     NULL,                       /* head_tree */
217     NULL,                       /* end_tree */
218     NULL,                       /* pred */
219     NULL,                       /* succ */
220     NULL,                       /* local_set */
221     NULL,                       /* cond_local_set */
222     NULL,                       /* global_live_at_start */
223     NULL,                       /* global_live_at_end */
224     NULL,                       /* aux */
225     EXIT_BLOCK,                 /* index */
226     0,                          /* loop_depth */
227     0,                          /* count */
228     0                           /* frequency */
229   }
230 };
231
232 /* Nonzero if the second flow pass has completed.  */
233 int flow2_completed;
234
235 /* Maximum register number used in this function, plus one.  */
236
237 int max_regno;
238
239 /* Indexed by n, giving various register information */
240
241 varray_type reg_n_info;
242
243 /* Size of a regset for the current function,
244    in (1) bytes and (2) elements.  */
245
246 int regset_bytes;
247 int regset_size;
248
249 /* Regset of regs live when calls to `setjmp'-like functions happen.  */
250 /* ??? Does this exist only for the setjmp-clobbered warning message?  */
251
252 regset regs_live_at_setjmp;
253
254 /* List made of EXPR_LIST rtx's which gives pairs of pseudo registers
255    that have to go in the same hard reg.
256    The first two regs in the list are a pair, and the next two
257    are another pair, etc.  */
258 rtx regs_may_share;
259
260 /* Callback that determines if it's ok for a function to have no
261    noreturn attribute.  */
262 int (*lang_missing_noreturn_ok_p) PARAMS ((tree));
263
264 /* Set of registers that may be eliminable.  These are handled specially
265    in updating regs_ever_live.  */
266
267 static HARD_REG_SET elim_reg_set;
268
269 /* The basic block structure for every insn, indexed by uid.  */
270
271 varray_type basic_block_for_insn;
272
273 /* The labels mentioned in non-jump rtl.  Valid during find_basic_blocks.  */
274 /* ??? Should probably be using LABEL_NUSES instead.  It would take a
275    bit of surgery to be able to use or co-opt the routines in jump.  */
276
277 static rtx label_value_list;
278 static rtx tail_recursion_label_list;
279
280 /* Holds information for tracking conditional register life information.  */
281 struct reg_cond_life_info
282 {
283   /* A boolean expression of conditions under which a register is dead.  */
284   rtx condition;
285   /* Conditions under which a register is dead at the basic block end.  */
286   rtx orig_condition;
287
288   /* A boolean expression of conditions under which a register has been
289      stored into.  */
290   rtx stores;
291
292   /* ??? Could store mask of bytes that are dead, so that we could finally
293      track lifetimes of multi-word registers accessed via subregs.  */
294 };
295
296 /* For use in communicating between propagate_block and its subroutines.
297    Holds all information needed to compute life and def-use information.  */
298
299 struct propagate_block_info
300 {
301   /* The basic block we're considering.  */
302   basic_block bb;
303
304   /* Bit N is set if register N is conditionally or unconditionally live.  */
305   regset reg_live;
306
307   /* Bit N is set if register N is set this insn.  */
308   regset new_set;
309
310   /* Element N is the next insn that uses (hard or pseudo) register N
311      within the current basic block; or zero, if there is no such insn.  */
312   rtx *reg_next_use;
313
314   /* Contains a list of all the MEMs we are tracking for dead store
315      elimination.  */
316   rtx mem_set_list;
317
318   /* If non-null, record the set of registers set unconditionally in the
319      basic block.  */
320   regset local_set;
321
322   /* If non-null, record the set of registers set conditionally in the
323      basic block.  */
324   regset cond_local_set;
325
326 #ifdef HAVE_conditional_execution
327   /* Indexed by register number, holds a reg_cond_life_info for each
328      register that is not unconditionally live or dead.  */
329   splay_tree reg_cond_dead;
330
331   /* Bit N is set if register N is in an expression in reg_cond_dead.  */
332   regset reg_cond_reg;
333 #endif
334
335   /* The length of mem_set_list.  */
336   int mem_set_list_len;
337
338   /* Non-zero if the value of CC0 is live.  */
339   int cc0_live;
340
341   /* Flags controling the set of information propagate_block collects.  */
342   int flags;
343 };
344
345 /* Maximum length of pbi->mem_set_list before we start dropping
346    new elements on the floor.  */
347 #define MAX_MEM_SET_LIST_LEN    100
348
349 /* Store the data structures necessary for depth-first search.  */
350 struct depth_first_search_dsS {
351   /* stack for backtracking during the algorithm */
352   basic_block *stack;
353
354   /* number of edges in the stack.  That is, positions 0, ..., sp-1
355      have edges.  */
356   unsigned int sp;
357
358   /* record of basic blocks already seen by depth-first search */
359   sbitmap visited_blocks;
360 };
361 typedef struct depth_first_search_dsS *depth_first_search_ds;
362
363 /* Have print_rtl_and_abort give the same information that fancy_abort
364    does.  */
365 #define print_rtl_and_abort() \
366   print_rtl_and_abort_fcn (__FILE__, __LINE__, __FUNCTION__)
367
368 /* Forward declarations */
369 static bool try_crossjump_to_edge       PARAMS ((int, edge, edge));
370 static bool try_crossjump_bb            PARAMS ((int, basic_block));
371 static bool outgoing_edges_match        PARAMS ((basic_block, basic_block));
372 static int flow_find_cross_jump         PARAMS ((int, basic_block, basic_block,
373                                                  rtx *, rtx *));
374 static int count_basic_blocks           PARAMS ((rtx));
375 static void find_basic_blocks_1         PARAMS ((rtx));
376 static rtx find_label_refs              PARAMS ((rtx, rtx));
377 static void make_edges                  PARAMS ((rtx));
378 static void make_label_edge             PARAMS ((sbitmap *, basic_block,
379                                                  rtx, int));
380 static void make_eh_edge                PARAMS ((sbitmap *, basic_block, rtx));
381
382 static void commit_one_edge_insertion   PARAMS ((edge));
383
384 static void delete_unreachable_blocks   PARAMS ((void));
385 static int can_delete_note_p            PARAMS ((rtx));
386 static void expunge_block               PARAMS ((basic_block));
387 static int can_delete_label_p           PARAMS ((rtx));
388 static int tail_recursion_label_p       PARAMS ((rtx));
389 static int merge_blocks_move_predecessor_nojumps PARAMS ((basic_block,
390                                                           basic_block));
391 static int merge_blocks_move_successor_nojumps PARAMS ((basic_block,
392                                                         basic_block));
393 static int merge_blocks                 PARAMS ((edge,basic_block,basic_block,
394                                                  int));
395 static bool try_optimize_cfg            PARAMS ((int));
396 static bool can_fallthru                PARAMS ((basic_block, basic_block));
397 static bool try_redirect_by_replacing_jump PARAMS ((edge, basic_block));
398 static bool try_simplify_condjump       PARAMS ((basic_block));
399 static bool try_forward_edges           PARAMS ((basic_block));
400 static void tidy_fallthru_edges         PARAMS ((void));
401 static int verify_wide_reg_1            PARAMS ((rtx *, void *));
402 static void verify_wide_reg             PARAMS ((int, rtx, rtx));
403 static void verify_local_live_at_start  PARAMS ((regset, basic_block));
404 static int noop_move_p                  PARAMS ((rtx));
405 static void delete_noop_moves           PARAMS ((rtx));
406 static void notice_stack_pointer_modification_1 PARAMS ((rtx, rtx, void *));
407 static void notice_stack_pointer_modification PARAMS ((rtx));
408 static void mark_reg                    PARAMS ((rtx, void *));
409 static void mark_regs_live_at_end       PARAMS ((regset));
410 static int set_phi_alternative_reg      PARAMS ((rtx, int, int, void *));
411 static void calculate_global_regs_live  PARAMS ((sbitmap, sbitmap, int));
412 static void propagate_block_delete_insn PARAMS ((basic_block, rtx));
413 static rtx propagate_block_delete_libcall PARAMS ((basic_block, rtx, rtx));
414 static int insn_dead_p                  PARAMS ((struct propagate_block_info *,
415                                                  rtx, int, rtx));
416 static int libcall_dead_p               PARAMS ((struct propagate_block_info *,
417                                                  rtx, rtx));
418 static void mark_set_regs               PARAMS ((struct propagate_block_info *,
419                                                  rtx, rtx));
420 static void mark_set_1                  PARAMS ((struct propagate_block_info *,
421                                                  enum rtx_code, rtx, rtx,
422                                                  rtx, int));
423 #ifdef HAVE_conditional_execution
424 static int mark_regno_cond_dead         PARAMS ((struct propagate_block_info *,
425                                                  int, rtx));
426 static void free_reg_cond_life_info     PARAMS ((splay_tree_value));
427 static int flush_reg_cond_reg_1         PARAMS ((splay_tree_node, void *));
428 static void flush_reg_cond_reg          PARAMS ((struct propagate_block_info *,
429                                                  int));
430 static rtx elim_reg_cond                PARAMS ((rtx, unsigned int));
431 static rtx ior_reg_cond                 PARAMS ((rtx, rtx, int));
432 static rtx not_reg_cond                 PARAMS ((rtx));
433 static rtx and_reg_cond                 PARAMS ((rtx, rtx, int));
434 #endif
435 #ifdef AUTO_INC_DEC
436 static void attempt_auto_inc            PARAMS ((struct propagate_block_info *,
437                                                  rtx, rtx, rtx, rtx, rtx));
438 static void find_auto_inc               PARAMS ((struct propagate_block_info *,
439                                                  rtx, rtx));
440 static int try_pre_increment_1          PARAMS ((struct propagate_block_info *,
441                                                  rtx));
442 static int try_pre_increment            PARAMS ((rtx, rtx, HOST_WIDE_INT));
443 #endif
444 static void mark_used_reg               PARAMS ((struct propagate_block_info *,
445                                                  rtx, rtx, rtx));
446 static void mark_used_regs              PARAMS ((struct propagate_block_info *,
447                                                  rtx, rtx, rtx));
448 void dump_flow_info                     PARAMS ((FILE *));
449 void debug_flow_info                    PARAMS ((void));
450 static void print_rtl_and_abort_fcn     PARAMS ((const char *, int,
451                                                  const char *))
452                                         ATTRIBUTE_NORETURN;
453
454 static void invalidate_mems_from_autoinc PARAMS ((struct propagate_block_info *,
455                                                   rtx));
456 static void invalidate_mems_from_set    PARAMS ((struct propagate_block_info *,
457                                                  rtx));
458 static void remove_fake_successors      PARAMS ((basic_block));
459 static void flow_nodes_print            PARAMS ((const char *, const sbitmap,
460                                                  FILE *));
461 static void flow_edge_list_print        PARAMS ((const char *, const edge *,
462                                                  int, FILE *));
463 static void flow_loops_cfg_dump         PARAMS ((const struct loops *,
464                                                  FILE *));
465 static int flow_loop_nested_p           PARAMS ((struct loop *,
466                                                  struct loop *));
467 static int flow_loop_entry_edges_find   PARAMS ((basic_block, const sbitmap,
468                                                  edge **));
469 static int flow_loop_exit_edges_find    PARAMS ((const sbitmap, edge **));
470 static int flow_loop_nodes_find PARAMS ((basic_block, basic_block, sbitmap));
471 static void flow_dfs_compute_reverse_init
472   PARAMS ((depth_first_search_ds));
473 static void flow_dfs_compute_reverse_add_bb
474   PARAMS ((depth_first_search_ds, basic_block));
475 static basic_block flow_dfs_compute_reverse_execute
476   PARAMS ((depth_first_search_ds));
477 static void flow_dfs_compute_reverse_finish
478   PARAMS ((depth_first_search_ds));
479 static void flow_loop_pre_header_scan PARAMS ((struct loop *));
480 static basic_block flow_loop_pre_header_find PARAMS ((basic_block,
481                                                       const sbitmap *));
482 static void flow_loop_tree_node_add     PARAMS ((struct loop *, struct loop *));
483 static void flow_loops_tree_build       PARAMS ((struct loops *));
484 static int flow_loop_level_compute      PARAMS ((struct loop *, int));
485 static int flow_loops_level_compute     PARAMS ((struct loops *));
486 static void find_sub_basic_blocks       PARAMS ((basic_block));
487 \f
488 /* Find basic blocks of the current function.
489    F is the first insn of the function and NREGS the number of register
490    numbers in use.  */
491
492 void
493 find_basic_blocks (f, nregs, file)
494      rtx f;
495      int nregs ATTRIBUTE_UNUSED;
496      FILE *file ATTRIBUTE_UNUSED;
497 {
498   int max_uid;
499   timevar_push (TV_CFG);
500
501   /* Flush out existing data.  */
502   if (basic_block_info != NULL)
503     {
504       int i;
505
506       clear_edges ();
507
508       /* Clear bb->aux on all extant basic blocks.  We'll use this as a
509          tag for reuse during create_basic_block, just in case some pass
510          copies around basic block notes improperly.  */
511       for (i = 0; i < n_basic_blocks; ++i)
512         BASIC_BLOCK (i)->aux = NULL;
513
514       VARRAY_FREE (basic_block_info);
515     }
516
517   n_basic_blocks = count_basic_blocks (f);
518
519   /* Size the basic block table.  The actual structures will be allocated
520      by find_basic_blocks_1, since we want to keep the structure pointers
521      stable across calls to find_basic_blocks.  */
522   /* ??? This whole issue would be much simpler if we called find_basic_blocks
523      exactly once, and thereafter we don't have a single long chain of
524      instructions at all until close to the end of compilation when we
525      actually lay them out.  */
526
527   VARRAY_BB_INIT (basic_block_info, n_basic_blocks, "basic_block_info");
528
529   find_basic_blocks_1 (f);
530
531   /* Record the block to which an insn belongs.  */
532   /* ??? This should be done another way, by which (perhaps) a label is
533      tagged directly with the basic block that it starts.  It is used for
534      more than that currently, but IMO that is the only valid use.  */
535
536   max_uid = get_max_uid ();
537 #ifdef AUTO_INC_DEC
538   /* Leave space for insns life_analysis makes in some cases for auto-inc.
539      These cases are rare, so we don't need too much space.  */
540   max_uid += max_uid / 10;
541 #endif
542
543   compute_bb_for_insn (max_uid);
544
545   /* Discover the edges of our cfg.  */
546   make_edges (label_value_list);
547
548   /* Do very simple cleanup now, for the benefit of code that runs between
549      here and cleanup_cfg, e.g. thread_prologue_and_epilogue_insns.  */
550   tidy_fallthru_edges ();
551
552   mark_critical_edges ();
553
554 #ifdef ENABLE_CHECKING
555   verify_flow_info ();
556 #endif
557   timevar_pop (TV_CFG);
558 }
559
560 void
561 check_function_return_warnings ()
562 {
563   if (warn_missing_noreturn
564       && !TREE_THIS_VOLATILE (cfun->decl)
565       && EXIT_BLOCK_PTR->pred == NULL
566       && (lang_missing_noreturn_ok_p
567           && !lang_missing_noreturn_ok_p (cfun->decl)))
568     warning ("function might be possible candidate for attribute `noreturn'");
569
570   /* If we have a path to EXIT, then we do return.  */
571   if (TREE_THIS_VOLATILE (cfun->decl)
572       && EXIT_BLOCK_PTR->pred != NULL)
573     warning ("`noreturn' function does return");
574
575   /* If the clobber_return_insn appears in some basic block, then we
576      do reach the end without returning a value.  */
577   else if (warn_return_type
578            && cfun->x_clobber_return_insn != NULL
579            && EXIT_BLOCK_PTR->pred != NULL)
580     {
581       int max_uid = get_max_uid ();
582
583       /* If clobber_return_insn was excised by jump1, then renumber_insns
584          can make max_uid smaller than the number still recorded in our rtx.
585          That's fine, since this is a quick way of verifying that the insn
586          is no longer in the chain.  */
587       if (INSN_UID (cfun->x_clobber_return_insn) < max_uid)
588         {
589           /* Recompute insn->block mapping, since the initial mapping is
590              set before we delete unreachable blocks.  */
591           compute_bb_for_insn (max_uid);
592
593           if (BLOCK_FOR_INSN (cfun->x_clobber_return_insn) != NULL)
594             warning ("control reaches end of non-void function");
595         }
596     }
597 }
598
599 /* Count the basic blocks of the function.  */
600
601 static int
602 count_basic_blocks (f)
603      rtx f;
604 {
605   register rtx insn;
606   register RTX_CODE prev_code;
607   register int count = 0;
608   int saw_abnormal_edge = 0;
609
610   prev_code = JUMP_INSN;
611   for (insn = f; insn; insn = NEXT_INSN (insn))
612     {
613       enum rtx_code code = GET_CODE (insn);
614
615       if (code == CODE_LABEL
616           || (GET_RTX_CLASS (code) == 'i'
617               && (prev_code == JUMP_INSN
618                   || prev_code == BARRIER
619                   || saw_abnormal_edge)))
620         {
621           saw_abnormal_edge = 0;
622           count++;
623         }
624
625       /* Record whether this insn created an edge.  */
626       if (code == CALL_INSN)
627         {
628           rtx note;
629
630           /* If there is a nonlocal goto label and the specified
631              region number isn't -1, we have an edge.  */
632           if (nonlocal_goto_handler_labels
633               && ((note = find_reg_note (insn, REG_EH_REGION, NULL_RTX)) == 0
634                   || INTVAL (XEXP (note, 0)) >= 0))
635             saw_abnormal_edge = 1;
636
637           else if (can_throw_internal (insn))
638             saw_abnormal_edge = 1;
639         }
640       else if (flag_non_call_exceptions
641                && code == INSN
642                && can_throw_internal (insn))
643         saw_abnormal_edge = 1;
644
645       if (code != NOTE)
646         prev_code = code;
647     }
648
649   /* The rest of the compiler works a bit smoother when we don't have to
650      check for the edge case of do-nothing functions with no basic blocks.  */
651   if (count == 0)
652     {
653       emit_insn (gen_rtx_USE (VOIDmode, const0_rtx));
654       count = 1;
655     }
656
657   return count;
658 }
659
660 /* Scan a list of insns for labels referred to other than by jumps.
661    This is used to scan the alternatives of a call placeholder.  */
662 static rtx
663 find_label_refs (f, lvl)
664      rtx f;
665      rtx lvl;
666 {
667   rtx insn;
668
669   for (insn = f; insn; insn = NEXT_INSN (insn))
670     if (INSN_P (insn) && GET_CODE (insn) != JUMP_INSN)
671       {
672         rtx note;
673
674         /* Make a list of all labels referred to other than by jumps
675            (which just don't have the REG_LABEL notes).
676
677            Make a special exception for labels followed by an ADDR*VEC,
678            as this would be a part of the tablejump setup code.
679
680            Make a special exception to registers loaded with label
681            values just before jump insns that use them.  */
682
683         for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
684           if (REG_NOTE_KIND (note) == REG_LABEL)
685             {
686               rtx lab = XEXP (note, 0), next;
687
688               if ((next = next_nonnote_insn (lab)) != NULL
689                        && GET_CODE (next) == JUMP_INSN
690                        && (GET_CODE (PATTERN (next)) == ADDR_VEC
691                            || GET_CODE (PATTERN (next)) == ADDR_DIFF_VEC))
692                 ;
693               else if (GET_CODE (lab) == NOTE)
694                 ;
695               else if (GET_CODE (NEXT_INSN (insn)) == JUMP_INSN
696                        && find_reg_note (NEXT_INSN (insn), REG_LABEL, lab))
697                 ;
698               else
699                 lvl = alloc_EXPR_LIST (0, XEXP (note, 0), lvl);
700             }
701       }
702
703   return lvl;
704 }
705
706 /* Assume that someone emitted code with control flow instructions to the
707    basic block.  Update the data structure.  */
708 static void
709 find_sub_basic_blocks (bb)
710      basic_block bb;
711 {
712   rtx first_insn = bb->head, insn;
713   rtx end = bb->end;
714   edge succ_list = bb->succ;
715   rtx jump_insn = NULL_RTX;
716   int created = 0;
717   int barrier = 0;
718   edge falltru = 0;
719   basic_block first_bb = bb, last_bb;
720   int i;
721
722   if (GET_CODE (first_insn) == LABEL_REF)
723     first_insn = NEXT_INSN (first_insn);
724   first_insn = NEXT_INSN (first_insn);
725   bb->succ = NULL;
726
727   insn = first_insn;
728   /* Scan insn chain and try to find new basic block boundaries.  */
729   while (insn != end)
730     {
731       enum rtx_code code = GET_CODE (insn);
732       switch (code)
733         {
734         case JUMP_INSN:
735           /* We need some special care for those expressions.  */
736           if (GET_CODE (PATTERN (insn)) == ADDR_VEC
737               || GET_CODE (PATTERN (insn)) == ADDR_DIFF_VEC)
738             abort();
739           jump_insn = insn;
740           break;
741         case BARRIER:
742           if (!jump_insn)
743             abort ();
744           barrier = 1;
745           break;
746         /* On code label, split current basic block.  */
747         case CODE_LABEL:
748           falltru = split_block (bb, PREV_INSN (insn));
749           if (jump_insn)
750             bb->end = jump_insn;
751           bb = falltru->dest;
752           if (barrier)
753             remove_edge (falltru);
754           barrier = 0;
755           jump_insn = 0;
756           created = 1;
757           if (LABEL_ALTERNATE_NAME (insn))
758             make_edge (NULL, ENTRY_BLOCK_PTR, bb, 0);
759           break;
760         case INSN:
761           /* In case we've previously split insn on the JUMP_INSN, move the
762              block header to proper place.  */
763           if (jump_insn)
764             {
765               falltru = split_block (bb, PREV_INSN (insn));
766               bb->end = jump_insn;
767               bb = falltru->dest;
768               if (barrier)
769                 abort ();
770               jump_insn = 0;
771             }
772         default:
773           break;
774         }
775       insn = NEXT_INSN (insn);
776     }
777   /* Last basic block must end in the original BB end.  */
778   if (jump_insn)
779     abort ();
780
781   /* Wire in the original edges for last basic block.  */
782   if (created)
783     {
784       bb->succ = succ_list;
785       while (succ_list)
786         succ_list->src = bb, succ_list = succ_list->succ_next;
787     }
788   else
789     bb->succ = succ_list;
790
791   /* Now re-scan and wire in all edges.  This expect simple (conditional)
792      jumps at the end of each new basic blocks.  */
793   last_bb = bb;
794   for (i = first_bb->index; i < last_bb->index; i++)
795     {
796       bb = BASIC_BLOCK (i);
797       if (GET_CODE (bb->end) == JUMP_INSN)
798         {
799           mark_jump_label (PATTERN (bb->end), bb->end, 0);
800           make_label_edge (NULL, bb, JUMP_LABEL (bb->end), 0);
801         }
802       insn = NEXT_INSN (insn);
803     }
804 }
805
806 /* Find all basic blocks of the function whose first insn is F.
807
808    Collect and return a list of labels whose addresses are taken.  This
809    will be used in make_edges for use with computed gotos.  */
810
811 static void
812 find_basic_blocks_1 (f)
813      rtx f;
814 {
815   register rtx insn, next;
816   int i = 0;
817   rtx bb_note = NULL_RTX;
818   rtx lvl = NULL_RTX;
819   rtx trll = NULL_RTX;
820   rtx head = NULL_RTX;
821   rtx end = NULL_RTX;
822
823   /* We process the instructions in a slightly different way than we did
824      previously.  This is so that we see a NOTE_BASIC_BLOCK after we have
825      closed out the previous block, so that it gets attached at the proper
826      place.  Since this form should be equivalent to the previous,
827      count_basic_blocks continues to use the old form as a check.  */
828
829   for (insn = f; insn; insn = next)
830     {
831       enum rtx_code code = GET_CODE (insn);
832
833       next = NEXT_INSN (insn);
834
835       switch (code)
836         {
837         case NOTE:
838           {
839             int kind = NOTE_LINE_NUMBER (insn);
840
841             /* Look for basic block notes with which to keep the
842                basic_block_info pointers stable.  Unthread the note now;
843                we'll put it back at the right place in create_basic_block.
844                Or not at all if we've already found a note in this block.  */
845             if (kind == NOTE_INSN_BASIC_BLOCK)
846               {
847                 if (bb_note == NULL_RTX)
848                   bb_note = insn;
849                 else
850                   next = flow_delete_insn (insn);
851               }
852             break;
853           }
854
855         case CODE_LABEL:
856           /* A basic block starts at a label.  If we've closed one off due
857              to a barrier or some such, no need to do it again.  */
858           if (head != NULL_RTX)
859             {
860               create_basic_block (i++, head, end, bb_note);
861               bb_note = NULL_RTX;
862             }
863
864           head = end = insn;
865           break;
866
867         case JUMP_INSN:
868           /* A basic block ends at a jump.  */
869           if (head == NULL_RTX)
870             head = insn;
871           else
872             {
873               /* ??? Make a special check for table jumps.  The way this
874                  happens is truly and amazingly gross.  We are about to
875                  create a basic block that contains just a code label and
876                  an addr*vec jump insn.  Worse, an addr_diff_vec creates
877                  its own natural loop.
878
879                  Prevent this bit of brain damage, pasting things together
880                  correctly in make_edges.
881
882                  The correct solution involves emitting the table directly
883                  on the tablejump instruction as a note, or JUMP_LABEL.  */
884
885               if (GET_CODE (PATTERN (insn)) == ADDR_VEC
886                   || GET_CODE (PATTERN (insn)) == ADDR_DIFF_VEC)
887                 {
888                   head = end = NULL;
889                   n_basic_blocks--;
890                   break;
891                 }
892             }
893           end = insn;
894           goto new_bb_inclusive;
895
896         case BARRIER:
897           /* A basic block ends at a barrier.  It may be that an unconditional
898              jump already closed the basic block -- no need to do it again.  */
899           if (head == NULL_RTX)
900             break;
901           goto new_bb_exclusive;
902
903         case CALL_INSN:
904           {
905             /* Record whether this call created an edge.  */
906             rtx note = find_reg_note (insn, REG_EH_REGION, NULL_RTX);
907             int region = (note ? INTVAL (XEXP (note, 0)) : 0);
908
909             if (GET_CODE (PATTERN (insn)) == CALL_PLACEHOLDER)
910               {
911                 /* Scan each of the alternatives for label refs.  */
912                 lvl = find_label_refs (XEXP (PATTERN (insn), 0), lvl);
913                 lvl = find_label_refs (XEXP (PATTERN (insn), 1), lvl);
914                 lvl = find_label_refs (XEXP (PATTERN (insn), 2), lvl);
915                 /* Record its tail recursion label, if any.  */
916                 if (XEXP (PATTERN (insn), 3) != NULL_RTX)
917                   trll = alloc_EXPR_LIST (0, XEXP (PATTERN (insn), 3), trll);
918               }
919
920             /* A basic block ends at a call that can either throw or
921                do a non-local goto.  */
922             if ((nonlocal_goto_handler_labels && region >= 0)
923                 || can_throw_internal (insn))
924               {
925               new_bb_inclusive:
926                 if (head == NULL_RTX)
927                   head = insn;
928                 end = insn;
929
930               new_bb_exclusive:
931                 create_basic_block (i++, head, end, bb_note);
932                 head = end = NULL_RTX;
933                 bb_note = NULL_RTX;
934                 break;
935               }
936           }
937           /* Fall through.  */
938
939         case INSN:
940           /* Non-call exceptions generate new blocks just like calls.  */
941           if (flag_non_call_exceptions && can_throw_internal (insn))
942             goto new_bb_inclusive;
943
944           if (head == NULL_RTX)
945             head = insn;
946           end = insn;
947           break;
948
949         default:
950           abort ();
951         }
952
953       if (GET_CODE (insn) == INSN || GET_CODE (insn) == CALL_INSN)
954         {
955           rtx note;
956
957           /* Make a list of all labels referred to other than by jumps.
958
959              Make a special exception for labels followed by an ADDR*VEC,
960              as this would be a part of the tablejump setup code.
961
962              Make a special exception to registers loaded with label
963              values just before jump insns that use them.  */
964
965           for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
966             if (REG_NOTE_KIND (note) == REG_LABEL)
967               {
968                 rtx lab = XEXP (note, 0), next;
969
970                 if ((next = next_nonnote_insn (lab)) != NULL
971                          && GET_CODE (next) == JUMP_INSN
972                          && (GET_CODE (PATTERN (next)) == ADDR_VEC
973                              || GET_CODE (PATTERN (next)) == ADDR_DIFF_VEC))
974                   ;
975                 else if (GET_CODE (lab) == NOTE)
976                   ;
977                 else if (GET_CODE (NEXT_INSN (insn)) == JUMP_INSN
978                          && find_reg_note (NEXT_INSN (insn), REG_LABEL, lab))
979                   ;
980                 else
981                   lvl = alloc_EXPR_LIST (0, XEXP (note, 0), lvl);
982               }
983         }
984     }
985
986   if (head != NULL_RTX)
987     create_basic_block (i++, head, end, bb_note);
988   else if (bb_note)
989     flow_delete_insn (bb_note);
990
991   if (i != n_basic_blocks)
992     abort ();
993
994   label_value_list = lvl;
995   tail_recursion_label_list = trll;
996 }
997
998 /* Tidy the CFG by deleting unreachable code and whatnot.  */
999
1000 void
1001 cleanup_cfg (mode)
1002      int mode;
1003 {
1004   timevar_push (TV_CLEANUP_CFG);
1005   delete_unreachable_blocks ();
1006   if (try_optimize_cfg (mode))
1007     delete_unreachable_blocks ();
1008   mark_critical_edges ();
1009
1010   /* Kill the data we won't maintain.  */
1011   free_EXPR_LIST_list (&label_value_list);
1012   free_EXPR_LIST_list (&tail_recursion_label_list);
1013   timevar_pop (TV_CLEANUP_CFG);
1014 }
1015
1016 /* Create a new basic block consisting of the instructions between
1017    HEAD and END inclusive.  Reuses the note and basic block struct
1018    in BB_NOTE, if any.  */
1019
1020 void
1021 create_basic_block (index, head, end, bb_note)
1022      int index;
1023      rtx head, end, bb_note;
1024 {
1025   basic_block bb;
1026
1027   if (bb_note
1028       && ! RTX_INTEGRATED_P (bb_note)
1029       && (bb = NOTE_BASIC_BLOCK (bb_note)) != NULL
1030       && bb->aux == NULL)
1031     {
1032       /* If we found an existing note, thread it back onto the chain.  */
1033
1034       rtx after;
1035
1036       if (GET_CODE (head) == CODE_LABEL)
1037         after = head;
1038       else
1039         {
1040           after = PREV_INSN (head);
1041           head = bb_note;
1042         }
1043
1044       if (after != bb_note && NEXT_INSN (after) != bb_note)
1045         reorder_insns (bb_note, bb_note, after);
1046     }
1047   else
1048     {
1049       /* Otherwise we must create a note and a basic block structure.
1050          Since we allow basic block structs in rtl, give the struct
1051          the same lifetime by allocating it off the function obstack
1052          rather than using malloc.  */
1053
1054       bb = (basic_block) obstack_alloc (&flow_obstack, sizeof (*bb));
1055       memset (bb, 0, sizeof (*bb));
1056
1057       if (GET_CODE (head) == CODE_LABEL)
1058         bb_note = emit_note_after (NOTE_INSN_BASIC_BLOCK, head);
1059       else
1060         {
1061           bb_note = emit_note_before (NOTE_INSN_BASIC_BLOCK, head);
1062           head = bb_note;
1063         }
1064       NOTE_BASIC_BLOCK (bb_note) = bb;
1065     }
1066
1067   /* Always include the bb note in the block.  */
1068   if (NEXT_INSN (end) == bb_note)
1069     end = bb_note;
1070
1071   bb->head = head;
1072   bb->end = end;
1073   bb->index = index;
1074   BASIC_BLOCK (index) = bb;
1075
1076   /* Tag the block so that we know it has been used when considering
1077      other basic block notes.  */
1078   bb->aux = bb;
1079 }
1080 \f
1081 /* Return the INSN immediately following the NOTE_INSN_BASIC_BLOCK
1082    note associated with the BLOCK.  */
1083
1084 rtx
1085 first_insn_after_basic_block_note (block)
1086      basic_block block;
1087 {
1088   rtx insn;
1089
1090   /* Get the first instruction in the block.  */
1091   insn = block->head;
1092
1093   if (insn == NULL_RTX)
1094     return NULL_RTX;
1095   if (GET_CODE (insn) == CODE_LABEL)
1096     insn = NEXT_INSN (insn);
1097   if (!NOTE_INSN_BASIC_BLOCK_P (insn))
1098     abort ();
1099
1100   return NEXT_INSN (insn);
1101 }
1102
1103 /* Records the basic block struct in BB_FOR_INSN, for every instruction
1104    indexed by INSN_UID.  MAX is the size of the array.  */
1105
1106 void
1107 compute_bb_for_insn (max)
1108      int max;
1109 {
1110   int i;
1111
1112   if (basic_block_for_insn)
1113     VARRAY_FREE (basic_block_for_insn);
1114   VARRAY_BB_INIT (basic_block_for_insn, max, "basic_block_for_insn");
1115
1116   for (i = 0; i < n_basic_blocks; ++i)
1117     {
1118       basic_block bb = BASIC_BLOCK (i);
1119       rtx insn, end;
1120
1121       end = bb->end;
1122       insn = bb->head;
1123       while (1)
1124         {
1125           int uid = INSN_UID (insn);
1126           if (uid < max)
1127             VARRAY_BB (basic_block_for_insn, uid) = bb;
1128           if (insn == end)
1129             break;
1130           insn = NEXT_INSN (insn);
1131         }
1132     }
1133 }
1134
1135 /* Free the memory associated with the edge structures.  */
1136
1137 void
1138 clear_edges ()
1139 {
1140   int i;
1141   edge n, e;
1142
1143   for (i = 0; i < n_basic_blocks; ++i)
1144     {
1145       basic_block bb = BASIC_BLOCK (i);
1146
1147       for (e = bb->succ; e; e = n)
1148         {
1149           n = e->succ_next;
1150           free (e);
1151         }
1152
1153       bb->succ = 0;
1154       bb->pred = 0;
1155     }
1156
1157   for (e = ENTRY_BLOCK_PTR->succ; e; e = n)
1158     {
1159       n = e->succ_next;
1160       free (e);
1161     }
1162
1163   ENTRY_BLOCK_PTR->succ = 0;
1164   EXIT_BLOCK_PTR->pred = 0;
1165
1166   n_edges = 0;
1167 }
1168
1169 /* Identify the edges between basic blocks.
1170
1171    NONLOCAL_LABEL_LIST is a list of non-local labels in the function.  Blocks
1172    that are otherwise unreachable may be reachable with a non-local goto.
1173
1174    BB_EH_END is an array indexed by basic block number in which we record
1175    the list of exception regions active at the end of the basic block.  */
1176
1177 static void
1178 make_edges (label_value_list)
1179      rtx label_value_list;
1180 {
1181   int i;
1182   sbitmap *edge_cache = NULL;
1183
1184   /* Assume no computed jump; revise as we create edges.  */
1185   current_function_has_computed_jump = 0;
1186
1187   /* Heavy use of computed goto in machine-generated code can lead to
1188      nearly fully-connected CFGs.  In that case we spend a significant
1189      amount of time searching the edge lists for duplicates.  */
1190   if (forced_labels || label_value_list)
1191     {
1192       edge_cache = sbitmap_vector_alloc (n_basic_blocks, n_basic_blocks);
1193       sbitmap_vector_zero (edge_cache, n_basic_blocks);
1194     }
1195
1196   /* By nature of the way these get numbered, block 0 is always the entry.  */
1197   make_edge (edge_cache, ENTRY_BLOCK_PTR, BASIC_BLOCK (0), EDGE_FALLTHRU);
1198
1199   for (i = 0; i < n_basic_blocks; ++i)
1200     {
1201       basic_block bb = BASIC_BLOCK (i);
1202       rtx insn, x;
1203       enum rtx_code code;
1204       int force_fallthru = 0;
1205
1206       if (GET_CODE (bb->head) == CODE_LABEL
1207           && LABEL_ALTERNATE_NAME (bb->head))
1208         make_edge (NULL, ENTRY_BLOCK_PTR, bb, 0);
1209
1210       /* Examine the last instruction of the block, and discover the
1211          ways we can leave the block.  */
1212
1213       insn = bb->end;
1214       code = GET_CODE (insn);
1215
1216       /* A branch.  */
1217       if (code == JUMP_INSN)
1218         {
1219           rtx tmp;
1220
1221           /* Recognize exception handling placeholders.  */
1222           if (GET_CODE (PATTERN (insn)) == RESX)
1223             make_eh_edge (edge_cache, bb, insn);
1224
1225           /* Recognize a non-local goto as a branch outside the
1226              current function.  */
1227           else if (find_reg_note (insn, REG_NON_LOCAL_GOTO, NULL_RTX))
1228             ;
1229
1230           /* ??? Recognize a tablejump and do the right thing.  */
1231           else if ((tmp = JUMP_LABEL (insn)) != NULL_RTX
1232                    && (tmp = NEXT_INSN (tmp)) != NULL_RTX
1233                    && GET_CODE (tmp) == JUMP_INSN
1234                    && (GET_CODE (PATTERN (tmp)) == ADDR_VEC
1235                        || GET_CODE (PATTERN (tmp)) == ADDR_DIFF_VEC))
1236             {
1237               rtvec vec;
1238               int j;
1239
1240               if (GET_CODE (PATTERN (tmp)) == ADDR_VEC)
1241                 vec = XVEC (PATTERN (tmp), 0);
1242               else
1243                 vec = XVEC (PATTERN (tmp), 1);
1244
1245               for (j = GET_NUM_ELEM (vec) - 1; j >= 0; --j)
1246                 make_label_edge (edge_cache, bb,
1247                                  XEXP (RTVEC_ELT (vec, j), 0), 0);
1248
1249               /* Some targets (eg, ARM) emit a conditional jump that also
1250                  contains the out-of-range target.  Scan for these and
1251                  add an edge if necessary.  */
1252               if ((tmp = single_set (insn)) != NULL
1253                   && SET_DEST (tmp) == pc_rtx
1254                   && GET_CODE (SET_SRC (tmp)) == IF_THEN_ELSE
1255                   && GET_CODE (XEXP (SET_SRC (tmp), 2)) == LABEL_REF)
1256                 make_label_edge (edge_cache, bb,
1257                                  XEXP (XEXP (SET_SRC (tmp), 2), 0), 0);
1258
1259 #ifdef CASE_DROPS_THROUGH
1260               /* Silly VAXen.  The ADDR_VEC is going to be in the way of
1261                  us naturally detecting fallthru into the next block.  */
1262               force_fallthru = 1;
1263 #endif
1264             }
1265
1266           /* If this is a computed jump, then mark it as reaching
1267              everything on the label_value_list and forced_labels list.  */
1268           else if (computed_jump_p (insn))
1269             {
1270               current_function_has_computed_jump = 1;
1271
1272               for (x = label_value_list; x; x = XEXP (x, 1))
1273                 make_label_edge (edge_cache, bb, XEXP (x, 0), EDGE_ABNORMAL);
1274
1275               for (x = forced_labels; x; x = XEXP (x, 1))
1276                 make_label_edge (edge_cache, bb, XEXP (x, 0), EDGE_ABNORMAL);
1277             }
1278
1279           /* Returns create an exit out.  */
1280           else if (returnjump_p (insn))
1281             make_edge (edge_cache, bb, EXIT_BLOCK_PTR, 0);
1282
1283           /* Otherwise, we have a plain conditional or unconditional jump.  */
1284           else
1285             {
1286               if (! JUMP_LABEL (insn))
1287                 abort ();
1288               make_label_edge (edge_cache, bb, JUMP_LABEL (insn), 0);
1289             }
1290         }
1291
1292       /* If this is a sibling call insn, then this is in effect a
1293          combined call and return, and so we need an edge to the
1294          exit block.  No need to worry about EH edges, since we
1295          wouldn't have created the sibling call in the first place.  */
1296
1297       if (code == CALL_INSN && SIBLING_CALL_P (insn))
1298         make_edge (edge_cache, bb, EXIT_BLOCK_PTR,
1299                    EDGE_ABNORMAL | EDGE_ABNORMAL_CALL);
1300
1301       /* If this is a CALL_INSN, then mark it as reaching the active EH
1302          handler for this CALL_INSN.  If we're handling non-call
1303          exceptions then any insn can reach any of the active handlers.
1304
1305          Also mark the CALL_INSN as reaching any nonlocal goto handler.  */
1306
1307       else if (code == CALL_INSN || flag_non_call_exceptions)
1308         {
1309           /* Add any appropriate EH edges.  */
1310           make_eh_edge (edge_cache, bb, insn);
1311
1312           if (code == CALL_INSN && nonlocal_goto_handler_labels)
1313             {
1314               /* ??? This could be made smarter: in some cases it's possible
1315                  to tell that certain calls will not do a nonlocal goto.
1316
1317                  For example, if the nested functions that do the nonlocal
1318                  gotos do not have their addresses taken, then only calls to
1319                  those functions or to other nested functions that use them
1320                  could possibly do nonlocal gotos.  */
1321               /* We do know that a REG_EH_REGION note with a value less
1322                  than 0 is guaranteed not to perform a non-local goto.  */
1323               rtx note = find_reg_note (insn, REG_EH_REGION, NULL_RTX);
1324               if (!note || INTVAL (XEXP (note, 0)) >=  0)
1325                 for (x = nonlocal_goto_handler_labels; x; x = XEXP (x, 1))
1326                   make_label_edge (edge_cache, bb, XEXP (x, 0),
1327                                    EDGE_ABNORMAL | EDGE_ABNORMAL_CALL);
1328             }
1329         }
1330
1331       /* Find out if we can drop through to the next block.  */
1332       insn = next_nonnote_insn (insn);
1333       if (!insn || (i + 1 == n_basic_blocks && force_fallthru))
1334         make_edge (edge_cache, bb, EXIT_BLOCK_PTR, EDGE_FALLTHRU);
1335       else if (i + 1 < n_basic_blocks)
1336         {
1337           rtx tmp = BLOCK_HEAD (i + 1);
1338           if (GET_CODE (tmp) == NOTE)
1339             tmp = next_nonnote_insn (tmp);
1340           if (force_fallthru || insn == tmp)
1341             make_edge (edge_cache, bb, BASIC_BLOCK (i + 1), EDGE_FALLTHRU);
1342         }
1343     }
1344
1345   if (edge_cache)
1346     sbitmap_vector_free (edge_cache);
1347 }
1348
1349 /* Create an edge between two basic blocks.  FLAGS are auxiliary information
1350    about the edge that is accumulated between calls.  */
1351
1352 void
1353 make_edge (edge_cache, src, dst, flags)
1354      sbitmap *edge_cache;
1355      basic_block src, dst;
1356      int flags;
1357 {
1358   int use_edge_cache;
1359   edge e;
1360
1361   /* Don't bother with edge cache for ENTRY or EXIT; there aren't that
1362      many edges to them, and we didn't allocate memory for it.  */
1363   use_edge_cache = (edge_cache
1364                     && src != ENTRY_BLOCK_PTR
1365                     && dst != EXIT_BLOCK_PTR);
1366
1367   /* Make sure we don't add duplicate edges.  */
1368   switch (use_edge_cache)
1369     {
1370     default:
1371       /* Quick test for non-existance of the edge.  */
1372       if (! TEST_BIT (edge_cache[src->index], dst->index))
1373         break;
1374
1375       /* The edge exists; early exit if no work to do.  */
1376       if (flags == 0)
1377         return;
1378
1379       /* FALLTHRU */
1380     case 0:
1381       for (e = src->succ; e; e = e->succ_next)
1382         if (e->dest == dst)
1383           {
1384             e->flags |= flags;
1385             return;
1386           }
1387       break;
1388     }
1389
1390   e = (edge) xcalloc (1, sizeof (*e));
1391   n_edges++;
1392
1393   e->succ_next = src->succ;
1394   e->pred_next = dst->pred;
1395   e->src = src;
1396   e->dest = dst;
1397   e->flags = flags;
1398
1399   src->succ = e;
1400   dst->pred = e;
1401
1402   if (use_edge_cache)
1403     SET_BIT (edge_cache[src->index], dst->index);
1404 }
1405
1406 /* Create an edge from a basic block to a label.  */
1407
1408 static void
1409 make_label_edge (edge_cache, src, label, flags)
1410      sbitmap *edge_cache;
1411      basic_block src;
1412      rtx label;
1413      int flags;
1414 {
1415   if (GET_CODE (label) != CODE_LABEL)
1416     abort ();
1417
1418   /* If the label was never emitted, this insn is junk, but avoid a
1419      crash trying to refer to BLOCK_FOR_INSN (label).  This can happen
1420      as a result of a syntax error and a diagnostic has already been
1421      printed.  */
1422
1423   if (INSN_UID (label) == 0)
1424     return;
1425
1426   make_edge (edge_cache, src, BLOCK_FOR_INSN (label), flags);
1427 }
1428
1429 /* Create the edges generated by INSN in REGION.  */
1430
1431 static void
1432 make_eh_edge (edge_cache, src, insn)
1433      sbitmap *edge_cache;
1434      basic_block src;
1435      rtx insn;
1436 {
1437   int is_call = (GET_CODE (insn) == CALL_INSN ? EDGE_ABNORMAL_CALL : 0);
1438   rtx handlers, i;
1439
1440   handlers = reachable_handlers (insn);
1441
1442   for (i = handlers; i; i = XEXP (i, 1))
1443     make_label_edge (edge_cache, src, XEXP (i, 0),
1444                      EDGE_ABNORMAL | EDGE_EH | is_call);
1445
1446   free_INSN_LIST_list (&handlers);
1447 }
1448
1449 /* Identify critical edges and set the bits appropriately.  */
1450
1451 void
1452 mark_critical_edges ()
1453 {
1454   int i, n = n_basic_blocks;
1455   basic_block bb;
1456
1457   /* We begin with the entry block.  This is not terribly important now,
1458      but could be if a front end (Fortran) implemented alternate entry
1459      points.  */
1460   bb = ENTRY_BLOCK_PTR;
1461   i = -1;
1462
1463   while (1)
1464     {
1465       edge e;
1466
1467       /* (1) Critical edges must have a source with multiple successors.  */
1468       if (bb->succ && bb->succ->succ_next)
1469         {
1470           for (e = bb->succ; e; e = e->succ_next)
1471             {
1472               /* (2) Critical edges must have a destination with multiple
1473                  predecessors.  Note that we know there is at least one
1474                  predecessor -- the edge we followed to get here.  */
1475               if (e->dest->pred->pred_next)
1476                 e->flags |= EDGE_CRITICAL;
1477               else
1478                 e->flags &= ~EDGE_CRITICAL;
1479             }
1480         }
1481       else
1482         {
1483           for (e = bb->succ; e; e = e->succ_next)
1484             e->flags &= ~EDGE_CRITICAL;
1485         }
1486
1487       if (++i >= n)
1488         break;
1489       bb = BASIC_BLOCK (i);
1490     }
1491 }
1492 \f
1493 /* Split a block BB after insn INSN creating a new fallthru edge.
1494    Return the new edge.  Note that to keep other parts of the compiler happy,
1495    this function renumbers all the basic blocks so that the new
1496    one has a number one greater than the block split.  */
1497
1498 edge
1499 split_block (bb, insn)
1500      basic_block bb;
1501      rtx insn;
1502 {
1503   basic_block new_bb;
1504   edge new_edge;
1505   edge e;
1506   rtx bb_note;
1507   int i, j;
1508
1509   /* There is no point splitting the block after its end.  */
1510   if (bb->end == insn)
1511     return 0;
1512
1513   /* Create the new structures.  */
1514   new_bb = (basic_block) obstack_alloc (&flow_obstack, sizeof (*new_bb));
1515   new_edge = (edge) xcalloc (1, sizeof (*new_edge));
1516   n_edges++;
1517
1518   memset (new_bb, 0, sizeof (*new_bb));
1519
1520   new_bb->head = NEXT_INSN (insn);
1521   new_bb->end = bb->end;
1522   bb->end = insn;
1523
1524   new_bb->succ = bb->succ;
1525   bb->succ = new_edge;
1526   new_bb->pred = new_edge;
1527   new_bb->count = bb->count;
1528   new_bb->frequency = bb->frequency;
1529   new_bb->loop_depth = bb->loop_depth;
1530
1531   new_edge->src = bb;
1532   new_edge->dest = new_bb;
1533   new_edge->flags = EDGE_FALLTHRU;
1534   new_edge->probability = REG_BR_PROB_BASE;
1535   new_edge->count = bb->count;
1536
1537   /* Redirect the src of the successor edges of bb to point to new_bb.  */
1538   for (e = new_bb->succ; e; e = e->succ_next)
1539     e->src = new_bb;
1540
1541   /* Place the new block just after the block being split.  */
1542   VARRAY_GROW (basic_block_info, ++n_basic_blocks);
1543
1544   /* Some parts of the compiler expect blocks to be number in
1545      sequential order so insert the new block immediately after the
1546      block being split..  */
1547   j = bb->index;
1548   for (i = n_basic_blocks - 1; i > j + 1; --i)
1549     {
1550       basic_block tmp = BASIC_BLOCK (i - 1);
1551       BASIC_BLOCK (i) = tmp;
1552       tmp->index = i;
1553     }
1554
1555   BASIC_BLOCK (i) = new_bb;
1556   new_bb->index = i;
1557
1558   if (GET_CODE (new_bb->head) == CODE_LABEL)
1559     {
1560       /* Create the basic block note.  */
1561       bb_note = emit_note_after (NOTE_INSN_BASIC_BLOCK,
1562                                  new_bb->head);
1563       NOTE_BASIC_BLOCK (bb_note) = new_bb;
1564
1565       /* If the only thing in this new block was the label, make sure
1566          the block note gets included.  */
1567       if (new_bb->head == new_bb->end)
1568         new_bb->end = bb_note;
1569     }
1570   else
1571     {
1572       /* Create the basic block note.  */
1573       bb_note = emit_note_before (NOTE_INSN_BASIC_BLOCK,
1574                                   new_bb->head);
1575       NOTE_BASIC_BLOCK (bb_note) = new_bb;
1576       new_bb->head = bb_note;
1577     }
1578
1579   update_bb_for_insn (new_bb);
1580
1581   if (bb->global_live_at_start)
1582     {
1583       new_bb->global_live_at_start = OBSTACK_ALLOC_REG_SET (&flow_obstack);
1584       new_bb->global_live_at_end = OBSTACK_ALLOC_REG_SET (&flow_obstack);
1585       COPY_REG_SET (new_bb->global_live_at_end, bb->global_live_at_end);
1586
1587       /* We now have to calculate which registers are live at the end
1588          of the split basic block and at the start of the new basic
1589          block.  Start with those registers that are known to be live
1590          at the end of the original basic block and get
1591          propagate_block to determine which registers are live.  */
1592       COPY_REG_SET (new_bb->global_live_at_start, bb->global_live_at_end);
1593       propagate_block (new_bb, new_bb->global_live_at_start, NULL, NULL, 0);
1594       COPY_REG_SET (bb->global_live_at_end,
1595                     new_bb->global_live_at_start);
1596     }
1597
1598   return new_edge;
1599 }
1600
1601 /* Return label in the head of basic block.  Create one if it doesn't exist.  */
1602 rtx
1603 block_label (block)
1604      basic_block block;
1605 {
1606   if (block == EXIT_BLOCK_PTR)
1607     return NULL_RTX;
1608   if (GET_CODE (block->head) != CODE_LABEL)
1609     block->head = emit_label_before (gen_label_rtx (), block->head);
1610   return block->head;
1611 }
1612
1613 /* Return true if the block has no effect and only forwards control flow to
1614    its single destination.  */
1615 bool
1616 forwarder_block_p (bb)
1617      basic_block bb;
1618 {
1619   rtx insn = bb->head;
1620   if (bb == EXIT_BLOCK_PTR || bb == ENTRY_BLOCK_PTR
1621       || !bb->succ || bb->succ->succ_next)
1622     return false;
1623
1624   while (insn != bb->end)
1625     {
1626       if (active_insn_p (insn))
1627         return false;
1628       insn = NEXT_INSN (insn);
1629     }
1630   return (!active_insn_p (insn)
1631           || (GET_CODE (insn) == JUMP_INSN && onlyjump_p (insn)));
1632 }
1633
1634 /* Return nonzero if we can reach target from src by falling trought.  */
1635 static bool
1636 can_fallthru (src, target)
1637      basic_block src, target;
1638 {
1639   rtx insn = src->end;
1640   rtx insn2 = target->head;
1641
1642   if (src->index + 1 == target->index && !active_insn_p (insn2))
1643     insn2 = next_active_insn (insn2);
1644   /* ??? Later we may add code to move jump tables offline.  */
1645   return next_active_insn (insn) == insn2;
1646 }
1647
1648 /* Attempt to perform edge redirection by replacing possibly complex jump
1649    instruction by unconditional jump or removing jump completely.
1650    This can apply only if all edges now point to the same block. 
1651
1652    The parameters and return values are equivalent to redirect_edge_and_branch.
1653  */
1654 static bool
1655 try_redirect_by_replacing_jump (e, target)
1656      edge e;
1657      basic_block target;
1658 {
1659   basic_block src = e->src;
1660   rtx insn = src->end, kill_from;
1661   edge tmp;
1662   rtx set;
1663   int fallthru = 0;
1664
1665   /* Verify that all targets will be TARGET.  */
1666   for (tmp = src->succ; tmp; tmp = tmp->succ_next)
1667     if (tmp->dest != target && tmp != e)
1668       break;
1669   if (tmp || !onlyjump_p (insn))
1670     return false;
1671
1672   /* Avoid removing branch with side effects.  */
1673   set = single_set (insn);
1674   if (!set || side_effects_p (set))
1675     return false;
1676
1677   /* In case we zap a conditional jump, we'll need to kill
1678      the cc0 setter too.  */
1679   kill_from = insn;
1680 #ifdef HAVE_cc0
1681   if (reg_mentioned_p (cc0_rtx, PATTERN (insn)))
1682     kill_from = PREV_INSN (insn);
1683 #endif
1684
1685   /* See if we can create the fallthru edge.  */
1686   if (can_fallthru (src, target))
1687     {
1688       src->end = PREV_INSN (kill_from);
1689       if (rtl_dump_file)
1690         fprintf (rtl_dump_file, "Removing jump %i.\n", INSN_UID (insn));
1691       fallthru = 1;
1692
1693       /* Selectivly unlink whole insn chain.  */
1694       flow_delete_insn_chain (kill_from, PREV_INSN (target->head));
1695     }
1696   /* If this already is simplejump, redirect it.  */
1697   else if (simplejump_p (insn))
1698     {
1699       if (e->dest == target)
1700         return false;
1701       if (rtl_dump_file)
1702         fprintf (rtl_dump_file, "Redirecting jump %i from %i to %i.\n",
1703                  INSN_UID (insn), e->dest->index, target->index);
1704       redirect_jump (insn, block_label (target), 0);
1705     }
1706   /* Or replace possibly complicated jump insn by simple jump insn.  */
1707   else
1708     {
1709       rtx target_label = block_label (target);
1710       rtx barrier;
1711
1712       src->end = emit_jump_insn_before (gen_jump (target_label), kill_from);
1713       JUMP_LABEL (src->end) = target_label;
1714       LABEL_NUSES (target_label)++;
1715       if (basic_block_for_insn)
1716         set_block_for_new_insns (src->end, src);
1717       if (rtl_dump_file)
1718         fprintf (rtl_dump_file, "Replacing insn %i by jump %i\n",
1719                  INSN_UID (insn), INSN_UID (src->end));
1720
1721       flow_delete_insn_chain (kill_from, insn);
1722
1723       barrier = next_nonnote_insn (src->end);
1724       if (!barrier || GET_CODE (barrier) != BARRIER)
1725         emit_barrier_after (src->end);
1726     }
1727
1728   /* Keep only one edge out and set proper flags.  */
1729   while (src->succ->succ_next)
1730     remove_edge (src->succ);
1731   e = src->succ;
1732   if (fallthru)
1733     e->flags = EDGE_FALLTHRU;
1734   else
1735     e->flags = 0;
1736   e->probability = REG_BR_PROB_BASE;
1737   e->count = src->count;
1738
1739   /* We don't want a block to end on a line-number note since that has
1740      the potential of changing the code between -g and not -g.  */
1741   while (GET_CODE (e->src->end) == NOTE
1742          && NOTE_LINE_NUMBER (e->src->end) >= 0)
1743     {
1744       rtx prev = PREV_INSN (e->src->end);
1745       flow_delete_insn (e->src->end);
1746       e->src->end = prev;
1747     }
1748
1749   if (e->dest != target)
1750     redirect_edge_succ (e, target);
1751   return true;
1752 }
1753
1754 /* Attempt to change code to redirect edge E to TARGET.
1755    Don't do that on expense of adding new instructions or reordering
1756    basic blocks.
1757
1758    Function can be also called with edge destionation equivalent to the
1759    TARGET.  Then it should try the simplifications and do nothing if
1760    none is possible.
1761
1762    Return true if transformation suceeded.  We still return flase in case
1763    E already destinated TARGET and we didn't managed to simplify instruction
1764    stream.  */
1765 bool
1766 redirect_edge_and_branch (e, target)
1767      edge e;
1768      basic_block target;
1769 {
1770   rtx tmp;
1771   rtx old_label = e->dest->head;
1772   basic_block src = e->src;
1773   rtx insn = src->end;
1774
1775   if (e->flags & EDGE_COMPLEX)
1776     return false;
1777
1778   if (try_redirect_by_replacing_jump (e, target))
1779     return true;
1780   /* Do this fast path late, as we want above code to simplify for cases
1781      where called on single edge leaving basic block containing nontrivial
1782      jump insn.  */
1783   else if (e->dest == target)
1784     return false;
1785
1786   /* We can only redirect non-fallthru edges of jump insn.  */
1787   if (e->flags & EDGE_FALLTHRU)
1788     return false;
1789   if (GET_CODE (insn) != JUMP_INSN)
1790     return false;
1791
1792   /* Recognize a tablejump and adjust all matching cases.  */
1793   if ((tmp = JUMP_LABEL (insn)) != NULL_RTX
1794       && (tmp = NEXT_INSN (tmp)) != NULL_RTX
1795       && GET_CODE (tmp) == JUMP_INSN
1796       && (GET_CODE (PATTERN (tmp)) == ADDR_VEC
1797           || GET_CODE (PATTERN (tmp)) == ADDR_DIFF_VEC))
1798     {
1799       rtvec vec;
1800       int j;
1801       rtx new_label = block_label (target);
1802
1803       if (GET_CODE (PATTERN (tmp)) == ADDR_VEC)
1804         vec = XVEC (PATTERN (tmp), 0);
1805       else
1806         vec = XVEC (PATTERN (tmp), 1);
1807
1808       for (j = GET_NUM_ELEM (vec) - 1; j >= 0; --j)
1809         if (XEXP (RTVEC_ELT (vec, j), 0) == old_label)
1810           {
1811             RTVEC_ELT (vec, j) = gen_rtx_LABEL_REF (Pmode, new_label);
1812             --LABEL_NUSES (old_label);
1813             ++LABEL_NUSES (new_label);
1814           }
1815
1816       /* Handle casesi dispatch insns */
1817       if ((tmp = single_set (insn)) != NULL
1818           && SET_DEST (tmp) == pc_rtx
1819           && GET_CODE (SET_SRC (tmp)) == IF_THEN_ELSE
1820           && GET_CODE (XEXP (SET_SRC (tmp), 2)) == LABEL_REF
1821           && XEXP (XEXP (SET_SRC (tmp), 2), 0) == old_label)
1822         {
1823           XEXP (SET_SRC (tmp), 2) = gen_rtx_LABEL_REF (VOIDmode,
1824                                                        new_label);
1825           --LABEL_NUSES (old_label);
1826           ++LABEL_NUSES (new_label);
1827         }
1828     }
1829   else
1830     {
1831       /* ?? We may play the games with moving the named labels from
1832          one basic block to the other in case only one computed_jump is
1833          available.  */
1834       if (computed_jump_p (insn))
1835         return false;
1836
1837       /* A return instruction can't be redirected.  */
1838       if (returnjump_p (insn))
1839         return false;
1840
1841       /* If the insn doesn't go where we think, we're confused.  */
1842       if (JUMP_LABEL (insn) != old_label)
1843         abort ();
1844       redirect_jump (insn, block_label (target), 0);
1845     }
1846
1847   if (rtl_dump_file)
1848     fprintf (rtl_dump_file, "Edge %i->%i redirected to %i\n",
1849              e->src->index, e->dest->index, target->index);
1850   if (e->dest != target)
1851     {
1852       edge s;
1853       /* Check whether the edge is already present.  */
1854       for (s = src->succ; s; s=s->succ_next)
1855         if (s->dest == target)
1856           break;
1857       if (s)
1858         {
1859           s->flags |= e->flags;
1860           s->probability += e->probability;
1861           s->count += e->count;
1862           remove_edge (e);
1863         }
1864       else
1865         redirect_edge_succ (e, target);
1866     }
1867   return true;
1868 }
1869
1870 /* Redirect edge even at the expense of creating new jump insn or
1871    basic block.  Return new basic block if created, NULL otherwise.
1872    Abort if converison is impossible.  */
1873 basic_block
1874 redirect_edge_and_branch_force (e, target)
1875      edge e;
1876      basic_block target;
1877 {
1878   basic_block new_bb;
1879   edge new_edge;
1880   rtx label;
1881   rtx bb_note;
1882   int i, j;
1883
1884   if (redirect_edge_and_branch (e, target))
1885     return NULL;
1886   if (e->dest == target)
1887     return NULL;
1888   if (e->flags & EDGE_ABNORMAL)
1889     abort ();
1890   if (!(e->flags & EDGE_FALLTHRU))
1891     abort ();
1892
1893   e->flags &= ~EDGE_FALLTHRU;
1894   label = block_label (target);
1895   /* Case of the fallthru block.  */
1896   if (!e->src->succ->succ_next)
1897     {
1898       e->src->end = emit_jump_insn_after (gen_jump (label), e->src->end);
1899       JUMP_LABEL (e->src->end) = label;
1900       LABEL_NUSES (label)++;
1901       if (basic_block_for_insn)
1902         set_block_for_new_insns (e->src->end, e->src);
1903       emit_barrier_after (e->src->end);
1904       if (rtl_dump_file)
1905         fprintf (rtl_dump_file,
1906                  "Emitting jump insn %i to redirect edge %i->%i to %i\n",
1907                  INSN_UID (e->src->end), e->src->index, e->dest->index,
1908                  target->index);
1909       redirect_edge_succ (e, target);
1910       return NULL;
1911     }
1912   /* Redirecting fallthru edge of the conditional needs extra work.  */
1913
1914   if (rtl_dump_file)
1915     fprintf (rtl_dump_file,
1916              "Emitting jump insn %i in new BB to redirect edge %i->%i to %i\n",
1917              INSN_UID (e->src->end), e->src->index, e->dest->index,
1918              target->index);
1919
1920   /* Create the new structures.  */
1921   new_bb = (basic_block) obstack_alloc (&flow_obstack, sizeof (*new_bb));
1922   new_edge = (edge) xcalloc (1, sizeof (*new_edge));
1923   n_edges++;
1924
1925   memset (new_bb, 0, sizeof (*new_bb));
1926
1927   new_bb->end = new_bb->head = e->src->end;
1928   new_bb->succ = NULL;
1929   new_bb->pred = new_edge;
1930   new_bb->count = e->count;
1931   new_bb->frequency = e->probability * e->src->frequency / REG_BR_PROB_BASE;
1932   new_bb->loop_depth = e->dest->loop_depth;
1933
1934   new_edge->flags = EDGE_FALLTHRU;
1935   new_edge->probability = e->probability;
1936   new_edge->count = e->count;
1937
1938   if (e->dest->global_live_at_start)
1939     {
1940       new_bb->global_live_at_start = OBSTACK_ALLOC_REG_SET (&flow_obstack);
1941       new_bb->global_live_at_end = OBSTACK_ALLOC_REG_SET (&flow_obstack);
1942       COPY_REG_SET (new_bb->global_live_at_start,
1943                     target->global_live_at_start);
1944       COPY_REG_SET (new_bb->global_live_at_end, new_bb->global_live_at_start);
1945     }
1946
1947   /* Wire edge in.  */
1948   new_edge->src = e->src;
1949   new_edge->dest = new_bb;
1950   new_edge->succ_next = e->src->succ;
1951   e->src->succ = new_edge;
1952   new_edge->pred_next = NULL;
1953
1954   /* Redirect old edge.  */
1955   redirect_edge_succ (e, target);
1956   redirect_edge_pred (e, new_bb);
1957   e->probability = REG_BR_PROB_BASE;
1958
1959   /* Place the new block just after the block being split.  */
1960   VARRAY_GROW (basic_block_info, ++n_basic_blocks);
1961
1962   /* Some parts of the compiler expect blocks to be number in
1963      sequential order so insert the new block immediately after the
1964      block being split..  */
1965   j = new_edge->src->index;
1966   for (i = n_basic_blocks - 1; i > j + 1; --i)
1967     {
1968       basic_block tmp = BASIC_BLOCK (i - 1);
1969       BASIC_BLOCK (i) = tmp;
1970       tmp->index = i;
1971     }
1972
1973   BASIC_BLOCK (i) = new_bb;
1974   new_bb->index = i;
1975
1976   /* Create the basic block note.  */
1977   bb_note = emit_note_after (NOTE_INSN_BASIC_BLOCK, new_bb->head);
1978   NOTE_BASIC_BLOCK (bb_note) = new_bb;
1979   new_bb->head = bb_note;
1980
1981   new_bb->end = emit_jump_insn_after (gen_jump (label), new_bb->head);
1982   JUMP_LABEL (new_bb->end) = label;
1983   LABEL_NUSES (label)++;
1984   if (basic_block_for_insn)
1985     set_block_for_new_insns (new_bb->end, new_bb);
1986   emit_barrier_after (new_bb->end);
1987   return new_bb;
1988 }
1989
1990 /* Split a (typically critical) edge.  Return the new block.
1991    Abort on abnormal edges.
1992
1993    ??? The code generally expects to be called on critical edges.
1994    The case of a block ending in an unconditional jump to a
1995    block with multiple predecessors is not handled optimally.  */
1996
1997 basic_block
1998 split_edge (edge_in)
1999      edge edge_in;
2000 {
2001   basic_block old_pred, bb, old_succ;
2002   edge edge_out;
2003   rtx bb_note;
2004   int i, j;
2005
2006   /* Abnormal edges cannot be split.  */
2007   if ((edge_in->flags & EDGE_ABNORMAL) != 0)
2008     abort ();
2009
2010   old_pred = edge_in->src;
2011   old_succ = edge_in->dest;
2012
2013   /* Create the new structures.  */
2014   bb = (basic_block) obstack_alloc (&flow_obstack, sizeof (*bb));
2015   edge_out = (edge) xcalloc (1, sizeof (*edge_out));
2016   n_edges++;
2017
2018   memset (bb, 0, sizeof (*bb));
2019
2020   /* ??? This info is likely going to be out of date very soon.  */
2021   if (old_succ->global_live_at_start)
2022     {
2023       bb->global_live_at_start = OBSTACK_ALLOC_REG_SET (&flow_obstack);
2024       bb->global_live_at_end = OBSTACK_ALLOC_REG_SET (&flow_obstack);
2025       COPY_REG_SET (bb->global_live_at_start, old_succ->global_live_at_start);
2026       COPY_REG_SET (bb->global_live_at_end, old_succ->global_live_at_start);
2027     }
2028
2029   /* Wire them up.  */
2030   bb->succ = edge_out;
2031   bb->count = edge_in->count;
2032   bb->frequency = (edge_in->probability * edge_in->src->frequency
2033                    / REG_BR_PROB_BASE);
2034
2035   edge_in->flags &= ~EDGE_CRITICAL;
2036
2037   edge_out->pred_next = old_succ->pred;
2038   edge_out->succ_next = NULL;
2039   edge_out->src = bb;
2040   edge_out->dest = old_succ;
2041   edge_out->flags = EDGE_FALLTHRU;
2042   edge_out->probability = REG_BR_PROB_BASE;
2043   edge_out->count = edge_in->count;
2044
2045   old_succ->pred = edge_out;
2046
2047   /* Tricky case -- if there existed a fallthru into the successor
2048      (and we're not it) we must add a new unconditional jump around
2049      the new block we're actually interested in.
2050
2051      Further, if that edge is critical, this means a second new basic
2052      block must be created to hold it.  In order to simplify correct
2053      insn placement, do this before we touch the existing basic block
2054      ordering for the block we were really wanting.  */
2055   if ((edge_in->flags & EDGE_FALLTHRU) == 0)
2056     {
2057       edge e;
2058       for (e = edge_out->pred_next; e; e = e->pred_next)
2059         if (e->flags & EDGE_FALLTHRU)
2060           break;
2061
2062       if (e)
2063         {
2064           basic_block jump_block;
2065           rtx pos;
2066
2067           if ((e->flags & EDGE_CRITICAL) == 0
2068               && e->src != ENTRY_BLOCK_PTR)
2069             {
2070               /* Non critical -- we can simply add a jump to the end
2071                  of the existing predecessor.  */
2072               jump_block = e->src;
2073             }
2074           else
2075             {
2076               /* We need a new block to hold the jump.  The simplest
2077                  way to do the bulk of the work here is to recursively
2078                  call ourselves.  */
2079               jump_block = split_edge (e);
2080               e = jump_block->succ;
2081             }
2082
2083           /* Now add the jump insn ...  */
2084           pos = emit_jump_insn_after (gen_jump (old_succ->head),
2085                                       jump_block->end);
2086           jump_block->end = pos;
2087           if (basic_block_for_insn)
2088             set_block_for_new_insns (pos, jump_block);
2089           emit_barrier_after (pos);
2090
2091           /* ... let jump know that label is in use, ...  */
2092           JUMP_LABEL (pos) = old_succ->head;
2093           ++LABEL_NUSES (old_succ->head);
2094
2095           /* ... and clear fallthru on the outgoing edge.  */
2096           e->flags &= ~EDGE_FALLTHRU;
2097
2098           /* Continue splitting the interesting edge.  */
2099         }
2100     }
2101
2102   /* Place the new block just in front of the successor.  */
2103   VARRAY_GROW (basic_block_info, ++n_basic_blocks);
2104   if (old_succ == EXIT_BLOCK_PTR)
2105     j = n_basic_blocks - 1;
2106   else
2107     j = old_succ->index;
2108   for (i = n_basic_blocks - 1; i > j; --i)
2109     {
2110       basic_block tmp = BASIC_BLOCK (i - 1);
2111       BASIC_BLOCK (i) = tmp;
2112       tmp->index = i;
2113     }
2114   BASIC_BLOCK (i) = bb;
2115   bb->index = i;
2116
2117   /* Create the basic block note.
2118
2119      Where we place the note can have a noticable impact on the generated
2120      code.  Consider this cfg:
2121
2122                         E
2123                         |
2124                         0
2125                        / \
2126                    +->1-->2--->E
2127                    |  |
2128                    +--+
2129
2130       If we need to insert an insn on the edge from block 0 to block 1,
2131       we want to ensure the instructions we insert are outside of any
2132       loop notes that physically sit between block 0 and block 1.  Otherwise
2133       we confuse the loop optimizer into thinking the loop is a phony.  */
2134   if (old_succ != EXIT_BLOCK_PTR
2135       && PREV_INSN (old_succ->head)
2136       && GET_CODE (PREV_INSN (old_succ->head)) == NOTE
2137       && NOTE_LINE_NUMBER (PREV_INSN (old_succ->head)) == NOTE_INSN_LOOP_BEG)
2138     bb_note = emit_note_before (NOTE_INSN_BASIC_BLOCK,
2139                                 PREV_INSN (old_succ->head));
2140   else if (old_succ != EXIT_BLOCK_PTR)
2141     bb_note = emit_note_before (NOTE_INSN_BASIC_BLOCK, old_succ->head);
2142   else
2143     bb_note = emit_note_after (NOTE_INSN_BASIC_BLOCK, get_last_insn ());
2144   NOTE_BASIC_BLOCK (bb_note) = bb;
2145   bb->head = bb->end = bb_note;
2146
2147   /* For non-fallthry edges, we must adjust the predecessor's
2148      jump instruction to target our new block.  */
2149   if ((edge_in->flags & EDGE_FALLTHRU) == 0)
2150     {
2151       if (!redirect_edge_and_branch (edge_in, bb))
2152         abort ();
2153     }
2154   else
2155     redirect_edge_succ (edge_in, bb);
2156
2157   return bb;
2158 }
2159
2160 /* Queue instructions for insertion on an edge between two basic blocks.
2161    The new instructions and basic blocks (if any) will not appear in the
2162    CFG until commit_edge_insertions is called.  */
2163
2164 void
2165 insert_insn_on_edge (pattern, e)
2166      rtx pattern;
2167      edge e;
2168 {
2169   /* We cannot insert instructions on an abnormal critical edge.
2170      It will be easier to find the culprit if we die now.  */
2171   if ((e->flags & (EDGE_ABNORMAL|EDGE_CRITICAL))
2172       == (EDGE_ABNORMAL|EDGE_CRITICAL))
2173     abort ();
2174
2175   if (e->insns == NULL_RTX)
2176     start_sequence ();
2177   else
2178     push_to_sequence (e->insns);
2179
2180   emit_insn (pattern);
2181
2182   e->insns = get_insns ();
2183   end_sequence ();
2184 }
2185
2186 /* Update the CFG for the instructions queued on edge E.  */
2187
2188 static void
2189 commit_one_edge_insertion (e)
2190      edge e;
2191 {
2192   rtx before = NULL_RTX, after = NULL_RTX, insns, tmp, last;
2193   basic_block bb;
2194
2195   /* Pull the insns off the edge now since the edge might go away.  */
2196   insns = e->insns;
2197   e->insns = NULL_RTX;
2198
2199   /* Figure out where to put these things.  If the destination has
2200      one predecessor, insert there.  Except for the exit block.  */
2201   if (e->dest->pred->pred_next == NULL
2202       && e->dest != EXIT_BLOCK_PTR)
2203     {
2204       bb = e->dest;
2205
2206       /* Get the location correct wrt a code label, and "nice" wrt
2207          a basic block note, and before everything else.  */
2208       tmp = bb->head;
2209       if (GET_CODE (tmp) == CODE_LABEL)
2210         tmp = NEXT_INSN (tmp);
2211       if (NOTE_INSN_BASIC_BLOCK_P (tmp))
2212         tmp = NEXT_INSN (tmp);
2213       if (tmp == bb->head)
2214         before = tmp;
2215       else
2216         after = PREV_INSN (tmp);
2217     }
2218
2219   /* If the source has one successor and the edge is not abnormal,
2220      insert there.  Except for the entry block.  */
2221   else if ((e->flags & EDGE_ABNORMAL) == 0
2222            && e->src->succ->succ_next == NULL
2223            && e->src != ENTRY_BLOCK_PTR)
2224     {
2225       bb = e->src;
2226       /* It is possible to have a non-simple jump here.  Consider a target
2227          where some forms of unconditional jumps clobber a register.  This
2228          happens on the fr30 for example.
2229
2230          We know this block has a single successor, so we can just emit
2231          the queued insns before the jump.  */
2232       if (GET_CODE (bb->end) == JUMP_INSN)
2233         {
2234           before = bb->end;
2235         }
2236       else
2237         {
2238           /* We'd better be fallthru, or we've lost track of what's what.  */
2239           if ((e->flags & EDGE_FALLTHRU) == 0)
2240             abort ();
2241
2242           after = bb->end;
2243         }
2244     }
2245
2246   /* Otherwise we must split the edge.  */
2247   else
2248     {
2249       bb = split_edge (e);
2250       after = bb->end;
2251     }
2252
2253   /* Now that we've found the spot, do the insertion.  */
2254
2255   /* Set the new block number for these insns, if structure is allocated.  */
2256   if (basic_block_for_insn)
2257     {
2258       rtx i;
2259       for (i = insns; i != NULL_RTX; i = NEXT_INSN (i))
2260         set_block_for_insn (i, bb);
2261     }
2262
2263   if (before)
2264     {
2265       emit_insns_before (insns, before);
2266       if (before == bb->head)
2267         bb->head = insns;
2268
2269       last = prev_nonnote_insn (before);
2270     }
2271   else
2272     {
2273       last = emit_insns_after (insns, after);
2274       if (after == bb->end)
2275         bb->end = last;
2276     }
2277
2278   if (returnjump_p (last))
2279     {
2280       /* ??? Remove all outgoing edges from BB and add one for EXIT.
2281          This is not currently a problem because this only happens
2282          for the (single) epilogue, which already has a fallthru edge
2283          to EXIT.  */
2284
2285       e = bb->succ;
2286       if (e->dest != EXIT_BLOCK_PTR
2287           || e->succ_next != NULL
2288           || (e->flags & EDGE_FALLTHRU) == 0)
2289         abort ();
2290       e->flags &= ~EDGE_FALLTHRU;
2291
2292       emit_barrier_after (last);
2293       bb->end = last;
2294
2295       if (before)
2296         flow_delete_insn (before);
2297     }
2298   else if (GET_CODE (last) == JUMP_INSN)
2299     abort ();
2300   find_sub_basic_blocks (bb);
2301 }
2302
2303 /* Update the CFG for all queued instructions.  */
2304
2305 void
2306 commit_edge_insertions ()
2307 {
2308   int i;
2309   basic_block bb;
2310
2311 #ifdef ENABLE_CHECKING
2312   verify_flow_info ();
2313 #endif
2314
2315   i = -1;
2316   bb = ENTRY_BLOCK_PTR;
2317   while (1)
2318     {
2319       edge e, next;
2320
2321       for (e = bb->succ; e; e = next)
2322         {
2323           next = e->succ_next;
2324           if (e->insns)
2325             commit_one_edge_insertion (e);
2326         }
2327
2328       if (++i >= n_basic_blocks)
2329         break;
2330       bb = BASIC_BLOCK (i);
2331     }
2332 }
2333
2334 /* Add fake edges to the function exit for any non constant calls in
2335    the bitmap of blocks specified by BLOCKS or to the whole CFG if
2336    BLOCKS is zero.  Return the nuber of blocks that were split.  */
2337
2338 int
2339 flow_call_edges_add (blocks)
2340      sbitmap blocks;
2341 {
2342   int i;
2343   int blocks_split = 0;
2344   int bb_num = 0;
2345   basic_block *bbs;
2346
2347   /* Map bb indicies into basic block pointers since split_block
2348      will renumber the basic blocks.  */
2349
2350   bbs = xmalloc (n_basic_blocks * sizeof (*bbs));
2351
2352   if (! blocks)
2353     {
2354       for (i = 0; i < n_basic_blocks; i++)
2355         bbs[bb_num++] = BASIC_BLOCK (i);
2356     }
2357   else
2358     {
2359       EXECUTE_IF_SET_IN_SBITMAP (blocks, 0, i, 
2360       {
2361         bbs[bb_num++] = BASIC_BLOCK (i);
2362       });
2363     }
2364
2365
2366   /* Now add fake edges to the function exit for any non constant
2367      calls since there is no way that we can determine if they will
2368      return or not...  */
2369
2370   for (i = 0; i < bb_num; i++)
2371     {
2372       basic_block bb = bbs[i];
2373       rtx insn;
2374       rtx prev_insn;
2375
2376       for (insn = bb->end; ; insn = prev_insn)
2377         {
2378           prev_insn = PREV_INSN (insn);
2379           if (GET_CODE (insn) == CALL_INSN && ! CONST_CALL_P (insn))
2380             {
2381               edge e;
2382
2383               /* Note that the following may create a new basic block
2384                  and renumber the existing basic blocks.  */
2385               e = split_block (bb, insn);
2386               if (e)
2387                 blocks_split++;
2388
2389               make_edge (NULL, bb, EXIT_BLOCK_PTR, EDGE_FAKE);
2390             }
2391           if (insn == bb->head)
2392             break;
2393         }
2394     }
2395
2396   if (blocks_split)
2397     verify_flow_info ();
2398
2399   free (bbs);
2400   return blocks_split;
2401 }
2402 \f
2403 /* Find unreachable blocks.  An unreachable block will have NULL in
2404    block->aux, a non-NULL value indicates the block is reachable.  */
2405
2406 void
2407 find_unreachable_blocks ()
2408 {
2409   edge e;
2410   int i, n;
2411   basic_block *tos, *worklist;
2412
2413   n = n_basic_blocks;
2414   tos = worklist = (basic_block *) xmalloc (sizeof (basic_block) * n);
2415
2416   /* Use basic_block->aux as a marker.  Clear them all.  */
2417
2418   for (i = 0; i < n; ++i)
2419     BASIC_BLOCK (i)->aux = NULL;
2420
2421   /* Add our starting points to the worklist.  Almost always there will
2422      be only one.  It isn't inconcievable that we might one day directly
2423      support Fortran alternate entry points.  */
2424
2425   for (e = ENTRY_BLOCK_PTR->succ; e; e = e->succ_next)
2426     {
2427       *tos++ = e->dest;
2428
2429       /* Mark the block with a handy non-null value.  */
2430       e->dest->aux = e;
2431     }
2432
2433   /* Iterate: find everything reachable from what we've already seen.  */
2434
2435   while (tos != worklist)
2436     {
2437       basic_block b = *--tos;
2438
2439       for (e = b->succ; e; e = e->succ_next)
2440         if (!e->dest->aux)
2441           {
2442             *tos++ = e->dest;
2443             e->dest->aux = e;
2444           }
2445     }
2446
2447   free (worklist);
2448 }
2449
2450 /* Delete all unreachable basic blocks.   */
2451 static void
2452 delete_unreachable_blocks ()
2453 {
2454   int i;
2455
2456   find_unreachable_blocks ();
2457
2458   /* Delete all unreachable basic blocks.  Count down so that we
2459      don't interfere with the block renumbering that happens in
2460      flow_delete_block.  */
2461
2462   for (i = n_basic_blocks - 1; i >= 0; --i)
2463     {
2464       basic_block b = BASIC_BLOCK (i);
2465
2466       if (b->aux != NULL)
2467         /* This block was found.  Tidy up the mark.  */
2468         b->aux = NULL;
2469       else
2470         flow_delete_block (b);
2471     }
2472
2473   tidy_fallthru_edges ();
2474 }
2475
2476 /* Return true if NOTE is not one of the ones that must be kept paired,
2477    so that we may simply delete them.  */
2478
2479 static int
2480 can_delete_note_p (note)
2481      rtx note;
2482 {
2483   return (NOTE_LINE_NUMBER (note) == NOTE_INSN_DELETED
2484           || NOTE_LINE_NUMBER (note) == NOTE_INSN_BASIC_BLOCK);
2485 }
2486
2487 /* Unlink a chain of insns between START and FINISH, leaving notes
2488    that must be paired.  */
2489
2490 void
2491 flow_delete_insn_chain (start, finish)
2492      rtx start, finish;
2493 {
2494   /* Unchain the insns one by one.  It would be quicker to delete all
2495      of these with a single unchaining, rather than one at a time, but
2496      we need to keep the NOTE's.  */
2497
2498   rtx next;
2499
2500   while (1)
2501     {
2502       next = NEXT_INSN (start);
2503       if (GET_CODE (start) == NOTE && !can_delete_note_p (start))
2504         ;
2505       else if (GET_CODE (start) == CODE_LABEL
2506                && ! can_delete_label_p (start))
2507         {
2508           const char *name = LABEL_NAME (start);
2509           PUT_CODE (start, NOTE);
2510           NOTE_LINE_NUMBER (start) = NOTE_INSN_DELETED_LABEL;
2511           NOTE_SOURCE_FILE (start) = name;
2512         }
2513       else
2514         next = flow_delete_insn (start);
2515
2516       if (start == finish)
2517         break;
2518       start = next;
2519     }
2520 }
2521
2522 /* Delete the insns in a (non-live) block.  We physically delete every
2523    non-deleted-note insn, and update the flow graph appropriately.
2524
2525    Return nonzero if we deleted an exception handler.  */
2526
2527 /* ??? Preserving all such notes strikes me as wrong.  It would be nice
2528    to post-process the stream to remove empty blocks, loops, ranges, etc.  */
2529
2530 int
2531 flow_delete_block (b)
2532      basic_block b;
2533 {
2534   int deleted_handler = 0;
2535   rtx insn, end, tmp;
2536
2537   /* If the head of this block is a CODE_LABEL, then it might be the
2538      label for an exception handler which can't be reached.
2539
2540      We need to remove the label from the exception_handler_label list
2541      and remove the associated NOTE_INSN_EH_REGION_BEG and
2542      NOTE_INSN_EH_REGION_END notes.  */
2543
2544   insn = b->head;
2545
2546   never_reached_warning (insn);
2547
2548   if (GET_CODE (insn) == CODE_LABEL)
2549     maybe_remove_eh_handler (insn);
2550
2551   /* Include any jump table following the basic block.  */
2552   end = b->end;
2553   if (GET_CODE (end) == JUMP_INSN
2554       && (tmp = JUMP_LABEL (end)) != NULL_RTX
2555       && (tmp = NEXT_INSN (tmp)) != NULL_RTX
2556       && GET_CODE (tmp) == JUMP_INSN
2557       && (GET_CODE (PATTERN (tmp)) == ADDR_VEC
2558           || GET_CODE (PATTERN (tmp)) == ADDR_DIFF_VEC))
2559     end = tmp;
2560
2561   /* Include any barrier that may follow the basic block.  */
2562   tmp = next_nonnote_insn (end);
2563   if (tmp && GET_CODE (tmp) == BARRIER)
2564     end = tmp;
2565
2566   /* Selectively delete the entire chain.  */
2567   flow_delete_insn_chain (insn, end);
2568
2569   /* Remove the edges into and out of this block.  Note that there may
2570      indeed be edges in, if we are removing an unreachable loop.  */
2571   {
2572     edge e, next, *q;
2573
2574     for (e = b->pred; e; e = next)
2575       {
2576         for (q = &e->src->succ; *q != e; q = &(*q)->succ_next)
2577           continue;
2578         *q = e->succ_next;
2579         next = e->pred_next;
2580         n_edges--;
2581         free (e);
2582       }
2583     for (e = b->succ; e; e = next)
2584       {
2585         for (q = &e->dest->pred; *q != e; q = &(*q)->pred_next)
2586           continue;
2587         *q = e->pred_next;
2588         next = e->succ_next;
2589         n_edges--;
2590         free (e);
2591       }
2592
2593     b->pred = NULL;
2594     b->succ = NULL;
2595   }
2596
2597   /* Remove the basic block from the array, and compact behind it.  */
2598   expunge_block (b);
2599
2600   return deleted_handler;
2601 }
2602
2603 /* Remove block B from the basic block array and compact behind it.  */
2604
2605 static void
2606 expunge_block (b)
2607      basic_block b;
2608 {
2609   int i, n = n_basic_blocks;
2610
2611   for (i = b->index; i + 1 < n; ++i)
2612     {
2613       basic_block x = BASIC_BLOCK (i + 1);
2614       BASIC_BLOCK (i) = x;
2615       x->index = i;
2616     }
2617
2618   basic_block_info->num_elements--;
2619   n_basic_blocks--;
2620 }
2621
2622 /* Delete INSN by patching it out.  Return the next insn.  */
2623
2624 rtx
2625 flow_delete_insn (insn)
2626      rtx insn;
2627 {
2628   rtx prev = PREV_INSN (insn);
2629   rtx next = NEXT_INSN (insn);
2630   rtx note;
2631
2632   PREV_INSN (insn) = NULL_RTX;
2633   NEXT_INSN (insn) = NULL_RTX;
2634   INSN_DELETED_P (insn) = 1;
2635
2636   if (prev)
2637     NEXT_INSN (prev) = next;
2638   if (next)
2639     PREV_INSN (next) = prev;
2640   else
2641     set_last_insn (prev);
2642
2643   if (GET_CODE (insn) == CODE_LABEL)
2644     remove_node_from_expr_list (insn, &nonlocal_goto_handler_labels);
2645
2646   /* If deleting a jump, decrement the use count of the label.  Deleting
2647      the label itself should happen in the normal course of block merging.  */
2648   if (GET_CODE (insn) == JUMP_INSN
2649       && JUMP_LABEL (insn)
2650       && GET_CODE (JUMP_LABEL (insn)) == CODE_LABEL)
2651     LABEL_NUSES (JUMP_LABEL (insn))--;
2652
2653   /* Also if deleting an insn that references a label.  */
2654   else if ((note = find_reg_note (insn, REG_LABEL, NULL_RTX)) != NULL_RTX
2655            && GET_CODE (XEXP (note, 0)) == CODE_LABEL)
2656     LABEL_NUSES (XEXP (note, 0))--;
2657
2658   if (GET_CODE (insn) == JUMP_INSN
2659       && (GET_CODE (PATTERN (insn)) == ADDR_VEC
2660           || GET_CODE (PATTERN (insn)) == ADDR_DIFF_VEC))
2661     {
2662       rtx pat = PATTERN (insn);
2663       int diff_vec_p = GET_CODE (PATTERN (insn)) == ADDR_DIFF_VEC;
2664       int len = XVECLEN (pat, diff_vec_p);
2665       int i;
2666
2667       for (i = 0; i < len; i++)
2668         LABEL_NUSES (XEXP (XVECEXP (pat, diff_vec_p, i), 0))--;
2669     }
2670
2671   return next;
2672 }
2673
2674 /* True if a given label can be deleted.  */
2675
2676 static int
2677 can_delete_label_p (label)
2678      rtx label;
2679 {
2680   rtx x;
2681
2682   if (LABEL_PRESERVE_P (label))
2683     return 0;
2684
2685   for (x = forced_labels; x; x = XEXP (x, 1))
2686     if (label == XEXP (x, 0))
2687       return 0;
2688   for (x = label_value_list; x; x = XEXP (x, 1))
2689     if (label == XEXP (x, 0))
2690       return 0;
2691   for (x = exception_handler_labels; x; x = XEXP (x, 1))
2692     if (label == XEXP (x, 0))
2693       return 0;
2694
2695   /* User declared labels must be preserved.  */
2696   if (LABEL_NAME (label) != 0)
2697     return 0;
2698
2699   return 1;
2700 }
2701
2702 static int
2703 tail_recursion_label_p (label)
2704      rtx label;
2705 {
2706   rtx x;
2707
2708   for (x = tail_recursion_label_list; x; x = XEXP (x, 1))
2709     if (label == XEXP (x, 0))
2710       return 1;
2711
2712   return 0;
2713 }
2714
2715 /* Blocks A and B are to be merged into a single block A.  The insns
2716    are already contiguous, hence `nomove'.  */
2717
2718 void
2719 merge_blocks_nomove (a, b)
2720      basic_block a, b;
2721 {
2722   edge e;
2723   rtx b_head, b_end, a_end;
2724   rtx del_first = NULL_RTX, del_last = NULL_RTX;
2725   int b_empty = 0;
2726
2727   /* If there was a CODE_LABEL beginning B, delete it.  */
2728   b_head = b->head;
2729   b_end = b->end;
2730   if (GET_CODE (b_head) == CODE_LABEL)
2731     {
2732       /* Detect basic blocks with nothing but a label.  This can happen
2733          in particular at the end of a function.  */
2734       if (b_head == b_end)
2735         b_empty = 1;
2736       del_first = del_last = b_head;
2737       b_head = NEXT_INSN (b_head);
2738     }
2739
2740   /* Delete the basic block note.  */
2741   if (NOTE_INSN_BASIC_BLOCK_P (b_head))
2742     {
2743       if (b_head == b_end)
2744         b_empty = 1;
2745       if (! del_last)
2746         del_first = b_head;
2747       del_last = b_head;
2748       b_head = NEXT_INSN (b_head);
2749     }
2750
2751   /* If there was a jump out of A, delete it.  */
2752   a_end = a->end;
2753   if (GET_CODE (a_end) == JUMP_INSN)
2754     {
2755       rtx prev;
2756
2757       for (prev = PREV_INSN (a_end); ; prev = PREV_INSN (prev))
2758         if (GET_CODE (prev) != NOTE
2759             || NOTE_LINE_NUMBER (prev) == NOTE_INSN_BASIC_BLOCK
2760             || prev == a->head)
2761           break;
2762
2763       del_first = a_end;
2764
2765 #ifdef HAVE_cc0
2766       /* If this was a conditional jump, we need to also delete
2767          the insn that set cc0.  */
2768       if (prev && sets_cc0_p (prev))
2769         {
2770           rtx tmp = prev;
2771           prev = prev_nonnote_insn (prev);
2772           if (!prev)
2773             prev = a->head;
2774           del_first = tmp;
2775         }
2776 #endif
2777
2778       a_end = prev;
2779     }
2780   else if (GET_CODE (NEXT_INSN (a_end)) == BARRIER)
2781     del_first = NEXT_INSN (a_end);
2782
2783   /* Delete everything marked above as well as crap that might be
2784      hanging out between the two blocks.  */
2785   flow_delete_insn_chain (del_first, del_last);
2786
2787   /* Normally there should only be one successor of A and that is B, but
2788      partway though the merge of blocks for conditional_execution we'll
2789      be merging a TEST block with THEN and ELSE successors.  Free the
2790      whole lot of them and hope the caller knows what they're doing.  */
2791   while (a->succ)
2792     remove_edge (a->succ);
2793
2794   /* Adjust the edges out of B for the new owner.  */
2795   for (e = b->succ; e; e = e->succ_next)
2796     e->src = a;
2797   a->succ = b->succ;
2798
2799   /* B hasn't quite yet ceased to exist.  Attempt to prevent mishap.  */
2800   b->pred = b->succ = NULL;
2801
2802   /* Reassociate the insns of B with A.  */
2803   if (!b_empty)
2804     {
2805       if (basic_block_for_insn)
2806         {
2807           BLOCK_FOR_INSN (b_head) = a;
2808           while (b_head != b_end)
2809             {
2810               b_head = NEXT_INSN (b_head);
2811               BLOCK_FOR_INSN (b_head) = a;
2812             }
2813         }
2814       a_end = b_end;
2815     }
2816   a->end = a_end;
2817
2818   expunge_block (b);
2819 }
2820
2821 /* Blocks A and B are to be merged into a single block.  A has no incoming
2822    fallthru edge, so it can be moved before B without adding or modifying
2823    any jumps (aside from the jump from A to B).  */
2824
2825 static int
2826 merge_blocks_move_predecessor_nojumps (a, b)
2827      basic_block a, b;
2828 {
2829   rtx start, end, barrier;
2830   int index;
2831
2832   start = a->head;
2833   end = a->end;
2834
2835   barrier = next_nonnote_insn (end);
2836   if (GET_CODE (barrier) != BARRIER)
2837     abort ();
2838   flow_delete_insn (barrier);
2839
2840   /* Move block and loop notes out of the chain so that we do not
2841      disturb their order.
2842
2843      ??? A better solution would be to squeeze out all the non-nested notes
2844      and adjust the block trees appropriately.   Even better would be to have
2845      a tighter connection between block trees and rtl so that this is not
2846      necessary.  */
2847   start = squeeze_notes (start, end);
2848
2849   /* Scramble the insn chain.  */
2850   if (end != PREV_INSN (b->head))
2851     reorder_insns (start, end, PREV_INSN (b->head));
2852
2853   if (rtl_dump_file)
2854     {
2855       fprintf (rtl_dump_file, "Moved block %d before %d and merged.\n",
2856                a->index, b->index);
2857     }
2858
2859   /* Swap the records for the two blocks around.  Although we are deleting B,
2860      A is now where B was and we want to compact the BB array from where
2861      A used to be.  */
2862   BASIC_BLOCK (a->index) = b;
2863   BASIC_BLOCK (b->index) = a;
2864   index = a->index;
2865   a->index = b->index;
2866   b->index = index;
2867
2868   /* Now blocks A and B are contiguous.  Merge them.  */
2869   merge_blocks_nomove (a, b);
2870
2871   return 1;
2872 }
2873
2874 /* Blocks A and B are to be merged into a single block.  B has no outgoing
2875    fallthru edge, so it can be moved after A without adding or modifying
2876    any jumps (aside from the jump from A to B).  */
2877
2878 static int
2879 merge_blocks_move_successor_nojumps (a, b)
2880      basic_block a, b;
2881 {
2882   rtx start, end, barrier;
2883
2884   start = b->head;
2885   end = b->end;
2886   barrier = NEXT_INSN (end);
2887
2888   /* Recognize a jump table following block B.  */
2889   if (barrier
2890       && GET_CODE (barrier) == CODE_LABEL
2891       && NEXT_INSN (barrier)
2892       && GET_CODE (NEXT_INSN (barrier)) == JUMP_INSN
2893       && (GET_CODE (PATTERN (NEXT_INSN (barrier))) == ADDR_VEC
2894           || GET_CODE (PATTERN (NEXT_INSN (barrier))) == ADDR_DIFF_VEC))
2895     {
2896       end = NEXT_INSN (barrier);
2897       barrier = NEXT_INSN (end);
2898     }
2899
2900   /* There had better have been a barrier there.  Delete it.  */
2901   if (barrier && GET_CODE (barrier) == BARRIER)
2902     flow_delete_insn (barrier);
2903
2904   /* Move block and loop notes out of the chain so that we do not
2905      disturb their order.
2906
2907      ??? A better solution would be to squeeze out all the non-nested notes
2908      and adjust the block trees appropriately.   Even better would be to have
2909      a tighter connection between block trees and rtl so that this is not
2910      necessary.  */
2911   start = squeeze_notes (start, end);
2912
2913   /* Scramble the insn chain.  */
2914   reorder_insns (start, end, a->end);
2915
2916   /* Now blocks A and B are contiguous.  Merge them.  */
2917   merge_blocks_nomove (a, b);
2918
2919   if (rtl_dump_file)
2920     {
2921       fprintf (rtl_dump_file, "Moved block %d after %d and merged.\n",
2922                b->index, a->index);
2923     }
2924
2925   return 1;
2926 }
2927
2928 /* Attempt to merge basic blocks that are potentially non-adjacent.
2929    Return true iff the attempt succeeded.  */
2930
2931 static int
2932 merge_blocks (e, b, c, mode)
2933      edge e;
2934      basic_block b, c;
2935      int mode;
2936 {
2937   /* If C has a tail recursion label, do not merge.  There is no
2938      edge recorded from the call_placeholder back to this label, as
2939      that would make optimize_sibling_and_tail_recursive_calls more
2940      complex for no gain.  */
2941   if (GET_CODE (c->head) == CODE_LABEL
2942       && tail_recursion_label_p (c->head))
2943     return 0;
2944
2945   /* If B has a fallthru edge to C, no need to move anything.  */
2946   if (e->flags & EDGE_FALLTHRU)
2947     {
2948       merge_blocks_nomove (b, c);
2949
2950       if (rtl_dump_file)
2951         {
2952           fprintf (rtl_dump_file, "Merged %d and %d without moving.\n",
2953                    b->index, c->index);
2954         }
2955
2956       return 1;
2957     }
2958   /* Otherwise we will need to move code around.  Do that only if expensive
2959      transformations are allowed.  */
2960   else if (mode & CLEANUP_EXPENSIVE)
2961     {
2962       edge tmp_edge, c_fallthru_edge;
2963       int c_has_outgoing_fallthru;
2964       int b_has_incoming_fallthru;
2965
2966       /* Avoid overactive code motion, as the forwarder blocks should eb
2967          eliminated by the edge redirection instead. Only exception is the
2968          case b is an forwarder block and c has no fallthru edge, but no
2969          optimizers should be confused by this extra jump and we are about
2970          to kill the jump in bb_reorder pass instead.  */
2971       if (forwarder_block_p (b) || forwarder_block_p (c))
2972         return 0;
2973
2974       /* We must make sure to not munge nesting of exception regions,
2975          lexical blocks, and loop notes.
2976
2977          The first is taken care of by requiring that the active eh
2978          region at the end of one block always matches the active eh
2979          region at the beginning of the next block.
2980
2981          The later two are taken care of by squeezing out all the notes.  */
2982
2983       /* ???  A throw/catch edge (or any abnormal edge) should be rarely
2984          executed and we may want to treat blocks which have two out
2985          edges, one normal, one abnormal as only having one edge for
2986          block merging purposes.  */
2987
2988       for (tmp_edge = c->succ; tmp_edge; tmp_edge = tmp_edge->succ_next)
2989         if (tmp_edge->flags & EDGE_FALLTHRU)
2990           break;
2991       c_has_outgoing_fallthru = (tmp_edge != NULL);
2992       c_fallthru_edge = tmp_edge;
2993
2994       for (tmp_edge = b->pred; tmp_edge; tmp_edge = tmp_edge->pred_next)
2995         if (tmp_edge->flags & EDGE_FALLTHRU)
2996           break;
2997       b_has_incoming_fallthru = (tmp_edge != NULL);
2998
2999       /* If B does not have an incoming fallthru, then it can be moved
3000          immediately before C without introducing or modifying jumps.
3001          C cannot be the first block, so we do not have to worry about
3002          accessing a non-existent block.  */
3003       if (! b_has_incoming_fallthru)
3004         return merge_blocks_move_predecessor_nojumps (b, c);
3005
3006       /* Otherwise, we're going to try to move C after B.  If C does
3007          not have an outgoing fallthru, then it can be moved
3008          immediately after B without introducing or modifying jumps.  */
3009       if (! c_has_outgoing_fallthru)
3010         return merge_blocks_move_successor_nojumps (b, c);
3011
3012       /* Otherwise, we'll need to insert an extra jump, and possibly
3013          a new block to contain it.  We can't redirect to EXIT_BLOCK_PTR,
3014          as we don't have explicit return instructions before epilogues
3015          are generated, so give up on that case.  */
3016
3017       if (c_fallthru_edge->dest != EXIT_BLOCK_PTR
3018           && merge_blocks_move_successor_nojumps (b, c))
3019         {
3020           basic_block target = c_fallthru_edge->dest;
3021           rtx barrier;
3022           basic_block new;
3023
3024           /* This is a dirty hack to avoid code duplication.
3025
3026              Set edge to point to wrong basic block, so
3027              redirect_edge_and_branch_force will do the trick
3028              and rewire edge back to the original location.  */
3029           redirect_edge_succ (c_fallthru_edge, ENTRY_BLOCK_PTR);
3030           new = redirect_edge_and_branch_force (c_fallthru_edge, target);
3031
3032           /* We've just created barrier, but other barrier is already present
3033              in the stream.  Avoid duplicate.  */
3034           barrier = next_nonnote_insn (new ? new->end : b->end);
3035           if (GET_CODE (barrier) != BARRIER)
3036             abort ();
3037           flow_delete_insn (barrier);
3038         }
3039
3040       return 0;
3041     }
3042   return 0;
3043 }
3044
3045 /* Simplify conditional jump around an jump.  
3046    Return nonzero in case optimization matched.  */
3047
3048 static bool
3049 try_simplify_condjump (src)
3050      basic_block src;
3051 {
3052   basic_block final_block, next_block;
3053   rtx insn = src->end;
3054   edge branch, fallthru;
3055
3056   /* Verify that there are exactly two successors.  */
3057   if (!src->succ || !src->succ->succ_next || src->succ->succ_next->succ_next
3058       || !any_condjump_p (insn))
3059     return false;
3060
3061   fallthru = FALLTHRU_EDGE (src);
3062
3063   /* Following block must be simple forwarder block with single
3064      entry and must not be last in the stream.  */
3065   next_block = fallthru->dest;
3066   if (!forwarder_block_p (next_block)
3067       || next_block->pred->pred_next
3068       || next_block->index == n_basic_blocks - 1)
3069     return false;
3070
3071   /* The branch must target to block afterwards.  */
3072   final_block = BASIC_BLOCK (next_block->index + 1);
3073
3074   branch = BRANCH_EDGE (src);
3075
3076   if (branch->dest != final_block)
3077     return false;
3078
3079   /* Avoid jump.c from being overactive on removin ureachable insns.  */
3080   LABEL_NUSES (JUMP_LABEL (insn))++;
3081   if (!invert_jump (insn, block_label (next_block->succ->dest), 1))
3082     {
3083       LABEL_NUSES (JUMP_LABEL (insn))--;
3084       return false;
3085     }
3086   if (rtl_dump_file)
3087     fprintf (rtl_dump_file, "Simplifying condjump %i around jump %i\n",
3088              INSN_UID (insn), INSN_UID (next_block->end));
3089
3090   redirect_edge_succ (branch, final_block);
3091   redirect_edge_succ (fallthru, next_block->succ->dest);
3092
3093   branch->flags |= EDGE_FALLTHRU;
3094   fallthru->flags &= ~EDGE_FALLTHRU;
3095   
3096   flow_delete_block (next_block);
3097   return true;
3098 }
3099
3100 /* Attempt to forward edges leaving basic block B.
3101    Return nonzero if sucessfull.  */
3102
3103 static bool
3104 try_forward_edges (b)
3105      basic_block b;
3106 {
3107   bool changed = 0;
3108   edge e;
3109   for (e = b->succ; e; e = e->succ_next)
3110     {
3111       basic_block target = e->dest, first = e->dest;
3112       int counter = 0;
3113
3114       /* Look for the real destination of jump.
3115          Avoid inifinite loop in the infinite empty loop by counting
3116          up to n_basic_blocks.  */
3117       while (forwarder_block_p (target)
3118              && target->succ->dest != EXIT_BLOCK_PTR
3119              && counter < n_basic_blocks)
3120         {
3121           /* Bypass trivial infinite loops.  */
3122           if (target == target->succ->dest)
3123             counter = n_basic_blocks;
3124           target = target->succ->dest, counter++;
3125         }
3126
3127       if (target != first && counter < n_basic_blocks
3128           && redirect_edge_and_branch (e, target))
3129         {
3130           while (first != target)
3131             {
3132               first->count -= e->count;
3133               first->succ->count -= e->count;
3134               first->frequency -= ((e->probability * b->frequency
3135                                     + REG_BR_PROB_BASE / 2)
3136                                    / REG_BR_PROB_BASE);
3137               first = first->succ->dest;
3138             }
3139           /* We've possibly removed the edge.  */
3140           changed = 1;
3141           e = b->succ;
3142         }
3143       else if (rtl_dump_file && counter == n_basic_blocks)
3144         fprintf (rtl_dump_file, "Infinite loop in BB %i.\n", target->index);
3145       else if (rtl_dump_file && first != target)
3146         fprintf (rtl_dump_file,
3147                  "Forwarding edge %i->%i to %i failed.\n", b->index,
3148                  e->dest->index, target->index);
3149     }
3150   return changed;
3151 }
3152
3153 /* Compare the instructions before end of B1 and B2
3154    to find an opportunity for cross jumping.
3155    (This means detecting identical sequences of insns)
3156    Find the longest possible equivalent sequences
3157    and store the first insns of those sequences into *F1 and *F2
3158    and return length of that sequence.
3159
3160    To simplify callers of this function, in the
3161    all instructions were matched, allways store bb->head.  */
3162
3163 static int
3164 flow_find_cross_jump (mode, bb1, bb2, f1, f2)
3165      int mode;
3166      basic_block bb1, bb2;
3167      rtx *f1, *f2;
3168 {
3169   rtx i1 = onlyjump_p (bb1->end) ? PREV_INSN (bb1->end): bb1->end;
3170   rtx i2 = onlyjump_p (bb2->end) ? PREV_INSN (bb2->end): bb2->end;
3171   rtx p1, p2;
3172   int lose = 0;
3173   int ninsns = 0;
3174   rtx last1 = bb1->end, last2 = bb2->end;
3175   rtx afterlast1 = bb1->end, afterlast2 = bb2->end;
3176
3177   /* In case basic block ends by nontrivial jump instruction, count it as
3178      an instruction.  Do not count an unconditional jump, as it will be
3179      removed by basic_block reordering pass in case it is on the common
3180      path.  */
3181   if (bb1->succ->succ_next && bb1->end != i1)
3182     ninsns++;
3183
3184   for (;i1 != bb1->head; i1 = PREV_INSN (i1))
3185     {
3186       /* Ignore notes.  */
3187       if (GET_CODE (i1) == NOTE)
3188         continue;
3189       while ((GET_CODE (i2) == NOTE && i2 != bb2->head))
3190         i2 = PREV_INSN (i2);
3191
3192       if (GET_CODE (i1) != GET_CODE (i2))
3193         break;
3194
3195       p1 = PATTERN (i1);
3196       p2 = PATTERN (i2);
3197
3198       /* If this is a CALL_INSN, compare register usage information.
3199          If we don't check this on stack register machines, the two
3200          CALL_INSNs might be merged leaving reg-stack.c with mismatching
3201          numbers of stack registers in the same basic block.
3202          If we don't check this on machines with delay slots, a delay slot may
3203          be filled that clobbers a parameter expected by the subroutine.
3204
3205          ??? We take the simple route for now and assume that if they're
3206          equal, they were constructed identically.  */
3207
3208       if (GET_CODE (i1) == CALL_INSN
3209           && ! rtx_equal_p (CALL_INSN_FUNCTION_USAGE (i1),
3210                             CALL_INSN_FUNCTION_USAGE (i2)))
3211         lose = 1;
3212
3213 #ifdef STACK_REGS
3214       /* If cross_jump_death_matters is not 0, the insn's mode
3215          indicates whether or not the insn contains any stack-like
3216          regs.  */
3217
3218       if (!lose && (mode & CLEANUP_POST_REGSTACK ) && stack_regs_mentioned (i1))
3219         {
3220           /* If register stack conversion has already been done, then
3221              death notes must also be compared before it is certain that
3222              the two instruction streams match.  */
3223
3224           rtx note;
3225           HARD_REG_SET i1_regset, i2_regset;
3226
3227           CLEAR_HARD_REG_SET (i1_regset);
3228           CLEAR_HARD_REG_SET (i2_regset);
3229
3230           for (note = REG_NOTES (i1); note; note = XEXP (note, 1))
3231             if (REG_NOTE_KIND (note) == REG_DEAD
3232                 && STACK_REG_P (XEXP (note, 0)))
3233               SET_HARD_REG_BIT (i1_regset, REGNO (XEXP (note, 0)));
3234
3235           for (note = REG_NOTES (i2); note; note = XEXP (note, 1))
3236             if (REG_NOTE_KIND (note) == REG_DEAD
3237                 && STACK_REG_P (XEXP (note, 0)))
3238               SET_HARD_REG_BIT (i2_regset, REGNO (XEXP (note, 0)));
3239
3240           GO_IF_HARD_REG_EQUAL (i1_regset, i2_regset, done);
3241
3242           lose = 1;
3243
3244         done:
3245           ;
3246         }
3247 #endif
3248
3249       if (lose || GET_CODE (p1) != GET_CODE (p2)
3250           || ! rtx_renumbered_equal_p (p1, p2))
3251         {
3252           /* The following code helps take care of G++ cleanups.  */
3253           rtx equiv1;
3254           rtx equiv2;
3255
3256           if (!lose && GET_CODE (p1) == GET_CODE (p2)
3257               && ((equiv1 = find_reg_note (i1, REG_EQUAL, NULL_RTX)) != 0
3258                   || (equiv1 = find_reg_note (i1, REG_EQUIV, NULL_RTX)) != 0)
3259               && ((equiv2 = find_reg_note (i2, REG_EQUAL, NULL_RTX)) != 0
3260                   || (equiv2 = find_reg_note (i2, REG_EQUIV, NULL_RTX)) != 0)
3261               /* If the equivalences are not to a constant, they may
3262                  reference pseudos that no longer exist, so we can't
3263                  use them.  */
3264               && CONSTANT_P (XEXP (equiv1, 0))
3265               && rtx_equal_p (XEXP (equiv1, 0), XEXP (equiv2, 0)))
3266             {
3267               rtx s1 = single_set (i1);
3268               rtx s2 = single_set (i2);
3269               if (s1 != 0 && s2 != 0
3270                   && rtx_renumbered_equal_p (SET_DEST (s1), SET_DEST (s2)))
3271                 {
3272                   validate_change (i1, &SET_SRC (s1), XEXP (equiv1, 0), 1);
3273                   validate_change (i2, &SET_SRC (s2), XEXP (equiv2, 0), 1);
3274                   if (! rtx_renumbered_equal_p (p1, p2))
3275                     cancel_changes (0);
3276                   else if (apply_change_group ())
3277                     goto win;
3278                 }
3279             }
3280
3281           /* Insns fail to match; cross jumping is limited to the following
3282              insns.  */
3283
3284 #ifdef HAVE_cc0
3285           /* Don't allow the insn after a compare to be shared by
3286              cross-jumping unless the compare is also shared.
3287              Here, if either of these non-matching insns is a compare,
3288              exclude the following insn from possible cross-jumping.  */
3289           if (sets_cc0_p (p1) || sets_cc0_p (p2))
3290             last1 = afterlast1, last2 = afterlast2, ninsns--;
3291 #endif
3292           break;
3293         }
3294
3295     win:
3296       if (GET_CODE (p1) != USE && GET_CODE (p1) != CLOBBER)
3297         {
3298           /* Ok, this insn is potentially includable in a cross-jump here.  */
3299           afterlast1 = last1, afterlast2 = last2;
3300           last1 = i1, last2 = i2;
3301           ninsns++;
3302         }
3303
3304       if (i2 == bb2->end)
3305         break;
3306       i2 = PREV_INSN (i2);
3307     }
3308
3309   /* Skip the notes to reach potential head of basic block.  */
3310   while (last1 != bb1->head && GET_CODE (PREV_INSN (last1)) == NOTE)
3311     last1 = PREV_INSN (last1);
3312   if (last1 != bb1->head && GET_CODE (PREV_INSN (last1)) == CODE_LABEL)
3313     last1 = PREV_INSN (last1);
3314   while (last2 != bb2->head && GET_CODE (PREV_INSN (last2)) == NOTE)
3315     last2 = PREV_INSN (last2);
3316   if (last2 != bb2->head && GET_CODE (PREV_INSN (last2)) == CODE_LABEL)
3317     last2 = PREV_INSN (last2);
3318
3319   *f1 = last1;
3320   *f2 = last2;
3321   return ninsns;
3322 }
3323
3324 /* Return true iff outgoing edges of BB1 and BB2 match, together with
3325    the branch instruction.  This means that if we commonize the control
3326    flow before end of the basic block, the semantic remains unchanged.  
3327
3328    Assume that at least one outgoing edge is forwarded to the same
3329    location.  */
3330 static bool
3331 outgoing_edges_match (bb1, bb2)
3332      basic_block bb1;
3333      basic_block bb2;
3334 {
3335   /* bb1 has one succesor,  so we are seeing unconditional jump.  */
3336   if (bb1->succ && !bb1->succ->succ_next)
3337     return (bb2->succ && !bb2->succ->succ_next);
3338
3339   /* Match conditional jumps - this may get tricky when fallthru and branch
3340      edges are crossed.  */
3341   if (bb1->succ && bb1->succ->succ_next && !bb1->succ->succ_next->succ_next
3342       && any_condjump_p (bb1->end))
3343     {
3344       edge b1, f1, b2, f2;
3345       bool reverse, match;
3346       rtx set1, set2, cond1, cond2;
3347       enum rtx_code code1, code2;
3348
3349       if (!bb2->succ || !bb2->succ->succ_next
3350           || bb1->succ->succ_next->succ_next || !any_condjump_p (bb2->end))
3351         return false;
3352       b1 = BRANCH_EDGE (bb1);
3353       b2 = BRANCH_EDGE (bb2);
3354       f1 = FALLTHRU_EDGE (bb1);
3355       f2 = FALLTHRU_EDGE (bb2);
3356
3357       /* Get around possible forwarders on fallthru edges.  Other cases
3358          should be optimized out already.  */
3359       if (forwarder_block_p (f1->dest))
3360         f1 = f1->dest->succ;
3361       if (forwarder_block_p (f2->dest))
3362         f2 = f2->dest->succ;
3363
3364       /* To simplify use of this function, return false if there are
3365          unneeded forwarder blocks.  These will get eliminated later
3366          during cleanup_cfg.  */
3367       if (forwarder_block_p (f1->dest)
3368           || forwarder_block_p (f2->dest)
3369           || forwarder_block_p (b1->dest)
3370           || forwarder_block_p (b2->dest))
3371         return false;
3372
3373       if (f1->dest == f2->dest && b1->dest == b2->dest)
3374         reverse = false;
3375       else if (f1->dest == b2->dest && b1->dest == f2->dest)
3376         reverse = true;
3377       else
3378         return false;
3379
3380       set1 = pc_set (bb1->end);
3381       set2 = pc_set (bb2->end);
3382       if ((XEXP (SET_SRC (set1), 1) == pc_rtx)
3383           != (XEXP (SET_SRC (set2), 1) == pc_rtx))
3384         reverse = !reverse;
3385
3386       cond1 = XEXP (SET_SRC (set1), 0);
3387       cond2 = XEXP (SET_SRC (set2), 0);
3388       code1 = GET_CODE (cond1);
3389       if (reverse)
3390         code2 = reversed_comparison_code (cond2, bb2->end);
3391       else
3392         code2 = GET_CODE (cond2);
3393
3394       if (code2 == UNKNOWN)
3395         return false;
3396
3397       /* See if we don have (cross) match in the codes and operands.  */
3398       match = ((code1 == code2
3399                 && rtx_renumbered_equal_p (XEXP (cond1, 0), XEXP (cond2, 0))
3400                 && rtx_renumbered_equal_p (XEXP (cond1, 1), XEXP (cond2, 1)))
3401                || (code1 == swap_condition (code2)
3402                    && rtx_renumbered_equal_p (XEXP (cond1, 1),
3403                                               XEXP (cond2, 0))
3404                    && rtx_renumbered_equal_p (XEXP (cond1, 0),
3405                                               XEXP (cond2, 1))));
3406       /* In case of returning true, we will commonize the flow.
3407          This also means, that both branches will contain only single
3408          branch prediction algorithm.  To match require resulting branch
3409          to be still well predictable.  */
3410       if (match && !optimize_size)
3411         {
3412           rtx note1, note2;
3413           int prob1, prob2;
3414           note1 = find_reg_note (bb1->end, REG_BR_PROB, 0);
3415           note2 = find_reg_note (bb2->end, REG_BR_PROB, 0);
3416           if (!note1 || !note2)
3417             return false;
3418           prob1 = INTVAL (XEXP (note1, 0));
3419           prob2 = INTVAL (XEXP (note2, 0));
3420           if (reverse)
3421             prob2 = REG_BR_PROB_BASE - prob2;
3422
3423           /* ??? Later we should use basic block frequency to allow merging
3424              in the infrequent blocks, but at the moment it is not
3425              available when cleanup_cfg is run.  */
3426           if (abs (prob1 - prob2) > REG_BR_PROB_BASE / 90)
3427             return false;
3428         }
3429       if (rtl_dump_file && match)
3430         fprintf (rtl_dump_file, "Conditionals in bb %i and %i match.\n",
3431                  bb1->index, bb2->index);
3432       return match;
3433     }
3434   /* ??? We can handle computed jumps too.  This may be important for
3435      inlined functions containing switch statements.  Also jumps w/o
3436      fallthru edges can be handled by simply matching whole insn.  */
3437   return false;
3438 }
3439
3440 /* Assume that e1 and e2 are the edges from the same basic block.
3441    Attempt to find common code on both paths and forward control flow
3442    from the first path to second if such exist.  */
3443 static bool
3444 try_crossjump_to_edge (mode, e1, e2)
3445      int mode;
3446      edge e1, e2;
3447 {
3448   int nmatch;
3449   basic_block redirect_to;
3450   rtx newpos1, newpos2;
3451   rtx first, last;
3452   edge s;
3453   rtx label;
3454   rtx barrier;
3455
3456   /* Skip forwarder blocks.  This is needed to avoid forced forwarders
3457      after conditional jumps from making us to miss optimization.
3458
3459      We don't need to worry about multiple entry or chained forwarders, as they
3460      will be optimized out.  */
3461   if (e1->src->pred && !e1->src->pred->pred_next
3462       && forwarder_block_p (e1->src))
3463     e1 = e1->src->pred;
3464   if (e2->src->pred && !e2->src->pred->pred_next
3465       && forwarder_block_p (e2->src))
3466     e2 = e2->src->pred;
3467
3468   if (e1->src == ENTRY_BLOCK_PTR || e2->src == ENTRY_BLOCK_PTR)
3469     return false;
3470   if (e1->src == e2->src)
3471     return false;
3472
3473   /* Seeing more than 1 forwarder blocks would confuse us later...  */
3474   if (forwarder_block_p (e1->dest)
3475       && forwarder_block_p (e1->dest->succ->dest))
3476     return false;
3477   if (forwarder_block_p (e2->dest)
3478       && forwarder_block_p (e2->dest->succ->dest))
3479     return false;
3480   /* ... similary as seeing dead code...  */
3481   if (!e1->src->pred || !e2->src->pred)
3482     return false;
3483   /* ...similary non-jump edges.  */
3484   if (e1->flags & EDGE_COMPLEX)
3485     return false;
3486
3487   if (!outgoing_edges_match (e1->src, e2->src))
3488     return false;
3489   nmatch = flow_find_cross_jump (mode, e1->src, e2->src, &newpos1, &newpos2);
3490   if (!nmatch)
3491     return false;
3492
3493   /* Avoid splitting if possible.  */
3494   if (newpos2 == e2->src->head)
3495     redirect_to = e2->src;
3496   else
3497     {
3498       if (rtl_dump_file)
3499         fprintf (rtl_dump_file, "Splitting bb %i before %i insns\n",
3500                  e2->src->index, nmatch);
3501       redirect_to = split_block (e2->src, PREV_INSN (newpos2))->dest;
3502     }
3503
3504   if (rtl_dump_file)
3505     fprintf (rtl_dump_file,
3506              "Cross jumping from bb %i to bb %i. %i insn commoized\n",
3507              e1->src->index, e2->src->index, nmatch);
3508
3509   redirect_to->count += e1->src->count;
3510   redirect_to->frequency += e1->src->frequency;
3511
3512   /* Recompute the frequencies and counts of outgoing edges.  */
3513   for (s = redirect_to->succ; s; s = s->succ_next)
3514     {
3515       edge s2;
3516       basic_block d = (forwarder_block_p (s->dest) ? s->dest->succ->dest
3517                        : s->dest);
3518       for (s2 = e1->src->succ;; s2 = s2->succ_next)
3519         {
3520           basic_block d2 =
3521             (forwarder_block_p (s2->dest) ? s2->dest->succ->dest : s2->dest);
3522           if (d == d2)
3523             break;
3524         }
3525       s->count += s2->count;
3526
3527       /* Take care to update possible forwarder blocks.  We took care
3528          that there is no more than one in chain, so we can't run
3529          into infinite loop.  */
3530       if (forwarder_block_p (s->dest))
3531         {
3532           s->dest->succ->count += s2->count;
3533           s->dest->count += s2->count;
3534           s->dest->frequency += ((s->probability * s->src->frequency)
3535                                  / REG_BR_PROB_BASE);
3536         }
3537       if (forwarder_block_p (s2->dest))
3538         {
3539           s2->dest->succ->count -= s2->count;
3540           s2->dest->count -= s2->count;
3541           s2->dest->frequency -= ((s->probability * s->src->frequency)
3542                                   / REG_BR_PROB_BASE);
3543         }
3544       if (!redirect_to->frequency && !e1->src->frequency)
3545         s->probability = (s->probability + s2->probability) / 2;
3546       else
3547         s->probability =
3548           ((s->probability * redirect_to->frequency +
3549             s2->probability * e1->src->frequency)
3550            / (redirect_to->frequency + e1->src->frequency));
3551     }
3552
3553   /* FIXME: enable once probabilities are fetched properly at
3554      CFG build.  */
3555 #if 0
3556   note = find_reg_note (redirect_to->end, REG_BR_PROB, 0);
3557   if (note)
3558     XEXP (note, 0) = GEN_INT (BRANCH_EDGE (redirect_to)->probability);
3559 #endif
3560
3561   /* Skip possible basic block header.  */
3562   first = newpos1;
3563   if (GET_CODE (first) == CODE_LABEL)
3564     first = NEXT_INSN (first);
3565   if (GET_CODE (first) == NOTE)
3566     first = NEXT_INSN (first);
3567
3568   last = e1->src->end;
3569
3570   /* Now emit the jump insn.   */
3571   label = block_label (redirect_to);
3572   e1->src->end = emit_jump_insn_after (gen_jump (label), e1->src->end);
3573   JUMP_LABEL (e1->src->end) = label;
3574   LABEL_NUSES (label)++;
3575   if (basic_block_for_insn)
3576     set_block_for_new_insns (e1->src->end, e1->src);
3577
3578   flow_delete_insn_chain (first, last);
3579
3580   barrier = next_nonnote_insn (e1->src->end);
3581   if (!barrier || GET_CODE (barrier) != BARRIER)
3582     emit_barrier_after (e1->src->end);
3583
3584   /* Update CFG.  */
3585   while (e1->src->succ->succ_next)
3586     remove_edge (e1->src->succ);
3587   e1->src->succ->flags = 0;
3588   redirect_edge_succ (e1->src->succ, redirect_to);
3589   return true;
3590 }
3591
3592 /* Attempt to implement cross jumping.  This means moving one or more branches
3593    to BB earlier to BB predecesors commonizing some code.  */
3594 static bool
3595 try_crossjump_bb (mode, bb)
3596      int mode;
3597      basic_block bb;
3598 {
3599   edge e, e2, nexte2, nexte, fallthru;
3600   bool changed = false;
3601
3602   /* In case basic block has single predecesor, do nothing.  */
3603   if (!bb->pred || !bb->pred->pred_next)
3604     return false;
3605
3606   /* It is always cheapest to jump into fallthru edge.  */
3607   for (fallthru = bb->pred; fallthru; fallthru = fallthru->pred_next)
3608     if (fallthru->flags & EDGE_FALLTHRU)
3609       break;
3610
3611   for (e = bb->pred; e; e = nexte)
3612     {
3613       nexte = e->pred_next;
3614       /* First of all prioritize the fallthru edge, as the cheapest.  */
3615       if (e != fallthru && fallthru
3616           && try_crossjump_to_edge (mode, e, fallthru))
3617         changed = true, nexte = bb->pred;
3618       else
3619         /* Try match in other incomming edges.
3620
3621            Loop only over the earlier edges to avoid,as the later
3622            will be examined in the oposite direction.  */
3623         for (e2 = bb->pred; e2 != e; e2 = nexte2)
3624           {
3625             nexte2 = e2->pred_next;
3626             if (e2 != fallthru && try_crossjump_to_edge (mode, e, e2))
3627               {
3628                 changed = true;
3629                 nexte = bb->pred;
3630
3631                 /* We may've removed the fallthru edge.  */
3632                 for (fallthru = bb->pred; fallthru;
3633                      fallthru = fallthru->pred_next)
3634                   if (fallthru->flags & EDGE_FALLTHRU)
3635                     break;
3636                 break;
3637               }
3638           }
3639     }
3640   return changed;
3641 }
3642
3643 /* Do simple CFG optimizations - basic block merging, simplifying of jump
3644    instructions etc.
3645
3646    Return nonzero in case some optimizations matched.  */
3647
3648 static bool
3649 try_optimize_cfg (mode)
3650      int mode;
3651 {
3652   int i;
3653   bool changed_overall = 0;
3654   bool changed;
3655   int iterations = 0;
3656
3657   /* Attempt to merge blocks as made possible by edge removal.  If a block
3658      has only one successor, and the successor has only one predecessor,
3659      they may be combined.  */
3660
3661   do
3662     {
3663       changed = 0;
3664       iterations++;
3665       if (rtl_dump_file)
3666         fprintf (rtl_dump_file, "\n\ntry_optimize_cfg iteration %i\n\n",
3667                  iterations);
3668       for (i = 0; i < n_basic_blocks;)
3669         {
3670           basic_block c, b = BASIC_BLOCK (i);
3671           edge s;
3672           int changed_here = 0;
3673
3674           /* Delete trivially dead basic blocks.  */
3675           while (b->pred == NULL)
3676             {
3677               c = BASIC_BLOCK (b->index - 1);
3678               if (rtl_dump_file)
3679                 fprintf (rtl_dump_file, "Deleting block %i.\n", b->index);
3680               flow_delete_block (b);
3681               changed = 1;
3682               b = c;
3683             }
3684           /* Remove code labels no longer used.  
3685              Don't do the optimization before sibling calls are discovered,
3686              as some branches may be hidden inside CALL_PLACEHOLDERs.  */
3687           if (b->pred->pred_next == NULL
3688               && (b->pred->flags & EDGE_FALLTHRU)
3689               && !(b->pred->flags & EDGE_COMPLEX)
3690               && GET_CODE (b->head) == CODE_LABEL
3691               && (!(mode & CLEANUP_PRE_SIBCALL)
3692                   || !tail_recursion_label_p (b->head))
3693               /* If previous block does end with condjump jumping to next BB,
3694                  we can't delete the label.  */
3695               && (b->pred->src == ENTRY_BLOCK_PTR
3696                   || !reg_mentioned_p (b->head, b->pred->src->end)))
3697             {
3698               rtx label = b->head;
3699               b->head = NEXT_INSN (b->head);
3700               flow_delete_insn_chain (label, label);
3701               if (rtl_dump_file)
3702                 fprintf (rtl_dump_file, "Deleted label in block %i.\n",
3703                          b->index);
3704             }
3705           /* The fallthru forwarder block can be deleted.  */
3706           if (b->pred->pred_next == NULL
3707               && forwarder_block_p (b)
3708               && n_basic_blocks > 1
3709               && (b->pred->flags & EDGE_FALLTHRU)
3710               && (b->succ->flags & EDGE_FALLTHRU)
3711               && GET_CODE (b->head) != CODE_LABEL)
3712             {
3713               if (rtl_dump_file)
3714                 fprintf (rtl_dump_file, "Deleting fallthru block %i.\n",
3715                          b->index);
3716               c = BASIC_BLOCK (i ? i - 1 : i + 1);
3717               redirect_edge_succ (b->pred, b->succ->dest);
3718               flow_delete_block (b);
3719               changed = 1;
3720               b = c;
3721             }
3722
3723
3724           /* A loop because chains of blocks might be combineable.  */
3725           while ((s = b->succ) != NULL
3726                  && s->succ_next == NULL
3727                  && (s->flags & EDGE_EH) == 0
3728                  && (c = s->dest) != EXIT_BLOCK_PTR
3729                  && !(s->flags & EDGE_COMPLEX)
3730                  && c->pred->pred_next == NULL
3731                  /* If the jump insn has side effects,
3732                     we can't kill the edge.  */
3733                  && (GET_CODE (b->end) != JUMP_INSN
3734                      || onlyjump_p (b->end)) && merge_blocks (s, b, c, mode))
3735             changed_here = 1;
3736
3737           if ((mode & CLEANUP_EXPENSIVE) && try_simplify_condjump (b))
3738             changed_here = 1;
3739
3740           /* In the case basic blocks has single outgoing edge, but over by the
3741              non-trivial jump instruction, we can replace it by unconditional
3742              jump, or delete the jump completely.  Use logic of
3743              redirect_edge_and_branch to do the dirty job for us.  
3744
3745              We match cases as conditional jumps jumping to the next block or
3746              dispatch tables.  */
3747
3748           if (b->succ
3749               && b->succ->succ_next == NULL
3750               && GET_CODE (b->end) == JUMP_INSN
3751               && b->succ->dest != EXIT_BLOCK_PTR
3752               && redirect_edge_and_branch (b->succ, b->succ->dest))
3753             changed_here = 1;
3754
3755           if (try_forward_edges (b))
3756             changed_here = 1;
3757
3758           if ((mode & CLEANUP_CROSSJUMP) && try_crossjump_bb (mode, b))
3759             changed_here = 1;
3760
3761           /* Don't get confused by the index shift caused by deleting
3762              blocks.  */
3763           if (!changed_here)
3764             i = b->index + 1;
3765           else
3766             changed = 1;
3767         }
3768       if ((mode & CLEANUP_CROSSJUMP) && try_crossjump_bb (mode, EXIT_BLOCK_PTR))
3769         changed = 1;
3770 #ifdef ENABLE_CHECKING
3771       if (changed)
3772         verify_flow_info ();
3773 #endif
3774       changed_overall |= changed;
3775     }
3776   while (changed);
3777   return changed_overall;
3778 }
3779
3780 /* The given edge should potentially be a fallthru edge.  If that is in
3781    fact true, delete the jump and barriers that are in the way.  */
3782
3783 void
3784 tidy_fallthru_edge (e, b, c)
3785      edge e;
3786      basic_block b, c;
3787 {
3788   rtx q;
3789
3790   /* ??? In a late-running flow pass, other folks may have deleted basic
3791      blocks by nopping out blocks, leaving multiple BARRIERs between here
3792      and the target label. They ought to be chastized and fixed.
3793
3794      We can also wind up with a sequence of undeletable labels between
3795      one block and the next.
3796
3797      So search through a sequence of barriers, labels, and notes for
3798      the head of block C and assert that we really do fall through.  */
3799
3800   if (next_real_insn (b->end) != next_real_insn (PREV_INSN (c->head)))
3801     return;
3802
3803   /* Remove what will soon cease being the jump insn from the source block.
3804      If block B consisted only of this single jump, turn it into a deleted
3805      note.  */
3806   q = b->end;
3807   if (GET_CODE (q) == JUMP_INSN
3808       && onlyjump_p (q)
3809       && (any_uncondjump_p (q)
3810           || (b->succ == e && e->succ_next == NULL)))
3811     {
3812 #ifdef HAVE_cc0
3813       /* If this was a conditional jump, we need to also delete
3814          the insn that set cc0.  */
3815       if (any_condjump_p (q) && sets_cc0_p (PREV_INSN (q)))
3816         q = PREV_INSN (q);
3817 #endif
3818
3819       if (b->head == q)
3820         {
3821           PUT_CODE (q, NOTE);
3822           NOTE_LINE_NUMBER (q) = NOTE_INSN_DELETED;
3823           NOTE_SOURCE_FILE (q) = 0;
3824         }
3825       else
3826         {
3827           q = PREV_INSN (q);
3828
3829           /* We don't want a block to end on a line-number note since that has
3830              the potential of changing the code between -g and not -g.  */
3831           while (GET_CODE (q) == NOTE && NOTE_LINE_NUMBER (q) >= 0)
3832             q = PREV_INSN (q);
3833         }
3834
3835       b->end = q;
3836     }
3837
3838   /* Selectively unlink the sequence.  */
3839   if (q != PREV_INSN (c->head))
3840     flow_delete_insn_chain (NEXT_INSN (q), PREV_INSN (c->head));
3841
3842   e->flags |= EDGE_FALLTHRU;
3843 }
3844
3845 /* Fix up edges that now fall through, or rather should now fall through
3846    but previously required a jump around now deleted blocks.  Simplify
3847    the search by only examining blocks numerically adjacent, since this
3848    is how find_basic_blocks created them.  */
3849
3850 static void
3851 tidy_fallthru_edges ()
3852 {
3853   int i;
3854
3855   for (i = 1; i < n_basic_blocks; ++i)
3856     {
3857       basic_block b = BASIC_BLOCK (i - 1);
3858       basic_block c = BASIC_BLOCK (i);
3859       edge s;
3860
3861       /* We care about simple conditional or unconditional jumps with
3862          a single successor.
3863
3864          If we had a conditional branch to the next instruction when
3865          find_basic_blocks was called, then there will only be one
3866          out edge for the block which ended with the conditional
3867          branch (since we do not create duplicate edges).
3868
3869          Furthermore, the edge will be marked as a fallthru because we
3870          merge the flags for the duplicate edges.  So we do not want to
3871          check that the edge is not a FALLTHRU edge.  */
3872       if ((s = b->succ) != NULL
3873           && ! (s->flags & EDGE_COMPLEX)
3874           && s->succ_next == NULL
3875           && s->dest == c
3876           /* If the jump insn has side effects, we can't tidy the edge.  */
3877           && (GET_CODE (b->end) != JUMP_INSN
3878               || onlyjump_p (b->end)))
3879         tidy_fallthru_edge (s, b, c);
3880     }
3881 }
3882 \f
3883 /* Perform data flow analysis.
3884    F is the first insn of the function; FLAGS is a set of PROP_* flags
3885    to be used in accumulating flow info.  */
3886
3887 void
3888 life_analysis (f, file, flags)
3889      rtx f;
3890      FILE *file;
3891      int flags;
3892 {
3893 #ifdef ELIMINABLE_REGS
3894   register int i;
3895   static struct {int from, to; } eliminables[] = ELIMINABLE_REGS;
3896 #endif
3897
3898   /* Record which registers will be eliminated.  We use this in
3899      mark_used_regs.  */
3900
3901   CLEAR_HARD_REG_SET (elim_reg_set);
3902
3903 #ifdef ELIMINABLE_REGS
3904   for (i = 0; i < (int) ARRAY_SIZE (eliminables); i++)
3905     SET_HARD_REG_BIT (elim_reg_set, eliminables[i].from);
3906 #else
3907   SET_HARD_REG_BIT (elim_reg_set, FRAME_POINTER_REGNUM);
3908 #endif
3909
3910   if (! optimize)
3911     flags &= ~(PROP_LOG_LINKS | PROP_AUTOINC);
3912
3913   /* The post-reload life analysis have (on a global basis) the same
3914      registers live as was computed by reload itself.  elimination
3915      Otherwise offsets and such may be incorrect.
3916
3917      Reload will make some registers as live even though they do not
3918      appear in the rtl.
3919
3920      We don't want to create new auto-incs after reload, since they
3921      are unlikely to be useful and can cause problems with shared
3922      stack slots.  */
3923   if (reload_completed)
3924     flags &= ~(PROP_REG_INFO | PROP_AUTOINC);
3925
3926   /* We want alias analysis information for local dead store elimination.  */
3927   if (optimize && (flags & PROP_SCAN_DEAD_CODE))
3928     init_alias_analysis ();
3929
3930   /* Always remove no-op moves.  Do this before other processing so
3931      that we don't have to keep re-scanning them.  */
3932   delete_noop_moves (f);
3933
3934   /* Some targets can emit simpler epilogues if they know that sp was
3935      not ever modified during the function.  After reload, of course,
3936      we've already emitted the epilogue so there's no sense searching.  */
3937   if (! reload_completed)
3938     notice_stack_pointer_modification (f);
3939
3940   /* Allocate and zero out data structures that will record the
3941      data from lifetime analysis.  */
3942   allocate_reg_life_data ();
3943   allocate_bb_life_data ();
3944
3945   /* Find the set of registers live on function exit.  */
3946   mark_regs_live_at_end (EXIT_BLOCK_PTR->global_live_at_start);
3947
3948   /* "Update" life info from zero.  It'd be nice to begin the
3949      relaxation with just the exit and noreturn blocks, but that set
3950      is not immediately handy.  */
3951
3952   if (flags & PROP_REG_INFO)
3953     memset (regs_ever_live, 0, sizeof (regs_ever_live));
3954   update_life_info (NULL, UPDATE_LIFE_GLOBAL, flags);
3955
3956   /* Clean up.  */
3957   if (optimize && (flags & PROP_SCAN_DEAD_CODE))
3958     end_alias_analysis ();
3959
3960   if (file)
3961     dump_flow_info (file);
3962
3963   free_basic_block_vars (1);
3964
3965 #ifdef ENABLE_CHECKING
3966   {
3967     rtx insn;
3968
3969     /* Search for any REG_LABEL notes which reference deleted labels.  */
3970     for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
3971       {
3972         rtx inote = find_reg_note (insn, REG_LABEL, NULL_RTX);
3973
3974         if (inote && GET_CODE (inote) == NOTE_INSN_DELETED_LABEL)
3975           abort ();
3976       }
3977   }
3978 #endif
3979 }
3980
3981 /* A subroutine of verify_wide_reg, called through for_each_rtx.
3982    Search for REGNO.  If found, abort if it is not wider than word_mode.  */
3983
3984 static int
3985 verify_wide_reg_1 (px, pregno)
3986      rtx *px;
3987      void *pregno;
3988 {
3989   rtx x = *px;
3990   unsigned int regno = *(int *) pregno;
3991
3992   if (GET_CODE (x) == REG && REGNO (x) == regno)
3993     {
3994       if (GET_MODE_BITSIZE (GET_MODE (x)) <= BITS_PER_WORD)
3995         abort ();
3996       return 1;
3997     }
3998   return 0;
3999 }
4000
4001 /* A subroutine of verify_local_live_at_start.  Search through insns
4002    between HEAD and END looking for register REGNO.  */
4003
4004 static void
4005 verify_wide_reg (regno, head, end)
4006      int regno;
4007      rtx head, end;
4008 {
4009   while (1)
4010     {
4011       if (INSN_P (head)
4012           && for_each_rtx (&PATTERN (head), verify_wide_reg_1, &regno))
4013         return;
4014       if (head == end)
4015         break;
4016       head = NEXT_INSN (head);
4017     }
4018
4019   /* We didn't find the register at all.  Something's way screwy.  */
4020   if (rtl_dump_file)
4021     fprintf (rtl_dump_file, "Aborting in verify_wide_reg; reg %d\n", regno);
4022   print_rtl_and_abort ();
4023 }
4024
4025 /* A subroutine of update_life_info.  Verify that there are no untoward
4026    changes in live_at_start during a local update.  */
4027
4028 static void
4029 verify_local_live_at_start (new_live_at_start, bb)
4030      regset new_live_at_start;
4031      basic_block bb;
4032 {
4033   if (reload_completed)
4034     {
4035       /* After reload, there are no pseudos, nor subregs of multi-word
4036          registers.  The regsets should exactly match.  */
4037       if (! REG_SET_EQUAL_P (new_live_at_start, bb->global_live_at_start))
4038         {
4039           if (rtl_dump_file)
4040             {
4041               fprintf (rtl_dump_file,
4042                        "live_at_start mismatch in bb %d, aborting\n",
4043                        bb->index);
4044               debug_bitmap_file (rtl_dump_file, bb->global_live_at_start);
4045               debug_bitmap_file (rtl_dump_file, new_live_at_start);
4046             }
4047           print_rtl_and_abort ();
4048         }
4049     }
4050   else
4051     {
4052       int i;
4053
4054       /* Find the set of changed registers.  */
4055       XOR_REG_SET (new_live_at_start, bb->global_live_at_start);
4056
4057       EXECUTE_IF_SET_IN_REG_SET (new_live_at_start, 0, i,
4058         {
4059           /* No registers should die.  */
4060           if (REGNO_REG_SET_P (bb->global_live_at_start, i))
4061             {
4062               if (rtl_dump_file)
4063                 fprintf (rtl_dump_file,
4064                          "Register %d died unexpectedly in block %d\n", i,
4065                          bb->index);
4066               print_rtl_and_abort ();
4067             }
4068
4069           /* Verify that the now-live register is wider than word_mode.  */
4070           verify_wide_reg (i, bb->head, bb->end);
4071         });
4072     }
4073 }
4074
4075 /* Updates life information starting with the basic blocks set in BLOCKS.
4076    If BLOCKS is null, consider it to be the universal set.
4077
4078    If EXTENT is UPDATE_LIFE_LOCAL, such as after splitting or peepholeing,
4079    we are only expecting local modifications to basic blocks.  If we find
4080    extra registers live at the beginning of a block, then we either killed
4081    useful data, or we have a broken split that wants data not provided.
4082    If we find registers removed from live_at_start, that means we have
4083    a broken peephole that is killing a register it shouldn't.
4084
4085    ??? This is not true in one situation -- when a pre-reload splitter
4086    generates subregs of a multi-word pseudo, current life analysis will
4087    lose the kill.  So we _can_ have a pseudo go live.  How irritating.
4088
4089    Including PROP_REG_INFO does not properly refresh regs_ever_live
4090    unless the caller resets it to zero.  */
4091
4092 void
4093 update_life_info (blocks, extent, prop_flags)
4094      sbitmap blocks;
4095      enum update_life_extent extent;
4096      int prop_flags;
4097 {
4098   regset tmp;
4099   regset_head tmp_head;
4100   int i;
4101
4102   tmp = INITIALIZE_REG_SET (tmp_head);
4103
4104   /* For a global update, we go through the relaxation process again.  */
4105   if (extent != UPDATE_LIFE_LOCAL)
4106     {
4107       calculate_global_regs_live (blocks, blocks,
4108                                   prop_flags & PROP_SCAN_DEAD_CODE);
4109
4110       /* If asked, remove notes from the blocks we'll update.  */
4111       if (extent == UPDATE_LIFE_GLOBAL_RM_NOTES)
4112         count_or_remove_death_notes (blocks, 1);
4113     }
4114
4115   if (blocks)
4116     {
4117       EXECUTE_IF_SET_IN_SBITMAP (blocks, 0, i,
4118         {
4119           basic_block bb = BASIC_BLOCK (i);
4120
4121           COPY_REG_SET (tmp, bb->global_live_at_end);
4122           propagate_block (bb, tmp, NULL, NULL, prop_flags);
4123
4124           if (extent == UPDATE_LIFE_LOCAL)
4125             verify_local_live_at_start (tmp, bb);
4126         });
4127     }
4128   else
4129     {
4130       for (i = n_basic_blocks - 1; i >= 0; --i)
4131         {
4132           basic_block bb = BASIC_BLOCK (i);
4133
4134           COPY_REG_SET (tmp, bb->global_live_at_end);
4135           propagate_block (bb, tmp, NULL, NULL, prop_flags);
4136
4137           if (extent == UPDATE_LIFE_LOCAL)
4138             verify_local_live_at_start (tmp, bb);
4139         }
4140     }
4141
4142   FREE_REG_SET (tmp);
4143
4144   if (prop_flags & PROP_REG_INFO)
4145     {
4146       /* The only pseudos that are live at the beginning of the function
4147          are those that were not set anywhere in the function.  local-alloc
4148          doesn't know how to handle these correctly, so mark them as not
4149          local to any one basic block.  */
4150       EXECUTE_IF_SET_IN_REG_SET (ENTRY_BLOCK_PTR->global_live_at_end,
4151                                  FIRST_PSEUDO_REGISTER, i,
4152                                  { REG_BASIC_BLOCK (i) = REG_BLOCK_GLOBAL; });
4153
4154       /* We have a problem with any pseudoreg that lives across the setjmp.
4155          ANSI says that if a user variable does not change in value between
4156          the setjmp and the longjmp, then the longjmp preserves it.  This
4157          includes longjmp from a place where the pseudo appears dead.
4158          (In principle, the value still exists if it is in scope.)
4159          If the pseudo goes in a hard reg, some other value may occupy
4160          that hard reg where this pseudo is dead, thus clobbering the pseudo.
4161          Conclusion: such a pseudo must not go in a hard reg.  */
4162       EXECUTE_IF_SET_IN_REG_SET (regs_live_at_setjmp,
4163                                  FIRST_PSEUDO_REGISTER, i,
4164                                  {
4165                                    if (regno_reg_rtx[i] != 0)
4166                                      {
4167                                        REG_LIVE_LENGTH (i) = -1;
4168                                        REG_BASIC_BLOCK (i) = REG_BLOCK_UNKNOWN;
4169                                      }
4170                                  });
4171     }
4172 }
4173
4174 /* Free the variables allocated by find_basic_blocks.
4175
4176    KEEP_HEAD_END_P is non-zero if basic_block_info is not to be freed.  */
4177
4178 void
4179 free_basic_block_vars (keep_head_end_p)
4180      int keep_head_end_p;
4181 {
4182   if (basic_block_for_insn)
4183     {
4184       VARRAY_FREE (basic_block_for_insn);
4185       basic_block_for_insn = NULL;
4186     }
4187
4188   if (! keep_head_end_p)
4189     {
4190       if (basic_block_info)
4191         {
4192           clear_edges ();
4193           VARRAY_FREE (basic_block_info);
4194         }
4195       n_basic_blocks = 0;
4196
4197       ENTRY_BLOCK_PTR->aux = NULL;
4198       ENTRY_BLOCK_PTR->global_live_at_end = NULL;
4199       EXIT_BLOCK_PTR->aux = NULL;
4200       EXIT_BLOCK_PTR->global_live_at_start = NULL;
4201     }
4202 }
4203
4204 /* Return nonzero if an insn consists only of SETs, each of which only sets a
4205    value to itself.  */
4206
4207 static int
4208 noop_move_p (insn)
4209      rtx insn;
4210 {
4211   rtx pat = PATTERN (insn);
4212
4213   /* Insns carrying these notes are useful later on.  */
4214   if (find_reg_note (insn, REG_EQUAL, NULL_RTX))
4215     return 0;
4216
4217   if (GET_CODE (pat) == SET && set_noop_p (pat))
4218     return 1;
4219
4220   if (GET_CODE (pat) == PARALLEL)
4221     {
4222       int i;
4223       /* If nothing but SETs of registers to themselves,
4224          this insn can also be deleted.  */
4225       for (i = 0; i < XVECLEN (pat, 0); i++)
4226         {
4227           rtx tem = XVECEXP (pat, 0, i);
4228
4229           if (GET_CODE (tem) == USE
4230               || GET_CODE (tem) == CLOBBER)
4231             continue;
4232
4233           if (GET_CODE (tem) != SET || ! set_noop_p (tem))
4234             return 0;
4235         }
4236
4237       return 1;
4238     }
4239   return 0;
4240 }
4241
4242 /* Delete any insns that copy a register to itself.  */
4243
4244 static void
4245 delete_noop_moves (f)
4246      rtx f;
4247 {
4248   rtx insn;
4249   for (insn = f; insn; insn = NEXT_INSN (insn))
4250     {
4251       if (GET_CODE (insn) == INSN && noop_move_p (insn))
4252         {
4253           PUT_CODE (insn, NOTE);
4254           NOTE_LINE_NUMBER (insn) = NOTE_INSN_DELETED;
4255           NOTE_SOURCE_FILE (insn) = 0;
4256         }
4257     }
4258 }
4259
4260 /* Determine if the stack pointer is constant over the life of the function.
4261    Only useful before prologues have been emitted.  */
4262
4263 static void
4264 notice_stack_pointer_modification_1 (x, pat, data)
4265      rtx x;
4266      rtx pat ATTRIBUTE_UNUSED;
4267      void *data ATTRIBUTE_UNUSED;
4268 {
4269   if (x == stack_pointer_rtx
4270       /* The stack pointer is only modified indirectly as the result
4271          of a push until later in flow.  See the comments in rtl.texi
4272          regarding Embedded Side-Effects on Addresses.  */
4273       || (GET_CODE (x) == MEM
4274           && GET_RTX_CLASS (GET_CODE (XEXP (x, 0))) == 'a'
4275           && XEXP (XEXP (x, 0), 0) == stack_pointer_rtx))
4276     current_function_sp_is_unchanging = 0;
4277 }
4278
4279 static void
4280 notice_stack_pointer_modification (f)
4281      rtx f;
4282 {
4283   rtx insn;
4284
4285   /* Assume that the stack pointer is unchanging if alloca hasn't
4286      been used.  */
4287   current_function_sp_is_unchanging = !current_function_calls_alloca;
4288   if (! current_function_sp_is_unchanging)
4289     return;
4290
4291   for (insn = f; insn; insn = NEXT_INSN (insn))
4292     {
4293       if (INSN_P (insn))
4294         {
4295           /* Check if insn modifies the stack pointer.  */
4296           note_stores (PATTERN (insn), notice_stack_pointer_modification_1,
4297                        NULL);
4298           if (! current_function_sp_is_unchanging)
4299             return;
4300         }
4301     }
4302 }
4303
4304 /* Mark a register in SET.  Hard registers in large modes get all
4305    of their component registers set as well.  */
4306
4307 static void
4308 mark_reg (reg, xset)
4309      rtx reg;
4310      void *xset;
4311 {
4312   regset set = (regset) xset;
4313   int regno = REGNO (reg);
4314
4315   if (GET_MODE (reg) == BLKmode)
4316     abort ();
4317
4318   SET_REGNO_REG_SET (set, regno);
4319   if (regno < FIRST_PSEUDO_REGISTER)
4320     {
4321       int n = HARD_REGNO_NREGS (regno, GET_MODE (reg));
4322       while (--n > 0)
4323         SET_REGNO_REG_SET (set, regno + n);
4324     }
4325 }
4326
4327 /* Mark those regs which are needed at the end of the function as live
4328    at the end of the last basic block.  */
4329
4330 static void
4331 mark_regs_live_at_end (set)
4332      regset set;
4333 {
4334   unsigned int i;
4335
4336   /* If exiting needs the right stack value, consider the stack pointer
4337      live at the end of the function.  */
4338   if ((HAVE_epilogue && reload_completed)
4339       || ! EXIT_IGNORE_STACK
4340       || (! FRAME_POINTER_REQUIRED
4341           && ! current_function_calls_alloca
4342           && flag_omit_frame_pointer)
4343       || current_function_sp_is_unchanging)
4344     {
4345       SET_REGNO_REG_SET (set, STACK_POINTER_REGNUM);
4346     }
4347
4348   /* Mark the frame pointer if needed at the end of the function.  If
4349      we end up eliminating it, it will be removed from the live list
4350      of each basic block by reload.  */
4351
4352   if (! reload_completed || frame_pointer_needed)
4353     {
4354       SET_REGNO_REG_SET (set, FRAME_POINTER_REGNUM);
4355 #if FRAME_POINTER_REGNUM != HARD_FRAME_POINTER_REGNUM
4356       /* If they are different, also mark the hard frame pointer as live.  */
4357       if (! LOCAL_REGNO (HARD_FRAME_POINTER_REGNUM))
4358         SET_REGNO_REG_SET (set, HARD_FRAME_POINTER_REGNUM);
4359 #endif
4360     }
4361
4362 #ifndef PIC_OFFSET_TABLE_REG_CALL_CLOBBERED
4363   /* Many architectures have a GP register even without flag_pic.
4364      Assume the pic register is not in use, or will be handled by
4365      other means, if it is not fixed.  */
4366   if (PIC_OFFSET_TABLE_REGNUM != INVALID_REGNUM
4367       && fixed_regs[PIC_OFFSET_TABLE_REGNUM])
4368     SET_REGNO_REG_SET (set, PIC_OFFSET_TABLE_REGNUM);
4369 #endif
4370
4371   /* Mark all global registers, and all registers used by the epilogue
4372      as being live at the end of the function since they may be
4373      referenced by our caller.  */
4374   for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
4375     if (global_regs[i] || EPILOGUE_USES (i))
4376       SET_REGNO_REG_SET (set, i);
4377
4378   if (HAVE_epilogue && reload_completed)
4379     {
4380       /* Mark all call-saved registers that we actually used.  */
4381       for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
4382         if (regs_ever_live[i] && ! call_used_regs[i] && ! LOCAL_REGNO (i))
4383           SET_REGNO_REG_SET (set, i);
4384     }
4385
4386 #ifdef EH_RETURN_DATA_REGNO
4387   /* Mark the registers that will contain data for the handler.  */
4388   if (reload_completed && current_function_calls_eh_return)
4389     for (i = 0; ; ++i)
4390       {
4391         unsigned regno = EH_RETURN_DATA_REGNO(i);
4392         if (regno == INVALID_REGNUM)
4393           break;
4394         SET_REGNO_REG_SET (set, regno);
4395       }
4396 #endif
4397 #ifdef EH_RETURN_STACKADJ_RTX
4398   if ((! HAVE_epilogue || ! reload_completed)
4399       && current_function_calls_eh_return)
4400     {
4401       rtx tmp = EH_RETURN_STACKADJ_RTX;
4402       if (tmp && REG_P (tmp))
4403         mark_reg (tmp, set);
4404     }
4405 #endif
4406 #ifdef EH_RETURN_HANDLER_RTX
4407   if ((! HAVE_epilogue || ! reload_completed)
4408       && current_function_calls_eh_return)
4409     {
4410       rtx tmp = EH_RETURN_HANDLER_RTX;
4411       if (tmp && REG_P (tmp))
4412         mark_reg (tmp, set);
4413     }
4414 #endif
4415
4416   /* Mark function return value.  */
4417   diddle_return_value (mark_reg, set);
4418 }
4419
4420 /* Callback function for for_each_successor_phi.  DATA is a regset.
4421    Sets the SRC_REGNO, the regno of the phi alternative for phi node
4422    INSN, in the regset.  */
4423
4424 static int
4425 set_phi_alternative_reg (insn, dest_regno, src_regno, data)
4426      rtx insn ATTRIBUTE_UNUSED;
4427      int dest_regno ATTRIBUTE_UNUSED;
4428      int src_regno;
4429      void *data;
4430 {
4431   regset live = (regset) data;
4432   SET_REGNO_REG_SET (live, src_regno);
4433   return 0;
4434 }
4435
4436 /* Propagate global life info around the graph of basic blocks.  Begin
4437    considering blocks with their corresponding bit set in BLOCKS_IN.
4438    If BLOCKS_IN is null, consider it the universal set.
4439
4440    BLOCKS_OUT is set for every block that was changed.  */
4441
4442 static void
4443 calculate_global_regs_live (blocks_in, blocks_out, flags)
4444      sbitmap blocks_in, blocks_out;
4445      int flags;
4446 {
4447   basic_block *queue, *qhead, *qtail, *qend;
4448   regset tmp, new_live_at_end, call_used;
4449   regset_head tmp_head, call_used_head;
4450   regset_head new_live_at_end_head;
4451   int i;
4452
4453   tmp = INITIALIZE_REG_SET (tmp_head);
4454   new_live_at_end = INITIALIZE_REG_SET (new_live_at_end_head);
4455   call_used = INITIALIZE_REG_SET (call_used_head);
4456
4457   /* Inconveniently, this is only redily available in hard reg set form.  */
4458   for (i = 0; i < FIRST_PSEUDO_REGISTER; ++i)
4459     if (call_used_regs[i])
4460       SET_REGNO_REG_SET (call_used, i);
4461
4462   /* Create a worklist.  Allocate an extra slot for ENTRY_BLOCK, and one
4463      because the `head == tail' style test for an empty queue doesn't
4464      work with a full queue.  */
4465   queue = (basic_block *) xmalloc ((n_basic_blocks + 2) * sizeof (*queue));
4466   qtail = queue;
4467   qhead = qend = queue + n_basic_blocks + 2;
4468
4469   /* Queue the blocks set in the initial mask.  Do this in reverse block
4470      number order so that we are more likely for the first round to do
4471      useful work.  We use AUX non-null to flag that the block is queued.  */
4472   if (blocks_in)
4473     {
4474       /* Clear out the garbage that might be hanging out in bb->aux.  */
4475       for (i = n_basic_blocks - 1; i >= 0; --i)
4476         BASIC_BLOCK (i)->aux = NULL;
4477
4478       EXECUTE_IF_SET_IN_SBITMAP (blocks_in, 0, i,
4479         {
4480           basic_block bb = BASIC_BLOCK (i);
4481           *--qhead = bb;
4482           bb->aux = bb;
4483         });
4484     }
4485   else
4486     {
4487       for (i = 0; i < n_basic_blocks; ++i)
4488         {
4489           basic_block bb = BASIC_BLOCK (i);
4490           *--qhead = bb;
4491           bb->aux = bb;
4492         }
4493     }
4494
4495   if (blocks_out)
4496     sbitmap_zero (blocks_out);
4497
4498   /* We work through the queue until there are no more blocks.  What
4499      is live at the end of this block is precisely the union of what
4500      is live at the beginning of all its successors.  So, we set its
4501      GLOBAL_LIVE_AT_END field based on the GLOBAL_LIVE_AT_START field
4502      for its successors.  Then, we compute GLOBAL_LIVE_AT_START for
4503      this block by walking through the instructions in this block in
4504      reverse order and updating as we go.  If that changed
4505      GLOBAL_LIVE_AT_START, we add the predecessors of the block to the
4506      queue; they will now need to recalculate GLOBAL_LIVE_AT_END.
4507
4508      We are guaranteed to terminate, because GLOBAL_LIVE_AT_START
4509      never shrinks.  If a register appears in GLOBAL_LIVE_AT_START, it
4510      must either be live at the end of the block, or used within the
4511      block.  In the latter case, it will certainly never disappear
4512      from GLOBAL_LIVE_AT_START.  In the former case, the register
4513      could go away only if it disappeared from GLOBAL_LIVE_AT_START
4514      for one of the successor blocks.  By induction, that cannot
4515      occur.  */
4516   while (qhead != qtail)
4517     {
4518       int rescan, changed;
4519       basic_block bb;
4520       edge e;
4521
4522       bb = *qhead++;
4523       if (qhead == qend)
4524         qhead = queue;
4525       bb->aux = NULL;
4526
4527       /* Begin by propagating live_at_start from the successor blocks.  */
4528       CLEAR_REG_SET (new_live_at_end);
4529       for (e = bb->succ; e; e = e->succ_next)
4530         {
4531           basic_block sb = e->dest;
4532
4533           /* Call-clobbered registers die across exception and call edges.  */
4534           /* ??? Abnormal call edges ignored for the moment, as this gets
4535              confused by sibling call edges, which crashes reg-stack.  */
4536           if (e->flags & EDGE_EH)
4537             {
4538               bitmap_operation (tmp, sb->global_live_at_start,
4539                                 call_used, BITMAP_AND_COMPL);
4540               IOR_REG_SET (new_live_at_end, tmp);
4541             }
4542           else
4543             IOR_REG_SET (new_live_at_end, sb->global_live_at_start);
4544         }
4545
4546       /* The all-important stack pointer must always be live.  */
4547       SET_REGNO_REG_SET (new_live_at_end, STACK_POINTER_REGNUM);
4548
4549       /* Before reload, there are a few registers that must be forced
4550          live everywhere -- which might not already be the case for
4551          blocks within infinite loops.  */
4552       if (! reload_completed)
4553         {
4554           /* Any reference to any pseudo before reload is a potential
4555              reference of the frame pointer.  */
4556           SET_REGNO_REG_SET (new_live_at_end, FRAME_POINTER_REGNUM);
4557
4558 #if FRAME_POINTER_REGNUM != ARG_POINTER_REGNUM
4559           /* Pseudos with argument area equivalences may require
4560              reloading via the argument pointer.  */
4561           if (fixed_regs[ARG_POINTER_REGNUM])
4562             SET_REGNO_REG_SET (new_live_at_end, ARG_POINTER_REGNUM);
4563 #endif
4564
4565           /* Any constant, or pseudo with constant equivalences, may
4566              require reloading from memory using the pic register.  */
4567           if (PIC_OFFSET_TABLE_REGNUM != INVALID_REGNUM
4568               && fixed_regs[PIC_OFFSET_TABLE_REGNUM])
4569             SET_REGNO_REG_SET (new_live_at_end, PIC_OFFSET_TABLE_REGNUM);
4570         }
4571
4572       /* Regs used in phi nodes are not included in
4573          global_live_at_start, since they are live only along a
4574          particular edge.  Set those regs that are live because of a
4575          phi node alternative corresponding to this particular block.  */
4576       if (in_ssa_form)
4577         for_each_successor_phi (bb, &set_phi_alternative_reg,
4578                                 new_live_at_end);
4579
4580       if (bb == ENTRY_BLOCK_PTR)
4581         {
4582           COPY_REG_SET (bb->global_live_at_end, new_live_at_end);
4583           continue;
4584         }
4585
4586       /* On our first pass through this block, we'll go ahead and continue.
4587          Recognize first pass by local_set NULL.  On subsequent passes, we
4588          get to skip out early if live_at_end wouldn't have changed.  */
4589
4590       if (bb->local_set == NULL)
4591         {
4592           bb->local_set = OBSTACK_ALLOC_REG_SET (&flow_obstack);
4593           bb->cond_local_set = OBSTACK_ALLOC_REG_SET (&flow_obstack);
4594           rescan = 1;
4595         }
4596       else
4597         {
4598           /* If any bits were removed from live_at_end, we'll have to
4599              rescan the block.  This wouldn't be necessary if we had
4600              precalculated local_live, however with PROP_SCAN_DEAD_CODE
4601              local_live is really dependent on live_at_end.  */
4602           CLEAR_REG_SET (tmp);
4603           rescan = bitmap_operation (tmp, bb->global_live_at_end,
4604                                      new_live_at_end, BITMAP_AND_COMPL);
4605
4606           if (! rescan)
4607             {
4608               /* If any of the registers in the new live_at_end set are
4609                  conditionally set in this basic block, we must rescan.
4610                  This is because conditional lifetimes at the end of the
4611                  block do not just take the live_at_end set into account,
4612                  but also the liveness at the start of each successor
4613                  block.  We can miss changes in those sets if we only
4614                  compare the new live_at_end against the previous one.  */
4615               CLEAR_REG_SET (tmp);
4616               rescan = bitmap_operation (tmp, new_live_at_end,
4617                                          bb->cond_local_set, BITMAP_AND);
4618             }
4619
4620           if (! rescan)
4621             {
4622               /* Find the set of changed bits.  Take this opportunity
4623                  to notice that this set is empty and early out.  */
4624               CLEAR_REG_SET (tmp);
4625               changed = bitmap_operation (tmp, bb->global_live_at_end,
4626                                           new_live_at_end, BITMAP_XOR);
4627               if (! changed)
4628                 continue;
4629
4630               /* If any of the changed bits overlap with local_set,
4631                  we'll have to rescan the block.  Detect overlap by
4632                  the AND with ~local_set turning off bits.  */
4633               rescan = bitmap_operation (tmp, tmp, bb->local_set,
4634                                          BITMAP_AND_COMPL);
4635             }
4636         }
4637
4638       /* Let our caller know that BB changed enough to require its
4639          death notes updated.  */
4640       if (blocks_out)
4641         SET_BIT (blocks_out, bb->index);
4642
4643       if (! rescan)
4644         {
4645           /* Add to live_at_start the set of all registers in
4646              new_live_at_end that aren't in the old live_at_end.  */
4647
4648           bitmap_operation (tmp, new_live_at_end, bb->global_live_at_end,
4649                             BITMAP_AND_COMPL);
4650           COPY_REG_SET (bb->global_live_at_end, new_live_at_end);
4651
4652           changed = bitmap_operation (bb->global_live_at_start,
4653                                       bb->global_live_at_start,
4654                                       tmp, BITMAP_IOR);
4655           if (! changed)
4656             continue;
4657         }
4658       else
4659         {
4660           COPY_REG_SET (bb->global_live_at_end, new_live_at_end);
4661
4662           /* Rescan the block insn by insn to turn (a copy of) live_at_end
4663              into live_at_start.  */
4664           propagate_block (bb, new_live_at_end, bb->local_set,
4665                            bb->cond_local_set, flags);
4666
4667           /* If live_at start didn't change, no need to go farther.  */
4668           if (REG_SET_EQUAL_P (bb->global_live_at_start, new_live_at_end))
4669             continue;
4670
4671           COPY_REG_SET (bb->global_live_at_start, new_live_at_end);
4672         }
4673
4674       /* Queue all predecessors of BB so that we may re-examine
4675          their live_at_end.  */
4676       for (e = bb->pred; e; e = e->pred_next)
4677         {
4678           basic_block pb = e->src;
4679           if (pb->aux == NULL)
4680             {
4681               *qtail++ = pb;
4682               if (qtail == qend)
4683                 qtail = queue;
4684               pb->aux = pb;
4685             }
4686         }
4687     }
4688
4689   FREE_REG_SET (tmp);
4690   FREE_REG_SET (new_live_at_end);
4691   FREE_REG_SET (call_used);
4692
4693   if (blocks_out)
4694     {
4695       EXECUTE_IF_SET_IN_SBITMAP (blocks_out, 0, i,
4696         {
4697           basic_block bb = BASIC_BLOCK (i);
4698           FREE_REG_SET (bb->local_set);
4699           FREE_REG_SET (bb->cond_local_set);
4700         });
4701     }
4702   else
4703     {
4704       for (i = n_basic_blocks - 1; i >= 0; --i)
4705         {
4706           basic_block bb = BASIC_BLOCK (i);
4707           FREE_REG_SET (bb->local_set);
4708           FREE_REG_SET (bb->cond_local_set);
4709         }
4710     }
4711
4712   free (queue);
4713 }
4714 \f
4715 /* Subroutines of life analysis.  */
4716
4717 /* Allocate the permanent data structures that represent the results
4718    of life analysis.  Not static since used also for stupid life analysis.  */
4719
4720 void
4721 allocate_bb_life_data ()
4722 {
4723   register int i;
4724
4725   for (i = 0; i < n_basic_blocks; i++)
4726     {
4727       basic_block bb = BASIC_BLOCK (i);
4728
4729       bb->global_live_at_start = OBSTACK_ALLOC_REG_SET (&flow_obstack);
4730       bb->global_live_at_end = OBSTACK_ALLOC_REG_SET (&flow_obstack);
4731     }
4732
4733   ENTRY_BLOCK_PTR->global_live_at_end
4734     = OBSTACK_ALLOC_REG_SET (&flow_obstack);
4735   EXIT_BLOCK_PTR->global_live_at_start
4736     = OBSTACK_ALLOC_REG_SET (&flow_obstack);
4737
4738   regs_live_at_setjmp = OBSTACK_ALLOC_REG_SET (&flow_obstack);
4739 }
4740
4741 void
4742 allocate_reg_life_data ()
4743 {
4744   int i;
4745
4746   max_regno = max_reg_num ();
4747
4748   /* Recalculate the register space, in case it has grown.  Old style
4749      vector oriented regsets would set regset_{size,bytes} here also.  */
4750   allocate_reg_info (max_regno, FALSE, FALSE);
4751
4752   /* Reset all the data we'll collect in propagate_block and its
4753      subroutines.  */
4754   for (i = 0; i < max_regno; i++)
4755     {
4756       REG_N_SETS (i) = 0;
4757       REG_N_REFS (i) = 0;
4758       REG_N_DEATHS (i) = 0;
4759       REG_N_CALLS_CROSSED (i) = 0;
4760       REG_LIVE_LENGTH (i) = 0;
4761       REG_BASIC_BLOCK (i) = REG_BLOCK_UNKNOWN;
4762     }
4763 }
4764
4765 /* Delete dead instructions for propagate_block.  */
4766
4767 static void
4768 propagate_block_delete_insn (bb, insn)
4769      basic_block bb;
4770      rtx insn;
4771 {
4772   rtx inote = find_reg_note (insn, REG_LABEL, NULL_RTX);
4773
4774   /* If the insn referred to a label, and that label was attached to
4775      an ADDR_VEC, it's safe to delete the ADDR_VEC.  In fact, it's
4776      pretty much mandatory to delete it, because the ADDR_VEC may be
4777      referencing labels that no longer exist.
4778
4779      INSN may reference a deleted label, particularly when a jump
4780      table has been optimized into a direct jump.  There's no
4781      real good way to fix up the reference to the deleted label
4782      when the label is deleted, so we just allow it here.
4783
4784      After dead code elimination is complete, we do search for
4785      any REG_LABEL notes which reference deleted labels as a
4786      sanity check.  */
4787
4788   if (inote && GET_CODE (inote) == CODE_LABEL)
4789     {
4790       rtx label = XEXP (inote, 0);
4791       rtx next;
4792
4793       /* The label may be forced if it has been put in the constant
4794          pool.  If that is the only use we must discard the table
4795          jump following it, but not the label itself.  */
4796       if (LABEL_NUSES (label) == 1 + LABEL_PRESERVE_P (label)
4797           && (next = next_nonnote_insn (label)) != NULL
4798           && GET_CODE (next) == JUMP_INSN
4799           && (GET_CODE (PATTERN (next)) == ADDR_VEC
4800               || GET_CODE (PATTERN (next)) == ADDR_DIFF_VEC))
4801         {
4802           rtx pat = PATTERN (next);
4803           int diff_vec_p = GET_CODE (pat) == ADDR_DIFF_VEC;
4804           int len = XVECLEN (pat, diff_vec_p);
4805           int i;
4806
4807           for (i = 0; i < len; i++)
4808             LABEL_NUSES (XEXP (XVECEXP (pat, diff_vec_p, i), 0))--;
4809
4810           flow_delete_insn (next);
4811         }
4812     }
4813
4814   if (bb->end == insn)
4815     bb->end = PREV_INSN (insn);
4816   flow_delete_insn (insn);
4817 }
4818
4819 /* Delete dead libcalls for propagate_block.  Return the insn
4820    before the libcall.  */
4821
4822 static rtx
4823 propagate_block_delete_libcall (bb, insn, note)
4824      basic_block bb;
4825      rtx insn, note;
4826 {
4827   rtx first = XEXP (note, 0);
4828   rtx before = PREV_INSN (first);
4829
4830   if (insn == bb->end)
4831     bb->end = before;
4832
4833   flow_delete_insn_chain (first, insn);
4834   return before;
4835 }
4836
4837 /* Update the life-status of regs for one insn.  Return the previous insn.  */
4838
4839 rtx
4840 propagate_one_insn (pbi, insn)
4841      struct propagate_block_info *pbi;
4842      rtx insn;
4843 {
4844   rtx prev = PREV_INSN (insn);
4845   int flags = pbi->flags;
4846   int insn_is_dead = 0;
4847   int libcall_is_dead = 0;
4848   rtx note;
4849   int i;
4850
4851   if (! INSN_P (insn))
4852     return prev;
4853
4854   note = find_reg_note (insn, REG_RETVAL, NULL_RTX);
4855   if (flags & PROP_SCAN_DEAD_CODE)
4856     {
4857       insn_is_dead = insn_dead_p (pbi, PATTERN (insn), 0, REG_NOTES (insn));
4858       libcall_is_dead = (insn_is_dead && note != 0
4859                          && libcall_dead_p (pbi, note, insn));
4860     }
4861
4862   /* If an instruction consists of just dead store(s) on final pass,
4863      delete it.  */
4864   if ((flags & PROP_KILL_DEAD_CODE) && insn_is_dead)
4865     {
4866       /* If we're trying to delete a prologue or epilogue instruction
4867          that isn't flagged as possibly being dead, something is wrong.
4868          But if we are keeping the stack pointer depressed, we might well
4869          be deleting insns that are used to compute the amount to update
4870          it by, so they are fine.  */
4871       if (reload_completed
4872           && !(TREE_CODE (TREE_TYPE (current_function_decl)) == FUNCTION_TYPE
4873                 && (TYPE_RETURNS_STACK_DEPRESSED
4874                     (TREE_TYPE (current_function_decl))))
4875           && (((HAVE_epilogue || HAVE_prologue)
4876                && prologue_epilogue_contains (insn))
4877               || (HAVE_sibcall_epilogue
4878                   && sibcall_epilogue_contains (insn)))
4879           && find_reg_note (insn, REG_MAYBE_DEAD, NULL_RTX) == 0)
4880         abort ();
4881
4882       /* Record sets.  Do this even for dead instructions, since they
4883          would have killed the values if they hadn't been deleted.  */
4884       mark_set_regs (pbi, PATTERN (insn), insn);
4885
4886       /* CC0 is now known to be dead.  Either this insn used it,
4887          in which case it doesn't anymore, or clobbered it,
4888          so the next insn can't use it.  */
4889       pbi->cc0_live = 0;
4890
4891       if (libcall_is_dead)
4892         prev = propagate_block_delete_libcall (pbi->bb, insn, note);
4893       else
4894         propagate_block_delete_insn (pbi->bb, insn);
4895
4896       return prev;
4897     }
4898
4899   /* See if this is an increment or decrement that can be merged into
4900      a following memory address.  */
4901 #ifdef AUTO_INC_DEC
4902   {
4903     register rtx x = single_set (insn);
4904
4905     /* Does this instruction increment or decrement a register?  */
4906     if ((flags & PROP_AUTOINC)
4907         && x != 0
4908         && GET_CODE (SET_DEST (x)) == REG
4909         && (GET_CODE (SET_SRC (x)) == PLUS
4910             || GET_CODE (SET_SRC (x)) == MINUS)
4911         && XEXP (SET_SRC (x), 0) == SET_DEST (x)
4912         && GET_CODE (XEXP (SET_SRC (x), 1)) == CONST_INT
4913         /* Ok, look for a following memory ref we can combine with.
4914            If one is found, change the memory ref to a PRE_INC
4915            or PRE_DEC, cancel this insn, and return 1.
4916            Return 0 if nothing has been done.  */
4917         && try_pre_increment_1 (pbi, insn))
4918       return prev;
4919   }
4920 #endif /* AUTO_INC_DEC */
4921
4922   CLEAR_REG_SET (pbi->new_set);
4923
4924   /* If this is not the final pass, and this insn is copying the value of
4925      a library call and it's dead, don't scan the insns that perform the
4926      library call, so that the call's arguments are not marked live.  */
4927   if (libcall_is_dead)
4928     {
4929       /* Record the death of the dest reg.  */
4930       mark_set_regs (pbi, PATTERN (insn), insn);
4931
4932       insn = XEXP (note, 0);
4933       return PREV_INSN (insn);
4934     }
4935   else if (GET_CODE (PATTERN (insn)) == SET
4936            && SET_DEST (PATTERN (insn)) == stack_pointer_rtx
4937            && GET_CODE (SET_SRC (PATTERN (insn))) == PLUS
4938            && XEXP (SET_SRC (PATTERN (insn)), 0) == stack_pointer_rtx
4939            && GET_CODE (XEXP (SET_SRC (PATTERN (insn)), 1)) == CONST_INT)
4940     /* We have an insn to pop a constant amount off the stack.
4941        (Such insns use PLUS regardless of the direction of the stack,
4942        and any insn to adjust the stack by a constant is always a pop.)
4943        These insns, if not dead stores, have no effect on life.  */
4944     ;
4945   else
4946     {
4947       /* Any regs live at the time of a call instruction must not go
4948          in a register clobbered by calls.  Find all regs now live and
4949          record this for them.  */
4950
4951       if (GET_CODE (insn) == CALL_INSN && (flags & PROP_REG_INFO))
4952         EXECUTE_IF_SET_IN_REG_SET (pbi->reg_live, 0, i,
4953                                    { REG_N_CALLS_CROSSED (i)++; });
4954
4955       /* Record sets.  Do this even for dead instructions, since they
4956          would have killed the values if they hadn't been deleted.  */
4957       mark_set_regs (pbi, PATTERN (insn), insn);
4958
4959       if (GET_CODE (insn) == CALL_INSN)
4960         {
4961           register int i;
4962           rtx note, cond;
4963
4964           cond = NULL_RTX;
4965           if (GET_CODE (PATTERN (insn)) == COND_EXEC)
4966             cond = COND_EXEC_TEST (PATTERN (insn));
4967
4968           /* Non-constant calls clobber memory.  */
4969           if (! CONST_CALL_P (insn))
4970             {
4971               free_EXPR_LIST_list (&pbi->mem_set_list);
4972               pbi->mem_set_list_len = 0;
4973             }
4974
4975           /* There may be extra registers to be clobbered.  */
4976           for (note = CALL_INSN_FUNCTION_USAGE (insn);
4977                note;
4978                note = XEXP (note, 1))
4979             if (GET_CODE (XEXP (note, 0)) == CLOBBER)
4980               mark_set_1 (pbi, CLOBBER, XEXP (XEXP (note, 0), 0),
4981                           cond, insn, pbi->flags);
4982
4983           /* Calls change all call-used and global registers.  */
4984           for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
4985             if (TEST_HARD_REG_BIT (regs_invalidated_by_call, i))
4986               {
4987                 /* We do not want REG_UNUSED notes for these registers.  */
4988                 mark_set_1 (pbi, CLOBBER, gen_rtx_REG (reg_raw_mode[i], i),
4989                             cond, insn,
4990                             pbi->flags & ~(PROP_DEATH_NOTES | PROP_REG_INFO));
4991               }
4992         }
4993
4994       /* If an insn doesn't use CC0, it becomes dead since we assume
4995          that every insn clobbers it.  So show it dead here;
4996          mark_used_regs will set it live if it is referenced.  */
4997       pbi->cc0_live = 0;
4998
4999       /* Record uses.  */
5000       if (! insn_is_dead)
5001         mark_used_regs (pbi, PATTERN (insn), NULL_RTX, insn);
5002
5003       /* Sometimes we may have inserted something before INSN (such as a move)
5004          when we make an auto-inc.  So ensure we will scan those insns.  */
5005 #ifdef AUTO_INC_DEC
5006       prev = PREV_INSN (insn);
5007 #endif
5008
5009       if (! insn_is_dead && GET_CODE (insn) == CALL_INSN)
5010         {
5011           register int i;
5012           rtx note, cond;
5013
5014           cond = NULL_RTX;
5015           if (GET_CODE (PATTERN (insn)) == COND_EXEC)
5016             cond = COND_EXEC_TEST (PATTERN (insn));
5017
5018           /* Calls use their arguments.  */
5019           for (note = CALL_INSN_FUNCTION_USAGE (insn);
5020                note;
5021                note = XEXP (note, 1))
5022             if (GET_CODE (XEXP (note, 0)) == USE)
5023               mark_used_regs (pbi, XEXP (XEXP (note, 0), 0),
5024                               cond, insn);
5025
5026           /* The stack ptr is used (honorarily) by a CALL insn.  */
5027           SET_REGNO_REG_SET (pbi->reg_live, STACK_POINTER_REGNUM);
5028
5029           /* Calls may also reference any of the global registers,
5030              so they are made live.  */
5031           for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
5032             if (global_regs[i])
5033               mark_used_reg (pbi, gen_rtx_REG (reg_raw_mode[i], i),
5034                              cond, insn);
5035         }
5036     }
5037
5038   /* On final pass, update counts of how many insns in which each reg
5039      is live.  */
5040   if (flags & PROP_REG_INFO)
5041     EXECUTE_IF_SET_IN_REG_SET (pbi->reg_live, 0, i,
5042                                { REG_LIVE_LENGTH (i)++; });
5043
5044   return prev;
5045 }
5046
5047 /* Initialize a propagate_block_info struct for public consumption.
5048    Note that the structure itself is opaque to this file, but that
5049    the user can use the regsets provided here.  */
5050
5051 struct propagate_block_info *
5052 init_propagate_block_info (bb, live, local_set, cond_local_set, flags)
5053      basic_block bb;
5054      regset live, local_set, cond_local_set;
5055      int flags;
5056 {
5057   struct propagate_block_info *pbi = xmalloc (sizeof (*pbi));
5058
5059   pbi->bb = bb;
5060   pbi->reg_live = live;
5061   pbi->mem_set_list = NULL_RTX;
5062   pbi->mem_set_list_len = 0;
5063   pbi->local_set = local_set;
5064   pbi->cond_local_set = cond_local_set;
5065   pbi->cc0_live = 0;
5066   pbi->flags = flags;
5067
5068   if (flags & (PROP_LOG_LINKS | PROP_AUTOINC))
5069     pbi->reg_next_use = (rtx *) xcalloc (max_reg_num (), sizeof (rtx));
5070   else
5071     pbi->reg_next_use = NULL;
5072
5073   pbi->new_set = BITMAP_XMALLOC ();
5074
5075 #ifdef HAVE_conditional_execution
5076   pbi->reg_cond_dead = splay_tree_new (splay_tree_compare_ints, NULL,
5077                                        free_reg_cond_life_info);
5078   pbi->reg_cond_reg = BITMAP_XMALLOC ();
5079
5080   /* If this block ends in a conditional branch, for each register live
5081      from one side of the branch and not the other, record the register
5082      as conditionally dead.  */
5083   if (GET_CODE (bb->end) == JUMP_INSN
5084       && any_condjump_p (bb->end))
5085     {
5086       regset_head diff_head;
5087       regset diff = INITIALIZE_REG_SET (diff_head);
5088       basic_block bb_true, bb_false;
5089       rtx cond_true, cond_false, set_src;
5090       int i;
5091
5092       /* Identify the successor blocks.  */
5093       bb_true = bb->succ->dest;
5094       if (bb->succ->succ_next != NULL)
5095         {
5096           bb_false = bb->succ->succ_next->dest;
5097
5098           if (bb->succ->flags & EDGE_FALLTHRU)
5099             {
5100               basic_block t = bb_false;
5101               bb_false = bb_true;
5102               bb_true = t;
5103             }
5104           else if (! (bb->succ->succ_next->flags & EDGE_FALLTHRU))
5105             abort ();
5106         }
5107       else
5108         {
5109           /* This can happen with a conditional jump to the next insn.  */
5110           if (JUMP_LABEL (bb->end) != bb_true->head)
5111             abort ();
5112
5113           /* Simplest way to do nothing.  */
5114           bb_false = bb_true;
5115         }
5116
5117       /* Extract the condition from the branch.  */
5118       set_src = SET_SRC (pc_set (bb->end));
5119       cond_true = XEXP (set_src, 0);
5120       cond_false = gen_rtx_fmt_ee (reverse_condition (GET_CODE (cond_true)),
5121                                    GET_MODE (cond_true), XEXP (cond_true, 0),
5122                                    XEXP (cond_true, 1));
5123       if (GET_CODE (XEXP (set_src, 1)) == PC)
5124         {
5125           rtx t = cond_false;
5126           cond_false = cond_true;
5127           cond_true = t;
5128         }
5129
5130       /* Compute which register lead different lives in the successors.  */
5131       if (bitmap_operation (diff, bb_true->global_live_at_start,
5132                             bb_false->global_live_at_start, BITMAP_XOR))
5133         {
5134           rtx reg = XEXP (cond_true, 0);
5135
5136           if (GET_CODE (reg) == SUBREG)
5137             reg = SUBREG_REG (reg);
5138
5139           if (GET_CODE (reg) != REG)
5140             abort ();
5141
5142           SET_REGNO_REG_SET (pbi->reg_cond_reg, REGNO (reg));
5143
5144           /* For each such register, mark it conditionally dead.  */
5145           EXECUTE_IF_SET_IN_REG_SET
5146             (diff, 0, i,
5147              {
5148                struct reg_cond_life_info *rcli;
5149                rtx cond;
5150
5151                rcli = (struct reg_cond_life_info *) xmalloc (sizeof (*rcli));
5152
5153                if (REGNO_REG_SET_P (bb_true->global_live_at_start, i))
5154                  cond = cond_false;
5155                else
5156                  cond = cond_true;
5157                rcli->condition = cond;
5158                rcli->stores = const0_rtx;
5159                rcli->orig_condition = cond;
5160
5161                splay_tree_insert (pbi->reg_cond_dead, i,
5162                                   (splay_tree_value) rcli);
5163              });
5164         }
5165
5166       FREE_REG_SET (diff);
5167     }
5168 #endif
5169
5170   /* If this block has no successors, any stores to the frame that aren't
5171      used later in the block are dead.  So make a pass over the block
5172      recording any such that are made and show them dead at the end.  We do
5173      a very conservative and simple job here.  */
5174   if (optimize
5175       && ! (TREE_CODE (TREE_TYPE (current_function_decl)) == FUNCTION_TYPE
5176             && (TYPE_RETURNS_STACK_DEPRESSED
5177                 (TREE_TYPE (current_function_decl))))
5178       && (flags & PROP_SCAN_DEAD_CODE)
5179       && (bb->succ == NULL
5180           || (bb->succ->succ_next == NULL
5181               && bb->succ->dest == EXIT_BLOCK_PTR
5182               && ! current_function_calls_eh_return)))
5183     {
5184       rtx insn, set;
5185       for (insn = bb->end; insn != bb->head; insn = PREV_INSN (insn))
5186         if (GET_CODE (insn) == INSN
5187             && (set = single_set (insn))
5188             && GET_CODE (SET_DEST (set)) == MEM)
5189           {
5190             rtx mem = SET_DEST (set);
5191             rtx canon_mem = canon_rtx (mem);
5192
5193             /* This optimization is performed by faking a store to the
5194                memory at the end of the block.  This doesn't work for
5195                unchanging memories because multiple stores to unchanging
5196                memory is illegal and alias analysis doesn't consider it.  */
5197             if (RTX_UNCHANGING_P (canon_mem))
5198               continue;
5199
5200             if (XEXP (canon_mem, 0) == frame_pointer_rtx
5201                 || (GET_CODE (XEXP (canon_mem, 0)) == PLUS
5202                     && XEXP (XEXP (canon_mem, 0), 0) == frame_pointer_rtx
5203                     && GET_CODE (XEXP (XEXP (canon_mem, 0), 1)) == CONST_INT))
5204               {
5205 #ifdef AUTO_INC_DEC
5206                 /* Store a copy of mem, otherwise the address may be scrogged
5207                    by find_auto_inc.  This matters because insn_dead_p uses
5208                    an rtx_equal_p check to determine if two addresses are
5209                    the same.  This works before find_auto_inc, but fails
5210                    after find_auto_inc, causing discrepencies between the
5211                    set of live registers calculated during the
5212                    calculate_global_regs_live phase and what actually exists
5213                    after flow completes, leading to aborts.  */
5214                 if (flags & PROP_AUTOINC)
5215                   mem = shallow_copy_rtx (mem);
5216 #endif
5217                 pbi->mem_set_list = alloc_EXPR_LIST (0, mem, pbi->mem_set_list);
5218                 if (++pbi->mem_set_list_len >= MAX_MEM_SET_LIST_LEN)
5219                   break;
5220               }
5221           }
5222     }
5223
5224   return pbi;
5225 }
5226
5227 /* Release a propagate_block_info struct.  */
5228
5229 void
5230 free_propagate_block_info (pbi)
5231      struct propagate_block_info *pbi;
5232 {
5233   free_EXPR_LIST_list (&pbi->mem_set_list);
5234
5235   BITMAP_XFREE (pbi->new_set);
5236
5237 #ifdef HAVE_conditional_execution
5238   splay_tree_delete (pbi->reg_cond_dead);
5239   BITMAP_XFREE (pbi->reg_cond_reg);
5240 #endif
5241
5242   if (pbi->reg_next_use)
5243     free (pbi->reg_next_use);
5244
5245   free (pbi);
5246 }
5247
5248 /* Compute the registers live at the beginning of a basic block BB from
5249    those live at the end.
5250
5251    When called, REG_LIVE contains those live at the end.  On return, it
5252    contains those live at the beginning.
5253
5254    LOCAL_SET, if non-null, will be set with all registers killed
5255    unconditionally by this basic block.
5256    Likewise, COND_LOCAL_SET, if non-null, will be set with all registers
5257    killed conditionally by this basic block.  If there is any unconditional
5258    set of a register, then the corresponding bit will be set in LOCAL_SET
5259    and cleared in COND_LOCAL_SET.
5260    It is valid for LOCAL_SET and COND_LOCAL_SET to be the same set.  In this
5261    case, the resulting set will be equal to the union of the two sets that
5262    would otherwise be computed.  */
5263
5264 void
5265 propagate_block (bb, live, local_set, cond_local_set, flags)
5266      basic_block bb;
5267      regset live;
5268      regset local_set;
5269      regset cond_local_set;
5270      int flags;
5271 {
5272   struct propagate_block_info *pbi;
5273   rtx insn, prev;
5274
5275   pbi = init_propagate_block_info (bb, live, local_set, cond_local_set, flags);
5276
5277   if (flags & PROP_REG_INFO)
5278     {
5279       register int i;
5280
5281       /* Process the regs live at the end of the block.
5282          Mark them as not local to any one basic block.  */
5283       EXECUTE_IF_SET_IN_REG_SET (live, 0, i,
5284                                  { REG_BASIC_BLOCK (i) = REG_BLOCK_GLOBAL; });
5285     }
5286
5287   /* Scan the block an insn at a time from end to beginning.  */
5288
5289   for (insn = bb->end;; insn = prev)
5290     {
5291       /* If this is a call to `setjmp' et al, warn if any
5292          non-volatile datum is live.  */
5293       if ((flags & PROP_REG_INFO)
5294           && GET_CODE (insn) == NOTE
5295           && NOTE_LINE_NUMBER (insn) == NOTE_INSN_SETJMP)
5296         IOR_REG_SET (regs_live_at_setjmp, pbi->reg_live);
5297
5298       prev = propagate_one_insn (pbi, insn);
5299
5300       if (insn == bb->head)
5301         break;
5302     }
5303
5304   free_propagate_block_info (pbi);
5305 }
5306 \f
5307 /* Return 1 if X (the body of an insn, or part of it) is just dead stores
5308    (SET expressions whose destinations are registers dead after the insn).
5309    NEEDED is the regset that says which regs are alive after the insn.
5310
5311    Unless CALL_OK is non-zero, an insn is needed if it contains a CALL.
5312
5313    If X is the entire body of an insn, NOTES contains the reg notes
5314    pertaining to the insn.  */
5315
5316 static int
5317 insn_dead_p (pbi, x, call_ok, notes)
5318      struct propagate_block_info *pbi;
5319      rtx x;
5320      int call_ok;
5321      rtx notes ATTRIBUTE_UNUSED;
5322 {
5323   enum rtx_code code = GET_CODE (x);
5324
5325 #ifdef AUTO_INC_DEC
5326   /* If flow is invoked after reload, we must take existing AUTO_INC
5327      expresions into account.  */
5328   if (reload_completed)
5329     {
5330       for (; notes; notes = XEXP (notes, 1))
5331         {
5332           if (REG_NOTE_KIND (notes) == REG_INC)
5333             {
5334               int regno = REGNO (XEXP (notes, 0));
5335
5336               /* Don't delete insns to set global regs.  */
5337               if ((regno < FIRST_PSEUDO_REGISTER && global_regs[regno])
5338                   || REGNO_REG_SET_P (pbi->reg_live, regno))
5339                 return 0;
5340             }
5341         }
5342     }
5343 #endif
5344
5345   /* If setting something that's a reg or part of one,
5346      see if that register's altered value will be live.  */
5347
5348   if (code == SET)
5349     {
5350       rtx r = SET_DEST (x);
5351
5352 #ifdef HAVE_cc0
5353       if (GET_CODE (r) == CC0)
5354         return ! pbi->cc0_live;
5355 #endif
5356
5357       /* A SET that is a subroutine call cannot be dead.  */
5358       if (GET_CODE (SET_SRC (x)) == CALL)
5359         {
5360           if (! call_ok)
5361             return 0;
5362         }
5363
5364       /* Don't eliminate loads from volatile memory or volatile asms.  */
5365       else if (volatile_refs_p (SET_SRC (x)))
5366         return 0;
5367
5368       if (GET_CODE (r) == MEM)
5369         {
5370           rtx temp;
5371
5372           if (MEM_VOLATILE_P (r))
5373             return 0;
5374
5375           /* Walk the set of memory locations we are currently tracking
5376              and see if one is an identical match to this memory location.
5377              If so, this memory write is dead (remember, we're walking
5378              backwards from the end of the block to the start).  Since
5379              rtx_equal_p does not check the alias set or flags, we also
5380              must have the potential for them to conflict (anti_dependence). */
5381           for (temp = pbi->mem_set_list; temp != 0; temp = XEXP (temp, 1))
5382             if (anti_dependence (r, XEXP (temp, 0)))
5383               {
5384                 rtx mem = XEXP (temp, 0);
5385
5386                 if (rtx_equal_p (mem, r))
5387                   return 1;
5388 #ifdef AUTO_INC_DEC
5389                 /* Check if memory reference matches an auto increment. Only
5390                    post increment/decrement or modify are valid.  */
5391                 if (GET_MODE (mem) == GET_MODE (r)
5392                     && (GET_CODE (XEXP (mem, 0)) == POST_DEC
5393                         || GET_CODE (XEXP (mem, 0)) == POST_INC
5394                         || GET_CODE (XEXP (mem, 0)) == POST_MODIFY)
5395                     && GET_MODE (XEXP (mem, 0)) == GET_MODE (r)
5396                     && rtx_equal_p (XEXP (XEXP (mem, 0), 0), XEXP (r, 0)))
5397                   return 1;
5398 #endif
5399               }
5400         }
5401       else
5402         {
5403           while (GET_CODE (r) == SUBREG
5404                  || GET_CODE (r) == STRICT_LOW_PART
5405                  || GET_CODE (r) == ZERO_EXTRACT)
5406             r = XEXP (r, 0);
5407
5408           if (GET_CODE (r) == REG)
5409             {
5410               int regno = REGNO (r);
5411
5412               /* Obvious.  */
5413               if (REGNO_REG_SET_P (pbi->reg_live, regno))
5414                 return 0;
5415
5416               /* If this is a hard register, verify that subsequent
5417                  words are not needed.  */
5418               if (regno < FIRST_PSEUDO_REGISTER)
5419                 {
5420                   int n = HARD_REGNO_NREGS (regno, GET_MODE (r));
5421
5422                   while (--n > 0)
5423                     if (REGNO_REG_SET_P (pbi->reg_live, regno+n))
5424                       return 0;
5425                 }
5426
5427               /* Don't delete insns to set global regs.  */
5428               if (regno < FIRST_PSEUDO_REGISTER && global_regs[regno])
5429                 return 0;
5430
5431               /* Make sure insns to set the stack pointer aren't deleted.  */
5432               if (regno == STACK_POINTER_REGNUM)
5433                 return 0;
5434
5435               /* ??? These bits might be redundant with the force live bits
5436                  in calculate_global_regs_live.  We would delete from
5437                  sequential sets; whether this actually affects real code
5438                  for anything but the stack pointer I don't know.  */
5439               /* Make sure insns to set the frame pointer aren't deleted.  */
5440               if (regno == FRAME_POINTER_REGNUM
5441                   && (! reload_completed || frame_pointer_needed))
5442                 return 0;
5443 #if FRAME_POINTER_REGNUM != HARD_FRAME_POINTER_REGNUM
5444               if (regno == HARD_FRAME_POINTER_REGNUM
5445                   && (! reload_completed || frame_pointer_needed))
5446                 return 0;
5447 #endif
5448
5449 #if FRAME_POINTER_REGNUM != ARG_POINTER_REGNUM
5450               /* Make sure insns to set arg pointer are never deleted
5451                  (if the arg pointer isn't fixed, there will be a USE
5452                  for it, so we can treat it normally).  */
5453               if (regno == ARG_POINTER_REGNUM && fixed_regs[regno])
5454                 return 0;
5455 #endif
5456
5457               /* Otherwise, the set is dead.  */
5458               return 1;
5459             }
5460         }
5461     }
5462
5463   /* If performing several activities, insn is dead if each activity
5464      is individually dead.  Also, CLOBBERs and USEs can be ignored; a
5465      CLOBBER or USE that's inside a PARALLEL doesn't make the insn
5466      worth keeping.  */
5467   else if (code == PARALLEL)
5468     {
5469       int i = XVECLEN (x, 0);
5470
5471       for (i--; i >= 0; i--)
5472         if (GET_CODE (XVECEXP (x, 0, i)) != CLOBBER
5473             && GET_CODE (XVECEXP (x, 0, i)) != USE
5474             && ! insn_dead_p (pbi, XVECEXP (x, 0, i), call_ok, NULL_RTX))
5475           return 0;
5476
5477       return 1;
5478     }
5479
5480   /* A CLOBBER of a pseudo-register that is dead serves no purpose.  That
5481      is not necessarily true for hard registers.  */
5482   else if (code == CLOBBER && GET_CODE (XEXP (x, 0)) == REG
5483            && REGNO (XEXP (x, 0)) >= FIRST_PSEUDO_REGISTER
5484            && ! REGNO_REG_SET_P (pbi->reg_live, REGNO (XEXP (x, 0))))
5485     return 1;
5486
5487   /* We do not check other CLOBBER or USE here.  An insn consisting of just
5488      a CLOBBER or just a USE should not be deleted.  */
5489   return 0;
5490 }
5491
5492 /* If INSN is the last insn in a libcall, and assuming INSN is dead,
5493    return 1 if the entire library call is dead.
5494    This is true if INSN copies a register (hard or pseudo)
5495    and if the hard return reg of the call insn is dead.
5496    (The caller should have tested the destination of the SET inside
5497    INSN already for death.)
5498
5499    If this insn doesn't just copy a register, then we don't
5500    have an ordinary libcall.  In that case, cse could not have
5501    managed to substitute the source for the dest later on,
5502    so we can assume the libcall is dead.
5503
5504    PBI is the block info giving pseudoregs live before this insn.
5505    NOTE is the REG_RETVAL note of the insn.  */
5506
5507 static int
5508 libcall_dead_p (pbi, note, insn)
5509      struct propagate_block_info *pbi;
5510      rtx note;
5511      rtx insn;
5512 {
5513   rtx x = single_set (insn);
5514
5515   if (x)
5516     {
5517       register rtx r = SET_SRC (x);
5518       if (GET_CODE (r) == REG)
5519         {
5520           rtx call = XEXP (note, 0);
5521           rtx call_pat;
5522           register int i;
5523
5524           /* Find the call insn.  */
5525           while (call != insn && GET_CODE (call) != CALL_INSN)
5526             call = NEXT_INSN (call);
5527
5528           /* If there is none, do nothing special,
5529              since ordinary death handling can understand these insns.  */
5530           if (call == insn)
5531             return 0;
5532
5533           /* See if the hard reg holding the value is dead.
5534              If this is a PARALLEL, find the call within it.  */
5535           call_pat = PATTERN (call);
5536           if (GET_CODE (call_pat) == PARALLEL)
5537             {
5538               for (i = XVECLEN (call_pat, 0) - 1; i >= 0; i--)
5539                 if (GET_CODE (XVECEXP (call_pat, 0, i)) == SET
5540                     && GET_CODE (SET_SRC (XVECEXP (call_pat, 0, i))) == CALL)
5541                   break;
5542
5543               /* This may be a library call that is returning a value
5544                  via invisible pointer.  Do nothing special, since
5545                  ordinary death handling can understand these insns.  */
5546               if (i < 0)
5547                 return 0;
5548
5549               call_pat = XVECEXP (call_pat, 0, i);
5550             }
5551
5552           return insn_dead_p (pbi, call_pat, 1, REG_NOTES (call));
5553         }
5554     }
5555   return 1;
5556 }
5557
5558 /* Return 1 if register REGNO was used before it was set, i.e. if it is
5559    live at function entry.  Don't count global register variables, variables
5560    in registers that can be used for function arg passing, or variables in
5561    fixed hard registers.  */
5562
5563 int
5564 regno_uninitialized (regno)
5565      int regno;
5566 {
5567   if (n_basic_blocks == 0
5568       || (regno < FIRST_PSEUDO_REGISTER
5569           && (global_regs[regno]
5570               || fixed_regs[regno]
5571               || FUNCTION_ARG_REGNO_P (regno))))
5572     return 0;
5573
5574   return REGNO_REG_SET_P (BASIC_BLOCK (0)->global_live_at_start, regno);
5575 }
5576
5577 /* 1 if register REGNO was alive at a place where `setjmp' was called
5578    and was set more than once or is an argument.
5579    Such regs may be clobbered by `longjmp'.  */
5580
5581 int
5582 regno_clobbered_at_setjmp (regno)
5583      int regno;
5584 {
5585   if (n_basic_blocks == 0)
5586     return 0;
5587
5588   return ((REG_N_SETS (regno) > 1
5589            || REGNO_REG_SET_P (BASIC_BLOCK (0)->global_live_at_start, regno))
5590           && REGNO_REG_SET_P (regs_live_at_setjmp, regno));
5591 }
5592 \f
5593 /* INSN references memory, possibly using autoincrement addressing modes.
5594    Find any entries on the mem_set_list that need to be invalidated due
5595    to an address change.  */
5596
5597 static void
5598 invalidate_mems_from_autoinc (pbi, insn)
5599      struct propagate_block_info *pbi;
5600      rtx insn;
5601 {
5602   rtx note = REG_NOTES (insn);
5603   for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
5604     {
5605       if (REG_NOTE_KIND (note) == REG_INC)
5606         {
5607           rtx temp = pbi->mem_set_list;
5608           rtx prev = NULL_RTX;
5609           rtx next;
5610
5611           while (temp)
5612             {
5613               next = XEXP (temp, 1);
5614               if (reg_overlap_mentioned_p (XEXP (note, 0), XEXP (temp, 0)))
5615                 {
5616                   /* Splice temp out of list.  */
5617                   if (prev)
5618                     XEXP (prev, 1) = next;
5619                   else
5620                     pbi->mem_set_list = next;
5621                   free_EXPR_LIST_node (temp);
5622                   pbi->mem_set_list_len--;
5623                 }
5624               else
5625                 prev = temp;
5626               temp = next;
5627             }
5628         }
5629     }
5630 }
5631
5632 /* EXP is either a MEM or a REG.  Remove any dependant entries
5633    from pbi->mem_set_list.  */
5634
5635 static void
5636 invalidate_mems_from_set (pbi, exp)
5637      struct propagate_block_info *pbi;
5638      rtx exp;
5639 {
5640   rtx temp = pbi->mem_set_list;
5641   rtx prev = NULL_RTX;
5642   rtx next;
5643
5644   while (temp)
5645     {
5646       next = XEXP (temp, 1);
5647       if ((GET_CODE (exp) == MEM
5648            && output_dependence (XEXP (temp, 0), exp))
5649           || (GET_CODE (exp) == REG
5650               && reg_overlap_mentioned_p (exp, XEXP (temp, 0))))
5651         {
5652           /* Splice this entry out of the list.  */
5653           if (prev)
5654             XEXP (prev, 1) = next;
5655           else
5656             pbi->mem_set_list = next;
5657           free_EXPR_LIST_node (temp);
5658           pbi->mem_set_list_len--;
5659         }
5660       else
5661         prev = temp;
5662       temp = next;
5663     }
5664 }
5665
5666 /* Process the registers that are set within X.  Their bits are set to
5667    1 in the regset DEAD, because they are dead prior to this insn.
5668
5669    If INSN is nonzero, it is the insn being processed.
5670
5671    FLAGS is the set of operations to perform.  */
5672
5673 static void
5674 mark_set_regs (pbi, x, insn)
5675      struct propagate_block_info *pbi;
5676      rtx x, insn;
5677 {
5678   rtx cond = NULL_RTX;
5679   rtx link;
5680   enum rtx_code code;
5681
5682   if (insn)
5683     for (link = REG_NOTES (insn); link; link = XEXP (link, 1))
5684       {
5685         if (REG_NOTE_KIND (link) == REG_INC)
5686           mark_set_1 (pbi, SET, XEXP (link, 0),
5687                       (GET_CODE (x) == COND_EXEC
5688                        ? COND_EXEC_TEST (x) : NULL_RTX),
5689                       insn, pbi->flags);
5690       }
5691  retry:
5692   switch (code = GET_CODE (x))
5693     {
5694     case SET:
5695     case CLOBBER:
5696       mark_set_1 (pbi, code, SET_DEST (x), cond, insn, pbi->flags);
5697       return;
5698
5699     case COND_EXEC:
5700       cond = COND_EXEC_TEST (x);
5701       x = COND_EXEC_CODE (x);
5702       goto retry;
5703
5704     case PARALLEL:
5705       {
5706         register int i;
5707         for (i = XVECLEN (x, 0) - 1; i >= 0; i--)
5708           {
5709             rtx sub = XVECEXP (x, 0, i);
5710             switch (code = GET_CODE (sub))
5711               {
5712               case COND_EXEC:
5713                 if (cond != NULL_RTX)
5714                   abort ();
5715
5716                 cond = COND_EXEC_TEST (sub);
5717                 sub = COND_EXEC_CODE (sub);
5718                 if (GET_CODE (sub) != SET && GET_CODE (sub) != CLOBBER)
5719                   break;
5720                 /* Fall through.  */
5721
5722               case SET:
5723               case CLOBBER:
5724                 mark_set_1 (pbi, code, SET_DEST (sub), cond, insn, pbi->flags);
5725                 break;
5726
5727               default:
5728                 break;
5729               }
5730           }
5731         break;
5732       }
5733
5734     default:
5735       break;
5736     }
5737 }
5738
5739 /* Process a single set, which appears in INSN.  REG (which may not
5740    actually be a REG, it may also be a SUBREG, PARALLEL, etc.) is
5741    being set using the CODE (which may be SET, CLOBBER, or COND_EXEC).
5742    If the set is conditional (because it appear in a COND_EXEC), COND
5743    will be the condition.  */
5744
5745 static void
5746 mark_set_1 (pbi, code, reg, cond, insn, flags)
5747      struct propagate_block_info *pbi;
5748      enum rtx_code code;
5749      rtx reg, cond, insn;
5750      int flags;
5751 {
5752   int regno_first = -1, regno_last = -1;
5753   unsigned long not_dead = 0;
5754   int i;
5755
5756   /* Modifying just one hardware register of a multi-reg value or just a
5757      byte field of a register does not mean the value from before this insn
5758      is now dead.  Of course, if it was dead after it's unused now.  */
5759
5760   switch (GET_CODE (reg))
5761     {
5762     case PARALLEL:
5763       /* Some targets place small structures in registers for return values of
5764          functions.  We have to detect this case specially here to get correct
5765          flow information.  */
5766       for (i = XVECLEN (reg, 0) - 1; i >= 0; i--)
5767         if (XEXP (XVECEXP (reg, 0, i), 0) != 0)
5768           mark_set_1 (pbi, code, XEXP (XVECEXP (reg, 0, i), 0), cond, insn,
5769                       flags);
5770       return;
5771
5772     case ZERO_EXTRACT:
5773     case SIGN_EXTRACT:
5774     case STRICT_LOW_PART:
5775       /* ??? Assumes STRICT_LOW_PART not used on multi-word registers.  */
5776       do
5777         reg = XEXP (reg, 0);
5778       while (GET_CODE (reg) == SUBREG
5779              || GET_CODE (reg) == ZERO_EXTRACT
5780              || GET_CODE (reg) == SIGN_EXTRACT
5781              || GET_CODE (reg) == STRICT_LOW_PART);
5782       if (GET_CODE (reg) == MEM)
5783         break;
5784       not_dead = (unsigned long) REGNO_REG_SET_P (pbi->reg_live, REGNO (reg));
5785       /* Fall through.  */
5786
5787     case REG:
5788       regno_last = regno_first = REGNO (reg);
5789       if (regno_first < FIRST_PSEUDO_REGISTER)
5790         regno_last += HARD_REGNO_NREGS (regno_first, GET_MODE (reg)) - 1;
5791       break;
5792
5793     case SUBREG:
5794       if (GET_CODE (SUBREG_REG (reg)) == REG)
5795         {
5796           enum machine_mode outer_mode = GET_MODE (reg);
5797           enum machine_mode inner_mode = GET_MODE (SUBREG_REG (reg));
5798
5799           /* Identify the range of registers affected.  This is moderately
5800              tricky for hard registers.  See alter_subreg.  */
5801
5802           regno_last = regno_first = REGNO (SUBREG_REG (reg));
5803           if (regno_first < FIRST_PSEUDO_REGISTER)
5804             {
5805               regno_first += subreg_regno_offset (regno_first, inner_mode,
5806                                                   SUBREG_BYTE (reg),
5807                                                   outer_mode);
5808               regno_last = (regno_first
5809                             + HARD_REGNO_NREGS (regno_first, outer_mode) - 1);
5810
5811               /* Since we've just adjusted the register number ranges, make
5812                  sure REG matches.  Otherwise some_was_live will be clear
5813                  when it shouldn't have been, and we'll create incorrect
5814                  REG_UNUSED notes.  */
5815               reg = gen_rtx_REG (outer_mode, regno_first);
5816             }
5817           else
5818             {
5819               /* If the number of words in the subreg is less than the number
5820                  of words in the full register, we have a well-defined partial
5821                  set.  Otherwise the high bits are undefined.
5822
5823                  This is only really applicable to pseudos, since we just took
5824                  care of multi-word hard registers.  */
5825               if (((GET_MODE_SIZE (outer_mode)
5826                     + UNITS_PER_WORD - 1) / UNITS_PER_WORD)
5827                   < ((GET_MODE_SIZE (inner_mode)
5828                       + UNITS_PER_WORD - 1) / UNITS_PER_WORD))
5829                 not_dead = (unsigned long) REGNO_REG_SET_P (pbi->reg_live,
5830                                                             regno_first);
5831
5832               reg = SUBREG_REG (reg);
5833             }
5834         }
5835       else
5836         reg = SUBREG_REG (reg);
5837       break;
5838
5839     default:
5840       break;
5841     }
5842
5843   /* If this set is a MEM, then it kills any aliased writes.
5844      If this set is a REG, then it kills any MEMs which use the reg.  */
5845   if (optimize && (flags & PROP_SCAN_DEAD_CODE))
5846     {
5847       if (GET_CODE (reg) == MEM || GET_CODE (reg) == REG)
5848         invalidate_mems_from_set (pbi, reg);
5849
5850       /* If the memory reference had embedded side effects (autoincrement
5851          address modes.  Then we may need to kill some entries on the
5852          memory set list.  */
5853       if (insn && GET_CODE (reg) == MEM)
5854         invalidate_mems_from_autoinc (pbi, insn);
5855
5856       if (pbi->mem_set_list_len < MAX_MEM_SET_LIST_LEN
5857           && GET_CODE (reg) == MEM && ! side_effects_p (reg)
5858           /* ??? With more effort we could track conditional memory life.  */
5859           && ! cond
5860           /* We do not know the size of a BLKmode store, so we do not track
5861              them for redundant store elimination.  */
5862           && GET_MODE (reg) != BLKmode
5863           /* There are no REG_INC notes for SP, so we can't assume we'll see
5864              everything that invalidates it.  To be safe, don't eliminate any
5865              stores though SP; none of them should be redundant anyway.  */
5866           && ! reg_mentioned_p (stack_pointer_rtx, reg))
5867         {
5868 #ifdef AUTO_INC_DEC
5869           /* Store a copy of mem, otherwise the address may be
5870              scrogged by find_auto_inc.  */
5871           if (flags & PROP_AUTOINC)
5872             reg = shallow_copy_rtx (reg);
5873 #endif
5874           pbi->mem_set_list = alloc_EXPR_LIST (0, reg, pbi->mem_set_list);
5875           pbi->mem_set_list_len++;
5876         }
5877     }
5878
5879   if (GET_CODE (reg) == REG
5880       && ! (regno_first == FRAME_POINTER_REGNUM
5881             && (! reload_completed || frame_pointer_needed))
5882 #if FRAME_POINTER_REGNUM != HARD_FRAME_POINTER_REGNUM
5883       && ! (regno_first == HARD_FRAME_POINTER_REGNUM
5884             && (! reload_completed || frame_pointer_needed))
5885 #endif
5886 #if FRAME_POINTER_REGNUM != ARG_POINTER_REGNUM
5887       && ! (regno_first == ARG_POINTER_REGNUM && fixed_regs[regno_first])
5888 #endif
5889       )
5890     {
5891       int some_was_live = 0, some_was_dead = 0;
5892
5893       for (i = regno_first; i <= regno_last; ++i)
5894         {
5895           int needed_regno = REGNO_REG_SET_P (pbi->reg_live, i);
5896           if (pbi->local_set)
5897             {
5898               /* Order of the set operation matters here since both
5899                  sets may be the same.  */
5900               CLEAR_REGNO_REG_SET (pbi->cond_local_set, i);
5901               if (cond != NULL_RTX
5902                   && ! REGNO_REG_SET_P (pbi->local_set, i))
5903                 SET_REGNO_REG_SET (pbi->cond_local_set, i);
5904               else
5905                 SET_REGNO_REG_SET (pbi->local_set, i);
5906             }
5907           if (code != CLOBBER)
5908             SET_REGNO_REG_SET (pbi->new_set, i);
5909
5910           some_was_live |= needed_regno;
5911           some_was_dead |= ! needed_regno;
5912         }
5913
5914 #ifdef HAVE_conditional_execution
5915       /* Consider conditional death in deciding that the register needs
5916          a death note.  */
5917       if (some_was_live && ! not_dead
5918           /* The stack pointer is never dead.  Well, not strictly true,
5919              but it's very difficult to tell from here.  Hopefully
5920              combine_stack_adjustments will fix up the most egregious
5921              errors.  */
5922           && regno_first != STACK_POINTER_REGNUM)
5923         {
5924           for (i = regno_first; i <= regno_last; ++i)
5925             if (! mark_regno_cond_dead (pbi, i, cond))
5926               not_dead |= ((unsigned long) 1) << (i - regno_first);
5927         }
5928 #endif
5929
5930       /* Additional data to record if this is the final pass.  */
5931       if (flags & (PROP_LOG_LINKS | PROP_REG_INFO
5932                    | PROP_DEATH_NOTES | PROP_AUTOINC))
5933         {
5934           register rtx y;
5935           register int blocknum = pbi->bb->index;
5936
5937           y = NULL_RTX;
5938           if (flags & (PROP_LOG_LINKS | PROP_AUTOINC))
5939             {
5940               y = pbi->reg_next_use[regno_first];
5941
5942               /* The next use is no longer next, since a store intervenes.  */
5943               for (i = regno_first; i <= regno_last; ++i)
5944                 pbi->reg_next_use[i] = 0;
5945             }
5946
5947           if (flags & PROP_REG_INFO)
5948             {
5949               for (i = regno_first; i <= regno_last; ++i)
5950                 {
5951                   /* Count (weighted) references, stores, etc.  This counts a
5952                      register twice if it is modified, but that is correct.  */
5953                   REG_N_SETS (i) += 1;
5954                   REG_N_REFS (i) += 1;
5955                   REG_FREQ (i) += (optimize_size || !pbi->bb->frequency
5956                                    ? 1 : pbi->bb->frequency);
5957
5958                   /* The insns where a reg is live are normally counted
5959                      elsewhere, but we want the count to include the insn
5960                      where the reg is set, and the normal counting mechanism
5961                      would not count it.  */
5962                   REG_LIVE_LENGTH (i) += 1;
5963                 }
5964
5965               /* If this is a hard reg, record this function uses the reg.  */
5966               if (regno_first < FIRST_PSEUDO_REGISTER)
5967                 {
5968                   for (i = regno_first; i <= regno_last; i++)
5969                     regs_ever_live[i] = 1;
5970                 }
5971               else
5972                 {
5973                   /* Keep track of which basic blocks each reg appears in.  */
5974                   if (REG_BASIC_BLOCK (regno_first) == REG_BLOCK_UNKNOWN)
5975                     REG_BASIC_BLOCK (regno_first) = blocknum;
5976                   else if (REG_BASIC_BLOCK (regno_first) != blocknum)
5977                     REG_BASIC_BLOCK (regno_first) = REG_BLOCK_GLOBAL;
5978                 }
5979             }
5980
5981           if (! some_was_dead)
5982             {
5983               if (flags & PROP_LOG_LINKS)
5984                 {
5985                   /* Make a logical link from the next following insn
5986                      that uses this register, back to this insn.
5987                      The following insns have already been processed.
5988
5989                      We don't build a LOG_LINK for hard registers containing
5990                      in ASM_OPERANDs.  If these registers get replaced,
5991                      we might wind up changing the semantics of the insn,
5992                      even if reload can make what appear to be valid
5993                      assignments later.  */
5994                   if (y && (BLOCK_NUM (y) == blocknum)
5995                       && (regno_first >= FIRST_PSEUDO_REGISTER
5996                           || asm_noperands (PATTERN (y)) < 0))
5997                     LOG_LINKS (y) = alloc_INSN_LIST (insn, LOG_LINKS (y));
5998                 }
5999             }
6000           else if (not_dead)
6001             ;
6002           else if (! some_was_live)
6003             {
6004               if (flags & PROP_REG_INFO)
6005                 REG_N_DEATHS (regno_first) += 1;
6006
6007               if (flags & PROP_DEATH_NOTES)
6008                 {
6009                   /* Note that dead stores have already been deleted
6010                      when possible.  If we get here, we have found a
6011                      dead store that cannot be eliminated (because the
6012                      same insn does something useful).  Indicate this
6013                      by marking the reg being set as dying here.  */
6014                   REG_NOTES (insn)
6015                     = alloc_EXPR_LIST (REG_UNUSED, reg, REG_NOTES (insn));
6016                 }
6017             }
6018           else
6019             {
6020               if (flags & PROP_DEATH_NOTES)
6021                 {
6022                   /* This is a case where we have a multi-word hard register
6023                      and some, but not all, of the words of the register are
6024                      needed in subsequent insns.  Write REG_UNUSED notes
6025                      for those parts that were not needed.  This case should
6026                      be rare.  */
6027
6028                   for (i = regno_first; i <= regno_last; ++i)
6029                     if (! REGNO_REG_SET_P (pbi->reg_live, i))
6030                       REG_NOTES (insn)
6031                         = alloc_EXPR_LIST (REG_UNUSED,
6032                                            gen_rtx_REG (reg_raw_mode[i], i),
6033                                            REG_NOTES (insn));
6034                 }
6035             }
6036         }
6037
6038       /* Mark the register as being dead.  */
6039       if (some_was_live
6040           /* The stack pointer is never dead.  Well, not strictly true,
6041              but it's very difficult to tell from here.  Hopefully
6042              combine_stack_adjustments will fix up the most egregious
6043              errors.  */
6044           && regno_first != STACK_POINTER_REGNUM)
6045         {
6046           for (i = regno_first; i <= regno_last; ++i)
6047             if (!(not_dead & (((unsigned long) 1) << (i - regno_first))))
6048               CLEAR_REGNO_REG_SET (pbi->reg_live, i);
6049         }
6050     }
6051   else if (GET_CODE (reg) == REG)
6052     {
6053       if (flags & (PROP_LOG_LINKS | PROP_AUTOINC))
6054         pbi->reg_next_use[regno_first] = 0;
6055     }
6056
6057   /* If this is the last pass and this is a SCRATCH, show it will be dying
6058      here and count it.  */
6059   else if (GET_CODE (reg) == SCRATCH)
6060     {
6061       if (flags & PROP_DEATH_NOTES)
6062         REG_NOTES (insn)
6063           = alloc_EXPR_LIST (REG_UNUSED, reg, REG_NOTES (insn));
6064     }
6065 }
6066 \f
6067 #ifdef HAVE_conditional_execution
6068 /* Mark REGNO conditionally dead.
6069    Return true if the register is now unconditionally dead.  */
6070
6071 static int
6072 mark_regno_cond_dead (pbi, regno, cond)
6073      struct propagate_block_info *pbi;
6074      int regno;
6075      rtx cond;
6076 {
6077   /* If this is a store to a predicate register, the value of the
6078      predicate is changing, we don't know that the predicate as seen
6079      before is the same as that seen after.  Flush all dependent
6080      conditions from reg_cond_dead.  This will make all such
6081      conditionally live registers unconditionally live.  */
6082   if (REGNO_REG_SET_P (pbi->reg_cond_reg, regno))
6083     flush_reg_cond_reg (pbi, regno);
6084
6085   /* If this is an unconditional store, remove any conditional
6086      life that may have existed.  */
6087   if (cond == NULL_RTX)
6088     splay_tree_remove (pbi->reg_cond_dead, regno);
6089   else
6090     {
6091       splay_tree_node node;
6092       struct reg_cond_life_info *rcli;
6093       rtx ncond;
6094
6095       /* Otherwise this is a conditional set.  Record that fact.
6096          It may have been conditionally used, or there may be a
6097          subsequent set with a complimentary condition.  */
6098
6099       node = splay_tree_lookup (pbi->reg_cond_dead, regno);
6100       if (node == NULL)
6101         {
6102           /* The register was unconditionally live previously.
6103              Record the current condition as the condition under
6104              which it is dead.  */
6105           rcli = (struct reg_cond_life_info *) xmalloc (sizeof (*rcli));
6106           rcli->condition = cond;
6107           rcli->stores = cond;
6108           rcli->orig_condition = const0_rtx;
6109           splay_tree_insert (pbi->reg_cond_dead, regno,
6110                              (splay_tree_value) rcli);
6111
6112           SET_REGNO_REG_SET (pbi->reg_cond_reg, REGNO (XEXP (cond, 0)));
6113
6114           /* Not unconditionaly dead.  */
6115           return 0;
6116         }
6117       else
6118         {
6119           /* The register was conditionally live previously.
6120              Add the new condition to the old.  */
6121           rcli = (struct reg_cond_life_info *) node->value;
6122           ncond = rcli->condition;
6123           ncond = ior_reg_cond (ncond, cond, 1);
6124           if (rcli->stores == const0_rtx)
6125             rcli->stores = cond;
6126           else if (rcli->stores != const1_rtx)
6127             rcli->stores = ior_reg_cond (rcli->stores, cond, 1);
6128
6129           /* If the register is now unconditionally dead, remove the entry
6130              in the splay_tree.  A register is unconditionally dead if the
6131              dead condition ncond is true.  A register is also unconditionally
6132              dead if the sum of all conditional stores is an unconditional
6133              store (stores is true), and the dead condition is identically the
6134              same as the original dead condition initialized at the end of
6135              the block.  This is a pointer compare, not an rtx_equal_p
6136              compare.  */
6137           if (ncond == const1_rtx
6138               || (ncond == rcli->orig_condition && rcli->stores == const1_rtx))
6139             splay_tree_remove (pbi->reg_cond_dead, regno);
6140           else
6141             {
6142               rcli->condition = ncond;
6143
6144               SET_REGNO_REG_SET (pbi->reg_cond_reg, REGNO (XEXP (cond, 0)));
6145
6146               /* Not unconditionaly dead.  */
6147               return 0;
6148             }
6149         }
6150     }
6151
6152   return 1;
6153 }
6154
6155 /* Called from splay_tree_delete for pbi->reg_cond_life.  */
6156
6157 static void
6158 free_reg_cond_life_info (value)
6159      splay_tree_value value;
6160 {
6161   struct reg_cond_life_info *rcli = (struct reg_cond_life_info *) value;
6162   free (rcli);
6163 }
6164
6165 /* Helper function for flush_reg_cond_reg.  */
6166
6167 static int
6168 flush_reg_cond_reg_1 (node, data)
6169      splay_tree_node node;
6170      void *data;
6171 {
6172   struct reg_cond_life_info *rcli;
6173   int *xdata = (int *) data;
6174   unsigned int regno = xdata[0];
6175
6176   /* Don't need to search if last flushed value was farther on in
6177      the in-order traversal.  */
6178   if (xdata[1] >= (int) node->key)
6179     return 0;
6180
6181   /* Splice out portions of the expression that refer to regno.  */
6182   rcli = (struct reg_cond_life_info *) node->value;
6183   rcli->condition = elim_reg_cond (rcli->condition, regno);
6184   if (rcli->stores != const0_rtx && rcli->stores != const1_rtx)
6185     rcli->stores = elim_reg_cond (rcli->stores, regno);
6186
6187   /* If the entire condition is now false, signal the node to be removed.  */
6188   if (rcli->condition == const0_rtx)
6189     {
6190       xdata[1] = node->key;
6191       return -1;
6192     }
6193   else if (rcli->condition == const1_rtx)
6194     abort ();
6195
6196   return 0;
6197 }
6198
6199 /* Flush all (sub) expressions referring to REGNO from REG_COND_LIVE.  */
6200
6201 static void
6202 flush_reg_cond_reg (pbi, regno)
6203      struct propagate_block_info *pbi;
6204      int regno;
6205 {
6206   int pair[2];
6207
6208   pair[0] = regno;
6209   pair[1] = -1;
6210   while (splay_tree_foreach (pbi->reg_cond_dead,
6211                              flush_reg_cond_reg_1, pair) == -1)
6212     splay_tree_remove (pbi->reg_cond_dead, pair[1]);
6213
6214   CLEAR_REGNO_REG_SET (pbi->reg_cond_reg, regno);
6215 }
6216
6217 /* Logical arithmetic on predicate conditions.  IOR, NOT and AND.
6218    For ior/and, the ADD flag determines whether we want to add the new
6219    condition X to the old one unconditionally.  If it is zero, we will
6220    only return a new expression if X allows us to simplify part of
6221    OLD, otherwise we return OLD unchanged to the caller.
6222    If ADD is nonzero, we will return a new condition in all cases.  The
6223    toplevel caller of one of these functions should always pass 1 for
6224    ADD.  */
6225
6226 static rtx
6227 ior_reg_cond (old, x, add)
6228      rtx old, x;
6229      int add;
6230 {
6231   rtx op0, op1;
6232
6233   if (GET_RTX_CLASS (GET_CODE (old)) == '<')
6234     {
6235       if (GET_RTX_CLASS (GET_CODE (x)) == '<'
6236           && REVERSE_CONDEXEC_PREDICATES_P (GET_CODE (x), GET_CODE (old))
6237           && REGNO (XEXP (x, 0)) == REGNO (XEXP (old, 0)))
6238         return const1_rtx;
6239       if (GET_CODE (x) == GET_CODE (old)
6240           && REGNO (XEXP (x, 0)) == REGNO (XEXP (old, 0)))
6241         return old;
6242       if (! add)
6243         return old;
6244       return gen_rtx_IOR (0, old, x);
6245     }
6246
6247   switch (GET_CODE (old))
6248     {
6249     case IOR:
6250       op0 = ior_reg_cond (XEXP (old, 0), x, 0);
6251       op1 = ior_reg_cond (XEXP (old, 1), x, 0);
6252       if (op0 != XEXP (old, 0) || op1 != XEXP (old, 1))
6253         {
6254           if (op0 == const0_rtx)
6255             return op1;
6256           if (op1 == const0_rtx)
6257             return op0;
6258           if (op0 == const1_rtx || op1 == const1_rtx)
6259             return const1_rtx;
6260           if (op0 == XEXP (old, 0))
6261             op0 = gen_rtx_IOR (0, op0, x);
6262           else
6263             op1 = gen_rtx_IOR (0, op1, x);
6264           return gen_rtx_IOR (0, op0, op1);
6265         }
6266       if (! add)
6267         return old;
6268       return gen_rtx_IOR (0, old, x);
6269
6270     case AND:
6271       op0 = ior_reg_cond (XEXP (old, 0), x, 0);
6272       op1 = ior_reg_cond (XEXP (old, 1), x, 0);
6273       if (op0 != XEXP (old, 0) || op1 != XEXP (old, 1))
6274         {
6275           if (op0 == const1_rtx)
6276             return op1;
6277           if (op1 == const1_rtx)
6278             return op0;
6279           if (op0 == const0_rtx || op1 == const0_rtx)
6280             return const0_rtx;
6281           if (op0 == XEXP (old, 0))
6282             op0 = gen_rtx_IOR (0, op0, x);
6283           else
6284             op1 = gen_rtx_IOR (0, op1, x);
6285           return gen_rtx_AND (0, op0, op1);
6286         }
6287       if (! add)
6288         return old;
6289       return gen_rtx_IOR (0, old, x);
6290
6291     case NOT:
6292       op0 = and_reg_cond (XEXP (old, 0), not_reg_cond (x), 0);
6293       if (op0 != XEXP (old, 0))
6294         return not_reg_cond (op0);
6295       if (! add)
6296         return old;
6297       return gen_rtx_IOR (0, old, x);
6298
6299     default:
6300       abort ();
6301     }
6302 }
6303
6304 static rtx
6305 not_reg_cond (x)
6306      rtx x;
6307 {
6308   enum rtx_code x_code;
6309
6310   if (x == const0_rtx)
6311     return const1_rtx;
6312   else if (x == const1_rtx)
6313     return const0_rtx;
6314   x_code = GET_CODE (x);
6315   if (x_code == NOT)
6316     return XEXP (x, 0);
6317   if (GET_RTX_CLASS (x_code) == '<'
6318       && GET_CODE (XEXP (x, 0)) == REG)
6319     {
6320       if (XEXP (x, 1) != const0_rtx)
6321         abort ();
6322
6323       return gen_rtx_fmt_ee (reverse_condition (x_code),
6324                              VOIDmode, XEXP (x, 0), const0_rtx);
6325     }
6326   return gen_rtx_NOT (0, x);
6327 }
6328
6329 static rtx
6330 and_reg_cond (old, x, add)
6331      rtx old, x;
6332      int add;
6333 {
6334   rtx op0, op1;
6335
6336   if (GET_RTX_CLASS (GET_CODE (old)) == '<')
6337     {
6338       if (GET_RTX_CLASS (GET_CODE (x)) == '<'
6339           && GET_CODE (x) == reverse_condition (GET_CODE (old))
6340           && REGNO (XEXP (x, 0)) == REGNO (XEXP (old, 0)))
6341         return const0_rtx;
6342       if (GET_CODE (x) == GET_CODE (old)
6343           && REGNO (XEXP (x, 0)) == REGNO (XEXP (old, 0)))
6344         return old;
6345       if (! add)
6346         return old;
6347       return gen_rtx_AND (0, old, x);
6348     }
6349
6350   switch (GET_CODE (old))
6351     {
6352     case IOR:
6353       op0 = and_reg_cond (XEXP (old, 0), x, 0);
6354       op1 = and_reg_cond (XEXP (old, 1), x, 0);
6355       if (op0 != XEXP (old, 0) || op1 != XEXP (old, 1))
6356         {
6357           if (op0 == const0_rtx)
6358             return op1;
6359           if (op1 == const0_rtx)
6360             return op0;
6361           if (op0 == const1_rtx || op1 == const1_rtx)
6362             return const1_rtx;
6363           if (op0 == XEXP (old, 0))
6364             op0 = gen_rtx_AND (0, op0, x);
6365           else
6366             op1 = gen_rtx_AND (0, op1, x);
6367           return gen_rtx_IOR (0, op0, op1);
6368         }
6369       if (! add)
6370         return old;
6371       return gen_rtx_AND (0, old, x);
6372
6373     case AND:
6374       op0 = and_reg_cond (XEXP (old, 0), x, 0);
6375       op1 = and_reg_cond (XEXP (old, 1), x, 0);
6376       if (op0 != XEXP (old, 0) || op1 != XEXP (old, 1))
6377         {
6378           if (op0 == const1_rtx)
6379             return op1;
6380           if (op1 == const1_rtx)
6381             return op0;
6382           if (op0 == const0_rtx || op1 == const0_rtx)
6383             return const0_rtx;
6384           if (op0 == XEXP (old, 0))
6385             op0 = gen_rtx_AND (0, op0, x);
6386           else
6387             op1 = gen_rtx_AND (0, op1, x);
6388           return gen_rtx_AND (0, op0, op1);
6389         }
6390       if (! add)
6391         return old;
6392
6393       /* If X is identical to one of the existing terms of the AND,
6394          then just return what we already have.  */
6395       /* ??? There really should be some sort of recursive check here in
6396          case there are nested ANDs.  */
6397       if ((GET_CODE (XEXP (old, 0)) == GET_CODE (x)
6398            && REGNO (XEXP (XEXP (old, 0), 0)) == REGNO (XEXP (x, 0)))
6399           || (GET_CODE (XEXP (old, 1)) == GET_CODE (x)
6400               && REGNO (XEXP (XEXP (old, 1), 0)) == REGNO (XEXP (x, 0))))
6401         return old;
6402
6403       return gen_rtx_AND (0, old, x);
6404
6405     case NOT:
6406       op0 = ior_reg_cond (XEXP (old, 0), not_reg_cond (x), 0);
6407       if (op0 != XEXP (old, 0))
6408         return not_reg_cond (op0);
6409       if (! add)
6410         return old;
6411       return gen_rtx_AND (0, old, x);
6412
6413     default:
6414       abort ();
6415     }
6416 }
6417
6418 /* Given a condition X, remove references to reg REGNO and return the
6419    new condition.  The removal will be done so that all conditions
6420    involving REGNO are considered to evaluate to false.  This function
6421    is used when the value of REGNO changes.  */
6422
6423 static rtx
6424 elim_reg_cond (x, regno)
6425      rtx x;
6426      unsigned int regno;
6427 {
6428   rtx op0, op1;
6429
6430   if (GET_RTX_CLASS (GET_CODE (x)) == '<')
6431     {
6432       if (REGNO (XEXP (x, 0)) == regno)
6433         return const0_rtx;
6434       return x;
6435     }
6436
6437   switch (GET_CODE (x))
6438     {
6439     case AND:
6440       op0 = elim_reg_cond (XEXP (x, 0), regno);
6441       op1 = elim_reg_cond (XEXP (x, 1), regno);
6442       if (op0 == const0_rtx || op1 == const0_rtx)
6443         return const0_rtx;
6444       if (op0 == const1_rtx)
6445         return op1;
6446       if (op1 == const1_rtx)
6447         return op0;
6448       if (op0 == XEXP (x, 0) && op1 == XEXP (x, 1))
6449         return x;
6450       return gen_rtx_AND (0, op0, op1);
6451
6452     case IOR:
6453       op0 = elim_reg_cond (XEXP (x, 0), regno);
6454       op1 = elim_reg_cond (XEXP (x, 1), regno);
6455       if (op0 == const1_rtx || op1 == const1_rtx)
6456         return const1_rtx;
6457       if (op0 == const0_rtx)
6458         return op1;
6459       if (op1 == const0_rtx)
6460         return op0;
6461       if (op0 == XEXP (x, 0) && op1 == XEXP (x, 1))
6462         return x;
6463       return gen_rtx_IOR (0, op0, op1);
6464
6465     case NOT:
6466       op0 = elim_reg_cond (XEXP (x, 0), regno);
6467       if (op0 == const0_rtx)
6468         return const1_rtx;
6469       if (op0 == const1_rtx)
6470         return const0_rtx;
6471       if (op0 != XEXP (x, 0))
6472         return not_reg_cond (op0);
6473       return x;
6474
6475     default:
6476       abort ();
6477     }
6478 }
6479 #endif /* HAVE_conditional_execution */
6480 \f
6481 #ifdef AUTO_INC_DEC
6482
6483 /* Try to substitute the auto-inc expression INC as the address inside
6484    MEM which occurs in INSN.  Currently, the address of MEM is an expression
6485    involving INCR_REG, and INCR is the next use of INCR_REG; it is an insn
6486    that has a single set whose source is a PLUS of INCR_REG and something
6487    else.  */
6488
6489 static void
6490 attempt_auto_inc (pbi, inc, insn, mem, incr, incr_reg)
6491      struct propagate_block_info *pbi;
6492      rtx inc, insn, mem, incr, incr_reg;
6493 {
6494   int regno = REGNO (incr_reg);
6495   rtx set = single_set (incr);
6496   rtx q = SET_DEST (set);
6497   rtx y = SET_SRC (set);
6498   int opnum = XEXP (y, 0) == incr_reg ? 0 : 1;
6499
6500   /* Make sure this reg appears only once in this insn.  */
6501   if (count_occurrences (PATTERN (insn), incr_reg, 1) != 1)
6502     return;
6503
6504   if (dead_or_set_p (incr, incr_reg)
6505       /* Mustn't autoinc an eliminable register.  */
6506       && (regno >= FIRST_PSEUDO_REGISTER
6507           || ! TEST_HARD_REG_BIT (elim_reg_set, regno)))
6508     {
6509       /* This is the simple case.  Try to make the auto-inc.  If
6510          we can't, we are done.  Otherwise, we will do any
6511          needed updates below.  */
6512       if (! validate_change (insn, &XEXP (mem, 0), inc, 0))
6513         return;
6514     }
6515   else if (GET_CODE (q) == REG
6516            /* PREV_INSN used here to check the semi-open interval
6517               [insn,incr).  */
6518            && ! reg_used_between_p (q,  PREV_INSN (insn), incr)
6519            /* We must also check for sets of q as q may be
6520               a call clobbered hard register and there may
6521               be a call between PREV_INSN (insn) and incr.  */
6522            && ! reg_set_between_p (q,  PREV_INSN (insn), incr))
6523     {
6524       /* We have *p followed sometime later by q = p+size.
6525          Both p and q must be live afterward,
6526          and q is not used between INSN and its assignment.
6527          Change it to q = p, ...*q..., q = q+size.
6528          Then fall into the usual case.  */
6529       rtx insns, temp;
6530
6531       start_sequence ();
6532       emit_move_insn (q, incr_reg);
6533       insns = get_insns ();
6534       end_sequence ();
6535
6536       if (basic_block_for_insn)
6537         for (temp = insns; temp; temp = NEXT_INSN (temp))
6538           set_block_for_insn (temp, pbi->bb);
6539
6540       /* If we can't make the auto-inc, or can't make the
6541          replacement into Y, exit.  There's no point in making
6542          the change below if we can't do the auto-inc and doing
6543          so is not correct in the pre-inc case.  */
6544
6545       XEXP (inc, 0) = q;
6546       validate_change (insn, &XEXP (mem, 0), inc, 1);
6547       validate_change (incr, &XEXP (y, opnum), q, 1);
6548       if (! apply_change_group ())
6549         return;
6550
6551       /* We now know we'll be doing this change, so emit the
6552          new insn(s) and do the updates.  */
6553       emit_insns_before (insns, insn);
6554
6555       if (pbi->bb->head == insn)
6556         pbi->bb->head = insns;
6557
6558       /* INCR will become a NOTE and INSN won't contain a
6559          use of INCR_REG.  If a use of INCR_REG was just placed in
6560          the insn before INSN, make that the next use.
6561          Otherwise, invalidate it.  */
6562       if (GET_CODE (PREV_INSN (insn)) == INSN
6563           && GET_CODE (PATTERN (PREV_INSN (insn))) == SET
6564           && SET_SRC (PATTERN (PREV_INSN (insn))) == incr_reg)
6565         pbi->reg_next_use[regno] = PREV_INSN (insn);
6566       else
6567         pbi->reg_next_use[regno] = 0;
6568
6569       incr_reg = q;
6570       regno = REGNO (q);
6571
6572       /* REGNO is now used in INCR which is below INSN, but
6573          it previously wasn't live here.  If we don't mark
6574          it as live, we'll put a REG_DEAD note for it
6575          on this insn, which is incorrect.  */
6576       SET_REGNO_REG_SET (pbi->reg_live, regno);
6577
6578       /* If there are any calls between INSN and INCR, show
6579          that REGNO now crosses them.  */
6580       for (temp = insn; temp != incr; temp = NEXT_INSN (temp))
6581         if (GET_CODE (temp) == CALL_INSN)
6582           REG_N_CALLS_CROSSED (regno)++;
6583     }
6584   else
6585     return;
6586
6587   /* If we haven't returned, it means we were able to make the
6588      auto-inc, so update the status.  First, record that this insn
6589      has an implicit side effect.  */
6590
6591   REG_NOTES (insn) = alloc_EXPR_LIST (REG_INC, incr_reg, REG_NOTES (insn));
6592
6593   /* Modify the old increment-insn to simply copy
6594      the already-incremented value of our register.  */
6595   if (! validate_change (incr, &SET_SRC (set), incr_reg, 0))
6596     abort ();
6597
6598   /* If that makes it a no-op (copying the register into itself) delete
6599      it so it won't appear to be a "use" and a "set" of this
6600      register.  */
6601   if (REGNO (SET_DEST (set)) == REGNO (incr_reg))
6602     {
6603       /* If the original source was dead, it's dead now.  */
6604       rtx note;
6605
6606       while ((note = find_reg_note (incr, REG_DEAD, NULL_RTX)) != NULL_RTX)
6607         {
6608           remove_note (incr, note);
6609           if (XEXP (note, 0) != incr_reg)
6610             CLEAR_REGNO_REG_SET (pbi->reg_live, REGNO (XEXP (note, 0)));
6611         }
6612
6613       PUT_CODE (incr, NOTE);
6614       NOTE_LINE_NUMBER (incr) = NOTE_INSN_DELETED;
6615       NOTE_SOURCE_FILE (incr) = 0;
6616     }
6617
6618   if (regno >= FIRST_PSEUDO_REGISTER)
6619     {
6620       /* Count an extra reference to the reg.  When a reg is
6621          incremented, spilling it is worse, so we want to make
6622          that less likely.  */
6623       REG_FREQ (regno) += (optimize_size || !pbi->bb->frequency
6624                            ? 1 : pbi->bb->frequency);
6625
6626       /* Count the increment as a setting of the register,
6627          even though it isn't a SET in rtl.  */
6628       REG_N_SETS (regno)++;
6629     }
6630 }
6631
6632 /* X is a MEM found in INSN.  See if we can convert it into an auto-increment
6633    reference.  */
6634
6635 static void
6636 find_auto_inc (pbi, x, insn)
6637      struct propagate_block_info *pbi;
6638      rtx x;
6639      rtx insn;
6640 {
6641   rtx addr = XEXP (x, 0);
6642   HOST_WIDE_INT offset = 0;
6643   rtx set, y, incr, inc_val;
6644   int regno;
6645   int size = GET_MODE_SIZE (GET_MODE (x));
6646
6647   if (GET_CODE (insn) == JUMP_INSN)
6648     return;
6649
6650   /* Here we detect use of an index register which might be good for
6651      postincrement, postdecrement, preincrement, or predecrement.  */
6652
6653   if (GET_CODE (addr) == PLUS && GET_CODE (XEXP (addr, 1)) == CONST_INT)
6654     offset = INTVAL (XEXP (addr, 1)), addr = XEXP (addr, 0);
6655
6656   if (GET_CODE (addr) != REG)
6657     return;
6658
6659   regno = REGNO (addr);
6660
6661   /* Is the next use an increment that might make auto-increment? */
6662   incr = pbi->reg_next_use[regno];
6663   if (incr == 0 || BLOCK_NUM (incr) != BLOCK_NUM (insn))
6664     return;
6665   set = single_set (incr);
6666   if (set == 0 || GET_CODE (set) != SET)
6667     return;
6668   y = SET_SRC (set);
6669
6670   if (GET_CODE (y) != PLUS)
6671     return;
6672
6673   if (REG_P (XEXP (y, 0)) && REGNO (XEXP (y, 0)) == REGNO (addr))
6674     inc_val = XEXP (y, 1);
6675   else if (REG_P (XEXP (y, 1)) && REGNO (XEXP (y, 1)) == REGNO (addr))
6676     inc_val = XEXP (y, 0);
6677   else
6678     return;
6679
6680   if (GET_CODE (inc_val) == CONST_INT)
6681     {
6682       if (HAVE_POST_INCREMENT
6683           && (INTVAL (inc_val) == size && offset == 0))
6684         attempt_auto_inc (pbi, gen_rtx_POST_INC (Pmode, addr), insn, x,
6685                           incr, addr);
6686       else if (HAVE_POST_DECREMENT
6687                && (INTVAL (inc_val) == -size && offset == 0))
6688         attempt_auto_inc (pbi, gen_rtx_POST_DEC (Pmode, addr), insn, x,
6689                           incr, addr);
6690       else if (HAVE_PRE_INCREMENT
6691                && (INTVAL (inc_val) == size && offset == size))
6692         attempt_auto_inc (pbi, gen_rtx_PRE_INC (Pmode, addr), insn, x,
6693                           incr, addr);
6694       else if (HAVE_PRE_DECREMENT
6695                && (INTVAL (inc_val) == -size && offset == -size))
6696         attempt_auto_inc (pbi, gen_rtx_PRE_DEC (Pmode, addr), insn, x,
6697                           incr, addr);
6698       else if (HAVE_POST_MODIFY_DISP && offset == 0)
6699         attempt_auto_inc (pbi, gen_rtx_POST_MODIFY (Pmode, addr,
6700                                                     gen_rtx_PLUS (Pmode,
6701                                                                   addr,
6702                                                                   inc_val)),
6703                           insn, x, incr, addr);
6704     }
6705   else if (GET_CODE (inc_val) == REG
6706            && ! reg_set_between_p (inc_val, PREV_INSN (insn),
6707                                    NEXT_INSN (incr)))
6708
6709     {
6710       if (HAVE_POST_MODIFY_REG && offset == 0)
6711         attempt_auto_inc (pbi, gen_rtx_POST_MODIFY (Pmode, addr,
6712                                                     gen_rtx_PLUS (Pmode,
6713                                                                   addr,
6714                                                                   inc_val)),
6715                           insn, x, incr, addr);
6716     }
6717 }
6718
6719 #endif /* AUTO_INC_DEC */
6720 \f
6721 static void
6722 mark_used_reg (pbi, reg, cond, insn)
6723      struct propagate_block_info *pbi;
6724      rtx reg;
6725      rtx cond ATTRIBUTE_UNUSED;
6726      rtx insn;
6727 {
6728   unsigned int regno_first, regno_last, i;
6729   int some_was_live, some_was_dead, some_not_set;
6730
6731   regno_last = regno_first = REGNO (reg);
6732   if (regno_first < FIRST_PSEUDO_REGISTER)
6733     regno_last += HARD_REGNO_NREGS (regno_first, GET_MODE (reg)) - 1;
6734
6735   /* Find out if any of this register is live after this instruction.  */
6736   some_was_live = some_was_dead = 0;
6737   for (i = regno_first; i <= regno_last; ++i)
6738     {
6739       int needed_regno = REGNO_REG_SET_P (pbi->reg_live, i);
6740       some_was_live |= needed_regno;
6741       some_was_dead |= ! needed_regno;
6742     }
6743
6744   /* Find out if any of the register was set this insn.  */
6745   some_not_set = 0;
6746   for (i = regno_first; i <= regno_last; ++i)
6747     some_not_set |= ! REGNO_REG_SET_P (pbi->new_set, i);
6748
6749   if (pbi->flags & (PROP_LOG_LINKS | PROP_AUTOINC))
6750     {
6751       /* Record where each reg is used, so when the reg is set we know
6752          the next insn that uses it.  */
6753       pbi->reg_next_use[regno_first] = insn;
6754     }
6755
6756   if (pbi->flags & PROP_REG_INFO)
6757     {
6758       if (regno_first < FIRST_PSEUDO_REGISTER)
6759         {
6760           /* If this is a register we are going to try to eliminate,
6761              don't mark it live here.  If we are successful in
6762              eliminating it, it need not be live unless it is used for
6763              pseudos, in which case it will have been set live when it
6764              was allocated to the pseudos.  If the register will not
6765              be eliminated, reload will set it live at that point.
6766
6767              Otherwise, record that this function uses this register.  */
6768           /* ??? The PPC backend tries to "eliminate" on the pic
6769              register to itself.  This should be fixed.  In the mean
6770              time, hack around it.  */
6771
6772           if (! (TEST_HARD_REG_BIT (elim_reg_set, regno_first)
6773                  && (regno_first == FRAME_POINTER_REGNUM
6774                      || regno_first == ARG_POINTER_REGNUM)))
6775             for (i = regno_first; i <= regno_last; ++i)
6776               regs_ever_live[i] = 1;
6777         }
6778       else
6779         {
6780           /* Keep track of which basic block each reg appears in.  */
6781
6782           register int blocknum = pbi->bb->index;
6783           if (REG_BASIC_BLOCK (regno_first) == REG_BLOCK_UNKNOWN)
6784             REG_BASIC_BLOCK (regno_first) = blocknum;
6785           else if (REG_BASIC_BLOCK (regno_first) != blocknum)
6786             REG_BASIC_BLOCK (regno_first) = REG_BLOCK_GLOBAL;
6787
6788           /* Count (weighted) number of uses of each reg.  */
6789           REG_FREQ (regno_first)
6790             += (optimize_size || !pbi->bb->frequency ? 1 : pbi->bb->frequency);
6791           REG_N_REFS (regno_first)++;
6792         }
6793     }
6794
6795   /* Record and count the insns in which a reg dies.  If it is used in
6796      this insn and was dead below the insn then it dies in this insn.
6797      If it was set in this insn, we do not make a REG_DEAD note;
6798      likewise if we already made such a note.  */
6799   if ((pbi->flags & (PROP_DEATH_NOTES | PROP_REG_INFO))
6800       && some_was_dead
6801       && some_not_set)
6802     {
6803       /* Check for the case where the register dying partially
6804          overlaps the register set by this insn.  */
6805       if (regno_first != regno_last)
6806         for (i = regno_first; i <= regno_last; ++i)
6807           some_was_live |= REGNO_REG_SET_P (pbi->new_set, i);
6808
6809       /* If none of the words in X is needed, make a REG_DEAD note.
6810          Otherwise, we must make partial REG_DEAD notes.  */
6811       if (! some_was_live)
6812         {
6813           if ((pbi->flags & PROP_DEATH_NOTES)
6814               && ! find_regno_note (insn, REG_DEAD, regno_first))
6815             REG_NOTES (insn)
6816               = alloc_EXPR_LIST (REG_DEAD, reg, REG_NOTES (insn));
6817
6818           if (pbi->flags & PROP_REG_INFO)
6819             REG_N_DEATHS (regno_first)++;
6820         }
6821       else
6822         {
6823           /* Don't make a REG_DEAD note for a part of a register
6824              that is set in the insn.  */
6825           for (i = regno_first; i <= regno_last; ++i)
6826             if (! REGNO_REG_SET_P (pbi->reg_live, i)
6827                 && ! dead_or_set_regno_p (insn, i))
6828               REG_NOTES (insn)
6829                 = alloc_EXPR_LIST (REG_DEAD,
6830                                    gen_rtx_REG (reg_raw_mode[i], i),
6831                                    REG_NOTES (insn));
6832         }
6833     }
6834
6835   /* Mark the register as being live.  */
6836   for (i = regno_first; i <= regno_last; ++i)
6837     {
6838       SET_REGNO_REG_SET (pbi->reg_live, i);
6839
6840 #ifdef HAVE_conditional_execution
6841       /* If this is a conditional use, record that fact.  If it is later
6842          conditionally set, we'll know to kill the register.  */
6843       if (cond != NULL_RTX)
6844         {
6845           splay_tree_node node;
6846           struct reg_cond_life_info *rcli;
6847           rtx ncond;
6848
6849           if (some_was_live)
6850             {
6851               node = splay_tree_lookup (pbi->reg_cond_dead, i);
6852               if (node == NULL)
6853                 {
6854                   /* The register was unconditionally live previously.
6855                      No need to do anything.  */
6856                 }
6857               else
6858                 {
6859                   /* The register was conditionally live previously.
6860                      Subtract the new life cond from the old death cond.  */
6861                   rcli = (struct reg_cond_life_info *) node->value;
6862                   ncond = rcli->condition;
6863                   ncond = and_reg_cond (ncond, not_reg_cond (cond), 1);
6864
6865                   /* If the register is now unconditionally live,
6866                      remove the entry in the splay_tree.  */
6867                   if (ncond == const0_rtx)
6868                     splay_tree_remove (pbi->reg_cond_dead, i);
6869                   else
6870                     {
6871                       rcli->condition = ncond;
6872                       SET_REGNO_REG_SET (pbi->reg_cond_reg,
6873                                          REGNO (XEXP (cond, 0)));
6874                     }
6875                 }
6876             }
6877           else
6878             {
6879               /* The register was not previously live at all.  Record
6880                  the condition under which it is still dead.  */
6881               rcli = (struct reg_cond_life_info *) xmalloc (sizeof (*rcli));
6882               rcli->condition = not_reg_cond (cond);
6883               rcli->stores = const0_rtx;
6884               rcli->orig_condition = const0_rtx;
6885               splay_tree_insert (pbi->reg_cond_dead, i,
6886                                  (splay_tree_value) rcli);
6887
6888               SET_REGNO_REG_SET (pbi->reg_cond_reg, REGNO (XEXP (cond, 0)));
6889             }
6890         }
6891       else if (some_was_live)
6892         {
6893           /* The register may have been conditionally live previously, but
6894              is now unconditionally live.  Remove it from the conditionally
6895              dead list, so that a conditional set won't cause us to think
6896              it dead.  */
6897           splay_tree_remove (pbi->reg_cond_dead, i);
6898         }
6899 #endif
6900     }
6901 }
6902
6903 /* Scan expression X and store a 1-bit in NEW_LIVE for each reg it uses.
6904    This is done assuming the registers needed from X are those that
6905    have 1-bits in PBI->REG_LIVE.
6906
6907    INSN is the containing instruction.  If INSN is dead, this function
6908    is not called.  */
6909
6910 static void
6911 mark_used_regs (pbi, x, cond, insn)
6912      struct propagate_block_info *pbi;
6913      rtx x, cond, insn;
6914 {
6915   register RTX_CODE code;
6916   register int regno;
6917   int flags = pbi->flags;
6918
6919  retry:
6920   code = GET_CODE (x);
6921   switch (code)
6922     {
6923     case LABEL_REF:
6924     case SYMBOL_REF:
6925     case CONST_INT:
6926     case CONST:
6927     case CONST_DOUBLE:
6928     case PC:
6929     case ADDR_VEC:
6930     case ADDR_DIFF_VEC:
6931       return;
6932
6933 #ifdef HAVE_cc0
6934     case CC0:
6935       pbi->cc0_live = 1;
6936       return;
6937 #endif
6938
6939     case CLOBBER:
6940       /* If we are clobbering a MEM, mark any registers inside the address
6941          as being used.  */
6942       if (GET_CODE (XEXP (x, 0)) == MEM)
6943         mark_used_regs (pbi, XEXP (XEXP (x, 0), 0), cond, insn);
6944       return;
6945
6946     case MEM:
6947       /* Don't bother watching stores to mems if this is not the
6948          final pass.  We'll not be deleting dead stores this round.  */
6949       if (optimize && (flags & PROP_SCAN_DEAD_CODE))
6950         {
6951           /* Invalidate the data for the last MEM stored, but only if MEM is
6952              something that can be stored into.  */
6953           if (GET_CODE (XEXP (x, 0)) == SYMBOL_REF
6954               && CONSTANT_POOL_ADDRESS_P (XEXP (x, 0)))
6955             /* Needn't clear the memory set list.  */
6956             ;
6957           else
6958             {
6959               rtx temp = pbi->mem_set_list;
6960               rtx prev = NULL_RTX;
6961               rtx next;
6962
6963               while (temp)
6964                 {
6965                   next = XEXP (temp, 1);
6966                   if (anti_dependence (XEXP (temp, 0), x))
6967                     {
6968                       /* Splice temp out of the list.  */
6969                       if (prev)
6970                         XEXP (prev, 1) = next;
6971                       else
6972                         pbi->mem_set_list = next;
6973                       free_EXPR_LIST_node (temp);
6974                       pbi->mem_set_list_len--;
6975                     }
6976                   else
6977                     prev = temp;
6978                   temp = next;
6979                 }
6980             }
6981
6982           /* If the memory reference had embedded side effects (autoincrement
6983              address modes.  Then we may need to kill some entries on the
6984              memory set list.  */
6985           if (insn)
6986             invalidate_mems_from_autoinc (pbi, insn);
6987         }
6988
6989 #ifdef AUTO_INC_DEC
6990       if (flags & PROP_AUTOINC)
6991         find_auto_inc (pbi, x, insn);
6992 #endif
6993       break;
6994
6995     case SUBREG:
6996 #ifdef CLASS_CANNOT_CHANGE_MODE
6997       if (GET_CODE (SUBREG_REG (x)) == REG
6998           && REGNO (SUBREG_REG (x)) >= FIRST_PSEUDO_REGISTER
6999           && CLASS_CANNOT_CHANGE_MODE_P (GET_MODE (x),
7000                                          GET_MODE (SUBREG_REG (x))))
7001         REG_CHANGES_MODE (REGNO (SUBREG_REG (x))) = 1;
7002 #endif
7003
7004       /* While we're here, optimize this case.  */
7005       x = SUBREG_REG (x);
7006       if (GET_CODE (x) != REG)
7007         goto retry;
7008       /* Fall through.  */
7009
7010     case REG:
7011       /* See a register other than being set => mark it as needed.  */
7012       mark_used_reg (pbi, x, cond, insn);
7013       return;
7014
7015     case SET:
7016       {
7017         register rtx testreg = SET_DEST (x);
7018         int mark_dest = 0;
7019
7020         /* If storing into MEM, don't show it as being used.  But do
7021            show the address as being used.  */
7022         if (GET_CODE (testreg) == MEM)
7023           {
7024 #ifdef AUTO_INC_DEC
7025             if (flags & PROP_AUTOINC)
7026               find_auto_inc (pbi, testreg, insn);
7027 #endif
7028             mark_used_regs (pbi, XEXP (testreg, 0), cond, insn);
7029             mark_used_regs (pbi, SET_SRC (x), cond, insn);
7030             return;
7031           }
7032
7033         /* Storing in STRICT_LOW_PART is like storing in a reg
7034            in that this SET might be dead, so ignore it in TESTREG.
7035            but in some other ways it is like using the reg.
7036
7037            Storing in a SUBREG or a bit field is like storing the entire
7038            register in that if the register's value is not used
7039            then this SET is not needed.  */
7040         while (GET_CODE (testreg) == STRICT_LOW_PART
7041                || GET_CODE (testreg) == ZERO_EXTRACT
7042                || GET_CODE (testreg) == SIGN_EXTRACT
7043                || GET_CODE (testreg) == SUBREG)
7044           {
7045 #ifdef CLASS_CANNOT_CHANGE_MODE
7046             if (GET_CODE (testreg) == SUBREG
7047                 && GET_CODE (SUBREG_REG (testreg)) == REG
7048                 && REGNO (SUBREG_REG (testreg)) >= FIRST_PSEUDO_REGISTER
7049                 && CLASS_CANNOT_CHANGE_MODE_P (GET_MODE (SUBREG_REG (testreg)),
7050                                                GET_MODE (testreg)))
7051               REG_CHANGES_MODE (REGNO (SUBREG_REG (testreg))) = 1;
7052 #endif
7053
7054             /* Modifying a single register in an alternate mode
7055                does not use any of the old value.  But these other
7056                ways of storing in a register do use the old value.  */
7057             if (GET_CODE (testreg) == SUBREG
7058                 && !(REG_SIZE (SUBREG_REG (testreg)) > REG_SIZE (testreg)))
7059               ;
7060             else
7061               mark_dest = 1;
7062
7063             testreg = XEXP (testreg, 0);
7064           }
7065
7066         /* If this is a store into a register or group of registers,
7067            recursively scan the value being stored.  */
7068
7069         if ((GET_CODE (testreg) == PARALLEL
7070              && GET_MODE (testreg) == BLKmode)
7071             || (GET_CODE (testreg) == REG
7072                 && (regno = REGNO (testreg),
7073                     ! (regno == FRAME_POINTER_REGNUM
7074                        && (! reload_completed || frame_pointer_needed)))
7075 #if FRAME_POINTER_REGNUM != HARD_FRAME_POINTER_REGNUM
7076                 && ! (regno == HARD_FRAME_POINTER_REGNUM
7077                       && (! reload_completed || frame_pointer_needed))
7078 #endif
7079 #if FRAME_POINTER_REGNUM != ARG_POINTER_REGNUM
7080                 && ! (regno == ARG_POINTER_REGNUM && fixed_regs[regno])
7081 #endif
7082                 ))
7083           {
7084             if (mark_dest)
7085               mark_used_regs (pbi, SET_DEST (x), cond, insn);
7086             mark_used_regs (pbi, SET_SRC (x), cond, insn);
7087             return;
7088           }
7089       }
7090       break;
7091
7092     case ASM_OPERANDS:
7093     case UNSPEC_VOLATILE:
7094     case TRAP_IF:
7095     case ASM_INPUT:
7096       {
7097         /* Traditional and volatile asm instructions must be considered to use
7098            and clobber all hard registers, all pseudo-registers and all of
7099            memory.  So must TRAP_IF and UNSPEC_VOLATILE operations.
7100
7101            Consider for instance a volatile asm that changes the fpu rounding
7102            mode.  An insn should not be moved across this even if it only uses
7103            pseudo-regs because it might give an incorrectly rounded result.
7104
7105            ?!? Unfortunately, marking all hard registers as live causes massive
7106            problems for the register allocator and marking all pseudos as live
7107            creates mountains of uninitialized variable warnings.
7108
7109            So for now, just clear the memory set list and mark any regs
7110            we can find in ASM_OPERANDS as used.  */
7111         if (code != ASM_OPERANDS || MEM_VOLATILE_P (x))
7112           {
7113             free_EXPR_LIST_list (&pbi->mem_set_list);
7114             pbi->mem_set_list_len = 0;
7115           }
7116
7117         /* For all ASM_OPERANDS, we must traverse the vector of input operands.
7118            We can not just fall through here since then we would be confused
7119            by the ASM_INPUT rtx inside ASM_OPERANDS, which do not indicate
7120            traditional asms unlike their normal usage.  */
7121         if (code == ASM_OPERANDS)
7122           {
7123             int j;
7124
7125             for (j = 0; j < ASM_OPERANDS_INPUT_LENGTH (x); j++)
7126               mark_used_regs (pbi, ASM_OPERANDS_INPUT (x, j), cond, insn);
7127           }
7128         break;
7129       }
7130
7131     case COND_EXEC:
7132       if (cond != NULL_RTX)
7133         abort ();
7134
7135       mark_used_regs (pbi, COND_EXEC_TEST (x), NULL_RTX, insn);
7136
7137       cond = COND_EXEC_TEST (x);
7138       x = COND_EXEC_CODE (x);
7139       goto retry;
7140
7141     case PHI:
7142       /* We _do_not_ want to scan operands of phi nodes.  Operands of
7143          a phi function are evaluated only when control reaches this
7144          block along a particular edge.  Therefore, regs that appear
7145          as arguments to phi should not be added to the global live at
7146          start.  */
7147       return;
7148
7149     default:
7150       break;
7151     }
7152
7153   /* Recursively scan the operands of this expression.  */
7154
7155   {
7156     register const char *fmt = GET_RTX_FORMAT (code);
7157     register int i;
7158
7159     for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
7160       {
7161         if (fmt[i] == 'e')
7162           {
7163             /* Tail recursive case: save a function call level.  */
7164             if (i == 0)
7165               {
7166                 x = XEXP (x, 0);
7167                 goto retry;
7168               }
7169             mark_used_regs (pbi, XEXP (x, i), cond, insn);
7170           }
7171         else if (fmt[i] == 'E')
7172           {
7173             register int j;
7174             for (j = 0; j < XVECLEN (x, i); j++)
7175               mark_used_regs (pbi, XVECEXP (x, i, j), cond, insn);
7176           }
7177       }
7178   }
7179 }
7180 \f
7181 #ifdef AUTO_INC_DEC
7182
7183 static int
7184 try_pre_increment_1 (pbi, insn)
7185      struct propagate_block_info *pbi;
7186      rtx insn;
7187 {
7188   /* Find the next use of this reg.  If in same basic block,
7189      make it do pre-increment or pre-decrement if appropriate.  */
7190   rtx x = single_set (insn);
7191   HOST_WIDE_INT amount = ((GET_CODE (SET_SRC (x)) == PLUS ? 1 : -1)
7192                           * INTVAL (XEXP (SET_SRC (x), 1)));
7193   int regno = REGNO (SET_DEST (x));
7194   rtx y = pbi->reg_next_use[regno];
7195   if (y != 0
7196       && SET_DEST (x) != stack_pointer_rtx
7197       && BLOCK_NUM (y) == BLOCK_NUM (insn)
7198       /* Don't do this if the reg dies, or gets set in y; a standard addressing
7199          mode would be better.  */
7200       && ! dead_or_set_p (y, SET_DEST (x))
7201       && try_pre_increment (y, SET_DEST (x), amount))
7202     {
7203       /* We have found a suitable auto-increment and already changed
7204          insn Y to do it.  So flush this increment instruction.  */
7205       propagate_block_delete_insn (pbi->bb, insn);
7206
7207       /* Count a reference to this reg for the increment insn we are
7208          deleting.  When a reg is incremented, spilling it is worse,
7209          so we want to make that less likely.  */
7210       if (regno >= FIRST_PSEUDO_REGISTER)
7211         {
7212           REG_FREQ (regno) += (optimize_size || !pbi->bb->frequency
7213                                ? 1 : pbi->bb->frequency);
7214           REG_N_SETS (regno)++;
7215         }
7216
7217       /* Flush any remembered memories depending on the value of
7218          the incremented register.  */
7219       invalidate_mems_from_set (pbi, SET_DEST (x));
7220
7221       return 1;
7222     }
7223   return 0;
7224 }
7225
7226 /* Try to change INSN so that it does pre-increment or pre-decrement
7227    addressing on register REG in order to add AMOUNT to REG.
7228    AMOUNT is negative for pre-decrement.
7229    Returns 1 if the change could be made.
7230    This checks all about the validity of the result of modifying INSN.  */
7231
7232 static int
7233 try_pre_increment (insn, reg, amount)
7234      rtx insn, reg;
7235      HOST_WIDE_INT amount;
7236 {
7237   register rtx use;
7238
7239   /* Nonzero if we can try to make a pre-increment or pre-decrement.
7240      For example, addl $4,r1; movl (r1),... can become movl +(r1),...  */
7241   int pre_ok = 0;
7242   /* Nonzero if we can try to make a post-increment or post-decrement.
7243      For example, addl $4,r1; movl -4(r1),... can become movl (r1)+,...
7244      It is possible for both PRE_OK and POST_OK to be nonzero if the machine
7245      supports both pre-inc and post-inc, or both pre-dec and post-dec.  */
7246   int post_ok = 0;
7247
7248   /* Nonzero if the opportunity actually requires post-inc or post-dec.  */
7249   int do_post = 0;
7250
7251   /* From the sign of increment, see which possibilities are conceivable
7252      on this target machine.  */
7253   if (HAVE_PRE_INCREMENT && amount > 0)
7254     pre_ok = 1;
7255   if (HAVE_POST_INCREMENT && amount > 0)
7256     post_ok = 1;
7257
7258   if (HAVE_PRE_DECREMENT && amount < 0)
7259     pre_ok = 1;
7260   if (HAVE_POST_DECREMENT && amount < 0)
7261     post_ok = 1;
7262
7263   if (! (pre_ok || post_ok))
7264     return 0;
7265
7266   /* It is not safe to add a side effect to a jump insn
7267      because if the incremented register is spilled and must be reloaded
7268      there would be no way to store the incremented value back in memory.  */
7269
7270   if (GET_CODE (insn) == JUMP_INSN)
7271     return 0;
7272
7273   use = 0;
7274   if (pre_ok)
7275     use = find_use_as_address (PATTERN (insn), reg, 0);
7276   if (post_ok && (use == 0 || use == (rtx) 1))
7277     {
7278       use = find_use_as_address (PATTERN (insn), reg, -amount);
7279       do_post = 1;
7280     }
7281
7282   if (use == 0 || use == (rtx) 1)
7283     return 0;
7284
7285   if (GET_MODE_SIZE (GET_MODE (use)) != (amount > 0 ? amount : - amount))
7286     return 0;
7287
7288   /* See if this combination of instruction and addressing mode exists.  */
7289   if (! validate_change (insn, &XEXP (use, 0),
7290                          gen_rtx_fmt_e (amount > 0
7291                                         ? (do_post ? POST_INC : PRE_INC)
7292                                         : (do_post ? POST_DEC : PRE_DEC),
7293                                         Pmode, reg), 0))
7294     return 0;
7295
7296   /* Record that this insn now has an implicit side effect on X.  */
7297   REG_NOTES (insn) = alloc_EXPR_LIST (REG_INC, reg, REG_NOTES (insn));
7298   return 1;
7299 }
7300
7301 #endif /* AUTO_INC_DEC */
7302 \f
7303 /* Find the place in the rtx X where REG is used as a memory address.
7304    Return the MEM rtx that so uses it.
7305    If PLUSCONST is nonzero, search instead for a memory address equivalent to
7306    (plus REG (const_int PLUSCONST)).
7307
7308    If such an address does not appear, return 0.
7309    If REG appears more than once, or is used other than in such an address,
7310    return (rtx)1.  */
7311
7312 rtx
7313 find_use_as_address (x, reg, plusconst)
7314      register rtx x;
7315      rtx reg;
7316      HOST_WIDE_INT plusconst;
7317 {
7318   enum rtx_code code = GET_CODE (x);
7319   const char *fmt = GET_RTX_FORMAT (code);
7320   register int i;
7321   register rtx value = 0;
7322   register rtx tem;
7323
7324   if (code == MEM && XEXP (x, 0) == reg && plusconst == 0)
7325     return x;
7326
7327   if (code == MEM && GET_CODE (XEXP (x, 0)) == PLUS
7328       && XEXP (XEXP (x, 0), 0) == reg
7329       && GET_CODE (XEXP (XEXP (x, 0), 1)) == CONST_INT
7330       && INTVAL (XEXP (XEXP (x, 0), 1)) == plusconst)
7331     return x;
7332
7333   if (code == SIGN_EXTRACT || code == ZERO_EXTRACT)
7334     {
7335       /* If REG occurs inside a MEM used in a bit-field reference,
7336          that is unacceptable.  */
7337       if (find_use_as_address (XEXP (x, 0), reg, 0) != 0)
7338         return (rtx) (HOST_WIDE_INT) 1;
7339     }
7340
7341   if (x == reg)
7342     return (rtx) (HOST_WIDE_INT) 1;
7343
7344   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
7345     {
7346       if (fmt[i] == 'e')
7347         {
7348           tem = find_use_as_address (XEXP (x, i), reg, plusconst);
7349           if (value == 0)
7350             value = tem;
7351           else if (tem != 0)
7352             return (rtx) (HOST_WIDE_INT) 1;
7353         }
7354       else if (fmt[i] == 'E')
7355         {
7356           register int j;
7357           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
7358             {
7359               tem = find_use_as_address (XVECEXP (x, i, j), reg, plusconst);
7360               if (value == 0)
7361                 value = tem;
7362               else if (tem != 0)
7363                 return (rtx) (HOST_WIDE_INT) 1;
7364             }
7365         }
7366     }
7367
7368   return value;
7369 }
7370 \f
7371 /* Write information about registers and basic blocks into FILE.
7372    This is part of making a debugging dump.  */
7373
7374 void
7375 dump_regset (r, outf)
7376      regset r;
7377      FILE *outf;
7378 {
7379   int i;
7380   if (r == NULL)
7381     {
7382       fputs (" (nil)", outf);
7383       return;
7384     }
7385
7386   EXECUTE_IF_SET_IN_REG_SET (r, 0, i,
7387     {
7388       fprintf (outf, " %d", i);
7389       if (i < FIRST_PSEUDO_REGISTER)
7390         fprintf (outf, " [%s]",
7391                  reg_names[i]);
7392     });
7393 }
7394
7395 /* Print a human-reaable representation of R on the standard error
7396    stream.  This function is designed to be used from within the
7397    debugger.  */
7398
7399 void
7400 debug_regset (r)
7401      regset r;
7402 {
7403   dump_regset (r, stderr);
7404   putc ('\n', stderr);
7405 }
7406
7407 void
7408 dump_flow_info (file)
7409      FILE *file;
7410 {
7411   register int i;
7412   static const char * const reg_class_names[] = REG_CLASS_NAMES;
7413
7414   fprintf (file, "%d registers.\n", max_regno);
7415   for (i = FIRST_PSEUDO_REGISTER; i < max_regno; i++)
7416     if (REG_N_REFS (i))
7417       {
7418         enum reg_class class, altclass;
7419         fprintf (file, "\nRegister %d used %d times across %d insns",
7420                  i, REG_N_REFS (i), REG_LIVE_LENGTH (i));
7421         if (REG_BASIC_BLOCK (i) >= 0)
7422           fprintf (file, " in block %d", REG_BASIC_BLOCK (i));
7423         if (REG_N_SETS (i))
7424           fprintf (file, "; set %d time%s", REG_N_SETS (i),
7425                    (REG_N_SETS (i) == 1) ? "" : "s");
7426         if (REG_USERVAR_P (regno_reg_rtx[i]))
7427           fprintf (file, "; user var");
7428         if (REG_N_DEATHS (i) != 1)
7429           fprintf (file, "; dies in %d places", REG_N_DEATHS (i));
7430         if (REG_N_CALLS_CROSSED (i) == 1)
7431           fprintf (file, "; crosses 1 call");
7432         else if (REG_N_CALLS_CROSSED (i))
7433           fprintf (file, "; crosses %d calls", REG_N_CALLS_CROSSED (i));
7434         if (PSEUDO_REGNO_BYTES (i) != UNITS_PER_WORD)
7435           fprintf (file, "; %d bytes", PSEUDO_REGNO_BYTES (i));
7436         class = reg_preferred_class (i);
7437         altclass = reg_alternate_class (i);
7438         if (class != GENERAL_REGS || altclass != ALL_REGS)
7439           {
7440             if (altclass == ALL_REGS || class == ALL_REGS)
7441               fprintf (file, "; pref %s", reg_class_names[(int) class]);
7442             else if (altclass == NO_REGS)
7443               fprintf (file, "; %s or none", reg_class_names[(int) class]);
7444             else
7445               fprintf (file, "; pref %s, else %s",
7446                        reg_class_names[(int) class],
7447                        reg_class_names[(int) altclass]);
7448           }
7449         if (REG_POINTER (regno_reg_rtx[i]))
7450           fprintf (file, "; pointer");
7451         fprintf (file, ".\n");
7452       }
7453
7454   fprintf (file, "\n%d basic blocks, %d edges.\n", n_basic_blocks, n_edges);
7455   for (i = 0; i < n_basic_blocks; i++)
7456     {
7457       register basic_block bb = BASIC_BLOCK (i);
7458       register edge e;
7459
7460       fprintf (file, "\nBasic block %d: first insn %d, last %d, loop_depth %d, count ",
7461                i, INSN_UID (bb->head), INSN_UID (bb->end), bb->loop_depth);
7462       fprintf (file, HOST_WIDEST_INT_PRINT_DEC, (HOST_WIDEST_INT) bb->count);
7463       fprintf (file, ", freq %i.\n", bb->frequency);
7464
7465       fprintf (file, "Predecessors: ");
7466       for (e = bb->pred; e; e = e->pred_next)
7467         dump_edge_info (file, e, 0);
7468
7469       fprintf (file, "\nSuccessors: ");
7470       for (e = bb->succ; e; e = e->succ_next)
7471         dump_edge_info (file, e, 1);
7472
7473       fprintf (file, "\nRegisters live at start:");
7474       dump_regset (bb->global_live_at_start, file);
7475
7476       fprintf (file, "\nRegisters live at end:");
7477       dump_regset (bb->global_live_at_end, file);
7478
7479       putc ('\n', file);
7480     }
7481
7482   putc ('\n', file);
7483 }
7484
7485 void
7486 debug_flow_info ()
7487 {
7488   dump_flow_info (stderr);
7489 }
7490
7491 void
7492 dump_edge_info (file, e, do_succ)
7493      FILE *file;
7494      edge e;
7495      int do_succ;
7496 {
7497   basic_block side = (do_succ ? e->dest : e->src);
7498
7499   if (side == ENTRY_BLOCK_PTR)
7500     fputs (" ENTRY", file);
7501   else if (side == EXIT_BLOCK_PTR)
7502     fputs (" EXIT", file);
7503   else
7504     fprintf (file, " %d", side->index);
7505
7506   if (e->probability)
7507     fprintf (file, " [%.1f%%] ", e->probability * 100.0 / REG_BR_PROB_BASE);
7508
7509   if (e->count)
7510     {
7511       fprintf (file, " count:");
7512       fprintf (file, HOST_WIDEST_INT_PRINT_DEC, (HOST_WIDEST_INT) e->count);
7513     }
7514
7515   if (e->flags)
7516     {
7517       static const char * const bitnames[] = {
7518         "fallthru", "crit", "ab", "abcall", "eh", "fake"
7519       };
7520       int comma = 0;
7521       int i, flags = e->flags;
7522
7523       fputc (' ', file);
7524       fputc ('(', file);
7525       for (i = 0; flags; i++)
7526         if (flags & (1 << i))
7527           {
7528             flags &= ~(1 << i);
7529
7530             if (comma)
7531               fputc (',', file);
7532             if (i < (int) ARRAY_SIZE (bitnames))
7533               fputs (bitnames[i], file);
7534             else
7535               fprintf (file, "%d", i);
7536             comma = 1;
7537           }
7538       fputc (')', file);
7539     }
7540 }
7541 \f
7542 /* Print out one basic block with live information at start and end.  */
7543
7544 void
7545 dump_bb (bb, outf)
7546      basic_block bb;
7547      FILE *outf;
7548 {
7549   rtx insn;
7550   rtx last;
7551   edge e;
7552
7553   fprintf (outf, ";; Basic block %d, loop depth %d, count ",
7554            bb->index, bb->loop_depth);
7555   fprintf (outf, HOST_WIDEST_INT_PRINT_DEC, (HOST_WIDEST_INT) bb->count);
7556   putc ('\n', outf);
7557
7558   fputs (";; Predecessors: ", outf);
7559   for (e = bb->pred; e; e = e->pred_next)
7560     dump_edge_info (outf, e, 0);
7561   putc ('\n', outf);
7562
7563   fputs (";; Registers live at start:", outf);
7564   dump_regset (bb->global_live_at_start, outf);
7565   putc ('\n', outf);
7566
7567   for (insn = bb->head, last = NEXT_INSN (bb->end);
7568        insn != last;
7569        insn = NEXT_INSN (insn))
7570     print_rtl_single (outf, insn);
7571
7572   fputs (";; Registers live at end:", outf);
7573   dump_regset (bb->global_live_at_end, outf);
7574   putc ('\n', outf);
7575
7576   fputs (";; Successors: ", outf);
7577   for (e = bb->succ; e; e = e->succ_next)
7578     dump_edge_info (outf, e, 1);
7579   putc ('\n', outf);
7580 }
7581
7582 void
7583 debug_bb (bb)
7584      basic_block bb;
7585 {
7586   dump_bb (bb, stderr);
7587 }
7588
7589 void
7590 debug_bb_n (n)
7591      int n;
7592 {
7593   dump_bb (BASIC_BLOCK (n), stderr);
7594 }
7595
7596 /* Like print_rtl, but also print out live information for the start of each
7597    basic block.  */
7598
7599 void
7600 print_rtl_with_bb (outf, rtx_first)
7601      FILE *outf;
7602      rtx rtx_first;
7603 {
7604   register rtx tmp_rtx;
7605
7606   if (rtx_first == 0)
7607     fprintf (outf, "(nil)\n");
7608   else
7609     {
7610       int i;
7611       enum bb_state { NOT_IN_BB, IN_ONE_BB, IN_MULTIPLE_BB };
7612       int max_uid = get_max_uid ();
7613       basic_block *start = (basic_block *)
7614         xcalloc (max_uid, sizeof (basic_block));
7615       basic_block *end = (basic_block *)
7616         xcalloc (max_uid, sizeof (basic_block));
7617       enum bb_state *in_bb_p = (enum bb_state *)
7618         xcalloc (max_uid, sizeof (enum bb_state));
7619
7620       for (i = n_basic_blocks - 1; i >= 0; i--)
7621         {
7622           basic_block bb = BASIC_BLOCK (i);
7623           rtx x;
7624
7625           start[INSN_UID (bb->head)] = bb;
7626           end[INSN_UID (bb->end)] = bb;
7627           for (x = bb->head; x != NULL_RTX; x = NEXT_INSN (x))
7628             {
7629               enum bb_state state = IN_MULTIPLE_BB;
7630               if (in_bb_p[INSN_UID (x)] == NOT_IN_BB)
7631                 state = IN_ONE_BB;
7632               in_bb_p[INSN_UID (x)] = state;
7633
7634               if (x == bb->end)
7635                 break;
7636             }
7637         }
7638
7639       for (tmp_rtx = rtx_first; NULL != tmp_rtx; tmp_rtx = NEXT_INSN (tmp_rtx))
7640         {
7641           int did_output;
7642           basic_block bb;
7643
7644           if ((bb = start[INSN_UID (tmp_rtx)]) != NULL)
7645             {
7646               fprintf (outf, ";; Start of basic block %d, registers live:",
7647                        bb->index);
7648               dump_regset (bb->global_live_at_start, outf);
7649               putc ('\n', outf);
7650             }
7651
7652           if (in_bb_p[INSN_UID (tmp_rtx)] == NOT_IN_BB
7653               && GET_CODE (tmp_rtx) != NOTE
7654               && GET_CODE (tmp_rtx) != BARRIER)
7655             fprintf (outf, ";; Insn is not within a basic block\n");
7656           else if (in_bb_p[INSN_UID (tmp_rtx)] == IN_MULTIPLE_BB)
7657             fprintf (outf, ";; Insn is in multiple basic blocks\n");
7658
7659           did_output = print_rtl_single (outf, tmp_rtx);
7660
7661           if ((bb = end[INSN_UID (tmp_rtx)]) != NULL)
7662             {
7663               fprintf (outf, ";; End of basic block %d, registers live:\n",
7664                        bb->index);
7665               dump_regset (bb->global_live_at_end, outf);
7666               putc ('\n', outf);
7667             }
7668
7669           if (did_output)
7670             putc ('\n', outf);
7671         }
7672
7673       free (start);
7674       free (end);
7675       free (in_bb_p);
7676     }
7677
7678   if (current_function_epilogue_delay_list != 0)
7679     {
7680       fprintf (outf, "\n;; Insns in epilogue delay list:\n\n");
7681       for (tmp_rtx = current_function_epilogue_delay_list; tmp_rtx != 0;
7682            tmp_rtx = XEXP (tmp_rtx, 1))
7683         print_rtl_single (outf, XEXP (tmp_rtx, 0));
7684     }
7685 }
7686
7687 /* Dump the rtl into the current debugging dump file, then abort.  */
7688
7689 static void
7690 print_rtl_and_abort_fcn (file, line, function)
7691      const char *file;
7692      int line;
7693      const char *function;
7694 {
7695   if (rtl_dump_file)
7696     {
7697       print_rtl_with_bb (rtl_dump_file, get_insns ());
7698       fclose (rtl_dump_file);
7699     }
7700
7701   fancy_abort (file, line, function);
7702 }
7703
7704 /* Recompute register set/reference counts immediately prior to register
7705    allocation.
7706
7707    This avoids problems with set/reference counts changing to/from values
7708    which have special meanings to the register allocators.
7709
7710    Additionally, the reference counts are the primary component used by the
7711    register allocators to prioritize pseudos for allocation to hard regs.
7712    More accurate reference counts generally lead to better register allocation.
7713
7714    F is the first insn to be scanned.
7715
7716    LOOP_STEP denotes how much loop_depth should be incremented per
7717    loop nesting level in order to increase the ref count more for
7718    references in a loop.
7719
7720    It might be worthwhile to update REG_LIVE_LENGTH, REG_BASIC_BLOCK and
7721    possibly other information which is used by the register allocators.  */
7722
7723 void
7724 recompute_reg_usage (f, loop_step)
7725      rtx f ATTRIBUTE_UNUSED;
7726      int loop_step ATTRIBUTE_UNUSED;
7727 {
7728   allocate_reg_life_data ();
7729   update_life_info (NULL, UPDATE_LIFE_LOCAL, PROP_REG_INFO);
7730 }
7731
7732 /* Optionally removes all the REG_DEAD and REG_UNUSED notes from a set of
7733    blocks.  If BLOCKS is NULL, assume the universal set.  Returns a count
7734    of the number of registers that died.  */
7735
7736 int
7737 count_or_remove_death_notes (blocks, kill)
7738      sbitmap blocks;
7739      int kill;
7740 {
7741   int i, count = 0;
7742
7743   for (i = n_basic_blocks - 1; i >= 0; --i)
7744     {
7745       basic_block bb;
7746       rtx insn;
7747
7748       if (blocks && ! TEST_BIT (blocks, i))
7749         continue;
7750
7751       bb = BASIC_BLOCK (i);
7752
7753       for (insn = bb->head;; insn = NEXT_INSN (insn))
7754         {
7755           if (INSN_P (insn))
7756             {
7757               rtx *pprev = &REG_NOTES (insn);
7758               rtx link = *pprev;
7759
7760               while (link)
7761                 {
7762                   switch (REG_NOTE_KIND (link))
7763                     {
7764                     case REG_DEAD:
7765                       if (GET_CODE (XEXP (link, 0)) == REG)
7766                         {
7767                           rtx reg = XEXP (link, 0);
7768                           int n;
7769
7770                           if (REGNO (reg) >= FIRST_PSEUDO_REGISTER)
7771                             n = 1;
7772                           else
7773                             n = HARD_REGNO_NREGS (REGNO (reg), GET_MODE (reg));
7774                           count += n;
7775                         }
7776                       /* Fall through.  */
7777
7778                     case REG_UNUSED:
7779                       if (kill)
7780                         {
7781                           rtx next = XEXP (link, 1);
7782                           free_EXPR_LIST_node (link);
7783                           *pprev = link = next;
7784                           break;
7785                         }
7786                       /* Fall through.  */
7787
7788                     default:
7789                       pprev = &XEXP (link, 1);
7790                       link = *pprev;
7791                       break;
7792                     }
7793                 }
7794             }
7795
7796           if (insn == bb->end)
7797             break;
7798         }
7799     }
7800
7801   return count;
7802 }
7803
7804
7805 /* Update insns block within BB.  */
7806
7807 void
7808 update_bb_for_insn (bb)
7809      basic_block bb;
7810 {
7811   rtx insn;
7812
7813   if (! basic_block_for_insn)
7814     return;
7815
7816   for (insn = bb->head; ; insn = NEXT_INSN (insn))
7817     {
7818       set_block_for_insn (insn, bb);
7819
7820       if (insn == bb->end)
7821         break;
7822     }
7823 }
7824
7825
7826 /* Record INSN's block as BB.  */
7827
7828 void
7829 set_block_for_insn (insn, bb)
7830      rtx insn;
7831      basic_block bb;
7832 {
7833   size_t uid = INSN_UID (insn);
7834   if (uid >= basic_block_for_insn->num_elements)
7835     {
7836       int new_size;
7837
7838       /* Add one-eighth the size so we don't keep calling xrealloc.  */
7839       new_size = uid + (uid + 7) / 8;
7840
7841       VARRAY_GROW (basic_block_for_insn, new_size);
7842     }
7843   VARRAY_BB (basic_block_for_insn, uid) = bb;
7844 }
7845
7846 /* When a new insn has been inserted into an existing block, it will
7847    sometimes emit more than a single insn. This routine will set the
7848    block number for the specified insn, and look backwards in the insn
7849    chain to see if there are any other uninitialized insns immediately 
7850    previous to this one, and set the block number for them too.  */
7851
7852 void
7853 set_block_for_new_insns (insn, bb)
7854      rtx insn;
7855      basic_block bb;
7856 {
7857   set_block_for_insn (insn, bb);
7858
7859   /* Scan the previous instructions setting the block number until we find 
7860      an instruction that has the block number set, or we find a note 
7861      of any kind.  */
7862   for (insn = PREV_INSN (insn); insn != NULL_RTX; insn = PREV_INSN (insn))
7863     {
7864       if (GET_CODE (insn) == NOTE)
7865         break;
7866       if (INSN_UID (insn) >= basic_block_for_insn->num_elements 
7867           || BLOCK_FOR_INSN (insn) == 0)
7868         set_block_for_insn (insn, bb);
7869       else
7870         break;
7871     }
7872 }
7873 \f
7874 /* Verify the CFG consistency.  This function check some CFG invariants and
7875    aborts when something is wrong.  Hope that this function will help to
7876    convert many optimization passes to preserve CFG consistent.
7877
7878    Currently it does following checks:
7879
7880    - test head/end pointers
7881    - overlapping of basic blocks
7882    - edge list corectness
7883    - headers of basic blocks (the NOTE_INSN_BASIC_BLOCK note)
7884    - tails of basic blocks (ensure that boundary is necesary)
7885    - scans body of the basic block for JUMP_INSN, CODE_LABEL
7886      and NOTE_INSN_BASIC_BLOCK
7887    - check that all insns are in the basic blocks
7888    (except the switch handling code, barriers and notes)
7889    - check that all returns are followed by barriers
7890
7891    In future it can be extended check a lot of other stuff as well
7892    (reachability of basic blocks, life information, etc. etc.).  */
7893
7894 void
7895 verify_flow_info ()
7896 {
7897   const int max_uid = get_max_uid ();
7898   const rtx rtx_first = get_insns ();
7899   rtx last_head = get_last_insn ();
7900   basic_block *bb_info;
7901   rtx x;
7902   int i, last_bb_num_seen, num_bb_notes, err = 0;
7903
7904   bb_info = (basic_block *) xcalloc (max_uid, sizeof (basic_block));
7905
7906   for (i = n_basic_blocks - 1; i >= 0; i--)
7907     {
7908       basic_block bb = BASIC_BLOCK (i);
7909       rtx head = bb->head;
7910       rtx end = bb->end;
7911
7912       /* Verify the end of the basic block is in the INSN chain.  */
7913       for (x = last_head; x != NULL_RTX; x = PREV_INSN (x))
7914         if (x == end)
7915           break;
7916       if (!x)
7917         {
7918           error ("End insn %d for block %d not found in the insn stream.",
7919                  INSN_UID (end), bb->index);
7920           err = 1;
7921         }
7922
7923       /* Work backwards from the end to the head of the basic block
7924          to verify the head is in the RTL chain.  */
7925       for (; x != NULL_RTX; x = PREV_INSN (x))
7926         {
7927           /* While walking over the insn chain, verify insns appear
7928              in only one basic block and initialize the BB_INFO array
7929              used by other passes.  */
7930           if (bb_info[INSN_UID (x)] != NULL)
7931             {
7932               error ("Insn %d is in multiple basic blocks (%d and %d)",
7933                      INSN_UID (x), bb->index, bb_info[INSN_UID (x)]->index);
7934               err = 1;
7935             }
7936           bb_info[INSN_UID (x)] = bb;
7937
7938           if (x == head)
7939             break;
7940         }
7941       if (!x)
7942         {
7943           error ("Head insn %d for block %d not found in the insn stream.",
7944                  INSN_UID (head), bb->index);
7945           err = 1;
7946         }
7947
7948       last_head = x;
7949     }
7950
7951   /* Now check the basic blocks (boundaries etc.) */
7952   for (i = n_basic_blocks - 1; i >= 0; i--)
7953     {
7954       basic_block bb = BASIC_BLOCK (i);
7955       /* Check corectness of edge lists */
7956       edge e;
7957
7958       e = bb->succ;
7959       while (e)
7960         {
7961           if ((e->flags & EDGE_FALLTHRU)
7962               && e->src != ENTRY_BLOCK_PTR
7963               && e->dest != EXIT_BLOCK_PTR
7964               && (e->src->index + 1 != e->dest->index
7965                   || !can_fallthru (e->src, e->dest)))
7966             {
7967               error ("verify_flow_info: Incorrect fallthru edge %i->%i",
7968                      e->src->index, e->dest->index);
7969               err = 1;
7970             }
7971             
7972           if (e->src != bb)
7973             {
7974               error ("verify_flow_info: Basic block %d succ edge is corrupted",
7975                      bb->index);
7976               fprintf (stderr, "Predecessor: ");
7977               dump_edge_info (stderr, e, 0);
7978               fprintf (stderr, "\nSuccessor: ");
7979               dump_edge_info (stderr, e, 1);
7980               fprintf (stderr, "\n");
7981               err = 1;
7982             }
7983           if (e->dest != EXIT_BLOCK_PTR)
7984             {
7985               edge e2 = e->dest->pred;
7986               while (e2 && e2 != e)
7987                 e2 = e2->pred_next;
7988               if (!e2)
7989                 {
7990                   error ("Basic block %i edge lists are corrupted", bb->index);
7991                   err = 1;
7992                 }
7993             }
7994           e = e->succ_next;
7995         }
7996
7997       e = bb->pred;
7998       while (e)
7999         {
8000           if (e->dest != bb)
8001             {
8002               error ("Basic block %d pred edge is corrupted", bb->index);
8003               fputs ("Predecessor: ", stderr);
8004               dump_edge_info (stderr, e, 0);
8005               fputs ("\nSuccessor: ", stderr);
8006               dump_edge_info (stderr, e, 1);
8007               fputc ('\n', stderr);
8008               err = 1;
8009             }
8010           if (e->src != ENTRY_BLOCK_PTR)
8011             {
8012               edge e2 = e->src->succ;
8013               while (e2 && e2 != e)
8014                 e2 = e2->succ_next;
8015               if (!e2)
8016                 {
8017                   error ("Basic block %i edge lists are corrupted", bb->index);
8018                   err = 1;
8019                 }
8020             }
8021           e = e->pred_next;
8022         }
8023
8024       /* OK pointers are correct.  Now check the header of basic
8025          block.  It ought to contain optional CODE_LABEL followed
8026          by NOTE_BASIC_BLOCK.  */
8027       x = bb->head;
8028       if (GET_CODE (x) == CODE_LABEL)
8029         {
8030           if (bb->end == x)
8031             {
8032               error ("NOTE_INSN_BASIC_BLOCK is missing for block %d",
8033                      bb->index);
8034               err = 1;
8035             }
8036           x = NEXT_INSN (x);
8037         }
8038       if (!NOTE_INSN_BASIC_BLOCK_P (x) || NOTE_BASIC_BLOCK (x) != bb)
8039         {
8040           error ("NOTE_INSN_BASIC_BLOCK is missing for block %d\n",
8041                  bb->index);
8042           err = 1;
8043         }
8044
8045       if (bb->end == x)
8046         {
8047           /* Do checks for empty blocks here */
8048         }
8049       else
8050         {
8051           x = NEXT_INSN (x);
8052           while (x)
8053             {
8054               if (NOTE_INSN_BASIC_BLOCK_P (x))
8055                 {
8056                   error ("NOTE_INSN_BASIC_BLOCK %d in the middle of basic block %d",
8057                          INSN_UID (x), bb->index);
8058                   err = 1;
8059                 }
8060
8061               if (x == bb->end)
8062                 break;
8063
8064               if (GET_CODE (x) == JUMP_INSN
8065                   || GET_CODE (x) == CODE_LABEL
8066                   || GET_CODE (x) == BARRIER)
8067                 {
8068                   error ("In basic block %d:", bb->index);
8069                   fatal_insn ("Flow control insn inside a basic block", x);
8070                 }
8071
8072               x = NEXT_INSN (x);
8073             }
8074         }
8075     }
8076
8077   last_bb_num_seen = -1;
8078   num_bb_notes = 0;
8079   x = rtx_first;
8080   while (x)
8081     {
8082       if (NOTE_INSN_BASIC_BLOCK_P (x))
8083         {
8084           basic_block bb = NOTE_BASIC_BLOCK (x);
8085           num_bb_notes++;
8086           if (bb->index != last_bb_num_seen + 1)
8087             /* Basic blocks not numbered consecutively.  */
8088             abort ();
8089                
8090           last_bb_num_seen = bb->index;
8091         }
8092
8093       if (!bb_info[INSN_UID (x)])
8094         {
8095           switch (GET_CODE (x))
8096             {
8097             case BARRIER:
8098             case NOTE:
8099               break;
8100
8101             case CODE_LABEL:
8102               /* An addr_vec is placed outside any block block.  */
8103               if (NEXT_INSN (x)
8104                   && GET_CODE (NEXT_INSN (x)) == JUMP_INSN
8105                   && (GET_CODE (PATTERN (NEXT_INSN (x))) == ADDR_DIFF_VEC
8106                       || GET_CODE (PATTERN (NEXT_INSN (x))) == ADDR_VEC))
8107                 {
8108                   x = NEXT_INSN (x);
8109                 }
8110
8111               /* But in any case, non-deletable labels can appear anywhere.  */
8112               break;
8113
8114             default:
8115               fatal_insn ("Insn outside basic block", x);
8116             }
8117         }
8118
8119       if (INSN_P (x)
8120           && GET_CODE (x) == JUMP_INSN
8121           && returnjump_p (x) && ! condjump_p (x)
8122           && ! (NEXT_INSN (x) && GET_CODE (NEXT_INSN (x)) == BARRIER))
8123             fatal_insn ("Return not followed by barrier", x);
8124
8125       x = NEXT_INSN (x);
8126     }
8127
8128   if (num_bb_notes != n_basic_blocks)
8129     internal_error
8130       ("number of bb notes in insn chain (%d) != n_basic_blocks (%d)",
8131        num_bb_notes, n_basic_blocks);
8132
8133   if (err)
8134     abort ();
8135
8136   /* Clean up.  */
8137   free (bb_info);
8138 }
8139 \f
8140 /* Functions to access an edge list with a vector representation.
8141    Enough data is kept such that given an index number, the
8142    pred and succ that edge represents can be determined, or
8143    given a pred and a succ, its index number can be returned.
8144    This allows algorithms which consume a lot of memory to
8145    represent the normally full matrix of edge (pred,succ) with a
8146    single indexed vector,  edge (EDGE_INDEX (pred, succ)), with no
8147    wasted space in the client code due to sparse flow graphs.  */
8148
8149 /* This functions initializes the edge list. Basically the entire
8150    flowgraph is processed, and all edges are assigned a number,
8151    and the data structure is filled in.  */
8152
8153 struct edge_list *
8154 create_edge_list ()
8155 {
8156   struct edge_list *elist;
8157   edge e;
8158   int num_edges;
8159   int x;
8160   int block_count;
8161
8162   block_count = n_basic_blocks + 2;   /* Include the entry and exit blocks.  */
8163
8164   num_edges = 0;
8165
8166   /* Determine the number of edges in the flow graph by counting successor
8167      edges on each basic block.  */
8168   for (x = 0; x < n_basic_blocks; x++)
8169     {
8170       basic_block bb = BASIC_BLOCK (x);
8171
8172       for (e = bb->succ; e; e = e->succ_next)
8173         num_edges++;
8174     }
8175   /* Don't forget successors of the entry block.  */
8176   for (e = ENTRY_BLOCK_PTR->succ; e; e = e->succ_next)
8177     num_edges++;
8178
8179   elist = (struct edge_list *) xmalloc (sizeof (struct edge_list));
8180   elist->num_blocks = block_count;
8181   elist->num_edges = num_edges;
8182   elist->index_to_edge = (edge *) xmalloc (sizeof (edge) * num_edges);
8183
8184   num_edges = 0;
8185
8186   /* Follow successors of the entry block, and register these edges.  */
8187   for (e = ENTRY_BLOCK_PTR->succ; e; e = e->succ_next)
8188     {
8189       elist->index_to_edge[num_edges] = e;
8190       num_edges++;
8191     }
8192
8193   for (x = 0; x < n_basic_blocks; x++)
8194     {
8195       basic_block bb = BASIC_BLOCK (x);
8196
8197       /* Follow all successors of blocks, and register these edges.  */
8198       for (e = bb->succ; e; e = e->succ_next)
8199         {
8200           elist->index_to_edge[num_edges] = e;
8201           num_edges++;
8202         }
8203     }
8204   return elist;
8205 }
8206
8207 /* This function free's memory associated with an edge list.  */
8208
8209 void
8210 free_edge_list (elist)
8211      struct edge_list *elist;
8212 {
8213   if (elist)
8214     {
8215       free (elist->index_to_edge);
8216       free (elist);
8217     }
8218 }
8219
8220 /* This function provides debug output showing an edge list.  */
8221
8222 void
8223 print_edge_list (f, elist)
8224      FILE *f;
8225      struct edge_list *elist;
8226 {
8227   int x;
8228   fprintf (f, "Compressed edge list, %d BBs + entry & exit, and %d edges\n",
8229            elist->num_blocks - 2, elist->num_edges);
8230
8231   for (x = 0; x < elist->num_edges; x++)
8232     {
8233       fprintf (f, " %-4d - edge(", x);
8234       if (INDEX_EDGE_PRED_BB (elist, x) == ENTRY_BLOCK_PTR)
8235         fprintf (f, "entry,");
8236       else
8237         fprintf (f, "%d,", INDEX_EDGE_PRED_BB (elist, x)->index);
8238
8239       if (INDEX_EDGE_SUCC_BB (elist, x) == EXIT_BLOCK_PTR)
8240         fprintf (f, "exit)\n");
8241       else
8242         fprintf (f, "%d)\n", INDEX_EDGE_SUCC_BB (elist, x)->index);
8243     }
8244 }
8245
8246 /* This function provides an internal consistency check of an edge list,
8247    verifying that all edges are present, and that there are no
8248    extra edges.  */
8249
8250 void
8251 verify_edge_list (f, elist)
8252      FILE *f;
8253      struct edge_list *elist;
8254 {
8255   int x, pred, succ, index;
8256   edge e;
8257
8258   for (x = 0; x < n_basic_blocks; x++)
8259     {
8260       basic_block bb = BASIC_BLOCK (x);
8261
8262       for (e = bb->succ; e; e = e->succ_next)
8263         {
8264           pred = e->src->index;
8265           succ = e->dest->index;
8266           index = EDGE_INDEX (elist, e->src, e->dest);
8267           if (index == EDGE_INDEX_NO_EDGE)
8268             {
8269               fprintf (f, "*p* No index for edge from %d to %d\n", pred, succ);
8270               continue;
8271             }
8272           if (INDEX_EDGE_PRED_BB (elist, index)->index != pred)
8273             fprintf (f, "*p* Pred for index %d should be %d not %d\n",
8274                      index, pred, INDEX_EDGE_PRED_BB (elist, index)->index);
8275           if (INDEX_EDGE_SUCC_BB (elist, index)->index != succ)
8276             fprintf (f, "*p* Succ for index %d should be %d not %d\n",
8277                      index, succ, INDEX_EDGE_SUCC_BB (elist, index)->index);
8278         }
8279     }
8280   for (e = ENTRY_BLOCK_PTR->succ; e; e = e->succ_next)
8281     {
8282       pred = e->src->index;
8283       succ = e->dest->index;
8284       index = EDGE_INDEX (elist, e->src, e->dest);
8285       if (index == EDGE_INDEX_NO_EDGE)
8286         {
8287           fprintf (f, "*p* No index for edge from %d to %d\n", pred, succ);
8288           continue;
8289         }
8290       if (INDEX_EDGE_PRED_BB (elist, index)->index != pred)
8291         fprintf (f, "*p* Pred for index %d should be %d not %d\n",
8292                  index, pred, INDEX_EDGE_PRED_BB (elist, index)->index);
8293       if (INDEX_EDGE_SUCC_BB (elist, index)->index != succ)
8294         fprintf (f, "*p* Succ for index %d should be %d not %d\n",
8295                  index, succ, INDEX_EDGE_SUCC_BB (elist, index)->index);
8296     }
8297   /* We've verified that all the edges are in the list, no lets make sure
8298      there are no spurious edges in the list.  */
8299
8300   for (pred = 0; pred < n_basic_blocks; pred++)
8301     for (succ = 0; succ < n_basic_blocks; succ++)
8302       {
8303         basic_block p = BASIC_BLOCK (pred);
8304         basic_block s = BASIC_BLOCK (succ);
8305
8306         int found_edge = 0;
8307
8308         for (e = p->succ; e; e = e->succ_next)
8309           if (e->dest == s)
8310             {
8311               found_edge = 1;
8312               break;
8313             }
8314         for (e = s->pred; e; e = e->pred_next)
8315           if (e->src == p)
8316             {
8317               found_edge = 1;
8318               break;
8319             }
8320         if (EDGE_INDEX (elist, BASIC_BLOCK (pred), BASIC_BLOCK (succ))
8321             == EDGE_INDEX_NO_EDGE && found_edge != 0)
8322           fprintf (f, "*** Edge (%d, %d) appears to not have an index\n",
8323                    pred, succ);
8324         if (EDGE_INDEX (elist, BASIC_BLOCK (pred), BASIC_BLOCK (succ))
8325             != EDGE_INDEX_NO_EDGE && found_edge == 0)
8326           fprintf (f, "*** Edge (%d, %d) has index %d, but there is no edge\n",
8327                    pred, succ, EDGE_INDEX (elist, BASIC_BLOCK (pred),
8328                                            BASIC_BLOCK (succ)));
8329       }
8330   for (succ = 0; succ < n_basic_blocks; succ++)
8331     {
8332       basic_block p = ENTRY_BLOCK_PTR;
8333       basic_block s = BASIC_BLOCK (succ);
8334
8335       int found_edge = 0;
8336
8337       for (e = p->succ; e; e = e->succ_next)
8338         if (e->dest == s)
8339           {
8340             found_edge = 1;
8341             break;
8342           }
8343       for (e = s->pred; e; e = e->pred_next)
8344         if (e->src == p)
8345           {
8346             found_edge = 1;
8347             break;
8348           }
8349       if (EDGE_INDEX (elist, ENTRY_BLOCK_PTR, BASIC_BLOCK (succ))
8350           == EDGE_INDEX_NO_EDGE && found_edge != 0)
8351         fprintf (f, "*** Edge (entry, %d) appears to not have an index\n",
8352                  succ);
8353       if (EDGE_INDEX (elist, ENTRY_BLOCK_PTR, BASIC_BLOCK (succ))
8354           != EDGE_INDEX_NO_EDGE && found_edge == 0)
8355         fprintf (f, "*** Edge (entry, %d) has index %d, but no edge exists\n",
8356                  succ, EDGE_INDEX (elist, ENTRY_BLOCK_PTR,
8357                                    BASIC_BLOCK (succ)));
8358     }
8359   for (pred = 0; pred < n_basic_blocks; pred++)
8360     {
8361       basic_block p = BASIC_BLOCK (pred);
8362       basic_block s = EXIT_BLOCK_PTR;
8363
8364       int found_edge = 0;
8365
8366       for (e = p->succ; e; e = e->succ_next)
8367         if (e->dest == s)
8368           {
8369             found_edge = 1;
8370             break;
8371           }
8372       for (e = s->pred; e; e = e->pred_next)
8373         if (e->src == p)
8374           {
8375             found_edge = 1;
8376             break;
8377           }
8378       if (EDGE_INDEX (elist, BASIC_BLOCK (pred), EXIT_BLOCK_PTR)
8379           == EDGE_INDEX_NO_EDGE && found_edge != 0)
8380         fprintf (f, "*** Edge (%d, exit) appears to not have an index\n",
8381                  pred);
8382       if (EDGE_INDEX (elist, BASIC_BLOCK (pred), EXIT_BLOCK_PTR)
8383           != EDGE_INDEX_NO_EDGE && found_edge == 0)
8384         fprintf (f, "*** Edge (%d, exit) has index %d, but no edge exists\n",
8385                  pred, EDGE_INDEX (elist, BASIC_BLOCK (pred),
8386                                    EXIT_BLOCK_PTR));
8387     }
8388 }
8389
8390 /* This routine will determine what, if any, edge there is between
8391    a specified predecessor and successor.  */
8392
8393 int
8394 find_edge_index (edge_list, pred, succ)
8395      struct edge_list *edge_list;
8396      basic_block pred, succ;
8397 {
8398   int x;
8399   for (x = 0; x < NUM_EDGES (edge_list); x++)
8400     {
8401       if (INDEX_EDGE_PRED_BB (edge_list, x) == pred
8402           && INDEX_EDGE_SUCC_BB (edge_list, x) == succ)
8403         return x;
8404     }
8405   return (EDGE_INDEX_NO_EDGE);
8406 }
8407
8408 /* This function will remove an edge from the flow graph.  */
8409
8410 void
8411 remove_edge (e)
8412      edge e;
8413 {
8414   edge last_pred = NULL;
8415   edge last_succ = NULL;
8416   edge tmp;
8417   basic_block src, dest;
8418   src = e->src;
8419   dest = e->dest;
8420   for (tmp = src->succ; tmp && tmp != e; tmp = tmp->succ_next)
8421     last_succ = tmp;
8422
8423   if (!tmp)
8424     abort ();
8425   if (last_succ)
8426     last_succ->succ_next = e->succ_next;
8427   else
8428     src->succ = e->succ_next;
8429
8430   for (tmp = dest->pred; tmp && tmp != e; tmp = tmp->pred_next)
8431     last_pred = tmp;
8432
8433   if (!tmp)
8434     abort ();
8435   if (last_pred)
8436     last_pred->pred_next = e->pred_next;
8437   else
8438     dest->pred = e->pred_next;
8439
8440   n_edges--;
8441   free (e);
8442 }
8443
8444 /* This routine will remove any fake successor edges for a basic block.
8445    When the edge is removed, it is also removed from whatever predecessor
8446    list it is in.  */
8447
8448 static void
8449 remove_fake_successors (bb)
8450      basic_block bb;
8451 {
8452   edge e;
8453   for (e = bb->succ; e;)
8454     {
8455       edge tmp = e;
8456       e = e->succ_next;
8457       if ((tmp->flags & EDGE_FAKE) == EDGE_FAKE)
8458         remove_edge (tmp);
8459     }
8460 }
8461
8462 /* This routine will remove all fake edges from the flow graph.  If
8463    we remove all fake successors, it will automatically remove all
8464    fake predecessors.  */
8465
8466 void
8467 remove_fake_edges ()
8468 {
8469   int x;
8470
8471   for (x = 0; x < n_basic_blocks; x++)
8472     remove_fake_successors (BASIC_BLOCK (x));
8473
8474   /* We've handled all successors except the entry block's.  */
8475   remove_fake_successors (ENTRY_BLOCK_PTR);
8476 }
8477
8478 /* This function will add a fake edge between any block which has no
8479    successors, and the exit block. Some data flow equations require these
8480    edges to exist.  */
8481
8482 void
8483 add_noreturn_fake_exit_edges ()
8484 {
8485   int x;
8486
8487   for (x = 0; x < n_basic_blocks; x++)
8488     if (BASIC_BLOCK (x)->succ == NULL)
8489       make_edge (NULL, BASIC_BLOCK (x), EXIT_BLOCK_PTR, EDGE_FAKE);
8490 }
8491
8492 /* This function adds a fake edge between any infinite loops to the
8493    exit block.  Some optimizations require a path from each node to
8494    the exit node.
8495
8496    See also Morgan, Figure 3.10, pp. 82-83.
8497
8498    The current implementation is ugly, not attempting to minimize the
8499    number of inserted fake edges.  To reduce the number of fake edges
8500    to insert, add fake edges from _innermost_ loops containing only
8501    nodes not reachable from the exit block.  */
8502
8503 void
8504 connect_infinite_loops_to_exit ()
8505 {
8506   basic_block unvisited_block;
8507
8508   /* Perform depth-first search in the reverse graph to find nodes
8509      reachable from the exit block.  */
8510   struct depth_first_search_dsS dfs_ds;
8511
8512   flow_dfs_compute_reverse_init (&dfs_ds);
8513   flow_dfs_compute_reverse_add_bb (&dfs_ds, EXIT_BLOCK_PTR);
8514
8515   /* Repeatedly add fake edges, updating the unreachable nodes.  */
8516   while (1)
8517     {
8518       unvisited_block = flow_dfs_compute_reverse_execute (&dfs_ds);
8519       if (!unvisited_block)
8520         break;
8521       make_edge (NULL, unvisited_block, EXIT_BLOCK_PTR, EDGE_FAKE);
8522       flow_dfs_compute_reverse_add_bb (&dfs_ds, unvisited_block);
8523     }
8524
8525   flow_dfs_compute_reverse_finish (&dfs_ds);
8526
8527   return;
8528 }
8529
8530 /* Redirect an edge's successor from one block to another.  */
8531
8532 void
8533 redirect_edge_succ (e, new_succ)
8534      edge e;
8535      basic_block new_succ;
8536 {
8537   edge *pe;
8538
8539   /* Disconnect the edge from the old successor block.  */
8540   for (pe = &e->dest->pred; *pe != e; pe = &(*pe)->pred_next)
8541     continue;
8542   *pe = (*pe)->pred_next;
8543
8544   /* Reconnect the edge to the new successor block.  */
8545   e->pred_next = new_succ->pred;
8546   new_succ->pred = e;
8547   e->dest = new_succ;
8548 }
8549
8550 /* Redirect an edge's predecessor from one block to another.  */
8551
8552 void
8553 redirect_edge_pred (e, new_pred)
8554      edge e;
8555      basic_block new_pred;
8556 {
8557   edge *pe;
8558
8559   /* Disconnect the edge from the old predecessor block.  */
8560   for (pe = &e->src->succ; *pe != e; pe = &(*pe)->succ_next)
8561     continue;
8562   *pe = (*pe)->succ_next;
8563
8564   /* Reconnect the edge to the new predecessor block.  */
8565   e->succ_next = new_pred->succ;
8566   new_pred->succ = e;
8567   e->src = new_pred;
8568 }
8569 \f
8570 /* Dump the list of basic blocks in the bitmap NODES.  */
8571
8572 static void
8573 flow_nodes_print (str, nodes, file)
8574      const char *str;
8575      const sbitmap nodes;
8576      FILE *file;
8577 {
8578   int node;
8579
8580   if (! nodes)
8581     return;
8582
8583   fprintf (file, "%s { ", str);
8584   EXECUTE_IF_SET_IN_SBITMAP (nodes, 0, node, {fprintf (file, "%d ", node);});
8585   fputs ("}\n", file);
8586 }
8587
8588
8589 /* Dump the list of edges in the array EDGE_LIST.  */
8590
8591 static void
8592 flow_edge_list_print (str, edge_list, num_edges, file)
8593      const char *str;
8594      const edge *edge_list;
8595      int num_edges;
8596      FILE *file;
8597 {
8598   int i;
8599
8600   if (! edge_list)
8601     return;
8602
8603   fprintf (file, "%s { ", str);
8604   for (i = 0; i < num_edges; i++)
8605     fprintf (file, "%d->%d ", edge_list[i]->src->index,
8606              edge_list[i]->dest->index);
8607   fputs ("}\n", file);
8608 }
8609
8610
8611 /* Dump loop related CFG information.  */
8612
8613 static void
8614 flow_loops_cfg_dump (loops, file)
8615      const struct loops *loops;
8616      FILE *file;
8617 {
8618   int i;
8619
8620   if (! loops->num || ! file || ! loops->cfg.dom)
8621     return;
8622
8623   for (i = 0; i < n_basic_blocks; i++)
8624     {
8625       edge succ;
8626
8627       fprintf (file, ";; %d succs { ", i);
8628       for (succ = BASIC_BLOCK (i)->succ; succ; succ = succ->succ_next)
8629         fprintf (file, "%d ", succ->dest->index);
8630       flow_nodes_print ("} dom", loops->cfg.dom[i], file);
8631     }
8632
8633   /* Dump the DFS node order.  */
8634   if (loops->cfg.dfs_order)
8635     {
8636       fputs (";; DFS order: ", file);
8637       for (i = 0; i < n_basic_blocks; i++)
8638         fprintf (file, "%d ", loops->cfg.dfs_order[i]);
8639       fputs ("\n", file);
8640     }
8641   /* Dump the reverse completion node order.  */
8642   if (loops->cfg.rc_order)
8643     {
8644       fputs (";; RC order: ", file);
8645       for (i = 0; i < n_basic_blocks; i++)
8646         fprintf (file, "%d ", loops->cfg.rc_order[i]);
8647       fputs ("\n", file);
8648     }
8649 }
8650
8651 /* Return non-zero if the nodes of LOOP are a subset of OUTER.  */
8652
8653 static int
8654 flow_loop_nested_p (outer, loop)
8655      struct loop *outer;
8656      struct loop *loop;
8657 {
8658   return sbitmap_a_subset_b_p (loop->nodes, outer->nodes);
8659 }
8660
8661
8662 /* Dump the loop information specified by LOOP to the stream FILE
8663    using auxiliary dump callback function LOOP_DUMP_AUX if non null.  */
8664 void
8665 flow_loop_dump (loop, file, loop_dump_aux, verbose)
8666      const struct loop *loop;
8667      FILE *file;
8668      void (*loop_dump_aux) PARAMS((const struct loop *, FILE *, int));
8669      int verbose;
8670 {
8671   if (! loop || ! loop->header)
8672     return;
8673
8674   fprintf (file, ";;\n;; Loop %d (%d to %d):%s%s\n",
8675            loop->num, INSN_UID (loop->first->head),
8676            INSN_UID (loop->last->end),
8677            loop->shared ? " shared" : "",
8678            loop->invalid ? " invalid" : "");
8679   fprintf (file, ";;  header %d, latch %d, pre-header %d, first %d, last %d\n",
8680            loop->header->index, loop->latch->index,
8681            loop->pre_header ? loop->pre_header->index : -1,
8682            loop->first->index, loop->last->index);
8683   fprintf (file, ";;  depth %d, level %d, outer %ld\n",
8684            loop->depth, loop->level,
8685            (long) (loop->outer ? loop->outer->num : -1));
8686
8687   if (loop->pre_header_edges)
8688     flow_edge_list_print (";;  pre-header edges", loop->pre_header_edges,
8689                           loop->num_pre_header_edges, file);
8690   flow_edge_list_print (";;  entry edges", loop->entry_edges,
8691                         loop->num_entries, file);
8692   fprintf (file, ";;  %d", loop->num_nodes);
8693   flow_nodes_print (" nodes", loop->nodes, file);
8694   flow_edge_list_print (";;  exit edges", loop->exit_edges,
8695                         loop->num_exits, file);
8696   if (loop->exits_doms)
8697     flow_nodes_print (";;  exit doms", loop->exits_doms, file);
8698   if (loop_dump_aux)
8699     loop_dump_aux (loop, file, verbose);
8700 }
8701
8702
8703 /* Dump the loop information specified by LOOPS to the stream FILE,
8704    using auxiliary dump callback function LOOP_DUMP_AUX if non null.  */
8705 void
8706 flow_loops_dump (loops, file, loop_dump_aux, verbose)
8707      const struct loops *loops;
8708      FILE *file;
8709      void (*loop_dump_aux) PARAMS((const struct loop *, FILE *, int));
8710      int verbose;
8711 {
8712   int i;
8713   int num_loops;
8714
8715   num_loops = loops->num;
8716   if (! num_loops || ! file)
8717     return;
8718
8719   fprintf (file, ";; %d loops found, %d levels\n",
8720            num_loops, loops->levels);
8721
8722   for (i = 0; i < num_loops; i++)
8723     {
8724       struct loop *loop = &loops->array[i];
8725
8726       flow_loop_dump (loop, file, loop_dump_aux, verbose);
8727
8728       if (loop->shared)
8729         {
8730           int j;
8731
8732           for (j = 0; j < i; j++)
8733             {
8734               struct loop *oloop = &loops->array[j];
8735
8736               if (loop->header == oloop->header)
8737                 {
8738                   int disjoint;
8739                   int smaller;
8740
8741                   smaller = loop->num_nodes < oloop->num_nodes;
8742
8743                   /* If the union of LOOP and OLOOP is different than
8744                      the larger of LOOP and OLOOP then LOOP and OLOOP
8745                      must be disjoint.  */
8746                   disjoint = ! flow_loop_nested_p (smaller ? loop : oloop,
8747                                                    smaller ? oloop : loop);
8748                   fprintf (file,
8749                            ";; loop header %d shared by loops %d, %d %s\n",
8750                            loop->header->index, i, j,
8751                            disjoint ? "disjoint" : "nested");
8752                 }
8753             }
8754         }
8755     }
8756
8757   if (verbose)
8758     flow_loops_cfg_dump (loops, file);
8759 }
8760
8761
8762 /* Free all the memory allocated for LOOPS.  */
8763
8764 void
8765 flow_loops_free (loops)
8766      struct loops *loops;
8767 {
8768   if (loops->array)
8769     {
8770       int i;
8771
8772       if (! loops->num)
8773         abort ();
8774
8775       /* Free the loop descriptors.  */
8776       for (i = 0; i < loops->num; i++)
8777         {
8778           struct loop *loop = &loops->array[i];
8779
8780           if (loop->pre_header_edges)
8781             free (loop->pre_header_edges);
8782           if (loop->nodes)
8783             sbitmap_free (loop->nodes);
8784           if (loop->entry_edges)
8785             free (loop->entry_edges);
8786           if (loop->exit_edges)
8787             free (loop->exit_edges);
8788           if (loop->exits_doms)
8789             sbitmap_free (loop->exits_doms);
8790         }
8791       free (loops->array);
8792       loops->array = NULL;
8793
8794       if (loops->cfg.dom)
8795         sbitmap_vector_free (loops->cfg.dom);
8796       if (loops->cfg.dfs_order)
8797         free (loops->cfg.dfs_order);
8798
8799       if (loops->shared_headers)
8800         sbitmap_free (loops->shared_headers);
8801     }
8802 }
8803
8804
8805 /* Find the entry edges into the loop with header HEADER and nodes
8806    NODES and store in ENTRY_EDGES array.  Return the number of entry
8807    edges from the loop.  */
8808
8809 static int
8810 flow_loop_entry_edges_find (header, nodes, entry_edges)
8811      basic_block header;
8812      const sbitmap nodes;
8813      edge **entry_edges;
8814 {
8815   edge e;
8816   int num_entries;
8817
8818   *entry_edges = NULL;
8819
8820   num_entries = 0;
8821   for (e = header->pred; e; e = e->pred_next)
8822     {
8823       basic_block src = e->src;
8824
8825       if (src == ENTRY_BLOCK_PTR || ! TEST_BIT (nodes, src->index))
8826         num_entries++;
8827     }
8828
8829   if (! num_entries)
8830     abort ();
8831
8832   *entry_edges = (edge *) xmalloc (num_entries * sizeof (edge *));
8833
8834   num_entries = 0;
8835   for (e = header->pred; e; e = e->pred_next)
8836     {
8837       basic_block src = e->src;
8838
8839       if (src == ENTRY_BLOCK_PTR || ! TEST_BIT (nodes, src->index))
8840         (*entry_edges)[num_entries++] = e;
8841     }
8842
8843   return num_entries;
8844 }
8845
8846
8847 /* Find the exit edges from the loop using the bitmap of loop nodes
8848    NODES and store in EXIT_EDGES array.  Return the number of
8849    exit edges from the loop.  */
8850
8851 static int
8852 flow_loop_exit_edges_find (nodes, exit_edges)
8853      const sbitmap nodes;
8854      edge **exit_edges;
8855 {
8856   edge e;
8857   int node;
8858   int num_exits;
8859
8860   *exit_edges = NULL;
8861
8862   /* Check all nodes within the loop to see if there are any
8863      successors not in the loop.  Note that a node may have multiple
8864      exiting edges ?????  A node can have one jumping edge and one fallthru
8865      edge so only one of these can exit the loop.  */
8866   num_exits = 0;
8867   EXECUTE_IF_SET_IN_SBITMAP (nodes, 0, node, {
8868     for (e = BASIC_BLOCK (node)->succ; e; e = e->succ_next)
8869       {
8870         basic_block dest = e->dest;
8871
8872         if (dest == EXIT_BLOCK_PTR || ! TEST_BIT (nodes, dest->index))
8873             num_exits++;
8874       }
8875   });
8876
8877   if (! num_exits)
8878     return 0;
8879
8880   *exit_edges = (edge *) xmalloc (num_exits * sizeof (edge *));
8881
8882   /* Store all exiting edges into an array.  */
8883   num_exits = 0;
8884   EXECUTE_IF_SET_IN_SBITMAP (nodes, 0, node, {
8885     for (e = BASIC_BLOCK (node)->succ; e; e = e->succ_next)
8886       {
8887         basic_block dest = e->dest;
8888
8889         if (dest == EXIT_BLOCK_PTR || ! TEST_BIT (nodes, dest->index))
8890           (*exit_edges)[num_exits++] = e;
8891       }
8892   });
8893
8894   return num_exits;
8895 }
8896
8897
8898 /* Find the nodes contained within the loop with header HEADER and
8899    latch LATCH and store in NODES.  Return the number of nodes within
8900    the loop.  */
8901
8902 static int
8903 flow_loop_nodes_find (header, latch, nodes)
8904      basic_block header;
8905      basic_block latch;
8906      sbitmap nodes;
8907 {
8908   basic_block *stack;
8909   int sp;
8910   int num_nodes = 0;
8911
8912   stack = (basic_block *) xmalloc (n_basic_blocks * sizeof (basic_block));
8913   sp = 0;
8914
8915   /* Start with only the loop header in the set of loop nodes.  */
8916   sbitmap_zero (nodes);
8917   SET_BIT (nodes, header->index);
8918   num_nodes++;
8919   header->loop_depth++;
8920
8921   /* Push the loop latch on to the stack.  */
8922   if (! TEST_BIT (nodes, latch->index))
8923     {
8924       SET_BIT (nodes, latch->index);
8925       latch->loop_depth++;
8926       num_nodes++;
8927       stack[sp++] = latch;
8928     }
8929
8930   while (sp)
8931     {
8932       basic_block node;
8933       edge e;
8934
8935       node = stack[--sp];
8936       for (e = node->pred; e; e = e->pred_next)
8937         {
8938           basic_block ancestor = e->src;
8939
8940           /* If each ancestor not marked as part of loop, add to set of
8941              loop nodes and push on to stack.  */
8942           if (ancestor != ENTRY_BLOCK_PTR
8943               && ! TEST_BIT (nodes, ancestor->index))
8944             {
8945               SET_BIT (nodes, ancestor->index);
8946               ancestor->loop_depth++;
8947               num_nodes++;
8948               stack[sp++] = ancestor;
8949             }
8950         }
8951     }
8952   free (stack);
8953   return num_nodes;
8954 }
8955
8956 /* Compute the depth first search order and store in the array
8957   DFS_ORDER if non-zero, marking the nodes visited in VISITED.  If
8958   RC_ORDER is non-zero, return the reverse completion number for each
8959   node.  Returns the number of nodes visited.  A depth first search
8960   tries to get as far away from the starting point as quickly as
8961   possible.  */
8962
8963 int
8964 flow_depth_first_order_compute (dfs_order, rc_order)
8965      int *dfs_order;
8966      int *rc_order;
8967 {
8968   edge *stack;
8969   int sp;
8970   int dfsnum = 0;
8971   int rcnum = n_basic_blocks - 1;
8972   sbitmap visited;
8973
8974   /* Allocate stack for back-tracking up CFG.  */
8975   stack = (edge *) xmalloc ((n_basic_blocks + 1) * sizeof (edge));
8976   sp = 0;
8977
8978   /* Allocate bitmap to track nodes that have been visited.  */
8979   visited = sbitmap_alloc (n_basic_blocks);
8980
8981   /* None of the nodes in the CFG have been visited yet.  */
8982   sbitmap_zero (visited);
8983
8984   /* Push the first edge on to the stack.  */
8985   stack[sp++] = ENTRY_BLOCK_PTR->succ;
8986
8987   while (sp)
8988     {
8989       edge e;
8990       basic_block src;
8991       basic_block dest;
8992
8993       /* Look at the edge on the top of the stack.  */
8994       e = stack[sp - 1];
8995       src = e->src;
8996       dest = e->dest;
8997
8998       /* Check if the edge destination has been visited yet.  */
8999       if (dest != EXIT_BLOCK_PTR && ! TEST_BIT (visited, dest->index))
9000         {
9001           /* Mark that we have visited the destination.  */
9002           SET_BIT (visited, dest->index);
9003
9004           if (dfs_order)
9005             dfs_order[dfsnum++] = dest->index;
9006
9007           if (dest->succ)
9008             {
9009               /* Since the DEST node has been visited for the first
9010                  time, check its successors.  */
9011               stack[sp++] = dest->succ;
9012             }
9013           else
9014             {
9015               /* There are no successors for the DEST node so assign
9016                  its reverse completion number.  */
9017               if (rc_order)
9018                 rc_order[rcnum--] = dest->index;
9019             }
9020         }
9021       else
9022         {
9023           if (! e->succ_next && src != ENTRY_BLOCK_PTR)
9024             {
9025               /* There are no more successors for the SRC node
9026                  so assign its reverse completion number.  */
9027               if (rc_order)
9028                 rc_order[rcnum--] = src->index;
9029             }
9030
9031           if (e->succ_next)
9032             stack[sp - 1] = e->succ_next;
9033           else
9034             sp--;
9035         }
9036     }
9037
9038   free (stack);
9039   sbitmap_free (visited);
9040
9041   /* The number of nodes visited should not be greater than
9042      n_basic_blocks.  */
9043   if (dfsnum > n_basic_blocks)
9044     abort ();
9045
9046   /* There are some nodes left in the CFG that are unreachable.  */
9047   if (dfsnum < n_basic_blocks)
9048     abort ();
9049   return dfsnum;
9050 }
9051
9052 /* Compute the depth first search order on the _reverse_ graph and
9053    store in the array DFS_ORDER, marking the nodes visited in VISITED.
9054    Returns the number of nodes visited.
9055
9056    The computation is split into three pieces:
9057
9058    flow_dfs_compute_reverse_init () creates the necessary data
9059    structures.
9060
9061    flow_dfs_compute_reverse_add_bb () adds a basic block to the data
9062    structures.  The block will start the search.
9063
9064    flow_dfs_compute_reverse_execute () continues (or starts) the
9065    search using the block on the top of the stack, stopping when the
9066    stack is empty.
9067
9068    flow_dfs_compute_reverse_finish () destroys the necessary data
9069    structures.
9070
9071    Thus, the user will probably call ..._init(), call ..._add_bb() to
9072    add a beginning basic block to the stack, call ..._execute(),
9073    possibly add another bb to the stack and again call ..._execute(),
9074    ..., and finally call _finish().  */
9075
9076 /* Initialize the data structures used for depth-first search on the
9077    reverse graph.  If INITIALIZE_STACK is nonzero, the exit block is
9078    added to the basic block stack.  DATA is the current depth-first
9079    search context.  If INITIALIZE_STACK is non-zero, there is an
9080    element on the stack.  */
9081
9082 static void
9083 flow_dfs_compute_reverse_init (data)
9084      depth_first_search_ds data;
9085 {
9086   /* Allocate stack for back-tracking up CFG.  */
9087   data->stack =
9088     (basic_block *) xmalloc ((n_basic_blocks - (INVALID_BLOCK + 1))
9089                              * sizeof (basic_block));
9090   data->sp = 0;
9091
9092   /* Allocate bitmap to track nodes that have been visited.  */
9093   data->visited_blocks = sbitmap_alloc (n_basic_blocks - (INVALID_BLOCK + 1));
9094
9095   /* None of the nodes in the CFG have been visited yet.  */
9096   sbitmap_zero (data->visited_blocks);
9097
9098   return;
9099 }
9100
9101 /* Add the specified basic block to the top of the dfs data
9102    structures.  When the search continues, it will start at the
9103    block.  */
9104
9105 static void
9106 flow_dfs_compute_reverse_add_bb (data, bb)
9107      depth_first_search_ds data;
9108      basic_block bb;
9109 {
9110   data->stack[data->sp++] = bb;
9111   return;
9112 }
9113
9114 /* Continue the depth-first search through the reverse graph starting
9115    with the block at the stack's top and ending when the stack is
9116    empty.  Visited nodes are marked.  Returns an unvisited basic
9117    block, or NULL if there is none available.  */
9118
9119 static basic_block
9120 flow_dfs_compute_reverse_execute (data)
9121      depth_first_search_ds data;
9122 {
9123   basic_block bb;
9124   edge e;
9125   int i;
9126
9127   while (data->sp > 0)
9128     {
9129       bb = data->stack[--data->sp];
9130
9131       /* Mark that we have visited this node.  */
9132       if (!TEST_BIT (data->visited_blocks, bb->index - (INVALID_BLOCK + 1)))
9133         {
9134           SET_BIT (data->visited_blocks, bb->index - (INVALID_BLOCK + 1));
9135
9136           /* Perform depth-first search on adjacent vertices.  */
9137           for (e = bb->pred; e; e = e->pred_next)
9138             flow_dfs_compute_reverse_add_bb (data, e->src);
9139         }
9140     }
9141
9142   /* Determine if there are unvisited basic blocks.  */
9143   for (i = n_basic_blocks - (INVALID_BLOCK + 1); --i >= 0;)
9144     if (!TEST_BIT (data->visited_blocks, i))
9145       return BASIC_BLOCK (i + (INVALID_BLOCK + 1));
9146   return NULL;
9147 }
9148
9149 /* Destroy the data structures needed for depth-first search on the
9150    reverse graph.  */
9151
9152 static void
9153 flow_dfs_compute_reverse_finish (data)
9154      depth_first_search_ds data;
9155 {
9156   free (data->stack);
9157   sbitmap_free (data->visited_blocks);
9158   return;
9159 }
9160
9161
9162 /* Find the root node of the loop pre-header extended basic block and
9163    the edges along the trace from the root node to the loop header.  */
9164
9165 static void
9166 flow_loop_pre_header_scan (loop)
9167      struct loop *loop;
9168 {
9169   int num = 0;
9170   basic_block ebb;
9171
9172   loop->num_pre_header_edges = 0;
9173
9174   if (loop->num_entries != 1)
9175      return;
9176
9177   ebb = loop->entry_edges[0]->src;
9178
9179   if (ebb != ENTRY_BLOCK_PTR)
9180     {
9181       edge e;
9182
9183       /* Count number of edges along trace from loop header to
9184          root of pre-header extended basic block.  Usually this is
9185          only one or two edges. */
9186       num++;
9187       while (ebb->pred->src != ENTRY_BLOCK_PTR && ! ebb->pred->pred_next)
9188         {
9189           ebb = ebb->pred->src;
9190           num++;
9191         }
9192
9193       loop->pre_header_edges = (edge *) xmalloc (num * sizeof (edge *));
9194       loop->num_pre_header_edges = num;
9195
9196       /* Store edges in order that they are followed.   The source
9197          of the first edge is the root node of the pre-header extended
9198          basic block and the destination of the last last edge is
9199          the loop header.  */
9200       for (e = loop->entry_edges[0]; num; e = e->src->pred)
9201         {
9202           loop->pre_header_edges[--num] = e;
9203         }
9204     }
9205 }
9206
9207
9208 /* Return the block for the pre-header of the loop with header
9209    HEADER where DOM specifies the dominator information.  Return NULL if
9210    there is no pre-header.  */
9211
9212 static basic_block
9213 flow_loop_pre_header_find (header, dom)
9214      basic_block header;
9215      const sbitmap *dom;
9216 {
9217   basic_block pre_header;
9218   edge e;
9219
9220   /* If block p is a predecessor of the header and is the only block
9221      that the header does not dominate, then it is the pre-header.  */
9222   pre_header = NULL;
9223   for (e = header->pred; e; e = e->pred_next)
9224     {
9225       basic_block node = e->src;
9226
9227       if (node != ENTRY_BLOCK_PTR
9228           && ! TEST_BIT (dom[node->index], header->index))
9229         {
9230           if (pre_header == NULL)
9231             pre_header = node;
9232           else
9233             {
9234               /* There are multiple edges into the header from outside
9235                  the loop so there is no pre-header block.  */
9236               pre_header = NULL;
9237               break;
9238             }
9239         }
9240     }
9241   return pre_header;
9242 }
9243
9244 /* Add LOOP to the loop hierarchy tree where PREVLOOP was the loop
9245    previously added.  The insertion algorithm assumes that the loops
9246    are added in the order found by a depth first search of the CFG.  */
9247
9248 static void
9249 flow_loop_tree_node_add (prevloop, loop)
9250      struct loop *prevloop;
9251      struct loop *loop;
9252 {
9253
9254   if (flow_loop_nested_p (prevloop, loop))
9255     {
9256       prevloop->inner = loop;
9257       loop->outer = prevloop;
9258       return;
9259     }
9260
9261   while (prevloop->outer)
9262     {
9263       if (flow_loop_nested_p (prevloop->outer, loop))
9264         {
9265           prevloop->next = loop;
9266           loop->outer = prevloop->outer;
9267           return;
9268         }
9269       prevloop = prevloop->outer;
9270     }
9271
9272   prevloop->next = loop;
9273   loop->outer = NULL;
9274 }
9275
9276 /* Build the loop hierarchy tree for LOOPS.  */
9277
9278 static void
9279 flow_loops_tree_build (loops)
9280      struct loops *loops;
9281 {
9282   int i;
9283   int num_loops;
9284
9285   num_loops = loops->num;
9286   if (! num_loops)
9287     return;
9288
9289   /* Root the loop hierarchy tree with the first loop found.
9290      Since we used a depth first search this should be the
9291      outermost loop.  */
9292   loops->tree_root = &loops->array[0];
9293   loops->tree_root->outer = loops->tree_root->inner = loops->tree_root->next = NULL;
9294
9295   /* Add the remaining loops to the tree.  */
9296   for (i = 1; i < num_loops; i++)
9297     flow_loop_tree_node_add (&loops->array[i - 1], &loops->array[i]);
9298 }
9299
9300 /* Helper function to compute loop nesting depth and enclosed loop level
9301    for the natural loop specified by LOOP at the loop depth DEPTH.
9302    Returns the loop level.  */
9303
9304 static int
9305 flow_loop_level_compute (loop, depth)
9306      struct loop *loop;
9307      int depth;
9308 {
9309   struct loop *inner;
9310   int level = 1;
9311
9312   if (! loop)
9313     return 0;
9314
9315   /* Traverse loop tree assigning depth and computing level as the
9316      maximum level of all the inner loops of this loop.  The loop
9317      level is equivalent to the height of the loop in the loop tree
9318      and corresponds to the number of enclosed loop levels (including
9319      itself).  */
9320   for (inner = loop->inner; inner; inner = inner->next)
9321     {
9322       int ilevel;
9323
9324       ilevel = flow_loop_level_compute (inner, depth + 1) + 1;
9325
9326       if (ilevel > level)
9327         level = ilevel;
9328     }
9329   loop->level = level;
9330   loop->depth = depth;
9331   return level;
9332 }
9333
9334 /* Compute the loop nesting depth and enclosed loop level for the loop
9335    hierarchy tree specfied by LOOPS.  Return the maximum enclosed loop
9336    level.  */
9337
9338 static int
9339 flow_loops_level_compute (loops)
9340      struct loops *loops;
9341 {
9342   struct loop *loop;
9343   int level;
9344   int levels = 0;
9345
9346   /* Traverse all the outer level loops.  */
9347   for (loop = loops->tree_root; loop; loop = loop->next)
9348     {
9349       level = flow_loop_level_compute (loop, 1);
9350       if (level > levels)
9351         levels = level;
9352     }
9353   return levels;
9354 }
9355
9356
9357 /* Scan a single natural loop specified by LOOP collecting information
9358    about it specified by FLAGS.  */
9359
9360 int
9361 flow_loop_scan (loops, loop, flags)
9362      struct loops *loops;
9363      struct loop *loop;
9364      int flags;
9365 {
9366   /* Determine prerequisites.  */
9367   if ((flags & LOOP_EXITS_DOMS) && ! loop->exit_edges)
9368     flags |= LOOP_EXIT_EDGES;
9369
9370   if (flags & LOOP_ENTRY_EDGES)
9371     {
9372       /* Find edges which enter the loop header.
9373          Note that the entry edges should only
9374          enter the header of a natural loop.  */
9375       loop->num_entries
9376         = flow_loop_entry_edges_find (loop->header,
9377                                       loop->nodes,
9378                                       &loop->entry_edges);
9379     }
9380
9381   if (flags & LOOP_EXIT_EDGES)
9382     {
9383       /* Find edges which exit the loop.  */
9384       loop->num_exits
9385         = flow_loop_exit_edges_find (loop->nodes,
9386                                      &loop->exit_edges);
9387     }
9388
9389   if (flags & LOOP_EXITS_DOMS)
9390     {
9391       int j;
9392
9393       /* Determine which loop nodes dominate all the exits
9394          of the loop.  */
9395       loop->exits_doms = sbitmap_alloc (n_basic_blocks);
9396       sbitmap_copy (loop->exits_doms, loop->nodes);
9397       for (j = 0; j < loop->num_exits; j++)
9398         sbitmap_a_and_b (loop->exits_doms, loop->exits_doms,
9399                          loops->cfg.dom[loop->exit_edges[j]->src->index]);
9400       
9401       /* The header of a natural loop must dominate
9402          all exits.  */
9403       if (! TEST_BIT (loop->exits_doms, loop->header->index))
9404         abort ();
9405     }
9406   
9407   if (flags & LOOP_PRE_HEADER)
9408     {
9409       /* Look to see if the loop has a pre-header node.  */
9410       loop->pre_header
9411         = flow_loop_pre_header_find (loop->header, loops->cfg.dom);
9412
9413       /* Find the blocks within the extended basic block of
9414          the loop pre-header.  */
9415       flow_loop_pre_header_scan (loop);
9416     }
9417   return 1;
9418 }
9419
9420
9421 /* Find all the natural loops in the function and save in LOOPS structure
9422    and recalculate loop_depth information in basic block structures.
9423    FLAGS controls which loop information is collected.
9424    Return the number of natural loops found.  */
9425
9426 int
9427 flow_loops_find (loops, flags)
9428      struct loops *loops;
9429      int flags;
9430 {
9431   int i;
9432   int b;
9433   int num_loops;
9434   edge e;
9435   sbitmap headers;
9436   sbitmap *dom;
9437   int *dfs_order;
9438   int *rc_order;
9439
9440   /* This function cannot be repeatedly called with different
9441      flags to build up the loop information.  The loop tree
9442      must always be built if this function is called.  */
9443   if (! (flags & LOOP_TREE))
9444     abort ();
9445
9446   memset (loops, 0, sizeof (*loops));
9447
9448   /* Taking care of this degenerate case makes the rest of
9449      this code simpler.  */
9450   if (n_basic_blocks == 0)
9451     return 0;
9452
9453   dfs_order = NULL;
9454   rc_order = NULL;
9455
9456   /* Compute the dominators.  */
9457   dom = sbitmap_vector_alloc (n_basic_blocks, n_basic_blocks);
9458   calculate_dominance_info (NULL, dom, CDI_DOMINATORS);
9459
9460   /* Count the number of loop edges (back edges).  This should be the
9461      same as the number of natural loops.  */
9462
9463   num_loops = 0;
9464   for (b = 0; b < n_basic_blocks; b++)
9465     {
9466       basic_block header;
9467
9468       header = BASIC_BLOCK (b);
9469       header->loop_depth = 0;
9470
9471       for (e = header->pred; e; e = e->pred_next)
9472         {
9473           basic_block latch = e->src;
9474
9475           /* Look for back edges where a predecessor is dominated
9476              by this block.  A natural loop has a single entry
9477              node (header) that dominates all the nodes in the
9478              loop.  It also has single back edge to the header
9479              from a latch node.  Note that multiple natural loops
9480              may share the same header.  */
9481           if (b != header->index)
9482             abort ();
9483
9484           if (latch != ENTRY_BLOCK_PTR && TEST_BIT (dom[latch->index], b))
9485             num_loops++;
9486         }
9487     }
9488
9489   if (num_loops)
9490     {
9491       /* Compute depth first search order of the CFG so that outer
9492          natural loops will be found before inner natural loops.  */
9493       dfs_order = (int *) xmalloc (n_basic_blocks * sizeof (int));
9494       rc_order = (int *) xmalloc (n_basic_blocks * sizeof (int));
9495       flow_depth_first_order_compute (dfs_order, rc_order);
9496
9497       /* Save CFG derived information to avoid recomputing it.  */
9498       loops->cfg.dom = dom;
9499       loops->cfg.dfs_order = dfs_order;
9500       loops->cfg.rc_order = rc_order;
9501
9502       /* Allocate loop structures.  */
9503       loops->array
9504         = (struct loop *) xcalloc (num_loops, sizeof (struct loop));
9505
9506       headers = sbitmap_alloc (n_basic_blocks);
9507       sbitmap_zero (headers);
9508
9509       loops->shared_headers = sbitmap_alloc (n_basic_blocks);
9510       sbitmap_zero (loops->shared_headers);
9511
9512       /* Find and record information about all the natural loops
9513          in the CFG.  */
9514       num_loops = 0;
9515       for (b = 0; b < n_basic_blocks; b++)
9516         {
9517           basic_block header;
9518
9519           /* Search the nodes of the CFG in reverse completion order
9520              so that we can find outer loops first.  */
9521           header = BASIC_BLOCK (rc_order[b]);
9522
9523           /* Look for all the possible latch blocks for this header.  */
9524           for (e = header->pred; e; e = e->pred_next)
9525             {
9526               basic_block latch = e->src;
9527
9528               /* Look for back edges where a predecessor is dominated
9529                  by this block.  A natural loop has a single entry
9530                  node (header) that dominates all the nodes in the
9531                  loop.  It also has single back edge to the header
9532                  from a latch node.  Note that multiple natural loops
9533                  may share the same header.  */
9534               if (latch != ENTRY_BLOCK_PTR
9535                   && TEST_BIT (dom[latch->index], header->index))
9536                 {
9537                   struct loop *loop;
9538
9539                   loop = loops->array + num_loops;
9540
9541                   loop->header = header;
9542                   loop->latch = latch;
9543                   loop->num = num_loops;
9544
9545                   num_loops++;
9546                 }
9547             }
9548         }
9549
9550       for (i = 0; i < num_loops; i++)
9551         {
9552           struct loop *loop = &loops->array[i];
9553
9554           /* Keep track of blocks that are loop headers so
9555              that we can tell which loops should be merged.  */
9556           if (TEST_BIT (headers, loop->header->index))
9557             SET_BIT (loops->shared_headers, loop->header->index);
9558           SET_BIT (headers, loop->header->index);
9559
9560           /* Find nodes contained within the loop.  */
9561           loop->nodes = sbitmap_alloc (n_basic_blocks);
9562           loop->num_nodes
9563             = flow_loop_nodes_find (loop->header, loop->latch, loop->nodes);
9564
9565           /* Compute first and last blocks within the loop.
9566              These are often the same as the loop header and
9567              loop latch respectively, but this is not always
9568              the case.  */
9569           loop->first
9570             = BASIC_BLOCK (sbitmap_first_set_bit (loop->nodes));
9571           loop->last
9572             = BASIC_BLOCK (sbitmap_last_set_bit (loop->nodes));
9573
9574           flow_loop_scan (loops, loop, flags);
9575         }
9576
9577       /* Natural loops with shared headers may either be disjoint or
9578          nested.  Disjoint loops with shared headers cannot be inner
9579          loops and should be merged.  For now just mark loops that share
9580          headers.  */
9581       for (i = 0; i < num_loops; i++)
9582         if (TEST_BIT (loops->shared_headers, loops->array[i].header->index))
9583           loops->array[i].shared = 1;
9584
9585       sbitmap_free (headers);
9586     }
9587   else
9588     {
9589       sbitmap_vector_free (dom);
9590     }
9591
9592   loops->num = num_loops;
9593
9594   /* Build the loop hierarchy tree.  */
9595   flow_loops_tree_build (loops);
9596
9597   /* Assign the loop nesting depth and enclosed loop level for each
9598      loop.  */
9599   loops->levels = flow_loops_level_compute (loops);
9600
9601   return num_loops;
9602 }
9603
9604
9605 /* Update the information regarding the loops in the CFG
9606    specified by LOOPS.  */
9607 int
9608 flow_loops_update (loops, flags)
9609      struct loops *loops;
9610      int flags;
9611 {
9612   /* One day we may want to update the current loop data.  For now
9613      throw away the old stuff and rebuild what we need.  */
9614   if (loops->array)
9615     flow_loops_free (loops);
9616
9617   return flow_loops_find (loops, flags);
9618 }
9619
9620
9621 /* Return non-zero if edge E enters header of LOOP from outside of LOOP.  */
9622
9623 int
9624 flow_loop_outside_edge_p (loop, e)
9625      const struct loop *loop;
9626      edge e;
9627 {
9628   if (e->dest != loop->header)
9629     abort ();
9630   return (e->src == ENTRY_BLOCK_PTR)
9631     || ! TEST_BIT (loop->nodes, e->src->index);
9632 }
9633
9634 /* Clear LOG_LINKS fields of insns in a chain.
9635    Also clear the global_live_at_{start,end} fields of the basic block
9636    structures.  */
9637
9638 void
9639 clear_log_links (insns)
9640      rtx insns;
9641 {
9642   rtx i;
9643   int b;
9644
9645   for (i = insns; i; i = NEXT_INSN (i))
9646     if (INSN_P (i))
9647       LOG_LINKS (i) = 0;
9648
9649   for (b = 0; b < n_basic_blocks; b++)
9650     {
9651       basic_block bb = BASIC_BLOCK (b);
9652
9653       bb->global_live_at_start = NULL;
9654       bb->global_live_at_end = NULL;
9655     }
9656
9657   ENTRY_BLOCK_PTR->global_live_at_end = NULL;
9658   EXIT_BLOCK_PTR->global_live_at_start = NULL;
9659 }
9660
9661 /* Given a register bitmap, turn on the bits in a HARD_REG_SET that
9662    correspond to the hard registers, if any, set in that map.  This
9663    could be done far more efficiently by having all sorts of special-cases
9664    with moving single words, but probably isn't worth the trouble.  */
9665
9666 void
9667 reg_set_to_hard_reg_set (to, from)
9668      HARD_REG_SET *to;
9669      bitmap from;
9670 {
9671   int i;
9672
9673   EXECUTE_IF_SET_IN_BITMAP
9674     (from, 0, i,
9675      {
9676        if (i >= FIRST_PSEUDO_REGISTER)
9677          return;
9678        SET_HARD_REG_BIT (*to, i);
9679      });
9680 }
9681
9682 /* Called once at intialization time.  */
9683
9684 void
9685 init_flow ()
9686 {
9687   static int initialized;
9688
9689   if (!initialized)
9690     {
9691       gcc_obstack_init (&flow_obstack);
9692       flow_firstobj = (char *) obstack_alloc (&flow_obstack, 0);
9693       initialized = 1;
9694     }
9695   else
9696     {
9697       obstack_free (&flow_obstack, flow_firstobj);
9698       flow_firstobj = (char *) obstack_alloc (&flow_obstack, 0);
9699     }
9700 }