OSDN Git Service

In include:
[pf3gnuchains/gcc-fork.git] / gcc / gcse.c
1 /* Global common subexpression elimination/Partial redundancy elimination
2    and global constant/copy propagation for GNU compiler.
3    Copyright (C) 1997, 1998, 1999, 2000 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 /* TODO
23    - reordering of memory allocation and freeing to be more space efficient
24    - do rough calc of how many regs are needed in each block, and a rough
25      calc of how many regs are available in each class and use that to
26      throttle back the code in cases where RTX_COST is minimal.
27    - dead store elimination
28    - a store to the same address as a load does not kill the load if the
29      source of the store is also the destination of the load.  Handling this
30      allows more load motion, particularly out of loops.
31    - ability to realloc sbitmap vectors would allow one initial computation
32      of reg_set_in_block with only subsequent additions, rather than
33      recomputing it for each pass
34
35 */
36
37 /* References searched while implementing this.
38
39    Compilers Principles, Techniques and Tools
40    Aho, Sethi, Ullman
41    Addison-Wesley, 1988
42
43    Global Optimization by Suppression of Partial Redundancies
44    E. Morel, C. Renvoise
45    communications of the acm, Vol. 22, Num. 2, Feb. 1979
46
47    A Portable Machine-Independent Global Optimizer - Design and Measurements
48    Frederick Chow
49    Stanford Ph.D. thesis, Dec. 1983
50
51    A Fast Algorithm for Code Movement Optimization
52    D.M. Dhamdhere
53    SIGPLAN Notices, Vol. 23, Num. 10, Oct. 1988
54
55    A Solution to a Problem with Morel and Renvoise's
56    Global Optimization by Suppression of Partial Redundancies
57    K-H Drechsler, M.P. Stadel
58    ACM TOPLAS, Vol. 10, Num. 4, Oct. 1988
59
60    Practical Adaptation of the Global Optimization
61    Algorithm of Morel and Renvoise
62    D.M. Dhamdhere
63    ACM TOPLAS, Vol. 13, Num. 2. Apr. 1991
64
65    Efficiently Computing Static Single Assignment Form and the Control
66    Dependence Graph
67    R. Cytron, J. Ferrante, B.K. Rosen, M.N. Wegman, and F.K. Zadeck
68    ACM TOPLAS, Vol. 13, Num. 4, Oct. 1991
69
70    Lazy Code Motion
71    J. Knoop, O. Ruthing, B. Steffen
72    ACM SIGPLAN Notices Vol. 27, Num. 7, Jul. 1992, '92 Conference on PLDI
73
74    What's In a Region?  Or Computing Control Dependence Regions in Near-Linear
75    Time for Reducible Flow Control
76    Thomas Ball
77    ACM Letters on Programming Languages and Systems,
78    Vol. 2, Num. 1-4, Mar-Dec 1993
79
80    An Efficient Representation for Sparse Sets
81    Preston Briggs, Linda Torczon
82    ACM Letters on Programming Languages and Systems,
83    Vol. 2, Num. 1-4, Mar-Dec 1993
84
85    A Variation of Knoop, Ruthing, and Steffen's Lazy Code Motion
86    K-H Drechsler, M.P. Stadel
87    ACM SIGPLAN Notices, Vol. 28, Num. 5, May 1993
88
89    Partial Dead Code Elimination
90    J. Knoop, O. Ruthing, B. Steffen
91    ACM SIGPLAN Notices, Vol. 29, Num. 6, Jun. 1994
92
93    Effective Partial Redundancy Elimination
94    P. Briggs, K.D. Cooper
95    ACM SIGPLAN Notices, Vol. 29, Num. 6, Jun. 1994
96
97    The Program Structure Tree: Computing Control Regions in Linear Time
98    R. Johnson, D. Pearson, K. Pingali
99    ACM SIGPLAN Notices, Vol. 29, Num. 6, Jun. 1994
100
101    Optimal Code Motion: Theory and Practice
102    J. Knoop, O. Ruthing, B. Steffen
103    ACM TOPLAS, Vol. 16, Num. 4, Jul. 1994
104
105    The power of assignment motion
106    J. Knoop, O. Ruthing, B. Steffen
107    ACM SIGPLAN Notices Vol. 30, Num. 6, Jun. 1995, '95 Conference on PLDI
108
109    Global code motion / global value numbering
110    C. Click
111    ACM SIGPLAN Notices Vol. 30, Num. 6, Jun. 1995, '95 Conference on PLDI
112
113    Value Driven Redundancy Elimination
114    L.T. Simpson
115    Rice University Ph.D. thesis, Apr. 1996
116
117    Value Numbering
118    L.T. Simpson
119    Massively Scalar Compiler Project, Rice University, Sep. 1996
120
121    High Performance Compilers for Parallel Computing
122    Michael Wolfe
123    Addison-Wesley, 1996
124
125    Advanced Compiler Design and Implementation
126    Steven Muchnick
127    Morgan Kaufmann, 1997
128
129    Building an Optimizing Compiler
130    Robert Morgan
131    Digital Press, 1998
132
133    People wishing to speed up the code here should read:
134      Elimination Algorithms for Data Flow Analysis
135      B.G. Ryder, M.C. Paull
136      ACM Computing Surveys, Vol. 18, Num. 3, Sep. 1986
137
138      How to Analyze Large Programs Efficiently and Informatively
139      D.M. Dhamdhere, B.K. Rosen, F.K. Zadeck
140      ACM SIGPLAN Notices Vol. 27, Num. 7, Jul. 1992, '92 Conference on PLDI
141
142    People wishing to do something different can find various possibilities
143    in the above papers and elsewhere.
144 */
145
146 #include "config.h"
147 #include "system.h"
148 #include "toplev.h"
149
150 #include "rtl.h"
151 #include "tm_p.h"
152 #include "regs.h"
153 #include "hard-reg-set.h"
154 #include "flags.h"
155 #include "real.h"
156 #include "insn-config.h"
157 #include "recog.h"
158 #include "basic-block.h"
159 #include "output.h"
160 #include "function.h"
161 #include "expr.h" 
162
163 #include "obstack.h"
164 #define obstack_chunk_alloc gmalloc
165 #define obstack_chunk_free free
166
167 /* Maximum number of passes to perform.  */
168 #define MAX_PASSES 1
169
170 /* Propagate flow information through back edges and thus enable PRE's
171    moving loop invariant calculations out of loops.
172
173    Originally this tended to create worse overall code, but several
174    improvements during the development of PRE seem to have made following
175    back edges generally a win.
176
177    Note much of the loop invariant code motion done here would normally
178    be done by loop.c, which has more heuristics for when to move invariants
179    out of loops.  At some point we might need to move some of those
180    heuristics into gcse.c.  */
181 #define FOLLOW_BACK_EDGES 1
182
183 /* We support GCSE via Partial Redundancy Elimination.  PRE optimizations
184    are a superset of those done by GCSE.
185
186    We perform the following steps:
187
188    1) Compute basic block information.
189
190    2) Compute table of places where registers are set.
191
192    3) Perform copy/constant propagation.
193
194    4) Perform global cse.
195
196    5) Perform another pass of copy/constant propagation.
197
198    Two passes of copy/constant propagation are done because the first one
199    enables more GCSE and the second one helps to clean up the copies that
200    GCSE creates.  This is needed more for PRE than for Classic because Classic
201    GCSE will try to use an existing register containing the common
202    subexpression rather than create a new one.  This is harder to do for PRE
203    because of the code motion (which Classic GCSE doesn't do).
204
205    Expressions we are interested in GCSE-ing are of the form
206    (set (pseudo-reg) (expression)).
207    Function want_to_gcse_p says what these are.
208
209    PRE handles moving invariant expressions out of loops (by treating them as
210    partially redundant).
211
212    Eventually it would be nice to replace cse.c/gcse.c with SSA (static single
213    assignment) based GVN (global value numbering).  L. T. Simpson's paper
214    (Rice University) on value numbering is a useful reference for this.
215
216    **********************
217
218    We used to support multiple passes but there are diminishing returns in
219    doing so.  The first pass usually makes 90% of the changes that are doable.
220    A second pass can make a few more changes made possible by the first pass.
221    Experiments show any further passes don't make enough changes to justify
222    the expense.
223
224    A study of spec92 using an unlimited number of passes:
225    [1 pass] = 1208 substitutions, [2] = 577, [3] = 202, [4] = 192, [5] = 83,
226    [6] = 34, [7] = 17, [8] = 9, [9] = 4, [10] = 4, [11] = 2,
227    [12] = 2, [13] = 1, [15] = 1, [16] = 2, [41] = 1
228
229    It was found doing copy propagation between each pass enables further
230    substitutions.
231
232    PRE is quite expensive in complicated functions because the DFA can take
233    awhile to converge.  Hence we only perform one pass.  Macro MAX_PASSES can
234    be modified if one wants to experiment.
235
236    **********************
237
238    The steps for PRE are:
239
240    1) Build the hash table of expressions we wish to GCSE (expr_hash_table).
241
242    2) Perform the data flow analysis for PRE.
243
244    3) Delete the redundant instructions
245
246    4) Insert the required copies [if any] that make the partially
247       redundant instructions fully redundant.
248
249    5) For other reaching expressions, insert an instruction to copy the value
250       to a newly created pseudo that will reach the redundant instruction.
251
252    The deletion is done first so that when we do insertions we
253    know which pseudo reg to use.
254
255    Various papers have argued that PRE DFA is expensive (O(n^2)) and others
256    argue it is not.  The number of iterations for the algorithm to converge
257    is typically 2-4 so I don't view it as that expensive (relatively speaking).
258
259    PRE GCSE depends heavily on the second CSE pass to clean up the copies
260    we create.  To make an expression reach the place where it's redundant,
261    the result of the expression is copied to a new register, and the redundant
262    expression is deleted by replacing it with this new register.  Classic GCSE
263    doesn't have this problem as much as it computes the reaching defs of
264    each register in each block and thus can try to use an existing register.
265
266    **********************
267
268    A fair bit of simplicity is created by creating small functions for simple
269    tasks, even when the function is only called in one place.  This may
270    measurably slow things down [or may not] by creating more function call
271    overhead than is necessary.  The source is laid out so that it's trivial
272    to make the affected functions inline so that one can measure what speed
273    up, if any, can be achieved, and maybe later when things settle things can
274    be rearranged.
275
276    Help stamp out big monolithic functions!  */
277 \f
278 /* GCSE global vars.  */
279
280 /* -dG dump file.  */
281 static FILE *gcse_file;
282
283 /* Note whether or not we should run jump optimization after gcse.  We
284    want to do this for two cases.
285
286     * If we changed any jumps via cprop.
287
288     * If we added any labels via edge splitting.  */
289
290 static int run_jump_opt_after_gcse;
291
292 /* Bitmaps are normally not included in debugging dumps.
293    However it's useful to be able to print them from GDB.
294    We could create special functions for this, but it's simpler to
295    just allow passing stderr to the dump_foo fns.  Since stderr can
296    be a macro, we store a copy here.  */
297 static FILE *debug_stderr;
298
299 /* An obstack for our working variables.  */
300 static struct obstack gcse_obstack;
301
302 /* Non-zero for each mode that supports (set (reg) (reg)).
303    This is trivially true for integer and floating point values.
304    It may or may not be true for condition codes.  */
305 static char can_copy_p[(int) NUM_MACHINE_MODES];
306
307 /* Non-zero if can_copy_p has been initialized.  */
308 static int can_copy_init_p;
309
310 struct reg_use {rtx reg_rtx; };
311
312 /* Hash table of expressions.  */
313
314 struct expr
315 {
316   /* The expression (SET_SRC for expressions, PATTERN for assignments).  */
317   rtx expr;
318   /* Index in the available expression bitmaps.  */
319   int bitmap_index;
320   /* Next entry with the same hash.  */
321   struct expr *next_same_hash;
322   /* List of anticipatable occurrences in basic blocks in the function.
323      An "anticipatable occurrence" is one that is the first occurrence in the
324      basic block, the operands are not modified in the basic block prior
325      to the occurrence and the output is not used between the start of
326      the block and the occurrence.  */
327   struct occr *antic_occr;
328   /* List of available occurrence in basic blocks in the function.
329      An "available occurrence" is one that is the last occurrence in the
330      basic block and the operands are not modified by following statements in
331      the basic block [including this insn].  */
332   struct occr *avail_occr;
333   /* Non-null if the computation is PRE redundant.
334      The value is the newly created pseudo-reg to record a copy of the
335      expression in all the places that reach the redundant copy.  */
336   rtx reaching_reg;
337 };
338
339 /* Occurrence of an expression.
340    There is one per basic block.  If a pattern appears more than once the
341    last appearance is used [or first for anticipatable expressions].  */
342
343 struct occr
344 {
345   /* Next occurrence of this expression.  */
346   struct occr *next;
347   /* The insn that computes the expression.  */
348   rtx insn;
349   /* Non-zero if this [anticipatable] occurrence has been deleted.  */
350   char deleted_p;
351   /* Non-zero if this [available] occurrence has been copied to
352      reaching_reg.  */
353   /* ??? This is mutually exclusive with deleted_p, so they could share
354      the same byte.  */
355   char copied_p;
356 };
357
358 /* Expression and copy propagation hash tables.
359    Each hash table is an array of buckets.
360    ??? It is known that if it were an array of entries, structure elements
361    `next_same_hash' and `bitmap_index' wouldn't be necessary.  However, it is
362    not clear whether in the final analysis a sufficient amount of memory would
363    be saved as the size of the available expression bitmaps would be larger
364    [one could build a mapping table without holes afterwards though].
365    Someday I'll perform the computation and figure it out.  */
366
367 /* Total size of the expression hash table, in elements.  */
368 static unsigned int expr_hash_table_size;
369
370 /* The table itself.
371    This is an array of `expr_hash_table_size' elements.  */
372 static struct expr **expr_hash_table;
373
374 /* Total size of the copy propagation hash table, in elements.  */
375 static int set_hash_table_size;
376
377 /* The table itself.
378    This is an array of `set_hash_table_size' elements.  */
379 static struct expr **set_hash_table;
380
381 /* Mapping of uids to cuids.
382    Only real insns get cuids.  */
383 static int *uid_cuid;
384
385 /* Highest UID in UID_CUID.  */
386 static int max_uid;
387
388 /* Get the cuid of an insn.  */
389 #ifdef ENABLE_CHECKING
390 #define INSN_CUID(INSN) (INSN_UID (INSN) > max_uid ? (abort (), 0) : uid_cuid[INSN_UID (INSN)])
391 #else
392 #define INSN_CUID(INSN) (uid_cuid[INSN_UID (INSN)])
393 #endif
394
395 /* Number of cuids.  */
396 static int max_cuid;
397
398 /* Mapping of cuids to insns.  */
399 static rtx *cuid_insn;
400
401 /* Get insn from cuid.  */
402 #define CUID_INSN(CUID) (cuid_insn[CUID])
403
404 /* Maximum register number in function prior to doing gcse + 1.
405    Registers created during this pass have regno >= max_gcse_regno.
406    This is named with "gcse" to not collide with global of same name.  */
407 static unsigned int max_gcse_regno;
408
409 /* Maximum number of cse-able expressions found.  */
410 static int n_exprs;
411
412 /* Maximum number of assignments for copy propagation found.  */
413 static int n_sets;
414
415 /* Table of registers that are modified.
416
417    For each register, each element is a list of places where the pseudo-reg
418    is set.
419
420    For simplicity, GCSE is done on sets of pseudo-regs only.  PRE GCSE only
421    requires knowledge of which blocks kill which regs [and thus could use
422    a bitmap instead of the lists `reg_set_table' uses].
423
424    `reg_set_table' and could be turned into an array of bitmaps (num-bbs x
425    num-regs) [however perhaps it may be useful to keep the data as is].  One
426    advantage of recording things this way is that `reg_set_table' is fairly
427    sparse with respect to pseudo regs but for hard regs could be fairly dense
428    [relatively speaking].  And recording sets of pseudo-regs in lists speeds
429    up functions like compute_transp since in the case of pseudo-regs we only
430    need to iterate over the number of times a pseudo-reg is set, not over the
431    number of basic blocks [clearly there is a bit of a slow down in the cases
432    where a pseudo is set more than once in a block, however it is believed
433    that the net effect is to speed things up].  This isn't done for hard-regs
434    because recording call-clobbered hard-regs in `reg_set_table' at each
435    function call can consume a fair bit of memory, and iterating over
436    hard-regs stored this way in compute_transp will be more expensive.  */
437
438 typedef struct reg_set
439 {
440   /* The next setting of this register.  */
441   struct reg_set *next;
442   /* The insn where it was set.  */
443   rtx insn;
444 } reg_set;
445
446 static reg_set **reg_set_table;
447
448 /* Size of `reg_set_table'.
449    The table starts out at max_gcse_regno + slop, and is enlarged as
450    necessary.  */
451 static int reg_set_table_size;
452
453 /* Amount to grow `reg_set_table' by when it's full.  */
454 #define REG_SET_TABLE_SLOP 100
455
456 /* Bitmap containing one bit for each register in the program.
457    Used when performing GCSE to track which registers have been set since
458    the start of the basic block.  */
459 static sbitmap reg_set_bitmap;
460
461 /* For each block, a bitmap of registers set in the block.
462    This is used by expr_killed_p and compute_transp.
463    It is computed during hash table computation and not by compute_sets
464    as it includes registers added since the last pass (or between cprop and
465    gcse) and it's currently not easy to realloc sbitmap vectors.  */
466 static sbitmap *reg_set_in_block;
467
468 /* For each block, non-zero if memory is set in that block.
469    This is computed during hash table computation and is used by
470    expr_killed_p and compute_transp.
471    ??? Handling of memory is very simple, we don't make any attempt
472    to optimize things (later).
473    ??? This can be computed by compute_sets since the information
474    doesn't change.  */
475 static char *mem_set_in_block;
476
477 /* Various variables for statistics gathering.  */
478
479 /* Memory used in a pass.
480    This isn't intended to be absolutely precise.  Its intent is only
481    to keep an eye on memory usage.  */
482 static int bytes_used;
483
484 /* GCSE substitutions made.  */
485 static int gcse_subst_count;
486 /* Number of copy instructions created.  */
487 static int gcse_create_count;
488 /* Number of constants propagated.  */
489 static int const_prop_count;
490 /* Number of copys propagated.  */
491 static int copy_prop_count;
492 \f
493 /* These variables are used by classic GCSE.
494    Normally they'd be defined a bit later, but `rd_gen' needs to
495    be declared sooner.  */
496
497 /* Each block has a bitmap of each type.
498    The length of each blocks bitmap is:
499
500        max_cuid  - for reaching definitions
501        n_exprs - for available expressions
502
503    Thus we view the bitmaps as 2 dimensional arrays.  i.e.
504    rd_kill[block_num][cuid_num]
505    ae_kill[block_num][expr_num]                  */
506
507 /* For reaching defs */
508 static sbitmap *rd_kill, *rd_gen, *reaching_defs, *rd_out;
509
510 /* for available exprs */
511 static sbitmap *ae_kill, *ae_gen, *ae_in, *ae_out;
512
513 /* Objects of this type are passed around by the null-pointer check
514    removal routines.  */
515 struct null_pointer_info
516 {
517   /* The basic block being processed.  */
518   int current_block;
519   /* The first register to be handled in this pass.  */
520   unsigned int min_reg;
521   /* One greater than the last register to be handled in this pass.  */
522   unsigned int max_reg;
523   sbitmap *nonnull_local;
524   sbitmap *nonnull_killed;
525 };
526 \f
527 static void compute_can_copy    PARAMS ((void));
528 static char *gmalloc            PARAMS ((unsigned int));
529 static char *grealloc           PARAMS ((char *, unsigned int));
530 static char *gcse_alloc         PARAMS ((unsigned long));
531 static void alloc_gcse_mem      PARAMS ((rtx));
532 static void free_gcse_mem       PARAMS ((void));
533 static void alloc_reg_set_mem   PARAMS ((int));
534 static void free_reg_set_mem    PARAMS ((void));
535 static int get_bitmap_width     PARAMS ((int, int, int));
536 static void record_one_set      PARAMS ((int, rtx));
537 static void record_set_info     PARAMS ((rtx, rtx, void *));
538 static void compute_sets        PARAMS ((rtx));
539 static void hash_scan_insn      PARAMS ((rtx, int, int));
540 static void hash_scan_set       PARAMS ((rtx, rtx, int));
541 static void hash_scan_clobber   PARAMS ((rtx, rtx));
542 static void hash_scan_call      PARAMS ((rtx, rtx));
543 static int want_to_gcse_p       PARAMS ((rtx));
544 static int oprs_unchanged_p     PARAMS ((rtx, rtx, int));
545 static int oprs_anticipatable_p PARAMS ((rtx, rtx));
546 static int oprs_available_p     PARAMS ((rtx, rtx));
547 static void insert_expr_in_table PARAMS ((rtx, enum machine_mode, rtx,
548                                           int, int));
549 static void insert_set_in_table PARAMS ((rtx, rtx));
550 static unsigned int hash_expr   PARAMS ((rtx, enum machine_mode, int *, int));
551 static unsigned int hash_expr_1 PARAMS ((rtx, enum machine_mode, int *));
552 static unsigned int hash_set    PARAMS ((int, int));
553 static int expr_equiv_p         PARAMS ((rtx, rtx));
554 static void record_last_reg_set_info PARAMS ((rtx, int));
555 static void record_last_mem_set_info PARAMS ((rtx));
556 static void record_last_set_info PARAMS ((rtx, rtx, void *));
557 static void compute_hash_table  PARAMS ((int));
558 static void alloc_set_hash_table PARAMS ((int));
559 static void free_set_hash_table PARAMS ((void));
560 static void compute_set_hash_table PARAMS ((void));
561 static void alloc_expr_hash_table PARAMS ((unsigned int));
562 static void free_expr_hash_table PARAMS ((void));
563 static void compute_expr_hash_table PARAMS ((void));
564 static void dump_hash_table     PARAMS ((FILE *, const char *, struct expr **,
565                                          int, int));
566 static struct expr *lookup_expr PARAMS ((rtx));
567 static struct expr *lookup_set  PARAMS ((unsigned int, rtx));
568 static struct expr *next_set    PARAMS ((unsigned int, struct expr *));
569 static void reset_opr_set_tables PARAMS ((void));
570 static int oprs_not_set_p       PARAMS ((rtx, rtx));
571 static void mark_call           PARAMS ((rtx));
572 static void mark_set            PARAMS ((rtx, rtx));
573 static void mark_clobber        PARAMS ((rtx, rtx));
574 static void mark_oprs_set       PARAMS ((rtx));
575 static void alloc_cprop_mem     PARAMS ((int, int));
576 static void free_cprop_mem      PARAMS ((void));
577 static void compute_transp      PARAMS ((rtx, int, sbitmap *, int));
578 static void compute_transpout   PARAMS ((void));
579 static void compute_local_properties PARAMS ((sbitmap *, sbitmap *, sbitmap *,
580                                               int));
581 static void compute_cprop_data  PARAMS ((void));
582 static void find_used_regs      PARAMS ((rtx));
583 static int try_replace_reg      PARAMS ((rtx, rtx, rtx));
584 static struct expr *find_avail_set PARAMS ((int, rtx));
585 static int cprop_jump           PARAMS ((rtx, rtx, struct reg_use *, rtx));
586 #ifdef HAVE_cc0
587 static int cprop_cc0_jump       PARAMS ((rtx, struct reg_use *, rtx));
588 #endif
589 static int cprop_insn           PARAMS ((rtx, int));
590 static int cprop                PARAMS ((int));
591 static int one_cprop_pass       PARAMS ((int, int));
592 static void alloc_pre_mem       PARAMS ((int, int));
593 static void free_pre_mem        PARAMS ((void));
594 static void compute_pre_data    PARAMS ((void));
595 static int pre_expr_reaches_here_p PARAMS ((int, struct expr *, int));
596 static void insert_insn_end_bb  PARAMS ((struct expr *, int, int));
597 static void pre_insert_copy_insn PARAMS ((struct expr *, rtx));
598 static void pre_insert_copies   PARAMS ((void));
599 static int pre_delete           PARAMS ((void));
600 static int pre_gcse             PARAMS ((void));
601 static int one_pre_gcse_pass    PARAMS ((int));
602 static void add_label_notes     PARAMS ((rtx, rtx));
603 static void alloc_code_hoist_mem PARAMS ((int, int));
604 static void free_code_hoist_mem PARAMS ((void));
605 static void compute_code_hoist_vbeinout PARAMS ((void));
606 static void compute_code_hoist_data PARAMS ((void));
607 static int hoist_expr_reaches_here_p PARAMS ((int, int, int, char *));
608 static void hoist_code          PARAMS ((void));
609 static int one_code_hoisting_pass PARAMS ((void));
610 static void alloc_rd_mem        PARAMS ((int, int));
611 static void free_rd_mem         PARAMS ((void));
612 static void handle_rd_kill_set  PARAMS ((rtx, int, int));
613 static void compute_kill_rd     PARAMS ((void));
614 static void compute_rd          PARAMS ((void));
615 static void alloc_avail_expr_mem PARAMS ((int, int));
616 static void free_avail_expr_mem PARAMS ((void));
617 static void compute_ae_gen      PARAMS ((void));
618 static int expr_killed_p        PARAMS ((rtx, int));
619 static void compute_ae_kill     PARAMS ((sbitmap *, sbitmap *));
620 static int expr_reaches_here_p  PARAMS ((struct occr *, struct expr *,
621                                          int, int));
622 static rtx computing_insn       PARAMS ((struct expr *, rtx));
623 static int def_reaches_here_p   PARAMS ((rtx, rtx));
624 static int can_disregard_other_sets PARAMS ((struct reg_set **, rtx, int));
625 static int handle_avail_expr    PARAMS ((rtx, struct expr *));
626 static int classic_gcse         PARAMS ((void));
627 static int one_classic_gcse_pass PARAMS ((int));
628 static void invalidate_nonnull_info PARAMS ((rtx, rtx, void *));
629 static void delete_null_pointer_checks_1 PARAMS ((unsigned int *, sbitmap *,
630                                                   sbitmap *,
631                                                   struct null_pointer_info *));
632 static rtx process_insert_insn  PARAMS ((struct expr *));
633 static int pre_edge_insert      PARAMS ((struct edge_list *, struct expr **));
634 static int expr_reaches_here_p_work PARAMS ((struct occr *, struct expr *,
635                                              int, int, char *));
636 static int pre_expr_reaches_here_p_work PARAMS ((int, struct expr *,
637                                                  int, char *));
638 \f
639 /* Entry point for global common subexpression elimination.
640    F is the first instruction in the function.  */
641
642 int
643 gcse_main (f, file)
644      rtx f;
645      FILE *file;
646 {
647   int changed, pass;
648   /* Bytes used at start of pass.  */
649   int initial_bytes_used;
650   /* Maximum number of bytes used by a pass.  */
651   int max_pass_bytes;
652   /* Point to release obstack data from for each pass.  */
653   char *gcse_obstack_bottom;
654
655   /* We do not construct an accurate cfg in functions which call
656      setjmp, so just punt to be safe.  */
657   if (current_function_calls_setjmp)
658     return 0;
659    
660   /* Assume that we do not need to run jump optimizations after gcse.  */
661   run_jump_opt_after_gcse = 0;
662
663   /* For calling dump_foo fns from gdb.  */
664   debug_stderr = stderr;
665   gcse_file = file;
666
667   /* Identify the basic block information for this function, including
668      successors and predecessors.  */
669   max_gcse_regno = max_reg_num ();
670
671   if (file)
672     dump_flow_info (file);
673
674   /* Return if there's nothing to do.  */
675   if (n_basic_blocks <= 1)
676     return 0;
677
678   /* Trying to perform global optimizations on flow graphs which have
679      a high connectivity will take a long time and is unlikely to be
680      particularly useful.
681
682      In normal circumstances a cfg should have about twice has many edges
683      as blocks.  But we do not want to punish small functions which have
684      a couple switch statements.  So we require a relatively large number
685      of basic blocks and the ratio of edges to blocks to be high.  */
686   if (n_basic_blocks > 1000 && n_edges / n_basic_blocks >= 20)
687     return 0;
688
689   /* See what modes support reg/reg copy operations.  */
690   if (! can_copy_init_p)
691     {
692       compute_can_copy ();
693       can_copy_init_p = 1;
694     }
695
696   gcc_obstack_init (&gcse_obstack);
697   bytes_used = 0;
698
699   /* Record where pseudo-registers are set.  This data is kept accurate
700      during each pass.  ??? We could also record hard-reg information here
701      [since it's unchanging], however it is currently done during hash table
702      computation.
703
704      It may be tempting to compute MEM set information here too, but MEM sets
705      will be subject to code motion one day and thus we need to compute
706      information about memory sets when we build the hash tables.  */
707
708   alloc_reg_set_mem (max_gcse_regno);
709   compute_sets (f);
710
711   pass = 0;
712   initial_bytes_used = bytes_used;
713   max_pass_bytes = 0;
714   gcse_obstack_bottom = gcse_alloc (1);
715   changed = 1;
716   while (changed && pass < MAX_PASSES)
717     {
718       changed = 0;
719       if (file)
720         fprintf (file, "GCSE pass %d\n\n", pass + 1);
721
722       /* Initialize bytes_used to the space for the pred/succ lists,
723          and the reg_set_table data.  */
724       bytes_used = initial_bytes_used;
725
726       /* Each pass may create new registers, so recalculate each time.  */
727       max_gcse_regno = max_reg_num ();
728
729       alloc_gcse_mem (f);
730
731       /* Don't allow constant propagation to modify jumps
732          during this pass.  */
733       changed = one_cprop_pass (pass + 1, 0);
734
735       if (optimize_size)
736         changed |= one_classic_gcse_pass (pass + 1);
737       else
738         {
739           changed |= one_pre_gcse_pass (pass + 1);
740           free_reg_set_mem ();
741           alloc_reg_set_mem (max_reg_num ());
742           compute_sets (f);
743           run_jump_opt_after_gcse = 1;
744         }
745
746       if (max_pass_bytes < bytes_used)
747         max_pass_bytes = bytes_used;
748
749       /* Free up memory, then reallocate for code hoisting.  We can
750          not re-use the existing allocated memory because the tables
751          will not have info for the insns or registers created by
752          partial redundancy elimination.  */
753       free_gcse_mem ();
754
755       /* It does not make sense to run code hoisting unless we optimizing
756          for code size -- it rarely makes programs faster, and can make
757          them bigger if we did partial redundancy elimination (when optimizing
758          for space, we use a classic gcse algorithm instead of partial
759          redundancy algorithms).  */
760       if (optimize_size)
761         {
762           max_gcse_regno = max_reg_num ();
763           alloc_gcse_mem (f);
764           changed |= one_code_hoisting_pass ();
765           free_gcse_mem ();
766
767           if (max_pass_bytes < bytes_used)
768             max_pass_bytes = bytes_used;
769         }
770
771       if (file)
772         {
773           fprintf (file, "\n");
774           fflush (file);
775         }
776
777       obstack_free (&gcse_obstack, gcse_obstack_bottom);
778       pass++;
779     }
780
781   /* Do one last pass of copy propagation, including cprop into
782      conditional jumps.  */
783
784   max_gcse_regno = max_reg_num ();
785   alloc_gcse_mem (f);
786   /* This time, go ahead and allow cprop to alter jumps.  */
787   one_cprop_pass (pass + 1, 1);
788   free_gcse_mem ();
789
790   if (file)
791     {
792       fprintf (file, "GCSE of %s: %d basic blocks, ",
793                current_function_name, n_basic_blocks);
794       fprintf (file, "%d pass%s, %d bytes\n\n",
795                pass, pass > 1 ? "es" : "", max_pass_bytes);
796     }
797
798   obstack_free (&gcse_obstack, NULL_PTR);
799   free_reg_set_mem ();
800   return run_jump_opt_after_gcse;
801 }
802 \f
803 /* Misc. utilities.  */
804
805 /* Compute which modes support reg/reg copy operations.  */
806
807 static void
808 compute_can_copy ()
809 {
810   int i;
811 #ifndef AVOID_CCMODE_COPIES
812   rtx reg,insn;
813 #endif
814   char *free_point = (char *) oballoc (1);
815
816   bzero (can_copy_p, NUM_MACHINE_MODES);
817
818   start_sequence ();
819   for (i = 0; i < NUM_MACHINE_MODES; i++)
820     if (GET_MODE_CLASS (i) == MODE_CC)
821       {
822 #ifdef AVOID_CCMODE_COPIES
823         can_copy_p[i] = 0;
824 #else
825         reg = gen_rtx_REG ((enum machine_mode) i, LAST_VIRTUAL_REGISTER + 1);
826         insn = emit_insn (gen_rtx_SET (VOIDmode, reg, reg));
827         if (recog (PATTERN (insn), insn, NULL_PTR) >= 0)
828           can_copy_p[i] = 1;
829 #endif
830       }
831     else
832       can_copy_p[i] = 1;
833
834   end_sequence ();
835
836   /* Free the objects we just allocated.  */
837   obfree (free_point);
838 }
839 \f
840 /* Cover function to xmalloc to record bytes allocated.  */
841
842 static char *
843 gmalloc (size)
844      unsigned int size;
845 {
846   bytes_used += size;
847   return xmalloc (size);
848 }
849
850 /* Cover function to xrealloc.
851    We don't record the additional size since we don't know it.
852    It won't affect memory usage stats much anyway.  */
853
854 static char *
855 grealloc (ptr, size)
856      char *ptr;
857      unsigned int size;
858 {
859   return xrealloc (ptr, size);
860 }
861
862 /* Cover function to obstack_alloc.
863    We don't need to record the bytes allocated here since
864    obstack_chunk_alloc is set to gmalloc.  */
865
866 static char *
867 gcse_alloc (size)
868      unsigned long size;
869 {
870   return (char *) obstack_alloc (&gcse_obstack, size);
871 }
872
873 /* Allocate memory for the cuid mapping array,
874    and reg/memory set tracking tables.
875
876    This is called at the start of each pass.  */
877
878 static void
879 alloc_gcse_mem (f)
880      rtx f;
881 {
882   int i,n;
883   rtx insn;
884
885   /* Find the largest UID and create a mapping from UIDs to CUIDs.
886      CUIDs are like UIDs except they increase monotonically, have no gaps,
887      and only apply to real insns.  */
888
889   max_uid = get_max_uid ();
890   n = (max_uid + 1) * sizeof (int);
891   uid_cuid = (int *) gmalloc (n);
892   bzero ((char *) uid_cuid, n);
893   for (insn = f, i = 0; insn; insn = NEXT_INSN (insn))
894     {
895       if (INSN_P (insn))
896         uid_cuid[INSN_UID (insn)] = i++;
897       else
898         uid_cuid[INSN_UID (insn)] = i;
899     }
900
901   /* Create a table mapping cuids to insns.  */
902
903   max_cuid = i;
904   n = (max_cuid + 1) * sizeof (rtx);
905   cuid_insn = (rtx *) gmalloc (n);
906   bzero ((char *) cuid_insn, n);
907   for (insn = f, i = 0; insn; insn = NEXT_INSN (insn))
908     if (INSN_P (insn))
909       CUID_INSN (i++) = insn;
910
911   /* Allocate vars to track sets of regs.  */
912   reg_set_bitmap = (sbitmap) sbitmap_alloc (max_gcse_regno);
913
914   /* Allocate vars to track sets of regs, memory per block.  */
915   reg_set_in_block = (sbitmap *) sbitmap_vector_alloc (n_basic_blocks,
916                                                        max_gcse_regno);
917   mem_set_in_block = (char *) gmalloc (n_basic_blocks);
918 }
919
920 /* Free memory allocated by alloc_gcse_mem.  */
921
922 static void
923 free_gcse_mem ()
924 {
925   free (uid_cuid);
926   free (cuid_insn);
927
928   free (reg_set_bitmap);
929
930   free (reg_set_in_block);
931   free (mem_set_in_block);
932 }
933
934 /* Many of the global optimization algorithms work by solving dataflow
935    equations for various expressions.  Initially, some local value is
936    computed for each expression in each block.  Then, the values across the
937    various blocks are combined (by following flow graph edges) to arrive at
938    global values.  Conceptually, each set of equations is independent.  We
939    may therefore solve all the equations in parallel, solve them one at a
940    time, or pick any intermediate approach.
941
942    When you're going to need N two-dimensional bitmaps, each X (say, the
943    number of blocks) by Y (say, the number of expressions), call this
944    function.  It's not important what X and Y represent; only that Y
945    correspond to the things that can be done in parallel.  This function will
946    return an appropriate chunking factor C; you should solve C sets of
947    equations in parallel.  By going through this function, we can easily
948    trade space against time; by solving fewer equations in parallel we use
949    less space.  */
950
951 static int
952 get_bitmap_width (n, x, y)
953      int n;
954      int x;
955      int y;
956 {
957   /* It's not really worth figuring out *exactly* how much memory will
958      be used by a particular choice.  The important thing is to get
959      something approximately right.  */
960   size_t max_bitmap_memory = 10 * 1024 * 1024;
961
962   /* The number of bytes we'd use for a single column of minimum
963      width.  */
964   size_t column_size = n * x * sizeof (SBITMAP_ELT_TYPE);
965
966   /* Often, it's reasonable just to solve all the equations in
967      parallel.  */
968   if (column_size * SBITMAP_SET_SIZE (y) <= max_bitmap_memory)
969     return y;
970
971   /* Otherwise, pick the largest width we can, without going over the
972      limit.  */
973   return SBITMAP_ELT_BITS * ((max_bitmap_memory + column_size - 1)
974                              / column_size);
975 }
976 \f
977 /* Compute the local properties of each recorded expression.
978
979    Local properties are those that are defined by the block, irrespective of
980    other blocks.
981
982    An expression is transparent in a block if its operands are not modified
983    in the block.
984
985    An expression is computed (locally available) in a block if it is computed
986    at least once and expression would contain the same value if the
987    computation was moved to the end of the block.
988
989    An expression is locally anticipatable in a block if it is computed at
990    least once and expression would contain the same value if the computation
991    was moved to the beginning of the block.
992
993    We call this routine for cprop, pre and code hoisting.  They all compute
994    basically the same information and thus can easily share this code.
995
996    TRANSP, COMP, and ANTLOC are destination sbitmaps for recording local
997    properties.  If NULL, then it is not necessary to compute or record that
998    particular property.
999
1000    SETP controls which hash table to look at.  If zero, this routine looks at
1001    the expr hash table; if nonzero this routine looks at the set hash table.
1002    Additionally, TRANSP is computed as ~TRANSP, since this is really cprop's
1003    ABSALTERED.  */
1004  
1005 static void
1006 compute_local_properties (transp, comp, antloc, setp)
1007      sbitmap *transp;
1008      sbitmap *comp;
1009      sbitmap *antloc;
1010      int setp;
1011 {
1012   unsigned int i, hash_table_size;
1013   struct expr **hash_table;
1014   
1015   /* Initialize any bitmaps that were passed in.  */
1016   if (transp)
1017     {
1018       if (setp)
1019         sbitmap_vector_zero (transp, n_basic_blocks);
1020       else
1021         sbitmap_vector_ones (transp, n_basic_blocks);
1022     }
1023
1024   if (comp)
1025     sbitmap_vector_zero (comp, n_basic_blocks);
1026   if (antloc)
1027     sbitmap_vector_zero (antloc, n_basic_blocks);
1028
1029   /* We use the same code for cprop, pre and hoisting.  For cprop
1030      we care about the set hash table, for pre and hoisting we
1031      care about the expr hash table.  */
1032   hash_table_size = setp ? set_hash_table_size : expr_hash_table_size;
1033   hash_table = setp ? set_hash_table : expr_hash_table;
1034
1035   for (i = 0; i < hash_table_size; i++)
1036     {
1037       struct expr *expr;
1038
1039       for (expr = hash_table[i]; expr != NULL; expr = expr->next_same_hash)
1040         {
1041           int indx = expr->bitmap_index;
1042           struct occr *occr;
1043
1044           /* The expression is transparent in this block if it is not killed.
1045              We start by assuming all are transparent [none are killed], and
1046              then reset the bits for those that are.  */
1047           if (transp)
1048             compute_transp (expr->expr, indx, transp, setp);
1049
1050           /* The occurrences recorded in antic_occr are exactly those that
1051              we want to set to non-zero in ANTLOC.  */
1052           if (antloc)
1053             for (occr = expr->antic_occr; occr != NULL; occr = occr->next)
1054               {
1055                 SET_BIT (antloc[BLOCK_NUM (occr->insn)], indx);
1056
1057                 /* While we're scanning the table, this is a good place to
1058                    initialize this.  */
1059                 occr->deleted_p = 0;
1060               }
1061
1062           /* The occurrences recorded in avail_occr are exactly those that
1063              we want to set to non-zero in COMP.  */
1064           if (comp)
1065             for (occr = expr->avail_occr; occr != NULL; occr = occr->next)
1066               {
1067                 SET_BIT (comp[BLOCK_NUM (occr->insn)], indx);
1068
1069                 /* While we're scanning the table, this is a good place to
1070                    initialize this.  */
1071                 occr->copied_p = 0;
1072               }
1073
1074           /* While we're scanning the table, this is a good place to
1075              initialize this.  */
1076           expr->reaching_reg = 0;
1077         }
1078     }
1079 }
1080 \f
1081 /* Register set information.
1082
1083    `reg_set_table' records where each register is set or otherwise
1084    modified.  */
1085
1086 static struct obstack reg_set_obstack;
1087
1088 static void
1089 alloc_reg_set_mem (n_regs)
1090      int n_regs;
1091 {
1092   unsigned int n;
1093
1094   reg_set_table_size = n_regs + REG_SET_TABLE_SLOP;
1095   n = reg_set_table_size * sizeof (struct reg_set *);
1096   reg_set_table = (struct reg_set **) gmalloc (n);
1097   bzero ((char *) reg_set_table, n);
1098
1099   gcc_obstack_init (&reg_set_obstack);
1100 }
1101
1102 static void
1103 free_reg_set_mem ()
1104 {
1105   free (reg_set_table);
1106   obstack_free (&reg_set_obstack, NULL_PTR);
1107 }
1108
1109 /* Record REGNO in the reg_set table.  */
1110
1111 static void
1112 record_one_set (regno, insn)
1113      int regno;
1114      rtx insn;
1115 {
1116   /* allocate a new reg_set element and link it onto the list */
1117   struct reg_set *new_reg_info;
1118
1119   /* If the table isn't big enough, enlarge it.  */
1120   if (regno >= reg_set_table_size)
1121     {
1122       int new_size = regno + REG_SET_TABLE_SLOP;
1123
1124       reg_set_table
1125         = (struct reg_set **) grealloc ((char *) reg_set_table,
1126                                         new_size * sizeof (struct reg_set *));
1127       bzero ((char *) (reg_set_table + reg_set_table_size),
1128              (new_size - reg_set_table_size) * sizeof (struct reg_set *));
1129       reg_set_table_size = new_size;
1130     }
1131
1132   new_reg_info = (struct reg_set *) obstack_alloc (&reg_set_obstack,
1133                                                    sizeof (struct reg_set));
1134   bytes_used += sizeof (struct reg_set);
1135   new_reg_info->insn = insn;
1136   new_reg_info->next = reg_set_table[regno];
1137   reg_set_table[regno] = new_reg_info;
1138 }
1139
1140 /* Called from compute_sets via note_stores to handle one SET or CLOBBER in
1141    an insn.  The DATA is really the instruction in which the SET is
1142    occurring.  */
1143
1144 static void
1145 record_set_info (dest, setter, data)
1146      rtx dest, setter ATTRIBUTE_UNUSED;
1147      void *data;
1148 {
1149   rtx record_set_insn = (rtx) data;
1150
1151   if (GET_CODE (dest) == REG && REGNO (dest) >= FIRST_PSEUDO_REGISTER)
1152     record_one_set (REGNO (dest), record_set_insn);
1153 }
1154
1155 /* Scan the function and record each set of each pseudo-register.
1156
1157    This is called once, at the start of the gcse pass.  See the comments for
1158    `reg_set_table' for further documenation.  */
1159
1160 static void
1161 compute_sets (f)
1162      rtx f;
1163 {
1164   rtx insn;
1165
1166   for (insn = f; insn != 0; insn = NEXT_INSN (insn))
1167     if (INSN_P (insn))
1168       note_stores (PATTERN (insn), record_set_info, insn);
1169 }
1170 \f
1171 /* Hash table support.  */
1172
1173 /* For each register, the cuid of the first/last insn in the block to set it,
1174    or -1 if not set.  */
1175 #define NEVER_SET -1
1176 static int *reg_first_set;
1177 static int *reg_last_set;
1178
1179 /* While computing "first/last set" info, this is the CUID of first/last insn
1180    to set memory or -1 if not set.  `mem_last_set' is also used when
1181    performing GCSE to record whether memory has been set since the beginning
1182    of the block.
1183
1184    Note that handling of memory is very simple, we don't make any attempt
1185    to optimize things (later).  */
1186 static int mem_first_set;
1187 static int mem_last_set;
1188
1189 /* Perform a quick check whether X, the source of a set, is something
1190    we want to consider for GCSE.  */
1191
1192 static int
1193 want_to_gcse_p (x)
1194      rtx x;
1195 {
1196   switch (GET_CODE (x))
1197     {
1198     case REG:
1199     case SUBREG:
1200     case CONST_INT:
1201     case CONST_DOUBLE:
1202     case CALL:
1203       return 0;
1204
1205     default:
1206       break;
1207     }
1208
1209   return 1;
1210 }
1211
1212 /* Return non-zero if the operands of expression X are unchanged from the
1213    start of INSN's basic block up to but not including INSN (if AVAIL_P == 0),
1214    or from INSN to the end of INSN's basic block (if AVAIL_P != 0).  */
1215
1216 static int
1217 oprs_unchanged_p (x, insn, avail_p)
1218      rtx x, insn;
1219      int avail_p;
1220 {
1221   int i, j;
1222   enum rtx_code code;
1223   const char *fmt;
1224
1225   if (x == 0)
1226     return 1;
1227
1228   code = GET_CODE (x);
1229   switch (code)
1230     {
1231     case REG:
1232       if (avail_p)
1233         return (reg_last_set[REGNO (x)] == NEVER_SET
1234                 || reg_last_set[REGNO (x)] < INSN_CUID (insn));
1235       else
1236         return (reg_first_set[REGNO (x)] == NEVER_SET
1237                 || reg_first_set[REGNO (x)] >= INSN_CUID (insn));
1238
1239     case MEM:
1240       if (avail_p && mem_last_set != NEVER_SET
1241           && mem_last_set >= INSN_CUID (insn))
1242         return 0;
1243       else if (! avail_p && mem_first_set != NEVER_SET
1244                && mem_first_set < INSN_CUID (insn))
1245         return 0;
1246       else
1247         return oprs_unchanged_p (XEXP (x, 0), insn, avail_p);
1248
1249     case PRE_DEC:
1250     case PRE_INC:
1251     case POST_DEC:
1252     case POST_INC:
1253     case PRE_MODIFY:
1254     case POST_MODIFY:
1255       return 0;
1256
1257     case PC:
1258     case CC0: /*FIXME*/
1259     case CONST:
1260     case CONST_INT:
1261     case CONST_DOUBLE:
1262     case SYMBOL_REF:
1263     case LABEL_REF:
1264     case ADDR_VEC:
1265     case ADDR_DIFF_VEC:
1266       return 1;
1267
1268     default:
1269       break;
1270     }
1271
1272   for (i = GET_RTX_LENGTH (code) - 1, fmt = GET_RTX_FORMAT (code); i >= 0; i--)
1273     {
1274       if (fmt[i] == 'e')
1275         {
1276           /* If we are about to do the last recursive call needed at this
1277              level, change it into iteration.  This function is called enough
1278              to be worth it.  */
1279           if (i == 0)
1280             return oprs_unchanged_p (XEXP (x, i), insn, avail_p);
1281
1282           else if (! oprs_unchanged_p (XEXP (x, i), insn, avail_p))
1283             return 0;
1284         }
1285       else if (fmt[i] == 'E')
1286         for (j = 0; j < XVECLEN (x, i); j++)
1287           if (! oprs_unchanged_p (XVECEXP (x, i, j), insn, avail_p))
1288             return 0;
1289     }
1290
1291   return 1;
1292 }
1293
1294 /* Return non-zero if the operands of expression X are unchanged from
1295    the start of INSN's basic block up to but not including INSN.  */
1296
1297 static int
1298 oprs_anticipatable_p (x, insn)
1299      rtx x, insn;
1300 {
1301   return oprs_unchanged_p (x, insn, 0);
1302 }
1303
1304 /* Return non-zero if the operands of expression X are unchanged from
1305    INSN to the end of INSN's basic block.  */
1306
1307 static int
1308 oprs_available_p (x, insn)
1309      rtx x, insn;
1310 {
1311   return oprs_unchanged_p (x, insn, 1);
1312 }
1313
1314 /* Hash expression X.
1315
1316    MODE is only used if X is a CONST_INT.  DO_NOT_RECORD_P is a boolean
1317    indicating if a volatile operand is found or if the expression contains
1318    something we don't want to insert in the table.
1319
1320    ??? One might want to merge this with canon_hash.  Later.  */
1321
1322 static unsigned int
1323 hash_expr (x, mode, do_not_record_p, hash_table_size)
1324      rtx x;
1325      enum machine_mode mode;
1326      int *do_not_record_p;
1327      int hash_table_size;
1328 {
1329   unsigned int hash;
1330
1331   *do_not_record_p = 0;
1332
1333   hash = hash_expr_1 (x, mode, do_not_record_p);
1334   return hash % hash_table_size;
1335 }
1336 /* Hash a string.  Just add its bytes up.  */
1337 static inline unsigned
1338 hash_string_1 (ps)
1339      const char *ps;
1340 {
1341   unsigned hash = 0;
1342   const unsigned char *p = (const unsigned char *)ps;
1343   
1344   if (p)
1345     while (*p)
1346       hash += *p++;
1347
1348   return hash;
1349 }
1350
1351 /* Subroutine of hash_expr to do the actual work.  */
1352
1353 static unsigned int
1354 hash_expr_1 (x, mode, do_not_record_p)
1355      rtx x;
1356      enum machine_mode mode;
1357      int *do_not_record_p;
1358 {
1359   int i, j;
1360   unsigned hash = 0;
1361   enum rtx_code code;
1362   const char *fmt;
1363
1364   /* Used to turn recursion into iteration.  We can't rely on GCC's
1365      tail-recursion eliminatio since we need to keep accumulating values
1366      in HASH.  */
1367
1368   if (x == 0)
1369     return hash;
1370
1371  repeat:
1372   code = GET_CODE (x);
1373   switch (code)
1374     {
1375     case REG:
1376       hash += ((unsigned int) REG << 7) + REGNO (x);
1377       return hash;
1378
1379     case CONST_INT:
1380       hash += (((unsigned int) CONST_INT << 7) + (unsigned int) mode
1381                + (unsigned int) INTVAL (x));
1382       return hash;
1383
1384     case CONST_DOUBLE:
1385       /* This is like the general case, except that it only counts
1386          the integers representing the constant.  */
1387       hash += (unsigned int) code + (unsigned int) GET_MODE (x);
1388       if (GET_MODE (x) != VOIDmode)
1389         for (i = 2; i < GET_RTX_LENGTH (CONST_DOUBLE); i++)
1390           hash += (unsigned int) XWINT (x, i);
1391       else
1392         hash += ((unsigned int) CONST_DOUBLE_LOW (x)
1393                  + (unsigned int) CONST_DOUBLE_HIGH (x));
1394       return hash;
1395
1396       /* Assume there is only one rtx object for any given label.  */
1397     case LABEL_REF:
1398       /* We don't hash on the address of the CODE_LABEL to avoid bootstrap
1399          differences and differences between each stage's debugging dumps.  */
1400       hash += (((unsigned int) LABEL_REF << 7)
1401                + CODE_LABEL_NUMBER (XEXP (x, 0)));
1402       return hash;
1403
1404     case SYMBOL_REF:
1405       {
1406         /* Don't hash on the symbol's address to avoid bootstrap differences.
1407            Different hash values may cause expressions to be recorded in
1408            different orders and thus different registers to be used in the
1409            final assembler.  This also avoids differences in the dump files
1410            between various stages.  */
1411         unsigned int h = 0;
1412         const unsigned char *p = (const unsigned char *) XSTR (x, 0);
1413
1414         while (*p)
1415           h += (h << 7) + *p++; /* ??? revisit */
1416
1417         hash += ((unsigned int) SYMBOL_REF << 7) + h;
1418         return hash;
1419       }
1420
1421     case MEM:
1422       if (MEM_VOLATILE_P (x))
1423         {
1424           *do_not_record_p = 1;
1425           return 0;
1426         }
1427
1428       hash += (unsigned int) MEM;
1429       hash += MEM_ALIAS_SET (x);
1430       x = XEXP (x, 0);
1431       goto repeat;
1432
1433     case PRE_DEC:
1434     case PRE_INC:
1435     case POST_DEC:
1436     case POST_INC:
1437     case PC:
1438     case CC0:
1439     case CALL:
1440     case UNSPEC_VOLATILE:
1441       *do_not_record_p = 1;
1442       return 0;
1443
1444     case ASM_OPERANDS:
1445       if (MEM_VOLATILE_P (x))
1446         {
1447           *do_not_record_p = 1;
1448           return 0;
1449         }
1450       else
1451         {
1452           /* We don't want to take the filename and line into account.  */
1453           hash += (unsigned) code + (unsigned) GET_MODE (x)
1454             + hash_string_1 (ASM_OPERANDS_TEMPLATE (x))
1455             + hash_string_1 (ASM_OPERANDS_OUTPUT_CONSTRAINT (x))
1456             + (unsigned) ASM_OPERANDS_OUTPUT_IDX (x);
1457
1458           if (ASM_OPERANDS_INPUT_LENGTH (x))
1459             {
1460               for (i = 1; i < ASM_OPERANDS_INPUT_LENGTH (x); i++)
1461                 {
1462                   hash += (hash_expr_1 (ASM_OPERANDS_INPUT (x, i),
1463                                         GET_MODE (ASM_OPERANDS_INPUT (x, i)),
1464                                         do_not_record_p)
1465                            + hash_string_1 (ASM_OPERANDS_INPUT_CONSTRAINT
1466                                             (x, i)));
1467                 }
1468
1469               hash += hash_string_1 (ASM_OPERANDS_INPUT_CONSTRAINT (x, 0));
1470               x = ASM_OPERANDS_INPUT (x, 0);
1471               mode = GET_MODE (x);
1472               goto repeat;
1473             }
1474           return hash;
1475         }
1476
1477     default:
1478       break;
1479     }
1480
1481   hash += (unsigned) code + (unsigned) GET_MODE (x);
1482   for (i = GET_RTX_LENGTH (code) - 1, fmt = GET_RTX_FORMAT (code); i >= 0; i--)
1483     {
1484       if (fmt[i] == 'e')
1485         {
1486           /* If we are about to do the last recursive call
1487              needed at this level, change it into iteration.
1488              This function is called enough to be worth it.  */
1489           if (i == 0)
1490             {
1491               x = XEXP (x, i);
1492               goto repeat;
1493             }
1494
1495           hash += hash_expr_1 (XEXP (x, i), 0, do_not_record_p);
1496           if (*do_not_record_p)
1497             return 0;
1498         }
1499
1500       else if (fmt[i] == 'E')
1501         for (j = 0; j < XVECLEN (x, i); j++)
1502           {
1503             hash += hash_expr_1 (XVECEXP (x, i, j), 0, do_not_record_p);
1504             if (*do_not_record_p)
1505               return 0;
1506           }
1507
1508       else if (fmt[i] == 's')
1509         hash += hash_string_1 (XSTR (x, i));
1510       else if (fmt[i] == 'i')
1511         hash += (unsigned int) XINT (x, i);
1512       else
1513         abort ();
1514     }
1515
1516   return hash;
1517 }
1518
1519 /* Hash a set of register REGNO.
1520
1521    Sets are hashed on the register that is set.  This simplifies the PRE copy
1522    propagation code.
1523
1524    ??? May need to make things more elaborate.  Later, as necessary.  */
1525
1526 static unsigned int
1527 hash_set (regno, hash_table_size)
1528      int regno;
1529      int hash_table_size;
1530 {
1531   unsigned int hash;
1532
1533   hash = regno;
1534   return hash % hash_table_size;
1535 }
1536
1537 /* Return non-zero if exp1 is equivalent to exp2.
1538    ??? Borrowed from cse.c.  Might want to remerge with cse.c.  Later.  */
1539
1540 static int
1541 expr_equiv_p (x, y)
1542      rtx x, y;
1543 {
1544   register int i, j;
1545   register enum rtx_code code;
1546   register const char *fmt;
1547
1548   if (x == y)
1549     return 1;
1550
1551   if (x == 0 || y == 0)
1552     return x == y;
1553
1554   code = GET_CODE (x);
1555   if (code != GET_CODE (y))
1556     return 0;
1557
1558   /* (MULT:SI x y) and (MULT:HI x y) are NOT equivalent.  */
1559   if (GET_MODE (x) != GET_MODE (y))
1560     return 0;
1561
1562   switch (code)
1563     {
1564     case PC:
1565     case CC0:
1566       return x == y;
1567
1568     case CONST_INT:
1569       return INTVAL (x) == INTVAL (y);
1570
1571     case LABEL_REF:
1572       return XEXP (x, 0) == XEXP (y, 0);
1573
1574     case SYMBOL_REF:
1575       return XSTR (x, 0) == XSTR (y, 0);
1576
1577     case REG:
1578       return REGNO (x) == REGNO (y);
1579
1580     case MEM:
1581       /* Can't merge two expressions in different alias sets, since we can
1582          decide that the expression is transparent in a block when it isn't,
1583          due to it being set with the different alias set.  */
1584       if (MEM_ALIAS_SET (x) != MEM_ALIAS_SET (y))
1585         return 0;
1586       break;
1587
1588     /*  For commutative operations, check both orders.  */
1589     case PLUS:
1590     case MULT:
1591     case AND:
1592     case IOR:
1593     case XOR:
1594     case NE:
1595     case EQ:
1596       return ((expr_equiv_p (XEXP (x, 0), XEXP (y, 0))
1597                && expr_equiv_p (XEXP (x, 1), XEXP (y, 1)))
1598               || (expr_equiv_p (XEXP (x, 0), XEXP (y, 1))
1599                   && expr_equiv_p (XEXP (x, 1), XEXP (y, 0))));
1600
1601     case ASM_OPERANDS:
1602       /* We don't use the generic code below because we want to
1603          disregard filename and line numbers.  */
1604
1605       /* A volatile asm isn't equivalent to any other.  */
1606       if (MEM_VOLATILE_P (x) || MEM_VOLATILE_P (y))
1607         return 0;
1608
1609       if (GET_MODE (x) != GET_MODE (y)
1610           || strcmp (ASM_OPERANDS_TEMPLATE (x), ASM_OPERANDS_TEMPLATE (y))
1611           || strcmp (ASM_OPERANDS_OUTPUT_CONSTRAINT (x),
1612                      ASM_OPERANDS_OUTPUT_CONSTRAINT (y))
1613           || ASM_OPERANDS_OUTPUT_IDX (x) != ASM_OPERANDS_OUTPUT_IDX (y)
1614           || ASM_OPERANDS_INPUT_LENGTH (x) != ASM_OPERANDS_INPUT_LENGTH (y))
1615         return 0;
1616
1617       if (ASM_OPERANDS_INPUT_LENGTH (x))
1618         {
1619           for (i = ASM_OPERANDS_INPUT_LENGTH (x) - 1; i >= 0; i--)
1620             if (! expr_equiv_p (ASM_OPERANDS_INPUT (x, i),
1621                                 ASM_OPERANDS_INPUT (y, i))
1622                 || strcmp (ASM_OPERANDS_INPUT_CONSTRAINT (x, i),
1623                            ASM_OPERANDS_INPUT_CONSTRAINT (y, i)))
1624               return 0;
1625         }
1626
1627       return 1;
1628
1629     default:
1630       break;
1631     }
1632
1633   /* Compare the elements.  If any pair of corresponding elements
1634      fail to match, return 0 for the whole thing.  */
1635
1636   fmt = GET_RTX_FORMAT (code);
1637   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1638     {
1639       switch (fmt[i])
1640         {
1641         case 'e':
1642           if (! expr_equiv_p (XEXP (x, i), XEXP (y, i)))
1643             return 0;
1644           break;
1645
1646         case 'E':
1647           if (XVECLEN (x, i) != XVECLEN (y, i))
1648             return 0;
1649           for (j = 0; j < XVECLEN (x, i); j++)
1650             if (! expr_equiv_p (XVECEXP (x, i, j), XVECEXP (y, i, j)))
1651               return 0;
1652           break;
1653
1654         case 's':
1655           if (strcmp (XSTR (x, i), XSTR (y, i)))
1656             return 0;
1657           break;
1658
1659         case 'i':
1660           if (XINT (x, i) != XINT (y, i))
1661             return 0;
1662           break;
1663
1664         case 'w':
1665           if (XWINT (x, i) != XWINT (y, i))
1666             return 0;
1667         break;
1668
1669         case '0':
1670           break;
1671
1672         default:
1673           abort ();
1674         }
1675       }
1676
1677   return 1;
1678 }
1679
1680 /* Insert expression X in INSN in the hash table.
1681    If it is already present, record it as the last occurrence in INSN's
1682    basic block.
1683
1684    MODE is the mode of the value X is being stored into.
1685    It is only used if X is a CONST_INT.
1686
1687    ANTIC_P is non-zero if X is an anticipatable expression.
1688    AVAIL_P is non-zero if X is an available expression.  */
1689
1690 static void
1691 insert_expr_in_table (x, mode, insn, antic_p, avail_p)
1692      rtx x;
1693      enum machine_mode mode;
1694      rtx insn;
1695      int antic_p, avail_p;
1696 {
1697   int found, do_not_record_p;
1698   unsigned int hash;
1699   struct expr *cur_expr, *last_expr = NULL;
1700   struct occr *antic_occr, *avail_occr;
1701   struct occr *last_occr = NULL;
1702
1703   hash = hash_expr (x, mode, &do_not_record_p, expr_hash_table_size);
1704
1705   /* Do not insert expression in table if it contains volatile operands,
1706      or if hash_expr determines the expression is something we don't want
1707      to or can't handle.  */
1708   if (do_not_record_p)
1709     return;
1710
1711   cur_expr = expr_hash_table[hash];
1712   found = 0;
1713
1714   while (cur_expr && 0 == (found = expr_equiv_p (cur_expr->expr, x)))
1715     {
1716       /* If the expression isn't found, save a pointer to the end of
1717          the list.  */
1718       last_expr = cur_expr;
1719       cur_expr = cur_expr->next_same_hash;
1720     }
1721
1722   if (! found)
1723     {
1724       cur_expr = (struct expr *) gcse_alloc (sizeof (struct expr));
1725       bytes_used += sizeof (struct expr);
1726       if (expr_hash_table[hash] == NULL)
1727         /* This is the first pattern that hashed to this index.  */
1728         expr_hash_table[hash] = cur_expr;
1729       else
1730         /* Add EXPR to end of this hash chain.  */
1731         last_expr->next_same_hash = cur_expr;
1732
1733       /* Set the fields of the expr element.  */ 
1734       cur_expr->expr = x;
1735       cur_expr->bitmap_index = n_exprs++;
1736       cur_expr->next_same_hash = NULL;
1737       cur_expr->antic_occr = NULL;
1738       cur_expr->avail_occr = NULL;
1739     }
1740
1741   /* Now record the occurrence(s).  */
1742   if (antic_p)
1743     {
1744       antic_occr = cur_expr->antic_occr;
1745
1746       /* Search for another occurrence in the same basic block.  */
1747       while (antic_occr && BLOCK_NUM (antic_occr->insn) != BLOCK_NUM (insn))
1748         {
1749           /* If an occurrence isn't found, save a pointer to the end of
1750              the list.  */
1751           last_occr = antic_occr;
1752           antic_occr = antic_occr->next;
1753         }
1754
1755       if (antic_occr)
1756         /* Found another instance of the expression in the same basic block.
1757            Prefer the currently recorded one.  We want the first one in the
1758            block and the block is scanned from start to end.  */
1759         ; /* nothing to do */
1760       else
1761         {
1762           /* First occurrence of this expression in this basic block.  */
1763           antic_occr = (struct occr *) gcse_alloc (sizeof (struct occr));
1764           bytes_used += sizeof (struct occr);
1765           /* First occurrence of this expression in any block?  */
1766           if (cur_expr->antic_occr == NULL)
1767             cur_expr->antic_occr = antic_occr;
1768           else
1769             last_occr->next = antic_occr;
1770
1771           antic_occr->insn = insn;
1772           antic_occr->next = NULL;
1773         }
1774     }
1775
1776   if (avail_p)
1777     {
1778       avail_occr = cur_expr->avail_occr;
1779
1780       /* Search for another occurrence in the same basic block.  */
1781       while (avail_occr && BLOCK_NUM (avail_occr->insn) != BLOCK_NUM (insn))
1782         {
1783           /* If an occurrence isn't found, save a pointer to the end of
1784              the list.  */
1785           last_occr = avail_occr;
1786           avail_occr = avail_occr->next;
1787         }
1788
1789       if (avail_occr)
1790         /* Found another instance of the expression in the same basic block.
1791            Prefer this occurrence to the currently recorded one.  We want
1792            the last one in the block and the block is scanned from start
1793            to end.  */
1794         avail_occr->insn = insn;
1795       else
1796         {
1797           /* First occurrence of this expression in this basic block.  */
1798           avail_occr = (struct occr *) gcse_alloc (sizeof (struct occr));
1799           bytes_used += sizeof (struct occr);
1800
1801           /* First occurrence of this expression in any block?  */
1802           if (cur_expr->avail_occr == NULL)
1803             cur_expr->avail_occr = avail_occr;
1804           else
1805             last_occr->next = avail_occr;
1806
1807           avail_occr->insn = insn;
1808           avail_occr->next = NULL;
1809         }
1810     }
1811 }
1812
1813 /* Insert pattern X in INSN in the hash table.
1814    X is a SET of a reg to either another reg or a constant.
1815    If it is already present, record it as the last occurrence in INSN's
1816    basic block.  */
1817
1818 static void
1819 insert_set_in_table (x, insn)
1820      rtx x;
1821      rtx insn;
1822 {
1823   int found;
1824   unsigned int hash;
1825   struct expr *cur_expr, *last_expr = NULL;
1826   struct occr *cur_occr, *last_occr = NULL;
1827
1828   if (GET_CODE (x) != SET
1829       || GET_CODE (SET_DEST (x)) != REG)
1830     abort ();
1831
1832   hash = hash_set (REGNO (SET_DEST (x)), set_hash_table_size);
1833
1834   cur_expr = set_hash_table[hash];
1835   found = 0;
1836
1837   while (cur_expr && 0 == (found = expr_equiv_p (cur_expr->expr, x)))
1838     {
1839       /* If the expression isn't found, save a pointer to the end of
1840          the list.  */
1841       last_expr = cur_expr;
1842       cur_expr = cur_expr->next_same_hash;
1843     }
1844
1845   if (! found)
1846     {
1847       cur_expr = (struct expr *) gcse_alloc (sizeof (struct expr));
1848       bytes_used += sizeof (struct expr);
1849       if (set_hash_table[hash] == NULL)
1850         /* This is the first pattern that hashed to this index.  */
1851         set_hash_table[hash] = cur_expr;
1852       else
1853         /* Add EXPR to end of this hash chain.  */
1854         last_expr->next_same_hash = cur_expr;
1855
1856       /* Set the fields of the expr element.
1857          We must copy X because it can be modified when copy propagation is
1858          performed on its operands.  */
1859       /* ??? Should this go in a different obstack?  */
1860       cur_expr->expr = copy_rtx (x);
1861       cur_expr->bitmap_index = n_sets++;
1862       cur_expr->next_same_hash = NULL;
1863       cur_expr->antic_occr = NULL;
1864       cur_expr->avail_occr = NULL;
1865     }
1866
1867   /* Now record the occurrence.  */
1868   cur_occr = cur_expr->avail_occr;
1869
1870   /* Search for another occurrence in the same basic block.  */
1871   while (cur_occr && BLOCK_NUM (cur_occr->insn) != BLOCK_NUM (insn))
1872     {
1873       /* If an occurrence isn't found, save a pointer to the end of
1874          the list.  */
1875       last_occr = cur_occr;
1876       cur_occr = cur_occr->next;
1877     }
1878
1879   if (cur_occr)
1880     /* Found another instance of the expression in the same basic block.
1881        Prefer this occurrence to the currently recorded one.  We want the
1882        last one in the block and the block is scanned from start to end.  */
1883     cur_occr->insn = insn;
1884   else
1885     {
1886       /* First occurrence of this expression in this basic block.  */
1887       cur_occr = (struct occr *) gcse_alloc (sizeof (struct occr));
1888       bytes_used += sizeof (struct occr);
1889
1890       /* First occurrence of this expression in any block?  */
1891       if (cur_expr->avail_occr == NULL)
1892         cur_expr->avail_occr = cur_occr;
1893       else
1894         last_occr->next = cur_occr;
1895
1896       cur_occr->insn = insn;
1897       cur_occr->next = NULL;
1898     }
1899 }
1900
1901 /* Scan pattern PAT of INSN and add an entry to the hash table.  If SET_P is
1902    non-zero, this is for the assignment hash table, otherwise it is for the
1903    expression hash table.  */
1904
1905 static void
1906 hash_scan_set (pat, insn, set_p)
1907      rtx pat, insn;
1908      int set_p;
1909 {
1910   rtx src = SET_SRC (pat);
1911   rtx dest = SET_DEST (pat);
1912
1913   if (GET_CODE (src) == CALL)
1914     hash_scan_call (src, insn);
1915
1916   if (GET_CODE (dest) == REG)
1917     {
1918       int regno = REGNO (dest);
1919       rtx tmp;
1920
1921       /* Only record sets of pseudo-regs in the hash table.  */
1922       if (! set_p
1923           && regno >= FIRST_PSEUDO_REGISTER
1924           /* Don't GCSE something if we can't do a reg/reg copy.  */
1925           && can_copy_p [GET_MODE (dest)]
1926           /* Is SET_SRC something we want to gcse?  */
1927           && want_to_gcse_p (src))
1928         {
1929           /* An expression is not anticipatable if its operands are
1930              modified before this insn.  */
1931           int antic_p = oprs_anticipatable_p (src, insn);
1932           /* An expression is not available if its operands are
1933              subsequently modified, including this insn.  */
1934           int avail_p = oprs_available_p (src, insn);
1935
1936           insert_expr_in_table (src, GET_MODE (dest), insn, antic_p, avail_p);
1937         }
1938
1939       /* Record sets for constant/copy propagation.  */
1940       else if (set_p
1941                && regno >= FIRST_PSEUDO_REGISTER
1942                && ((GET_CODE (src) == REG
1943                     && REGNO (src) >= FIRST_PSEUDO_REGISTER
1944                     && can_copy_p [GET_MODE (dest)])
1945                    || GET_CODE (src) == CONST_INT
1946                    || GET_CODE (src) == SYMBOL_REF
1947                    || GET_CODE (src) == CONST_DOUBLE)
1948                /* A copy is not available if its src or dest is subsequently
1949                   modified.  Here we want to search from INSN+1 on, but
1950                   oprs_available_p searches from INSN on.  */
1951                && (insn == BLOCK_END (BLOCK_NUM (insn))
1952                    || ((tmp = next_nonnote_insn (insn)) != NULL_RTX
1953                        && oprs_available_p (pat, tmp))))
1954         insert_set_in_table (pat, insn);
1955     }
1956 }
1957
1958 static void
1959 hash_scan_clobber (x, insn)
1960      rtx x ATTRIBUTE_UNUSED, insn ATTRIBUTE_UNUSED;
1961 {
1962   /* Currently nothing to do.  */
1963 }
1964
1965 static void
1966 hash_scan_call (x, insn)
1967      rtx x ATTRIBUTE_UNUSED, insn ATTRIBUTE_UNUSED;
1968 {
1969   /* Currently nothing to do.  */
1970 }
1971
1972 /* Process INSN and add hash table entries as appropriate.
1973
1974    Only available expressions that set a single pseudo-reg are recorded.
1975
1976    Single sets in a PARALLEL could be handled, but it's an extra complication
1977    that isn't dealt with right now.  The trick is handling the CLOBBERs that
1978    are also in the PARALLEL.  Later.
1979
1980    If SET_P is non-zero, this is for the assignment hash table,
1981    otherwise it is for the expression hash table.
1982    If IN_LIBCALL_BLOCK nonzero, we are in a libcall block, and should
1983    not record any expressions.  */
1984
1985 static void
1986 hash_scan_insn (insn, set_p, in_libcall_block)
1987      rtx insn;
1988      int set_p;
1989      int in_libcall_block;
1990 {
1991   rtx pat = PATTERN (insn);
1992   int i;
1993
1994   /* Pick out the sets of INSN and for other forms of instructions record
1995      what's been modified.  */
1996
1997   if (GET_CODE (pat) == SET && ! in_libcall_block)
1998     {
1999       /* Ignore obvious no-ops.  */
2000       if (SET_SRC (pat) != SET_DEST (pat))
2001         hash_scan_set (pat, insn, set_p);
2002     }
2003   else if (GET_CODE (pat) == PARALLEL)
2004     for (i = 0; i < XVECLEN (pat, 0); i++)
2005       {
2006         rtx x = XVECEXP (pat, 0, i);
2007
2008         if (GET_CODE (x) == SET)
2009           {
2010             if (GET_CODE (SET_SRC (x)) == CALL)
2011               hash_scan_call (SET_SRC (x), insn);
2012           }
2013         else if (GET_CODE (x) == CLOBBER)
2014           hash_scan_clobber (x, insn);
2015         else if (GET_CODE (x) == CALL)
2016           hash_scan_call (x, insn);
2017       }
2018
2019   else if (GET_CODE (pat) == CLOBBER)
2020     hash_scan_clobber (pat, insn);
2021   else if (GET_CODE (pat) == CALL)
2022     hash_scan_call (pat, insn);
2023 }
2024
2025 static void
2026 dump_hash_table (file, name, table, table_size, total_size)
2027      FILE *file;
2028      const char *name;
2029      struct expr **table;
2030      int table_size, total_size;
2031 {
2032   int i;
2033   /* Flattened out table, so it's printed in proper order.  */
2034   struct expr **flat_table;
2035   unsigned int *hash_val;
2036   struct expr *expr;
2037
2038   flat_table 
2039     = (struct expr **) xcalloc (total_size, sizeof (struct expr *));
2040   hash_val = (unsigned int *) xmalloc (total_size * sizeof (unsigned int));
2041
2042   for (i = 0; i < table_size; i++)
2043     for (expr = table[i]; expr != NULL; expr = expr->next_same_hash)
2044       {
2045         flat_table[expr->bitmap_index] = expr;
2046         hash_val[expr->bitmap_index] = i;
2047       }
2048
2049   fprintf (file, "%s hash table (%d buckets, %d entries)\n",
2050            name, table_size, total_size);
2051
2052   for (i = 0; i < total_size; i++)
2053     if (flat_table[i] != 0)
2054       {
2055         expr = flat_table[i];
2056         fprintf (file, "Index %d (hash value %d)\n  ",
2057                  expr->bitmap_index, hash_val[i]);
2058         print_rtl (file, expr->expr);
2059         fprintf (file, "\n");
2060       }
2061
2062   fprintf (file, "\n");
2063
2064   free (flat_table);
2065   free (hash_val);
2066 }
2067
2068 /* Record register first/last/block set information for REGNO in INSN.
2069
2070    reg_first_set records the first place in the block where the register
2071    is set and is used to compute "anticipatability".
2072
2073    reg_last_set records the last place in the block where the register
2074    is set and is used to compute "availability".
2075
2076    reg_set_in_block records whether the register is set in the block
2077    and is used to compute "transparency".  */
2078
2079 static void
2080 record_last_reg_set_info (insn, regno)
2081      rtx insn;
2082      int regno;
2083 {
2084   if (reg_first_set[regno] == NEVER_SET)
2085     reg_first_set[regno] = INSN_CUID (insn);
2086
2087   reg_last_set[regno] = INSN_CUID (insn);
2088   SET_BIT (reg_set_in_block[BLOCK_NUM (insn)], regno);
2089 }
2090
2091 /* Record memory first/last/block set information for INSN.  */
2092
2093 static void
2094 record_last_mem_set_info (insn)
2095      rtx insn;
2096 {
2097   if (mem_first_set == NEVER_SET)
2098     mem_first_set = INSN_CUID (insn);
2099
2100   mem_last_set = INSN_CUID (insn);
2101   mem_set_in_block[BLOCK_NUM (insn)] = 1;
2102 }
2103
2104 /* Called from compute_hash_table via note_stores to handle one
2105    SET or CLOBBER in an insn.  DATA is really the instruction in which
2106    the SET is taking place.  */
2107
2108 static void
2109 record_last_set_info (dest, setter, data)
2110      rtx dest, setter ATTRIBUTE_UNUSED;
2111      void *data;
2112 {
2113   rtx last_set_insn = (rtx) data;
2114
2115   if (GET_CODE (dest) == SUBREG)
2116     dest = SUBREG_REG (dest);
2117
2118   if (GET_CODE (dest) == REG)
2119     record_last_reg_set_info (last_set_insn, REGNO (dest));
2120   else if (GET_CODE (dest) == MEM
2121            /* Ignore pushes, they clobber nothing.  */
2122            && ! push_operand (dest, GET_MODE (dest)))
2123     record_last_mem_set_info (last_set_insn);
2124 }
2125
2126 /* Top level function to create an expression or assignment hash table.
2127
2128    Expression entries are placed in the hash table if
2129    - they are of the form (set (pseudo-reg) src),
2130    - src is something we want to perform GCSE on,
2131    - none of the operands are subsequently modified in the block
2132
2133    Assignment entries are placed in the hash table if
2134    - they are of the form (set (pseudo-reg) src),
2135    - src is something we want to perform const/copy propagation on,
2136    - none of the operands or target are subsequently modified in the block
2137
2138    Currently src must be a pseudo-reg or a const_int.
2139
2140    F is the first insn.
2141    SET_P is non-zero for computing the assignment hash table.  */
2142
2143 static void
2144 compute_hash_table (set_p)
2145      int set_p;
2146 {
2147   int bb;
2148
2149   /* While we compute the hash table we also compute a bit array of which
2150      registers are set in which blocks.
2151      We also compute which blocks set memory, in the absence of aliasing
2152      support [which is TODO].
2153      ??? This isn't needed during const/copy propagation, but it's cheap to
2154      compute.  Later.  */
2155   sbitmap_vector_zero (reg_set_in_block, n_basic_blocks);
2156   bzero ((char *) mem_set_in_block, n_basic_blocks);
2157
2158   /* Some working arrays used to track first and last set in each block.  */
2159   /* ??? One could use alloca here, but at some size a threshold is crossed
2160      beyond which one should use malloc.  Are we at that threshold here?  */
2161   reg_first_set = (int *) gmalloc (max_gcse_regno * sizeof (int));
2162   reg_last_set = (int *) gmalloc (max_gcse_regno * sizeof (int));
2163
2164   for (bb = 0; bb < n_basic_blocks; bb++)
2165     {
2166       rtx insn;
2167       unsigned int regno;
2168       int in_libcall_block;
2169       unsigned int i;
2170
2171       /* First pass over the instructions records information used to
2172          determine when registers and memory are first and last set.
2173          ??? The mem_set_in_block and hard-reg reg_set_in_block computation
2174          could be moved to compute_sets since they currently don't change.  */
2175
2176       for (i = 0; i < max_gcse_regno; i++)
2177         reg_first_set[i] = reg_last_set[i] = NEVER_SET;
2178
2179       mem_first_set = NEVER_SET;
2180       mem_last_set = NEVER_SET;
2181
2182       for (insn = BLOCK_HEAD (bb);
2183            insn && insn != NEXT_INSN (BLOCK_END (bb));
2184            insn = NEXT_INSN (insn))
2185         {
2186 #ifdef NON_SAVING_SETJMP 
2187           if (NON_SAVING_SETJMP && GET_CODE (insn) == NOTE
2188               && NOTE_LINE_NUMBER (insn) == NOTE_INSN_SETJMP)
2189             {
2190               for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
2191                 record_last_reg_set_info (insn, regno);
2192               continue;
2193             }
2194 #endif
2195
2196           if (! INSN_P (insn))
2197             continue;
2198
2199           if (GET_CODE (insn) == CALL_INSN)
2200             {
2201               for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
2202                 if ((call_used_regs[regno]
2203                      && regno != STACK_POINTER_REGNUM
2204 #if HARD_FRAME_POINTER_REGNUM != FRAME_POINTER_REGNUM
2205                      && regno != HARD_FRAME_POINTER_REGNUM
2206 #endif
2207 #if ARG_POINTER_REGNUM != FRAME_POINTER_REGNUM
2208                      && ! (regno == ARG_POINTER_REGNUM && fixed_regs[regno])
2209 #endif
2210 #if defined (PIC_OFFSET_TABLE_REGNUM) && !defined (PIC_OFFSET_TABLE_REG_CALL_CLOBBERED)
2211                      && ! (regno == PIC_OFFSET_TABLE_REGNUM && flag_pic)
2212 #endif
2213
2214                      && regno != FRAME_POINTER_REGNUM)
2215                     || global_regs[regno])
2216                   record_last_reg_set_info (insn, regno);
2217
2218               if (! CONST_CALL_P (insn))
2219                 record_last_mem_set_info (insn);
2220             }
2221
2222           note_stores (PATTERN (insn), record_last_set_info, insn);
2223         }
2224
2225       /* The next pass builds the hash table.  */
2226
2227       for (insn = BLOCK_HEAD (bb), in_libcall_block = 0;
2228            insn && insn != NEXT_INSN (BLOCK_END (bb));
2229            insn = NEXT_INSN (insn))
2230         if (INSN_P (insn))
2231           {
2232             if (find_reg_note (insn, REG_LIBCALL, NULL_RTX))
2233               in_libcall_block = 1;
2234             else if (find_reg_note (insn, REG_RETVAL, NULL_RTX))
2235               in_libcall_block = 0;
2236             hash_scan_insn (insn, set_p, in_libcall_block);
2237         }
2238     }
2239
2240   free (reg_first_set);
2241   free (reg_last_set);
2242
2243   /* Catch bugs early.  */
2244   reg_first_set = reg_last_set = 0;
2245 }
2246
2247 /* Allocate space for the set hash table.
2248    N_INSNS is the number of instructions in the function.
2249    It is used to determine the number of buckets to use.  */
2250
2251 static void
2252 alloc_set_hash_table (n_insns)
2253      int n_insns;
2254 {
2255   int n;
2256
2257   set_hash_table_size = n_insns / 4;
2258   if (set_hash_table_size < 11)
2259     set_hash_table_size = 11;
2260
2261   /* Attempt to maintain efficient use of hash table.
2262      Making it an odd number is simplest for now.
2263      ??? Later take some measurements.  */
2264   set_hash_table_size |= 1;
2265   n = set_hash_table_size * sizeof (struct expr *);
2266   set_hash_table = (struct expr **) gmalloc (n);
2267 }
2268
2269 /* Free things allocated by alloc_set_hash_table.  */
2270
2271 static void
2272 free_set_hash_table ()
2273 {
2274   free (set_hash_table);
2275 }
2276
2277 /* Compute the hash table for doing copy/const propagation.  */
2278
2279 static void
2280 compute_set_hash_table ()
2281 {
2282   /* Initialize count of number of entries in hash table.  */
2283   n_sets = 0;
2284   bzero ((char *) set_hash_table,
2285          set_hash_table_size * sizeof (struct expr *));
2286
2287   compute_hash_table (1);
2288 }
2289
2290 /* Allocate space for the expression hash table.
2291    N_INSNS is the number of instructions in the function.
2292    It is used to determine the number of buckets to use.  */
2293
2294 static void
2295 alloc_expr_hash_table (n_insns)
2296      unsigned int n_insns;
2297 {
2298   int n;
2299
2300   expr_hash_table_size = n_insns / 2;
2301   /* Make sure the amount is usable.  */
2302   if (expr_hash_table_size < 11)
2303     expr_hash_table_size = 11;
2304
2305   /* Attempt to maintain efficient use of hash table.
2306      Making it an odd number is simplest for now.
2307      ??? Later take some measurements.  */
2308   expr_hash_table_size |= 1;
2309   n = expr_hash_table_size * sizeof (struct expr *);
2310   expr_hash_table = (struct expr **) gmalloc (n);
2311 }
2312
2313 /* Free things allocated by alloc_expr_hash_table.  */
2314
2315 static void
2316 free_expr_hash_table ()
2317 {
2318   free (expr_hash_table);
2319 }
2320
2321 /* Compute the hash table for doing GCSE.  */
2322
2323 static void
2324 compute_expr_hash_table ()
2325 {
2326   /* Initialize count of number of entries in hash table.  */
2327   n_exprs = 0;
2328   bzero ((char *) expr_hash_table,
2329          expr_hash_table_size * sizeof (struct expr *));
2330
2331   compute_hash_table (0);
2332 }
2333 \f
2334 /* Expression tracking support.  */
2335
2336 /* Lookup pattern PAT in the expression table.
2337    The result is a pointer to the table entry, or NULL if not found.  */
2338
2339 static struct expr *
2340 lookup_expr (pat)
2341      rtx pat;
2342 {
2343   int do_not_record_p;
2344   unsigned int hash = hash_expr (pat, GET_MODE (pat), &do_not_record_p,
2345                                  expr_hash_table_size);
2346   struct expr *expr;
2347
2348   if (do_not_record_p)
2349     return NULL;
2350
2351   expr = expr_hash_table[hash];
2352
2353   while (expr && ! expr_equiv_p (expr->expr, pat))
2354     expr = expr->next_same_hash;
2355
2356   return expr;
2357 }
2358
2359 /* Lookup REGNO in the set table.  If PAT is non-NULL look for the entry that
2360    matches it, otherwise return the first entry for REGNO.  The result is a
2361    pointer to the table entry, or NULL if not found.  */
2362
2363 static struct expr *
2364 lookup_set (regno, pat)
2365      unsigned int regno;
2366      rtx pat;
2367 {
2368   unsigned int hash = hash_set (regno, set_hash_table_size);
2369   struct expr *expr;
2370
2371   expr = set_hash_table[hash];
2372
2373   if (pat)
2374     {
2375       while (expr && ! expr_equiv_p (expr->expr, pat))
2376         expr = expr->next_same_hash;
2377     }
2378   else
2379     {
2380       while (expr && REGNO (SET_DEST (expr->expr)) != regno)
2381         expr = expr->next_same_hash;
2382     }
2383
2384   return expr;
2385 }
2386
2387 /* Return the next entry for REGNO in list EXPR.  */
2388
2389 static struct expr *
2390 next_set (regno, expr)
2391      unsigned int regno;
2392      struct expr *expr;
2393 {
2394   do
2395     expr = expr->next_same_hash;
2396   while (expr && REGNO (SET_DEST (expr->expr)) != regno);
2397
2398   return expr;
2399 }
2400
2401 /* Reset tables used to keep track of what's still available [since the
2402    start of the block].  */
2403
2404 static void
2405 reset_opr_set_tables ()
2406 {
2407   /* Maintain a bitmap of which regs have been set since beginning of
2408      the block.  */
2409   sbitmap_zero (reg_set_bitmap);
2410
2411   /* Also keep a record of the last instruction to modify memory.
2412      For now this is very trivial, we only record whether any memory
2413      location has been modified.  */
2414   mem_last_set = 0;
2415 }
2416
2417 /* Return non-zero if the operands of X are not set before INSN in
2418    INSN's basic block.  */
2419
2420 static int
2421 oprs_not_set_p (x, insn)
2422      rtx x, insn;
2423 {
2424   int i, j;
2425   enum rtx_code code;
2426   const char *fmt;
2427
2428   if (x == 0)
2429     return 1;
2430
2431   code = GET_CODE (x);
2432   switch (code)
2433     {
2434     case PC:
2435     case CC0:
2436     case CONST:
2437     case CONST_INT:
2438     case CONST_DOUBLE:
2439     case SYMBOL_REF:
2440     case LABEL_REF:
2441     case ADDR_VEC:
2442     case ADDR_DIFF_VEC:
2443       return 1;
2444
2445     case MEM:
2446       if (mem_last_set != 0)
2447         return 0;
2448       else
2449         return oprs_not_set_p (XEXP (x, 0), insn);
2450
2451     case REG:
2452       return ! TEST_BIT (reg_set_bitmap, REGNO (x));
2453
2454     default:
2455       break;
2456     }
2457
2458   for (i = GET_RTX_LENGTH (code) - 1, fmt = GET_RTX_FORMAT (code); i >= 0; i--)
2459     {
2460       if (fmt[i] == 'e')
2461         {
2462           /* If we are about to do the last recursive call
2463              needed at this level, change it into iteration.
2464              This function is called enough to be worth it.  */
2465           if (i == 0)
2466             return oprs_not_set_p (XEXP (x, i), insn);
2467
2468           if (! oprs_not_set_p (XEXP (x, i), insn))
2469             return 0;
2470         }
2471       else if (fmt[i] == 'E')
2472         for (j = 0; j < XVECLEN (x, i); j++)
2473           if (! oprs_not_set_p (XVECEXP (x, i, j), insn))
2474             return 0;
2475     }
2476
2477   return 1;
2478 }
2479
2480 /* Mark things set by a CALL.  */
2481
2482 static void
2483 mark_call (insn)
2484      rtx insn;
2485 {
2486   mem_last_set = INSN_CUID (insn);
2487 }
2488
2489 /* Mark things set by a SET.  */
2490
2491 static void
2492 mark_set (pat, insn)
2493      rtx pat, insn;
2494 {
2495   rtx dest = SET_DEST (pat);
2496
2497   while (GET_CODE (dest) == SUBREG
2498          || GET_CODE (dest) == ZERO_EXTRACT
2499          || GET_CODE (dest) == SIGN_EXTRACT
2500          || GET_CODE (dest) == STRICT_LOW_PART)
2501     dest = XEXP (dest, 0);
2502
2503   if (GET_CODE (dest) == REG)
2504     SET_BIT (reg_set_bitmap, REGNO (dest));
2505   else if (GET_CODE (dest) == MEM)
2506     mem_last_set = INSN_CUID (insn);
2507
2508   if (GET_CODE (SET_SRC (pat)) == CALL)
2509     mark_call (insn);
2510 }
2511
2512 /* Record things set by a CLOBBER.  */
2513
2514 static void
2515 mark_clobber (pat, insn)
2516      rtx pat, insn;
2517 {
2518   rtx clob = XEXP (pat, 0);
2519
2520   while (GET_CODE (clob) == SUBREG || GET_CODE (clob) == STRICT_LOW_PART)
2521     clob = XEXP (clob, 0);
2522
2523   if (GET_CODE (clob) == REG)
2524     SET_BIT (reg_set_bitmap, REGNO (clob));
2525   else
2526     mem_last_set = INSN_CUID (insn);
2527 }
2528
2529 /* Record things set by INSN.
2530    This data is used by oprs_not_set_p.  */
2531
2532 static void
2533 mark_oprs_set (insn)
2534      rtx insn;
2535 {
2536   rtx pat = PATTERN (insn);
2537   int i;
2538
2539   if (GET_CODE (pat) == SET)
2540     mark_set (pat, insn);
2541   else if (GET_CODE (pat) == PARALLEL)
2542     for (i = 0; i < XVECLEN (pat, 0); i++)
2543       {
2544         rtx x = XVECEXP (pat, 0, i);
2545
2546         if (GET_CODE (x) == SET)
2547           mark_set (x, insn);
2548         else if (GET_CODE (x) == CLOBBER)
2549           mark_clobber (x, insn);
2550         else if (GET_CODE (x) == CALL)
2551           mark_call (insn);
2552       }
2553
2554   else if (GET_CODE (pat) == CLOBBER)
2555     mark_clobber (pat, insn);
2556   else if (GET_CODE (pat) == CALL)
2557     mark_call (insn);
2558 }
2559
2560 \f
2561 /* Classic GCSE reaching definition support.  */
2562
2563 /* Allocate reaching def variables.  */
2564
2565 static void
2566 alloc_rd_mem (n_blocks, n_insns)
2567      int n_blocks, n_insns;
2568 {
2569   rd_kill = (sbitmap *) sbitmap_vector_alloc (n_blocks, n_insns);
2570   sbitmap_vector_zero (rd_kill, n_basic_blocks);
2571
2572   rd_gen = (sbitmap *) sbitmap_vector_alloc (n_blocks, n_insns);
2573   sbitmap_vector_zero (rd_gen, n_basic_blocks);
2574
2575   reaching_defs = (sbitmap *) sbitmap_vector_alloc (n_blocks, n_insns);
2576   sbitmap_vector_zero (reaching_defs, n_basic_blocks);
2577
2578   rd_out = (sbitmap *) sbitmap_vector_alloc (n_blocks, n_insns);
2579   sbitmap_vector_zero (rd_out, n_basic_blocks);
2580 }
2581
2582 /* Free reaching def variables.  */
2583
2584 static void
2585 free_rd_mem ()
2586 {
2587   free (rd_kill);
2588   free (rd_gen);
2589   free (reaching_defs);
2590   free (rd_out);
2591 }
2592
2593 /* Add INSN to the kills of BB.  REGNO, set in BB, is killed by INSN.  */
2594
2595 static void
2596 handle_rd_kill_set (insn, regno, bb)
2597      rtx insn;
2598      int regno, bb;
2599 {
2600   struct reg_set *this_reg;
2601
2602   for (this_reg = reg_set_table[regno]; this_reg; this_reg = this_reg ->next)
2603     if (BLOCK_NUM (this_reg->insn) != BLOCK_NUM (insn))
2604       SET_BIT (rd_kill[bb], INSN_CUID (this_reg->insn));
2605 }
2606
2607 /* Compute the set of kill's for reaching definitions.  */
2608
2609 static void
2610 compute_kill_rd ()
2611 {
2612   int bb, cuid;
2613   int regno, i;
2614
2615   /* For each block
2616        For each set bit in `gen' of the block (i.e each insn which
2617            generates a definition in the block)
2618          Call the reg set by the insn corresponding to that bit regx
2619          Look at the linked list starting at reg_set_table[regx]
2620          For each setting of regx in the linked list, which is not in
2621              this block
2622            Set the bit in `kill' corresponding to that insn.   */
2623   for (bb = 0; bb < n_basic_blocks; bb++)
2624     for (cuid = 0; cuid < max_cuid; cuid++)
2625       if (TEST_BIT (rd_gen[bb], cuid))
2626         {
2627           rtx insn = CUID_INSN (cuid);
2628           rtx pat = PATTERN (insn);
2629
2630           if (GET_CODE (insn) == CALL_INSN)
2631             {
2632               for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
2633                 {
2634                   if ((call_used_regs[regno]
2635                        && regno != STACK_POINTER_REGNUM
2636 #if HARD_FRAME_POINTER_REGNUM != FRAME_POINTER_REGNUM
2637                        && regno != HARD_FRAME_POINTER_REGNUM
2638 #endif
2639 #if ARG_POINTER_REGNUM != FRAME_POINTER_REGNUM
2640                        && ! (regno == ARG_POINTER_REGNUM
2641                              && fixed_regs[regno])
2642 #endif
2643 #if defined (PIC_OFFSET_TABLE_REGNUM) && !defined (PIC_OFFSET_TABLE_REG_CALL_CLOBBERED)
2644                        && ! (regno == PIC_OFFSET_TABLE_REGNUM && flag_pic)
2645 #endif
2646                        && regno != FRAME_POINTER_REGNUM)
2647                       || global_regs[regno])
2648                     handle_rd_kill_set (insn, regno, bb);
2649                 }
2650             }
2651
2652           if (GET_CODE (pat) == PARALLEL)
2653             {
2654               for (i = XVECLEN (pat, 0) - 1; i >= 0; i--)
2655                 {
2656                   enum rtx_code code = GET_CODE (XVECEXP (pat, 0, i));
2657
2658                   if ((code == SET || code == CLOBBER)
2659                       && GET_CODE (XEXP (XVECEXP (pat, 0, i), 0)) == REG)
2660                     handle_rd_kill_set (insn,
2661                                         REGNO (XEXP (XVECEXP (pat, 0, i), 0)),
2662                                         bb);
2663                 }
2664             }
2665           else if (GET_CODE (pat) == SET && GET_CODE (SET_DEST (pat)) == REG)
2666             /* Each setting of this register outside of this block
2667                must be marked in the set of kills in this block.  */
2668             handle_rd_kill_set (insn, REGNO (SET_DEST (pat)), bb);
2669         }
2670 }
2671
2672 /* Compute the reaching definitions as in 
2673    Compilers Principles, Techniques, and Tools. Aho, Sethi, Ullman,
2674    Chapter 10.  It is the same algorithm as used for computing available
2675    expressions but applied to the gens and kills of reaching definitions.  */
2676
2677 static void
2678 compute_rd ()
2679 {
2680   int bb, changed, passes;
2681
2682   for (bb = 0; bb < n_basic_blocks; bb++)
2683     sbitmap_copy (rd_out[bb] /*dst*/, rd_gen[bb] /*src*/);
2684
2685   passes = 0;
2686   changed = 1;
2687   while (changed)
2688     {
2689       changed = 0;
2690       for (bb = 0; bb < n_basic_blocks; bb++)
2691         {
2692           sbitmap_union_of_preds (reaching_defs[bb], rd_out, bb);
2693           changed |= sbitmap_union_of_diff (rd_out[bb], rd_gen[bb],
2694                                             reaching_defs[bb], rd_kill[bb]);
2695         }
2696       passes++;
2697     }
2698
2699   if (gcse_file)
2700     fprintf (gcse_file, "reaching def computation: %d passes\n", passes);
2701 }
2702 \f
2703 /* Classic GCSE available expression support.  */
2704
2705 /* Allocate memory for available expression computation.  */
2706
2707 static void
2708 alloc_avail_expr_mem (n_blocks, n_exprs)
2709      int n_blocks, n_exprs;
2710 {
2711   ae_kill = (sbitmap *) sbitmap_vector_alloc (n_blocks, n_exprs);
2712   sbitmap_vector_zero (ae_kill, n_basic_blocks);
2713
2714   ae_gen = (sbitmap *) sbitmap_vector_alloc (n_blocks, n_exprs);
2715   sbitmap_vector_zero (ae_gen, n_basic_blocks);
2716
2717   ae_in = (sbitmap *) sbitmap_vector_alloc (n_blocks, n_exprs);
2718   sbitmap_vector_zero (ae_in, n_basic_blocks);
2719
2720   ae_out = (sbitmap *) sbitmap_vector_alloc (n_blocks, n_exprs);
2721   sbitmap_vector_zero (ae_out, n_basic_blocks);
2722 }
2723
2724 static void
2725 free_avail_expr_mem ()
2726 {
2727   free (ae_kill);
2728   free (ae_gen);
2729   free (ae_in);
2730   free (ae_out);
2731 }
2732
2733 /* Compute the set of available expressions generated in each basic block.  */
2734
2735 static void
2736 compute_ae_gen ()
2737 {
2738   unsigned int i;
2739   struct expr *expr;
2740   struct occr *occr;
2741
2742   /* For each recorded occurrence of each expression, set ae_gen[bb][expr].
2743      This is all we have to do because an expression is not recorded if it
2744      is not available, and the only expressions we want to work with are the
2745      ones that are recorded.  */
2746   for (i = 0; i < expr_hash_table_size; i++)
2747     for (expr = expr_hash_table[i]; expr != 0; expr = expr->next_same_hash)
2748       for (occr = expr->avail_occr; occr != 0; occr = occr->next)
2749         SET_BIT (ae_gen[BLOCK_NUM (occr->insn)], expr->bitmap_index);
2750 }
2751
2752 /* Return non-zero if expression X is killed in BB.  */
2753
2754 static int
2755 expr_killed_p (x, bb)
2756      rtx x;
2757      int bb;
2758 {
2759   int i, j;
2760   enum rtx_code code;
2761   const char *fmt;
2762
2763   if (x == 0)
2764     return 1;
2765
2766   code = GET_CODE (x);
2767   switch (code)
2768     {
2769     case REG:
2770       return TEST_BIT (reg_set_in_block[bb], REGNO (x));
2771
2772     case MEM:
2773       if (mem_set_in_block[bb])
2774         return 1;
2775       else
2776         return expr_killed_p (XEXP (x, 0), bb);
2777
2778     case PC:
2779     case CC0: /*FIXME*/
2780     case CONST:
2781     case CONST_INT:
2782     case CONST_DOUBLE:
2783     case SYMBOL_REF:
2784     case LABEL_REF:
2785     case ADDR_VEC:
2786     case ADDR_DIFF_VEC:
2787       return 0;
2788
2789     default:
2790       break;
2791     }
2792
2793   for (i = GET_RTX_LENGTH (code) - 1, fmt = GET_RTX_FORMAT (code); i >= 0; i--)
2794     {
2795       if (fmt[i] == 'e')
2796         {
2797           /* If we are about to do the last recursive call
2798              needed at this level, change it into iteration.
2799              This function is called enough to be worth it.  */
2800           if (i == 0)
2801             return expr_killed_p (XEXP (x, i), bb);
2802           else if (expr_killed_p (XEXP (x, i), bb))
2803             return 1;
2804         }
2805       else if (fmt[i] == 'E')
2806         for (j = 0; j < XVECLEN (x, i); j++)
2807           if (expr_killed_p (XVECEXP (x, i, j), bb))
2808             return 1;
2809     }
2810
2811   return 0;
2812 }
2813
2814 /* Compute the set of available expressions killed in each basic block.  */
2815
2816 static void
2817 compute_ae_kill (ae_gen, ae_kill)
2818      sbitmap *ae_gen, *ae_kill;
2819 {
2820   int bb;
2821   unsigned int i;
2822   struct expr *expr;
2823
2824   for (bb = 0; bb < n_basic_blocks; bb++)
2825     for (i = 0; i < expr_hash_table_size; i++)
2826       for (expr = expr_hash_table[i]; expr; expr = expr->next_same_hash)
2827         {
2828           /* Skip EXPR if generated in this block.  */
2829           if (TEST_BIT (ae_gen[bb], expr->bitmap_index))
2830             continue;
2831
2832           if (expr_killed_p (expr->expr, bb))
2833             SET_BIT (ae_kill[bb], expr->bitmap_index);
2834         }
2835 }
2836 \f
2837 /* Actually perform the Classic GCSE optimizations.  */
2838
2839 /* Return non-zero if occurrence OCCR of expression EXPR reaches block BB.
2840
2841    CHECK_SELF_LOOP is non-zero if we should consider a block reaching itself
2842    as a positive reach.  We want to do this when there are two computations
2843    of the expression in the block.
2844
2845    VISITED is a pointer to a working buffer for tracking which BB's have
2846    been visited.  It is NULL for the top-level call.
2847
2848    We treat reaching expressions that go through blocks containing the same
2849    reaching expression as "not reaching".  E.g. if EXPR is generated in blocks
2850    2 and 3, INSN is in block 4, and 2->3->4, we treat the expression in block
2851    2 as not reaching.  The intent is to improve the probability of finding
2852    only one reaching expression and to reduce register lifetimes by picking
2853    the closest such expression.  */
2854
2855 static int
2856 expr_reaches_here_p_work (occr, expr, bb, check_self_loop, visited)
2857      struct occr *occr;
2858      struct expr *expr;
2859      int bb;
2860      int check_self_loop;
2861      char *visited;
2862 {
2863   edge pred;
2864
2865   for (pred = BASIC_BLOCK(bb)->pred; pred != NULL; pred = pred->pred_next)
2866     {
2867       int pred_bb = pred->src->index;
2868
2869       if (visited[pred_bb])
2870         /* This predecessor has already been visited. Nothing to do.  */
2871           ;
2872       else if (pred_bb == bb)
2873         {
2874           /* BB loops on itself.  */
2875           if (check_self_loop
2876               && TEST_BIT (ae_gen[pred_bb], expr->bitmap_index)
2877               && BLOCK_NUM (occr->insn) == pred_bb)
2878             return 1;
2879
2880           visited[pred_bb] = 1;
2881         }
2882
2883       /* Ignore this predecessor if it kills the expression.  */
2884       else if (TEST_BIT (ae_kill[pred_bb], expr->bitmap_index))
2885         visited[pred_bb] = 1;
2886
2887       /* Does this predecessor generate this expression?  */
2888       else if (TEST_BIT (ae_gen[pred_bb], expr->bitmap_index))
2889         {
2890           /* Is this the occurrence we're looking for?
2891              Note that there's only one generating occurrence per block
2892              so we just need to check the block number.  */
2893           if (BLOCK_NUM (occr->insn) == pred_bb)
2894             return 1;
2895
2896           visited[pred_bb] = 1;
2897         }
2898
2899       /* Neither gen nor kill.  */
2900       else
2901         {
2902           visited[pred_bb] = 1;
2903           if (expr_reaches_here_p_work (occr, expr, pred_bb, check_self_loop, 
2904               visited))
2905
2906             return 1;
2907         }
2908     }
2909
2910   /* All paths have been checked.  */
2911   return 0;
2912 }
2913
2914 /* This wrapper for expr_reaches_here_p_work() is to ensure that any
2915    memory allocated for that function is returned. */
2916
2917 static int
2918 expr_reaches_here_p (occr, expr, bb, check_self_loop)
2919      struct occr *occr;
2920      struct expr *expr;
2921      int bb;
2922      int check_self_loop;
2923 {
2924   int rval;
2925   char *visited = (char *) xcalloc (n_basic_blocks, 1);
2926
2927   rval = expr_reaches_here_p_work (occr, expr, bb, check_self_loop, visited);
2928   
2929   free (visited);
2930   return rval;
2931 }
2932
2933 /* Return the instruction that computes EXPR that reaches INSN's basic block.
2934    If there is more than one such instruction, return NULL.
2935
2936    Called only by handle_avail_expr.  */
2937
2938 static rtx
2939 computing_insn (expr, insn)
2940      struct expr *expr;
2941      rtx insn;
2942 {
2943   int bb = BLOCK_NUM (insn);
2944
2945   if (expr->avail_occr->next == NULL)
2946     {    
2947       if (BLOCK_NUM (expr->avail_occr->insn) == bb)
2948         /* The available expression is actually itself
2949            (i.e. a loop in the flow graph) so do nothing.  */
2950         return NULL;
2951
2952       /* (FIXME) Case that we found a pattern that was created by
2953          a substitution that took place.  */
2954       return expr->avail_occr->insn;
2955     }
2956   else
2957     {
2958       /* Pattern is computed more than once.
2959          Search backwards from this insn to see how many of these 
2960          computations actually reach this insn.  */
2961       struct occr *occr;
2962       rtx insn_computes_expr = NULL;
2963       int can_reach = 0;
2964
2965       for (occr = expr->avail_occr; occr != NULL; occr = occr->next)
2966         {
2967           if (BLOCK_NUM (occr->insn) == bb)
2968             {
2969               /* The expression is generated in this block.
2970                  The only time we care about this is when the expression
2971                  is generated later in the block [and thus there's a loop].
2972                  We let the normal cse pass handle the other cases.  */
2973               if (INSN_CUID (insn) < INSN_CUID (occr->insn)
2974                   && expr_reaches_here_p (occr, expr, bb, 1))
2975                 {
2976                   can_reach++;
2977                   if (can_reach > 1)
2978                     return NULL;
2979
2980                   insn_computes_expr = occr->insn;
2981                 }
2982             }
2983           else if (expr_reaches_here_p (occr, expr, bb, 0))
2984             {
2985               can_reach++;
2986               if (can_reach > 1)
2987                 return NULL;
2988
2989               insn_computes_expr = occr->insn;
2990             }
2991         }
2992
2993       if (insn_computes_expr == NULL)
2994         abort ();
2995
2996       return insn_computes_expr;
2997     }
2998 }
2999
3000 /* Return non-zero if the definition in DEF_INSN can reach INSN.
3001    Only called by can_disregard_other_sets.  */
3002
3003 static int
3004 def_reaches_here_p (insn, def_insn)
3005      rtx insn, def_insn;
3006 {
3007   rtx reg;
3008
3009   if (TEST_BIT (reaching_defs[BLOCK_NUM (insn)], INSN_CUID (def_insn)))
3010     return 1;
3011
3012   if (BLOCK_NUM (insn) == BLOCK_NUM (def_insn))
3013     {
3014       if (INSN_CUID (def_insn) < INSN_CUID (insn))
3015         {
3016           if (GET_CODE (PATTERN (def_insn)) == PARALLEL)
3017             return 1;
3018           else if (GET_CODE (PATTERN (def_insn)) == CLOBBER)
3019             reg = XEXP (PATTERN (def_insn), 0);
3020           else if (GET_CODE (PATTERN (def_insn)) == SET)
3021             reg = SET_DEST (PATTERN (def_insn));
3022           else
3023             abort ();
3024
3025           return ! reg_set_between_p (reg, NEXT_INSN (def_insn), insn);
3026         }
3027       else
3028         return 0;
3029     }
3030
3031   return 0;
3032 }
3033
3034 /* Return non-zero if *ADDR_THIS_REG can only have one value at INSN.  The
3035    value returned is the number of definitions that reach INSN.  Returning a
3036    value of zero means that [maybe] more than one definition reaches INSN and
3037    the caller can't perform whatever optimization it is trying.  i.e. it is
3038    always safe to return zero.  */
3039
3040 static int
3041 can_disregard_other_sets (addr_this_reg, insn, for_combine)
3042      struct reg_set **addr_this_reg;
3043      rtx insn;
3044      int for_combine;
3045 {
3046   int number_of_reaching_defs = 0;
3047   struct reg_set *this_reg;
3048
3049   for (this_reg = *addr_this_reg; this_reg != 0; this_reg = this_reg->next)
3050     if (def_reaches_here_p (insn, this_reg->insn))
3051       {
3052         number_of_reaching_defs++;
3053         /* Ignore parallels for now.  */
3054         if (GET_CODE (PATTERN (this_reg->insn)) == PARALLEL)
3055           return 0;
3056
3057         if (!for_combine
3058             && (GET_CODE (PATTERN (this_reg->insn)) == CLOBBER
3059                 || ! rtx_equal_p (SET_SRC (PATTERN (this_reg->insn)),
3060                                   SET_SRC (PATTERN (insn)))))
3061           /* A setting of the reg to a different value reaches INSN.  */
3062           return 0;
3063
3064         if (number_of_reaching_defs > 1)
3065           {
3066             /* If in this setting the value the register is being set to is
3067                equal to the previous value the register was set to and this
3068                setting reaches the insn we are trying to do the substitution
3069                on then we are ok.  */
3070             if (GET_CODE (PATTERN (this_reg->insn)) == CLOBBER)
3071               return 0;
3072             else if (! rtx_equal_p (SET_SRC (PATTERN (this_reg->insn)),
3073                                     SET_SRC (PATTERN (insn))))
3074               return 0;
3075           }
3076
3077         *addr_this_reg = this_reg; 
3078       }
3079
3080   return number_of_reaching_defs;
3081 }
3082
3083 /* Expression computed by insn is available and the substitution is legal,
3084    so try to perform the substitution.
3085
3086    The result is non-zero if any changes were made.  */
3087
3088 static int
3089 handle_avail_expr (insn, expr)
3090      rtx insn;
3091      struct expr *expr;
3092 {
3093   rtx pat, insn_computes_expr;
3094   rtx to;
3095   struct reg_set *this_reg;
3096   int found_setting, use_src;
3097   int changed = 0;
3098
3099   /* We only handle the case where one computation of the expression
3100      reaches this instruction.  */
3101   insn_computes_expr = computing_insn (expr, insn);
3102   if (insn_computes_expr == NULL)
3103     return 0;
3104
3105   found_setting = 0;
3106   use_src = 0;
3107
3108   /* At this point we know only one computation of EXPR outside of this
3109      block reaches this insn.  Now try to find a register that the
3110      expression is computed into.  */
3111   if (GET_CODE (SET_SRC (PATTERN (insn_computes_expr))) == REG)
3112     {
3113       /* This is the case when the available expression that reaches
3114          here has already been handled as an available expression.  */
3115       unsigned int regnum_for_replacing
3116         = REGNO (SET_SRC (PATTERN (insn_computes_expr)));
3117
3118       /* If the register was created by GCSE we can't use `reg_set_table',
3119          however we know it's set only once.  */
3120       if (regnum_for_replacing >= max_gcse_regno
3121           /* If the register the expression is computed into is set only once,
3122              or only one set reaches this insn, we can use it.  */
3123           || (((this_reg = reg_set_table[regnum_for_replacing]),
3124                this_reg->next == NULL)
3125               || can_disregard_other_sets (&this_reg, insn, 0)))
3126        {
3127          use_src = 1;
3128          found_setting = 1;
3129        }
3130     }
3131
3132   if (!found_setting)
3133     {
3134       unsigned int regnum_for_replacing
3135         = REGNO (SET_DEST (PATTERN (insn_computes_expr)));
3136
3137       /* This shouldn't happen.  */
3138       if (regnum_for_replacing >= max_gcse_regno)
3139         abort ();
3140
3141       this_reg = reg_set_table[regnum_for_replacing];
3142
3143       /* If the register the expression is computed into is set only once,
3144          or only one set reaches this insn, use it.  */
3145       if (this_reg->next == NULL
3146           || can_disregard_other_sets (&this_reg, insn, 0))
3147         found_setting = 1;
3148     }
3149
3150   if (found_setting)
3151     {
3152       pat = PATTERN (insn);
3153       if (use_src)
3154         to = SET_SRC (PATTERN (insn_computes_expr));
3155       else
3156         to = SET_DEST (PATTERN (insn_computes_expr));
3157       changed = validate_change (insn, &SET_SRC (pat), to, 0);
3158
3159       /* We should be able to ignore the return code from validate_change but
3160          to play it safe we check.  */
3161       if (changed)
3162         {
3163           gcse_subst_count++;
3164           if (gcse_file != NULL)
3165             {
3166               fprintf (gcse_file, "GCSE: Replacing the source in insn %d with",
3167                        INSN_UID (insn));
3168               fprintf (gcse_file, " reg %d %s insn %d\n",
3169                        REGNO (to), use_src ? "from" : "set in",
3170                        INSN_UID (insn_computes_expr));
3171             }
3172         }
3173     }
3174
3175   /* The register that the expr is computed into is set more than once.  */
3176   else if (1 /*expensive_op(this_pattrn->op) && do_expensive_gcse)*/)
3177     {
3178       /* Insert an insn after insnx that copies the reg set in insnx
3179          into a new pseudo register call this new register REGN.
3180          From insnb until end of basic block or until REGB is set
3181          replace all uses of REGB with REGN.  */
3182       rtx new_insn;
3183
3184       to = gen_reg_rtx (GET_MODE (SET_DEST (PATTERN (insn_computes_expr))));
3185
3186       /* Generate the new insn.  */
3187       /* ??? If the change fails, we return 0, even though we created
3188          an insn.  I think this is ok.  */
3189       new_insn
3190         = emit_insn_after (gen_rtx_SET (VOIDmode, to,
3191                                         SET_DEST (PATTERN
3192                                                   (insn_computes_expr))),
3193                            insn_computes_expr);
3194
3195       /* Keep block number table up to date.  */
3196       set_block_num (new_insn, BLOCK_NUM (insn_computes_expr));
3197
3198       /* Keep register set table up to date.  */
3199       record_one_set (REGNO (to), new_insn);
3200
3201       gcse_create_count++;
3202       if (gcse_file != NULL)
3203         {
3204           fprintf (gcse_file, "GCSE: Creating insn %d to copy value of reg %d",
3205                    INSN_UID (NEXT_INSN (insn_computes_expr)),
3206                    REGNO (SET_SRC (PATTERN (NEXT_INSN (insn_computes_expr)))));
3207           fprintf (gcse_file, ", computed in insn %d,\n",
3208                    INSN_UID (insn_computes_expr));
3209           fprintf (gcse_file, "      into newly allocated reg %d\n",
3210                    REGNO (to));
3211         }
3212
3213       pat = PATTERN (insn);
3214
3215       /* Do register replacement for INSN.  */
3216       changed = validate_change (insn, &SET_SRC (pat),
3217                                  SET_DEST (PATTERN
3218                                            (NEXT_INSN (insn_computes_expr))),
3219                                  0);
3220
3221       /* We should be able to ignore the return code from validate_change but
3222          to play it safe we check.  */
3223       if (changed)
3224         {
3225           gcse_subst_count++;
3226           if (gcse_file != NULL)
3227             {
3228               fprintf (gcse_file,
3229                        "GCSE: Replacing the source in insn %d with reg %d ",
3230                        INSN_UID (insn),
3231                        REGNO (SET_DEST (PATTERN (NEXT_INSN
3232                                                  (insn_computes_expr)))));
3233               fprintf (gcse_file, "set in insn %d\n",
3234                        INSN_UID (insn_computes_expr)); 
3235             }
3236         }
3237     }
3238
3239   return changed;
3240 }
3241
3242 /* Perform classic GCSE.  This is called by one_classic_gcse_pass after all
3243    the dataflow analysis has been done.
3244
3245    The result is non-zero if a change was made.  */
3246
3247 static int
3248 classic_gcse ()
3249 {
3250   int bb, changed;
3251   rtx insn;
3252
3253   /* Note we start at block 1.  */
3254
3255   changed = 0;
3256   for (bb = 1; bb < n_basic_blocks; bb++)
3257     {
3258       /* Reset tables used to keep track of what's still valid [since the
3259          start of the block].  */
3260       reset_opr_set_tables ();
3261
3262       for (insn = BLOCK_HEAD (bb);
3263            insn != NULL && insn != NEXT_INSN (BLOCK_END (bb));
3264            insn = NEXT_INSN (insn))
3265         {
3266           /* Is insn of form (set (pseudo-reg) ...)?  */
3267           if (GET_CODE (insn) == INSN
3268               && GET_CODE (PATTERN (insn)) == SET
3269               && GET_CODE (SET_DEST (PATTERN (insn))) == REG
3270               && REGNO (SET_DEST (PATTERN (insn))) >= FIRST_PSEUDO_REGISTER)
3271             {
3272               rtx pat = PATTERN (insn);
3273               rtx src = SET_SRC (pat);
3274               struct expr *expr;
3275
3276               if (want_to_gcse_p (src)
3277                   /* Is the expression recorded?  */
3278                   && ((expr = lookup_expr (src)) != NULL)
3279                   /* Is the expression available [at the start of the
3280                      block]?  */
3281                   && TEST_BIT (ae_in[bb], expr->bitmap_index)
3282                   /* Are the operands unchanged since the start of the
3283                      block?  */
3284                   && oprs_not_set_p (src, insn))
3285                 changed |= handle_avail_expr (insn, expr);
3286             }
3287
3288           /* Keep track of everything modified by this insn.  */
3289           /* ??? Need to be careful w.r.t. mods done to INSN.  */
3290           if (INSN_P (insn))
3291             mark_oprs_set (insn);
3292         }
3293     }
3294
3295   return changed;
3296 }
3297
3298 /* Top level routine to perform one classic GCSE pass.
3299
3300    Return non-zero if a change was made.  */
3301
3302 static int
3303 one_classic_gcse_pass (pass)
3304      int pass;
3305 {
3306   int changed = 0;
3307
3308   gcse_subst_count = 0;
3309   gcse_create_count = 0;
3310
3311   alloc_expr_hash_table (max_cuid);
3312   alloc_rd_mem (n_basic_blocks, max_cuid);
3313   compute_expr_hash_table ();
3314   if (gcse_file)
3315     dump_hash_table (gcse_file, "Expression", expr_hash_table,
3316                      expr_hash_table_size, n_exprs);
3317
3318   if (n_exprs > 0)
3319     {
3320       compute_kill_rd ();
3321       compute_rd ();
3322       alloc_avail_expr_mem (n_basic_blocks, n_exprs);
3323       compute_ae_gen ();
3324       compute_ae_kill (ae_gen, ae_kill);
3325       compute_available (ae_gen, ae_kill, ae_out, ae_in);
3326       changed = classic_gcse ();
3327       free_avail_expr_mem ();
3328     }
3329
3330   free_rd_mem ();
3331   free_expr_hash_table ();
3332
3333   if (gcse_file)
3334     {
3335       fprintf (gcse_file, "\n");
3336       fprintf (gcse_file, "GCSE of %s, pass %d: %d bytes needed, %d substs,",
3337                current_function_name, pass, bytes_used, gcse_subst_count);
3338       fprintf (gcse_file, "%d insns created\n", gcse_create_count);
3339     }
3340
3341   return changed;
3342 }
3343 \f
3344 /* Compute copy/constant propagation working variables.  */
3345
3346 /* Local properties of assignments.  */
3347 static sbitmap *cprop_pavloc;
3348 static sbitmap *cprop_absaltered;
3349
3350 /* Global properties of assignments (computed from the local properties).  */
3351 static sbitmap *cprop_avin;
3352 static sbitmap *cprop_avout;
3353
3354 /* Allocate vars used for copy/const propagation.  N_BLOCKS is the number of
3355    basic blocks.  N_SETS is the number of sets.  */
3356
3357 static void
3358 alloc_cprop_mem (n_blocks, n_sets)
3359      int n_blocks, n_sets;
3360 {
3361   cprop_pavloc = sbitmap_vector_alloc (n_blocks, n_sets);
3362   cprop_absaltered = sbitmap_vector_alloc (n_blocks, n_sets);
3363
3364   cprop_avin = sbitmap_vector_alloc (n_blocks, n_sets);
3365   cprop_avout = sbitmap_vector_alloc (n_blocks, n_sets);
3366 }
3367
3368 /* Free vars used by copy/const propagation.  */
3369
3370 static void
3371 free_cprop_mem ()
3372 {
3373   free (cprop_pavloc);
3374   free (cprop_absaltered);
3375   free (cprop_avin);
3376   free (cprop_avout);
3377 }
3378
3379 /* For each block, compute whether X is transparent.  X is either an
3380    expression or an assignment [though we don't care which, for this context
3381    an assignment is treated as an expression].  For each block where an
3382    element of X is modified, set (SET_P == 1) or reset (SET_P == 0) the INDX
3383    bit in BMAP.  */
3384
3385 static void
3386 compute_transp (x, indx, bmap, set_p)
3387      rtx x;
3388      int indx;
3389      sbitmap *bmap;
3390      int set_p;
3391 {
3392   int bb, i, j;
3393   enum rtx_code code;
3394   reg_set *r;
3395   const char *fmt;
3396
3397   /* repeat is used to turn tail-recursion into iteration since GCC
3398      can't do it when there's no return value.  */
3399  repeat:
3400
3401   if (x == 0)
3402     return;
3403
3404   code = GET_CODE (x);
3405   switch (code)
3406     {
3407     case REG:
3408       if (set_p)
3409         {
3410           if (REGNO (x) < FIRST_PSEUDO_REGISTER)
3411             {
3412               for (bb = 0; bb < n_basic_blocks; bb++)
3413                 if (TEST_BIT (reg_set_in_block[bb], REGNO (x)))
3414                   SET_BIT (bmap[bb], indx);
3415             }
3416           else
3417             {
3418               for (r = reg_set_table[REGNO (x)]; r != NULL; r = r->next)
3419                 SET_BIT (bmap[BLOCK_NUM (r->insn)], indx);
3420             }
3421         }
3422       else
3423         {
3424           if (REGNO (x) < FIRST_PSEUDO_REGISTER)
3425             {
3426               for (bb = 0; bb < n_basic_blocks; bb++)
3427                 if (TEST_BIT (reg_set_in_block[bb], REGNO (x)))
3428                   RESET_BIT (bmap[bb], indx);
3429             }
3430           else
3431             {
3432               for (r = reg_set_table[REGNO (x)]; r != NULL; r = r->next)
3433                 RESET_BIT (bmap[BLOCK_NUM (r->insn)], indx);
3434             }
3435         }
3436
3437       return;
3438
3439     case MEM:
3440       if (set_p)
3441         {
3442           for (bb = 0; bb < n_basic_blocks; bb++)
3443             if (mem_set_in_block[bb])
3444               SET_BIT (bmap[bb], indx);
3445         }
3446       else
3447         {
3448           for (bb = 0; bb < n_basic_blocks; bb++)
3449             if (mem_set_in_block[bb])
3450               RESET_BIT (bmap[bb], indx);
3451         }
3452
3453       x = XEXP (x, 0);
3454       goto repeat;
3455
3456     case PC:
3457     case CC0: /*FIXME*/
3458     case CONST:
3459     case CONST_INT:
3460     case CONST_DOUBLE:
3461     case SYMBOL_REF:
3462     case LABEL_REF:
3463     case ADDR_VEC:
3464     case ADDR_DIFF_VEC:
3465       return;
3466
3467     default:
3468       break;
3469     }
3470
3471   for (i = GET_RTX_LENGTH (code) - 1, fmt = GET_RTX_FORMAT (code); i >= 0; i--)
3472     {
3473       if (fmt[i] == 'e')
3474         {
3475           /* If we are about to do the last recursive call
3476              needed at this level, change it into iteration.
3477              This function is called enough to be worth it.  */
3478           if (i == 0)
3479             {
3480               x = XEXP (x, i);
3481               goto repeat;
3482             }
3483
3484           compute_transp (XEXP (x, i), indx, bmap, set_p);
3485         }
3486       else if (fmt[i] == 'E')
3487         for (j = 0; j < XVECLEN (x, i); j++)
3488           compute_transp (XVECEXP (x, i, j), indx, bmap, set_p);
3489     }
3490 }
3491
3492 /* Top level routine to do the dataflow analysis needed by copy/const
3493    propagation.  */
3494
3495 static void
3496 compute_cprop_data ()
3497 {
3498   compute_local_properties (cprop_absaltered, cprop_pavloc, NULL, 1);
3499   compute_available (cprop_pavloc, cprop_absaltered,
3500                      cprop_avout, cprop_avin);
3501 }
3502 \f
3503 /* Copy/constant propagation.  */
3504
3505 /* Maximum number of register uses in an insn that we handle.  */
3506 #define MAX_USES 8
3507
3508 /* Table of uses found in an insn.
3509    Allocated statically to avoid alloc/free complexity and overhead.  */
3510 static struct reg_use reg_use_table[MAX_USES];
3511
3512 /* Index into `reg_use_table' while building it.  */
3513 static int reg_use_count;
3514
3515 /* Set up a list of register numbers used in INSN.  The found uses are stored
3516    in `reg_use_table'.  `reg_use_count' is initialized to zero before entry,
3517    and contains the number of uses in the table upon exit.
3518
3519    ??? If a register appears multiple times we will record it multiple times.
3520    This doesn't hurt anything but it will slow things down.  */
3521
3522 static void
3523 find_used_regs (x)
3524      rtx x;
3525 {
3526   int i, j;
3527   enum rtx_code code;
3528   const char *fmt;
3529
3530   /* repeat is used to turn tail-recursion into iteration since GCC
3531      can't do it when there's no return value.  */
3532  repeat:
3533
3534   if (x == 0)
3535     return;
3536
3537   code = GET_CODE (x);
3538   switch (code)
3539     {
3540     case REG:
3541       if (reg_use_count == MAX_USES)
3542         return;
3543
3544       reg_use_table[reg_use_count].reg_rtx = x;
3545       reg_use_count++;
3546       return;
3547
3548     case MEM:
3549       x = XEXP (x, 0);
3550       goto repeat;
3551
3552     case PC:
3553     case CC0:
3554     case CONST:
3555     case CONST_INT:
3556     case CONST_DOUBLE:
3557     case SYMBOL_REF:
3558     case LABEL_REF:
3559     case CLOBBER:
3560     case ADDR_VEC:
3561     case ADDR_DIFF_VEC:
3562     case ASM_INPUT: /*FIXME*/
3563       return;
3564
3565     case SET:
3566       if (GET_CODE (SET_DEST (x)) == MEM)
3567         find_used_regs (SET_DEST (x));
3568       x = SET_SRC (x);
3569       goto repeat;
3570
3571     default:
3572       break;
3573     }
3574
3575   /* Recursively scan the operands of this expression.  */
3576
3577   for (i = GET_RTX_LENGTH (code) - 1, fmt = GET_RTX_FORMAT (code); i >= 0; i--)
3578     {
3579       if (fmt[i] == 'e')
3580         {
3581           /* If we are about to do the last recursive call
3582              needed at this level, change it into iteration.
3583              This function is called enough to be worth it.  */
3584           if (i == 0)
3585             {
3586               x = XEXP (x, 0);
3587               goto repeat;
3588             }
3589
3590           find_used_regs (XEXP (x, i));
3591         }
3592       else if (fmt[i] == 'E')
3593         for (j = 0; j < XVECLEN (x, i); j++)
3594           find_used_regs (XVECEXP (x, i, j));
3595     }
3596 }
3597
3598 /* Try to replace all non-SET_DEST occurrences of FROM in INSN with TO.
3599    Returns non-zero is successful.  */
3600
3601 static int
3602 try_replace_reg (from, to, insn)
3603      rtx from, to, insn;
3604 {
3605   rtx note;
3606   rtx src;
3607   int success;
3608   rtx set;
3609
3610   note = find_reg_note (insn, REG_EQUAL, NULL_RTX);
3611
3612   if (!note)
3613     note = find_reg_note (insn, REG_EQUIV, NULL_RTX);
3614
3615   /* If this fails we could try to simplify the result of the
3616      replacement and attempt to recognize the simplified insn.
3617
3618      But we need a general simplify_rtx that doesn't have pass
3619      specific state variables.  I'm not aware of one at the moment.  */
3620
3621   success = validate_replace_src (from, to, insn);
3622   set = single_set (insn);
3623
3624   /* We've failed to do replacement. Try to add REG_EQUAL note to not loose
3625      information.  */
3626   if (!success && !note)
3627     {
3628       if (!set)
3629         return 0;
3630
3631       note = REG_NOTES (insn) = gen_rtx_EXPR_LIST (REG_EQUAL,
3632                                                    copy_rtx (SET_SRC (set)),
3633                                                    REG_NOTES (insn));
3634     }
3635
3636   /* Always do the replacement in REQ_EQUAL and REG_EQUIV notes.  Also
3637      try to simplify them.  */
3638   if (note)
3639     {
3640       rtx simplified;
3641
3642       if (!validate_replace_rtx_subexp (from, to, insn, &XEXP (note, 0)))
3643         abort();
3644
3645       src = XEXP (note, 0);
3646
3647       /* Try to simplify resulting note. */
3648       simplified = simplify_rtx (src);
3649       if (simplified)
3650         {
3651           src = simplified;
3652           XEXP (note, 0) = src;
3653         }
3654
3655       /* REG_EQUAL may get simplified into register.
3656          We don't allow that. Remove that note. This code ought
3657          not to hapen, because previous code ought to syntetize
3658          reg-reg move, but be on the safe side.  */
3659       else if (REG_P (src))
3660         remove_note (insn, note);
3661     }
3662   return success;
3663 }
3664
3665 /* Find a set of REGNOs that are available on entry to INSN's block.  Returns
3666    NULL no such set is found.  */
3667
3668 static struct expr *
3669 find_avail_set (regno, insn)
3670      int regno;
3671      rtx insn;
3672 {
3673   /* SET1 contains the last set found that can be returned to the caller for
3674      use in a substitution.  */
3675   struct expr *set1 = 0;
3676  
3677   /* Loops are not possible here.  To get a loop we would need two sets
3678      available at the start of the block containing INSN.  ie we would
3679      need two sets like this available at the start of the block:
3680
3681        (set (reg X) (reg Y))
3682        (set (reg Y) (reg X))
3683
3684      This can not happen since the set of (reg Y) would have killed the
3685      set of (reg X) making it unavailable at the start of this block.  */
3686   while (1)
3687      {
3688       rtx src;
3689       struct expr *set = lookup_set (regno, NULL_RTX);
3690
3691       /* Find a set that is available at the start of the block
3692          which contains INSN.  */
3693       while (set)
3694         {
3695           if (TEST_BIT (cprop_avin[BLOCK_NUM (insn)], set->bitmap_index))
3696             break;
3697           set = next_set (regno, set);
3698         }
3699
3700       /* If no available set was found we've reached the end of the
3701          (possibly empty) copy chain.  */
3702       if (set == 0)
3703         break;
3704
3705       if (GET_CODE (set->expr) != SET)
3706         abort ();
3707
3708       src = SET_SRC (set->expr);
3709
3710       /* We know the set is available.
3711          Now check that SRC is ANTLOC (i.e. none of the source operands
3712          have changed since the start of the block).  
3713
3714          If the source operand changed, we may still use it for the next
3715          iteration of this loop, but we may not use it for substitutions.  */
3716
3717       if (CONSTANT_P (src) || oprs_not_set_p (src, insn))
3718         set1 = set;
3719
3720       /* If the source of the set is anything except a register, then
3721          we have reached the end of the copy chain.  */
3722       if (GET_CODE (src) != REG)
3723         break;
3724
3725       /* Follow the copy chain, ie start another iteration of the loop
3726          and see if we have an available copy into SRC.  */
3727       regno = REGNO (src);
3728      }
3729
3730   /* SET1 holds the last set that was available and anticipatable at
3731      INSN.  */
3732   return set1;
3733 }
3734
3735 /* Subroutine of cprop_insn that tries to propagate constants into
3736    JUMP_INSNS.  INSN must be a conditional jump; COPY is a copy of it
3737    that we can use for substitutions.
3738    REG_USED is the use we will try to replace, SRC is the constant we
3739    will try to substitute for it.
3740    Returns nonzero if a change was made.  */
3741
3742 static int
3743 cprop_jump (insn, copy, reg_used, src)
3744      rtx insn, copy;
3745      struct reg_use *reg_used;
3746      rtx src;
3747 {
3748   rtx set = PATTERN (copy);
3749   rtx temp;
3750
3751   /* Replace the register with the appropriate constant.  */
3752   replace_rtx (SET_SRC (set), reg_used->reg_rtx, src);
3753
3754   temp = simplify_ternary_operation (GET_CODE (SET_SRC (set)),
3755                                      GET_MODE (SET_SRC (set)),
3756                                      GET_MODE (XEXP (SET_SRC (set), 0)),
3757                                      XEXP (SET_SRC (set), 0),
3758                                      XEXP (SET_SRC (set), 1),
3759                                      XEXP (SET_SRC (set), 2));
3760
3761   /* If no simplification can be made, then try the next
3762      register.  */
3763   if (temp == 0)
3764     return 0;
3765  
3766   SET_SRC (set) = temp;
3767
3768   /* That may have changed the structure of TEMP, so
3769      force it to be rerecognized if it has not turned
3770      into a nop or unconditional jump.  */
3771                 
3772   INSN_CODE (copy) = -1;
3773   if ((SET_DEST (set) == pc_rtx
3774        && (SET_SRC (set) == pc_rtx
3775            || GET_CODE (SET_SRC (set)) == LABEL_REF))
3776       || recog (PATTERN (copy), copy, NULL) >= 0)
3777     {
3778       /* This has either become an unconditional jump
3779          or a nop-jump.  We'd like to delete nop jumps
3780          here, but doing so confuses gcse.  So we just
3781          make the replacement and let later passes
3782          sort things out.  */
3783       PATTERN (insn) = set;
3784       INSN_CODE (insn) = -1;
3785
3786       /* One less use of the label this insn used to jump to
3787          if we turned this into a NOP jump.  */
3788       if (SET_SRC (set) == pc_rtx && JUMP_LABEL (insn) != 0)
3789         --LABEL_NUSES (JUMP_LABEL (insn));
3790
3791       /* If this has turned into an unconditional jump,
3792          then put a barrier after it so that the unreachable
3793          code will be deleted.  */
3794       if (GET_CODE (SET_SRC (set)) == LABEL_REF)
3795         emit_barrier_after (insn);
3796
3797       run_jump_opt_after_gcse = 1;
3798
3799       const_prop_count++;
3800       if (gcse_file != NULL)
3801         {
3802           fprintf (gcse_file,
3803                    "CONST-PROP: Replacing reg %d in insn %d with constant ",
3804                    REGNO (reg_used->reg_rtx), INSN_UID (insn));
3805           print_rtl (gcse_file, src);
3806           fprintf (gcse_file, "\n");
3807         }
3808
3809       return 1;
3810     }
3811   return 0;
3812 }
3813
3814 #ifdef HAVE_cc0
3815
3816 /* Subroutine of cprop_insn that tries to propagate constants into JUMP_INSNS
3817    for machines that have CC0.  INSN is a single set that stores into CC0;
3818    the insn following it is a conditional jump.  REG_USED is the use we will
3819    try to replace, SRC is the constant we will try to substitute for it.
3820    Returns nonzero if a change was made.  */
3821
3822 static int
3823 cprop_cc0_jump (insn, reg_used, src)
3824      rtx insn;
3825      struct reg_use *reg_used;
3826      rtx src;
3827 {
3828   rtx jump = NEXT_INSN (insn);
3829   rtx copy = copy_rtx (jump);
3830   rtx set = PATTERN (copy);
3831
3832   /* We need to copy the source of the cc0 setter, as cprop_jump is going to
3833      substitute into it.  */
3834   replace_rtx (SET_SRC (set), cc0_rtx, copy_rtx (SET_SRC (PATTERN (insn))));
3835   if (! cprop_jump (jump, copy, reg_used, src))
3836     return 0;
3837
3838   /* If we succeeded, delete the cc0 setter.  */
3839   PUT_CODE (insn, NOTE);
3840   NOTE_LINE_NUMBER (insn) = NOTE_INSN_DELETED;
3841   NOTE_SOURCE_FILE (insn) = 0;
3842   return 1;
3843  }
3844 #endif
3845  
3846 /* Perform constant and copy propagation on INSN.
3847    The result is non-zero if a change was made.  */
3848
3849 static int
3850 cprop_insn (insn, alter_jumps)
3851      rtx insn;
3852      int alter_jumps;
3853 {
3854   struct reg_use *reg_used;
3855   int changed = 0;
3856   rtx note;
3857
3858   /* Only propagate into SETs.  Note that a conditional jump is a
3859      SET with pc_rtx as the destination.  */
3860   if ((GET_CODE (insn) != INSN
3861        && GET_CODE (insn) != JUMP_INSN)
3862       || GET_CODE (PATTERN (insn)) != SET)
3863     return 0;
3864
3865   reg_use_count = 0;
3866   find_used_regs (PATTERN (insn));
3867   
3868   note = find_reg_note (insn, REG_EQUIV, NULL_RTX);
3869   if (!note)
3870     note = find_reg_note (insn, REG_EQUAL, NULL_RTX);
3871
3872   /* We may win even when propagating constants into notes. */
3873   if (note)
3874     find_used_regs (XEXP (note, 0));
3875
3876   for (reg_used = &reg_use_table[0]; reg_use_count > 0;
3877        reg_used++, reg_use_count--)
3878     {
3879       unsigned int regno = REGNO (reg_used->reg_rtx);
3880       rtx pat, src;
3881       struct expr *set;
3882
3883       /* Ignore registers created by GCSE.
3884          We do this because ... */
3885       if (regno >= max_gcse_regno)
3886         continue;
3887
3888       /* If the register has already been set in this block, there's
3889          nothing we can do.  */
3890       if (! oprs_not_set_p (reg_used->reg_rtx, insn))
3891         continue;
3892
3893       /* Find an assignment that sets reg_used and is available
3894          at the start of the block.  */
3895       set = find_avail_set (regno, insn);
3896       if (! set)
3897         continue;
3898   
3899       pat = set->expr;
3900       /* ??? We might be able to handle PARALLELs.  Later.  */
3901       if (GET_CODE (pat) != SET)
3902         abort ();
3903
3904       src = SET_SRC (pat);
3905
3906       /* Constant propagation.  */
3907       if (GET_CODE (src) == CONST_INT || GET_CODE (src) == CONST_DOUBLE
3908           || GET_CODE (src) == SYMBOL_REF)
3909         {
3910           /* Handle normal insns first.  */
3911           if (GET_CODE (insn) == INSN
3912               && try_replace_reg (reg_used->reg_rtx, src, insn))
3913             {
3914               changed = 1;
3915               const_prop_count++;
3916               if (gcse_file != NULL)
3917                 {
3918                   fprintf (gcse_file, "CONST-PROP: Replacing reg %d in ",
3919                            regno);
3920                   fprintf (gcse_file, "insn %d with constant ",
3921                            INSN_UID (insn));
3922                   print_rtl (gcse_file, src);
3923                   fprintf (gcse_file, "\n");
3924                 }
3925
3926               /* The original insn setting reg_used may or may not now be
3927                  deletable.  We leave the deletion to flow.  */
3928             }
3929
3930           /* Try to propagate a CONST_INT into a conditional jump.
3931              We're pretty specific about what we will handle in this
3932              code, we can extend this as necessary over time.
3933
3934              Right now the insn in question must look like
3935              (set (pc) (if_then_else ...))  */
3936           else if (alter_jumps
3937                    && GET_CODE (insn) == JUMP_INSN
3938                    && condjump_p (insn)
3939                    && ! simplejump_p (insn))
3940             changed |= cprop_jump (insn, copy_rtx (insn), reg_used, src);
3941 #ifdef HAVE_cc0
3942           /* Similar code for machines that use a pair of CC0 setter and
3943              conditional jump insn.  */
3944           else if (alter_jumps
3945                    && GET_CODE (PATTERN (insn)) == SET
3946                    && SET_DEST (PATTERN (insn)) == cc0_rtx
3947                    && GET_CODE (NEXT_INSN (insn)) == JUMP_INSN
3948                    && condjump_p (NEXT_INSN (insn))
3949                    && ! simplejump_p (NEXT_INSN (insn)))
3950             changed |= cprop_cc0_jump (insn, reg_used, src);
3951 #endif
3952         }
3953       else if (GET_CODE (src) == REG
3954                && REGNO (src) >= FIRST_PSEUDO_REGISTER
3955                && REGNO (src) != regno)
3956         {
3957           if (try_replace_reg (reg_used->reg_rtx, src, insn))
3958             {
3959               changed = 1;
3960               copy_prop_count++;
3961               if (gcse_file != NULL)
3962                 {
3963                   fprintf (gcse_file, "COPY-PROP: Replacing reg %d in insn %d",
3964                            regno, INSN_UID (insn));
3965                   fprintf (gcse_file, " with reg %d\n", REGNO (src));
3966                 }
3967
3968               /* The original insn setting reg_used may or may not now be
3969                  deletable.  We leave the deletion to flow.  */
3970               /* FIXME: If it turns out that the insn isn't deletable,
3971                  then we may have unnecessarily extended register lifetimes
3972                  and made things worse.  */
3973             }
3974         }
3975     }
3976
3977   return changed;
3978 }
3979
3980 /* Forward propagate copies.  This includes copies and constants.  Return
3981    non-zero if a change was made.  */
3982
3983 static int
3984 cprop (alter_jumps)
3985      int alter_jumps;
3986 {
3987   int bb, changed;
3988   rtx insn;
3989
3990   /* Note we start at block 1.  */
3991
3992   changed = 0;
3993   for (bb = 1; bb < n_basic_blocks; bb++)
3994     {
3995       /* Reset tables used to keep track of what's still valid [since the
3996          start of the block].  */
3997       reset_opr_set_tables ();
3998
3999       for (insn = BLOCK_HEAD (bb);
4000            insn != NULL && insn != NEXT_INSN (BLOCK_END (bb));
4001            insn = NEXT_INSN (insn))
4002         {
4003           if (INSN_P (insn))
4004             {
4005               changed |= cprop_insn (insn, alter_jumps);
4006
4007               /* Keep track of everything modified by this insn.  */
4008               /* ??? Need to be careful w.r.t. mods done to INSN.  Don't
4009                  call mark_oprs_set if we turned the insn into a NOTE.  */
4010               if (GET_CODE (insn) != NOTE)
4011                 mark_oprs_set (insn);
4012             }
4013         }
4014     }
4015
4016   if (gcse_file != NULL)
4017     fprintf (gcse_file, "\n");
4018
4019   return changed;
4020 }
4021
4022 /* Perform one copy/constant propagation pass.
4023    F is the first insn in the function.
4024    PASS is the pass count.  */
4025
4026 static int
4027 one_cprop_pass (pass, alter_jumps)
4028      int pass;
4029      int alter_jumps;
4030 {
4031   int changed = 0;
4032
4033   const_prop_count = 0;
4034   copy_prop_count = 0;
4035
4036   alloc_set_hash_table (max_cuid);
4037   compute_set_hash_table ();
4038   if (gcse_file)
4039     dump_hash_table (gcse_file, "SET", set_hash_table, set_hash_table_size,
4040                      n_sets);
4041   if (n_sets > 0)
4042     {
4043       alloc_cprop_mem (n_basic_blocks, n_sets);
4044       compute_cprop_data ();
4045       changed = cprop (alter_jumps);
4046       free_cprop_mem ();
4047     }
4048
4049   free_set_hash_table ();
4050
4051   if (gcse_file)
4052     {
4053       fprintf (gcse_file, "CPROP of %s, pass %d: %d bytes needed, ",
4054                current_function_name, pass, bytes_used);
4055       fprintf (gcse_file, "%d const props, %d copy props\n\n",
4056                const_prop_count, copy_prop_count);
4057     }
4058
4059   return changed;
4060 }
4061 \f
4062 /* Compute PRE+LCM working variables.  */
4063
4064 /* Local properties of expressions.  */
4065 /* Nonzero for expressions that are transparent in the block.  */
4066 static sbitmap *transp;
4067
4068 /* Nonzero for expressions that are transparent at the end of the block.
4069    This is only zero for expressions killed by abnormal critical edge
4070    created by a calls.  */
4071 static sbitmap *transpout;
4072
4073 /* Nonzero for expressions that are computed (available) in the block.  */
4074 static sbitmap *comp;
4075
4076 /* Nonzero for expressions that are locally anticipatable in the block.  */
4077 static sbitmap *antloc;
4078
4079 /* Nonzero for expressions where this block is an optimal computation
4080    point.  */
4081 static sbitmap *pre_optimal;
4082
4083 /* Nonzero for expressions which are redundant in a particular block.  */
4084 static sbitmap *pre_redundant;
4085
4086 /* Nonzero for expressions which should be inserted on a specific edge.  */
4087 static sbitmap *pre_insert_map;
4088
4089 /* Nonzero for expressions which should be deleted in a specific block.  */
4090 static sbitmap *pre_delete_map;
4091
4092 /* Contains the edge_list returned by pre_edge_lcm.  */
4093 static struct edge_list *edge_list;
4094
4095 /* Redundant insns.  */
4096 static sbitmap pre_redundant_insns;
4097
4098 /* Allocate vars used for PRE analysis.  */
4099
4100 static void
4101 alloc_pre_mem (n_blocks, n_exprs)
4102      int n_blocks, n_exprs;
4103 {
4104   transp = sbitmap_vector_alloc (n_blocks, n_exprs);
4105   comp = sbitmap_vector_alloc (n_blocks, n_exprs);
4106   antloc = sbitmap_vector_alloc (n_blocks, n_exprs);
4107
4108   pre_optimal = NULL;
4109   pre_redundant = NULL;
4110   pre_insert_map = NULL;
4111   pre_delete_map = NULL;
4112   ae_in = NULL;
4113   ae_out = NULL;
4114   ae_kill = sbitmap_vector_alloc (n_blocks, n_exprs);
4115
4116   /* pre_insert and pre_delete are allocated later.  */
4117 }
4118
4119 /* Free vars used for PRE analysis.  */
4120
4121 static void
4122 free_pre_mem ()
4123 {
4124   free (transp);
4125   free (comp);
4126
4127   /* ANTLOC and AE_KILL are freed just after pre_lcm finishes.  */
4128
4129   if (pre_optimal)
4130     free (pre_optimal);
4131   if (pre_redundant)
4132     free (pre_redundant);
4133   if (pre_insert_map)
4134     free (pre_insert_map);
4135   if (pre_delete_map)
4136     free (pre_delete_map);
4137
4138   if (ae_in)
4139     free (ae_in);
4140   if (ae_out)
4141     free (ae_out);
4142
4143   transp = comp = NULL;
4144   pre_optimal = pre_redundant = pre_insert_map = pre_delete_map = NULL;
4145   ae_in = ae_out = NULL;
4146 }
4147
4148 /* Top level routine to do the dataflow analysis needed by PRE.  */
4149
4150 static void
4151 compute_pre_data ()
4152 {
4153   int i;
4154
4155   compute_local_properties (transp, comp, antloc, 0);
4156   sbitmap_vector_zero (ae_kill, n_basic_blocks);
4157
4158   /* Compute ae_kill for each basic block using:
4159
4160      ~(TRANSP | COMP)
4161
4162      This is significantly faster than compute_ae_kill.  */
4163
4164   for (i = 0; i < n_basic_blocks; i++)
4165     {
4166       sbitmap_a_or_b (ae_kill[i], transp[i], comp[i]);
4167       sbitmap_not (ae_kill[i], ae_kill[i]);
4168     }
4169
4170   edge_list = pre_edge_lcm (gcse_file, n_exprs, transp, comp, antloc,
4171                             ae_kill, &pre_insert_map, &pre_delete_map);
4172   free (antloc);
4173   antloc = NULL;
4174   free (ae_kill);
4175   ae_kill = NULL; 
4176 }
4177 \f
4178 /* PRE utilities */
4179
4180 /* Return non-zero if an occurrence of expression EXPR in OCCR_BB would reach
4181    block BB.
4182
4183    VISITED is a pointer to a working buffer for tracking which BB's have
4184    been visited.  It is NULL for the top-level call.
4185
4186    We treat reaching expressions that go through blocks containing the same
4187    reaching expression as "not reaching".  E.g. if EXPR is generated in blocks
4188    2 and 3, INSN is in block 4, and 2->3->4, we treat the expression in block
4189    2 as not reaching.  The intent is to improve the probability of finding
4190    only one reaching expression and to reduce register lifetimes by picking
4191    the closest such expression.  */
4192
4193 static int
4194 pre_expr_reaches_here_p_work (occr_bb, expr, bb, visited)
4195      int occr_bb;
4196      struct expr *expr;
4197      int bb;
4198      char *visited;
4199 {
4200   edge pred;
4201
4202   for (pred = BASIC_BLOCK (bb)->pred; pred != NULL; pred = pred->pred_next)
4203     {
4204       int pred_bb = pred->src->index;
4205
4206       if (pred->src == ENTRY_BLOCK_PTR
4207           /* Has predecessor has already been visited?  */
4208           || visited[pred_bb])
4209         ;/* Nothing to do.  */
4210
4211       /* Does this predecessor generate this expression?  */
4212       else if (TEST_BIT (comp[pred_bb], expr->bitmap_index))
4213         {
4214           /* Is this the occurrence we're looking for?
4215              Note that there's only one generating occurrence per block
4216              so we just need to check the block number.  */
4217           if (occr_bb == pred_bb)
4218             return 1;
4219
4220           visited[pred_bb] = 1;
4221         }
4222       /* Ignore this predecessor if it kills the expression.  */
4223       else if (! TEST_BIT (transp[pred_bb], expr->bitmap_index))
4224         visited[pred_bb] = 1;
4225
4226       /* Neither gen nor kill.  */
4227       else
4228         {
4229           visited[pred_bb] = 1;
4230           if (pre_expr_reaches_here_p_work (occr_bb, expr, pred_bb, visited))
4231             return 1;
4232         }
4233     }
4234
4235   /* All paths have been checked.  */
4236   return 0;
4237 }
4238
4239 /* The wrapper for pre_expr_reaches_here_work that ensures that any
4240    memory allocated for that function is returned. */
4241
4242 static int
4243 pre_expr_reaches_here_p (occr_bb, expr, bb)
4244      int occr_bb;
4245      struct expr *expr;
4246      int bb;
4247 {
4248   int rval;
4249   char *visited = (char *) xcalloc (n_basic_blocks, 1);
4250
4251   rval = pre_expr_reaches_here_p_work(occr_bb, expr, bb, visited);
4252
4253   free (visited);
4254   return rval;
4255 }
4256 \f
4257
4258 /* Given an expr, generate RTL which we can insert at the end of a BB,
4259    or on an edge.  Set the block number of any insns generated to 
4260    the value of BB.  */
4261
4262 static rtx
4263 process_insert_insn (expr)
4264      struct expr *expr;
4265 {
4266   rtx reg = expr->reaching_reg;
4267   rtx pat, copied_expr;
4268   rtx first_new_insn;
4269
4270   start_sequence ();
4271   copied_expr = copy_rtx (expr->expr);
4272   emit_move_insn (reg, copied_expr);
4273   first_new_insn = get_insns ();
4274   pat = gen_sequence ();
4275   end_sequence ();
4276
4277   return pat;
4278 }
4279   
4280 /* Add EXPR to the end of basic block BB.
4281
4282    This is used by both the PRE and code hoisting.
4283
4284    For PRE, we want to verify that the expr is either transparent
4285    or locally anticipatable in the target block.  This check makes
4286    no sense for code hoisting.  */
4287
4288 static void
4289 insert_insn_end_bb (expr, bb, pre)
4290      struct expr *expr;
4291      int bb;
4292      int pre;
4293 {
4294   rtx insn = BLOCK_END (bb);
4295   rtx new_insn;
4296   rtx reg = expr->reaching_reg;
4297   int regno = REGNO (reg);
4298   rtx pat;
4299   int i;
4300
4301   pat = process_insert_insn (expr);
4302
4303   /* If the last insn is a jump, insert EXPR in front [taking care to
4304      handle cc0, etc. properly].  */
4305
4306   if (GET_CODE (insn) == JUMP_INSN)
4307     {
4308 #ifdef HAVE_cc0
4309       rtx note;
4310 #endif
4311
4312       /* If this is a jump table, then we can't insert stuff here.  Since
4313          we know the previous real insn must be the tablejump, we insert
4314          the new instruction just before the tablejump.  */
4315       if (GET_CODE (PATTERN (insn)) == ADDR_VEC
4316           || GET_CODE (PATTERN (insn)) == ADDR_DIFF_VEC)
4317         insn = prev_real_insn (insn);
4318
4319 #ifdef HAVE_cc0
4320       /* FIXME: 'twould be nice to call prev_cc0_setter here but it aborts
4321          if cc0 isn't set.  */
4322       note = find_reg_note (insn, REG_CC_SETTER, NULL_RTX);
4323       if (note)
4324         insn = XEXP (note, 0);
4325       else
4326         {
4327           rtx maybe_cc0_setter = prev_nonnote_insn (insn);
4328           if (maybe_cc0_setter
4329               && INSN_P (maybe_cc0_setter)
4330               && sets_cc0_p (PATTERN (maybe_cc0_setter)))
4331             insn = maybe_cc0_setter;
4332         }
4333 #endif
4334       /* FIXME: What if something in cc0/jump uses value set in new insn?  */
4335       new_insn = emit_block_insn_before (pat, insn, BASIC_BLOCK (bb));
4336     }
4337
4338   /* Likewise if the last insn is a call, as will happen in the presence
4339      of exception handling.  */
4340   else if (GET_CODE (insn) == CALL_INSN)
4341     {
4342       HARD_REG_SET parm_regs;
4343       int nparm_regs;
4344       rtx p;
4345
4346       /* Keeping in mind SMALL_REGISTER_CLASSES and parameters in registers,
4347          we search backward and place the instructions before the first
4348          parameter is loaded.  Do this for everyone for consistency and a
4349          presumtion that we'll get better code elsewhere as well.  
4350
4351          It should always be the case that we can put these instructions
4352          anywhere in the basic block with performing PRE optimizations.
4353          Check this.  */
4354
4355       if (pre
4356           && !TEST_BIT (antloc[bb], expr->bitmap_index)
4357           && !TEST_BIT (transp[bb], expr->bitmap_index))
4358         abort ();
4359
4360       /* Since different machines initialize their parameter registers
4361          in different orders, assume nothing.  Collect the set of all
4362          parameter registers.  */
4363       CLEAR_HARD_REG_SET (parm_regs);
4364       nparm_regs = 0;
4365       for (p = CALL_INSN_FUNCTION_USAGE (insn); p ; p = XEXP (p, 1))
4366         if (GET_CODE (XEXP (p, 0)) == USE
4367             && GET_CODE (XEXP (XEXP (p, 0), 0)) == REG)
4368           {
4369             if (REGNO (XEXP (XEXP (p, 0), 0)) >= FIRST_PSEUDO_REGISTER)
4370               abort ();
4371
4372             SET_HARD_REG_BIT (parm_regs, REGNO (XEXP (XEXP (p, 0), 0)));
4373             nparm_regs++;
4374           }
4375
4376       /* Search backward for the first set of a register in this set.  */
4377       while (nparm_regs && BLOCK_HEAD (bb) != insn)
4378         {
4379           insn = PREV_INSN (insn);
4380           p = single_set (insn);
4381           if (p && GET_CODE (SET_DEST (p)) == REG
4382               && REGNO (SET_DEST (p)) < FIRST_PSEUDO_REGISTER
4383               && TEST_HARD_REG_BIT (parm_regs, REGNO (SET_DEST (p))))
4384             {
4385               CLEAR_HARD_REG_BIT (parm_regs, REGNO (SET_DEST (p)));
4386               nparm_regs--;
4387             }
4388         }
4389       
4390       /* If we found all the parameter loads, then we want to insert
4391          before the first parameter load.
4392
4393          If we did not find all the parameter loads, then we might have
4394          stopped on the head of the block, which could be a CODE_LABEL.
4395          If we inserted before the CODE_LABEL, then we would be putting
4396          the insn in the wrong basic block.  In that case, put the insn
4397          after the CODE_LABEL.  Also, respect NOTE_INSN_BASIC_BLOCK.  */
4398       while (GET_CODE (insn) == CODE_LABEL
4399              || NOTE_INSN_BASIC_BLOCK_P (insn))
4400         insn = NEXT_INSN (insn);
4401
4402       new_insn = emit_block_insn_before (pat, insn, BASIC_BLOCK (bb));
4403     }
4404   else
4405     {
4406       new_insn = emit_insn_after (pat, insn);
4407       BLOCK_END (bb) = new_insn;
4408     }
4409
4410   /* Keep block number table up to date.
4411      Note, PAT could be a multiple insn sequence, we have to make
4412      sure that each insn in the sequence is handled.  */
4413   if (GET_CODE (pat) == SEQUENCE)
4414     {
4415       for (i = 0; i < XVECLEN (pat, 0); i++)
4416         {
4417           rtx insn = XVECEXP (pat, 0, i);
4418
4419           set_block_num (insn, bb);
4420           if (INSN_P (insn))
4421             add_label_notes (PATTERN (insn), new_insn);
4422
4423           note_stores (PATTERN (insn), record_set_info, insn);
4424         }
4425     }
4426   else
4427     {
4428       add_label_notes (SET_SRC (pat), new_insn);
4429       set_block_num (new_insn, bb);
4430
4431       /* Keep register set table up to date.  */
4432       record_one_set (regno, new_insn);
4433     }
4434
4435   gcse_create_count++;
4436
4437   if (gcse_file)
4438     {
4439       fprintf (gcse_file, "PRE/HOIST: end of bb %d, insn %d, ",
4440                bb, INSN_UID (new_insn));
4441       fprintf (gcse_file, "copying expression %d to reg %d\n",
4442                expr->bitmap_index, regno);
4443     }
4444 }
4445
4446 /* Insert partially redundant expressions on edges in the CFG to make
4447    the expressions fully redundant.  */
4448
4449 static int
4450 pre_edge_insert (edge_list, index_map)
4451      struct edge_list *edge_list;
4452      struct expr **index_map;
4453 {
4454   int e, i, j, num_edges, set_size, did_insert = 0;
4455   sbitmap *inserted;
4456
4457   /* Where PRE_INSERT_MAP is nonzero, we add the expression on that edge
4458      if it reaches any of the deleted expressions.  */
4459
4460   set_size = pre_insert_map[0]->size;
4461   num_edges = NUM_EDGES (edge_list);
4462   inserted = sbitmap_vector_alloc (num_edges, n_exprs);
4463   sbitmap_vector_zero (inserted, num_edges);
4464
4465   for (e = 0; e < num_edges; e++)
4466     {
4467       int indx;
4468       basic_block pred = INDEX_EDGE_PRED_BB (edge_list, e);
4469       int bb = pred->index;
4470
4471       for (i = indx = 0; i < set_size; i++, indx += SBITMAP_ELT_BITS)
4472         {
4473           SBITMAP_ELT_TYPE insert = pre_insert_map[e]->elms[i];
4474
4475           for (j = indx; insert && j < n_exprs; j++, insert >>= 1)
4476             if ((insert & 1) != 0 && index_map[j]->reaching_reg != NULL_RTX)
4477               {
4478                 struct expr *expr = index_map[j];
4479                 struct occr *occr;
4480
4481                 /* Now look at each deleted occurence of this expression.  */
4482                 for (occr = expr->antic_occr; occr != NULL; occr = occr->next)
4483                   {
4484                     if (! occr->deleted_p)
4485                       continue;
4486
4487                     /* Insert this expression on this edge if if it would
4488                        reach the deleted occurence in BB.  */
4489                     if (!TEST_BIT (inserted[e], j))
4490                       {
4491                         rtx insn;
4492                         edge eg = INDEX_EDGE (edge_list, e);
4493
4494                         /* We can't insert anything on an abnormal and
4495                            critical edge, so we insert the insn at the end of
4496                            the previous block. There are several alternatives
4497                            detailed in Morgans book P277 (sec 10.5) for
4498                            handling this situation.  This one is easiest for
4499                            now.  */
4500
4501                         if ((eg->flags & EDGE_ABNORMAL) == EDGE_ABNORMAL)
4502                           insert_insn_end_bb (index_map[j], bb, 0);
4503                         else
4504                           {
4505                             insn = process_insert_insn (index_map[j]);
4506                             insert_insn_on_edge (insn, eg);
4507                           }
4508
4509                         if (gcse_file)
4510                           {
4511                             fprintf (gcse_file, "PRE/HOIST: edge (%d,%d), ",
4512                                      bb,
4513                                      INDEX_EDGE_SUCC_BB (edge_list, e)->index);
4514                             fprintf (gcse_file, "copy expression %d\n",
4515                                      expr->bitmap_index);
4516                           }
4517
4518                         SET_BIT (inserted[e], j);
4519                         did_insert = 1;
4520                         gcse_create_count++;
4521                       }
4522                   }
4523               }
4524         }
4525     }
4526
4527   free (inserted);
4528   return did_insert;
4529 }
4530
4531 /* Copy the result of INSN to REG.  INDX is the expression number.  */
4532
4533 static void
4534 pre_insert_copy_insn (expr, insn)
4535      struct expr *expr;
4536      rtx insn;
4537 {
4538   rtx reg = expr->reaching_reg;
4539   int regno = REGNO (reg);
4540   int indx = expr->bitmap_index;
4541   rtx set = single_set (insn);
4542   rtx new_insn;
4543   int bb = BLOCK_NUM (insn);
4544
4545   if (!set)
4546     abort ();
4547
4548   new_insn = emit_insn_after (gen_rtx_SET (VOIDmode, reg, SET_DEST (set)),
4549                               insn);
4550
4551   /* Keep block number table up to date.  */
4552   set_block_num (new_insn, bb);
4553
4554   /* Keep register set table up to date.  */
4555   record_one_set (regno, new_insn);
4556   if (insn == BLOCK_END (bb))
4557     BLOCK_END (bb) = new_insn;
4558
4559   gcse_create_count++;
4560
4561   if (gcse_file)
4562     fprintf (gcse_file,
4563              "PRE: bb %d, insn %d, copy expression %d in insn %d to reg %d\n",
4564               BLOCK_NUM (insn), INSN_UID (new_insn), indx,
4565               INSN_UID (insn), regno);
4566 }
4567
4568 /* Copy available expressions that reach the redundant expression
4569    to `reaching_reg'.  */
4570
4571 static void
4572 pre_insert_copies ()
4573 {
4574   unsigned int i;
4575   struct expr *expr;
4576   struct occr *occr;
4577   struct occr *avail;
4578
4579   /* For each available expression in the table, copy the result to
4580      `reaching_reg' if the expression reaches a deleted one.
4581
4582      ??? The current algorithm is rather brute force.
4583      Need to do some profiling.  */
4584
4585   for (i = 0; i < expr_hash_table_size; i++)
4586     for (expr = expr_hash_table[i]; expr != NULL; expr = expr->next_same_hash)
4587       {
4588         /* If the basic block isn't reachable, PPOUT will be TRUE.  However,
4589            we don't want to insert a copy here because the expression may not
4590            really be redundant.  So only insert an insn if the expression was
4591            deleted.  This test also avoids further processing if the
4592            expression wasn't deleted anywhere.  */
4593         if (expr->reaching_reg == NULL)
4594           continue;
4595
4596         for (occr = expr->antic_occr; occr != NULL; occr = occr->next)
4597           {
4598             if (! occr->deleted_p)
4599               continue;
4600
4601             for (avail = expr->avail_occr; avail != NULL; avail = avail->next)
4602               {
4603                 rtx insn = avail->insn;
4604
4605                 /* No need to handle this one if handled already.  */
4606                 if (avail->copied_p)
4607                   continue;
4608
4609                 /* Don't handle this one if it's a redundant one.  */
4610                 if (TEST_BIT (pre_redundant_insns, INSN_CUID (insn)))
4611                   continue;
4612
4613                 /* Or if the expression doesn't reach the deleted one.  */
4614                 if (! pre_expr_reaches_here_p (BLOCK_NUM (avail->insn), expr,
4615                                                BLOCK_NUM (occr->insn)))
4616                   continue;
4617
4618                 /* Copy the result of avail to reaching_reg.  */
4619                 pre_insert_copy_insn (expr, insn);
4620                 avail->copied_p = 1;
4621               }
4622           }
4623       }
4624 }
4625
4626 /* Delete redundant computations.
4627    Deletion is done by changing the insn to copy the `reaching_reg' of
4628    the expression into the result of the SET.  It is left to later passes
4629    (cprop, cse2, flow, combine, regmove) to propagate the copy or eliminate it.
4630
4631    Returns non-zero if a change is made.  */
4632
4633 static int
4634 pre_delete ()
4635 {
4636   unsigned int i;
4637   int changed;
4638   struct expr *expr;
4639   struct occr *occr;
4640
4641   changed = 0;
4642   for (i = 0; i < expr_hash_table_size; i++)
4643     for (expr = expr_hash_table[i]; expr != NULL; expr = expr->next_same_hash)
4644       {
4645         int indx = expr->bitmap_index;
4646
4647         /* We only need to search antic_occr since we require
4648            ANTLOC != 0.  */
4649
4650         for (occr = expr->antic_occr; occr != NULL; occr = occr->next)
4651           {
4652             rtx insn = occr->insn;
4653             rtx set;
4654             int bb = BLOCK_NUM (insn);
4655
4656             if (TEST_BIT (pre_delete_map[bb], indx))
4657               {
4658                 set = single_set (insn);
4659                 if (! set)
4660                   abort ();
4661
4662                 /* Create a pseudo-reg to store the result of reaching
4663                    expressions into.  Get the mode for the new pseudo from
4664                    the mode of the original destination pseudo.  */
4665                 if (expr->reaching_reg == NULL)
4666                   expr->reaching_reg
4667                     = gen_reg_rtx (GET_MODE (SET_DEST (set)));
4668
4669                 /* In theory this should never fail since we're creating
4670                    a reg->reg copy.
4671
4672                    However, on the x86 some of the movXX patterns actually
4673                    contain clobbers of scratch regs.  This may cause the
4674                    insn created by validate_change to not match any pattern
4675                    and thus cause validate_change to fail.   */
4676                 if (validate_change (insn, &SET_SRC (set),
4677                                      expr->reaching_reg, 0))
4678                   {
4679                     occr->deleted_p = 1;
4680                     SET_BIT (pre_redundant_insns, INSN_CUID (insn));
4681                     changed = 1;
4682                     gcse_subst_count++;
4683                   }
4684
4685                 if (gcse_file)
4686                   {
4687                     fprintf (gcse_file,
4688                              "PRE: redundant insn %d (expression %d) in ",
4689                                INSN_UID (insn), indx);
4690                     fprintf (gcse_file, "bb %d, reaching reg is %d\n",
4691                              bb, REGNO (expr->reaching_reg));
4692                   }
4693               }
4694           }
4695       }
4696
4697   return changed;
4698 }
4699
4700 /* Perform GCSE optimizations using PRE.
4701    This is called by one_pre_gcse_pass after all the dataflow analysis
4702    has been done.
4703
4704    This is based on the original Morel-Renvoise paper Fred Chow's thesis, and
4705    lazy code motion from Knoop, Ruthing and Steffen as described in Advanced
4706    Compiler Design and Implementation.
4707
4708    ??? A new pseudo reg is created to hold the reaching expression.  The nice
4709    thing about the classical approach is that it would try to use an existing
4710    reg.  If the register can't be adequately optimized [i.e. we introduce
4711    reload problems], one could add a pass here to propagate the new register
4712    through the block.
4713
4714    ??? We don't handle single sets in PARALLELs because we're [currently] not
4715    able to copy the rest of the parallel when we insert copies to create full
4716    redundancies from partial redundancies.  However, there's no reason why we
4717    can't handle PARALLELs in the cases where there are no partial
4718    redundancies.  */
4719
4720 static int
4721 pre_gcse ()
4722 {
4723   unsigned int i;
4724   int did_insert, changed;
4725   struct expr **index_map;
4726   struct expr *expr;
4727
4728   /* Compute a mapping from expression number (`bitmap_index') to
4729      hash table entry.  */
4730
4731   index_map = (struct expr **) xcalloc (n_exprs, sizeof (struct expr *));
4732   for (i = 0; i < expr_hash_table_size; i++)
4733     for (expr = expr_hash_table[i]; expr != NULL; expr = expr->next_same_hash)
4734       index_map[expr->bitmap_index] = expr;
4735
4736   /* Reset bitmap used to track which insns are redundant.  */
4737   pre_redundant_insns = sbitmap_alloc (max_cuid);
4738   sbitmap_zero (pre_redundant_insns);
4739
4740   /* Delete the redundant insns first so that
4741      - we know what register to use for the new insns and for the other
4742        ones with reaching expressions
4743      - we know which insns are redundant when we go to create copies  */
4744
4745   changed = pre_delete ();
4746
4747   did_insert = pre_edge_insert (edge_list, index_map);
4748
4749   /* In other places with reaching expressions, copy the expression to the
4750      specially allocated pseudo-reg that reaches the redundant expr.  */
4751   pre_insert_copies ();
4752   if (did_insert)
4753     {
4754       commit_edge_insertions ();
4755       changed = 1;
4756     }
4757
4758   free (index_map);
4759   free (pre_redundant_insns);
4760   return changed;
4761 }
4762
4763 /* Top level routine to perform one PRE GCSE pass.
4764
4765    Return non-zero if a change was made.  */
4766
4767 static int
4768 one_pre_gcse_pass (pass)
4769      int pass;
4770 {
4771   int changed = 0;
4772
4773   gcse_subst_count = 0;
4774   gcse_create_count = 0;
4775
4776   alloc_expr_hash_table (max_cuid);
4777   add_noreturn_fake_exit_edges ();
4778   compute_expr_hash_table ();
4779   if (gcse_file)
4780     dump_hash_table (gcse_file, "Expression", expr_hash_table,
4781                      expr_hash_table_size, n_exprs);
4782
4783   if (n_exprs > 0)
4784     {
4785       alloc_pre_mem (n_basic_blocks, n_exprs);
4786       compute_pre_data ();
4787       changed |= pre_gcse ();
4788       free_edge_list (edge_list);
4789       free_pre_mem ();
4790     }
4791
4792   remove_fake_edges ();
4793   free_expr_hash_table ();
4794
4795   if (gcse_file)
4796     {
4797       fprintf (gcse_file, "\nPRE GCSE of %s, pass %d: %d bytes needed, ",
4798                current_function_name, pass, bytes_used);
4799       fprintf (gcse_file, "%d substs, %d insns created\n",
4800                gcse_subst_count, gcse_create_count);
4801     }
4802
4803   return changed;
4804 }
4805 \f
4806 /* If X contains any LABEL_REF's, add REG_LABEL notes for them to INSN.
4807    We have to add REG_LABEL notes, because the following loop optimization
4808    pass requires them.  */
4809
4810 /* ??? This is very similar to the loop.c add_label_notes function.  We
4811    could probably share code here.  */
4812
4813 /* ??? If there was a jump optimization pass after gcse and before loop,
4814    then we would not need to do this here, because jump would add the
4815    necessary REG_LABEL notes.  */
4816
4817 static void
4818 add_label_notes (x, insn)
4819      rtx x;
4820      rtx insn;
4821 {
4822   enum rtx_code code = GET_CODE (x);
4823   int i, j;
4824   const char *fmt;
4825
4826   if (code == LABEL_REF && !LABEL_REF_NONLOCAL_P (x))
4827     {
4828       /* This code used to ignore labels that referred to dispatch tables to
4829          avoid flow generating (slighly) worse code.
4830
4831          We no longer ignore such label references (see LABEL_REF handling in
4832          mark_jump_label for additional information).  */
4833
4834       REG_NOTES (insn) = gen_rtx_EXPR_LIST (REG_LABEL, XEXP (x, 0),
4835                                             REG_NOTES (insn));
4836       return;
4837     }
4838
4839   for (i = GET_RTX_LENGTH (code) - 1, fmt = GET_RTX_FORMAT (code); i >= 0; i--)
4840     {
4841       if (fmt[i] == 'e')
4842         add_label_notes (XEXP (x, i), insn);
4843       else if (fmt[i] == 'E')
4844         for (j = XVECLEN (x, i) - 1; j >= 0; j--)
4845           add_label_notes (XVECEXP (x, i, j), insn);
4846     }
4847 }
4848
4849 /* Compute transparent outgoing information for each block.
4850
4851    An expression is transparent to an edge unless it is killed by
4852    the edge itself.  This can only happen with abnormal control flow,
4853    when the edge is traversed through a call.  This happens with
4854    non-local labels and exceptions.
4855
4856    This would not be necessary if we split the edge.  While this is
4857    normally impossible for abnormal critical edges, with some effort
4858    it should be possible with exception handling, since we still have
4859    control over which handler should be invoked.  But due to increased
4860    EH table sizes, this may not be worthwhile.  */
4861
4862 static void
4863 compute_transpout ()
4864 {
4865   int bb;
4866   unsigned int i;
4867   struct expr *expr;
4868
4869   sbitmap_vector_ones (transpout, n_basic_blocks);
4870
4871   for (bb = 0; bb < n_basic_blocks; ++bb)
4872     {
4873       /* Note that flow inserted a nop a the end of basic blocks that
4874          end in call instructions for reasons other than abnormal
4875          control flow.  */
4876       if (GET_CODE (BLOCK_END (bb)) != CALL_INSN)
4877         continue;
4878
4879       for (i = 0; i < expr_hash_table_size; i++)
4880         for (expr = expr_hash_table[i]; expr ; expr = expr->next_same_hash)
4881           if (GET_CODE (expr->expr) == MEM)
4882             {
4883               if (GET_CODE (XEXP (expr->expr, 0)) == SYMBOL_REF
4884                   && CONSTANT_POOL_ADDRESS_P (XEXP (expr->expr, 0)))
4885                 continue;
4886                 
4887               /* ??? Optimally, we would use interprocedural alias
4888                  analysis to determine if this mem is actually killed
4889                  by this call.  */
4890               RESET_BIT (transpout[bb], expr->bitmap_index);
4891             }
4892     }
4893 }
4894
4895 /* Removal of useless null pointer checks */
4896
4897 /* Called via note_stores.  X is set by SETTER.  If X is a register we must
4898    invalidate nonnull_local and set nonnull_killed.  DATA is really a
4899    `null_pointer_info *'.
4900
4901    We ignore hard registers.  */
4902
4903 static void
4904 invalidate_nonnull_info (x, setter, data)
4905      rtx x;
4906      rtx setter ATTRIBUTE_UNUSED;
4907      void *data;
4908 {
4909   unsigned int regno;
4910   struct null_pointer_info *npi = (struct null_pointer_info *) data;
4911
4912   while (GET_CODE (x) == SUBREG)
4913     x = SUBREG_REG (x);
4914
4915   /* Ignore anything that is not a register or is a hard register.  */
4916   if (GET_CODE (x) != REG
4917       || REGNO (x) < npi->min_reg
4918       || REGNO (x) >= npi->max_reg)
4919     return;
4920
4921   regno = REGNO (x) - npi->min_reg;
4922
4923   RESET_BIT (npi->nonnull_local[npi->current_block], regno);
4924   SET_BIT (npi->nonnull_killed[npi->current_block], regno);
4925 }
4926
4927 /* Do null-pointer check elimination for the registers indicated in
4928    NPI.  NONNULL_AVIN and NONNULL_AVOUT are pre-allocated sbitmaps;
4929    they are not our responsibility to free.  */
4930
4931 static void
4932 delete_null_pointer_checks_1 (block_reg, nonnull_avin, nonnull_avout, npi)
4933      unsigned int *block_reg;
4934      sbitmap *nonnull_avin;
4935      sbitmap *nonnull_avout;
4936      struct null_pointer_info *npi;
4937 {
4938   int bb;
4939   int current_block;
4940   sbitmap *nonnull_local = npi->nonnull_local;
4941   sbitmap *nonnull_killed = npi->nonnull_killed;
4942   
4943   /* Compute local properties, nonnull and killed.  A register will have
4944      the nonnull property if at the end of the current block its value is
4945      known to be nonnull.  The killed property indicates that somewhere in
4946      the block any information we had about the register is killed.
4947
4948      Note that a register can have both properties in a single block.  That
4949      indicates that it's killed, then later in the block a new value is
4950      computed.  */
4951   sbitmap_vector_zero (nonnull_local, n_basic_blocks);
4952   sbitmap_vector_zero (nonnull_killed, n_basic_blocks);
4953
4954   for (current_block = 0; current_block < n_basic_blocks; current_block++)
4955     {
4956       rtx insn, stop_insn;
4957
4958       /* Set the current block for invalidate_nonnull_info.  */
4959       npi->current_block = current_block;
4960
4961       /* Scan each insn in the basic block looking for memory references and
4962          register sets.  */
4963       stop_insn = NEXT_INSN (BLOCK_END (current_block));
4964       for (insn = BLOCK_HEAD (current_block);
4965            insn != stop_insn;
4966            insn = NEXT_INSN (insn))
4967         {
4968           rtx set;
4969           rtx reg;
4970
4971           /* Ignore anything that is not a normal insn.  */
4972           if (! INSN_P (insn))
4973             continue;
4974
4975           /* Basically ignore anything that is not a simple SET.  We do have
4976              to make sure to invalidate nonnull_local and set nonnull_killed
4977              for such insns though.  */
4978           set = single_set (insn);
4979           if (!set)
4980             {
4981               note_stores (PATTERN (insn), invalidate_nonnull_info, npi);
4982               continue;
4983             }
4984
4985           /* See if we've got a useable memory load.  We handle it first
4986              in case it uses its address register as a dest (which kills
4987              the nonnull property).  */
4988           if (GET_CODE (SET_SRC (set)) == MEM
4989               && GET_CODE ((reg = XEXP (SET_SRC (set), 0))) == REG
4990               && REGNO (reg) >= npi->min_reg
4991               && REGNO (reg) < npi->max_reg)
4992             SET_BIT (nonnull_local[current_block],
4993                      REGNO (reg) - npi->min_reg);
4994
4995           /* Now invalidate stuff clobbered by this insn.  */
4996           note_stores (PATTERN (insn), invalidate_nonnull_info, npi);
4997
4998           /* And handle stores, we do these last since any sets in INSN can
4999              not kill the nonnull property if it is derived from a MEM
5000              appearing in a SET_DEST.  */
5001           if (GET_CODE (SET_DEST (set)) == MEM
5002               && GET_CODE ((reg = XEXP (SET_DEST (set), 0))) == REG
5003               && REGNO (reg) >= npi->min_reg
5004               && REGNO (reg) < npi->max_reg)
5005             SET_BIT (nonnull_local[current_block],
5006                      REGNO (reg) - npi->min_reg);
5007         }
5008     }
5009
5010   /* Now compute global properties based on the local properties.   This
5011      is a classic global availablity algorithm.  */
5012   compute_available (nonnull_local, nonnull_killed,
5013                      nonnull_avout, nonnull_avin);
5014
5015   /* Now look at each bb and see if it ends with a compare of a value
5016      against zero.  */
5017   for (bb = 0; bb < n_basic_blocks; bb++)
5018     {
5019       rtx last_insn = BLOCK_END (bb);
5020       rtx condition, earliest;
5021       int compare_and_branch;
5022
5023       /* Since MIN_REG is always at least FIRST_PSEUDO_REGISTER, and
5024          since BLOCK_REG[BB] is zero if this block did not end with a
5025          comparison against zero, this condition works.  */
5026       if (block_reg[bb] < npi->min_reg
5027           || block_reg[bb] >= npi->max_reg)
5028         continue;
5029
5030       /* LAST_INSN is a conditional jump.  Get its condition.  */
5031       condition = get_condition (last_insn, &earliest);
5032
5033       /* If we can't determine the condition then skip.  */
5034       if (! condition)
5035         continue;
5036
5037       /* Is the register known to have a nonzero value?  */
5038       if (!TEST_BIT (nonnull_avout[bb], block_reg[bb] - npi->min_reg))
5039         continue;
5040
5041       /* Try to compute whether the compare/branch at the loop end is one or
5042          two instructions.  */
5043       if (earliest == last_insn)
5044         compare_and_branch = 1;
5045       else if (earliest == prev_nonnote_insn (last_insn))
5046         compare_and_branch = 2;
5047       else
5048         continue;
5049
5050       /* We know the register in this comparison is nonnull at exit from
5051          this block.  We can optimize this comparison.  */
5052       if (GET_CODE (condition) == NE)
5053         {
5054           rtx new_jump;
5055
5056           new_jump = emit_jump_insn_before (gen_jump (JUMP_LABEL (last_insn)),
5057                                             last_insn);
5058           JUMP_LABEL (new_jump) = JUMP_LABEL (last_insn);
5059           LABEL_NUSES (JUMP_LABEL (new_jump))++;
5060           emit_barrier_after (new_jump);
5061         }
5062       delete_insn (last_insn);
5063       if (compare_and_branch == 2)
5064         delete_insn (earliest);
5065
5066       /* Don't check this block again.  (Note that BLOCK_END is
5067          invalid here; we deleted the last instruction in the 
5068          block.)  */
5069       block_reg[bb] = 0;
5070     }
5071 }
5072
5073 /* Find EQ/NE comparisons against zero which can be (indirectly) evaluated
5074    at compile time.
5075
5076    This is conceptually similar to global constant/copy propagation and
5077    classic global CSE (it even uses the same dataflow equations as cprop).
5078
5079    If a register is used as memory address with the form (mem (reg)), then we
5080    know that REG can not be zero at that point in the program.  Any instruction
5081    which sets REG "kills" this property.
5082
5083    So, if every path leading to a conditional branch has an available memory
5084    reference of that form, then we know the register can not have the value
5085    zero at the conditional branch.  
5086
5087    So we merely need to compute the local properies and propagate that data
5088    around the cfg, then optimize where possible.
5089
5090    We run this pass two times.  Once before CSE, then again after CSE.  This
5091    has proven to be the most profitable approach.  It is rare for new
5092    optimization opportunities of this nature to appear after the first CSE
5093    pass.
5094
5095    This could probably be integrated with global cprop with a little work.  */
5096
5097 void
5098 delete_null_pointer_checks (f)
5099      rtx f ATTRIBUTE_UNUSED;
5100 {
5101   sbitmap *nonnull_avin, *nonnull_avout;
5102   unsigned int *block_reg;
5103   int bb;
5104   int reg;
5105   int regs_per_pass;
5106   int max_reg;
5107   struct null_pointer_info npi;
5108
5109   /* If we have only a single block, then there's nothing to do.  */
5110   if (n_basic_blocks <= 1)
5111     return;
5112
5113   /* Trying to perform global optimizations on flow graphs which have
5114      a high connectivity will take a long time and is unlikely to be
5115      particularly useful.
5116
5117      In normal circumstances a cfg should have about twice has many edges
5118      as blocks.  But we do not want to punish small functions which have
5119      a couple switch statements.  So we require a relatively large number
5120      of basic blocks and the ratio of edges to blocks to be high.  */
5121   if (n_basic_blocks > 1000 && n_edges / n_basic_blocks >= 20)
5122     return;
5123
5124   /* We need four bitmaps, each with a bit for each register in each
5125      basic block.  */
5126   max_reg = max_reg_num ();
5127   regs_per_pass = get_bitmap_width (4, n_basic_blocks, max_reg);
5128
5129   /* Allocate bitmaps to hold local and global properties.  */
5130   npi.nonnull_local = sbitmap_vector_alloc (n_basic_blocks, regs_per_pass);
5131   npi.nonnull_killed = sbitmap_vector_alloc (n_basic_blocks, regs_per_pass);
5132   nonnull_avin = sbitmap_vector_alloc (n_basic_blocks, regs_per_pass);
5133   nonnull_avout = sbitmap_vector_alloc (n_basic_blocks, regs_per_pass);
5134
5135   /* Go through the basic blocks, seeing whether or not each block
5136      ends with a conditional branch whose condition is a comparison
5137      against zero.  Record the register compared in BLOCK_REG.  */
5138   block_reg = (unsigned int *) xcalloc (n_basic_blocks, sizeof (int));
5139   for (bb = 0; bb < n_basic_blocks; bb++)
5140     {
5141       rtx last_insn = BLOCK_END (bb);
5142       rtx condition, earliest, reg;
5143
5144       /* We only want conditional branches.  */
5145       if (GET_CODE (last_insn) != JUMP_INSN
5146           || !any_condjump_p (last_insn)
5147           || !onlyjump_p (last_insn))
5148         continue;
5149
5150       /* LAST_INSN is a conditional jump.  Get its condition.  */
5151       condition = get_condition (last_insn, &earliest);
5152
5153       /* If we were unable to get the condition, or it is not a equality
5154          comparison against zero then there's nothing we can do.  */
5155       if (!condition
5156           || (GET_CODE (condition) != NE && GET_CODE (condition) != EQ)
5157           || GET_CODE (XEXP (condition, 1)) != CONST_INT
5158           || (XEXP (condition, 1) 
5159               != CONST0_RTX (GET_MODE (XEXP (condition, 0)))))
5160         continue;
5161
5162       /* We must be checking a register against zero.  */
5163       reg = XEXP (condition, 0);
5164       if (GET_CODE (reg) != REG)
5165         continue;
5166
5167       block_reg[bb] = REGNO (reg);
5168     }
5169
5170   /* Go through the algorithm for each block of registers.  */
5171   for (reg = FIRST_PSEUDO_REGISTER; reg < max_reg; reg += regs_per_pass)
5172     {
5173       npi.min_reg = reg;
5174       npi.max_reg = MIN (reg + regs_per_pass, max_reg);
5175       delete_null_pointer_checks_1 (block_reg, nonnull_avin,
5176                                     nonnull_avout, &npi);
5177     }
5178
5179   /* Free the table of registers compared at the end of every block.  */
5180   free (block_reg);
5181
5182   /* Free bitmaps.  */
5183   free (npi.nonnull_local);
5184   free (npi.nonnull_killed);
5185   free (nonnull_avin);
5186   free (nonnull_avout);
5187 }
5188
5189 /* Code Hoisting variables and subroutines.  */
5190
5191 /* Very busy expressions.  */
5192 static sbitmap *hoist_vbein;
5193 static sbitmap *hoist_vbeout;
5194
5195 /* Hoistable expressions.  */
5196 static sbitmap *hoist_exprs;
5197
5198 /* Dominator bitmaps.  */
5199 static sbitmap *dominators;
5200
5201 /* ??? We could compute post dominators and run this algorithm in
5202    reverse to to perform tail merging, doing so would probably be
5203    more effective than the tail merging code in jump.c.
5204
5205    It's unclear if tail merging could be run in parallel with
5206    code hoisting.  It would be nice.  */
5207
5208 /* Allocate vars used for code hoisting analysis.  */
5209
5210 static void
5211 alloc_code_hoist_mem (n_blocks, n_exprs)
5212      int n_blocks, n_exprs;
5213 {
5214   antloc = sbitmap_vector_alloc (n_blocks, n_exprs);
5215   transp = sbitmap_vector_alloc (n_blocks, n_exprs);
5216   comp = sbitmap_vector_alloc (n_blocks, n_exprs);
5217
5218   hoist_vbein = sbitmap_vector_alloc (n_blocks, n_exprs);
5219   hoist_vbeout = sbitmap_vector_alloc (n_blocks, n_exprs);
5220   hoist_exprs = sbitmap_vector_alloc (n_blocks, n_exprs);
5221   transpout = sbitmap_vector_alloc (n_blocks, n_exprs);
5222
5223   dominators = sbitmap_vector_alloc (n_blocks, n_blocks);
5224 }
5225
5226 /* Free vars used for code hoisting analysis.  */
5227
5228 static void
5229 free_code_hoist_mem ()
5230 {
5231   free (antloc);
5232   free (transp);
5233   free (comp);
5234
5235   free (hoist_vbein);
5236   free (hoist_vbeout);
5237   free (hoist_exprs);
5238   free (transpout);
5239
5240   free (dominators);
5241 }
5242
5243 /* Compute the very busy expressions at entry/exit from each block.
5244
5245    An expression is very busy if all paths from a given point
5246    compute the expression.  */
5247
5248 static void
5249 compute_code_hoist_vbeinout ()
5250 {
5251   int bb, changed, passes;
5252
5253   sbitmap_vector_zero (hoist_vbeout, n_basic_blocks);
5254   sbitmap_vector_zero (hoist_vbein, n_basic_blocks);
5255
5256   passes = 0;
5257   changed = 1;
5258
5259   while (changed)
5260     {
5261       changed = 0;
5262
5263       /* We scan the blocks in the reverse order to speed up
5264          the convergence.  */
5265       for (bb = n_basic_blocks - 1; bb >= 0; bb--)
5266         {
5267           changed |= sbitmap_a_or_b_and_c (hoist_vbein[bb], antloc[bb],
5268                                            hoist_vbeout[bb], transp[bb]);
5269           if (bb != n_basic_blocks - 1)
5270             sbitmap_intersection_of_succs (hoist_vbeout[bb], hoist_vbein, bb);
5271         }
5272
5273       passes++;
5274     }
5275
5276   if (gcse_file)
5277     fprintf (gcse_file, "hoisting vbeinout computation: %d passes\n", passes);
5278 }
5279
5280 /* Top level routine to do the dataflow analysis needed by code hoisting.  */
5281
5282 static void
5283 compute_code_hoist_data ()
5284 {
5285   compute_local_properties (transp, comp, antloc, 0);
5286   compute_transpout ();
5287   compute_code_hoist_vbeinout ();
5288   compute_flow_dominators (dominators, NULL);
5289   if (gcse_file)
5290     fprintf (gcse_file, "\n");
5291 }
5292
5293 /* Determine if the expression identified by EXPR_INDEX would
5294    reach BB unimpared if it was placed at the end of EXPR_BB.
5295
5296    It's unclear exactly what Muchnick meant by "unimpared".  It seems
5297    to me that the expression must either be computed or transparent in
5298    *every* block in the path(s) from EXPR_BB to BB.  Any other definition
5299    would allow the expression to be hoisted out of loops, even if
5300    the expression wasn't a loop invariant.
5301
5302    Contrast this to reachability for PRE where an expression is
5303    considered reachable if *any* path reaches instead of *all*
5304    paths.  */
5305
5306 static int
5307 hoist_expr_reaches_here_p (expr_bb, expr_index, bb, visited)
5308      int expr_bb;
5309      int expr_index;
5310      int bb;
5311      char *visited;
5312 {
5313   edge pred;
5314   int visited_allocated_locally = 0;
5315   
5316
5317   if (visited == NULL)
5318     {
5319        visited_allocated_locally = 1;
5320        visited = xcalloc (n_basic_blocks, 1);
5321     }
5322
5323   visited[expr_bb] = 1;
5324   for (pred = BASIC_BLOCK (bb)->pred; pred != NULL; pred = pred->pred_next)
5325     {
5326       int pred_bb = pred->src->index;
5327
5328       if (pred->src == ENTRY_BLOCK_PTR)
5329         break;
5330       else if (visited[pred_bb])
5331         continue;
5332
5333       /* Does this predecessor generate this expression?  */
5334       else if (TEST_BIT (comp[pred_bb], expr_index))
5335         break;
5336       else if (! TEST_BIT (transp[pred_bb], expr_index))
5337         break;
5338
5339       /* Not killed.  */
5340       else
5341         {
5342           visited[pred_bb] = 1;
5343           if (! hoist_expr_reaches_here_p (expr_bb, expr_index,
5344                                            pred_bb, visited))
5345             break;
5346         }
5347     }
5348   if (visited_allocated_locally) 
5349     free (visited);
5350
5351   return (pred == NULL);
5352 }
5353 \f
5354 /* Actually perform code hoisting.  */
5355
5356 static void
5357 hoist_code ()
5358 {
5359   int bb, dominated;
5360   unsigned int i;
5361   struct expr **index_map;
5362   struct expr *expr;
5363
5364   sbitmap_vector_zero (hoist_exprs, n_basic_blocks);
5365
5366   /* Compute a mapping from expression number (`bitmap_index') to
5367      hash table entry.  */
5368
5369   index_map = (struct expr **) xcalloc (n_exprs, sizeof (struct expr *));
5370   for (i = 0; i < expr_hash_table_size; i++)
5371     for (expr = expr_hash_table[i]; expr != NULL; expr = expr->next_same_hash)
5372       index_map[expr->bitmap_index] = expr;
5373
5374   /* Walk over each basic block looking for potentially hoistable
5375      expressions, nothing gets hoisted from the entry block.  */
5376   for (bb = 0; bb < n_basic_blocks; bb++)
5377     {
5378       int found = 0;
5379       int insn_inserted_p;
5380
5381       /* Examine each expression that is very busy at the exit of this
5382          block.  These are the potentially hoistable expressions.  */
5383       for (i = 0; i < hoist_vbeout[bb]->n_bits; i++)
5384         {
5385           int hoistable = 0;
5386
5387           if (TEST_BIT (hoist_vbeout[bb], i) && TEST_BIT (transpout[bb], i))
5388             {
5389               /* We've found a potentially hoistable expression, now
5390                  we look at every block BB dominates to see if it
5391                  computes the expression.  */
5392               for (dominated = 0; dominated < n_basic_blocks; dominated++)
5393                 {
5394                   /* Ignore self dominance.  */
5395                   if (bb == dominated
5396                       || ! TEST_BIT (dominators[dominated], bb))
5397                     continue;
5398
5399                   /* We've found a dominated block, now see if it computes
5400                      the busy expression and whether or not moving that
5401                      expression to the "beginning" of that block is safe.  */
5402                   if (!TEST_BIT (antloc[dominated], i))
5403                     continue;
5404
5405                   /* Note if the expression would reach the dominated block
5406                      unimpared if it was placed at the end of BB. 
5407
5408                      Keep track of how many times this expression is hoistable
5409                      from a dominated block into BB.  */
5410                   if (hoist_expr_reaches_here_p (bb, i, dominated, NULL))
5411                     hoistable++;
5412                 }
5413
5414               /* If we found more than one hoistable occurence of this
5415                  expression, then note it in the bitmap of expressions to
5416                  hoist.  It makes no sense to hoist things which are computed
5417                  in only one BB, and doing so tends to pessimize register
5418                  allocation.  One could increase this value to try harder
5419                  to avoid any possible code expansion due to register
5420                  allocation issues; however experiments have shown that
5421                  the vast majority of hoistable expressions are only movable
5422                  from two successors, so raising this threshhold is likely
5423                  to nullify any benefit we get from code hoisting.  */
5424               if (hoistable > 1)
5425                 {
5426                   SET_BIT (hoist_exprs[bb], i);
5427                   found = 1;
5428                 }
5429             }
5430         }
5431                 
5432       /* If we found nothing to hoist, then quit now.  */
5433       if (! found)
5434         continue;
5435
5436       /* Loop over all the hoistable expressions.  */
5437       for (i = 0; i < hoist_exprs[bb]->n_bits; i++)
5438         {
5439           /* We want to insert the expression into BB only once, so
5440              note when we've inserted it.  */
5441           insn_inserted_p = 0;
5442
5443           /* These tests should be the same as the tests above.  */
5444           if (TEST_BIT (hoist_vbeout[bb], i))
5445             {
5446               /* We've found a potentially hoistable expression, now
5447                  we look at every block BB dominates to see if it
5448                  computes the expression.  */
5449               for (dominated = 0; dominated < n_basic_blocks; dominated++)
5450                 {
5451                   /* Ignore self dominance.  */
5452                   if (bb == dominated
5453                       || ! TEST_BIT (dominators[dominated], bb))
5454                     continue;
5455
5456                   /* We've found a dominated block, now see if it computes
5457                      the busy expression and whether or not moving that
5458                      expression to the "beginning" of that block is safe.  */
5459                   if (!TEST_BIT (antloc[dominated], i))
5460                     continue;
5461
5462                   /* The expression is computed in the dominated block and
5463                      it would be safe to compute it at the start of the
5464                      dominated block.  Now we have to determine if the
5465                      expresion would reach the dominated block if it was
5466                      placed at the end of BB.  */
5467                   if (hoist_expr_reaches_here_p (bb, i, dominated, NULL))
5468                     {
5469                       struct expr *expr = index_map[i];
5470                       struct occr *occr = expr->antic_occr;
5471                       rtx insn;
5472                       rtx set;
5473
5474                       /* Find the right occurence of this expression.  */
5475                       while (BLOCK_NUM (occr->insn) != dominated && occr)
5476                         occr = occr->next;
5477
5478                       /* Should never happen.  */
5479                       if (!occr)
5480                         abort ();
5481
5482                       insn = occr->insn;
5483                  
5484                       set = single_set (insn);
5485                       if (! set)
5486                         abort ();
5487
5488                       /* Create a pseudo-reg to store the result of reaching
5489                          expressions into.  Get the mode for the new pseudo
5490                          from the mode of the original destination pseudo.  */
5491                       if (expr->reaching_reg == NULL)
5492                         expr->reaching_reg
5493                           = gen_reg_rtx (GET_MODE (SET_DEST (set)));
5494
5495                       /* In theory this should never fail since we're creating
5496                          a reg->reg copy.
5497
5498                          However, on the x86 some of the movXX patterns
5499                          actually contain clobbers of scratch regs.  This may
5500                          cause the insn created by validate_change to not
5501                          match any pattern and thus cause validate_change to
5502                          fail.  */
5503                       if (validate_change (insn, &SET_SRC (set),
5504                                            expr->reaching_reg, 0))
5505                         {
5506                           occr->deleted_p = 1;
5507                           if (!insn_inserted_p)
5508                             {
5509                               insert_insn_end_bb (index_map[i], bb, 0);
5510                               insn_inserted_p = 1;
5511                             }
5512                         }
5513                     }
5514                 }
5515             }
5516         }
5517     }
5518
5519     free (index_map);
5520 }
5521
5522 /* Top level routine to perform one code hoisting (aka unification) pass
5523
5524    Return non-zero if a change was made.  */
5525
5526 static int
5527 one_code_hoisting_pass ()
5528 {
5529   int changed = 0;
5530
5531   alloc_expr_hash_table (max_cuid);
5532   compute_expr_hash_table ();
5533   if (gcse_file)
5534     dump_hash_table (gcse_file, "Code Hosting Expressions", expr_hash_table,
5535                      expr_hash_table_size, n_exprs);
5536
5537   if (n_exprs > 0)
5538     {
5539       alloc_code_hoist_mem (n_basic_blocks, n_exprs);
5540       compute_code_hoist_data ();
5541       hoist_code ();
5542       free_code_hoist_mem ();
5543     }
5544
5545   free_expr_hash_table ();
5546
5547   return changed;
5548 }