kernel - support dummy reallocblks in devfs
[dragonfly.git] / contrib / gcc-5.0 / gcc / tree-predcom.c
blob8f6a75ec9427d309971b44cd6800b240ff7e0f3d
1 /* Predictive commoning.
2 Copyright (C) 2005-2015 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 3, or (at your option) any
9 later version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 /* This file implements the predictive commoning optimization. Predictive
21 commoning can be viewed as CSE around a loop, and with some improvements,
22 as generalized strength reduction-- i.e., reusing values computed in
23 earlier iterations of a loop in the later ones. So far, the pass only
24 handles the most useful case, that is, reusing values of memory references.
25 If you think this is all just a special case of PRE, you are sort of right;
26 however, concentrating on loops is simpler, and makes it possible to
27 incorporate data dependence analysis to detect the opportunities, perform
28 loop unrolling to avoid copies together with renaming immediately,
29 and if needed, we could also take register pressure into account.
31 Let us demonstrate what is done on an example:
33 for (i = 0; i < 100; i++)
35 a[i+2] = a[i] + a[i+1];
36 b[10] = b[10] + i;
37 c[i] = c[99 - i];
38 d[i] = d[i + 1];
41 1) We find data references in the loop, and split them to mutually
42 independent groups (i.e., we find components of a data dependence
43 graph). We ignore read-read dependences whose distance is not constant.
44 (TODO -- we could also ignore antidependences). In this example, we
45 find the following groups:
47 a[i]{read}, a[i+1]{read}, a[i+2]{write}
48 b[10]{read}, b[10]{write}
49 c[99 - i]{read}, c[i]{write}
50 d[i + 1]{read}, d[i]{write}
52 2) Inside each of the group, we verify several conditions:
53 a) all the references must differ in indices only, and the indices
54 must all have the same step
55 b) the references must dominate loop latch (and thus, they must be
56 ordered by dominance relation).
57 c) the distance of the indices must be a small multiple of the step
58 We are then able to compute the difference of the references (# of
59 iterations before they point to the same place as the first of them).
60 Also, in case there are writes in the loop, we split the groups into
61 chains whose head is the write whose values are used by the reads in
62 the same chain. The chains are then processed independently,
63 making the further transformations simpler. Also, the shorter chains
64 need the same number of registers, but may require lower unrolling
65 factor in order to get rid of the copies on the loop latch.
67 In our example, we get the following chains (the chain for c is invalid).
69 a[i]{read,+0}, a[i+1]{read,-1}, a[i+2]{write,-2}
70 b[10]{read,+0}, b[10]{write,+0}
71 d[i + 1]{read,+0}, d[i]{write,+1}
73 3) For each read, we determine the read or write whose value it reuses,
74 together with the distance of this reuse. I.e. we take the last
75 reference before it with distance 0, or the last of the references
76 with the smallest positive distance to the read. Then, we remove
77 the references that are not used in any of these chains, discard the
78 empty groups, and propagate all the links so that they point to the
79 single root reference of the chain (adjusting their distance
80 appropriately). Some extra care needs to be taken for references with
81 step 0. In our example (the numbers indicate the distance of the
82 reuse),
84 a[i] --> (*) 2, a[i+1] --> (*) 1, a[i+2] (*)
85 b[10] --> (*) 1, b[10] (*)
87 4) The chains are combined together if possible. If the corresponding
88 elements of two chains are always combined together with the same
89 operator, we remember just the result of this combination, instead
90 of remembering the values separately. We may need to perform
91 reassociation to enable combining, for example
93 e[i] + f[i+1] + e[i+1] + f[i]
95 can be reassociated as
97 (e[i] + f[i]) + (e[i+1] + f[i+1])
99 and we can combine the chains for e and f into one chain.
101 5) For each root reference (end of the chain) R, let N be maximum distance
102 of a reference reusing its value. Variables R0 up to RN are created,
103 together with phi nodes that transfer values from R1 .. RN to
104 R0 .. R(N-1).
105 Initial values are loaded to R0..R(N-1) (in case not all references
106 must necessarily be accessed and they may trap, we may fail here;
107 TODO sometimes, the loads could be guarded by a check for the number
108 of iterations). Values loaded/stored in roots are also copied to
109 RN. Other reads are replaced with the appropriate variable Ri.
110 Everything is put to SSA form.
112 As a small improvement, if R0 is dead after the root (i.e., all uses of
113 the value with the maximum distance dominate the root), we can avoid
114 creating RN and use R0 instead of it.
116 In our example, we get (only the parts concerning a and b are shown):
117 for (i = 0; i < 100; i++)
119 f = phi (a[0], s);
120 s = phi (a[1], f);
121 x = phi (b[10], x);
123 f = f + s;
124 a[i+2] = f;
125 x = x + i;
126 b[10] = x;
129 6) Factor F for unrolling is determined as the smallest common multiple of
130 (N + 1) for each root reference (N for references for that we avoided
131 creating RN). If F and the loop is small enough, loop is unrolled F
132 times. The stores to RN (R0) in the copies of the loop body are
133 periodically replaced with R0, R1, ... (R1, R2, ...), so that they can
134 be coalesced and the copies can be eliminated.
136 TODO -- copy propagation and other optimizations may change the live
137 ranges of the temporary registers and prevent them from being coalesced;
138 this may increase the register pressure.
140 In our case, F = 2 and the (main loop of the) result is
142 for (i = 0; i < ...; i += 2)
144 f = phi (a[0], f);
145 s = phi (a[1], s);
146 x = phi (b[10], x);
148 f = f + s;
149 a[i+2] = f;
150 x = x + i;
151 b[10] = x;
153 s = s + f;
154 a[i+3] = s;
155 x = x + i;
156 b[10] = x;
159 TODO -- stores killing other stores can be taken into account, e.g.,
160 for (i = 0; i < n; i++)
162 a[i] = 1;
163 a[i+2] = 2;
166 can be replaced with
168 t0 = a[0];
169 t1 = a[1];
170 for (i = 0; i < n; i++)
172 a[i] = 1;
173 t2 = 2;
174 t0 = t1;
175 t1 = t2;
177 a[n] = t0;
178 a[n+1] = t1;
180 The interesting part is that this would generalize store motion; still, since
181 sm is performed elsewhere, it does not seem that important.
183 Predictive commoning can be generalized for arbitrary computations (not
184 just memory loads), and also nontrivial transfer functions (e.g., replacing
185 i * i with ii_last + 2 * i + 1), to generalize strength reduction. */
187 #include "config.h"
188 #include "system.h"
189 #include "coretypes.h"
190 #include "tm.h"
191 #include "hash-set.h"
192 #include "machmode.h"
193 #include "vec.h"
194 #include "double-int.h"
195 #include "input.h"
196 #include "alias.h"
197 #include "symtab.h"
198 #include "wide-int.h"
199 #include "inchash.h"
200 #include "tree.h"
201 #include "fold-const.h"
202 #include "tm_p.h"
203 #include "cfgloop.h"
204 #include "predict.h"
205 #include "hard-reg-set.h"
206 #include "function.h"
207 #include "dominance.h"
208 #include "cfg.h"
209 #include "basic-block.h"
210 #include "tree-ssa-alias.h"
211 #include "internal-fn.h"
212 #include "tree-eh.h"
213 #include "gimple-expr.h"
214 #include "is-a.h"
215 #include "gimple.h"
216 #include "gimplify.h"
217 #include "gimple-iterator.h"
218 #include "gimplify-me.h"
219 #include "gimple-ssa.h"
220 #include "tree-phinodes.h"
221 #include "ssa-iterators.h"
222 #include "stringpool.h"
223 #include "tree-ssanames.h"
224 #include "tree-ssa-loop-ivopts.h"
225 #include "tree-ssa-loop-manip.h"
226 #include "tree-ssa-loop-niter.h"
227 #include "tree-ssa-loop.h"
228 #include "tree-into-ssa.h"
229 #include "hashtab.h"
230 #include "rtl.h"
231 #include "flags.h"
232 #include "statistics.h"
233 #include "real.h"
234 #include "fixed-value.h"
235 #include "insn-config.h"
236 #include "expmed.h"
237 #include "dojump.h"
238 #include "explow.h"
239 #include "calls.h"
240 #include "emit-rtl.h"
241 #include "varasm.h"
242 #include "stmt.h"
243 #include "expr.h"
244 #include "tree-dfa.h"
245 #include "tree-ssa.h"
246 #include "tree-data-ref.h"
247 #include "tree-scalar-evolution.h"
248 #include "tree-chrec.h"
249 #include "params.h"
250 #include "gimple-pretty-print.h"
251 #include "tree-pass.h"
252 #include "tree-affine.h"
253 #include "tree-inline.h"
254 #include "wide-int-print.h"
255 #include "builtins.h"
257 /* The maximum number of iterations between the considered memory
258 references. */
260 #define MAX_DISTANCE (target_avail_regs < 16 ? 4 : 8)
262 /* Data references (or phi nodes that carry data reference values across
263 loop iterations). */
265 typedef struct dref_d
267 /* The reference itself. */
268 struct data_reference *ref;
270 /* The statement in that the reference appears. */
271 gimple stmt;
273 /* In case that STMT is a phi node, this field is set to the SSA name
274 defined by it in replace_phis_by_defined_names (in order to avoid
275 pointing to phi node that got reallocated in the meantime). */
276 tree name_defined_by_phi;
278 /* Distance of the reference from the root of the chain (in number of
279 iterations of the loop). */
280 unsigned distance;
282 /* Number of iterations offset from the first reference in the component. */
283 widest_int offset;
285 /* Number of the reference in a component, in dominance ordering. */
286 unsigned pos;
288 /* True if the memory reference is always accessed when the loop is
289 entered. */
290 unsigned always_accessed : 1;
291 } *dref;
294 /* Type of the chain of the references. */
296 enum chain_type
298 /* The addresses of the references in the chain are constant. */
299 CT_INVARIANT,
301 /* There are only loads in the chain. */
302 CT_LOAD,
304 /* Root of the chain is store, the rest are loads. */
305 CT_STORE_LOAD,
307 /* A combination of two chains. */
308 CT_COMBINATION
311 /* Chains of data references. */
313 typedef struct chain
315 /* Type of the chain. */
316 enum chain_type type;
318 /* For combination chains, the operator and the two chains that are
319 combined, and the type of the result. */
320 enum tree_code op;
321 tree rslt_type;
322 struct chain *ch1, *ch2;
324 /* The references in the chain. */
325 vec<dref> refs;
327 /* The maximum distance of the reference in the chain from the root. */
328 unsigned length;
330 /* The variables used to copy the value throughout iterations. */
331 vec<tree> vars;
333 /* Initializers for the variables. */
334 vec<tree> inits;
336 /* True if there is a use of a variable with the maximal distance
337 that comes after the root in the loop. */
338 unsigned has_max_use_after : 1;
340 /* True if all the memory references in the chain are always accessed. */
341 unsigned all_always_accessed : 1;
343 /* True if this chain was combined together with some other chain. */
344 unsigned combined : 1;
345 } *chain_p;
348 /* Describes the knowledge about the step of the memory references in
349 the component. */
351 enum ref_step_type
353 /* The step is zero. */
354 RS_INVARIANT,
356 /* The step is nonzero. */
357 RS_NONZERO,
359 /* The step may or may not be nonzero. */
360 RS_ANY
363 /* Components of the data dependence graph. */
365 struct component
367 /* The references in the component. */
368 vec<dref> refs;
370 /* What we know about the step of the references in the component. */
371 enum ref_step_type comp_step;
373 /* Next component in the list. */
374 struct component *next;
377 /* Bitmap of ssa names defined by looparound phi nodes covered by chains. */
379 static bitmap looparound_phis;
381 /* Cache used by tree_to_aff_combination_expand. */
383 static hash_map<tree, name_expansion *> *name_expansions;
385 /* Dumps data reference REF to FILE. */
387 extern void dump_dref (FILE *, dref);
388 void
389 dump_dref (FILE *file, dref ref)
391 if (ref->ref)
393 fprintf (file, " ");
394 print_generic_expr (file, DR_REF (ref->ref), TDF_SLIM);
395 fprintf (file, " (id %u%s)\n", ref->pos,
396 DR_IS_READ (ref->ref) ? "" : ", write");
398 fprintf (file, " offset ");
399 print_decs (ref->offset, file);
400 fprintf (file, "\n");
402 fprintf (file, " distance %u\n", ref->distance);
404 else
406 if (gimple_code (ref->stmt) == GIMPLE_PHI)
407 fprintf (file, " looparound ref\n");
408 else
409 fprintf (file, " combination ref\n");
410 fprintf (file, " in statement ");
411 print_gimple_stmt (file, ref->stmt, 0, TDF_SLIM);
412 fprintf (file, "\n");
413 fprintf (file, " distance %u\n", ref->distance);
418 /* Dumps CHAIN to FILE. */
420 extern void dump_chain (FILE *, chain_p);
421 void
422 dump_chain (FILE *file, chain_p chain)
424 dref a;
425 const char *chain_type;
426 unsigned i;
427 tree var;
429 switch (chain->type)
431 case CT_INVARIANT:
432 chain_type = "Load motion";
433 break;
435 case CT_LOAD:
436 chain_type = "Loads-only";
437 break;
439 case CT_STORE_LOAD:
440 chain_type = "Store-loads";
441 break;
443 case CT_COMBINATION:
444 chain_type = "Combination";
445 break;
447 default:
448 gcc_unreachable ();
451 fprintf (file, "%s chain %p%s\n", chain_type, (void *) chain,
452 chain->combined ? " (combined)" : "");
453 if (chain->type != CT_INVARIANT)
454 fprintf (file, " max distance %u%s\n", chain->length,
455 chain->has_max_use_after ? "" : ", may reuse first");
457 if (chain->type == CT_COMBINATION)
459 fprintf (file, " equal to %p %s %p in type ",
460 (void *) chain->ch1, op_symbol_code (chain->op),
461 (void *) chain->ch2);
462 print_generic_expr (file, chain->rslt_type, TDF_SLIM);
463 fprintf (file, "\n");
466 if (chain->vars.exists ())
468 fprintf (file, " vars");
469 FOR_EACH_VEC_ELT (chain->vars, i, var)
471 fprintf (file, " ");
472 print_generic_expr (file, var, TDF_SLIM);
474 fprintf (file, "\n");
477 if (chain->inits.exists ())
479 fprintf (file, " inits");
480 FOR_EACH_VEC_ELT (chain->inits, i, var)
482 fprintf (file, " ");
483 print_generic_expr (file, var, TDF_SLIM);
485 fprintf (file, "\n");
488 fprintf (file, " references:\n");
489 FOR_EACH_VEC_ELT (chain->refs, i, a)
490 dump_dref (file, a);
492 fprintf (file, "\n");
495 /* Dumps CHAINS to FILE. */
497 extern void dump_chains (FILE *, vec<chain_p> );
498 void
499 dump_chains (FILE *file, vec<chain_p> chains)
501 chain_p chain;
502 unsigned i;
504 FOR_EACH_VEC_ELT (chains, i, chain)
505 dump_chain (file, chain);
508 /* Dumps COMP to FILE. */
510 extern void dump_component (FILE *, struct component *);
511 void
512 dump_component (FILE *file, struct component *comp)
514 dref a;
515 unsigned i;
517 fprintf (file, "Component%s:\n",
518 comp->comp_step == RS_INVARIANT ? " (invariant)" : "");
519 FOR_EACH_VEC_ELT (comp->refs, i, a)
520 dump_dref (file, a);
521 fprintf (file, "\n");
524 /* Dumps COMPS to FILE. */
526 extern void dump_components (FILE *, struct component *);
527 void
528 dump_components (FILE *file, struct component *comps)
530 struct component *comp;
532 for (comp = comps; comp; comp = comp->next)
533 dump_component (file, comp);
536 /* Frees a chain CHAIN. */
538 static void
539 release_chain (chain_p chain)
541 dref ref;
542 unsigned i;
544 if (chain == NULL)
545 return;
547 FOR_EACH_VEC_ELT (chain->refs, i, ref)
548 free (ref);
550 chain->refs.release ();
551 chain->vars.release ();
552 chain->inits.release ();
554 free (chain);
557 /* Frees CHAINS. */
559 static void
560 release_chains (vec<chain_p> chains)
562 unsigned i;
563 chain_p chain;
565 FOR_EACH_VEC_ELT (chains, i, chain)
566 release_chain (chain);
567 chains.release ();
570 /* Frees a component COMP. */
572 static void
573 release_component (struct component *comp)
575 comp->refs.release ();
576 free (comp);
579 /* Frees list of components COMPS. */
581 static void
582 release_components (struct component *comps)
584 struct component *act, *next;
586 for (act = comps; act; act = next)
588 next = act->next;
589 release_component (act);
593 /* Finds a root of tree given by FATHERS containing A, and performs path
594 shortening. */
596 static unsigned
597 component_of (unsigned fathers[], unsigned a)
599 unsigned root, n;
601 for (root = a; root != fathers[root]; root = fathers[root])
602 continue;
604 for (; a != root; a = n)
606 n = fathers[a];
607 fathers[a] = root;
610 return root;
613 /* Join operation for DFU. FATHERS gives the tree, SIZES are sizes of the
614 components, A and B are components to merge. */
616 static void
617 merge_comps (unsigned fathers[], unsigned sizes[], unsigned a, unsigned b)
619 unsigned ca = component_of (fathers, a);
620 unsigned cb = component_of (fathers, b);
622 if (ca == cb)
623 return;
625 if (sizes[ca] < sizes[cb])
627 sizes[cb] += sizes[ca];
628 fathers[ca] = cb;
630 else
632 sizes[ca] += sizes[cb];
633 fathers[cb] = ca;
637 /* Returns true if A is a reference that is suitable for predictive commoning
638 in the innermost loop that contains it. REF_STEP is set according to the
639 step of the reference A. */
641 static bool
642 suitable_reference_p (struct data_reference *a, enum ref_step_type *ref_step)
644 tree ref = DR_REF (a), step = DR_STEP (a);
646 if (!step
647 || TREE_THIS_VOLATILE (ref)
648 || !is_gimple_reg_type (TREE_TYPE (ref))
649 || tree_could_throw_p (ref))
650 return false;
652 if (integer_zerop (step))
653 *ref_step = RS_INVARIANT;
654 else if (integer_nonzerop (step))
655 *ref_step = RS_NONZERO;
656 else
657 *ref_step = RS_ANY;
659 return true;
662 /* Stores DR_OFFSET (DR) + DR_INIT (DR) to OFFSET. */
664 static void
665 aff_combination_dr_offset (struct data_reference *dr, aff_tree *offset)
667 tree type = TREE_TYPE (DR_OFFSET (dr));
668 aff_tree delta;
670 tree_to_aff_combination_expand (DR_OFFSET (dr), type, offset,
671 &name_expansions);
672 aff_combination_const (&delta, type, wi::to_widest (DR_INIT (dr)));
673 aff_combination_add (offset, &delta);
676 /* Determines number of iterations of the innermost enclosing loop before B
677 refers to exactly the same location as A and stores it to OFF. If A and
678 B do not have the same step, they never meet, or anything else fails,
679 returns false, otherwise returns true. Both A and B are assumed to
680 satisfy suitable_reference_p. */
682 static bool
683 determine_offset (struct data_reference *a, struct data_reference *b,
684 widest_int *off)
686 aff_tree diff, baseb, step;
687 tree typea, typeb;
689 /* Check that both the references access the location in the same type. */
690 typea = TREE_TYPE (DR_REF (a));
691 typeb = TREE_TYPE (DR_REF (b));
692 if (!useless_type_conversion_p (typeb, typea))
693 return false;
695 /* Check whether the base address and the step of both references is the
696 same. */
697 if (!operand_equal_p (DR_STEP (a), DR_STEP (b), 0)
698 || !operand_equal_p (DR_BASE_ADDRESS (a), DR_BASE_ADDRESS (b), 0))
699 return false;
701 if (integer_zerop (DR_STEP (a)))
703 /* If the references have loop invariant address, check that they access
704 exactly the same location. */
705 *off = 0;
706 return (operand_equal_p (DR_OFFSET (a), DR_OFFSET (b), 0)
707 && operand_equal_p (DR_INIT (a), DR_INIT (b), 0));
710 /* Compare the offsets of the addresses, and check whether the difference
711 is a multiple of step. */
712 aff_combination_dr_offset (a, &diff);
713 aff_combination_dr_offset (b, &baseb);
714 aff_combination_scale (&baseb, -1);
715 aff_combination_add (&diff, &baseb);
717 tree_to_aff_combination_expand (DR_STEP (a), TREE_TYPE (DR_STEP (a)),
718 &step, &name_expansions);
719 return aff_combination_constant_multiple_p (&diff, &step, off);
722 /* Returns the last basic block in LOOP for that we are sure that
723 it is executed whenever the loop is entered. */
725 static basic_block
726 last_always_executed_block (struct loop *loop)
728 unsigned i;
729 vec<edge> exits = get_loop_exit_edges (loop);
730 edge ex;
731 basic_block last = loop->latch;
733 FOR_EACH_VEC_ELT (exits, i, ex)
734 last = nearest_common_dominator (CDI_DOMINATORS, last, ex->src);
735 exits.release ();
737 return last;
740 /* Splits dependence graph on DATAREFS described by DEPENDS to components. */
742 static struct component *
743 split_data_refs_to_components (struct loop *loop,
744 vec<data_reference_p> datarefs,
745 vec<ddr_p> depends)
747 unsigned i, n = datarefs.length ();
748 unsigned ca, ia, ib, bad;
749 unsigned *comp_father = XNEWVEC (unsigned, n + 1);
750 unsigned *comp_size = XNEWVEC (unsigned, n + 1);
751 struct component **comps;
752 struct data_reference *dr, *dra, *drb;
753 struct data_dependence_relation *ddr;
754 struct component *comp_list = NULL, *comp;
755 dref dataref;
756 basic_block last_always_executed = last_always_executed_block (loop);
758 FOR_EACH_VEC_ELT (datarefs, i, dr)
760 if (!DR_REF (dr))
762 /* A fake reference for call or asm_expr that may clobber memory;
763 just fail. */
764 goto end;
766 /* predcom pass isn't prepared to handle calls with data references. */
767 if (is_gimple_call (DR_STMT (dr)))
768 goto end;
769 dr->aux = (void *) (size_t) i;
770 comp_father[i] = i;
771 comp_size[i] = 1;
774 /* A component reserved for the "bad" data references. */
775 comp_father[n] = n;
776 comp_size[n] = 1;
778 FOR_EACH_VEC_ELT (datarefs, i, dr)
780 enum ref_step_type dummy;
782 if (!suitable_reference_p (dr, &dummy))
784 ia = (unsigned) (size_t) dr->aux;
785 merge_comps (comp_father, comp_size, n, ia);
789 FOR_EACH_VEC_ELT (depends, i, ddr)
791 widest_int dummy_off;
793 if (DDR_ARE_DEPENDENT (ddr) == chrec_known)
794 continue;
796 dra = DDR_A (ddr);
797 drb = DDR_B (ddr);
798 ia = component_of (comp_father, (unsigned) (size_t) dra->aux);
799 ib = component_of (comp_father, (unsigned) (size_t) drb->aux);
800 if (ia == ib)
801 continue;
803 bad = component_of (comp_father, n);
805 /* If both A and B are reads, we may ignore unsuitable dependences. */
806 if (DR_IS_READ (dra) && DR_IS_READ (drb))
808 if (ia == bad || ib == bad
809 || !determine_offset (dra, drb, &dummy_off))
810 continue;
812 /* If A is read and B write or vice versa and there is unsuitable
813 dependence, instead of merging both components into a component
814 that will certainly not pass suitable_component_p, just put the
815 read into bad component, perhaps at least the write together with
816 all the other data refs in it's component will be optimizable. */
817 else if (DR_IS_READ (dra) && ib != bad)
819 if (ia == bad)
820 continue;
821 else if (!determine_offset (dra, drb, &dummy_off))
823 merge_comps (comp_father, comp_size, bad, ia);
824 continue;
827 else if (DR_IS_READ (drb) && ia != bad)
829 if (ib == bad)
830 continue;
831 else if (!determine_offset (dra, drb, &dummy_off))
833 merge_comps (comp_father, comp_size, bad, ib);
834 continue;
838 merge_comps (comp_father, comp_size, ia, ib);
841 comps = XCNEWVEC (struct component *, n);
842 bad = component_of (comp_father, n);
843 FOR_EACH_VEC_ELT (datarefs, i, dr)
845 ia = (unsigned) (size_t) dr->aux;
846 ca = component_of (comp_father, ia);
847 if (ca == bad)
848 continue;
850 comp = comps[ca];
851 if (!comp)
853 comp = XCNEW (struct component);
854 comp->refs.create (comp_size[ca]);
855 comps[ca] = comp;
858 dataref = XCNEW (struct dref_d);
859 dataref->ref = dr;
860 dataref->stmt = DR_STMT (dr);
861 dataref->offset = 0;
862 dataref->distance = 0;
864 dataref->always_accessed
865 = dominated_by_p (CDI_DOMINATORS, last_always_executed,
866 gimple_bb (dataref->stmt));
867 dataref->pos = comp->refs.length ();
868 comp->refs.quick_push (dataref);
871 for (i = 0; i < n; i++)
873 comp = comps[i];
874 if (comp)
876 comp->next = comp_list;
877 comp_list = comp;
880 free (comps);
882 end:
883 free (comp_father);
884 free (comp_size);
885 return comp_list;
888 /* Returns true if the component COMP satisfies the conditions
889 described in 2) at the beginning of this file. LOOP is the current
890 loop. */
892 static bool
893 suitable_component_p (struct loop *loop, struct component *comp)
895 unsigned i;
896 dref a, first;
897 basic_block ba, bp = loop->header;
898 bool ok, has_write = false;
900 FOR_EACH_VEC_ELT (comp->refs, i, a)
902 ba = gimple_bb (a->stmt);
904 if (!just_once_each_iteration_p (loop, ba))
905 return false;
907 gcc_assert (dominated_by_p (CDI_DOMINATORS, ba, bp));
908 bp = ba;
910 if (DR_IS_WRITE (a->ref))
911 has_write = true;
914 first = comp->refs[0];
915 ok = suitable_reference_p (first->ref, &comp->comp_step);
916 gcc_assert (ok);
917 first->offset = 0;
919 for (i = 1; comp->refs.iterate (i, &a); i++)
921 if (!determine_offset (first->ref, a->ref, &a->offset))
922 return false;
924 #ifdef ENABLE_CHECKING
926 enum ref_step_type a_step;
927 ok = suitable_reference_p (a->ref, &a_step);
928 gcc_assert (ok && a_step == comp->comp_step);
930 #endif
933 /* If there is a write inside the component, we must know whether the
934 step is nonzero or not -- we would not otherwise be able to recognize
935 whether the value accessed by reads comes from the OFFSET-th iteration
936 or the previous one. */
937 if (has_write && comp->comp_step == RS_ANY)
938 return false;
940 return true;
943 /* Check the conditions on references inside each of components COMPS,
944 and remove the unsuitable components from the list. The new list
945 of components is returned. The conditions are described in 2) at
946 the beginning of this file. LOOP is the current loop. */
948 static struct component *
949 filter_suitable_components (struct loop *loop, struct component *comps)
951 struct component **comp, *act;
953 for (comp = &comps; *comp; )
955 act = *comp;
956 if (suitable_component_p (loop, act))
957 comp = &act->next;
958 else
960 dref ref;
961 unsigned i;
963 *comp = act->next;
964 FOR_EACH_VEC_ELT (act->refs, i, ref)
965 free (ref);
966 release_component (act);
970 return comps;
973 /* Compares two drefs A and B by their offset and position. Callback for
974 qsort. */
976 static int
977 order_drefs (const void *a, const void *b)
979 const dref *const da = (const dref *) a;
980 const dref *const db = (const dref *) b;
981 int offcmp = wi::cmps ((*da)->offset, (*db)->offset);
983 if (offcmp != 0)
984 return offcmp;
986 return (*da)->pos - (*db)->pos;
989 /* Returns root of the CHAIN. */
991 static inline dref
992 get_chain_root (chain_p chain)
994 return chain->refs[0];
997 /* Adds REF to the chain CHAIN. */
999 static void
1000 add_ref_to_chain (chain_p chain, dref ref)
1002 dref root = get_chain_root (chain);
1004 gcc_assert (wi::les_p (root->offset, ref->offset));
1005 widest_int dist = ref->offset - root->offset;
1006 if (wi::leu_p (MAX_DISTANCE, dist))
1008 free (ref);
1009 return;
1011 gcc_assert (wi::fits_uhwi_p (dist));
1013 chain->refs.safe_push (ref);
1015 ref->distance = dist.to_uhwi ();
1017 if (ref->distance >= chain->length)
1019 chain->length = ref->distance;
1020 chain->has_max_use_after = false;
1023 if (ref->distance == chain->length
1024 && ref->pos > root->pos)
1025 chain->has_max_use_after = true;
1027 chain->all_always_accessed &= ref->always_accessed;
1030 /* Returns the chain for invariant component COMP. */
1032 static chain_p
1033 make_invariant_chain (struct component *comp)
1035 chain_p chain = XCNEW (struct chain);
1036 unsigned i;
1037 dref ref;
1039 chain->type = CT_INVARIANT;
1041 chain->all_always_accessed = true;
1043 FOR_EACH_VEC_ELT (comp->refs, i, ref)
1045 chain->refs.safe_push (ref);
1046 chain->all_always_accessed &= ref->always_accessed;
1049 return chain;
1052 /* Make a new chain rooted at REF. */
1054 static chain_p
1055 make_rooted_chain (dref ref)
1057 chain_p chain = XCNEW (struct chain);
1059 chain->type = DR_IS_READ (ref->ref) ? CT_LOAD : CT_STORE_LOAD;
1061 chain->refs.safe_push (ref);
1062 chain->all_always_accessed = ref->always_accessed;
1064 ref->distance = 0;
1066 return chain;
1069 /* Returns true if CHAIN is not trivial. */
1071 static bool
1072 nontrivial_chain_p (chain_p chain)
1074 return chain != NULL && chain->refs.length () > 1;
1077 /* Returns the ssa name that contains the value of REF, or NULL_TREE if there
1078 is no such name. */
1080 static tree
1081 name_for_ref (dref ref)
1083 tree name;
1085 if (is_gimple_assign (ref->stmt))
1087 if (!ref->ref || DR_IS_READ (ref->ref))
1088 name = gimple_assign_lhs (ref->stmt);
1089 else
1090 name = gimple_assign_rhs1 (ref->stmt);
1092 else
1093 name = PHI_RESULT (ref->stmt);
1095 return (TREE_CODE (name) == SSA_NAME ? name : NULL_TREE);
1098 /* Returns true if REF is a valid initializer for ROOT with given DISTANCE (in
1099 iterations of the innermost enclosing loop). */
1101 static bool
1102 valid_initializer_p (struct data_reference *ref,
1103 unsigned distance, struct data_reference *root)
1105 aff_tree diff, base, step;
1106 widest_int off;
1108 /* Both REF and ROOT must be accessing the same object. */
1109 if (!operand_equal_p (DR_BASE_ADDRESS (ref), DR_BASE_ADDRESS (root), 0))
1110 return false;
1112 /* The initializer is defined outside of loop, hence its address must be
1113 invariant inside the loop. */
1114 gcc_assert (integer_zerop (DR_STEP (ref)));
1116 /* If the address of the reference is invariant, initializer must access
1117 exactly the same location. */
1118 if (integer_zerop (DR_STEP (root)))
1119 return (operand_equal_p (DR_OFFSET (ref), DR_OFFSET (root), 0)
1120 && operand_equal_p (DR_INIT (ref), DR_INIT (root), 0));
1122 /* Verify that this index of REF is equal to the root's index at
1123 -DISTANCE-th iteration. */
1124 aff_combination_dr_offset (root, &diff);
1125 aff_combination_dr_offset (ref, &base);
1126 aff_combination_scale (&base, -1);
1127 aff_combination_add (&diff, &base);
1129 tree_to_aff_combination_expand (DR_STEP (root), TREE_TYPE (DR_STEP (root)),
1130 &step, &name_expansions);
1131 if (!aff_combination_constant_multiple_p (&diff, &step, &off))
1132 return false;
1134 if (off != distance)
1135 return false;
1137 return true;
1140 /* Finds looparound phi node of LOOP that copies the value of REF, and if its
1141 initial value is correct (equal to initial value of REF shifted by one
1142 iteration), returns the phi node. Otherwise, NULL_TREE is returned. ROOT
1143 is the root of the current chain. */
1145 static gphi *
1146 find_looparound_phi (struct loop *loop, dref ref, dref root)
1148 tree name, init, init_ref;
1149 gphi *phi = NULL;
1150 gimple init_stmt;
1151 edge latch = loop_latch_edge (loop);
1152 struct data_reference init_dr;
1153 gphi_iterator psi;
1155 if (is_gimple_assign (ref->stmt))
1157 if (DR_IS_READ (ref->ref))
1158 name = gimple_assign_lhs (ref->stmt);
1159 else
1160 name = gimple_assign_rhs1 (ref->stmt);
1162 else
1163 name = PHI_RESULT (ref->stmt);
1164 if (!name)
1165 return NULL;
1167 for (psi = gsi_start_phis (loop->header); !gsi_end_p (psi); gsi_next (&psi))
1169 phi = psi.phi ();
1170 if (PHI_ARG_DEF_FROM_EDGE (phi, latch) == name)
1171 break;
1174 if (gsi_end_p (psi))
1175 return NULL;
1177 init = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
1178 if (TREE_CODE (init) != SSA_NAME)
1179 return NULL;
1180 init_stmt = SSA_NAME_DEF_STMT (init);
1181 if (gimple_code (init_stmt) != GIMPLE_ASSIGN)
1182 return NULL;
1183 gcc_assert (gimple_assign_lhs (init_stmt) == init);
1185 init_ref = gimple_assign_rhs1 (init_stmt);
1186 if (!REFERENCE_CLASS_P (init_ref)
1187 && !DECL_P (init_ref))
1188 return NULL;
1190 /* Analyze the behavior of INIT_REF with respect to LOOP (innermost
1191 loop enclosing PHI). */
1192 memset (&init_dr, 0, sizeof (struct data_reference));
1193 DR_REF (&init_dr) = init_ref;
1194 DR_STMT (&init_dr) = phi;
1195 if (!dr_analyze_innermost (&init_dr, loop))
1196 return NULL;
1198 if (!valid_initializer_p (&init_dr, ref->distance + 1, root->ref))
1199 return NULL;
1201 return phi;
1204 /* Adds a reference for the looparound copy of REF in PHI to CHAIN. */
1206 static void
1207 insert_looparound_copy (chain_p chain, dref ref, gphi *phi)
1209 dref nw = XCNEW (struct dref_d), aref;
1210 unsigned i;
1212 nw->stmt = phi;
1213 nw->distance = ref->distance + 1;
1214 nw->always_accessed = 1;
1216 FOR_EACH_VEC_ELT (chain->refs, i, aref)
1217 if (aref->distance >= nw->distance)
1218 break;
1219 chain->refs.safe_insert (i, nw);
1221 if (nw->distance > chain->length)
1223 chain->length = nw->distance;
1224 chain->has_max_use_after = false;
1228 /* For references in CHAIN that are copied around the LOOP (created previously
1229 by PRE, or by user), add the results of such copies to the chain. This
1230 enables us to remove the copies by unrolling, and may need less registers
1231 (also, it may allow us to combine chains together). */
1233 static void
1234 add_looparound_copies (struct loop *loop, chain_p chain)
1236 unsigned i;
1237 dref ref, root = get_chain_root (chain);
1238 gphi *phi;
1240 FOR_EACH_VEC_ELT (chain->refs, i, ref)
1242 phi = find_looparound_phi (loop, ref, root);
1243 if (!phi)
1244 continue;
1246 bitmap_set_bit (looparound_phis, SSA_NAME_VERSION (PHI_RESULT (phi)));
1247 insert_looparound_copy (chain, ref, phi);
1251 /* Find roots of the values and determine distances in the component COMP.
1252 The references are redistributed into CHAINS. LOOP is the current
1253 loop. */
1255 static void
1256 determine_roots_comp (struct loop *loop,
1257 struct component *comp,
1258 vec<chain_p> *chains)
1260 unsigned i;
1261 dref a;
1262 chain_p chain = NULL;
1263 widest_int last_ofs = 0;
1265 /* Invariants are handled specially. */
1266 if (comp->comp_step == RS_INVARIANT)
1268 chain = make_invariant_chain (comp);
1269 chains->safe_push (chain);
1270 return;
1273 comp->refs.qsort (order_drefs);
1275 FOR_EACH_VEC_ELT (comp->refs, i, a)
1277 if (!chain || DR_IS_WRITE (a->ref)
1278 || wi::leu_p (MAX_DISTANCE, a->offset - last_ofs))
1280 if (nontrivial_chain_p (chain))
1282 add_looparound_copies (loop, chain);
1283 chains->safe_push (chain);
1285 else
1286 release_chain (chain);
1287 chain = make_rooted_chain (a);
1288 last_ofs = a->offset;
1289 continue;
1292 add_ref_to_chain (chain, a);
1295 if (nontrivial_chain_p (chain))
1297 add_looparound_copies (loop, chain);
1298 chains->safe_push (chain);
1300 else
1301 release_chain (chain);
1304 /* Find roots of the values and determine distances in components COMPS, and
1305 separates the references to CHAINS. LOOP is the current loop. */
1307 static void
1308 determine_roots (struct loop *loop,
1309 struct component *comps, vec<chain_p> *chains)
1311 struct component *comp;
1313 for (comp = comps; comp; comp = comp->next)
1314 determine_roots_comp (loop, comp, chains);
1317 /* Replace the reference in statement STMT with temporary variable
1318 NEW_TREE. If SET is true, NEW_TREE is instead initialized to the value of
1319 the reference in the statement. IN_LHS is true if the reference
1320 is in the lhs of STMT, false if it is in rhs. */
1322 static void
1323 replace_ref_with (gimple stmt, tree new_tree, bool set, bool in_lhs)
1325 tree val;
1326 gassign *new_stmt;
1327 gimple_stmt_iterator bsi, psi;
1329 if (gimple_code (stmt) == GIMPLE_PHI)
1331 gcc_assert (!in_lhs && !set);
1333 val = PHI_RESULT (stmt);
1334 bsi = gsi_after_labels (gimple_bb (stmt));
1335 psi = gsi_for_stmt (stmt);
1336 remove_phi_node (&psi, false);
1338 /* Turn the phi node into GIMPLE_ASSIGN. */
1339 new_stmt = gimple_build_assign (val, new_tree);
1340 gsi_insert_before (&bsi, new_stmt, GSI_NEW_STMT);
1341 return;
1344 /* Since the reference is of gimple_reg type, it should only
1345 appear as lhs or rhs of modify statement. */
1346 gcc_assert (is_gimple_assign (stmt));
1348 bsi = gsi_for_stmt (stmt);
1350 /* If we do not need to initialize NEW_TREE, just replace the use of OLD. */
1351 if (!set)
1353 gcc_assert (!in_lhs);
1354 gimple_assign_set_rhs_from_tree (&bsi, new_tree);
1355 stmt = gsi_stmt (bsi);
1356 update_stmt (stmt);
1357 return;
1360 if (in_lhs)
1362 /* We have statement
1364 OLD = VAL
1366 If OLD is a memory reference, then VAL is gimple_val, and we transform
1367 this to
1369 OLD = VAL
1370 NEW = VAL
1372 Otherwise, we are replacing a combination chain,
1373 VAL is the expression that performs the combination, and OLD is an
1374 SSA name. In this case, we transform the assignment to
1376 OLD = VAL
1377 NEW = OLD
1381 val = gimple_assign_lhs (stmt);
1382 if (TREE_CODE (val) != SSA_NAME)
1384 val = gimple_assign_rhs1 (stmt);
1385 gcc_assert (gimple_assign_single_p (stmt));
1386 if (TREE_CLOBBER_P (val))
1387 val = get_or_create_ssa_default_def (cfun, SSA_NAME_VAR (new_tree));
1388 else
1389 gcc_assert (gimple_assign_copy_p (stmt));
1392 else
1394 /* VAL = OLD
1396 is transformed to
1398 VAL = OLD
1399 NEW = VAL */
1401 val = gimple_assign_lhs (stmt);
1404 new_stmt = gimple_build_assign (new_tree, unshare_expr (val));
1405 gsi_insert_after (&bsi, new_stmt, GSI_NEW_STMT);
1408 /* Returns a memory reference to DR in the ITER-th iteration of
1409 the loop it was analyzed in. Append init stmts to STMTS. */
1411 static tree
1412 ref_at_iteration (data_reference_p dr, int iter, gimple_seq *stmts)
1414 tree off = DR_OFFSET (dr);
1415 tree coff = DR_INIT (dr);
1416 if (iter == 0)
1418 else if (TREE_CODE (DR_STEP (dr)) == INTEGER_CST)
1419 coff = size_binop (PLUS_EXPR, coff,
1420 size_binop (MULT_EXPR, DR_STEP (dr), ssize_int (iter)));
1421 else
1422 off = size_binop (PLUS_EXPR, off,
1423 size_binop (MULT_EXPR, DR_STEP (dr), ssize_int (iter)));
1424 tree addr = fold_build_pointer_plus (DR_BASE_ADDRESS (dr), off);
1425 addr = force_gimple_operand_1 (unshare_expr (addr), stmts,
1426 is_gimple_mem_ref_addr, NULL_TREE);
1427 tree alias_ptr = fold_convert (reference_alias_ptr_type (DR_REF (dr)), coff);
1428 tree type = build_aligned_type (TREE_TYPE (DR_REF (dr)),
1429 get_object_alignment (DR_REF (dr)));
1430 /* While data-ref analysis punts on bit offsets it still handles
1431 bitfield accesses at byte boundaries. Cope with that. Note that
1432 we cannot simply re-apply the outer COMPONENT_REF because the
1433 byte-granular portion of it is already applied via DR_INIT and
1434 DR_OFFSET, so simply build a BIT_FIELD_REF knowing that the bits
1435 start at offset zero. */
1436 if (TREE_CODE (DR_REF (dr)) == COMPONENT_REF
1437 && DECL_BIT_FIELD (TREE_OPERAND (DR_REF (dr), 1)))
1439 tree field = TREE_OPERAND (DR_REF (dr), 1);
1440 return build3 (BIT_FIELD_REF, TREE_TYPE (DR_REF (dr)),
1441 build2 (MEM_REF, type, addr, alias_ptr),
1442 DECL_SIZE (field), bitsize_zero_node);
1444 else
1445 return fold_build2 (MEM_REF, type, addr, alias_ptr);
1448 /* Get the initialization expression for the INDEX-th temporary variable
1449 of CHAIN. */
1451 static tree
1452 get_init_expr (chain_p chain, unsigned index)
1454 if (chain->type == CT_COMBINATION)
1456 tree e1 = get_init_expr (chain->ch1, index);
1457 tree e2 = get_init_expr (chain->ch2, index);
1459 return fold_build2 (chain->op, chain->rslt_type, e1, e2);
1461 else
1462 return chain->inits[index];
1465 /* Returns a new temporary variable used for the I-th variable carrying
1466 value of REF. The variable's uid is marked in TMP_VARS. */
1468 static tree
1469 predcom_tmp_var (tree ref, unsigned i, bitmap tmp_vars)
1471 tree type = TREE_TYPE (ref);
1472 /* We never access the components of the temporary variable in predictive
1473 commoning. */
1474 tree var = create_tmp_reg (type, get_lsm_tmp_name (ref, i));
1475 bitmap_set_bit (tmp_vars, DECL_UID (var));
1476 return var;
1479 /* Creates the variables for CHAIN, as well as phi nodes for them and
1480 initialization on entry to LOOP. Uids of the newly created
1481 temporary variables are marked in TMP_VARS. */
1483 static void
1484 initialize_root_vars (struct loop *loop, chain_p chain, bitmap tmp_vars)
1486 unsigned i;
1487 unsigned n = chain->length;
1488 dref root = get_chain_root (chain);
1489 bool reuse_first = !chain->has_max_use_after;
1490 tree ref, init, var, next;
1491 gphi *phi;
1492 gimple_seq stmts;
1493 edge entry = loop_preheader_edge (loop), latch = loop_latch_edge (loop);
1495 /* If N == 0, then all the references are within the single iteration. And
1496 since this is an nonempty chain, reuse_first cannot be true. */
1497 gcc_assert (n > 0 || !reuse_first);
1499 chain->vars.create (n + 1);
1501 if (chain->type == CT_COMBINATION)
1502 ref = gimple_assign_lhs (root->stmt);
1503 else
1504 ref = DR_REF (root->ref);
1506 for (i = 0; i < n + (reuse_first ? 0 : 1); i++)
1508 var = predcom_tmp_var (ref, i, tmp_vars);
1509 chain->vars.quick_push (var);
1511 if (reuse_first)
1512 chain->vars.quick_push (chain->vars[0]);
1514 FOR_EACH_VEC_ELT (chain->vars, i, var)
1515 chain->vars[i] = make_ssa_name (var);
1517 for (i = 0; i < n; i++)
1519 var = chain->vars[i];
1520 next = chain->vars[i + 1];
1521 init = get_init_expr (chain, i);
1523 init = force_gimple_operand (init, &stmts, true, NULL_TREE);
1524 if (stmts)
1525 gsi_insert_seq_on_edge_immediate (entry, stmts);
1527 phi = create_phi_node (var, loop->header);
1528 add_phi_arg (phi, init, entry, UNKNOWN_LOCATION);
1529 add_phi_arg (phi, next, latch, UNKNOWN_LOCATION);
1533 /* Create the variables and initialization statement for root of chain
1534 CHAIN. Uids of the newly created temporary variables are marked
1535 in TMP_VARS. */
1537 static void
1538 initialize_root (struct loop *loop, chain_p chain, bitmap tmp_vars)
1540 dref root = get_chain_root (chain);
1541 bool in_lhs = (chain->type == CT_STORE_LOAD
1542 || chain->type == CT_COMBINATION);
1544 initialize_root_vars (loop, chain, tmp_vars);
1545 replace_ref_with (root->stmt,
1546 chain->vars[chain->length],
1547 true, in_lhs);
1550 /* Initializes a variable for load motion for ROOT and prepares phi nodes and
1551 initialization on entry to LOOP if necessary. The ssa name for the variable
1552 is stored in VARS. If WRITTEN is true, also a phi node to copy its value
1553 around the loop is created. Uid of the newly created temporary variable
1554 is marked in TMP_VARS. INITS is the list containing the (single)
1555 initializer. */
1557 static void
1558 initialize_root_vars_lm (struct loop *loop, dref root, bool written,
1559 vec<tree> *vars, vec<tree> inits,
1560 bitmap tmp_vars)
1562 unsigned i;
1563 tree ref = DR_REF (root->ref), init, var, next;
1564 gimple_seq stmts;
1565 gphi *phi;
1566 edge entry = loop_preheader_edge (loop), latch = loop_latch_edge (loop);
1568 /* Find the initializer for the variable, and check that it cannot
1569 trap. */
1570 init = inits[0];
1572 vars->create (written ? 2 : 1);
1573 var = predcom_tmp_var (ref, 0, tmp_vars);
1574 vars->quick_push (var);
1575 if (written)
1576 vars->quick_push ((*vars)[0]);
1578 FOR_EACH_VEC_ELT (*vars, i, var)
1579 (*vars)[i] = make_ssa_name (var);
1581 var = (*vars)[0];
1583 init = force_gimple_operand (init, &stmts, written, NULL_TREE);
1584 if (stmts)
1585 gsi_insert_seq_on_edge_immediate (entry, stmts);
1587 if (written)
1589 next = (*vars)[1];
1590 phi = create_phi_node (var, loop->header);
1591 add_phi_arg (phi, init, entry, UNKNOWN_LOCATION);
1592 add_phi_arg (phi, next, latch, UNKNOWN_LOCATION);
1594 else
1596 gassign *init_stmt = gimple_build_assign (var, init);
1597 gsi_insert_on_edge_immediate (entry, init_stmt);
1602 /* Execute load motion for references in chain CHAIN. Uids of the newly
1603 created temporary variables are marked in TMP_VARS. */
1605 static void
1606 execute_load_motion (struct loop *loop, chain_p chain, bitmap tmp_vars)
1608 auto_vec<tree> vars;
1609 dref a;
1610 unsigned n_writes = 0, ridx, i;
1611 tree var;
1613 gcc_assert (chain->type == CT_INVARIANT);
1614 gcc_assert (!chain->combined);
1615 FOR_EACH_VEC_ELT (chain->refs, i, a)
1616 if (DR_IS_WRITE (a->ref))
1617 n_writes++;
1619 /* If there are no reads in the loop, there is nothing to do. */
1620 if (n_writes == chain->refs.length ())
1621 return;
1623 initialize_root_vars_lm (loop, get_chain_root (chain), n_writes > 0,
1624 &vars, chain->inits, tmp_vars);
1626 ridx = 0;
1627 FOR_EACH_VEC_ELT (chain->refs, i, a)
1629 bool is_read = DR_IS_READ (a->ref);
1631 if (DR_IS_WRITE (a->ref))
1633 n_writes--;
1634 if (n_writes)
1636 var = vars[0];
1637 var = make_ssa_name (SSA_NAME_VAR (var));
1638 vars[0] = var;
1640 else
1641 ridx = 1;
1644 replace_ref_with (a->stmt, vars[ridx],
1645 !is_read, !is_read);
1649 /* Returns the single statement in that NAME is used, excepting
1650 the looparound phi nodes contained in one of the chains. If there is no
1651 such statement, or more statements, NULL is returned. */
1653 static gimple
1654 single_nonlooparound_use (tree name)
1656 use_operand_p use;
1657 imm_use_iterator it;
1658 gimple stmt, ret = NULL;
1660 FOR_EACH_IMM_USE_FAST (use, it, name)
1662 stmt = USE_STMT (use);
1664 if (gimple_code (stmt) == GIMPLE_PHI)
1666 /* Ignore uses in looparound phi nodes. Uses in other phi nodes
1667 could not be processed anyway, so just fail for them. */
1668 if (bitmap_bit_p (looparound_phis,
1669 SSA_NAME_VERSION (PHI_RESULT (stmt))))
1670 continue;
1672 return NULL;
1674 else if (is_gimple_debug (stmt))
1675 continue;
1676 else if (ret != NULL)
1677 return NULL;
1678 else
1679 ret = stmt;
1682 return ret;
1685 /* Remove statement STMT, as well as the chain of assignments in that it is
1686 used. */
1688 static void
1689 remove_stmt (gimple stmt)
1691 tree name;
1692 gimple next;
1693 gimple_stmt_iterator psi;
1695 if (gimple_code (stmt) == GIMPLE_PHI)
1697 name = PHI_RESULT (stmt);
1698 next = single_nonlooparound_use (name);
1699 reset_debug_uses (stmt);
1700 psi = gsi_for_stmt (stmt);
1701 remove_phi_node (&psi, true);
1703 if (!next
1704 || !gimple_assign_ssa_name_copy_p (next)
1705 || gimple_assign_rhs1 (next) != name)
1706 return;
1708 stmt = next;
1711 while (1)
1713 gimple_stmt_iterator bsi;
1715 bsi = gsi_for_stmt (stmt);
1717 name = gimple_assign_lhs (stmt);
1718 gcc_assert (TREE_CODE (name) == SSA_NAME);
1720 next = single_nonlooparound_use (name);
1721 reset_debug_uses (stmt);
1723 unlink_stmt_vdef (stmt);
1724 gsi_remove (&bsi, true);
1725 release_defs (stmt);
1727 if (!next
1728 || !gimple_assign_ssa_name_copy_p (next)
1729 || gimple_assign_rhs1 (next) != name)
1730 return;
1732 stmt = next;
1736 /* Perform the predictive commoning optimization for a chain CHAIN.
1737 Uids of the newly created temporary variables are marked in TMP_VARS.*/
1739 static void
1740 execute_pred_commoning_chain (struct loop *loop, chain_p chain,
1741 bitmap tmp_vars)
1743 unsigned i;
1744 dref a;
1745 tree var;
1747 if (chain->combined)
1749 /* For combined chains, just remove the statements that are used to
1750 compute the values of the expression (except for the root one).
1751 We delay this until after all chains are processed. */
1753 else
1755 /* For non-combined chains, set up the variables that hold its value,
1756 and replace the uses of the original references by these
1757 variables. */
1758 initialize_root (loop, chain, tmp_vars);
1759 for (i = 1; chain->refs.iterate (i, &a); i++)
1761 var = chain->vars[chain->length - a->distance];
1762 replace_ref_with (a->stmt, var, false, false);
1767 /* Determines the unroll factor necessary to remove as many temporary variable
1768 copies as possible. CHAINS is the list of chains that will be
1769 optimized. */
1771 static unsigned
1772 determine_unroll_factor (vec<chain_p> chains)
1774 chain_p chain;
1775 unsigned factor = 1, af, nfactor, i;
1776 unsigned max = PARAM_VALUE (PARAM_MAX_UNROLL_TIMES);
1778 FOR_EACH_VEC_ELT (chains, i, chain)
1780 if (chain->type == CT_INVARIANT)
1781 continue;
1783 if (chain->combined)
1785 /* For combined chains, we can't handle unrolling if we replace
1786 looparound PHIs. */
1787 dref a;
1788 unsigned j;
1789 for (j = 1; chain->refs.iterate (j, &a); j++)
1790 if (gimple_code (a->stmt) == GIMPLE_PHI)
1791 return 1;
1792 continue;
1795 /* The best unroll factor for this chain is equal to the number of
1796 temporary variables that we create for it. */
1797 af = chain->length;
1798 if (chain->has_max_use_after)
1799 af++;
1801 nfactor = factor * af / gcd (factor, af);
1802 if (nfactor <= max)
1803 factor = nfactor;
1806 return factor;
1809 /* Perform the predictive commoning optimization for CHAINS.
1810 Uids of the newly created temporary variables are marked in TMP_VARS. */
1812 static void
1813 execute_pred_commoning (struct loop *loop, vec<chain_p> chains,
1814 bitmap tmp_vars)
1816 chain_p chain;
1817 unsigned i;
1819 FOR_EACH_VEC_ELT (chains, i, chain)
1821 if (chain->type == CT_INVARIANT)
1822 execute_load_motion (loop, chain, tmp_vars);
1823 else
1824 execute_pred_commoning_chain (loop, chain, tmp_vars);
1827 FOR_EACH_VEC_ELT (chains, i, chain)
1829 if (chain->type == CT_INVARIANT)
1831 else if (chain->combined)
1833 /* For combined chains, just remove the statements that are used to
1834 compute the values of the expression (except for the root one). */
1835 dref a;
1836 unsigned j;
1837 for (j = 1; chain->refs.iterate (j, &a); j++)
1838 remove_stmt (a->stmt);
1842 update_ssa (TODO_update_ssa_only_virtuals);
1845 /* For each reference in CHAINS, if its defining statement is
1846 phi node, record the ssa name that is defined by it. */
1848 static void
1849 replace_phis_by_defined_names (vec<chain_p> chains)
1851 chain_p chain;
1852 dref a;
1853 unsigned i, j;
1855 FOR_EACH_VEC_ELT (chains, i, chain)
1856 FOR_EACH_VEC_ELT (chain->refs, j, a)
1858 if (gimple_code (a->stmt) == GIMPLE_PHI)
1860 a->name_defined_by_phi = PHI_RESULT (a->stmt);
1861 a->stmt = NULL;
1866 /* For each reference in CHAINS, if name_defined_by_phi is not
1867 NULL, use it to set the stmt field. */
1869 static void
1870 replace_names_by_phis (vec<chain_p> chains)
1872 chain_p chain;
1873 dref a;
1874 unsigned i, j;
1876 FOR_EACH_VEC_ELT (chains, i, chain)
1877 FOR_EACH_VEC_ELT (chain->refs, j, a)
1878 if (a->stmt == NULL)
1880 a->stmt = SSA_NAME_DEF_STMT (a->name_defined_by_phi);
1881 gcc_assert (gimple_code (a->stmt) == GIMPLE_PHI);
1882 a->name_defined_by_phi = NULL_TREE;
1886 /* Wrapper over execute_pred_commoning, to pass it as a callback
1887 to tree_transform_and_unroll_loop. */
1889 struct epcc_data
1891 vec<chain_p> chains;
1892 bitmap tmp_vars;
1895 static void
1896 execute_pred_commoning_cbck (struct loop *loop, void *data)
1898 struct epcc_data *const dta = (struct epcc_data *) data;
1900 /* Restore phi nodes that were replaced by ssa names before
1901 tree_transform_and_unroll_loop (see detailed description in
1902 tree_predictive_commoning_loop). */
1903 replace_names_by_phis (dta->chains);
1904 execute_pred_commoning (loop, dta->chains, dta->tmp_vars);
1907 /* Base NAME and all the names in the chain of phi nodes that use it
1908 on variable VAR. The phi nodes are recognized by being in the copies of
1909 the header of the LOOP. */
1911 static void
1912 base_names_in_chain_on (struct loop *loop, tree name, tree var)
1914 gimple stmt, phi;
1915 imm_use_iterator iter;
1917 replace_ssa_name_symbol (name, var);
1919 while (1)
1921 phi = NULL;
1922 FOR_EACH_IMM_USE_STMT (stmt, iter, name)
1924 if (gimple_code (stmt) == GIMPLE_PHI
1925 && flow_bb_inside_loop_p (loop, gimple_bb (stmt)))
1927 phi = stmt;
1928 BREAK_FROM_IMM_USE_STMT (iter);
1931 if (!phi)
1932 return;
1934 name = PHI_RESULT (phi);
1935 replace_ssa_name_symbol (name, var);
1939 /* Given an unrolled LOOP after predictive commoning, remove the
1940 register copies arising from phi nodes by changing the base
1941 variables of SSA names. TMP_VARS is the set of the temporary variables
1942 for those we want to perform this. */
1944 static void
1945 eliminate_temp_copies (struct loop *loop, bitmap tmp_vars)
1947 edge e;
1948 gphi *phi;
1949 gimple stmt;
1950 tree name, use, var;
1951 gphi_iterator psi;
1953 e = loop_latch_edge (loop);
1954 for (psi = gsi_start_phis (loop->header); !gsi_end_p (psi); gsi_next (&psi))
1956 phi = psi.phi ();
1957 name = PHI_RESULT (phi);
1958 var = SSA_NAME_VAR (name);
1959 if (!var || !bitmap_bit_p (tmp_vars, DECL_UID (var)))
1960 continue;
1961 use = PHI_ARG_DEF_FROM_EDGE (phi, e);
1962 gcc_assert (TREE_CODE (use) == SSA_NAME);
1964 /* Base all the ssa names in the ud and du chain of NAME on VAR. */
1965 stmt = SSA_NAME_DEF_STMT (use);
1966 while (gimple_code (stmt) == GIMPLE_PHI
1967 /* In case we could not unroll the loop enough to eliminate
1968 all copies, we may reach the loop header before the defining
1969 statement (in that case, some register copies will be present
1970 in loop latch in the final code, corresponding to the newly
1971 created looparound phi nodes). */
1972 && gimple_bb (stmt) != loop->header)
1974 gcc_assert (single_pred_p (gimple_bb (stmt)));
1975 use = PHI_ARG_DEF (stmt, 0);
1976 stmt = SSA_NAME_DEF_STMT (use);
1979 base_names_in_chain_on (loop, use, var);
1983 /* Returns true if CHAIN is suitable to be combined. */
1985 static bool
1986 chain_can_be_combined_p (chain_p chain)
1988 return (!chain->combined
1989 && (chain->type == CT_LOAD || chain->type == CT_COMBINATION));
1992 /* Returns the modify statement that uses NAME. Skips over assignment
1993 statements, NAME is replaced with the actual name used in the returned
1994 statement. */
1996 static gimple
1997 find_use_stmt (tree *name)
1999 gimple stmt;
2000 tree rhs, lhs;
2002 /* Skip over assignments. */
2003 while (1)
2005 stmt = single_nonlooparound_use (*name);
2006 if (!stmt)
2007 return NULL;
2009 if (gimple_code (stmt) != GIMPLE_ASSIGN)
2010 return NULL;
2012 lhs = gimple_assign_lhs (stmt);
2013 if (TREE_CODE (lhs) != SSA_NAME)
2014 return NULL;
2016 if (gimple_assign_copy_p (stmt))
2018 rhs = gimple_assign_rhs1 (stmt);
2019 if (rhs != *name)
2020 return NULL;
2022 *name = lhs;
2024 else if (get_gimple_rhs_class (gimple_assign_rhs_code (stmt))
2025 == GIMPLE_BINARY_RHS)
2026 return stmt;
2027 else
2028 return NULL;
2032 /* Returns true if we may perform reassociation for operation CODE in TYPE. */
2034 static bool
2035 may_reassociate_p (tree type, enum tree_code code)
2037 if (FLOAT_TYPE_P (type)
2038 && !flag_unsafe_math_optimizations)
2039 return false;
2041 return (commutative_tree_code (code)
2042 && associative_tree_code (code));
2045 /* If the operation used in STMT is associative and commutative, go through the
2046 tree of the same operations and returns its root. Distance to the root
2047 is stored in DISTANCE. */
2049 static gimple
2050 find_associative_operation_root (gimple stmt, unsigned *distance)
2052 tree lhs;
2053 gimple next;
2054 enum tree_code code = gimple_assign_rhs_code (stmt);
2055 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
2056 unsigned dist = 0;
2058 if (!may_reassociate_p (type, code))
2059 return NULL;
2061 while (1)
2063 lhs = gimple_assign_lhs (stmt);
2064 gcc_assert (TREE_CODE (lhs) == SSA_NAME);
2066 next = find_use_stmt (&lhs);
2067 if (!next
2068 || gimple_assign_rhs_code (next) != code)
2069 break;
2071 stmt = next;
2072 dist++;
2075 if (distance)
2076 *distance = dist;
2077 return stmt;
2080 /* Returns the common statement in that NAME1 and NAME2 have a use. If there
2081 is no such statement, returns NULL_TREE. In case the operation used on
2082 NAME1 and NAME2 is associative and commutative, returns the root of the
2083 tree formed by this operation instead of the statement that uses NAME1 or
2084 NAME2. */
2086 static gimple
2087 find_common_use_stmt (tree *name1, tree *name2)
2089 gimple stmt1, stmt2;
2091 stmt1 = find_use_stmt (name1);
2092 if (!stmt1)
2093 return NULL;
2095 stmt2 = find_use_stmt (name2);
2096 if (!stmt2)
2097 return NULL;
2099 if (stmt1 == stmt2)
2100 return stmt1;
2102 stmt1 = find_associative_operation_root (stmt1, NULL);
2103 if (!stmt1)
2104 return NULL;
2105 stmt2 = find_associative_operation_root (stmt2, NULL);
2106 if (!stmt2)
2107 return NULL;
2109 return (stmt1 == stmt2 ? stmt1 : NULL);
2112 /* Checks whether R1 and R2 are combined together using CODE, with the result
2113 in RSLT_TYPE, in order R1 CODE R2 if SWAP is false and in order R2 CODE R1
2114 if it is true. If CODE is ERROR_MARK, set these values instead. */
2116 static bool
2117 combinable_refs_p (dref r1, dref r2,
2118 enum tree_code *code, bool *swap, tree *rslt_type)
2120 enum tree_code acode;
2121 bool aswap;
2122 tree atype;
2123 tree name1, name2;
2124 gimple stmt;
2126 name1 = name_for_ref (r1);
2127 name2 = name_for_ref (r2);
2128 gcc_assert (name1 != NULL_TREE && name2 != NULL_TREE);
2130 stmt = find_common_use_stmt (&name1, &name2);
2132 if (!stmt
2133 /* A simple post-dominance check - make sure the combination
2134 is executed under the same condition as the references. */
2135 || (gimple_bb (stmt) != gimple_bb (r1->stmt)
2136 && gimple_bb (stmt) != gimple_bb (r2->stmt)))
2137 return false;
2139 acode = gimple_assign_rhs_code (stmt);
2140 aswap = (!commutative_tree_code (acode)
2141 && gimple_assign_rhs1 (stmt) != name1);
2142 atype = TREE_TYPE (gimple_assign_lhs (stmt));
2144 if (*code == ERROR_MARK)
2146 *code = acode;
2147 *swap = aswap;
2148 *rslt_type = atype;
2149 return true;
2152 return (*code == acode
2153 && *swap == aswap
2154 && *rslt_type == atype);
2157 /* Remove OP from the operation on rhs of STMT, and replace STMT with
2158 an assignment of the remaining operand. */
2160 static void
2161 remove_name_from_operation (gimple stmt, tree op)
2163 tree other_op;
2164 gimple_stmt_iterator si;
2166 gcc_assert (is_gimple_assign (stmt));
2168 if (gimple_assign_rhs1 (stmt) == op)
2169 other_op = gimple_assign_rhs2 (stmt);
2170 else
2171 other_op = gimple_assign_rhs1 (stmt);
2173 si = gsi_for_stmt (stmt);
2174 gimple_assign_set_rhs_from_tree (&si, other_op);
2176 /* We should not have reallocated STMT. */
2177 gcc_assert (gsi_stmt (si) == stmt);
2179 update_stmt (stmt);
2182 /* Reassociates the expression in that NAME1 and NAME2 are used so that they
2183 are combined in a single statement, and returns this statement. */
2185 static gimple
2186 reassociate_to_the_same_stmt (tree name1, tree name2)
2188 gimple stmt1, stmt2, root1, root2, s1, s2;
2189 gassign *new_stmt, *tmp_stmt;
2190 tree new_name, tmp_name, var, r1, r2;
2191 unsigned dist1, dist2;
2192 enum tree_code code;
2193 tree type = TREE_TYPE (name1);
2194 gimple_stmt_iterator bsi;
2196 stmt1 = find_use_stmt (&name1);
2197 stmt2 = find_use_stmt (&name2);
2198 root1 = find_associative_operation_root (stmt1, &dist1);
2199 root2 = find_associative_operation_root (stmt2, &dist2);
2200 code = gimple_assign_rhs_code (stmt1);
2202 gcc_assert (root1 && root2 && root1 == root2
2203 && code == gimple_assign_rhs_code (stmt2));
2205 /* Find the root of the nearest expression in that both NAME1 and NAME2
2206 are used. */
2207 r1 = name1;
2208 s1 = stmt1;
2209 r2 = name2;
2210 s2 = stmt2;
2212 while (dist1 > dist2)
2214 s1 = find_use_stmt (&r1);
2215 r1 = gimple_assign_lhs (s1);
2216 dist1--;
2218 while (dist2 > dist1)
2220 s2 = find_use_stmt (&r2);
2221 r2 = gimple_assign_lhs (s2);
2222 dist2--;
2225 while (s1 != s2)
2227 s1 = find_use_stmt (&r1);
2228 r1 = gimple_assign_lhs (s1);
2229 s2 = find_use_stmt (&r2);
2230 r2 = gimple_assign_lhs (s2);
2233 /* Remove NAME1 and NAME2 from the statements in that they are used
2234 currently. */
2235 remove_name_from_operation (stmt1, name1);
2236 remove_name_from_operation (stmt2, name2);
2238 /* Insert the new statement combining NAME1 and NAME2 before S1, and
2239 combine it with the rhs of S1. */
2240 var = create_tmp_reg (type, "predreastmp");
2241 new_name = make_ssa_name (var);
2242 new_stmt = gimple_build_assign (new_name, code, name1, name2);
2244 var = create_tmp_reg (type, "predreastmp");
2245 tmp_name = make_ssa_name (var);
2247 /* Rhs of S1 may now be either a binary expression with operation
2248 CODE, or gimple_val (in case that stmt1 == s1 or stmt2 == s1,
2249 so that name1 or name2 was removed from it). */
2250 tmp_stmt = gimple_build_assign (tmp_name, gimple_assign_rhs_code (s1),
2251 gimple_assign_rhs1 (s1),
2252 gimple_assign_rhs2 (s1));
2254 bsi = gsi_for_stmt (s1);
2255 gimple_assign_set_rhs_with_ops (&bsi, code, new_name, tmp_name);
2256 s1 = gsi_stmt (bsi);
2257 update_stmt (s1);
2259 gsi_insert_before (&bsi, new_stmt, GSI_SAME_STMT);
2260 gsi_insert_before (&bsi, tmp_stmt, GSI_SAME_STMT);
2262 return new_stmt;
2265 /* Returns the statement that combines references R1 and R2. In case R1
2266 and R2 are not used in the same statement, but they are used with an
2267 associative and commutative operation in the same expression, reassociate
2268 the expression so that they are used in the same statement. */
2270 static gimple
2271 stmt_combining_refs (dref r1, dref r2)
2273 gimple stmt1, stmt2;
2274 tree name1 = name_for_ref (r1);
2275 tree name2 = name_for_ref (r2);
2277 stmt1 = find_use_stmt (&name1);
2278 stmt2 = find_use_stmt (&name2);
2279 if (stmt1 == stmt2)
2280 return stmt1;
2282 return reassociate_to_the_same_stmt (name1, name2);
2285 /* Tries to combine chains CH1 and CH2 together. If this succeeds, the
2286 description of the new chain is returned, otherwise we return NULL. */
2288 static chain_p
2289 combine_chains (chain_p ch1, chain_p ch2)
2291 dref r1, r2, nw;
2292 enum tree_code op = ERROR_MARK;
2293 bool swap = false;
2294 chain_p new_chain;
2295 unsigned i;
2296 gimple root_stmt;
2297 tree rslt_type = NULL_TREE;
2299 if (ch1 == ch2)
2300 return NULL;
2301 if (ch1->length != ch2->length)
2302 return NULL;
2304 if (ch1->refs.length () != ch2->refs.length ())
2305 return NULL;
2307 for (i = 0; (ch1->refs.iterate (i, &r1)
2308 && ch2->refs.iterate (i, &r2)); i++)
2310 if (r1->distance != r2->distance)
2311 return NULL;
2313 if (!combinable_refs_p (r1, r2, &op, &swap, &rslt_type))
2314 return NULL;
2317 if (swap)
2319 chain_p tmp = ch1;
2320 ch1 = ch2;
2321 ch2 = tmp;
2324 new_chain = XCNEW (struct chain);
2325 new_chain->type = CT_COMBINATION;
2326 new_chain->op = op;
2327 new_chain->ch1 = ch1;
2328 new_chain->ch2 = ch2;
2329 new_chain->rslt_type = rslt_type;
2330 new_chain->length = ch1->length;
2332 for (i = 0; (ch1->refs.iterate (i, &r1)
2333 && ch2->refs.iterate (i, &r2)); i++)
2335 nw = XCNEW (struct dref_d);
2336 nw->stmt = stmt_combining_refs (r1, r2);
2337 nw->distance = r1->distance;
2339 new_chain->refs.safe_push (nw);
2342 new_chain->has_max_use_after = false;
2343 root_stmt = get_chain_root (new_chain)->stmt;
2344 for (i = 1; new_chain->refs.iterate (i, &nw); i++)
2346 if (nw->distance == new_chain->length
2347 && !stmt_dominates_stmt_p (nw->stmt, root_stmt))
2349 new_chain->has_max_use_after = true;
2350 break;
2354 ch1->combined = true;
2355 ch2->combined = true;
2356 return new_chain;
2359 /* Try to combine the CHAINS. */
2361 static void
2362 try_combine_chains (vec<chain_p> *chains)
2364 unsigned i, j;
2365 chain_p ch1, ch2, cch;
2366 auto_vec<chain_p> worklist;
2368 FOR_EACH_VEC_ELT (*chains, i, ch1)
2369 if (chain_can_be_combined_p (ch1))
2370 worklist.safe_push (ch1);
2372 while (!worklist.is_empty ())
2374 ch1 = worklist.pop ();
2375 if (!chain_can_be_combined_p (ch1))
2376 continue;
2378 FOR_EACH_VEC_ELT (*chains, j, ch2)
2380 if (!chain_can_be_combined_p (ch2))
2381 continue;
2383 cch = combine_chains (ch1, ch2);
2384 if (cch)
2386 worklist.safe_push (cch);
2387 chains->safe_push (cch);
2388 break;
2394 /* Prepare initializers for CHAIN in LOOP. Returns false if this is
2395 impossible because one of these initializers may trap, true otherwise. */
2397 static bool
2398 prepare_initializers_chain (struct loop *loop, chain_p chain)
2400 unsigned i, n = (chain->type == CT_INVARIANT) ? 1 : chain->length;
2401 struct data_reference *dr = get_chain_root (chain)->ref;
2402 tree init;
2403 dref laref;
2404 edge entry = loop_preheader_edge (loop);
2406 /* Find the initializers for the variables, and check that they cannot
2407 trap. */
2408 chain->inits.create (n);
2409 for (i = 0; i < n; i++)
2410 chain->inits.quick_push (NULL_TREE);
2412 /* If we have replaced some looparound phi nodes, use their initializers
2413 instead of creating our own. */
2414 FOR_EACH_VEC_ELT (chain->refs, i, laref)
2416 if (gimple_code (laref->stmt) != GIMPLE_PHI)
2417 continue;
2419 gcc_assert (laref->distance > 0);
2420 chain->inits[n - laref->distance]
2421 = PHI_ARG_DEF_FROM_EDGE (laref->stmt, entry);
2424 for (i = 0; i < n; i++)
2426 gimple_seq stmts = NULL;
2428 if (chain->inits[i] != NULL_TREE)
2429 continue;
2431 init = ref_at_iteration (dr, (int) i - n, &stmts);
2432 if (!chain->all_always_accessed && tree_could_trap_p (init))
2434 gimple_seq_discard (stmts);
2435 return false;
2438 if (stmts)
2439 gsi_insert_seq_on_edge_immediate (entry, stmts);
2441 chain->inits[i] = init;
2444 return true;
2447 /* Prepare initializers for CHAINS in LOOP, and free chains that cannot
2448 be used because the initializers might trap. */
2450 static void
2451 prepare_initializers (struct loop *loop, vec<chain_p> chains)
2453 chain_p chain;
2454 unsigned i;
2456 for (i = 0; i < chains.length (); )
2458 chain = chains[i];
2459 if (prepare_initializers_chain (loop, chain))
2460 i++;
2461 else
2463 release_chain (chain);
2464 chains.unordered_remove (i);
2469 /* Performs predictive commoning for LOOP. Returns true if LOOP was
2470 unrolled. */
2472 static bool
2473 tree_predictive_commoning_loop (struct loop *loop)
2475 vec<data_reference_p> datarefs;
2476 vec<ddr_p> dependences;
2477 struct component *components;
2478 vec<chain_p> chains = vNULL;
2479 unsigned unroll_factor;
2480 struct tree_niter_desc desc;
2481 bool unroll = false;
2482 edge exit;
2483 bitmap tmp_vars;
2485 if (dump_file && (dump_flags & TDF_DETAILS))
2486 fprintf (dump_file, "Processing loop %d\n", loop->num);
2488 /* Find the data references and split them into components according to their
2489 dependence relations. */
2490 auto_vec<loop_p, 3> loop_nest;
2491 dependences.create (10);
2492 datarefs.create (10);
2493 if (! compute_data_dependences_for_loop (loop, true, &loop_nest, &datarefs,
2494 &dependences))
2496 if (dump_file && (dump_flags & TDF_DETAILS))
2497 fprintf (dump_file, "Cannot analyze data dependencies\n");
2498 free_data_refs (datarefs);
2499 free_dependence_relations (dependences);
2500 return false;
2503 if (dump_file && (dump_flags & TDF_DETAILS))
2504 dump_data_dependence_relations (dump_file, dependences);
2506 components = split_data_refs_to_components (loop, datarefs, dependences);
2507 loop_nest.release ();
2508 free_dependence_relations (dependences);
2509 if (!components)
2511 free_data_refs (datarefs);
2512 free_affine_expand_cache (&name_expansions);
2513 return false;
2516 if (dump_file && (dump_flags & TDF_DETAILS))
2518 fprintf (dump_file, "Initial state:\n\n");
2519 dump_components (dump_file, components);
2522 /* Find the suitable components and split them into chains. */
2523 components = filter_suitable_components (loop, components);
2525 tmp_vars = BITMAP_ALLOC (NULL);
2526 looparound_phis = BITMAP_ALLOC (NULL);
2527 determine_roots (loop, components, &chains);
2528 release_components (components);
2530 if (!chains.exists ())
2532 if (dump_file && (dump_flags & TDF_DETAILS))
2533 fprintf (dump_file,
2534 "Predictive commoning failed: no suitable chains\n");
2535 goto end;
2537 prepare_initializers (loop, chains);
2539 /* Try to combine the chains that are always worked with together. */
2540 try_combine_chains (&chains);
2542 if (dump_file && (dump_flags & TDF_DETAILS))
2544 fprintf (dump_file, "Before commoning:\n\n");
2545 dump_chains (dump_file, chains);
2548 /* Determine the unroll factor, and if the loop should be unrolled, ensure
2549 that its number of iterations is divisible by the factor. */
2550 unroll_factor = determine_unroll_factor (chains);
2551 scev_reset ();
2552 unroll = (unroll_factor > 1
2553 && can_unroll_loop_p (loop, unroll_factor, &desc));
2554 exit = single_dom_exit (loop);
2556 /* Execute the predictive commoning transformations, and possibly unroll the
2557 loop. */
2558 if (unroll)
2560 struct epcc_data dta;
2562 if (dump_file && (dump_flags & TDF_DETAILS))
2563 fprintf (dump_file, "Unrolling %u times.\n", unroll_factor);
2565 dta.chains = chains;
2566 dta.tmp_vars = tmp_vars;
2568 update_ssa (TODO_update_ssa_only_virtuals);
2570 /* Cfg manipulations performed in tree_transform_and_unroll_loop before
2571 execute_pred_commoning_cbck is called may cause phi nodes to be
2572 reallocated, which is a problem since CHAINS may point to these
2573 statements. To fix this, we store the ssa names defined by the
2574 phi nodes here instead of the phi nodes themselves, and restore
2575 the phi nodes in execute_pred_commoning_cbck. A bit hacky. */
2576 replace_phis_by_defined_names (chains);
2578 tree_transform_and_unroll_loop (loop, unroll_factor, exit, &desc,
2579 execute_pred_commoning_cbck, &dta);
2580 eliminate_temp_copies (loop, tmp_vars);
2582 else
2584 if (dump_file && (dump_flags & TDF_DETAILS))
2585 fprintf (dump_file,
2586 "Executing predictive commoning without unrolling.\n");
2587 execute_pred_commoning (loop, chains, tmp_vars);
2590 end: ;
2591 release_chains (chains);
2592 free_data_refs (datarefs);
2593 BITMAP_FREE (tmp_vars);
2594 BITMAP_FREE (looparound_phis);
2596 free_affine_expand_cache (&name_expansions);
2598 return unroll;
2601 /* Runs predictive commoning. */
2603 unsigned
2604 tree_predictive_commoning (void)
2606 bool unrolled = false;
2607 struct loop *loop;
2608 unsigned ret = 0;
2610 initialize_original_copy_tables ();
2611 FOR_EACH_LOOP (loop, LI_ONLY_INNERMOST)
2612 if (optimize_loop_for_speed_p (loop))
2614 unrolled |= tree_predictive_commoning_loop (loop);
2617 if (unrolled)
2619 scev_reset ();
2620 ret = TODO_cleanup_cfg;
2622 free_original_copy_tables ();
2624 return ret;
2627 /* Predictive commoning Pass. */
2629 static unsigned
2630 run_tree_predictive_commoning (struct function *fun)
2632 if (number_of_loops (fun) <= 1)
2633 return 0;
2635 return tree_predictive_commoning ();
2638 namespace {
2640 const pass_data pass_data_predcom =
2642 GIMPLE_PASS, /* type */
2643 "pcom", /* name */
2644 OPTGROUP_LOOP, /* optinfo_flags */
2645 TV_PREDCOM, /* tv_id */
2646 PROP_cfg, /* properties_required */
2647 0, /* properties_provided */
2648 0, /* properties_destroyed */
2649 0, /* todo_flags_start */
2650 TODO_update_ssa_only_virtuals, /* todo_flags_finish */
2653 class pass_predcom : public gimple_opt_pass
2655 public:
2656 pass_predcom (gcc::context *ctxt)
2657 : gimple_opt_pass (pass_data_predcom, ctxt)
2660 /* opt_pass methods: */
2661 virtual bool gate (function *) { return flag_predictive_commoning != 0; }
2662 virtual unsigned int execute (function *fun)
2664 return run_tree_predictive_commoning (fun);
2667 }; // class pass_predcom
2669 } // anon namespace
2671 gimple_opt_pass *
2672 make_pass_predcom (gcc::context *ctxt)
2674 return new pass_predcom (ctxt);