OSDN Git Service

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