2013-03-21 Richard Biener <rguenther@suse.de>
[official-gcc.git] / gcc / tree-ssa-loop-im.c
blobac625959d1368f94fa0b0c499610dc76cd95ffc7
1 /* Loop invariant motion.
2 Copyright (C) 2003-2013 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 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "tm.h"
24 #include "tree.h"
25 #include "tm_p.h"
26 #include "basic-block.h"
27 #include "gimple-pretty-print.h"
28 #include "tree-flow.h"
29 #include "cfgloop.h"
30 #include "domwalk.h"
31 #include "params.h"
32 #include "tree-pass.h"
33 #include "flags.h"
34 #include "hashtab.h"
35 #include "tree-affine.h"
36 #include "pointer-set.h"
37 #include "tree-ssa-propagate.h"
39 /* TODO: Support for predicated code motion. I.e.
41 while (1)
43 if (cond)
45 a = inv;
46 something;
50 Where COND and INV are invariants, but evaluating INV may trap or be
51 invalid from some other reason if !COND. This may be transformed to
53 if (cond)
54 a = inv;
55 while (1)
57 if (cond)
58 something;
59 } */
61 /* A type for the list of statements that have to be moved in order to be able
62 to hoist an invariant computation. */
64 struct depend
66 gimple stmt;
67 struct depend *next;
70 /* The auxiliary data kept for each statement. */
72 struct lim_aux_data
74 struct loop *max_loop; /* The outermost loop in that the statement
75 is invariant. */
77 struct loop *tgt_loop; /* The loop out of that we want to move the
78 invariant. */
80 struct loop *always_executed_in;
81 /* The outermost loop for that we are sure
82 the statement is executed if the loop
83 is entered. */
85 unsigned cost; /* Cost of the computation performed by the
86 statement. */
88 struct depend *depends; /* List of statements that must be also hoisted
89 out of the loop when this statement is
90 hoisted; i.e. those that define the operands
91 of the statement and are inside of the
92 MAX_LOOP loop. */
95 /* Maps statements to their lim_aux_data. */
97 static struct pointer_map_t *lim_aux_data_map;
99 /* Description of a memory reference location. */
101 typedef struct mem_ref_loc
103 tree *ref; /* The reference itself. */
104 gimple stmt; /* The statement in that it occurs. */
105 } *mem_ref_loc_p;
108 /* The list of memory reference locations in a loop. */
110 typedef struct mem_ref_locs
112 vec<mem_ref_loc_p> locs;
113 } *mem_ref_locs_p;
116 /* Description of a memory reference. */
118 typedef struct mem_ref
120 unsigned id; /* ID assigned to the memory reference
121 (its index in memory_accesses.refs_list) */
122 hashval_t hash; /* Its hash value. */
124 /* The memory access itself and associated caching of alias-oracle
125 query meta-data. */
126 ao_ref mem;
128 bitmap stored; /* The set of loops in that this memory location
129 is stored to. */
130 vec<mem_ref_locs_p> accesses_in_loop;
131 /* The locations of the accesses. Vector
132 indexed by the loop number. */
134 /* The following sets are computed on demand. We keep both set and
135 its complement, so that we know whether the information was
136 already computed or not. */
137 bitmap indep_loop; /* The set of loops in that the memory
138 reference is independent, meaning:
139 If it is stored in the loop, this store
140 is independent on all other loads and
141 stores.
142 If it is only loaded, then it is independent
143 on all stores in the loop. */
144 bitmap dep_loop; /* The complement of INDEP_LOOP. */
146 bitmap indep_ref; /* The set of memory references on that
147 this reference is independent. */
148 bitmap dep_ref; /* The complement of INDEP_REF. */
149 } *mem_ref_p;
154 /* Description of memory accesses in loops. */
156 static struct
158 /* The hash table of memory references accessed in loops. */
159 htab_t refs;
161 /* The list of memory references. */
162 vec<mem_ref_p> refs_list;
164 /* The set of memory references accessed in each loop. */
165 vec<bitmap> refs_in_loop;
167 /* The set of memory references accessed in each loop, including
168 subloops. */
169 vec<bitmap> all_refs_in_loop;
171 /* The set of memory references stored in each loop, including
172 subloops. */
173 vec<bitmap> all_refs_stored_in_loop;
175 /* Cache for expanding memory addresses. */
176 struct pointer_map_t *ttae_cache;
177 } memory_accesses;
179 /* Obstack for the bitmaps in the above data structures. */
180 static bitmap_obstack lim_bitmap_obstack;
182 static bool ref_indep_loop_p (struct loop *, mem_ref_p);
184 /* Minimum cost of an expensive expression. */
185 #define LIM_EXPENSIVE ((unsigned) PARAM_VALUE (PARAM_LIM_EXPENSIVE))
187 /* The outermost loop for which execution of the header guarantees that the
188 block will be executed. */
189 #define ALWAYS_EXECUTED_IN(BB) ((struct loop *) (BB)->aux)
190 #define SET_ALWAYS_EXECUTED_IN(BB, VAL) ((BB)->aux = (void *) (VAL))
192 /* ID of the shared unanalyzable mem. */
193 #define UNANALYZABLE_MEM_ID 0
195 /* Whether the reference was analyzable. */
196 #define MEM_ANALYZABLE(REF) ((REF)->id != UNANALYZABLE_MEM_ID)
198 static struct lim_aux_data *
199 init_lim_data (gimple stmt)
201 void **p = pointer_map_insert (lim_aux_data_map, stmt);
203 *p = XCNEW (struct lim_aux_data);
204 return (struct lim_aux_data *) *p;
207 static struct lim_aux_data *
208 get_lim_data (gimple stmt)
210 void **p = pointer_map_contains (lim_aux_data_map, stmt);
211 if (!p)
212 return NULL;
214 return (struct lim_aux_data *) *p;
217 /* Releases the memory occupied by DATA. */
219 static void
220 free_lim_aux_data (struct lim_aux_data *data)
222 struct depend *dep, *next;
224 for (dep = data->depends; dep; dep = next)
226 next = dep->next;
227 free (dep);
229 free (data);
232 static void
233 clear_lim_data (gimple stmt)
235 void **p = pointer_map_contains (lim_aux_data_map, stmt);
236 if (!p)
237 return;
239 free_lim_aux_data ((struct lim_aux_data *) *p);
240 *p = NULL;
243 /* Calls CBCK for each index in memory reference ADDR_P. There are two
244 kinds situations handled; in each of these cases, the memory reference
245 and DATA are passed to the callback:
247 Access to an array: ARRAY_{RANGE_}REF (base, index). In this case we also
248 pass the pointer to the index to the callback.
250 Pointer dereference: INDIRECT_REF (addr). In this case we also pass the
251 pointer to addr to the callback.
253 If the callback returns false, the whole search stops and false is returned.
254 Otherwise the function returns true after traversing through the whole
255 reference *ADDR_P. */
257 bool
258 for_each_index (tree *addr_p, bool (*cbck) (tree, tree *, void *), void *data)
260 tree *nxt, *idx;
262 for (; ; addr_p = nxt)
264 switch (TREE_CODE (*addr_p))
266 case SSA_NAME:
267 return cbck (*addr_p, addr_p, data);
269 case MEM_REF:
270 nxt = &TREE_OPERAND (*addr_p, 0);
271 return cbck (*addr_p, nxt, data);
273 case BIT_FIELD_REF:
274 case VIEW_CONVERT_EXPR:
275 case REALPART_EXPR:
276 case IMAGPART_EXPR:
277 nxt = &TREE_OPERAND (*addr_p, 0);
278 break;
280 case COMPONENT_REF:
281 /* If the component has varying offset, it behaves like index
282 as well. */
283 idx = &TREE_OPERAND (*addr_p, 2);
284 if (*idx
285 && !cbck (*addr_p, idx, data))
286 return false;
288 nxt = &TREE_OPERAND (*addr_p, 0);
289 break;
291 case ARRAY_REF:
292 case ARRAY_RANGE_REF:
293 nxt = &TREE_OPERAND (*addr_p, 0);
294 if (!cbck (*addr_p, &TREE_OPERAND (*addr_p, 1), data))
295 return false;
296 break;
298 case VAR_DECL:
299 case PARM_DECL:
300 case CONST_DECL:
301 case STRING_CST:
302 case RESULT_DECL:
303 case VECTOR_CST:
304 case COMPLEX_CST:
305 case INTEGER_CST:
306 case REAL_CST:
307 case FIXED_CST:
308 case CONSTRUCTOR:
309 return true;
311 case ADDR_EXPR:
312 gcc_assert (is_gimple_min_invariant (*addr_p));
313 return true;
315 case TARGET_MEM_REF:
316 idx = &TMR_BASE (*addr_p);
317 if (*idx
318 && !cbck (*addr_p, idx, data))
319 return false;
320 idx = &TMR_INDEX (*addr_p);
321 if (*idx
322 && !cbck (*addr_p, idx, data))
323 return false;
324 idx = &TMR_INDEX2 (*addr_p);
325 if (*idx
326 && !cbck (*addr_p, idx, data))
327 return false;
328 return true;
330 default:
331 gcc_unreachable ();
336 /* If it is possible to hoist the statement STMT unconditionally,
337 returns MOVE_POSSIBLE.
338 If it is possible to hoist the statement STMT, but we must avoid making
339 it executed if it would not be executed in the original program (e.g.
340 because it may trap), return MOVE_PRESERVE_EXECUTION.
341 Otherwise return MOVE_IMPOSSIBLE. */
343 enum move_pos
344 movement_possibility (gimple stmt)
346 tree lhs;
347 enum move_pos ret = MOVE_POSSIBLE;
349 if (flag_unswitch_loops
350 && gimple_code (stmt) == GIMPLE_COND)
352 /* If we perform unswitching, force the operands of the invariant
353 condition to be moved out of the loop. */
354 return MOVE_POSSIBLE;
357 if (gimple_code (stmt) == GIMPLE_PHI
358 && gimple_phi_num_args (stmt) <= 2
359 && !virtual_operand_p (gimple_phi_result (stmt))
360 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (gimple_phi_result (stmt)))
361 return MOVE_POSSIBLE;
363 if (gimple_get_lhs (stmt) == NULL_TREE)
364 return MOVE_IMPOSSIBLE;
366 if (gimple_vdef (stmt))
367 return MOVE_IMPOSSIBLE;
369 if (stmt_ends_bb_p (stmt)
370 || gimple_has_volatile_ops (stmt)
371 || gimple_has_side_effects (stmt)
372 || stmt_could_throw_p (stmt))
373 return MOVE_IMPOSSIBLE;
375 if (is_gimple_call (stmt))
377 /* While pure or const call is guaranteed to have no side effects, we
378 cannot move it arbitrarily. Consider code like
380 char *s = something ();
382 while (1)
384 if (s)
385 t = strlen (s);
386 else
387 t = 0;
390 Here the strlen call cannot be moved out of the loop, even though
391 s is invariant. In addition to possibly creating a call with
392 invalid arguments, moving out a function call that is not executed
393 may cause performance regressions in case the call is costly and
394 not executed at all. */
395 ret = MOVE_PRESERVE_EXECUTION;
396 lhs = gimple_call_lhs (stmt);
398 else if (is_gimple_assign (stmt))
399 lhs = gimple_assign_lhs (stmt);
400 else
401 return MOVE_IMPOSSIBLE;
403 if (TREE_CODE (lhs) == SSA_NAME
404 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
405 return MOVE_IMPOSSIBLE;
407 if (TREE_CODE (lhs) != SSA_NAME
408 || gimple_could_trap_p (stmt))
409 return MOVE_PRESERVE_EXECUTION;
411 /* Non local loads in a transaction cannot be hoisted out. Well,
412 unless the load happens on every path out of the loop, but we
413 don't take this into account yet. */
414 if (flag_tm
415 && gimple_in_transaction (stmt)
416 && gimple_assign_single_p (stmt))
418 tree rhs = gimple_assign_rhs1 (stmt);
419 if (DECL_P (rhs) && is_global_var (rhs))
421 if (dump_file)
423 fprintf (dump_file, "Cannot hoist conditional load of ");
424 print_generic_expr (dump_file, rhs, TDF_SLIM);
425 fprintf (dump_file, " because it is in a transaction.\n");
427 return MOVE_IMPOSSIBLE;
431 return ret;
434 /* Suppose that operand DEF is used inside the LOOP. Returns the outermost
435 loop to that we could move the expression using DEF if it did not have
436 other operands, i.e. the outermost loop enclosing LOOP in that the value
437 of DEF is invariant. */
439 static struct loop *
440 outermost_invariant_loop (tree def, struct loop *loop)
442 gimple def_stmt;
443 basic_block def_bb;
444 struct loop *max_loop;
445 struct lim_aux_data *lim_data;
447 if (!def)
448 return superloop_at_depth (loop, 1);
450 if (TREE_CODE (def) != SSA_NAME)
452 gcc_assert (is_gimple_min_invariant (def));
453 return superloop_at_depth (loop, 1);
456 def_stmt = SSA_NAME_DEF_STMT (def);
457 def_bb = gimple_bb (def_stmt);
458 if (!def_bb)
459 return superloop_at_depth (loop, 1);
461 max_loop = find_common_loop (loop, def_bb->loop_father);
463 lim_data = get_lim_data (def_stmt);
464 if (lim_data != NULL && lim_data->max_loop != NULL)
465 max_loop = find_common_loop (max_loop,
466 loop_outer (lim_data->max_loop));
467 if (max_loop == loop)
468 return NULL;
469 max_loop = superloop_at_depth (loop, loop_depth (max_loop) + 1);
471 return max_loop;
474 /* DATA is a structure containing information associated with a statement
475 inside LOOP. DEF is one of the operands of this statement.
477 Find the outermost loop enclosing LOOP in that value of DEF is invariant
478 and record this in DATA->max_loop field. If DEF itself is defined inside
479 this loop as well (i.e. we need to hoist it out of the loop if we want
480 to hoist the statement represented by DATA), record the statement in that
481 DEF is defined to the DATA->depends list. Additionally if ADD_COST is true,
482 add the cost of the computation of DEF to the DATA->cost.
484 If DEF is not invariant in LOOP, return false. Otherwise return TRUE. */
486 static bool
487 add_dependency (tree def, struct lim_aux_data *data, struct loop *loop,
488 bool add_cost)
490 gimple def_stmt = SSA_NAME_DEF_STMT (def);
491 basic_block def_bb = gimple_bb (def_stmt);
492 struct loop *max_loop;
493 struct depend *dep;
494 struct lim_aux_data *def_data;
496 if (!def_bb)
497 return true;
499 max_loop = outermost_invariant_loop (def, loop);
500 if (!max_loop)
501 return false;
503 if (flow_loop_nested_p (data->max_loop, max_loop))
504 data->max_loop = max_loop;
506 def_data = get_lim_data (def_stmt);
507 if (!def_data)
508 return true;
510 if (add_cost
511 /* Only add the cost if the statement defining DEF is inside LOOP,
512 i.e. if it is likely that by moving the invariants dependent
513 on it, we will be able to avoid creating a new register for
514 it (since it will be only used in these dependent invariants). */
515 && def_bb->loop_father == loop)
516 data->cost += def_data->cost;
518 dep = XNEW (struct depend);
519 dep->stmt = def_stmt;
520 dep->next = data->depends;
521 data->depends = dep;
523 return true;
526 /* Returns an estimate for a cost of statement STMT. The values here
527 are just ad-hoc constants, similar to costs for inlining. */
529 static unsigned
530 stmt_cost (gimple stmt)
532 /* Always try to create possibilities for unswitching. */
533 if (gimple_code (stmt) == GIMPLE_COND
534 || gimple_code (stmt) == GIMPLE_PHI)
535 return LIM_EXPENSIVE;
537 /* We should be hoisting calls if possible. */
538 if (is_gimple_call (stmt))
540 tree fndecl;
542 /* Unless the call is a builtin_constant_p; this always folds to a
543 constant, so moving it is useless. */
544 fndecl = gimple_call_fndecl (stmt);
545 if (fndecl
546 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
547 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CONSTANT_P)
548 return 0;
550 return LIM_EXPENSIVE;
553 /* Hoisting memory references out should almost surely be a win. */
554 if (gimple_references_memory_p (stmt))
555 return LIM_EXPENSIVE;
557 if (gimple_code (stmt) != GIMPLE_ASSIGN)
558 return 1;
560 switch (gimple_assign_rhs_code (stmt))
562 case MULT_EXPR:
563 case WIDEN_MULT_EXPR:
564 case WIDEN_MULT_PLUS_EXPR:
565 case WIDEN_MULT_MINUS_EXPR:
566 case DOT_PROD_EXPR:
567 case FMA_EXPR:
568 case TRUNC_DIV_EXPR:
569 case CEIL_DIV_EXPR:
570 case FLOOR_DIV_EXPR:
571 case ROUND_DIV_EXPR:
572 case EXACT_DIV_EXPR:
573 case CEIL_MOD_EXPR:
574 case FLOOR_MOD_EXPR:
575 case ROUND_MOD_EXPR:
576 case TRUNC_MOD_EXPR:
577 case RDIV_EXPR:
578 /* Division and multiplication are usually expensive. */
579 return LIM_EXPENSIVE;
581 case LSHIFT_EXPR:
582 case RSHIFT_EXPR:
583 case WIDEN_LSHIFT_EXPR:
584 case LROTATE_EXPR:
585 case RROTATE_EXPR:
586 /* Shifts and rotates are usually expensive. */
587 return LIM_EXPENSIVE;
589 case CONSTRUCTOR:
590 /* Make vector construction cost proportional to the number
591 of elements. */
592 return CONSTRUCTOR_NELTS (gimple_assign_rhs1 (stmt));
594 case SSA_NAME:
595 case PAREN_EXPR:
596 /* Whether or not something is wrapped inside a PAREN_EXPR
597 should not change move cost. Nor should an intermediate
598 unpropagated SSA name copy. */
599 return 0;
601 default:
602 return 1;
606 /* Finds the outermost loop between OUTER and LOOP in that the memory reference
607 REF is independent. If REF is not independent in LOOP, NULL is returned
608 instead. */
610 static struct loop *
611 outermost_indep_loop (struct loop *outer, struct loop *loop, mem_ref_p ref)
613 struct loop *aloop;
615 if (bitmap_bit_p (ref->stored, loop->num))
616 return NULL;
618 for (aloop = outer;
619 aloop != loop;
620 aloop = superloop_at_depth (loop, loop_depth (aloop) + 1))
621 if (!bitmap_bit_p (ref->stored, aloop->num)
622 && ref_indep_loop_p (aloop, ref))
623 return aloop;
625 if (ref_indep_loop_p (loop, ref))
626 return loop;
627 else
628 return NULL;
631 /* If there is a simple load or store to a memory reference in STMT, returns
632 the location of the memory reference, and sets IS_STORE according to whether
633 it is a store or load. Otherwise, returns NULL. */
635 static tree *
636 simple_mem_ref_in_stmt (gimple stmt, bool *is_store)
638 tree *lhs, *rhs;
640 /* Recognize SSA_NAME = MEM and MEM = (SSA_NAME | invariant) patterns. */
641 if (!gimple_assign_single_p (stmt))
642 return NULL;
644 lhs = gimple_assign_lhs_ptr (stmt);
645 rhs = gimple_assign_rhs1_ptr (stmt);
647 if (TREE_CODE (*lhs) == SSA_NAME && gimple_vuse (stmt))
649 *is_store = false;
650 return rhs;
652 else if (gimple_vdef (stmt)
653 && (TREE_CODE (*rhs) == SSA_NAME || is_gimple_min_invariant (*rhs)))
655 *is_store = true;
656 return lhs;
658 else
659 return NULL;
662 /* Returns the memory reference contained in STMT. */
664 static mem_ref_p
665 mem_ref_in_stmt (gimple stmt)
667 bool store;
668 tree *mem = simple_mem_ref_in_stmt (stmt, &store);
669 hashval_t hash;
670 mem_ref_p ref;
672 if (!mem)
673 return NULL;
674 gcc_assert (!store);
676 hash = iterative_hash_expr (*mem, 0);
677 ref = (mem_ref_p) htab_find_with_hash (memory_accesses.refs, *mem, hash);
679 gcc_assert (ref != NULL);
680 return ref;
683 /* From a controlling predicate in DOM determine the arguments from
684 the PHI node PHI that are chosen if the predicate evaluates to
685 true and false and store them to *TRUE_ARG_P and *FALSE_ARG_P if
686 they are non-NULL. Returns true if the arguments can be determined,
687 else return false. */
689 static bool
690 extract_true_false_args_from_phi (basic_block dom, gimple phi,
691 tree *true_arg_p, tree *false_arg_p)
693 basic_block bb = gimple_bb (phi);
694 edge true_edge, false_edge, tem;
695 tree arg0 = NULL_TREE, arg1 = NULL_TREE;
697 /* We have to verify that one edge into the PHI node is dominated
698 by the true edge of the predicate block and the other edge
699 dominated by the false edge. This ensures that the PHI argument
700 we are going to take is completely determined by the path we
701 take from the predicate block.
702 We can only use BB dominance checks below if the destination of
703 the true/false edges are dominated by their edge, thus only
704 have a single predecessor. */
705 extract_true_false_edges_from_block (dom, &true_edge, &false_edge);
706 tem = EDGE_PRED (bb, 0);
707 if (tem == true_edge
708 || (single_pred_p (true_edge->dest)
709 && (tem->src == true_edge->dest
710 || dominated_by_p (CDI_DOMINATORS,
711 tem->src, true_edge->dest))))
712 arg0 = PHI_ARG_DEF (phi, tem->dest_idx);
713 else if (tem == false_edge
714 || (single_pred_p (false_edge->dest)
715 && (tem->src == false_edge->dest
716 || dominated_by_p (CDI_DOMINATORS,
717 tem->src, false_edge->dest))))
718 arg1 = PHI_ARG_DEF (phi, tem->dest_idx);
719 else
720 return false;
721 tem = EDGE_PRED (bb, 1);
722 if (tem == true_edge
723 || (single_pred_p (true_edge->dest)
724 && (tem->src == true_edge->dest
725 || dominated_by_p (CDI_DOMINATORS,
726 tem->src, true_edge->dest))))
727 arg0 = PHI_ARG_DEF (phi, tem->dest_idx);
728 else if (tem == false_edge
729 || (single_pred_p (false_edge->dest)
730 && (tem->src == false_edge->dest
731 || dominated_by_p (CDI_DOMINATORS,
732 tem->src, false_edge->dest))))
733 arg1 = PHI_ARG_DEF (phi, tem->dest_idx);
734 else
735 return false;
736 if (!arg0 || !arg1)
737 return false;
739 if (true_arg_p)
740 *true_arg_p = arg0;
741 if (false_arg_p)
742 *false_arg_p = arg1;
744 return true;
747 /* Determine the outermost loop to that it is possible to hoist a statement
748 STMT and store it to LIM_DATA (STMT)->max_loop. To do this we determine
749 the outermost loop in that the value computed by STMT is invariant.
750 If MUST_PRESERVE_EXEC is true, additionally choose such a loop that
751 we preserve the fact whether STMT is executed. It also fills other related
752 information to LIM_DATA (STMT).
754 The function returns false if STMT cannot be hoisted outside of the loop it
755 is defined in, and true otherwise. */
757 static bool
758 determine_max_movement (gimple stmt, bool must_preserve_exec)
760 basic_block bb = gimple_bb (stmt);
761 struct loop *loop = bb->loop_father;
762 struct loop *level;
763 struct lim_aux_data *lim_data = get_lim_data (stmt);
764 tree val;
765 ssa_op_iter iter;
767 if (must_preserve_exec)
768 level = ALWAYS_EXECUTED_IN (bb);
769 else
770 level = superloop_at_depth (loop, 1);
771 lim_data->max_loop = level;
773 if (gimple_code (stmt) == GIMPLE_PHI)
775 use_operand_p use_p;
776 unsigned min_cost = UINT_MAX;
777 unsigned total_cost = 0;
778 struct lim_aux_data *def_data;
780 /* We will end up promoting dependencies to be unconditionally
781 evaluated. For this reason the PHI cost (and thus the
782 cost we remove from the loop by doing the invariant motion)
783 is that of the cheapest PHI argument dependency chain. */
784 FOR_EACH_PHI_ARG (use_p, stmt, iter, SSA_OP_USE)
786 val = USE_FROM_PTR (use_p);
787 if (TREE_CODE (val) != SSA_NAME)
788 continue;
789 if (!add_dependency (val, lim_data, loop, false))
790 return false;
791 def_data = get_lim_data (SSA_NAME_DEF_STMT (val));
792 if (def_data)
794 min_cost = MIN (min_cost, def_data->cost);
795 total_cost += def_data->cost;
799 lim_data->cost += min_cost;
801 if (gimple_phi_num_args (stmt) > 1)
803 basic_block dom = get_immediate_dominator (CDI_DOMINATORS, bb);
804 gimple cond;
805 if (gsi_end_p (gsi_last_bb (dom)))
806 return false;
807 cond = gsi_stmt (gsi_last_bb (dom));
808 if (gimple_code (cond) != GIMPLE_COND)
809 return false;
810 /* Verify that this is an extended form of a diamond and
811 the PHI arguments are completely controlled by the
812 predicate in DOM. */
813 if (!extract_true_false_args_from_phi (dom, stmt, NULL, NULL))
814 return false;
816 /* Fold in dependencies and cost of the condition. */
817 FOR_EACH_SSA_TREE_OPERAND (val, cond, iter, SSA_OP_USE)
819 if (!add_dependency (val, lim_data, loop, false))
820 return false;
821 def_data = get_lim_data (SSA_NAME_DEF_STMT (val));
822 if (def_data)
823 total_cost += def_data->cost;
826 /* We want to avoid unconditionally executing very expensive
827 operations. As costs for our dependencies cannot be
828 negative just claim we are not invariand for this case.
829 We also are not sure whether the control-flow inside the
830 loop will vanish. */
831 if (total_cost - min_cost >= 2 * LIM_EXPENSIVE
832 && !(min_cost != 0
833 && total_cost / min_cost <= 2))
834 return false;
836 /* Assume that the control-flow in the loop will vanish.
837 ??? We should verify this and not artificially increase
838 the cost if that is not the case. */
839 lim_data->cost += stmt_cost (stmt);
842 return true;
844 else
845 FOR_EACH_SSA_TREE_OPERAND (val, stmt, iter, SSA_OP_USE)
846 if (!add_dependency (val, lim_data, loop, true))
847 return false;
849 if (gimple_vuse (stmt))
851 mem_ref_p ref = mem_ref_in_stmt (stmt);
853 if (ref)
855 lim_data->max_loop
856 = outermost_indep_loop (lim_data->max_loop, loop, ref);
857 if (!lim_data->max_loop)
858 return false;
860 else
862 if ((val = gimple_vuse (stmt)) != NULL_TREE)
864 if (!add_dependency (val, lim_data, loop, false))
865 return false;
870 lim_data->cost += stmt_cost (stmt);
872 return true;
875 /* Suppose that some statement in ORIG_LOOP is hoisted to the loop LEVEL,
876 and that one of the operands of this statement is computed by STMT.
877 Ensure that STMT (together with all the statements that define its
878 operands) is hoisted at least out of the loop LEVEL. */
880 static void
881 set_level (gimple stmt, struct loop *orig_loop, struct loop *level)
883 struct loop *stmt_loop = gimple_bb (stmt)->loop_father;
884 struct depend *dep;
885 struct lim_aux_data *lim_data;
887 stmt_loop = find_common_loop (orig_loop, stmt_loop);
888 lim_data = get_lim_data (stmt);
889 if (lim_data != NULL && lim_data->tgt_loop != NULL)
890 stmt_loop = find_common_loop (stmt_loop,
891 loop_outer (lim_data->tgt_loop));
892 if (flow_loop_nested_p (stmt_loop, level))
893 return;
895 gcc_assert (level == lim_data->max_loop
896 || flow_loop_nested_p (lim_data->max_loop, level));
898 lim_data->tgt_loop = level;
899 for (dep = lim_data->depends; dep; dep = dep->next)
900 set_level (dep->stmt, orig_loop, level);
903 /* Determines an outermost loop from that we want to hoist the statement STMT.
904 For now we chose the outermost possible loop. TODO -- use profiling
905 information to set it more sanely. */
907 static void
908 set_profitable_level (gimple stmt)
910 set_level (stmt, gimple_bb (stmt)->loop_father, get_lim_data (stmt)->max_loop);
913 /* Returns true if STMT is a call that has side effects. */
915 static bool
916 nonpure_call_p (gimple stmt)
918 if (gimple_code (stmt) != GIMPLE_CALL)
919 return false;
921 return gimple_has_side_effects (stmt);
924 /* Rewrite a/b to a*(1/b). Return the invariant stmt to process. */
926 static gimple
927 rewrite_reciprocal (gimple_stmt_iterator *bsi)
929 gimple stmt, stmt1, stmt2;
930 tree name, lhs, type;
931 tree real_one;
932 gimple_stmt_iterator gsi;
934 stmt = gsi_stmt (*bsi);
935 lhs = gimple_assign_lhs (stmt);
936 type = TREE_TYPE (lhs);
938 real_one = build_one_cst (type);
940 name = make_temp_ssa_name (type, NULL, "reciptmp");
941 stmt1 = gimple_build_assign_with_ops (RDIV_EXPR, name, real_one,
942 gimple_assign_rhs2 (stmt));
944 stmt2 = gimple_build_assign_with_ops (MULT_EXPR, lhs, name,
945 gimple_assign_rhs1 (stmt));
947 /* Replace division stmt with reciprocal and multiply stmts.
948 The multiply stmt is not invariant, so update iterator
949 and avoid rescanning. */
950 gsi = *bsi;
951 gsi_insert_before (bsi, stmt1, GSI_NEW_STMT);
952 gsi_replace (&gsi, stmt2, true);
954 /* Continue processing with invariant reciprocal statement. */
955 return stmt1;
958 /* Check if the pattern at *BSI is a bittest of the form
959 (A >> B) & 1 != 0 and in this case rewrite it to A & (1 << B) != 0. */
961 static gimple
962 rewrite_bittest (gimple_stmt_iterator *bsi)
964 gimple stmt, use_stmt, stmt1, stmt2;
965 tree lhs, name, t, a, b;
966 use_operand_p use;
968 stmt = gsi_stmt (*bsi);
969 lhs = gimple_assign_lhs (stmt);
971 /* Verify that the single use of lhs is a comparison against zero. */
972 if (TREE_CODE (lhs) != SSA_NAME
973 || !single_imm_use (lhs, &use, &use_stmt)
974 || gimple_code (use_stmt) != GIMPLE_COND)
975 return stmt;
976 if (gimple_cond_lhs (use_stmt) != lhs
977 || (gimple_cond_code (use_stmt) != NE_EXPR
978 && gimple_cond_code (use_stmt) != EQ_EXPR)
979 || !integer_zerop (gimple_cond_rhs (use_stmt)))
980 return stmt;
982 /* Get at the operands of the shift. The rhs is TMP1 & 1. */
983 stmt1 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
984 if (gimple_code (stmt1) != GIMPLE_ASSIGN)
985 return stmt;
987 /* There is a conversion in between possibly inserted by fold. */
988 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt1)))
990 t = gimple_assign_rhs1 (stmt1);
991 if (TREE_CODE (t) != SSA_NAME
992 || !has_single_use (t))
993 return stmt;
994 stmt1 = SSA_NAME_DEF_STMT (t);
995 if (gimple_code (stmt1) != GIMPLE_ASSIGN)
996 return stmt;
999 /* Verify that B is loop invariant but A is not. Verify that with
1000 all the stmt walking we are still in the same loop. */
1001 if (gimple_assign_rhs_code (stmt1) != RSHIFT_EXPR
1002 || loop_containing_stmt (stmt1) != loop_containing_stmt (stmt))
1003 return stmt;
1005 a = gimple_assign_rhs1 (stmt1);
1006 b = gimple_assign_rhs2 (stmt1);
1008 if (outermost_invariant_loop (b, loop_containing_stmt (stmt1)) != NULL
1009 && outermost_invariant_loop (a, loop_containing_stmt (stmt1)) == NULL)
1011 gimple_stmt_iterator rsi;
1013 /* 1 << B */
1014 t = fold_build2 (LSHIFT_EXPR, TREE_TYPE (a),
1015 build_int_cst (TREE_TYPE (a), 1), b);
1016 name = make_temp_ssa_name (TREE_TYPE (a), NULL, "shifttmp");
1017 stmt1 = gimple_build_assign (name, t);
1019 /* A & (1 << B) */
1020 t = fold_build2 (BIT_AND_EXPR, TREE_TYPE (a), a, name);
1021 name = make_temp_ssa_name (TREE_TYPE (a), NULL, "shifttmp");
1022 stmt2 = gimple_build_assign (name, t);
1024 /* Replace the SSA_NAME we compare against zero. Adjust
1025 the type of zero accordingly. */
1026 SET_USE (use, name);
1027 gimple_cond_set_rhs (use_stmt, build_int_cst_type (TREE_TYPE (name), 0));
1029 /* Don't use gsi_replace here, none of the new assignments sets
1030 the variable originally set in stmt. Move bsi to stmt1, and
1031 then remove the original stmt, so that we get a chance to
1032 retain debug info for it. */
1033 rsi = *bsi;
1034 gsi_insert_before (bsi, stmt1, GSI_NEW_STMT);
1035 gsi_insert_before (&rsi, stmt2, GSI_SAME_STMT);
1036 gsi_remove (&rsi, true);
1038 return stmt1;
1041 return stmt;
1045 /* Determine the outermost loops in that statements in basic block BB are
1046 invariant, and record them to the LIM_DATA associated with the statements.
1047 Callback for walk_dominator_tree. */
1049 static void
1050 determine_invariantness_stmt (struct dom_walk_data *dw_data ATTRIBUTE_UNUSED,
1051 basic_block bb)
1053 enum move_pos pos;
1054 gimple_stmt_iterator bsi;
1055 gimple stmt;
1056 bool maybe_never = ALWAYS_EXECUTED_IN (bb) == NULL;
1057 struct loop *outermost = ALWAYS_EXECUTED_IN (bb);
1058 struct lim_aux_data *lim_data;
1060 if (!loop_outer (bb->loop_father))
1061 return;
1063 if (dump_file && (dump_flags & TDF_DETAILS))
1064 fprintf (dump_file, "Basic block %d (loop %d -- depth %d):\n\n",
1065 bb->index, bb->loop_father->num, loop_depth (bb->loop_father));
1067 /* Look at PHI nodes, but only if there is at most two.
1068 ??? We could relax this further by post-processing the inserted
1069 code and transforming adjacent cond-exprs with the same predicate
1070 to control flow again. */
1071 bsi = gsi_start_phis (bb);
1072 if (!gsi_end_p (bsi)
1073 && ((gsi_next (&bsi), gsi_end_p (bsi))
1074 || (gsi_next (&bsi), gsi_end_p (bsi))))
1075 for (bsi = gsi_start_phis (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1077 stmt = gsi_stmt (bsi);
1079 pos = movement_possibility (stmt);
1080 if (pos == MOVE_IMPOSSIBLE)
1081 continue;
1083 lim_data = init_lim_data (stmt);
1084 lim_data->always_executed_in = outermost;
1086 if (!determine_max_movement (stmt, false))
1088 lim_data->max_loop = NULL;
1089 continue;
1092 if (dump_file && (dump_flags & TDF_DETAILS))
1094 print_gimple_stmt (dump_file, stmt, 2, 0);
1095 fprintf (dump_file, " invariant up to level %d, cost %d.\n\n",
1096 loop_depth (lim_data->max_loop),
1097 lim_data->cost);
1100 if (lim_data->cost >= LIM_EXPENSIVE)
1101 set_profitable_level (stmt);
1104 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1106 stmt = gsi_stmt (bsi);
1108 pos = movement_possibility (stmt);
1109 if (pos == MOVE_IMPOSSIBLE)
1111 if (nonpure_call_p (stmt))
1113 maybe_never = true;
1114 outermost = NULL;
1116 /* Make sure to note always_executed_in for stores to make
1117 store-motion work. */
1118 else if (stmt_makes_single_store (stmt))
1120 struct lim_aux_data *lim_data = init_lim_data (stmt);
1121 lim_data->always_executed_in = outermost;
1123 continue;
1126 if (is_gimple_assign (stmt)
1127 && (get_gimple_rhs_class (gimple_assign_rhs_code (stmt))
1128 == GIMPLE_BINARY_RHS))
1130 tree op0 = gimple_assign_rhs1 (stmt);
1131 tree op1 = gimple_assign_rhs2 (stmt);
1132 struct loop *ol1 = outermost_invariant_loop (op1,
1133 loop_containing_stmt (stmt));
1135 /* If divisor is invariant, convert a/b to a*(1/b), allowing reciprocal
1136 to be hoisted out of loop, saving expensive divide. */
1137 if (pos == MOVE_POSSIBLE
1138 && gimple_assign_rhs_code (stmt) == RDIV_EXPR
1139 && flag_unsafe_math_optimizations
1140 && !flag_trapping_math
1141 && ol1 != NULL
1142 && outermost_invariant_loop (op0, ol1) == NULL)
1143 stmt = rewrite_reciprocal (&bsi);
1145 /* If the shift count is invariant, convert (A >> B) & 1 to
1146 A & (1 << B) allowing the bit mask to be hoisted out of the loop
1147 saving an expensive shift. */
1148 if (pos == MOVE_POSSIBLE
1149 && gimple_assign_rhs_code (stmt) == BIT_AND_EXPR
1150 && integer_onep (op1)
1151 && TREE_CODE (op0) == SSA_NAME
1152 && has_single_use (op0))
1153 stmt = rewrite_bittest (&bsi);
1156 lim_data = init_lim_data (stmt);
1157 lim_data->always_executed_in = outermost;
1159 if (maybe_never && pos == MOVE_PRESERVE_EXECUTION)
1160 continue;
1162 if (!determine_max_movement (stmt, pos == MOVE_PRESERVE_EXECUTION))
1164 lim_data->max_loop = NULL;
1165 continue;
1168 if (dump_file && (dump_flags & TDF_DETAILS))
1170 print_gimple_stmt (dump_file, stmt, 2, 0);
1171 fprintf (dump_file, " invariant up to level %d, cost %d.\n\n",
1172 loop_depth (lim_data->max_loop),
1173 lim_data->cost);
1176 if (lim_data->cost >= LIM_EXPENSIVE)
1177 set_profitable_level (stmt);
1181 /* For each statement determines the outermost loop in that it is invariant,
1182 statements on whose motion it depends and the cost of the computation.
1183 This information is stored to the LIM_DATA structure associated with
1184 each statement. */
1186 static void
1187 determine_invariantness (void)
1189 struct dom_walk_data walk_data;
1191 memset (&walk_data, 0, sizeof (struct dom_walk_data));
1192 walk_data.dom_direction = CDI_DOMINATORS;
1193 walk_data.before_dom_children = determine_invariantness_stmt;
1195 init_walk_dominator_tree (&walk_data);
1196 walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
1197 fini_walk_dominator_tree (&walk_data);
1200 /* Hoist the statements in basic block BB out of the loops prescribed by
1201 data stored in LIM_DATA structures associated with each statement. Callback
1202 for walk_dominator_tree. */
1204 static void
1205 move_computations_stmt (struct dom_walk_data *dw_data,
1206 basic_block bb)
1208 struct loop *level;
1209 gimple_stmt_iterator bsi;
1210 gimple stmt;
1211 unsigned cost = 0;
1212 struct lim_aux_data *lim_data;
1214 if (!loop_outer (bb->loop_father))
1215 return;
1217 for (bsi = gsi_start_phis (bb); !gsi_end_p (bsi); )
1219 gimple new_stmt;
1220 stmt = gsi_stmt (bsi);
1222 lim_data = get_lim_data (stmt);
1223 if (lim_data == NULL)
1225 gsi_next (&bsi);
1226 continue;
1229 cost = lim_data->cost;
1230 level = lim_data->tgt_loop;
1231 clear_lim_data (stmt);
1233 if (!level)
1235 gsi_next (&bsi);
1236 continue;
1239 if (dump_file && (dump_flags & TDF_DETAILS))
1241 fprintf (dump_file, "Moving PHI node\n");
1242 print_gimple_stmt (dump_file, stmt, 0, 0);
1243 fprintf (dump_file, "(cost %u) out of loop %d.\n\n",
1244 cost, level->num);
1247 if (gimple_phi_num_args (stmt) == 1)
1249 tree arg = PHI_ARG_DEF (stmt, 0);
1250 new_stmt = gimple_build_assign_with_ops (TREE_CODE (arg),
1251 gimple_phi_result (stmt),
1252 arg, NULL_TREE);
1253 SSA_NAME_DEF_STMT (gimple_phi_result (stmt)) = new_stmt;
1255 else
1257 basic_block dom = get_immediate_dominator (CDI_DOMINATORS, bb);
1258 gimple cond = gsi_stmt (gsi_last_bb (dom));
1259 tree arg0 = NULL_TREE, arg1 = NULL_TREE, t;
1260 /* Get the PHI arguments corresponding to the true and false
1261 edges of COND. */
1262 extract_true_false_args_from_phi (dom, stmt, &arg0, &arg1);
1263 gcc_assert (arg0 && arg1);
1264 t = build2 (gimple_cond_code (cond), boolean_type_node,
1265 gimple_cond_lhs (cond), gimple_cond_rhs (cond));
1266 new_stmt = gimple_build_assign_with_ops (COND_EXPR,
1267 gimple_phi_result (stmt),
1268 t, arg0, arg1);
1269 SSA_NAME_DEF_STMT (gimple_phi_result (stmt)) = new_stmt;
1270 *((unsigned int *)(dw_data->global_data)) |= TODO_cleanup_cfg;
1272 gsi_insert_on_edge (loop_preheader_edge (level), new_stmt);
1273 remove_phi_node (&bsi, false);
1276 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); )
1278 edge e;
1280 stmt = gsi_stmt (bsi);
1282 lim_data = get_lim_data (stmt);
1283 if (lim_data == NULL)
1285 gsi_next (&bsi);
1286 continue;
1289 cost = lim_data->cost;
1290 level = lim_data->tgt_loop;
1291 clear_lim_data (stmt);
1293 if (!level)
1295 gsi_next (&bsi);
1296 continue;
1299 /* We do not really want to move conditionals out of the loop; we just
1300 placed it here to force its operands to be moved if necessary. */
1301 if (gimple_code (stmt) == GIMPLE_COND)
1302 continue;
1304 if (dump_file && (dump_flags & TDF_DETAILS))
1306 fprintf (dump_file, "Moving statement\n");
1307 print_gimple_stmt (dump_file, stmt, 0, 0);
1308 fprintf (dump_file, "(cost %u) out of loop %d.\n\n",
1309 cost, level->num);
1312 e = loop_preheader_edge (level);
1313 gcc_assert (!gimple_vdef (stmt));
1314 if (gimple_vuse (stmt))
1316 /* The new VUSE is the one from the virtual PHI in the loop
1317 header or the one already present. */
1318 gimple_stmt_iterator gsi2;
1319 for (gsi2 = gsi_start_phis (e->dest);
1320 !gsi_end_p (gsi2); gsi_next (&gsi2))
1322 gimple phi = gsi_stmt (gsi2);
1323 if (virtual_operand_p (gimple_phi_result (phi)))
1325 gimple_set_vuse (stmt, PHI_ARG_DEF_FROM_EDGE (phi, e));
1326 break;
1330 gsi_remove (&bsi, false);
1331 gsi_insert_on_edge (e, stmt);
1335 /* Hoist the statements out of the loops prescribed by data stored in
1336 LIM_DATA structures associated with each statement.*/
1338 static unsigned int
1339 move_computations (void)
1341 struct dom_walk_data walk_data;
1342 unsigned int todo = 0;
1344 memset (&walk_data, 0, sizeof (struct dom_walk_data));
1345 walk_data.global_data = &todo;
1346 walk_data.dom_direction = CDI_DOMINATORS;
1347 walk_data.before_dom_children = move_computations_stmt;
1349 init_walk_dominator_tree (&walk_data);
1350 walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
1351 fini_walk_dominator_tree (&walk_data);
1353 gsi_commit_edge_inserts ();
1354 if (need_ssa_update_p (cfun))
1355 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
1357 return todo;
1360 /* Checks whether the statement defining variable *INDEX can be hoisted
1361 out of the loop passed in DATA. Callback for for_each_index. */
1363 static bool
1364 may_move_till (tree ref, tree *index, void *data)
1366 struct loop *loop = (struct loop *) data, *max_loop;
1368 /* If REF is an array reference, check also that the step and the lower
1369 bound is invariant in LOOP. */
1370 if (TREE_CODE (ref) == ARRAY_REF)
1372 tree step = TREE_OPERAND (ref, 3);
1373 tree lbound = TREE_OPERAND (ref, 2);
1375 max_loop = outermost_invariant_loop (step, loop);
1376 if (!max_loop)
1377 return false;
1379 max_loop = outermost_invariant_loop (lbound, loop);
1380 if (!max_loop)
1381 return false;
1384 max_loop = outermost_invariant_loop (*index, loop);
1385 if (!max_loop)
1386 return false;
1388 return true;
1391 /* If OP is SSA NAME, force the statement that defines it to be
1392 moved out of the LOOP. ORIG_LOOP is the loop in that EXPR is used. */
1394 static void
1395 force_move_till_op (tree op, struct loop *orig_loop, struct loop *loop)
1397 gimple stmt;
1399 if (!op
1400 || is_gimple_min_invariant (op))
1401 return;
1403 gcc_assert (TREE_CODE (op) == SSA_NAME);
1405 stmt = SSA_NAME_DEF_STMT (op);
1406 if (gimple_nop_p (stmt))
1407 return;
1409 set_level (stmt, orig_loop, loop);
1412 /* Forces statement defining invariants in REF (and *INDEX) to be moved out of
1413 the LOOP. The reference REF is used in the loop ORIG_LOOP. Callback for
1414 for_each_index. */
1416 struct fmt_data
1418 struct loop *loop;
1419 struct loop *orig_loop;
1422 static bool
1423 force_move_till (tree ref, tree *index, void *data)
1425 struct fmt_data *fmt_data = (struct fmt_data *) data;
1427 if (TREE_CODE (ref) == ARRAY_REF)
1429 tree step = TREE_OPERAND (ref, 3);
1430 tree lbound = TREE_OPERAND (ref, 2);
1432 force_move_till_op (step, fmt_data->orig_loop, fmt_data->loop);
1433 force_move_till_op (lbound, fmt_data->orig_loop, fmt_data->loop);
1436 force_move_till_op (*index, fmt_data->orig_loop, fmt_data->loop);
1438 return true;
1441 /* A hash function for struct mem_ref object OBJ. */
1443 static hashval_t
1444 memref_hash (const void *obj)
1446 const struct mem_ref *const mem = (const struct mem_ref *) obj;
1448 return mem->hash;
1451 /* An equality function for struct mem_ref object OBJ1 with
1452 memory reference OBJ2. */
1454 static int
1455 memref_eq (const void *obj1, const void *obj2)
1457 const struct mem_ref *const mem1 = (const struct mem_ref *) obj1;
1459 return operand_equal_p (mem1->mem.ref, (const_tree) obj2, 0);
1462 /* Releases list of memory reference locations ACCS. */
1464 static void
1465 free_mem_ref_locs (mem_ref_locs_p accs)
1467 unsigned i;
1468 mem_ref_loc_p loc;
1470 if (!accs)
1471 return;
1473 FOR_EACH_VEC_ELT (accs->locs, i, loc)
1474 free (loc);
1475 accs->locs.release ();
1476 free (accs);
1479 /* A function to free the mem_ref object OBJ. */
1481 static void
1482 memref_free (struct mem_ref *mem)
1484 unsigned i;
1485 mem_ref_locs_p accs;
1487 FOR_EACH_VEC_ELT (mem->accesses_in_loop, i, accs)
1488 free_mem_ref_locs (accs);
1489 mem->accesses_in_loop.release ();
1491 free (mem);
1494 /* Allocates and returns a memory reference description for MEM whose hash
1495 value is HASH and id is ID. */
1497 static mem_ref_p
1498 mem_ref_alloc (tree mem, unsigned hash, unsigned id)
1500 mem_ref_p ref = XNEW (struct mem_ref);
1501 ao_ref_init (&ref->mem, mem);
1502 ref->id = id;
1503 ref->hash = hash;
1504 ref->stored = BITMAP_ALLOC (&lim_bitmap_obstack);
1505 ref->indep_loop = BITMAP_ALLOC (&lim_bitmap_obstack);
1506 ref->dep_loop = BITMAP_ALLOC (&lim_bitmap_obstack);
1507 ref->indep_ref = BITMAP_ALLOC (&lim_bitmap_obstack);
1508 ref->dep_ref = BITMAP_ALLOC (&lim_bitmap_obstack);
1509 ref->accesses_in_loop.create (0);
1511 return ref;
1514 /* Allocates and returns the new list of locations. */
1516 static mem_ref_locs_p
1517 mem_ref_locs_alloc (void)
1519 mem_ref_locs_p accs = XNEW (struct mem_ref_locs);
1520 accs->locs.create (0);
1521 return accs;
1524 /* Records memory reference location *LOC in LOOP to the memory reference
1525 description REF. The reference occurs in statement STMT. */
1527 static void
1528 record_mem_ref_loc (mem_ref_p ref, struct loop *loop, gimple stmt, tree *loc)
1530 mem_ref_loc_p aref = XNEW (struct mem_ref_loc);
1531 mem_ref_locs_p accs;
1533 if (ref->accesses_in_loop.length ()
1534 <= (unsigned) loop->num)
1535 ref->accesses_in_loop.safe_grow_cleared (loop->num + 1);
1536 accs = ref->accesses_in_loop[loop->num];
1537 if (!accs)
1539 accs = mem_ref_locs_alloc ();
1540 ref->accesses_in_loop[loop->num] = accs;
1543 aref->stmt = stmt;
1544 aref->ref = loc;
1546 accs->locs.safe_push (aref);
1549 /* Marks reference REF as stored in LOOP. */
1551 static void
1552 mark_ref_stored (mem_ref_p ref, struct loop *loop)
1554 for (;
1555 loop != current_loops->tree_root
1556 && !bitmap_bit_p (ref->stored, loop->num);
1557 loop = loop_outer (loop))
1558 bitmap_set_bit (ref->stored, loop->num);
1561 /* Gathers memory references in statement STMT in LOOP, storing the
1562 information about them in the memory_accesses structure. Marks
1563 the vops accessed through unrecognized statements there as
1564 well. */
1566 static void
1567 gather_mem_refs_stmt (struct loop *loop, gimple stmt)
1569 tree *mem = NULL;
1570 hashval_t hash;
1571 PTR *slot;
1572 mem_ref_p ref;
1573 bool is_stored;
1574 unsigned id;
1576 if (!gimple_vuse (stmt))
1577 return;
1579 mem = simple_mem_ref_in_stmt (stmt, &is_stored);
1580 if (!mem)
1582 /* We use the shared mem_ref for all unanalyzable refs. */
1583 id = UNANALYZABLE_MEM_ID;
1584 ref = memory_accesses.refs_list[id];
1585 if (dump_file && (dump_flags & TDF_DETAILS))
1587 fprintf (dump_file, "Unanalyzed memory reference %u: ", id);
1588 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
1590 is_stored = gimple_vdef (stmt);
1592 else
1594 hash = iterative_hash_expr (*mem, 0);
1595 slot = htab_find_slot_with_hash (memory_accesses.refs,
1596 *mem, hash, INSERT);
1597 if (*slot)
1599 ref = (mem_ref_p) *slot;
1600 id = ref->id;
1602 else
1604 id = memory_accesses.refs_list.length ();
1605 ref = mem_ref_alloc (*mem, hash, id);
1606 memory_accesses.refs_list.safe_push (ref);
1607 *slot = ref;
1609 if (dump_file && (dump_flags & TDF_DETAILS))
1611 fprintf (dump_file, "Memory reference %u: ", id);
1612 print_generic_expr (dump_file, ref->mem.ref, TDF_SLIM);
1613 fprintf (dump_file, "\n");
1617 record_mem_ref_loc (ref, loop, stmt, mem);
1619 bitmap_set_bit (memory_accesses.refs_in_loop[loop->num], ref->id);
1620 if (is_stored)
1621 mark_ref_stored (ref, loop);
1622 return;
1625 static unsigned *bb_loop_postorder;
1627 /* qsort sort function to sort blocks after their loop fathers postorder. */
1629 static int
1630 sort_bbs_in_loop_postorder_cmp (const void *bb1_, const void *bb2_)
1632 basic_block bb1 = *(basic_block *)const_cast<void *>(bb1_);
1633 basic_block bb2 = *(basic_block *)const_cast<void *>(bb2_);
1634 struct loop *loop1 = bb1->loop_father;
1635 struct loop *loop2 = bb2->loop_father;
1636 if (loop1->num == loop2->num)
1637 return 0;
1638 return bb_loop_postorder[loop1->num] < bb_loop_postorder[loop2->num] ? -1 : 1;
1641 /* Gathers memory references in loops. */
1643 static void
1644 gather_mem_refs_in_loops (void)
1646 gimple_stmt_iterator bsi;
1647 basic_block bb, *bbs;
1648 struct loop *loop;
1649 loop_iterator li;
1650 bitmap lrefs, alrefs, alrefso;
1651 unsigned i, n;
1653 /* Initialize bb_loop_postorder with a mapping from loop->num to
1654 its postorder index. */
1655 i = 0;
1656 bb_loop_postorder = XNEWVEC (unsigned, number_of_loops ());
1657 FOR_EACH_LOOP (li, loop, LI_FROM_INNERMOST)
1658 bb_loop_postorder[loop->num] = i++;
1659 /* Collect all basic-blocks in loops and sort them after their
1660 loops postorder. */
1661 i = 0;
1662 bbs = XNEWVEC (basic_block, n_basic_blocks - NUM_FIXED_BLOCKS);
1663 FOR_EACH_BB (bb)
1664 if (bb->loop_father != current_loops->tree_root)
1665 bbs[i++] = bb;
1666 n = i;
1667 qsort (bbs, n, sizeof (basic_block), sort_bbs_in_loop_postorder_cmp);
1668 free (bb_loop_postorder);
1670 /* Visit blocks in loop postorder and assign mem-ref IDs in that order.
1671 That results in better locality for all the bitmaps. */
1672 for (i = 0; i < n; ++i)
1674 basic_block bb = bbs[i];
1675 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1676 gather_mem_refs_stmt (bb->loop_father, gsi_stmt (bsi));
1679 free (bbs);
1681 /* Propagate the information about accessed memory references up
1682 the loop hierarchy. */
1683 FOR_EACH_LOOP (li, loop, LI_FROM_INNERMOST)
1685 lrefs = memory_accesses.refs_in_loop[loop->num];
1686 alrefs = memory_accesses.all_refs_in_loop[loop->num];
1687 bitmap_ior_into (alrefs, lrefs);
1689 if (loop_outer (loop) == current_loops->tree_root)
1690 continue;
1692 alrefso = memory_accesses.all_refs_in_loop[loop_outer (loop)->num];
1693 bitmap_ior_into (alrefso, alrefs);
1697 /* Create a mapping from virtual operands to references that touch them
1698 in LOOP. */
1700 static void
1701 create_vop_ref_mapping_loop (struct loop *loop)
1703 bitmap refs = memory_accesses.refs_in_loop[loop->num];
1704 struct loop *sloop;
1705 bitmap_iterator bi;
1706 unsigned i;
1707 mem_ref_p ref;
1709 EXECUTE_IF_SET_IN_BITMAP (refs, 0, i, bi)
1711 ref = memory_accesses.refs_list[i];
1712 for (sloop = loop; sloop != current_loops->tree_root;
1713 sloop = loop_outer (sloop))
1714 if (bitmap_bit_p (ref->stored, loop->num))
1716 bitmap refs_stored
1717 = memory_accesses.all_refs_stored_in_loop[sloop->num];
1718 bitmap_set_bit (refs_stored, ref->id);
1723 /* For each non-clobbered virtual operand and each loop, record the memory
1724 references in this loop that touch the operand. */
1726 static void
1727 create_vop_ref_mapping (void)
1729 loop_iterator li;
1730 struct loop *loop;
1732 FOR_EACH_LOOP (li, loop, 0)
1734 create_vop_ref_mapping_loop (loop);
1738 /* Gathers information about memory accesses in the loops. */
1740 static void
1741 analyze_memory_references (void)
1743 unsigned i;
1744 bitmap empty;
1746 memory_accesses.refs = htab_create (100, memref_hash, memref_eq, NULL);
1747 memory_accesses.refs_list.create (100);
1748 /* Allocate a special, unanalyzable mem-ref with ID zero. */
1749 memory_accesses.refs_list.quick_push
1750 (mem_ref_alloc (error_mark_node, 0, UNANALYZABLE_MEM_ID));
1752 memory_accesses.refs_in_loop.create (number_of_loops ());
1753 memory_accesses.all_refs_in_loop.create (number_of_loops ());
1754 memory_accesses.all_refs_stored_in_loop.create (number_of_loops ());
1756 for (i = 0; i < number_of_loops (); i++)
1758 empty = BITMAP_ALLOC (&lim_bitmap_obstack);
1759 memory_accesses.refs_in_loop.quick_push (empty);
1760 empty = BITMAP_ALLOC (&lim_bitmap_obstack);
1761 memory_accesses.all_refs_in_loop.quick_push (empty);
1762 empty = BITMAP_ALLOC (&lim_bitmap_obstack);
1763 memory_accesses.all_refs_stored_in_loop.quick_push (empty);
1766 memory_accesses.ttae_cache = NULL;
1768 gather_mem_refs_in_loops ();
1769 create_vop_ref_mapping ();
1772 /* Returns true if MEM1 and MEM2 may alias. TTAE_CACHE is used as a cache in
1773 tree_to_aff_combination_expand. */
1775 static bool
1776 mem_refs_may_alias_p (mem_ref_p mem1, mem_ref_p mem2,
1777 struct pointer_map_t **ttae_cache)
1779 /* Perform BASE + OFFSET analysis -- if MEM1 and MEM2 are based on the same
1780 object and their offset differ in such a way that the locations cannot
1781 overlap, then they cannot alias. */
1782 double_int size1, size2;
1783 aff_tree off1, off2;
1785 /* Perform basic offset and type-based disambiguation. */
1786 if (!refs_may_alias_p_1 (&mem1->mem, &mem2->mem, true))
1787 return false;
1789 /* The expansion of addresses may be a bit expensive, thus we only do
1790 the check at -O2 and higher optimization levels. */
1791 if (optimize < 2)
1792 return true;
1794 get_inner_reference_aff (mem1->mem.ref, &off1, &size1);
1795 get_inner_reference_aff (mem2->mem.ref, &off2, &size2);
1796 aff_combination_expand (&off1, ttae_cache);
1797 aff_combination_expand (&off2, ttae_cache);
1798 aff_combination_scale (&off1, double_int_minus_one);
1799 aff_combination_add (&off2, &off1);
1801 if (aff_comb_cannot_overlap_p (&off2, size1, size2))
1802 return false;
1804 return true;
1807 /* Rewrites location LOC by TMP_VAR. */
1809 static void
1810 rewrite_mem_ref_loc (mem_ref_loc_p loc, tree tmp_var)
1812 *loc->ref = tmp_var;
1813 update_stmt (loc->stmt);
1816 /* Adds all locations of REF in LOOP and its subloops to LOCS. */
1818 static void
1819 get_all_locs_in_loop (struct loop *loop, mem_ref_p ref,
1820 vec<mem_ref_loc_p> *locs)
1822 mem_ref_locs_p accs;
1823 unsigned i;
1824 mem_ref_loc_p loc;
1825 bitmap refs = memory_accesses.all_refs_in_loop[loop->num];
1826 struct loop *subloop;
1828 if (!bitmap_bit_p (refs, ref->id))
1829 return;
1831 if (ref->accesses_in_loop.length ()
1832 > (unsigned) loop->num)
1834 accs = ref->accesses_in_loop[loop->num];
1835 if (accs)
1837 FOR_EACH_VEC_ELT (accs->locs, i, loc)
1838 locs->safe_push (loc);
1842 for (subloop = loop->inner; subloop != NULL; subloop = subloop->next)
1843 get_all_locs_in_loop (subloop, ref, locs);
1846 /* Rewrites all references to REF in LOOP by variable TMP_VAR. */
1848 static void
1849 rewrite_mem_refs (struct loop *loop, mem_ref_p ref, tree tmp_var)
1851 unsigned i;
1852 mem_ref_loc_p loc;
1853 vec<mem_ref_loc_p> locs = vNULL;
1855 get_all_locs_in_loop (loop, ref, &locs);
1856 FOR_EACH_VEC_ELT (locs, i, loc)
1857 rewrite_mem_ref_loc (loc, tmp_var);
1858 locs.release ();
1861 /* The name and the length of the currently generated variable
1862 for lsm. */
1863 #define MAX_LSM_NAME_LENGTH 40
1864 static char lsm_tmp_name[MAX_LSM_NAME_LENGTH + 1];
1865 static int lsm_tmp_name_length;
1867 /* Adds S to lsm_tmp_name. */
1869 static void
1870 lsm_tmp_name_add (const char *s)
1872 int l = strlen (s) + lsm_tmp_name_length;
1873 if (l > MAX_LSM_NAME_LENGTH)
1874 return;
1876 strcpy (lsm_tmp_name + lsm_tmp_name_length, s);
1877 lsm_tmp_name_length = l;
1880 /* Stores the name for temporary variable that replaces REF to
1881 lsm_tmp_name. */
1883 static void
1884 gen_lsm_tmp_name (tree ref)
1886 const char *name;
1888 switch (TREE_CODE (ref))
1890 case MEM_REF:
1891 case TARGET_MEM_REF:
1892 gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
1893 lsm_tmp_name_add ("_");
1894 break;
1896 case ADDR_EXPR:
1897 gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
1898 break;
1900 case BIT_FIELD_REF:
1901 case VIEW_CONVERT_EXPR:
1902 case ARRAY_RANGE_REF:
1903 gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
1904 break;
1906 case REALPART_EXPR:
1907 gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
1908 lsm_tmp_name_add ("_RE");
1909 break;
1911 case IMAGPART_EXPR:
1912 gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
1913 lsm_tmp_name_add ("_IM");
1914 break;
1916 case COMPONENT_REF:
1917 gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
1918 lsm_tmp_name_add ("_");
1919 name = get_name (TREE_OPERAND (ref, 1));
1920 if (!name)
1921 name = "F";
1922 lsm_tmp_name_add (name);
1923 break;
1925 case ARRAY_REF:
1926 gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
1927 lsm_tmp_name_add ("_I");
1928 break;
1930 case SSA_NAME:
1931 case VAR_DECL:
1932 case PARM_DECL:
1933 name = get_name (ref);
1934 if (!name)
1935 name = "D";
1936 lsm_tmp_name_add (name);
1937 break;
1939 case STRING_CST:
1940 lsm_tmp_name_add ("S");
1941 break;
1943 case RESULT_DECL:
1944 lsm_tmp_name_add ("R");
1945 break;
1947 case INTEGER_CST:
1948 /* Nothing. */
1949 break;
1951 default:
1952 gcc_unreachable ();
1956 /* Determines name for temporary variable that replaces REF.
1957 The name is accumulated into the lsm_tmp_name variable.
1958 N is added to the name of the temporary. */
1960 char *
1961 get_lsm_tmp_name (tree ref, unsigned n)
1963 char ns[2];
1965 lsm_tmp_name_length = 0;
1966 gen_lsm_tmp_name (ref);
1967 lsm_tmp_name_add ("_lsm");
1968 if (n < 10)
1970 ns[0] = '0' + n;
1971 ns[1] = 0;
1972 lsm_tmp_name_add (ns);
1974 return lsm_tmp_name;
1977 struct prev_flag_edges {
1978 /* Edge to insert new flag comparison code. */
1979 edge append_cond_position;
1981 /* Edge for fall through from previous flag comparison. */
1982 edge last_cond_fallthru;
1985 /* Helper function for execute_sm. Emit code to store TMP_VAR into
1986 MEM along edge EX.
1988 The store is only done if MEM has changed. We do this so no
1989 changes to MEM occur on code paths that did not originally store
1990 into it.
1992 The common case for execute_sm will transform:
1994 for (...) {
1995 if (foo)
1996 stuff;
1997 else
1998 MEM = TMP_VAR;
2001 into:
2003 lsm = MEM;
2004 for (...) {
2005 if (foo)
2006 stuff;
2007 else
2008 lsm = TMP_VAR;
2010 MEM = lsm;
2012 This function will generate:
2014 lsm = MEM;
2016 lsm_flag = false;
2018 for (...) {
2019 if (foo)
2020 stuff;
2021 else {
2022 lsm = TMP_VAR;
2023 lsm_flag = true;
2026 if (lsm_flag) <--
2027 MEM = lsm; <--
2030 static void
2031 execute_sm_if_changed (edge ex, tree mem, tree tmp_var, tree flag)
2033 basic_block new_bb, then_bb, old_dest;
2034 bool loop_has_only_one_exit;
2035 edge then_old_edge, orig_ex = ex;
2036 gimple_stmt_iterator gsi;
2037 gimple stmt;
2038 struct prev_flag_edges *prev_edges = (struct prev_flag_edges *) ex->aux;
2040 /* ?? Insert store after previous store if applicable. See note
2041 below. */
2042 if (prev_edges)
2043 ex = prev_edges->append_cond_position;
2045 loop_has_only_one_exit = single_pred_p (ex->dest);
2047 if (loop_has_only_one_exit)
2048 ex = split_block_after_labels (ex->dest);
2050 old_dest = ex->dest;
2051 new_bb = split_edge (ex);
2052 then_bb = create_empty_bb (new_bb);
2053 if (current_loops && new_bb->loop_father)
2054 add_bb_to_loop (then_bb, new_bb->loop_father);
2056 gsi = gsi_start_bb (new_bb);
2057 stmt = gimple_build_cond (NE_EXPR, flag, boolean_false_node,
2058 NULL_TREE, NULL_TREE);
2059 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2061 gsi = gsi_start_bb (then_bb);
2062 /* Insert actual store. */
2063 stmt = gimple_build_assign (unshare_expr (mem), tmp_var);
2064 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2066 make_edge (new_bb, then_bb, EDGE_TRUE_VALUE);
2067 make_edge (new_bb, old_dest, EDGE_FALSE_VALUE);
2068 then_old_edge = make_edge (then_bb, old_dest, EDGE_FALLTHRU);
2070 set_immediate_dominator (CDI_DOMINATORS, then_bb, new_bb);
2072 if (prev_edges)
2074 basic_block prevbb = prev_edges->last_cond_fallthru->src;
2075 redirect_edge_succ (prev_edges->last_cond_fallthru, new_bb);
2076 set_immediate_dominator (CDI_DOMINATORS, new_bb, prevbb);
2077 set_immediate_dominator (CDI_DOMINATORS, old_dest,
2078 recompute_dominator (CDI_DOMINATORS, old_dest));
2081 /* ?? Because stores may alias, they must happen in the exact
2082 sequence they originally happened. Save the position right after
2083 the (_lsm) store we just created so we can continue appending after
2084 it and maintain the original order. */
2086 struct prev_flag_edges *p;
2088 if (orig_ex->aux)
2089 orig_ex->aux = NULL;
2090 alloc_aux_for_edge (orig_ex, sizeof (struct prev_flag_edges));
2091 p = (struct prev_flag_edges *) orig_ex->aux;
2092 p->append_cond_position = then_old_edge;
2093 p->last_cond_fallthru = find_edge (new_bb, old_dest);
2094 orig_ex->aux = (void *) p;
2097 if (!loop_has_only_one_exit)
2098 for (gsi = gsi_start_phis (old_dest); !gsi_end_p (gsi); gsi_next (&gsi))
2100 gimple phi = gsi_stmt (gsi);
2101 unsigned i;
2103 for (i = 0; i < gimple_phi_num_args (phi); i++)
2104 if (gimple_phi_arg_edge (phi, i)->src == new_bb)
2106 tree arg = gimple_phi_arg_def (phi, i);
2107 add_phi_arg (phi, arg, then_old_edge, UNKNOWN_LOCATION);
2108 update_stmt (phi);
2111 /* Remove the original fall through edge. This was the
2112 single_succ_edge (new_bb). */
2113 EDGE_SUCC (new_bb, 0)->flags &= ~EDGE_FALLTHRU;
2116 /* Helper function for execute_sm. On every location where REF is
2117 set, set an appropriate flag indicating the store. */
2119 static tree
2120 execute_sm_if_changed_flag_set (struct loop *loop, mem_ref_p ref)
2122 unsigned i;
2123 mem_ref_loc_p loc;
2124 tree flag;
2125 vec<mem_ref_loc_p> locs = vNULL;
2126 char *str = get_lsm_tmp_name (ref->mem.ref, ~0);
2128 lsm_tmp_name_add ("_flag");
2129 flag = create_tmp_reg (boolean_type_node, str);
2130 get_all_locs_in_loop (loop, ref, &locs);
2131 FOR_EACH_VEC_ELT (locs, i, loc)
2133 gimple_stmt_iterator gsi;
2134 gimple stmt;
2136 /* Only set the flag for writes. */
2137 if (is_gimple_assign (loc->stmt)
2138 && gimple_assign_lhs_ptr (loc->stmt) == loc->ref)
2140 gsi = gsi_for_stmt (loc->stmt);
2141 stmt = gimple_build_assign (flag, boolean_true_node);
2142 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2145 locs.release ();
2146 return flag;
2149 /* Executes store motion of memory reference REF from LOOP.
2150 Exits from the LOOP are stored in EXITS. The initialization of the
2151 temporary variable is put to the preheader of the loop, and assignments
2152 to the reference from the temporary variable are emitted to exits. */
2154 static void
2155 execute_sm (struct loop *loop, vec<edge> exits, mem_ref_p ref)
2157 tree tmp_var, store_flag;
2158 unsigned i;
2159 gimple load;
2160 struct fmt_data fmt_data;
2161 edge ex, latch_edge;
2162 struct lim_aux_data *lim_data;
2163 bool multi_threaded_model_p = false;
2165 if (dump_file && (dump_flags & TDF_DETAILS))
2167 fprintf (dump_file, "Executing store motion of ");
2168 print_generic_expr (dump_file, ref->mem.ref, 0);
2169 fprintf (dump_file, " from loop %d\n", loop->num);
2172 tmp_var = create_tmp_reg (TREE_TYPE (ref->mem.ref),
2173 get_lsm_tmp_name (ref->mem.ref, ~0));
2175 fmt_data.loop = loop;
2176 fmt_data.orig_loop = loop;
2177 for_each_index (&ref->mem.ref, force_move_till, &fmt_data);
2179 if (block_in_transaction (loop_preheader_edge (loop)->src)
2180 || !PARAM_VALUE (PARAM_ALLOW_STORE_DATA_RACES))
2181 multi_threaded_model_p = true;
2183 if (multi_threaded_model_p)
2184 store_flag = execute_sm_if_changed_flag_set (loop, ref);
2186 rewrite_mem_refs (loop, ref, tmp_var);
2188 /* Emit the load code into the latch, so that we are sure it will
2189 be processed after all dependencies. */
2190 latch_edge = loop_latch_edge (loop);
2192 /* FIXME/TODO: For the multi-threaded variant, we could avoid this
2193 load altogether, since the store is predicated by a flag. We
2194 could, do the load only if it was originally in the loop. */
2195 load = gimple_build_assign (tmp_var, unshare_expr (ref->mem.ref));
2196 lim_data = init_lim_data (load);
2197 lim_data->max_loop = loop;
2198 lim_data->tgt_loop = loop;
2199 gsi_insert_on_edge (latch_edge, load);
2201 if (multi_threaded_model_p)
2203 load = gimple_build_assign (store_flag, boolean_false_node);
2204 lim_data = init_lim_data (load);
2205 lim_data->max_loop = loop;
2206 lim_data->tgt_loop = loop;
2207 gsi_insert_on_edge (latch_edge, load);
2210 /* Sink the store to every exit from the loop. */
2211 FOR_EACH_VEC_ELT (exits, i, ex)
2212 if (!multi_threaded_model_p)
2214 gimple store;
2215 store = gimple_build_assign (unshare_expr (ref->mem.ref), tmp_var);
2216 gsi_insert_on_edge (ex, store);
2218 else
2219 execute_sm_if_changed (ex, ref->mem.ref, tmp_var, store_flag);
2222 /* Hoists memory references MEM_REFS out of LOOP. EXITS is the list of exit
2223 edges of the LOOP. */
2225 static void
2226 hoist_memory_references (struct loop *loop, bitmap mem_refs,
2227 vec<edge> exits)
2229 mem_ref_p ref;
2230 unsigned i;
2231 bitmap_iterator bi;
2233 EXECUTE_IF_SET_IN_BITMAP (mem_refs, 0, i, bi)
2235 ref = memory_accesses.refs_list[i];
2236 execute_sm (loop, exits, ref);
2240 /* Returns true if REF is always accessed in LOOP. If STORED_P is true
2241 make sure REF is always stored to in LOOP. */
2243 static bool
2244 ref_always_accessed_p (struct loop *loop, mem_ref_p ref, bool stored_p)
2246 vec<mem_ref_loc_p> locs = vNULL;
2247 unsigned i;
2248 mem_ref_loc_p loc;
2249 bool ret = false;
2250 struct loop *must_exec;
2251 tree base;
2253 base = ao_ref_base (&ref->mem);
2254 if (TREE_CODE (base) == MEM_REF)
2255 base = TREE_OPERAND (base, 0);
2257 get_all_locs_in_loop (loop, ref, &locs);
2258 FOR_EACH_VEC_ELT (locs, i, loc)
2260 if (!get_lim_data (loc->stmt))
2261 continue;
2263 /* If we require an always executed store make sure the statement
2264 stores to the reference. */
2265 if (stored_p)
2267 tree lhs;
2268 if (!gimple_get_lhs (loc->stmt))
2269 continue;
2270 lhs = get_base_address (gimple_get_lhs (loc->stmt));
2271 if (!lhs)
2272 continue;
2273 if (INDIRECT_REF_P (lhs)
2274 || TREE_CODE (lhs) == MEM_REF)
2275 lhs = TREE_OPERAND (lhs, 0);
2276 if (lhs != base)
2277 continue;
2280 must_exec = get_lim_data (loc->stmt)->always_executed_in;
2281 if (!must_exec)
2282 continue;
2284 if (must_exec == loop
2285 || flow_loop_nested_p (must_exec, loop))
2287 ret = true;
2288 break;
2291 locs.release ();
2293 return ret;
2296 /* Returns true if REF1 and REF2 are independent. */
2298 static bool
2299 refs_independent_p (mem_ref_p ref1, mem_ref_p ref2)
2301 if (ref1 == ref2)
2302 return true;
2304 /* Reference dependence in a loop is symmetric. */
2305 if (ref1->id > ref2->id)
2307 mem_ref_p tem = ref1;
2308 ref1 = ref2;
2309 ref2 = tem;
2312 if (bitmap_bit_p (ref1->indep_ref, ref2->id))
2313 return true;
2314 if (bitmap_bit_p (ref1->dep_ref, ref2->id))
2315 return false;
2317 if (dump_file && (dump_flags & TDF_DETAILS))
2318 fprintf (dump_file, "Querying dependency of refs %u and %u: ",
2319 ref1->id, ref2->id);
2321 if (mem_refs_may_alias_p (ref1, ref2, &memory_accesses.ttae_cache))
2323 bitmap_set_bit (ref1->dep_ref, ref2->id);
2324 if (dump_file && (dump_flags & TDF_DETAILS))
2325 fprintf (dump_file, "dependent.\n");
2326 return false;
2328 else
2330 bitmap_set_bit (ref1->indep_ref, ref2->id);
2331 if (dump_file && (dump_flags & TDF_DETAILS))
2332 fprintf (dump_file, "independent.\n");
2333 return true;
2337 /* Records the information whether REF is independent in LOOP (according
2338 to INDEP). */
2340 static void
2341 record_indep_loop (struct loop *loop, mem_ref_p ref, bool indep)
2343 if (indep)
2344 bitmap_set_bit (ref->indep_loop, loop->num);
2345 else
2346 bitmap_set_bit (ref->dep_loop, loop->num);
2349 /* Returns true if REF is independent on all other memory references in
2350 LOOP. */
2352 static bool
2353 ref_indep_loop_p_1 (struct loop *loop, mem_ref_p ref)
2355 bitmap refs_to_check;
2356 unsigned i;
2357 bitmap_iterator bi;
2358 bool ret = true, stored = bitmap_bit_p (ref->stored, loop->num);
2359 mem_ref_p aref;
2361 if (stored)
2362 refs_to_check = memory_accesses.all_refs_in_loop[loop->num];
2363 else
2364 refs_to_check = memory_accesses.all_refs_stored_in_loop[loop->num];
2366 if (bitmap_bit_p (refs_to_check, UNANALYZABLE_MEM_ID))
2367 return false;
2369 EXECUTE_IF_SET_IN_BITMAP (refs_to_check, 0, i, bi)
2371 aref = memory_accesses.refs_list[i];
2372 if (!refs_independent_p (ref, aref))
2374 ret = false;
2375 record_indep_loop (loop, aref, false);
2376 break;
2380 return ret;
2383 /* Returns true if REF is independent on all other memory references in
2384 LOOP. Wrapper over ref_indep_loop_p_1, caching its results. */
2386 static bool
2387 ref_indep_loop_p (struct loop *loop, mem_ref_p ref)
2389 bool ret;
2391 gcc_checking_assert (MEM_ANALYZABLE (ref));
2393 if (bitmap_bit_p (ref->indep_loop, loop->num))
2394 return true;
2395 if (bitmap_bit_p (ref->dep_loop, loop->num))
2396 return false;
2398 ret = ref_indep_loop_p_1 (loop, ref);
2400 if (dump_file && (dump_flags & TDF_DETAILS))
2401 fprintf (dump_file, "Querying dependencies of ref %u in loop %d: %s\n",
2402 ref->id, loop->num, ret ? "independent" : "dependent");
2404 record_indep_loop (loop, ref, ret);
2406 return ret;
2409 /* Returns true if we can perform store motion of REF from LOOP. */
2411 static bool
2412 can_sm_ref_p (struct loop *loop, mem_ref_p ref)
2414 tree base;
2416 /* Can't hoist unanalyzable refs. */
2417 if (!MEM_ANALYZABLE (ref))
2418 return false;
2420 /* It should be movable. */
2421 if (!is_gimple_reg_type (TREE_TYPE (ref->mem.ref))
2422 || TREE_THIS_VOLATILE (ref->mem.ref)
2423 || !for_each_index (&ref->mem.ref, may_move_till, loop))
2424 return false;
2426 /* If it can throw fail, we do not properly update EH info. */
2427 if (tree_could_throw_p (ref->mem.ref))
2428 return false;
2430 /* If it can trap, it must be always executed in LOOP.
2431 Readonly memory locations may trap when storing to them, but
2432 tree_could_trap_p is a predicate for rvalues, so check that
2433 explicitly. */
2434 base = get_base_address (ref->mem.ref);
2435 if ((tree_could_trap_p (ref->mem.ref)
2436 || (DECL_P (base) && TREE_READONLY (base)))
2437 && !ref_always_accessed_p (loop, ref, true))
2438 return false;
2440 /* And it must be independent on all other memory references
2441 in LOOP. */
2442 if (!ref_indep_loop_p (loop, ref))
2443 return false;
2445 return true;
2448 /* Marks the references in LOOP for that store motion should be performed
2449 in REFS_TO_SM. SM_EXECUTED is the set of references for that store
2450 motion was performed in one of the outer loops. */
2452 static void
2453 find_refs_for_sm (struct loop *loop, bitmap sm_executed, bitmap refs_to_sm)
2455 bitmap refs = memory_accesses.all_refs_stored_in_loop[loop->num];
2456 unsigned i;
2457 bitmap_iterator bi;
2458 mem_ref_p ref;
2460 EXECUTE_IF_AND_COMPL_IN_BITMAP (refs, sm_executed, 0, i, bi)
2462 ref = memory_accesses.refs_list[i];
2463 if (can_sm_ref_p (loop, ref))
2464 bitmap_set_bit (refs_to_sm, i);
2468 /* Checks whether LOOP (with exits stored in EXITS array) is suitable
2469 for a store motion optimization (i.e. whether we can insert statement
2470 on its exits). */
2472 static bool
2473 loop_suitable_for_sm (struct loop *loop ATTRIBUTE_UNUSED,
2474 vec<edge> exits)
2476 unsigned i;
2477 edge ex;
2479 FOR_EACH_VEC_ELT (exits, i, ex)
2480 if (ex->flags & (EDGE_ABNORMAL | EDGE_EH))
2481 return false;
2483 return true;
2486 /* Try to perform store motion for all memory references modified inside
2487 LOOP. SM_EXECUTED is the bitmap of the memory references for that
2488 store motion was executed in one of the outer loops. */
2490 static void
2491 store_motion_loop (struct loop *loop, bitmap sm_executed)
2493 vec<edge> exits = get_loop_exit_edges (loop);
2494 struct loop *subloop;
2495 bitmap sm_in_loop = BITMAP_ALLOC (&lim_bitmap_obstack);
2497 if (loop_suitable_for_sm (loop, exits))
2499 find_refs_for_sm (loop, sm_executed, sm_in_loop);
2500 hoist_memory_references (loop, sm_in_loop, exits);
2502 exits.release ();
2504 bitmap_ior_into (sm_executed, sm_in_loop);
2505 for (subloop = loop->inner; subloop != NULL; subloop = subloop->next)
2506 store_motion_loop (subloop, sm_executed);
2507 bitmap_and_compl_into (sm_executed, sm_in_loop);
2508 BITMAP_FREE (sm_in_loop);
2511 /* Try to perform store motion for all memory references modified inside
2512 loops. */
2514 static void
2515 store_motion (void)
2517 struct loop *loop;
2518 bitmap sm_executed = BITMAP_ALLOC (&lim_bitmap_obstack);
2520 for (loop = current_loops->tree_root->inner; loop != NULL; loop = loop->next)
2521 store_motion_loop (loop, sm_executed);
2523 BITMAP_FREE (sm_executed);
2524 gsi_commit_edge_inserts ();
2527 /* Fills ALWAYS_EXECUTED_IN information for basic blocks of LOOP, i.e.
2528 for each such basic block bb records the outermost loop for that execution
2529 of its header implies execution of bb. CONTAINS_CALL is the bitmap of
2530 blocks that contain a nonpure call. */
2532 static void
2533 fill_always_executed_in (struct loop *loop, sbitmap contains_call)
2535 basic_block bb = NULL, *bbs, last = NULL;
2536 unsigned i;
2537 edge e;
2538 struct loop *inn_loop = loop;
2540 if (ALWAYS_EXECUTED_IN (loop->header) == NULL)
2542 bbs = get_loop_body_in_dom_order (loop);
2544 for (i = 0; i < loop->num_nodes; i++)
2546 edge_iterator ei;
2547 bb = bbs[i];
2549 if (dominated_by_p (CDI_DOMINATORS, loop->latch, bb))
2550 last = bb;
2552 if (bitmap_bit_p (contains_call, bb->index))
2553 break;
2555 FOR_EACH_EDGE (e, ei, bb->succs)
2556 if (!flow_bb_inside_loop_p (loop, e->dest))
2557 break;
2558 if (e)
2559 break;
2561 /* A loop might be infinite (TODO use simple loop analysis
2562 to disprove this if possible). */
2563 if (bb->flags & BB_IRREDUCIBLE_LOOP)
2564 break;
2566 if (!flow_bb_inside_loop_p (inn_loop, bb))
2567 break;
2569 if (bb->loop_father->header == bb)
2571 if (!dominated_by_p (CDI_DOMINATORS, loop->latch, bb))
2572 break;
2574 /* In a loop that is always entered we may proceed anyway.
2575 But record that we entered it and stop once we leave it. */
2576 inn_loop = bb->loop_father;
2580 while (1)
2582 SET_ALWAYS_EXECUTED_IN (last, loop);
2583 if (last == loop->header)
2584 break;
2585 last = get_immediate_dominator (CDI_DOMINATORS, last);
2588 free (bbs);
2591 for (loop = loop->inner; loop; loop = loop->next)
2592 fill_always_executed_in (loop, contains_call);
2595 /* Compute the global information needed by the loop invariant motion pass. */
2597 static void
2598 tree_ssa_lim_initialize (void)
2600 sbitmap contains_call = sbitmap_alloc (last_basic_block);
2601 gimple_stmt_iterator bsi;
2602 struct loop *loop;
2603 basic_block bb;
2605 bitmap_obstack_initialize (&lim_bitmap_obstack);
2607 bitmap_clear (contains_call);
2608 FOR_EACH_BB (bb)
2610 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
2612 if (nonpure_call_p (gsi_stmt (bsi)))
2613 break;
2616 if (!gsi_end_p (bsi))
2617 bitmap_set_bit (contains_call, bb->index);
2620 for (loop = current_loops->tree_root->inner; loop; loop = loop->next)
2621 fill_always_executed_in (loop, contains_call);
2623 sbitmap_free (contains_call);
2625 lim_aux_data_map = pointer_map_create ();
2627 if (flag_tm)
2628 compute_transaction_bits ();
2630 alloc_aux_for_edges (0);
2633 /* Cleans up after the invariant motion pass. */
2635 static void
2636 tree_ssa_lim_finalize (void)
2638 basic_block bb;
2639 unsigned i;
2640 mem_ref_p ref;
2642 free_aux_for_edges ();
2644 FOR_EACH_BB (bb)
2645 SET_ALWAYS_EXECUTED_IN (bb, NULL);
2647 bitmap_obstack_release (&lim_bitmap_obstack);
2648 pointer_map_destroy (lim_aux_data_map);
2650 htab_delete (memory_accesses.refs);
2652 FOR_EACH_VEC_ELT (memory_accesses.refs_list, i, ref)
2653 memref_free (ref);
2654 memory_accesses.refs_list.release ();
2656 memory_accesses.refs_in_loop.release ();
2657 memory_accesses.all_refs_in_loop.release ();
2658 memory_accesses.all_refs_stored_in_loop.release ();
2660 if (memory_accesses.ttae_cache)
2661 free_affine_expand_cache (&memory_accesses.ttae_cache);
2664 /* Moves invariants from loops. Only "expensive" invariants are moved out --
2665 i.e. those that are likely to be win regardless of the register pressure. */
2667 unsigned int
2668 tree_ssa_lim (void)
2670 unsigned int todo;
2672 tree_ssa_lim_initialize ();
2674 /* Gathers information about memory accesses in the loops. */
2675 analyze_memory_references ();
2677 /* For each statement determine the outermost loop in that it is
2678 invariant and cost for computing the invariant. */
2679 determine_invariantness ();
2681 /* Execute store motion. Force the necessary invariants to be moved
2682 out of the loops as well. */
2683 store_motion ();
2685 /* Move the expressions that are expensive enough. */
2686 todo = move_computations ();
2688 tree_ssa_lim_finalize ();
2690 return todo;