2016-10-04 Richard Biener <rguenther@suse.de>
[official-gcc.git] / gcc / loop-invariant.c
blobd550a841d0695b9b55344e1655f6f9f3f79f1976
1 /* RTL-level loop invariant motion.
2 Copyright (C) 2004-2016 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 3, or (at your option) any
9 later version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT
12 ANY 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 /* This implements the loop invariant motion pass. It is very simple
21 (no calls, no loads/stores, etc.). This should be sufficient to cleanup
22 things like address arithmetics -- other more complicated invariants should
23 be eliminated on GIMPLE either in tree-ssa-loop-im.c or in tree-ssa-pre.c.
25 We proceed loop by loop -- it is simpler than trying to handle things
26 globally and should not lose much. First we inspect all sets inside loop
27 and create a dependency graph on insns (saying "to move this insn, you must
28 also move the following insns").
30 We then need to determine what to move. We estimate the number of registers
31 used and move as many invariants as possible while we still have enough free
32 registers. We prefer the expensive invariants.
34 Then we move the selected invariants out of the loop, creating a new
35 temporaries for them if necessary. */
37 #include "config.h"
38 #include "system.h"
39 #include "coretypes.h"
40 #include "backend.h"
41 #include "target.h"
42 #include "rtl.h"
43 #include "tree.h"
44 #include "cfghooks.h"
45 #include "df.h"
46 #include "tm_p.h"
47 #include "insn-config.h"
48 #include "regs.h"
49 #include "ira.h"
50 #include "recog.h"
51 #include "cfgrtl.h"
52 #include "cfgloop.h"
53 #include "expr.h"
54 #include "params.h"
55 #include "rtl-iter.h"
56 #include "dumpfile.h"
58 /* The data stored for the loop. */
60 struct loop_data
62 struct loop *outermost_exit; /* The outermost exit of the loop. */
63 bool has_call; /* True if the loop contains a call. */
64 /* Maximal register pressure inside loop for given register class
65 (defined only for the pressure classes). */
66 int max_reg_pressure[N_REG_CLASSES];
67 /* Loop regs referenced and live pseudo-registers. */
68 bitmap_head regs_ref;
69 bitmap_head regs_live;
72 #define LOOP_DATA(LOOP) ((struct loop_data *) (LOOP)->aux)
74 /* The description of an use. */
76 struct use
78 rtx *pos; /* Position of the use. */
79 rtx_insn *insn; /* The insn in that the use occurs. */
80 unsigned addr_use_p; /* Whether the use occurs in an address. */
81 struct use *next; /* Next use in the list. */
84 /* The description of a def. */
86 struct def
88 struct use *uses; /* The list of uses that are uniquely reached
89 by it. */
90 unsigned n_uses; /* Number of such uses. */
91 unsigned n_addr_uses; /* Number of uses in addresses. */
92 unsigned invno; /* The corresponding invariant. */
93 bool can_prop_to_addr_uses; /* True if the corresponding inv can be
94 propagated into its address uses. */
97 /* The data stored for each invariant. */
99 struct invariant
101 /* The number of the invariant. */
102 unsigned invno;
104 /* The number of the invariant with the same value. */
105 unsigned eqto;
107 /* The number of invariants which eqto this. */
108 unsigned eqno;
110 /* If we moved the invariant out of the loop, the register that contains its
111 value. */
112 rtx reg;
114 /* If we moved the invariant out of the loop, the original regno
115 that contained its value. */
116 int orig_regno;
118 /* The definition of the invariant. */
119 struct def *def;
121 /* The insn in that it is defined. */
122 rtx_insn *insn;
124 /* Whether it is always executed. */
125 bool always_executed;
127 /* Whether to move the invariant. */
128 bool move;
130 /* Whether the invariant is cheap when used as an address. */
131 bool cheap_address;
133 /* Cost of the invariant. */
134 unsigned cost;
136 /* The invariants it depends on. */
137 bitmap depends_on;
139 /* Used for detecting already visited invariants during determining
140 costs of movements. */
141 unsigned stamp;
144 /* Currently processed loop. */
145 static struct loop *curr_loop;
147 /* Table of invariants indexed by the df_ref uid field. */
149 static unsigned int invariant_table_size = 0;
150 static struct invariant ** invariant_table;
152 /* Entry for hash table of invariant expressions. */
154 struct invariant_expr_entry
156 /* The invariant. */
157 struct invariant *inv;
159 /* Its value. */
160 rtx expr;
162 /* Its mode. */
163 machine_mode mode;
165 /* Its hash. */
166 hashval_t hash;
169 /* The actual stamp for marking already visited invariants during determining
170 costs of movements. */
172 static unsigned actual_stamp;
174 typedef struct invariant *invariant_p;
177 /* The invariants. */
179 static vec<invariant_p> invariants;
181 /* Check the size of the invariant table and realloc if necessary. */
183 static void
184 check_invariant_table_size (void)
186 if (invariant_table_size < DF_DEFS_TABLE_SIZE ())
188 unsigned int new_size = DF_DEFS_TABLE_SIZE () + (DF_DEFS_TABLE_SIZE () / 4);
189 invariant_table = XRESIZEVEC (struct invariant *, invariant_table, new_size);
190 memset (&invariant_table[invariant_table_size], 0,
191 (new_size - invariant_table_size) * sizeof (struct invariant *));
192 invariant_table_size = new_size;
196 /* Test for possibility of invariantness of X. */
198 static bool
199 check_maybe_invariant (rtx x)
201 enum rtx_code code = GET_CODE (x);
202 int i, j;
203 const char *fmt;
205 switch (code)
207 CASE_CONST_ANY:
208 case SYMBOL_REF:
209 case CONST:
210 case LABEL_REF:
211 return true;
213 case PC:
214 case CC0:
215 case UNSPEC_VOLATILE:
216 case CALL:
217 return false;
219 case REG:
220 return true;
222 case MEM:
223 /* Load/store motion is done elsewhere. ??? Perhaps also add it here?
224 It should not be hard, and might be faster than "elsewhere". */
226 /* Just handle the most trivial case where we load from an unchanging
227 location (most importantly, pic tables). */
228 if (MEM_READONLY_P (x) && !MEM_VOLATILE_P (x))
229 break;
231 return false;
233 case ASM_OPERANDS:
234 /* Don't mess with insns declared volatile. */
235 if (MEM_VOLATILE_P (x))
236 return false;
237 break;
239 default:
240 break;
243 fmt = GET_RTX_FORMAT (code);
244 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
246 if (fmt[i] == 'e')
248 if (!check_maybe_invariant (XEXP (x, i)))
249 return false;
251 else if (fmt[i] == 'E')
253 for (j = 0; j < XVECLEN (x, i); j++)
254 if (!check_maybe_invariant (XVECEXP (x, i, j)))
255 return false;
259 return true;
262 /* Returns the invariant definition for USE, or NULL if USE is not
263 invariant. */
265 static struct invariant *
266 invariant_for_use (df_ref use)
268 struct df_link *defs;
269 df_ref def;
270 basic_block bb = DF_REF_BB (use), def_bb;
272 if (DF_REF_FLAGS (use) & DF_REF_READ_WRITE)
273 return NULL;
275 defs = DF_REF_CHAIN (use);
276 if (!defs || defs->next)
277 return NULL;
278 def = defs->ref;
279 check_invariant_table_size ();
280 if (!invariant_table[DF_REF_ID (def)])
281 return NULL;
283 def_bb = DF_REF_BB (def);
284 if (!dominated_by_p (CDI_DOMINATORS, bb, def_bb))
285 return NULL;
286 return invariant_table[DF_REF_ID (def)];
289 /* Computes hash value for invariant expression X in INSN. */
291 static hashval_t
292 hash_invariant_expr_1 (rtx_insn *insn, rtx x)
294 enum rtx_code code = GET_CODE (x);
295 int i, j;
296 const char *fmt;
297 hashval_t val = code;
298 int do_not_record_p;
299 df_ref use;
300 struct invariant *inv;
302 switch (code)
304 CASE_CONST_ANY:
305 case SYMBOL_REF:
306 case CONST:
307 case LABEL_REF:
308 return hash_rtx (x, GET_MODE (x), &do_not_record_p, NULL, false);
310 case REG:
311 use = df_find_use (insn, x);
312 if (!use)
313 return hash_rtx (x, GET_MODE (x), &do_not_record_p, NULL, false);
314 inv = invariant_for_use (use);
315 if (!inv)
316 return hash_rtx (x, GET_MODE (x), &do_not_record_p, NULL, false);
318 gcc_assert (inv->eqto != ~0u);
319 return inv->eqto;
321 default:
322 break;
325 fmt = GET_RTX_FORMAT (code);
326 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
328 if (fmt[i] == 'e')
329 val ^= hash_invariant_expr_1 (insn, XEXP (x, i));
330 else if (fmt[i] == 'E')
332 for (j = 0; j < XVECLEN (x, i); j++)
333 val ^= hash_invariant_expr_1 (insn, XVECEXP (x, i, j));
335 else if (fmt[i] == 'i' || fmt[i] == 'n')
336 val ^= XINT (x, i);
339 return val;
342 /* Returns true if the invariant expressions E1 and E2 used in insns INSN1
343 and INSN2 have always the same value. */
345 static bool
346 invariant_expr_equal_p (rtx_insn *insn1, rtx e1, rtx_insn *insn2, rtx e2)
348 enum rtx_code code = GET_CODE (e1);
349 int i, j;
350 const char *fmt;
351 df_ref use1, use2;
352 struct invariant *inv1 = NULL, *inv2 = NULL;
353 rtx sub1, sub2;
355 /* If mode of only one of the operands is VOIDmode, it is not equivalent to
356 the other one. If both are VOIDmode, we rely on the caller of this
357 function to verify that their modes are the same. */
358 if (code != GET_CODE (e2) || GET_MODE (e1) != GET_MODE (e2))
359 return false;
361 switch (code)
363 CASE_CONST_ANY:
364 case SYMBOL_REF:
365 case CONST:
366 case LABEL_REF:
367 return rtx_equal_p (e1, e2);
369 case REG:
370 use1 = df_find_use (insn1, e1);
371 use2 = df_find_use (insn2, e2);
372 if (use1)
373 inv1 = invariant_for_use (use1);
374 if (use2)
375 inv2 = invariant_for_use (use2);
377 if (!inv1 && !inv2)
378 return rtx_equal_p (e1, e2);
380 if (!inv1 || !inv2)
381 return false;
383 gcc_assert (inv1->eqto != ~0u);
384 gcc_assert (inv2->eqto != ~0u);
385 return inv1->eqto == inv2->eqto;
387 default:
388 break;
391 fmt = GET_RTX_FORMAT (code);
392 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
394 if (fmt[i] == 'e')
396 sub1 = XEXP (e1, i);
397 sub2 = XEXP (e2, i);
399 if (!invariant_expr_equal_p (insn1, sub1, insn2, sub2))
400 return false;
403 else if (fmt[i] == 'E')
405 if (XVECLEN (e1, i) != XVECLEN (e2, i))
406 return false;
408 for (j = 0; j < XVECLEN (e1, i); j++)
410 sub1 = XVECEXP (e1, i, j);
411 sub2 = XVECEXP (e2, i, j);
413 if (!invariant_expr_equal_p (insn1, sub1, insn2, sub2))
414 return false;
417 else if (fmt[i] == 'i' || fmt[i] == 'n')
419 if (XINT (e1, i) != XINT (e2, i))
420 return false;
422 /* Unhandled type of subexpression, we fail conservatively. */
423 else
424 return false;
427 return true;
430 struct invariant_expr_hasher : free_ptr_hash <invariant_expr_entry>
432 static inline hashval_t hash (const invariant_expr_entry *);
433 static inline bool equal (const invariant_expr_entry *,
434 const invariant_expr_entry *);
437 /* Returns hash value for invariant expression entry ENTRY. */
439 inline hashval_t
440 invariant_expr_hasher::hash (const invariant_expr_entry *entry)
442 return entry->hash;
445 /* Compares invariant expression entries ENTRY1 and ENTRY2. */
447 inline bool
448 invariant_expr_hasher::equal (const invariant_expr_entry *entry1,
449 const invariant_expr_entry *entry2)
451 if (entry1->mode != entry2->mode)
452 return 0;
454 return invariant_expr_equal_p (entry1->inv->insn, entry1->expr,
455 entry2->inv->insn, entry2->expr);
458 typedef hash_table<invariant_expr_hasher> invariant_htab_type;
460 /* Checks whether invariant with value EXPR in machine mode MODE is
461 recorded in EQ. If this is the case, return the invariant. Otherwise
462 insert INV to the table for this expression and return INV. */
464 static struct invariant *
465 find_or_insert_inv (invariant_htab_type *eq, rtx expr, machine_mode mode,
466 struct invariant *inv)
468 hashval_t hash = hash_invariant_expr_1 (inv->insn, expr);
469 struct invariant_expr_entry *entry;
470 struct invariant_expr_entry pentry;
471 invariant_expr_entry **slot;
473 pentry.expr = expr;
474 pentry.inv = inv;
475 pentry.mode = mode;
476 slot = eq->find_slot_with_hash (&pentry, hash, INSERT);
477 entry = *slot;
479 if (entry)
480 return entry->inv;
482 entry = XNEW (struct invariant_expr_entry);
483 entry->inv = inv;
484 entry->expr = expr;
485 entry->mode = mode;
486 entry->hash = hash;
487 *slot = entry;
489 return inv;
492 /* Finds invariants identical to INV and records the equivalence. EQ is the
493 hash table of the invariants. */
495 static void
496 find_identical_invariants (invariant_htab_type *eq, struct invariant *inv)
498 unsigned depno;
499 bitmap_iterator bi;
500 struct invariant *dep;
501 rtx expr, set;
502 machine_mode mode;
503 struct invariant *tmp;
505 if (inv->eqto != ~0u)
506 return;
508 EXECUTE_IF_SET_IN_BITMAP (inv->depends_on, 0, depno, bi)
510 dep = invariants[depno];
511 find_identical_invariants (eq, dep);
514 set = single_set (inv->insn);
515 expr = SET_SRC (set);
516 mode = GET_MODE (expr);
517 if (mode == VOIDmode)
518 mode = GET_MODE (SET_DEST (set));
520 tmp = find_or_insert_inv (eq, expr, mode, inv);
521 inv->eqto = tmp->invno;
523 if (tmp->invno != inv->invno && inv->always_executed)
524 tmp->eqno++;
526 if (dump_file && inv->eqto != inv->invno)
527 fprintf (dump_file,
528 "Invariant %d is equivalent to invariant %d.\n",
529 inv->invno, inv->eqto);
532 /* Find invariants with the same value and record the equivalences. */
534 static void
535 merge_identical_invariants (void)
537 unsigned i;
538 struct invariant *inv;
539 invariant_htab_type eq (invariants.length ());
541 FOR_EACH_VEC_ELT (invariants, i, inv)
542 find_identical_invariants (&eq, inv);
545 /* Determines the basic blocks inside LOOP that are always executed and
546 stores their bitmap to ALWAYS_REACHED. MAY_EXIT is a bitmap of
547 basic blocks that may either exit the loop, or contain the call that
548 does not have to return. BODY is body of the loop obtained by
549 get_loop_body_in_dom_order. */
551 static void
552 compute_always_reached (struct loop *loop, basic_block *body,
553 bitmap may_exit, bitmap always_reached)
555 unsigned i;
557 for (i = 0; i < loop->num_nodes; i++)
559 if (dominated_by_p (CDI_DOMINATORS, loop->latch, body[i]))
560 bitmap_set_bit (always_reached, i);
562 if (bitmap_bit_p (may_exit, i))
563 return;
567 /* Finds exits out of the LOOP with body BODY. Marks blocks in that we may
568 exit the loop by cfg edge to HAS_EXIT and MAY_EXIT. In MAY_EXIT
569 additionally mark blocks that may exit due to a call. */
571 static void
572 find_exits (struct loop *loop, basic_block *body,
573 bitmap may_exit, bitmap has_exit)
575 unsigned i;
576 edge_iterator ei;
577 edge e;
578 struct loop *outermost_exit = loop, *aexit;
579 bool has_call = false;
580 rtx_insn *insn;
582 for (i = 0; i < loop->num_nodes; i++)
584 if (body[i]->loop_father == loop)
586 FOR_BB_INSNS (body[i], insn)
588 if (CALL_P (insn)
589 && (RTL_LOOPING_CONST_OR_PURE_CALL_P (insn)
590 || !RTL_CONST_OR_PURE_CALL_P (insn)))
592 has_call = true;
593 bitmap_set_bit (may_exit, i);
594 break;
598 FOR_EACH_EDGE (e, ei, body[i]->succs)
600 if (flow_bb_inside_loop_p (loop, e->dest))
601 continue;
603 bitmap_set_bit (may_exit, i);
604 bitmap_set_bit (has_exit, i);
605 outermost_exit = find_common_loop (outermost_exit,
606 e->dest->loop_father);
608 continue;
611 /* Use the data stored for the subloop to decide whether we may exit
612 through it. It is sufficient to do this for header of the loop,
613 as other basic blocks inside it must be dominated by it. */
614 if (body[i]->loop_father->header != body[i])
615 continue;
617 if (LOOP_DATA (body[i]->loop_father)->has_call)
619 has_call = true;
620 bitmap_set_bit (may_exit, i);
622 aexit = LOOP_DATA (body[i]->loop_father)->outermost_exit;
623 if (aexit != loop)
625 bitmap_set_bit (may_exit, i);
626 bitmap_set_bit (has_exit, i);
628 if (flow_loop_nested_p (aexit, outermost_exit))
629 outermost_exit = aexit;
633 if (loop->aux == NULL)
635 loop->aux = xcalloc (1, sizeof (struct loop_data));
636 bitmap_initialize (&LOOP_DATA (loop)->regs_ref, &reg_obstack);
637 bitmap_initialize (&LOOP_DATA (loop)->regs_live, &reg_obstack);
639 LOOP_DATA (loop)->outermost_exit = outermost_exit;
640 LOOP_DATA (loop)->has_call = has_call;
643 /* Check whether we may assign a value to X from a register. */
645 static bool
646 may_assign_reg_p (rtx x)
648 return (GET_MODE (x) != VOIDmode
649 && GET_MODE (x) != BLKmode
650 && can_copy_p (GET_MODE (x))
651 && (!REG_P (x)
652 || !HARD_REGISTER_P (x)
653 || REGNO_REG_CLASS (REGNO (x)) != NO_REGS));
656 /* Finds definitions that may correspond to invariants in LOOP with body
657 BODY. */
659 static void
660 find_defs (struct loop *loop)
662 if (dump_file)
664 fprintf (dump_file,
665 "*****starting processing of loop %d ******\n",
666 loop->num);
669 df_remove_problem (df_chain);
670 df_process_deferred_rescans ();
671 df_chain_add_problem (DF_UD_CHAIN);
672 df_live_add_problem ();
673 df_live_set_all_dirty ();
674 df_set_flags (DF_RD_PRUNE_DEAD_DEFS);
675 df_analyze_loop (loop);
676 check_invariant_table_size ();
678 if (dump_file)
680 df_dump_region (dump_file);
681 fprintf (dump_file,
682 "*****ending processing of loop %d ******\n",
683 loop->num);
687 /* Creates a new invariant for definition DEF in INSN, depending on invariants
688 in DEPENDS_ON. ALWAYS_EXECUTED is true if the insn is always executed,
689 unless the program ends due to a function call. The newly created invariant
690 is returned. */
692 static struct invariant *
693 create_new_invariant (struct def *def, rtx_insn *insn, bitmap depends_on,
694 bool always_executed)
696 struct invariant *inv = XNEW (struct invariant);
697 rtx set = single_set (insn);
698 bool speed = optimize_bb_for_speed_p (BLOCK_FOR_INSN (insn));
700 inv->def = def;
701 inv->always_executed = always_executed;
702 inv->depends_on = depends_on;
704 /* If the set is simple, usually by moving it we move the whole store out of
705 the loop. Otherwise we save only cost of the computation. */
706 if (def)
708 inv->cost = set_rtx_cost (set, speed);
709 /* ??? Try to determine cheapness of address computation. Unfortunately
710 the address cost is only a relative measure, we can't really compare
711 it with any absolute number, but only with other address costs.
712 But here we don't have any other addresses, so compare with a magic
713 number anyway. It has to be large enough to not regress PR33928
714 (by avoiding to move reg+8,reg+16,reg+24 invariants), but small
715 enough to not regress 410.bwaves either (by still moving reg+reg
716 invariants).
717 See http://gcc.gnu.org/ml/gcc-patches/2009-10/msg01210.html . */
718 if (SCALAR_INT_MODE_P (GET_MODE (SET_DEST (set))))
719 inv->cheap_address = address_cost (SET_SRC (set), word_mode,
720 ADDR_SPACE_GENERIC, speed) < 3;
721 else
722 inv->cheap_address = false;
724 else
726 inv->cost = set_src_cost (SET_SRC (set), GET_MODE (SET_DEST (set)),
727 speed);
728 inv->cheap_address = false;
731 inv->move = false;
732 inv->reg = NULL_RTX;
733 inv->orig_regno = -1;
734 inv->stamp = 0;
735 inv->insn = insn;
737 inv->invno = invariants.length ();
738 inv->eqto = ~0u;
740 /* Itself. */
741 inv->eqno = 1;
743 if (def)
744 def->invno = inv->invno;
745 invariants.safe_push (inv);
747 if (dump_file)
749 fprintf (dump_file,
750 "Set in insn %d is invariant (%d), cost %d, depends on ",
751 INSN_UID (insn), inv->invno, inv->cost);
752 dump_bitmap (dump_file, inv->depends_on);
755 return inv;
758 /* Return a canonical version of X for the address, from the point of view,
759 that all multiplications are represented as MULT instead of the multiply
760 by a power of 2 being represented as ASHIFT.
762 Callers should prepare a copy of X because this function may modify it
763 in place. */
765 static void
766 canonicalize_address_mult (rtx x)
768 subrtx_var_iterator::array_type array;
769 FOR_EACH_SUBRTX_VAR (iter, array, x, NONCONST)
771 rtx sub = *iter;
773 if (GET_CODE (sub) == ASHIFT
774 && CONST_INT_P (XEXP (sub, 1))
775 && INTVAL (XEXP (sub, 1)) < GET_MODE_BITSIZE (GET_MODE (sub))
776 && INTVAL (XEXP (sub, 1)) >= 0)
778 HOST_WIDE_INT shift = INTVAL (XEXP (sub, 1));
779 PUT_CODE (sub, MULT);
780 XEXP (sub, 1) = gen_int_mode (HOST_WIDE_INT_1 << shift,
781 GET_MODE (sub));
782 iter.skip_subrtxes ();
787 /* Maximum number of sub expressions in address. We set it to
788 a small integer since it's unlikely to have a complicated
789 address expression. */
791 #define MAX_CANON_ADDR_PARTS (5)
793 /* Collect sub expressions in address X with PLUS as the seperator.
794 Sub expressions are stored in vector ADDR_PARTS. */
796 static void
797 collect_address_parts (rtx x, vec<rtx> *addr_parts)
799 subrtx_var_iterator::array_type array;
800 FOR_EACH_SUBRTX_VAR (iter, array, x, NONCONST)
802 rtx sub = *iter;
804 if (GET_CODE (sub) != PLUS)
806 addr_parts->safe_push (sub);
807 iter.skip_subrtxes ();
812 /* Compare function for sorting sub expressions X and Y based on
813 precedence defined for communitive operations. */
815 static int
816 compare_address_parts (const void *x, const void *y)
818 const rtx *rx = (const rtx *)x;
819 const rtx *ry = (const rtx *)y;
820 int px = commutative_operand_precedence (*rx);
821 int py = commutative_operand_precedence (*ry);
823 return (py - px);
826 /* Return a canonical version address for X by following steps:
827 1) Rewrite ASHIFT into MULT recursively.
828 2) Divide address into sub expressions with PLUS as the
829 separator.
830 3) Sort sub expressions according to precedence defined
831 for communative operations.
832 4) Simplify CONST_INT_P sub expressions.
833 5) Create new canonicalized address and return.
834 Callers should prepare a copy of X because this function may
835 modify it in place. */
837 static rtx
838 canonicalize_address (rtx x)
840 rtx res;
841 unsigned int i, j;
842 machine_mode mode = GET_MODE (x);
843 auto_vec<rtx, MAX_CANON_ADDR_PARTS> addr_parts;
845 /* Rewrite ASHIFT into MULT. */
846 canonicalize_address_mult (x);
847 /* Divide address into sub expressions. */
848 collect_address_parts (x, &addr_parts);
849 /* Unlikely to have very complicated address. */
850 if (addr_parts.length () < 2
851 || addr_parts.length () > MAX_CANON_ADDR_PARTS)
852 return x;
854 /* Sort sub expressions according to canonicalization precedence. */
855 addr_parts.qsort (compare_address_parts);
857 /* Simplify all constant int summary if possible. */
858 for (i = 0; i < addr_parts.length (); i++)
859 if (CONST_INT_P (addr_parts[i]))
860 break;
862 for (j = i + 1; j < addr_parts.length (); j++)
864 gcc_assert (CONST_INT_P (addr_parts[j]));
865 addr_parts[i] = simplify_gen_binary (PLUS, mode,
866 addr_parts[i],
867 addr_parts[j]);
870 /* Chain PLUS operators to the left for !CONST_INT_P sub expressions. */
871 res = addr_parts[0];
872 for (j = 1; j < i; j++)
873 res = simplify_gen_binary (PLUS, mode, res, addr_parts[j]);
875 /* Pickup the last CONST_INT_P sub expression. */
876 if (i < addr_parts.length ())
877 res = simplify_gen_binary (PLUS, mode, res, addr_parts[i]);
879 return res;
882 /* Given invariant DEF and its address USE, check if the corresponding
883 invariant expr can be propagated into the use or not. */
885 static bool
886 inv_can_prop_to_addr_use (struct def *def, df_ref use)
888 struct invariant *inv;
889 rtx *pos = DF_REF_REAL_LOC (use), def_set, use_set;
890 rtx_insn *use_insn = DF_REF_INSN (use);
891 rtx_insn *def_insn;
892 bool ok;
894 inv = invariants[def->invno];
895 /* No need to check if address expression is expensive. */
896 if (!inv->cheap_address)
897 return false;
899 def_insn = inv->insn;
900 def_set = single_set (def_insn);
901 if (!def_set)
902 return false;
904 validate_unshare_change (use_insn, pos, SET_SRC (def_set), true);
905 ok = verify_changes (0);
906 /* Try harder with canonicalization in address expression. */
907 if (!ok && (use_set = single_set (use_insn)) != NULL_RTX)
909 rtx src, dest, mem = NULL_RTX;
911 src = SET_SRC (use_set);
912 dest = SET_DEST (use_set);
913 if (MEM_P (src))
914 mem = src;
915 else if (MEM_P (dest))
916 mem = dest;
918 if (mem != NULL_RTX
919 && !memory_address_addr_space_p (GET_MODE (mem),
920 XEXP (mem, 0),
921 MEM_ADDR_SPACE (mem)))
923 rtx addr = canonicalize_address (copy_rtx (XEXP (mem, 0)));
924 if (memory_address_addr_space_p (GET_MODE (mem),
925 addr, MEM_ADDR_SPACE (mem)))
926 ok = true;
929 cancel_changes (0);
930 return ok;
933 /* Record USE at DEF. */
935 static void
936 record_use (struct def *def, df_ref use)
938 struct use *u = XNEW (struct use);
940 u->pos = DF_REF_REAL_LOC (use);
941 u->insn = DF_REF_INSN (use);
942 u->addr_use_p = (DF_REF_TYPE (use) == DF_REF_REG_MEM_LOAD
943 || DF_REF_TYPE (use) == DF_REF_REG_MEM_STORE);
944 u->next = def->uses;
945 def->uses = u;
946 def->n_uses++;
947 if (u->addr_use_p)
949 /* Initialize propagation information if this is the first addr
950 use of the inv def. */
951 if (def->n_addr_uses == 0)
952 def->can_prop_to_addr_uses = true;
954 def->n_addr_uses++;
955 if (def->can_prop_to_addr_uses && !inv_can_prop_to_addr_use (def, use))
956 def->can_prop_to_addr_uses = false;
960 /* Finds the invariants USE depends on and store them to the DEPENDS_ON
961 bitmap. Returns true if all dependencies of USE are known to be
962 loop invariants, false otherwise. */
964 static bool
965 check_dependency (basic_block bb, df_ref use, bitmap depends_on)
967 df_ref def;
968 basic_block def_bb;
969 struct df_link *defs;
970 struct def *def_data;
971 struct invariant *inv;
973 if (DF_REF_FLAGS (use) & DF_REF_READ_WRITE)
974 return false;
976 defs = DF_REF_CHAIN (use);
977 if (!defs)
979 unsigned int regno = DF_REF_REGNO (use);
981 /* If this is the use of an uninitialized argument register that is
982 likely to be spilled, do not move it lest this might extend its
983 lifetime and cause reload to die. This can occur for a call to
984 a function taking complex number arguments and moving the insns
985 preparing the arguments without moving the call itself wouldn't
986 gain much in practice. */
987 if ((DF_REF_FLAGS (use) & DF_HARD_REG_LIVE)
988 && FUNCTION_ARG_REGNO_P (regno)
989 && targetm.class_likely_spilled_p (REGNO_REG_CLASS (regno)))
990 return false;
992 return true;
995 if (defs->next)
996 return false;
998 def = defs->ref;
999 check_invariant_table_size ();
1000 inv = invariant_table[DF_REF_ID (def)];
1001 if (!inv)
1002 return false;
1004 def_data = inv->def;
1005 gcc_assert (def_data != NULL);
1007 def_bb = DF_REF_BB (def);
1008 /* Note that in case bb == def_bb, we know that the definition
1009 dominates insn, because def has invariant_table[DF_REF_ID(def)]
1010 defined and we process the insns in the basic block bb
1011 sequentially. */
1012 if (!dominated_by_p (CDI_DOMINATORS, bb, def_bb))
1013 return false;
1015 bitmap_set_bit (depends_on, def_data->invno);
1016 return true;
1020 /* Finds the invariants INSN depends on and store them to the DEPENDS_ON
1021 bitmap. Returns true if all dependencies of INSN are known to be
1022 loop invariants, false otherwise. */
1024 static bool
1025 check_dependencies (rtx_insn *insn, bitmap depends_on)
1027 struct df_insn_info *insn_info = DF_INSN_INFO_GET (insn);
1028 df_ref use;
1029 basic_block bb = BLOCK_FOR_INSN (insn);
1031 FOR_EACH_INSN_INFO_USE (use, insn_info)
1032 if (!check_dependency (bb, use, depends_on))
1033 return false;
1034 FOR_EACH_INSN_INFO_EQ_USE (use, insn_info)
1035 if (!check_dependency (bb, use, depends_on))
1036 return false;
1038 return true;
1041 /* Pre-check candidate DEST to skip the one which can not make a valid insn
1042 during move_invariant_reg. SIMPLE is to skip HARD_REGISTER. */
1043 static bool
1044 pre_check_invariant_p (bool simple, rtx dest)
1046 if (simple && REG_P (dest) && DF_REG_DEF_COUNT (REGNO (dest)) > 1)
1048 df_ref use;
1049 unsigned int i = REGNO (dest);
1050 struct df_insn_info *insn_info;
1051 df_ref def_rec;
1053 for (use = DF_REG_USE_CHAIN (i); use; use = DF_REF_NEXT_REG (use))
1055 rtx_insn *ref = DF_REF_INSN (use);
1056 insn_info = DF_INSN_INFO_GET (ref);
1058 FOR_EACH_INSN_INFO_DEF (def_rec, insn_info)
1059 if (DF_REF_REGNO (def_rec) == i)
1061 /* Multi definitions at this stage, most likely are due to
1062 instruction constraints, which requires both read and write
1063 on the same register. Since move_invariant_reg is not
1064 powerful enough to handle such cases, just ignore the INV
1065 and leave the chance to others. */
1066 return false;
1070 return true;
1073 /* Finds invariant in INSN. ALWAYS_REACHED is true if the insn is always
1074 executed. ALWAYS_EXECUTED is true if the insn is always executed,
1075 unless the program ends due to a function call. */
1077 static void
1078 find_invariant_insn (rtx_insn *insn, bool always_reached, bool always_executed)
1080 df_ref ref;
1081 struct def *def;
1082 bitmap depends_on;
1083 rtx set, dest;
1084 bool simple = true;
1085 struct invariant *inv;
1087 /* We can't move a CC0 setter without the user. */
1088 if (HAVE_cc0 && sets_cc0_p (insn))
1089 return;
1091 set = single_set (insn);
1092 if (!set)
1093 return;
1094 dest = SET_DEST (set);
1096 if (!REG_P (dest)
1097 || HARD_REGISTER_P (dest))
1098 simple = false;
1100 if (!may_assign_reg_p (dest)
1101 || !pre_check_invariant_p (simple, dest)
1102 || !check_maybe_invariant (SET_SRC (set)))
1103 return;
1105 /* If the insn can throw exception, we cannot move it at all without changing
1106 cfg. */
1107 if (can_throw_internal (insn))
1108 return;
1110 /* We cannot make trapping insn executed, unless it was executed before. */
1111 if (may_trap_or_fault_p (PATTERN (insn)) && !always_reached)
1112 return;
1114 depends_on = BITMAP_ALLOC (NULL);
1115 if (!check_dependencies (insn, depends_on))
1117 BITMAP_FREE (depends_on);
1118 return;
1121 if (simple)
1122 def = XCNEW (struct def);
1123 else
1124 def = NULL;
1126 inv = create_new_invariant (def, insn, depends_on, always_executed);
1128 if (simple)
1130 ref = df_find_def (insn, dest);
1131 check_invariant_table_size ();
1132 invariant_table[DF_REF_ID (ref)] = inv;
1136 /* Record registers used in INSN that have a unique invariant definition. */
1138 static void
1139 record_uses (rtx_insn *insn)
1141 struct df_insn_info *insn_info = DF_INSN_INFO_GET (insn);
1142 df_ref use;
1143 struct invariant *inv;
1145 FOR_EACH_INSN_INFO_USE (use, insn_info)
1147 inv = invariant_for_use (use);
1148 if (inv)
1149 record_use (inv->def, use);
1151 FOR_EACH_INSN_INFO_EQ_USE (use, insn_info)
1153 inv = invariant_for_use (use);
1154 if (inv)
1155 record_use (inv->def, use);
1159 /* Finds invariants in INSN. ALWAYS_REACHED is true if the insn is always
1160 executed. ALWAYS_EXECUTED is true if the insn is always executed,
1161 unless the program ends due to a function call. */
1163 static void
1164 find_invariants_insn (rtx_insn *insn, bool always_reached, bool always_executed)
1166 find_invariant_insn (insn, always_reached, always_executed);
1167 record_uses (insn);
1170 /* Finds invariants in basic block BB. ALWAYS_REACHED is true if the
1171 basic block is always executed. ALWAYS_EXECUTED is true if the basic
1172 block is always executed, unless the program ends due to a function
1173 call. */
1175 static void
1176 find_invariants_bb (basic_block bb, bool always_reached, bool always_executed)
1178 rtx_insn *insn;
1180 FOR_BB_INSNS (bb, insn)
1182 if (!NONDEBUG_INSN_P (insn))
1183 continue;
1185 find_invariants_insn (insn, always_reached, always_executed);
1187 if (always_reached
1188 && CALL_P (insn)
1189 && (RTL_LOOPING_CONST_OR_PURE_CALL_P (insn)
1190 || ! RTL_CONST_OR_PURE_CALL_P (insn)))
1191 always_reached = false;
1195 /* Finds invariants in LOOP with body BODY. ALWAYS_REACHED is the bitmap of
1196 basic blocks in BODY that are always executed. ALWAYS_EXECUTED is the
1197 bitmap of basic blocks in BODY that are always executed unless the program
1198 ends due to a function call. */
1200 static void
1201 find_invariants_body (struct loop *loop, basic_block *body,
1202 bitmap always_reached, bitmap always_executed)
1204 unsigned i;
1206 for (i = 0; i < loop->num_nodes; i++)
1207 find_invariants_bb (body[i],
1208 bitmap_bit_p (always_reached, i),
1209 bitmap_bit_p (always_executed, i));
1212 /* Finds invariants in LOOP. */
1214 static void
1215 find_invariants (struct loop *loop)
1217 bitmap may_exit = BITMAP_ALLOC (NULL);
1218 bitmap always_reached = BITMAP_ALLOC (NULL);
1219 bitmap has_exit = BITMAP_ALLOC (NULL);
1220 bitmap always_executed = BITMAP_ALLOC (NULL);
1221 basic_block *body = get_loop_body_in_dom_order (loop);
1223 find_exits (loop, body, may_exit, has_exit);
1224 compute_always_reached (loop, body, may_exit, always_reached);
1225 compute_always_reached (loop, body, has_exit, always_executed);
1227 find_defs (loop);
1228 find_invariants_body (loop, body, always_reached, always_executed);
1229 merge_identical_invariants ();
1231 BITMAP_FREE (always_reached);
1232 BITMAP_FREE (always_executed);
1233 BITMAP_FREE (may_exit);
1234 BITMAP_FREE (has_exit);
1235 free (body);
1238 /* Frees a list of uses USE. */
1240 static void
1241 free_use_list (struct use *use)
1243 struct use *next;
1245 for (; use; use = next)
1247 next = use->next;
1248 free (use);
1252 /* Return pressure class and number of hard registers (through *NREGS)
1253 for destination of INSN. */
1254 static enum reg_class
1255 get_pressure_class_and_nregs (rtx_insn *insn, int *nregs)
1257 rtx reg;
1258 enum reg_class pressure_class;
1259 rtx set = single_set (insn);
1261 /* Considered invariant insns have only one set. */
1262 gcc_assert (set != NULL_RTX);
1263 reg = SET_DEST (set);
1264 if (GET_CODE (reg) == SUBREG)
1265 reg = SUBREG_REG (reg);
1266 if (MEM_P (reg))
1268 *nregs = 0;
1269 pressure_class = NO_REGS;
1271 else
1273 if (! REG_P (reg))
1274 reg = NULL_RTX;
1275 if (reg == NULL_RTX)
1276 pressure_class = GENERAL_REGS;
1277 else
1279 pressure_class = reg_allocno_class (REGNO (reg));
1280 pressure_class = ira_pressure_class_translate[pressure_class];
1282 *nregs
1283 = ira_reg_class_max_nregs[pressure_class][GET_MODE (SET_SRC (set))];
1285 return pressure_class;
1288 /* Calculates cost and number of registers needed for moving invariant INV
1289 out of the loop and stores them to *COST and *REGS_NEEDED. *CL will be
1290 the REG_CLASS of INV. Return
1291 -1: if INV is invalid.
1292 0: if INV and its depends_on have same reg_class
1293 1: if INV and its depends_on have different reg_classes. */
1295 static int
1296 get_inv_cost (struct invariant *inv, int *comp_cost, unsigned *regs_needed,
1297 enum reg_class *cl)
1299 int i, acomp_cost;
1300 unsigned aregs_needed[N_REG_CLASSES];
1301 unsigned depno;
1302 struct invariant *dep;
1303 bitmap_iterator bi;
1304 int ret = 1;
1306 /* Find the representative of the class of the equivalent invariants. */
1307 inv = invariants[inv->eqto];
1309 *comp_cost = 0;
1310 if (! flag_ira_loop_pressure)
1311 regs_needed[0] = 0;
1312 else
1314 for (i = 0; i < ira_pressure_classes_num; i++)
1315 regs_needed[ira_pressure_classes[i]] = 0;
1318 if (inv->move
1319 || inv->stamp == actual_stamp)
1320 return -1;
1321 inv->stamp = actual_stamp;
1323 if (! flag_ira_loop_pressure)
1324 regs_needed[0]++;
1325 else
1327 int nregs;
1328 enum reg_class pressure_class;
1330 pressure_class = get_pressure_class_and_nregs (inv->insn, &nregs);
1331 regs_needed[pressure_class] += nregs;
1332 *cl = pressure_class;
1333 ret = 0;
1336 if (!inv->cheap_address
1337 || inv->def->n_uses == 0
1338 || inv->def->n_addr_uses < inv->def->n_uses
1339 /* Count cost if the inv can't be propagated into address uses. */
1340 || !inv->def->can_prop_to_addr_uses)
1341 (*comp_cost) += inv->cost * inv->eqno;
1343 #ifdef STACK_REGS
1345 /* Hoisting constant pool constants into stack regs may cost more than
1346 just single register. On x87, the balance is affected both by the
1347 small number of FP registers, and by its register stack organization,
1348 that forces us to add compensation code in and around the loop to
1349 shuffle the operands to the top of stack before use, and pop them
1350 from the stack after the loop finishes.
1352 To model this effect, we increase the number of registers needed for
1353 stack registers by two: one register push, and one register pop.
1354 This usually has the effect that FP constant loads from the constant
1355 pool are not moved out of the loop.
1357 Note that this also means that dependent invariants can not be moved.
1358 However, the primary purpose of this pass is to move loop invariant
1359 address arithmetic out of loops, and address arithmetic that depends
1360 on floating point constants is unlikely to ever occur. */
1361 rtx set = single_set (inv->insn);
1362 if (set
1363 && IS_STACK_MODE (GET_MODE (SET_SRC (set)))
1364 && constant_pool_constant_p (SET_SRC (set)))
1366 if (flag_ira_loop_pressure)
1367 regs_needed[ira_stack_reg_pressure_class] += 2;
1368 else
1369 regs_needed[0] += 2;
1372 #endif
1374 EXECUTE_IF_SET_IN_BITMAP (inv->depends_on, 0, depno, bi)
1376 bool check_p;
1377 enum reg_class dep_cl = ALL_REGS;
1378 int dep_ret;
1380 dep = invariants[depno];
1382 /* If DEP is moved out of the loop, it is not a depends_on any more. */
1383 if (dep->move)
1384 continue;
1386 dep_ret = get_inv_cost (dep, &acomp_cost, aregs_needed, &dep_cl);
1388 if (! flag_ira_loop_pressure)
1389 check_p = aregs_needed[0] != 0;
1390 else
1392 for (i = 0; i < ira_pressure_classes_num; i++)
1393 if (aregs_needed[ira_pressure_classes[i]] != 0)
1394 break;
1395 check_p = i < ira_pressure_classes_num;
1397 if ((dep_ret == 1) || ((dep_ret == 0) && (*cl != dep_cl)))
1399 *cl = ALL_REGS;
1400 ret = 1;
1403 if (check_p
1404 /* We need to check always_executed, since if the original value of
1405 the invariant may be preserved, we may need to keep it in a
1406 separate register. TODO check whether the register has an
1407 use outside of the loop. */
1408 && dep->always_executed
1409 && !dep->def->uses->next)
1411 /* If this is a single use, after moving the dependency we will not
1412 need a new register. */
1413 if (! flag_ira_loop_pressure)
1414 aregs_needed[0]--;
1415 else
1417 int nregs;
1418 enum reg_class pressure_class;
1420 pressure_class = get_pressure_class_and_nregs (inv->insn, &nregs);
1421 aregs_needed[pressure_class] -= nregs;
1425 if (! flag_ira_loop_pressure)
1426 regs_needed[0] += aregs_needed[0];
1427 else
1429 for (i = 0; i < ira_pressure_classes_num; i++)
1430 regs_needed[ira_pressure_classes[i]]
1431 += aregs_needed[ira_pressure_classes[i]];
1433 (*comp_cost) += acomp_cost;
1435 return ret;
1438 /* Calculates gain for eliminating invariant INV. REGS_USED is the number
1439 of registers used in the loop, NEW_REGS is the number of new variables
1440 already added due to the invariant motion. The number of registers needed
1441 for it is stored in *REGS_NEEDED. SPEED and CALL_P are flags passed
1442 through to estimate_reg_pressure_cost. */
1444 static int
1445 gain_for_invariant (struct invariant *inv, unsigned *regs_needed,
1446 unsigned *new_regs, unsigned regs_used,
1447 bool speed, bool call_p)
1449 int comp_cost, size_cost;
1450 /* Workaround -Wmaybe-uninitialized false positive during
1451 profiledbootstrap by initializing it. */
1452 enum reg_class cl = NO_REGS;
1453 int ret;
1455 actual_stamp++;
1457 ret = get_inv_cost (inv, &comp_cost, regs_needed, &cl);
1459 if (! flag_ira_loop_pressure)
1461 size_cost = (estimate_reg_pressure_cost (new_regs[0] + regs_needed[0],
1462 regs_used, speed, call_p)
1463 - estimate_reg_pressure_cost (new_regs[0],
1464 regs_used, speed, call_p));
1466 else if (ret < 0)
1467 return -1;
1468 else if ((ret == 0) && (cl == NO_REGS))
1469 /* Hoist it anyway since it does not impact register pressure. */
1470 return 1;
1471 else
1473 int i;
1474 enum reg_class pressure_class;
1476 for (i = 0; i < ira_pressure_classes_num; i++)
1478 pressure_class = ira_pressure_classes[i];
1480 if (!reg_classes_intersect_p (pressure_class, cl))
1481 continue;
1483 if ((int) new_regs[pressure_class]
1484 + (int) regs_needed[pressure_class]
1485 + LOOP_DATA (curr_loop)->max_reg_pressure[pressure_class]
1486 + IRA_LOOP_RESERVED_REGS
1487 > ira_class_hard_regs_num[pressure_class])
1488 break;
1490 if (i < ira_pressure_classes_num)
1491 /* There will be register pressure excess and we want not to
1492 make this loop invariant motion. All loop invariants with
1493 non-positive gains will be rejected in function
1494 find_invariants_to_move. Therefore we return the negative
1495 number here.
1497 One could think that this rejects also expensive loop
1498 invariant motions and this will hurt code performance.
1499 However numerous experiments with different heuristics
1500 taking invariant cost into account did not confirm this
1501 assumption. There are possible explanations for this
1502 result:
1503 o probably all expensive invariants were already moved out
1504 of the loop by PRE and gimple invariant motion pass.
1505 o expensive invariant execution will be hidden by insn
1506 scheduling or OOO processor hardware because usually such
1507 invariants have a lot of freedom to be executed
1508 out-of-order.
1509 Another reason for ignoring invariant cost vs spilling cost
1510 heuristics is also in difficulties to evaluate accurately
1511 spill cost at this stage. */
1512 return -1;
1513 else
1514 size_cost = 0;
1517 return comp_cost - size_cost;
1520 /* Finds invariant with best gain for moving. Returns the gain, stores
1521 the invariant in *BEST and number of registers needed for it to
1522 *REGS_NEEDED. REGS_USED is the number of registers used in the loop.
1523 NEW_REGS is the number of new variables already added due to invariant
1524 motion. */
1526 static int
1527 best_gain_for_invariant (struct invariant **best, unsigned *regs_needed,
1528 unsigned *new_regs, unsigned regs_used,
1529 bool speed, bool call_p)
1531 struct invariant *inv;
1532 int i, gain = 0, again;
1533 unsigned aregs_needed[N_REG_CLASSES], invno;
1535 FOR_EACH_VEC_ELT (invariants, invno, inv)
1537 if (inv->move)
1538 continue;
1540 /* Only consider the "representatives" of equivalent invariants. */
1541 if (inv->eqto != inv->invno)
1542 continue;
1544 again = gain_for_invariant (inv, aregs_needed, new_regs, regs_used,
1545 speed, call_p);
1546 if (again > gain)
1548 gain = again;
1549 *best = inv;
1550 if (! flag_ira_loop_pressure)
1551 regs_needed[0] = aregs_needed[0];
1552 else
1554 for (i = 0; i < ira_pressure_classes_num; i++)
1555 regs_needed[ira_pressure_classes[i]]
1556 = aregs_needed[ira_pressure_classes[i]];
1561 return gain;
1564 /* Marks invariant INVNO and all its dependencies for moving. */
1566 static void
1567 set_move_mark (unsigned invno, int gain)
1569 struct invariant *inv = invariants[invno];
1570 bitmap_iterator bi;
1572 /* Find the representative of the class of the equivalent invariants. */
1573 inv = invariants[inv->eqto];
1575 if (inv->move)
1576 return;
1577 inv->move = true;
1579 if (dump_file)
1581 if (gain >= 0)
1582 fprintf (dump_file, "Decided to move invariant %d -- gain %d\n",
1583 invno, gain);
1584 else
1585 fprintf (dump_file, "Decided to move dependent invariant %d\n",
1586 invno);
1589 EXECUTE_IF_SET_IN_BITMAP (inv->depends_on, 0, invno, bi)
1591 set_move_mark (invno, -1);
1595 /* Determines which invariants to move. */
1597 static void
1598 find_invariants_to_move (bool speed, bool call_p)
1600 int gain;
1601 unsigned i, regs_used, regs_needed[N_REG_CLASSES], new_regs[N_REG_CLASSES];
1602 struct invariant *inv = NULL;
1604 if (!invariants.length ())
1605 return;
1607 if (flag_ira_loop_pressure)
1608 /* REGS_USED is actually never used when the flag is on. */
1609 regs_used = 0;
1610 else
1611 /* We do not really do a good job in estimating number of
1612 registers used; we put some initial bound here to stand for
1613 induction variables etc. that we do not detect. */
1615 unsigned int n_regs = DF_REG_SIZE (df);
1617 regs_used = 2;
1619 for (i = 0; i < n_regs; i++)
1621 if (!DF_REGNO_FIRST_DEF (i) && DF_REGNO_LAST_USE (i))
1623 /* This is a value that is used but not changed inside loop. */
1624 regs_used++;
1629 if (! flag_ira_loop_pressure)
1630 new_regs[0] = regs_needed[0] = 0;
1631 else
1633 for (i = 0; (int) i < ira_pressure_classes_num; i++)
1634 new_regs[ira_pressure_classes[i]] = 0;
1636 while ((gain = best_gain_for_invariant (&inv, regs_needed,
1637 new_regs, regs_used,
1638 speed, call_p)) > 0)
1640 set_move_mark (inv->invno, gain);
1641 if (! flag_ira_loop_pressure)
1642 new_regs[0] += regs_needed[0];
1643 else
1645 for (i = 0; (int) i < ira_pressure_classes_num; i++)
1646 new_regs[ira_pressure_classes[i]]
1647 += regs_needed[ira_pressure_classes[i]];
1652 /* Replace the uses, reached by the definition of invariant INV, by REG.
1654 IN_GROUP is nonzero if this is part of a group of changes that must be
1655 performed as a group. In that case, the changes will be stored. The
1656 function `apply_change_group' will validate and apply the changes. */
1658 static int
1659 replace_uses (struct invariant *inv, rtx reg, bool in_group)
1661 /* Replace the uses we know to be dominated. It saves work for copy
1662 propagation, and also it is necessary so that dependent invariants
1663 are computed right. */
1664 if (inv->def)
1666 struct use *use;
1667 for (use = inv->def->uses; use; use = use->next)
1668 validate_change (use->insn, use->pos, reg, true);
1670 /* If we aren't part of a larger group, apply the changes now. */
1671 if (!in_group)
1672 return apply_change_group ();
1675 return 1;
1678 /* Whether invariant INV setting REG can be moved out of LOOP, at the end of
1679 the block preceding its header. */
1681 static bool
1682 can_move_invariant_reg (struct loop *loop, struct invariant *inv, rtx reg)
1684 df_ref def, use;
1685 unsigned int dest_regno, defs_in_loop_count = 0;
1686 rtx_insn *insn = inv->insn;
1687 basic_block bb = BLOCK_FOR_INSN (inv->insn);
1689 /* We ignore hard register and memory access for cost and complexity reasons.
1690 Hard register are few at this stage and expensive to consider as they
1691 require building a separate data flow. Memory access would require using
1692 df_simulate_* and can_move_insns_across functions and is more complex. */
1693 if (!REG_P (reg) || HARD_REGISTER_P (reg))
1694 return false;
1696 /* Check whether the set is always executed. We could omit this condition if
1697 we know that the register is unused outside of the loop, but it does not
1698 seem worth finding out. */
1699 if (!inv->always_executed)
1700 return false;
1702 /* Check that all uses that would be dominated by def are already dominated
1703 by it. */
1704 dest_regno = REGNO (reg);
1705 for (use = DF_REG_USE_CHAIN (dest_regno); use; use = DF_REF_NEXT_REG (use))
1707 rtx_insn *use_insn;
1708 basic_block use_bb;
1710 use_insn = DF_REF_INSN (use);
1711 use_bb = BLOCK_FOR_INSN (use_insn);
1713 /* Ignore instruction considered for moving. */
1714 if (use_insn == insn)
1715 continue;
1717 /* Don't consider uses outside loop. */
1718 if (!flow_bb_inside_loop_p (loop, use_bb))
1719 continue;
1721 /* Don't move if a use is not dominated by def in insn. */
1722 if (use_bb == bb && DF_INSN_LUID (insn) >= DF_INSN_LUID (use_insn))
1723 return false;
1724 if (!dominated_by_p (CDI_DOMINATORS, use_bb, bb))
1725 return false;
1728 /* Check for other defs. Any other def in the loop might reach a use
1729 currently reached by the def in insn. */
1730 for (def = DF_REG_DEF_CHAIN (dest_regno); def; def = DF_REF_NEXT_REG (def))
1732 basic_block def_bb = DF_REF_BB (def);
1734 /* Defs in exit block cannot reach a use they weren't already. */
1735 if (single_succ_p (def_bb))
1737 basic_block def_bb_succ;
1739 def_bb_succ = single_succ (def_bb);
1740 if (!flow_bb_inside_loop_p (loop, def_bb_succ))
1741 continue;
1744 if (++defs_in_loop_count > 1)
1745 return false;
1748 return true;
1751 /* Move invariant INVNO out of the LOOP. Returns true if this succeeds, false
1752 otherwise. */
1754 static bool
1755 move_invariant_reg (struct loop *loop, unsigned invno)
1757 struct invariant *inv = invariants[invno];
1758 struct invariant *repr = invariants[inv->eqto];
1759 unsigned i;
1760 basic_block preheader = loop_preheader_edge (loop)->src;
1761 rtx reg, set, dest, note;
1762 bitmap_iterator bi;
1763 int regno = -1;
1765 if (inv->reg)
1766 return true;
1767 if (!repr->move)
1768 return false;
1770 /* If this is a representative of the class of equivalent invariants,
1771 really move the invariant. Otherwise just replace its use with
1772 the register used for the representative. */
1773 if (inv == repr)
1775 if (inv->depends_on)
1777 EXECUTE_IF_SET_IN_BITMAP (inv->depends_on, 0, i, bi)
1779 if (!move_invariant_reg (loop, i))
1780 goto fail;
1784 /* If possible, just move the set out of the loop. Otherwise, we
1785 need to create a temporary register. */
1786 set = single_set (inv->insn);
1787 reg = dest = SET_DEST (set);
1788 if (GET_CODE (reg) == SUBREG)
1789 reg = SUBREG_REG (reg);
1790 if (REG_P (reg))
1791 regno = REGNO (reg);
1793 if (!can_move_invariant_reg (loop, inv, dest))
1795 reg = gen_reg_rtx_and_attrs (dest);
1797 /* Try replacing the destination by a new pseudoregister. */
1798 validate_change (inv->insn, &SET_DEST (set), reg, true);
1800 /* As well as all the dominated uses. */
1801 replace_uses (inv, reg, true);
1803 /* And validate all the changes. */
1804 if (!apply_change_group ())
1805 goto fail;
1807 emit_insn_after (gen_move_insn (dest, reg), inv->insn);
1809 else if (dump_file)
1810 fprintf (dump_file, "Invariant %d moved without introducing a new "
1811 "temporary register\n", invno);
1812 reorder_insns (inv->insn, inv->insn, BB_END (preheader));
1813 df_recompute_luids (preheader);
1815 /* If there is a REG_EQUAL note on the insn we just moved, and the
1816 insn is in a basic block that is not always executed or the note
1817 contains something for which we don't know the invariant status,
1818 the note may no longer be valid after we move the insn. Note that
1819 uses in REG_EQUAL notes are taken into account in the computation
1820 of invariants, so it is safe to retain the note even if it contains
1821 register references for which we know the invariant status. */
1822 if ((note = find_reg_note (inv->insn, REG_EQUAL, NULL_RTX))
1823 && (!inv->always_executed
1824 || !check_maybe_invariant (XEXP (note, 0))))
1825 remove_note (inv->insn, note);
1827 else
1829 if (!move_invariant_reg (loop, repr->invno))
1830 goto fail;
1831 reg = repr->reg;
1832 regno = repr->orig_regno;
1833 if (!replace_uses (inv, reg, false))
1834 goto fail;
1835 set = single_set (inv->insn);
1836 emit_insn_after (gen_move_insn (SET_DEST (set), reg), inv->insn);
1837 delete_insn (inv->insn);
1840 inv->reg = reg;
1841 inv->orig_regno = regno;
1843 return true;
1845 fail:
1846 /* If we failed, clear move flag, so that we do not try to move inv
1847 again. */
1848 if (dump_file)
1849 fprintf (dump_file, "Failed to move invariant %d\n", invno);
1850 inv->move = false;
1851 inv->reg = NULL_RTX;
1852 inv->orig_regno = -1;
1854 return false;
1857 /* Move selected invariant out of the LOOP. Newly created regs are marked
1858 in TEMPORARY_REGS. */
1860 static void
1861 move_invariants (struct loop *loop)
1863 struct invariant *inv;
1864 unsigned i;
1866 FOR_EACH_VEC_ELT (invariants, i, inv)
1867 move_invariant_reg (loop, i);
1868 if (flag_ira_loop_pressure && resize_reg_info ())
1870 FOR_EACH_VEC_ELT (invariants, i, inv)
1871 if (inv->reg != NULL_RTX)
1873 if (inv->orig_regno >= 0)
1874 setup_reg_classes (REGNO (inv->reg),
1875 reg_preferred_class (inv->orig_regno),
1876 reg_alternate_class (inv->orig_regno),
1877 reg_allocno_class (inv->orig_regno));
1878 else
1879 setup_reg_classes (REGNO (inv->reg),
1880 GENERAL_REGS, NO_REGS, GENERAL_REGS);
1885 /* Initializes invariant motion data. */
1887 static void
1888 init_inv_motion_data (void)
1890 actual_stamp = 1;
1892 invariants.create (100);
1895 /* Frees the data allocated by invariant motion. */
1897 static void
1898 free_inv_motion_data (void)
1900 unsigned i;
1901 struct def *def;
1902 struct invariant *inv;
1904 check_invariant_table_size ();
1905 for (i = 0; i < DF_DEFS_TABLE_SIZE (); i++)
1907 inv = invariant_table[i];
1908 if (inv)
1910 def = inv->def;
1911 gcc_assert (def != NULL);
1913 free_use_list (def->uses);
1914 free (def);
1915 invariant_table[i] = NULL;
1919 FOR_EACH_VEC_ELT (invariants, i, inv)
1921 BITMAP_FREE (inv->depends_on);
1922 free (inv);
1924 invariants.release ();
1927 /* Move the invariants out of the LOOP. */
1929 static void
1930 move_single_loop_invariants (struct loop *loop)
1932 init_inv_motion_data ();
1934 find_invariants (loop);
1935 find_invariants_to_move (optimize_loop_for_speed_p (loop),
1936 LOOP_DATA (loop)->has_call);
1937 move_invariants (loop);
1939 free_inv_motion_data ();
1942 /* Releases the auxiliary data for LOOP. */
1944 static void
1945 free_loop_data (struct loop *loop)
1947 struct loop_data *data = LOOP_DATA (loop);
1948 if (!data)
1949 return;
1951 bitmap_clear (&LOOP_DATA (loop)->regs_ref);
1952 bitmap_clear (&LOOP_DATA (loop)->regs_live);
1953 free (data);
1954 loop->aux = NULL;
1959 /* Registers currently living. */
1960 static bitmap_head curr_regs_live;
1962 /* Current reg pressure for each pressure class. */
1963 static int curr_reg_pressure[N_REG_CLASSES];
1965 /* Record all regs that are set in any one insn. Communication from
1966 mark_reg_{store,clobber} and global_conflicts. Asm can refer to
1967 all hard-registers. */
1968 static rtx regs_set[(FIRST_PSEUDO_REGISTER > MAX_RECOG_OPERANDS
1969 ? FIRST_PSEUDO_REGISTER : MAX_RECOG_OPERANDS) * 2];
1970 /* Number of regs stored in the previous array. */
1971 static int n_regs_set;
1973 /* Return pressure class and number of needed hard registers (through
1974 *NREGS) of register REGNO. */
1975 static enum reg_class
1976 get_regno_pressure_class (int regno, int *nregs)
1978 if (regno >= FIRST_PSEUDO_REGISTER)
1980 enum reg_class pressure_class;
1982 pressure_class = reg_allocno_class (regno);
1983 pressure_class = ira_pressure_class_translate[pressure_class];
1984 *nregs
1985 = ira_reg_class_max_nregs[pressure_class][PSEUDO_REGNO_MODE (regno)];
1986 return pressure_class;
1988 else if (! TEST_HARD_REG_BIT (ira_no_alloc_regs, regno)
1989 && ! TEST_HARD_REG_BIT (eliminable_regset, regno))
1991 *nregs = 1;
1992 return ira_pressure_class_translate[REGNO_REG_CLASS (regno)];
1994 else
1996 *nregs = 0;
1997 return NO_REGS;
2001 /* Increase (if INCR_P) or decrease current register pressure for
2002 register REGNO. */
2003 static void
2004 change_pressure (int regno, bool incr_p)
2006 int nregs;
2007 enum reg_class pressure_class;
2009 pressure_class = get_regno_pressure_class (regno, &nregs);
2010 if (! incr_p)
2011 curr_reg_pressure[pressure_class] -= nregs;
2012 else
2014 curr_reg_pressure[pressure_class] += nregs;
2015 if (LOOP_DATA (curr_loop)->max_reg_pressure[pressure_class]
2016 < curr_reg_pressure[pressure_class])
2017 LOOP_DATA (curr_loop)->max_reg_pressure[pressure_class]
2018 = curr_reg_pressure[pressure_class];
2022 /* Mark REGNO birth. */
2023 static void
2024 mark_regno_live (int regno)
2026 struct loop *loop;
2028 for (loop = curr_loop;
2029 loop != current_loops->tree_root;
2030 loop = loop_outer (loop))
2031 bitmap_set_bit (&LOOP_DATA (loop)->regs_live, regno);
2032 if (!bitmap_set_bit (&curr_regs_live, regno))
2033 return;
2034 change_pressure (regno, true);
2037 /* Mark REGNO death. */
2038 static void
2039 mark_regno_death (int regno)
2041 if (! bitmap_clear_bit (&curr_regs_live, regno))
2042 return;
2043 change_pressure (regno, false);
2046 /* Mark setting register REG. */
2047 static void
2048 mark_reg_store (rtx reg, const_rtx setter ATTRIBUTE_UNUSED,
2049 void *data ATTRIBUTE_UNUSED)
2051 if (GET_CODE (reg) == SUBREG)
2052 reg = SUBREG_REG (reg);
2054 if (! REG_P (reg))
2055 return;
2057 regs_set[n_regs_set++] = reg;
2059 unsigned int end_regno = END_REGNO (reg);
2060 for (unsigned int regno = REGNO (reg); regno < end_regno; ++regno)
2061 mark_regno_live (regno);
2064 /* Mark clobbering register REG. */
2065 static void
2066 mark_reg_clobber (rtx reg, const_rtx setter, void *data)
2068 if (GET_CODE (setter) == CLOBBER)
2069 mark_reg_store (reg, setter, data);
2072 /* Mark register REG death. */
2073 static void
2074 mark_reg_death (rtx reg)
2076 unsigned int end_regno = END_REGNO (reg);
2077 for (unsigned int regno = REGNO (reg); regno < end_regno; ++regno)
2078 mark_regno_death (regno);
2081 /* Mark occurrence of registers in X for the current loop. */
2082 static void
2083 mark_ref_regs (rtx x)
2085 RTX_CODE code;
2086 int i;
2087 const char *fmt;
2089 if (!x)
2090 return;
2092 code = GET_CODE (x);
2093 if (code == REG)
2095 struct loop *loop;
2097 for (loop = curr_loop;
2098 loop != current_loops->tree_root;
2099 loop = loop_outer (loop))
2100 bitmap_set_bit (&LOOP_DATA (loop)->regs_ref, REGNO (x));
2101 return;
2104 fmt = GET_RTX_FORMAT (code);
2105 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2106 if (fmt[i] == 'e')
2107 mark_ref_regs (XEXP (x, i));
2108 else if (fmt[i] == 'E')
2110 int j;
2112 for (j = 0; j < XVECLEN (x, i); j++)
2113 mark_ref_regs (XVECEXP (x, i, j));
2117 /* Calculate register pressure in the loops. */
2118 static void
2119 calculate_loop_reg_pressure (void)
2121 int i;
2122 unsigned int j;
2123 bitmap_iterator bi;
2124 basic_block bb;
2125 rtx_insn *insn;
2126 rtx link;
2127 struct loop *loop, *parent;
2129 FOR_EACH_LOOP (loop, 0)
2130 if (loop->aux == NULL)
2132 loop->aux = xcalloc (1, sizeof (struct loop_data));
2133 bitmap_initialize (&LOOP_DATA (loop)->regs_ref, &reg_obstack);
2134 bitmap_initialize (&LOOP_DATA (loop)->regs_live, &reg_obstack);
2136 ira_setup_eliminable_regset ();
2137 bitmap_initialize (&curr_regs_live, &reg_obstack);
2138 FOR_EACH_BB_FN (bb, cfun)
2140 curr_loop = bb->loop_father;
2141 if (curr_loop == current_loops->tree_root)
2142 continue;
2144 for (loop = curr_loop;
2145 loop != current_loops->tree_root;
2146 loop = loop_outer (loop))
2147 bitmap_ior_into (&LOOP_DATA (loop)->regs_live, DF_LR_IN (bb));
2149 bitmap_copy (&curr_regs_live, DF_LR_IN (bb));
2150 for (i = 0; i < ira_pressure_classes_num; i++)
2151 curr_reg_pressure[ira_pressure_classes[i]] = 0;
2152 EXECUTE_IF_SET_IN_BITMAP (&curr_regs_live, 0, j, bi)
2153 change_pressure (j, true);
2155 FOR_BB_INSNS (bb, insn)
2157 if (! NONDEBUG_INSN_P (insn))
2158 continue;
2160 mark_ref_regs (PATTERN (insn));
2161 n_regs_set = 0;
2162 note_stores (PATTERN (insn), mark_reg_clobber, NULL);
2164 /* Mark any registers dead after INSN as dead now. */
2166 for (link = REG_NOTES (insn); link; link = XEXP (link, 1))
2167 if (REG_NOTE_KIND (link) == REG_DEAD)
2168 mark_reg_death (XEXP (link, 0));
2170 /* Mark any registers set in INSN as live,
2171 and mark them as conflicting with all other live regs.
2172 Clobbers are processed again, so they conflict with
2173 the registers that are set. */
2175 note_stores (PATTERN (insn), mark_reg_store, NULL);
2177 if (AUTO_INC_DEC)
2178 for (link = REG_NOTES (insn); link; link = XEXP (link, 1))
2179 if (REG_NOTE_KIND (link) == REG_INC)
2180 mark_reg_store (XEXP (link, 0), NULL_RTX, NULL);
2182 while (n_regs_set-- > 0)
2184 rtx note = find_regno_note (insn, REG_UNUSED,
2185 REGNO (regs_set[n_regs_set]));
2186 if (! note)
2187 continue;
2189 mark_reg_death (XEXP (note, 0));
2193 bitmap_clear (&curr_regs_live);
2194 if (flag_ira_region == IRA_REGION_MIXED
2195 || flag_ira_region == IRA_REGION_ALL)
2196 FOR_EACH_LOOP (loop, 0)
2198 EXECUTE_IF_SET_IN_BITMAP (&LOOP_DATA (loop)->regs_live, 0, j, bi)
2199 if (! bitmap_bit_p (&LOOP_DATA (loop)->regs_ref, j))
2201 enum reg_class pressure_class;
2202 int nregs;
2204 pressure_class = get_regno_pressure_class (j, &nregs);
2205 LOOP_DATA (loop)->max_reg_pressure[pressure_class] -= nregs;
2208 if (dump_file == NULL)
2209 return;
2210 FOR_EACH_LOOP (loop, 0)
2212 parent = loop_outer (loop);
2213 fprintf (dump_file, "\n Loop %d (parent %d, header bb%d, depth %d)\n",
2214 loop->num, (parent == NULL ? -1 : parent->num),
2215 loop->header->index, loop_depth (loop));
2216 fprintf (dump_file, "\n ref. regnos:");
2217 EXECUTE_IF_SET_IN_BITMAP (&LOOP_DATA (loop)->regs_ref, 0, j, bi)
2218 fprintf (dump_file, " %d", j);
2219 fprintf (dump_file, "\n live regnos:");
2220 EXECUTE_IF_SET_IN_BITMAP (&LOOP_DATA (loop)->regs_live, 0, j, bi)
2221 fprintf (dump_file, " %d", j);
2222 fprintf (dump_file, "\n Pressure:");
2223 for (i = 0; (int) i < ira_pressure_classes_num; i++)
2225 enum reg_class pressure_class;
2227 pressure_class = ira_pressure_classes[i];
2228 if (LOOP_DATA (loop)->max_reg_pressure[pressure_class] == 0)
2229 continue;
2230 fprintf (dump_file, " %s=%d", reg_class_names[pressure_class],
2231 LOOP_DATA (loop)->max_reg_pressure[pressure_class]);
2233 fprintf (dump_file, "\n");
2239 /* Move the invariants out of the loops. */
2241 void
2242 move_loop_invariants (void)
2244 struct loop *loop;
2246 if (flag_ira_loop_pressure)
2248 df_analyze ();
2249 regstat_init_n_sets_and_refs ();
2250 ira_set_pseudo_classes (true, dump_file);
2251 calculate_loop_reg_pressure ();
2252 regstat_free_n_sets_and_refs ();
2254 df_set_flags (DF_EQ_NOTES + DF_DEFER_INSN_RESCAN);
2255 /* Process the loops, innermost first. */
2256 FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
2258 curr_loop = loop;
2259 /* move_single_loop_invariants for very large loops
2260 is time consuming and might need a lot of memory. */
2261 if (loop->num_nodes <= (unsigned) LOOP_INVARIANT_MAX_BBS_IN_LOOP)
2262 move_single_loop_invariants (loop);
2265 FOR_EACH_LOOP (loop, 0)
2267 free_loop_data (loop);
2270 if (flag_ira_loop_pressure)
2271 /* There is no sense to keep this info because it was most
2272 probably outdated by subsequent passes. */
2273 free_reg_info ();
2274 free (invariant_table);
2275 invariant_table = NULL;
2276 invariant_table_size = 0;
2278 checking_verify_flow_info ();