c++: catch parm initialization tweak
[official-gcc.git] / gcc / tree-ssa-loop-im.cc
blob2ea815050d18b93422bc2add54bf7d6c4d85f9b1
1 /* Loop invariant motion.
2 Copyright (C) 2003-2022 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 "backend.h"
24 #include "tree.h"
25 #include "gimple.h"
26 #include "cfghooks.h"
27 #include "tree-pass.h"
28 #include "ssa.h"
29 #include "gimple-pretty-print.h"
30 #include "fold-const.h"
31 #include "cfganal.h"
32 #include "tree-eh.h"
33 #include "gimplify.h"
34 #include "gimple-iterator.h"
35 #include "tree-cfg.h"
36 #include "tree-ssa-loop-manip.h"
37 #include "tree-ssa-loop.h"
38 #include "tree-into-ssa.h"
39 #include "cfgloop.h"
40 #include "tree-affine.h"
41 #include "tree-ssa-propagate.h"
42 #include "trans-mem.h"
43 #include "gimple-fold.h"
44 #include "tree-scalar-evolution.h"
45 #include "tree-ssa-loop-niter.h"
46 #include "alias.h"
47 #include "builtins.h"
48 #include "tree-dfa.h"
49 #include "dbgcnt.h"
51 /* TODO: Support for predicated code motion. I.e.
53 while (1)
55 if (cond)
57 a = inv;
58 something;
62 Where COND and INV are invariants, but evaluating INV may trap or be
63 invalid from some other reason if !COND. This may be transformed to
65 if (cond)
66 a = inv;
67 while (1)
69 if (cond)
70 something;
71 } */
73 /* The auxiliary data kept for each statement. */
75 struct lim_aux_data
77 class loop *max_loop; /* The outermost loop in that the statement
78 is invariant. */
80 class loop *tgt_loop; /* The loop out of that we want to move the
81 invariant. */
83 class loop *always_executed_in;
84 /* The outermost loop for that we are sure
85 the statement is executed if the loop
86 is entered. */
88 unsigned cost; /* Cost of the computation performed by the
89 statement. */
91 unsigned ref; /* The simple_mem_ref in this stmt or 0. */
93 vec<gimple *> depends; /* Vector of statements that must be also
94 hoisted out of the loop when this statement
95 is hoisted; i.e. those that define the
96 operands of the statement and are inside of
97 the MAX_LOOP loop. */
100 /* Maps statements to their lim_aux_data. */
102 static hash_map<gimple *, lim_aux_data *> *lim_aux_data_map;
104 /* Description of a memory reference location. */
106 struct mem_ref_loc
108 tree *ref; /* The reference itself. */
109 gimple *stmt; /* The statement in that it occurs. */
113 /* Description of a memory reference. */
115 class im_mem_ref
117 public:
118 unsigned id : 30; /* ID assigned to the memory reference
119 (its index in memory_accesses.refs_list) */
120 unsigned ref_canonical : 1; /* Whether mem.ref was canonicalized. */
121 unsigned ref_decomposed : 1; /* Whether the ref was hashed from mem. */
122 hashval_t hash; /* Its hash value. */
124 /* The memory access itself and associated caching of alias-oracle
125 query meta-data. We are using mem.ref == error_mark_node for the
126 case the reference is represented by its single access stmt
127 in accesses_in_loop[0]. */
128 ao_ref mem;
130 bitmap stored; /* The set of loops in that this memory location
131 is stored to. */
132 bitmap loaded; /* The set of loops in that this memory location
133 is loaded from. */
134 vec<mem_ref_loc> accesses_in_loop;
135 /* The locations of the accesses. */
137 /* The following set is computed on demand. */
138 bitmap_head dep_loop; /* The set of loops in that the memory
139 reference is {in,}dependent in
140 different modes. */
143 /* We use six bits per loop in the ref->dep_loop bitmap to record
144 the dep_kind x dep_state combinations. */
146 enum dep_kind { lim_raw, sm_war, sm_waw };
147 enum dep_state { dep_unknown, dep_independent, dep_dependent };
149 /* coldest outermost loop for given loop. */
150 vec<class loop *> coldest_outermost_loop;
151 /* hotter outer loop nearest to given loop. */
152 vec<class loop *> hotter_than_inner_loop;
154 /* Populate the loop dependence cache of REF for LOOP, KIND with STATE. */
156 static void
157 record_loop_dependence (class loop *loop, im_mem_ref *ref,
158 dep_kind kind, dep_state state)
160 gcc_assert (state != dep_unknown);
161 unsigned bit = 6 * loop->num + kind * 2 + state == dep_dependent ? 1 : 0;
162 bitmap_set_bit (&ref->dep_loop, bit);
165 /* Query the loop dependence cache of REF for LOOP, KIND. */
167 static dep_state
168 query_loop_dependence (class loop *loop, im_mem_ref *ref, dep_kind kind)
170 unsigned first_bit = 6 * loop->num + kind * 2;
171 if (bitmap_bit_p (&ref->dep_loop, first_bit))
172 return dep_independent;
173 else if (bitmap_bit_p (&ref->dep_loop, first_bit + 1))
174 return dep_dependent;
175 return dep_unknown;
178 /* Mem_ref hashtable helpers. */
180 struct mem_ref_hasher : nofree_ptr_hash <im_mem_ref>
182 typedef ao_ref *compare_type;
183 static inline hashval_t hash (const im_mem_ref *);
184 static inline bool equal (const im_mem_ref *, const ao_ref *);
187 /* A hash function for class im_mem_ref object OBJ. */
189 inline hashval_t
190 mem_ref_hasher::hash (const im_mem_ref *mem)
192 return mem->hash;
195 /* An equality function for class im_mem_ref object MEM1 with
196 memory reference OBJ2. */
198 inline bool
199 mem_ref_hasher::equal (const im_mem_ref *mem1, const ao_ref *obj2)
201 if (obj2->max_size_known_p ())
202 return (mem1->ref_decomposed
203 && ((TREE_CODE (mem1->mem.base) == MEM_REF
204 && TREE_CODE (obj2->base) == MEM_REF
205 && operand_equal_p (TREE_OPERAND (mem1->mem.base, 0),
206 TREE_OPERAND (obj2->base, 0), 0)
207 && known_eq (mem_ref_offset (mem1->mem.base) * BITS_PER_UNIT + mem1->mem.offset,
208 mem_ref_offset (obj2->base) * BITS_PER_UNIT + obj2->offset))
209 || (operand_equal_p (mem1->mem.base, obj2->base, 0)
210 && known_eq (mem1->mem.offset, obj2->offset)))
211 && known_eq (mem1->mem.size, obj2->size)
212 && known_eq (mem1->mem.max_size, obj2->max_size)
213 && mem1->mem.volatile_p == obj2->volatile_p
214 && (mem1->mem.ref_alias_set == obj2->ref_alias_set
215 /* We are not canonicalizing alias-sets but for the
216 special-case we didn't canonicalize yet and the
217 incoming ref is a alias-set zero MEM we pick
218 the correct one already. */
219 || (!mem1->ref_canonical
220 && (TREE_CODE (obj2->ref) == MEM_REF
221 || TREE_CODE (obj2->ref) == TARGET_MEM_REF)
222 && obj2->ref_alias_set == 0)
223 /* Likewise if there's a canonical ref with alias-set zero. */
224 || (mem1->ref_canonical && mem1->mem.ref_alias_set == 0))
225 && types_compatible_p (TREE_TYPE (mem1->mem.ref),
226 TREE_TYPE (obj2->ref)));
227 else
228 return operand_equal_p (mem1->mem.ref, obj2->ref, 0);
232 /* Description of memory accesses in loops. */
234 static struct
236 /* The hash table of memory references accessed in loops. */
237 hash_table<mem_ref_hasher> *refs;
239 /* The list of memory references. */
240 vec<im_mem_ref *> refs_list;
242 /* The set of memory references accessed in each loop. */
243 vec<bitmap_head> refs_loaded_in_loop;
245 /* The set of memory references stored in each loop. */
246 vec<bitmap_head> refs_stored_in_loop;
248 /* The set of memory references stored in each loop, including subloops . */
249 vec<bitmap_head> all_refs_stored_in_loop;
251 /* Cache for expanding memory addresses. */
252 hash_map<tree, name_expansion *> *ttae_cache;
253 } memory_accesses;
255 /* Obstack for the bitmaps in the above data structures. */
256 static bitmap_obstack lim_bitmap_obstack;
257 static obstack mem_ref_obstack;
259 static bool ref_indep_loop_p (class loop *, im_mem_ref *, dep_kind);
260 static bool ref_always_accessed_p (class loop *, im_mem_ref *, bool);
261 static bool refs_independent_p (im_mem_ref *, im_mem_ref *, bool = true);
263 /* Minimum cost of an expensive expression. */
264 #define LIM_EXPENSIVE ((unsigned) param_lim_expensive)
266 /* The outermost loop for which execution of the header guarantees that the
267 block will be executed. */
268 #define ALWAYS_EXECUTED_IN(BB) ((class loop *) (BB)->aux)
269 #define SET_ALWAYS_EXECUTED_IN(BB, VAL) ((BB)->aux = (void *) (VAL))
271 /* ID of the shared unanalyzable mem. */
272 #define UNANALYZABLE_MEM_ID 0
274 /* Whether the reference was analyzable. */
275 #define MEM_ANALYZABLE(REF) ((REF)->id != UNANALYZABLE_MEM_ID)
277 static struct lim_aux_data *
278 init_lim_data (gimple *stmt)
280 lim_aux_data *p = XCNEW (struct lim_aux_data);
281 lim_aux_data_map->put (stmt, p);
283 return p;
286 static struct lim_aux_data *
287 get_lim_data (gimple *stmt)
289 lim_aux_data **p = lim_aux_data_map->get (stmt);
290 if (!p)
291 return NULL;
293 return *p;
296 /* Releases the memory occupied by DATA. */
298 static void
299 free_lim_aux_data (struct lim_aux_data *data)
301 data->depends.release ();
302 free (data);
305 static void
306 clear_lim_data (gimple *stmt)
308 lim_aux_data **p = lim_aux_data_map->get (stmt);
309 if (!p)
310 return;
312 free_lim_aux_data (*p);
313 *p = NULL;
317 /* The possibilities of statement movement. */
318 enum move_pos
320 MOVE_IMPOSSIBLE, /* No movement -- side effect expression. */
321 MOVE_PRESERVE_EXECUTION, /* Must not cause the non-executed statement
322 become executed -- memory accesses, ... */
323 MOVE_POSSIBLE /* Unlimited movement. */
327 /* If it is possible to hoist the statement STMT unconditionally,
328 returns MOVE_POSSIBLE.
329 If it is possible to hoist the statement STMT, but we must avoid making
330 it executed if it would not be executed in the original program (e.g.
331 because it may trap), return MOVE_PRESERVE_EXECUTION.
332 Otherwise return MOVE_IMPOSSIBLE. */
334 enum move_pos
335 movement_possibility (gimple *stmt)
337 tree lhs;
338 enum move_pos ret = MOVE_POSSIBLE;
340 if (flag_unswitch_loops
341 && gimple_code (stmt) == GIMPLE_COND)
343 /* If we perform unswitching, force the operands of the invariant
344 condition to be moved out of the loop. */
345 return MOVE_POSSIBLE;
348 if (gimple_code (stmt) == GIMPLE_PHI
349 && gimple_phi_num_args (stmt) <= 2
350 && !virtual_operand_p (gimple_phi_result (stmt))
351 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (gimple_phi_result (stmt)))
352 return MOVE_POSSIBLE;
354 if (gimple_get_lhs (stmt) == NULL_TREE)
355 return MOVE_IMPOSSIBLE;
357 if (gimple_vdef (stmt))
358 return MOVE_IMPOSSIBLE;
360 if (stmt_ends_bb_p (stmt)
361 || gimple_has_volatile_ops (stmt)
362 || gimple_has_side_effects (stmt)
363 || stmt_could_throw_p (cfun, stmt))
364 return MOVE_IMPOSSIBLE;
366 if (is_gimple_call (stmt))
368 /* While pure or const call is guaranteed to have no side effects, we
369 cannot move it arbitrarily. Consider code like
371 char *s = something ();
373 while (1)
375 if (s)
376 t = strlen (s);
377 else
378 t = 0;
381 Here the strlen call cannot be moved out of the loop, even though
382 s is invariant. In addition to possibly creating a call with
383 invalid arguments, moving out a function call that is not executed
384 may cause performance regressions in case the call is costly and
385 not executed at all. */
386 ret = MOVE_PRESERVE_EXECUTION;
387 lhs = gimple_call_lhs (stmt);
389 else if (is_gimple_assign (stmt))
390 lhs = gimple_assign_lhs (stmt);
391 else
392 return MOVE_IMPOSSIBLE;
394 if (TREE_CODE (lhs) == SSA_NAME
395 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
396 return MOVE_IMPOSSIBLE;
398 if (TREE_CODE (lhs) != SSA_NAME
399 || gimple_could_trap_p (stmt))
400 return MOVE_PRESERVE_EXECUTION;
402 /* Non local loads in a transaction cannot be hoisted out. Well,
403 unless the load happens on every path out of the loop, but we
404 don't take this into account yet. */
405 if (flag_tm
406 && gimple_in_transaction (stmt)
407 && gimple_assign_single_p (stmt))
409 tree rhs = gimple_assign_rhs1 (stmt);
410 if (DECL_P (rhs) && is_global_var (rhs))
412 if (dump_file)
414 fprintf (dump_file, "Cannot hoist conditional load of ");
415 print_generic_expr (dump_file, rhs, TDF_SLIM);
416 fprintf (dump_file, " because it is in a transaction.\n");
418 return MOVE_IMPOSSIBLE;
422 return ret;
425 /* Compare the profile count inequality of bb and loop's preheader, it is
426 three-state as stated in profile-count.h, FALSE is returned if inequality
427 cannot be decided. */
428 bool
429 bb_colder_than_loop_preheader (basic_block bb, class loop *loop)
431 gcc_assert (bb && loop);
432 return bb->count < loop_preheader_edge (loop)->src->count;
435 /* Check coldest loop between OUTERMOST_LOOP and LOOP by comparing profile
436 count.
437 It does three steps check:
438 1) Check whether CURR_BB is cold in it's own loop_father, if it is cold, just
439 return NULL which means it should not be moved out at all;
440 2) CURR_BB is NOT cold, check if pre-computed COLDEST_LOOP is outside of
441 OUTERMOST_LOOP, if it is inside of OUTERMOST_LOOP, return the COLDEST_LOOP;
442 3) If COLDEST_LOOP is outside of OUTERMOST_LOOP, check whether there is a
443 hotter loop between OUTERMOST_LOOP and loop in pre-computed
444 HOTTER_THAN_INNER_LOOP, return it's nested inner loop, otherwise return
445 OUTERMOST_LOOP.
446 At last, the coldest_loop is inside of OUTERMOST_LOOP, just return it as
447 the hoist target. */
449 static class loop *
450 get_coldest_out_loop (class loop *outermost_loop, class loop *loop,
451 basic_block curr_bb)
453 gcc_assert (outermost_loop == loop
454 || flow_loop_nested_p (outermost_loop, loop));
456 /* If bb_colder_than_loop_preheader returns false due to three-state
457 comparision, OUTERMOST_LOOP is returned finally to preserve the behavior.
458 Otherwise, return the coldest loop between OUTERMOST_LOOP and LOOP. */
459 if (curr_bb && bb_colder_than_loop_preheader (curr_bb, loop))
460 return NULL;
462 class loop *coldest_loop = coldest_outermost_loop[loop->num];
463 if (loop_depth (coldest_loop) < loop_depth (outermost_loop))
465 class loop *hotter_loop = hotter_than_inner_loop[loop->num];
466 if (!hotter_loop
467 || loop_depth (hotter_loop) < loop_depth (outermost_loop))
468 return outermost_loop;
470 /* hotter_loop is between OUTERMOST_LOOP and LOOP like:
471 [loop tree root, ..., coldest_loop, ..., outermost_loop, ...,
472 hotter_loop, second_coldest_loop, ..., loop]
473 return second_coldest_loop to be the hoist target. */
474 class loop *aloop;
475 for (aloop = hotter_loop->inner; aloop; aloop = aloop->next)
476 if (aloop == loop || flow_loop_nested_p (aloop, loop))
477 return aloop;
479 return coldest_loop;
482 /* Suppose that operand DEF is used inside the LOOP. Returns the outermost
483 loop to that we could move the expression using DEF if it did not have
484 other operands, i.e. the outermost loop enclosing LOOP in that the value
485 of DEF is invariant. */
487 static class loop *
488 outermost_invariant_loop (tree def, class loop *loop)
490 gimple *def_stmt;
491 basic_block def_bb;
492 class loop *max_loop;
493 struct lim_aux_data *lim_data;
495 if (!def)
496 return superloop_at_depth (loop, 1);
498 if (TREE_CODE (def) != SSA_NAME)
500 gcc_assert (is_gimple_min_invariant (def));
501 return superloop_at_depth (loop, 1);
504 def_stmt = SSA_NAME_DEF_STMT (def);
505 def_bb = gimple_bb (def_stmt);
506 if (!def_bb)
507 return superloop_at_depth (loop, 1);
509 max_loop = find_common_loop (loop, def_bb->loop_father);
511 lim_data = get_lim_data (def_stmt);
512 if (lim_data != NULL && lim_data->max_loop != NULL)
513 max_loop = find_common_loop (max_loop,
514 loop_outer (lim_data->max_loop));
515 if (max_loop == loop)
516 return NULL;
517 max_loop = superloop_at_depth (loop, loop_depth (max_loop) + 1);
519 return max_loop;
522 /* DATA is a structure containing information associated with a statement
523 inside LOOP. DEF is one of the operands of this statement.
525 Find the outermost loop enclosing LOOP in that value of DEF is invariant
526 and record this in DATA->max_loop field. If DEF itself is defined inside
527 this loop as well (i.e. we need to hoist it out of the loop if we want
528 to hoist the statement represented by DATA), record the statement in that
529 DEF is defined to the DATA->depends list. Additionally if ADD_COST is true,
530 add the cost of the computation of DEF to the DATA->cost.
532 If DEF is not invariant in LOOP, return false. Otherwise return TRUE. */
534 static bool
535 add_dependency (tree def, struct lim_aux_data *data, class loop *loop,
536 bool add_cost)
538 gimple *def_stmt = SSA_NAME_DEF_STMT (def);
539 basic_block def_bb = gimple_bb (def_stmt);
540 class loop *max_loop;
541 struct lim_aux_data *def_data;
543 if (!def_bb)
544 return true;
546 max_loop = outermost_invariant_loop (def, loop);
547 if (!max_loop)
548 return false;
550 if (flow_loop_nested_p (data->max_loop, max_loop))
551 data->max_loop = max_loop;
553 def_data = get_lim_data (def_stmt);
554 if (!def_data)
555 return true;
557 if (add_cost
558 /* Only add the cost if the statement defining DEF is inside LOOP,
559 i.e. if it is likely that by moving the invariants dependent
560 on it, we will be able to avoid creating a new register for
561 it (since it will be only used in these dependent invariants). */
562 && def_bb->loop_father == loop)
563 data->cost += def_data->cost;
565 data->depends.safe_push (def_stmt);
567 return true;
570 /* Returns an estimate for a cost of statement STMT. The values here
571 are just ad-hoc constants, similar to costs for inlining. */
573 static unsigned
574 stmt_cost (gimple *stmt)
576 /* Always try to create possibilities for unswitching. */
577 if (gimple_code (stmt) == GIMPLE_COND
578 || gimple_code (stmt) == GIMPLE_PHI)
579 return LIM_EXPENSIVE;
581 /* We should be hoisting calls if possible. */
582 if (is_gimple_call (stmt))
584 tree fndecl;
586 /* Unless the call is a builtin_constant_p; this always folds to a
587 constant, so moving it is useless. */
588 fndecl = gimple_call_fndecl (stmt);
589 if (fndecl && fndecl_built_in_p (fndecl, BUILT_IN_CONSTANT_P))
590 return 0;
592 return LIM_EXPENSIVE;
595 /* Hoisting memory references out should almost surely be a win. */
596 if (gimple_references_memory_p (stmt))
597 return LIM_EXPENSIVE;
599 if (gimple_code (stmt) != GIMPLE_ASSIGN)
600 return 1;
602 switch (gimple_assign_rhs_code (stmt))
604 case MULT_EXPR:
605 case WIDEN_MULT_EXPR:
606 case WIDEN_MULT_PLUS_EXPR:
607 case WIDEN_MULT_MINUS_EXPR:
608 case DOT_PROD_EXPR:
609 case TRUNC_DIV_EXPR:
610 case CEIL_DIV_EXPR:
611 case FLOOR_DIV_EXPR:
612 case ROUND_DIV_EXPR:
613 case EXACT_DIV_EXPR:
614 case CEIL_MOD_EXPR:
615 case FLOOR_MOD_EXPR:
616 case ROUND_MOD_EXPR:
617 case TRUNC_MOD_EXPR:
618 case RDIV_EXPR:
619 /* Division and multiplication are usually expensive. */
620 return LIM_EXPENSIVE;
622 case LSHIFT_EXPR:
623 case RSHIFT_EXPR:
624 case WIDEN_LSHIFT_EXPR:
625 case LROTATE_EXPR:
626 case RROTATE_EXPR:
627 /* Shifts and rotates are usually expensive. */
628 return LIM_EXPENSIVE;
630 case CONSTRUCTOR:
631 /* Make vector construction cost proportional to the number
632 of elements. */
633 return CONSTRUCTOR_NELTS (gimple_assign_rhs1 (stmt));
635 case SSA_NAME:
636 case PAREN_EXPR:
637 /* Whether or not something is wrapped inside a PAREN_EXPR
638 should not change move cost. Nor should an intermediate
639 unpropagated SSA name copy. */
640 return 0;
642 default:
643 return 1;
647 /* Finds the outermost loop between OUTER and LOOP in that the memory reference
648 REF is independent. If REF is not independent in LOOP, NULL is returned
649 instead. */
651 static class loop *
652 outermost_indep_loop (class loop *outer, class loop *loop, im_mem_ref *ref)
654 class loop *aloop;
656 if (ref->stored && bitmap_bit_p (ref->stored, loop->num))
657 return NULL;
659 for (aloop = outer;
660 aloop != loop;
661 aloop = superloop_at_depth (loop, loop_depth (aloop) + 1))
662 if ((!ref->stored || !bitmap_bit_p (ref->stored, aloop->num))
663 && ref_indep_loop_p (aloop, ref, lim_raw))
664 return aloop;
666 if (ref_indep_loop_p (loop, ref, lim_raw))
667 return loop;
668 else
669 return NULL;
672 /* If there is a simple load or store to a memory reference in STMT, returns
673 the location of the memory reference, and sets IS_STORE according to whether
674 it is a store or load. Otherwise, returns NULL. */
676 static tree *
677 simple_mem_ref_in_stmt (gimple *stmt, bool *is_store)
679 tree *lhs, *rhs;
681 /* Recognize SSA_NAME = MEM and MEM = (SSA_NAME | invariant) patterns. */
682 if (!gimple_assign_single_p (stmt))
683 return NULL;
685 lhs = gimple_assign_lhs_ptr (stmt);
686 rhs = gimple_assign_rhs1_ptr (stmt);
688 if (TREE_CODE (*lhs) == SSA_NAME && gimple_vuse (stmt))
690 *is_store = false;
691 return rhs;
693 else if (gimple_vdef (stmt)
694 && (TREE_CODE (*rhs) == SSA_NAME || is_gimple_min_invariant (*rhs)))
696 *is_store = true;
697 return lhs;
699 else
700 return NULL;
703 /* From a controlling predicate in DOM determine the arguments from
704 the PHI node PHI that are chosen if the predicate evaluates to
705 true and false and store them to *TRUE_ARG_P and *FALSE_ARG_P if
706 they are non-NULL. Returns true if the arguments can be determined,
707 else return false. */
709 static bool
710 extract_true_false_args_from_phi (basic_block dom, gphi *phi,
711 tree *true_arg_p, tree *false_arg_p)
713 edge te, fe;
714 if (! extract_true_false_controlled_edges (dom, gimple_bb (phi),
715 &te, &fe))
716 return false;
718 if (true_arg_p)
719 *true_arg_p = PHI_ARG_DEF (phi, te->dest_idx);
720 if (false_arg_p)
721 *false_arg_p = PHI_ARG_DEF (phi, fe->dest_idx);
723 return true;
726 /* Determine the outermost loop to that it is possible to hoist a statement
727 STMT and store it to LIM_DATA (STMT)->max_loop. To do this we determine
728 the outermost loop in that the value computed by STMT is invariant.
729 If MUST_PRESERVE_EXEC is true, additionally choose such a loop that
730 we preserve the fact whether STMT is executed. It also fills other related
731 information to LIM_DATA (STMT).
733 The function returns false if STMT cannot be hoisted outside of the loop it
734 is defined in, and true otherwise. */
736 static bool
737 determine_max_movement (gimple *stmt, bool must_preserve_exec)
739 basic_block bb = gimple_bb (stmt);
740 class loop *loop = bb->loop_father;
741 class loop *level;
742 struct lim_aux_data *lim_data = get_lim_data (stmt);
743 tree val;
744 ssa_op_iter iter;
746 if (must_preserve_exec)
747 level = ALWAYS_EXECUTED_IN (bb);
748 else
749 level = superloop_at_depth (loop, 1);
750 lim_data->max_loop = get_coldest_out_loop (level, loop, bb);
751 if (!lim_data->max_loop)
752 return false;
754 if (gphi *phi = dyn_cast <gphi *> (stmt))
756 use_operand_p use_p;
757 unsigned min_cost = UINT_MAX;
758 unsigned total_cost = 0;
759 struct lim_aux_data *def_data;
761 /* We will end up promoting dependencies to be unconditionally
762 evaluated. For this reason the PHI cost (and thus the
763 cost we remove from the loop by doing the invariant motion)
764 is that of the cheapest PHI argument dependency chain. */
765 FOR_EACH_PHI_ARG (use_p, phi, iter, SSA_OP_USE)
767 val = USE_FROM_PTR (use_p);
769 if (TREE_CODE (val) != SSA_NAME)
771 /* Assign const 1 to constants. */
772 min_cost = MIN (min_cost, 1);
773 total_cost += 1;
774 continue;
776 if (!add_dependency (val, lim_data, loop, false))
777 return false;
779 gimple *def_stmt = SSA_NAME_DEF_STMT (val);
780 if (gimple_bb (def_stmt)
781 && gimple_bb (def_stmt)->loop_father == loop)
783 def_data = get_lim_data (def_stmt);
784 if (def_data)
786 min_cost = MIN (min_cost, def_data->cost);
787 total_cost += def_data->cost;
792 min_cost = MIN (min_cost, total_cost);
793 lim_data->cost += min_cost;
795 if (gimple_phi_num_args (phi) > 1)
797 basic_block dom = get_immediate_dominator (CDI_DOMINATORS, bb);
798 gimple *cond;
799 if (gsi_end_p (gsi_last_bb (dom)))
800 return false;
801 cond = gsi_stmt (gsi_last_bb (dom));
802 if (gimple_code (cond) != GIMPLE_COND)
803 return false;
804 /* Verify that this is an extended form of a diamond and
805 the PHI arguments are completely controlled by the
806 predicate in DOM. */
807 if (!extract_true_false_args_from_phi (dom, phi, NULL, NULL))
808 return false;
810 /* Fold in dependencies and cost of the condition. */
811 FOR_EACH_SSA_TREE_OPERAND (val, cond, iter, SSA_OP_USE)
813 if (!add_dependency (val, lim_data, loop, false))
814 return false;
815 def_data = get_lim_data (SSA_NAME_DEF_STMT (val));
816 if (def_data)
817 lim_data->cost += def_data->cost;
820 /* We want to avoid unconditionally executing very expensive
821 operations. As costs for our dependencies cannot be
822 negative just claim we are not invariand for this case.
823 We also are not sure whether the control-flow inside the
824 loop will vanish. */
825 if (total_cost - min_cost >= 2 * LIM_EXPENSIVE
826 && !(min_cost != 0
827 && total_cost / min_cost <= 2))
828 return false;
830 /* Assume that the control-flow in the loop will vanish.
831 ??? We should verify this and not artificially increase
832 the cost if that is not the case. */
833 lim_data->cost += stmt_cost (stmt);
836 return true;
838 else
839 FOR_EACH_SSA_TREE_OPERAND (val, stmt, iter, SSA_OP_USE)
840 if (!add_dependency (val, lim_data, loop, true))
841 return false;
843 if (gimple_vuse (stmt))
845 im_mem_ref *ref
846 = lim_data ? memory_accesses.refs_list[lim_data->ref] : NULL;
847 if (ref
848 && MEM_ANALYZABLE (ref))
850 lim_data->max_loop = outermost_indep_loop (lim_data->max_loop,
851 loop, ref);
852 if (!lim_data->max_loop)
853 return false;
855 else if (! add_dependency (gimple_vuse (stmt), lim_data, loop, false))
856 return false;
859 lim_data->cost += stmt_cost (stmt);
861 return true;
864 /* Suppose that some statement in ORIG_LOOP is hoisted to the loop LEVEL,
865 and that one of the operands of this statement is computed by STMT.
866 Ensure that STMT (together with all the statements that define its
867 operands) is hoisted at least out of the loop LEVEL. */
869 static void
870 set_level (gimple *stmt, class loop *orig_loop, class loop *level)
872 class loop *stmt_loop = gimple_bb (stmt)->loop_father;
873 struct lim_aux_data *lim_data;
874 gimple *dep_stmt;
875 unsigned i;
877 stmt_loop = find_common_loop (orig_loop, stmt_loop);
878 lim_data = get_lim_data (stmt);
879 if (lim_data != NULL && lim_data->tgt_loop != NULL)
880 stmt_loop = find_common_loop (stmt_loop,
881 loop_outer (lim_data->tgt_loop));
882 if (flow_loop_nested_p (stmt_loop, level))
883 return;
885 gcc_assert (level == lim_data->max_loop
886 || flow_loop_nested_p (lim_data->max_loop, level));
888 lim_data->tgt_loop = level;
889 FOR_EACH_VEC_ELT (lim_data->depends, i, dep_stmt)
890 set_level (dep_stmt, orig_loop, level);
893 /* Determines an outermost loop from that we want to hoist the statement STMT.
894 For now we chose the outermost possible loop. TODO -- use profiling
895 information to set it more sanely. */
897 static void
898 set_profitable_level (gimple *stmt)
900 set_level (stmt, gimple_bb (stmt)->loop_father, get_lim_data (stmt)->max_loop);
903 /* Returns true if STMT is a call that has side effects. */
905 static bool
906 nonpure_call_p (gimple *stmt)
908 if (gimple_code (stmt) != GIMPLE_CALL)
909 return false;
911 return gimple_has_side_effects (stmt);
914 /* Rewrite a/b to a*(1/b). Return the invariant stmt to process. */
916 static gimple *
917 rewrite_reciprocal (gimple_stmt_iterator *bsi)
919 gassign *stmt, *stmt1, *stmt2;
920 tree name, lhs, type;
921 tree real_one;
922 gimple_stmt_iterator gsi;
924 stmt = as_a <gassign *> (gsi_stmt (*bsi));
925 lhs = gimple_assign_lhs (stmt);
926 type = TREE_TYPE (lhs);
928 real_one = build_one_cst (type);
930 name = make_temp_ssa_name (type, NULL, "reciptmp");
931 stmt1 = gimple_build_assign (name, RDIV_EXPR, real_one,
932 gimple_assign_rhs2 (stmt));
933 stmt2 = gimple_build_assign (lhs, MULT_EXPR, name,
934 gimple_assign_rhs1 (stmt));
936 /* Replace division stmt with reciprocal and multiply stmts.
937 The multiply stmt is not invariant, so update iterator
938 and avoid rescanning. */
939 gsi = *bsi;
940 gsi_insert_before (bsi, stmt1, GSI_NEW_STMT);
941 gsi_replace (&gsi, stmt2, true);
943 /* Continue processing with invariant reciprocal statement. */
944 return stmt1;
947 /* Check if the pattern at *BSI is a bittest of the form
948 (A >> B) & 1 != 0 and in this case rewrite it to A & (1 << B) != 0. */
950 static gimple *
951 rewrite_bittest (gimple_stmt_iterator *bsi)
953 gassign *stmt;
954 gimple *stmt1;
955 gassign *stmt2;
956 gimple *use_stmt;
957 gcond *cond_stmt;
958 tree lhs, name, t, a, b;
959 use_operand_p use;
961 stmt = as_a <gassign *> (gsi_stmt (*bsi));
962 lhs = gimple_assign_lhs (stmt);
964 /* Verify that the single use of lhs is a comparison against zero. */
965 if (TREE_CODE (lhs) != SSA_NAME
966 || !single_imm_use (lhs, &use, &use_stmt))
967 return stmt;
968 cond_stmt = dyn_cast <gcond *> (use_stmt);
969 if (!cond_stmt)
970 return stmt;
971 if (gimple_cond_lhs (cond_stmt) != lhs
972 || (gimple_cond_code (cond_stmt) != NE_EXPR
973 && gimple_cond_code (cond_stmt) != EQ_EXPR)
974 || !integer_zerop (gimple_cond_rhs (cond_stmt)))
975 return stmt;
977 /* Get at the operands of the shift. The rhs is TMP1 & 1. */
978 stmt1 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
979 if (gimple_code (stmt1) != GIMPLE_ASSIGN)
980 return stmt;
982 /* There is a conversion in between possibly inserted by fold. */
983 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt1)))
985 t = gimple_assign_rhs1 (stmt1);
986 if (TREE_CODE (t) != SSA_NAME
987 || !has_single_use (t))
988 return stmt;
989 stmt1 = SSA_NAME_DEF_STMT (t);
990 if (gimple_code (stmt1) != GIMPLE_ASSIGN)
991 return stmt;
994 /* Verify that B is loop invariant but A is not. Verify that with
995 all the stmt walking we are still in the same loop. */
996 if (gimple_assign_rhs_code (stmt1) != RSHIFT_EXPR
997 || loop_containing_stmt (stmt1) != loop_containing_stmt (stmt))
998 return stmt;
1000 a = gimple_assign_rhs1 (stmt1);
1001 b = gimple_assign_rhs2 (stmt1);
1003 if (outermost_invariant_loop (b, loop_containing_stmt (stmt1)) != NULL
1004 && outermost_invariant_loop (a, loop_containing_stmt (stmt1)) == NULL)
1006 gimple_stmt_iterator rsi;
1008 /* 1 << B */
1009 t = fold_build2 (LSHIFT_EXPR, TREE_TYPE (a),
1010 build_int_cst (TREE_TYPE (a), 1), b);
1011 name = make_temp_ssa_name (TREE_TYPE (a), NULL, "shifttmp");
1012 stmt1 = gimple_build_assign (name, t);
1014 /* A & (1 << B) */
1015 t = fold_build2 (BIT_AND_EXPR, TREE_TYPE (a), a, name);
1016 name = make_temp_ssa_name (TREE_TYPE (a), NULL, "shifttmp");
1017 stmt2 = gimple_build_assign (name, t);
1019 /* Replace the SSA_NAME we compare against zero. Adjust
1020 the type of zero accordingly. */
1021 SET_USE (use, name);
1022 gimple_cond_set_rhs (cond_stmt,
1023 build_int_cst_type (TREE_TYPE (name),
1024 0));
1026 /* Don't use gsi_replace here, none of the new assignments sets
1027 the variable originally set in stmt. Move bsi to stmt1, and
1028 then remove the original stmt, so that we get a chance to
1029 retain debug info for it. */
1030 rsi = *bsi;
1031 gsi_insert_before (bsi, stmt1, GSI_NEW_STMT);
1032 gsi_insert_before (&rsi, stmt2, GSI_SAME_STMT);
1033 gimple *to_release = gsi_stmt (rsi);
1034 gsi_remove (&rsi, true);
1035 release_defs (to_release);
1037 return stmt1;
1040 return stmt;
1043 /* Determine the outermost loops in that statements in basic block BB are
1044 invariant, and record them to the LIM_DATA associated with the
1045 statements. */
1047 static void
1048 compute_invariantness (basic_block bb)
1050 enum move_pos pos;
1051 gimple_stmt_iterator bsi;
1052 gimple *stmt;
1053 bool maybe_never = ALWAYS_EXECUTED_IN (bb) == NULL;
1054 class loop *outermost = ALWAYS_EXECUTED_IN (bb);
1055 struct lim_aux_data *lim_data;
1057 if (!loop_outer (bb->loop_father))
1058 return;
1060 if (dump_file && (dump_flags & TDF_DETAILS))
1061 fprintf (dump_file, "Basic block %d (loop %d -- depth %d):\n\n",
1062 bb->index, bb->loop_father->num, loop_depth (bb->loop_father));
1064 /* Look at PHI nodes, but only if there is at most two.
1065 ??? We could relax this further by post-processing the inserted
1066 code and transforming adjacent cond-exprs with the same predicate
1067 to control flow again. */
1068 bsi = gsi_start_phis (bb);
1069 if (!gsi_end_p (bsi)
1070 && ((gsi_next (&bsi), gsi_end_p (bsi))
1071 || (gsi_next (&bsi), gsi_end_p (bsi))))
1072 for (bsi = gsi_start_phis (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1074 stmt = gsi_stmt (bsi);
1076 pos = movement_possibility (stmt);
1077 if (pos == MOVE_IMPOSSIBLE)
1078 continue;
1080 lim_data = get_lim_data (stmt);
1081 if (! lim_data)
1082 lim_data = init_lim_data (stmt);
1083 lim_data->always_executed_in = outermost;
1085 if (!determine_max_movement (stmt, false))
1087 lim_data->max_loop = NULL;
1088 continue;
1091 if (dump_file && (dump_flags & TDF_DETAILS))
1093 print_gimple_stmt (dump_file, stmt, 2);
1094 fprintf (dump_file, " invariant up to level %d, cost %d.\n\n",
1095 loop_depth (lim_data->max_loop),
1096 lim_data->cost);
1099 if (lim_data->cost >= LIM_EXPENSIVE)
1100 set_profitable_level (stmt);
1103 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1105 stmt = gsi_stmt (bsi);
1107 pos = movement_possibility (stmt);
1108 if (pos == MOVE_IMPOSSIBLE)
1110 if (nonpure_call_p (stmt))
1112 maybe_never = true;
1113 outermost = NULL;
1115 /* Make sure to note always_executed_in for stores to make
1116 store-motion work. */
1117 else if (stmt_makes_single_store (stmt))
1119 struct lim_aux_data *lim_data = get_lim_data (stmt);
1120 if (! lim_data)
1121 lim_data = init_lim_data (stmt);
1122 lim_data->always_executed_in = outermost;
1124 continue;
1127 if (is_gimple_assign (stmt)
1128 && (get_gimple_rhs_class (gimple_assign_rhs_code (stmt))
1129 == GIMPLE_BINARY_RHS))
1131 tree op0 = gimple_assign_rhs1 (stmt);
1132 tree op1 = gimple_assign_rhs2 (stmt);
1133 class loop *ol1 = outermost_invariant_loop (op1,
1134 loop_containing_stmt (stmt));
1136 /* If divisor is invariant, convert a/b to a*(1/b), allowing reciprocal
1137 to be hoisted out of loop, saving expensive divide. */
1138 if (pos == MOVE_POSSIBLE
1139 && gimple_assign_rhs_code (stmt) == RDIV_EXPR
1140 && flag_unsafe_math_optimizations
1141 && !flag_trapping_math
1142 && ol1 != NULL
1143 && outermost_invariant_loop (op0, ol1) == NULL)
1144 stmt = rewrite_reciprocal (&bsi);
1146 /* If the shift count is invariant, convert (A >> B) & 1 to
1147 A & (1 << B) allowing the bit mask to be hoisted out of the loop
1148 saving an expensive shift. */
1149 if (pos == MOVE_POSSIBLE
1150 && gimple_assign_rhs_code (stmt) == BIT_AND_EXPR
1151 && integer_onep (op1)
1152 && TREE_CODE (op0) == SSA_NAME
1153 && has_single_use (op0))
1154 stmt = rewrite_bittest (&bsi);
1157 lim_data = get_lim_data (stmt);
1158 if (! lim_data)
1159 lim_data = init_lim_data (stmt);
1160 lim_data->always_executed_in = outermost;
1162 if (maybe_never && pos == MOVE_PRESERVE_EXECUTION)
1163 continue;
1165 if (!determine_max_movement (stmt, pos == MOVE_PRESERVE_EXECUTION))
1167 lim_data->max_loop = NULL;
1168 continue;
1171 if (dump_file && (dump_flags & TDF_DETAILS))
1173 print_gimple_stmt (dump_file, stmt, 2);
1174 fprintf (dump_file, " invariant up to level %d, cost %d.\n\n",
1175 loop_depth (lim_data->max_loop),
1176 lim_data->cost);
1179 if (lim_data->cost >= LIM_EXPENSIVE)
1180 set_profitable_level (stmt);
1184 /* Hoist the statements in basic block BB out of the loops prescribed by
1185 data stored in LIM_DATA structures associated with each statement. Callback
1186 for walk_dominator_tree. */
1188 unsigned int
1189 move_computations_worker (basic_block bb)
1191 class loop *level;
1192 unsigned cost = 0;
1193 struct lim_aux_data *lim_data;
1194 unsigned int todo = 0;
1196 if (!loop_outer (bb->loop_father))
1197 return todo;
1199 for (gphi_iterator bsi = gsi_start_phis (bb); !gsi_end_p (bsi); )
1201 gassign *new_stmt;
1202 gphi *stmt = bsi.phi ();
1204 lim_data = get_lim_data (stmt);
1205 if (lim_data == NULL)
1207 gsi_next (&bsi);
1208 continue;
1211 cost = lim_data->cost;
1212 level = lim_data->tgt_loop;
1213 clear_lim_data (stmt);
1215 if (!level)
1217 gsi_next (&bsi);
1218 continue;
1221 if (dump_file && (dump_flags & TDF_DETAILS))
1223 fprintf (dump_file, "Moving PHI node\n");
1224 print_gimple_stmt (dump_file, stmt, 0);
1225 fprintf (dump_file, "(cost %u) out of loop %d.\n\n",
1226 cost, level->num);
1229 if (gimple_phi_num_args (stmt) == 1)
1231 tree arg = PHI_ARG_DEF (stmt, 0);
1232 new_stmt = gimple_build_assign (gimple_phi_result (stmt),
1233 TREE_CODE (arg), arg);
1235 else
1237 basic_block dom = get_immediate_dominator (CDI_DOMINATORS, bb);
1238 gimple *cond = gsi_stmt (gsi_last_bb (dom));
1239 tree arg0 = NULL_TREE, arg1 = NULL_TREE, t;
1240 /* Get the PHI arguments corresponding to the true and false
1241 edges of COND. */
1242 extract_true_false_args_from_phi (dom, stmt, &arg0, &arg1);
1243 gcc_assert (arg0 && arg1);
1244 t = make_ssa_name (boolean_type_node);
1245 new_stmt = gimple_build_assign (t, gimple_cond_code (cond),
1246 gimple_cond_lhs (cond),
1247 gimple_cond_rhs (cond));
1248 gsi_insert_on_edge (loop_preheader_edge (level), new_stmt);
1249 new_stmt = gimple_build_assign (gimple_phi_result (stmt),
1250 COND_EXPR, t, arg0, arg1);
1251 todo |= TODO_cleanup_cfg;
1253 if (!ALWAYS_EXECUTED_IN (bb)
1254 || (ALWAYS_EXECUTED_IN (bb) != level
1255 && !flow_loop_nested_p (ALWAYS_EXECUTED_IN (bb), level)))
1256 reset_flow_sensitive_info (gimple_assign_lhs (new_stmt));
1257 gsi_insert_on_edge (loop_preheader_edge (level), new_stmt);
1258 remove_phi_node (&bsi, false);
1261 for (gimple_stmt_iterator bsi = gsi_start_bb (bb); !gsi_end_p (bsi); )
1263 edge e;
1265 gimple *stmt = gsi_stmt (bsi);
1267 lim_data = get_lim_data (stmt);
1268 if (lim_data == NULL)
1270 gsi_next (&bsi);
1271 continue;
1274 cost = lim_data->cost;
1275 level = lim_data->tgt_loop;
1276 clear_lim_data (stmt);
1278 if (!level)
1280 gsi_next (&bsi);
1281 continue;
1284 /* We do not really want to move conditionals out of the loop; we just
1285 placed it here to force its operands to be moved if necessary. */
1286 if (gimple_code (stmt) == GIMPLE_COND)
1288 gsi_next (&bsi);
1289 continue;
1292 if (dump_file && (dump_flags & TDF_DETAILS))
1294 fprintf (dump_file, "Moving statement\n");
1295 print_gimple_stmt (dump_file, stmt, 0);
1296 fprintf (dump_file, "(cost %u) out of loop %d.\n\n",
1297 cost, level->num);
1300 e = loop_preheader_edge (level);
1301 gcc_assert (!gimple_vdef (stmt));
1302 if (gimple_vuse (stmt))
1304 /* The new VUSE is the one from the virtual PHI in the loop
1305 header or the one already present. */
1306 gphi_iterator gsi2;
1307 for (gsi2 = gsi_start_phis (e->dest);
1308 !gsi_end_p (gsi2); gsi_next (&gsi2))
1310 gphi *phi = gsi2.phi ();
1311 if (virtual_operand_p (gimple_phi_result (phi)))
1313 SET_USE (gimple_vuse_op (stmt),
1314 PHI_ARG_DEF_FROM_EDGE (phi, e));
1315 break;
1319 gsi_remove (&bsi, false);
1320 if (gimple_has_lhs (stmt)
1321 && TREE_CODE (gimple_get_lhs (stmt)) == SSA_NAME
1322 && (!ALWAYS_EXECUTED_IN (bb)
1323 || !(ALWAYS_EXECUTED_IN (bb) == level
1324 || flow_loop_nested_p (ALWAYS_EXECUTED_IN (bb), level))))
1325 reset_flow_sensitive_info (gimple_get_lhs (stmt));
1326 /* In case this is a stmt that is not unconditionally executed
1327 when the target loop header is executed and the stmt may
1328 invoke undefined integer or pointer overflow rewrite it to
1329 unsigned arithmetic. */
1330 if (is_gimple_assign (stmt)
1331 && INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_lhs (stmt)))
1332 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (gimple_assign_lhs (stmt)))
1333 && arith_code_with_undefined_signed_overflow
1334 (gimple_assign_rhs_code (stmt))
1335 && (!ALWAYS_EXECUTED_IN (bb)
1336 || !(ALWAYS_EXECUTED_IN (bb) == level
1337 || flow_loop_nested_p (ALWAYS_EXECUTED_IN (bb), level))))
1338 gsi_insert_seq_on_edge (e, rewrite_to_defined_overflow (stmt));
1339 else
1340 gsi_insert_on_edge (e, stmt);
1343 return todo;
1346 /* Checks whether the statement defining variable *INDEX can be hoisted
1347 out of the loop passed in DATA. Callback for for_each_index. */
1349 static bool
1350 may_move_till (tree ref, tree *index, void *data)
1352 class loop *loop = (class loop *) data, *max_loop;
1354 /* If REF is an array reference, check also that the step and the lower
1355 bound is invariant in LOOP. */
1356 if (TREE_CODE (ref) == ARRAY_REF)
1358 tree step = TREE_OPERAND (ref, 3);
1359 tree lbound = TREE_OPERAND (ref, 2);
1361 max_loop = outermost_invariant_loop (step, loop);
1362 if (!max_loop)
1363 return false;
1365 max_loop = outermost_invariant_loop (lbound, loop);
1366 if (!max_loop)
1367 return false;
1370 max_loop = outermost_invariant_loop (*index, loop);
1371 if (!max_loop)
1372 return false;
1374 return true;
1377 /* If OP is SSA NAME, force the statement that defines it to be
1378 moved out of the LOOP. ORIG_LOOP is the loop in that EXPR is used. */
1380 static void
1381 force_move_till_op (tree op, class loop *orig_loop, class loop *loop)
1383 gimple *stmt;
1385 if (!op
1386 || is_gimple_min_invariant (op))
1387 return;
1389 gcc_assert (TREE_CODE (op) == SSA_NAME);
1391 stmt = SSA_NAME_DEF_STMT (op);
1392 if (gimple_nop_p (stmt))
1393 return;
1395 set_level (stmt, orig_loop, loop);
1398 /* Forces statement defining invariants in REF (and *INDEX) to be moved out of
1399 the LOOP. The reference REF is used in the loop ORIG_LOOP. Callback for
1400 for_each_index. */
1402 struct fmt_data
1404 class loop *loop;
1405 class loop *orig_loop;
1408 static bool
1409 force_move_till (tree ref, tree *index, void *data)
1411 struct fmt_data *fmt_data = (struct fmt_data *) data;
1413 if (TREE_CODE (ref) == ARRAY_REF)
1415 tree step = TREE_OPERAND (ref, 3);
1416 tree lbound = TREE_OPERAND (ref, 2);
1418 force_move_till_op (step, fmt_data->orig_loop, fmt_data->loop);
1419 force_move_till_op (lbound, fmt_data->orig_loop, fmt_data->loop);
1422 force_move_till_op (*index, fmt_data->orig_loop, fmt_data->loop);
1424 return true;
1427 /* A function to free the mem_ref object OBJ. */
1429 static void
1430 memref_free (class im_mem_ref *mem)
1432 mem->accesses_in_loop.release ();
1435 /* Allocates and returns a memory reference description for MEM whose hash
1436 value is HASH and id is ID. */
1438 static im_mem_ref *
1439 mem_ref_alloc (ao_ref *mem, unsigned hash, unsigned id)
1441 im_mem_ref *ref = XOBNEW (&mem_ref_obstack, class im_mem_ref);
1442 if (mem)
1443 ref->mem = *mem;
1444 else
1445 ao_ref_init (&ref->mem, error_mark_node);
1446 ref->id = id;
1447 ref->ref_canonical = false;
1448 ref->ref_decomposed = false;
1449 ref->hash = hash;
1450 ref->stored = NULL;
1451 ref->loaded = NULL;
1452 bitmap_initialize (&ref->dep_loop, &lim_bitmap_obstack);
1453 ref->accesses_in_loop.create (1);
1455 return ref;
1458 /* Records memory reference location *LOC in LOOP to the memory reference
1459 description REF. The reference occurs in statement STMT. */
1461 static void
1462 record_mem_ref_loc (im_mem_ref *ref, gimple *stmt, tree *loc)
1464 mem_ref_loc aref;
1465 aref.stmt = stmt;
1466 aref.ref = loc;
1467 ref->accesses_in_loop.safe_push (aref);
1470 /* Set the LOOP bit in REF stored bitmap and allocate that if
1471 necessary. Return whether a bit was changed. */
1473 static bool
1474 set_ref_stored_in_loop (im_mem_ref *ref, class loop *loop)
1476 if (!ref->stored)
1477 ref->stored = BITMAP_ALLOC (&lim_bitmap_obstack);
1478 return bitmap_set_bit (ref->stored, loop->num);
1481 /* Marks reference REF as stored in LOOP. */
1483 static void
1484 mark_ref_stored (im_mem_ref *ref, class loop *loop)
1486 while (loop != current_loops->tree_root
1487 && set_ref_stored_in_loop (ref, loop))
1488 loop = loop_outer (loop);
1491 /* Set the LOOP bit in REF loaded bitmap and allocate that if
1492 necessary. Return whether a bit was changed. */
1494 static bool
1495 set_ref_loaded_in_loop (im_mem_ref *ref, class loop *loop)
1497 if (!ref->loaded)
1498 ref->loaded = BITMAP_ALLOC (&lim_bitmap_obstack);
1499 return bitmap_set_bit (ref->loaded, loop->num);
1502 /* Marks reference REF as loaded in LOOP. */
1504 static void
1505 mark_ref_loaded (im_mem_ref *ref, class loop *loop)
1507 while (loop != current_loops->tree_root
1508 && set_ref_loaded_in_loop (ref, loop))
1509 loop = loop_outer (loop);
1512 /* Gathers memory references in statement STMT in LOOP, storing the
1513 information about them in the memory_accesses structure. Marks
1514 the vops accessed through unrecognized statements there as
1515 well. */
1517 static void
1518 gather_mem_refs_stmt (class loop *loop, gimple *stmt)
1520 tree *mem = NULL;
1521 hashval_t hash;
1522 im_mem_ref **slot;
1523 im_mem_ref *ref;
1524 bool is_stored;
1525 unsigned id;
1527 if (!gimple_vuse (stmt))
1528 return;
1530 mem = simple_mem_ref_in_stmt (stmt, &is_stored);
1531 if (!mem && is_gimple_assign (stmt))
1533 /* For aggregate copies record distinct references but use them
1534 only for disambiguation purposes. */
1535 id = memory_accesses.refs_list.length ();
1536 ref = mem_ref_alloc (NULL, 0, id);
1537 memory_accesses.refs_list.safe_push (ref);
1538 if (dump_file && (dump_flags & TDF_DETAILS))
1540 fprintf (dump_file, "Unhandled memory reference %u: ", id);
1541 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
1543 record_mem_ref_loc (ref, stmt, mem);
1544 is_stored = gimple_vdef (stmt);
1546 else if (!mem)
1548 /* We use the shared mem_ref for all unanalyzable refs. */
1549 id = UNANALYZABLE_MEM_ID;
1550 ref = memory_accesses.refs_list[id];
1551 if (dump_file && (dump_flags & TDF_DETAILS))
1553 fprintf (dump_file, "Unanalyzed memory reference %u: ", id);
1554 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
1556 is_stored = gimple_vdef (stmt);
1558 else
1560 /* We are looking for equal refs that might differ in structure
1561 such as a.b vs. MEM[&a + 4]. So we key off the ao_ref but
1562 make sure we can canonicalize the ref in the hashtable if
1563 non-operand_equal_p refs are found. For the lookup we mark
1564 the case we want strict equality with aor.max_size == -1. */
1565 ao_ref aor;
1566 ao_ref_init (&aor, *mem);
1567 ao_ref_base (&aor);
1568 ao_ref_alias_set (&aor);
1569 HOST_WIDE_INT offset, size, max_size;
1570 poly_int64 saved_maxsize = aor.max_size, mem_off;
1571 tree mem_base;
1572 bool ref_decomposed;
1573 if (aor.max_size_known_p ()
1574 && aor.offset.is_constant (&offset)
1575 && aor.size.is_constant (&size)
1576 && aor.max_size.is_constant (&max_size)
1577 && size == max_size
1578 && (size % BITS_PER_UNIT) == 0
1579 /* We're canonicalizing to a MEM where TYPE_SIZE specifies the
1580 size. Make sure this is consistent with the extraction. */
1581 && poly_int_tree_p (TYPE_SIZE (TREE_TYPE (*mem)))
1582 && known_eq (wi::to_poly_offset (TYPE_SIZE (TREE_TYPE (*mem))),
1583 aor.size)
1584 && (mem_base = get_addr_base_and_unit_offset (aor.ref, &mem_off)))
1586 ref_decomposed = true;
1587 tree base = ao_ref_base (&aor);
1588 poly_int64 moffset;
1589 HOST_WIDE_INT mcoffset;
1590 if (TREE_CODE (base) == MEM_REF
1591 && (mem_ref_offset (base) * BITS_PER_UNIT + offset).to_shwi (&moffset)
1592 && moffset.is_constant (&mcoffset))
1594 hash = iterative_hash_expr (TREE_OPERAND (base, 0), 0);
1595 hash = iterative_hash_host_wide_int (mcoffset, hash);
1597 else
1599 hash = iterative_hash_expr (base, 0);
1600 hash = iterative_hash_host_wide_int (offset, hash);
1602 hash = iterative_hash_host_wide_int (size, hash);
1604 else
1606 ref_decomposed = false;
1607 hash = iterative_hash_expr (aor.ref, 0);
1608 aor.max_size = -1;
1610 slot = memory_accesses.refs->find_slot_with_hash (&aor, hash, INSERT);
1611 aor.max_size = saved_maxsize;
1612 if (*slot)
1614 if (!(*slot)->ref_canonical
1615 && !operand_equal_p (*mem, (*slot)->mem.ref, 0))
1617 /* If we didn't yet canonicalize the hashtable ref (which
1618 we'll end up using for code insertion) and hit a second
1619 equal ref that is not structurally equivalent create
1620 a canonical ref which is a bare MEM_REF. */
1621 if (TREE_CODE (*mem) == MEM_REF
1622 || TREE_CODE (*mem) == TARGET_MEM_REF)
1624 (*slot)->mem.ref = *mem;
1625 (*slot)->mem.base_alias_set = ao_ref_base_alias_set (&aor);
1627 else
1629 tree ref_alias_type = reference_alias_ptr_type (*mem);
1630 unsigned int ref_align = get_object_alignment (*mem);
1631 tree ref_type = TREE_TYPE (*mem);
1632 tree tmp = build1 (ADDR_EXPR, ptr_type_node,
1633 unshare_expr (mem_base));
1634 if (TYPE_ALIGN (ref_type) != ref_align)
1635 ref_type = build_aligned_type (ref_type, ref_align);
1636 (*slot)->mem.ref
1637 = fold_build2 (MEM_REF, ref_type, tmp,
1638 build_int_cst (ref_alias_type, mem_off));
1639 if ((*slot)->mem.volatile_p)
1640 TREE_THIS_VOLATILE ((*slot)->mem.ref) = 1;
1641 gcc_checking_assert (TREE_CODE ((*slot)->mem.ref) == MEM_REF
1642 && is_gimple_mem_ref_addr
1643 (TREE_OPERAND ((*slot)->mem.ref,
1644 0)));
1645 (*slot)->mem.base_alias_set = (*slot)->mem.ref_alias_set;
1647 (*slot)->ref_canonical = true;
1649 ref = *slot;
1650 id = ref->id;
1652 else
1654 id = memory_accesses.refs_list.length ();
1655 ref = mem_ref_alloc (&aor, hash, id);
1656 ref->ref_decomposed = ref_decomposed;
1657 memory_accesses.refs_list.safe_push (ref);
1658 *slot = ref;
1660 if (dump_file && (dump_flags & TDF_DETAILS))
1662 fprintf (dump_file, "Memory reference %u: ", id);
1663 print_generic_expr (dump_file, ref->mem.ref, TDF_SLIM);
1664 fprintf (dump_file, "\n");
1668 record_mem_ref_loc (ref, stmt, mem);
1670 if (is_stored)
1672 bitmap_set_bit (&memory_accesses.refs_stored_in_loop[loop->num], ref->id);
1673 mark_ref_stored (ref, loop);
1675 /* A not simple memory op is also a read when it is a write. */
1676 if (!is_stored || id == UNANALYZABLE_MEM_ID
1677 || ref->mem.ref == error_mark_node)
1679 bitmap_set_bit (&memory_accesses.refs_loaded_in_loop[loop->num], ref->id);
1680 mark_ref_loaded (ref, loop);
1682 init_lim_data (stmt)->ref = ref->id;
1683 return;
1686 static unsigned *bb_loop_postorder;
1688 /* qsort sort function to sort blocks after their loop fathers postorder. */
1690 static int
1691 sort_bbs_in_loop_postorder_cmp (const void *bb1_, const void *bb2_,
1692 void *bb_loop_postorder_)
1694 unsigned *bb_loop_postorder = (unsigned *)bb_loop_postorder_;
1695 basic_block bb1 = *(const basic_block *)bb1_;
1696 basic_block bb2 = *(const basic_block *)bb2_;
1697 class loop *loop1 = bb1->loop_father;
1698 class loop *loop2 = bb2->loop_father;
1699 if (loop1->num == loop2->num)
1700 return bb1->index - bb2->index;
1701 return bb_loop_postorder[loop1->num] < bb_loop_postorder[loop2->num] ? -1 : 1;
1704 /* qsort sort function to sort ref locs after their loop fathers postorder. */
1706 static int
1707 sort_locs_in_loop_postorder_cmp (const void *loc1_, const void *loc2_,
1708 void *bb_loop_postorder_)
1710 unsigned *bb_loop_postorder = (unsigned *)bb_loop_postorder_;
1711 const mem_ref_loc *loc1 = (const mem_ref_loc *)loc1_;
1712 const mem_ref_loc *loc2 = (const mem_ref_loc *)loc2_;
1713 class loop *loop1 = gimple_bb (loc1->stmt)->loop_father;
1714 class loop *loop2 = gimple_bb (loc2->stmt)->loop_father;
1715 if (loop1->num == loop2->num)
1716 return 0;
1717 return bb_loop_postorder[loop1->num] < bb_loop_postorder[loop2->num] ? -1 : 1;
1720 /* Gathers memory references in loops. */
1722 static void
1723 analyze_memory_references (bool store_motion)
1725 gimple_stmt_iterator bsi;
1726 basic_block bb, *bbs;
1727 class loop *outer;
1728 unsigned i, n;
1730 /* Collect all basic-blocks in loops and sort them after their
1731 loops postorder. */
1732 i = 0;
1733 bbs = XNEWVEC (basic_block, n_basic_blocks_for_fn (cfun) - NUM_FIXED_BLOCKS);
1734 FOR_EACH_BB_FN (bb, cfun)
1735 if (bb->loop_father != current_loops->tree_root)
1736 bbs[i++] = bb;
1737 n = i;
1738 gcc_sort_r (bbs, n, sizeof (basic_block), sort_bbs_in_loop_postorder_cmp,
1739 bb_loop_postorder);
1741 /* Visit blocks in loop postorder and assign mem-ref IDs in that order.
1742 That results in better locality for all the bitmaps. It also
1743 automatically sorts the location list of gathered memory references
1744 after their loop postorder number allowing to binary-search it. */
1745 for (i = 0; i < n; ++i)
1747 basic_block bb = bbs[i];
1748 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1749 gather_mem_refs_stmt (bb->loop_father, gsi_stmt (bsi));
1752 /* Verify the list of gathered memory references is sorted after their
1753 loop postorder number. */
1754 if (flag_checking)
1756 im_mem_ref *ref;
1757 FOR_EACH_VEC_ELT (memory_accesses.refs_list, i, ref)
1758 for (unsigned j = 1; j < ref->accesses_in_loop.length (); ++j)
1759 gcc_assert (sort_locs_in_loop_postorder_cmp
1760 (&ref->accesses_in_loop[j-1], &ref->accesses_in_loop[j],
1761 bb_loop_postorder) <= 0);
1764 free (bbs);
1766 if (!store_motion)
1767 return;
1769 /* Propagate the information about accessed memory references up
1770 the loop hierarchy. */
1771 for (auto loop : loops_list (cfun, LI_FROM_INNERMOST))
1773 /* Finalize the overall touched references (including subloops). */
1774 bitmap_ior_into (&memory_accesses.all_refs_stored_in_loop[loop->num],
1775 &memory_accesses.refs_stored_in_loop[loop->num]);
1777 /* Propagate the information about accessed memory references up
1778 the loop hierarchy. */
1779 outer = loop_outer (loop);
1780 if (outer == current_loops->tree_root)
1781 continue;
1783 bitmap_ior_into (&memory_accesses.all_refs_stored_in_loop[outer->num],
1784 &memory_accesses.all_refs_stored_in_loop[loop->num]);
1788 /* Returns true if MEM1 and MEM2 may alias. TTAE_CACHE is used as a cache in
1789 tree_to_aff_combination_expand. */
1791 static bool
1792 mem_refs_may_alias_p (im_mem_ref *mem1, im_mem_ref *mem2,
1793 hash_map<tree, name_expansion *> **ttae_cache,
1794 bool tbaa_p)
1796 gcc_checking_assert (mem1->mem.ref != error_mark_node
1797 && mem2->mem.ref != error_mark_node);
1799 /* Perform BASE + OFFSET analysis -- if MEM1 and MEM2 are based on the same
1800 object and their offset differ in such a way that the locations cannot
1801 overlap, then they cannot alias. */
1802 poly_widest_int size1, size2;
1803 aff_tree off1, off2;
1805 /* Perform basic offset and type-based disambiguation. */
1806 if (!refs_may_alias_p_1 (&mem1->mem, &mem2->mem, tbaa_p))
1807 return false;
1809 /* The expansion of addresses may be a bit expensive, thus we only do
1810 the check at -O2 and higher optimization levels. */
1811 if (optimize < 2)
1812 return true;
1814 get_inner_reference_aff (mem1->mem.ref, &off1, &size1);
1815 get_inner_reference_aff (mem2->mem.ref, &off2, &size2);
1816 aff_combination_expand (&off1, ttae_cache);
1817 aff_combination_expand (&off2, ttae_cache);
1818 aff_combination_scale (&off1, -1);
1819 aff_combination_add (&off2, &off1);
1821 if (aff_comb_cannot_overlap_p (&off2, size1, size2))
1822 return false;
1824 return true;
1827 /* Compare function for bsearch searching for reference locations
1828 in a loop. */
1830 static int
1831 find_ref_loc_in_loop_cmp (const void *loop_, const void *loc_,
1832 void *bb_loop_postorder_)
1834 unsigned *bb_loop_postorder = (unsigned *)bb_loop_postorder_;
1835 class loop *loop = (class loop *)const_cast<void *>(loop_);
1836 mem_ref_loc *loc = (mem_ref_loc *)const_cast<void *>(loc_);
1837 class loop *loc_loop = gimple_bb (loc->stmt)->loop_father;
1838 if (loop->num == loc_loop->num
1839 || flow_loop_nested_p (loop, loc_loop))
1840 return 0;
1841 return (bb_loop_postorder[loop->num] < bb_loop_postorder[loc_loop->num]
1842 ? -1 : 1);
1845 /* Iterates over all locations of REF in LOOP and its subloops calling
1846 fn.operator() with the location as argument. When that operator
1847 returns true the iteration is stopped and true is returned.
1848 Otherwise false is returned. */
1850 template <typename FN>
1851 static bool
1852 for_all_locs_in_loop (class loop *loop, im_mem_ref *ref, FN fn)
1854 unsigned i;
1855 mem_ref_loc *loc;
1857 /* Search for the cluster of locs in the accesses_in_loop vector
1858 which is sorted after postorder index of the loop father. */
1859 loc = ref->accesses_in_loop.bsearch (loop, find_ref_loc_in_loop_cmp,
1860 bb_loop_postorder);
1861 if (!loc)
1862 return false;
1864 /* We have found one location inside loop or its sub-loops. Iterate
1865 both forward and backward to cover the whole cluster. */
1866 i = loc - ref->accesses_in_loop.address ();
1867 while (i > 0)
1869 --i;
1870 mem_ref_loc *l = &ref->accesses_in_loop[i];
1871 if (!flow_bb_inside_loop_p (loop, gimple_bb (l->stmt)))
1872 break;
1873 if (fn (l))
1874 return true;
1876 for (i = loc - ref->accesses_in_loop.address ();
1877 i < ref->accesses_in_loop.length (); ++i)
1879 mem_ref_loc *l = &ref->accesses_in_loop[i];
1880 if (!flow_bb_inside_loop_p (loop, gimple_bb (l->stmt)))
1881 break;
1882 if (fn (l))
1883 return true;
1886 return false;
1889 /* Rewrites location LOC by TMP_VAR. */
1891 class rewrite_mem_ref_loc
1893 public:
1894 rewrite_mem_ref_loc (tree tmp_var_) : tmp_var (tmp_var_) {}
1895 bool operator () (mem_ref_loc *loc);
1896 tree tmp_var;
1899 bool
1900 rewrite_mem_ref_loc::operator () (mem_ref_loc *loc)
1902 *loc->ref = tmp_var;
1903 update_stmt (loc->stmt);
1904 return false;
1907 /* Rewrites all references to REF in LOOP by variable TMP_VAR. */
1909 static void
1910 rewrite_mem_refs (class loop *loop, im_mem_ref *ref, tree tmp_var)
1912 for_all_locs_in_loop (loop, ref, rewrite_mem_ref_loc (tmp_var));
1915 /* Stores the first reference location in LOCP. */
1917 class first_mem_ref_loc_1
1919 public:
1920 first_mem_ref_loc_1 (mem_ref_loc **locp_) : locp (locp_) {}
1921 bool operator () (mem_ref_loc *loc);
1922 mem_ref_loc **locp;
1925 bool
1926 first_mem_ref_loc_1::operator () (mem_ref_loc *loc)
1928 *locp = loc;
1929 return true;
1932 /* Returns the first reference location to REF in LOOP. */
1934 static mem_ref_loc *
1935 first_mem_ref_loc (class loop *loop, im_mem_ref *ref)
1937 mem_ref_loc *locp = NULL;
1938 for_all_locs_in_loop (loop, ref, first_mem_ref_loc_1 (&locp));
1939 return locp;
1942 /* Helper function for execute_sm. Emit code to store TMP_VAR into
1943 MEM along edge EX.
1945 The store is only done if MEM has changed. We do this so no
1946 changes to MEM occur on code paths that did not originally store
1947 into it.
1949 The common case for execute_sm will transform:
1951 for (...) {
1952 if (foo)
1953 stuff;
1954 else
1955 MEM = TMP_VAR;
1958 into:
1960 lsm = MEM;
1961 for (...) {
1962 if (foo)
1963 stuff;
1964 else
1965 lsm = TMP_VAR;
1967 MEM = lsm;
1969 This function will generate:
1971 lsm = MEM;
1973 lsm_flag = false;
1975 for (...) {
1976 if (foo)
1977 stuff;
1978 else {
1979 lsm = TMP_VAR;
1980 lsm_flag = true;
1983 if (lsm_flag) <--
1984 MEM = lsm; <-- (X)
1986 In case MEM and TMP_VAR are NULL the function will return the then
1987 block so the caller can insert (X) and other related stmts.
1990 static basic_block
1991 execute_sm_if_changed (edge ex, tree mem, tree tmp_var, tree flag,
1992 edge preheader, hash_set <basic_block> *flag_bbs,
1993 edge &append_cond_position, edge &last_cond_fallthru)
1995 basic_block new_bb, then_bb, old_dest;
1996 bool loop_has_only_one_exit;
1997 edge then_old_edge;
1998 gimple_stmt_iterator gsi;
1999 gimple *stmt;
2000 bool irr = ex->flags & EDGE_IRREDUCIBLE_LOOP;
2002 profile_count count_sum = profile_count::zero ();
2003 int nbbs = 0, ncount = 0;
2004 profile_probability flag_probability = profile_probability::uninitialized ();
2006 /* Flag is set in FLAG_BBS. Determine probability that flag will be true
2007 at loop exit.
2009 This code may look fancy, but it cannot update profile very realistically
2010 because we do not know the probability that flag will be true at given
2011 loop exit.
2013 We look for two interesting extremes
2014 - when exit is dominated by block setting the flag, we know it will
2015 always be true. This is a common case.
2016 - when all blocks setting the flag have very low frequency we know
2017 it will likely be false.
2018 In all other cases we default to 2/3 for flag being true. */
2020 for (hash_set<basic_block>::iterator it = flag_bbs->begin ();
2021 it != flag_bbs->end (); ++it)
2023 if ((*it)->count.initialized_p ())
2024 count_sum += (*it)->count, ncount ++;
2025 if (dominated_by_p (CDI_DOMINATORS, ex->src, *it))
2026 flag_probability = profile_probability::always ();
2027 nbbs++;
2030 profile_probability cap = profile_probability::always ().apply_scale (2, 3);
2032 if (flag_probability.initialized_p ())
2034 else if (ncount == nbbs
2035 && preheader->count () >= count_sum && preheader->count ().nonzero_p ())
2037 flag_probability = count_sum.probability_in (preheader->count ());
2038 if (flag_probability > cap)
2039 flag_probability = cap;
2042 if (!flag_probability.initialized_p ())
2043 flag_probability = cap;
2045 /* ?? Insert store after previous store if applicable. See note
2046 below. */
2047 if (append_cond_position)
2048 ex = append_cond_position;
2050 loop_has_only_one_exit = single_pred_p (ex->dest);
2052 if (loop_has_only_one_exit)
2053 ex = split_block_after_labels (ex->dest);
2054 else
2056 for (gphi_iterator gpi = gsi_start_phis (ex->dest);
2057 !gsi_end_p (gpi); gsi_next (&gpi))
2059 gphi *phi = gpi.phi ();
2060 if (virtual_operand_p (gimple_phi_result (phi)))
2061 continue;
2063 /* When the destination has a non-virtual PHI node with multiple
2064 predecessors make sure we preserve the PHI structure by
2065 forcing a forwarder block so that hoisting of that PHI will
2066 still work. */
2067 split_edge (ex);
2068 break;
2072 old_dest = ex->dest;
2073 new_bb = split_edge (ex);
2074 then_bb = create_empty_bb (new_bb);
2075 then_bb->count = new_bb->count.apply_probability (flag_probability);
2076 if (irr)
2077 then_bb->flags = BB_IRREDUCIBLE_LOOP;
2078 add_bb_to_loop (then_bb, new_bb->loop_father);
2080 gsi = gsi_start_bb (new_bb);
2081 stmt = gimple_build_cond (NE_EXPR, flag, boolean_false_node,
2082 NULL_TREE, NULL_TREE);
2083 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2085 /* Insert actual store. */
2086 if (mem)
2088 gsi = gsi_start_bb (then_bb);
2089 stmt = gimple_build_assign (unshare_expr (mem), tmp_var);
2090 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2093 edge e1 = single_succ_edge (new_bb);
2094 edge e2 = make_edge (new_bb, then_bb,
2095 EDGE_TRUE_VALUE | (irr ? EDGE_IRREDUCIBLE_LOOP : 0));
2096 e2->probability = flag_probability;
2098 e1->flags |= EDGE_FALSE_VALUE | (irr ? EDGE_IRREDUCIBLE_LOOP : 0);
2099 e1->flags &= ~EDGE_FALLTHRU;
2101 e1->probability = flag_probability.invert ();
2103 then_old_edge = make_single_succ_edge (then_bb, old_dest,
2104 EDGE_FALLTHRU | (irr ? EDGE_IRREDUCIBLE_LOOP : 0));
2106 set_immediate_dominator (CDI_DOMINATORS, then_bb, new_bb);
2108 if (append_cond_position)
2110 basic_block prevbb = last_cond_fallthru->src;
2111 redirect_edge_succ (last_cond_fallthru, new_bb);
2112 set_immediate_dominator (CDI_DOMINATORS, new_bb, prevbb);
2113 set_immediate_dominator (CDI_DOMINATORS, old_dest,
2114 recompute_dominator (CDI_DOMINATORS, old_dest));
2117 /* ?? Because stores may alias, they must happen in the exact
2118 sequence they originally happened. Save the position right after
2119 the (_lsm) store we just created so we can continue appending after
2120 it and maintain the original order. */
2121 append_cond_position = then_old_edge;
2122 last_cond_fallthru = find_edge (new_bb, old_dest);
2124 if (!loop_has_only_one_exit)
2125 for (gphi_iterator gpi = gsi_start_phis (old_dest);
2126 !gsi_end_p (gpi); gsi_next (&gpi))
2128 gphi *phi = gpi.phi ();
2129 unsigned i;
2131 for (i = 0; i < gimple_phi_num_args (phi); i++)
2132 if (gimple_phi_arg_edge (phi, i)->src == new_bb)
2134 tree arg = gimple_phi_arg_def (phi, i);
2135 add_phi_arg (phi, arg, then_old_edge, UNKNOWN_LOCATION);
2136 update_stmt (phi);
2140 return then_bb;
2143 /* When REF is set on the location, set flag indicating the store. */
2145 class sm_set_flag_if_changed
2147 public:
2148 sm_set_flag_if_changed (tree flag_, hash_set <basic_block> *bbs_)
2149 : flag (flag_), bbs (bbs_) {}
2150 bool operator () (mem_ref_loc *loc);
2151 tree flag;
2152 hash_set <basic_block> *bbs;
2155 bool
2156 sm_set_flag_if_changed::operator () (mem_ref_loc *loc)
2158 /* Only set the flag for writes. */
2159 if (is_gimple_assign (loc->stmt)
2160 && gimple_assign_lhs_ptr (loc->stmt) == loc->ref)
2162 gimple_stmt_iterator gsi = gsi_for_stmt (loc->stmt);
2163 gimple *stmt = gimple_build_assign (flag, boolean_true_node);
2164 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2165 bbs->add (gimple_bb (stmt));
2167 return false;
2170 /* Helper function for execute_sm. On every location where REF is
2171 set, set an appropriate flag indicating the store. */
2173 static tree
2174 execute_sm_if_changed_flag_set (class loop *loop, im_mem_ref *ref,
2175 hash_set <basic_block> *bbs)
2177 tree flag;
2178 char *str = get_lsm_tmp_name (ref->mem.ref, ~0, "_flag");
2179 flag = create_tmp_reg (boolean_type_node, str);
2180 for_all_locs_in_loop (loop, ref, sm_set_flag_if_changed (flag, bbs));
2181 return flag;
2184 struct sm_aux
2186 tree tmp_var;
2187 tree store_flag;
2188 hash_set <basic_block> flag_bbs;
2191 /* Executes store motion of memory reference REF from LOOP.
2192 Exits from the LOOP are stored in EXITS. The initialization of the
2193 temporary variable is put to the preheader of the loop, and assignments
2194 to the reference from the temporary variable are emitted to exits. */
2196 static void
2197 execute_sm (class loop *loop, im_mem_ref *ref,
2198 hash_map<im_mem_ref *, sm_aux *> &aux_map, bool maybe_mt,
2199 bool use_other_flag_var)
2201 gassign *load;
2202 struct fmt_data fmt_data;
2203 struct lim_aux_data *lim_data;
2204 bool multi_threaded_model_p = false;
2205 gimple_stmt_iterator gsi;
2206 sm_aux *aux = new sm_aux;
2208 if (dump_file && (dump_flags & TDF_DETAILS))
2210 fprintf (dump_file, "Executing store motion of ");
2211 print_generic_expr (dump_file, ref->mem.ref);
2212 fprintf (dump_file, " from loop %d\n", loop->num);
2215 aux->tmp_var = create_tmp_reg (TREE_TYPE (ref->mem.ref),
2216 get_lsm_tmp_name (ref->mem.ref, ~0));
2218 fmt_data.loop = loop;
2219 fmt_data.orig_loop = loop;
2220 for_each_index (&ref->mem.ref, force_move_till, &fmt_data);
2222 bool always_stored = ref_always_accessed_p (loop, ref, true);
2223 if (maybe_mt
2224 && (bb_in_transaction (loop_preheader_edge (loop)->src)
2225 || (! flag_store_data_races && ! always_stored)))
2226 multi_threaded_model_p = true;
2228 if (multi_threaded_model_p && !use_other_flag_var)
2229 aux->store_flag
2230 = execute_sm_if_changed_flag_set (loop, ref, &aux->flag_bbs);
2231 else
2232 aux->store_flag = NULL_TREE;
2234 /* Remember variable setup. */
2235 aux_map.put (ref, aux);
2237 rewrite_mem_refs (loop, ref, aux->tmp_var);
2239 /* Emit the load code on a random exit edge or into the latch if
2240 the loop does not exit, so that we are sure it will be processed
2241 by move_computations after all dependencies. */
2242 gsi = gsi_for_stmt (first_mem_ref_loc (loop, ref)->stmt);
2244 /* Avoid doing a load if there was no load of the ref in the loop.
2245 Esp. when the ref is not always stored we cannot optimize it
2246 away later. But when it is not always stored we must use a conditional
2247 store then. */
2248 if ((!always_stored && !multi_threaded_model_p)
2249 || (ref->loaded && bitmap_bit_p (ref->loaded, loop->num)))
2250 load = gimple_build_assign (aux->tmp_var, unshare_expr (ref->mem.ref));
2251 else
2253 /* If not emitting a load mark the uninitialized state on the
2254 loop entry as not to be warned for. */
2255 tree uninit = create_tmp_reg (TREE_TYPE (aux->tmp_var));
2256 suppress_warning (uninit, OPT_Wuninitialized);
2257 load = gimple_build_assign (aux->tmp_var, uninit);
2259 lim_data = init_lim_data (load);
2260 lim_data->max_loop = loop;
2261 lim_data->tgt_loop = loop;
2262 gsi_insert_before (&gsi, load, GSI_SAME_STMT);
2264 if (aux->store_flag)
2266 load = gimple_build_assign (aux->store_flag, boolean_false_node);
2267 lim_data = init_lim_data (load);
2268 lim_data->max_loop = loop;
2269 lim_data->tgt_loop = loop;
2270 gsi_insert_before (&gsi, load, GSI_SAME_STMT);
2274 /* sm_ord is used for ordinary stores we can retain order with respect
2275 to other stores
2276 sm_unord is used for conditional executed stores which need to be
2277 able to execute in arbitrary order with respect to other stores
2278 sm_other is used for stores we do not try to apply store motion to. */
2279 enum sm_kind { sm_ord, sm_unord, sm_other };
2280 struct seq_entry
2282 seq_entry () {}
2283 seq_entry (unsigned f, sm_kind k, tree fr = NULL)
2284 : first (f), second (k), from (fr) {}
2285 unsigned first;
2286 sm_kind second;
2287 tree from;
2290 static void
2291 execute_sm_exit (class loop *loop, edge ex, vec<seq_entry> &seq,
2292 hash_map<im_mem_ref *, sm_aux *> &aux_map, sm_kind kind,
2293 edge &append_cond_position, edge &last_cond_fallthru)
2295 /* Sink the stores to exit from the loop. */
2296 for (unsigned i = seq.length (); i > 0; --i)
2298 im_mem_ref *ref = memory_accesses.refs_list[seq[i-1].first];
2299 if (seq[i-1].second == sm_other)
2301 gcc_assert (kind == sm_ord && seq[i-1].from != NULL_TREE);
2302 if (dump_file && (dump_flags & TDF_DETAILS))
2304 fprintf (dump_file, "Re-issueing dependent store of ");
2305 print_generic_expr (dump_file, ref->mem.ref);
2306 fprintf (dump_file, " from loop %d on exit %d -> %d\n",
2307 loop->num, ex->src->index, ex->dest->index);
2309 gassign *store = gimple_build_assign (unshare_expr (ref->mem.ref),
2310 seq[i-1].from);
2311 gsi_insert_on_edge (ex, store);
2313 else
2315 sm_aux *aux = *aux_map.get (ref);
2316 if (!aux->store_flag || kind == sm_ord)
2318 gassign *store;
2319 store = gimple_build_assign (unshare_expr (ref->mem.ref),
2320 aux->tmp_var);
2321 gsi_insert_on_edge (ex, store);
2323 else
2324 execute_sm_if_changed (ex, ref->mem.ref, aux->tmp_var,
2325 aux->store_flag,
2326 loop_preheader_edge (loop), &aux->flag_bbs,
2327 append_cond_position, last_cond_fallthru);
2332 /* Push the SM candidate at index PTR in the sequence SEQ down until
2333 we hit the next SM candidate. Return true if that went OK and
2334 false if we could not disambiguate agains another unrelated ref.
2335 Update *AT to the index where the candidate now resides. */
2337 static bool
2338 sm_seq_push_down (vec<seq_entry> &seq, unsigned ptr, unsigned *at)
2340 *at = ptr;
2341 for (; ptr > 0; --ptr)
2343 seq_entry &new_cand = seq[ptr];
2344 seq_entry &against = seq[ptr-1];
2345 if (against.second == sm_ord
2346 || (against.second == sm_other && against.from != NULL_TREE))
2347 /* Found the tail of the sequence. */
2348 break;
2349 /* We may not ignore self-dependences here. */
2350 if (new_cand.first == against.first
2351 || !refs_independent_p (memory_accesses.refs_list[new_cand.first],
2352 memory_accesses.refs_list[against.first],
2353 false))
2354 /* ??? Prune new_cand from the list of refs to apply SM to. */
2355 return false;
2356 std::swap (new_cand, against);
2357 *at = ptr - 1;
2359 return true;
2362 /* Computes the sequence of stores from candidates in REFS_NOT_IN_SEQ to SEQ
2363 walking backwards from VDEF (or the end of BB if VDEF is NULL). */
2365 static int
2366 sm_seq_valid_bb (class loop *loop, basic_block bb, tree vdef,
2367 vec<seq_entry> &seq, bitmap refs_not_in_seq,
2368 bitmap refs_not_supported, bool forked,
2369 bitmap fully_visited)
2371 if (!vdef)
2372 for (gimple_stmt_iterator gsi = gsi_last_bb (bb); !gsi_end_p (gsi);
2373 gsi_prev (&gsi))
2375 vdef = gimple_vdef (gsi_stmt (gsi));
2376 if (vdef)
2377 break;
2379 if (!vdef)
2381 gphi *vphi = get_virtual_phi (bb);
2382 if (vphi)
2383 vdef = gimple_phi_result (vphi);
2385 if (!vdef)
2387 if (single_pred_p (bb))
2388 /* This handles the perfect nest case. */
2389 return sm_seq_valid_bb (loop, single_pred (bb), vdef,
2390 seq, refs_not_in_seq, refs_not_supported,
2391 forked, fully_visited);
2392 return 0;
2396 gimple *def = SSA_NAME_DEF_STMT (vdef);
2397 if (gimple_bb (def) != bb)
2399 /* If we forked by processing a PHI do not allow our walk to
2400 merge again until we handle that robustly. */
2401 if (forked)
2403 /* Mark refs_not_in_seq as unsupported. */
2404 bitmap_ior_into (refs_not_supported, refs_not_in_seq);
2405 return 1;
2407 /* Otherwise it doesn't really matter if we end up in different
2408 BBs. */
2409 bb = gimple_bb (def);
2411 if (gphi *phi = dyn_cast <gphi *> (def))
2413 /* Handle CFG merges. Until we handle forks (gimple_bb (def) != bb)
2414 this is still linear.
2415 Eventually we want to cache intermediate results per BB
2416 (but we can't easily cache for different exits?). */
2417 /* Stop at PHIs with possible backedges. */
2418 if (bb == bb->loop_father->header
2419 || bb->flags & BB_IRREDUCIBLE_LOOP)
2421 /* Mark refs_not_in_seq as unsupported. */
2422 bitmap_ior_into (refs_not_supported, refs_not_in_seq);
2423 return 1;
2425 if (gimple_phi_num_args (phi) == 1)
2426 return sm_seq_valid_bb (loop, gimple_phi_arg_edge (phi, 0)->src,
2427 gimple_phi_arg_def (phi, 0), seq,
2428 refs_not_in_seq, refs_not_supported,
2429 false, fully_visited);
2430 if (bitmap_bit_p (fully_visited,
2431 SSA_NAME_VERSION (gimple_phi_result (phi))))
2432 return 1;
2433 auto_vec<seq_entry> first_edge_seq;
2434 auto_bitmap tem_refs_not_in_seq (&lim_bitmap_obstack);
2435 int eret;
2436 bitmap_copy (tem_refs_not_in_seq, refs_not_in_seq);
2437 eret = sm_seq_valid_bb (loop, gimple_phi_arg_edge (phi, 0)->src,
2438 gimple_phi_arg_def (phi, 0),
2439 first_edge_seq,
2440 tem_refs_not_in_seq, refs_not_supported,
2441 true, fully_visited);
2442 if (eret != 1)
2443 return -1;
2444 /* Simplify our lives by pruning the sequence of !sm_ord. */
2445 while (!first_edge_seq.is_empty ()
2446 && first_edge_seq.last ().second != sm_ord)
2447 first_edge_seq.pop ();
2448 for (unsigned int i = 1; i < gimple_phi_num_args (phi); ++i)
2450 tree vuse = gimple_phi_arg_def (phi, i);
2451 edge e = gimple_phi_arg_edge (phi, i);
2452 auto_vec<seq_entry> edge_seq;
2453 bitmap_and_compl (tem_refs_not_in_seq,
2454 refs_not_in_seq, refs_not_supported);
2455 /* If we've marked all refs we search for as unsupported
2456 we can stop processing and use the sequence as before
2457 the PHI. */
2458 if (bitmap_empty_p (tem_refs_not_in_seq))
2459 return 1;
2460 eret = sm_seq_valid_bb (loop, e->src, vuse, edge_seq,
2461 tem_refs_not_in_seq, refs_not_supported,
2462 true, fully_visited);
2463 if (eret != 1)
2464 return -1;
2465 /* Simplify our lives by pruning the sequence of !sm_ord. */
2466 while (!edge_seq.is_empty ()
2467 && edge_seq.last ().second != sm_ord)
2468 edge_seq.pop ();
2469 unsigned min_len = MIN(first_edge_seq.length (),
2470 edge_seq.length ());
2471 /* Incrementally merge seqs into first_edge_seq. */
2472 int first_uneq = -1;
2473 auto_vec<seq_entry, 2> extra_refs;
2474 for (unsigned int i = 0; i < min_len; ++i)
2476 /* ??? We can more intelligently merge when we face different
2477 order by additional sinking operations in one sequence.
2478 For now we simply mark them as to be processed by the
2479 not order-preserving SM code. */
2480 if (first_edge_seq[i].first != edge_seq[i].first)
2482 if (first_edge_seq[i].second == sm_ord)
2483 bitmap_set_bit (refs_not_supported,
2484 first_edge_seq[i].first);
2485 if (edge_seq[i].second == sm_ord)
2486 bitmap_set_bit (refs_not_supported, edge_seq[i].first);
2487 first_edge_seq[i].second = sm_other;
2488 first_edge_seq[i].from = NULL_TREE;
2489 /* Record the dropped refs for later processing. */
2490 if (first_uneq == -1)
2491 first_uneq = i;
2492 extra_refs.safe_push (seq_entry (edge_seq[i].first,
2493 sm_other, NULL_TREE));
2495 /* sm_other prevails. */
2496 else if (first_edge_seq[i].second != edge_seq[i].second)
2498 /* Make sure the ref is marked as not supported. */
2499 bitmap_set_bit (refs_not_supported,
2500 first_edge_seq[i].first);
2501 first_edge_seq[i].second = sm_other;
2502 first_edge_seq[i].from = NULL_TREE;
2504 else if (first_edge_seq[i].second == sm_other
2505 && first_edge_seq[i].from != NULL_TREE
2506 && (edge_seq[i].from == NULL_TREE
2507 || !operand_equal_p (first_edge_seq[i].from,
2508 edge_seq[i].from, 0)))
2509 first_edge_seq[i].from = NULL_TREE;
2511 /* Any excess elements become sm_other since they are now
2512 coonditionally executed. */
2513 if (first_edge_seq.length () > edge_seq.length ())
2515 for (unsigned i = edge_seq.length ();
2516 i < first_edge_seq.length (); ++i)
2518 if (first_edge_seq[i].second == sm_ord)
2519 bitmap_set_bit (refs_not_supported,
2520 first_edge_seq[i].first);
2521 first_edge_seq[i].second = sm_other;
2524 else if (edge_seq.length () > first_edge_seq.length ())
2526 if (first_uneq == -1)
2527 first_uneq = first_edge_seq.length ();
2528 for (unsigned i = first_edge_seq.length ();
2529 i < edge_seq.length (); ++i)
2531 if (edge_seq[i].second == sm_ord)
2532 bitmap_set_bit (refs_not_supported, edge_seq[i].first);
2533 extra_refs.safe_push (seq_entry (edge_seq[i].first,
2534 sm_other, NULL_TREE));
2537 /* Put unmerged refs at first_uneq to force dependence checking
2538 on them. */
2539 if (first_uneq != -1)
2541 /* Missing ordered_splice_at. */
2542 if ((unsigned)first_uneq == first_edge_seq.length ())
2543 first_edge_seq.safe_splice (extra_refs);
2544 else
2546 unsigned fes_length = first_edge_seq.length ();
2547 first_edge_seq.safe_grow (fes_length
2548 + extra_refs.length ());
2549 memmove (&first_edge_seq[first_uneq + extra_refs.length ()],
2550 &first_edge_seq[first_uneq],
2551 (fes_length - first_uneq) * sizeof (seq_entry));
2552 memcpy (&first_edge_seq[first_uneq],
2553 extra_refs.address (),
2554 extra_refs.length () * sizeof (seq_entry));
2558 /* Use the sequence from the first edge and push SMs down. */
2559 for (unsigned i = 0; i < first_edge_seq.length (); ++i)
2561 unsigned id = first_edge_seq[i].first;
2562 seq.safe_push (first_edge_seq[i]);
2563 unsigned new_idx;
2564 if ((first_edge_seq[i].second == sm_ord
2565 || (first_edge_seq[i].second == sm_other
2566 && first_edge_seq[i].from != NULL_TREE))
2567 && !sm_seq_push_down (seq, seq.length () - 1, &new_idx))
2569 if (first_edge_seq[i].second == sm_ord)
2570 bitmap_set_bit (refs_not_supported, id);
2571 /* Mark it sm_other. */
2572 seq[new_idx].second = sm_other;
2573 seq[new_idx].from = NULL_TREE;
2576 bitmap_set_bit (fully_visited,
2577 SSA_NAME_VERSION (gimple_phi_result (phi)));
2578 return 1;
2580 lim_aux_data *data = get_lim_data (def);
2581 gcc_assert (data);
2582 if (data->ref == UNANALYZABLE_MEM_ID)
2583 return -1;
2584 /* Stop at memory references which we can't move. */
2585 else if (memory_accesses.refs_list[data->ref]->mem.ref == error_mark_node)
2587 /* Mark refs_not_in_seq as unsupported. */
2588 bitmap_ior_into (refs_not_supported, refs_not_in_seq);
2589 return 1;
2591 /* One of the stores we want to apply SM to and we've not yet seen. */
2592 else if (bitmap_clear_bit (refs_not_in_seq, data->ref))
2594 seq.safe_push (seq_entry (data->ref, sm_ord));
2596 /* 1) push it down the queue until a SMed
2597 and not ignored ref is reached, skipping all not SMed refs
2598 and ignored refs via non-TBAA disambiguation. */
2599 unsigned new_idx;
2600 if (!sm_seq_push_down (seq, seq.length () - 1, &new_idx)
2601 /* If that fails but we did not fork yet continue, we'll see
2602 to re-materialize all of the stores in the sequence then.
2603 Further stores will only be pushed up to this one. */
2604 && forked)
2606 bitmap_set_bit (refs_not_supported, data->ref);
2607 /* Mark it sm_other. */
2608 seq[new_idx].second = sm_other;
2611 /* 2) check whether we've seen all refs we want to SM and if so
2612 declare success for the active exit */
2613 if (bitmap_empty_p (refs_not_in_seq))
2614 return 1;
2616 else
2617 /* Another store not part of the final sequence. Simply push it. */
2618 seq.safe_push (seq_entry (data->ref, sm_other,
2619 gimple_assign_rhs1 (def)));
2621 vdef = gimple_vuse (def);
2623 while (1);
2626 /* Hoists memory references MEM_REFS out of LOOP. EXITS is the list of exit
2627 edges of the LOOP. */
2629 static void
2630 hoist_memory_references (class loop *loop, bitmap mem_refs,
2631 const vec<edge> &exits)
2633 im_mem_ref *ref;
2634 unsigned i;
2635 bitmap_iterator bi;
2637 /* There's a special case we can use ordered re-materialization for
2638 conditionally excuted stores which is when all stores in the loop
2639 happen in the same basic-block. In that case we know we'll reach
2640 all stores and thus can simply process that BB and emit a single
2641 conditional block of ordered materializations. See PR102436. */
2642 basic_block single_store_bb = NULL;
2643 EXECUTE_IF_SET_IN_BITMAP (&memory_accesses.all_refs_stored_in_loop[loop->num],
2644 0, i, bi)
2646 bool fail = false;
2647 ref = memory_accesses.refs_list[i];
2648 for (auto loc : ref->accesses_in_loop)
2649 if (!gimple_vdef (loc.stmt))
2651 else if (!single_store_bb)
2653 single_store_bb = gimple_bb (loc.stmt);
2654 bool conditional = false;
2655 for (edge e : exits)
2656 if (!dominated_by_p (CDI_DOMINATORS, e->src, single_store_bb))
2658 /* Conditional as seen from e. */
2659 conditional = true;
2660 break;
2662 if (!conditional)
2664 fail = true;
2665 break;
2668 else if (single_store_bb != gimple_bb (loc.stmt))
2670 fail = true;
2671 break;
2673 if (fail)
2675 single_store_bb = NULL;
2676 break;
2679 if (single_store_bb)
2681 /* Analyze the single block with stores. */
2682 auto_bitmap fully_visited;
2683 auto_bitmap refs_not_supported;
2684 auto_bitmap refs_not_in_seq;
2685 auto_vec<seq_entry> seq;
2686 bitmap_copy (refs_not_in_seq, mem_refs);
2687 int res = sm_seq_valid_bb (loop, single_store_bb, NULL_TREE,
2688 seq, refs_not_in_seq, refs_not_supported,
2689 false, fully_visited);
2690 if (res != 1)
2692 /* Unhandled refs can still fail this. */
2693 bitmap_clear (mem_refs);
2694 return;
2697 /* We cannot handle sm_other since we neither remember the
2698 stored location nor the value at the point we execute them. */
2699 for (unsigned i = 0; i < seq.length (); ++i)
2701 unsigned new_i;
2702 if (seq[i].second == sm_other
2703 && seq[i].from != NULL_TREE)
2704 seq[i].from = NULL_TREE;
2705 else if ((seq[i].second == sm_ord
2706 || (seq[i].second == sm_other
2707 && seq[i].from != NULL_TREE))
2708 && !sm_seq_push_down (seq, i, &new_i))
2710 bitmap_set_bit (refs_not_supported, seq[new_i].first);
2711 seq[new_i].second = sm_other;
2712 seq[new_i].from = NULL_TREE;
2715 bitmap_and_compl_into (mem_refs, refs_not_supported);
2716 if (bitmap_empty_p (mem_refs))
2717 return;
2719 /* Prune seq. */
2720 while (seq.last ().second == sm_other
2721 && seq.last ().from == NULL_TREE)
2722 seq.pop ();
2724 hash_map<im_mem_ref *, sm_aux *> aux_map;
2726 /* Execute SM but delay the store materialization for ordered
2727 sequences on exit. */
2728 bool first_p = true;
2729 EXECUTE_IF_SET_IN_BITMAP (mem_refs, 0, i, bi)
2731 ref = memory_accesses.refs_list[i];
2732 execute_sm (loop, ref, aux_map, true, !first_p);
2733 first_p = false;
2736 /* Get at the single flag variable we eventually produced. */
2737 im_mem_ref *ref
2738 = memory_accesses.refs_list[bitmap_first_set_bit (mem_refs)];
2739 sm_aux *aux = *aux_map.get (ref);
2741 /* Materialize ordered store sequences on exits. */
2742 edge e;
2743 FOR_EACH_VEC_ELT (exits, i, e)
2745 edge append_cond_position = NULL;
2746 edge last_cond_fallthru = NULL;
2747 edge insert_e = e;
2748 /* Construct the single flag variable control flow and insert
2749 the ordered seq of stores in the then block. With
2750 -fstore-data-races we can do the stores unconditionally. */
2751 if (aux->store_flag)
2752 insert_e
2753 = single_pred_edge
2754 (execute_sm_if_changed (e, NULL_TREE, NULL_TREE,
2755 aux->store_flag,
2756 loop_preheader_edge (loop),
2757 &aux->flag_bbs, append_cond_position,
2758 last_cond_fallthru));
2759 execute_sm_exit (loop, insert_e, seq, aux_map, sm_ord,
2760 append_cond_position, last_cond_fallthru);
2761 gsi_commit_one_edge_insert (insert_e, NULL);
2764 for (hash_map<im_mem_ref *, sm_aux *>::iterator iter = aux_map.begin ();
2765 iter != aux_map.end (); ++iter)
2766 delete (*iter).second;
2768 return;
2771 /* To address PR57359 before actually applying store-motion check
2772 the candidates found for validity with regards to reordering
2773 relative to other stores which we until here disambiguated using
2774 TBAA which isn't valid.
2775 What matters is the order of the last stores to the mem_refs
2776 with respect to the other stores of the loop at the point of the
2777 loop exits. */
2779 /* For each exit compute the store order, pruning from mem_refs
2780 on the fly. */
2781 /* The complexity of this is at least
2782 O(number of exits * number of SM refs) but more approaching
2783 O(number of exits * number of SM refs * number of stores). */
2784 /* ??? Somehow do this in a single sweep over the loop body. */
2785 auto_vec<std::pair<edge, vec<seq_entry> > > sms;
2786 auto_bitmap refs_not_supported (&lim_bitmap_obstack);
2787 edge e;
2788 FOR_EACH_VEC_ELT (exits, i, e)
2790 vec<seq_entry> seq;
2791 seq.create (4);
2792 auto_bitmap refs_not_in_seq (&lim_bitmap_obstack);
2793 bitmap_and_compl (refs_not_in_seq, mem_refs, refs_not_supported);
2794 if (bitmap_empty_p (refs_not_in_seq))
2796 seq.release ();
2797 break;
2799 auto_bitmap fully_visited;
2800 int res = sm_seq_valid_bb (loop, e->src, NULL_TREE,
2801 seq, refs_not_in_seq,
2802 refs_not_supported, false,
2803 fully_visited);
2804 if (res != 1)
2806 bitmap_copy (refs_not_supported, mem_refs);
2807 seq.release ();
2808 break;
2810 sms.safe_push (std::make_pair (e, seq));
2813 /* Prune pruned mem_refs from earlier processed exits. */
2814 bool changed = !bitmap_empty_p (refs_not_supported);
2815 while (changed)
2817 changed = false;
2818 std::pair<edge, vec<seq_entry> > *seq;
2819 FOR_EACH_VEC_ELT (sms, i, seq)
2821 bool need_to_push = false;
2822 for (unsigned i = 0; i < seq->second.length (); ++i)
2824 sm_kind kind = seq->second[i].second;
2825 if (kind == sm_other && seq->second[i].from == NULL_TREE)
2826 break;
2827 unsigned id = seq->second[i].first;
2828 unsigned new_idx;
2829 if (kind == sm_ord
2830 && bitmap_bit_p (refs_not_supported, id))
2832 seq->second[i].second = sm_other;
2833 gcc_assert (seq->second[i].from == NULL_TREE);
2834 need_to_push = true;
2836 else if (need_to_push
2837 && !sm_seq_push_down (seq->second, i, &new_idx))
2839 /* We need to push down both sm_ord and sm_other
2840 but for the latter we need to disqualify all
2841 following refs. */
2842 if (kind == sm_ord)
2844 if (bitmap_set_bit (refs_not_supported, id))
2845 changed = true;
2846 seq->second[new_idx].second = sm_other;
2848 else
2850 for (unsigned j = seq->second.length () - 1;
2851 j > new_idx; --j)
2852 if (seq->second[j].second == sm_ord
2853 && bitmap_set_bit (refs_not_supported,
2854 seq->second[j].first))
2855 changed = true;
2856 seq->second.truncate (new_idx);
2857 break;
2863 std::pair<edge, vec<seq_entry> > *seq;
2864 FOR_EACH_VEC_ELT (sms, i, seq)
2866 /* Prune sm_other from the end. */
2867 while (!seq->second.is_empty ()
2868 && seq->second.last ().second == sm_other)
2869 seq->second.pop ();
2870 /* Prune duplicates from the start. */
2871 auto_bitmap seen (&lim_bitmap_obstack);
2872 unsigned j, k;
2873 for (j = k = 0; j < seq->second.length (); ++j)
2874 if (bitmap_set_bit (seen, seq->second[j].first))
2876 if (k != j)
2877 seq->second[k] = seq->second[j];
2878 ++k;
2880 seq->second.truncate (k);
2881 /* And verify. */
2882 seq_entry *e;
2883 FOR_EACH_VEC_ELT (seq->second, j, e)
2884 gcc_assert (e->second == sm_ord
2885 || (e->second == sm_other && e->from != NULL_TREE));
2888 /* Verify dependence for refs we cannot handle with the order preserving
2889 code (refs_not_supported) or prune them from mem_refs. */
2890 auto_vec<seq_entry> unord_refs;
2891 EXECUTE_IF_SET_IN_BITMAP (refs_not_supported, 0, i, bi)
2893 ref = memory_accesses.refs_list[i];
2894 if (!ref_indep_loop_p (loop, ref, sm_waw))
2895 bitmap_clear_bit (mem_refs, i);
2896 /* We've now verified store order for ref with respect to all other
2897 stores in the loop does not matter. */
2898 else
2899 unord_refs.safe_push (seq_entry (i, sm_unord));
2902 hash_map<im_mem_ref *, sm_aux *> aux_map;
2904 /* Execute SM but delay the store materialization for ordered
2905 sequences on exit. */
2906 EXECUTE_IF_SET_IN_BITMAP (mem_refs, 0, i, bi)
2908 ref = memory_accesses.refs_list[i];
2909 execute_sm (loop, ref, aux_map, bitmap_bit_p (refs_not_supported, i),
2910 false);
2913 /* Materialize ordered store sequences on exits. */
2914 FOR_EACH_VEC_ELT (exits, i, e)
2916 edge append_cond_position = NULL;
2917 edge last_cond_fallthru = NULL;
2918 if (i < sms.length ())
2920 gcc_assert (sms[i].first == e);
2921 execute_sm_exit (loop, e, sms[i].second, aux_map, sm_ord,
2922 append_cond_position, last_cond_fallthru);
2923 sms[i].second.release ();
2925 if (!unord_refs.is_empty ())
2926 execute_sm_exit (loop, e, unord_refs, aux_map, sm_unord,
2927 append_cond_position, last_cond_fallthru);
2928 /* Commit edge inserts here to preserve the order of stores
2929 when an exit exits multiple loops. */
2930 gsi_commit_one_edge_insert (e, NULL);
2933 for (hash_map<im_mem_ref *, sm_aux *>::iterator iter = aux_map.begin ();
2934 iter != aux_map.end (); ++iter)
2935 delete (*iter).second;
2938 class ref_always_accessed
2940 public:
2941 ref_always_accessed (class loop *loop_, bool stored_p_)
2942 : loop (loop_), stored_p (stored_p_) {}
2943 bool operator () (mem_ref_loc *loc);
2944 class loop *loop;
2945 bool stored_p;
2948 bool
2949 ref_always_accessed::operator () (mem_ref_loc *loc)
2951 class loop *must_exec;
2953 struct lim_aux_data *lim_data = get_lim_data (loc->stmt);
2954 if (!lim_data)
2955 return false;
2957 /* If we require an always executed store make sure the statement
2958 is a store. */
2959 if (stored_p)
2961 tree lhs = gimple_get_lhs (loc->stmt);
2962 if (!lhs
2963 || !(DECL_P (lhs) || REFERENCE_CLASS_P (lhs)))
2964 return false;
2967 must_exec = lim_data->always_executed_in;
2968 if (!must_exec)
2969 return false;
2971 if (must_exec == loop
2972 || flow_loop_nested_p (must_exec, loop))
2973 return true;
2975 return false;
2978 /* Returns true if REF is always accessed in LOOP. If STORED_P is true
2979 make sure REF is always stored to in LOOP. */
2981 static bool
2982 ref_always_accessed_p (class loop *loop, im_mem_ref *ref, bool stored_p)
2984 return for_all_locs_in_loop (loop, ref,
2985 ref_always_accessed (loop, stored_p));
2988 /* Returns true if REF1 and REF2 are independent. */
2990 static bool
2991 refs_independent_p (im_mem_ref *ref1, im_mem_ref *ref2, bool tbaa_p)
2993 if (ref1 == ref2)
2994 return true;
2996 if (dump_file && (dump_flags & TDF_DETAILS))
2997 fprintf (dump_file, "Querying dependency of refs %u and %u: ",
2998 ref1->id, ref2->id);
3000 if (mem_refs_may_alias_p (ref1, ref2, &memory_accesses.ttae_cache, tbaa_p))
3002 if (dump_file && (dump_flags & TDF_DETAILS))
3003 fprintf (dump_file, "dependent.\n");
3004 return false;
3006 else
3008 if (dump_file && (dump_flags & TDF_DETAILS))
3009 fprintf (dump_file, "independent.\n");
3010 return true;
3014 /* Returns true if REF is independent on all other accessess in LOOP.
3015 KIND specifies the kind of dependence to consider.
3016 lim_raw assumes REF is not stored in LOOP and disambiguates RAW
3017 dependences so if true REF can be hoisted out of LOOP
3018 sm_war disambiguates a store REF against all other loads to see
3019 whether the store can be sunk across loads out of LOOP
3020 sm_waw disambiguates a store REF against all other stores to see
3021 whether the store can be sunk across stores out of LOOP. */
3023 static bool
3024 ref_indep_loop_p (class loop *loop, im_mem_ref *ref, dep_kind kind)
3026 bool indep_p = true;
3027 bitmap refs_to_check;
3029 if (kind == sm_war)
3030 refs_to_check = &memory_accesses.refs_loaded_in_loop[loop->num];
3031 else
3032 refs_to_check = &memory_accesses.refs_stored_in_loop[loop->num];
3034 if (bitmap_bit_p (refs_to_check, UNANALYZABLE_MEM_ID)
3035 || ref->mem.ref == error_mark_node)
3036 indep_p = false;
3037 else
3039 /* tri-state, { unknown, independent, dependent } */
3040 dep_state state = query_loop_dependence (loop, ref, kind);
3041 if (state != dep_unknown)
3042 return state == dep_independent ? true : false;
3044 class loop *inner = loop->inner;
3045 while (inner)
3047 if (!ref_indep_loop_p (inner, ref, kind))
3049 indep_p = false;
3050 break;
3052 inner = inner->next;
3055 if (indep_p)
3057 unsigned i;
3058 bitmap_iterator bi;
3059 EXECUTE_IF_SET_IN_BITMAP (refs_to_check, 0, i, bi)
3061 im_mem_ref *aref = memory_accesses.refs_list[i];
3062 if (aref->mem.ref == error_mark_node)
3064 gimple *stmt = aref->accesses_in_loop[0].stmt;
3065 if ((kind == sm_war
3066 && ref_maybe_used_by_stmt_p (stmt, &ref->mem,
3067 kind != sm_waw))
3068 || stmt_may_clobber_ref_p_1 (stmt, &ref->mem,
3069 kind != sm_waw))
3071 indep_p = false;
3072 break;
3075 else if (!refs_independent_p (ref, aref, kind != sm_waw))
3077 indep_p = false;
3078 break;
3084 if (dump_file && (dump_flags & TDF_DETAILS))
3085 fprintf (dump_file, "Querying %s dependencies of ref %u in loop %d: %s\n",
3086 kind == lim_raw ? "RAW" : (kind == sm_war ? "SM WAR" : "SM WAW"),
3087 ref->id, loop->num, indep_p ? "independent" : "dependent");
3089 /* Record the computed result in the cache. */
3090 record_loop_dependence (loop, ref, kind,
3091 indep_p ? dep_independent : dep_dependent);
3093 return indep_p;
3096 class ref_in_loop_hot_body
3098 public:
3099 ref_in_loop_hot_body (class loop *loop_) : l (loop_) {}
3100 bool operator () (mem_ref_loc *loc);
3101 class loop *l;
3104 /* Check the coldest loop between loop L and innermost loop. If there is one
3105 cold loop between L and INNER_LOOP, store motion can be performed, otherwise
3106 no cold loop means no store motion. get_coldest_out_loop also handles cases
3107 when l is inner_loop. */
3108 bool
3109 ref_in_loop_hot_body::operator () (mem_ref_loc *loc)
3111 basic_block curr_bb = gimple_bb (loc->stmt);
3112 class loop *inner_loop = curr_bb->loop_father;
3113 return get_coldest_out_loop (l, inner_loop, curr_bb);
3117 /* Returns true if we can perform store motion of REF from LOOP. */
3119 static bool
3120 can_sm_ref_p (class loop *loop, im_mem_ref *ref)
3122 tree base;
3124 /* Can't hoist unanalyzable refs. */
3125 if (!MEM_ANALYZABLE (ref))
3126 return false;
3128 /* Can't hoist/sink aggregate copies. */
3129 if (ref->mem.ref == error_mark_node)
3130 return false;
3132 /* It should be movable. */
3133 if (!is_gimple_reg_type (TREE_TYPE (ref->mem.ref))
3134 || TREE_THIS_VOLATILE (ref->mem.ref)
3135 || !for_each_index (&ref->mem.ref, may_move_till, loop))
3136 return false;
3138 /* If it can throw fail, we do not properly update EH info. */
3139 if (tree_could_throw_p (ref->mem.ref))
3140 return false;
3142 /* If it can trap, it must be always executed in LOOP.
3143 Readonly memory locations may trap when storing to them, but
3144 tree_could_trap_p is a predicate for rvalues, so check that
3145 explicitly. */
3146 base = get_base_address (ref->mem.ref);
3147 if ((tree_could_trap_p (ref->mem.ref)
3148 || (DECL_P (base) && TREE_READONLY (base)))
3149 /* ??? We can at least use false here, allowing loads? We
3150 are forcing conditional stores if the ref is not always
3151 stored to later anyway. So this would only guard
3152 the load we need to emit. Thus when the ref is not
3153 loaded we can elide this completely? */
3154 && !ref_always_accessed_p (loop, ref, true))
3155 return false;
3157 /* Verify all loads of ref can be hoisted. */
3158 if (ref->loaded
3159 && bitmap_bit_p (ref->loaded, loop->num)
3160 && !ref_indep_loop_p (loop, ref, lim_raw))
3161 return false;
3163 /* Verify the candidate can be disambiguated against all loads,
3164 that is, we can elide all in-loop stores. Disambiguation
3165 against stores is done later when we cannot guarantee preserving
3166 the order of stores. */
3167 if (!ref_indep_loop_p (loop, ref, sm_war))
3168 return false;
3170 /* Verify whether the candidate is hot for LOOP. Only do store motion if the
3171 candidate's profile count is hot. Statement in cold BB shouldn't be moved
3172 out of it's loop_father. */
3173 if (!for_all_locs_in_loop (loop, ref, ref_in_loop_hot_body (loop)))
3174 return false;
3176 return true;
3179 /* Marks the references in LOOP for that store motion should be performed
3180 in REFS_TO_SM. SM_EXECUTED is the set of references for that store
3181 motion was performed in one of the outer loops. */
3183 static void
3184 find_refs_for_sm (class loop *loop, bitmap sm_executed, bitmap refs_to_sm)
3186 bitmap refs = &memory_accesses.all_refs_stored_in_loop[loop->num];
3187 unsigned i;
3188 bitmap_iterator bi;
3189 im_mem_ref *ref;
3191 EXECUTE_IF_AND_COMPL_IN_BITMAP (refs, sm_executed, 0, i, bi)
3193 ref = memory_accesses.refs_list[i];
3194 if (can_sm_ref_p (loop, ref) && dbg_cnt (lim))
3195 bitmap_set_bit (refs_to_sm, i);
3199 /* Checks whether LOOP (with exits stored in EXITS array) is suitable
3200 for a store motion optimization (i.e. whether we can insert statement
3201 on its exits). */
3203 static bool
3204 loop_suitable_for_sm (class loop *loop ATTRIBUTE_UNUSED,
3205 const vec<edge> &exits)
3207 unsigned i;
3208 edge ex;
3210 FOR_EACH_VEC_ELT (exits, i, ex)
3211 if (ex->flags & (EDGE_ABNORMAL | EDGE_EH))
3212 return false;
3214 return true;
3217 /* Try to perform store motion for all memory references modified inside
3218 LOOP. SM_EXECUTED is the bitmap of the memory references for that
3219 store motion was executed in one of the outer loops. */
3221 static void
3222 store_motion_loop (class loop *loop, bitmap sm_executed)
3224 auto_vec<edge> exits = get_loop_exit_edges (loop);
3225 class loop *subloop;
3226 bitmap sm_in_loop = BITMAP_ALLOC (&lim_bitmap_obstack);
3228 if (loop_suitable_for_sm (loop, exits))
3230 find_refs_for_sm (loop, sm_executed, sm_in_loop);
3231 if (!bitmap_empty_p (sm_in_loop))
3232 hoist_memory_references (loop, sm_in_loop, exits);
3235 bitmap_ior_into (sm_executed, sm_in_loop);
3236 for (subloop = loop->inner; subloop != NULL; subloop = subloop->next)
3237 store_motion_loop (subloop, sm_executed);
3238 bitmap_and_compl_into (sm_executed, sm_in_loop);
3239 BITMAP_FREE (sm_in_loop);
3242 /* Try to perform store motion for all memory references modified inside
3243 loops. */
3245 static void
3246 do_store_motion (void)
3248 class loop *loop;
3249 bitmap sm_executed = BITMAP_ALLOC (&lim_bitmap_obstack);
3251 for (loop = current_loops->tree_root->inner; loop != NULL; loop = loop->next)
3252 store_motion_loop (loop, sm_executed);
3254 BITMAP_FREE (sm_executed);
3257 /* Fills ALWAYS_EXECUTED_IN information for basic blocks of LOOP, i.e.
3258 for each such basic block bb records the outermost loop for that execution
3259 of its header implies execution of bb. CONTAINS_CALL is the bitmap of
3260 blocks that contain a nonpure call. */
3262 static void
3263 fill_always_executed_in_1 (class loop *loop, sbitmap contains_call)
3265 basic_block bb = NULL, last = NULL;
3266 edge e;
3267 class loop *inn_loop = loop;
3269 if (ALWAYS_EXECUTED_IN (loop->header) == NULL)
3271 auto_vec<basic_block, 64> worklist;
3272 worklist.reserve_exact (loop->num_nodes);
3273 worklist.quick_push (loop->header);
3276 edge_iterator ei;
3277 bb = worklist.pop ();
3279 if (!flow_bb_inside_loop_p (inn_loop, bb))
3281 /* When we are leaving a possibly infinite inner loop
3282 we have to stop processing. */
3283 if (!finite_loop_p (inn_loop))
3284 break;
3285 /* If the loop was finite we can continue with processing
3286 the loop we exited to. */
3287 inn_loop = bb->loop_father;
3290 if (dominated_by_p (CDI_DOMINATORS, loop->latch, bb))
3291 last = bb;
3293 if (bitmap_bit_p (contains_call, bb->index))
3294 break;
3296 /* If LOOP exits from this BB stop processing. */
3297 FOR_EACH_EDGE (e, ei, bb->succs)
3298 if (!flow_bb_inside_loop_p (loop, e->dest))
3299 break;
3300 if (e)
3301 break;
3303 /* A loop might be infinite (TODO use simple loop analysis
3304 to disprove this if possible). */
3305 if (bb->flags & BB_IRREDUCIBLE_LOOP)
3306 break;
3308 if (bb->loop_father->header == bb)
3309 /* Record that we enter into a subloop since it might not
3310 be finite. */
3311 /* ??? Entering into a not always executed subloop makes
3312 fill_always_executed_in quadratic in loop depth since
3313 we walk those loops N times. This is not a problem
3314 in practice though, see PR102253 for a worst-case testcase. */
3315 inn_loop = bb->loop_father;
3317 /* Walk the body of LOOP sorted by dominance relation. Additionally,
3318 if a basic block S dominates the latch, then only blocks dominated
3319 by S are after it.
3320 This is get_loop_body_in_dom_order using a worklist algorithm and
3321 stopping once we are no longer interested in visiting further
3322 blocks. */
3323 unsigned old_len = worklist.length ();
3324 unsigned postpone = 0;
3325 for (basic_block son = first_dom_son (CDI_DOMINATORS, bb);
3326 son;
3327 son = next_dom_son (CDI_DOMINATORS, son))
3329 if (!flow_bb_inside_loop_p (loop, son))
3330 continue;
3331 if (dominated_by_p (CDI_DOMINATORS, loop->latch, son))
3332 postpone = worklist.length ();
3333 worklist.quick_push (son);
3335 if (postpone)
3336 /* Postponing the block that dominates the latch means
3337 processing it last and thus putting it earliest in the
3338 worklist. */
3339 std::swap (worklist[old_len], worklist[postpone]);
3341 while (!worklist.is_empty ());
3343 while (1)
3345 if (dump_enabled_p ())
3346 dump_printf (MSG_NOTE, "BB %d is always executed in loop %d\n",
3347 last->index, loop->num);
3348 SET_ALWAYS_EXECUTED_IN (last, loop);
3349 if (last == loop->header)
3350 break;
3351 last = get_immediate_dominator (CDI_DOMINATORS, last);
3355 for (loop = loop->inner; loop; loop = loop->next)
3356 fill_always_executed_in_1 (loop, contains_call);
3359 /* Fills ALWAYS_EXECUTED_IN information for basic blocks, i.e.
3360 for each such basic block bb records the outermost loop for that execution
3361 of its header implies execution of bb. */
3363 static void
3364 fill_always_executed_in (void)
3366 basic_block bb;
3367 class loop *loop;
3369 auto_sbitmap contains_call (last_basic_block_for_fn (cfun));
3370 bitmap_clear (contains_call);
3371 FOR_EACH_BB_FN (bb, cfun)
3373 gimple_stmt_iterator gsi;
3374 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3376 if (nonpure_call_p (gsi_stmt (gsi)))
3377 break;
3380 if (!gsi_end_p (gsi))
3381 bitmap_set_bit (contains_call, bb->index);
3384 for (loop = current_loops->tree_root->inner; loop; loop = loop->next)
3385 fill_always_executed_in_1 (loop, contains_call);
3388 /* Find the coldest loop preheader for LOOP, also find the nearest hotter loop
3389 to LOOP. Then recursively iterate each inner loop. */
3391 void
3392 fill_coldest_and_hotter_out_loop (class loop *coldest_loop,
3393 class loop *hotter_loop, class loop *loop)
3395 if (bb_colder_than_loop_preheader (loop_preheader_edge (loop)->src,
3396 coldest_loop))
3397 coldest_loop = loop;
3399 coldest_outermost_loop[loop->num] = coldest_loop;
3401 hotter_than_inner_loop[loop->num] = NULL;
3402 class loop *outer_loop = loop_outer (loop);
3403 if (hotter_loop
3404 && bb_colder_than_loop_preheader (loop_preheader_edge (loop)->src,
3405 hotter_loop))
3406 hotter_than_inner_loop[loop->num] = hotter_loop;
3408 if (outer_loop && outer_loop != current_loops->tree_root
3409 && bb_colder_than_loop_preheader (loop_preheader_edge (loop)->src,
3410 outer_loop))
3411 hotter_than_inner_loop[loop->num] = outer_loop;
3413 if (dump_enabled_p ())
3415 dump_printf (MSG_NOTE, "loop %d's coldest_outermost_loop is %d, ",
3416 loop->num, coldest_loop->num);
3417 if (hotter_than_inner_loop[loop->num])
3418 dump_printf (MSG_NOTE, "hotter_than_inner_loop is %d\n",
3419 hotter_than_inner_loop[loop->num]->num);
3420 else
3421 dump_printf (MSG_NOTE, "hotter_than_inner_loop is NULL\n");
3424 class loop *inner_loop;
3425 for (inner_loop = loop->inner; inner_loop; inner_loop = inner_loop->next)
3426 fill_coldest_and_hotter_out_loop (coldest_loop,
3427 hotter_than_inner_loop[loop->num],
3428 inner_loop);
3431 /* Compute the global information needed by the loop invariant motion pass. */
3433 static void
3434 tree_ssa_lim_initialize (bool store_motion)
3436 unsigned i;
3438 bitmap_obstack_initialize (&lim_bitmap_obstack);
3439 gcc_obstack_init (&mem_ref_obstack);
3440 lim_aux_data_map = new hash_map<gimple *, lim_aux_data *>;
3442 if (flag_tm)
3443 compute_transaction_bits ();
3445 memory_accesses.refs = new hash_table<mem_ref_hasher> (100);
3446 memory_accesses.refs_list.create (100);
3447 /* Allocate a special, unanalyzable mem-ref with ID zero. */
3448 memory_accesses.refs_list.quick_push
3449 (mem_ref_alloc (NULL, 0, UNANALYZABLE_MEM_ID));
3451 memory_accesses.refs_loaded_in_loop.create (number_of_loops (cfun));
3452 memory_accesses.refs_loaded_in_loop.quick_grow (number_of_loops (cfun));
3453 memory_accesses.refs_stored_in_loop.create (number_of_loops (cfun));
3454 memory_accesses.refs_stored_in_loop.quick_grow (number_of_loops (cfun));
3455 if (store_motion)
3457 memory_accesses.all_refs_stored_in_loop.create (number_of_loops (cfun));
3458 memory_accesses.all_refs_stored_in_loop.quick_grow
3459 (number_of_loops (cfun));
3462 for (i = 0; i < number_of_loops (cfun); i++)
3464 bitmap_initialize (&memory_accesses.refs_loaded_in_loop[i],
3465 &lim_bitmap_obstack);
3466 bitmap_initialize (&memory_accesses.refs_stored_in_loop[i],
3467 &lim_bitmap_obstack);
3468 if (store_motion)
3469 bitmap_initialize (&memory_accesses.all_refs_stored_in_loop[i],
3470 &lim_bitmap_obstack);
3473 memory_accesses.ttae_cache = NULL;
3475 /* Initialize bb_loop_postorder with a mapping from loop->num to
3476 its postorder index. */
3477 i = 0;
3478 bb_loop_postorder = XNEWVEC (unsigned, number_of_loops (cfun));
3479 for (auto loop : loops_list (cfun, LI_FROM_INNERMOST))
3480 bb_loop_postorder[loop->num] = i++;
3483 /* Cleans up after the invariant motion pass. */
3485 static void
3486 tree_ssa_lim_finalize (void)
3488 basic_block bb;
3489 unsigned i;
3490 im_mem_ref *ref;
3492 FOR_EACH_BB_FN (bb, cfun)
3493 SET_ALWAYS_EXECUTED_IN (bb, NULL);
3495 bitmap_obstack_release (&lim_bitmap_obstack);
3496 delete lim_aux_data_map;
3498 delete memory_accesses.refs;
3499 memory_accesses.refs = NULL;
3501 FOR_EACH_VEC_ELT (memory_accesses.refs_list, i, ref)
3502 memref_free (ref);
3503 memory_accesses.refs_list.release ();
3504 obstack_free (&mem_ref_obstack, NULL);
3506 memory_accesses.refs_loaded_in_loop.release ();
3507 memory_accesses.refs_stored_in_loop.release ();
3508 memory_accesses.all_refs_stored_in_loop.release ();
3510 if (memory_accesses.ttae_cache)
3511 free_affine_expand_cache (&memory_accesses.ttae_cache);
3513 free (bb_loop_postorder);
3515 coldest_outermost_loop.release ();
3516 hotter_than_inner_loop.release ();
3519 /* Moves invariants from loops. Only "expensive" invariants are moved out --
3520 i.e. those that are likely to be win regardless of the register pressure.
3521 Only perform store motion if STORE_MOTION is true. */
3523 unsigned int
3524 loop_invariant_motion_in_fun (function *fun, bool store_motion)
3526 unsigned int todo = 0;
3528 tree_ssa_lim_initialize (store_motion);
3530 /* Gathers information about memory accesses in the loops. */
3531 analyze_memory_references (store_motion);
3533 /* Fills ALWAYS_EXECUTED_IN information for basic blocks. */
3534 fill_always_executed_in ();
3536 /* Pre-compute coldest outermost loop and nearest hotter loop of each loop.
3538 class loop *loop;
3539 coldest_outermost_loop.create (number_of_loops (cfun));
3540 coldest_outermost_loop.safe_grow_cleared (number_of_loops (cfun));
3541 hotter_than_inner_loop.create (number_of_loops (cfun));
3542 hotter_than_inner_loop.safe_grow_cleared (number_of_loops (cfun));
3543 for (loop = current_loops->tree_root->inner; loop != NULL; loop = loop->next)
3544 fill_coldest_and_hotter_out_loop (loop, NULL, loop);
3546 int *rpo = XNEWVEC (int, last_basic_block_for_fn (fun));
3547 int n = pre_and_rev_post_order_compute_fn (fun, NULL, rpo, false);
3549 /* For each statement determine the outermost loop in that it is
3550 invariant and cost for computing the invariant. */
3551 for (int i = 0; i < n; ++i)
3552 compute_invariantness (BASIC_BLOCK_FOR_FN (fun, rpo[i]));
3554 /* Execute store motion. Force the necessary invariants to be moved
3555 out of the loops as well. */
3556 if (store_motion)
3557 do_store_motion ();
3559 free (rpo);
3560 rpo = XNEWVEC (int, last_basic_block_for_fn (fun));
3561 n = pre_and_rev_post_order_compute_fn (fun, NULL, rpo, false);
3563 /* Move the expressions that are expensive enough. */
3564 for (int i = 0; i < n; ++i)
3565 todo |= move_computations_worker (BASIC_BLOCK_FOR_FN (fun, rpo[i]));
3567 free (rpo);
3569 gsi_commit_edge_inserts ();
3570 if (need_ssa_update_p (fun))
3571 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
3573 tree_ssa_lim_finalize ();
3575 return todo;
3578 /* Loop invariant motion pass. */
3580 namespace {
3582 const pass_data pass_data_lim =
3584 GIMPLE_PASS, /* type */
3585 "lim", /* name */
3586 OPTGROUP_LOOP, /* optinfo_flags */
3587 TV_LIM, /* tv_id */
3588 PROP_cfg, /* properties_required */
3589 0, /* properties_provided */
3590 0, /* properties_destroyed */
3591 0, /* todo_flags_start */
3592 0, /* todo_flags_finish */
3595 class pass_lim : public gimple_opt_pass
3597 public:
3598 pass_lim (gcc::context *ctxt)
3599 : gimple_opt_pass (pass_data_lim, ctxt)
3602 /* opt_pass methods: */
3603 opt_pass * clone () final override { return new pass_lim (m_ctxt); }
3604 bool gate (function *) final override { return flag_tree_loop_im != 0; }
3605 unsigned int execute (function *) final override;
3607 }; // class pass_lim
3609 unsigned int
3610 pass_lim::execute (function *fun)
3612 bool in_loop_pipeline = scev_initialized_p ();
3613 if (!in_loop_pipeline)
3614 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
3616 if (number_of_loops (fun) <= 1)
3617 return 0;
3618 unsigned int todo = loop_invariant_motion_in_fun (fun, flag_move_loop_stores);
3620 if (!in_loop_pipeline)
3621 loop_optimizer_finalize ();
3622 else
3623 scev_reset ();
3624 return todo;
3627 } // anon namespace
3629 gimple_opt_pass *
3630 make_pass_lim (gcc::context *ctxt)
3632 return new pass_lim (ctxt);