]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/tree-ssa-loop-im.c
alias.c: Reorder #include statements and remove duplicates.
[thirdparty/gcc.git] / gcc / tree-ssa-loop-im.c
1 /* Loop invariant motion.
2 Copyright (C) 2003-2015 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 "hard-reg-set.h"
25 #include "tree.h"
26 #include "gimple.h"
27 #include "cfghooks.h"
28 #include "tree-pass.h"
29 #include "tm_p.h"
30 #include "ssa.h"
31 #include "gimple-pretty-print.h"
32 #include "alias.h"
33 #include "fold-const.h"
34 #include "cfganal.h"
35 #include "internal-fn.h"
36 #include "tree-eh.h"
37 #include "gimplify.h"
38 #include "gimple-iterator.h"
39 #include "tree-cfg.h"
40 #include "tree-ssa-loop-manip.h"
41 #include "tree-ssa-loop.h"
42 #include "tree-into-ssa.h"
43 #include "cfgloop.h"
44 #include "domwalk.h"
45 #include "params.h"
46 #include "flags.h"
47 #include "tree-affine.h"
48 #include "tree-ssa-propagate.h"
49 #include "trans-mem.h"
50 #include "gimple-fold.h"
51
52 /* TODO: Support for predicated code motion. I.e.
53
54 while (1)
55 {
56 if (cond)
57 {
58 a = inv;
59 something;
60 }
61 }
62
63 Where COND and INV are invariants, but evaluating INV may trap or be
64 invalid from some other reason if !COND. This may be transformed to
65
66 if (cond)
67 a = inv;
68 while (1)
69 {
70 if (cond)
71 something;
72 } */
73
74 /* The auxiliary data kept for each statement. */
75
76 struct lim_aux_data
77 {
78 struct loop *max_loop; /* The outermost loop in that the statement
79 is invariant. */
80
81 struct loop *tgt_loop; /* The loop out of that we want to move the
82 invariant. */
83
84 struct loop *always_executed_in;
85 /* The outermost loop for that we are sure
86 the statement is executed if the loop
87 is entered. */
88
89 unsigned cost; /* Cost of the computation performed by the
90 statement. */
91
92 vec<gimple *> depends; /* Vector of statements that must be also
93 hoisted out of the loop when this statement
94 is hoisted; i.e. those that define the
95 operands of the statement and are inside of
96 the MAX_LOOP loop. */
97 };
98
99 /* Maps statements to their lim_aux_data. */
100
101 static hash_map<gimple *, lim_aux_data *> *lim_aux_data_map;
102
103 /* Description of a memory reference location. */
104
105 struct mem_ref_loc
106 {
107 tree *ref; /* The reference itself. */
108 gimple *stmt; /* The statement in that it occurs. */
109 };
110
111
112 /* Description of a memory reference. */
113
114 struct im_mem_ref
115 {
116 unsigned id; /* ID assigned to the memory reference
117 (its index in memory_accesses.refs_list) */
118 hashval_t hash; /* Its hash value. */
119
120 /* The memory access itself and associated caching of alias-oracle
121 query meta-data. */
122 ao_ref mem;
123
124 bitmap stored; /* The set of loops in that this memory location
125 is stored to. */
126 vec<mem_ref_loc> accesses_in_loop;
127 /* The locations of the accesses. Vector
128 indexed by the loop number. */
129
130 /* The following sets are computed on demand. We keep both set and
131 its complement, so that we know whether the information was
132 already computed or not. */
133 bitmap_head indep_loop; /* The set of loops in that the memory
134 reference is independent, meaning:
135 If it is stored in the loop, this store
136 is independent on all other loads and
137 stores.
138 If it is only loaded, then it is independent
139 on all stores in the loop. */
140 bitmap_head dep_loop; /* The complement of INDEP_LOOP. */
141 };
142
143 /* We use two bits per loop in the ref->{in,}dep_loop bitmaps, the first
144 to record (in)dependence against stores in the loop and its subloops, the
145 second to record (in)dependence against all references in the loop
146 and its subloops. */
147 #define LOOP_DEP_BIT(loopnum, storedp) (2 * (loopnum) + (storedp ? 1 : 0))
148
149 /* Mem_ref hashtable helpers. */
150
151 struct mem_ref_hasher : nofree_ptr_hash <im_mem_ref>
152 {
153 typedef tree_node *compare_type;
154 static inline hashval_t hash (const im_mem_ref *);
155 static inline bool equal (const im_mem_ref *, const tree_node *);
156 };
157
158 /* A hash function for struct im_mem_ref object OBJ. */
159
160 inline hashval_t
161 mem_ref_hasher::hash (const im_mem_ref *mem)
162 {
163 return mem->hash;
164 }
165
166 /* An equality function for struct im_mem_ref object MEM1 with
167 memory reference OBJ2. */
168
169 inline bool
170 mem_ref_hasher::equal (const im_mem_ref *mem1, const tree_node *obj2)
171 {
172 return operand_equal_p (mem1->mem.ref, (const_tree) obj2, 0);
173 }
174
175
176 /* Description of memory accesses in loops. */
177
178 static struct
179 {
180 /* The hash table of memory references accessed in loops. */
181 hash_table<mem_ref_hasher> *refs;
182
183 /* The list of memory references. */
184 vec<im_mem_ref *> refs_list;
185
186 /* The set of memory references accessed in each loop. */
187 vec<bitmap_head> refs_in_loop;
188
189 /* The set of memory references stored in each loop. */
190 vec<bitmap_head> refs_stored_in_loop;
191
192 /* The set of memory references stored in each loop, including subloops . */
193 vec<bitmap_head> all_refs_stored_in_loop;
194
195 /* Cache for expanding memory addresses. */
196 hash_map<tree, name_expansion *> *ttae_cache;
197 } memory_accesses;
198
199 /* Obstack for the bitmaps in the above data structures. */
200 static bitmap_obstack lim_bitmap_obstack;
201 static obstack mem_ref_obstack;
202
203 static bool ref_indep_loop_p (struct loop *, im_mem_ref *);
204
205 /* Minimum cost of an expensive expression. */
206 #define LIM_EXPENSIVE ((unsigned) PARAM_VALUE (PARAM_LIM_EXPENSIVE))
207
208 /* The outermost loop for which execution of the header guarantees that the
209 block will be executed. */
210 #define ALWAYS_EXECUTED_IN(BB) ((struct loop *) (BB)->aux)
211 #define SET_ALWAYS_EXECUTED_IN(BB, VAL) ((BB)->aux = (void *) (VAL))
212
213 /* ID of the shared unanalyzable mem. */
214 #define UNANALYZABLE_MEM_ID 0
215
216 /* Whether the reference was analyzable. */
217 #define MEM_ANALYZABLE(REF) ((REF)->id != UNANALYZABLE_MEM_ID)
218
219 static struct lim_aux_data *
220 init_lim_data (gimple *stmt)
221 {
222 lim_aux_data *p = XCNEW (struct lim_aux_data);
223 lim_aux_data_map->put (stmt, p);
224
225 return p;
226 }
227
228 static struct lim_aux_data *
229 get_lim_data (gimple *stmt)
230 {
231 lim_aux_data **p = lim_aux_data_map->get (stmt);
232 if (!p)
233 return NULL;
234
235 return *p;
236 }
237
238 /* Releases the memory occupied by DATA. */
239
240 static void
241 free_lim_aux_data (struct lim_aux_data *data)
242 {
243 data->depends.release ();
244 free (data);
245 }
246
247 static void
248 clear_lim_data (gimple *stmt)
249 {
250 lim_aux_data **p = lim_aux_data_map->get (stmt);
251 if (!p)
252 return;
253
254 free_lim_aux_data (*p);
255 *p = NULL;
256 }
257
258
259 /* The possibilities of statement movement. */
260 enum move_pos
261 {
262 MOVE_IMPOSSIBLE, /* No movement -- side effect expression. */
263 MOVE_PRESERVE_EXECUTION, /* Must not cause the non-executed statement
264 become executed -- memory accesses, ... */
265 MOVE_POSSIBLE /* Unlimited movement. */
266 };
267
268
269 /* If it is possible to hoist the statement STMT unconditionally,
270 returns MOVE_POSSIBLE.
271 If it is possible to hoist the statement STMT, but we must avoid making
272 it executed if it would not be executed in the original program (e.g.
273 because it may trap), return MOVE_PRESERVE_EXECUTION.
274 Otherwise return MOVE_IMPOSSIBLE. */
275
276 enum move_pos
277 movement_possibility (gimple *stmt)
278 {
279 tree lhs;
280 enum move_pos ret = MOVE_POSSIBLE;
281
282 if (flag_unswitch_loops
283 && gimple_code (stmt) == GIMPLE_COND)
284 {
285 /* If we perform unswitching, force the operands of the invariant
286 condition to be moved out of the loop. */
287 return MOVE_POSSIBLE;
288 }
289
290 if (gimple_code (stmt) == GIMPLE_PHI
291 && gimple_phi_num_args (stmt) <= 2
292 && !virtual_operand_p (gimple_phi_result (stmt))
293 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (gimple_phi_result (stmt)))
294 return MOVE_POSSIBLE;
295
296 if (gimple_get_lhs (stmt) == NULL_TREE)
297 return MOVE_IMPOSSIBLE;
298
299 if (gimple_vdef (stmt))
300 return MOVE_IMPOSSIBLE;
301
302 if (stmt_ends_bb_p (stmt)
303 || gimple_has_volatile_ops (stmt)
304 || gimple_has_side_effects (stmt)
305 || stmt_could_throw_p (stmt))
306 return MOVE_IMPOSSIBLE;
307
308 if (is_gimple_call (stmt))
309 {
310 /* While pure or const call is guaranteed to have no side effects, we
311 cannot move it arbitrarily. Consider code like
312
313 char *s = something ();
314
315 while (1)
316 {
317 if (s)
318 t = strlen (s);
319 else
320 t = 0;
321 }
322
323 Here the strlen call cannot be moved out of the loop, even though
324 s is invariant. In addition to possibly creating a call with
325 invalid arguments, moving out a function call that is not executed
326 may cause performance regressions in case the call is costly and
327 not executed at all. */
328 ret = MOVE_PRESERVE_EXECUTION;
329 lhs = gimple_call_lhs (stmt);
330 }
331 else if (is_gimple_assign (stmt))
332 lhs = gimple_assign_lhs (stmt);
333 else
334 return MOVE_IMPOSSIBLE;
335
336 if (TREE_CODE (lhs) == SSA_NAME
337 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
338 return MOVE_IMPOSSIBLE;
339
340 if (TREE_CODE (lhs) != SSA_NAME
341 || gimple_could_trap_p (stmt))
342 return MOVE_PRESERVE_EXECUTION;
343
344 /* Non local loads in a transaction cannot be hoisted out. Well,
345 unless the load happens on every path out of the loop, but we
346 don't take this into account yet. */
347 if (flag_tm
348 && gimple_in_transaction (stmt)
349 && gimple_assign_single_p (stmt))
350 {
351 tree rhs = gimple_assign_rhs1 (stmt);
352 if (DECL_P (rhs) && is_global_var (rhs))
353 {
354 if (dump_file)
355 {
356 fprintf (dump_file, "Cannot hoist conditional load of ");
357 print_generic_expr (dump_file, rhs, TDF_SLIM);
358 fprintf (dump_file, " because it is in a transaction.\n");
359 }
360 return MOVE_IMPOSSIBLE;
361 }
362 }
363
364 return ret;
365 }
366
367 /* Suppose that operand DEF is used inside the LOOP. Returns the outermost
368 loop to that we could move the expression using DEF if it did not have
369 other operands, i.e. the outermost loop enclosing LOOP in that the value
370 of DEF is invariant. */
371
372 static struct loop *
373 outermost_invariant_loop (tree def, struct loop *loop)
374 {
375 gimple *def_stmt;
376 basic_block def_bb;
377 struct loop *max_loop;
378 struct lim_aux_data *lim_data;
379
380 if (!def)
381 return superloop_at_depth (loop, 1);
382
383 if (TREE_CODE (def) != SSA_NAME)
384 {
385 gcc_assert (is_gimple_min_invariant (def));
386 return superloop_at_depth (loop, 1);
387 }
388
389 def_stmt = SSA_NAME_DEF_STMT (def);
390 def_bb = gimple_bb (def_stmt);
391 if (!def_bb)
392 return superloop_at_depth (loop, 1);
393
394 max_loop = find_common_loop (loop, def_bb->loop_father);
395
396 lim_data = get_lim_data (def_stmt);
397 if (lim_data != NULL && lim_data->max_loop != NULL)
398 max_loop = find_common_loop (max_loop,
399 loop_outer (lim_data->max_loop));
400 if (max_loop == loop)
401 return NULL;
402 max_loop = superloop_at_depth (loop, loop_depth (max_loop) + 1);
403
404 return max_loop;
405 }
406
407 /* DATA is a structure containing information associated with a statement
408 inside LOOP. DEF is one of the operands of this statement.
409
410 Find the outermost loop enclosing LOOP in that value of DEF is invariant
411 and record this in DATA->max_loop field. If DEF itself is defined inside
412 this loop as well (i.e. we need to hoist it out of the loop if we want
413 to hoist the statement represented by DATA), record the statement in that
414 DEF is defined to the DATA->depends list. Additionally if ADD_COST is true,
415 add the cost of the computation of DEF to the DATA->cost.
416
417 If DEF is not invariant in LOOP, return false. Otherwise return TRUE. */
418
419 static bool
420 add_dependency (tree def, struct lim_aux_data *data, struct loop *loop,
421 bool add_cost)
422 {
423 gimple *def_stmt = SSA_NAME_DEF_STMT (def);
424 basic_block def_bb = gimple_bb (def_stmt);
425 struct loop *max_loop;
426 struct lim_aux_data *def_data;
427
428 if (!def_bb)
429 return true;
430
431 max_loop = outermost_invariant_loop (def, loop);
432 if (!max_loop)
433 return false;
434
435 if (flow_loop_nested_p (data->max_loop, max_loop))
436 data->max_loop = max_loop;
437
438 def_data = get_lim_data (def_stmt);
439 if (!def_data)
440 return true;
441
442 if (add_cost
443 /* Only add the cost if the statement defining DEF is inside LOOP,
444 i.e. if it is likely that by moving the invariants dependent
445 on it, we will be able to avoid creating a new register for
446 it (since it will be only used in these dependent invariants). */
447 && def_bb->loop_father == loop)
448 data->cost += def_data->cost;
449
450 data->depends.safe_push (def_stmt);
451
452 return true;
453 }
454
455 /* Returns an estimate for a cost of statement STMT. The values here
456 are just ad-hoc constants, similar to costs for inlining. */
457
458 static unsigned
459 stmt_cost (gimple *stmt)
460 {
461 /* Always try to create possibilities for unswitching. */
462 if (gimple_code (stmt) == GIMPLE_COND
463 || gimple_code (stmt) == GIMPLE_PHI)
464 return LIM_EXPENSIVE;
465
466 /* We should be hoisting calls if possible. */
467 if (is_gimple_call (stmt))
468 {
469 tree fndecl;
470
471 /* Unless the call is a builtin_constant_p; this always folds to a
472 constant, so moving it is useless. */
473 fndecl = gimple_call_fndecl (stmt);
474 if (fndecl
475 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
476 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CONSTANT_P)
477 return 0;
478
479 return LIM_EXPENSIVE;
480 }
481
482 /* Hoisting memory references out should almost surely be a win. */
483 if (gimple_references_memory_p (stmt))
484 return LIM_EXPENSIVE;
485
486 if (gimple_code (stmt) != GIMPLE_ASSIGN)
487 return 1;
488
489 switch (gimple_assign_rhs_code (stmt))
490 {
491 case MULT_EXPR:
492 case WIDEN_MULT_EXPR:
493 case WIDEN_MULT_PLUS_EXPR:
494 case WIDEN_MULT_MINUS_EXPR:
495 case DOT_PROD_EXPR:
496 case FMA_EXPR:
497 case TRUNC_DIV_EXPR:
498 case CEIL_DIV_EXPR:
499 case FLOOR_DIV_EXPR:
500 case ROUND_DIV_EXPR:
501 case EXACT_DIV_EXPR:
502 case CEIL_MOD_EXPR:
503 case FLOOR_MOD_EXPR:
504 case ROUND_MOD_EXPR:
505 case TRUNC_MOD_EXPR:
506 case RDIV_EXPR:
507 /* Division and multiplication are usually expensive. */
508 return LIM_EXPENSIVE;
509
510 case LSHIFT_EXPR:
511 case RSHIFT_EXPR:
512 case WIDEN_LSHIFT_EXPR:
513 case LROTATE_EXPR:
514 case RROTATE_EXPR:
515 /* Shifts and rotates are usually expensive. */
516 return LIM_EXPENSIVE;
517
518 case CONSTRUCTOR:
519 /* Make vector construction cost proportional to the number
520 of elements. */
521 return CONSTRUCTOR_NELTS (gimple_assign_rhs1 (stmt));
522
523 case SSA_NAME:
524 case PAREN_EXPR:
525 /* Whether or not something is wrapped inside a PAREN_EXPR
526 should not change move cost. Nor should an intermediate
527 unpropagated SSA name copy. */
528 return 0;
529
530 default:
531 return 1;
532 }
533 }
534
535 /* Finds the outermost loop between OUTER and LOOP in that the memory reference
536 REF is independent. If REF is not independent in LOOP, NULL is returned
537 instead. */
538
539 static struct loop *
540 outermost_indep_loop (struct loop *outer, struct loop *loop, im_mem_ref *ref)
541 {
542 struct loop *aloop;
543
544 if (ref->stored && bitmap_bit_p (ref->stored, loop->num))
545 return NULL;
546
547 for (aloop = outer;
548 aloop != loop;
549 aloop = superloop_at_depth (loop, loop_depth (aloop) + 1))
550 if ((!ref->stored || !bitmap_bit_p (ref->stored, aloop->num))
551 && ref_indep_loop_p (aloop, ref))
552 return aloop;
553
554 if (ref_indep_loop_p (loop, ref))
555 return loop;
556 else
557 return NULL;
558 }
559
560 /* If there is a simple load or store to a memory reference in STMT, returns
561 the location of the memory reference, and sets IS_STORE according to whether
562 it is a store or load. Otherwise, returns NULL. */
563
564 static tree *
565 simple_mem_ref_in_stmt (gimple *stmt, bool *is_store)
566 {
567 tree *lhs, *rhs;
568
569 /* Recognize SSA_NAME = MEM and MEM = (SSA_NAME | invariant) patterns. */
570 if (!gimple_assign_single_p (stmt))
571 return NULL;
572
573 lhs = gimple_assign_lhs_ptr (stmt);
574 rhs = gimple_assign_rhs1_ptr (stmt);
575
576 if (TREE_CODE (*lhs) == SSA_NAME && gimple_vuse (stmt))
577 {
578 *is_store = false;
579 return rhs;
580 }
581 else if (gimple_vdef (stmt)
582 && (TREE_CODE (*rhs) == SSA_NAME || is_gimple_min_invariant (*rhs)))
583 {
584 *is_store = true;
585 return lhs;
586 }
587 else
588 return NULL;
589 }
590
591 /* Returns the memory reference contained in STMT. */
592
593 static im_mem_ref *
594 mem_ref_in_stmt (gimple *stmt)
595 {
596 bool store;
597 tree *mem = simple_mem_ref_in_stmt (stmt, &store);
598 hashval_t hash;
599 im_mem_ref *ref;
600
601 if (!mem)
602 return NULL;
603 gcc_assert (!store);
604
605 hash = iterative_hash_expr (*mem, 0);
606 ref = memory_accesses.refs->find_with_hash (*mem, hash);
607
608 gcc_assert (ref != NULL);
609 return ref;
610 }
611
612 /* From a controlling predicate in DOM determine the arguments from
613 the PHI node PHI that are chosen if the predicate evaluates to
614 true and false and store them to *TRUE_ARG_P and *FALSE_ARG_P if
615 they are non-NULL. Returns true if the arguments can be determined,
616 else return false. */
617
618 static bool
619 extract_true_false_args_from_phi (basic_block dom, gphi *phi,
620 tree *true_arg_p, tree *false_arg_p)
621 {
622 edge te, fe;
623 if (! extract_true_false_controlled_edges (dom, gimple_bb (phi),
624 &te, &fe))
625 return false;
626
627 if (true_arg_p)
628 *true_arg_p = PHI_ARG_DEF (phi, te->dest_idx);
629 if (false_arg_p)
630 *false_arg_p = PHI_ARG_DEF (phi, fe->dest_idx);
631
632 return true;
633 }
634
635 /* Determine the outermost loop to that it is possible to hoist a statement
636 STMT and store it to LIM_DATA (STMT)->max_loop. To do this we determine
637 the outermost loop in that the value computed by STMT is invariant.
638 If MUST_PRESERVE_EXEC is true, additionally choose such a loop that
639 we preserve the fact whether STMT is executed. It also fills other related
640 information to LIM_DATA (STMT).
641
642 The function returns false if STMT cannot be hoisted outside of the loop it
643 is defined in, and true otherwise. */
644
645 static bool
646 determine_max_movement (gimple *stmt, bool must_preserve_exec)
647 {
648 basic_block bb = gimple_bb (stmt);
649 struct loop *loop = bb->loop_father;
650 struct loop *level;
651 struct lim_aux_data *lim_data = get_lim_data (stmt);
652 tree val;
653 ssa_op_iter iter;
654
655 if (must_preserve_exec)
656 level = ALWAYS_EXECUTED_IN (bb);
657 else
658 level = superloop_at_depth (loop, 1);
659 lim_data->max_loop = level;
660
661 if (gphi *phi = dyn_cast <gphi *> (stmt))
662 {
663 use_operand_p use_p;
664 unsigned min_cost = UINT_MAX;
665 unsigned total_cost = 0;
666 struct lim_aux_data *def_data;
667
668 /* We will end up promoting dependencies to be unconditionally
669 evaluated. For this reason the PHI cost (and thus the
670 cost we remove from the loop by doing the invariant motion)
671 is that of the cheapest PHI argument dependency chain. */
672 FOR_EACH_PHI_ARG (use_p, phi, iter, SSA_OP_USE)
673 {
674 val = USE_FROM_PTR (use_p);
675
676 if (TREE_CODE (val) != SSA_NAME)
677 {
678 /* Assign const 1 to constants. */
679 min_cost = MIN (min_cost, 1);
680 total_cost += 1;
681 continue;
682 }
683 if (!add_dependency (val, lim_data, loop, false))
684 return false;
685
686 gimple *def_stmt = SSA_NAME_DEF_STMT (val);
687 if (gimple_bb (def_stmt)
688 && gimple_bb (def_stmt)->loop_father == loop)
689 {
690 def_data = get_lim_data (def_stmt);
691 if (def_data)
692 {
693 min_cost = MIN (min_cost, def_data->cost);
694 total_cost += def_data->cost;
695 }
696 }
697 }
698
699 min_cost = MIN (min_cost, total_cost);
700 lim_data->cost += min_cost;
701
702 if (gimple_phi_num_args (phi) > 1)
703 {
704 basic_block dom = get_immediate_dominator (CDI_DOMINATORS, bb);
705 gimple *cond;
706 if (gsi_end_p (gsi_last_bb (dom)))
707 return false;
708 cond = gsi_stmt (gsi_last_bb (dom));
709 if (gimple_code (cond) != GIMPLE_COND)
710 return false;
711 /* Verify that this is an extended form of a diamond and
712 the PHI arguments are completely controlled by the
713 predicate in DOM. */
714 if (!extract_true_false_args_from_phi (dom, phi, NULL, NULL))
715 return false;
716
717 /* Fold in dependencies and cost of the condition. */
718 FOR_EACH_SSA_TREE_OPERAND (val, cond, iter, SSA_OP_USE)
719 {
720 if (!add_dependency (val, lim_data, loop, false))
721 return false;
722 def_data = get_lim_data (SSA_NAME_DEF_STMT (val));
723 if (def_data)
724 total_cost += def_data->cost;
725 }
726
727 /* We want to avoid unconditionally executing very expensive
728 operations. As costs for our dependencies cannot be
729 negative just claim we are not invariand for this case.
730 We also are not sure whether the control-flow inside the
731 loop will vanish. */
732 if (total_cost - min_cost >= 2 * LIM_EXPENSIVE
733 && !(min_cost != 0
734 && total_cost / min_cost <= 2))
735 return false;
736
737 /* Assume that the control-flow in the loop will vanish.
738 ??? We should verify this and not artificially increase
739 the cost if that is not the case. */
740 lim_data->cost += stmt_cost (stmt);
741 }
742
743 return true;
744 }
745 else
746 FOR_EACH_SSA_TREE_OPERAND (val, stmt, iter, SSA_OP_USE)
747 if (!add_dependency (val, lim_data, loop, true))
748 return false;
749
750 if (gimple_vuse (stmt))
751 {
752 im_mem_ref *ref = mem_ref_in_stmt (stmt);
753
754 if (ref)
755 {
756 lim_data->max_loop
757 = outermost_indep_loop (lim_data->max_loop, loop, ref);
758 if (!lim_data->max_loop)
759 return false;
760 }
761 else
762 {
763 if ((val = gimple_vuse (stmt)) != NULL_TREE)
764 {
765 if (!add_dependency (val, lim_data, loop, false))
766 return false;
767 }
768 }
769 }
770
771 lim_data->cost += stmt_cost (stmt);
772
773 return true;
774 }
775
776 /* Suppose that some statement in ORIG_LOOP is hoisted to the loop LEVEL,
777 and that one of the operands of this statement is computed by STMT.
778 Ensure that STMT (together with all the statements that define its
779 operands) is hoisted at least out of the loop LEVEL. */
780
781 static void
782 set_level (gimple *stmt, struct loop *orig_loop, struct loop *level)
783 {
784 struct loop *stmt_loop = gimple_bb (stmt)->loop_father;
785 struct lim_aux_data *lim_data;
786 gimple *dep_stmt;
787 unsigned i;
788
789 stmt_loop = find_common_loop (orig_loop, stmt_loop);
790 lim_data = get_lim_data (stmt);
791 if (lim_data != NULL && lim_data->tgt_loop != NULL)
792 stmt_loop = find_common_loop (stmt_loop,
793 loop_outer (lim_data->tgt_loop));
794 if (flow_loop_nested_p (stmt_loop, level))
795 return;
796
797 gcc_assert (level == lim_data->max_loop
798 || flow_loop_nested_p (lim_data->max_loop, level));
799
800 lim_data->tgt_loop = level;
801 FOR_EACH_VEC_ELT (lim_data->depends, i, dep_stmt)
802 set_level (dep_stmt, orig_loop, level);
803 }
804
805 /* Determines an outermost loop from that we want to hoist the statement STMT.
806 For now we chose the outermost possible loop. TODO -- use profiling
807 information to set it more sanely. */
808
809 static void
810 set_profitable_level (gimple *stmt)
811 {
812 set_level (stmt, gimple_bb (stmt)->loop_father, get_lim_data (stmt)->max_loop);
813 }
814
815 /* Returns true if STMT is a call that has side effects. */
816
817 static bool
818 nonpure_call_p (gimple *stmt)
819 {
820 if (gimple_code (stmt) != GIMPLE_CALL)
821 return false;
822
823 return gimple_has_side_effects (stmt);
824 }
825
826 /* Rewrite a/b to a*(1/b). Return the invariant stmt to process. */
827
828 static gimple *
829 rewrite_reciprocal (gimple_stmt_iterator *bsi)
830 {
831 gassign *stmt, *stmt1, *stmt2;
832 tree name, lhs, type;
833 tree real_one;
834 gimple_stmt_iterator gsi;
835
836 stmt = as_a <gassign *> (gsi_stmt (*bsi));
837 lhs = gimple_assign_lhs (stmt);
838 type = TREE_TYPE (lhs);
839
840 real_one = build_one_cst (type);
841
842 name = make_temp_ssa_name (type, NULL, "reciptmp");
843 stmt1 = gimple_build_assign (name, RDIV_EXPR, real_one,
844 gimple_assign_rhs2 (stmt));
845 stmt2 = gimple_build_assign (lhs, MULT_EXPR, name,
846 gimple_assign_rhs1 (stmt));
847
848 /* Replace division stmt with reciprocal and multiply stmts.
849 The multiply stmt is not invariant, so update iterator
850 and avoid rescanning. */
851 gsi = *bsi;
852 gsi_insert_before (bsi, stmt1, GSI_NEW_STMT);
853 gsi_replace (&gsi, stmt2, true);
854
855 /* Continue processing with invariant reciprocal statement. */
856 return stmt1;
857 }
858
859 /* Check if the pattern at *BSI is a bittest of the form
860 (A >> B) & 1 != 0 and in this case rewrite it to A & (1 << B) != 0. */
861
862 static gimple *
863 rewrite_bittest (gimple_stmt_iterator *bsi)
864 {
865 gassign *stmt;
866 gimple *stmt1;
867 gassign *stmt2;
868 gimple *use_stmt;
869 gcond *cond_stmt;
870 tree lhs, name, t, a, b;
871 use_operand_p use;
872
873 stmt = as_a <gassign *> (gsi_stmt (*bsi));
874 lhs = gimple_assign_lhs (stmt);
875
876 /* Verify that the single use of lhs is a comparison against zero. */
877 if (TREE_CODE (lhs) != SSA_NAME
878 || !single_imm_use (lhs, &use, &use_stmt))
879 return stmt;
880 cond_stmt = dyn_cast <gcond *> (use_stmt);
881 if (!cond_stmt)
882 return stmt;
883 if (gimple_cond_lhs (cond_stmt) != lhs
884 || (gimple_cond_code (cond_stmt) != NE_EXPR
885 && gimple_cond_code (cond_stmt) != EQ_EXPR)
886 || !integer_zerop (gimple_cond_rhs (cond_stmt)))
887 return stmt;
888
889 /* Get at the operands of the shift. The rhs is TMP1 & 1. */
890 stmt1 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
891 if (gimple_code (stmt1) != GIMPLE_ASSIGN)
892 return stmt;
893
894 /* There is a conversion in between possibly inserted by fold. */
895 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt1)))
896 {
897 t = gimple_assign_rhs1 (stmt1);
898 if (TREE_CODE (t) != SSA_NAME
899 || !has_single_use (t))
900 return stmt;
901 stmt1 = SSA_NAME_DEF_STMT (t);
902 if (gimple_code (stmt1) != GIMPLE_ASSIGN)
903 return stmt;
904 }
905
906 /* Verify that B is loop invariant but A is not. Verify that with
907 all the stmt walking we are still in the same loop. */
908 if (gimple_assign_rhs_code (stmt1) != RSHIFT_EXPR
909 || loop_containing_stmt (stmt1) != loop_containing_stmt (stmt))
910 return stmt;
911
912 a = gimple_assign_rhs1 (stmt1);
913 b = gimple_assign_rhs2 (stmt1);
914
915 if (outermost_invariant_loop (b, loop_containing_stmt (stmt1)) != NULL
916 && outermost_invariant_loop (a, loop_containing_stmt (stmt1)) == NULL)
917 {
918 gimple_stmt_iterator rsi;
919
920 /* 1 << B */
921 t = fold_build2 (LSHIFT_EXPR, TREE_TYPE (a),
922 build_int_cst (TREE_TYPE (a), 1), b);
923 name = make_temp_ssa_name (TREE_TYPE (a), NULL, "shifttmp");
924 stmt1 = gimple_build_assign (name, t);
925
926 /* A & (1 << B) */
927 t = fold_build2 (BIT_AND_EXPR, TREE_TYPE (a), a, name);
928 name = make_temp_ssa_name (TREE_TYPE (a), NULL, "shifttmp");
929 stmt2 = gimple_build_assign (name, t);
930
931 /* Replace the SSA_NAME we compare against zero. Adjust
932 the type of zero accordingly. */
933 SET_USE (use, name);
934 gimple_cond_set_rhs (cond_stmt,
935 build_int_cst_type (TREE_TYPE (name),
936 0));
937
938 /* Don't use gsi_replace here, none of the new assignments sets
939 the variable originally set in stmt. Move bsi to stmt1, and
940 then remove the original stmt, so that we get a chance to
941 retain debug info for it. */
942 rsi = *bsi;
943 gsi_insert_before (bsi, stmt1, GSI_NEW_STMT);
944 gsi_insert_before (&rsi, stmt2, GSI_SAME_STMT);
945 gimple *to_release = gsi_stmt (rsi);
946 gsi_remove (&rsi, true);
947 release_defs (to_release);
948
949 return stmt1;
950 }
951
952 return stmt;
953 }
954
955 /* For each statement determines the outermost loop in that it is invariant,
956 - statements on whose motion it depends and the cost of the computation.
957 - This information is stored to the LIM_DATA structure associated with
958 - each statement. */
959 class invariantness_dom_walker : public dom_walker
960 {
961 public:
962 invariantness_dom_walker (cdi_direction direction)
963 : dom_walker (direction) {}
964
965 virtual void before_dom_children (basic_block);
966 };
967
968 /* Determine the outermost loops in that statements in basic block BB are
969 invariant, and record them to the LIM_DATA associated with the statements.
970 Callback for dom_walker. */
971
972 void
973 invariantness_dom_walker::before_dom_children (basic_block bb)
974 {
975 enum move_pos pos;
976 gimple_stmt_iterator bsi;
977 gimple *stmt;
978 bool maybe_never = ALWAYS_EXECUTED_IN (bb) == NULL;
979 struct loop *outermost = ALWAYS_EXECUTED_IN (bb);
980 struct lim_aux_data *lim_data;
981
982 if (!loop_outer (bb->loop_father))
983 return;
984
985 if (dump_file && (dump_flags & TDF_DETAILS))
986 fprintf (dump_file, "Basic block %d (loop %d -- depth %d):\n\n",
987 bb->index, bb->loop_father->num, loop_depth (bb->loop_father));
988
989 /* Look at PHI nodes, but only if there is at most two.
990 ??? We could relax this further by post-processing the inserted
991 code and transforming adjacent cond-exprs with the same predicate
992 to control flow again. */
993 bsi = gsi_start_phis (bb);
994 if (!gsi_end_p (bsi)
995 && ((gsi_next (&bsi), gsi_end_p (bsi))
996 || (gsi_next (&bsi), gsi_end_p (bsi))))
997 for (bsi = gsi_start_phis (bb); !gsi_end_p (bsi); gsi_next (&bsi))
998 {
999 stmt = gsi_stmt (bsi);
1000
1001 pos = movement_possibility (stmt);
1002 if (pos == MOVE_IMPOSSIBLE)
1003 continue;
1004
1005 lim_data = init_lim_data (stmt);
1006 lim_data->always_executed_in = outermost;
1007
1008 if (!determine_max_movement (stmt, false))
1009 {
1010 lim_data->max_loop = NULL;
1011 continue;
1012 }
1013
1014 if (dump_file && (dump_flags & TDF_DETAILS))
1015 {
1016 print_gimple_stmt (dump_file, stmt, 2, 0);
1017 fprintf (dump_file, " invariant up to level %d, cost %d.\n\n",
1018 loop_depth (lim_data->max_loop),
1019 lim_data->cost);
1020 }
1021
1022 if (lim_data->cost >= LIM_EXPENSIVE)
1023 set_profitable_level (stmt);
1024 }
1025
1026 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1027 {
1028 stmt = gsi_stmt (bsi);
1029
1030 pos = movement_possibility (stmt);
1031 if (pos == MOVE_IMPOSSIBLE)
1032 {
1033 if (nonpure_call_p (stmt))
1034 {
1035 maybe_never = true;
1036 outermost = NULL;
1037 }
1038 /* Make sure to note always_executed_in for stores to make
1039 store-motion work. */
1040 else if (stmt_makes_single_store (stmt))
1041 {
1042 struct lim_aux_data *lim_data = init_lim_data (stmt);
1043 lim_data->always_executed_in = outermost;
1044 }
1045 continue;
1046 }
1047
1048 if (is_gimple_assign (stmt)
1049 && (get_gimple_rhs_class (gimple_assign_rhs_code (stmt))
1050 == GIMPLE_BINARY_RHS))
1051 {
1052 tree op0 = gimple_assign_rhs1 (stmt);
1053 tree op1 = gimple_assign_rhs2 (stmt);
1054 struct loop *ol1 = outermost_invariant_loop (op1,
1055 loop_containing_stmt (stmt));
1056
1057 /* If divisor is invariant, convert a/b to a*(1/b), allowing reciprocal
1058 to be hoisted out of loop, saving expensive divide. */
1059 if (pos == MOVE_POSSIBLE
1060 && gimple_assign_rhs_code (stmt) == RDIV_EXPR
1061 && flag_unsafe_math_optimizations
1062 && !flag_trapping_math
1063 && ol1 != NULL
1064 && outermost_invariant_loop (op0, ol1) == NULL)
1065 stmt = rewrite_reciprocal (&bsi);
1066
1067 /* If the shift count is invariant, convert (A >> B) & 1 to
1068 A & (1 << B) allowing the bit mask to be hoisted out of the loop
1069 saving an expensive shift. */
1070 if (pos == MOVE_POSSIBLE
1071 && gimple_assign_rhs_code (stmt) == BIT_AND_EXPR
1072 && integer_onep (op1)
1073 && TREE_CODE (op0) == SSA_NAME
1074 && has_single_use (op0))
1075 stmt = rewrite_bittest (&bsi);
1076 }
1077
1078 lim_data = init_lim_data (stmt);
1079 lim_data->always_executed_in = outermost;
1080
1081 if (maybe_never && pos == MOVE_PRESERVE_EXECUTION)
1082 continue;
1083
1084 if (!determine_max_movement (stmt, pos == MOVE_PRESERVE_EXECUTION))
1085 {
1086 lim_data->max_loop = NULL;
1087 continue;
1088 }
1089
1090 if (dump_file && (dump_flags & TDF_DETAILS))
1091 {
1092 print_gimple_stmt (dump_file, stmt, 2, 0);
1093 fprintf (dump_file, " invariant up to level %d, cost %d.\n\n",
1094 loop_depth (lim_data->max_loop),
1095 lim_data->cost);
1096 }
1097
1098 if (lim_data->cost >= LIM_EXPENSIVE)
1099 set_profitable_level (stmt);
1100 }
1101 }
1102
1103 class move_computations_dom_walker : public dom_walker
1104 {
1105 public:
1106 move_computations_dom_walker (cdi_direction direction)
1107 : dom_walker (direction), todo_ (0) {}
1108
1109 virtual void before_dom_children (basic_block);
1110
1111 unsigned int todo_;
1112 };
1113
1114 /* Hoist the statements in basic block BB out of the loops prescribed by
1115 data stored in LIM_DATA structures associated with each statement. Callback
1116 for walk_dominator_tree. */
1117
1118 void
1119 move_computations_dom_walker::before_dom_children (basic_block bb)
1120 {
1121 struct loop *level;
1122 unsigned cost = 0;
1123 struct lim_aux_data *lim_data;
1124
1125 if (!loop_outer (bb->loop_father))
1126 return;
1127
1128 for (gphi_iterator bsi = gsi_start_phis (bb); !gsi_end_p (bsi); )
1129 {
1130 gassign *new_stmt;
1131 gphi *stmt = bsi.phi ();
1132
1133 lim_data = get_lim_data (stmt);
1134 if (lim_data == NULL)
1135 {
1136 gsi_next (&bsi);
1137 continue;
1138 }
1139
1140 cost = lim_data->cost;
1141 level = lim_data->tgt_loop;
1142 clear_lim_data (stmt);
1143
1144 if (!level)
1145 {
1146 gsi_next (&bsi);
1147 continue;
1148 }
1149
1150 if (dump_file && (dump_flags & TDF_DETAILS))
1151 {
1152 fprintf (dump_file, "Moving PHI node\n");
1153 print_gimple_stmt (dump_file, stmt, 0, 0);
1154 fprintf (dump_file, "(cost %u) out of loop %d.\n\n",
1155 cost, level->num);
1156 }
1157
1158 if (gimple_phi_num_args (stmt) == 1)
1159 {
1160 tree arg = PHI_ARG_DEF (stmt, 0);
1161 new_stmt = gimple_build_assign (gimple_phi_result (stmt),
1162 TREE_CODE (arg), arg);
1163 }
1164 else
1165 {
1166 basic_block dom = get_immediate_dominator (CDI_DOMINATORS, bb);
1167 gimple *cond = gsi_stmt (gsi_last_bb (dom));
1168 tree arg0 = NULL_TREE, arg1 = NULL_TREE, t;
1169 /* Get the PHI arguments corresponding to the true and false
1170 edges of COND. */
1171 extract_true_false_args_from_phi (dom, stmt, &arg0, &arg1);
1172 gcc_assert (arg0 && arg1);
1173 t = build2 (gimple_cond_code (cond), boolean_type_node,
1174 gimple_cond_lhs (cond), gimple_cond_rhs (cond));
1175 new_stmt = gimple_build_assign (gimple_phi_result (stmt),
1176 COND_EXPR, t, arg0, arg1);
1177 todo_ |= TODO_cleanup_cfg;
1178 }
1179 if (INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_lhs (new_stmt)))
1180 && (!ALWAYS_EXECUTED_IN (bb)
1181 || (ALWAYS_EXECUTED_IN (bb) != level
1182 && !flow_loop_nested_p (ALWAYS_EXECUTED_IN (bb), level))))
1183 {
1184 tree lhs = gimple_assign_lhs (new_stmt);
1185 SSA_NAME_RANGE_INFO (lhs) = NULL;
1186 }
1187 gsi_insert_on_edge (loop_preheader_edge (level), new_stmt);
1188 remove_phi_node (&bsi, false);
1189 }
1190
1191 for (gimple_stmt_iterator bsi = gsi_start_bb (bb); !gsi_end_p (bsi); )
1192 {
1193 edge e;
1194
1195 gimple *stmt = gsi_stmt (bsi);
1196
1197 lim_data = get_lim_data (stmt);
1198 if (lim_data == NULL)
1199 {
1200 gsi_next (&bsi);
1201 continue;
1202 }
1203
1204 cost = lim_data->cost;
1205 level = lim_data->tgt_loop;
1206 clear_lim_data (stmt);
1207
1208 if (!level)
1209 {
1210 gsi_next (&bsi);
1211 continue;
1212 }
1213
1214 /* We do not really want to move conditionals out of the loop; we just
1215 placed it here to force its operands to be moved if necessary. */
1216 if (gimple_code (stmt) == GIMPLE_COND)
1217 continue;
1218
1219 if (dump_file && (dump_flags & TDF_DETAILS))
1220 {
1221 fprintf (dump_file, "Moving statement\n");
1222 print_gimple_stmt (dump_file, stmt, 0, 0);
1223 fprintf (dump_file, "(cost %u) out of loop %d.\n\n",
1224 cost, level->num);
1225 }
1226
1227 e = loop_preheader_edge (level);
1228 gcc_assert (!gimple_vdef (stmt));
1229 if (gimple_vuse (stmt))
1230 {
1231 /* The new VUSE is the one from the virtual PHI in the loop
1232 header or the one already present. */
1233 gphi_iterator gsi2;
1234 for (gsi2 = gsi_start_phis (e->dest);
1235 !gsi_end_p (gsi2); gsi_next (&gsi2))
1236 {
1237 gphi *phi = gsi2.phi ();
1238 if (virtual_operand_p (gimple_phi_result (phi)))
1239 {
1240 gimple_set_vuse (stmt, PHI_ARG_DEF_FROM_EDGE (phi, e));
1241 break;
1242 }
1243 }
1244 }
1245 gsi_remove (&bsi, false);
1246 if (gimple_has_lhs (stmt)
1247 && TREE_CODE (gimple_get_lhs (stmt)) == SSA_NAME
1248 && INTEGRAL_TYPE_P (TREE_TYPE (gimple_get_lhs (stmt)))
1249 && (!ALWAYS_EXECUTED_IN (bb)
1250 || !(ALWAYS_EXECUTED_IN (bb) == level
1251 || flow_loop_nested_p (ALWAYS_EXECUTED_IN (bb), level))))
1252 {
1253 tree lhs = gimple_get_lhs (stmt);
1254 SSA_NAME_RANGE_INFO (lhs) = NULL;
1255 }
1256 /* In case this is a stmt that is not unconditionally executed
1257 when the target loop header is executed and the stmt may
1258 invoke undefined integer or pointer overflow rewrite it to
1259 unsigned arithmetic. */
1260 if (is_gimple_assign (stmt)
1261 && INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_lhs (stmt)))
1262 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (gimple_assign_lhs (stmt)))
1263 && arith_code_with_undefined_signed_overflow
1264 (gimple_assign_rhs_code (stmt))
1265 && (!ALWAYS_EXECUTED_IN (bb)
1266 || !(ALWAYS_EXECUTED_IN (bb) == level
1267 || flow_loop_nested_p (ALWAYS_EXECUTED_IN (bb), level))))
1268 gsi_insert_seq_on_edge (e, rewrite_to_defined_overflow (stmt));
1269 else
1270 gsi_insert_on_edge (e, stmt);
1271 }
1272 }
1273
1274 /* Hoist the statements out of the loops prescribed by data stored in
1275 LIM_DATA structures associated with each statement.*/
1276
1277 static unsigned int
1278 move_computations (void)
1279 {
1280 move_computations_dom_walker walker (CDI_DOMINATORS);
1281 walker.walk (cfun->cfg->x_entry_block_ptr);
1282
1283 gsi_commit_edge_inserts ();
1284 if (need_ssa_update_p (cfun))
1285 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
1286
1287 return walker.todo_;
1288 }
1289
1290 /* Checks whether the statement defining variable *INDEX can be hoisted
1291 out of the loop passed in DATA. Callback for for_each_index. */
1292
1293 static bool
1294 may_move_till (tree ref, tree *index, void *data)
1295 {
1296 struct loop *loop = (struct loop *) data, *max_loop;
1297
1298 /* If REF is an array reference, check also that the step and the lower
1299 bound is invariant in LOOP. */
1300 if (TREE_CODE (ref) == ARRAY_REF)
1301 {
1302 tree step = TREE_OPERAND (ref, 3);
1303 tree lbound = TREE_OPERAND (ref, 2);
1304
1305 max_loop = outermost_invariant_loop (step, loop);
1306 if (!max_loop)
1307 return false;
1308
1309 max_loop = outermost_invariant_loop (lbound, loop);
1310 if (!max_loop)
1311 return false;
1312 }
1313
1314 max_loop = outermost_invariant_loop (*index, loop);
1315 if (!max_loop)
1316 return false;
1317
1318 return true;
1319 }
1320
1321 /* If OP is SSA NAME, force the statement that defines it to be
1322 moved out of the LOOP. ORIG_LOOP is the loop in that EXPR is used. */
1323
1324 static void
1325 force_move_till_op (tree op, struct loop *orig_loop, struct loop *loop)
1326 {
1327 gimple *stmt;
1328
1329 if (!op
1330 || is_gimple_min_invariant (op))
1331 return;
1332
1333 gcc_assert (TREE_CODE (op) == SSA_NAME);
1334
1335 stmt = SSA_NAME_DEF_STMT (op);
1336 if (gimple_nop_p (stmt))
1337 return;
1338
1339 set_level (stmt, orig_loop, loop);
1340 }
1341
1342 /* Forces statement defining invariants in REF (and *INDEX) to be moved out of
1343 the LOOP. The reference REF is used in the loop ORIG_LOOP. Callback for
1344 for_each_index. */
1345
1346 struct fmt_data
1347 {
1348 struct loop *loop;
1349 struct loop *orig_loop;
1350 };
1351
1352 static bool
1353 force_move_till (tree ref, tree *index, void *data)
1354 {
1355 struct fmt_data *fmt_data = (struct fmt_data *) data;
1356
1357 if (TREE_CODE (ref) == ARRAY_REF)
1358 {
1359 tree step = TREE_OPERAND (ref, 3);
1360 tree lbound = TREE_OPERAND (ref, 2);
1361
1362 force_move_till_op (step, fmt_data->orig_loop, fmt_data->loop);
1363 force_move_till_op (lbound, fmt_data->orig_loop, fmt_data->loop);
1364 }
1365
1366 force_move_till_op (*index, fmt_data->orig_loop, fmt_data->loop);
1367
1368 return true;
1369 }
1370
1371 /* A function to free the mem_ref object OBJ. */
1372
1373 static void
1374 memref_free (struct im_mem_ref *mem)
1375 {
1376 mem->accesses_in_loop.release ();
1377 }
1378
1379 /* Allocates and returns a memory reference description for MEM whose hash
1380 value is HASH and id is ID. */
1381
1382 static im_mem_ref *
1383 mem_ref_alloc (tree mem, unsigned hash, unsigned id)
1384 {
1385 im_mem_ref *ref = XOBNEW (&mem_ref_obstack, struct im_mem_ref);
1386 ao_ref_init (&ref->mem, mem);
1387 ref->id = id;
1388 ref->hash = hash;
1389 ref->stored = NULL;
1390 bitmap_initialize (&ref->indep_loop, &lim_bitmap_obstack);
1391 bitmap_initialize (&ref->dep_loop, &lim_bitmap_obstack);
1392 ref->accesses_in_loop.create (1);
1393
1394 return ref;
1395 }
1396
1397 /* Records memory reference location *LOC in LOOP to the memory reference
1398 description REF. The reference occurs in statement STMT. */
1399
1400 static void
1401 record_mem_ref_loc (im_mem_ref *ref, gimple *stmt, tree *loc)
1402 {
1403 mem_ref_loc aref;
1404 aref.stmt = stmt;
1405 aref.ref = loc;
1406 ref->accesses_in_loop.safe_push (aref);
1407 }
1408
1409 /* Set the LOOP bit in REF stored bitmap and allocate that if
1410 necessary. Return whether a bit was changed. */
1411
1412 static bool
1413 set_ref_stored_in_loop (im_mem_ref *ref, struct loop *loop)
1414 {
1415 if (!ref->stored)
1416 ref->stored = BITMAP_ALLOC (&lim_bitmap_obstack);
1417 return bitmap_set_bit (ref->stored, loop->num);
1418 }
1419
1420 /* Marks reference REF as stored in LOOP. */
1421
1422 static void
1423 mark_ref_stored (im_mem_ref *ref, struct loop *loop)
1424 {
1425 while (loop != current_loops->tree_root
1426 && set_ref_stored_in_loop (ref, loop))
1427 loop = loop_outer (loop);
1428 }
1429
1430 /* Gathers memory references in statement STMT in LOOP, storing the
1431 information about them in the memory_accesses structure. Marks
1432 the vops accessed through unrecognized statements there as
1433 well. */
1434
1435 static void
1436 gather_mem_refs_stmt (struct loop *loop, gimple *stmt)
1437 {
1438 tree *mem = NULL;
1439 hashval_t hash;
1440 im_mem_ref **slot;
1441 im_mem_ref *ref;
1442 bool is_stored;
1443 unsigned id;
1444
1445 if (!gimple_vuse (stmt))
1446 return;
1447
1448 mem = simple_mem_ref_in_stmt (stmt, &is_stored);
1449 if (!mem)
1450 {
1451 /* We use the shared mem_ref for all unanalyzable refs. */
1452 id = UNANALYZABLE_MEM_ID;
1453 ref = memory_accesses.refs_list[id];
1454 if (dump_file && (dump_flags & TDF_DETAILS))
1455 {
1456 fprintf (dump_file, "Unanalyzed memory reference %u: ", id);
1457 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
1458 }
1459 is_stored = gimple_vdef (stmt);
1460 }
1461 else
1462 {
1463 hash = iterative_hash_expr (*mem, 0);
1464 slot = memory_accesses.refs->find_slot_with_hash (*mem, hash, INSERT);
1465 if (*slot)
1466 {
1467 ref = *slot;
1468 id = ref->id;
1469 }
1470 else
1471 {
1472 id = memory_accesses.refs_list.length ();
1473 ref = mem_ref_alloc (*mem, hash, id);
1474 memory_accesses.refs_list.safe_push (ref);
1475 *slot = ref;
1476
1477 if (dump_file && (dump_flags & TDF_DETAILS))
1478 {
1479 fprintf (dump_file, "Memory reference %u: ", id);
1480 print_generic_expr (dump_file, ref->mem.ref, TDF_SLIM);
1481 fprintf (dump_file, "\n");
1482 }
1483 }
1484
1485 record_mem_ref_loc (ref, stmt, mem);
1486 }
1487 bitmap_set_bit (&memory_accesses.refs_in_loop[loop->num], ref->id);
1488 if (is_stored)
1489 {
1490 bitmap_set_bit (&memory_accesses.refs_stored_in_loop[loop->num], ref->id);
1491 mark_ref_stored (ref, loop);
1492 }
1493 return;
1494 }
1495
1496 static unsigned *bb_loop_postorder;
1497
1498 /* qsort sort function to sort blocks after their loop fathers postorder. */
1499
1500 static int
1501 sort_bbs_in_loop_postorder_cmp (const void *bb1_, const void *bb2_)
1502 {
1503 basic_block bb1 = *(basic_block *)const_cast<void *>(bb1_);
1504 basic_block bb2 = *(basic_block *)const_cast<void *>(bb2_);
1505 struct loop *loop1 = bb1->loop_father;
1506 struct loop *loop2 = bb2->loop_father;
1507 if (loop1->num == loop2->num)
1508 return 0;
1509 return bb_loop_postorder[loop1->num] < bb_loop_postorder[loop2->num] ? -1 : 1;
1510 }
1511
1512 /* qsort sort function to sort ref locs after their loop fathers postorder. */
1513
1514 static int
1515 sort_locs_in_loop_postorder_cmp (const void *loc1_, const void *loc2_)
1516 {
1517 mem_ref_loc *loc1 = (mem_ref_loc *)const_cast<void *>(loc1_);
1518 mem_ref_loc *loc2 = (mem_ref_loc *)const_cast<void *>(loc2_);
1519 struct loop *loop1 = gimple_bb (loc1->stmt)->loop_father;
1520 struct loop *loop2 = gimple_bb (loc2->stmt)->loop_father;
1521 if (loop1->num == loop2->num)
1522 return 0;
1523 return bb_loop_postorder[loop1->num] < bb_loop_postorder[loop2->num] ? -1 : 1;
1524 }
1525
1526 /* Gathers memory references in loops. */
1527
1528 static void
1529 analyze_memory_references (void)
1530 {
1531 gimple_stmt_iterator bsi;
1532 basic_block bb, *bbs;
1533 struct loop *loop, *outer;
1534 unsigned i, n;
1535
1536 /* Collect all basic-blocks in loops and sort them after their
1537 loops postorder. */
1538 i = 0;
1539 bbs = XNEWVEC (basic_block, n_basic_blocks_for_fn (cfun) - NUM_FIXED_BLOCKS);
1540 FOR_EACH_BB_FN (bb, cfun)
1541 if (bb->loop_father != current_loops->tree_root)
1542 bbs[i++] = bb;
1543 n = i;
1544 qsort (bbs, n, sizeof (basic_block), sort_bbs_in_loop_postorder_cmp);
1545
1546 /* Visit blocks in loop postorder and assign mem-ref IDs in that order.
1547 That results in better locality for all the bitmaps. */
1548 for (i = 0; i < n; ++i)
1549 {
1550 basic_block bb = bbs[i];
1551 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1552 gather_mem_refs_stmt (bb->loop_father, gsi_stmt (bsi));
1553 }
1554
1555 /* Sort the location list of gathered memory references after their
1556 loop postorder number. */
1557 im_mem_ref *ref;
1558 FOR_EACH_VEC_ELT (memory_accesses.refs_list, i, ref)
1559 ref->accesses_in_loop.qsort (sort_locs_in_loop_postorder_cmp);
1560
1561 free (bbs);
1562 // free (bb_loop_postorder);
1563
1564 /* Propagate the information about accessed memory references up
1565 the loop hierarchy. */
1566 FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
1567 {
1568 /* Finalize the overall touched references (including subloops). */
1569 bitmap_ior_into (&memory_accesses.all_refs_stored_in_loop[loop->num],
1570 &memory_accesses.refs_stored_in_loop[loop->num]);
1571
1572 /* Propagate the information about accessed memory references up
1573 the loop hierarchy. */
1574 outer = loop_outer (loop);
1575 if (outer == current_loops->tree_root)
1576 continue;
1577
1578 bitmap_ior_into (&memory_accesses.all_refs_stored_in_loop[outer->num],
1579 &memory_accesses.all_refs_stored_in_loop[loop->num]);
1580 }
1581 }
1582
1583 /* Returns true if MEM1 and MEM2 may alias. TTAE_CACHE is used as a cache in
1584 tree_to_aff_combination_expand. */
1585
1586 static bool
1587 mem_refs_may_alias_p (im_mem_ref *mem1, im_mem_ref *mem2,
1588 hash_map<tree, name_expansion *> **ttae_cache)
1589 {
1590 /* Perform BASE + OFFSET analysis -- if MEM1 and MEM2 are based on the same
1591 object and their offset differ in such a way that the locations cannot
1592 overlap, then they cannot alias. */
1593 widest_int size1, size2;
1594 aff_tree off1, off2;
1595
1596 /* Perform basic offset and type-based disambiguation. */
1597 if (!refs_may_alias_p_1 (&mem1->mem, &mem2->mem, true))
1598 return false;
1599
1600 /* The expansion of addresses may be a bit expensive, thus we only do
1601 the check at -O2 and higher optimization levels. */
1602 if (optimize < 2)
1603 return true;
1604
1605 get_inner_reference_aff (mem1->mem.ref, &off1, &size1);
1606 get_inner_reference_aff (mem2->mem.ref, &off2, &size2);
1607 aff_combination_expand (&off1, ttae_cache);
1608 aff_combination_expand (&off2, ttae_cache);
1609 aff_combination_scale (&off1, -1);
1610 aff_combination_add (&off2, &off1);
1611
1612 if (aff_comb_cannot_overlap_p (&off2, size1, size2))
1613 return false;
1614
1615 return true;
1616 }
1617
1618 /* Compare function for bsearch searching for reference locations
1619 in a loop. */
1620
1621 static int
1622 find_ref_loc_in_loop_cmp (const void *loop_, const void *loc_)
1623 {
1624 struct loop *loop = (struct loop *)const_cast<void *>(loop_);
1625 mem_ref_loc *loc = (mem_ref_loc *)const_cast<void *>(loc_);
1626 struct loop *loc_loop = gimple_bb (loc->stmt)->loop_father;
1627 if (loop->num == loc_loop->num
1628 || flow_loop_nested_p (loop, loc_loop))
1629 return 0;
1630 return (bb_loop_postorder[loop->num] < bb_loop_postorder[loc_loop->num]
1631 ? -1 : 1);
1632 }
1633
1634 /* Iterates over all locations of REF in LOOP and its subloops calling
1635 fn.operator() with the location as argument. When that operator
1636 returns true the iteration is stopped and true is returned.
1637 Otherwise false is returned. */
1638
1639 template <typename FN>
1640 static bool
1641 for_all_locs_in_loop (struct loop *loop, im_mem_ref *ref, FN fn)
1642 {
1643 unsigned i;
1644 mem_ref_loc *loc;
1645
1646 /* Search for the cluster of locs in the accesses_in_loop vector
1647 which is sorted after postorder index of the loop father. */
1648 loc = ref->accesses_in_loop.bsearch (loop, find_ref_loc_in_loop_cmp);
1649 if (!loc)
1650 return false;
1651
1652 /* We have found one location inside loop or its sub-loops. Iterate
1653 both forward and backward to cover the whole cluster. */
1654 i = loc - ref->accesses_in_loop.address ();
1655 while (i > 0)
1656 {
1657 --i;
1658 mem_ref_loc *l = &ref->accesses_in_loop[i];
1659 if (!flow_bb_inside_loop_p (loop, gimple_bb (l->stmt)))
1660 break;
1661 if (fn (l))
1662 return true;
1663 }
1664 for (i = loc - ref->accesses_in_loop.address ();
1665 i < ref->accesses_in_loop.length (); ++i)
1666 {
1667 mem_ref_loc *l = &ref->accesses_in_loop[i];
1668 if (!flow_bb_inside_loop_p (loop, gimple_bb (l->stmt)))
1669 break;
1670 if (fn (l))
1671 return true;
1672 }
1673
1674 return false;
1675 }
1676
1677 /* Rewrites location LOC by TMP_VAR. */
1678
1679 struct rewrite_mem_ref_loc
1680 {
1681 rewrite_mem_ref_loc (tree tmp_var_) : tmp_var (tmp_var_) {}
1682 bool operator () (mem_ref_loc *loc);
1683 tree tmp_var;
1684 };
1685
1686 bool
1687 rewrite_mem_ref_loc::operator () (mem_ref_loc *loc)
1688 {
1689 *loc->ref = tmp_var;
1690 update_stmt (loc->stmt);
1691 return false;
1692 }
1693
1694 /* Rewrites all references to REF in LOOP by variable TMP_VAR. */
1695
1696 static void
1697 rewrite_mem_refs (struct loop *loop, im_mem_ref *ref, tree tmp_var)
1698 {
1699 for_all_locs_in_loop (loop, ref, rewrite_mem_ref_loc (tmp_var));
1700 }
1701
1702 /* Stores the first reference location in LOCP. */
1703
1704 struct first_mem_ref_loc_1
1705 {
1706 first_mem_ref_loc_1 (mem_ref_loc **locp_) : locp (locp_) {}
1707 bool operator () (mem_ref_loc *loc);
1708 mem_ref_loc **locp;
1709 };
1710
1711 bool
1712 first_mem_ref_loc_1::operator () (mem_ref_loc *loc)
1713 {
1714 *locp = loc;
1715 return true;
1716 }
1717
1718 /* Returns the first reference location to REF in LOOP. */
1719
1720 static mem_ref_loc *
1721 first_mem_ref_loc (struct loop *loop, im_mem_ref *ref)
1722 {
1723 mem_ref_loc *locp = NULL;
1724 for_all_locs_in_loop (loop, ref, first_mem_ref_loc_1 (&locp));
1725 return locp;
1726 }
1727
1728 struct prev_flag_edges {
1729 /* Edge to insert new flag comparison code. */
1730 edge append_cond_position;
1731
1732 /* Edge for fall through from previous flag comparison. */
1733 edge last_cond_fallthru;
1734 };
1735
1736 /* Helper function for execute_sm. Emit code to store TMP_VAR into
1737 MEM along edge EX.
1738
1739 The store is only done if MEM has changed. We do this so no
1740 changes to MEM occur on code paths that did not originally store
1741 into it.
1742
1743 The common case for execute_sm will transform:
1744
1745 for (...) {
1746 if (foo)
1747 stuff;
1748 else
1749 MEM = TMP_VAR;
1750 }
1751
1752 into:
1753
1754 lsm = MEM;
1755 for (...) {
1756 if (foo)
1757 stuff;
1758 else
1759 lsm = TMP_VAR;
1760 }
1761 MEM = lsm;
1762
1763 This function will generate:
1764
1765 lsm = MEM;
1766
1767 lsm_flag = false;
1768 ...
1769 for (...) {
1770 if (foo)
1771 stuff;
1772 else {
1773 lsm = TMP_VAR;
1774 lsm_flag = true;
1775 }
1776 }
1777 if (lsm_flag) <--
1778 MEM = lsm; <--
1779 */
1780
1781 static void
1782 execute_sm_if_changed (edge ex, tree mem, tree tmp_var, tree flag)
1783 {
1784 basic_block new_bb, then_bb, old_dest;
1785 bool loop_has_only_one_exit;
1786 edge then_old_edge, orig_ex = ex;
1787 gimple_stmt_iterator gsi;
1788 gimple *stmt;
1789 struct prev_flag_edges *prev_edges = (struct prev_flag_edges *) ex->aux;
1790 bool irr = ex->flags & EDGE_IRREDUCIBLE_LOOP;
1791
1792 /* ?? Insert store after previous store if applicable. See note
1793 below. */
1794 if (prev_edges)
1795 ex = prev_edges->append_cond_position;
1796
1797 loop_has_only_one_exit = single_pred_p (ex->dest);
1798
1799 if (loop_has_only_one_exit)
1800 ex = split_block_after_labels (ex->dest);
1801 else
1802 {
1803 for (gphi_iterator gpi = gsi_start_phis (ex->dest);
1804 !gsi_end_p (gpi); gsi_next (&gpi))
1805 {
1806 gphi *phi = gpi.phi ();
1807 if (virtual_operand_p (gimple_phi_result (phi)))
1808 continue;
1809
1810 /* When the destination has a non-virtual PHI node with multiple
1811 predecessors make sure we preserve the PHI structure by
1812 forcing a forwarder block so that hoisting of that PHI will
1813 still work. */
1814 split_edge (ex);
1815 break;
1816 }
1817 }
1818
1819 old_dest = ex->dest;
1820 new_bb = split_edge (ex);
1821 then_bb = create_empty_bb (new_bb);
1822 if (irr)
1823 then_bb->flags = BB_IRREDUCIBLE_LOOP;
1824 add_bb_to_loop (then_bb, new_bb->loop_father);
1825
1826 gsi = gsi_start_bb (new_bb);
1827 stmt = gimple_build_cond (NE_EXPR, flag, boolean_false_node,
1828 NULL_TREE, NULL_TREE);
1829 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
1830
1831 gsi = gsi_start_bb (then_bb);
1832 /* Insert actual store. */
1833 stmt = gimple_build_assign (unshare_expr (mem), tmp_var);
1834 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
1835
1836 make_edge (new_bb, then_bb,
1837 EDGE_TRUE_VALUE | (irr ? EDGE_IRREDUCIBLE_LOOP : 0));
1838 make_edge (new_bb, old_dest,
1839 EDGE_FALSE_VALUE | (irr ? EDGE_IRREDUCIBLE_LOOP : 0));
1840 then_old_edge = make_edge (then_bb, old_dest,
1841 EDGE_FALLTHRU | (irr ? EDGE_IRREDUCIBLE_LOOP : 0));
1842
1843 set_immediate_dominator (CDI_DOMINATORS, then_bb, new_bb);
1844
1845 if (prev_edges)
1846 {
1847 basic_block prevbb = prev_edges->last_cond_fallthru->src;
1848 redirect_edge_succ (prev_edges->last_cond_fallthru, new_bb);
1849 set_immediate_dominator (CDI_DOMINATORS, new_bb, prevbb);
1850 set_immediate_dominator (CDI_DOMINATORS, old_dest,
1851 recompute_dominator (CDI_DOMINATORS, old_dest));
1852 }
1853
1854 /* ?? Because stores may alias, they must happen in the exact
1855 sequence they originally happened. Save the position right after
1856 the (_lsm) store we just created so we can continue appending after
1857 it and maintain the original order. */
1858 {
1859 struct prev_flag_edges *p;
1860
1861 if (orig_ex->aux)
1862 orig_ex->aux = NULL;
1863 alloc_aux_for_edge (orig_ex, sizeof (struct prev_flag_edges));
1864 p = (struct prev_flag_edges *) orig_ex->aux;
1865 p->append_cond_position = then_old_edge;
1866 p->last_cond_fallthru = find_edge (new_bb, old_dest);
1867 orig_ex->aux = (void *) p;
1868 }
1869
1870 if (!loop_has_only_one_exit)
1871 for (gphi_iterator gpi = gsi_start_phis (old_dest);
1872 !gsi_end_p (gpi); gsi_next (&gpi))
1873 {
1874 gphi *phi = gpi.phi ();
1875 unsigned i;
1876
1877 for (i = 0; i < gimple_phi_num_args (phi); i++)
1878 if (gimple_phi_arg_edge (phi, i)->src == new_bb)
1879 {
1880 tree arg = gimple_phi_arg_def (phi, i);
1881 add_phi_arg (phi, arg, then_old_edge, UNKNOWN_LOCATION);
1882 update_stmt (phi);
1883 }
1884 }
1885 /* Remove the original fall through edge. This was the
1886 single_succ_edge (new_bb). */
1887 EDGE_SUCC (new_bb, 0)->flags &= ~EDGE_FALLTHRU;
1888 }
1889
1890 /* When REF is set on the location, set flag indicating the store. */
1891
1892 struct sm_set_flag_if_changed
1893 {
1894 sm_set_flag_if_changed (tree flag_) : flag (flag_) {}
1895 bool operator () (mem_ref_loc *loc);
1896 tree flag;
1897 };
1898
1899 bool
1900 sm_set_flag_if_changed::operator () (mem_ref_loc *loc)
1901 {
1902 /* Only set the flag for writes. */
1903 if (is_gimple_assign (loc->stmt)
1904 && gimple_assign_lhs_ptr (loc->stmt) == loc->ref)
1905 {
1906 gimple_stmt_iterator gsi = gsi_for_stmt (loc->stmt);
1907 gimple *stmt = gimple_build_assign (flag, boolean_true_node);
1908 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
1909 }
1910 return false;
1911 }
1912
1913 /* Helper function for execute_sm. On every location where REF is
1914 set, set an appropriate flag indicating the store. */
1915
1916 static tree
1917 execute_sm_if_changed_flag_set (struct loop *loop, im_mem_ref *ref)
1918 {
1919 tree flag;
1920 char *str = get_lsm_tmp_name (ref->mem.ref, ~0, "_flag");
1921 flag = create_tmp_reg (boolean_type_node, str);
1922 for_all_locs_in_loop (loop, ref, sm_set_flag_if_changed (flag));
1923 return flag;
1924 }
1925
1926 /* Executes store motion of memory reference REF from LOOP.
1927 Exits from the LOOP are stored in EXITS. The initialization of the
1928 temporary variable is put to the preheader of the loop, and assignments
1929 to the reference from the temporary variable are emitted to exits. */
1930
1931 static void
1932 execute_sm (struct loop *loop, vec<edge> exits, im_mem_ref *ref)
1933 {
1934 tree tmp_var, store_flag = NULL_TREE;
1935 unsigned i;
1936 gassign *load;
1937 struct fmt_data fmt_data;
1938 edge ex;
1939 struct lim_aux_data *lim_data;
1940 bool multi_threaded_model_p = false;
1941 gimple_stmt_iterator gsi;
1942
1943 if (dump_file && (dump_flags & TDF_DETAILS))
1944 {
1945 fprintf (dump_file, "Executing store motion of ");
1946 print_generic_expr (dump_file, ref->mem.ref, 0);
1947 fprintf (dump_file, " from loop %d\n", loop->num);
1948 }
1949
1950 tmp_var = create_tmp_reg (TREE_TYPE (ref->mem.ref),
1951 get_lsm_tmp_name (ref->mem.ref, ~0));
1952
1953 fmt_data.loop = loop;
1954 fmt_data.orig_loop = loop;
1955 for_each_index (&ref->mem.ref, force_move_till, &fmt_data);
1956
1957 if (bb_in_transaction (loop_preheader_edge (loop)->src)
1958 || !PARAM_VALUE (PARAM_ALLOW_STORE_DATA_RACES))
1959 multi_threaded_model_p = true;
1960
1961 if (multi_threaded_model_p)
1962 store_flag = execute_sm_if_changed_flag_set (loop, ref);
1963
1964 rewrite_mem_refs (loop, ref, tmp_var);
1965
1966 /* Emit the load code on a random exit edge or into the latch if
1967 the loop does not exit, so that we are sure it will be processed
1968 by move_computations after all dependencies. */
1969 gsi = gsi_for_stmt (first_mem_ref_loc (loop, ref)->stmt);
1970
1971 /* FIXME/TODO: For the multi-threaded variant, we could avoid this
1972 load altogether, since the store is predicated by a flag. We
1973 could, do the load only if it was originally in the loop. */
1974 load = gimple_build_assign (tmp_var, unshare_expr (ref->mem.ref));
1975 lim_data = init_lim_data (load);
1976 lim_data->max_loop = loop;
1977 lim_data->tgt_loop = loop;
1978 gsi_insert_before (&gsi, load, GSI_SAME_STMT);
1979
1980 if (multi_threaded_model_p)
1981 {
1982 load = gimple_build_assign (store_flag, boolean_false_node);
1983 lim_data = init_lim_data (load);
1984 lim_data->max_loop = loop;
1985 lim_data->tgt_loop = loop;
1986 gsi_insert_before (&gsi, load, GSI_SAME_STMT);
1987 }
1988
1989 /* Sink the store to every exit from the loop. */
1990 FOR_EACH_VEC_ELT (exits, i, ex)
1991 if (!multi_threaded_model_p)
1992 {
1993 gassign *store;
1994 store = gimple_build_assign (unshare_expr (ref->mem.ref), tmp_var);
1995 gsi_insert_on_edge (ex, store);
1996 }
1997 else
1998 execute_sm_if_changed (ex, ref->mem.ref, tmp_var, store_flag);
1999 }
2000
2001 /* Hoists memory references MEM_REFS out of LOOP. EXITS is the list of exit
2002 edges of the LOOP. */
2003
2004 static void
2005 hoist_memory_references (struct loop *loop, bitmap mem_refs,
2006 vec<edge> exits)
2007 {
2008 im_mem_ref *ref;
2009 unsigned i;
2010 bitmap_iterator bi;
2011
2012 EXECUTE_IF_SET_IN_BITMAP (mem_refs, 0, i, bi)
2013 {
2014 ref = memory_accesses.refs_list[i];
2015 execute_sm (loop, exits, ref);
2016 }
2017 }
2018
2019 struct ref_always_accessed
2020 {
2021 ref_always_accessed (struct loop *loop_, bool stored_p_)
2022 : loop (loop_), stored_p (stored_p_) {}
2023 bool operator () (mem_ref_loc *loc);
2024 struct loop *loop;
2025 bool stored_p;
2026 };
2027
2028 bool
2029 ref_always_accessed::operator () (mem_ref_loc *loc)
2030 {
2031 struct loop *must_exec;
2032
2033 if (!get_lim_data (loc->stmt))
2034 return false;
2035
2036 /* If we require an always executed store make sure the statement
2037 stores to the reference. */
2038 if (stored_p)
2039 {
2040 tree lhs = gimple_get_lhs (loc->stmt);
2041 if (!lhs
2042 || lhs != *loc->ref)
2043 return false;
2044 }
2045
2046 must_exec = get_lim_data (loc->stmt)->always_executed_in;
2047 if (!must_exec)
2048 return false;
2049
2050 if (must_exec == loop
2051 || flow_loop_nested_p (must_exec, loop))
2052 return true;
2053
2054 return false;
2055 }
2056
2057 /* Returns true if REF is always accessed in LOOP. If STORED_P is true
2058 make sure REF is always stored to in LOOP. */
2059
2060 static bool
2061 ref_always_accessed_p (struct loop *loop, im_mem_ref *ref, bool stored_p)
2062 {
2063 return for_all_locs_in_loop (loop, ref,
2064 ref_always_accessed (loop, stored_p));
2065 }
2066
2067 /* Returns true if REF1 and REF2 are independent. */
2068
2069 static bool
2070 refs_independent_p (im_mem_ref *ref1, im_mem_ref *ref2)
2071 {
2072 if (ref1 == ref2)
2073 return true;
2074
2075 if (dump_file && (dump_flags & TDF_DETAILS))
2076 fprintf (dump_file, "Querying dependency of refs %u and %u: ",
2077 ref1->id, ref2->id);
2078
2079 if (mem_refs_may_alias_p (ref1, ref2, &memory_accesses.ttae_cache))
2080 {
2081 if (dump_file && (dump_flags & TDF_DETAILS))
2082 fprintf (dump_file, "dependent.\n");
2083 return false;
2084 }
2085 else
2086 {
2087 if (dump_file && (dump_flags & TDF_DETAILS))
2088 fprintf (dump_file, "independent.\n");
2089 return true;
2090 }
2091 }
2092
2093 /* Mark REF dependent on stores or loads (according to STORED_P) in LOOP
2094 and its super-loops. */
2095
2096 static void
2097 record_dep_loop (struct loop *loop, im_mem_ref *ref, bool stored_p)
2098 {
2099 /* We can propagate dependent-in-loop bits up the loop
2100 hierarchy to all outer loops. */
2101 while (loop != current_loops->tree_root
2102 && bitmap_set_bit (&ref->dep_loop, LOOP_DEP_BIT (loop->num, stored_p)))
2103 loop = loop_outer (loop);
2104 }
2105
2106 /* Returns true if REF is independent on all other memory references in
2107 LOOP. */
2108
2109 static bool
2110 ref_indep_loop_p_1 (struct loop *loop, im_mem_ref *ref, bool stored_p)
2111 {
2112 bitmap refs_to_check;
2113 unsigned i;
2114 bitmap_iterator bi;
2115 im_mem_ref *aref;
2116
2117 if (stored_p)
2118 refs_to_check = &memory_accesses.refs_in_loop[loop->num];
2119 else
2120 refs_to_check = &memory_accesses.refs_stored_in_loop[loop->num];
2121
2122 if (bitmap_bit_p (refs_to_check, UNANALYZABLE_MEM_ID))
2123 return false;
2124
2125 EXECUTE_IF_SET_IN_BITMAP (refs_to_check, 0, i, bi)
2126 {
2127 aref = memory_accesses.refs_list[i];
2128 if (!refs_independent_p (ref, aref))
2129 return false;
2130 }
2131
2132 return true;
2133 }
2134
2135 /* Returns true if REF is independent on all other memory references in
2136 LOOP. Wrapper over ref_indep_loop_p_1, caching its results. */
2137
2138 static bool
2139 ref_indep_loop_p_2 (struct loop *loop, im_mem_ref *ref, bool stored_p)
2140 {
2141 stored_p |= (ref->stored && bitmap_bit_p (ref->stored, loop->num));
2142
2143 if (bitmap_bit_p (&ref->indep_loop, LOOP_DEP_BIT (loop->num, stored_p)))
2144 return true;
2145 if (bitmap_bit_p (&ref->dep_loop, LOOP_DEP_BIT (loop->num, stored_p)))
2146 return false;
2147
2148 struct loop *inner = loop->inner;
2149 while (inner)
2150 {
2151 if (!ref_indep_loop_p_2 (inner, ref, stored_p))
2152 return false;
2153 inner = inner->next;
2154 }
2155
2156 bool indep_p = ref_indep_loop_p_1 (loop, ref, stored_p);
2157
2158 if (dump_file && (dump_flags & TDF_DETAILS))
2159 fprintf (dump_file, "Querying dependencies of ref %u in loop %d: %s\n",
2160 ref->id, loop->num, indep_p ? "independent" : "dependent");
2161
2162 /* Record the computed result in the cache. */
2163 if (indep_p)
2164 {
2165 if (bitmap_set_bit (&ref->indep_loop, LOOP_DEP_BIT (loop->num, stored_p))
2166 && stored_p)
2167 {
2168 /* If it's independend against all refs then it's independent
2169 against stores, too. */
2170 bitmap_set_bit (&ref->indep_loop, LOOP_DEP_BIT (loop->num, false));
2171 }
2172 }
2173 else
2174 {
2175 record_dep_loop (loop, ref, stored_p);
2176 if (!stored_p)
2177 {
2178 /* If it's dependent against stores it's dependent against
2179 all refs, too. */
2180 record_dep_loop (loop, ref, true);
2181 }
2182 }
2183
2184 return indep_p;
2185 }
2186
2187 /* Returns true if REF is independent on all other memory references in
2188 LOOP. */
2189
2190 static bool
2191 ref_indep_loop_p (struct loop *loop, im_mem_ref *ref)
2192 {
2193 gcc_checking_assert (MEM_ANALYZABLE (ref));
2194
2195 return ref_indep_loop_p_2 (loop, ref, false);
2196 }
2197
2198 /* Returns true if we can perform store motion of REF from LOOP. */
2199
2200 static bool
2201 can_sm_ref_p (struct loop *loop, im_mem_ref *ref)
2202 {
2203 tree base;
2204
2205 /* Can't hoist unanalyzable refs. */
2206 if (!MEM_ANALYZABLE (ref))
2207 return false;
2208
2209 /* It should be movable. */
2210 if (!is_gimple_reg_type (TREE_TYPE (ref->mem.ref))
2211 || TREE_THIS_VOLATILE (ref->mem.ref)
2212 || !for_each_index (&ref->mem.ref, may_move_till, loop))
2213 return false;
2214
2215 /* If it can throw fail, we do not properly update EH info. */
2216 if (tree_could_throw_p (ref->mem.ref))
2217 return false;
2218
2219 /* If it can trap, it must be always executed in LOOP.
2220 Readonly memory locations may trap when storing to them, but
2221 tree_could_trap_p is a predicate for rvalues, so check that
2222 explicitly. */
2223 base = get_base_address (ref->mem.ref);
2224 if ((tree_could_trap_p (ref->mem.ref)
2225 || (DECL_P (base) && TREE_READONLY (base)))
2226 && !ref_always_accessed_p (loop, ref, true))
2227 return false;
2228
2229 /* And it must be independent on all other memory references
2230 in LOOP. */
2231 if (!ref_indep_loop_p (loop, ref))
2232 return false;
2233
2234 return true;
2235 }
2236
2237 /* Marks the references in LOOP for that store motion should be performed
2238 in REFS_TO_SM. SM_EXECUTED is the set of references for that store
2239 motion was performed in one of the outer loops. */
2240
2241 static void
2242 find_refs_for_sm (struct loop *loop, bitmap sm_executed, bitmap refs_to_sm)
2243 {
2244 bitmap refs = &memory_accesses.all_refs_stored_in_loop[loop->num];
2245 unsigned i;
2246 bitmap_iterator bi;
2247 im_mem_ref *ref;
2248
2249 EXECUTE_IF_AND_COMPL_IN_BITMAP (refs, sm_executed, 0, i, bi)
2250 {
2251 ref = memory_accesses.refs_list[i];
2252 if (can_sm_ref_p (loop, ref))
2253 bitmap_set_bit (refs_to_sm, i);
2254 }
2255 }
2256
2257 /* Checks whether LOOP (with exits stored in EXITS array) is suitable
2258 for a store motion optimization (i.e. whether we can insert statement
2259 on its exits). */
2260
2261 static bool
2262 loop_suitable_for_sm (struct loop *loop ATTRIBUTE_UNUSED,
2263 vec<edge> exits)
2264 {
2265 unsigned i;
2266 edge ex;
2267
2268 FOR_EACH_VEC_ELT (exits, i, ex)
2269 if (ex->flags & (EDGE_ABNORMAL | EDGE_EH))
2270 return false;
2271
2272 return true;
2273 }
2274
2275 /* Try to perform store motion for all memory references modified inside
2276 LOOP. SM_EXECUTED is the bitmap of the memory references for that
2277 store motion was executed in one of the outer loops. */
2278
2279 static void
2280 store_motion_loop (struct loop *loop, bitmap sm_executed)
2281 {
2282 vec<edge> exits = get_loop_exit_edges (loop);
2283 struct loop *subloop;
2284 bitmap sm_in_loop = BITMAP_ALLOC (&lim_bitmap_obstack);
2285
2286 if (loop_suitable_for_sm (loop, exits))
2287 {
2288 find_refs_for_sm (loop, sm_executed, sm_in_loop);
2289 hoist_memory_references (loop, sm_in_loop, exits);
2290 }
2291 exits.release ();
2292
2293 bitmap_ior_into (sm_executed, sm_in_loop);
2294 for (subloop = loop->inner; subloop != NULL; subloop = subloop->next)
2295 store_motion_loop (subloop, sm_executed);
2296 bitmap_and_compl_into (sm_executed, sm_in_loop);
2297 BITMAP_FREE (sm_in_loop);
2298 }
2299
2300 /* Try to perform store motion for all memory references modified inside
2301 loops. */
2302
2303 static void
2304 store_motion (void)
2305 {
2306 struct loop *loop;
2307 bitmap sm_executed = BITMAP_ALLOC (&lim_bitmap_obstack);
2308
2309 for (loop = current_loops->tree_root->inner; loop != NULL; loop = loop->next)
2310 store_motion_loop (loop, sm_executed);
2311
2312 BITMAP_FREE (sm_executed);
2313 gsi_commit_edge_inserts ();
2314 }
2315
2316 /* Fills ALWAYS_EXECUTED_IN information for basic blocks of LOOP, i.e.
2317 for each such basic block bb records the outermost loop for that execution
2318 of its header implies execution of bb. CONTAINS_CALL is the bitmap of
2319 blocks that contain a nonpure call. */
2320
2321 static void
2322 fill_always_executed_in_1 (struct loop *loop, sbitmap contains_call)
2323 {
2324 basic_block bb = NULL, *bbs, last = NULL;
2325 unsigned i;
2326 edge e;
2327 struct loop *inn_loop = loop;
2328
2329 if (ALWAYS_EXECUTED_IN (loop->header) == NULL)
2330 {
2331 bbs = get_loop_body_in_dom_order (loop);
2332
2333 for (i = 0; i < loop->num_nodes; i++)
2334 {
2335 edge_iterator ei;
2336 bb = bbs[i];
2337
2338 if (dominated_by_p (CDI_DOMINATORS, loop->latch, bb))
2339 last = bb;
2340
2341 if (bitmap_bit_p (contains_call, bb->index))
2342 break;
2343
2344 FOR_EACH_EDGE (e, ei, bb->succs)
2345 if (!flow_bb_inside_loop_p (loop, e->dest))
2346 break;
2347 if (e)
2348 break;
2349
2350 /* A loop might be infinite (TODO use simple loop analysis
2351 to disprove this if possible). */
2352 if (bb->flags & BB_IRREDUCIBLE_LOOP)
2353 break;
2354
2355 if (!flow_bb_inside_loop_p (inn_loop, bb))
2356 break;
2357
2358 if (bb->loop_father->header == bb)
2359 {
2360 if (!dominated_by_p (CDI_DOMINATORS, loop->latch, bb))
2361 break;
2362
2363 /* In a loop that is always entered we may proceed anyway.
2364 But record that we entered it and stop once we leave it. */
2365 inn_loop = bb->loop_father;
2366 }
2367 }
2368
2369 while (1)
2370 {
2371 SET_ALWAYS_EXECUTED_IN (last, loop);
2372 if (last == loop->header)
2373 break;
2374 last = get_immediate_dominator (CDI_DOMINATORS, last);
2375 }
2376
2377 free (bbs);
2378 }
2379
2380 for (loop = loop->inner; loop; loop = loop->next)
2381 fill_always_executed_in_1 (loop, contains_call);
2382 }
2383
2384 /* Fills ALWAYS_EXECUTED_IN information for basic blocks, i.e.
2385 for each such basic block bb records the outermost loop for that execution
2386 of its header implies execution of bb. */
2387
2388 static void
2389 fill_always_executed_in (void)
2390 {
2391 sbitmap contains_call = sbitmap_alloc (last_basic_block_for_fn (cfun));
2392 basic_block bb;
2393 struct loop *loop;
2394
2395 bitmap_clear (contains_call);
2396 FOR_EACH_BB_FN (bb, cfun)
2397 {
2398 gimple_stmt_iterator gsi;
2399 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2400 {
2401 if (nonpure_call_p (gsi_stmt (gsi)))
2402 break;
2403 }
2404
2405 if (!gsi_end_p (gsi))
2406 bitmap_set_bit (contains_call, bb->index);
2407 }
2408
2409 for (loop = current_loops->tree_root->inner; loop; loop = loop->next)
2410 fill_always_executed_in_1 (loop, contains_call);
2411
2412 sbitmap_free (contains_call);
2413 }
2414
2415
2416 /* Compute the global information needed by the loop invariant motion pass. */
2417
2418 static void
2419 tree_ssa_lim_initialize (void)
2420 {
2421 struct loop *loop;
2422 unsigned i;
2423
2424 bitmap_obstack_initialize (&lim_bitmap_obstack);
2425 gcc_obstack_init (&mem_ref_obstack);
2426 lim_aux_data_map = new hash_map<gimple *, lim_aux_data *>;
2427
2428 if (flag_tm)
2429 compute_transaction_bits ();
2430
2431 alloc_aux_for_edges (0);
2432
2433 memory_accesses.refs = new hash_table<mem_ref_hasher> (100);
2434 memory_accesses.refs_list.create (100);
2435 /* Allocate a special, unanalyzable mem-ref with ID zero. */
2436 memory_accesses.refs_list.quick_push
2437 (mem_ref_alloc (error_mark_node, 0, UNANALYZABLE_MEM_ID));
2438
2439 memory_accesses.refs_in_loop.create (number_of_loops (cfun));
2440 memory_accesses.refs_in_loop.quick_grow (number_of_loops (cfun));
2441 memory_accesses.refs_stored_in_loop.create (number_of_loops (cfun));
2442 memory_accesses.refs_stored_in_loop.quick_grow (number_of_loops (cfun));
2443 memory_accesses.all_refs_stored_in_loop.create (number_of_loops (cfun));
2444 memory_accesses.all_refs_stored_in_loop.quick_grow (number_of_loops (cfun));
2445
2446 for (i = 0; i < number_of_loops (cfun); i++)
2447 {
2448 bitmap_initialize (&memory_accesses.refs_in_loop[i],
2449 &lim_bitmap_obstack);
2450 bitmap_initialize (&memory_accesses.refs_stored_in_loop[i],
2451 &lim_bitmap_obstack);
2452 bitmap_initialize (&memory_accesses.all_refs_stored_in_loop[i],
2453 &lim_bitmap_obstack);
2454 }
2455
2456 memory_accesses.ttae_cache = NULL;
2457
2458 /* Initialize bb_loop_postorder with a mapping from loop->num to
2459 its postorder index. */
2460 i = 0;
2461 bb_loop_postorder = XNEWVEC (unsigned, number_of_loops (cfun));
2462 FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
2463 bb_loop_postorder[loop->num] = i++;
2464 }
2465
2466 /* Cleans up after the invariant motion pass. */
2467
2468 static void
2469 tree_ssa_lim_finalize (void)
2470 {
2471 basic_block bb;
2472 unsigned i;
2473 im_mem_ref *ref;
2474
2475 free_aux_for_edges ();
2476
2477 FOR_EACH_BB_FN (bb, cfun)
2478 SET_ALWAYS_EXECUTED_IN (bb, NULL);
2479
2480 bitmap_obstack_release (&lim_bitmap_obstack);
2481 delete lim_aux_data_map;
2482
2483 delete memory_accesses.refs;
2484 memory_accesses.refs = NULL;
2485
2486 FOR_EACH_VEC_ELT (memory_accesses.refs_list, i, ref)
2487 memref_free (ref);
2488 memory_accesses.refs_list.release ();
2489 obstack_free (&mem_ref_obstack, NULL);
2490
2491 memory_accesses.refs_in_loop.release ();
2492 memory_accesses.refs_stored_in_loop.release ();
2493 memory_accesses.all_refs_stored_in_loop.release ();
2494
2495 if (memory_accesses.ttae_cache)
2496 free_affine_expand_cache (&memory_accesses.ttae_cache);
2497
2498 free (bb_loop_postorder);
2499 }
2500
2501 /* Moves invariants from loops. Only "expensive" invariants are moved out --
2502 i.e. those that are likely to be win regardless of the register pressure. */
2503
2504 unsigned int
2505 tree_ssa_lim (void)
2506 {
2507 unsigned int todo;
2508
2509 tree_ssa_lim_initialize ();
2510
2511 /* Gathers information about memory accesses in the loops. */
2512 analyze_memory_references ();
2513
2514 /* Fills ALWAYS_EXECUTED_IN information for basic blocks. */
2515 fill_always_executed_in ();
2516
2517 /* For each statement determine the outermost loop in that it is
2518 invariant and cost for computing the invariant. */
2519 invariantness_dom_walker (CDI_DOMINATORS)
2520 .walk (cfun->cfg->x_entry_block_ptr);
2521
2522 /* Execute store motion. Force the necessary invariants to be moved
2523 out of the loops as well. */
2524 store_motion ();
2525
2526 /* Move the expressions that are expensive enough. */
2527 todo = move_computations ();
2528
2529 tree_ssa_lim_finalize ();
2530
2531 return todo;
2532 }
2533
2534 /* Loop invariant motion pass. */
2535
2536 namespace {
2537
2538 const pass_data pass_data_lim =
2539 {
2540 GIMPLE_PASS, /* type */
2541 "lim", /* name */
2542 OPTGROUP_LOOP, /* optinfo_flags */
2543 TV_LIM, /* tv_id */
2544 PROP_cfg, /* properties_required */
2545 0, /* properties_provided */
2546 0, /* properties_destroyed */
2547 0, /* todo_flags_start */
2548 0, /* todo_flags_finish */
2549 };
2550
2551 class pass_lim : public gimple_opt_pass
2552 {
2553 public:
2554 pass_lim (gcc::context *ctxt)
2555 : gimple_opt_pass (pass_data_lim, ctxt)
2556 {}
2557
2558 /* opt_pass methods: */
2559 opt_pass * clone () { return new pass_lim (m_ctxt); }
2560 virtual bool gate (function *) { return flag_tree_loop_im != 0; }
2561 virtual unsigned int execute (function *);
2562
2563 }; // class pass_lim
2564
2565 unsigned int
2566 pass_lim::execute (function *fun)
2567 {
2568 if (number_of_loops (fun) <= 1)
2569 return 0;
2570
2571 return tree_ssa_lim ();
2572 }
2573
2574 } // anon namespace
2575
2576 gimple_opt_pass *
2577 make_pass_lim (gcc::context *ctxt)
2578 {
2579 return new pass_lim (ctxt);
2580 }
2581
2582