* config/i386/gnu-user.h (TARGET_CAN_SPLIT_STACK): Move from here ...
[official-gcc.git] / gcc / postreload-gcse.c
blob1923e189c71a2ad2891b7cf6d0f12a91e4039c43
1 /* Post reload partially redundant load elimination
2 Copyright (C) 2004-2014 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "tm.h"
24 #include "diagnostic-core.h"
26 #include "hash-table.h"
27 #include "rtl.h"
28 #include "tree.h"
29 #include "tm_p.h"
30 #include "regs.h"
31 #include "hard-reg-set.h"
32 #include "flags.h"
33 #include "insn-config.h"
34 #include "recog.h"
35 #include "predict.h"
36 #include "vec.h"
37 #include "hashtab.h"
38 #include "hash-set.h"
39 #include "machmode.h"
40 #include "input.h"
41 #include "function.h"
42 #include "dominance.h"
43 #include "cfg.h"
44 #include "cfgrtl.h"
45 #include "basic-block.h"
46 #include "profile.h"
47 #include "expr.h"
48 #include "except.h"
49 #include "intl.h"
50 #include "obstack.h"
51 #include "params.h"
52 #include "target.h"
53 #include "tree-pass.h"
54 #include "dbgcnt.h"
56 /* The following code implements gcse after reload, the purpose of this
57 pass is to cleanup redundant loads generated by reload and other
58 optimizations that come after gcse. It searches for simple inter-block
59 redundancies and tries to eliminate them by adding moves and loads
60 in cold places.
62 Perform partially redundant load elimination, try to eliminate redundant
63 loads created by the reload pass. We try to look for full or partial
64 redundant loads fed by one or more loads/stores in predecessor BBs,
65 and try adding loads to make them fully redundant. We also check if
66 it's worth adding loads to be able to delete the redundant load.
68 Algorithm:
69 1. Build available expressions hash table:
70 For each load/store instruction, if the loaded/stored memory didn't
71 change until the end of the basic block add this memory expression to
72 the hash table.
73 2. Perform Redundancy elimination:
74 For each load instruction do the following:
75 perform partial redundancy elimination, check if it's worth adding
76 loads to make the load fully redundant. If so add loads and
77 register copies and delete the load.
78 3. Delete instructions made redundant in step 2.
80 Future enhancement:
81 If the loaded register is used/defined between load and some store,
82 look for some other free register between load and all its stores,
83 and replace the load with a copy from this register to the loaded
84 register.
88 /* Keep statistics of this pass. */
89 static struct
91 int moves_inserted;
92 int copies_inserted;
93 int insns_deleted;
94 } stats;
96 /* We need to keep a hash table of expressions. The table entries are of
97 type 'struct expr', and for each expression there is a single linked
98 list of occurrences. */
100 /* Expression elements in the hash table. */
101 struct expr
103 /* The expression (SET_SRC for expressions, PATTERN for assignments). */
104 rtx expr;
106 /* The same hash for this entry. */
107 hashval_t hash;
109 /* List of available occurrence in basic blocks in the function. */
110 struct occr *avail_occr;
113 /* Hashtable helpers. */
115 struct expr_hasher : typed_noop_remove <expr>
117 typedef expr value_type;
118 typedef expr compare_type;
119 static inline hashval_t hash (const value_type *);
120 static inline bool equal (const value_type *, const compare_type *);
124 /* Hash expression X.
125 DO_NOT_RECORD_P is a boolean indicating if a volatile operand is found
126 or if the expression contains something we don't want to insert in the
127 table. */
129 static hashval_t
130 hash_expr (rtx x, int *do_not_record_p)
132 *do_not_record_p = 0;
133 return hash_rtx (x, GET_MODE (x), do_not_record_p,
134 NULL, /*have_reg_qty=*/false);
137 /* Callback for hashtab.
138 Return the hash value for expression EXP. We don't actually hash
139 here, we just return the cached hash value. */
141 inline hashval_t
142 expr_hasher::hash (const value_type *exp)
144 return exp->hash;
147 /* Callback for hashtab.
148 Return nonzero if exp1 is equivalent to exp2. */
150 inline bool
151 expr_hasher::equal (const value_type *exp1, const compare_type *exp2)
153 int equiv_p = exp_equiv_p (exp1->expr, exp2->expr, 0, true);
155 gcc_assert (!equiv_p || exp1->hash == exp2->hash);
156 return equiv_p;
159 /* The table itself. */
160 static hash_table<expr_hasher> *expr_table;
163 static struct obstack expr_obstack;
165 /* Occurrence of an expression.
166 There is at most one occurrence per basic block. If a pattern appears
167 more than once, the last appearance is used. */
169 struct occr
171 /* Next occurrence of this expression. */
172 struct occr *next;
173 /* The insn that computes the expression. */
174 rtx_insn *insn;
175 /* Nonzero if this [anticipatable] occurrence has been deleted. */
176 char deleted_p;
179 static struct obstack occr_obstack;
181 /* The following structure holds the information about the occurrences of
182 the redundant instructions. */
183 struct unoccr
185 struct unoccr *next;
186 edge pred;
187 rtx_insn *insn;
190 static struct obstack unoccr_obstack;
192 /* Array where each element is the CUID if the insn that last set the hard
193 register with the number of the element, since the start of the current
194 basic block.
196 This array is used during the building of the hash table (step 1) to
197 determine if a reg is killed before the end of a basic block.
199 It is also used when eliminating partial redundancies (step 2) to see
200 if a reg was modified since the start of a basic block. */
201 static int *reg_avail_info;
203 /* A list of insns that may modify memory within the current basic block. */
204 struct modifies_mem
206 rtx_insn *insn;
207 struct modifies_mem *next;
209 static struct modifies_mem *modifies_mem_list;
211 /* The modifies_mem structs also go on an obstack, only this obstack is
212 freed each time after completing the analysis or transformations on
213 a basic block. So we allocate a dummy modifies_mem_obstack_bottom
214 object on the obstack to keep track of the bottom of the obstack. */
215 static struct obstack modifies_mem_obstack;
216 static struct modifies_mem *modifies_mem_obstack_bottom;
218 /* Mapping of insn UIDs to CUIDs.
219 CUIDs are like UIDs except they increase monotonically in each basic
220 block, have no gaps, and only apply to real insns. */
221 static int *uid_cuid;
222 #define INSN_CUID(INSN) (uid_cuid[INSN_UID (INSN)])
225 /* Helpers for memory allocation/freeing. */
226 static void alloc_mem (void);
227 static void free_mem (void);
229 /* Support for hash table construction and transformations. */
230 static bool oprs_unchanged_p (rtx, rtx_insn *, bool);
231 static void record_last_reg_set_info (rtx_insn *, rtx);
232 static void record_last_reg_set_info_regno (rtx_insn *, int);
233 static void record_last_mem_set_info (rtx_insn *);
234 static void record_last_set_info (rtx, const_rtx, void *);
235 static void record_opr_changes (rtx_insn *);
237 static void find_mem_conflicts (rtx, const_rtx, void *);
238 static int load_killed_in_block_p (int, rtx, bool);
239 static void reset_opr_set_tables (void);
241 /* Hash table support. */
242 static hashval_t hash_expr (rtx, int *);
243 static void insert_expr_in_table (rtx, rtx_insn *);
244 static struct expr *lookup_expr_in_table (rtx);
245 static void dump_hash_table (FILE *);
247 /* Helpers for eliminate_partially_redundant_load. */
248 static bool reg_killed_on_edge (rtx, edge);
249 static bool reg_used_on_edge (rtx, edge);
251 static rtx get_avail_load_store_reg (rtx_insn *);
253 static bool bb_has_well_behaved_predecessors (basic_block);
254 static struct occr* get_bb_avail_insn (basic_block, struct occr *);
255 static void hash_scan_set (rtx_insn *);
256 static void compute_hash_table (void);
258 /* The work horses of this pass. */
259 static void eliminate_partially_redundant_load (basic_block,
260 rtx_insn *,
261 struct expr *);
262 static void eliminate_partially_redundant_loads (void);
265 /* Allocate memory for the CUID mapping array and register/memory
266 tracking tables. */
268 static void
269 alloc_mem (void)
271 int i;
272 basic_block bb;
273 rtx_insn *insn;
275 /* Find the largest UID and create a mapping from UIDs to CUIDs. */
276 uid_cuid = XCNEWVEC (int, get_max_uid () + 1);
277 i = 1;
278 FOR_EACH_BB_FN (bb, cfun)
279 FOR_BB_INSNS (bb, insn)
281 if (INSN_P (insn))
282 uid_cuid[INSN_UID (insn)] = i++;
283 else
284 uid_cuid[INSN_UID (insn)] = i;
287 /* Allocate the available expressions hash table. We don't want to
288 make the hash table too small, but unnecessarily making it too large
289 also doesn't help. The i/4 is a gcse.c relic, and seems like a
290 reasonable choice. */
291 expr_table = new hash_table<expr_hasher> (MAX (i / 4, 13));
293 /* We allocate everything on obstacks because we often can roll back
294 the whole obstack to some point. Freeing obstacks is very fast. */
295 gcc_obstack_init (&expr_obstack);
296 gcc_obstack_init (&occr_obstack);
297 gcc_obstack_init (&unoccr_obstack);
298 gcc_obstack_init (&modifies_mem_obstack);
300 /* Working array used to track the last set for each register
301 in the current block. */
302 reg_avail_info = (int *) xmalloc (FIRST_PSEUDO_REGISTER * sizeof (int));
304 /* Put a dummy modifies_mem object on the modifies_mem_obstack, so we
305 can roll it back in reset_opr_set_tables. */
306 modifies_mem_obstack_bottom =
307 (struct modifies_mem *) obstack_alloc (&modifies_mem_obstack,
308 sizeof (struct modifies_mem));
311 /* Free memory allocated by alloc_mem. */
313 static void
314 free_mem (void)
316 free (uid_cuid);
318 delete expr_table;
319 expr_table = NULL;
321 obstack_free (&expr_obstack, NULL);
322 obstack_free (&occr_obstack, NULL);
323 obstack_free (&unoccr_obstack, NULL);
324 obstack_free (&modifies_mem_obstack, NULL);
326 free (reg_avail_info);
330 /* Insert expression X in INSN in the hash TABLE.
331 If it is already present, record it as the last occurrence in INSN's
332 basic block. */
334 static void
335 insert_expr_in_table (rtx x, rtx_insn *insn)
337 int do_not_record_p;
338 hashval_t hash;
339 struct expr *cur_expr, **slot;
340 struct occr *avail_occr, *last_occr = NULL;
342 hash = hash_expr (x, &do_not_record_p);
344 /* Do not insert expression in the table if it contains volatile operands,
345 or if hash_expr determines the expression is something we don't want
346 to or can't handle. */
347 if (do_not_record_p)
348 return;
350 /* We anticipate that redundant expressions are rare, so for convenience
351 allocate a new hash table element here already and set its fields.
352 If we don't do this, we need a hack with a static struct expr. Anyway,
353 obstack_free is really fast and one more obstack_alloc doesn't hurt if
354 we're going to see more expressions later on. */
355 cur_expr = (struct expr *) obstack_alloc (&expr_obstack,
356 sizeof (struct expr));
357 cur_expr->expr = x;
358 cur_expr->hash = hash;
359 cur_expr->avail_occr = NULL;
361 slot = expr_table->find_slot_with_hash (cur_expr, hash, INSERT);
363 if (! (*slot))
364 /* The expression isn't found, so insert it. */
365 *slot = cur_expr;
366 else
368 /* The expression is already in the table, so roll back the
369 obstack and use the existing table entry. */
370 obstack_free (&expr_obstack, cur_expr);
371 cur_expr = *slot;
374 /* Search for another occurrence in the same basic block. */
375 avail_occr = cur_expr->avail_occr;
376 while (avail_occr
377 && BLOCK_FOR_INSN (avail_occr->insn) != BLOCK_FOR_INSN (insn))
379 /* If an occurrence isn't found, save a pointer to the end of
380 the list. */
381 last_occr = avail_occr;
382 avail_occr = avail_occr->next;
385 if (avail_occr)
386 /* Found another instance of the expression in the same basic block.
387 Prefer this occurrence to the currently recorded one. We want
388 the last one in the block and the block is scanned from start
389 to end. */
390 avail_occr->insn = insn;
391 else
393 /* First occurrence of this expression in this basic block. */
394 avail_occr = (struct occr *) obstack_alloc (&occr_obstack,
395 sizeof (struct occr));
397 /* First occurrence of this expression in any block? */
398 if (cur_expr->avail_occr == NULL)
399 cur_expr->avail_occr = avail_occr;
400 else
401 last_occr->next = avail_occr;
403 avail_occr->insn = insn;
404 avail_occr->next = NULL;
405 avail_occr->deleted_p = 0;
410 /* Lookup pattern PAT in the expression hash table.
411 The result is a pointer to the table entry, or NULL if not found. */
413 static struct expr *
414 lookup_expr_in_table (rtx pat)
416 int do_not_record_p;
417 struct expr **slot, *tmp_expr;
418 hashval_t hash = hash_expr (pat, &do_not_record_p);
420 if (do_not_record_p)
421 return NULL;
423 tmp_expr = (struct expr *) obstack_alloc (&expr_obstack,
424 sizeof (struct expr));
425 tmp_expr->expr = pat;
426 tmp_expr->hash = hash;
427 tmp_expr->avail_occr = NULL;
429 slot = expr_table->find_slot_with_hash (tmp_expr, hash, INSERT);
430 obstack_free (&expr_obstack, tmp_expr);
432 if (!slot)
433 return NULL;
434 else
435 return (*slot);
439 /* Dump all expressions and occurrences that are currently in the
440 expression hash table to FILE. */
442 /* This helper is called via htab_traverse. */
444 dump_expr_hash_table_entry (expr **slot, FILE *file)
446 struct expr *exprs = *slot;
447 struct occr *occr;
449 fprintf (file, "expr: ");
450 print_rtl (file, exprs->expr);
451 fprintf (file,"\nhashcode: %u\n", exprs->hash);
452 fprintf (file,"list of occurrences:\n");
453 occr = exprs->avail_occr;
454 while (occr)
456 rtx_insn *insn = occr->insn;
457 print_rtl_single (file, insn);
458 fprintf (file, "\n");
459 occr = occr->next;
461 fprintf (file, "\n");
462 return 1;
465 static void
466 dump_hash_table (FILE *file)
468 fprintf (file, "\n\nexpression hash table\n");
469 fprintf (file, "size %ld, %ld elements, %f collision/search ratio\n",
470 (long) expr_table->size (),
471 (long) expr_table->elements (),
472 expr_table->collisions ());
473 if (expr_table->elements () > 0)
475 fprintf (file, "\n\ntable entries:\n");
476 expr_table->traverse <FILE *, dump_expr_hash_table_entry> (file);
478 fprintf (file, "\n");
481 /* Return true if register X is recorded as being set by an instruction
482 whose CUID is greater than the one given. */
484 static bool
485 reg_changed_after_insn_p (rtx x, int cuid)
487 unsigned int regno, end_regno;
489 regno = REGNO (x);
490 end_regno = END_HARD_REGNO (x);
492 if (reg_avail_info[regno] > cuid)
493 return true;
494 while (++regno < end_regno);
495 return false;
498 /* Return nonzero if the operands of expression X are unchanged
499 1) from the start of INSN's basic block up to but not including INSN
500 if AFTER_INSN is false, or
501 2) from INSN to the end of INSN's basic block if AFTER_INSN is true. */
503 static bool
504 oprs_unchanged_p (rtx x, rtx_insn *insn, bool after_insn)
506 int i, j;
507 enum rtx_code code;
508 const char *fmt;
510 if (x == 0)
511 return 1;
513 code = GET_CODE (x);
514 switch (code)
516 case REG:
517 /* We are called after register allocation. */
518 gcc_assert (REGNO (x) < FIRST_PSEUDO_REGISTER);
519 if (after_insn)
520 return !reg_changed_after_insn_p (x, INSN_CUID (insn) - 1);
521 else
522 return !reg_changed_after_insn_p (x, 0);
524 case MEM:
525 if (load_killed_in_block_p (INSN_CUID (insn), x, after_insn))
526 return 0;
527 else
528 return oprs_unchanged_p (XEXP (x, 0), insn, after_insn);
530 case PC:
531 case CC0: /*FIXME*/
532 case CONST:
533 CASE_CONST_ANY:
534 case SYMBOL_REF:
535 case LABEL_REF:
536 case ADDR_VEC:
537 case ADDR_DIFF_VEC:
538 return 1;
540 case PRE_DEC:
541 case PRE_INC:
542 case POST_DEC:
543 case POST_INC:
544 case PRE_MODIFY:
545 case POST_MODIFY:
546 if (after_insn)
547 return 0;
548 break;
550 default:
551 break;
554 for (i = GET_RTX_LENGTH (code) - 1, fmt = GET_RTX_FORMAT (code); i >= 0; i--)
556 if (fmt[i] == 'e')
558 if (! oprs_unchanged_p (XEXP (x, i), insn, after_insn))
559 return 0;
561 else if (fmt[i] == 'E')
562 for (j = 0; j < XVECLEN (x, i); j++)
563 if (! oprs_unchanged_p (XVECEXP (x, i, j), insn, after_insn))
564 return 0;
567 return 1;
571 /* Used for communication between find_mem_conflicts and
572 load_killed_in_block_p. Nonzero if find_mem_conflicts finds a
573 conflict between two memory references.
574 This is a bit of a hack to work around the limitations of note_stores. */
575 static int mems_conflict_p;
577 /* DEST is the output of an instruction. If it is a memory reference, and
578 possibly conflicts with the load found in DATA, then set mems_conflict_p
579 to a nonzero value. */
581 static void
582 find_mem_conflicts (rtx dest, const_rtx setter ATTRIBUTE_UNUSED,
583 void *data)
585 rtx mem_op = (rtx) data;
587 while (GET_CODE (dest) == SUBREG
588 || GET_CODE (dest) == ZERO_EXTRACT
589 || GET_CODE (dest) == STRICT_LOW_PART)
590 dest = XEXP (dest, 0);
592 /* If DEST is not a MEM, then it will not conflict with the load. Note
593 that function calls are assumed to clobber memory, but are handled
594 elsewhere. */
595 if (! MEM_P (dest))
596 return;
598 if (true_dependence (dest, GET_MODE (dest), mem_op))
599 mems_conflict_p = 1;
603 /* Return nonzero if the expression in X (a memory reference) is killed
604 in the current basic block before (if AFTER_INSN is false) or after
605 (if AFTER_INSN is true) the insn with the CUID in UID_LIMIT.
607 This function assumes that the modifies_mem table is flushed when
608 the hash table construction or redundancy elimination phases start
609 processing a new basic block. */
611 static int
612 load_killed_in_block_p (int uid_limit, rtx x, bool after_insn)
614 struct modifies_mem *list_entry = modifies_mem_list;
616 while (list_entry)
618 rtx_insn *setter = list_entry->insn;
620 /* Ignore entries in the list that do not apply. */
621 if ((after_insn
622 && INSN_CUID (setter) < uid_limit)
623 || (! after_insn
624 && INSN_CUID (setter) > uid_limit))
626 list_entry = list_entry->next;
627 continue;
630 /* If SETTER is a call everything is clobbered. Note that calls
631 to pure functions are never put on the list, so we need not
632 worry about them. */
633 if (CALL_P (setter))
634 return 1;
636 /* SETTER must be an insn of some kind that sets memory. Call
637 note_stores to examine each hunk of memory that is modified.
638 It will set mems_conflict_p to nonzero if there may be a
639 conflict between X and SETTER. */
640 mems_conflict_p = 0;
641 note_stores (PATTERN (setter), find_mem_conflicts, x);
642 if (mems_conflict_p)
643 return 1;
645 list_entry = list_entry->next;
647 return 0;
651 /* Record register first/last/block set information for REGNO in INSN. */
653 static inline void
654 record_last_reg_set_info (rtx_insn *insn, rtx reg)
656 unsigned int regno, end_regno;
658 regno = REGNO (reg);
659 end_regno = END_HARD_REGNO (reg);
661 reg_avail_info[regno] = INSN_CUID (insn);
662 while (++regno < end_regno);
665 static inline void
666 record_last_reg_set_info_regno (rtx_insn *insn, int regno)
668 reg_avail_info[regno] = INSN_CUID (insn);
672 /* Record memory modification information for INSN. We do not actually care
673 about the memory location(s) that are set, or even how they are set (consider
674 a CALL_INSN). We merely need to record which insns modify memory. */
676 static void
677 record_last_mem_set_info (rtx_insn *insn)
679 struct modifies_mem *list_entry;
681 list_entry = (struct modifies_mem *) obstack_alloc (&modifies_mem_obstack,
682 sizeof (struct modifies_mem));
683 list_entry->insn = insn;
684 list_entry->next = modifies_mem_list;
685 modifies_mem_list = list_entry;
688 /* Called from compute_hash_table via note_stores to handle one
689 SET or CLOBBER in an insn. DATA is really the instruction in which
690 the SET is taking place. */
692 static void
693 record_last_set_info (rtx dest, const_rtx setter ATTRIBUTE_UNUSED, void *data)
695 rtx_insn *last_set_insn = (rtx_insn *) data;
697 if (GET_CODE (dest) == SUBREG)
698 dest = SUBREG_REG (dest);
700 if (REG_P (dest))
701 record_last_reg_set_info (last_set_insn, dest);
702 else if (MEM_P (dest))
704 /* Ignore pushes, they don't clobber memory. They may still
705 clobber the stack pointer though. Some targets do argument
706 pushes without adding REG_INC notes. See e.g. PR25196,
707 where a pushsi2 on i386 doesn't have REG_INC notes. Note
708 such changes here too. */
709 if (! push_operand (dest, GET_MODE (dest)))
710 record_last_mem_set_info (last_set_insn);
711 else
712 record_last_reg_set_info_regno (last_set_insn, STACK_POINTER_REGNUM);
717 /* Reset tables used to keep track of what's still available since the
718 start of the block. */
720 static void
721 reset_opr_set_tables (void)
723 memset (reg_avail_info, 0, FIRST_PSEUDO_REGISTER * sizeof (int));
724 obstack_free (&modifies_mem_obstack, modifies_mem_obstack_bottom);
725 modifies_mem_list = NULL;
729 /* Record things set by INSN.
730 This data is used by oprs_unchanged_p. */
732 static void
733 record_opr_changes (rtx_insn *insn)
735 rtx note;
737 /* Find all stores and record them. */
738 note_stores (PATTERN (insn), record_last_set_info, insn);
740 /* Also record autoincremented REGs for this insn as changed. */
741 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
742 if (REG_NOTE_KIND (note) == REG_INC)
743 record_last_reg_set_info (insn, XEXP (note, 0));
745 /* Finally, if this is a call, record all call clobbers. */
746 if (CALL_P (insn))
748 unsigned int regno;
749 rtx link, x;
750 hard_reg_set_iterator hrsi;
751 EXECUTE_IF_SET_IN_HARD_REG_SET (regs_invalidated_by_call, 0, regno, hrsi)
752 record_last_reg_set_info_regno (insn, regno);
754 for (link = CALL_INSN_FUNCTION_USAGE (insn); link; link = XEXP (link, 1))
755 if (GET_CODE (XEXP (link, 0)) == CLOBBER)
757 x = XEXP (XEXP (link, 0), 0);
758 if (REG_P (x))
760 gcc_assert (HARD_REGISTER_P (x));
761 record_last_reg_set_info (insn, x);
765 if (! RTL_CONST_OR_PURE_CALL_P (insn))
766 record_last_mem_set_info (insn);
771 /* Scan the pattern of INSN and add an entry to the hash TABLE.
772 After reload we are interested in loads/stores only. */
774 static void
775 hash_scan_set (rtx_insn *insn)
777 rtx pat = PATTERN (insn);
778 rtx src = SET_SRC (pat);
779 rtx dest = SET_DEST (pat);
781 /* We are only interested in loads and stores. */
782 if (! MEM_P (src) && ! MEM_P (dest))
783 return;
785 /* Don't mess with jumps and nops. */
786 if (JUMP_P (insn) || set_noop_p (pat))
787 return;
789 if (REG_P (dest))
791 if (/* Don't CSE something if we can't do a reg/reg copy. */
792 can_copy_p (GET_MODE (dest))
793 /* Is SET_SRC something we want to gcse? */
794 && general_operand (src, GET_MODE (src))
795 #ifdef STACK_REGS
796 /* Never consider insns touching the register stack. It may
797 create situations that reg-stack cannot handle (e.g. a stack
798 register live across an abnormal edge). */
799 && (REGNO (dest) < FIRST_STACK_REG || REGNO (dest) > LAST_STACK_REG)
800 #endif
801 /* An expression is not available if its operands are
802 subsequently modified, including this insn. */
803 && oprs_unchanged_p (src, insn, true))
805 insert_expr_in_table (src, insn);
808 else if (REG_P (src))
810 /* Only record sets of pseudo-regs in the hash table. */
811 if (/* Don't CSE something if we can't do a reg/reg copy. */
812 can_copy_p (GET_MODE (src))
813 /* Is SET_DEST something we want to gcse? */
814 && general_operand (dest, GET_MODE (dest))
815 #ifdef STACK_REGS
816 /* As above for STACK_REGS. */
817 && (REGNO (src) < FIRST_STACK_REG || REGNO (src) > LAST_STACK_REG)
818 #endif
819 && ! (flag_float_store && FLOAT_MODE_P (GET_MODE (dest)))
820 /* Check if the memory expression is killed after insn. */
821 && ! load_killed_in_block_p (INSN_CUID (insn) + 1, dest, true)
822 && oprs_unchanged_p (XEXP (dest, 0), insn, true))
824 insert_expr_in_table (dest, insn);
830 /* Create hash table of memory expressions available at end of basic
831 blocks. Basically you should think of this hash table as the
832 representation of AVAIL_OUT. This is the set of expressions that
833 is generated in a basic block and not killed before the end of the
834 same basic block. Notice that this is really a local computation. */
836 static void
837 compute_hash_table (void)
839 basic_block bb;
841 FOR_EACH_BB_FN (bb, cfun)
843 rtx_insn *insn;
845 /* First pass over the instructions records information used to
846 determine when registers and memory are last set.
847 Since we compute a "local" AVAIL_OUT, reset the tables that
848 help us keep track of what has been modified since the start
849 of the block. */
850 reset_opr_set_tables ();
851 FOR_BB_INSNS (bb, insn)
853 if (INSN_P (insn))
854 record_opr_changes (insn);
857 /* The next pass actually builds the hash table. */
858 FOR_BB_INSNS (bb, insn)
859 if (INSN_P (insn) && GET_CODE (PATTERN (insn)) == SET)
860 hash_scan_set (insn);
865 /* Check if register REG is killed in any insn waiting to be inserted on
866 edge E. This function is required to check that our data flow analysis
867 is still valid prior to commit_edge_insertions. */
869 static bool
870 reg_killed_on_edge (rtx reg, edge e)
872 rtx_insn *insn;
874 for (insn = e->insns.r; insn; insn = NEXT_INSN (insn))
875 if (INSN_P (insn) && reg_set_p (reg, insn))
876 return true;
878 return false;
881 /* Similar to above - check if register REG is used in any insn waiting
882 to be inserted on edge E.
883 Assumes no such insn can be a CALL_INSN; if so call reg_used_between_p
884 with PREV(insn),NEXT(insn) instead of calling reg_overlap_mentioned_p. */
886 static bool
887 reg_used_on_edge (rtx reg, edge e)
889 rtx_insn *insn;
891 for (insn = e->insns.r; insn; insn = NEXT_INSN (insn))
892 if (INSN_P (insn) && reg_overlap_mentioned_p (reg, PATTERN (insn)))
893 return true;
895 return false;
898 /* Return the loaded/stored register of a load/store instruction. */
900 static rtx
901 get_avail_load_store_reg (rtx_insn *insn)
903 if (REG_P (SET_DEST (PATTERN (insn))))
904 /* A load. */
905 return SET_DEST (PATTERN (insn));
906 else
908 /* A store. */
909 gcc_assert (REG_P (SET_SRC (PATTERN (insn))));
910 return SET_SRC (PATTERN (insn));
914 /* Return nonzero if the predecessors of BB are "well behaved". */
916 static bool
917 bb_has_well_behaved_predecessors (basic_block bb)
919 edge pred;
920 edge_iterator ei;
922 if (EDGE_COUNT (bb->preds) == 0)
923 return false;
925 FOR_EACH_EDGE (pred, ei, bb->preds)
927 if ((pred->flags & EDGE_ABNORMAL) && EDGE_CRITICAL_P (pred))
928 return false;
930 if ((pred->flags & EDGE_ABNORMAL_CALL) && cfun->has_nonlocal_label)
931 return false;
933 if (tablejump_p (BB_END (pred->src), NULL, NULL))
934 return false;
936 return true;
940 /* Search for the occurrences of expression in BB. */
942 static struct occr*
943 get_bb_avail_insn (basic_block bb, struct occr *occr)
945 for (; occr != NULL; occr = occr->next)
946 if (BLOCK_FOR_INSN (occr->insn) == bb)
947 return occr;
948 return NULL;
952 /* This handles the case where several stores feed a partially redundant
953 load. It checks if the redundancy elimination is possible and if it's
954 worth it.
956 Redundancy elimination is possible if,
957 1) None of the operands of an insn have been modified since the start
958 of the current basic block.
959 2) In any predecessor of the current basic block, the same expression
960 is generated.
962 See the function body for the heuristics that determine if eliminating
963 a redundancy is also worth doing, assuming it is possible. */
965 static void
966 eliminate_partially_redundant_load (basic_block bb, rtx_insn *insn,
967 struct expr *expr)
969 edge pred;
970 rtx_insn *avail_insn = NULL;
971 rtx avail_reg;
972 rtx dest, pat;
973 struct occr *a_occr;
974 struct unoccr *occr, *avail_occrs = NULL;
975 struct unoccr *unoccr, *unavail_occrs = NULL, *rollback_unoccr = NULL;
976 int npred_ok = 0;
977 gcov_type ok_count = 0; /* Redundant load execution count. */
978 gcov_type critical_count = 0; /* Execution count of critical edges. */
979 edge_iterator ei;
980 bool critical_edge_split = false;
982 /* The execution count of the loads to be added to make the
983 load fully redundant. */
984 gcov_type not_ok_count = 0;
985 basic_block pred_bb;
987 pat = PATTERN (insn);
988 dest = SET_DEST (pat);
990 /* Check that the loaded register is not used, set, or killed from the
991 beginning of the block. */
992 if (reg_changed_after_insn_p (dest, 0)
993 || reg_used_between_p (dest, PREV_INSN (BB_HEAD (bb)), insn))
994 return;
996 /* Check potential for replacing load with copy for predecessors. */
997 FOR_EACH_EDGE (pred, ei, bb->preds)
999 rtx_insn *next_pred_bb_end;
1001 avail_insn = NULL;
1002 avail_reg = NULL_RTX;
1003 pred_bb = pred->src;
1004 next_pred_bb_end = NEXT_INSN (BB_END (pred_bb));
1005 for (a_occr = get_bb_avail_insn (pred_bb, expr->avail_occr); a_occr;
1006 a_occr = get_bb_avail_insn (pred_bb, a_occr->next))
1008 /* Check if the loaded register is not used. */
1009 avail_insn = a_occr->insn;
1010 avail_reg = get_avail_load_store_reg (avail_insn);
1011 gcc_assert (avail_reg);
1013 /* Make sure we can generate a move from register avail_reg to
1014 dest. */
1015 rtx_insn *move = as_a <rtx_insn *>
1016 (gen_move_insn (copy_rtx (dest), copy_rtx (avail_reg)));
1017 extract_insn (move);
1018 if (! constrain_operands (1, get_preferred_alternatives (insn,
1019 pred_bb))
1020 || reg_killed_on_edge (avail_reg, pred)
1021 || reg_used_on_edge (dest, pred))
1023 avail_insn = NULL;
1024 continue;
1026 if (!reg_set_between_p (avail_reg, avail_insn, next_pred_bb_end))
1027 /* AVAIL_INSN remains non-null. */
1028 break;
1029 else
1030 avail_insn = NULL;
1033 if (EDGE_CRITICAL_P (pred))
1034 critical_count += pred->count;
1036 if (avail_insn != NULL_RTX)
1038 npred_ok++;
1039 ok_count += pred->count;
1040 if (! set_noop_p (PATTERN (gen_move_insn (copy_rtx (dest),
1041 copy_rtx (avail_reg)))))
1043 /* Check if there is going to be a split. */
1044 if (EDGE_CRITICAL_P (pred))
1045 critical_edge_split = true;
1047 else /* Its a dead move no need to generate. */
1048 continue;
1049 occr = (struct unoccr *) obstack_alloc (&unoccr_obstack,
1050 sizeof (struct unoccr));
1051 occr->insn = avail_insn;
1052 occr->pred = pred;
1053 occr->next = avail_occrs;
1054 avail_occrs = occr;
1055 if (! rollback_unoccr)
1056 rollback_unoccr = occr;
1058 else
1060 /* Adding a load on a critical edge will cause a split. */
1061 if (EDGE_CRITICAL_P (pred))
1062 critical_edge_split = true;
1063 not_ok_count += pred->count;
1064 unoccr = (struct unoccr *) obstack_alloc (&unoccr_obstack,
1065 sizeof (struct unoccr));
1066 unoccr->insn = NULL;
1067 unoccr->pred = pred;
1068 unoccr->next = unavail_occrs;
1069 unavail_occrs = unoccr;
1070 if (! rollback_unoccr)
1071 rollback_unoccr = unoccr;
1075 if (/* No load can be replaced by copy. */
1076 npred_ok == 0
1077 /* Prevent exploding the code. */
1078 || (optimize_bb_for_size_p (bb) && npred_ok > 1)
1079 /* If we don't have profile information we cannot tell if splitting
1080 a critical edge is profitable or not so don't do it. */
1081 || ((! profile_info || ! flag_branch_probabilities
1082 || targetm.cannot_modify_jumps_p ())
1083 && critical_edge_split))
1084 goto cleanup;
1086 /* Check if it's worth applying the partial redundancy elimination. */
1087 if (ok_count < GCSE_AFTER_RELOAD_PARTIAL_FRACTION * not_ok_count)
1088 goto cleanup;
1089 if (ok_count < GCSE_AFTER_RELOAD_CRITICAL_FRACTION * critical_count)
1090 goto cleanup;
1092 /* Generate moves to the loaded register from where
1093 the memory is available. */
1094 for (occr = avail_occrs; occr; occr = occr->next)
1096 avail_insn = occr->insn;
1097 pred = occr->pred;
1098 /* Set avail_reg to be the register having the value of the
1099 memory. */
1100 avail_reg = get_avail_load_store_reg (avail_insn);
1101 gcc_assert (avail_reg);
1103 insert_insn_on_edge (gen_move_insn (copy_rtx (dest),
1104 copy_rtx (avail_reg)),
1105 pred);
1106 stats.moves_inserted++;
1108 if (dump_file)
1109 fprintf (dump_file,
1110 "generating move from %d to %d on edge from %d to %d\n",
1111 REGNO (avail_reg),
1112 REGNO (dest),
1113 pred->src->index,
1114 pred->dest->index);
1117 /* Regenerate loads where the memory is unavailable. */
1118 for (unoccr = unavail_occrs; unoccr; unoccr = unoccr->next)
1120 pred = unoccr->pred;
1121 insert_insn_on_edge (copy_insn (PATTERN (insn)), pred);
1122 stats.copies_inserted++;
1124 if (dump_file)
1126 fprintf (dump_file,
1127 "generating on edge from %d to %d a copy of load: ",
1128 pred->src->index,
1129 pred->dest->index);
1130 print_rtl (dump_file, PATTERN (insn));
1131 fprintf (dump_file, "\n");
1135 /* Delete the insn if it is not available in this block and mark it
1136 for deletion if it is available. If insn is available it may help
1137 discover additional redundancies, so mark it for later deletion. */
1138 for (a_occr = get_bb_avail_insn (bb, expr->avail_occr);
1139 a_occr && (a_occr->insn != insn);
1140 a_occr = get_bb_avail_insn (bb, a_occr->next))
1143 if (!a_occr)
1145 stats.insns_deleted++;
1147 if (dump_file)
1149 fprintf (dump_file, "deleting insn:\n");
1150 print_rtl_single (dump_file, insn);
1151 fprintf (dump_file, "\n");
1153 delete_insn (insn);
1155 else
1156 a_occr->deleted_p = 1;
1158 cleanup:
1159 if (rollback_unoccr)
1160 obstack_free (&unoccr_obstack, rollback_unoccr);
1163 /* Performing the redundancy elimination as described before. */
1165 static void
1166 eliminate_partially_redundant_loads (void)
1168 rtx_insn *insn;
1169 basic_block bb;
1171 /* Note we start at block 1. */
1173 if (ENTRY_BLOCK_PTR_FOR_FN (cfun)->next_bb == EXIT_BLOCK_PTR_FOR_FN (cfun))
1174 return;
1176 FOR_BB_BETWEEN (bb,
1177 ENTRY_BLOCK_PTR_FOR_FN (cfun)->next_bb->next_bb,
1178 EXIT_BLOCK_PTR_FOR_FN (cfun),
1179 next_bb)
1181 /* Don't try anything on basic blocks with strange predecessors. */
1182 if (! bb_has_well_behaved_predecessors (bb))
1183 continue;
1185 /* Do not try anything on cold basic blocks. */
1186 if (optimize_bb_for_size_p (bb))
1187 continue;
1189 /* Reset the table of things changed since the start of the current
1190 basic block. */
1191 reset_opr_set_tables ();
1193 /* Look at all insns in the current basic block and see if there are
1194 any loads in it that we can record. */
1195 FOR_BB_INSNS (bb, insn)
1197 /* Is it a load - of the form (set (reg) (mem))? */
1198 if (NONJUMP_INSN_P (insn)
1199 && GET_CODE (PATTERN (insn)) == SET
1200 && REG_P (SET_DEST (PATTERN (insn)))
1201 && MEM_P (SET_SRC (PATTERN (insn))))
1203 rtx pat = PATTERN (insn);
1204 rtx src = SET_SRC (pat);
1205 struct expr *expr;
1207 if (!MEM_VOLATILE_P (src)
1208 && GET_MODE (src) != BLKmode
1209 && general_operand (src, GET_MODE (src))
1210 /* Are the operands unchanged since the start of the
1211 block? */
1212 && oprs_unchanged_p (src, insn, false)
1213 && !(cfun->can_throw_non_call_exceptions && may_trap_p (src))
1214 && !side_effects_p (src)
1215 /* Is the expression recorded? */
1216 && (expr = lookup_expr_in_table (src)) != NULL)
1218 /* We now have a load (insn) and an available memory at
1219 its BB start (expr). Try to remove the loads if it is
1220 redundant. */
1221 eliminate_partially_redundant_load (bb, insn, expr);
1225 /* Keep track of everything modified by this insn, so that we
1226 know what has been modified since the start of the current
1227 basic block. */
1228 if (INSN_P (insn))
1229 record_opr_changes (insn);
1233 commit_edge_insertions ();
1236 /* Go over the expression hash table and delete insns that were
1237 marked for later deletion. */
1239 /* This helper is called via htab_traverse. */
1241 delete_redundant_insns_1 (expr **slot, void *data ATTRIBUTE_UNUSED)
1243 struct expr *exprs = *slot;
1244 struct occr *occr;
1246 for (occr = exprs->avail_occr; occr != NULL; occr = occr->next)
1248 if (occr->deleted_p && dbg_cnt (gcse2_delete))
1250 delete_insn (occr->insn);
1251 stats.insns_deleted++;
1253 if (dump_file)
1255 fprintf (dump_file, "deleting insn:\n");
1256 print_rtl_single (dump_file, occr->insn);
1257 fprintf (dump_file, "\n");
1262 return 1;
1265 static void
1266 delete_redundant_insns (void)
1268 expr_table->traverse <void *, delete_redundant_insns_1> (NULL);
1269 if (dump_file)
1270 fprintf (dump_file, "\n");
1273 /* Main entry point of the GCSE after reload - clean some redundant loads
1274 due to spilling. */
1276 static void
1277 gcse_after_reload_main (rtx f ATTRIBUTE_UNUSED)
1280 memset (&stats, 0, sizeof (stats));
1282 /* Allocate memory for this pass.
1283 Also computes and initializes the insns' CUIDs. */
1284 alloc_mem ();
1286 /* We need alias analysis. */
1287 init_alias_analysis ();
1289 compute_hash_table ();
1291 if (dump_file)
1292 dump_hash_table (dump_file);
1294 if (expr_table->elements () > 0)
1296 eliminate_partially_redundant_loads ();
1297 delete_redundant_insns ();
1299 if (dump_file)
1301 fprintf (dump_file, "GCSE AFTER RELOAD stats:\n");
1302 fprintf (dump_file, "copies inserted: %d\n", stats.copies_inserted);
1303 fprintf (dump_file, "moves inserted: %d\n", stats.moves_inserted);
1304 fprintf (dump_file, "insns deleted: %d\n", stats.insns_deleted);
1305 fprintf (dump_file, "\n\n");
1308 statistics_counter_event (cfun, "copies inserted",
1309 stats.copies_inserted);
1310 statistics_counter_event (cfun, "moves inserted",
1311 stats.moves_inserted);
1312 statistics_counter_event (cfun, "insns deleted",
1313 stats.insns_deleted);
1316 /* We are finished with alias. */
1317 end_alias_analysis ();
1319 free_mem ();
1324 static unsigned int
1325 rest_of_handle_gcse2 (void)
1327 gcse_after_reload_main (get_insns ());
1328 rebuild_jump_labels (get_insns ());
1329 return 0;
1332 namespace {
1334 const pass_data pass_data_gcse2 =
1336 RTL_PASS, /* type */
1337 "gcse2", /* name */
1338 OPTGROUP_NONE, /* optinfo_flags */
1339 TV_GCSE_AFTER_RELOAD, /* tv_id */
1340 0, /* properties_required */
1341 0, /* properties_provided */
1342 0, /* properties_destroyed */
1343 0, /* todo_flags_start */
1344 0, /* todo_flags_finish */
1347 class pass_gcse2 : public rtl_opt_pass
1349 public:
1350 pass_gcse2 (gcc::context *ctxt)
1351 : rtl_opt_pass (pass_data_gcse2, ctxt)
1354 /* opt_pass methods: */
1355 virtual bool gate (function *fun)
1357 return (optimize > 0 && flag_gcse_after_reload
1358 && optimize_function_for_speed_p (fun));
1361 virtual unsigned int execute (function *) { return rest_of_handle_gcse2 (); }
1363 }; // class pass_gcse2
1365 } // anon namespace
1367 rtl_opt_pass *
1368 make_pass_gcse2 (gcc::context *ctxt)
1370 return new pass_gcse2 (ctxt);