Debian Codegraph @

gcc/tree-ssa-loop-im.cc

raw
1 /* Loop invariant motion.
2 Copyright (C) 2003-2025 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
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.
10
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.
15
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/>. */
19
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 "tree-ssa.h"
50 #include "dbgcnt.h"
51 #include "insn-codes.h"
52 #include "optabs-tree.h"
53
54 /* TODO: Support for predicated code motion. I.e.
55
56 while (1)
57 {
58 if (cond)
59 {
60 a = inv;
61 something;
62 }
63 }
64
65 Where COND and INV are invariants, but evaluating INV may trap or be
66 invalid from some other reason if !COND. This may be transformed to
67
68 if (cond)
69 a = inv;
70 while (1)
71 {
72 if (cond)
73 something;
74 } */
75
76 /* The auxiliary data kept for each statement. */
77
78 struct lim_aux_data
79 {
80 class loop *max_loop; /* The outermost loop in that the statement
81 is invariant. */
82
83 class loop *tgt_loop; /* The loop out of that we want to move the
84 invariant. */
85
86 class loop *always_executed_in;
87 /* The outermost loop for that we are sure
88 the statement is executed if the loop
89 is entered. */
90
91 unsigned cost; /* Cost of the computation performed by the
92 statement. */
93
94 unsigned ref; /* The simple_mem_ref in this stmt or 0. */
95
96 vec<gimple *> depends; /* Vector of statements that must be also
97 hoisted out of the loop when this statement
98 is hoisted; i.e. those that define the
99 operands of the statement and are inside of
100 the MAX_LOOP loop. */
101 };
102
103 /* Maps statements to their lim_aux_data. */
104
105 static hash_map<gimple *, lim_aux_data *> *lim_aux_data_map;
106
107 /* Description of a memory reference location. */
108
109 struct mem_ref_loc
110 {
111 tree *ref; /* The reference itself. */
112 gimple *stmt; /* The statement in that it occurs. */
113 };
114
115
116 /* Description of a memory reference. */
117
118 class im_mem_ref
119 {
120 public:
121 unsigned id : 30; /* ID assigned to the memory reference
122 (its index in memory_accesses.refs_list) */
123 unsigned ref_canonical : 1; /* Whether mem.ref was canonicalized. */
124 unsigned ref_decomposed : 1; /* Whether the ref was hashed from mem. */
125 hashval_t hash; /* Its hash value. */
126
127 /* The memory access itself and associated caching of alias-oracle
128 query meta-data. We are using mem.ref == error_mark_node for the
129 case the reference is represented by its single access stmt
130 in accesses_in_loop[0]. */
131 ao_ref mem;
132
133 bitmap stored; /* The set of loops in that this memory location
134 is stored to. */
135 bitmap loaded; /* The set of loops in that this memory location
136 is loaded from. */
137 vec<mem_ref_loc> accesses_in_loop;
138 /* The locations of the accesses. */
139
140 /* The following set is computed on demand. */
141 bitmap_head dep_loop; /* The set of loops in that the memory
142 reference is {in,}dependent in
143 different modes. */
144 };
145
146 /* We use six bits per loop in the ref->dep_loop bitmap to record
147 the dep_kind x dep_state combinations. */
148
149 enum dep_kind { lim_raw, sm_war, sm_waw };
150 enum dep_state { dep_unknown, dep_independent, dep_dependent };
151
152 /* coldest outermost loop for given loop. */
153 vec<class loop *> coldest_outermost_loop;
154 /* hotter outer loop nearest to given loop. */
155 vec<class loop *> hotter_than_inner_loop;
156
157 /* Populate the loop dependence cache of REF for LOOP, KIND with STATE. */
158
159 static void
160 record_loop_dependence (class loop *loop, im_mem_ref *ref,
161 dep_kind kind, dep_state state)
162 {
163 gcc_assert (state != dep_unknown);
164 unsigned bit = 6 * loop->num + kind * 2 + state == dep_dependent ? 1 : 0;
165 bitmap_set_bit (&ref->dep_loop, bit);
166 }
167
168 /* Query the loop dependence cache of REF for LOOP, KIND. */
169
170 static dep_state
171 query_loop_dependence (class loop *loop, im_mem_ref *ref, dep_kind kind)
172 {
173 unsigned first_bit = 6 * loop->num + kind * 2;
174 if (bitmap_bit_p (&ref->dep_loop, first_bit))
175 return dep_independent;
176 else if (bitmap_bit_p (&ref->dep_loop, first_bit + 1))
177 return dep_dependent;
178 return dep_unknown;
179 }
180
181 /* Mem_ref hashtable helpers. */
182
183 struct mem_ref_hasher : nofree_ptr_hash <im_mem_ref>
184 {
185 typedef ao_ref *compare_type;
186 static inline hashval_t hash (const im_mem_ref *);
187 static inline bool equal (const im_mem_ref *, const ao_ref *);
188 };
189
190 /* A hash function for class im_mem_ref object OBJ. */
191
192 inline hashval_t
193 mem_ref_hasher::hash (const im_mem_ref *mem)
194 {
195 return mem->hash;
196 }
197
198 /* An equality function for class im_mem_ref object MEM1 with
199 memory reference OBJ2. */
200
201 inline bool
202 mem_ref_hasher::equal (const im_mem_ref *mem1, const ao_ref *obj2)
203 {
204 if (obj2->max_size_known_p ())
205 return (mem1->ref_decomposed
206 && ((TREE_CODE (mem1->mem.base) == MEM_REF
207 && TREE_CODE (obj2->base) == MEM_REF
208 && operand_equal_p (TREE_OPERAND (mem1->mem.base, 0),
209 TREE_OPERAND (obj2->base, 0), 0)
210 && known_eq (mem_ref_offset (mem1->mem.base) * BITS_PER_UNIT + mem1->mem.offset,
211 mem_ref_offset (obj2->base) * BITS_PER_UNIT + obj2->offset))
212 || (operand_equal_p (mem1->mem.base, obj2->base, 0)
213 && known_eq (mem1->mem.offset, obj2->offset)))
214 && known_eq (mem1->mem.size, obj2->size)
215 && known_eq (mem1->mem.max_size, obj2->max_size)
216 && mem1->mem.volatile_p == obj2->volatile_p
217 && (mem1->mem.ref_alias_set == obj2->ref_alias_set
218 /* We are not canonicalizing alias-sets but for the
219 special-case we didn't canonicalize yet and the
220 incoming ref is a alias-set zero MEM we pick
221 the correct one already. */
222 || (!mem1->ref_canonical
223 && (TREE_CODE (obj2->ref) == MEM_REF
224 || TREE_CODE (obj2->ref) == TARGET_MEM_REF)
225 && obj2->ref_alias_set == 0)
226 /* Likewise if there's a canonical ref with alias-set zero. */
227 || (mem1->ref_canonical && mem1->mem.ref_alias_set == 0))
228 && types_compatible_p (TREE_TYPE (mem1->mem.ref),
229 TREE_TYPE (obj2->ref)));
230 else
231 return operand_equal_p (mem1->mem.ref, obj2->ref, 0);
232 }
233
234
235 /* Description of memory accesses in loops. */
236
237 static struct
238 {
239 /* The hash table of memory references accessed in loops. */
240 hash_table<mem_ref_hasher> *refs;
241
242 /* The list of memory references. */
243 vec<im_mem_ref *> refs_list;
244
245 /* The set of memory references accessed in each loop. */
246 vec<bitmap_head> refs_loaded_in_loop;
247
248 /* The set of memory references stored in each loop. */
249 vec<bitmap_head> refs_stored_in_loop;
250
251 /* The set of memory references stored in each loop, including subloops . */
252 vec<bitmap_head> all_refs_stored_in_loop;
253
254 /* Cache for expanding memory addresses. */
255 hash_map<tree, name_expansion *> *ttae_cache;
256 } memory_accesses;
257
258 /* Obstack for the bitmaps in the above data structures. */
259 static bitmap_obstack lim_bitmap_obstack;
260 static obstack mem_ref_obstack;
261
262 static bool ref_indep_loop_p (class loop *, im_mem_ref *, dep_kind);
263 static bool ref_always_accessed_p (class loop *, im_mem_ref *, bool);
264 static bool refs_independent_p (im_mem_ref *, im_mem_ref *, bool = true);
265
266 /* Minimum cost of an expensive expression. */
267 #define LIM_EXPENSIVE ((unsigned) param_lim_expensive)
268
269 /* The outermost loop for which execution of the header guarantees that the
270 block will be executed. */
271 #define ALWAYS_EXECUTED_IN(BB) ((class loop *) (BB)->aux)
272 #define SET_ALWAYS_EXECUTED_IN(BB, VAL) ((BB)->aux = (void *) (VAL))
273
274 /* ID of the shared unanalyzable mem. */
275 #define UNANALYZABLE_MEM_ID 0
276
277 /* Whether the reference was analyzable. */
278 #define MEM_ANALYZABLE(REF) ((REF)->id != UNANALYZABLE_MEM_ID)
279
280 static struct lim_aux_data *
281 init_lim_data (gimple *stmt)
282 {
283 lim_aux_data *p = XCNEW (struct lim_aux_data);
284 lim_aux_data_map->put (stmt, p);
285
286 return p;
287 }
288
289 static struct lim_aux_data *
290 get_lim_data (gimple *stmt)
291 {
292 lim_aux_data **p = lim_aux_data_map->get (stmt);
293 if (!p)
294 return NULL;
295
296 return *p;
297 }
298
299 /* Releases the memory occupied by DATA. */
300
301 static void
302 free_lim_aux_data (struct lim_aux_data *data)
303 {
304 data->depends.release ();
305 free (data);
306 }
307
308 static void
309 clear_lim_data (gimple *stmt)
310 {
311 lim_aux_data **p = lim_aux_data_map->get (stmt);
312 if (!p)
313 return;
314
315 free_lim_aux_data (*p);
316 *p = NULL;
317 }
318
319
320 /* The possibilities of statement movement. */
321 enum move_pos
322 {
323 MOVE_IMPOSSIBLE, /* No movement -- side effect expression. */
324 MOVE_PRESERVE_EXECUTION, /* Must not cause the non-executed statement
325 become executed -- memory accesses, ... */
326 MOVE_POSSIBLE /* Unlimited movement. */
327 };
328
329
330 /* If it is possible to hoist the statement STMT unconditionally,
331 returns MOVE_POSSIBLE.
332 If it is possible to hoist the statement STMT, but we must avoid making
333 it executed if it would not be executed in the original program (e.g.
334 because it may trap), return MOVE_PRESERVE_EXECUTION.
335 Otherwise return MOVE_IMPOSSIBLE. */
336
337 static enum move_pos
338 movement_possibility_1 (gimple *stmt)
339 {
340 tree lhs;
341 enum move_pos ret = MOVE_POSSIBLE;
342
343 if (flag_unswitch_loops
344 && gimple_code (stmt) == GIMPLE_COND)
345 {
346 /* If we perform unswitching, force the operands of the invariant
347 condition to be moved out of the loop. */
348 return MOVE_POSSIBLE;
349 }
350
351 if (gimple_code (stmt) == GIMPLE_PHI
352 && gimple_phi_num_args (stmt) <= 2
353 && !virtual_operand_p (gimple_phi_result (stmt))
354 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (gimple_phi_result (stmt)))
355 return MOVE_POSSIBLE;
356
357 if (gimple_get_lhs (stmt) == NULL_TREE)
358 return MOVE_IMPOSSIBLE;
359
360 if (gimple_vdef (stmt))
361 return MOVE_IMPOSSIBLE;
362
363 if (stmt_ends_bb_p (stmt)
364 || gimple_has_volatile_ops (stmt)
365 || gimple_has_side_effects (stmt)
366 || stmt_could_throw_p (cfun, stmt))
367 return MOVE_IMPOSSIBLE;
368
369 if (is_gimple_call (stmt))
370 {
371 /* While pure or const call is guaranteed to have no side effects, we
372 cannot move it arbitrarily. Consider code like
373
374 char *s = something ();
375
376 while (1)
377 {
378 if (s)
379 t = strlen (s);
380 else
381 t = 0;
382 }
383
384 Here the strlen call cannot be moved out of the loop, even though
385 s is invariant. In addition to possibly creating a call with
386 invalid arguments, moving out a function call that is not executed
387 may cause performance regressions in case the call is costly and
388 not executed at all. */
389 ret = MOVE_PRESERVE_EXECUTION;
390 lhs = gimple_call_lhs (stmt);
391 }
392 else if (is_gimple_assign (stmt))
393 lhs = gimple_assign_lhs (stmt);
394 else
395 return MOVE_IMPOSSIBLE;
396
397 if (TREE_CODE (lhs) == SSA_NAME
398 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
399 return MOVE_IMPOSSIBLE;
400
401 if (TREE_CODE (lhs) != SSA_NAME
402 || gimple_could_trap_p (stmt))
403 return MOVE_PRESERVE_EXECUTION;
404
405 if (is_gimple_assign (stmt))
406 {
407 auto code = gimple_assign_rhs_code (stmt);
408 tree type = TREE_TYPE (gimple_assign_rhs1 (stmt));
409 /* For shifts and rotates and possibly out-of-bound shift operands
410 we currently cannot rewrite them into something unconditionally
411 well-defined. */
412 if ((code == LSHIFT_EXPR
413 || code == RSHIFT_EXPR
414 || code == LROTATE_EXPR
415 || code == RROTATE_EXPR)
416 && (TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST
417 /* We cannot use ranges at 'stmt' here. */
418 || wi::ltu_p (wi::to_wide (gimple_assign_rhs2 (stmt)),
419 element_precision (type))))
420 ret = MOVE_PRESERVE_EXECUTION;
421 }
422
423 /* Non local loads in a transaction cannot be hoisted out. Well,
424 unless the load happens on every path out of the loop, but we
425 don't take this into account yet. */
426 if (flag_tm
427 && gimple_in_transaction (stmt)
428 && gimple_assign_single_p (stmt))
429 {
430 tree rhs = gimple_assign_rhs1 (stmt);
431 if (DECL_P (rhs) && is_global_var (rhs))
432 {
433 if (dump_file)
434 {
435 fprintf (dump_file, "Cannot hoist conditional load of ");
436 print_generic_expr (dump_file, rhs, TDF_SLIM);
437 fprintf (dump_file, " because it is in a transaction.\n");
438 }
439 return MOVE_IMPOSSIBLE;
440 }
441 }
442
443 return ret;
444 }
445
446 static enum move_pos
447 movement_possibility (gimple *stmt)
448 {
449 enum move_pos pos = movement_possibility_1 (stmt);
450 if (pos == MOVE_POSSIBLE)
451 {
452 use_operand_p use_p;
453 ssa_op_iter ssa_iter;
454 FOR_EACH_PHI_OR_STMT_USE (use_p, stmt, ssa_iter, SSA_OP_USE)
455 if (TREE_CODE (USE_FROM_PTR (use_p)) == SSA_NAME
456 && ssa_name_maybe_undef_p (USE_FROM_PTR (use_p)))
457 return MOVE_PRESERVE_EXECUTION;
458 }
459 return pos;
460 }
461
462
463 /* Compare the profile count inequality of bb and loop's preheader, it is
464 three-state as stated in profile-count.h, FALSE is returned if inequality
465 cannot be decided. */
466 bool
467 bb_colder_than_loop_preheader (basic_block bb, class loop *loop)
468 {
469 gcc_assert (bb && loop);
470 return bb->count < loop_preheader_edge (loop)->src->count;
471 }
472
473 /* Check coldest loop between OUTERMOST_LOOP and LOOP by comparing profile
474 count.
475 It does three steps check:
476 1) Check whether CURR_BB is cold in it's own loop_father, if it is cold, just
477 return NULL which means it should not be moved out at all;
478 2) CURR_BB is NOT cold, check if pre-computed COLDEST_LOOP is outside of
479 OUTERMOST_LOOP, if it is inside of OUTERMOST_LOOP, return the COLDEST_LOOP;
480 3) If COLDEST_LOOP is outside of OUTERMOST_LOOP, check whether there is a
481 hotter loop between OUTERMOST_LOOP and loop in pre-computed
482 HOTTER_THAN_INNER_LOOP, return it's nested inner loop, otherwise return
483 OUTERMOST_LOOP.
484 At last, the coldest_loop is inside of OUTERMOST_LOOP, just return it as
485 the hoist target. */
486
487 static class loop *
488 get_coldest_out_loop (class loop *outermost_loop, class loop *loop,
489 basic_block curr_bb)
490 {
491 gcc_assert (outermost_loop == loop
492 || flow_loop_nested_p (outermost_loop, loop));
493
494 /* If bb_colder_than_loop_preheader returns false due to three-state
495 comparision, OUTERMOST_LOOP is returned finally to preserve the behavior.
496 Otherwise, return the coldest loop between OUTERMOST_LOOP and LOOP. */
497 if (curr_bb && bb_colder_than_loop_preheader (curr_bb, loop))
498 return NULL;
499
500 class loop *coldest_loop = coldest_outermost_loop[loop->num];
501 if (loop_depth (coldest_loop) < loop_depth (outermost_loop))
502 {
503 class loop *hotter_loop = hotter_than_inner_loop[loop->num];
504 if (!hotter_loop
505 || loop_depth (hotter_loop) < loop_depth (outermost_loop))
506 return outermost_loop;
507
508 /* hotter_loop is between OUTERMOST_LOOP and LOOP like:
509 [loop tree root, ..., coldest_loop, ..., outermost_loop, ...,
510 hotter_loop, second_coldest_loop, ..., loop]
511 return second_coldest_loop to be the hoist target. */
512 class loop *aloop;
513 for (aloop = hotter_loop->inner; aloop; aloop = aloop->next)
514 if (aloop == loop || flow_loop_nested_p (aloop, loop))
515 return aloop;
516 }
517 return coldest_loop;
518 }
519
520 /* Suppose that operand DEF is used inside the LOOP. Returns the outermost
521 loop to that we could move the expression using DEF if it did not have
522 other operands, i.e. the outermost loop enclosing LOOP in that the value
523 of DEF is invariant. */
524
525 static class loop *
526 outermost_invariant_loop (tree def, class loop *loop)
527 {
528 gimple *def_stmt;
529 basic_block def_bb;
530 class loop *max_loop;
531 struct lim_aux_data *lim_data;
532
533 if (!def)
534 return superloop_at_depth (loop, 1);
535
536 if (TREE_CODE (def) != SSA_NAME)
537 {
538 gcc_assert (is_gimple_min_invariant (def));
539 return superloop_at_depth (loop, 1);
540 }
541
542 def_stmt = SSA_NAME_DEF_STMT (def);
543 def_bb = gimple_bb (def_stmt);
544 if (!def_bb)
545 return superloop_at_depth (loop, 1);
546
547 max_loop = find_common_loop (loop, def_bb->loop_father);
548
549 lim_data = get_lim_data (def_stmt);
550 if (lim_data != NULL && lim_data->max_loop != NULL)
551 max_loop = find_common_loop (max_loop,
552 loop_outer (lim_data->max_loop));
553 if (max_loop == loop)
554 return NULL;
555 max_loop = superloop_at_depth (loop, loop_depth (max_loop) + 1);
556
557 return max_loop;
558 }
559
560 /* DATA is a structure containing information associated with a statement
561 inside LOOP. DEF is one of the operands of this statement.
562
563 Find the outermost loop enclosing LOOP in that value of DEF is invariant
564 and record this in DATA->max_loop field. If DEF itself is defined inside
565 this loop as well (i.e. we need to hoist it out of the loop if we want
566 to hoist the statement represented by DATA), record the statement in that
567 DEF is defined to the DATA->depends list. Additionally if ADD_COST is true,
568 add the cost of the computation of DEF to the DATA->cost.
569
570 If DEF is not invariant in LOOP, return false. Otherwise return TRUE. */
571
572 static bool
573 add_dependency (tree def, struct lim_aux_data *data, class loop *loop,
574 bool add_cost)
575 {
576 gimple *def_stmt = SSA_NAME_DEF_STMT (def);
577 basic_block def_bb = gimple_bb (def_stmt);
578 class loop *max_loop;
579 struct lim_aux_data *def_data;
580
581 if (!def_bb)
582 return true;
583
584 max_loop = outermost_invariant_loop (def, loop);
585 if (!max_loop)
586 return false;
587
588 if (flow_loop_nested_p (data->max_loop, max_loop))
589 data->max_loop = max_loop;
590
591 def_data = get_lim_data (def_stmt);
592 if (!def_data)
593 return true;
594
595 if (add_cost
596 /* Only add the cost if the statement defining DEF is inside LOOP,
597 i.e. if it is likely that by moving the invariants dependent
598 on it, we will be able to avoid creating a new register for
599 it (since it will be only used in these dependent invariants). */
600 && def_bb->loop_father == loop)
601 data->cost += def_data->cost;
602
603 data->depends.safe_push (def_stmt);
604
605 return true;
606 }
607
608 /* Returns an estimate for a cost of statement STMT. The values here
609 are just ad-hoc constants, similar to costs for inlining. */
610
611 static unsigned
612 stmt_cost (gimple *stmt)
613 {
614 /* Always try to create possibilities for unswitching. */
615 if (gimple_code (stmt) == GIMPLE_COND
616 || gimple_code (stmt) == GIMPLE_PHI)
617 return LIM_EXPENSIVE;
618
619 /* We should be hoisting calls if possible. */
620 if (is_gimple_call (stmt))
621 {
622 tree fndecl;
623
624 /* Unless the call is a builtin_constant_p; this always folds to a
625 constant, so moving it is useless. */
626 fndecl = gimple_call_fndecl (stmt);
627 if (fndecl && fndecl_built_in_p (fndecl, BUILT_IN_CONSTANT_P))
628 return 0;
629
630 return LIM_EXPENSIVE;
631 }
632
633 /* Hoisting memory references out should almost surely be a win. */
634 if (gimple_references_memory_p (stmt))
635 return LIM_EXPENSIVE;
636
637 if (gimple_code (stmt) != GIMPLE_ASSIGN)
638 return 1;
639
640 enum tree_code code = gimple_assign_rhs_code (stmt);
641 switch (code)
642 {
643 case MULT_EXPR:
644 case WIDEN_MULT_EXPR:
645 case WIDEN_MULT_PLUS_EXPR:
646 case WIDEN_MULT_MINUS_EXPR:
647 case DOT_PROD_EXPR:
648 case TRUNC_DIV_EXPR:
649 case CEIL_DIV_EXPR:
650 case FLOOR_DIV_EXPR:
651 case ROUND_DIV_EXPR:
652 case EXACT_DIV_EXPR:
653 case CEIL_MOD_EXPR:
654 case FLOOR_MOD_EXPR:
655 case ROUND_MOD_EXPR:
656 case TRUNC_MOD_EXPR:
657 case RDIV_EXPR:
658 /* Division and multiplication are usually expensive. */
659 return LIM_EXPENSIVE;
660
661 case LSHIFT_EXPR:
662 case RSHIFT_EXPR:
663 case WIDEN_LSHIFT_EXPR:
664 case LROTATE_EXPR:
665 case RROTATE_EXPR:
666 /* Shifts and rotates are usually expensive. */
667 return LIM_EXPENSIVE;
668
669 case COND_EXPR:
670 case VEC_COND_EXPR:
671 /* Conditionals are expensive. */
672 return LIM_EXPENSIVE;
673
674 case CONSTRUCTOR:
675 /* Make vector construction cost proportional to the number
676 of elements. */
677 return CONSTRUCTOR_NELTS (gimple_assign_rhs1 (stmt));
678
679 case SSA_NAME:
680 case PAREN_EXPR:
681 /* Whether or not something is wrapped inside a PAREN_EXPR
682 should not change move cost. Nor should an intermediate
683 unpropagated SSA name copy. */
684 return 0;
685
686 default:
687 /* Comparisons are usually expensive. */
688 if (TREE_CODE_CLASS (code) == tcc_comparison)
689 return LIM_EXPENSIVE;
690 return 1;
691 }
692 }
693
694 /* Finds the outermost loop between OUTER and LOOP in that the memory reference
695 REF is independent. If REF is not independent in LOOP, NULL is returned
696 instead. */
697
698 static class loop *
699 outermost_indep_loop (class loop *outer, class loop *loop, im_mem_ref *ref)
700 {
701 class loop *aloop;
702
703 if (ref->stored && bitmap_bit_p (ref->stored, loop->num))
704 return NULL;
705
706 for (aloop = outer;
707 aloop != loop;
708 aloop = superloop_at_depth (loop, loop_depth (aloop) + 1))
709 if ((!ref->stored || !bitmap_bit_p (ref->stored, aloop->num))
710 && ref_indep_loop_p (aloop, ref, lim_raw))
711 return aloop;
712
713 if (ref_indep_loop_p (loop, ref, lim_raw))
714 return loop;
715 else
716 return NULL;
717 }
718
719 /* If there is a simple load or store to a memory reference in STMT, returns
720 the location of the memory reference, and sets IS_STORE according to whether
721 it is a store or load. Otherwise, returns NULL. */
722
723 static tree *
724 simple_mem_ref_in_stmt (gimple *stmt, bool *is_store)
725 {
726 tree *lhs, *rhs;
727
728 /* Recognize SSA_NAME = MEM and MEM = (SSA_NAME | invariant) patterns. */
729 if (!gimple_assign_single_p (stmt))
730 return NULL;
731
732 lhs = gimple_assign_lhs_ptr (stmt);
733 rhs = gimple_assign_rhs1_ptr (stmt);
734
735 if (TREE_CODE (*lhs) == SSA_NAME && gimple_vuse (stmt))
736 {
737 *is_store = false;
738 return rhs;
739 }
740 else if (gimple_vdef (stmt)
741 && (TREE_CODE (*rhs) == SSA_NAME || is_gimple_min_invariant (*rhs)))
742 {
743 *is_store = true;
744 return lhs;
745 }
746 else
747 return NULL;
748 }
749
750 /* From a controlling predicate in DOM determine the arguments from
751 the PHI node PHI that are chosen if the predicate evaluates to
752 true and false and store them to *TRUE_ARG_P and *FALSE_ARG_P if
753 they are non-NULL. Returns true if the arguments can be determined,
754 else return false. */
755
756 static bool
757 extract_true_false_args_from_phi (basic_block dom, gphi *phi,
758 tree *true_arg_p, tree *false_arg_p)
759 {
760 edge te, fe;
761 if (! extract_true_false_controlled_edges (dom, gimple_bb (phi),
762 &te, &fe))
763 return false;
764
765 if (true_arg_p)
766 *true_arg_p = PHI_ARG_DEF (phi, te->dest_idx);
767 if (false_arg_p)
768 *false_arg_p = PHI_ARG_DEF (phi, fe->dest_idx);
769
770 return true;
771 }
772
773 /* Determine the outermost loop to that it is possible to hoist a statement
774 STMT and store it to LIM_DATA (STMT)->max_loop. To do this we determine
775 the outermost loop in that the value computed by STMT is invariant.
776 If MUST_PRESERVE_EXEC is true, additionally choose such a loop that
777 we preserve the fact whether STMT is executed. It also fills other related
778 information to LIM_DATA (STMT).
779
780 The function returns false if STMT cannot be hoisted outside of the loop it
781 is defined in, and true otherwise. */
782
783 static bool
784 determine_max_movement (gimple *stmt, bool must_preserve_exec)
785 {
786 basic_block bb = gimple_bb (stmt);
787 class loop *loop = bb->loop_father;
788 class loop *level;
789 struct lim_aux_data *lim_data = get_lim_data (stmt);
790 tree val;
791 ssa_op_iter iter;
792
793 if (must_preserve_exec)
794 level = ALWAYS_EXECUTED_IN (bb);
795 else
796 level = superloop_at_depth (loop, 1);
797 lim_data->max_loop = get_coldest_out_loop (level, loop, bb);
798 if (!lim_data->max_loop)
799 return false;
800
801 if (gphi *phi = dyn_cast <gphi *> (stmt))
802 {
803 use_operand_p use_p;
804 unsigned min_cost = UINT_MAX;
805 unsigned total_cost = 0;
806 struct lim_aux_data *def_data;
807
808 /* We will end up promoting dependencies to be unconditionally
809 evaluated. For this reason the PHI cost (and thus the
810 cost we remove from the loop by doing the invariant motion)
811 is that of the cheapest PHI argument dependency chain. */
812 FOR_EACH_PHI_ARG (use_p, phi, iter, SSA_OP_USE)
813 {
814 val = USE_FROM_PTR (use_p);
815
816 if (TREE_CODE (val) != SSA_NAME)
817 {
818 /* Assign const 1 to constants. */
819 min_cost = MIN (min_cost, 1);
820 total_cost += 1;
821 continue;
822 }
823 if (!add_dependency (val, lim_data, loop, false))
824 return false;
825
826 gimple *def_stmt = SSA_NAME_DEF_STMT (val);
827 if (gimple_bb (def_stmt)
828 && gimple_bb (def_stmt)->loop_father == loop)
829 {
830 def_data = get_lim_data (def_stmt);
831 if (def_data)
832 {
833 min_cost = MIN (min_cost, def_data->cost);
834 total_cost += def_data->cost;
835 }
836 }
837 }
838
839 min_cost = MIN (min_cost, total_cost);
840 lim_data->cost += min_cost;
841
842 if (gimple_phi_num_args (phi) > 1)
843 {
844 basic_block dom = get_immediate_dominator (CDI_DOMINATORS, bb);
845 gimple *cond;
846 if (gsi_end_p (gsi_last_bb (dom)))
847 return false;
848 cond = gsi_stmt (gsi_last_bb (dom));
849 if (gimple_code (cond) != GIMPLE_COND)
850 return false;
851 /* Verify that this is an extended form of a diamond and
852 the PHI arguments are completely controlled by the
853 predicate in DOM. */
854 if (!extract_true_false_args_from_phi (dom, phi, NULL, NULL))
855 return false;
856
857 /* Check if one of the depedent statement is a vector compare whether
858 the target supports it, otherwise it's invalid to hoist it out of
859 the gcond it belonged to. */
860 if (VECTOR_TYPE_P (TREE_TYPE (gimple_cond_lhs (cond))))
861 {
862 tree type = TREE_TYPE (gimple_cond_lhs (cond));
863 auto code = gimple_cond_code (cond);
864 if (!target_supports_op_p (type, code, optab_vector))
865 return false;
866 }
867
868 /* Fold in dependencies and cost of the condition. */
869 FOR_EACH_SSA_TREE_OPERAND (val, cond, iter, SSA_OP_USE)
870 {
871 if (!add_dependency (val, lim_data, loop, false))
872 return false;
873 def_data = get_lim_data (SSA_NAME_DEF_STMT (val));
874 if (def_data)
875 lim_data->cost += def_data->cost;
876 }
877
878 /* We want to avoid unconditionally executing very expensive
879 operations. As costs for our dependencies cannot be
880 negative just claim we are not invariand for this case.
881 We also are not sure whether the control-flow inside the
882 loop will vanish. */
883 if (total_cost - min_cost >= 2 * LIM_EXPENSIVE
884 && !(min_cost != 0
885 && total_cost / min_cost <= 2))
886 return false;
887
888 /* Assume that the control-flow in the loop will vanish.
889 ??? We should verify this and not artificially increase
890 the cost if that is not the case. */
891 lim_data->cost += stmt_cost (stmt);
892 }
893
894 return true;
895 }
896
897 /* A stmt that receives abnormal edges cannot be hoisted. */
898 if (is_a <gcall *> (stmt)
899 && (gimple_call_flags (stmt) & ECF_RETURNS_TWICE))
900 return false;
901
902 FOR_EACH_SSA_TREE_OPERAND (val, stmt, iter, SSA_OP_USE)
903 if (!add_dependency (val, lim_data, loop, true))
904 return false;
905
906 if (gimple_vuse (stmt))
907 {
908 im_mem_ref *ref
909 = lim_data ? memory_accesses.refs_list[lim_data->ref] : NULL;
910 if (ref
911 && MEM_ANALYZABLE (ref))
912 {
913 lim_data->max_loop = outermost_indep_loop (lim_data->max_loop,
914 loop, ref);
915 if (!lim_data->max_loop)
916 return false;
917 }
918 else if (! add_dependency (gimple_vuse (stmt), lim_data, loop, false))
919 return false;
920 }
921
922 lim_data->cost += stmt_cost (stmt);
923
924 return true;
925 }
926
927 /* Suppose that some statement in ORIG_LOOP is hoisted to the loop LEVEL,
928 and that one of the operands of this statement is computed by STMT.
929 Ensure that STMT (together with all the statements that define its
930 operands) is hoisted at least out of the loop LEVEL. */
931
932 static void
933 set_level (gimple *stmt, class loop *orig_loop, class loop *level)
934 {
935 class loop *stmt_loop = gimple_bb (stmt)->loop_father;
936 struct lim_aux_data *lim_data;
937 gimple *dep_stmt;
938 unsigned i;
939
940 stmt_loop = find_common_loop (orig_loop, stmt_loop);
941 lim_data = get_lim_data (stmt);
942 if (lim_data != NULL && lim_data->tgt_loop != NULL)
943 stmt_loop = find_common_loop (stmt_loop,
944 loop_outer (lim_data->tgt_loop));
945 if (flow_loop_nested_p (stmt_loop, level))
946 return;
947
948 gcc_assert (level == lim_data->max_loop
949 || flow_loop_nested_p (lim_data->max_loop, level));
950
951 lim_data->tgt_loop = level;
952 FOR_EACH_VEC_ELT (lim_data->depends, i, dep_stmt)
953 set_level (dep_stmt, orig_loop, level);
954 }
955
956 /* Determines an outermost loop from that we want to hoist the statement STMT.
957 For now we chose the outermost possible loop. TODO -- use profiling
958 information to set it more sanely. */
959
960 static void
961 set_profitable_level (gimple *stmt)
962 {
963 set_level (stmt, gimple_bb (stmt)->loop_father, get_lim_data (stmt)->max_loop);
964 }
965
966 /* Returns true if STMT is a call that has side effects. */
967
968 static bool
969 nonpure_call_p (gimple *stmt)
970 {
971 if (gimple_code (stmt) != GIMPLE_CALL)
972 return false;
973
974 return gimple_has_side_effects (stmt);
975 }
976
977 /* Rewrite a/b to a*(1/b). Return the invariant stmt to process. */
978
979 static gimple *
980 rewrite_reciprocal (gimple_stmt_iterator *bsi)
981 {
982 gassign *stmt, *stmt1, *stmt2;
983 tree name, lhs, type;
984 tree real_one;
985 gimple_stmt_iterator gsi;
986
987 stmt = as_a <gassign *> (gsi_stmt (*bsi));
988 lhs = gimple_assign_lhs (stmt);
989 type = TREE_TYPE (lhs);
990
991 real_one = build_one_cst (type);
992
993 name = make_temp_ssa_name (type, NULL, "reciptmp");
994 stmt1 = gimple_build_assign (name, RDIV_EXPR, real_one,
995 gimple_assign_rhs2 (stmt));
996 stmt2 = gimple_build_assign (lhs, MULT_EXPR, name,
997 gimple_assign_rhs1 (stmt));
998
999 /* Replace division stmt with reciprocal and multiply stmts.
1000 The multiply stmt is not invariant, so update iterator
1001 and avoid rescanning. */
1002 gsi = *bsi;
1003 gsi_insert_before (bsi, stmt1, GSI_NEW_STMT);
1004 gsi_replace (&gsi, stmt2, true);
1005
1006 /* Continue processing with invariant reciprocal statement. */
1007 return stmt1;
1008 }
1009
1010 /* Check if the pattern at *BSI is a bittest of the form
1011 (A >> B) & 1 != 0 and in this case rewrite it to A & (1 << B) != 0. */
1012
1013 static gimple *
1014 rewrite_bittest (gimple_stmt_iterator *bsi)
1015 {
1016 gassign *stmt;
1017 gimple *stmt1;
1018 gassign *stmt2;
1019 gimple *use_stmt;
1020 gcond *cond_stmt;
1021 tree lhs, name, t, a, b;
1022 use_operand_p use;
1023
1024 stmt = as_a <gassign *> (gsi_stmt (*bsi));
1025 lhs = gimple_assign_lhs (stmt);
1026
1027 /* Verify that the single use of lhs is a comparison against zero. */
1028 if (TREE_CODE (lhs) != SSA_NAME
1029 || !single_imm_use (lhs, &use, &use_stmt))
1030 return stmt;
1031 cond_stmt = dyn_cast <gcond *> (use_stmt);
1032 if (!cond_stmt)
1033 return stmt;
1034 if (gimple_cond_lhs (cond_stmt) != lhs
1035 || (gimple_cond_code (cond_stmt) != NE_EXPR
1036 && gimple_cond_code (cond_stmt) != EQ_EXPR)
1037 || !integer_zerop (gimple_cond_rhs (cond_stmt)))
1038 return stmt;
1039
1040 /* Get at the operands of the shift. The rhs is TMP1 & 1. */
1041 stmt1 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
1042 if (gimple_code (stmt1) != GIMPLE_ASSIGN)
1043 return stmt;
1044
1045 /* There is a conversion in between possibly inserted by fold. */
1046 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt1)))
1047 {
1048 t = gimple_assign_rhs1 (stmt1);
1049 if (TREE_CODE (t) != SSA_NAME
1050 || !has_single_use (t))
1051 return stmt;
1052 stmt1 = SSA_NAME_DEF_STMT (t);
1053 if (gimple_code (stmt1) != GIMPLE_ASSIGN)
1054 return stmt;
1055 }
1056
1057 /* Verify that B is loop invariant but A is not. Verify that with
1058 all the stmt walking we are still in the same loop. */
1059 if (gimple_assign_rhs_code (stmt1) != RSHIFT_EXPR
1060 || loop_containing_stmt (stmt1) != loop_containing_stmt (stmt))
1061 return stmt;
1062
1063 a = gimple_assign_rhs1 (stmt1);
1064 b = gimple_assign_rhs2 (stmt1);
1065
1066 if (outermost_invariant_loop (b, loop_containing_stmt (stmt1)) != NULL
1067 && outermost_invariant_loop (a, loop_containing_stmt (stmt1)) == NULL)
1068 {
1069 gimple_stmt_iterator rsi;
1070
1071 /* 1 << B */
1072 t = fold_build2 (LSHIFT_EXPR, TREE_TYPE (a),
1073 build_int_cst (TREE_TYPE (a), 1), b);
1074 name = make_temp_ssa_name (TREE_TYPE (a), NULL, "shifttmp");
1075 stmt1 = gimple_build_assign (name, t);
1076
1077 /* A & (1 << B) */
1078 t = fold_build2 (BIT_AND_EXPR, TREE_TYPE (a), a, name);
1079 name = make_temp_ssa_name (TREE_TYPE (a), NULL, "shifttmp");
1080 stmt2 = gimple_build_assign (name, t);
1081
1082 /* Replace the SSA_NAME we compare against zero. Adjust
1083 the type of zero accordingly. */
1084 SET_USE (use, name);
1085 gimple_cond_set_rhs (cond_stmt,
1086 build_int_cst_type (TREE_TYPE (name),
1087 0));
1088
1089 /* Don't use gsi_replace here, none of the new assignments sets
1090 the variable originally set in stmt. Move bsi to stmt1, and
1091 then remove the original stmt, so that we get a chance to
1092 retain debug info for it. */
1093 rsi = *bsi;
1094 gsi_insert_before (bsi, stmt1, GSI_NEW_STMT);
1095 gsi_insert_before (&rsi, stmt2, GSI_SAME_STMT);
1096 gimple *to_release = gsi_stmt (rsi);
1097 gsi_remove (&rsi, true);
1098 release_defs (to_release);
1099
1100 return stmt1;
1101 }
1102
1103 return stmt;
1104 }
1105
1106 /* Determine the outermost loops in that statements in basic block BB are
1107 invariant, and record them to the LIM_DATA associated with the
1108 statements. */
1109
1110 static void
1111 compute_invariantness (basic_block bb)
1112 {
1113 enum move_pos pos;
1114 gimple_stmt_iterator bsi;
1115 gimple *stmt;
1116 bool maybe_never = ALWAYS_EXECUTED_IN (bb) == NULL;
1117 class loop *outermost = ALWAYS_EXECUTED_IN (bb);
1118 struct lim_aux_data *lim_data;
1119
1120 if (!loop_outer (bb->loop_father))
1121 return;
1122
1123 if (dump_file && (dump_flags & TDF_DETAILS))
1124 fprintf (dump_file, "Basic block %d (loop %d -- depth %d):\n\n",
1125 bb->index, bb->loop_father->num, loop_depth (bb->loop_father));
1126
1127 /* Look at PHI nodes, but only if there is at most two.
1128 ??? We could relax this further by post-processing the inserted
1129 code and transforming adjacent cond-exprs with the same predicate
1130 to control flow again. */
1131 bsi = gsi_start_phis (bb);
1132 if (!gsi_end_p (bsi)
1133 && ((gsi_next (&bsi), gsi_end_p (bsi))
1134 || (gsi_next (&bsi), gsi_end_p (bsi))))
1135 for (bsi = gsi_start_phis (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1136 {
1137 stmt = gsi_stmt (bsi);
1138
1139 pos = movement_possibility (stmt);
1140 if (pos == MOVE_IMPOSSIBLE)
1141 continue;
1142
1143 lim_data = get_lim_data (stmt);
1144 if (! lim_data)
1145 lim_data = init_lim_data (stmt);
1146 lim_data->always_executed_in = outermost;
1147
1148 if (!determine_max_movement (stmt, false))
1149 {
1150 lim_data->max_loop = NULL;
1151 continue;
1152 }
1153
1154 if (dump_file && (dump_flags & TDF_DETAILS))
1155 {
1156 print_gimple_stmt (dump_file, stmt, 2);
1157 fprintf (dump_file, " invariant up to level %d, cost %d.\n\n",
1158 loop_depth (lim_data->max_loop),
1159 lim_data->cost);
1160 }
1161
1162 if (lim_data->cost >= LIM_EXPENSIVE)
1163 set_profitable_level (stmt);
1164 }
1165
1166 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1167 {
1168 stmt = gsi_stmt (bsi);
1169
1170 pos = movement_possibility (stmt);
1171 if (pos == MOVE_IMPOSSIBLE)
1172 {
1173 if (nonpure_call_p (stmt))
1174 {
1175 maybe_never = true;
1176 outermost = NULL;
1177 }
1178 /* Make sure to note always_executed_in for stores to make
1179 store-motion work. */
1180 else if (stmt_makes_single_store (stmt))
1181 {
1182 struct lim_aux_data *lim_data = get_lim_data (stmt);
1183 if (! lim_data)
1184 lim_data = init_lim_data (stmt);
1185 lim_data->always_executed_in = outermost;
1186 }
1187 continue;
1188 }
1189
1190 if (is_gimple_assign (stmt)
1191 && (get_gimple_rhs_class (gimple_assign_rhs_code (stmt))
1192 == GIMPLE_BINARY_RHS))
1193 {
1194 tree op0 = gimple_assign_rhs1 (stmt);
1195 tree op1 = gimple_assign_rhs2 (stmt);
1196 class loop *ol1 = outermost_invariant_loop (op1,
1197 loop_containing_stmt (stmt));
1198
1199 /* If divisor is invariant, convert a/b to a*(1/b), allowing reciprocal
1200 to be hoisted out of loop, saving expensive divide. */
1201 if (pos == MOVE_POSSIBLE
1202 && gimple_assign_rhs_code (stmt) == RDIV_EXPR
1203 && flag_unsafe_math_optimizations
1204 && !flag_trapping_math
1205 && ol1 != NULL
1206 && outermost_invariant_loop (op0, ol1) == NULL)
1207 stmt = rewrite_reciprocal (&bsi);
1208
1209 /* If the shift count is invariant, convert (A >> B) & 1 to
1210 A & (1 << B) allowing the bit mask to be hoisted out of the loop
1211 saving an expensive shift. */
1212 if (pos == MOVE_POSSIBLE
1213 && gimple_assign_rhs_code (stmt) == BIT_AND_EXPR
1214 && integer_onep (op1)
1215 && TREE_CODE (op0) == SSA_NAME
1216 && has_single_use (op0))
1217 stmt = rewrite_bittest (&bsi);
1218 }
1219
1220 lim_data = get_lim_data (stmt);
1221 if (! lim_data)
1222 lim_data = init_lim_data (stmt);
1223 lim_data->always_executed_in = outermost;
1224
1225 if (maybe_never && pos == MOVE_PRESERVE_EXECUTION)
1226 continue;
1227
1228 if (!determine_max_movement (stmt, pos == MOVE_PRESERVE_EXECUTION))
1229 {
1230 lim_data->max_loop = NULL;
1231 continue;
1232 }
1233
1234 if (dump_file && (dump_flags & TDF_DETAILS))
1235 {
1236 print_gimple_stmt (dump_file, stmt, 2);
1237 fprintf (dump_file, " invariant up to level %d, cost %d.\n\n",
1238 loop_depth (lim_data->max_loop),
1239 lim_data->cost);
1240 }
1241
1242 if (lim_data->cost >= LIM_EXPENSIVE)
1243 set_profitable_level (stmt);
1244 }
1245 }
1246
1247 /* Hoist the statements in basic block BB out of the loops prescribed by
1248 data stored in LIM_DATA structures associated with each statement. Callback
1249 for walk_dominator_tree. */
1250
1251 unsigned int
1252 move_computations_worker (basic_block bb)
1253 {
1254 class loop *level;
1255 unsigned cost = 0;
1256 struct lim_aux_data *lim_data;
1257 unsigned int todo = 0;
1258
1259 if (!loop_outer (bb->loop_father))
1260 return todo;
1261
1262 for (gphi_iterator bsi = gsi_start_phis (bb); !gsi_end_p (bsi); )
1263 {
1264 gassign *new_stmt;
1265 gphi *stmt = bsi.phi ();
1266
1267 lim_data = get_lim_data (stmt);
1268 if (lim_data == NULL)
1269 {
1270 gsi_next (&bsi);
1271 continue;
1272 }
1273
1274 cost = lim_data->cost;
1275 level = lim_data->tgt_loop;
1276 clear_lim_data (stmt);
1277
1278 if (!level)
1279 {
1280 gsi_next (&bsi);
1281 continue;
1282 }
1283
1284 if (dump_file && (dump_flags & TDF_DETAILS))
1285 {
1286 fprintf (dump_file, "Moving PHI node\n");
1287 print_gimple_stmt (dump_file, stmt, 0);
1288 fprintf (dump_file, "(cost %u) out of loop %d.\n\n",
1289 cost, level->num);
1290 }
1291
1292 if (gimple_phi_num_args (stmt) == 1)
1293 {
1294 tree arg = PHI_ARG_DEF (stmt, 0);
1295 new_stmt = gimple_build_assign (gimple_phi_result (stmt),
1296 TREE_CODE (arg), arg);
1297 }
1298 else
1299 {
1300 basic_block dom = get_immediate_dominator (CDI_DOMINATORS, bb);
1301 gimple *cond = gsi_stmt (gsi_last_bb (dom));
1302 tree arg0 = NULL_TREE, arg1 = NULL_TREE, t;
1303 /* Get the PHI arguments corresponding to the true and false
1304 edges of COND. */
1305 extract_true_false_args_from_phi (dom, stmt, &arg0, &arg1);
1306 gcc_assert (arg0 && arg1);
1307 /* For `bool_val != 0`, reuse bool_val. */
1308 if (gimple_cond_code (cond) == NE_EXPR
1309 && integer_zerop (gimple_cond_rhs (cond))
1310 && types_compatible_p (TREE_TYPE (gimple_cond_lhs (cond)),
1311 boolean_type_node))
1312 {
1313 t = gimple_cond_lhs (cond);
1314 }
1315 else
1316 {
1317 t = make_ssa_name (boolean_type_node);
1318 new_stmt = gimple_build_assign (t, gimple_cond_code (cond),
1319 gimple_cond_lhs (cond),
1320 gimple_cond_rhs (cond));
1321 gsi_insert_on_edge (loop_preheader_edge (level), new_stmt);
1322 }
1323 new_stmt = gimple_build_assign (gimple_phi_result (stmt),
1324 COND_EXPR, t, arg0, arg1);
1325 todo |= TODO_cleanup_cfg;
1326 }
1327 if (!ALWAYS_EXECUTED_IN (bb)
1328 || (ALWAYS_EXECUTED_IN (bb) != level
1329 && !flow_loop_nested_p (ALWAYS_EXECUTED_IN (bb), level)))
1330 reset_flow_sensitive_info (gimple_assign_lhs (new_stmt));
1331 gsi_insert_on_edge (loop_preheader_edge (level), new_stmt);
1332 remove_phi_node (&bsi, false);
1333 }
1334
1335 for (gimple_stmt_iterator bsi = gsi_start_bb (bb); !gsi_end_p (bsi); )
1336 {
1337 edge e;
1338
1339 gimple *stmt = gsi_stmt (bsi);
1340
1341 lim_data = get_lim_data (stmt);
1342 if (lim_data == NULL)
1343 {
1344 gsi_next (&bsi);
1345 continue;
1346 }
1347
1348 cost = lim_data->cost;
1349 level = lim_data->tgt_loop;
1350 clear_lim_data (stmt);
1351
1352 if (!level)
1353 {
1354 gsi_next (&bsi);
1355 continue;
1356 }
1357
1358 /* We do not really want to move conditionals out of the loop; we just
1359 placed it here to force its operands to be moved if necessary. */
1360 if (gimple_code (stmt) == GIMPLE_COND)
1361 {
1362 gsi_next (&bsi);
1363 continue;
1364 }
1365
1366 if (dump_file && (dump_flags & TDF_DETAILS))
1367 {
1368 fprintf (dump_file, "Moving statement\n");
1369 print_gimple_stmt (dump_file, stmt, 0);
1370 fprintf (dump_file, "(cost %u) out of loop %d.\n\n",
1371 cost, level->num);
1372 }
1373
1374 e = loop_preheader_edge (level);
1375 gcc_assert (!gimple_vdef (stmt));
1376 if (gimple_vuse (stmt))
1377 {
1378 /* The new VUSE is the one from the virtual PHI in the loop
1379 header or the one already present. */
1380 gphi_iterator gsi2;
1381 for (gsi2 = gsi_start_phis (e->dest);
1382 !gsi_end_p (gsi2); gsi_next (&gsi2))
1383 {
1384 gphi *phi = gsi2.phi ();
1385 if (virtual_operand_p (gimple_phi_result (phi)))
1386 {
1387 SET_USE (gimple_vuse_op (stmt),
1388 PHI_ARG_DEF_FROM_EDGE (phi, e));
1389 break;
1390 }
1391 }
1392 }
1393 gsi_remove (&bsi, false);
1394 if (gimple_has_lhs (stmt)
1395 && TREE_CODE (gimple_get_lhs (stmt)) == SSA_NAME
1396 && (!ALWAYS_EXECUTED_IN (bb)
1397 || !(ALWAYS_EXECUTED_IN (bb) == level
1398 || flow_loop_nested_p (ALWAYS_EXECUTED_IN (bb), level))))
1399 reset_flow_sensitive_info (gimple_get_lhs (stmt));
1400 /* In case this is a stmt that is not unconditionally executed
1401 when the target loop header is executed and the stmt may
1402 invoke undefined integer or pointer overflow rewrite it to
1403 unsigned arithmetic. */
1404 if (is_gimple_assign (stmt)
1405 && INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_lhs (stmt)))
1406 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (gimple_assign_lhs (stmt)))
1407 && arith_code_with_undefined_signed_overflow
1408 (gimple_assign_rhs_code (stmt))
1409 && (!ALWAYS_EXECUTED_IN (bb)
1410 || !(ALWAYS_EXECUTED_IN (bb) == level
1411 || flow_loop_nested_p (ALWAYS_EXECUTED_IN (bb), level))))
1412 gsi_insert_seq_on_edge (e, rewrite_to_defined_overflow (stmt));
1413 else
1414 gsi_insert_on_edge (e, stmt);
1415 }
1416
1417 return todo;
1418 }
1419
1420 /* Checks whether the statement defining variable *INDEX can be hoisted
1421 out of the loop passed in DATA. Callback for for_each_index. */
1422
1423 static bool
1424 may_move_till (tree ref, tree *index, void *data)
1425 {
1426 class loop *loop = (class loop *) data, *max_loop;
1427
1428 /* If REF is an array reference, check also that the step and the lower
1429 bound is invariant in LOOP. */
1430 if (TREE_CODE (ref) == ARRAY_REF)
1431 {
1432 tree step = TREE_OPERAND (ref, 3);
1433 tree lbound = TREE_OPERAND (ref, 2);
1434
1435 max_loop = outermost_invariant_loop (step, loop);
1436 if (!max_loop)
1437 return false;
1438
1439 max_loop = outermost_invariant_loop (lbound, loop);
1440 if (!max_loop)
1441 return false;
1442 }
1443
1444 max_loop = outermost_invariant_loop (*index, loop);
1445 if (!max_loop)
1446 return false;
1447
1448 return true;
1449 }
1450
1451 /* If OP is SSA NAME, force the statement that defines it to be
1452 moved out of the LOOP. ORIG_LOOP is the loop in that EXPR is used. */
1453
1454 static void
1455 force_move_till_op (tree op, class loop *orig_loop, class loop *loop)
1456 {
1457 gimple *stmt;
1458
1459 if (!op
1460 || is_gimple_min_invariant (op))
1461 return;
1462
1463 gcc_assert (TREE_CODE (op) == SSA_NAME);
1464
1465 stmt = SSA_NAME_DEF_STMT (op);
1466 if (gimple_nop_p (stmt))
1467 return;
1468
1469 set_level (stmt, orig_loop, loop);
1470 }
1471
1472 /* Forces statement defining invariants in REF (and *INDEX) to be moved out of
1473 the LOOP. The reference REF is used in the loop ORIG_LOOP. Callback for
1474 for_each_index. */
1475
1476 struct fmt_data
1477 {
1478 class loop *loop;
1479 class loop *orig_loop;
1480 };
1481
1482 static bool
1483 force_move_till (tree ref, tree *index, void *data)
1484 {
1485 struct fmt_data *fmt_data = (struct fmt_data *) data;
1486
1487 if (TREE_CODE (ref) == ARRAY_REF)
1488 {
1489 tree step = TREE_OPERAND (ref, 3);
1490 tree lbound = TREE_OPERAND (ref, 2);
1491
1492 force_move_till_op (step, fmt_data->orig_loop, fmt_data->loop);
1493 force_move_till_op (lbound, fmt_data->orig_loop, fmt_data->loop);
1494 }
1495
1496 force_move_till_op (*index, fmt_data->orig_loop, fmt_data->loop);
1497
1498 return true;
1499 }
1500
1501 /* A function to free the mem_ref object OBJ. */
1502
1503 static void
1504 memref_free (class im_mem_ref *mem)
1505 {
1506 mem->accesses_in_loop.release ();
1507 }
1508
1509 /* Allocates and returns a memory reference description for MEM whose hash
1510 value is HASH and id is ID. */
1511
1512 static im_mem_ref *
1513 mem_ref_alloc (ao_ref *mem, unsigned hash, unsigned id)
1514 {
1515 im_mem_ref *ref = XOBNEW (&mem_ref_obstack, class im_mem_ref);
1516 if (mem)
1517 ref->mem = *mem;
1518 else
1519 ao_ref_init (&ref->mem, error_mark_node);
1520 ref->id = id;
1521 ref->ref_canonical = false;
1522 ref->ref_decomposed = false;
1523 ref->hash = hash;
1524 ref->stored = NULL;
1525 ref->loaded = NULL;
1526 bitmap_initialize (&ref->dep_loop, &lim_bitmap_obstack);
1527 ref->accesses_in_loop.create (1);
1528
1529 return ref;
1530 }
1531
1532 /* Records memory reference location *LOC in LOOP to the memory reference
1533 description REF. The reference occurs in statement STMT. */
1534
1535 static void
1536 record_mem_ref_loc (im_mem_ref *ref, gimple *stmt, tree *loc)
1537 {
1538 mem_ref_loc aref;
1539 aref.stmt = stmt;
1540 aref.ref = loc;
1541 ref->accesses_in_loop.safe_push (aref);
1542 }
1543
1544 /* Set the LOOP bit in REF stored bitmap and allocate that if
1545 necessary. Return whether a bit was changed. */
1546
1547 static bool
1548 set_ref_stored_in_loop (im_mem_ref *ref, class loop *loop)
1549 {
1550 if (!ref->stored)
1551 ref->stored = BITMAP_ALLOC (&lim_bitmap_obstack);
1552 return bitmap_set_bit (ref->stored, loop->num);
1553 }
1554
1555 /* Marks reference REF as stored in LOOP. */
1556
1557 static void
1558 mark_ref_stored (im_mem_ref *ref, class loop *loop)
1559 {
1560 while (loop != current_loops->tree_root
1561 && set_ref_stored_in_loop (ref, loop))
1562 loop = loop_outer (loop);
1563 }
1564
1565 /* Set the LOOP bit in REF loaded bitmap and allocate that if
1566 necessary. Return whether a bit was changed. */
1567
1568 static bool
1569 set_ref_loaded_in_loop (im_mem_ref *ref, class loop *loop)
1570 {
1571 if (!ref->loaded)
1572 ref->loaded = BITMAP_ALLOC (&lim_bitmap_obstack);
1573 return bitmap_set_bit (ref->loaded, loop->num);
1574 }
1575
1576 /* Marks reference REF as loaded in LOOP. */
1577
1578 static void
1579 mark_ref_loaded (im_mem_ref *ref, class loop *loop)
1580 {
1581 while (loop != current_loops->tree_root
1582 && set_ref_loaded_in_loop (ref, loop))
1583 loop = loop_outer (loop);
1584 }
1585
1586 /* Gathers memory references in statement STMT in LOOP, storing the
1587 information about them in the memory_accesses structure. Marks
1588 the vops accessed through unrecognized statements there as
1589 well. */
1590
1591 static void
1592 gather_mem_refs_stmt (class loop *loop, gimple *stmt)
1593 {
1594 tree *mem = NULL;
1595 hashval_t hash;
1596 im_mem_ref **slot;
1597 im_mem_ref *ref;
1598 bool is_stored;
1599 unsigned id;
1600
1601 if (!gimple_vuse (stmt))
1602 return;
1603
1604 mem = simple_mem_ref_in_stmt (stmt, &is_stored);
1605 if (!mem && is_gimple_assign (stmt))
1606 {
1607 /* For aggregate copies record distinct references but use them
1608 only for disambiguation purposes. */
1609 id = memory_accesses.refs_list.length ();
1610 ref = mem_ref_alloc (NULL, 0, id);
1611 memory_accesses.refs_list.safe_push (ref);
1612 if (dump_file && (dump_flags & TDF_DETAILS))
1613 {
1614 fprintf (dump_file, "Unhandled memory reference %u: ", id);
1615 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
1616 }
1617 record_mem_ref_loc (ref, stmt, mem);
1618 is_stored = gimple_vdef (stmt);
1619 }
1620 else if (!mem)
1621 {
1622 /* We use the shared mem_ref for all unanalyzable refs. */
1623 id = UNANALYZABLE_MEM_ID;
1624 ref = memory_accesses.refs_list[id];
1625 if (dump_file && (dump_flags & TDF_DETAILS))
1626 {
1627 fprintf (dump_file, "Unanalyzed memory reference %u: ", id);
1628 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
1629 }
1630 is_stored = gimple_vdef (stmt);
1631 }
1632 else
1633 {
1634 /* We are looking for equal refs that might differ in structure
1635 such as a.b vs. MEM[&a + 4]. So we key off the ao_ref but
1636 make sure we can canonicalize the ref in the hashtable if
1637 non-operand_equal_p refs are found. For the lookup we mark
1638 the case we want strict equality with aor.max_size == -1. */
1639 ao_ref aor;
1640 ao_ref_init (&aor, *mem);
1641 ao_ref_base (&aor);
1642 ao_ref_alias_set (&aor);
1643 HOST_WIDE_INT offset, size, max_size;
1644 poly_int64 saved_maxsize = aor.max_size, mem_off;
1645 tree mem_base;
1646 bool ref_decomposed;
1647 if (aor.max_size_known_p ()
1648 && aor.offset.is_constant (&offset)
1649 && aor.size.is_constant (&size)
1650 && aor.max_size.is_constant (&max_size)
1651 && size == max_size
1652 && (size % BITS_PER_UNIT) == 0
1653 /* We're canonicalizing to a MEM where TYPE_SIZE specifies the
1654 size. Make sure this is consistent with the extraction. */
1655 && poly_int_tree_p (TYPE_SIZE (TREE_TYPE (*mem)))
1656 && known_eq (wi::to_poly_offset (TYPE_SIZE (TREE_TYPE (*mem))),
1657 aor.size)
1658 && (mem_base = get_addr_base_and_unit_offset (aor.ref, &mem_off)))
1659 {
1660 ref_decomposed = true;
1661 tree base = ao_ref_base (&aor);
1662 poly_int64 moffset;
1663 HOST_WIDE_INT mcoffset;
1664 if (TREE_CODE (base) == MEM_REF
1665 && (mem_ref_offset (base) * BITS_PER_UNIT + offset).to_shwi (&moffset)
1666 && moffset.is_constant (&mcoffset))
1667 {
1668 hash = iterative_hash_expr (TREE_OPERAND (base, 0), 0);
1669 hash = iterative_hash_host_wide_int (mcoffset, hash);
1670 }
1671 else
1672 {
1673 hash = iterative_hash_expr (base, 0);
1674 hash = iterative_hash_host_wide_int (offset, hash);
1675 }
1676 hash = iterative_hash_host_wide_int (size, hash);
1677 }
1678 else
1679 {
1680 ref_decomposed = false;
1681 hash = iterative_hash_expr (aor.ref, 0);
1682 aor.max_size = -1;
1683 }
1684 slot = memory_accesses.refs->find_slot_with_hash (&aor, hash, INSERT);
1685 aor.max_size = saved_maxsize;
1686 if (*slot)
1687 {
1688 if (!(*slot)->ref_canonical
1689 && !operand_equal_p (*mem, (*slot)->mem.ref, 0))
1690 {
1691 /* If we didn't yet canonicalize the hashtable ref (which
1692 we'll end up using for code insertion) and hit a second
1693 equal ref that is not structurally equivalent create
1694 a canonical ref which is a bare MEM_REF. */
1695 if (TREE_CODE (*mem) == MEM_REF
1696 || TREE_CODE (*mem) == TARGET_MEM_REF)
1697 {
1698 (*slot)->mem.ref = *mem;
1699 (*slot)->mem.base_alias_set = ao_ref_base_alias_set (&aor);
1700 }
1701 else
1702 {
1703 tree ref_alias_type = reference_alias_ptr_type (*mem);
1704 unsigned int ref_align = get_object_alignment (*mem);
1705 tree ref_type = TREE_TYPE (*mem);
1706 tree tmp = build1 (ADDR_EXPR, ptr_type_node,
1707 unshare_expr (mem_base));
1708 if (TYPE_ALIGN (ref_type) != ref_align)
1709 ref_type = build_aligned_type (ref_type, ref_align);
1710 tree new_ref
1711 = fold_build2 (MEM_REF, ref_type, tmp,
1712 build_int_cst (ref_alias_type, mem_off));
1713 if ((*slot)->mem.volatile_p)
1714 TREE_THIS_VOLATILE (new_ref) = 1;
1715 (*slot)->mem.ref = new_ref;
1716 /* Make sure the recorded base and offset are consistent
1717 with the newly built ref. */
1718 if (TREE_CODE (TREE_OPERAND (new_ref, 0)) == ADDR_EXPR)
1719 ;
1720 else
1721 {
1722 (*slot)->mem.base = new_ref;
1723 (*slot)->mem.offset = 0;
1724 }
1725 gcc_checking_assert (TREE_CODE ((*slot)->mem.ref) == MEM_REF
1726 && is_gimple_mem_ref_addr
1727 (TREE_OPERAND ((*slot)->mem.ref,
1728 0)));
1729 (*slot)->mem.base_alias_set = (*slot)->mem.ref_alias_set;
1730 }
1731 (*slot)->ref_canonical = true;
1732 }
1733 ref = *slot;
1734 id = ref->id;
1735 }
1736 else
1737 {
1738 id = memory_accesses.refs_list.length ();
1739 ref = mem_ref_alloc (&aor, hash, id);
1740 ref->ref_decomposed = ref_decomposed;
1741 memory_accesses.refs_list.safe_push (ref);
1742 *slot = ref;
1743
1744 if (dump_file && (dump_flags & TDF_DETAILS))
1745 {
1746 fprintf (dump_file, "Memory reference %u: ", id);
1747 print_generic_expr (dump_file, ref->mem.ref, TDF_SLIM);
1748 fprintf (dump_file, "\n");
1749 }
1750 }
1751
1752 record_mem_ref_loc (ref, stmt, mem);
1753 }
1754 if (is_stored)
1755 {
1756 bitmap_set_bit (&memory_accesses.refs_stored_in_loop[loop->num], ref->id);
1757 mark_ref_stored (ref, loop);
1758 }
1759 /* A not simple memory op is also a read when it is a write. */
1760 if (!is_stored || id == UNANALYZABLE_MEM_ID
1761 || ref->mem.ref == error_mark_node)
1762 {
1763 bitmap_set_bit (&memory_accesses.refs_loaded_in_loop[loop->num], ref->id);
1764 mark_ref_loaded (ref, loop);
1765 }
1766 init_lim_data (stmt)->ref = ref->id;
1767 return;
1768 }
1769
1770 static unsigned *bb_loop_postorder;
1771
1772 /* qsort sort function to sort blocks after their loop fathers postorder. */
1773
1774 static int
1775 sort_bbs_in_loop_postorder_cmp (const void *bb1_, const void *bb2_,
1776 void *bb_loop_postorder_)
1777 {
1778 unsigned *bb_loop_postorder = (unsigned *)bb_loop_postorder_;
1779 basic_block bb1 = *(const basic_block *)bb1_;
1780 basic_block bb2 = *(const basic_block *)bb2_;
1781 class loop *loop1 = bb1->loop_father;
1782 class loop *loop2 = bb2->loop_father;
1783 if (loop1->num == loop2->num)
1784 return bb1->index - bb2->index;
1785 return bb_loop_postorder[loop1->num] < bb_loop_postorder[loop2->num] ? -1 : 1;
1786 }
1787
1788 /* qsort sort function to sort ref locs after their loop fathers postorder. */
1789
1790 static int
1791 sort_locs_in_loop_postorder_cmp (const void *loc1_, const void *loc2_,
1792 void *bb_loop_postorder_)
1793 {
1794 unsigned *bb_loop_postorder = (unsigned *)bb_loop_postorder_;
1795 const mem_ref_loc *loc1 = (const mem_ref_loc *)loc1_;
1796 const mem_ref_loc *loc2 = (const mem_ref_loc *)loc2_;
1797 class loop *loop1 = gimple_bb (loc1->stmt)->loop_father;
1798 class loop *loop2 = gimple_bb (loc2->stmt)->loop_father;
1799 if (loop1->num == loop2->num)
1800 return 0;
1801 return bb_loop_postorder[loop1->num] < bb_loop_postorder[loop2->num] ? -1 : 1;
1802 }
1803
1804 /* Gathers memory references in loops. */
1805
1806 static void
1807 analyze_memory_references (bool store_motion)
1808 {
1809 gimple_stmt_iterator bsi;
1810 basic_block bb, *bbs;
1811 class loop *outer;
1812 unsigned i, n;
1813
1814 /* Collect all basic-blocks in loops and sort them after their
1815 loops postorder. */
1816 i = 0;
1817 bbs = XNEWVEC (basic_block, n_basic_blocks_for_fn (cfun) - NUM_FIXED_BLOCKS);
1818 FOR_EACH_BB_FN (bb, cfun)
1819 if (bb->loop_father != current_loops->tree_root)
1820 bbs[i++] = bb;
1821 n = i;
1822 gcc_sort_r (bbs, n, sizeof (basic_block), sort_bbs_in_loop_postorder_cmp,
1823 bb_loop_postorder);
1824
1825 /* Visit blocks in loop postorder and assign mem-ref IDs in that order.
1826 That results in better locality for all the bitmaps. It also
1827 automatically sorts the location list of gathered memory references
1828 after their loop postorder number allowing to binary-search it. */
1829 for (i = 0; i < n; ++i)
1830 {
1831 basic_block bb = bbs[i];
1832 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1833 gather_mem_refs_stmt (bb->loop_father, gsi_stmt (bsi));
1834 }
1835
1836 /* Verify the list of gathered memory references is sorted after their
1837 loop postorder number. */
1838 if (flag_checking)
1839 {
1840 im_mem_ref *ref;
1841 FOR_EACH_VEC_ELT (memory_accesses.refs_list, i, ref)
1842 for (unsigned j = 1; j < ref->accesses_in_loop.length (); ++j)
1843 gcc_assert (sort_locs_in_loop_postorder_cmp
1844 (&ref->accesses_in_loop[j-1], &ref->accesses_in_loop[j],
1845 bb_loop_postorder) <= 0);
1846 }
1847
1848 free (bbs);
1849
1850 if (!store_motion)
1851 return;
1852
1853 /* Propagate the information about accessed memory references up
1854 the loop hierarchy. */
1855 for (auto loop : loops_list (cfun, LI_FROM_INNERMOST))
1856 {
1857 /* Finalize the overall touched references (including subloops). */
1858 bitmap_ior_into (&memory_accesses.all_refs_stored_in_loop[loop->num],
1859 &memory_accesses.refs_stored_in_loop[loop->num]);
1860
1861 /* Propagate the information about accessed memory references up
1862 the loop hierarchy. */
1863 outer = loop_outer (loop);
1864 if (outer == current_loops->tree_root)
1865 continue;
1866
1867 bitmap_ior_into (&memory_accesses.all_refs_stored_in_loop[outer->num],
1868 &memory_accesses.all_refs_stored_in_loop[loop->num]);
1869 }
1870 }
1871
1872 /* Returns true if MEM1 and MEM2 may alias. TTAE_CACHE is used as a cache in
1873 tree_to_aff_combination_expand. */
1874
1875 static bool
1876 mem_refs_may_alias_p (im_mem_ref *mem1, im_mem_ref *mem2,
1877 hash_map<tree, name_expansion *> **ttae_cache,
1878 bool tbaa_p)
1879 {
1880 gcc_checking_assert (mem1->mem.ref != error_mark_node
1881 && mem2->mem.ref != error_mark_node);
1882
1883 /* Perform BASE + OFFSET analysis -- if MEM1 and MEM2 are based on the same
1884 object and their offset differ in such a way that the locations cannot
1885 overlap, then they cannot alias. */
1886 poly_widest_int size1, size2;
1887 aff_tree off1, off2;
1888
1889 /* Perform basic offset and type-based disambiguation. */
1890 if (!refs_may_alias_p_1 (&mem1->mem, &mem2->mem, tbaa_p))
1891 return false;
1892
1893 /* The expansion of addresses may be a bit expensive, thus we only do
1894 the check at -O2 and higher optimization levels. */
1895 if (optimize < 2)
1896 return true;
1897
1898 get_inner_reference_aff (mem1->mem.ref, &off1, &size1);
1899 get_inner_reference_aff (mem2->mem.ref, &off2, &size2);
1900 aff_combination_expand (&off1, ttae_cache);
1901 aff_combination_expand (&off2, ttae_cache);
1902 aff_combination_scale (&off1, -1);
1903 aff_combination_add (&off2, &off1);
1904
1905 if (aff_comb_cannot_overlap_p (&off2, size1, size2))
1906 return false;
1907
1908 return true;
1909 }
1910
1911 /* Compare function for bsearch searching for reference locations
1912 in a loop. */
1913
1914 static int
1915 find_ref_loc_in_loop_cmp (const void *loop_, const void *loc_,
1916 void *bb_loop_postorder_)
1917 {
1918 unsigned *bb_loop_postorder = (unsigned *)bb_loop_postorder_;
1919 class loop *loop = (class loop *)const_cast<void *>(loop_);
1920 mem_ref_loc *loc = (mem_ref_loc *)const_cast<void *>(loc_);
1921 class loop *loc_loop = gimple_bb (loc->stmt)->loop_father;
1922 if (loop->num == loc_loop->num
1923 || flow_loop_nested_p (loop, loc_loop))
1924 return 0;
1925 return (bb_loop_postorder[loop->num] < bb_loop_postorder[loc_loop->num]
1926 ? -1 : 1);
1927 }
1928
1929 /* Iterates over all locations of REF in LOOP and its subloops calling
1930 fn.operator() with the location as argument. When that operator
1931 returns true the iteration is stopped and true is returned.
1932 Otherwise false is returned. */
1933
1934 template <typename FN>
1935 static bool
1936 for_all_locs_in_loop (class loop *loop, im_mem_ref *ref, FN fn)
1937 {
1938 unsigned i;
1939 mem_ref_loc *loc;
1940
1941 /* Search for the cluster of locs in the accesses_in_loop vector
1942 which is sorted after postorder index of the loop father. */
1943 loc = ref->accesses_in_loop.bsearch (loop, find_ref_loc_in_loop_cmp,
1944 bb_loop_postorder);
1945 if (!loc)
1946 return false;
1947
1948 /* We have found one location inside loop or its sub-loops. Iterate
1949 both forward and backward to cover the whole cluster. */
1950 i = loc - ref->accesses_in_loop.address ();
1951 while (i > 0)
1952 {
1953 --i;
1954 mem_ref_loc *l = &ref->accesses_in_loop[i];
1955 if (!flow_bb_inside_loop_p (loop, gimple_bb (l->stmt)))
1956 break;
1957 if (fn (l))
1958 return true;
1959 }
1960 for (i = loc - ref->accesses_in_loop.address ();
1961 i < ref->accesses_in_loop.length (); ++i)
1962 {
1963 mem_ref_loc *l = &ref->accesses_in_loop[i];
1964 if (!flow_bb_inside_loop_p (loop, gimple_bb (l->stmt)))
1965 break;
1966 if (fn (l))
1967 return true;
1968 }
1969
1970 return false;
1971 }
1972
1973 /* Rewrites location LOC by TMP_VAR. */
1974
1975 class rewrite_mem_ref_loc
1976 {
1977 public:
1978 rewrite_mem_ref_loc (tree tmp_var_) : tmp_var (tmp_var_) {}
1979 bool operator () (mem_ref_loc *loc);
1980 tree tmp_var;
1981 };
1982
1983 bool
1984 rewrite_mem_ref_loc::operator () (mem_ref_loc *loc)
1985 {
1986 *loc->ref = tmp_var;
1987 update_stmt (loc->stmt);
1988 return false;
1989 }
1990
1991 /* Rewrites all references to REF in LOOP by variable TMP_VAR. */
1992
1993 static void
1994 rewrite_mem_refs (class loop *loop, im_mem_ref *ref, tree tmp_var)
1995 {
1996 for_all_locs_in_loop (loop, ref, rewrite_mem_ref_loc (tmp_var));
1997 }
1998
1999 /* Stores the first reference location in LOCP. */
2000
2001 class first_mem_ref_loc_1
2002 {
2003 public:
2004 first_mem_ref_loc_1 (mem_ref_loc **locp_) : locp (locp_) {}
2005 bool operator () (mem_ref_loc *loc);
2006 mem_ref_loc **locp;
2007 };
2008
2009 bool
2010 first_mem_ref_loc_1::operator () (mem_ref_loc *loc)
2011 {
2012 *locp = loc;
2013 return true;
2014 }
2015
2016 /* Returns the first reference location to REF in LOOP. */
2017
2018 static mem_ref_loc *
2019 first_mem_ref_loc (class loop *loop, im_mem_ref *ref)
2020 {
2021 mem_ref_loc *locp = NULL;
2022 for_all_locs_in_loop (loop, ref, first_mem_ref_loc_1 (&locp));
2023 return locp;
2024 }
2025
2026 /* Helper function for execute_sm. Emit code to store TMP_VAR into
2027 MEM along edge EX.
2028
2029 The store is only done if MEM has changed. We do this so no
2030 changes to MEM occur on code paths that did not originally store
2031 into it.
2032
2033 The common case for execute_sm will transform:
2034
2035 for (...) {
2036 if (foo)
2037 stuff;
2038 else
2039 MEM = TMP_VAR;
2040 }
2041
2042 into:
2043
2044 lsm = MEM;
2045 for (...) {
2046 if (foo)
2047 stuff;
2048 else
2049 lsm = TMP_VAR;
2050 }
2051 MEM = lsm;
2052
2053 This function will generate:
2054
2055 lsm = MEM;
2056
2057 lsm_flag = false;
2058 ...
2059 for (...) {
2060 if (foo)
2061 stuff;
2062 else {
2063 lsm = TMP_VAR;
2064 lsm_flag = true;
2065 }
2066 }
2067 if (lsm_flag) <--
2068 MEM = lsm; <-- (X)
2069
2070 In case MEM and TMP_VAR are NULL the function will return the then
2071 block so the caller can insert (X) and other related stmts.
2072 */
2073
2074 static basic_block
2075 execute_sm_if_changed (edge ex, tree mem, tree tmp_var, tree flag,
2076 edge preheader, hash_set <basic_block> *flag_bbs,
2077 edge &append_cond_position, edge &last_cond_fallthru)
2078 {
2079 basic_block new_bb, then_bb, old_dest;
2080 bool loop_has_only_one_exit;
2081 edge then_old_edge;
2082 gimple_stmt_iterator gsi;
2083 gimple *stmt;
2084 bool irr = ex->flags & EDGE_IRREDUCIBLE_LOOP;
2085
2086 profile_count count_sum = profile_count::zero ();
2087 int nbbs = 0, ncount = 0;
2088 profile_probability flag_probability = profile_probability::uninitialized ();
2089
2090 /* Flag is set in FLAG_BBS. Determine probability that flag will be true
2091 at loop exit.
2092
2093 This code may look fancy, but it cannot update profile very realistically
2094 because we do not know the probability that flag will be true at given
2095 loop exit.
2096
2097 We look for two interesting extremes
2098 - when exit is dominated by block setting the flag, we know it will
2099 always be true. This is a common case.
2100 - when all blocks setting the flag have very low frequency we know
2101 it will likely be false.
2102 In all other cases we default to 2/3 for flag being true. */
2103
2104 for (hash_set<basic_block>::iterator it = flag_bbs->begin ();
2105 it != flag_bbs->end (); ++it)
2106 {
2107 if ((*it)->count.initialized_p ())
2108 count_sum += (*it)->count, ncount ++;
2109 if (dominated_by_p (CDI_DOMINATORS, ex->src, *it))
2110 flag_probability = profile_probability::always ();
2111 nbbs++;
2112 }
2113
2114 profile_probability cap
2115 = profile_probability::guessed_always ().apply_scale (2, 3);
2116
2117 if (flag_probability.initialized_p ())
2118 ;
2119 else if (ncount == nbbs
2120 && preheader->count () >= count_sum && preheader->count ().nonzero_p ())
2121 {
2122 flag_probability = count_sum.probability_in (preheader->count ());
2123 if (flag_probability > cap)
2124 flag_probability = cap;
2125 }
2126
2127 if (!flag_probability.initialized_p ())
2128 flag_probability = cap;
2129
2130 /* ?? Insert store after previous store if applicable. See note
2131 below. */
2132 if (append_cond_position)
2133 ex = append_cond_position;
2134
2135 loop_has_only_one_exit = single_pred_p (ex->dest);
2136
2137 if (loop_has_only_one_exit)
2138 ex = split_block_after_labels (ex->dest);
2139 else
2140 {
2141 for (gphi_iterator gpi = gsi_start_phis (ex->dest);
2142 !gsi_end_p (gpi); gsi_next (&gpi))
2143 {
2144 gphi *phi = gpi.phi ();
2145 if (virtual_operand_p (gimple_phi_result (phi)))
2146 continue;
2147
2148 /* When the destination has a non-virtual PHI node with multiple
2149 predecessors make sure we preserve the PHI structure by
2150 forcing a forwarder block so that hoisting of that PHI will
2151 still work. */
2152 split_edge (ex);
2153 break;
2154 }
2155 }
2156
2157 old_dest = ex->dest;
2158 new_bb = split_edge (ex);
2159 if (append_cond_position)
2160 new_bb->count += last_cond_fallthru->count ();
2161 then_bb = create_empty_bb (new_bb);
2162 then_bb->count = new_bb->count.apply_probability (flag_probability);
2163 if (irr)
2164 then_bb->flags = BB_IRREDUCIBLE_LOOP;
2165 add_bb_to_loop (then_bb, new_bb->loop_father);
2166
2167 gsi = gsi_start_bb (new_bb);
2168 stmt = gimple_build_cond (NE_EXPR, flag, boolean_false_node,
2169 NULL_TREE, NULL_TREE);
2170 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2171
2172 /* Insert actual store. */
2173 if (mem)
2174 {
2175 gsi = gsi_start_bb (then_bb);
2176 stmt = gimple_build_assign (unshare_expr (mem), tmp_var);
2177 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2178 }
2179
2180 edge e1 = single_succ_edge (new_bb);
2181 edge e2 = make_edge (new_bb, then_bb,
2182 EDGE_TRUE_VALUE | (irr ? EDGE_IRREDUCIBLE_LOOP : 0));
2183 e2->probability = flag_probability;
2184
2185 e1->flags |= EDGE_FALSE_VALUE | (irr ? EDGE_IRREDUCIBLE_LOOP : 0);
2186 e1->flags &= ~EDGE_FALLTHRU;
2187
2188 e1->probability = flag_probability.invert ();
2189
2190 then_old_edge = make_single_succ_edge (then_bb, old_dest,
2191 EDGE_FALLTHRU | (irr ? EDGE_IRREDUCIBLE_LOOP : 0));
2192
2193 set_immediate_dominator (CDI_DOMINATORS, then_bb, new_bb);
2194
2195 if (append_cond_position)
2196 {
2197 basic_block prevbb = last_cond_fallthru->src;
2198 redirect_edge_succ (last_cond_fallthru, new_bb);
2199 set_immediate_dominator (CDI_DOMINATORS, new_bb, prevbb);
2200 set_immediate_dominator (CDI_DOMINATORS, old_dest,
2201 recompute_dominator (CDI_DOMINATORS, old_dest));
2202 }
2203
2204 /* ?? Because stores may alias, they must happen in the exact
2205 sequence they originally happened. Save the position right after
2206 the (_lsm) store we just created so we can continue appending after
2207 it and maintain the original order. */
2208 append_cond_position = then_old_edge;
2209 last_cond_fallthru = find_edge (new_bb, old_dest);
2210
2211 if (!loop_has_only_one_exit)
2212 for (gphi_iterator gpi = gsi_start_phis (old_dest);
2213 !gsi_end_p (gpi); gsi_next (&gpi))
2214 {
2215 gphi *phi = gpi.phi ();
2216 unsigned i;
2217
2218 for (i = 0; i < gimple_phi_num_args (phi); i++)
2219 if (gimple_phi_arg_edge (phi, i)->src == new_bb)
2220 {
2221 tree arg = gimple_phi_arg_def (phi, i);
2222 add_phi_arg (phi, arg, then_old_edge, UNKNOWN_LOCATION);
2223 update_stmt (phi);
2224 }
2225 }
2226
2227 return then_bb;
2228 }
2229
2230 /* When REF is set on the location, set flag indicating the store. */
2231
2232 class sm_set_flag_if_changed
2233 {
2234 public:
2235 sm_set_flag_if_changed (tree flag_, hash_set <basic_block> *bbs_)
2236 : flag (flag_), bbs (bbs_) {}
2237 bool operator () (mem_ref_loc *loc);
2238 tree flag;
2239 hash_set <basic_block> *bbs;
2240 };
2241
2242 bool
2243 sm_set_flag_if_changed::operator () (mem_ref_loc *loc)
2244 {
2245 /* Only set the flag for writes. */
2246 if (is_gimple_assign (loc->stmt)
2247 && gimple_assign_lhs_ptr (loc->stmt) == loc->ref)
2248 {
2249 gimple_stmt_iterator gsi = gsi_for_stmt (loc->stmt);
2250 gimple *stmt = gimple_build_assign (flag, boolean_true_node);
2251 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2252 bbs->add (gimple_bb (stmt));
2253 }
2254 return false;
2255 }
2256
2257 /* Helper function for execute_sm. On every location where REF is
2258 set, set an appropriate flag indicating the store. */
2259
2260 static tree
2261 execute_sm_if_changed_flag_set (class loop *loop, im_mem_ref *ref,
2262 hash_set <basic_block> *bbs)
2263 {
2264 tree flag;
2265 char *str = get_lsm_tmp_name (ref->mem.ref, ~0, "_flag");
2266 flag = create_tmp_reg (boolean_type_node, str);
2267 for_all_locs_in_loop (loop, ref, sm_set_flag_if_changed (flag, bbs));
2268 return flag;
2269 }
2270
2271 struct sm_aux
2272 {
2273 tree tmp_var;
2274 tree store_flag;
2275 hash_set <basic_block> flag_bbs;
2276 };
2277
2278 /* Executes store motion of memory reference REF from LOOP.
2279 Exits from the LOOP are stored in EXITS. The initialization of the
2280 temporary variable is put to the preheader of the loop, and assignments
2281 to the reference from the temporary variable are emitted to exits. */
2282
2283 static sm_aux *
2284 execute_sm (class loop *loop, im_mem_ref *ref,
2285 hash_map<im_mem_ref *, sm_aux *> &aux_map, bool maybe_mt,
2286 bool use_other_flag_var)
2287 {
2288 gassign *load;
2289 struct fmt_data fmt_data;
2290 struct lim_aux_data *lim_data;
2291 bool multi_threaded_model_p = false;
2292 gimple_stmt_iterator gsi;
2293 sm_aux *aux = new sm_aux;
2294
2295 if (dump_file && (dump_flags & TDF_DETAILS))
2296 {
2297 fprintf (dump_file, "Executing store motion of ");
2298 print_generic_expr (dump_file, ref->mem.ref);
2299 fprintf (dump_file, " from loop %d\n", loop->num);
2300 }
2301
2302 aux->tmp_var = create_tmp_reg (TREE_TYPE (ref->mem.ref),
2303 get_lsm_tmp_name (ref->mem.ref, ~0));
2304
2305 fmt_data.loop = loop;
2306 fmt_data.orig_loop = loop;
2307 for_each_index (&ref->mem.ref, force_move_till, &fmt_data);
2308
2309 bool always_stored = ref_always_accessed_p (loop, ref, true);
2310 if (maybe_mt
2311 && (bb_in_transaction (loop_preheader_edge (loop)->src)
2312 || (ref_can_have_store_data_races (ref->mem.ref) && ! always_stored)
2313 /* Do not speculate a load/store when that's not a noop, either
2314 because the mode cannot be transferred or because there's
2315 UB involved for out-of-bound values. */
2316 || !mode_can_transfer_bits (TYPE_MODE (TREE_TYPE (ref->mem.ref)))
2317 || TREE_CODE (TREE_TYPE (ref->mem.ref)) == BOOLEAN_TYPE
2318 || (TREE_CODE (ref->mem.ref) == COMPONENT_REF
2319 && DECL_BIT_FIELD (TREE_OPERAND (ref->mem.ref, 1)))))
2320 multi_threaded_model_p = true;
2321
2322 if (multi_threaded_model_p && !use_other_flag_var)
2323 aux->store_flag
2324 = execute_sm_if_changed_flag_set (loop, ref, &aux->flag_bbs);
2325 else
2326 aux->store_flag = NULL_TREE;
2327
2328 /* Remember variable setup. */
2329 aux_map.put (ref, aux);
2330
2331 rewrite_mem_refs (loop, ref, aux->tmp_var);
2332
2333 /* Emit the load code on a random exit edge or into the latch if
2334 the loop does not exit, so that we are sure it will be processed
2335 by move_computations after all dependencies. */
2336 gsi = gsi_for_stmt (first_mem_ref_loc (loop, ref)->stmt);
2337
2338 /* Avoid doing a load if there was no load of the ref in the loop.
2339 Esp. when the ref is not always stored we cannot optimize it
2340 away later. But when it is not always stored we must use a conditional
2341 store then. */
2342 if ((!always_stored && !multi_threaded_model_p)
2343 || (ref->loaded && bitmap_bit_p (ref->loaded, loop->num)))
2344 load = gimple_build_assign (aux->tmp_var, unshare_expr (ref->mem.ref));
2345 else
2346 {
2347 /* If not emitting a load mark the uninitialized state on the
2348 loop entry as not to be warned for. */
2349 tree uninit = create_tmp_reg (TREE_TYPE (aux->tmp_var));
2350 suppress_warning (uninit, OPT_Wuninitialized);
2351 load = gimple_build_assign (aux->tmp_var, uninit);
2352 }
2353 lim_data = init_lim_data (load);
2354 lim_data->max_loop = loop;
2355 lim_data->tgt_loop = loop;
2356 gsi_insert_before (&gsi, load, GSI_SAME_STMT);
2357
2358 if (aux->store_flag)
2359 {
2360 load = gimple_build_assign (aux->store_flag, boolean_false_node);
2361 lim_data = init_lim_data (load);
2362 lim_data->max_loop = loop;
2363 lim_data->tgt_loop = loop;
2364 gsi_insert_before (&gsi, load, GSI_SAME_STMT);
2365 }
2366
2367 return aux;
2368 }
2369
2370 /* sm_ord is used for ordinary stores we can retain order with respect
2371 to other stores
2372 sm_unord is used for conditional executed stores which need to be
2373 able to execute in arbitrary order with respect to other stores
2374 sm_other is used for stores we do not try to apply store motion to. */
2375 enum sm_kind { sm_ord, sm_unord, sm_other };
2376 struct seq_entry
2377 {
2378 seq_entry () = default;
2379 seq_entry (unsigned f, sm_kind k, tree fr = NULL)
2380 : first (f), second (k), from (fr) {}
2381 unsigned first;
2382 sm_kind second;
2383 tree from;
2384 };
2385
2386 static void
2387 execute_sm_exit (class loop *loop, edge ex, vec<seq_entry> &seq,
2388 hash_map<im_mem_ref *, sm_aux *> &aux_map, sm_kind kind,
2389 edge &append_cond_position, edge &last_cond_fallthru,
2390 bitmap clobbers_to_prune)
2391 {
2392 /* Sink the stores to exit from the loop. */
2393 for (unsigned i = seq.length (); i > 0; --i)
2394 {
2395 im_mem_ref *ref = memory_accesses.refs_list[seq[i-1].first];
2396 if (seq[i-1].second == sm_other)
2397 {
2398 gcc_assert (kind == sm_ord && seq[i-1].from != NULL_TREE);
2399 gassign *store;
2400 if (ref->mem.ref == error_mark_node)
2401 {
2402 tree lhs = gimple_assign_lhs (ref->accesses_in_loop[0].stmt);
2403 if (dump_file && (dump_flags & TDF_DETAILS))
2404 {
2405 fprintf (dump_file, "Re-issueing dependent ");
2406 print_generic_expr (dump_file, unshare_expr (seq[i-1].from));
2407 fprintf (dump_file, " of ");
2408 print_generic_expr (dump_file, lhs);
2409 fprintf (dump_file, " from loop %d on exit %d -> %d\n",
2410 loop->num, ex->src->index, ex->dest->index);
2411 }
2412 store = gimple_build_assign (unshare_expr (lhs),
2413 unshare_expr (seq[i-1].from));
2414 bitmap_set_bit (clobbers_to_prune, seq[i-1].first);
2415 }
2416 else
2417 {
2418 if (dump_file && (dump_flags & TDF_DETAILS))
2419 {
2420 fprintf (dump_file, "Re-issueing dependent store of ");
2421 print_generic_expr (dump_file, ref->mem.ref);
2422 fprintf (dump_file, " from loop %d on exit %d -> %d\n",
2423 loop->num, ex->src->index, ex->dest->index);
2424 }
2425 store = gimple_build_assign (unshare_expr (ref->mem.ref),
2426 seq[i-1].from);
2427 }
2428 gsi_insert_on_edge (ex, store);
2429 }
2430 else
2431 {
2432 sm_aux *aux = *aux_map.get (ref);
2433 if (!aux->store_flag || kind == sm_ord)
2434 {
2435 gassign *store;
2436 store = gimple_build_assign (unshare_expr (ref->mem.ref),
2437 aux->tmp_var);
2438 gsi_insert_on_edge (ex, store);
2439 }
2440 else
2441 execute_sm_if_changed (ex, ref->mem.ref, aux->tmp_var,
2442 aux->store_flag,
2443 loop_preheader_edge (loop), &aux->flag_bbs,
2444 append_cond_position, last_cond_fallthru);
2445 }
2446 }
2447 }
2448
2449 /* Push the SM candidate at index PTR in the sequence SEQ down until
2450 we hit the next SM candidate. Return true if that went OK and
2451 false if we could not disambiguate agains another unrelated ref.
2452 Update *AT to the index where the candidate now resides. */
2453
2454 static bool
2455 sm_seq_push_down (vec<seq_entry> &seq, unsigned ptr, unsigned *at)
2456 {
2457 *at = ptr;
2458 for (; ptr > 0; --ptr)
2459 {
2460 seq_entry &new_cand = seq[ptr];
2461 seq_entry &against = seq[ptr-1];
2462 if (against.second == sm_ord
2463 || (against.second == sm_other && against.from != NULL_TREE))
2464 /* Found the tail of the sequence. */
2465 break;
2466 /* We may not ignore self-dependences here. */
2467 if (new_cand.first == against.first
2468 /* ??? We could actually handle clobbers here, but not easily
2469 with LIMs dependence analysis. */
2470 || (memory_accesses.refs_list[new_cand.first]->mem.ref
2471 == error_mark_node)
2472 || (memory_accesses.refs_list[against.first]->mem.ref
2473 == error_mark_node)
2474 || !refs_independent_p (memory_accesses.refs_list[new_cand.first],
2475 memory_accesses.refs_list[against.first],
2476 false))
2477 /* ??? Prune new_cand from the list of refs to apply SM to. */
2478 return false;
2479 std::swap (new_cand, against);
2480 *at = ptr - 1;
2481 }
2482 return true;
2483 }
2484
2485 /* Computes the sequence of stores from candidates in REFS_NOT_IN_SEQ to SEQ
2486 walking backwards from VDEF (or the end of BB if VDEF is NULL). */
2487
2488 static int
2489 sm_seq_valid_bb (class loop *loop, basic_block bb, tree vdef,
2490 vec<seq_entry> &seq, bitmap refs_not_in_seq,
2491 bitmap refs_not_supported, bool forked,
2492 bitmap fully_visited)
2493 {
2494 if (!vdef)
2495 for (gimple_stmt_iterator gsi = gsi_last_bb (bb); !gsi_end_p (gsi);
2496 gsi_prev (&gsi))
2497 {
2498 vdef = gimple_vdef (gsi_stmt (gsi));
2499 if (vdef)
2500 break;
2501 }
2502 if (!vdef)
2503 {
2504 gphi *vphi = get_virtual_phi (bb);
2505 if (vphi)
2506 vdef = gimple_phi_result (vphi);
2507 }
2508 if (!vdef)
2509 {
2510 if (single_pred_p (bb))
2511 /* This handles the perfect nest case. */
2512 return sm_seq_valid_bb (loop, single_pred (bb), vdef,
2513 seq, refs_not_in_seq, refs_not_supported,
2514 forked, fully_visited);
2515 return 0;
2516 }
2517 do
2518 {
2519 gimple *def = SSA_NAME_DEF_STMT (vdef);
2520 if (gimple_bb (def) != bb)
2521 {
2522 /* If we forked by processing a PHI do not allow our walk to
2523 merge again until we handle that robustly. */
2524 if (forked)
2525 {
2526 /* Mark refs_not_in_seq as unsupported. */
2527 bitmap_ior_into (refs_not_supported, refs_not_in_seq);
2528 return 1;
2529 }
2530 /* Otherwise it doesn't really matter if we end up in different
2531 BBs. */
2532 bb = gimple_bb (def);
2533 }
2534 if (gphi *phi = dyn_cast <gphi *> (def))
2535 {
2536 /* Handle CFG merges. Until we handle forks (gimple_bb (def) != bb)
2537 this is still linear.
2538 Eventually we want to cache intermediate results per BB
2539 (but we can't easily cache for different exits?). */
2540 /* Stop at PHIs with possible backedges. */
2541 if (bb == bb->loop_father->header
2542 || bb->flags & BB_IRREDUCIBLE_LOOP)
2543 {
2544 /* Mark refs_not_in_seq as unsupported. */
2545 bitmap_ior_into (refs_not_supported, refs_not_in_seq);
2546 return 1;
2547 }
2548 if (gimple_phi_num_args (phi) == 1)
2549 return sm_seq_valid_bb (loop, gimple_phi_arg_edge (phi, 0)->src,
2550 gimple_phi_arg_def (phi, 0), seq,
2551 refs_not_in_seq, refs_not_supported,
2552 false, fully_visited);
2553 if (bitmap_bit_p (fully_visited,
2554 SSA_NAME_VERSION (gimple_phi_result (phi))))
2555 return 1;
2556 auto_vec<seq_entry> first_edge_seq;
2557 auto_bitmap tem_refs_not_in_seq (&lim_bitmap_obstack);
2558 int eret;
2559 bitmap_copy (tem_refs_not_in_seq, refs_not_in_seq);
2560 eret = sm_seq_valid_bb (loop, gimple_phi_arg_edge (phi, 0)->src,
2561 gimple_phi_arg_def (phi, 0),
2562 first_edge_seq,
2563 tem_refs_not_in_seq, refs_not_supported,
2564 true, fully_visited);
2565 if (eret != 1)
2566 return -1;
2567 /* Simplify our lives by pruning the sequence of !sm_ord. */
2568 while (!first_edge_seq.is_empty ()
2569 && first_edge_seq.last ().second != sm_ord)
2570 first_edge_seq.pop ();
2571 for (unsigned int i = 1; i < gimple_phi_num_args (phi); ++i)
2572 {
2573 tree vuse = gimple_phi_arg_def (phi, i);
2574 edge e = gimple_phi_arg_edge (phi, i);
2575 auto_vec<seq_entry> edge_seq;
2576 bitmap_and_compl (tem_refs_not_in_seq,
2577 refs_not_in_seq, refs_not_supported);
2578 /* If we've marked all refs we search for as unsupported
2579 we can stop processing and use the sequence as before
2580 the PHI. */
2581 if (bitmap_empty_p (tem_refs_not_in_seq))
2582 return 1;
2583 eret = sm_seq_valid_bb (loop, e->src, vuse, edge_seq,
2584 tem_refs_not_in_seq, refs_not_supported,
2585 true, fully_visited);
2586 if (eret != 1)
2587 return -1;
2588 /* Simplify our lives by pruning the sequence of !sm_ord. */
2589 while (!edge_seq.is_empty ()
2590 && edge_seq.last ().second != sm_ord)
2591 edge_seq.pop ();
2592 unsigned min_len = MIN(first_edge_seq.length (),
2593 edge_seq.length ());
2594 /* Incrementally merge seqs into first_edge_seq. */
2595 int first_uneq = -1;
2596 auto_vec<seq_entry, 2> extra_refs;
2597 for (unsigned int i = 0; i < min_len; ++i)
2598 {
2599 /* ??? We can more intelligently merge when we face different
2600 order by additional sinking operations in one sequence.
2601 For now we simply mark them as to be processed by the
2602 not order-preserving SM code. */
2603 if (first_edge_seq[i].first != edge_seq[i].first)
2604 {
2605 if (first_edge_seq[i].second == sm_ord)
2606 bitmap_set_bit (refs_not_supported,
2607 first_edge_seq[i].first);
2608 if (edge_seq[i].second == sm_ord)
2609 bitmap_set_bit (refs_not_supported, edge_seq[i].first);
2610 first_edge_seq[i].second = sm_other;
2611 first_edge_seq[i].from = NULL_TREE;
2612 /* Record the dropped refs for later processing. */
2613 if (first_uneq == -1)
2614 first_uneq = i;
2615 extra_refs.safe_push (seq_entry (edge_seq[i].first,
2616 sm_other, NULL_TREE));
2617 }
2618 /* sm_other prevails. */
2619 else if (first_edge_seq[i].second != edge_seq[i].second)
2620 {
2621 /* Make sure the ref is marked as not supported. */
2622 bitmap_set_bit (refs_not_supported,
2623 first_edge_seq[i].first);
2624 first_edge_seq[i].second = sm_other;
2625 first_edge_seq[i].from = NULL_TREE;
2626 }
2627 else if (first_edge_seq[i].second == sm_other
2628 && first_edge_seq[i].from != NULL_TREE
2629 && (edge_seq[i].from == NULL_TREE
2630 || !operand_equal_p (first_edge_seq[i].from,
2631 edge_seq[i].from, 0)))
2632 first_edge_seq[i].from = NULL_TREE;
2633 }
2634 /* Any excess elements become sm_other since they are now
2635 coonditionally executed. */
2636 if (first_edge_seq.length () > edge_seq.length ())
2637 {
2638 for (unsigned i = edge_seq.length ();
2639 i < first_edge_seq.length (); ++i)
2640 {
2641 if (first_edge_seq[i].second == sm_ord)
2642 bitmap_set_bit (refs_not_supported,
2643 first_edge_seq[i].first);
2644 first_edge_seq[i].second = sm_other;
2645 }
2646 }
2647 else if (edge_seq.length () > first_edge_seq.length ())
2648 {
2649 if (first_uneq == -1)
2650 first_uneq = first_edge_seq.length ();
2651 for (unsigned i = first_edge_seq.length ();
2652 i < edge_seq.length (); ++i)
2653 {
2654 if (edge_seq[i].second == sm_ord)
2655 bitmap_set_bit (refs_not_supported, edge_seq[i].first);
2656 extra_refs.safe_push (seq_entry (edge_seq[i].first,
2657 sm_other, NULL_TREE));
2658 }
2659 }
2660 /* Put unmerged refs at first_uneq to force dependence checking
2661 on them. */
2662 if (first_uneq != -1)
2663 {
2664 /* Missing ordered_splice_at. */
2665 if ((unsigned)first_uneq == first_edge_seq.length ())
2666 first_edge_seq.safe_splice (extra_refs);
2667 else
2668 {
2669 unsigned fes_length = first_edge_seq.length ();
2670 first_edge_seq.safe_grow (fes_length
2671 + extra_refs.length ());
2672 memmove (&first_edge_seq[first_uneq + extra_refs.length ()],
2673 &first_edge_seq[first_uneq],
2674 (fes_length - first_uneq) * sizeof (seq_entry));
2675 memcpy (&first_edge_seq[first_uneq],
2676 extra_refs.address (),
2677 extra_refs.length () * sizeof (seq_entry));
2678 }
2679 }
2680 }
2681 /* Use the sequence from the first edge and push SMs down. */
2682 for (unsigned i = 0; i < first_edge_seq.length (); ++i)
2683 {
2684 unsigned id = first_edge_seq[i].first;
2685 seq.safe_push (first_edge_seq[i]);
2686 unsigned new_idx;
2687 if ((first_edge_seq[i].second == sm_ord
2688 || (first_edge_seq[i].second == sm_other
2689 && first_edge_seq[i].from != NULL_TREE))
2690 && !sm_seq_push_down (seq, seq.length () - 1, &new_idx))
2691 {
2692 if (first_edge_seq[i].second == sm_ord)
2693 bitmap_set_bit (refs_not_supported, id);
2694 /* Mark it sm_other. */
2695 seq[new_idx].second = sm_other;
2696 seq[new_idx].from = NULL_TREE;
2697 }
2698 }
2699 bitmap_set_bit (fully_visited,
2700 SSA_NAME_VERSION (gimple_phi_result (phi)));
2701 return 1;
2702 }
2703 lim_aux_data *data = get_lim_data (def);
2704 im_mem_ref *ref = memory_accesses.refs_list[data->ref];
2705 if (data->ref == UNANALYZABLE_MEM_ID)
2706 return -1;
2707 /* Stop at memory references which we can't move. */
2708 else if ((ref->mem.ref == error_mark_node
2709 /* We can move end-of-storage/object down. */
2710 && !gimple_clobber_p (ref->accesses_in_loop[0].stmt,
2711 CLOBBER_STORAGE_END)
2712 && !gimple_clobber_p (ref->accesses_in_loop[0].stmt,
2713 CLOBBER_OBJECT_END))
2714 || TREE_THIS_VOLATILE (ref->mem.ref))
2715 {
2716 /* Mark refs_not_in_seq as unsupported. */
2717 bitmap_ior_into (refs_not_supported, refs_not_in_seq);
2718 return 1;
2719 }
2720 /* One of the stores we want to apply SM to and we've not yet seen. */
2721 else if (bitmap_clear_bit (refs_not_in_seq, data->ref))
2722 {
2723 seq.safe_push (seq_entry (data->ref, sm_ord));
2724
2725 /* 1) push it down the queue until a SMed
2726 and not ignored ref is reached, skipping all not SMed refs
2727 and ignored refs via non-TBAA disambiguation. */
2728 unsigned new_idx;
2729 if (!sm_seq_push_down (seq, seq.length () - 1, &new_idx)
2730 /* If that fails but we did not fork yet continue, we'll see
2731 to re-materialize all of the stores in the sequence then.
2732 Further stores will only be pushed up to this one. */
2733 && forked)
2734 {
2735 bitmap_set_bit (refs_not_supported, data->ref);
2736 /* Mark it sm_other. */
2737 seq[new_idx].second = sm_other;
2738 }
2739
2740 /* 2) check whether we've seen all refs we want to SM and if so
2741 declare success for the active exit */
2742 if (bitmap_empty_p (refs_not_in_seq))
2743 return 1;
2744 }
2745 else
2746 /* Another store not part of the final sequence. Simply push it. */
2747 seq.safe_push (seq_entry (data->ref, sm_other,
2748 gimple_assign_rhs1 (def)));
2749
2750 vdef = gimple_vuse (def);
2751 }
2752 while (1);
2753 }
2754
2755 /* Hoists memory references MEM_REFS out of LOOP. EXITS is the list of exit
2756 edges of the LOOP. */
2757
2758 static void
2759 hoist_memory_references (class loop *loop, bitmap mem_refs,
2760 const vec<edge> &exits)
2761 {
2762 im_mem_ref *ref;
2763 unsigned i;
2764 bitmap_iterator bi;
2765
2766 /* There's a special case we can use ordered re-materialization for
2767 conditionally excuted stores which is when all stores in the loop
2768 happen in the same basic-block. In that case we know we'll reach
2769 all stores and thus can simply process that BB and emit a single
2770 conditional block of ordered materializations. See PR102436. */
2771 basic_block single_store_bb = NULL;
2772 EXECUTE_IF_SET_IN_BITMAP (&memory_accesses.all_refs_stored_in_loop[loop->num],
2773 0, i, bi)
2774 {
2775 bool fail = false;
2776 ref = memory_accesses.refs_list[i];
2777 for (auto loc : ref->accesses_in_loop)
2778 if (!gimple_vdef (loc.stmt))
2779 ;
2780 else if (!single_store_bb)
2781 {
2782 single_store_bb = gimple_bb (loc.stmt);
2783 bool conditional = false;
2784 for (edge e : exits)
2785 if (!dominated_by_p (CDI_DOMINATORS, e->src, single_store_bb))
2786 {
2787 /* Conditional as seen from e. */
2788 conditional = true;
2789 break;
2790 }
2791 if (!conditional)
2792 {
2793 fail = true;
2794 break;
2795 }
2796 }
2797 else if (single_store_bb != gimple_bb (loc.stmt))
2798 {
2799 fail = true;
2800 break;
2801 }
2802 if (fail)
2803 {
2804 single_store_bb = NULL;
2805 break;
2806 }
2807 }
2808 if (single_store_bb)
2809 {
2810 /* Analyze the single block with stores. */
2811 auto_bitmap fully_visited;
2812 auto_bitmap refs_not_supported;
2813 auto_bitmap refs_not_in_seq;
2814 auto_vec<seq_entry> seq;
2815 bitmap_copy (refs_not_in_seq, mem_refs);
2816 int res = sm_seq_valid_bb (loop, single_store_bb, NULL_TREE,
2817 seq, refs_not_in_seq, refs_not_supported,
2818 false, fully_visited);
2819 if (res != 1)
2820 {
2821 /* Unhandled refs can still fail this. */
2822 bitmap_clear (mem_refs);
2823 return;
2824 }
2825
2826 /* We cannot handle sm_other since we neither remember the
2827 stored location nor the value at the point we execute them. */
2828 for (unsigned i = 0; i < seq.length (); ++i)
2829 {
2830 unsigned new_i;
2831 if (seq[i].second == sm_other
2832 && seq[i].from != NULL_TREE)
2833 seq[i].from = NULL_TREE;
2834 else if ((seq[i].second == sm_ord
2835 || (seq[i].second == sm_other
2836 && seq[i].from != NULL_TREE))
2837 && !sm_seq_push_down (seq, i, &new_i))
2838 {
2839 bitmap_set_bit (refs_not_supported, seq[new_i].first);
2840 seq[new_i].second = sm_other;
2841 seq[new_i].from = NULL_TREE;
2842 }
2843 }
2844 bitmap_and_compl_into (mem_refs, refs_not_supported);
2845 if (bitmap_empty_p (mem_refs))
2846 return;
2847
2848 /* Prune seq. */
2849 while (seq.last ().second == sm_other
2850 && seq.last ().from == NULL_TREE)
2851 seq.pop ();
2852
2853 hash_map<im_mem_ref *, sm_aux *> aux_map;
2854
2855 /* Execute SM but delay the store materialization for ordered
2856 sequences on exit. Remember a created flag var and make
2857 sure to re-use it. */
2858 sm_aux *flag_var_aux = nullptr;
2859 EXECUTE_IF_SET_IN_BITMAP (mem_refs, 0, i, bi)
2860 {
2861 ref = memory_accesses.refs_list[i];
2862 sm_aux *aux = execute_sm (loop, ref, aux_map, true,
2863 flag_var_aux != nullptr);
2864 if (aux->store_flag)
2865 flag_var_aux = aux;
2866 }
2867
2868 /* Materialize ordered store sequences on exits. */
2869 edge e;
2870 auto_bitmap clobbers_to_prune;
2871 FOR_EACH_VEC_ELT (exits, i, e)
2872 {
2873 edge append_cond_position = NULL;
2874 edge last_cond_fallthru = NULL;
2875 edge insert_e = e;
2876 /* Construct the single flag variable control flow and insert
2877 the ordered seq of stores in the then block. With
2878 -fstore-data-races we can do the stores unconditionally. */
2879 if (flag_var_aux)
2880 insert_e
2881 = single_pred_edge
2882 (execute_sm_if_changed (e, NULL_TREE, NULL_TREE,
2883 flag_var_aux->store_flag,
2884 loop_preheader_edge (loop),
2885 &flag_var_aux->flag_bbs,
2886 append_cond_position,
2887 last_cond_fallthru));
2888 execute_sm_exit (loop, insert_e, seq, aux_map, sm_ord,
2889 append_cond_position, last_cond_fallthru,
2890 clobbers_to_prune);
2891 gsi_commit_one_edge_insert (insert_e, NULL);
2892 }
2893
2894 /* Remove clobbers inside the loop we re-materialized on exits. */
2895 EXECUTE_IF_SET_IN_BITMAP (clobbers_to_prune, 0, i, bi)
2896 {
2897 gimple *stmt = memory_accesses.refs_list[i]->accesses_in_loop[0].stmt;
2898 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
2899 unlink_stmt_vdef (stmt);
2900 release_defs (stmt);
2901 gimple_set_vdef (stmt, NULL_TREE);
2902 gsi_remove (&gsi, true);
2903 }
2904
2905 for (hash_map<im_mem_ref *, sm_aux *>::iterator iter = aux_map.begin ();
2906 iter != aux_map.end (); ++iter)
2907 delete (*iter).second;
2908
2909 return;
2910 }
2911
2912 /* To address PR57359 before actually applying store-motion check
2913 the candidates found for validity with regards to reordering
2914 relative to other stores which we until here disambiguated using
2915 TBAA which isn't valid.
2916 What matters is the order of the last stores to the mem_refs
2917 with respect to the other stores of the loop at the point of the
2918 loop exits. */
2919
2920 /* For each exit compute the store order, pruning from mem_refs
2921 on the fly. */
2922 /* The complexity of this is at least
2923 O(number of exits * number of SM refs) but more approaching
2924 O(number of exits * number of SM refs * number of stores). */
2925 /* ??? Somehow do this in a single sweep over the loop body. */
2926 auto_vec<std::pair<edge, vec<seq_entry> > > sms;
2927 auto_bitmap refs_not_supported (&lim_bitmap_obstack);
2928 edge e;
2929 FOR_EACH_VEC_ELT (exits, i, e)
2930 {
2931 vec<seq_entry> seq;
2932 seq.create (4);
2933 auto_bitmap refs_not_in_seq (&lim_bitmap_obstack);
2934 bitmap_and_compl (refs_not_in_seq, mem_refs, refs_not_supported);
2935 if (bitmap_empty_p (refs_not_in_seq))
2936 {
2937 seq.release ();
2938 break;
2939 }
2940 auto_bitmap fully_visited;
2941 int res = sm_seq_valid_bb (loop, e->src, NULL_TREE,
2942 seq, refs_not_in_seq,
2943 refs_not_supported, false,
2944 fully_visited);
2945 if (res != 1)
2946 {
2947 bitmap_copy (refs_not_supported, mem_refs);
2948 seq.release ();
2949 break;
2950 }
2951 sms.safe_push (std::make_pair (e, seq));
2952 }
2953
2954 /* Prune pruned mem_refs from earlier processed exits. */
2955 bool changed = !bitmap_empty_p (refs_not_supported);
2956 while (changed)
2957 {
2958 changed = false;
2959 std::pair<edge, vec<seq_entry> > *seq;
2960 FOR_EACH_VEC_ELT (sms, i, seq)
2961 {
2962 bool need_to_push = false;
2963 for (unsigned i = 0; i < seq->second.length (); ++i)
2964 {
2965 sm_kind kind = seq->second[i].second;
2966 if (kind == sm_other && seq->second[i].from == NULL_TREE)
2967 break;
2968 unsigned id = seq->second[i].first;
2969 unsigned new_idx;
2970 if (kind == sm_ord
2971 && bitmap_bit_p (refs_not_supported, id))
2972 {
2973 seq->second[i].second = sm_other;
2974 gcc_assert (seq->second[i].from == NULL_TREE);
2975 need_to_push = true;
2976 }
2977 else if (need_to_push
2978 && !sm_seq_push_down (seq->second, i, &new_idx))
2979 {
2980 /* We need to push down both sm_ord and sm_other
2981 but for the latter we need to disqualify all
2982 following refs. */
2983 if (kind == sm_ord)
2984 {
2985 if (bitmap_set_bit (refs_not_supported, id))
2986 changed = true;
2987 seq->second[new_idx].second = sm_other;
2988 }
2989 else
2990 {
2991 for (unsigned j = seq->second.length () - 1;
2992 j > new_idx; --j)
2993 if (seq->second[j].second == sm_ord
2994 && bitmap_set_bit (refs_not_supported,
2995 seq->second[j].first))
2996 changed = true;
2997 seq->second.truncate (new_idx);
2998 break;
2999 }
3000 }
3001 }
3002 }
3003 }
3004 std::pair<edge, vec<seq_entry> > *seq;
3005 FOR_EACH_VEC_ELT (sms, i, seq)
3006 {
3007 /* Prune sm_other from the end. */
3008 while (!seq->second.is_empty ()
3009 && seq->second.last ().second == sm_other)
3010 seq->second.pop ();
3011 /* Prune duplicates from the start. */
3012 auto_bitmap seen (&lim_bitmap_obstack);
3013 unsigned j, k;
3014 for (j = k = 0; j < seq->second.length (); ++j)
3015 if (bitmap_set_bit (seen, seq->second[j].first))
3016 {
3017 if (k != j)
3018 seq->second[k] = seq->second[j];
3019 ++k;
3020 }
3021 seq->second.truncate (k);
3022 /* And verify. */
3023 seq_entry *e;
3024 FOR_EACH_VEC_ELT (seq->second, j, e)
3025 gcc_assert (e->second == sm_ord
3026 || (e->second == sm_other && e->from != NULL_TREE));
3027 }
3028
3029 /* Verify dependence for refs we cannot handle with the order preserving
3030 code (refs_not_supported) or prune them from mem_refs. */
3031 auto_vec<seq_entry> unord_refs;
3032 EXECUTE_IF_SET_IN_BITMAP (refs_not_supported, 0, i, bi)
3033 {
3034 ref = memory_accesses.refs_list[i];
3035 if (!ref_indep_loop_p (loop, ref, sm_waw))
3036 bitmap_clear_bit (mem_refs, i);
3037 /* We've now verified store order for ref with respect to all other
3038 stores in the loop does not matter. */
3039 else
3040 unord_refs.safe_push (seq_entry (i, sm_unord));
3041 }
3042
3043 hash_map<im_mem_ref *, sm_aux *> aux_map;
3044
3045 /* Execute SM but delay the store materialization for ordered
3046 sequences on exit. */
3047 EXECUTE_IF_SET_IN_BITMAP (mem_refs, 0, i, bi)
3048 {
3049 ref = memory_accesses.refs_list[i];
3050 execute_sm (loop, ref, aux_map, bitmap_bit_p (refs_not_supported, i),
3051 false);
3052 }
3053
3054 /* Materialize ordered store sequences on exits. */
3055 auto_bitmap clobbers_to_prune;
3056 FOR_EACH_VEC_ELT (exits, i, e)
3057 {
3058 edge append_cond_position = NULL;
3059 edge last_cond_fallthru = NULL;
3060 if (i < sms.length ())
3061 {
3062 gcc_assert (sms[i].first == e);
3063 execute_sm_exit (loop, e, sms[i].second, aux_map, sm_ord,
3064 append_cond_position, last_cond_fallthru,
3065 clobbers_to_prune);
3066 sms[i].second.release ();
3067 }
3068 if (!unord_refs.is_empty ())
3069 execute_sm_exit (loop, e, unord_refs, aux_map, sm_unord,
3070 append_cond_position, last_cond_fallthru,
3071 clobbers_to_prune);
3072 /* Commit edge inserts here to preserve the order of stores
3073 when an exit exits multiple loops. */
3074 gsi_commit_one_edge_insert (e, NULL);
3075 }
3076
3077 /* Remove clobbers inside the loop we re-materialized on exits. */
3078 EXECUTE_IF_SET_IN_BITMAP (clobbers_to_prune, 0, i, bi)
3079 {
3080 gimple *stmt = memory_accesses.refs_list[i]->accesses_in_loop[0].stmt;
3081 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
3082 unlink_stmt_vdef (stmt);
3083 release_defs (stmt);
3084 gimple_set_vdef (stmt, NULL_TREE);
3085 gsi_remove (&gsi, true);
3086 }
3087
3088 for (hash_map<im_mem_ref *, sm_aux *>::iterator iter = aux_map.begin ();
3089 iter != aux_map.end (); ++iter)
3090 delete (*iter).second;
3091 }
3092
3093 class ref_always_accessed
3094 {
3095 public:
3096 ref_always_accessed (class loop *loop_, bool stored_p_)
3097 : loop (loop_), stored_p (stored_p_) {}
3098 bool operator () (mem_ref_loc *loc);
3099 class loop *loop;
3100 bool stored_p;
3101 };
3102
3103 bool
3104 ref_always_accessed::operator () (mem_ref_loc *loc)
3105 {
3106 class loop *must_exec;
3107
3108 struct lim_aux_data *lim_data = get_lim_data (loc->stmt);
3109 if (!lim_data)
3110 return false;
3111
3112 /* If we require an always executed store make sure the statement
3113 is a store. */
3114 if (stored_p)
3115 {
3116 tree lhs = gimple_get_lhs (loc->stmt);
3117 if (!lhs
3118 || !(DECL_P (lhs) || REFERENCE_CLASS_P (lhs)))
3119 return false;
3120 }
3121
3122 must_exec = lim_data->always_executed_in;
3123 if (!must_exec)
3124 return false;
3125
3126 if (must_exec == loop
3127 || flow_loop_nested_p (must_exec, loop))
3128 return true;
3129
3130 return false;
3131 }
3132
3133 /* Returns true if REF is always accessed in LOOP. If STORED_P is true
3134 make sure REF is always stored to in LOOP. */
3135
3136 static bool
3137 ref_always_accessed_p (class loop *loop, im_mem_ref *ref, bool stored_p)
3138 {
3139 return for_all_locs_in_loop (loop, ref,
3140 ref_always_accessed (loop, stored_p));
3141 }
3142
3143 /* Returns true if REF1 and REF2 are independent. */
3144
3145 static bool
3146 refs_independent_p (im_mem_ref *ref1, im_mem_ref *ref2, bool tbaa_p)
3147 {
3148 if (ref1 == ref2)
3149 return true;
3150
3151 if (dump_file && (dump_flags & TDF_DETAILS))
3152 fprintf (dump_file, "Querying dependency of refs %u and %u: ",
3153 ref1->id, ref2->id);
3154
3155 if (mem_refs_may_alias_p (ref1, ref2, &memory_accesses.ttae_cache, tbaa_p))
3156 {
3157 if (dump_file && (dump_flags & TDF_DETAILS))
3158 fprintf (dump_file, "dependent.\n");
3159 return false;
3160 }
3161 else
3162 {
3163 if (dump_file && (dump_flags & TDF_DETAILS))
3164 fprintf (dump_file, "independent.\n");
3165 return true;
3166 }
3167 }
3168
3169 /* Returns true if REF is independent on all other accessess in LOOP.
3170 KIND specifies the kind of dependence to consider.
3171 lim_raw assumes REF is not stored in LOOP and disambiguates RAW
3172 dependences so if true REF can be hoisted out of LOOP
3173 sm_war disambiguates a store REF against all other loads to see
3174 whether the store can be sunk across loads out of LOOP
3175 sm_waw disambiguates a store REF against all other stores to see
3176 whether the store can be sunk across stores out of LOOP. */
3177
3178 static bool
3179 ref_indep_loop_p (class loop *loop, im_mem_ref *ref, dep_kind kind)
3180 {
3181 bool indep_p = true;
3182 bitmap refs_to_check;
3183
3184 if (kind == sm_war)
3185 refs_to_check = &memory_accesses.refs_loaded_in_loop[loop->num];
3186 else
3187 refs_to_check = &memory_accesses.refs_stored_in_loop[loop->num];
3188
3189 if (bitmap_bit_p (refs_to_check, UNANALYZABLE_MEM_ID)
3190 || ref->mem.ref == error_mark_node)
3191 indep_p = false;
3192 else
3193 {
3194 /* tri-state, { unknown, independent, dependent } */
3195 dep_state state = query_loop_dependence (loop, ref, kind);
3196 if (state != dep_unknown)
3197 return state == dep_independent ? true : false;
3198
3199 class loop *inner = loop->inner;
3200 while (inner)
3201 {
3202 if (!ref_indep_loop_p (inner, ref, kind))
3203 {
3204 indep_p = false;
3205 break;
3206 }
3207 inner = inner->next;
3208 }
3209
3210 if (indep_p)
3211 {
3212 unsigned i;
3213 bitmap_iterator bi;
3214 EXECUTE_IF_SET_IN_BITMAP (refs_to_check, 0, i, bi)
3215 {
3216 im_mem_ref *aref = memory_accesses.refs_list[i];
3217 if (aref->mem.ref == error_mark_node)
3218 {
3219 gimple *stmt = aref->accesses_in_loop[0].stmt;
3220 if ((kind == sm_war
3221 && ref_maybe_used_by_stmt_p (stmt, &ref->mem,
3222 kind != sm_waw))
3223 || stmt_may_clobber_ref_p_1 (stmt, &ref->mem,
3224 kind != sm_waw))
3225 {
3226 indep_p = false;
3227 break;
3228 }
3229 }
3230 else if (!refs_independent_p (ref, aref, kind != sm_waw))
3231 {
3232 indep_p = false;
3233 break;
3234 }
3235 }
3236 }
3237 }
3238
3239 if (dump_file && (dump_flags & TDF_DETAILS))
3240 fprintf (dump_file, "Querying %s dependencies of ref %u in loop %d: %s\n",
3241 kind == lim_raw ? "RAW" : (kind == sm_war ? "SM WAR" : "SM WAW"),
3242 ref->id, loop->num, indep_p ? "independent" : "dependent");
3243
3244 /* Record the computed result in the cache. */
3245 record_loop_dependence (loop, ref, kind,
3246 indep_p ? dep_independent : dep_dependent);
3247
3248 return indep_p;
3249 }
3250
3251 class ref_in_loop_hot_body
3252 {
3253 public:
3254 ref_in_loop_hot_body (class loop *loop_) : l (loop_) {}
3255 bool operator () (mem_ref_loc *loc);
3256 class loop *l;
3257 };
3258
3259 /* Check the coldest loop between loop L and innermost loop. If there is one
3260 cold loop between L and INNER_LOOP, store motion can be performed, otherwise
3261 no cold loop means no store motion. get_coldest_out_loop also handles cases
3262 when l is inner_loop. */
3263 bool
3264 ref_in_loop_hot_body::operator () (mem_ref_loc *loc)
3265 {
3266 basic_block curr_bb = gimple_bb (loc->stmt);
3267 class loop *inner_loop = curr_bb->loop_father;
3268 return get_coldest_out_loop (l, inner_loop, curr_bb);
3269 }
3270
3271
3272 /* Returns true if we can perform store motion of REF from LOOP. */
3273
3274 static bool
3275 can_sm_ref_p (class loop *loop, im_mem_ref *ref)
3276 {
3277 tree base;
3278
3279 /* Can't hoist unanalyzable refs. */
3280 if (!MEM_ANALYZABLE (ref))
3281 return false;
3282
3283 /* Can't hoist/sink aggregate copies. */
3284 if (ref->mem.ref == error_mark_node)
3285 return false;
3286
3287 /* It should be movable. */
3288 if (!is_gimple_reg_type (TREE_TYPE (ref->mem.ref))
3289 || TREE_THIS_VOLATILE (ref->mem.ref)
3290 || !for_each_index (&ref->mem.ref, may_move_till, loop))
3291 return false;
3292
3293 /* If it can throw fail, we do not properly update EH info. */
3294 if (tree_could_throw_p (ref->mem.ref))
3295 return false;
3296
3297 /* If it can trap, it must be always executed in LOOP.
3298 Readonly memory locations may trap when storing to them, but
3299 tree_could_trap_p is a predicate for rvalues, so check that
3300 explicitly. */
3301 base = get_base_address (ref->mem.ref);
3302 if ((tree_could_trap_p (ref->mem.ref)
3303 || (DECL_P (base) && TREE_READONLY (base))
3304 || TREE_CODE (base) == STRING_CST)
3305 /* ??? We can at least use false here, allowing loads? We
3306 are forcing conditional stores if the ref is not always
3307 stored to later anyway. So this would only guard
3308 the load we need to emit. Thus when the ref is not
3309 loaded we can elide this completely? */
3310 && !ref_always_accessed_p (loop, ref, true))
3311 return false;
3312
3313 /* Verify all loads of ref can be hoisted. */
3314 if (ref->loaded
3315 && bitmap_bit_p (ref->loaded, loop->num)
3316 && !ref_indep_loop_p (loop, ref, lim_raw))
3317 return false;
3318
3319 /* Verify the candidate can be disambiguated against all loads,
3320 that is, we can elide all in-loop stores. Disambiguation
3321 against stores is done later when we cannot guarantee preserving
3322 the order of stores. */
3323 if (!ref_indep_loop_p (loop, ref, sm_war))
3324 return false;
3325
3326 /* Verify whether the candidate is hot for LOOP. Only do store motion if the
3327 candidate's profile count is hot. Statement in cold BB shouldn't be moved
3328 out of it's loop_father. */
3329 if (!for_all_locs_in_loop (loop, ref, ref_in_loop_hot_body (loop)))
3330 return false;
3331
3332 return true;
3333 }
3334
3335 /* Marks the references in LOOP for that store motion should be performed
3336 in REFS_TO_SM. SM_EXECUTED is the set of references for that store
3337 motion was performed in one of the outer loops. */
3338
3339 static void
3340 find_refs_for_sm (class loop *loop, bitmap sm_executed, bitmap refs_to_sm)
3341 {
3342 bitmap refs = &memory_accesses.all_refs_stored_in_loop[loop->num];
3343 unsigned i;
3344 bitmap_iterator bi;
3345 im_mem_ref *ref;
3346
3347 EXECUTE_IF_AND_COMPL_IN_BITMAP (refs, sm_executed, 0, i, bi)
3348 {
3349 ref = memory_accesses.refs_list[i];
3350 if (can_sm_ref_p (loop, ref) && dbg_cnt (lim))
3351 bitmap_set_bit (refs_to_sm, i);
3352 }
3353 }
3354
3355 /* Checks whether LOOP (with exits stored in EXITS array) is suitable
3356 for a store motion optimization (i.e. whether we can insert statement
3357 on its exits). */
3358
3359 static bool
3360 loop_suitable_for_sm (class loop *loop ATTRIBUTE_UNUSED,
3361 const vec<edge> &exits)
3362 {
3363 unsigned i;
3364 edge ex;
3365
3366 FOR_EACH_VEC_ELT (exits, i, ex)
3367 if (ex->flags & (EDGE_ABNORMAL | EDGE_EH))
3368 return false;
3369
3370 return true;
3371 }
3372
3373 /* Try to perform store motion for all memory references modified inside
3374 LOOP. SM_EXECUTED is the bitmap of the memory references for that
3375 store motion was executed in one of the outer loops. */
3376
3377 static void
3378 store_motion_loop (class loop *loop, bitmap sm_executed)
3379 {
3380 auto_vec<edge> exits = get_loop_exit_edges (loop);
3381 class loop *subloop;
3382 bitmap sm_in_loop = BITMAP_ALLOC (&lim_bitmap_obstack);
3383
3384 if (loop_suitable_for_sm (loop, exits))
3385 {
3386 find_refs_for_sm (loop, sm_executed, sm_in_loop);
3387 if (!bitmap_empty_p (sm_in_loop))
3388 hoist_memory_references (loop, sm_in_loop, exits);
3389 }
3390
3391 bitmap_ior_into (sm_executed, sm_in_loop);
3392 for (subloop = loop->inner; subloop != NULL; subloop = subloop->next)
3393 store_motion_loop (subloop, sm_executed);
3394 bitmap_and_compl_into (sm_executed, sm_in_loop);
3395 BITMAP_FREE (sm_in_loop);
3396 }
3397
3398 /* Try to perform store motion for all memory references modified inside
3399 loops. */
3400
3401 static void
3402 do_store_motion (void)
3403 {
3404 class loop *loop;
3405 bitmap sm_executed = BITMAP_ALLOC (&lim_bitmap_obstack);
3406
3407 for (loop = current_loops->tree_root->inner; loop != NULL; loop = loop->next)
3408 store_motion_loop (loop, sm_executed);
3409
3410 BITMAP_FREE (sm_executed);
3411 }
3412
3413 /* Fills ALWAYS_EXECUTED_IN information for basic blocks of LOOP, i.e.
3414 for each such basic block bb records the outermost loop for that execution
3415 of its header implies execution of bb. CONTAINS_CALL is the bitmap of
3416 blocks that contain a nonpure call. */
3417
3418 static void
3419 fill_always_executed_in_1 (class loop *loop, sbitmap contains_call)
3420 {
3421 basic_block bb = NULL, last = NULL;
3422 edge e;
3423 class loop *inn_loop = loop;
3424
3425 for (class loop *inner = loop->inner; inner; inner = inner->next)
3426 fill_always_executed_in_1 (inner, contains_call);
3427
3428 auto_vec<basic_block, 64> worklist;
3429 worklist.reserve_exact (loop->num_nodes);
3430 worklist.quick_push (loop->header);
3431 do
3432 {
3433 edge_iterator ei;
3434 bb = worklist.pop ();
3435
3436 if (!flow_bb_inside_loop_p (inn_loop, bb))
3437 {
3438 /* When we are leaving a possibly infinite inner loop
3439 we have to stop processing. */
3440 if (!finite_loop_p (inn_loop))
3441 break;
3442 /* If the loop was finite we can continue with processing
3443 the loop we exited to. */
3444 inn_loop = bb->loop_father;
3445 }
3446
3447 if (dominated_by_p (CDI_DOMINATORS, loop->latch, bb))
3448 last = bb;
3449
3450 if (bitmap_bit_p (contains_call, bb->index))
3451 break;
3452
3453 /* If LOOP exits from this BB stop processing. */
3454 FOR_EACH_EDGE (e, ei, bb->succs)
3455 if (!flow_bb_inside_loop_p (loop, e->dest))
3456 break;
3457 if (e)
3458 break;
3459
3460 /* A loop might be infinite (TODO use simple loop analysis
3461 to disprove this if possible). */
3462 if (bb->flags & BB_IRREDUCIBLE_LOOP)
3463 break;
3464
3465 if (bb->loop_father->header == bb)
3466 /* Record that we enter into a subloop since it might not
3467 be finite. */
3468 /* ??? Entering into a not always executed subloop makes
3469 fill_always_executed_in quadratic in loop depth since
3470 we walk those loops N times. This is not a problem
3471 in practice though, see PR102253 for a worst-case testcase. */
3472 inn_loop = bb->loop_father;
3473
3474 /* Walk the body of LOOP sorted by dominance relation. Additionally,
3475 if a basic block S dominates the latch, then only blocks dominated
3476 by S are after it.
3477 This is get_loop_body_in_dom_order using a worklist algorithm and
3478 stopping once we are no longer interested in visiting further
3479 blocks. */
3480 unsigned old_len = worklist.length ();
3481 unsigned postpone = 0;
3482 for (basic_block son = first_dom_son (CDI_DOMINATORS, bb);
3483 son;
3484 son = next_dom_son (CDI_DOMINATORS, son))
3485 {
3486 if (!flow_bb_inside_loop_p (loop, son))
3487 continue;
3488 if (dominated_by_p (CDI_DOMINATORS, loop->latch, son))
3489 postpone = worklist.length ();
3490 worklist.quick_push (son);
3491 }
3492 if (postpone)
3493 /* Postponing the block that dominates the latch means
3494 processing it last and thus putting it earliest in the
3495 worklist. */
3496 std::swap (worklist[old_len], worklist[postpone]);
3497 }
3498 while (!worklist.is_empty ());
3499
3500 while (1)
3501 {
3502 if (last->loop_father == loop
3503 || (ALWAYS_EXECUTED_IN (last)
3504 && loop_outer (ALWAYS_EXECUTED_IN (last)) == loop))
3505 {
3506 if (dump_enabled_p ())
3507 dump_printf (MSG_NOTE, "BB %d is always executed in loop %d\n",
3508 last->index, loop->num);
3509 SET_ALWAYS_EXECUTED_IN (last, loop);
3510 }
3511 if (last == loop->header)
3512 break;
3513 last = get_immediate_dominator (CDI_DOMINATORS, last);
3514 }
3515 }
3516
3517 /* Fills ALWAYS_EXECUTED_IN information for basic blocks, i.e.
3518 for each such basic block bb records the outermost loop for that execution
3519 of its header implies execution of bb. */
3520
3521 static void
3522 fill_always_executed_in (void)
3523 {
3524 basic_block bb;
3525 class loop *loop;
3526
3527 auto_sbitmap contains_call (last_basic_block_for_fn (cfun));
3528 bitmap_clear (contains_call);
3529 FOR_EACH_BB_FN (bb, cfun)
3530 {
3531 gimple_stmt_iterator gsi;
3532 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3533 {
3534 if (nonpure_call_p (gsi_stmt (gsi)))
3535 break;
3536 }
3537
3538 if (!gsi_end_p (gsi))
3539 bitmap_set_bit (contains_call, bb->index);
3540 }
3541
3542 for (loop = current_loops->tree_root->inner; loop; loop = loop->next)
3543 fill_always_executed_in_1 (loop, contains_call);
3544 }
3545
3546 /* Find the coldest loop preheader for LOOP, also find the nearest hotter loop
3547 to LOOP. Then recursively iterate each inner loop. */
3548
3549 void
3550 fill_coldest_and_hotter_out_loop (class loop *coldest_loop,
3551 class loop *hotter_loop, class loop *loop)
3552 {
3553 if (bb_colder_than_loop_preheader (loop_preheader_edge (loop)->src,
3554 coldest_loop))
3555 coldest_loop = loop;
3556
3557 coldest_outermost_loop[loop->num] = coldest_loop;
3558
3559 hotter_than_inner_loop[loop->num] = NULL;
3560 class loop *outer_loop = loop_outer (loop);
3561 if (hotter_loop
3562 && bb_colder_than_loop_preheader (loop_preheader_edge (loop)->src,
3563 hotter_loop))
3564 hotter_than_inner_loop[loop->num] = hotter_loop;
3565
3566 if (outer_loop && outer_loop != current_loops->tree_root
3567 && bb_colder_than_loop_preheader (loop_preheader_edge (loop)->src,
3568 outer_loop))
3569 hotter_than_inner_loop[loop->num] = outer_loop;
3570
3571 if (dump_enabled_p ())
3572 {
3573 dump_printf (MSG_NOTE, "loop %d's coldest_outermost_loop is %d, ",
3574 loop->num, coldest_loop->num);
3575 if (hotter_than_inner_loop[loop->num])
3576 dump_printf (MSG_NOTE, "hotter_than_inner_loop is %d\n",
3577 hotter_than_inner_loop[loop->num]->num);
3578 else
3579 dump_printf (MSG_NOTE, "hotter_than_inner_loop is NULL\n");
3580 }
3581
3582 class loop *inner_loop;
3583 for (inner_loop = loop->inner; inner_loop; inner_loop = inner_loop->next)
3584 fill_coldest_and_hotter_out_loop (coldest_loop,
3585 hotter_than_inner_loop[loop->num],
3586 inner_loop);
3587 }
3588
3589 /* Compute the global information needed by the loop invariant motion pass. */
3590
3591 static void
3592 tree_ssa_lim_initialize (bool store_motion)
3593 {
3594 unsigned i;
3595
3596 bitmap_obstack_initialize (&lim_bitmap_obstack);
3597 gcc_obstack_init (&mem_ref_obstack);
3598 lim_aux_data_map = new hash_map<gimple *, lim_aux_data *>;
3599
3600 if (flag_tm)
3601 compute_transaction_bits ();
3602
3603 memory_accesses.refs = new hash_table<mem_ref_hasher> (100);
3604 memory_accesses.refs_list.create (100);
3605 /* Allocate a special, unanalyzable mem-ref with ID zero. */
3606 memory_accesses.refs_list.quick_push
3607 (mem_ref_alloc (NULL, 0, UNANALYZABLE_MEM_ID));
3608
3609 memory_accesses.refs_loaded_in_loop.create (number_of_loops (cfun));
3610 memory_accesses.refs_loaded_in_loop.quick_grow_cleared (number_of_loops (cfun));
3611 memory_accesses.refs_stored_in_loop.create (number_of_loops (cfun));
3612 memory_accesses.refs_stored_in_loop.quick_grow_cleared (number_of_loops (cfun));
3613 if (store_motion)
3614 {
3615 memory_accesses.all_refs_stored_in_loop.create (number_of_loops (cfun));
3616 memory_accesses.all_refs_stored_in_loop.quick_grow_cleared
3617 (number_of_loops (cfun));
3618 }
3619
3620 for (i = 0; i < number_of_loops (cfun); i++)
3621 {
3622 bitmap_initialize (&memory_accesses.refs_loaded_in_loop[i],
3623 &lim_bitmap_obstack);
3624 bitmap_initialize (&memory_accesses.refs_stored_in_loop[i],
3625 &lim_bitmap_obstack);
3626 if (store_motion)
3627 bitmap_initialize (&memory_accesses.all_refs_stored_in_loop[i],
3628 &lim_bitmap_obstack);
3629 }
3630
3631 memory_accesses.ttae_cache = NULL;
3632
3633 /* Initialize bb_loop_postorder with a mapping from loop->num to
3634 its postorder index. */
3635 i = 0;
3636 bb_loop_postorder = XNEWVEC (unsigned, number_of_loops (cfun));
3637 for (auto loop : loops_list (cfun, LI_FROM_INNERMOST))
3638 bb_loop_postorder[loop->num] = i++;
3639 }
3640
3641 /* Cleans up after the invariant motion pass. */
3642
3643 static void
3644 tree_ssa_lim_finalize (void)
3645 {
3646 basic_block bb;
3647 unsigned i;
3648 im_mem_ref *ref;
3649
3650 FOR_EACH_BB_FN (bb, cfun)
3651 SET_ALWAYS_EXECUTED_IN (bb, NULL);
3652
3653 bitmap_obstack_release (&lim_bitmap_obstack);
3654 delete lim_aux_data_map;
3655
3656 delete memory_accesses.refs;
3657 memory_accesses.refs = NULL;
3658
3659 FOR_EACH_VEC_ELT (memory_accesses.refs_list, i, ref)
3660 memref_free (ref);
3661 memory_accesses.refs_list.release ();
3662 obstack_free (&mem_ref_obstack, NULL);
3663
3664 memory_accesses.refs_loaded_in_loop.release ();
3665 memory_accesses.refs_stored_in_loop.release ();
3666 memory_accesses.all_refs_stored_in_loop.release ();
3667
3668 if (memory_accesses.ttae_cache)
3669 free_affine_expand_cache (&memory_accesses.ttae_cache);
3670
3671 free (bb_loop_postorder);
3672
3673 coldest_outermost_loop.release ();
3674 hotter_than_inner_loop.release ();
3675 }
3676
3677 /* Moves invariants from loops. Only "expensive" invariants are moved out --
3678 i.e. those that are likely to be win regardless of the register pressure.
3679 Only perform store motion if STORE_MOTION is true. */
3680
3681 unsigned int
3682 loop_invariant_motion_in_fun (function *fun, bool store_motion)
3683 {
3684 unsigned int todo = 0;
3685
3686 tree_ssa_lim_initialize (store_motion);
3687
3688 mark_ssa_maybe_undefs ();
3689
3690 /* Gathers information about memory accesses in the loops. */
3691 analyze_memory_references (store_motion);
3692
3693 /* Fills ALWAYS_EXECUTED_IN information for basic blocks. */
3694 fill_always_executed_in ();
3695
3696 /* Pre-compute coldest outermost loop and nearest hotter loop of each loop.
3697 */
3698 class loop *loop;
3699 coldest_outermost_loop.create (number_of_loops (cfun));
3700 coldest_outermost_loop.safe_grow_cleared (number_of_loops (cfun));
3701 hotter_than_inner_loop.create (number_of_loops (cfun));
3702 hotter_than_inner_loop.safe_grow_cleared (number_of_loops (cfun));
3703 for (loop = current_loops->tree_root->inner; loop != NULL; loop = loop->next)
3704 fill_coldest_and_hotter_out_loop (loop, NULL, loop);
3705
3706 int *rpo = XNEWVEC (int, last_basic_block_for_fn (fun));
3707 int n = pre_and_rev_post_order_compute_fn (fun, NULL, rpo, false);
3708
3709 /* For each statement determine the outermost loop in that it is
3710 invariant and cost for computing the invariant. */
3711 for (int i = 0; i < n; ++i)
3712 compute_invariantness (BASIC_BLOCK_FOR_FN (fun, rpo[i]));
3713
3714 /* Execute store motion. Force the necessary invariants to be moved
3715 out of the loops as well. */
3716 if (store_motion)
3717 do_store_motion ();
3718
3719 free (rpo);
3720 rpo = XNEWVEC (int, last_basic_block_for_fn (fun));
3721 n = pre_and_rev_post_order_compute_fn (fun, NULL, rpo, false);
3722
3723 /* Move the expressions that are expensive enough. */
3724 for (int i = 0; i < n; ++i)
3725 todo |= move_computations_worker (BASIC_BLOCK_FOR_FN (fun, rpo[i]));
3726
3727 free (rpo);
3728
3729 gsi_commit_edge_inserts ();
3730 if (need_ssa_update_p (fun))
3731 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
3732
3733 tree_ssa_lim_finalize ();
3734
3735 return todo;
3736 }
3737
3738 /* Loop invariant motion pass. */
3739
3740 namespace {
3741
3742 const pass_data pass_data_lim =
3743 {
3744 GIMPLE_PASS, /* type */
3745 "lim", /* name */
3746 OPTGROUP_LOOP, /* optinfo_flags */
3747 TV_LIM, /* tv_id */
3748 PROP_cfg, /* properties_required */
3749 0, /* properties_provided */
3750 0, /* properties_destroyed */
3751 0, /* todo_flags_start */
3752 0, /* todo_flags_finish */
3753 };
3754
3755 class pass_lim : public gimple_opt_pass
3756 {
3757 public:
3758 pass_lim (gcc::context *ctxt)
3759 : gimple_opt_pass (pass_data_lim, ctxt)
3760 {}
3761
3762 /* opt_pass methods: */
3763 opt_pass * clone () final override { return new pass_lim (m_ctxt); }
3764 bool gate (function *) final override { return flag_tree_loop_im != 0; }
3765 unsigned int execute (function *) final override;
3766
3767 }; // class pass_lim
3768
3769 unsigned int
3770 pass_lim::execute (function *fun)
3771 {
3772 bool in_loop_pipeline = scev_initialized_p ();
3773 if (!in_loop_pipeline)
3774 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
3775
3776 if (number_of_loops (fun) <= 1)
3777 return 0;
3778 unsigned int todo = loop_invariant_motion_in_fun (fun, flag_move_loop_stores);
3779
3780 if (!in_loop_pipeline)
3781 loop_optimizer_finalize ();
3782 else
3783 scev_reset ();
3784 return todo;
3785 }
3786
3787 } // anon namespace
3788
3789 gimple_opt_pass *
3790 make_pass_lim (gcc::context *ctxt)
3791 {
3792 return new pass_lim (ctxt);
3793 }
3794
3795