* gcc.target/powerpc/altivec-volatile.c: Adjust expected warning.
[official-gcc.git] / gcc / gcse.c
blobb0a18689326e86105a5c3817be052ed7a2e3bb92
1 /* Global common subexpression elimination/Partial redundancy elimination
2 and global constant/copy propagation for GNU compiler.
3 Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
4 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
6 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 for more details.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
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 - a store to the same address as a load does not kill the load if the
28 source of the store is also the destination of the load. Handling this
29 allows more load motion, particularly out of loops.
33 /* References searched while implementing this.
35 Compilers Principles, Techniques and Tools
36 Aho, Sethi, Ullman
37 Addison-Wesley, 1988
39 Global Optimization by Suppression of Partial Redundancies
40 E. Morel, C. Renvoise
41 communications of the acm, Vol. 22, Num. 2, Feb. 1979
43 A Portable Machine-Independent Global Optimizer - Design and Measurements
44 Frederick Chow
45 Stanford Ph.D. thesis, Dec. 1983
47 A Fast Algorithm for Code Movement Optimization
48 D.M. Dhamdhere
49 SIGPLAN Notices, Vol. 23, Num. 10, Oct. 1988
51 A Solution to a Problem with Morel and Renvoise's
52 Global Optimization by Suppression of Partial Redundancies
53 K-H Drechsler, M.P. Stadel
54 ACM TOPLAS, Vol. 10, Num. 4, Oct. 1988
56 Practical Adaptation of the Global Optimization
57 Algorithm of Morel and Renvoise
58 D.M. Dhamdhere
59 ACM TOPLAS, Vol. 13, Num. 2. Apr. 1991
61 Efficiently Computing Static Single Assignment Form and the Control
62 Dependence Graph
63 R. Cytron, J. Ferrante, B.K. Rosen, M.N. Wegman, and F.K. Zadeck
64 ACM TOPLAS, Vol. 13, Num. 4, Oct. 1991
66 Lazy Code Motion
67 J. Knoop, O. Ruthing, B. Steffen
68 ACM SIGPLAN Notices Vol. 27, Num. 7, Jul. 1992, '92 Conference on PLDI
70 What's In a Region? Or Computing Control Dependence Regions in Near-Linear
71 Time for Reducible Flow Control
72 Thomas Ball
73 ACM Letters on Programming Languages and Systems,
74 Vol. 2, Num. 1-4, Mar-Dec 1993
76 An Efficient Representation for Sparse Sets
77 Preston Briggs, Linda Torczon
78 ACM Letters on Programming Languages and Systems,
79 Vol. 2, Num. 1-4, Mar-Dec 1993
81 A Variation of Knoop, Ruthing, and Steffen's Lazy Code Motion
82 K-H Drechsler, M.P. Stadel
83 ACM SIGPLAN Notices, Vol. 28, Num. 5, May 1993
85 Partial Dead Code Elimination
86 J. Knoop, O. Ruthing, B. Steffen
87 ACM SIGPLAN Notices, Vol. 29, Num. 6, Jun. 1994
89 Effective Partial Redundancy Elimination
90 P. Briggs, K.D. Cooper
91 ACM SIGPLAN Notices, Vol. 29, Num. 6, Jun. 1994
93 The Program Structure Tree: Computing Control Regions in Linear Time
94 R. Johnson, D. Pearson, K. Pingali
95 ACM SIGPLAN Notices, Vol. 29, Num. 6, Jun. 1994
97 Optimal Code Motion: Theory and Practice
98 J. Knoop, O. Ruthing, B. Steffen
99 ACM TOPLAS, Vol. 16, Num. 4, Jul. 1994
101 The power of assignment motion
102 J. Knoop, O. Ruthing, B. Steffen
103 ACM SIGPLAN Notices Vol. 30, Num. 6, Jun. 1995, '95 Conference on PLDI
105 Global code motion / global value numbering
106 C. Click
107 ACM SIGPLAN Notices Vol. 30, Num. 6, Jun. 1995, '95 Conference on PLDI
109 Value Driven Redundancy Elimination
110 L.T. Simpson
111 Rice University Ph.D. thesis, Apr. 1996
113 Value Numbering
114 L.T. Simpson
115 Massively Scalar Compiler Project, Rice University, Sep. 1996
117 High Performance Compilers for Parallel Computing
118 Michael Wolfe
119 Addison-Wesley, 1996
121 Advanced Compiler Design and Implementation
122 Steven Muchnick
123 Morgan Kaufmann, 1997
125 Building an Optimizing Compiler
126 Robert Morgan
127 Digital Press, 1998
129 People wishing to speed up the code here should read:
130 Elimination Algorithms for Data Flow Analysis
131 B.G. Ryder, M.C. Paull
132 ACM Computing Surveys, Vol. 18, Num. 3, Sep. 1986
134 How to Analyze Large Programs Efficiently and Informatively
135 D.M. Dhamdhere, B.K. Rosen, F.K. Zadeck
136 ACM SIGPLAN Notices Vol. 27, Num. 7, Jul. 1992, '92 Conference on PLDI
138 People wishing to do something different can find various possibilities
139 in the above papers and elsewhere.
142 #include "config.h"
143 #include "system.h"
144 #include "coretypes.h"
145 #include "tm.h"
146 #include "toplev.h"
148 #include "rtl.h"
149 #include "tree.h"
150 #include "tm_p.h"
151 #include "regs.h"
152 #include "hard-reg-set.h"
153 #include "flags.h"
154 #include "insn-config.h"
155 #include "recog.h"
156 #include "basic-block.h"
157 #include "output.h"
158 #include "function.h"
159 #include "expr.h"
160 #include "except.h"
161 #include "ggc.h"
162 #include "params.h"
163 #include "cselib.h"
164 #include "intl.h"
165 #include "obstack.h"
166 #include "timevar.h"
167 #include "tree-pass.h"
168 #include "hashtab.h"
169 #include "df.h"
170 #include "dbgcnt.h"
171 #include "target.h"
173 /* We support GCSE via Partial Redundancy Elimination. PRE optimizations
174 are a superset of those done by classic GCSE.
176 We perform the following steps:
178 1) Compute table of places where registers are set.
180 2) Perform copy/constant propagation.
182 3) Perform global cse using lazy code motion if not optimizing
183 for size, or code hoisting if we are.
185 4) Perform another pass of copy/constant propagation. Try to bypass
186 conditional jumps if the condition can be computed from a value of
187 an incoming edge.
189 Two passes of copy/constant propagation are done because the first one
190 enables more GCSE and the second one helps to clean up the copies that
191 GCSE creates. This is needed more for PRE than for Classic because Classic
192 GCSE will try to use an existing register containing the common
193 subexpression rather than create a new one. This is harder to do for PRE
194 because of the code motion (which Classic GCSE doesn't do).
196 Expressions we are interested in GCSE-ing are of the form
197 (set (pseudo-reg) (expression)).
198 Function want_to_gcse_p says what these are.
200 In addition, expressions in REG_EQUAL notes are candidates for GCSE-ing.
201 This allows PRE to hoist expressions that are expressed in multiple insns,
202 such as complex address calculations (e.g. for PIC code, or loads with a
203 high part and a low part).
205 PRE handles moving invariant expressions out of loops (by treating them as
206 partially redundant).
208 **********************
210 We used to support multiple passes but there are diminishing returns in
211 doing so. The first pass usually makes 90% of the changes that are doable.
212 A second pass can make a few more changes made possible by the first pass.
213 Experiments show any further passes don't make enough changes to justify
214 the expense.
216 A study of spec92 using an unlimited number of passes:
217 [1 pass] = 1208 substitutions, [2] = 577, [3] = 202, [4] = 192, [5] = 83,
218 [6] = 34, [7] = 17, [8] = 9, [9] = 4, [10] = 4, [11] = 2,
219 [12] = 2, [13] = 1, [15] = 1, [16] = 2, [41] = 1
221 It was found doing copy propagation between each pass enables further
222 substitutions.
224 This study was done before expressions in REG_EQUAL notes were added as
225 candidate expressions for optimization, and before the GIMPLE optimizers
226 were added. Probably, multiple passes is even less efficient now than
227 at the time when the study was conducted.
229 PRE is quite expensive in complicated functions because the DFA can take
230 a while to converge. Hence we only perform one pass.
232 **********************
234 The steps for PRE are:
236 1) Build the hash table of expressions we wish to GCSE (expr_hash_table).
238 2) Perform the data flow analysis for PRE.
240 3) Delete the redundant instructions
242 4) Insert the required copies [if any] that make the partially
243 redundant instructions fully redundant.
245 5) For other reaching expressions, insert an instruction to copy the value
246 to a newly created pseudo that will reach the redundant instruction.
248 The deletion is done first so that when we do insertions we
249 know which pseudo reg to use.
251 Various papers have argued that PRE DFA is expensive (O(n^2)) and others
252 argue it is not. The number of iterations for the algorithm to converge
253 is typically 2-4 so I don't view it as that expensive (relatively speaking).
255 PRE GCSE depends heavily on the second CPROP pass to clean up the copies
256 we create. To make an expression reach the place where it's redundant,
257 the result of the expression is copied to a new register, and the redundant
258 expression is deleted by replacing it with this new register. Classic GCSE
259 doesn't have this problem as much as it computes the reaching defs of
260 each register in each block and thus can try to use an existing
261 register. */
263 /* GCSE global vars. */
265 /* Set to non-zero if CSE should run after all GCSE optimizations are done. */
266 int flag_rerun_cse_after_global_opts;
268 /* An obstack for our working variables. */
269 static struct obstack gcse_obstack;
271 struct reg_use {rtx reg_rtx; };
273 /* Hash table of expressions. */
275 struct expr
277 /* The expression (SET_SRC for expressions, PATTERN for assignments). */
278 rtx expr;
279 /* Index in the available expression bitmaps. */
280 int bitmap_index;
281 /* Next entry with the same hash. */
282 struct expr *next_same_hash;
283 /* List of anticipatable occurrences in basic blocks in the function.
284 An "anticipatable occurrence" is one that is the first occurrence in the
285 basic block, the operands are not modified in the basic block prior
286 to the occurrence and the output is not used between the start of
287 the block and the occurrence. */
288 struct occr *antic_occr;
289 /* List of available occurrence in basic blocks in the function.
290 An "available occurrence" is one that is the last occurrence in the
291 basic block and the operands are not modified by following statements in
292 the basic block [including this insn]. */
293 struct occr *avail_occr;
294 /* Non-null if the computation is PRE redundant.
295 The value is the newly created pseudo-reg to record a copy of the
296 expression in all the places that reach the redundant copy. */
297 rtx reaching_reg;
300 /* Occurrence of an expression.
301 There is one per basic block. If a pattern appears more than once the
302 last appearance is used [or first for anticipatable expressions]. */
304 struct occr
306 /* Next occurrence of this expression. */
307 struct occr *next;
308 /* The insn that computes the expression. */
309 rtx insn;
310 /* Nonzero if this [anticipatable] occurrence has been deleted. */
311 char deleted_p;
312 /* Nonzero if this [available] occurrence has been copied to
313 reaching_reg. */
314 /* ??? This is mutually exclusive with deleted_p, so they could share
315 the same byte. */
316 char copied_p;
319 /* Expression and copy propagation hash tables.
320 Each hash table is an array of buckets.
321 ??? It is known that if it were an array of entries, structure elements
322 `next_same_hash' and `bitmap_index' wouldn't be necessary. However, it is
323 not clear whether in the final analysis a sufficient amount of memory would
324 be saved as the size of the available expression bitmaps would be larger
325 [one could build a mapping table without holes afterwards though].
326 Someday I'll perform the computation and figure it out. */
328 struct hash_table_d
330 /* The table itself.
331 This is an array of `expr_hash_table_size' elements. */
332 struct expr **table;
334 /* Size of the hash table, in elements. */
335 unsigned int size;
337 /* Number of hash table elements. */
338 unsigned int n_elems;
340 /* Whether the table is expression of copy propagation one. */
341 int set_p;
344 /* Expression hash table. */
345 static struct hash_table_d expr_hash_table;
347 /* Copy propagation hash table. */
348 static struct hash_table_d set_hash_table;
350 /* This is a list of expressions which are MEMs and will be used by load
351 or store motion.
352 Load motion tracks MEMs which aren't killed by
353 anything except itself. (i.e., loads and stores to a single location).
354 We can then allow movement of these MEM refs with a little special
355 allowance. (all stores copy the same value to the reaching reg used
356 for the loads). This means all values used to store into memory must have
357 no side effects so we can re-issue the setter value.
358 Store Motion uses this structure as an expression table to track stores
359 which look interesting, and might be moveable towards the exit block. */
361 struct ls_expr
363 struct expr * expr; /* Gcse expression reference for LM. */
364 rtx pattern; /* Pattern of this mem. */
365 rtx pattern_regs; /* List of registers mentioned by the mem. */
366 rtx loads; /* INSN list of loads seen. */
367 rtx stores; /* INSN list of stores seen. */
368 struct ls_expr * next; /* Next in the list. */
369 int invalid; /* Invalid for some reason. */
370 int index; /* If it maps to a bitmap index. */
371 unsigned int hash_index; /* Index when in a hash table. */
372 rtx reaching_reg; /* Register to use when re-writing. */
375 /* Array of implicit set patterns indexed by basic block index. */
376 static rtx *implicit_sets;
378 /* Head of the list of load/store memory refs. */
379 static struct ls_expr * pre_ldst_mems = NULL;
381 /* Hashtable for the load/store memory refs. */
382 static htab_t pre_ldst_table = NULL;
384 /* Bitmap containing one bit for each register in the program.
385 Used when performing GCSE to track which registers have been set since
386 the start of the basic block. */
387 static regset reg_set_bitmap;
389 /* Array, indexed by basic block number for a list of insns which modify
390 memory within that block. */
391 static rtx * modify_mem_list;
392 static bitmap modify_mem_list_set;
394 /* This array parallels modify_mem_list, but is kept canonicalized. */
395 static rtx * canon_modify_mem_list;
397 /* Bitmap indexed by block numbers to record which blocks contain
398 function calls. */
399 static bitmap blocks_with_calls;
401 /* Various variables for statistics gathering. */
403 /* Memory used in a pass.
404 This isn't intended to be absolutely precise. Its intent is only
405 to keep an eye on memory usage. */
406 static int bytes_used;
408 /* GCSE substitutions made. */
409 static int gcse_subst_count;
410 /* Number of copy instructions created. */
411 static int gcse_create_count;
412 /* Number of local constants propagated. */
413 static int local_const_prop_count;
414 /* Number of local copies propagated. */
415 static int local_copy_prop_count;
416 /* Number of global constants propagated. */
417 static int global_const_prop_count;
418 /* Number of global copies propagated. */
419 static int global_copy_prop_count;
421 /* For available exprs */
422 static sbitmap *ae_kill;
424 static void compute_can_copy (void);
425 static void *gmalloc (size_t) ATTRIBUTE_MALLOC;
426 static void *gcalloc (size_t, size_t) ATTRIBUTE_MALLOC;
427 static void *gcse_alloc (unsigned long);
428 static void alloc_gcse_mem (void);
429 static void free_gcse_mem (void);
430 static void hash_scan_insn (rtx, struct hash_table_d *);
431 static void hash_scan_set (rtx, rtx, struct hash_table_d *);
432 static void hash_scan_clobber (rtx, rtx, struct hash_table_d *);
433 static void hash_scan_call (rtx, rtx, struct hash_table_d *);
434 static int want_to_gcse_p (rtx);
435 static bool gcse_constant_p (const_rtx);
436 static int oprs_unchanged_p (const_rtx, const_rtx, int);
437 static int oprs_anticipatable_p (const_rtx, const_rtx);
438 static int oprs_available_p (const_rtx, const_rtx);
439 static void insert_expr_in_table (rtx, enum machine_mode, rtx, int, int,
440 struct hash_table_d *);
441 static void insert_set_in_table (rtx, rtx, struct hash_table_d *);
442 static unsigned int hash_expr (const_rtx, enum machine_mode, int *, int);
443 static unsigned int hash_set (int, int);
444 static int expr_equiv_p (const_rtx, const_rtx);
445 static void record_last_reg_set_info (rtx, int);
446 static void record_last_mem_set_info (rtx);
447 static void record_last_set_info (rtx, const_rtx, void *);
448 static void compute_hash_table (struct hash_table_d *);
449 static void alloc_hash_table (struct hash_table_d *, int);
450 static void free_hash_table (struct hash_table_d *);
451 static void compute_hash_table_work (struct hash_table_d *);
452 static void dump_hash_table (FILE *, const char *, struct hash_table_d *);
453 static struct expr *lookup_set (unsigned int, struct hash_table_d *);
454 static struct expr *next_set (unsigned int, struct expr *);
455 static void reset_opr_set_tables (void);
456 static int oprs_not_set_p (const_rtx, const_rtx);
457 static void mark_call (rtx);
458 static void mark_set (rtx, rtx);
459 static void mark_clobber (rtx, rtx);
460 static void mark_oprs_set (rtx);
461 static void alloc_cprop_mem (int, int);
462 static void free_cprop_mem (void);
463 static void compute_transp (const_rtx, int, sbitmap *, int);
464 static void compute_transpout (void);
465 static void compute_local_properties (sbitmap *, sbitmap *, sbitmap *,
466 struct hash_table_d *);
467 static void compute_cprop_data (void);
468 static void find_used_regs (rtx *, void *);
469 static int try_replace_reg (rtx, rtx, rtx);
470 static struct expr *find_avail_set (int, rtx);
471 static int cprop_jump (basic_block, rtx, rtx, rtx, rtx);
472 static void mems_conflict_for_gcse_p (rtx, const_rtx, void *);
473 static int load_killed_in_block_p (const_basic_block, int, const_rtx, int);
474 static void canon_list_insert (rtx, const_rtx, void *);
475 static int cprop_insn (rtx);
476 static void find_implicit_sets (void);
477 static int one_cprop_pass (void);
478 static bool constprop_register (rtx, rtx, rtx);
479 static struct expr *find_bypass_set (int, int);
480 static bool reg_killed_on_edge (const_rtx, const_edge);
481 static int bypass_block (basic_block, rtx, rtx);
482 static int bypass_conditional_jumps (void);
483 static void alloc_pre_mem (int, int);
484 static void free_pre_mem (void);
485 static void compute_pre_data (void);
486 static int pre_expr_reaches_here_p (basic_block, struct expr *,
487 basic_block);
488 static void insert_insn_end_basic_block (struct expr *, basic_block, int);
489 static void pre_insert_copy_insn (struct expr *, rtx);
490 static void pre_insert_copies (void);
491 static int pre_delete (void);
492 static int pre_gcse (void);
493 static int one_pre_gcse_pass (void);
494 static void add_label_notes (rtx, rtx);
495 static void alloc_code_hoist_mem (int, int);
496 static void free_code_hoist_mem (void);
497 static void compute_code_hoist_vbeinout (void);
498 static void compute_code_hoist_data (void);
499 static int hoist_expr_reaches_here_p (basic_block, int, basic_block, char *);
500 static int hoist_code (void);
501 static int one_code_hoisting_pass (void);
502 static rtx process_insert_insn (struct expr *);
503 static int pre_edge_insert (struct edge_list *, struct expr **);
504 static int pre_expr_reaches_here_p_work (basic_block, struct expr *,
505 basic_block, char *);
506 static struct ls_expr * ldst_entry (rtx);
507 static void free_ldst_entry (struct ls_expr *);
508 static void free_ldst_mems (void);
509 static void print_ldst_list (FILE *);
510 static struct ls_expr * find_rtx_in_ldst (rtx);
511 static inline struct ls_expr * first_ls_expr (void);
512 static inline struct ls_expr * next_ls_expr (struct ls_expr *);
513 static int simple_mem (const_rtx);
514 static void invalidate_any_buried_refs (rtx);
515 static void compute_ld_motion_mems (void);
516 static void trim_ld_motion_mems (void);
517 static void update_ld_motion_stores (struct expr *);
518 static void free_insn_expr_list_list (rtx *);
519 static void clear_modify_mem_tables (void);
520 static void free_modify_mem_tables (void);
521 static rtx gcse_emit_move_after (rtx, rtx, rtx);
522 static void local_cprop_find_used_regs (rtx *, void *);
523 static bool do_local_cprop (rtx, rtx);
524 static int local_cprop_pass (void);
525 static bool is_too_expensive (const char *);
527 #define GNEW(T) ((T *) gmalloc (sizeof (T)))
528 #define GCNEW(T) ((T *) gcalloc (1, sizeof (T)))
530 #define GNEWVEC(T, N) ((T *) gmalloc (sizeof (T) * (N)))
531 #define GCNEWVEC(T, N) ((T *) gcalloc ((N), sizeof (T)))
533 #define GNEWVAR(T, S) ((T *) gmalloc ((S)))
534 #define GCNEWVAR(T, S) ((T *) gcalloc (1, (S)))
536 #define GOBNEW(T) ((T *) gcse_alloc (sizeof (T)))
537 #define GOBNEWVAR(T, S) ((T *) gcse_alloc ((S)))
539 /* Misc. utilities. */
541 /* Nonzero for each mode that supports (set (reg) (reg)).
542 This is trivially true for integer and floating point values.
543 It may or may not be true for condition codes. */
544 static char can_copy[(int) NUM_MACHINE_MODES];
546 /* Compute which modes support reg/reg copy operations. */
548 static void
549 compute_can_copy (void)
551 int i;
552 #ifndef AVOID_CCMODE_COPIES
553 rtx reg, insn;
554 #endif
555 memset (can_copy, 0, NUM_MACHINE_MODES);
557 start_sequence ();
558 for (i = 0; i < NUM_MACHINE_MODES; i++)
559 if (GET_MODE_CLASS (i) == MODE_CC)
561 #ifdef AVOID_CCMODE_COPIES
562 can_copy[i] = 0;
563 #else
564 reg = gen_rtx_REG ((enum machine_mode) i, LAST_VIRTUAL_REGISTER + 1);
565 insn = emit_insn (gen_rtx_SET (VOIDmode, reg, reg));
566 if (recog (PATTERN (insn), insn, NULL) >= 0)
567 can_copy[i] = 1;
568 #endif
570 else
571 can_copy[i] = 1;
573 end_sequence ();
576 /* Returns whether the mode supports reg/reg copy operations. */
578 bool
579 can_copy_p (enum machine_mode mode)
581 static bool can_copy_init_p = false;
583 if (! can_copy_init_p)
585 compute_can_copy ();
586 can_copy_init_p = true;
589 return can_copy[mode] != 0;
593 /* Cover function to xmalloc to record bytes allocated. */
595 static void *
596 gmalloc (size_t size)
598 bytes_used += size;
599 return xmalloc (size);
602 /* Cover function to xcalloc to record bytes allocated. */
604 static void *
605 gcalloc (size_t nelem, size_t elsize)
607 bytes_used += nelem * elsize;
608 return xcalloc (nelem, elsize);
611 /* Cover function to obstack_alloc. */
613 static void *
614 gcse_alloc (unsigned long size)
616 bytes_used += size;
617 return obstack_alloc (&gcse_obstack, size);
620 /* Allocate memory for the reg/memory set tracking tables.
621 This is called at the start of each pass. */
623 static void
624 alloc_gcse_mem (void)
626 /* Allocate vars to track sets of regs. */
627 reg_set_bitmap = ALLOC_REG_SET (NULL);
629 /* Allocate array to keep a list of insns which modify memory in each
630 basic block. */
631 modify_mem_list = GCNEWVEC (rtx, last_basic_block);
632 canon_modify_mem_list = GCNEWVEC (rtx, last_basic_block);
633 modify_mem_list_set = BITMAP_ALLOC (NULL);
634 blocks_with_calls = BITMAP_ALLOC (NULL);
637 /* Free memory allocated by alloc_gcse_mem. */
639 static void
640 free_gcse_mem (void)
642 free_modify_mem_tables ();
643 BITMAP_FREE (modify_mem_list_set);
644 BITMAP_FREE (blocks_with_calls);
647 /* Compute the local properties of each recorded expression.
649 Local properties are those that are defined by the block, irrespective of
650 other blocks.
652 An expression is transparent in a block if its operands are not modified
653 in the block.
655 An expression is computed (locally available) in a block if it is computed
656 at least once and expression would contain the same value if the
657 computation was moved to the end of the block.
659 An expression is locally anticipatable in a block if it is computed at
660 least once and expression would contain the same value if the computation
661 was moved to the beginning of the block.
663 We call this routine for cprop, pre and code hoisting. They all compute
664 basically the same information and thus can easily share this code.
666 TRANSP, COMP, and ANTLOC are destination sbitmaps for recording local
667 properties. If NULL, then it is not necessary to compute or record that
668 particular property.
670 TABLE controls which hash table to look at. If it is set hash table,
671 additionally, TRANSP is computed as ~TRANSP, since this is really cprop's
672 ABSALTERED. */
674 static void
675 compute_local_properties (sbitmap *transp, sbitmap *comp, sbitmap *antloc,
676 struct hash_table_d *table)
678 unsigned int i;
680 /* Initialize any bitmaps that were passed in. */
681 if (transp)
683 if (table->set_p)
684 sbitmap_vector_zero (transp, last_basic_block);
685 else
686 sbitmap_vector_ones (transp, last_basic_block);
689 if (comp)
690 sbitmap_vector_zero (comp, last_basic_block);
691 if (antloc)
692 sbitmap_vector_zero (antloc, last_basic_block);
694 for (i = 0; i < table->size; i++)
696 struct expr *expr;
698 for (expr = table->table[i]; expr != NULL; expr = expr->next_same_hash)
700 int indx = expr->bitmap_index;
701 struct occr *occr;
703 /* The expression is transparent in this block if it is not killed.
704 We start by assuming all are transparent [none are killed], and
705 then reset the bits for those that are. */
706 if (transp)
707 compute_transp (expr->expr, indx, transp, table->set_p);
709 /* The occurrences recorded in antic_occr are exactly those that
710 we want to set to nonzero in ANTLOC. */
711 if (antloc)
712 for (occr = expr->antic_occr; occr != NULL; occr = occr->next)
714 SET_BIT (antloc[BLOCK_FOR_INSN (occr->insn)->index], indx);
716 /* While we're scanning the table, this is a good place to
717 initialize this. */
718 occr->deleted_p = 0;
721 /* The occurrences recorded in avail_occr are exactly those that
722 we want to set to nonzero in COMP. */
723 if (comp)
724 for (occr = expr->avail_occr; occr != NULL; occr = occr->next)
726 SET_BIT (comp[BLOCK_FOR_INSN (occr->insn)->index], indx);
728 /* While we're scanning the table, this is a good place to
729 initialize this. */
730 occr->copied_p = 0;
733 /* While we're scanning the table, this is a good place to
734 initialize this. */
735 expr->reaching_reg = 0;
740 /* Hash table support. */
742 struct reg_avail_info
744 basic_block last_bb;
745 int first_set;
746 int last_set;
749 static struct reg_avail_info *reg_avail_info;
750 static basic_block current_bb;
753 /* See whether X, the source of a set, is something we want to consider for
754 GCSE. */
756 static int
757 want_to_gcse_p (rtx x)
759 #ifdef STACK_REGS
760 /* On register stack architectures, don't GCSE constants from the
761 constant pool, as the benefits are often swamped by the overhead
762 of shuffling the register stack between basic blocks. */
763 if (IS_STACK_MODE (GET_MODE (x)))
764 x = avoid_constant_pool_reference (x);
765 #endif
767 switch (GET_CODE (x))
769 case REG:
770 case SUBREG:
771 case CONST_INT:
772 case CONST_DOUBLE:
773 case CONST_FIXED:
774 case CONST_VECTOR:
775 case CALL:
776 return 0;
778 default:
779 return can_assign_to_reg_without_clobbers_p (x);
783 /* Used internally by can_assign_to_reg_without_clobbers_p. */
785 static GTY(()) rtx test_insn;
787 /* Return true if we can assign X to a pseudo register such that the
788 resulting insn does not result in clobbering a hard register as a
789 side-effect.
791 Additionally, if the target requires it, check that the resulting insn
792 can be copied. If it cannot, this means that X is special and probably
793 has hidden side-effects we don't want to mess with.
795 This function is typically used by code motion passes, to verify
796 that it is safe to insert an insn without worrying about clobbering
797 maybe live hard regs. */
799 bool
800 can_assign_to_reg_without_clobbers_p (rtx x)
802 int num_clobbers = 0;
803 int icode;
805 /* If this is a valid operand, we are OK. If it's VOIDmode, we aren't. */
806 if (general_operand (x, GET_MODE (x)))
807 return 1;
808 else if (GET_MODE (x) == VOIDmode)
809 return 0;
811 /* Otherwise, check if we can make a valid insn from it. First initialize
812 our test insn if we haven't already. */
813 if (test_insn == 0)
815 test_insn
816 = make_insn_raw (gen_rtx_SET (VOIDmode,
817 gen_rtx_REG (word_mode,
818 FIRST_PSEUDO_REGISTER * 2),
819 const0_rtx));
820 NEXT_INSN (test_insn) = PREV_INSN (test_insn) = 0;
823 /* Now make an insn like the one we would make when GCSE'ing and see if
824 valid. */
825 PUT_MODE (SET_DEST (PATTERN (test_insn)), GET_MODE (x));
826 SET_SRC (PATTERN (test_insn)) = x;
828 icode = recog (PATTERN (test_insn), test_insn, &num_clobbers);
829 if (icode < 0)
830 return false;
832 if (num_clobbers > 0 && added_clobbers_hard_reg_p (icode))
833 return false;
835 if (targetm.cannot_copy_insn_p && targetm.cannot_copy_insn_p (test_insn))
836 return false;
838 return true;
841 /* Return nonzero if the operands of expression X are unchanged from the
842 start of INSN's basic block up to but not including INSN (if AVAIL_P == 0),
843 or from INSN to the end of INSN's basic block (if AVAIL_P != 0). */
845 static int
846 oprs_unchanged_p (const_rtx x, const_rtx insn, int avail_p)
848 int i, j;
849 enum rtx_code code;
850 const char *fmt;
852 if (x == 0)
853 return 1;
855 code = GET_CODE (x);
856 switch (code)
858 case REG:
860 struct reg_avail_info *info = &reg_avail_info[REGNO (x)];
862 if (info->last_bb != current_bb)
863 return 1;
864 if (avail_p)
865 return info->last_set < DF_INSN_LUID (insn);
866 else
867 return info->first_set >= DF_INSN_LUID (insn);
870 case MEM:
871 if (load_killed_in_block_p (current_bb, DF_INSN_LUID (insn),
872 x, avail_p))
873 return 0;
874 else
875 return oprs_unchanged_p (XEXP (x, 0), insn, avail_p);
877 case PRE_DEC:
878 case PRE_INC:
879 case POST_DEC:
880 case POST_INC:
881 case PRE_MODIFY:
882 case POST_MODIFY:
883 return 0;
885 case PC:
886 case CC0: /*FIXME*/
887 case CONST:
888 case CONST_INT:
889 case CONST_DOUBLE:
890 case CONST_FIXED:
891 case CONST_VECTOR:
892 case SYMBOL_REF:
893 case LABEL_REF:
894 case ADDR_VEC:
895 case ADDR_DIFF_VEC:
896 return 1;
898 default:
899 break;
902 for (i = GET_RTX_LENGTH (code) - 1, fmt = GET_RTX_FORMAT (code); i >= 0; i--)
904 if (fmt[i] == 'e')
906 /* If we are about to do the last recursive call needed at this
907 level, change it into iteration. This function is called enough
908 to be worth it. */
909 if (i == 0)
910 return oprs_unchanged_p (XEXP (x, i), insn, avail_p);
912 else if (! oprs_unchanged_p (XEXP (x, i), insn, avail_p))
913 return 0;
915 else if (fmt[i] == 'E')
916 for (j = 0; j < XVECLEN (x, i); j++)
917 if (! oprs_unchanged_p (XVECEXP (x, i, j), insn, avail_p))
918 return 0;
921 return 1;
924 /* Used for communication between mems_conflict_for_gcse_p and
925 load_killed_in_block_p. Nonzero if mems_conflict_for_gcse_p finds a
926 conflict between two memory references. */
927 static int gcse_mems_conflict_p;
929 /* Used for communication between mems_conflict_for_gcse_p and
930 load_killed_in_block_p. A memory reference for a load instruction,
931 mems_conflict_for_gcse_p will see if a memory store conflicts with
932 this memory load. */
933 static const_rtx gcse_mem_operand;
935 /* DEST is the output of an instruction. If it is a memory reference, and
936 possibly conflicts with the load found in gcse_mem_operand, then set
937 gcse_mems_conflict_p to a nonzero value. */
939 static void
940 mems_conflict_for_gcse_p (rtx dest, const_rtx setter ATTRIBUTE_UNUSED,
941 void *data ATTRIBUTE_UNUSED)
943 while (GET_CODE (dest) == SUBREG
944 || GET_CODE (dest) == ZERO_EXTRACT
945 || GET_CODE (dest) == STRICT_LOW_PART)
946 dest = XEXP (dest, 0);
948 /* If DEST is not a MEM, then it will not conflict with the load. Note
949 that function calls are assumed to clobber memory, but are handled
950 elsewhere. */
951 if (! MEM_P (dest))
952 return;
954 /* If we are setting a MEM in our list of specially recognized MEMs,
955 don't mark as killed this time. */
957 if (expr_equiv_p (dest, gcse_mem_operand) && pre_ldst_mems != NULL)
959 if (!find_rtx_in_ldst (dest))
960 gcse_mems_conflict_p = 1;
961 return;
964 if (true_dependence (dest, GET_MODE (dest), gcse_mem_operand,
965 rtx_addr_varies_p))
966 gcse_mems_conflict_p = 1;
969 /* Return nonzero if the expression in X (a memory reference) is killed
970 in block BB before or after the insn with the LUID in UID_LIMIT.
971 AVAIL_P is nonzero for kills after UID_LIMIT, and zero for kills
972 before UID_LIMIT.
974 To check the entire block, set UID_LIMIT to max_uid + 1 and
975 AVAIL_P to 0. */
977 static int
978 load_killed_in_block_p (const_basic_block bb, int uid_limit, const_rtx x, int avail_p)
980 rtx list_entry = modify_mem_list[bb->index];
982 /* If this is a readonly then we aren't going to be changing it. */
983 if (MEM_READONLY_P (x))
984 return 0;
986 while (list_entry)
988 rtx setter;
989 /* Ignore entries in the list that do not apply. */
990 if ((avail_p
991 && DF_INSN_LUID (XEXP (list_entry, 0)) < uid_limit)
992 || (! avail_p
993 && DF_INSN_LUID (XEXP (list_entry, 0)) > uid_limit))
995 list_entry = XEXP (list_entry, 1);
996 continue;
999 setter = XEXP (list_entry, 0);
1001 /* If SETTER is a call everything is clobbered. Note that calls
1002 to pure functions are never put on the list, so we need not
1003 worry about them. */
1004 if (CALL_P (setter))
1005 return 1;
1007 /* SETTER must be an INSN of some kind that sets memory. Call
1008 note_stores to examine each hunk of memory that is modified.
1010 The note_stores interface is pretty limited, so we have to
1011 communicate via global variables. Yuk. */
1012 gcse_mem_operand = x;
1013 gcse_mems_conflict_p = 0;
1014 note_stores (PATTERN (setter), mems_conflict_for_gcse_p, NULL);
1015 if (gcse_mems_conflict_p)
1016 return 1;
1017 list_entry = XEXP (list_entry, 1);
1019 return 0;
1022 /* Return nonzero if the operands of expression X are unchanged from
1023 the start of INSN's basic block up to but not including INSN. */
1025 static int
1026 oprs_anticipatable_p (const_rtx x, const_rtx insn)
1028 return oprs_unchanged_p (x, insn, 0);
1031 /* Return nonzero if the operands of expression X are unchanged from
1032 INSN to the end of INSN's basic block. */
1034 static int
1035 oprs_available_p (const_rtx x, const_rtx insn)
1037 return oprs_unchanged_p (x, insn, 1);
1040 /* Hash expression X.
1042 MODE is only used if X is a CONST_INT. DO_NOT_RECORD_P is a boolean
1043 indicating if a volatile operand is found or if the expression contains
1044 something we don't want to insert in the table. HASH_TABLE_SIZE is
1045 the current size of the hash table to be probed. */
1047 static unsigned int
1048 hash_expr (const_rtx x, enum machine_mode mode, int *do_not_record_p,
1049 int hash_table_size)
1051 unsigned int hash;
1053 *do_not_record_p = 0;
1055 hash = hash_rtx (x, mode, do_not_record_p,
1056 NULL, /*have_reg_qty=*/false);
1057 return hash % hash_table_size;
1060 /* Hash a set of register REGNO.
1062 Sets are hashed on the register that is set. This simplifies the PRE copy
1063 propagation code.
1065 ??? May need to make things more elaborate. Later, as necessary. */
1067 static unsigned int
1068 hash_set (int regno, int hash_table_size)
1070 unsigned int hash;
1072 hash = regno;
1073 return hash % hash_table_size;
1076 /* Return nonzero if exp1 is equivalent to exp2. */
1078 static int
1079 expr_equiv_p (const_rtx x, const_rtx y)
1081 return exp_equiv_p (x, y, 0, true);
1084 /* Insert expression X in INSN in the hash TABLE.
1085 If it is already present, record it as the last occurrence in INSN's
1086 basic block.
1088 MODE is the mode of the value X is being stored into.
1089 It is only used if X is a CONST_INT.
1091 ANTIC_P is nonzero if X is an anticipatable expression.
1092 AVAIL_P is nonzero if X is an available expression. */
1094 static void
1095 insert_expr_in_table (rtx x, enum machine_mode mode, rtx insn, int antic_p,
1096 int avail_p, struct hash_table_d *table)
1098 int found, do_not_record_p;
1099 unsigned int hash;
1100 struct expr *cur_expr, *last_expr = NULL;
1101 struct occr *antic_occr, *avail_occr;
1103 hash = hash_expr (x, mode, &do_not_record_p, table->size);
1105 /* Do not insert expression in table if it contains volatile operands,
1106 or if hash_expr determines the expression is something we don't want
1107 to or can't handle. */
1108 if (do_not_record_p)
1109 return;
1111 cur_expr = table->table[hash];
1112 found = 0;
1114 while (cur_expr && 0 == (found = expr_equiv_p (cur_expr->expr, x)))
1116 /* If the expression isn't found, save a pointer to the end of
1117 the list. */
1118 last_expr = cur_expr;
1119 cur_expr = cur_expr->next_same_hash;
1122 if (! found)
1124 cur_expr = GOBNEW (struct expr);
1125 bytes_used += sizeof (struct expr);
1126 if (table->table[hash] == NULL)
1127 /* This is the first pattern that hashed to this index. */
1128 table->table[hash] = cur_expr;
1129 else
1130 /* Add EXPR to end of this hash chain. */
1131 last_expr->next_same_hash = cur_expr;
1133 /* Set the fields of the expr element. */
1134 cur_expr->expr = x;
1135 cur_expr->bitmap_index = table->n_elems++;
1136 cur_expr->next_same_hash = NULL;
1137 cur_expr->antic_occr = NULL;
1138 cur_expr->avail_occr = NULL;
1141 /* Now record the occurrence(s). */
1142 if (antic_p)
1144 antic_occr = cur_expr->antic_occr;
1146 if (antic_occr
1147 && BLOCK_FOR_INSN (antic_occr->insn) != BLOCK_FOR_INSN (insn))
1148 antic_occr = NULL;
1150 if (antic_occr)
1151 /* Found another instance of the expression in the same basic block.
1152 Prefer the currently recorded one. We want the first one in the
1153 block and the block is scanned from start to end. */
1154 ; /* nothing to do */
1155 else
1157 /* First occurrence of this expression in this basic block. */
1158 antic_occr = GOBNEW (struct occr);
1159 bytes_used += sizeof (struct occr);
1160 antic_occr->insn = insn;
1161 antic_occr->next = cur_expr->antic_occr;
1162 antic_occr->deleted_p = 0;
1163 cur_expr->antic_occr = antic_occr;
1167 if (avail_p)
1169 avail_occr = cur_expr->avail_occr;
1171 if (avail_occr
1172 && BLOCK_FOR_INSN (avail_occr->insn) == BLOCK_FOR_INSN (insn))
1174 /* Found another instance of the expression in the same basic block.
1175 Prefer this occurrence to the currently recorded one. We want
1176 the last one in the block and the block is scanned from start
1177 to end. */
1178 avail_occr->insn = insn;
1180 else
1182 /* First occurrence of this expression in this basic block. */
1183 avail_occr = GOBNEW (struct occr);
1184 bytes_used += sizeof (struct occr);
1185 avail_occr->insn = insn;
1186 avail_occr->next = cur_expr->avail_occr;
1187 avail_occr->deleted_p = 0;
1188 cur_expr->avail_occr = avail_occr;
1193 /* Insert pattern X in INSN in the hash table.
1194 X is a SET of a reg to either another reg or a constant.
1195 If it is already present, record it as the last occurrence in INSN's
1196 basic block. */
1198 static void
1199 insert_set_in_table (rtx x, rtx insn, struct hash_table_d *table)
1201 int found;
1202 unsigned int hash;
1203 struct expr *cur_expr, *last_expr = NULL;
1204 struct occr *cur_occr;
1206 gcc_assert (GET_CODE (x) == SET && REG_P (SET_DEST (x)));
1208 hash = hash_set (REGNO (SET_DEST (x)), table->size);
1210 cur_expr = table->table[hash];
1211 found = 0;
1213 while (cur_expr && 0 == (found = expr_equiv_p (cur_expr->expr, x)))
1215 /* If the expression isn't found, save a pointer to the end of
1216 the list. */
1217 last_expr = cur_expr;
1218 cur_expr = cur_expr->next_same_hash;
1221 if (! found)
1223 cur_expr = GOBNEW (struct expr);
1224 bytes_used += sizeof (struct expr);
1225 if (table->table[hash] == NULL)
1226 /* This is the first pattern that hashed to this index. */
1227 table->table[hash] = cur_expr;
1228 else
1229 /* Add EXPR to end of this hash chain. */
1230 last_expr->next_same_hash = cur_expr;
1232 /* Set the fields of the expr element.
1233 We must copy X because it can be modified when copy propagation is
1234 performed on its operands. */
1235 cur_expr->expr = copy_rtx (x);
1236 cur_expr->bitmap_index = table->n_elems++;
1237 cur_expr->next_same_hash = NULL;
1238 cur_expr->antic_occr = NULL;
1239 cur_expr->avail_occr = NULL;
1242 /* Now record the occurrence. */
1243 cur_occr = cur_expr->avail_occr;
1245 if (cur_occr
1246 && BLOCK_FOR_INSN (cur_occr->insn) == BLOCK_FOR_INSN (insn))
1248 /* Found another instance of the expression in the same basic block.
1249 Prefer this occurrence to the currently recorded one. We want
1250 the last one in the block and the block is scanned from start
1251 to end. */
1252 cur_occr->insn = insn;
1254 else
1256 /* First occurrence of this expression in this basic block. */
1257 cur_occr = GOBNEW (struct occr);
1258 bytes_used += sizeof (struct occr);
1259 cur_occr->insn = insn;
1260 cur_occr->next = cur_expr->avail_occr;
1261 cur_occr->deleted_p = 0;
1262 cur_expr->avail_occr = cur_occr;
1266 /* Determine whether the rtx X should be treated as a constant for
1267 the purposes of GCSE's constant propagation. */
1269 static bool
1270 gcse_constant_p (const_rtx x)
1272 /* Consider a COMPARE of two integers constant. */
1273 if (GET_CODE (x) == COMPARE
1274 && CONST_INT_P (XEXP (x, 0))
1275 && CONST_INT_P (XEXP (x, 1)))
1276 return true;
1278 /* Consider a COMPARE of the same registers is a constant
1279 if they are not floating point registers. */
1280 if (GET_CODE(x) == COMPARE
1281 && REG_P (XEXP (x, 0)) && REG_P (XEXP (x, 1))
1282 && REGNO (XEXP (x, 0)) == REGNO (XEXP (x, 1))
1283 && ! FLOAT_MODE_P (GET_MODE (XEXP (x, 0)))
1284 && ! FLOAT_MODE_P (GET_MODE (XEXP (x, 1))))
1285 return true;
1287 /* Since X might be inserted more than once we have to take care that it
1288 is sharable. */
1289 return CONSTANT_P (x) && (GET_CODE (x) != CONST || shared_const_p (x));
1292 /* Scan pattern PAT of INSN and add an entry to the hash TABLE (set or
1293 expression one). */
1295 static void
1296 hash_scan_set (rtx pat, rtx insn, struct hash_table_d *table)
1298 rtx src = SET_SRC (pat);
1299 rtx dest = SET_DEST (pat);
1300 rtx note;
1302 if (GET_CODE (src) == CALL)
1303 hash_scan_call (src, insn, table);
1305 else if (REG_P (dest))
1307 unsigned int regno = REGNO (dest);
1308 rtx tmp;
1310 /* See if a REG_EQUAL note shows this equivalent to a simpler expression.
1312 This allows us to do a single GCSE pass and still eliminate
1313 redundant constants, addresses or other expressions that are
1314 constructed with multiple instructions.
1316 However, keep the original SRC if INSN is a simple reg-reg move. In
1317 In this case, there will almost always be a REG_EQUAL note on the
1318 insn that sets SRC. By recording the REG_EQUAL value here as SRC
1319 for INSN, we miss copy propagation opportunities and we perform the
1320 same PRE GCSE operation repeatedly on the same REG_EQUAL value if we
1321 do more than one PRE GCSE pass.
1323 Note that this does not impede profitable constant propagations. We
1324 "look through" reg-reg sets in lookup_avail_set. */
1325 note = find_reg_equal_equiv_note (insn);
1326 if (note != 0
1327 && REG_NOTE_KIND (note) == REG_EQUAL
1328 && !REG_P (src)
1329 && (table->set_p
1330 ? gcse_constant_p (XEXP (note, 0))
1331 : want_to_gcse_p (XEXP (note, 0))))
1332 src = XEXP (note, 0), pat = gen_rtx_SET (VOIDmode, dest, src);
1334 /* Only record sets of pseudo-regs in the hash table. */
1335 if (! table->set_p
1336 && regno >= FIRST_PSEUDO_REGISTER
1337 /* Don't GCSE something if we can't do a reg/reg copy. */
1338 && can_copy_p (GET_MODE (dest))
1339 /* GCSE commonly inserts instruction after the insn. We can't
1340 do that easily for EH edges so disable GCSE on these for now. */
1341 /* ??? We can now easily create new EH landing pads at the
1342 gimple level, for splitting edges; there's no reason we
1343 can't do the same thing at the rtl level. */
1344 && !can_throw_internal (insn)
1345 /* Is SET_SRC something we want to gcse? */
1346 && want_to_gcse_p (src)
1347 /* Don't CSE a nop. */
1348 && ! set_noop_p (pat)
1349 /* Don't GCSE if it has attached REG_EQUIV note.
1350 At this point this only function parameters should have
1351 REG_EQUIV notes and if the argument slot is used somewhere
1352 explicitly, it means address of parameter has been taken,
1353 so we should not extend the lifetime of the pseudo. */
1354 && (note == NULL_RTX || ! MEM_P (XEXP (note, 0))))
1356 /* An expression is not anticipatable if its operands are
1357 modified before this insn or if this is not the only SET in
1358 this insn. The latter condition does not have to mean that
1359 SRC itself is not anticipatable, but we just will not be
1360 able to handle code motion of insns with multiple sets. */
1361 int antic_p = oprs_anticipatable_p (src, insn)
1362 && !multiple_sets (insn);
1363 /* An expression is not available if its operands are
1364 subsequently modified, including this insn. It's also not
1365 available if this is a branch, because we can't insert
1366 a set after the branch. */
1367 int avail_p = (oprs_available_p (src, insn)
1368 && ! JUMP_P (insn));
1370 insert_expr_in_table (src, GET_MODE (dest), insn, antic_p, avail_p, table);
1373 /* Record sets for constant/copy propagation. */
1374 else if (table->set_p
1375 && regno >= FIRST_PSEUDO_REGISTER
1376 && ((REG_P (src)
1377 && REGNO (src) >= FIRST_PSEUDO_REGISTER
1378 && can_copy_p (GET_MODE (dest))
1379 && REGNO (src) != regno)
1380 || gcse_constant_p (src))
1381 /* A copy is not available if its src or dest is subsequently
1382 modified. Here we want to search from INSN+1 on, but
1383 oprs_available_p searches from INSN on. */
1384 && (insn == BB_END (BLOCK_FOR_INSN (insn))
1385 || (tmp = next_nonnote_insn (insn)) == NULL_RTX
1386 || BLOCK_FOR_INSN (tmp) != BLOCK_FOR_INSN (insn)
1387 || oprs_available_p (pat, tmp)))
1388 insert_set_in_table (pat, insn, table);
1390 /* In case of store we want to consider the memory value as available in
1391 the REG stored in that memory. This makes it possible to remove
1392 redundant loads from due to stores to the same location. */
1393 else if (flag_gcse_las && REG_P (src) && MEM_P (dest))
1395 unsigned int regno = REGNO (src);
1397 /* Do not do this for constant/copy propagation. */
1398 if (! table->set_p
1399 /* Only record sets of pseudo-regs in the hash table. */
1400 && regno >= FIRST_PSEUDO_REGISTER
1401 /* Don't GCSE something if we can't do a reg/reg copy. */
1402 && can_copy_p (GET_MODE (src))
1403 /* GCSE commonly inserts instruction after the insn. We can't
1404 do that easily for EH edges so disable GCSE on these for now. */
1405 && !can_throw_internal (insn)
1406 /* Is SET_DEST something we want to gcse? */
1407 && want_to_gcse_p (dest)
1408 /* Don't CSE a nop. */
1409 && ! set_noop_p (pat)
1410 /* Don't GCSE if it has attached REG_EQUIV note.
1411 At this point this only function parameters should have
1412 REG_EQUIV notes and if the argument slot is used somewhere
1413 explicitly, it means address of parameter has been taken,
1414 so we should not extend the lifetime of the pseudo. */
1415 && ((note = find_reg_note (insn, REG_EQUIV, NULL_RTX)) == 0
1416 || ! MEM_P (XEXP (note, 0))))
1418 /* Stores are never anticipatable. */
1419 int antic_p = 0;
1420 /* An expression is not available if its operands are
1421 subsequently modified, including this insn. It's also not
1422 available if this is a branch, because we can't insert
1423 a set after the branch. */
1424 int avail_p = oprs_available_p (dest, insn)
1425 && ! JUMP_P (insn);
1427 /* Record the memory expression (DEST) in the hash table. */
1428 insert_expr_in_table (dest, GET_MODE (dest), insn,
1429 antic_p, avail_p, table);
1434 static void
1435 hash_scan_clobber (rtx x ATTRIBUTE_UNUSED, rtx insn ATTRIBUTE_UNUSED,
1436 struct hash_table_d *table ATTRIBUTE_UNUSED)
1438 /* Currently nothing to do. */
1441 static void
1442 hash_scan_call (rtx x ATTRIBUTE_UNUSED, rtx insn ATTRIBUTE_UNUSED,
1443 struct hash_table_d *table ATTRIBUTE_UNUSED)
1445 /* Currently nothing to do. */
1448 /* Process INSN and add hash table entries as appropriate.
1450 Only available expressions that set a single pseudo-reg are recorded.
1452 Single sets in a PARALLEL could be handled, but it's an extra complication
1453 that isn't dealt with right now. The trick is handling the CLOBBERs that
1454 are also in the PARALLEL. Later.
1456 If SET_P is nonzero, this is for the assignment hash table,
1457 otherwise it is for the expression hash table. */
1459 static void
1460 hash_scan_insn (rtx insn, struct hash_table_d *table)
1462 rtx pat = PATTERN (insn);
1463 int i;
1465 /* Pick out the sets of INSN and for other forms of instructions record
1466 what's been modified. */
1468 if (GET_CODE (pat) == SET)
1469 hash_scan_set (pat, insn, table);
1470 else if (GET_CODE (pat) == PARALLEL)
1471 for (i = 0; i < XVECLEN (pat, 0); i++)
1473 rtx x = XVECEXP (pat, 0, i);
1475 if (GET_CODE (x) == SET)
1476 hash_scan_set (x, insn, table);
1477 else if (GET_CODE (x) == CLOBBER)
1478 hash_scan_clobber (x, insn, table);
1479 else if (GET_CODE (x) == CALL)
1480 hash_scan_call (x, insn, table);
1483 else if (GET_CODE (pat) == CLOBBER)
1484 hash_scan_clobber (pat, insn, table);
1485 else if (GET_CODE (pat) == CALL)
1486 hash_scan_call (pat, insn, table);
1489 static void
1490 dump_hash_table (FILE *file, const char *name, struct hash_table_d *table)
1492 int i;
1493 /* Flattened out table, so it's printed in proper order. */
1494 struct expr **flat_table;
1495 unsigned int *hash_val;
1496 struct expr *expr;
1498 flat_table = XCNEWVEC (struct expr *, table->n_elems);
1499 hash_val = XNEWVEC (unsigned int, table->n_elems);
1501 for (i = 0; i < (int) table->size; i++)
1502 for (expr = table->table[i]; expr != NULL; expr = expr->next_same_hash)
1504 flat_table[expr->bitmap_index] = expr;
1505 hash_val[expr->bitmap_index] = i;
1508 fprintf (file, "%s hash table (%d buckets, %d entries)\n",
1509 name, table->size, table->n_elems);
1511 for (i = 0; i < (int) table->n_elems; i++)
1512 if (flat_table[i] != 0)
1514 expr = flat_table[i];
1515 fprintf (file, "Index %d (hash value %d)\n ",
1516 expr->bitmap_index, hash_val[i]);
1517 print_rtl (file, expr->expr);
1518 fprintf (file, "\n");
1521 fprintf (file, "\n");
1523 free (flat_table);
1524 free (hash_val);
1527 /* Record register first/last/block set information for REGNO in INSN.
1529 first_set records the first place in the block where the register
1530 is set and is used to compute "anticipatability".
1532 last_set records the last place in the block where the register
1533 is set and is used to compute "availability".
1535 last_bb records the block for which first_set and last_set are
1536 valid, as a quick test to invalidate them. */
1538 static void
1539 record_last_reg_set_info (rtx insn, int regno)
1541 struct reg_avail_info *info = &reg_avail_info[regno];
1542 int luid = DF_INSN_LUID (insn);
1544 info->last_set = luid;
1545 if (info->last_bb != current_bb)
1547 info->last_bb = current_bb;
1548 info->first_set = luid;
1553 /* Record all of the canonicalized MEMs of record_last_mem_set_info's insn.
1554 Note we store a pair of elements in the list, so they have to be
1555 taken off pairwise. */
1557 static void
1558 canon_list_insert (rtx dest ATTRIBUTE_UNUSED, const_rtx unused1 ATTRIBUTE_UNUSED,
1559 void * v_insn)
1561 rtx dest_addr, insn;
1562 int bb;
1564 while (GET_CODE (dest) == SUBREG
1565 || GET_CODE (dest) == ZERO_EXTRACT
1566 || GET_CODE (dest) == STRICT_LOW_PART)
1567 dest = XEXP (dest, 0);
1569 /* If DEST is not a MEM, then it will not conflict with a load. Note
1570 that function calls are assumed to clobber memory, but are handled
1571 elsewhere. */
1573 if (! MEM_P (dest))
1574 return;
1576 dest_addr = get_addr (XEXP (dest, 0));
1577 dest_addr = canon_rtx (dest_addr);
1578 insn = (rtx) v_insn;
1579 bb = BLOCK_FOR_INSN (insn)->index;
1581 canon_modify_mem_list[bb] =
1582 alloc_EXPR_LIST (VOIDmode, dest_addr, canon_modify_mem_list[bb]);
1583 canon_modify_mem_list[bb] =
1584 alloc_EXPR_LIST (VOIDmode, dest, canon_modify_mem_list[bb]);
1587 /* Record memory modification information for INSN. We do not actually care
1588 about the memory location(s) that are set, or even how they are set (consider
1589 a CALL_INSN). We merely need to record which insns modify memory. */
1591 static void
1592 record_last_mem_set_info (rtx insn)
1594 int bb = BLOCK_FOR_INSN (insn)->index;
1596 /* load_killed_in_block_p will handle the case of calls clobbering
1597 everything. */
1598 modify_mem_list[bb] = alloc_INSN_LIST (insn, modify_mem_list[bb]);
1599 bitmap_set_bit (modify_mem_list_set, bb);
1601 if (CALL_P (insn))
1603 /* Note that traversals of this loop (other than for free-ing)
1604 will break after encountering a CALL_INSN. So, there's no
1605 need to insert a pair of items, as canon_list_insert does. */
1606 canon_modify_mem_list[bb] =
1607 alloc_INSN_LIST (insn, canon_modify_mem_list[bb]);
1608 bitmap_set_bit (blocks_with_calls, bb);
1610 else
1611 note_stores (PATTERN (insn), canon_list_insert, (void*) insn);
1614 /* Called from compute_hash_table via note_stores to handle one
1615 SET or CLOBBER in an insn. DATA is really the instruction in which
1616 the SET is taking place. */
1618 static void
1619 record_last_set_info (rtx dest, const_rtx setter ATTRIBUTE_UNUSED, void *data)
1621 rtx last_set_insn = (rtx) data;
1623 if (GET_CODE (dest) == SUBREG)
1624 dest = SUBREG_REG (dest);
1626 if (REG_P (dest))
1627 record_last_reg_set_info (last_set_insn, REGNO (dest));
1628 else if (MEM_P (dest)
1629 /* Ignore pushes, they clobber nothing. */
1630 && ! push_operand (dest, GET_MODE (dest)))
1631 record_last_mem_set_info (last_set_insn);
1634 /* Top level function to create an expression or assignment hash table.
1636 Expression entries are placed in the hash table if
1637 - they are of the form (set (pseudo-reg) src),
1638 - src is something we want to perform GCSE on,
1639 - none of the operands are subsequently modified in the block
1641 Assignment entries are placed in the hash table if
1642 - they are of the form (set (pseudo-reg) src),
1643 - src is something we want to perform const/copy propagation on,
1644 - none of the operands or target are subsequently modified in the block
1646 Currently src must be a pseudo-reg or a const_int.
1648 TABLE is the table computed. */
1650 static void
1651 compute_hash_table_work (struct hash_table_d *table)
1653 int i;
1655 /* re-Cache any INSN_LIST nodes we have allocated. */
1656 clear_modify_mem_tables ();
1657 /* Some working arrays used to track first and last set in each block. */
1658 reg_avail_info = GNEWVEC (struct reg_avail_info, max_reg_num ());
1660 for (i = 0; i < max_reg_num (); ++i)
1661 reg_avail_info[i].last_bb = NULL;
1663 FOR_EACH_BB (current_bb)
1665 rtx insn;
1666 unsigned int regno;
1668 /* First pass over the instructions records information used to
1669 determine when registers and memory are first and last set. */
1670 FOR_BB_INSNS (current_bb, insn)
1672 if (! INSN_P (insn))
1673 continue;
1675 if (CALL_P (insn))
1677 for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1678 if (TEST_HARD_REG_BIT (regs_invalidated_by_call, regno))
1679 record_last_reg_set_info (insn, regno);
1681 mark_call (insn);
1684 note_stores (PATTERN (insn), record_last_set_info, insn);
1687 /* Insert implicit sets in the hash table. */
1688 if (table->set_p
1689 && implicit_sets[current_bb->index] != NULL_RTX)
1690 hash_scan_set (implicit_sets[current_bb->index],
1691 BB_HEAD (current_bb), table);
1693 /* The next pass builds the hash table. */
1694 FOR_BB_INSNS (current_bb, insn)
1695 if (INSN_P (insn))
1696 hash_scan_insn (insn, table);
1699 free (reg_avail_info);
1700 reg_avail_info = NULL;
1703 /* Allocate space for the set/expr hash TABLE.
1704 It is used to determine the number of buckets to use.
1705 SET_P determines whether set or expression table will
1706 be created. */
1708 static void
1709 alloc_hash_table (struct hash_table_d *table, int set_p)
1711 int n;
1713 n = get_max_insn_count ();
1715 table->size = n / 4;
1716 if (table->size < 11)
1717 table->size = 11;
1719 /* Attempt to maintain efficient use of hash table.
1720 Making it an odd number is simplest for now.
1721 ??? Later take some measurements. */
1722 table->size |= 1;
1723 n = table->size * sizeof (struct expr *);
1724 table->table = GNEWVAR (struct expr *, n);
1725 table->set_p = set_p;
1728 /* Free things allocated by alloc_hash_table. */
1730 static void
1731 free_hash_table (struct hash_table_d *table)
1733 free (table->table);
1736 /* Compute the hash TABLE for doing copy/const propagation or
1737 expression hash table. */
1739 static void
1740 compute_hash_table (struct hash_table_d *table)
1742 /* Initialize count of number of entries in hash table. */
1743 table->n_elems = 0;
1744 memset (table->table, 0, table->size * sizeof (struct expr *));
1746 compute_hash_table_work (table);
1749 /* Expression tracking support. */
1751 /* Lookup REGNO in the set TABLE. The result is a pointer to the
1752 table entry, or NULL if not found. */
1754 static struct expr *
1755 lookup_set (unsigned int regno, struct hash_table_d *table)
1757 unsigned int hash = hash_set (regno, table->size);
1758 struct expr *expr;
1760 expr = table->table[hash];
1762 while (expr && REGNO (SET_DEST (expr->expr)) != regno)
1763 expr = expr->next_same_hash;
1765 return expr;
1768 /* Return the next entry for REGNO in list EXPR. */
1770 static struct expr *
1771 next_set (unsigned int regno, struct expr *expr)
1774 expr = expr->next_same_hash;
1775 while (expr && REGNO (SET_DEST (expr->expr)) != regno);
1777 return expr;
1780 /* Like free_INSN_LIST_list or free_EXPR_LIST_list, except that the node
1781 types may be mixed. */
1783 static void
1784 free_insn_expr_list_list (rtx *listp)
1786 rtx list, next;
1788 for (list = *listp; list ; list = next)
1790 next = XEXP (list, 1);
1791 if (GET_CODE (list) == EXPR_LIST)
1792 free_EXPR_LIST_node (list);
1793 else
1794 free_INSN_LIST_node (list);
1797 *listp = NULL;
1800 /* Clear canon_modify_mem_list and modify_mem_list tables. */
1801 static void
1802 clear_modify_mem_tables (void)
1804 unsigned i;
1805 bitmap_iterator bi;
1807 EXECUTE_IF_SET_IN_BITMAP (modify_mem_list_set, 0, i, bi)
1809 free_INSN_LIST_list (modify_mem_list + i);
1810 free_insn_expr_list_list (canon_modify_mem_list + i);
1812 bitmap_clear (modify_mem_list_set);
1813 bitmap_clear (blocks_with_calls);
1816 /* Release memory used by modify_mem_list_set. */
1818 static void
1819 free_modify_mem_tables (void)
1821 clear_modify_mem_tables ();
1822 free (modify_mem_list);
1823 free (canon_modify_mem_list);
1824 modify_mem_list = 0;
1825 canon_modify_mem_list = 0;
1828 /* Reset tables used to keep track of what's still available [since the
1829 start of the block]. */
1831 static void
1832 reset_opr_set_tables (void)
1834 /* Maintain a bitmap of which regs have been set since beginning of
1835 the block. */
1836 CLEAR_REG_SET (reg_set_bitmap);
1838 /* Also keep a record of the last instruction to modify memory.
1839 For now this is very trivial, we only record whether any memory
1840 location has been modified. */
1841 clear_modify_mem_tables ();
1844 /* Return nonzero if the operands of X are not set before INSN in
1845 INSN's basic block. */
1847 static int
1848 oprs_not_set_p (const_rtx x, const_rtx insn)
1850 int i, j;
1851 enum rtx_code code;
1852 const char *fmt;
1854 if (x == 0)
1855 return 1;
1857 code = GET_CODE (x);
1858 switch (code)
1860 case PC:
1861 case CC0:
1862 case CONST:
1863 case CONST_INT:
1864 case CONST_DOUBLE:
1865 case CONST_FIXED:
1866 case CONST_VECTOR:
1867 case SYMBOL_REF:
1868 case LABEL_REF:
1869 case ADDR_VEC:
1870 case ADDR_DIFF_VEC:
1871 return 1;
1873 case MEM:
1874 if (load_killed_in_block_p (BLOCK_FOR_INSN (insn),
1875 DF_INSN_LUID (insn), x, 0))
1876 return 0;
1877 else
1878 return oprs_not_set_p (XEXP (x, 0), insn);
1880 case REG:
1881 return ! REGNO_REG_SET_P (reg_set_bitmap, REGNO (x));
1883 default:
1884 break;
1887 for (i = GET_RTX_LENGTH (code) - 1, fmt = GET_RTX_FORMAT (code); i >= 0; i--)
1889 if (fmt[i] == 'e')
1891 /* If we are about to do the last recursive call
1892 needed at this level, change it into iteration.
1893 This function is called enough to be worth it. */
1894 if (i == 0)
1895 return oprs_not_set_p (XEXP (x, i), insn);
1897 if (! oprs_not_set_p (XEXP (x, i), insn))
1898 return 0;
1900 else if (fmt[i] == 'E')
1901 for (j = 0; j < XVECLEN (x, i); j++)
1902 if (! oprs_not_set_p (XVECEXP (x, i, j), insn))
1903 return 0;
1906 return 1;
1909 /* Mark things set by a CALL. */
1911 static void
1912 mark_call (rtx insn)
1914 if (! RTL_CONST_OR_PURE_CALL_P (insn))
1915 record_last_mem_set_info (insn);
1918 /* Mark things set by a SET. */
1920 static void
1921 mark_set (rtx pat, rtx insn)
1923 rtx dest = SET_DEST (pat);
1925 while (GET_CODE (dest) == SUBREG
1926 || GET_CODE (dest) == ZERO_EXTRACT
1927 || GET_CODE (dest) == STRICT_LOW_PART)
1928 dest = XEXP (dest, 0);
1930 if (REG_P (dest))
1931 SET_REGNO_REG_SET (reg_set_bitmap, REGNO (dest));
1932 else if (MEM_P (dest))
1933 record_last_mem_set_info (insn);
1935 if (GET_CODE (SET_SRC (pat)) == CALL)
1936 mark_call (insn);
1939 /* Record things set by a CLOBBER. */
1941 static void
1942 mark_clobber (rtx pat, rtx insn)
1944 rtx clob = XEXP (pat, 0);
1946 while (GET_CODE (clob) == SUBREG || GET_CODE (clob) == STRICT_LOW_PART)
1947 clob = XEXP (clob, 0);
1949 if (REG_P (clob))
1950 SET_REGNO_REG_SET (reg_set_bitmap, REGNO (clob));
1951 else
1952 record_last_mem_set_info (insn);
1955 /* Record things set by INSN.
1956 This data is used by oprs_not_set_p. */
1958 static void
1959 mark_oprs_set (rtx insn)
1961 rtx pat = PATTERN (insn);
1962 int i;
1964 if (GET_CODE (pat) == SET)
1965 mark_set (pat, insn);
1966 else if (GET_CODE (pat) == PARALLEL)
1967 for (i = 0; i < XVECLEN (pat, 0); i++)
1969 rtx x = XVECEXP (pat, 0, i);
1971 if (GET_CODE (x) == SET)
1972 mark_set (x, insn);
1973 else if (GET_CODE (x) == CLOBBER)
1974 mark_clobber (x, insn);
1975 else if (GET_CODE (x) == CALL)
1976 mark_call (insn);
1979 else if (GET_CODE (pat) == CLOBBER)
1980 mark_clobber (pat, insn);
1981 else if (GET_CODE (pat) == CALL)
1982 mark_call (insn);
1986 /* Compute copy/constant propagation working variables. */
1988 /* Local properties of assignments. */
1989 static sbitmap *cprop_pavloc;
1990 static sbitmap *cprop_absaltered;
1992 /* Global properties of assignments (computed from the local properties). */
1993 static sbitmap *cprop_avin;
1994 static sbitmap *cprop_avout;
1996 /* Allocate vars used for copy/const propagation. N_BLOCKS is the number of
1997 basic blocks. N_SETS is the number of sets. */
1999 static void
2000 alloc_cprop_mem (int n_blocks, int n_sets)
2002 cprop_pavloc = sbitmap_vector_alloc (n_blocks, n_sets);
2003 cprop_absaltered = sbitmap_vector_alloc (n_blocks, n_sets);
2005 cprop_avin = sbitmap_vector_alloc (n_blocks, n_sets);
2006 cprop_avout = sbitmap_vector_alloc (n_blocks, n_sets);
2009 /* Free vars used by copy/const propagation. */
2011 static void
2012 free_cprop_mem (void)
2014 sbitmap_vector_free (cprop_pavloc);
2015 sbitmap_vector_free (cprop_absaltered);
2016 sbitmap_vector_free (cprop_avin);
2017 sbitmap_vector_free (cprop_avout);
2020 /* For each block, compute whether X is transparent. X is either an
2021 expression or an assignment [though we don't care which, for this context
2022 an assignment is treated as an expression]. For each block where an
2023 element of X is modified, set (SET_P == 1) or reset (SET_P == 0) the INDX
2024 bit in BMAP. */
2026 static void
2027 compute_transp (const_rtx x, int indx, sbitmap *bmap, int set_p)
2029 int i, j;
2030 enum rtx_code code;
2031 const char *fmt;
2033 /* repeat is used to turn tail-recursion into iteration since GCC
2034 can't do it when there's no return value. */
2035 repeat:
2037 if (x == 0)
2038 return;
2040 code = GET_CODE (x);
2041 switch (code)
2043 case REG:
2044 if (set_p)
2046 df_ref def;
2047 for (def = DF_REG_DEF_CHAIN (REGNO (x));
2048 def;
2049 def = DF_REF_NEXT_REG (def))
2050 SET_BIT (bmap[DF_REF_BB (def)->index], indx);
2052 else
2054 df_ref def;
2055 for (def = DF_REG_DEF_CHAIN (REGNO (x));
2056 def;
2057 def = DF_REF_NEXT_REG (def))
2058 RESET_BIT (bmap[DF_REF_BB (def)->index], indx);
2061 return;
2063 case MEM:
2064 if (! MEM_READONLY_P (x))
2066 bitmap_iterator bi;
2067 unsigned bb_index;
2069 /* First handle all the blocks with calls. We don't need to
2070 do any list walking for them. */
2071 EXECUTE_IF_SET_IN_BITMAP (blocks_with_calls, 0, bb_index, bi)
2073 if (set_p)
2074 SET_BIT (bmap[bb_index], indx);
2075 else
2076 RESET_BIT (bmap[bb_index], indx);
2079 /* Now iterate over the blocks which have memory modifications
2080 but which do not have any calls. */
2081 EXECUTE_IF_AND_COMPL_IN_BITMAP (modify_mem_list_set,
2082 blocks_with_calls,
2083 0, bb_index, bi)
2085 rtx list_entry = canon_modify_mem_list[bb_index];
2087 while (list_entry)
2089 rtx dest, dest_addr;
2091 /* LIST_ENTRY must be an INSN of some kind that sets memory.
2092 Examine each hunk of memory that is modified. */
2094 dest = XEXP (list_entry, 0);
2095 list_entry = XEXP (list_entry, 1);
2096 dest_addr = XEXP (list_entry, 0);
2098 if (canon_true_dependence (dest, GET_MODE (dest), dest_addr,
2099 x, NULL_RTX, rtx_addr_varies_p))
2101 if (set_p)
2102 SET_BIT (bmap[bb_index], indx);
2103 else
2104 RESET_BIT (bmap[bb_index], indx);
2105 break;
2107 list_entry = XEXP (list_entry, 1);
2112 x = XEXP (x, 0);
2113 goto repeat;
2115 case PC:
2116 case CC0: /*FIXME*/
2117 case CONST:
2118 case CONST_INT:
2119 case CONST_DOUBLE:
2120 case CONST_FIXED:
2121 case CONST_VECTOR:
2122 case SYMBOL_REF:
2123 case LABEL_REF:
2124 case ADDR_VEC:
2125 case ADDR_DIFF_VEC:
2126 return;
2128 default:
2129 break;
2132 for (i = GET_RTX_LENGTH (code) - 1, fmt = GET_RTX_FORMAT (code); i >= 0; i--)
2134 if (fmt[i] == 'e')
2136 /* If we are about to do the last recursive call
2137 needed at this level, change it into iteration.
2138 This function is called enough to be worth it. */
2139 if (i == 0)
2141 x = XEXP (x, i);
2142 goto repeat;
2145 compute_transp (XEXP (x, i), indx, bmap, set_p);
2147 else if (fmt[i] == 'E')
2148 for (j = 0; j < XVECLEN (x, i); j++)
2149 compute_transp (XVECEXP (x, i, j), indx, bmap, set_p);
2153 /* Top level routine to do the dataflow analysis needed by copy/const
2154 propagation. */
2156 static void
2157 compute_cprop_data (void)
2159 compute_local_properties (cprop_absaltered, cprop_pavloc, NULL, &set_hash_table);
2160 compute_available (cprop_pavloc, cprop_absaltered,
2161 cprop_avout, cprop_avin);
2164 /* Copy/constant propagation. */
2166 /* Maximum number of register uses in an insn that we handle. */
2167 #define MAX_USES 8
2169 /* Table of uses found in an insn.
2170 Allocated statically to avoid alloc/free complexity and overhead. */
2171 static struct reg_use reg_use_table[MAX_USES];
2173 /* Index into `reg_use_table' while building it. */
2174 static int reg_use_count;
2176 /* Set up a list of register numbers used in INSN. The found uses are stored
2177 in `reg_use_table'. `reg_use_count' is initialized to zero before entry,
2178 and contains the number of uses in the table upon exit.
2180 ??? If a register appears multiple times we will record it multiple times.
2181 This doesn't hurt anything but it will slow things down. */
2183 static void
2184 find_used_regs (rtx *xptr, void *data ATTRIBUTE_UNUSED)
2186 int i, j;
2187 enum rtx_code code;
2188 const char *fmt;
2189 rtx x = *xptr;
2191 /* repeat is used to turn tail-recursion into iteration since GCC
2192 can't do it when there's no return value. */
2193 repeat:
2194 if (x == 0)
2195 return;
2197 code = GET_CODE (x);
2198 if (REG_P (x))
2200 if (reg_use_count == MAX_USES)
2201 return;
2203 reg_use_table[reg_use_count].reg_rtx = x;
2204 reg_use_count++;
2207 /* Recursively scan the operands of this expression. */
2209 for (i = GET_RTX_LENGTH (code) - 1, fmt = GET_RTX_FORMAT (code); i >= 0; i--)
2211 if (fmt[i] == 'e')
2213 /* If we are about to do the last recursive call
2214 needed at this level, change it into iteration.
2215 This function is called enough to be worth it. */
2216 if (i == 0)
2218 x = XEXP (x, 0);
2219 goto repeat;
2222 find_used_regs (&XEXP (x, i), data);
2224 else if (fmt[i] == 'E')
2225 for (j = 0; j < XVECLEN (x, i); j++)
2226 find_used_regs (&XVECEXP (x, i, j), data);
2230 /* Try to replace all non-SET_DEST occurrences of FROM in INSN with TO.
2231 Returns nonzero is successful. */
2233 static int
2234 try_replace_reg (rtx from, rtx to, rtx insn)
2236 rtx note = find_reg_equal_equiv_note (insn);
2237 rtx src = 0;
2238 int success = 0;
2239 rtx set = single_set (insn);
2241 /* Usually we substitute easy stuff, so we won't copy everything.
2242 We however need to take care to not duplicate non-trivial CONST
2243 expressions. */
2244 to = copy_rtx (to);
2246 validate_replace_src_group (from, to, insn);
2247 if (num_changes_pending () && apply_change_group ())
2248 success = 1;
2250 /* Try to simplify SET_SRC if we have substituted a constant. */
2251 if (success && set && CONSTANT_P (to))
2253 src = simplify_rtx (SET_SRC (set));
2255 if (src)
2256 validate_change (insn, &SET_SRC (set), src, 0);
2259 /* If there is already a REG_EQUAL note, update the expression in it
2260 with our replacement. */
2261 if (note != 0 && REG_NOTE_KIND (note) == REG_EQUAL)
2262 set_unique_reg_note (insn, REG_EQUAL,
2263 simplify_replace_rtx (XEXP (note, 0), from, to));
2264 if (!success && set && reg_mentioned_p (from, SET_SRC (set)))
2266 /* If above failed and this is a single set, try to simplify the source of
2267 the set given our substitution. We could perhaps try this for multiple
2268 SETs, but it probably won't buy us anything. */
2269 src = simplify_replace_rtx (SET_SRC (set), from, to);
2271 if (!rtx_equal_p (src, SET_SRC (set))
2272 && validate_change (insn, &SET_SRC (set), src, 0))
2273 success = 1;
2275 /* If we've failed to do replacement, have a single SET, don't already
2276 have a note, and have no special SET, add a REG_EQUAL note to not
2277 lose information. */
2278 if (!success && note == 0 && set != 0
2279 && GET_CODE (SET_DEST (set)) != ZERO_EXTRACT
2280 && GET_CODE (SET_DEST (set)) != STRICT_LOW_PART)
2281 note = set_unique_reg_note (insn, REG_EQUAL, copy_rtx (src));
2284 /* REG_EQUAL may get simplified into register.
2285 We don't allow that. Remove that note. This code ought
2286 not to happen, because previous code ought to synthesize
2287 reg-reg move, but be on the safe side. */
2288 if (note && REG_NOTE_KIND (note) == REG_EQUAL && REG_P (XEXP (note, 0)))
2289 remove_note (insn, note);
2291 return success;
2294 /* Find a set of REGNOs that are available on entry to INSN's block. Returns
2295 NULL no such set is found. */
2297 static struct expr *
2298 find_avail_set (int regno, rtx insn)
2300 /* SET1 contains the last set found that can be returned to the caller for
2301 use in a substitution. */
2302 struct expr *set1 = 0;
2304 /* Loops are not possible here. To get a loop we would need two sets
2305 available at the start of the block containing INSN. i.e. we would
2306 need two sets like this available at the start of the block:
2308 (set (reg X) (reg Y))
2309 (set (reg Y) (reg X))
2311 This can not happen since the set of (reg Y) would have killed the
2312 set of (reg X) making it unavailable at the start of this block. */
2313 while (1)
2315 rtx src;
2316 struct expr *set = lookup_set (regno, &set_hash_table);
2318 /* Find a set that is available at the start of the block
2319 which contains INSN. */
2320 while (set)
2322 if (TEST_BIT (cprop_avin[BLOCK_FOR_INSN (insn)->index],
2323 set->bitmap_index))
2324 break;
2325 set = next_set (regno, set);
2328 /* If no available set was found we've reached the end of the
2329 (possibly empty) copy chain. */
2330 if (set == 0)
2331 break;
2333 gcc_assert (GET_CODE (set->expr) == SET);
2335 src = SET_SRC (set->expr);
2337 /* We know the set is available.
2338 Now check that SRC is ANTLOC (i.e. none of the source operands
2339 have changed since the start of the block).
2341 If the source operand changed, we may still use it for the next
2342 iteration of this loop, but we may not use it for substitutions. */
2344 if (gcse_constant_p (src) || oprs_not_set_p (src, insn))
2345 set1 = set;
2347 /* If the source of the set is anything except a register, then
2348 we have reached the end of the copy chain. */
2349 if (! REG_P (src))
2350 break;
2352 /* Follow the copy chain, i.e. start another iteration of the loop
2353 and see if we have an available copy into SRC. */
2354 regno = REGNO (src);
2357 /* SET1 holds the last set that was available and anticipatable at
2358 INSN. */
2359 return set1;
2362 /* Subroutine of cprop_insn that tries to propagate constants into
2363 JUMP_INSNS. JUMP must be a conditional jump. If SETCC is non-NULL
2364 it is the instruction that immediately precedes JUMP, and must be a
2365 single SET of a register. FROM is what we will try to replace,
2366 SRC is the constant we will try to substitute for it. Returns nonzero
2367 if a change was made. */
2369 static int
2370 cprop_jump (basic_block bb, rtx setcc, rtx jump, rtx from, rtx src)
2372 rtx new_rtx, set_src, note_src;
2373 rtx set = pc_set (jump);
2374 rtx note = find_reg_equal_equiv_note (jump);
2376 if (note)
2378 note_src = XEXP (note, 0);
2379 if (GET_CODE (note_src) == EXPR_LIST)
2380 note_src = NULL_RTX;
2382 else note_src = NULL_RTX;
2384 /* Prefer REG_EQUAL notes except those containing EXPR_LISTs. */
2385 set_src = note_src ? note_src : SET_SRC (set);
2387 /* First substitute the SETCC condition into the JUMP instruction,
2388 then substitute that given values into this expanded JUMP. */
2389 if (setcc != NULL_RTX
2390 && !modified_between_p (from, setcc, jump)
2391 && !modified_between_p (src, setcc, jump))
2393 rtx setcc_src;
2394 rtx setcc_set = single_set (setcc);
2395 rtx setcc_note = find_reg_equal_equiv_note (setcc);
2396 setcc_src = (setcc_note && GET_CODE (XEXP (setcc_note, 0)) != EXPR_LIST)
2397 ? XEXP (setcc_note, 0) : SET_SRC (setcc_set);
2398 set_src = simplify_replace_rtx (set_src, SET_DEST (setcc_set),
2399 setcc_src);
2401 else
2402 setcc = NULL_RTX;
2404 new_rtx = simplify_replace_rtx (set_src, from, src);
2406 /* If no simplification can be made, then try the next register. */
2407 if (rtx_equal_p (new_rtx, SET_SRC (set)))
2408 return 0;
2410 /* If this is now a no-op delete it, otherwise this must be a valid insn. */
2411 if (new_rtx == pc_rtx)
2412 delete_insn (jump);
2413 else
2415 /* Ensure the value computed inside the jump insn to be equivalent
2416 to one computed by setcc. */
2417 if (setcc && modified_in_p (new_rtx, setcc))
2418 return 0;
2419 if (! validate_unshare_change (jump, &SET_SRC (set), new_rtx, 0))
2421 /* When (some) constants are not valid in a comparison, and there
2422 are two registers to be replaced by constants before the entire
2423 comparison can be folded into a constant, we need to keep
2424 intermediate information in REG_EQUAL notes. For targets with
2425 separate compare insns, such notes are added by try_replace_reg.
2426 When we have a combined compare-and-branch instruction, however,
2427 we need to attach a note to the branch itself to make this
2428 optimization work. */
2430 if (!rtx_equal_p (new_rtx, note_src))
2431 set_unique_reg_note (jump, REG_EQUAL, copy_rtx (new_rtx));
2432 return 0;
2435 /* Remove REG_EQUAL note after simplification. */
2436 if (note_src)
2437 remove_note (jump, note);
2440 #ifdef HAVE_cc0
2441 /* Delete the cc0 setter. */
2442 if (setcc != NULL && CC0_P (SET_DEST (single_set (setcc))))
2443 delete_insn (setcc);
2444 #endif
2446 global_const_prop_count++;
2447 if (dump_file != NULL)
2449 fprintf (dump_file,
2450 "GLOBAL CONST-PROP: Replacing reg %d in jump_insn %d with constant ",
2451 REGNO (from), INSN_UID (jump));
2452 print_rtl (dump_file, src);
2453 fprintf (dump_file, "\n");
2455 purge_dead_edges (bb);
2457 /* If a conditional jump has been changed into unconditional jump, remove
2458 the jump and make the edge fallthru - this is always called in
2459 cfglayout mode. */
2460 if (new_rtx != pc_rtx && simplejump_p (jump))
2462 edge e;
2463 edge_iterator ei;
2465 for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); ei_next (&ei))
2466 if (e->dest != EXIT_BLOCK_PTR
2467 && BB_HEAD (e->dest) == JUMP_LABEL (jump))
2469 e->flags |= EDGE_FALLTHRU;
2470 break;
2472 delete_insn (jump);
2475 return 1;
2478 static bool
2479 constprop_register (rtx insn, rtx from, rtx to)
2481 rtx sset;
2483 /* Check for reg or cc0 setting instructions followed by
2484 conditional branch instructions first. */
2485 if ((sset = single_set (insn)) != NULL
2486 && NEXT_INSN (insn)
2487 && any_condjump_p (NEXT_INSN (insn)) && onlyjump_p (NEXT_INSN (insn)))
2489 rtx dest = SET_DEST (sset);
2490 if ((REG_P (dest) || CC0_P (dest))
2491 && cprop_jump (BLOCK_FOR_INSN (insn), insn, NEXT_INSN (insn), from, to))
2492 return 1;
2495 /* Handle normal insns next. */
2496 if (NONJUMP_INSN_P (insn)
2497 && try_replace_reg (from, to, insn))
2498 return 1;
2500 /* Try to propagate a CONST_INT into a conditional jump.
2501 We're pretty specific about what we will handle in this
2502 code, we can extend this as necessary over time.
2504 Right now the insn in question must look like
2505 (set (pc) (if_then_else ...)) */
2506 else if (any_condjump_p (insn) && onlyjump_p (insn))
2507 return cprop_jump (BLOCK_FOR_INSN (insn), NULL, insn, from, to);
2508 return 0;
2511 /* Perform constant and copy propagation on INSN.
2512 The result is nonzero if a change was made. */
2514 static int
2515 cprop_insn (rtx insn)
2517 struct reg_use *reg_used;
2518 int changed = 0;
2519 rtx note;
2521 if (!INSN_P (insn))
2522 return 0;
2524 reg_use_count = 0;
2525 note_uses (&PATTERN (insn), find_used_regs, NULL);
2527 note = find_reg_equal_equiv_note (insn);
2529 /* We may win even when propagating constants into notes. */
2530 if (note)
2531 find_used_regs (&XEXP (note, 0), NULL);
2533 for (reg_used = &reg_use_table[0]; reg_use_count > 0;
2534 reg_used++, reg_use_count--)
2536 unsigned int regno = REGNO (reg_used->reg_rtx);
2537 rtx pat, src;
2538 struct expr *set;
2540 /* If the register has already been set in this block, there's
2541 nothing we can do. */
2542 if (! oprs_not_set_p (reg_used->reg_rtx, insn))
2543 continue;
2545 /* Find an assignment that sets reg_used and is available
2546 at the start of the block. */
2547 set = find_avail_set (regno, insn);
2548 if (! set)
2549 continue;
2551 pat = set->expr;
2552 /* ??? We might be able to handle PARALLELs. Later. */
2553 gcc_assert (GET_CODE (pat) == SET);
2555 src = SET_SRC (pat);
2557 /* Constant propagation. */
2558 if (gcse_constant_p (src))
2560 if (constprop_register (insn, reg_used->reg_rtx, src))
2562 changed = 1;
2563 global_const_prop_count++;
2564 if (dump_file != NULL)
2566 fprintf (dump_file, "GLOBAL CONST-PROP: Replacing reg %d in ", regno);
2567 fprintf (dump_file, "insn %d with constant ", INSN_UID (insn));
2568 print_rtl (dump_file, src);
2569 fprintf (dump_file, "\n");
2571 if (INSN_DELETED_P (insn))
2572 return 1;
2575 else if (REG_P (src)
2576 && REGNO (src) >= FIRST_PSEUDO_REGISTER
2577 && REGNO (src) != regno)
2579 if (try_replace_reg (reg_used->reg_rtx, src, insn))
2581 changed = 1;
2582 global_copy_prop_count++;
2583 if (dump_file != NULL)
2585 fprintf (dump_file, "GLOBAL COPY-PROP: Replacing reg %d in insn %d",
2586 regno, INSN_UID (insn));
2587 fprintf (dump_file, " with reg %d\n", REGNO (src));
2590 /* The original insn setting reg_used may or may not now be
2591 deletable. We leave the deletion to flow. */
2592 /* FIXME: If it turns out that the insn isn't deletable,
2593 then we may have unnecessarily extended register lifetimes
2594 and made things worse. */
2599 if (changed && DEBUG_INSN_P (insn))
2600 return 0;
2602 return changed;
2605 /* Like find_used_regs, but avoid recording uses that appear in
2606 input-output contexts such as zero_extract or pre_dec. This
2607 restricts the cases we consider to those for which local cprop
2608 can legitimately make replacements. */
2610 static void
2611 local_cprop_find_used_regs (rtx *xptr, void *data)
2613 rtx x = *xptr;
2615 if (x == 0)
2616 return;
2618 switch (GET_CODE (x))
2620 case ZERO_EXTRACT:
2621 case SIGN_EXTRACT:
2622 case STRICT_LOW_PART:
2623 return;
2625 case PRE_DEC:
2626 case PRE_INC:
2627 case POST_DEC:
2628 case POST_INC:
2629 case PRE_MODIFY:
2630 case POST_MODIFY:
2631 /* Can only legitimately appear this early in the context of
2632 stack pushes for function arguments, but handle all of the
2633 codes nonetheless. */
2634 return;
2636 case SUBREG:
2637 /* Setting a subreg of a register larger than word_mode leaves
2638 the non-written words unchanged. */
2639 if (GET_MODE_BITSIZE (GET_MODE (SUBREG_REG (x))) > BITS_PER_WORD)
2640 return;
2641 break;
2643 default:
2644 break;
2647 find_used_regs (xptr, data);
2650 /* Try to perform local const/copy propagation on X in INSN. */
2652 static bool
2653 do_local_cprop (rtx x, rtx insn)
2655 rtx newreg = NULL, newcnst = NULL;
2657 /* Rule out USE instructions and ASM statements as we don't want to
2658 change the hard registers mentioned. */
2659 if (REG_P (x)
2660 && (REGNO (x) >= FIRST_PSEUDO_REGISTER
2661 || (GET_CODE (PATTERN (insn)) != USE
2662 && asm_noperands (PATTERN (insn)) < 0)))
2664 cselib_val *val = cselib_lookup (x, GET_MODE (x), 0);
2665 struct elt_loc_list *l;
2667 if (!val)
2668 return false;
2669 for (l = val->locs; l; l = l->next)
2671 rtx this_rtx = l->loc;
2672 rtx note;
2674 if (gcse_constant_p (this_rtx))
2675 newcnst = this_rtx;
2676 if (REG_P (this_rtx) && REGNO (this_rtx) >= FIRST_PSEUDO_REGISTER
2677 /* Don't copy propagate if it has attached REG_EQUIV note.
2678 At this point this only function parameters should have
2679 REG_EQUIV notes and if the argument slot is used somewhere
2680 explicitly, it means address of parameter has been taken,
2681 so we should not extend the lifetime of the pseudo. */
2682 && (!(note = find_reg_note (l->setting_insn, REG_EQUIV, NULL_RTX))
2683 || ! MEM_P (XEXP (note, 0))))
2684 newreg = this_rtx;
2686 if (newcnst && constprop_register (insn, x, newcnst))
2688 if (dump_file != NULL)
2690 fprintf (dump_file, "LOCAL CONST-PROP: Replacing reg %d in ",
2691 REGNO (x));
2692 fprintf (dump_file, "insn %d with constant ",
2693 INSN_UID (insn));
2694 print_rtl (dump_file, newcnst);
2695 fprintf (dump_file, "\n");
2697 local_const_prop_count++;
2698 return true;
2700 else if (newreg && newreg != x && try_replace_reg (x, newreg, insn))
2702 if (dump_file != NULL)
2704 fprintf (dump_file,
2705 "LOCAL COPY-PROP: Replacing reg %d in insn %d",
2706 REGNO (x), INSN_UID (insn));
2707 fprintf (dump_file, " with reg %d\n", REGNO (newreg));
2709 local_copy_prop_count++;
2710 return true;
2713 return false;
2716 /* Do local const/copy propagation (i.e. within each basic block). */
2718 static int
2719 local_cprop_pass (void)
2721 basic_block bb;
2722 rtx insn;
2723 struct reg_use *reg_used;
2724 bool changed = false;
2726 cselib_init (0);
2727 FOR_EACH_BB (bb)
2729 FOR_BB_INSNS (bb, insn)
2731 if (INSN_P (insn))
2733 rtx note = find_reg_equal_equiv_note (insn);
2736 reg_use_count = 0;
2737 note_uses (&PATTERN (insn), local_cprop_find_used_regs,
2738 NULL);
2739 if (note)
2740 local_cprop_find_used_regs (&XEXP (note, 0), NULL);
2742 for (reg_used = &reg_use_table[0]; reg_use_count > 0;
2743 reg_used++, reg_use_count--)
2745 if (do_local_cprop (reg_used->reg_rtx, insn))
2747 changed = true;
2748 break;
2751 if (INSN_DELETED_P (insn))
2752 break;
2754 while (reg_use_count);
2756 cselib_process_insn (insn);
2759 /* Forget everything at the end of a basic block. */
2760 cselib_clear_table ();
2763 cselib_finish ();
2765 return changed;
2768 /* Similar to get_condition, only the resulting condition must be
2769 valid at JUMP, instead of at EARLIEST.
2771 This differs from noce_get_condition in ifcvt.c in that we prefer not to
2772 settle for the condition variable in the jump instruction being integral.
2773 We prefer to be able to record the value of a user variable, rather than
2774 the value of a temporary used in a condition. This could be solved by
2775 recording the value of *every* register scanned by canonicalize_condition,
2776 but this would require some code reorganization. */
2779 fis_get_condition (rtx jump)
2781 return get_condition (jump, NULL, false, true);
2784 /* Check the comparison COND to see if we can safely form an implicit set from
2785 it. COND is either an EQ or NE comparison. */
2787 static bool
2788 implicit_set_cond_p (const_rtx cond)
2790 const enum machine_mode mode = GET_MODE (XEXP (cond, 0));
2791 const_rtx cst = XEXP (cond, 1);
2793 /* We can't perform this optimization if either operand might be or might
2794 contain a signed zero. */
2795 if (HONOR_SIGNED_ZEROS (mode))
2797 /* It is sufficient to check if CST is or contains a zero. We must
2798 handle float, complex, and vector. If any subpart is a zero, then
2799 the optimization can't be performed. */
2800 /* ??? The complex and vector checks are not implemented yet. We just
2801 always return zero for them. */
2802 if (GET_CODE (cst) == CONST_DOUBLE)
2804 REAL_VALUE_TYPE d;
2805 REAL_VALUE_FROM_CONST_DOUBLE (d, cst);
2806 if (REAL_VALUES_EQUAL (d, dconst0))
2807 return 0;
2809 else
2810 return 0;
2813 return gcse_constant_p (cst);
2816 /* Find the implicit sets of a function. An "implicit set" is a constraint
2817 on the value of a variable, implied by a conditional jump. For example,
2818 following "if (x == 2)", the then branch may be optimized as though the
2819 conditional performed an "explicit set", in this example, "x = 2". This
2820 function records the set patterns that are implicit at the start of each
2821 basic block.
2823 FIXME: This would be more effective if critical edges are pre-split. As
2824 it is now, we can't record implicit sets for blocks that have
2825 critical successor edges. This results in missed optimizations
2826 and in more (unnecessary) work in cfgcleanup.c:thread_jump(). */
2828 static void
2829 find_implicit_sets (void)
2831 basic_block bb, dest;
2832 unsigned int count;
2833 rtx cond, new_rtx;
2835 count = 0;
2836 FOR_EACH_BB (bb)
2837 /* Check for more than one successor. */
2838 if (EDGE_COUNT (bb->succs) > 1)
2840 cond = fis_get_condition (BB_END (bb));
2842 if (cond
2843 && (GET_CODE (cond) == EQ || GET_CODE (cond) == NE)
2844 && REG_P (XEXP (cond, 0))
2845 && REGNO (XEXP (cond, 0)) >= FIRST_PSEUDO_REGISTER
2846 && implicit_set_cond_p (cond))
2848 dest = GET_CODE (cond) == EQ ? BRANCH_EDGE (bb)->dest
2849 : FALLTHRU_EDGE (bb)->dest;
2851 if (dest
2852 /* Record nothing for a critical edge. */
2853 && single_pred_p (dest)
2854 && dest != EXIT_BLOCK_PTR)
2856 new_rtx = gen_rtx_SET (VOIDmode, XEXP (cond, 0),
2857 XEXP (cond, 1));
2858 implicit_sets[dest->index] = new_rtx;
2859 if (dump_file)
2861 fprintf(dump_file, "Implicit set of reg %d in ",
2862 REGNO (XEXP (cond, 0)));
2863 fprintf(dump_file, "basic block %d\n", dest->index);
2865 count++;
2870 if (dump_file)
2871 fprintf (dump_file, "Found %d implicit sets\n", count);
2874 /* Bypass conditional jumps. */
2876 /* The value of last_basic_block at the beginning of the jump_bypass
2877 pass. The use of redirect_edge_and_branch_force may introduce new
2878 basic blocks, but the data flow analysis is only valid for basic
2879 block indices less than bypass_last_basic_block. */
2881 static int bypass_last_basic_block;
2883 /* Find a set of REGNO to a constant that is available at the end of basic
2884 block BB. Returns NULL if no such set is found. Based heavily upon
2885 find_avail_set. */
2887 static struct expr *
2888 find_bypass_set (int regno, int bb)
2890 struct expr *result = 0;
2892 for (;;)
2894 rtx src;
2895 struct expr *set = lookup_set (regno, &set_hash_table);
2897 while (set)
2899 if (TEST_BIT (cprop_avout[bb], set->bitmap_index))
2900 break;
2901 set = next_set (regno, set);
2904 if (set == 0)
2905 break;
2907 gcc_assert (GET_CODE (set->expr) == SET);
2909 src = SET_SRC (set->expr);
2910 if (gcse_constant_p (src))
2911 result = set;
2913 if (! REG_P (src))
2914 break;
2916 regno = REGNO (src);
2918 return result;
2922 /* Subroutine of bypass_block that checks whether a pseudo is killed by
2923 any of the instructions inserted on an edge. Jump bypassing places
2924 condition code setters on CFG edges using insert_insn_on_edge. This
2925 function is required to check that our data flow analysis is still
2926 valid prior to commit_edge_insertions. */
2928 static bool
2929 reg_killed_on_edge (const_rtx reg, const_edge e)
2931 rtx insn;
2933 for (insn = e->insns.r; insn; insn = NEXT_INSN (insn))
2934 if (INSN_P (insn) && reg_set_p (reg, insn))
2935 return true;
2937 return false;
2940 /* Subroutine of bypass_conditional_jumps that attempts to bypass the given
2941 basic block BB which has more than one predecessor. If not NULL, SETCC
2942 is the first instruction of BB, which is immediately followed by JUMP_INSN
2943 JUMP. Otherwise, SETCC is NULL, and JUMP is the first insn of BB.
2944 Returns nonzero if a change was made.
2946 During the jump bypassing pass, we may place copies of SETCC instructions
2947 on CFG edges. The following routine must be careful to pay attention to
2948 these inserted insns when performing its transformations. */
2950 static int
2951 bypass_block (basic_block bb, rtx setcc, rtx jump)
2953 rtx insn, note;
2954 edge e, edest;
2955 int i, change;
2956 int may_be_loop_header;
2957 unsigned removed_p;
2958 edge_iterator ei;
2960 insn = (setcc != NULL) ? setcc : jump;
2962 /* Determine set of register uses in INSN. */
2963 reg_use_count = 0;
2964 note_uses (&PATTERN (insn), find_used_regs, NULL);
2965 note = find_reg_equal_equiv_note (insn);
2966 if (note)
2967 find_used_regs (&XEXP (note, 0), NULL);
2969 may_be_loop_header = false;
2970 FOR_EACH_EDGE (e, ei, bb->preds)
2971 if (e->flags & EDGE_DFS_BACK)
2973 may_be_loop_header = true;
2974 break;
2977 change = 0;
2978 for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
2980 removed_p = 0;
2982 if (e->flags & EDGE_COMPLEX)
2984 ei_next (&ei);
2985 continue;
2988 /* We can't redirect edges from new basic blocks. */
2989 if (e->src->index >= bypass_last_basic_block)
2991 ei_next (&ei);
2992 continue;
2995 /* The irreducible loops created by redirecting of edges entering the
2996 loop from outside would decrease effectiveness of some of the following
2997 optimizations, so prevent this. */
2998 if (may_be_loop_header
2999 && !(e->flags & EDGE_DFS_BACK))
3001 ei_next (&ei);
3002 continue;
3005 for (i = 0; i < reg_use_count; i++)
3007 struct reg_use *reg_used = &reg_use_table[i];
3008 unsigned int regno = REGNO (reg_used->reg_rtx);
3009 basic_block dest, old_dest;
3010 struct expr *set;
3011 rtx src, new_rtx;
3013 set = find_bypass_set (regno, e->src->index);
3015 if (! set)
3016 continue;
3018 /* Check the data flow is valid after edge insertions. */
3019 if (e->insns.r && reg_killed_on_edge (reg_used->reg_rtx, e))
3020 continue;
3022 src = SET_SRC (pc_set (jump));
3024 if (setcc != NULL)
3025 src = simplify_replace_rtx (src,
3026 SET_DEST (PATTERN (setcc)),
3027 SET_SRC (PATTERN (setcc)));
3029 new_rtx = simplify_replace_rtx (src, reg_used->reg_rtx,
3030 SET_SRC (set->expr));
3032 /* Jump bypassing may have already placed instructions on
3033 edges of the CFG. We can't bypass an outgoing edge that
3034 has instructions associated with it, as these insns won't
3035 get executed if the incoming edge is redirected. */
3037 if (new_rtx == pc_rtx)
3039 edest = FALLTHRU_EDGE (bb);
3040 dest = edest->insns.r ? NULL : edest->dest;
3042 else if (GET_CODE (new_rtx) == LABEL_REF)
3044 dest = BLOCK_FOR_INSN (XEXP (new_rtx, 0));
3045 /* Don't bypass edges containing instructions. */
3046 edest = find_edge (bb, dest);
3047 if (edest && edest->insns.r)
3048 dest = NULL;
3050 else
3051 dest = NULL;
3053 /* Avoid unification of the edge with other edges from original
3054 branch. We would end up emitting the instruction on "both"
3055 edges. */
3057 if (dest && setcc && !CC0_P (SET_DEST (PATTERN (setcc)))
3058 && find_edge (e->src, dest))
3059 dest = NULL;
3061 old_dest = e->dest;
3062 if (dest != NULL
3063 && dest != old_dest
3064 && dest != EXIT_BLOCK_PTR)
3066 redirect_edge_and_branch_force (e, dest);
3068 /* Copy the register setter to the redirected edge.
3069 Don't copy CC0 setters, as CC0 is dead after jump. */
3070 if (setcc)
3072 rtx pat = PATTERN (setcc);
3073 if (!CC0_P (SET_DEST (pat)))
3074 insert_insn_on_edge (copy_insn (pat), e);
3077 if (dump_file != NULL)
3079 fprintf (dump_file, "JUMP-BYPASS: Proved reg %d "
3080 "in jump_insn %d equals constant ",
3081 regno, INSN_UID (jump));
3082 print_rtl (dump_file, SET_SRC (set->expr));
3083 fprintf (dump_file, "\nBypass edge from %d->%d to %d\n",
3084 e->src->index, old_dest->index, dest->index);
3086 change = 1;
3087 removed_p = 1;
3088 break;
3091 if (!removed_p)
3092 ei_next (&ei);
3094 return change;
3097 /* Find basic blocks with more than one predecessor that only contain a
3098 single conditional jump. If the result of the comparison is known at
3099 compile-time from any incoming edge, redirect that edge to the
3100 appropriate target. Returns nonzero if a change was made.
3102 This function is now mis-named, because we also handle indirect jumps. */
3104 static int
3105 bypass_conditional_jumps (void)
3107 basic_block bb;
3108 int changed;
3109 rtx setcc;
3110 rtx insn;
3111 rtx dest;
3113 /* Note we start at block 1. */
3114 if (ENTRY_BLOCK_PTR->next_bb == EXIT_BLOCK_PTR)
3115 return 0;
3117 bypass_last_basic_block = last_basic_block;
3118 mark_dfs_back_edges ();
3120 changed = 0;
3121 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR->next_bb->next_bb,
3122 EXIT_BLOCK_PTR, next_bb)
3124 /* Check for more than one predecessor. */
3125 if (!single_pred_p (bb))
3127 setcc = NULL_RTX;
3128 FOR_BB_INSNS (bb, insn)
3129 if (DEBUG_INSN_P (insn))
3130 continue;
3131 else if (NONJUMP_INSN_P (insn))
3133 if (setcc)
3134 break;
3135 if (GET_CODE (PATTERN (insn)) != SET)
3136 break;
3138 dest = SET_DEST (PATTERN (insn));
3139 if (REG_P (dest) || CC0_P (dest))
3140 setcc = insn;
3141 else
3142 break;
3144 else if (JUMP_P (insn))
3146 if ((any_condjump_p (insn) || computed_jump_p (insn))
3147 && onlyjump_p (insn))
3148 changed |= bypass_block (bb, setcc, insn);
3149 break;
3151 else if (INSN_P (insn))
3152 break;
3156 /* If we bypassed any register setting insns, we inserted a
3157 copy on the redirected edge. These need to be committed. */
3158 if (changed)
3159 commit_edge_insertions ();
3161 return changed;
3164 /* Compute PRE+LCM working variables. */
3166 /* Local properties of expressions. */
3167 /* Nonzero for expressions that are transparent in the block. */
3168 static sbitmap *transp;
3170 /* Nonzero for expressions that are transparent at the end of the block.
3171 This is only zero for expressions killed by abnormal critical edge
3172 created by a calls. */
3173 static sbitmap *transpout;
3175 /* Nonzero for expressions that are computed (available) in the block. */
3176 static sbitmap *comp;
3178 /* Nonzero for expressions that are locally anticipatable in the block. */
3179 static sbitmap *antloc;
3181 /* Nonzero for expressions where this block is an optimal computation
3182 point. */
3183 static sbitmap *pre_optimal;
3185 /* Nonzero for expressions which are redundant in a particular block. */
3186 static sbitmap *pre_redundant;
3188 /* Nonzero for expressions which should be inserted on a specific edge. */
3189 static sbitmap *pre_insert_map;
3191 /* Nonzero for expressions which should be deleted in a specific block. */
3192 static sbitmap *pre_delete_map;
3194 /* Contains the edge_list returned by pre_edge_lcm. */
3195 static struct edge_list *edge_list;
3197 /* Allocate vars used for PRE analysis. */
3199 static void
3200 alloc_pre_mem (int n_blocks, int n_exprs)
3202 transp = sbitmap_vector_alloc (n_blocks, n_exprs);
3203 comp = sbitmap_vector_alloc (n_blocks, n_exprs);
3204 antloc = sbitmap_vector_alloc (n_blocks, n_exprs);
3206 pre_optimal = NULL;
3207 pre_redundant = NULL;
3208 pre_insert_map = NULL;
3209 pre_delete_map = NULL;
3210 ae_kill = sbitmap_vector_alloc (n_blocks, n_exprs);
3212 /* pre_insert and pre_delete are allocated later. */
3215 /* Free vars used for PRE analysis. */
3217 static void
3218 free_pre_mem (void)
3220 sbitmap_vector_free (transp);
3221 sbitmap_vector_free (comp);
3223 /* ANTLOC and AE_KILL are freed just after pre_lcm finishes. */
3225 if (pre_optimal)
3226 sbitmap_vector_free (pre_optimal);
3227 if (pre_redundant)
3228 sbitmap_vector_free (pre_redundant);
3229 if (pre_insert_map)
3230 sbitmap_vector_free (pre_insert_map);
3231 if (pre_delete_map)
3232 sbitmap_vector_free (pre_delete_map);
3234 transp = comp = NULL;
3235 pre_optimal = pre_redundant = pre_insert_map = pre_delete_map = NULL;
3238 /* Top level routine to do the dataflow analysis needed by PRE. */
3240 static void
3241 compute_pre_data (void)
3243 sbitmap trapping_expr;
3244 basic_block bb;
3245 unsigned int ui;
3247 compute_local_properties (transp, comp, antloc, &expr_hash_table);
3248 sbitmap_vector_zero (ae_kill, last_basic_block);
3250 /* Collect expressions which might trap. */
3251 trapping_expr = sbitmap_alloc (expr_hash_table.n_elems);
3252 sbitmap_zero (trapping_expr);
3253 for (ui = 0; ui < expr_hash_table.size; ui++)
3255 struct expr *e;
3256 for (e = expr_hash_table.table[ui]; e != NULL; e = e->next_same_hash)
3257 if (may_trap_p (e->expr))
3258 SET_BIT (trapping_expr, e->bitmap_index);
3261 /* Compute ae_kill for each basic block using:
3263 ~(TRANSP | COMP)
3266 FOR_EACH_BB (bb)
3268 edge e;
3269 edge_iterator ei;
3271 /* If the current block is the destination of an abnormal edge, we
3272 kill all trapping expressions because we won't be able to properly
3273 place the instruction on the edge. So make them neither
3274 anticipatable nor transparent. This is fairly conservative. */
3275 FOR_EACH_EDGE (e, ei, bb->preds)
3276 if (e->flags & EDGE_ABNORMAL)
3278 sbitmap_difference (antloc[bb->index], antloc[bb->index], trapping_expr);
3279 sbitmap_difference (transp[bb->index], transp[bb->index], trapping_expr);
3280 break;
3283 sbitmap_a_or_b (ae_kill[bb->index], transp[bb->index], comp[bb->index]);
3284 sbitmap_not (ae_kill[bb->index], ae_kill[bb->index]);
3287 edge_list = pre_edge_lcm (expr_hash_table.n_elems, transp, comp, antloc,
3288 ae_kill, &pre_insert_map, &pre_delete_map);
3289 sbitmap_vector_free (antloc);
3290 antloc = NULL;
3291 sbitmap_vector_free (ae_kill);
3292 ae_kill = NULL;
3293 sbitmap_free (trapping_expr);
3296 /* PRE utilities */
3298 /* Return nonzero if an occurrence of expression EXPR in OCCR_BB would reach
3299 block BB.
3301 VISITED is a pointer to a working buffer for tracking which BB's have
3302 been visited. It is NULL for the top-level call.
3304 We treat reaching expressions that go through blocks containing the same
3305 reaching expression as "not reaching". E.g. if EXPR is generated in blocks
3306 2 and 3, INSN is in block 4, and 2->3->4, we treat the expression in block
3307 2 as not reaching. The intent is to improve the probability of finding
3308 only one reaching expression and to reduce register lifetimes by picking
3309 the closest such expression. */
3311 static int
3312 pre_expr_reaches_here_p_work (basic_block occr_bb, struct expr *expr, basic_block bb, char *visited)
3314 edge pred;
3315 edge_iterator ei;
3317 FOR_EACH_EDGE (pred, ei, bb->preds)
3319 basic_block pred_bb = pred->src;
3321 if (pred->src == ENTRY_BLOCK_PTR
3322 /* Has predecessor has already been visited? */
3323 || visited[pred_bb->index])
3324 ;/* Nothing to do. */
3326 /* Does this predecessor generate this expression? */
3327 else if (TEST_BIT (comp[pred_bb->index], expr->bitmap_index))
3329 /* Is this the occurrence we're looking for?
3330 Note that there's only one generating occurrence per block
3331 so we just need to check the block number. */
3332 if (occr_bb == pred_bb)
3333 return 1;
3335 visited[pred_bb->index] = 1;
3337 /* Ignore this predecessor if it kills the expression. */
3338 else if (! TEST_BIT (transp[pred_bb->index], expr->bitmap_index))
3339 visited[pred_bb->index] = 1;
3341 /* Neither gen nor kill. */
3342 else
3344 visited[pred_bb->index] = 1;
3345 if (pre_expr_reaches_here_p_work (occr_bb, expr, pred_bb, visited))
3346 return 1;
3350 /* All paths have been checked. */
3351 return 0;
3354 /* The wrapper for pre_expr_reaches_here_work that ensures that any
3355 memory allocated for that function is returned. */
3357 static int
3358 pre_expr_reaches_here_p (basic_block occr_bb, struct expr *expr, basic_block bb)
3360 int rval;
3361 char *visited = XCNEWVEC (char, last_basic_block);
3363 rval = pre_expr_reaches_here_p_work (occr_bb, expr, bb, visited);
3365 free (visited);
3366 return rval;
3370 /* Given an expr, generate RTL which we can insert at the end of a BB,
3371 or on an edge. Set the block number of any insns generated to
3372 the value of BB. */
3374 static rtx
3375 process_insert_insn (struct expr *expr)
3377 rtx reg = expr->reaching_reg;
3378 rtx exp = copy_rtx (expr->expr);
3379 rtx pat;
3381 start_sequence ();
3383 /* If the expression is something that's an operand, like a constant,
3384 just copy it to a register. */
3385 if (general_operand (exp, GET_MODE (reg)))
3386 emit_move_insn (reg, exp);
3388 /* Otherwise, make a new insn to compute this expression and make sure the
3389 insn will be recognized (this also adds any needed CLOBBERs). Copy the
3390 expression to make sure we don't have any sharing issues. */
3391 else
3393 rtx insn = emit_insn (gen_rtx_SET (VOIDmode, reg, exp));
3395 if (insn_invalid_p (insn))
3396 gcc_unreachable ();
3400 pat = get_insns ();
3401 end_sequence ();
3403 return pat;
3406 /* Add EXPR to the end of basic block BB.
3408 This is used by both the PRE and code hoisting.
3410 For PRE, we want to verify that the expr is either transparent
3411 or locally anticipatable in the target block. This check makes
3412 no sense for code hoisting. */
3414 static void
3415 insert_insn_end_basic_block (struct expr *expr, basic_block bb, int pre)
3417 rtx insn = BB_END (bb);
3418 rtx new_insn;
3419 rtx reg = expr->reaching_reg;
3420 int regno = REGNO (reg);
3421 rtx pat, pat_end;
3423 pat = process_insert_insn (expr);
3424 gcc_assert (pat && INSN_P (pat));
3426 pat_end = pat;
3427 while (NEXT_INSN (pat_end) != NULL_RTX)
3428 pat_end = NEXT_INSN (pat_end);
3430 /* If the last insn is a jump, insert EXPR in front [taking care to
3431 handle cc0, etc. properly]. Similarly we need to care trapping
3432 instructions in presence of non-call exceptions. */
3434 if (JUMP_P (insn)
3435 || (NONJUMP_INSN_P (insn)
3436 && (!single_succ_p (bb)
3437 || single_succ_edge (bb)->flags & EDGE_ABNORMAL)))
3439 #ifdef HAVE_cc0
3440 rtx note;
3441 #endif
3442 /* It should always be the case that we can put these instructions
3443 anywhere in the basic block with performing PRE optimizations.
3444 Check this. */
3445 gcc_assert (!NONJUMP_INSN_P (insn) || !pre
3446 || TEST_BIT (antloc[bb->index], expr->bitmap_index)
3447 || TEST_BIT (transp[bb->index], expr->bitmap_index));
3449 /* If this is a jump table, then we can't insert stuff here. Since
3450 we know the previous real insn must be the tablejump, we insert
3451 the new instruction just before the tablejump. */
3452 if (GET_CODE (PATTERN (insn)) == ADDR_VEC
3453 || GET_CODE (PATTERN (insn)) == ADDR_DIFF_VEC)
3454 insn = prev_real_insn (insn);
3456 #ifdef HAVE_cc0
3457 /* FIXME: 'twould be nice to call prev_cc0_setter here but it aborts
3458 if cc0 isn't set. */
3459 note = find_reg_note (insn, REG_CC_SETTER, NULL_RTX);
3460 if (note)
3461 insn = XEXP (note, 0);
3462 else
3464 rtx maybe_cc0_setter = prev_nonnote_insn (insn);
3465 if (maybe_cc0_setter
3466 && INSN_P (maybe_cc0_setter)
3467 && sets_cc0_p (PATTERN (maybe_cc0_setter)))
3468 insn = maybe_cc0_setter;
3470 #endif
3471 /* FIXME: What if something in cc0/jump uses value set in new insn? */
3472 new_insn = emit_insn_before_noloc (pat, insn, bb);
3475 /* Likewise if the last insn is a call, as will happen in the presence
3476 of exception handling. */
3477 else if (CALL_P (insn)
3478 && (!single_succ_p (bb)
3479 || single_succ_edge (bb)->flags & EDGE_ABNORMAL))
3481 /* Keeping in mind targets with small register classes and parameters
3482 in registers, we search backward and place the instructions before
3483 the first parameter is loaded. Do this for everyone for consistency
3484 and a presumption that we'll get better code elsewhere as well.
3486 It should always be the case that we can put these instructions
3487 anywhere in the basic block with performing PRE optimizations.
3488 Check this. */
3490 gcc_assert (!pre
3491 || TEST_BIT (antloc[bb->index], expr->bitmap_index)
3492 || TEST_BIT (transp[bb->index], expr->bitmap_index));
3494 /* Since different machines initialize their parameter registers
3495 in different orders, assume nothing. Collect the set of all
3496 parameter registers. */
3497 insn = find_first_parameter_load (insn, BB_HEAD (bb));
3499 /* If we found all the parameter loads, then we want to insert
3500 before the first parameter load.
3502 If we did not find all the parameter loads, then we might have
3503 stopped on the head of the block, which could be a CODE_LABEL.
3504 If we inserted before the CODE_LABEL, then we would be putting
3505 the insn in the wrong basic block. In that case, put the insn
3506 after the CODE_LABEL. Also, respect NOTE_INSN_BASIC_BLOCK. */
3507 while (LABEL_P (insn)
3508 || NOTE_INSN_BASIC_BLOCK_P (insn))
3509 insn = NEXT_INSN (insn);
3511 new_insn = emit_insn_before_noloc (pat, insn, bb);
3513 else
3514 new_insn = emit_insn_after_noloc (pat, insn, bb);
3516 while (1)
3518 if (INSN_P (pat))
3519 add_label_notes (PATTERN (pat), new_insn);
3520 if (pat == pat_end)
3521 break;
3522 pat = NEXT_INSN (pat);
3525 gcse_create_count++;
3527 if (dump_file)
3529 fprintf (dump_file, "PRE/HOIST: end of bb %d, insn %d, ",
3530 bb->index, INSN_UID (new_insn));
3531 fprintf (dump_file, "copying expression %d to reg %d\n",
3532 expr->bitmap_index, regno);
3536 /* Insert partially redundant expressions on edges in the CFG to make
3537 the expressions fully redundant. */
3539 static int
3540 pre_edge_insert (struct edge_list *edge_list, struct expr **index_map)
3542 int e, i, j, num_edges, set_size, did_insert = 0;
3543 sbitmap *inserted;
3545 /* Where PRE_INSERT_MAP is nonzero, we add the expression on that edge
3546 if it reaches any of the deleted expressions. */
3548 set_size = pre_insert_map[0]->size;
3549 num_edges = NUM_EDGES (edge_list);
3550 inserted = sbitmap_vector_alloc (num_edges, expr_hash_table.n_elems);
3551 sbitmap_vector_zero (inserted, num_edges);
3553 for (e = 0; e < num_edges; e++)
3555 int indx;
3556 basic_block bb = INDEX_EDGE_PRED_BB (edge_list, e);
3558 for (i = indx = 0; i < set_size; i++, indx += SBITMAP_ELT_BITS)
3560 SBITMAP_ELT_TYPE insert = pre_insert_map[e]->elms[i];
3562 for (j = indx; insert && j < (int) expr_hash_table.n_elems; j++, insert >>= 1)
3563 if ((insert & 1) != 0 && index_map[j]->reaching_reg != NULL_RTX)
3565 struct expr *expr = index_map[j];
3566 struct occr *occr;
3568 /* Now look at each deleted occurrence of this expression. */
3569 for (occr = expr->antic_occr; occr != NULL; occr = occr->next)
3571 if (! occr->deleted_p)
3572 continue;
3574 /* Insert this expression on this edge if it would
3575 reach the deleted occurrence in BB. */
3576 if (!TEST_BIT (inserted[e], j))
3578 rtx insn;
3579 edge eg = INDEX_EDGE (edge_list, e);
3581 /* We can't insert anything on an abnormal and
3582 critical edge, so we insert the insn at the end of
3583 the previous block. There are several alternatives
3584 detailed in Morgans book P277 (sec 10.5) for
3585 handling this situation. This one is easiest for
3586 now. */
3588 if (eg->flags & EDGE_ABNORMAL)
3589 insert_insn_end_basic_block (index_map[j], bb, 0);
3590 else
3592 insn = process_insert_insn (index_map[j]);
3593 insert_insn_on_edge (insn, eg);
3596 if (dump_file)
3598 fprintf (dump_file, "PRE: edge (%d,%d), ",
3599 bb->index,
3600 INDEX_EDGE_SUCC_BB (edge_list, e)->index);
3601 fprintf (dump_file, "copy expression %d\n",
3602 expr->bitmap_index);
3605 update_ld_motion_stores (expr);
3606 SET_BIT (inserted[e], j);
3607 did_insert = 1;
3608 gcse_create_count++;
3615 sbitmap_vector_free (inserted);
3616 return did_insert;
3619 /* Copy the result of EXPR->EXPR generated by INSN to EXPR->REACHING_REG.
3620 Given "old_reg <- expr" (INSN), instead of adding after it
3621 reaching_reg <- old_reg
3622 it's better to do the following:
3623 reaching_reg <- expr
3624 old_reg <- reaching_reg
3625 because this way copy propagation can discover additional PRE
3626 opportunities. But if this fails, we try the old way.
3627 When "expr" is a store, i.e.
3628 given "MEM <- old_reg", instead of adding after it
3629 reaching_reg <- old_reg
3630 it's better to add it before as follows:
3631 reaching_reg <- old_reg
3632 MEM <- reaching_reg. */
3634 static void
3635 pre_insert_copy_insn (struct expr *expr, rtx insn)
3637 rtx reg = expr->reaching_reg;
3638 int regno = REGNO (reg);
3639 int indx = expr->bitmap_index;
3640 rtx pat = PATTERN (insn);
3641 rtx set, first_set, new_insn;
3642 rtx old_reg;
3643 int i;
3645 /* This block matches the logic in hash_scan_insn. */
3646 switch (GET_CODE (pat))
3648 case SET:
3649 set = pat;
3650 break;
3652 case PARALLEL:
3653 /* Search through the parallel looking for the set whose
3654 source was the expression that we're interested in. */
3655 first_set = NULL_RTX;
3656 set = NULL_RTX;
3657 for (i = 0; i < XVECLEN (pat, 0); i++)
3659 rtx x = XVECEXP (pat, 0, i);
3660 if (GET_CODE (x) == SET)
3662 /* If the source was a REG_EQUAL or REG_EQUIV note, we
3663 may not find an equivalent expression, but in this
3664 case the PARALLEL will have a single set. */
3665 if (first_set == NULL_RTX)
3666 first_set = x;
3667 if (expr_equiv_p (SET_SRC (x), expr->expr))
3669 set = x;
3670 break;
3675 gcc_assert (first_set);
3676 if (set == NULL_RTX)
3677 set = first_set;
3678 break;
3680 default:
3681 gcc_unreachable ();
3684 if (REG_P (SET_DEST (set)))
3686 old_reg = SET_DEST (set);
3687 /* Check if we can modify the set destination in the original insn. */
3688 if (validate_change (insn, &SET_DEST (set), reg, 0))
3690 new_insn = gen_move_insn (old_reg, reg);
3691 new_insn = emit_insn_after (new_insn, insn);
3693 else
3695 new_insn = gen_move_insn (reg, old_reg);
3696 new_insn = emit_insn_after (new_insn, insn);
3699 else /* This is possible only in case of a store to memory. */
3701 old_reg = SET_SRC (set);
3702 new_insn = gen_move_insn (reg, old_reg);
3704 /* Check if we can modify the set source in the original insn. */
3705 if (validate_change (insn, &SET_SRC (set), reg, 0))
3706 new_insn = emit_insn_before (new_insn, insn);
3707 else
3708 new_insn = emit_insn_after (new_insn, insn);
3711 gcse_create_count++;
3713 if (dump_file)
3714 fprintf (dump_file,
3715 "PRE: bb %d, insn %d, copy expression %d in insn %d to reg %d\n",
3716 BLOCK_FOR_INSN (insn)->index, INSN_UID (new_insn), indx,
3717 INSN_UID (insn), regno);
3720 /* Copy available expressions that reach the redundant expression
3721 to `reaching_reg'. */
3723 static void
3724 pre_insert_copies (void)
3726 unsigned int i, added_copy;
3727 struct expr *expr;
3728 struct occr *occr;
3729 struct occr *avail;
3731 /* For each available expression in the table, copy the result to
3732 `reaching_reg' if the expression reaches a deleted one.
3734 ??? The current algorithm is rather brute force.
3735 Need to do some profiling. */
3737 for (i = 0; i < expr_hash_table.size; i++)
3738 for (expr = expr_hash_table.table[i]; expr != NULL; expr = expr->next_same_hash)
3740 /* If the basic block isn't reachable, PPOUT will be TRUE. However,
3741 we don't want to insert a copy here because the expression may not
3742 really be redundant. So only insert an insn if the expression was
3743 deleted. This test also avoids further processing if the
3744 expression wasn't deleted anywhere. */
3745 if (expr->reaching_reg == NULL)
3746 continue;
3748 /* Set when we add a copy for that expression. */
3749 added_copy = 0;
3751 for (occr = expr->antic_occr; occr != NULL; occr = occr->next)
3753 if (! occr->deleted_p)
3754 continue;
3756 for (avail = expr->avail_occr; avail != NULL; avail = avail->next)
3758 rtx insn = avail->insn;
3760 /* No need to handle this one if handled already. */
3761 if (avail->copied_p)
3762 continue;
3764 /* Don't handle this one if it's a redundant one. */
3765 if (INSN_DELETED_P (insn))
3766 continue;
3768 /* Or if the expression doesn't reach the deleted one. */
3769 if (! pre_expr_reaches_here_p (BLOCK_FOR_INSN (avail->insn),
3770 expr,
3771 BLOCK_FOR_INSN (occr->insn)))
3772 continue;
3774 added_copy = 1;
3776 /* Copy the result of avail to reaching_reg. */
3777 pre_insert_copy_insn (expr, insn);
3778 avail->copied_p = 1;
3782 if (added_copy)
3783 update_ld_motion_stores (expr);
3787 /* Emit move from SRC to DEST noting the equivalence with expression computed
3788 in INSN. */
3789 static rtx
3790 gcse_emit_move_after (rtx src, rtx dest, rtx insn)
3792 rtx new_rtx;
3793 rtx set = single_set (insn), set2;
3794 rtx note;
3795 rtx eqv;
3797 /* This should never fail since we're creating a reg->reg copy
3798 we've verified to be valid. */
3800 new_rtx = emit_insn_after (gen_move_insn (dest, src), insn);
3802 /* Note the equivalence for local CSE pass. */
3803 set2 = single_set (new_rtx);
3804 if (!set2 || !rtx_equal_p (SET_DEST (set2), dest))
3805 return new_rtx;
3806 if ((note = find_reg_equal_equiv_note (insn)))
3807 eqv = XEXP (note, 0);
3808 else
3809 eqv = SET_SRC (set);
3811 set_unique_reg_note (new_rtx, REG_EQUAL, copy_insn_1 (eqv));
3813 return new_rtx;
3816 /* Delete redundant computations.
3817 Deletion is done by changing the insn to copy the `reaching_reg' of
3818 the expression into the result of the SET. It is left to later passes
3819 (cprop, cse2, flow, combine, regmove) to propagate the copy or eliminate it.
3821 Returns nonzero if a change is made. */
3823 static int
3824 pre_delete (void)
3826 unsigned int i;
3827 int changed;
3828 struct expr *expr;
3829 struct occr *occr;
3831 changed = 0;
3832 for (i = 0; i < expr_hash_table.size; i++)
3833 for (expr = expr_hash_table.table[i];
3834 expr != NULL;
3835 expr = expr->next_same_hash)
3837 int indx = expr->bitmap_index;
3839 /* We only need to search antic_occr since we require
3840 ANTLOC != 0. */
3842 for (occr = expr->antic_occr; occr != NULL; occr = occr->next)
3844 rtx insn = occr->insn;
3845 rtx set;
3846 basic_block bb = BLOCK_FOR_INSN (insn);
3848 /* We only delete insns that have a single_set. */
3849 if (TEST_BIT (pre_delete_map[bb->index], indx)
3850 && (set = single_set (insn)) != 0
3851 && dbg_cnt (pre_insn))
3853 /* Create a pseudo-reg to store the result of reaching
3854 expressions into. Get the mode for the new pseudo from
3855 the mode of the original destination pseudo. */
3856 if (expr->reaching_reg == NULL)
3857 expr->reaching_reg = gen_reg_rtx_and_attrs (SET_DEST (set));
3859 gcse_emit_move_after (expr->reaching_reg, SET_DEST (set), insn);
3860 delete_insn (insn);
3861 occr->deleted_p = 1;
3862 changed = 1;
3863 gcse_subst_count++;
3865 if (dump_file)
3867 fprintf (dump_file,
3868 "PRE: redundant insn %d (expression %d) in ",
3869 INSN_UID (insn), indx);
3870 fprintf (dump_file, "bb %d, reaching reg is %d\n",
3871 bb->index, REGNO (expr->reaching_reg));
3877 return changed;
3880 /* Perform GCSE optimizations using PRE.
3881 This is called by one_pre_gcse_pass after all the dataflow analysis
3882 has been done.
3884 This is based on the original Morel-Renvoise paper Fred Chow's thesis, and
3885 lazy code motion from Knoop, Ruthing and Steffen as described in Advanced
3886 Compiler Design and Implementation.
3888 ??? A new pseudo reg is created to hold the reaching expression. The nice
3889 thing about the classical approach is that it would try to use an existing
3890 reg. If the register can't be adequately optimized [i.e. we introduce
3891 reload problems], one could add a pass here to propagate the new register
3892 through the block.
3894 ??? We don't handle single sets in PARALLELs because we're [currently] not
3895 able to copy the rest of the parallel when we insert copies to create full
3896 redundancies from partial redundancies. However, there's no reason why we
3897 can't handle PARALLELs in the cases where there are no partial
3898 redundancies. */
3900 static int
3901 pre_gcse (void)
3903 unsigned int i;
3904 int did_insert, changed;
3905 struct expr **index_map;
3906 struct expr *expr;
3908 /* Compute a mapping from expression number (`bitmap_index') to
3909 hash table entry. */
3911 index_map = XCNEWVEC (struct expr *, expr_hash_table.n_elems);
3912 for (i = 0; i < expr_hash_table.size; i++)
3913 for (expr = expr_hash_table.table[i]; expr != NULL; expr = expr->next_same_hash)
3914 index_map[expr->bitmap_index] = expr;
3916 /* Delete the redundant insns first so that
3917 - we know what register to use for the new insns and for the other
3918 ones with reaching expressions
3919 - we know which insns are redundant when we go to create copies */
3921 changed = pre_delete ();
3922 did_insert = pre_edge_insert (edge_list, index_map);
3924 /* In other places with reaching expressions, copy the expression to the
3925 specially allocated pseudo-reg that reaches the redundant expr. */
3926 pre_insert_copies ();
3927 if (did_insert)
3929 commit_edge_insertions ();
3930 changed = 1;
3933 free (index_map);
3934 return changed;
3937 /* Top level routine to perform one PRE GCSE pass.
3939 Return nonzero if a change was made. */
3941 static int
3942 one_pre_gcse_pass (void)
3944 int changed = 0;
3946 gcse_subst_count = 0;
3947 gcse_create_count = 0;
3949 /* Return if there's nothing to do, or it is too expensive. */
3950 if (n_basic_blocks <= NUM_FIXED_BLOCKS + 1
3951 || is_too_expensive (_("PRE disabled")))
3952 return 0;
3954 /* We need alias. */
3955 init_alias_analysis ();
3957 bytes_used = 0;
3958 gcc_obstack_init (&gcse_obstack);
3959 alloc_gcse_mem ();
3961 alloc_hash_table (&expr_hash_table, 0);
3962 add_noreturn_fake_exit_edges ();
3963 if (flag_gcse_lm)
3964 compute_ld_motion_mems ();
3966 compute_hash_table (&expr_hash_table);
3967 trim_ld_motion_mems ();
3968 if (dump_file)
3969 dump_hash_table (dump_file, "Expression", &expr_hash_table);
3971 if (expr_hash_table.n_elems > 0)
3973 alloc_pre_mem (last_basic_block, expr_hash_table.n_elems);
3974 compute_pre_data ();
3975 changed |= pre_gcse ();
3976 free_edge_list (edge_list);
3977 free_pre_mem ();
3980 free_ldst_mems ();
3981 remove_fake_exit_edges ();
3982 free_hash_table (&expr_hash_table);
3984 free_gcse_mem ();
3985 obstack_free (&gcse_obstack, NULL);
3987 /* We are finished with alias. */
3988 end_alias_analysis ();
3990 if (dump_file)
3992 fprintf (dump_file, "PRE GCSE of %s, %d basic blocks, %d bytes needed, ",
3993 current_function_name (), n_basic_blocks, bytes_used);
3994 fprintf (dump_file, "%d substs, %d insns created\n",
3995 gcse_subst_count, gcse_create_count);
3998 return changed;
4001 /* If X contains any LABEL_REF's, add REG_LABEL_OPERAND notes for them
4002 to INSN. If such notes are added to an insn which references a
4003 CODE_LABEL, the LABEL_NUSES count is incremented. We have to add
4004 that note, because the following loop optimization pass requires
4005 them. */
4007 /* ??? If there was a jump optimization pass after gcse and before loop,
4008 then we would not need to do this here, because jump would add the
4009 necessary REG_LABEL_OPERAND and REG_LABEL_TARGET notes. */
4011 static void
4012 add_label_notes (rtx x, rtx insn)
4014 enum rtx_code code = GET_CODE (x);
4015 int i, j;
4016 const char *fmt;
4018 if (code == LABEL_REF && !LABEL_REF_NONLOCAL_P (x))
4020 /* This code used to ignore labels that referred to dispatch tables to
4021 avoid flow generating (slightly) worse code.
4023 We no longer ignore such label references (see LABEL_REF handling in
4024 mark_jump_label for additional information). */
4026 /* There's no reason for current users to emit jump-insns with
4027 such a LABEL_REF, so we don't have to handle REG_LABEL_TARGET
4028 notes. */
4029 gcc_assert (!JUMP_P (insn));
4030 add_reg_note (insn, REG_LABEL_OPERAND, XEXP (x, 0));
4032 if (LABEL_P (XEXP (x, 0)))
4033 LABEL_NUSES (XEXP (x, 0))++;
4035 return;
4038 for (i = GET_RTX_LENGTH (code) - 1, fmt = GET_RTX_FORMAT (code); i >= 0; i--)
4040 if (fmt[i] == 'e')
4041 add_label_notes (XEXP (x, i), insn);
4042 else if (fmt[i] == 'E')
4043 for (j = XVECLEN (x, i) - 1; j >= 0; j--)
4044 add_label_notes (XVECEXP (x, i, j), insn);
4048 /* Compute transparent outgoing information for each block.
4050 An expression is transparent to an edge unless it is killed by
4051 the edge itself. This can only happen with abnormal control flow,
4052 when the edge is traversed through a call. This happens with
4053 non-local labels and exceptions.
4055 This would not be necessary if we split the edge. While this is
4056 normally impossible for abnormal critical edges, with some effort
4057 it should be possible with exception handling, since we still have
4058 control over which handler should be invoked. But due to increased
4059 EH table sizes, this may not be worthwhile. */
4061 static void
4062 compute_transpout (void)
4064 basic_block bb;
4065 unsigned int i;
4066 struct expr *expr;
4068 sbitmap_vector_ones (transpout, last_basic_block);
4070 FOR_EACH_BB (bb)
4072 /* Note that flow inserted a nop at the end of basic blocks that
4073 end in call instructions for reasons other than abnormal
4074 control flow. */
4075 if (! CALL_P (BB_END (bb)))
4076 continue;
4078 for (i = 0; i < expr_hash_table.size; i++)
4079 for (expr = expr_hash_table.table[i]; expr ; expr = expr->next_same_hash)
4080 if (MEM_P (expr->expr))
4082 if (GET_CODE (XEXP (expr->expr, 0)) == SYMBOL_REF
4083 && CONSTANT_POOL_ADDRESS_P (XEXP (expr->expr, 0)))
4084 continue;
4086 /* ??? Optimally, we would use interprocedural alias
4087 analysis to determine if this mem is actually killed
4088 by this call. */
4089 RESET_BIT (transpout[bb->index], expr->bitmap_index);
4094 /* Code Hoisting variables and subroutines. */
4096 /* Very busy expressions. */
4097 static sbitmap *hoist_vbein;
4098 static sbitmap *hoist_vbeout;
4100 /* Hoistable expressions. */
4101 static sbitmap *hoist_exprs;
4103 /* ??? We could compute post dominators and run this algorithm in
4104 reverse to perform tail merging, doing so would probably be
4105 more effective than the tail merging code in jump.c.
4107 It's unclear if tail merging could be run in parallel with
4108 code hoisting. It would be nice. */
4110 /* Allocate vars used for code hoisting analysis. */
4112 static void
4113 alloc_code_hoist_mem (int n_blocks, int n_exprs)
4115 antloc = sbitmap_vector_alloc (n_blocks, n_exprs);
4116 transp = sbitmap_vector_alloc (n_blocks, n_exprs);
4117 comp = sbitmap_vector_alloc (n_blocks, n_exprs);
4119 hoist_vbein = sbitmap_vector_alloc (n_blocks, n_exprs);
4120 hoist_vbeout = sbitmap_vector_alloc (n_blocks, n_exprs);
4121 hoist_exprs = sbitmap_vector_alloc (n_blocks, n_exprs);
4122 transpout = sbitmap_vector_alloc (n_blocks, n_exprs);
4125 /* Free vars used for code hoisting analysis. */
4127 static void
4128 free_code_hoist_mem (void)
4130 sbitmap_vector_free (antloc);
4131 sbitmap_vector_free (transp);
4132 sbitmap_vector_free (comp);
4134 sbitmap_vector_free (hoist_vbein);
4135 sbitmap_vector_free (hoist_vbeout);
4136 sbitmap_vector_free (hoist_exprs);
4137 sbitmap_vector_free (transpout);
4139 free_dominance_info (CDI_DOMINATORS);
4142 /* Compute the very busy expressions at entry/exit from each block.
4144 An expression is very busy if all paths from a given point
4145 compute the expression. */
4147 static void
4148 compute_code_hoist_vbeinout (void)
4150 int changed, passes;
4151 basic_block bb;
4153 sbitmap_vector_zero (hoist_vbeout, last_basic_block);
4154 sbitmap_vector_zero (hoist_vbein, last_basic_block);
4156 passes = 0;
4157 changed = 1;
4159 while (changed)
4161 changed = 0;
4163 /* We scan the blocks in the reverse order to speed up
4164 the convergence. */
4165 FOR_EACH_BB_REVERSE (bb)
4167 if (bb->next_bb != EXIT_BLOCK_PTR)
4168 sbitmap_intersection_of_succs (hoist_vbeout[bb->index],
4169 hoist_vbein, bb->index);
4171 changed |= sbitmap_a_or_b_and_c_cg (hoist_vbein[bb->index],
4172 antloc[bb->index],
4173 hoist_vbeout[bb->index],
4174 transp[bb->index]);
4177 passes++;
4180 if (dump_file)
4181 fprintf (dump_file, "hoisting vbeinout computation: %d passes\n", passes);
4184 /* Top level routine to do the dataflow analysis needed by code hoisting. */
4186 static void
4187 compute_code_hoist_data (void)
4189 compute_local_properties (transp, comp, antloc, &expr_hash_table);
4190 compute_transpout ();
4191 compute_code_hoist_vbeinout ();
4192 calculate_dominance_info (CDI_DOMINATORS);
4193 if (dump_file)
4194 fprintf (dump_file, "\n");
4197 /* Determine if the expression identified by EXPR_INDEX would
4198 reach BB unimpared if it was placed at the end of EXPR_BB.
4200 It's unclear exactly what Muchnick meant by "unimpared". It seems
4201 to me that the expression must either be computed or transparent in
4202 *every* block in the path(s) from EXPR_BB to BB. Any other definition
4203 would allow the expression to be hoisted out of loops, even if
4204 the expression wasn't a loop invariant.
4206 Contrast this to reachability for PRE where an expression is
4207 considered reachable if *any* path reaches instead of *all*
4208 paths. */
4210 static int
4211 hoist_expr_reaches_here_p (basic_block expr_bb, int expr_index, basic_block bb, char *visited)
4213 edge pred;
4214 edge_iterator ei;
4215 int visited_allocated_locally = 0;
4218 if (visited == NULL)
4220 visited_allocated_locally = 1;
4221 visited = XCNEWVEC (char, last_basic_block);
4224 FOR_EACH_EDGE (pred, ei, bb->preds)
4226 basic_block pred_bb = pred->src;
4228 if (pred->src == ENTRY_BLOCK_PTR)
4229 break;
4230 else if (pred_bb == expr_bb)
4231 continue;
4232 else if (visited[pred_bb->index])
4233 continue;
4235 /* Does this predecessor generate this expression? */
4236 else if (TEST_BIT (comp[pred_bb->index], expr_index))
4237 break;
4238 else if (! TEST_BIT (transp[pred_bb->index], expr_index))
4239 break;
4241 /* Not killed. */
4242 else
4244 visited[pred_bb->index] = 1;
4245 if (! hoist_expr_reaches_here_p (expr_bb, expr_index,
4246 pred_bb, visited))
4247 break;
4250 if (visited_allocated_locally)
4251 free (visited);
4253 return (pred == NULL);
4256 /* Actually perform code hoisting. */
4258 static int
4259 hoist_code (void)
4261 basic_block bb, dominated;
4262 VEC (basic_block, heap) *domby;
4263 unsigned int i,j;
4264 struct expr **index_map;
4265 struct expr *expr;
4266 int changed = 0;
4268 sbitmap_vector_zero (hoist_exprs, last_basic_block);
4270 /* Compute a mapping from expression number (`bitmap_index') to
4271 hash table entry. */
4273 index_map = XCNEWVEC (struct expr *, expr_hash_table.n_elems);
4274 for (i = 0; i < expr_hash_table.size; i++)
4275 for (expr = expr_hash_table.table[i]; expr != NULL; expr = expr->next_same_hash)
4276 index_map[expr->bitmap_index] = expr;
4278 /* Walk over each basic block looking for potentially hoistable
4279 expressions, nothing gets hoisted from the entry block. */
4280 FOR_EACH_BB (bb)
4282 int found = 0;
4283 int insn_inserted_p;
4285 domby = get_dominated_by (CDI_DOMINATORS, bb);
4286 /* Examine each expression that is very busy at the exit of this
4287 block. These are the potentially hoistable expressions. */
4288 for (i = 0; i < hoist_vbeout[bb->index]->n_bits; i++)
4290 int hoistable = 0;
4292 if (TEST_BIT (hoist_vbeout[bb->index], i)
4293 && TEST_BIT (transpout[bb->index], i))
4295 /* We've found a potentially hoistable expression, now
4296 we look at every block BB dominates to see if it
4297 computes the expression. */
4298 for (j = 0; VEC_iterate (basic_block, domby, j, dominated); j++)
4300 /* Ignore self dominance. */
4301 if (bb == dominated)
4302 continue;
4303 /* We've found a dominated block, now see if it computes
4304 the busy expression and whether or not moving that
4305 expression to the "beginning" of that block is safe. */
4306 if (!TEST_BIT (antloc[dominated->index], i))
4307 continue;
4309 /* Note if the expression would reach the dominated block
4310 unimpared if it was placed at the end of BB.
4312 Keep track of how many times this expression is hoistable
4313 from a dominated block into BB. */
4314 if (hoist_expr_reaches_here_p (bb, i, dominated, NULL))
4315 hoistable++;
4318 /* If we found more than one hoistable occurrence of this
4319 expression, then note it in the bitmap of expressions to
4320 hoist. It makes no sense to hoist things which are computed
4321 in only one BB, and doing so tends to pessimize register
4322 allocation. One could increase this value to try harder
4323 to avoid any possible code expansion due to register
4324 allocation issues; however experiments have shown that
4325 the vast majority of hoistable expressions are only movable
4326 from two successors, so raising this threshold is likely
4327 to nullify any benefit we get from code hoisting. */
4328 if (hoistable > 1)
4330 SET_BIT (hoist_exprs[bb->index], i);
4331 found = 1;
4335 /* If we found nothing to hoist, then quit now. */
4336 if (! found)
4338 VEC_free (basic_block, heap, domby);
4339 continue;
4342 /* Loop over all the hoistable expressions. */
4343 for (i = 0; i < hoist_exprs[bb->index]->n_bits; i++)
4345 /* We want to insert the expression into BB only once, so
4346 note when we've inserted it. */
4347 insn_inserted_p = 0;
4349 /* These tests should be the same as the tests above. */
4350 if (TEST_BIT (hoist_exprs[bb->index], i))
4352 /* We've found a potentially hoistable expression, now
4353 we look at every block BB dominates to see if it
4354 computes the expression. */
4355 for (j = 0; VEC_iterate (basic_block, domby, j, dominated); j++)
4357 /* Ignore self dominance. */
4358 if (bb == dominated)
4359 continue;
4361 /* We've found a dominated block, now see if it computes
4362 the busy expression and whether or not moving that
4363 expression to the "beginning" of that block is safe. */
4364 if (!TEST_BIT (antloc[dominated->index], i))
4365 continue;
4367 /* The expression is computed in the dominated block and
4368 it would be safe to compute it at the start of the
4369 dominated block. Now we have to determine if the
4370 expression would reach the dominated block if it was
4371 placed at the end of BB. */
4372 if (hoist_expr_reaches_here_p (bb, i, dominated, NULL))
4374 struct expr *expr = index_map[i];
4375 struct occr *occr = expr->antic_occr;
4376 rtx insn;
4377 rtx set;
4379 /* Find the right occurrence of this expression. */
4380 while (BLOCK_FOR_INSN (occr->insn) != dominated && occr)
4381 occr = occr->next;
4383 gcc_assert (occr);
4384 insn = occr->insn;
4385 set = single_set (insn);
4386 gcc_assert (set);
4388 /* Create a pseudo-reg to store the result of reaching
4389 expressions into. Get the mode for the new pseudo
4390 from the mode of the original destination pseudo. */
4391 if (expr->reaching_reg == NULL)
4392 expr->reaching_reg
4393 = gen_reg_rtx_and_attrs (SET_DEST (set));
4395 gcse_emit_move_after (expr->reaching_reg, SET_DEST (set), insn);
4396 delete_insn (insn);
4397 occr->deleted_p = 1;
4398 changed = 1;
4399 gcse_subst_count++;
4401 if (!insn_inserted_p)
4403 insert_insn_end_basic_block (index_map[i], bb, 0);
4404 insn_inserted_p = 1;
4410 VEC_free (basic_block, heap, domby);
4413 free (index_map);
4415 return changed;
4418 /* Top level routine to perform one code hoisting (aka unification) pass
4420 Return nonzero if a change was made. */
4422 static int
4423 one_code_hoisting_pass (void)
4425 int changed = 0;
4427 gcse_subst_count = 0;
4428 gcse_create_count = 0;
4430 /* Return if there's nothing to do, or it is too expensive. */
4431 if (n_basic_blocks <= NUM_FIXED_BLOCKS + 1
4432 || is_too_expensive (_("GCSE disabled")))
4433 return 0;
4435 /* We need alias. */
4436 init_alias_analysis ();
4438 bytes_used = 0;
4439 gcc_obstack_init (&gcse_obstack);
4440 alloc_gcse_mem ();
4442 alloc_hash_table (&expr_hash_table, 0);
4443 compute_hash_table (&expr_hash_table);
4444 if (dump_file)
4445 dump_hash_table (dump_file, "Code Hosting Expressions", &expr_hash_table);
4447 if (expr_hash_table.n_elems > 0)
4449 alloc_code_hoist_mem (last_basic_block, expr_hash_table.n_elems);
4450 compute_code_hoist_data ();
4451 changed = hoist_code ();
4452 free_code_hoist_mem ();
4455 free_hash_table (&expr_hash_table);
4456 free_gcse_mem ();
4457 obstack_free (&gcse_obstack, NULL);
4459 /* We are finished with alias. */
4460 end_alias_analysis ();
4462 if (dump_file)
4464 fprintf (dump_file, "HOIST of %s, %d basic blocks, %d bytes needed, ",
4465 current_function_name (), n_basic_blocks, bytes_used);
4466 fprintf (dump_file, "%d substs, %d insns created\n",
4467 gcse_subst_count, gcse_create_count);
4470 return changed;
4473 /* Here we provide the things required to do store motion towards
4474 the exit. In order for this to be effective, gcse also needed to
4475 be taught how to move a load when it is kill only by a store to itself.
4477 int i;
4478 float a[10];
4480 void foo(float scale)
4482 for (i=0; i<10; i++)
4483 a[i] *= scale;
4486 'i' is both loaded and stored to in the loop. Normally, gcse cannot move
4487 the load out since its live around the loop, and stored at the bottom
4488 of the loop.
4490 The 'Load Motion' referred to and implemented in this file is
4491 an enhancement to gcse which when using edge based lcm, recognizes
4492 this situation and allows gcse to move the load out of the loop.
4494 Once gcse has hoisted the load, store motion can then push this
4495 load towards the exit, and we end up with no loads or stores of 'i'
4496 in the loop. */
4498 static hashval_t
4499 pre_ldst_expr_hash (const void *p)
4501 int do_not_record_p = 0;
4502 const struct ls_expr *const x = (const struct ls_expr *) p;
4503 return hash_rtx (x->pattern, GET_MODE (x->pattern), &do_not_record_p, NULL, false);
4506 static int
4507 pre_ldst_expr_eq (const void *p1, const void *p2)
4509 const struct ls_expr *const ptr1 = (const struct ls_expr *) p1,
4510 *const ptr2 = (const struct ls_expr *) p2;
4511 return expr_equiv_p (ptr1->pattern, ptr2->pattern);
4514 /* This will search the ldst list for a matching expression. If it
4515 doesn't find one, we create one and initialize it. */
4517 static struct ls_expr *
4518 ldst_entry (rtx x)
4520 int do_not_record_p = 0;
4521 struct ls_expr * ptr;
4522 unsigned int hash;
4523 void **slot;
4524 struct ls_expr e;
4526 hash = hash_rtx (x, GET_MODE (x), &do_not_record_p,
4527 NULL, /*have_reg_qty=*/false);
4529 e.pattern = x;
4530 slot = htab_find_slot_with_hash (pre_ldst_table, &e, hash, INSERT);
4531 if (*slot)
4532 return (struct ls_expr *)*slot;
4534 ptr = XNEW (struct ls_expr);
4536 ptr->next = pre_ldst_mems;
4537 ptr->expr = NULL;
4538 ptr->pattern = x;
4539 ptr->pattern_regs = NULL_RTX;
4540 ptr->loads = NULL_RTX;
4541 ptr->stores = NULL_RTX;
4542 ptr->reaching_reg = NULL_RTX;
4543 ptr->invalid = 0;
4544 ptr->index = 0;
4545 ptr->hash_index = hash;
4546 pre_ldst_mems = ptr;
4547 *slot = ptr;
4549 return ptr;
4552 /* Free up an individual ldst entry. */
4554 static void
4555 free_ldst_entry (struct ls_expr * ptr)
4557 free_INSN_LIST_list (& ptr->loads);
4558 free_INSN_LIST_list (& ptr->stores);
4560 free (ptr);
4563 /* Free up all memory associated with the ldst list. */
4565 static void
4566 free_ldst_mems (void)
4568 if (pre_ldst_table)
4569 htab_delete (pre_ldst_table);
4570 pre_ldst_table = NULL;
4572 while (pre_ldst_mems)
4574 struct ls_expr * tmp = pre_ldst_mems;
4576 pre_ldst_mems = pre_ldst_mems->next;
4578 free_ldst_entry (tmp);
4581 pre_ldst_mems = NULL;
4584 /* Dump debugging info about the ldst list. */
4586 static void
4587 print_ldst_list (FILE * file)
4589 struct ls_expr * ptr;
4591 fprintf (file, "LDST list: \n");
4593 for (ptr = first_ls_expr (); ptr != NULL; ptr = next_ls_expr (ptr))
4595 fprintf (file, " Pattern (%3d): ", ptr->index);
4597 print_rtl (file, ptr->pattern);
4599 fprintf (file, "\n Loads : ");
4601 if (ptr->loads)
4602 print_rtl (file, ptr->loads);
4603 else
4604 fprintf (file, "(nil)");
4606 fprintf (file, "\n Stores : ");
4608 if (ptr->stores)
4609 print_rtl (file, ptr->stores);
4610 else
4611 fprintf (file, "(nil)");
4613 fprintf (file, "\n\n");
4616 fprintf (file, "\n");
4619 /* Returns 1 if X is in the list of ldst only expressions. */
4621 static struct ls_expr *
4622 find_rtx_in_ldst (rtx x)
4624 struct ls_expr e;
4625 void **slot;
4626 if (!pre_ldst_table)
4627 return NULL;
4628 e.pattern = x;
4629 slot = htab_find_slot (pre_ldst_table, &e, NO_INSERT);
4630 if (!slot || ((struct ls_expr *)*slot)->invalid)
4631 return NULL;
4632 return (struct ls_expr *) *slot;
4635 /* Return first item in the list. */
4637 static inline struct ls_expr *
4638 first_ls_expr (void)
4640 return pre_ldst_mems;
4643 /* Return the next item in the list after the specified one. */
4645 static inline struct ls_expr *
4646 next_ls_expr (struct ls_expr * ptr)
4648 return ptr->next;
4651 /* Load Motion for loads which only kill themselves. */
4653 /* Return true if x is a simple MEM operation, with no registers or
4654 side effects. These are the types of loads we consider for the
4655 ld_motion list, otherwise we let the usual aliasing take care of it. */
4657 static int
4658 simple_mem (const_rtx x)
4660 if (! MEM_P (x))
4661 return 0;
4663 if (MEM_VOLATILE_P (x))
4664 return 0;
4666 if (GET_MODE (x) == BLKmode)
4667 return 0;
4669 /* If we are handling exceptions, we must be careful with memory references
4670 that may trap. If we are not, the behavior is undefined, so we may just
4671 continue. */
4672 if (cfun->can_throw_non_call_exceptions && may_trap_p (x))
4673 return 0;
4675 if (side_effects_p (x))
4676 return 0;
4678 /* Do not consider function arguments passed on stack. */
4679 if (reg_mentioned_p (stack_pointer_rtx, x))
4680 return 0;
4682 if (flag_float_store && FLOAT_MODE_P (GET_MODE (x)))
4683 return 0;
4685 return 1;
4688 /* Make sure there isn't a buried reference in this pattern anywhere.
4689 If there is, invalidate the entry for it since we're not capable
4690 of fixing it up just yet.. We have to be sure we know about ALL
4691 loads since the aliasing code will allow all entries in the
4692 ld_motion list to not-alias itself. If we miss a load, we will get
4693 the wrong value since gcse might common it and we won't know to
4694 fix it up. */
4696 static void
4697 invalidate_any_buried_refs (rtx x)
4699 const char * fmt;
4700 int i, j;
4701 struct ls_expr * ptr;
4703 /* Invalidate it in the list. */
4704 if (MEM_P (x) && simple_mem (x))
4706 ptr = ldst_entry (x);
4707 ptr->invalid = 1;
4710 /* Recursively process the insn. */
4711 fmt = GET_RTX_FORMAT (GET_CODE (x));
4713 for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
4715 if (fmt[i] == 'e')
4716 invalidate_any_buried_refs (XEXP (x, i));
4717 else if (fmt[i] == 'E')
4718 for (j = XVECLEN (x, i) - 1; j >= 0; j--)
4719 invalidate_any_buried_refs (XVECEXP (x, i, j));
4723 /* Find all the 'simple' MEMs which are used in LOADs and STORES. Simple
4724 being defined as MEM loads and stores to symbols, with no side effects
4725 and no registers in the expression. For a MEM destination, we also
4726 check that the insn is still valid if we replace the destination with a
4727 REG, as is done in update_ld_motion_stores. If there are any uses/defs
4728 which don't match this criteria, they are invalidated and trimmed out
4729 later. */
4731 static void
4732 compute_ld_motion_mems (void)
4734 struct ls_expr * ptr;
4735 basic_block bb;
4736 rtx insn;
4738 pre_ldst_mems = NULL;
4739 pre_ldst_table = htab_create (13, pre_ldst_expr_hash,
4740 pre_ldst_expr_eq, NULL);
4742 FOR_EACH_BB (bb)
4744 FOR_BB_INSNS (bb, insn)
4746 if (NONDEBUG_INSN_P (insn))
4748 if (GET_CODE (PATTERN (insn)) == SET)
4750 rtx src = SET_SRC (PATTERN (insn));
4751 rtx dest = SET_DEST (PATTERN (insn));
4753 /* Check for a simple LOAD... */
4754 if (MEM_P (src) && simple_mem (src))
4756 ptr = ldst_entry (src);
4757 if (REG_P (dest))
4758 ptr->loads = alloc_INSN_LIST (insn, ptr->loads);
4759 else
4760 ptr->invalid = 1;
4762 else
4764 /* Make sure there isn't a buried load somewhere. */
4765 invalidate_any_buried_refs (src);
4768 /* Check for stores. Don't worry about aliased ones, they
4769 will block any movement we might do later. We only care
4770 about this exact pattern since those are the only
4771 circumstance that we will ignore the aliasing info. */
4772 if (MEM_P (dest) && simple_mem (dest))
4774 ptr = ldst_entry (dest);
4776 if (! MEM_P (src)
4777 && GET_CODE (src) != ASM_OPERANDS
4778 /* Check for REG manually since want_to_gcse_p
4779 returns 0 for all REGs. */
4780 && can_assign_to_reg_without_clobbers_p (src))
4781 ptr->stores = alloc_INSN_LIST (insn, ptr->stores);
4782 else
4783 ptr->invalid = 1;
4786 else
4787 invalidate_any_buried_refs (PATTERN (insn));
4793 /* Remove any references that have been either invalidated or are not in the
4794 expression list for pre gcse. */
4796 static void
4797 trim_ld_motion_mems (void)
4799 struct ls_expr * * last = & pre_ldst_mems;
4800 struct ls_expr * ptr = pre_ldst_mems;
4802 while (ptr != NULL)
4804 struct expr * expr;
4806 /* Delete if entry has been made invalid. */
4807 if (! ptr->invalid)
4809 /* Delete if we cannot find this mem in the expression list. */
4810 unsigned int hash = ptr->hash_index % expr_hash_table.size;
4812 for (expr = expr_hash_table.table[hash];
4813 expr != NULL;
4814 expr = expr->next_same_hash)
4815 if (expr_equiv_p (expr->expr, ptr->pattern))
4816 break;
4818 else
4819 expr = (struct expr *) 0;
4821 if (expr)
4823 /* Set the expression field if we are keeping it. */
4824 ptr->expr = expr;
4825 last = & ptr->next;
4826 ptr = ptr->next;
4828 else
4830 *last = ptr->next;
4831 htab_remove_elt_with_hash (pre_ldst_table, ptr, ptr->hash_index);
4832 free_ldst_entry (ptr);
4833 ptr = * last;
4837 /* Show the world what we've found. */
4838 if (dump_file && pre_ldst_mems != NULL)
4839 print_ldst_list (dump_file);
4842 /* This routine will take an expression which we are replacing with
4843 a reaching register, and update any stores that are needed if
4844 that expression is in the ld_motion list. Stores are updated by
4845 copying their SRC to the reaching register, and then storing
4846 the reaching register into the store location. These keeps the
4847 correct value in the reaching register for the loads. */
4849 static void
4850 update_ld_motion_stores (struct expr * expr)
4852 struct ls_expr * mem_ptr;
4854 if ((mem_ptr = find_rtx_in_ldst (expr->expr)))
4856 /* We can try to find just the REACHED stores, but is shouldn't
4857 matter to set the reaching reg everywhere... some might be
4858 dead and should be eliminated later. */
4860 /* We replace (set mem expr) with (set reg expr) (set mem reg)
4861 where reg is the reaching reg used in the load. We checked in
4862 compute_ld_motion_mems that we can replace (set mem expr) with
4863 (set reg expr) in that insn. */
4864 rtx list = mem_ptr->stores;
4866 for ( ; list != NULL_RTX; list = XEXP (list, 1))
4868 rtx insn = XEXP (list, 0);
4869 rtx pat = PATTERN (insn);
4870 rtx src = SET_SRC (pat);
4871 rtx reg = expr->reaching_reg;
4872 rtx copy;
4874 /* If we've already copied it, continue. */
4875 if (expr->reaching_reg == src)
4876 continue;
4878 if (dump_file)
4880 fprintf (dump_file, "PRE: store updated with reaching reg ");
4881 print_rtl (dump_file, expr->reaching_reg);
4882 fprintf (dump_file, ":\n ");
4883 print_inline_rtx (dump_file, insn, 8);
4884 fprintf (dump_file, "\n");
4887 copy = gen_move_insn (reg, copy_rtx (SET_SRC (pat)));
4888 emit_insn_before (copy, insn);
4889 SET_SRC (pat) = reg;
4890 df_insn_rescan (insn);
4892 /* un-recognize this pattern since it's probably different now. */
4893 INSN_CODE (insn) = -1;
4894 gcse_create_count++;
4899 /* Return true if the graph is too expensive to optimize. PASS is the
4900 optimization about to be performed. */
4902 static bool
4903 is_too_expensive (const char *pass)
4905 /* Trying to perform global optimizations on flow graphs which have
4906 a high connectivity will take a long time and is unlikely to be
4907 particularly useful.
4909 In normal circumstances a cfg should have about twice as many
4910 edges as blocks. But we do not want to punish small functions
4911 which have a couple switch statements. Rather than simply
4912 threshold the number of blocks, uses something with a more
4913 graceful degradation. */
4914 if (n_edges > 20000 + n_basic_blocks * 4)
4916 warning (OPT_Wdisabled_optimization,
4917 "%s: %d basic blocks and %d edges/basic block",
4918 pass, n_basic_blocks, n_edges / n_basic_blocks);
4920 return true;
4923 /* If allocating memory for the cprop bitmap would take up too much
4924 storage it's better just to disable the optimization. */
4925 if ((n_basic_blocks
4926 * SBITMAP_SET_SIZE (max_reg_num ())
4927 * sizeof (SBITMAP_ELT_TYPE)) > MAX_GCSE_MEMORY)
4929 warning (OPT_Wdisabled_optimization,
4930 "%s: %d basic blocks and %d registers",
4931 pass, n_basic_blocks, max_reg_num ());
4933 return true;
4936 return false;
4940 /* Main function for the CPROP pass. */
4942 static int
4943 one_cprop_pass (void)
4945 int changed = 0;
4947 /* Return if there's nothing to do, or it is too expensive. */
4948 if (n_basic_blocks <= NUM_FIXED_BLOCKS + 1
4949 || is_too_expensive (_ ("const/copy propagation disabled")))
4950 return 0;
4952 global_const_prop_count = local_const_prop_count = 0;
4953 global_copy_prop_count = local_copy_prop_count = 0;
4955 bytes_used = 0;
4956 gcc_obstack_init (&gcse_obstack);
4957 alloc_gcse_mem ();
4959 /* Do a local const/copy propagation pass first. The global pass
4960 only handles global opportunities.
4961 If the local pass changes something, remove any unreachable blocks
4962 because the CPROP global dataflow analysis may get into infinite
4963 loops for CFGs with unreachable blocks.
4965 FIXME: This local pass should not be necessary after CSE (but for
4966 some reason it still is). It is also (proven) not necessary
4967 to run the local pass right after FWPWOP.
4969 FIXME: The global analysis would not get into infinite loops if it
4970 would use the DF solver (via df_simple_dataflow) instead of
4971 the solver implemented in this file. */
4972 if (local_cprop_pass ())
4974 delete_unreachable_blocks ();
4975 df_analyze ();
4978 /* Determine implicit sets. */
4979 implicit_sets = XCNEWVEC (rtx, last_basic_block);
4980 find_implicit_sets ();
4982 alloc_hash_table (&set_hash_table, 1);
4983 compute_hash_table (&set_hash_table);
4985 /* Free implicit_sets before peak usage. */
4986 free (implicit_sets);
4987 implicit_sets = NULL;
4989 if (dump_file)
4990 dump_hash_table (dump_file, "SET", &set_hash_table);
4991 if (set_hash_table.n_elems > 0)
4993 basic_block bb;
4994 rtx insn;
4996 alloc_cprop_mem (last_basic_block, set_hash_table.n_elems);
4997 compute_cprop_data ();
4999 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR->next_bb->next_bb, EXIT_BLOCK_PTR, next_bb)
5001 /* Reset tables used to keep track of what's still valid [since
5002 the start of the block]. */
5003 reset_opr_set_tables ();
5005 FOR_BB_INSNS (bb, insn)
5006 if (INSN_P (insn))
5008 changed |= cprop_insn (insn);
5010 /* Keep track of everything modified by this insn. */
5011 /* ??? Need to be careful w.r.t. mods done to INSN.
5012 Don't call mark_oprs_set if we turned the
5013 insn into a NOTE. */
5014 if (! NOTE_P (insn))
5015 mark_oprs_set (insn);
5019 changed |= bypass_conditional_jumps ();
5020 free_cprop_mem ();
5023 free_hash_table (&set_hash_table);
5024 free_gcse_mem ();
5025 obstack_free (&gcse_obstack, NULL);
5027 if (dump_file)
5029 fprintf (dump_file, "CPROP of %s, %d basic blocks, %d bytes needed, ",
5030 current_function_name (), n_basic_blocks, bytes_used);
5031 fprintf (dump_file, "%d local const props, %d local copy props, ",
5032 local_const_prop_count, local_copy_prop_count);
5033 fprintf (dump_file, "%d global const props, %d global copy props\n\n",
5034 global_const_prop_count, global_copy_prop_count);
5037 return changed;
5041 /* All the passes implemented in this file. Each pass has its
5042 own gate and execute function, and at the end of the file a
5043 pass definition for passes.c.
5045 We do not construct an accurate cfg in functions which call
5046 setjmp, so none of these passes runs if the function calls
5047 setjmp.
5048 FIXME: Should just handle setjmp via REG_SETJMP notes. */
5050 static bool
5051 gate_rtl_cprop (void)
5053 return optimize > 0 && flag_gcse
5054 && !cfun->calls_setjmp
5055 && dbg_cnt (cprop);
5058 static unsigned int
5059 execute_rtl_cprop (void)
5061 delete_unreachable_blocks ();
5062 df_set_flags (DF_LR_RUN_DCE);
5063 df_analyze ();
5064 flag_rerun_cse_after_global_opts |= one_cprop_pass ();
5065 return 0;
5068 static bool
5069 gate_rtl_pre (void)
5071 return optimize > 0 && flag_gcse
5072 && !cfun->calls_setjmp
5073 && optimize_function_for_speed_p (cfun)
5074 && dbg_cnt (pre);
5077 static unsigned int
5078 execute_rtl_pre (void)
5080 delete_unreachable_blocks ();
5081 df_analyze ();
5082 flag_rerun_cse_after_global_opts |= one_pre_gcse_pass ();
5083 return 0;
5086 static bool
5087 gate_rtl_hoist (void)
5089 return optimize > 0 && flag_gcse
5090 && !cfun->calls_setjmp
5091 /* It does not make sense to run code hoisting unless we are optimizing
5092 for code size -- it rarely makes programs faster, and can make then
5093 bigger if we did PRE (when optimizing for space, we don't run PRE). */
5094 && optimize_function_for_size_p (cfun)
5095 && dbg_cnt (hoist);
5098 static unsigned int
5099 execute_rtl_hoist (void)
5101 delete_unreachable_blocks ();
5102 df_analyze ();
5103 flag_rerun_cse_after_global_opts |= one_code_hoisting_pass ();
5104 return 0;
5107 struct rtl_opt_pass pass_rtl_cprop =
5110 RTL_PASS,
5111 "cprop", /* name */
5112 gate_rtl_cprop, /* gate */
5113 execute_rtl_cprop, /* execute */
5114 NULL, /* sub */
5115 NULL, /* next */
5116 0, /* static_pass_number */
5117 TV_CPROP, /* tv_id */
5118 PROP_cfglayout, /* properties_required */
5119 0, /* properties_provided */
5120 0, /* properties_destroyed */
5121 0, /* todo_flags_start */
5122 TODO_df_finish | TODO_verify_rtl_sharing |
5123 TODO_dump_func |
5124 TODO_verify_flow | TODO_ggc_collect /* todo_flags_finish */
5128 struct rtl_opt_pass pass_rtl_pre =
5131 RTL_PASS,
5132 "rtl pre", /* name */
5133 gate_rtl_pre, /* gate */
5134 execute_rtl_pre, /* execute */
5135 NULL, /* sub */
5136 NULL, /* next */
5137 0, /* static_pass_number */
5138 TV_PRE, /* tv_id */
5139 PROP_cfglayout, /* properties_required */
5140 0, /* properties_provided */
5141 0, /* properties_destroyed */
5142 0, /* todo_flags_start */
5143 TODO_df_finish | TODO_verify_rtl_sharing |
5144 TODO_dump_func |
5145 TODO_verify_flow | TODO_ggc_collect /* todo_flags_finish */
5149 struct rtl_opt_pass pass_rtl_hoist =
5152 RTL_PASS,
5153 "hoist", /* name */
5154 gate_rtl_hoist, /* gate */
5155 execute_rtl_hoist, /* execute */
5156 NULL, /* sub */
5157 NULL, /* next */
5158 0, /* static_pass_number */
5159 TV_HOIST, /* tv_id */
5160 PROP_cfglayout, /* properties_required */
5161 0, /* properties_provided */
5162 0, /* properties_destroyed */
5163 0, /* todo_flags_start */
5164 TODO_df_finish | TODO_verify_rtl_sharing |
5165 TODO_dump_func |
5166 TODO_verify_flow | TODO_ggc_collect /* todo_flags_finish */
5170 #include "gt-gcse.h"