* ipa/devirt9.C: Fix previous change.
[official-gcc.git] / gcc / tree-predcom.c
blob6d141842f1cec642bba843dbcc582984c7adaa37
1 /* Predictive commoning.
2 Copyright (C) 2005-2013 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 3, or (at your option) any
9 later version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 /* 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 "tree.h"
192 #include "tm_p.h"
193 #include "cfgloop.h"
194 #include "gimple.h"
195 #include "gimplify.h"
196 #include "gimple-iterator.h"
197 #include "gimplify-me.h"
198 #include "gimple-ssa.h"
199 #include "tree-phinodes.h"
200 #include "ssa-iterators.h"
201 #include "stringpool.h"
202 #include "tree-ssanames.h"
203 #include "tree-ssa-loop-ivopts.h"
204 #include "tree-ssa-loop-manip.h"
205 #include "tree-ssa-loop-niter.h"
206 #include "tree-ssa-loop.h"
207 #include "tree-into-ssa.h"
208 #include "expr.h"
209 #include "tree-dfa.h"
210 #include "tree-ssa.h"
211 #include "ggc.h"
212 #include "tree-data-ref.h"
213 #include "tree-scalar-evolution.h"
214 #include "tree-chrec.h"
215 #include "params.h"
216 #include "gimple-pretty-print.h"
217 #include "tree-pass.h"
218 #include "tree-affine.h"
219 #include "tree-inline.h"
221 /* The maximum number of iterations between the considered memory
222 references. */
224 #define MAX_DISTANCE (target_avail_regs < 16 ? 4 : 8)
226 /* Data references (or phi nodes that carry data reference values across
227 loop iterations). */
229 typedef struct dref_d
231 /* The reference itself. */
232 struct data_reference *ref;
234 /* The statement in that the reference appears. */
235 gimple stmt;
237 /* In case that STMT is a phi node, this field is set to the SSA name
238 defined by it in replace_phis_by_defined_names (in order to avoid
239 pointing to phi node that got reallocated in the meantime). */
240 tree name_defined_by_phi;
242 /* Distance of the reference from the root of the chain (in number of
243 iterations of the loop). */
244 unsigned distance;
246 /* Number of iterations offset from the first reference in the component. */
247 double_int offset;
249 /* Number of the reference in a component, in dominance ordering. */
250 unsigned pos;
252 /* True if the memory reference is always accessed when the loop is
253 entered. */
254 unsigned always_accessed : 1;
255 } *dref;
258 /* Type of the chain of the references. */
260 enum chain_type
262 /* The addresses of the references in the chain are constant. */
263 CT_INVARIANT,
265 /* There are only loads in the chain. */
266 CT_LOAD,
268 /* Root of the chain is store, the rest are loads. */
269 CT_STORE_LOAD,
271 /* A combination of two chains. */
272 CT_COMBINATION
275 /* Chains of data references. */
277 typedef struct chain
279 /* Type of the chain. */
280 enum chain_type type;
282 /* For combination chains, the operator and the two chains that are
283 combined, and the type of the result. */
284 enum tree_code op;
285 tree rslt_type;
286 struct chain *ch1, *ch2;
288 /* The references in the chain. */
289 vec<dref> refs;
291 /* The maximum distance of the reference in the chain from the root. */
292 unsigned length;
294 /* The variables used to copy the value throughout iterations. */
295 vec<tree> vars;
297 /* Initializers for the variables. */
298 vec<tree> inits;
300 /* True if there is a use of a variable with the maximal distance
301 that comes after the root in the loop. */
302 unsigned has_max_use_after : 1;
304 /* True if all the memory references in the chain are always accessed. */
305 unsigned all_always_accessed : 1;
307 /* True if this chain was combined together with some other chain. */
308 unsigned combined : 1;
309 } *chain_p;
312 /* Describes the knowledge about the step of the memory references in
313 the component. */
315 enum ref_step_type
317 /* The step is zero. */
318 RS_INVARIANT,
320 /* The step is nonzero. */
321 RS_NONZERO,
323 /* The step may or may not be nonzero. */
324 RS_ANY
327 /* Components of the data dependence graph. */
329 struct component
331 /* The references in the component. */
332 vec<dref> refs;
334 /* What we know about the step of the references in the component. */
335 enum ref_step_type comp_step;
337 /* Next component in the list. */
338 struct component *next;
341 /* Bitmap of ssa names defined by looparound phi nodes covered by chains. */
343 static bitmap looparound_phis;
345 /* Cache used by tree_to_aff_combination_expand. */
347 static struct pointer_map_t *name_expansions;
349 /* Dumps data reference REF to FILE. */
351 extern void dump_dref (FILE *, dref);
352 void
353 dump_dref (FILE *file, dref ref)
355 if (ref->ref)
357 fprintf (file, " ");
358 print_generic_expr (file, DR_REF (ref->ref), TDF_SLIM);
359 fprintf (file, " (id %u%s)\n", ref->pos,
360 DR_IS_READ (ref->ref) ? "" : ", write");
362 fprintf (file, " offset ");
363 dump_double_int (file, ref->offset, false);
364 fprintf (file, "\n");
366 fprintf (file, " distance %u\n", ref->distance);
368 else
370 if (gimple_code (ref->stmt) == GIMPLE_PHI)
371 fprintf (file, " looparound ref\n");
372 else
373 fprintf (file, " combination ref\n");
374 fprintf (file, " in statement ");
375 print_gimple_stmt (file, ref->stmt, 0, TDF_SLIM);
376 fprintf (file, "\n");
377 fprintf (file, " distance %u\n", ref->distance);
382 /* Dumps CHAIN to FILE. */
384 extern void dump_chain (FILE *, chain_p);
385 void
386 dump_chain (FILE *file, chain_p chain)
388 dref a;
389 const char *chain_type;
390 unsigned i;
391 tree var;
393 switch (chain->type)
395 case CT_INVARIANT:
396 chain_type = "Load motion";
397 break;
399 case CT_LOAD:
400 chain_type = "Loads-only";
401 break;
403 case CT_STORE_LOAD:
404 chain_type = "Store-loads";
405 break;
407 case CT_COMBINATION:
408 chain_type = "Combination";
409 break;
411 default:
412 gcc_unreachable ();
415 fprintf (file, "%s chain %p%s\n", chain_type, (void *) chain,
416 chain->combined ? " (combined)" : "");
417 if (chain->type != CT_INVARIANT)
418 fprintf (file, " max distance %u%s\n", chain->length,
419 chain->has_max_use_after ? "" : ", may reuse first");
421 if (chain->type == CT_COMBINATION)
423 fprintf (file, " equal to %p %s %p in type ",
424 (void *) chain->ch1, op_symbol_code (chain->op),
425 (void *) chain->ch2);
426 print_generic_expr (file, chain->rslt_type, TDF_SLIM);
427 fprintf (file, "\n");
430 if (chain->vars.exists ())
432 fprintf (file, " vars");
433 FOR_EACH_VEC_ELT (chain->vars, i, var)
435 fprintf (file, " ");
436 print_generic_expr (file, var, TDF_SLIM);
438 fprintf (file, "\n");
441 if (chain->inits.exists ())
443 fprintf (file, " inits");
444 FOR_EACH_VEC_ELT (chain->inits, i, var)
446 fprintf (file, " ");
447 print_generic_expr (file, var, TDF_SLIM);
449 fprintf (file, "\n");
452 fprintf (file, " references:\n");
453 FOR_EACH_VEC_ELT (chain->refs, i, a)
454 dump_dref (file, a);
456 fprintf (file, "\n");
459 /* Dumps CHAINS to FILE. */
461 extern void dump_chains (FILE *, vec<chain_p> );
462 void
463 dump_chains (FILE *file, vec<chain_p> chains)
465 chain_p chain;
466 unsigned i;
468 FOR_EACH_VEC_ELT (chains, i, chain)
469 dump_chain (file, chain);
472 /* Dumps COMP to FILE. */
474 extern void dump_component (FILE *, struct component *);
475 void
476 dump_component (FILE *file, struct component *comp)
478 dref a;
479 unsigned i;
481 fprintf (file, "Component%s:\n",
482 comp->comp_step == RS_INVARIANT ? " (invariant)" : "");
483 FOR_EACH_VEC_ELT (comp->refs, i, a)
484 dump_dref (file, a);
485 fprintf (file, "\n");
488 /* Dumps COMPS to FILE. */
490 extern void dump_components (FILE *, struct component *);
491 void
492 dump_components (FILE *file, struct component *comps)
494 struct component *comp;
496 for (comp = comps; comp; comp = comp->next)
497 dump_component (file, comp);
500 /* Frees a chain CHAIN. */
502 static void
503 release_chain (chain_p chain)
505 dref ref;
506 unsigned i;
508 if (chain == NULL)
509 return;
511 FOR_EACH_VEC_ELT (chain->refs, i, ref)
512 free (ref);
514 chain->refs.release ();
515 chain->vars.release ();
516 chain->inits.release ();
518 free (chain);
521 /* Frees CHAINS. */
523 static void
524 release_chains (vec<chain_p> chains)
526 unsigned i;
527 chain_p chain;
529 FOR_EACH_VEC_ELT (chains, i, chain)
530 release_chain (chain);
531 chains.release ();
534 /* Frees a component COMP. */
536 static void
537 release_component (struct component *comp)
539 comp->refs.release ();
540 free (comp);
543 /* Frees list of components COMPS. */
545 static void
546 release_components (struct component *comps)
548 struct component *act, *next;
550 for (act = comps; act; act = next)
552 next = act->next;
553 release_component (act);
557 /* Finds a root of tree given by FATHERS containing A, and performs path
558 shortening. */
560 static unsigned
561 component_of (unsigned fathers[], unsigned a)
563 unsigned root, n;
565 for (root = a; root != fathers[root]; root = fathers[root])
566 continue;
568 for (; a != root; a = n)
570 n = fathers[a];
571 fathers[a] = root;
574 return root;
577 /* Join operation for DFU. FATHERS gives the tree, SIZES are sizes of the
578 components, A and B are components to merge. */
580 static void
581 merge_comps (unsigned fathers[], unsigned sizes[], unsigned a, unsigned b)
583 unsigned ca = component_of (fathers, a);
584 unsigned cb = component_of (fathers, b);
586 if (ca == cb)
587 return;
589 if (sizes[ca] < sizes[cb])
591 sizes[cb] += sizes[ca];
592 fathers[ca] = cb;
594 else
596 sizes[ca] += sizes[cb];
597 fathers[cb] = ca;
601 /* Returns true if A is a reference that is suitable for predictive commoning
602 in the innermost loop that contains it. REF_STEP is set according to the
603 step of the reference A. */
605 static bool
606 suitable_reference_p (struct data_reference *a, enum ref_step_type *ref_step)
608 tree ref = DR_REF (a), step = DR_STEP (a);
610 if (!step
611 || TREE_THIS_VOLATILE (ref)
612 || !is_gimple_reg_type (TREE_TYPE (ref))
613 || tree_could_throw_p (ref))
614 return false;
616 if (integer_zerop (step))
617 *ref_step = RS_INVARIANT;
618 else if (integer_nonzerop (step))
619 *ref_step = RS_NONZERO;
620 else
621 *ref_step = RS_ANY;
623 return true;
626 /* Stores DR_OFFSET (DR) + DR_INIT (DR) to OFFSET. */
628 static void
629 aff_combination_dr_offset (struct data_reference *dr, aff_tree *offset)
631 tree type = TREE_TYPE (DR_OFFSET (dr));
632 aff_tree delta;
634 tree_to_aff_combination_expand (DR_OFFSET (dr), type, offset,
635 &name_expansions);
636 aff_combination_const (&delta, type, tree_to_double_int (DR_INIT (dr)));
637 aff_combination_add (offset, &delta);
640 /* Determines number of iterations of the innermost enclosing loop before B
641 refers to exactly the same location as A and stores it to OFF. If A and
642 B do not have the same step, they never meet, or anything else fails,
643 returns false, otherwise returns true. Both A and B are assumed to
644 satisfy suitable_reference_p. */
646 static bool
647 determine_offset (struct data_reference *a, struct data_reference *b,
648 double_int *off)
650 aff_tree diff, baseb, step;
651 tree typea, typeb;
653 /* Check that both the references access the location in the same type. */
654 typea = TREE_TYPE (DR_REF (a));
655 typeb = TREE_TYPE (DR_REF (b));
656 if (!useless_type_conversion_p (typeb, typea))
657 return false;
659 /* Check whether the base address and the step of both references is the
660 same. */
661 if (!operand_equal_p (DR_STEP (a), DR_STEP (b), 0)
662 || !operand_equal_p (DR_BASE_ADDRESS (a), DR_BASE_ADDRESS (b), 0))
663 return false;
665 if (integer_zerop (DR_STEP (a)))
667 /* If the references have loop invariant address, check that they access
668 exactly the same location. */
669 *off = double_int_zero;
670 return (operand_equal_p (DR_OFFSET (a), DR_OFFSET (b), 0)
671 && operand_equal_p (DR_INIT (a), DR_INIT (b), 0));
674 /* Compare the offsets of the addresses, and check whether the difference
675 is a multiple of step. */
676 aff_combination_dr_offset (a, &diff);
677 aff_combination_dr_offset (b, &baseb);
678 aff_combination_scale (&baseb, double_int_minus_one);
679 aff_combination_add (&diff, &baseb);
681 tree_to_aff_combination_expand (DR_STEP (a), TREE_TYPE (DR_STEP (a)),
682 &step, &name_expansions);
683 return aff_combination_constant_multiple_p (&diff, &step, off);
686 /* Returns the last basic block in LOOP for that we are sure that
687 it is executed whenever the loop is entered. */
689 static basic_block
690 last_always_executed_block (struct loop *loop)
692 unsigned i;
693 vec<edge> exits = get_loop_exit_edges (loop);
694 edge ex;
695 basic_block last = loop->latch;
697 FOR_EACH_VEC_ELT (exits, i, ex)
698 last = nearest_common_dominator (CDI_DOMINATORS, last, ex->src);
699 exits.release ();
701 return last;
704 /* Splits dependence graph on DATAREFS described by DEPENDS to components. */
706 static struct component *
707 split_data_refs_to_components (struct loop *loop,
708 vec<data_reference_p> datarefs,
709 vec<ddr_p> depends)
711 unsigned i, n = datarefs.length ();
712 unsigned ca, ia, ib, bad;
713 unsigned *comp_father = XNEWVEC (unsigned, n + 1);
714 unsigned *comp_size = XNEWVEC (unsigned, n + 1);
715 struct component **comps;
716 struct data_reference *dr, *dra, *drb;
717 struct data_dependence_relation *ddr;
718 struct component *comp_list = NULL, *comp;
719 dref dataref;
720 basic_block last_always_executed = last_always_executed_block (loop);
722 FOR_EACH_VEC_ELT (datarefs, i, dr)
724 if (!DR_REF (dr))
726 /* A fake reference for call or asm_expr that may clobber memory;
727 just fail. */
728 goto end;
730 dr->aux = (void *) (size_t) i;
731 comp_father[i] = i;
732 comp_size[i] = 1;
735 /* A component reserved for the "bad" data references. */
736 comp_father[n] = n;
737 comp_size[n] = 1;
739 FOR_EACH_VEC_ELT (datarefs, i, dr)
741 enum ref_step_type dummy;
743 if (!suitable_reference_p (dr, &dummy))
745 ia = (unsigned) (size_t) dr->aux;
746 merge_comps (comp_father, comp_size, n, ia);
750 FOR_EACH_VEC_ELT (depends, i, ddr)
752 double_int dummy_off;
754 if (DDR_ARE_DEPENDENT (ddr) == chrec_known)
755 continue;
757 dra = DDR_A (ddr);
758 drb = DDR_B (ddr);
759 ia = component_of (comp_father, (unsigned) (size_t) dra->aux);
760 ib = component_of (comp_father, (unsigned) (size_t) drb->aux);
761 if (ia == ib)
762 continue;
764 bad = component_of (comp_father, n);
766 /* If both A and B are reads, we may ignore unsuitable dependences. */
767 if (DR_IS_READ (dra) && DR_IS_READ (drb)
768 && (ia == bad || ib == bad
769 || !determine_offset (dra, drb, &dummy_off)))
770 continue;
772 merge_comps (comp_father, comp_size, ia, ib);
775 comps = XCNEWVEC (struct component *, n);
776 bad = component_of (comp_father, n);
777 FOR_EACH_VEC_ELT (datarefs, i, dr)
779 ia = (unsigned) (size_t) dr->aux;
780 ca = component_of (comp_father, ia);
781 if (ca == bad)
782 continue;
784 comp = comps[ca];
785 if (!comp)
787 comp = XCNEW (struct component);
788 comp->refs.create (comp_size[ca]);
789 comps[ca] = comp;
792 dataref = XCNEW (struct dref_d);
793 dataref->ref = dr;
794 dataref->stmt = DR_STMT (dr);
795 dataref->offset = double_int_zero;
796 dataref->distance = 0;
798 dataref->always_accessed
799 = dominated_by_p (CDI_DOMINATORS, last_always_executed,
800 gimple_bb (dataref->stmt));
801 dataref->pos = comp->refs.length ();
802 comp->refs.quick_push (dataref);
805 for (i = 0; i < n; i++)
807 comp = comps[i];
808 if (comp)
810 comp->next = comp_list;
811 comp_list = comp;
814 free (comps);
816 end:
817 free (comp_father);
818 free (comp_size);
819 return comp_list;
822 /* Returns true if the component COMP satisfies the conditions
823 described in 2) at the beginning of this file. LOOP is the current
824 loop. */
826 static bool
827 suitable_component_p (struct loop *loop, struct component *comp)
829 unsigned i;
830 dref a, first;
831 basic_block ba, bp = loop->header;
832 bool ok, has_write = false;
834 FOR_EACH_VEC_ELT (comp->refs, i, a)
836 ba = gimple_bb (a->stmt);
838 if (!just_once_each_iteration_p (loop, ba))
839 return false;
841 gcc_assert (dominated_by_p (CDI_DOMINATORS, ba, bp));
842 bp = ba;
844 if (DR_IS_WRITE (a->ref))
845 has_write = true;
848 first = comp->refs[0];
849 ok = suitable_reference_p (first->ref, &comp->comp_step);
850 gcc_assert (ok);
851 first->offset = double_int_zero;
853 for (i = 1; comp->refs.iterate (i, &a); i++)
855 if (!determine_offset (first->ref, a->ref, &a->offset))
856 return false;
858 #ifdef ENABLE_CHECKING
860 enum ref_step_type a_step;
861 ok = suitable_reference_p (a->ref, &a_step);
862 gcc_assert (ok && a_step == comp->comp_step);
864 #endif
867 /* If there is a write inside the component, we must know whether the
868 step is nonzero or not -- we would not otherwise be able to recognize
869 whether the value accessed by reads comes from the OFFSET-th iteration
870 or the previous one. */
871 if (has_write && comp->comp_step == RS_ANY)
872 return false;
874 return true;
877 /* Check the conditions on references inside each of components COMPS,
878 and remove the unsuitable components from the list. The new list
879 of components is returned. The conditions are described in 2) at
880 the beginning of this file. LOOP is the current loop. */
882 static struct component *
883 filter_suitable_components (struct loop *loop, struct component *comps)
885 struct component **comp, *act;
887 for (comp = &comps; *comp; )
889 act = *comp;
890 if (suitable_component_p (loop, act))
891 comp = &act->next;
892 else
894 dref ref;
895 unsigned i;
897 *comp = act->next;
898 FOR_EACH_VEC_ELT (act->refs, i, ref)
899 free (ref);
900 release_component (act);
904 return comps;
907 /* Compares two drefs A and B by their offset and position. Callback for
908 qsort. */
910 static int
911 order_drefs (const void *a, const void *b)
913 const dref *const da = (const dref *) a;
914 const dref *const db = (const dref *) b;
915 int offcmp = (*da)->offset.scmp ((*db)->offset);
917 if (offcmp != 0)
918 return offcmp;
920 return (*da)->pos - (*db)->pos;
923 /* Returns root of the CHAIN. */
925 static inline dref
926 get_chain_root (chain_p chain)
928 return chain->refs[0];
931 /* Adds REF to the chain CHAIN. */
933 static void
934 add_ref_to_chain (chain_p chain, dref ref)
936 dref root = get_chain_root (chain);
937 double_int dist;
939 gcc_assert (root->offset.sle (ref->offset));
940 dist = ref->offset - root->offset;
941 if (double_int::from_uhwi (MAX_DISTANCE).ule (dist))
943 free (ref);
944 return;
946 gcc_assert (dist.fits_uhwi ());
948 chain->refs.safe_push (ref);
950 ref->distance = dist.to_uhwi ();
952 if (ref->distance >= chain->length)
954 chain->length = ref->distance;
955 chain->has_max_use_after = false;
958 if (ref->distance == chain->length
959 && ref->pos > root->pos)
960 chain->has_max_use_after = true;
962 chain->all_always_accessed &= ref->always_accessed;
965 /* Returns the chain for invariant component COMP. */
967 static chain_p
968 make_invariant_chain (struct component *comp)
970 chain_p chain = XCNEW (struct chain);
971 unsigned i;
972 dref ref;
974 chain->type = CT_INVARIANT;
976 chain->all_always_accessed = true;
978 FOR_EACH_VEC_ELT (comp->refs, i, ref)
980 chain->refs.safe_push (ref);
981 chain->all_always_accessed &= ref->always_accessed;
984 return chain;
987 /* Make a new chain rooted at REF. */
989 static chain_p
990 make_rooted_chain (dref ref)
992 chain_p chain = XCNEW (struct chain);
994 chain->type = DR_IS_READ (ref->ref) ? CT_LOAD : CT_STORE_LOAD;
996 chain->refs.safe_push (ref);
997 chain->all_always_accessed = ref->always_accessed;
999 ref->distance = 0;
1001 return chain;
1004 /* Returns true if CHAIN is not trivial. */
1006 static bool
1007 nontrivial_chain_p (chain_p chain)
1009 return chain != NULL && chain->refs.length () > 1;
1012 /* Returns the ssa name that contains the value of REF, or NULL_TREE if there
1013 is no such name. */
1015 static tree
1016 name_for_ref (dref ref)
1018 tree name;
1020 if (is_gimple_assign (ref->stmt))
1022 if (!ref->ref || DR_IS_READ (ref->ref))
1023 name = gimple_assign_lhs (ref->stmt);
1024 else
1025 name = gimple_assign_rhs1 (ref->stmt);
1027 else
1028 name = PHI_RESULT (ref->stmt);
1030 return (TREE_CODE (name) == SSA_NAME ? name : NULL_TREE);
1033 /* Returns true if REF is a valid initializer for ROOT with given DISTANCE (in
1034 iterations of the innermost enclosing loop). */
1036 static bool
1037 valid_initializer_p (struct data_reference *ref,
1038 unsigned distance, struct data_reference *root)
1040 aff_tree diff, base, step;
1041 double_int off;
1043 /* Both REF and ROOT must be accessing the same object. */
1044 if (!operand_equal_p (DR_BASE_ADDRESS (ref), DR_BASE_ADDRESS (root), 0))
1045 return false;
1047 /* The initializer is defined outside of loop, hence its address must be
1048 invariant inside the loop. */
1049 gcc_assert (integer_zerop (DR_STEP (ref)));
1051 /* If the address of the reference is invariant, initializer must access
1052 exactly the same location. */
1053 if (integer_zerop (DR_STEP (root)))
1054 return (operand_equal_p (DR_OFFSET (ref), DR_OFFSET (root), 0)
1055 && operand_equal_p (DR_INIT (ref), DR_INIT (root), 0));
1057 /* Verify that this index of REF is equal to the root's index at
1058 -DISTANCE-th iteration. */
1059 aff_combination_dr_offset (root, &diff);
1060 aff_combination_dr_offset (ref, &base);
1061 aff_combination_scale (&base, double_int_minus_one);
1062 aff_combination_add (&diff, &base);
1064 tree_to_aff_combination_expand (DR_STEP (root), TREE_TYPE (DR_STEP (root)),
1065 &step, &name_expansions);
1066 if (!aff_combination_constant_multiple_p (&diff, &step, &off))
1067 return false;
1069 if (off != double_int::from_uhwi (distance))
1070 return false;
1072 return true;
1075 /* Finds looparound phi node of LOOP that copies the value of REF, and if its
1076 initial value is correct (equal to initial value of REF shifted by one
1077 iteration), returns the phi node. Otherwise, NULL_TREE is returned. ROOT
1078 is the root of the current chain. */
1080 static gimple
1081 find_looparound_phi (struct loop *loop, dref ref, dref root)
1083 tree name, init, init_ref;
1084 gimple phi = NULL, init_stmt;
1085 edge latch = loop_latch_edge (loop);
1086 struct data_reference init_dr;
1087 gimple_stmt_iterator psi;
1089 if (is_gimple_assign (ref->stmt))
1091 if (DR_IS_READ (ref->ref))
1092 name = gimple_assign_lhs (ref->stmt);
1093 else
1094 name = gimple_assign_rhs1 (ref->stmt);
1096 else
1097 name = PHI_RESULT (ref->stmt);
1098 if (!name)
1099 return NULL;
1101 for (psi = gsi_start_phis (loop->header); !gsi_end_p (psi); gsi_next (&psi))
1103 phi = gsi_stmt (psi);
1104 if (PHI_ARG_DEF_FROM_EDGE (phi, latch) == name)
1105 break;
1108 if (gsi_end_p (psi))
1109 return NULL;
1111 init = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
1112 if (TREE_CODE (init) != SSA_NAME)
1113 return NULL;
1114 init_stmt = SSA_NAME_DEF_STMT (init);
1115 if (gimple_code (init_stmt) != GIMPLE_ASSIGN)
1116 return NULL;
1117 gcc_assert (gimple_assign_lhs (init_stmt) == init);
1119 init_ref = gimple_assign_rhs1 (init_stmt);
1120 if (!REFERENCE_CLASS_P (init_ref)
1121 && !DECL_P (init_ref))
1122 return NULL;
1124 /* Analyze the behavior of INIT_REF with respect to LOOP (innermost
1125 loop enclosing PHI). */
1126 memset (&init_dr, 0, sizeof (struct data_reference));
1127 DR_REF (&init_dr) = init_ref;
1128 DR_STMT (&init_dr) = phi;
1129 if (!dr_analyze_innermost (&init_dr, loop))
1130 return NULL;
1132 if (!valid_initializer_p (&init_dr, ref->distance + 1, root->ref))
1133 return NULL;
1135 return phi;
1138 /* Adds a reference for the looparound copy of REF in PHI to CHAIN. */
1140 static void
1141 insert_looparound_copy (chain_p chain, dref ref, gimple phi)
1143 dref nw = XCNEW (struct dref_d), aref;
1144 unsigned i;
1146 nw->stmt = phi;
1147 nw->distance = ref->distance + 1;
1148 nw->always_accessed = 1;
1150 FOR_EACH_VEC_ELT (chain->refs, i, aref)
1151 if (aref->distance >= nw->distance)
1152 break;
1153 chain->refs.safe_insert (i, nw);
1155 if (nw->distance > chain->length)
1157 chain->length = nw->distance;
1158 chain->has_max_use_after = false;
1162 /* For references in CHAIN that are copied around the LOOP (created previously
1163 by PRE, or by user), add the results of such copies to the chain. This
1164 enables us to remove the copies by unrolling, and may need less registers
1165 (also, it may allow us to combine chains together). */
1167 static void
1168 add_looparound_copies (struct loop *loop, chain_p chain)
1170 unsigned i;
1171 dref ref, root = get_chain_root (chain);
1172 gimple phi;
1174 FOR_EACH_VEC_ELT (chain->refs, i, ref)
1176 phi = find_looparound_phi (loop, ref, root);
1177 if (!phi)
1178 continue;
1180 bitmap_set_bit (looparound_phis, SSA_NAME_VERSION (PHI_RESULT (phi)));
1181 insert_looparound_copy (chain, ref, phi);
1185 /* Find roots of the values and determine distances in the component COMP.
1186 The references are redistributed into CHAINS. LOOP is the current
1187 loop. */
1189 static void
1190 determine_roots_comp (struct loop *loop,
1191 struct component *comp,
1192 vec<chain_p> *chains)
1194 unsigned i;
1195 dref a;
1196 chain_p chain = NULL;
1197 double_int last_ofs = double_int_zero;
1199 /* Invariants are handled specially. */
1200 if (comp->comp_step == RS_INVARIANT)
1202 chain = make_invariant_chain (comp);
1203 chains->safe_push (chain);
1204 return;
1207 comp->refs.qsort (order_drefs);
1209 FOR_EACH_VEC_ELT (comp->refs, i, a)
1211 if (!chain || DR_IS_WRITE (a->ref)
1212 || double_int::from_uhwi (MAX_DISTANCE).ule (a->offset - last_ofs))
1214 if (nontrivial_chain_p (chain))
1216 add_looparound_copies (loop, chain);
1217 chains->safe_push (chain);
1219 else
1220 release_chain (chain);
1221 chain = make_rooted_chain (a);
1222 last_ofs = a->offset;
1223 continue;
1226 add_ref_to_chain (chain, a);
1229 if (nontrivial_chain_p (chain))
1231 add_looparound_copies (loop, chain);
1232 chains->safe_push (chain);
1234 else
1235 release_chain (chain);
1238 /* Find roots of the values and determine distances in components COMPS, and
1239 separates the references to CHAINS. LOOP is the current loop. */
1241 static void
1242 determine_roots (struct loop *loop,
1243 struct component *comps, vec<chain_p> *chains)
1245 struct component *comp;
1247 for (comp = comps; comp; comp = comp->next)
1248 determine_roots_comp (loop, comp, chains);
1251 /* Replace the reference in statement STMT with temporary variable
1252 NEW_TREE. If SET is true, NEW_TREE is instead initialized to the value of
1253 the reference in the statement. IN_LHS is true if the reference
1254 is in the lhs of STMT, false if it is in rhs. */
1256 static void
1257 replace_ref_with (gimple stmt, tree new_tree, bool set, bool in_lhs)
1259 tree val;
1260 gimple new_stmt;
1261 gimple_stmt_iterator bsi, psi;
1263 if (gimple_code (stmt) == GIMPLE_PHI)
1265 gcc_assert (!in_lhs && !set);
1267 val = PHI_RESULT (stmt);
1268 bsi = gsi_after_labels (gimple_bb (stmt));
1269 psi = gsi_for_stmt (stmt);
1270 remove_phi_node (&psi, false);
1272 /* Turn the phi node into GIMPLE_ASSIGN. */
1273 new_stmt = gimple_build_assign (val, new_tree);
1274 gsi_insert_before (&bsi, new_stmt, GSI_NEW_STMT);
1275 return;
1278 /* Since the reference is of gimple_reg type, it should only
1279 appear as lhs or rhs of modify statement. */
1280 gcc_assert (is_gimple_assign (stmt));
1282 bsi = gsi_for_stmt (stmt);
1284 /* If we do not need to initialize NEW_TREE, just replace the use of OLD. */
1285 if (!set)
1287 gcc_assert (!in_lhs);
1288 gimple_assign_set_rhs_from_tree (&bsi, new_tree);
1289 stmt = gsi_stmt (bsi);
1290 update_stmt (stmt);
1291 return;
1294 if (in_lhs)
1296 /* We have statement
1298 OLD = VAL
1300 If OLD is a memory reference, then VAL is gimple_val, and we transform
1301 this to
1303 OLD = VAL
1304 NEW = VAL
1306 Otherwise, we are replacing a combination chain,
1307 VAL is the expression that performs the combination, and OLD is an
1308 SSA name. In this case, we transform the assignment to
1310 OLD = VAL
1311 NEW = OLD
1315 val = gimple_assign_lhs (stmt);
1316 if (TREE_CODE (val) != SSA_NAME)
1318 val = gimple_assign_rhs1 (stmt);
1319 gcc_assert (gimple_assign_single_p (stmt));
1320 if (TREE_CLOBBER_P (val))
1321 val = get_or_create_ssa_default_def (cfun, SSA_NAME_VAR (new_tree));
1322 else
1323 gcc_assert (gimple_assign_copy_p (stmt));
1326 else
1328 /* VAL = OLD
1330 is transformed to
1332 VAL = OLD
1333 NEW = VAL */
1335 val = gimple_assign_lhs (stmt);
1338 new_stmt = gimple_build_assign (new_tree, unshare_expr (val));
1339 gsi_insert_after (&bsi, new_stmt, GSI_NEW_STMT);
1342 /* Returns a memory reference to DR in the ITER-th iteration of
1343 the loop it was analyzed in. Append init stmts to STMTS. */
1345 static tree
1346 ref_at_iteration (data_reference_p dr, int iter, gimple_seq *stmts)
1348 tree off = DR_OFFSET (dr);
1349 tree coff = DR_INIT (dr);
1350 if (iter == 0)
1352 else if (TREE_CODE (DR_STEP (dr)) == INTEGER_CST)
1353 coff = size_binop (PLUS_EXPR, coff,
1354 size_binop (MULT_EXPR, DR_STEP (dr), ssize_int (iter)));
1355 else
1356 off = size_binop (PLUS_EXPR, off,
1357 size_binop (MULT_EXPR, DR_STEP (dr), ssize_int (iter)));
1358 tree addr = fold_build_pointer_plus (DR_BASE_ADDRESS (dr), off);
1359 addr = force_gimple_operand_1 (addr, stmts, is_gimple_mem_ref_addr,
1360 NULL_TREE);
1361 tree alias_ptr = fold_convert (reference_alias_ptr_type (DR_REF (dr)), coff);
1362 /* While data-ref analysis punts on bit offsets it still handles
1363 bitfield accesses at byte boundaries. Cope with that. Note that
1364 we cannot simply re-apply the outer COMPONENT_REF because the
1365 byte-granular portion of it is already applied via DR_INIT and
1366 DR_OFFSET, so simply build a BIT_FIELD_REF knowing that the bits
1367 start at offset zero. */
1368 if (TREE_CODE (DR_REF (dr)) == COMPONENT_REF
1369 && DECL_BIT_FIELD (TREE_OPERAND (DR_REF (dr), 1)))
1371 tree field = TREE_OPERAND (DR_REF (dr), 1);
1372 return build3 (BIT_FIELD_REF, TREE_TYPE (DR_REF (dr)),
1373 build2 (MEM_REF, DECL_BIT_FIELD_TYPE (field),
1374 addr, alias_ptr),
1375 DECL_SIZE (field), bitsize_zero_node);
1377 else
1378 return fold_build2 (MEM_REF, TREE_TYPE (DR_REF (dr)), addr, alias_ptr);
1381 /* Get the initialization expression for the INDEX-th temporary variable
1382 of CHAIN. */
1384 static tree
1385 get_init_expr (chain_p chain, unsigned index)
1387 if (chain->type == CT_COMBINATION)
1389 tree e1 = get_init_expr (chain->ch1, index);
1390 tree e2 = get_init_expr (chain->ch2, index);
1392 return fold_build2 (chain->op, chain->rslt_type, e1, e2);
1394 else
1395 return chain->inits[index];
1398 /* Returns a new temporary variable used for the I-th variable carrying
1399 value of REF. The variable's uid is marked in TMP_VARS. */
1401 static tree
1402 predcom_tmp_var (tree ref, unsigned i, bitmap tmp_vars)
1404 tree type = TREE_TYPE (ref);
1405 /* We never access the components of the temporary variable in predictive
1406 commoning. */
1407 tree var = create_tmp_reg (type, get_lsm_tmp_name (ref, i));
1408 bitmap_set_bit (tmp_vars, DECL_UID (var));
1409 return var;
1412 /* Creates the variables for CHAIN, as well as phi nodes for them and
1413 initialization on entry to LOOP. Uids of the newly created
1414 temporary variables are marked in TMP_VARS. */
1416 static void
1417 initialize_root_vars (struct loop *loop, chain_p chain, bitmap tmp_vars)
1419 unsigned i;
1420 unsigned n = chain->length;
1421 dref root = get_chain_root (chain);
1422 bool reuse_first = !chain->has_max_use_after;
1423 tree ref, init, var, next;
1424 gimple phi;
1425 gimple_seq stmts;
1426 edge entry = loop_preheader_edge (loop), latch = loop_latch_edge (loop);
1428 /* If N == 0, then all the references are within the single iteration. And
1429 since this is an nonempty chain, reuse_first cannot be true. */
1430 gcc_assert (n > 0 || !reuse_first);
1432 chain->vars.create (n + 1);
1434 if (chain->type == CT_COMBINATION)
1435 ref = gimple_assign_lhs (root->stmt);
1436 else
1437 ref = DR_REF (root->ref);
1439 for (i = 0; i < n + (reuse_first ? 0 : 1); i++)
1441 var = predcom_tmp_var (ref, i, tmp_vars);
1442 chain->vars.quick_push (var);
1444 if (reuse_first)
1445 chain->vars.quick_push (chain->vars[0]);
1447 FOR_EACH_VEC_ELT (chain->vars, i, var)
1448 chain->vars[i] = make_ssa_name (var, NULL);
1450 for (i = 0; i < n; i++)
1452 var = chain->vars[i];
1453 next = chain->vars[i + 1];
1454 init = get_init_expr (chain, i);
1456 init = force_gimple_operand (init, &stmts, true, NULL_TREE);
1457 if (stmts)
1458 gsi_insert_seq_on_edge_immediate (entry, stmts);
1460 phi = create_phi_node (var, loop->header);
1461 add_phi_arg (phi, init, entry, UNKNOWN_LOCATION);
1462 add_phi_arg (phi, next, latch, UNKNOWN_LOCATION);
1466 /* Create the variables and initialization statement for root of chain
1467 CHAIN. Uids of the newly created temporary variables are marked
1468 in TMP_VARS. */
1470 static void
1471 initialize_root (struct loop *loop, chain_p chain, bitmap tmp_vars)
1473 dref root = get_chain_root (chain);
1474 bool in_lhs = (chain->type == CT_STORE_LOAD
1475 || chain->type == CT_COMBINATION);
1477 initialize_root_vars (loop, chain, tmp_vars);
1478 replace_ref_with (root->stmt,
1479 chain->vars[chain->length],
1480 true, in_lhs);
1483 /* Initializes a variable for load motion for ROOT and prepares phi nodes and
1484 initialization on entry to LOOP if necessary. The ssa name for the variable
1485 is stored in VARS. If WRITTEN is true, also a phi node to copy its value
1486 around the loop is created. Uid of the newly created temporary variable
1487 is marked in TMP_VARS. INITS is the list containing the (single)
1488 initializer. */
1490 static void
1491 initialize_root_vars_lm (struct loop *loop, dref root, bool written,
1492 vec<tree> *vars, vec<tree> inits,
1493 bitmap tmp_vars)
1495 unsigned i;
1496 tree ref = DR_REF (root->ref), init, var, next;
1497 gimple_seq stmts;
1498 gimple phi;
1499 edge entry = loop_preheader_edge (loop), latch = loop_latch_edge (loop);
1501 /* Find the initializer for the variable, and check that it cannot
1502 trap. */
1503 init = inits[0];
1505 vars->create (written ? 2 : 1);
1506 var = predcom_tmp_var (ref, 0, tmp_vars);
1507 vars->quick_push (var);
1508 if (written)
1509 vars->quick_push ((*vars)[0]);
1511 FOR_EACH_VEC_ELT (*vars, i, var)
1512 (*vars)[i] = make_ssa_name (var, NULL);
1514 var = (*vars)[0];
1516 init = force_gimple_operand (init, &stmts, written, NULL_TREE);
1517 if (stmts)
1518 gsi_insert_seq_on_edge_immediate (entry, stmts);
1520 if (written)
1522 next = (*vars)[1];
1523 phi = create_phi_node (var, loop->header);
1524 add_phi_arg (phi, init, entry, UNKNOWN_LOCATION);
1525 add_phi_arg (phi, next, latch, UNKNOWN_LOCATION);
1527 else
1529 gimple init_stmt = gimple_build_assign (var, init);
1530 gsi_insert_on_edge_immediate (entry, init_stmt);
1535 /* Execute load motion for references in chain CHAIN. Uids of the newly
1536 created temporary variables are marked in TMP_VARS. */
1538 static void
1539 execute_load_motion (struct loop *loop, chain_p chain, bitmap tmp_vars)
1541 vec<tree> vars;
1542 dref a;
1543 unsigned n_writes = 0, ridx, i;
1544 tree var;
1546 gcc_assert (chain->type == CT_INVARIANT);
1547 gcc_assert (!chain->combined);
1548 FOR_EACH_VEC_ELT (chain->refs, i, a)
1549 if (DR_IS_WRITE (a->ref))
1550 n_writes++;
1552 /* If there are no reads in the loop, there is nothing to do. */
1553 if (n_writes == chain->refs.length ())
1554 return;
1556 initialize_root_vars_lm (loop, get_chain_root (chain), n_writes > 0,
1557 &vars, chain->inits, tmp_vars);
1559 ridx = 0;
1560 FOR_EACH_VEC_ELT (chain->refs, i, a)
1562 bool is_read = DR_IS_READ (a->ref);
1564 if (DR_IS_WRITE (a->ref))
1566 n_writes--;
1567 if (n_writes)
1569 var = vars[0];
1570 var = make_ssa_name (SSA_NAME_VAR (var), NULL);
1571 vars[0] = var;
1573 else
1574 ridx = 1;
1577 replace_ref_with (a->stmt, vars[ridx],
1578 !is_read, !is_read);
1581 vars.release ();
1584 /* Returns the single statement in that NAME is used, excepting
1585 the looparound phi nodes contained in one of the chains. If there is no
1586 such statement, or more statements, NULL is returned. */
1588 static gimple
1589 single_nonlooparound_use (tree name)
1591 use_operand_p use;
1592 imm_use_iterator it;
1593 gimple stmt, ret = NULL;
1595 FOR_EACH_IMM_USE_FAST (use, it, name)
1597 stmt = USE_STMT (use);
1599 if (gimple_code (stmt) == GIMPLE_PHI)
1601 /* Ignore uses in looparound phi nodes. Uses in other phi nodes
1602 could not be processed anyway, so just fail for them. */
1603 if (bitmap_bit_p (looparound_phis,
1604 SSA_NAME_VERSION (PHI_RESULT (stmt))))
1605 continue;
1607 return NULL;
1609 else if (is_gimple_debug (stmt))
1610 continue;
1611 else if (ret != NULL)
1612 return NULL;
1613 else
1614 ret = stmt;
1617 return ret;
1620 /* Remove statement STMT, as well as the chain of assignments in that it is
1621 used. */
1623 static void
1624 remove_stmt (gimple stmt)
1626 tree name;
1627 gimple next;
1628 gimple_stmt_iterator psi;
1630 if (gimple_code (stmt) == GIMPLE_PHI)
1632 name = PHI_RESULT (stmt);
1633 next = single_nonlooparound_use (name);
1634 reset_debug_uses (stmt);
1635 psi = gsi_for_stmt (stmt);
1636 remove_phi_node (&psi, true);
1638 if (!next
1639 || !gimple_assign_ssa_name_copy_p (next)
1640 || gimple_assign_rhs1 (next) != name)
1641 return;
1643 stmt = next;
1646 while (1)
1648 gimple_stmt_iterator bsi;
1650 bsi = gsi_for_stmt (stmt);
1652 name = gimple_assign_lhs (stmt);
1653 gcc_assert (TREE_CODE (name) == SSA_NAME);
1655 next = single_nonlooparound_use (name);
1656 reset_debug_uses (stmt);
1658 unlink_stmt_vdef (stmt);
1659 gsi_remove (&bsi, true);
1660 release_defs (stmt);
1662 if (!next
1663 || !gimple_assign_ssa_name_copy_p (next)
1664 || gimple_assign_rhs1 (next) != name)
1665 return;
1667 stmt = next;
1671 /* Perform the predictive commoning optimization for a chain CHAIN.
1672 Uids of the newly created temporary variables are marked in TMP_VARS.*/
1674 static void
1675 execute_pred_commoning_chain (struct loop *loop, chain_p chain,
1676 bitmap tmp_vars)
1678 unsigned i;
1679 dref a;
1680 tree var;
1682 if (chain->combined)
1684 /* For combined chains, just remove the statements that are used to
1685 compute the values of the expression (except for the root one). */
1686 for (i = 1; chain->refs.iterate (i, &a); i++)
1687 remove_stmt (a->stmt);
1689 else
1691 /* For non-combined chains, set up the variables that hold its value,
1692 and replace the uses of the original references by these
1693 variables. */
1694 initialize_root (loop, chain, tmp_vars);
1695 for (i = 1; chain->refs.iterate (i, &a); i++)
1697 var = chain->vars[chain->length - a->distance];
1698 replace_ref_with (a->stmt, var, false, false);
1703 /* Determines the unroll factor necessary to remove as many temporary variable
1704 copies as possible. CHAINS is the list of chains that will be
1705 optimized. */
1707 static unsigned
1708 determine_unroll_factor (vec<chain_p> chains)
1710 chain_p chain;
1711 unsigned factor = 1, af, nfactor, i;
1712 unsigned max = PARAM_VALUE (PARAM_MAX_UNROLL_TIMES);
1714 FOR_EACH_VEC_ELT (chains, i, chain)
1716 if (chain->type == CT_INVARIANT || chain->combined)
1717 continue;
1719 /* The best unroll factor for this chain is equal to the number of
1720 temporary variables that we create for it. */
1721 af = chain->length;
1722 if (chain->has_max_use_after)
1723 af++;
1725 nfactor = factor * af / gcd (factor, af);
1726 if (nfactor <= max)
1727 factor = nfactor;
1730 return factor;
1733 /* Perform the predictive commoning optimization for CHAINS.
1734 Uids of the newly created temporary variables are marked in TMP_VARS. */
1736 static void
1737 execute_pred_commoning (struct loop *loop, vec<chain_p> chains,
1738 bitmap tmp_vars)
1740 chain_p chain;
1741 unsigned i;
1743 FOR_EACH_VEC_ELT (chains, i, chain)
1745 if (chain->type == CT_INVARIANT)
1746 execute_load_motion (loop, chain, tmp_vars);
1747 else
1748 execute_pred_commoning_chain (loop, chain, tmp_vars);
1751 update_ssa (TODO_update_ssa_only_virtuals);
1754 /* For each reference in CHAINS, if its defining statement is
1755 phi node, record the ssa name that is defined by it. */
1757 static void
1758 replace_phis_by_defined_names (vec<chain_p> chains)
1760 chain_p chain;
1761 dref a;
1762 unsigned i, j;
1764 FOR_EACH_VEC_ELT (chains, i, chain)
1765 FOR_EACH_VEC_ELT (chain->refs, j, a)
1767 if (gimple_code (a->stmt) == GIMPLE_PHI)
1769 a->name_defined_by_phi = PHI_RESULT (a->stmt);
1770 a->stmt = NULL;
1775 /* For each reference in CHAINS, if name_defined_by_phi is not
1776 NULL, use it to set the stmt field. */
1778 static void
1779 replace_names_by_phis (vec<chain_p> chains)
1781 chain_p chain;
1782 dref a;
1783 unsigned i, j;
1785 FOR_EACH_VEC_ELT (chains, i, chain)
1786 FOR_EACH_VEC_ELT (chain->refs, j, a)
1787 if (a->stmt == NULL)
1789 a->stmt = SSA_NAME_DEF_STMT (a->name_defined_by_phi);
1790 gcc_assert (gimple_code (a->stmt) == GIMPLE_PHI);
1791 a->name_defined_by_phi = NULL_TREE;
1795 /* Wrapper over execute_pred_commoning, to pass it as a callback
1796 to tree_transform_and_unroll_loop. */
1798 struct epcc_data
1800 vec<chain_p> chains;
1801 bitmap tmp_vars;
1804 static void
1805 execute_pred_commoning_cbck (struct loop *loop, void *data)
1807 struct epcc_data *const dta = (struct epcc_data *) data;
1809 /* Restore phi nodes that were replaced by ssa names before
1810 tree_transform_and_unroll_loop (see detailed description in
1811 tree_predictive_commoning_loop). */
1812 replace_names_by_phis (dta->chains);
1813 execute_pred_commoning (loop, dta->chains, dta->tmp_vars);
1816 /* Base NAME and all the names in the chain of phi nodes that use it
1817 on variable VAR. The phi nodes are recognized by being in the copies of
1818 the header of the LOOP. */
1820 static void
1821 base_names_in_chain_on (struct loop *loop, tree name, tree var)
1823 gimple stmt, phi;
1824 imm_use_iterator iter;
1826 replace_ssa_name_symbol (name, var);
1828 while (1)
1830 phi = NULL;
1831 FOR_EACH_IMM_USE_STMT (stmt, iter, name)
1833 if (gimple_code (stmt) == GIMPLE_PHI
1834 && flow_bb_inside_loop_p (loop, gimple_bb (stmt)))
1836 phi = stmt;
1837 BREAK_FROM_IMM_USE_STMT (iter);
1840 if (!phi)
1841 return;
1843 name = PHI_RESULT (phi);
1844 replace_ssa_name_symbol (name, var);
1848 /* Given an unrolled LOOP after predictive commoning, remove the
1849 register copies arising from phi nodes by changing the base
1850 variables of SSA names. TMP_VARS is the set of the temporary variables
1851 for those we want to perform this. */
1853 static void
1854 eliminate_temp_copies (struct loop *loop, bitmap tmp_vars)
1856 edge e;
1857 gimple phi, stmt;
1858 tree name, use, var;
1859 gimple_stmt_iterator psi;
1861 e = loop_latch_edge (loop);
1862 for (psi = gsi_start_phis (loop->header); !gsi_end_p (psi); gsi_next (&psi))
1864 phi = gsi_stmt (psi);
1865 name = PHI_RESULT (phi);
1866 var = SSA_NAME_VAR (name);
1867 if (!var || !bitmap_bit_p (tmp_vars, DECL_UID (var)))
1868 continue;
1869 use = PHI_ARG_DEF_FROM_EDGE (phi, e);
1870 gcc_assert (TREE_CODE (use) == SSA_NAME);
1872 /* Base all the ssa names in the ud and du chain of NAME on VAR. */
1873 stmt = SSA_NAME_DEF_STMT (use);
1874 while (gimple_code (stmt) == GIMPLE_PHI
1875 /* In case we could not unroll the loop enough to eliminate
1876 all copies, we may reach the loop header before the defining
1877 statement (in that case, some register copies will be present
1878 in loop latch in the final code, corresponding to the newly
1879 created looparound phi nodes). */
1880 && gimple_bb (stmt) != loop->header)
1882 gcc_assert (single_pred_p (gimple_bb (stmt)));
1883 use = PHI_ARG_DEF (stmt, 0);
1884 stmt = SSA_NAME_DEF_STMT (use);
1887 base_names_in_chain_on (loop, use, var);
1891 /* Returns true if CHAIN is suitable to be combined. */
1893 static bool
1894 chain_can_be_combined_p (chain_p chain)
1896 return (!chain->combined
1897 && (chain->type == CT_LOAD || chain->type == CT_COMBINATION));
1900 /* Returns the modify statement that uses NAME. Skips over assignment
1901 statements, NAME is replaced with the actual name used in the returned
1902 statement. */
1904 static gimple
1905 find_use_stmt (tree *name)
1907 gimple stmt;
1908 tree rhs, lhs;
1910 /* Skip over assignments. */
1911 while (1)
1913 stmt = single_nonlooparound_use (*name);
1914 if (!stmt)
1915 return NULL;
1917 if (gimple_code (stmt) != GIMPLE_ASSIGN)
1918 return NULL;
1920 lhs = gimple_assign_lhs (stmt);
1921 if (TREE_CODE (lhs) != SSA_NAME)
1922 return NULL;
1924 if (gimple_assign_copy_p (stmt))
1926 rhs = gimple_assign_rhs1 (stmt);
1927 if (rhs != *name)
1928 return NULL;
1930 *name = lhs;
1932 else if (get_gimple_rhs_class (gimple_assign_rhs_code (stmt))
1933 == GIMPLE_BINARY_RHS)
1934 return stmt;
1935 else
1936 return NULL;
1940 /* Returns true if we may perform reassociation for operation CODE in TYPE. */
1942 static bool
1943 may_reassociate_p (tree type, enum tree_code code)
1945 if (FLOAT_TYPE_P (type)
1946 && !flag_unsafe_math_optimizations)
1947 return false;
1949 return (commutative_tree_code (code)
1950 && associative_tree_code (code));
1953 /* If the operation used in STMT is associative and commutative, go through the
1954 tree of the same operations and returns its root. Distance to the root
1955 is stored in DISTANCE. */
1957 static gimple
1958 find_associative_operation_root (gimple stmt, unsigned *distance)
1960 tree lhs;
1961 gimple next;
1962 enum tree_code code = gimple_assign_rhs_code (stmt);
1963 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
1964 unsigned dist = 0;
1966 if (!may_reassociate_p (type, code))
1967 return NULL;
1969 while (1)
1971 lhs = gimple_assign_lhs (stmt);
1972 gcc_assert (TREE_CODE (lhs) == SSA_NAME);
1974 next = find_use_stmt (&lhs);
1975 if (!next
1976 || gimple_assign_rhs_code (next) != code)
1977 break;
1979 stmt = next;
1980 dist++;
1983 if (distance)
1984 *distance = dist;
1985 return stmt;
1988 /* Returns the common statement in that NAME1 and NAME2 have a use. If there
1989 is no such statement, returns NULL_TREE. In case the operation used on
1990 NAME1 and NAME2 is associative and commutative, returns the root of the
1991 tree formed by this operation instead of the statement that uses NAME1 or
1992 NAME2. */
1994 static gimple
1995 find_common_use_stmt (tree *name1, tree *name2)
1997 gimple stmt1, stmt2;
1999 stmt1 = find_use_stmt (name1);
2000 if (!stmt1)
2001 return NULL;
2003 stmt2 = find_use_stmt (name2);
2004 if (!stmt2)
2005 return NULL;
2007 if (stmt1 == stmt2)
2008 return stmt1;
2010 stmt1 = find_associative_operation_root (stmt1, NULL);
2011 if (!stmt1)
2012 return NULL;
2013 stmt2 = find_associative_operation_root (stmt2, NULL);
2014 if (!stmt2)
2015 return NULL;
2017 return (stmt1 == stmt2 ? stmt1 : NULL);
2020 /* Checks whether R1 and R2 are combined together using CODE, with the result
2021 in RSLT_TYPE, in order R1 CODE R2 if SWAP is false and in order R2 CODE R1
2022 if it is true. If CODE is ERROR_MARK, set these values instead. */
2024 static bool
2025 combinable_refs_p (dref r1, dref r2,
2026 enum tree_code *code, bool *swap, tree *rslt_type)
2028 enum tree_code acode;
2029 bool aswap;
2030 tree atype;
2031 tree name1, name2;
2032 gimple stmt;
2034 name1 = name_for_ref (r1);
2035 name2 = name_for_ref (r2);
2036 gcc_assert (name1 != NULL_TREE && name2 != NULL_TREE);
2038 stmt = find_common_use_stmt (&name1, &name2);
2040 if (!stmt
2041 /* A simple post-dominance check - make sure the combination
2042 is executed under the same condition as the references. */
2043 || (gimple_bb (stmt) != gimple_bb (r1->stmt)
2044 && gimple_bb (stmt) != gimple_bb (r2->stmt)))
2045 return false;
2047 acode = gimple_assign_rhs_code (stmt);
2048 aswap = (!commutative_tree_code (acode)
2049 && gimple_assign_rhs1 (stmt) != name1);
2050 atype = TREE_TYPE (gimple_assign_lhs (stmt));
2052 if (*code == ERROR_MARK)
2054 *code = acode;
2055 *swap = aswap;
2056 *rslt_type = atype;
2057 return true;
2060 return (*code == acode
2061 && *swap == aswap
2062 && *rslt_type == atype);
2065 /* Remove OP from the operation on rhs of STMT, and replace STMT with
2066 an assignment of the remaining operand. */
2068 static void
2069 remove_name_from_operation (gimple stmt, tree op)
2071 tree other_op;
2072 gimple_stmt_iterator si;
2074 gcc_assert (is_gimple_assign (stmt));
2076 if (gimple_assign_rhs1 (stmt) == op)
2077 other_op = gimple_assign_rhs2 (stmt);
2078 else
2079 other_op = gimple_assign_rhs1 (stmt);
2081 si = gsi_for_stmt (stmt);
2082 gimple_assign_set_rhs_from_tree (&si, other_op);
2084 /* We should not have reallocated STMT. */
2085 gcc_assert (gsi_stmt (si) == stmt);
2087 update_stmt (stmt);
2090 /* Reassociates the expression in that NAME1 and NAME2 are used so that they
2091 are combined in a single statement, and returns this statement. */
2093 static gimple
2094 reassociate_to_the_same_stmt (tree name1, tree name2)
2096 gimple stmt1, stmt2, root1, root2, s1, s2;
2097 gimple new_stmt, tmp_stmt;
2098 tree new_name, tmp_name, var, r1, r2;
2099 unsigned dist1, dist2;
2100 enum tree_code code;
2101 tree type = TREE_TYPE (name1);
2102 gimple_stmt_iterator bsi;
2104 stmt1 = find_use_stmt (&name1);
2105 stmt2 = find_use_stmt (&name2);
2106 root1 = find_associative_operation_root (stmt1, &dist1);
2107 root2 = find_associative_operation_root (stmt2, &dist2);
2108 code = gimple_assign_rhs_code (stmt1);
2110 gcc_assert (root1 && root2 && root1 == root2
2111 && code == gimple_assign_rhs_code (stmt2));
2113 /* Find the root of the nearest expression in that both NAME1 and NAME2
2114 are used. */
2115 r1 = name1;
2116 s1 = stmt1;
2117 r2 = name2;
2118 s2 = stmt2;
2120 while (dist1 > dist2)
2122 s1 = find_use_stmt (&r1);
2123 r1 = gimple_assign_lhs (s1);
2124 dist1--;
2126 while (dist2 > dist1)
2128 s2 = find_use_stmt (&r2);
2129 r2 = gimple_assign_lhs (s2);
2130 dist2--;
2133 while (s1 != s2)
2135 s1 = find_use_stmt (&r1);
2136 r1 = gimple_assign_lhs (s1);
2137 s2 = find_use_stmt (&r2);
2138 r2 = gimple_assign_lhs (s2);
2141 /* Remove NAME1 and NAME2 from the statements in that they are used
2142 currently. */
2143 remove_name_from_operation (stmt1, name1);
2144 remove_name_from_operation (stmt2, name2);
2146 /* Insert the new statement combining NAME1 and NAME2 before S1, and
2147 combine it with the rhs of S1. */
2148 var = create_tmp_reg (type, "predreastmp");
2149 new_name = make_ssa_name (var, NULL);
2150 new_stmt = gimple_build_assign_with_ops (code, new_name, name1, name2);
2152 var = create_tmp_reg (type, "predreastmp");
2153 tmp_name = make_ssa_name (var, NULL);
2155 /* Rhs of S1 may now be either a binary expression with operation
2156 CODE, or gimple_val (in case that stmt1 == s1 or stmt2 == s1,
2157 so that name1 or name2 was removed from it). */
2158 tmp_stmt = gimple_build_assign_with_ops (gimple_assign_rhs_code (s1),
2159 tmp_name,
2160 gimple_assign_rhs1 (s1),
2161 gimple_assign_rhs2 (s1));
2163 bsi = gsi_for_stmt (s1);
2164 gimple_assign_set_rhs_with_ops (&bsi, code, new_name, tmp_name);
2165 s1 = gsi_stmt (bsi);
2166 update_stmt (s1);
2168 gsi_insert_before (&bsi, new_stmt, GSI_SAME_STMT);
2169 gsi_insert_before (&bsi, tmp_stmt, GSI_SAME_STMT);
2171 return new_stmt;
2174 /* Returns the statement that combines references R1 and R2. In case R1
2175 and R2 are not used in the same statement, but they are used with an
2176 associative and commutative operation in the same expression, reassociate
2177 the expression so that they are used in the same statement. */
2179 static gimple
2180 stmt_combining_refs (dref r1, dref r2)
2182 gimple stmt1, stmt2;
2183 tree name1 = name_for_ref (r1);
2184 tree name2 = name_for_ref (r2);
2186 stmt1 = find_use_stmt (&name1);
2187 stmt2 = find_use_stmt (&name2);
2188 if (stmt1 == stmt2)
2189 return stmt1;
2191 return reassociate_to_the_same_stmt (name1, name2);
2194 /* Tries to combine chains CH1 and CH2 together. If this succeeds, the
2195 description of the new chain is returned, otherwise we return NULL. */
2197 static chain_p
2198 combine_chains (chain_p ch1, chain_p ch2)
2200 dref r1, r2, nw;
2201 enum tree_code op = ERROR_MARK;
2202 bool swap = false;
2203 chain_p new_chain;
2204 unsigned i;
2205 gimple root_stmt;
2206 tree rslt_type = NULL_TREE;
2208 if (ch1 == ch2)
2209 return NULL;
2210 if (ch1->length != ch2->length)
2211 return NULL;
2213 if (ch1->refs.length () != ch2->refs.length ())
2214 return NULL;
2216 for (i = 0; (ch1->refs.iterate (i, &r1)
2217 && ch2->refs.iterate (i, &r2)); i++)
2219 if (r1->distance != r2->distance)
2220 return NULL;
2222 if (!combinable_refs_p (r1, r2, &op, &swap, &rslt_type))
2223 return NULL;
2226 if (swap)
2228 chain_p tmp = ch1;
2229 ch1 = ch2;
2230 ch2 = tmp;
2233 new_chain = XCNEW (struct chain);
2234 new_chain->type = CT_COMBINATION;
2235 new_chain->op = op;
2236 new_chain->ch1 = ch1;
2237 new_chain->ch2 = ch2;
2238 new_chain->rslt_type = rslt_type;
2239 new_chain->length = ch1->length;
2241 for (i = 0; (ch1->refs.iterate (i, &r1)
2242 && ch2->refs.iterate (i, &r2)); i++)
2244 nw = XCNEW (struct dref_d);
2245 nw->stmt = stmt_combining_refs (r1, r2);
2246 nw->distance = r1->distance;
2248 new_chain->refs.safe_push (nw);
2251 new_chain->has_max_use_after = false;
2252 root_stmt = get_chain_root (new_chain)->stmt;
2253 for (i = 1; new_chain->refs.iterate (i, &nw); i++)
2255 if (nw->distance == new_chain->length
2256 && !stmt_dominates_stmt_p (nw->stmt, root_stmt))
2258 new_chain->has_max_use_after = true;
2259 break;
2263 ch1->combined = true;
2264 ch2->combined = true;
2265 return new_chain;
2268 /* Try to combine the CHAINS. */
2270 static void
2271 try_combine_chains (vec<chain_p> *chains)
2273 unsigned i, j;
2274 chain_p ch1, ch2, cch;
2275 vec<chain_p> worklist = vNULL;
2277 FOR_EACH_VEC_ELT (*chains, i, ch1)
2278 if (chain_can_be_combined_p (ch1))
2279 worklist.safe_push (ch1);
2281 while (!worklist.is_empty ())
2283 ch1 = worklist.pop ();
2284 if (!chain_can_be_combined_p (ch1))
2285 continue;
2287 FOR_EACH_VEC_ELT (*chains, j, ch2)
2289 if (!chain_can_be_combined_p (ch2))
2290 continue;
2292 cch = combine_chains (ch1, ch2);
2293 if (cch)
2295 worklist.safe_push (cch);
2296 chains->safe_push (cch);
2297 break;
2302 worklist.release ();
2305 /* Prepare initializers for CHAIN in LOOP. Returns false if this is
2306 impossible because one of these initializers may trap, true otherwise. */
2308 static bool
2309 prepare_initializers_chain (struct loop *loop, chain_p chain)
2311 unsigned i, n = (chain->type == CT_INVARIANT) ? 1 : chain->length;
2312 struct data_reference *dr = get_chain_root (chain)->ref;
2313 tree init;
2314 gimple_seq stmts;
2315 dref laref;
2316 edge entry = loop_preheader_edge (loop);
2318 /* Find the initializers for the variables, and check that they cannot
2319 trap. */
2320 chain->inits.create (n);
2321 for (i = 0; i < n; i++)
2322 chain->inits.quick_push (NULL_TREE);
2324 /* If we have replaced some looparound phi nodes, use their initializers
2325 instead of creating our own. */
2326 FOR_EACH_VEC_ELT (chain->refs, i, laref)
2328 if (gimple_code (laref->stmt) != GIMPLE_PHI)
2329 continue;
2331 gcc_assert (laref->distance > 0);
2332 chain->inits[n - laref->distance]
2333 = PHI_ARG_DEF_FROM_EDGE (laref->stmt, entry);
2336 for (i = 0; i < n; i++)
2338 if (chain->inits[i] != NULL_TREE)
2339 continue;
2341 init = ref_at_iteration (dr, (int) i - n, &stmts);
2342 if (!chain->all_always_accessed && tree_could_trap_p (init))
2343 return false;
2345 if (stmts)
2346 gsi_insert_seq_on_edge_immediate (entry, stmts);
2348 chain->inits[i] = init;
2351 return true;
2354 /* Prepare initializers for CHAINS in LOOP, and free chains that cannot
2355 be used because the initializers might trap. */
2357 static void
2358 prepare_initializers (struct loop *loop, vec<chain_p> chains)
2360 chain_p chain;
2361 unsigned i;
2363 for (i = 0; i < chains.length (); )
2365 chain = chains[i];
2366 if (prepare_initializers_chain (loop, chain))
2367 i++;
2368 else
2370 release_chain (chain);
2371 chains.unordered_remove (i);
2376 /* Performs predictive commoning for LOOP. Returns true if LOOP was
2377 unrolled. */
2379 static bool
2380 tree_predictive_commoning_loop (struct loop *loop)
2382 vec<data_reference_p> datarefs;
2383 vec<ddr_p> dependences;
2384 struct component *components;
2385 vec<chain_p> chains = vNULL;
2386 unsigned unroll_factor;
2387 struct tree_niter_desc desc;
2388 bool unroll = false;
2389 edge exit;
2390 bitmap tmp_vars;
2392 if (dump_file && (dump_flags & TDF_DETAILS))
2393 fprintf (dump_file, "Processing loop %d\n", loop->num);
2395 /* Find the data references and split them into components according to their
2396 dependence relations. */
2397 stack_vec<loop_p, 3> loop_nest;
2398 dependences.create (10);
2399 datarefs.create (10);
2400 if (! compute_data_dependences_for_loop (loop, true, &loop_nest, &datarefs,
2401 &dependences))
2403 if (dump_file && (dump_flags & TDF_DETAILS))
2404 fprintf (dump_file, "Cannot analyze data dependencies\n");
2405 free_data_refs (datarefs);
2406 free_dependence_relations (dependences);
2407 return false;
2410 if (dump_file && (dump_flags & TDF_DETAILS))
2411 dump_data_dependence_relations (dump_file, dependences);
2413 components = split_data_refs_to_components (loop, datarefs, dependences);
2414 loop_nest.release ();
2415 free_dependence_relations (dependences);
2416 if (!components)
2418 free_data_refs (datarefs);
2419 return false;
2422 if (dump_file && (dump_flags & TDF_DETAILS))
2424 fprintf (dump_file, "Initial state:\n\n");
2425 dump_components (dump_file, components);
2428 /* Find the suitable components and split them into chains. */
2429 components = filter_suitable_components (loop, components);
2431 tmp_vars = BITMAP_ALLOC (NULL);
2432 looparound_phis = BITMAP_ALLOC (NULL);
2433 determine_roots (loop, components, &chains);
2434 release_components (components);
2436 if (!chains.exists ())
2438 if (dump_file && (dump_flags & TDF_DETAILS))
2439 fprintf (dump_file,
2440 "Predictive commoning failed: no suitable chains\n");
2441 goto end;
2443 prepare_initializers (loop, chains);
2445 /* Try to combine the chains that are always worked with together. */
2446 try_combine_chains (&chains);
2448 if (dump_file && (dump_flags & TDF_DETAILS))
2450 fprintf (dump_file, "Before commoning:\n\n");
2451 dump_chains (dump_file, chains);
2454 /* Determine the unroll factor, and if the loop should be unrolled, ensure
2455 that its number of iterations is divisible by the factor. */
2456 unroll_factor = determine_unroll_factor (chains);
2457 scev_reset ();
2458 unroll = (unroll_factor > 1
2459 && can_unroll_loop_p (loop, unroll_factor, &desc));
2460 exit = single_dom_exit (loop);
2462 /* Execute the predictive commoning transformations, and possibly unroll the
2463 loop. */
2464 if (unroll)
2466 struct epcc_data dta;
2468 if (dump_file && (dump_flags & TDF_DETAILS))
2469 fprintf (dump_file, "Unrolling %u times.\n", unroll_factor);
2471 dta.chains = chains;
2472 dta.tmp_vars = tmp_vars;
2474 update_ssa (TODO_update_ssa_only_virtuals);
2476 /* Cfg manipulations performed in tree_transform_and_unroll_loop before
2477 execute_pred_commoning_cbck is called may cause phi nodes to be
2478 reallocated, which is a problem since CHAINS may point to these
2479 statements. To fix this, we store the ssa names defined by the
2480 phi nodes here instead of the phi nodes themselves, and restore
2481 the phi nodes in execute_pred_commoning_cbck. A bit hacky. */
2482 replace_phis_by_defined_names (chains);
2484 tree_transform_and_unroll_loop (loop, unroll_factor, exit, &desc,
2485 execute_pred_commoning_cbck, &dta);
2486 eliminate_temp_copies (loop, tmp_vars);
2488 else
2490 if (dump_file && (dump_flags & TDF_DETAILS))
2491 fprintf (dump_file,
2492 "Executing predictive commoning without unrolling.\n");
2493 execute_pred_commoning (loop, chains, tmp_vars);
2496 end: ;
2497 release_chains (chains);
2498 free_data_refs (datarefs);
2499 BITMAP_FREE (tmp_vars);
2500 BITMAP_FREE (looparound_phis);
2502 free_affine_expand_cache (&name_expansions);
2504 return unroll;
2507 /* Runs predictive commoning. */
2509 unsigned
2510 tree_predictive_commoning (void)
2512 bool unrolled = false;
2513 struct loop *loop;
2514 unsigned ret = 0;
2516 initialize_original_copy_tables ();
2517 FOR_EACH_LOOP (loop, LI_ONLY_INNERMOST)
2518 if (optimize_loop_for_speed_p (loop))
2520 unrolled |= tree_predictive_commoning_loop (loop);
2523 if (unrolled)
2525 scev_reset ();
2526 ret = TODO_cleanup_cfg;
2528 free_original_copy_tables ();
2530 return ret;
2533 /* Predictive commoning Pass. */
2535 static unsigned
2536 run_tree_predictive_commoning (void)
2538 if (!current_loops)
2539 return 0;
2541 return tree_predictive_commoning ();
2544 static bool
2545 gate_tree_predictive_commoning (void)
2547 return flag_predictive_commoning != 0;
2550 namespace {
2552 const pass_data pass_data_predcom =
2554 GIMPLE_PASS, /* type */
2555 "pcom", /* name */
2556 OPTGROUP_LOOP, /* optinfo_flags */
2557 true, /* has_gate */
2558 true, /* has_execute */
2559 TV_PREDCOM, /* tv_id */
2560 PROP_cfg, /* properties_required */
2561 0, /* properties_provided */
2562 0, /* properties_destroyed */
2563 0, /* todo_flags_start */
2564 TODO_update_ssa_only_virtuals, /* todo_flags_finish */
2567 class pass_predcom : public gimple_opt_pass
2569 public:
2570 pass_predcom (gcc::context *ctxt)
2571 : gimple_opt_pass (pass_data_predcom, ctxt)
2574 /* opt_pass methods: */
2575 bool gate () { return gate_tree_predictive_commoning (); }
2576 unsigned int execute () { return run_tree_predictive_commoning (); }
2578 }; // class pass_predcom
2580 } // anon namespace
2582 gimple_opt_pass *
2583 make_pass_predcom (gcc::context *ctxt)
2585 return new pass_predcom (ctxt);