Optimize powerpc*-*-linux* e500 hardfp/soft-fp use.
[official-gcc.git] / gcc / tree-predcom.c
blobdbb9e7102fc05382da4da46d9a4074b5d5413f47
1 /* Predictive commoning.
2 Copyright (C) 2005-2014 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 "predict.h"
195 #include "vec.h"
196 #include "hashtab.h"
197 #include "hash-set.h"
198 #include "machmode.h"
199 #include "hard-reg-set.h"
200 #include "input.h"
201 #include "function.h"
202 #include "dominance.h"
203 #include "cfg.h"
204 #include "basic-block.h"
205 #include "tree-ssa-alias.h"
206 #include "internal-fn.h"
207 #include "tree-eh.h"
208 #include "gimple-expr.h"
209 #include "is-a.h"
210 #include "gimple.h"
211 #include "gimplify.h"
212 #include "gimple-iterator.h"
213 #include "gimplify-me.h"
214 #include "gimple-ssa.h"
215 #include "tree-phinodes.h"
216 #include "ssa-iterators.h"
217 #include "stringpool.h"
218 #include "tree-ssanames.h"
219 #include "tree-ssa-loop-ivopts.h"
220 #include "tree-ssa-loop-manip.h"
221 #include "tree-ssa-loop-niter.h"
222 #include "tree-ssa-loop.h"
223 #include "tree-into-ssa.h"
224 #include "expr.h"
225 #include "tree-dfa.h"
226 #include "tree-ssa.h"
227 #include "tree-data-ref.h"
228 #include "tree-scalar-evolution.h"
229 #include "tree-chrec.h"
230 #include "params.h"
231 #include "gimple-pretty-print.h"
232 #include "tree-pass.h"
233 #include "tree-affine.h"
234 #include "tree-inline.h"
235 #include "wide-int-print.h"
237 /* The maximum number of iterations between the considered memory
238 references. */
240 #define MAX_DISTANCE (target_avail_regs < 16 ? 4 : 8)
242 /* Data references (or phi nodes that carry data reference values across
243 loop iterations). */
245 typedef struct dref_d
247 /* The reference itself. */
248 struct data_reference *ref;
250 /* The statement in that the reference appears. */
251 gimple stmt;
253 /* In case that STMT is a phi node, this field is set to the SSA name
254 defined by it in replace_phis_by_defined_names (in order to avoid
255 pointing to phi node that got reallocated in the meantime). */
256 tree name_defined_by_phi;
258 /* Distance of the reference from the root of the chain (in number of
259 iterations of the loop). */
260 unsigned distance;
262 /* Number of iterations offset from the first reference in the component. */
263 widest_int offset;
265 /* Number of the reference in a component, in dominance ordering. */
266 unsigned pos;
268 /* True if the memory reference is always accessed when the loop is
269 entered. */
270 unsigned always_accessed : 1;
271 } *dref;
274 /* Type of the chain of the references. */
276 enum chain_type
278 /* The addresses of the references in the chain are constant. */
279 CT_INVARIANT,
281 /* There are only loads in the chain. */
282 CT_LOAD,
284 /* Root of the chain is store, the rest are loads. */
285 CT_STORE_LOAD,
287 /* A combination of two chains. */
288 CT_COMBINATION
291 /* Chains of data references. */
293 typedef struct chain
295 /* Type of the chain. */
296 enum chain_type type;
298 /* For combination chains, the operator and the two chains that are
299 combined, and the type of the result. */
300 enum tree_code op;
301 tree rslt_type;
302 struct chain *ch1, *ch2;
304 /* The references in the chain. */
305 vec<dref> refs;
307 /* The maximum distance of the reference in the chain from the root. */
308 unsigned length;
310 /* The variables used to copy the value throughout iterations. */
311 vec<tree> vars;
313 /* Initializers for the variables. */
314 vec<tree> inits;
316 /* True if there is a use of a variable with the maximal distance
317 that comes after the root in the loop. */
318 unsigned has_max_use_after : 1;
320 /* True if all the memory references in the chain are always accessed. */
321 unsigned all_always_accessed : 1;
323 /* True if this chain was combined together with some other chain. */
324 unsigned combined : 1;
325 } *chain_p;
328 /* Describes the knowledge about the step of the memory references in
329 the component. */
331 enum ref_step_type
333 /* The step is zero. */
334 RS_INVARIANT,
336 /* The step is nonzero. */
337 RS_NONZERO,
339 /* The step may or may not be nonzero. */
340 RS_ANY
343 /* Components of the data dependence graph. */
345 struct component
347 /* The references in the component. */
348 vec<dref> refs;
350 /* What we know about the step of the references in the component. */
351 enum ref_step_type comp_step;
353 /* Next component in the list. */
354 struct component *next;
357 /* Bitmap of ssa names defined by looparound phi nodes covered by chains. */
359 static bitmap looparound_phis;
361 /* Cache used by tree_to_aff_combination_expand. */
363 static hash_map<tree, name_expansion *> *name_expansions;
365 /* Dumps data reference REF to FILE. */
367 extern void dump_dref (FILE *, dref);
368 void
369 dump_dref (FILE *file, dref ref)
371 if (ref->ref)
373 fprintf (file, " ");
374 print_generic_expr (file, DR_REF (ref->ref), TDF_SLIM);
375 fprintf (file, " (id %u%s)\n", ref->pos,
376 DR_IS_READ (ref->ref) ? "" : ", write");
378 fprintf (file, " offset ");
379 print_decs (ref->offset, file);
380 fprintf (file, "\n");
382 fprintf (file, " distance %u\n", ref->distance);
384 else
386 if (gimple_code (ref->stmt) == GIMPLE_PHI)
387 fprintf (file, " looparound ref\n");
388 else
389 fprintf (file, " combination ref\n");
390 fprintf (file, " in statement ");
391 print_gimple_stmt (file, ref->stmt, 0, TDF_SLIM);
392 fprintf (file, "\n");
393 fprintf (file, " distance %u\n", ref->distance);
398 /* Dumps CHAIN to FILE. */
400 extern void dump_chain (FILE *, chain_p);
401 void
402 dump_chain (FILE *file, chain_p chain)
404 dref a;
405 const char *chain_type;
406 unsigned i;
407 tree var;
409 switch (chain->type)
411 case CT_INVARIANT:
412 chain_type = "Load motion";
413 break;
415 case CT_LOAD:
416 chain_type = "Loads-only";
417 break;
419 case CT_STORE_LOAD:
420 chain_type = "Store-loads";
421 break;
423 case CT_COMBINATION:
424 chain_type = "Combination";
425 break;
427 default:
428 gcc_unreachable ();
431 fprintf (file, "%s chain %p%s\n", chain_type, (void *) chain,
432 chain->combined ? " (combined)" : "");
433 if (chain->type != CT_INVARIANT)
434 fprintf (file, " max distance %u%s\n", chain->length,
435 chain->has_max_use_after ? "" : ", may reuse first");
437 if (chain->type == CT_COMBINATION)
439 fprintf (file, " equal to %p %s %p in type ",
440 (void *) chain->ch1, op_symbol_code (chain->op),
441 (void *) chain->ch2);
442 print_generic_expr (file, chain->rslt_type, TDF_SLIM);
443 fprintf (file, "\n");
446 if (chain->vars.exists ())
448 fprintf (file, " vars");
449 FOR_EACH_VEC_ELT (chain->vars, i, var)
451 fprintf (file, " ");
452 print_generic_expr (file, var, TDF_SLIM);
454 fprintf (file, "\n");
457 if (chain->inits.exists ())
459 fprintf (file, " inits");
460 FOR_EACH_VEC_ELT (chain->inits, i, var)
462 fprintf (file, " ");
463 print_generic_expr (file, var, TDF_SLIM);
465 fprintf (file, "\n");
468 fprintf (file, " references:\n");
469 FOR_EACH_VEC_ELT (chain->refs, i, a)
470 dump_dref (file, a);
472 fprintf (file, "\n");
475 /* Dumps CHAINS to FILE. */
477 extern void dump_chains (FILE *, vec<chain_p> );
478 void
479 dump_chains (FILE *file, vec<chain_p> chains)
481 chain_p chain;
482 unsigned i;
484 FOR_EACH_VEC_ELT (chains, i, chain)
485 dump_chain (file, chain);
488 /* Dumps COMP to FILE. */
490 extern void dump_component (FILE *, struct component *);
491 void
492 dump_component (FILE *file, struct component *comp)
494 dref a;
495 unsigned i;
497 fprintf (file, "Component%s:\n",
498 comp->comp_step == RS_INVARIANT ? " (invariant)" : "");
499 FOR_EACH_VEC_ELT (comp->refs, i, a)
500 dump_dref (file, a);
501 fprintf (file, "\n");
504 /* Dumps COMPS to FILE. */
506 extern void dump_components (FILE *, struct component *);
507 void
508 dump_components (FILE *file, struct component *comps)
510 struct component *comp;
512 for (comp = comps; comp; comp = comp->next)
513 dump_component (file, comp);
516 /* Frees a chain CHAIN. */
518 static void
519 release_chain (chain_p chain)
521 dref ref;
522 unsigned i;
524 if (chain == NULL)
525 return;
527 FOR_EACH_VEC_ELT (chain->refs, i, ref)
528 free (ref);
530 chain->refs.release ();
531 chain->vars.release ();
532 chain->inits.release ();
534 free (chain);
537 /* Frees CHAINS. */
539 static void
540 release_chains (vec<chain_p> chains)
542 unsigned i;
543 chain_p chain;
545 FOR_EACH_VEC_ELT (chains, i, chain)
546 release_chain (chain);
547 chains.release ();
550 /* Frees a component COMP. */
552 static void
553 release_component (struct component *comp)
555 comp->refs.release ();
556 free (comp);
559 /* Frees list of components COMPS. */
561 static void
562 release_components (struct component *comps)
564 struct component *act, *next;
566 for (act = comps; act; act = next)
568 next = act->next;
569 release_component (act);
573 /* Finds a root of tree given by FATHERS containing A, and performs path
574 shortening. */
576 static unsigned
577 component_of (unsigned fathers[], unsigned a)
579 unsigned root, n;
581 for (root = a; root != fathers[root]; root = fathers[root])
582 continue;
584 for (; a != root; a = n)
586 n = fathers[a];
587 fathers[a] = root;
590 return root;
593 /* Join operation for DFU. FATHERS gives the tree, SIZES are sizes of the
594 components, A and B are components to merge. */
596 static void
597 merge_comps (unsigned fathers[], unsigned sizes[], unsigned a, unsigned b)
599 unsigned ca = component_of (fathers, a);
600 unsigned cb = component_of (fathers, b);
602 if (ca == cb)
603 return;
605 if (sizes[ca] < sizes[cb])
607 sizes[cb] += sizes[ca];
608 fathers[ca] = cb;
610 else
612 sizes[ca] += sizes[cb];
613 fathers[cb] = ca;
617 /* Returns true if A is a reference that is suitable for predictive commoning
618 in the innermost loop that contains it. REF_STEP is set according to the
619 step of the reference A. */
621 static bool
622 suitable_reference_p (struct data_reference *a, enum ref_step_type *ref_step)
624 tree ref = DR_REF (a), step = DR_STEP (a);
626 if (!step
627 || TREE_THIS_VOLATILE (ref)
628 || !is_gimple_reg_type (TREE_TYPE (ref))
629 || tree_could_throw_p (ref))
630 return false;
632 if (integer_zerop (step))
633 *ref_step = RS_INVARIANT;
634 else if (integer_nonzerop (step))
635 *ref_step = RS_NONZERO;
636 else
637 *ref_step = RS_ANY;
639 return true;
642 /* Stores DR_OFFSET (DR) + DR_INIT (DR) to OFFSET. */
644 static void
645 aff_combination_dr_offset (struct data_reference *dr, aff_tree *offset)
647 tree type = TREE_TYPE (DR_OFFSET (dr));
648 aff_tree delta;
650 tree_to_aff_combination_expand (DR_OFFSET (dr), type, offset,
651 &name_expansions);
652 aff_combination_const (&delta, type, wi::to_widest (DR_INIT (dr)));
653 aff_combination_add (offset, &delta);
656 /* Determines number of iterations of the innermost enclosing loop before B
657 refers to exactly the same location as A and stores it to OFF. If A and
658 B do not have the same step, they never meet, or anything else fails,
659 returns false, otherwise returns true. Both A and B are assumed to
660 satisfy suitable_reference_p. */
662 static bool
663 determine_offset (struct data_reference *a, struct data_reference *b,
664 widest_int *off)
666 aff_tree diff, baseb, step;
667 tree typea, typeb;
669 /* Check that both the references access the location in the same type. */
670 typea = TREE_TYPE (DR_REF (a));
671 typeb = TREE_TYPE (DR_REF (b));
672 if (!useless_type_conversion_p (typeb, typea))
673 return false;
675 /* Check whether the base address and the step of both references is the
676 same. */
677 if (!operand_equal_p (DR_STEP (a), DR_STEP (b), 0)
678 || !operand_equal_p (DR_BASE_ADDRESS (a), DR_BASE_ADDRESS (b), 0))
679 return false;
681 if (integer_zerop (DR_STEP (a)))
683 /* If the references have loop invariant address, check that they access
684 exactly the same location. */
685 *off = 0;
686 return (operand_equal_p (DR_OFFSET (a), DR_OFFSET (b), 0)
687 && operand_equal_p (DR_INIT (a), DR_INIT (b), 0));
690 /* Compare the offsets of the addresses, and check whether the difference
691 is a multiple of step. */
692 aff_combination_dr_offset (a, &diff);
693 aff_combination_dr_offset (b, &baseb);
694 aff_combination_scale (&baseb, -1);
695 aff_combination_add (&diff, &baseb);
697 tree_to_aff_combination_expand (DR_STEP (a), TREE_TYPE (DR_STEP (a)),
698 &step, &name_expansions);
699 return aff_combination_constant_multiple_p (&diff, &step, off);
702 /* Returns the last basic block in LOOP for that we are sure that
703 it is executed whenever the loop is entered. */
705 static basic_block
706 last_always_executed_block (struct loop *loop)
708 unsigned i;
709 vec<edge> exits = get_loop_exit_edges (loop);
710 edge ex;
711 basic_block last = loop->latch;
713 FOR_EACH_VEC_ELT (exits, i, ex)
714 last = nearest_common_dominator (CDI_DOMINATORS, last, ex->src);
715 exits.release ();
717 return last;
720 /* Splits dependence graph on DATAREFS described by DEPENDS to components. */
722 static struct component *
723 split_data_refs_to_components (struct loop *loop,
724 vec<data_reference_p> datarefs,
725 vec<ddr_p> depends)
727 unsigned i, n = datarefs.length ();
728 unsigned ca, ia, ib, bad;
729 unsigned *comp_father = XNEWVEC (unsigned, n + 1);
730 unsigned *comp_size = XNEWVEC (unsigned, n + 1);
731 struct component **comps;
732 struct data_reference *dr, *dra, *drb;
733 struct data_dependence_relation *ddr;
734 struct component *comp_list = NULL, *comp;
735 dref dataref;
736 basic_block last_always_executed = last_always_executed_block (loop);
738 FOR_EACH_VEC_ELT (datarefs, i, dr)
740 if (!DR_REF (dr))
742 /* A fake reference for call or asm_expr that may clobber memory;
743 just fail. */
744 goto end;
746 /* predcom pass isn't prepared to handle calls with data references. */
747 if (is_gimple_call (DR_STMT (dr)))
748 goto end;
749 dr->aux = (void *) (size_t) i;
750 comp_father[i] = i;
751 comp_size[i] = 1;
754 /* A component reserved for the "bad" data references. */
755 comp_father[n] = n;
756 comp_size[n] = 1;
758 FOR_EACH_VEC_ELT (datarefs, i, dr)
760 enum ref_step_type dummy;
762 if (!suitable_reference_p (dr, &dummy))
764 ia = (unsigned) (size_t) dr->aux;
765 merge_comps (comp_father, comp_size, n, ia);
769 FOR_EACH_VEC_ELT (depends, i, ddr)
771 widest_int dummy_off;
773 if (DDR_ARE_DEPENDENT (ddr) == chrec_known)
774 continue;
776 dra = DDR_A (ddr);
777 drb = DDR_B (ddr);
778 ia = component_of (comp_father, (unsigned) (size_t) dra->aux);
779 ib = component_of (comp_father, (unsigned) (size_t) drb->aux);
780 if (ia == ib)
781 continue;
783 bad = component_of (comp_father, n);
785 /* If both A and B are reads, we may ignore unsuitable dependences. */
786 if (DR_IS_READ (dra) && DR_IS_READ (drb))
788 if (ia == bad || ib == bad
789 || !determine_offset (dra, drb, &dummy_off))
790 continue;
792 /* If A is read and B write or vice versa and there is unsuitable
793 dependence, instead of merging both components into a component
794 that will certainly not pass suitable_component_p, just put the
795 read into bad component, perhaps at least the write together with
796 all the other data refs in it's component will be optimizable. */
797 else if (DR_IS_READ (dra) && ib != bad)
799 if (ia == bad)
800 continue;
801 else if (!determine_offset (dra, drb, &dummy_off))
803 merge_comps (comp_father, comp_size, bad, ia);
804 continue;
807 else if (DR_IS_READ (drb) && ia != bad)
809 if (ib == bad)
810 continue;
811 else if (!determine_offset (dra, drb, &dummy_off))
813 merge_comps (comp_father, comp_size, bad, ib);
814 continue;
818 merge_comps (comp_father, comp_size, ia, ib);
821 comps = XCNEWVEC (struct component *, n);
822 bad = component_of (comp_father, n);
823 FOR_EACH_VEC_ELT (datarefs, i, dr)
825 ia = (unsigned) (size_t) dr->aux;
826 ca = component_of (comp_father, ia);
827 if (ca == bad)
828 continue;
830 comp = comps[ca];
831 if (!comp)
833 comp = XCNEW (struct component);
834 comp->refs.create (comp_size[ca]);
835 comps[ca] = comp;
838 dataref = XCNEW (struct dref_d);
839 dataref->ref = dr;
840 dataref->stmt = DR_STMT (dr);
841 dataref->offset = 0;
842 dataref->distance = 0;
844 dataref->always_accessed
845 = dominated_by_p (CDI_DOMINATORS, last_always_executed,
846 gimple_bb (dataref->stmt));
847 dataref->pos = comp->refs.length ();
848 comp->refs.quick_push (dataref);
851 for (i = 0; i < n; i++)
853 comp = comps[i];
854 if (comp)
856 comp->next = comp_list;
857 comp_list = comp;
860 free (comps);
862 end:
863 free (comp_father);
864 free (comp_size);
865 return comp_list;
868 /* Returns true if the component COMP satisfies the conditions
869 described in 2) at the beginning of this file. LOOP is the current
870 loop. */
872 static bool
873 suitable_component_p (struct loop *loop, struct component *comp)
875 unsigned i;
876 dref a, first;
877 basic_block ba, bp = loop->header;
878 bool ok, has_write = false;
880 FOR_EACH_VEC_ELT (comp->refs, i, a)
882 ba = gimple_bb (a->stmt);
884 if (!just_once_each_iteration_p (loop, ba))
885 return false;
887 gcc_assert (dominated_by_p (CDI_DOMINATORS, ba, bp));
888 bp = ba;
890 if (DR_IS_WRITE (a->ref))
891 has_write = true;
894 first = comp->refs[0];
895 ok = suitable_reference_p (first->ref, &comp->comp_step);
896 gcc_assert (ok);
897 first->offset = 0;
899 for (i = 1; comp->refs.iterate (i, &a); i++)
901 if (!determine_offset (first->ref, a->ref, &a->offset))
902 return false;
904 #ifdef ENABLE_CHECKING
906 enum ref_step_type a_step;
907 ok = suitable_reference_p (a->ref, &a_step);
908 gcc_assert (ok && a_step == comp->comp_step);
910 #endif
913 /* If there is a write inside the component, we must know whether the
914 step is nonzero or not -- we would not otherwise be able to recognize
915 whether the value accessed by reads comes from the OFFSET-th iteration
916 or the previous one. */
917 if (has_write && comp->comp_step == RS_ANY)
918 return false;
920 return true;
923 /* Check the conditions on references inside each of components COMPS,
924 and remove the unsuitable components from the list. The new list
925 of components is returned. The conditions are described in 2) at
926 the beginning of this file. LOOP is the current loop. */
928 static struct component *
929 filter_suitable_components (struct loop *loop, struct component *comps)
931 struct component **comp, *act;
933 for (comp = &comps; *comp; )
935 act = *comp;
936 if (suitable_component_p (loop, act))
937 comp = &act->next;
938 else
940 dref ref;
941 unsigned i;
943 *comp = act->next;
944 FOR_EACH_VEC_ELT (act->refs, i, ref)
945 free (ref);
946 release_component (act);
950 return comps;
953 /* Compares two drefs A and B by their offset and position. Callback for
954 qsort. */
956 static int
957 order_drefs (const void *a, const void *b)
959 const dref *const da = (const dref *) a;
960 const dref *const db = (const dref *) b;
961 int offcmp = wi::cmps ((*da)->offset, (*db)->offset);
963 if (offcmp != 0)
964 return offcmp;
966 return (*da)->pos - (*db)->pos;
969 /* Returns root of the CHAIN. */
971 static inline dref
972 get_chain_root (chain_p chain)
974 return chain->refs[0];
977 /* Adds REF to the chain CHAIN. */
979 static void
980 add_ref_to_chain (chain_p chain, dref ref)
982 dref root = get_chain_root (chain);
984 gcc_assert (wi::les_p (root->offset, ref->offset));
985 widest_int dist = ref->offset - root->offset;
986 if (wi::leu_p (MAX_DISTANCE, dist))
988 free (ref);
989 return;
991 gcc_assert (wi::fits_uhwi_p (dist));
993 chain->refs.safe_push (ref);
995 ref->distance = dist.to_uhwi ();
997 if (ref->distance >= chain->length)
999 chain->length = ref->distance;
1000 chain->has_max_use_after = false;
1003 if (ref->distance == chain->length
1004 && ref->pos > root->pos)
1005 chain->has_max_use_after = true;
1007 chain->all_always_accessed &= ref->always_accessed;
1010 /* Returns the chain for invariant component COMP. */
1012 static chain_p
1013 make_invariant_chain (struct component *comp)
1015 chain_p chain = XCNEW (struct chain);
1016 unsigned i;
1017 dref ref;
1019 chain->type = CT_INVARIANT;
1021 chain->all_always_accessed = true;
1023 FOR_EACH_VEC_ELT (comp->refs, i, ref)
1025 chain->refs.safe_push (ref);
1026 chain->all_always_accessed &= ref->always_accessed;
1029 return chain;
1032 /* Make a new chain rooted at REF. */
1034 static chain_p
1035 make_rooted_chain (dref ref)
1037 chain_p chain = XCNEW (struct chain);
1039 chain->type = DR_IS_READ (ref->ref) ? CT_LOAD : CT_STORE_LOAD;
1041 chain->refs.safe_push (ref);
1042 chain->all_always_accessed = ref->always_accessed;
1044 ref->distance = 0;
1046 return chain;
1049 /* Returns true if CHAIN is not trivial. */
1051 static bool
1052 nontrivial_chain_p (chain_p chain)
1054 return chain != NULL && chain->refs.length () > 1;
1057 /* Returns the ssa name that contains the value of REF, or NULL_TREE if there
1058 is no such name. */
1060 static tree
1061 name_for_ref (dref ref)
1063 tree name;
1065 if (is_gimple_assign (ref->stmt))
1067 if (!ref->ref || DR_IS_READ (ref->ref))
1068 name = gimple_assign_lhs (ref->stmt);
1069 else
1070 name = gimple_assign_rhs1 (ref->stmt);
1072 else
1073 name = PHI_RESULT (ref->stmt);
1075 return (TREE_CODE (name) == SSA_NAME ? name : NULL_TREE);
1078 /* Returns true if REF is a valid initializer for ROOT with given DISTANCE (in
1079 iterations of the innermost enclosing loop). */
1081 static bool
1082 valid_initializer_p (struct data_reference *ref,
1083 unsigned distance, struct data_reference *root)
1085 aff_tree diff, base, step;
1086 widest_int off;
1088 /* Both REF and ROOT must be accessing the same object. */
1089 if (!operand_equal_p (DR_BASE_ADDRESS (ref), DR_BASE_ADDRESS (root), 0))
1090 return false;
1092 /* The initializer is defined outside of loop, hence its address must be
1093 invariant inside the loop. */
1094 gcc_assert (integer_zerop (DR_STEP (ref)));
1096 /* If the address of the reference is invariant, initializer must access
1097 exactly the same location. */
1098 if (integer_zerop (DR_STEP (root)))
1099 return (operand_equal_p (DR_OFFSET (ref), DR_OFFSET (root), 0)
1100 && operand_equal_p (DR_INIT (ref), DR_INIT (root), 0));
1102 /* Verify that this index of REF is equal to the root's index at
1103 -DISTANCE-th iteration. */
1104 aff_combination_dr_offset (root, &diff);
1105 aff_combination_dr_offset (ref, &base);
1106 aff_combination_scale (&base, -1);
1107 aff_combination_add (&diff, &base);
1109 tree_to_aff_combination_expand (DR_STEP (root), TREE_TYPE (DR_STEP (root)),
1110 &step, &name_expansions);
1111 if (!aff_combination_constant_multiple_p (&diff, &step, &off))
1112 return false;
1114 if (off != distance)
1115 return false;
1117 return true;
1120 /* Finds looparound phi node of LOOP that copies the value of REF, and if its
1121 initial value is correct (equal to initial value of REF shifted by one
1122 iteration), returns the phi node. Otherwise, NULL_TREE is returned. ROOT
1123 is the root of the current chain. */
1125 static gimple
1126 find_looparound_phi (struct loop *loop, dref ref, dref root)
1128 tree name, init, init_ref;
1129 gimple phi = NULL, init_stmt;
1130 edge latch = loop_latch_edge (loop);
1131 struct data_reference init_dr;
1132 gimple_stmt_iterator psi;
1134 if (is_gimple_assign (ref->stmt))
1136 if (DR_IS_READ (ref->ref))
1137 name = gimple_assign_lhs (ref->stmt);
1138 else
1139 name = gimple_assign_rhs1 (ref->stmt);
1141 else
1142 name = PHI_RESULT (ref->stmt);
1143 if (!name)
1144 return NULL;
1146 for (psi = gsi_start_phis (loop->header); !gsi_end_p (psi); gsi_next (&psi))
1148 phi = gsi_stmt (psi);
1149 if (PHI_ARG_DEF_FROM_EDGE (phi, latch) == name)
1150 break;
1153 if (gsi_end_p (psi))
1154 return NULL;
1156 init = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
1157 if (TREE_CODE (init) != SSA_NAME)
1158 return NULL;
1159 init_stmt = SSA_NAME_DEF_STMT (init);
1160 if (gimple_code (init_stmt) != GIMPLE_ASSIGN)
1161 return NULL;
1162 gcc_assert (gimple_assign_lhs (init_stmt) == init);
1164 init_ref = gimple_assign_rhs1 (init_stmt);
1165 if (!REFERENCE_CLASS_P (init_ref)
1166 && !DECL_P (init_ref))
1167 return NULL;
1169 /* Analyze the behavior of INIT_REF with respect to LOOP (innermost
1170 loop enclosing PHI). */
1171 memset (&init_dr, 0, sizeof (struct data_reference));
1172 DR_REF (&init_dr) = init_ref;
1173 DR_STMT (&init_dr) = phi;
1174 if (!dr_analyze_innermost (&init_dr, loop))
1175 return NULL;
1177 if (!valid_initializer_p (&init_dr, ref->distance + 1, root->ref))
1178 return NULL;
1180 return phi;
1183 /* Adds a reference for the looparound copy of REF in PHI to CHAIN. */
1185 static void
1186 insert_looparound_copy (chain_p chain, dref ref, gimple phi)
1188 dref nw = XCNEW (struct dref_d), aref;
1189 unsigned i;
1191 nw->stmt = phi;
1192 nw->distance = ref->distance + 1;
1193 nw->always_accessed = 1;
1195 FOR_EACH_VEC_ELT (chain->refs, i, aref)
1196 if (aref->distance >= nw->distance)
1197 break;
1198 chain->refs.safe_insert (i, nw);
1200 if (nw->distance > chain->length)
1202 chain->length = nw->distance;
1203 chain->has_max_use_after = false;
1207 /* For references in CHAIN that are copied around the LOOP (created previously
1208 by PRE, or by user), add the results of such copies to the chain. This
1209 enables us to remove the copies by unrolling, and may need less registers
1210 (also, it may allow us to combine chains together). */
1212 static void
1213 add_looparound_copies (struct loop *loop, chain_p chain)
1215 unsigned i;
1216 dref ref, root = get_chain_root (chain);
1217 gimple phi;
1219 FOR_EACH_VEC_ELT (chain->refs, i, ref)
1221 phi = find_looparound_phi (loop, ref, root);
1222 if (!phi)
1223 continue;
1225 bitmap_set_bit (looparound_phis, SSA_NAME_VERSION (PHI_RESULT (phi)));
1226 insert_looparound_copy (chain, ref, phi);
1230 /* Find roots of the values and determine distances in the component COMP.
1231 The references are redistributed into CHAINS. LOOP is the current
1232 loop. */
1234 static void
1235 determine_roots_comp (struct loop *loop,
1236 struct component *comp,
1237 vec<chain_p> *chains)
1239 unsigned i;
1240 dref a;
1241 chain_p chain = NULL;
1242 widest_int last_ofs = 0;
1244 /* Invariants are handled specially. */
1245 if (comp->comp_step == RS_INVARIANT)
1247 chain = make_invariant_chain (comp);
1248 chains->safe_push (chain);
1249 return;
1252 comp->refs.qsort (order_drefs);
1254 FOR_EACH_VEC_ELT (comp->refs, i, a)
1256 if (!chain || DR_IS_WRITE (a->ref)
1257 || wi::leu_p (MAX_DISTANCE, a->offset - last_ofs))
1259 if (nontrivial_chain_p (chain))
1261 add_looparound_copies (loop, chain);
1262 chains->safe_push (chain);
1264 else
1265 release_chain (chain);
1266 chain = make_rooted_chain (a);
1267 last_ofs = a->offset;
1268 continue;
1271 add_ref_to_chain (chain, a);
1274 if (nontrivial_chain_p (chain))
1276 add_looparound_copies (loop, chain);
1277 chains->safe_push (chain);
1279 else
1280 release_chain (chain);
1283 /* Find roots of the values and determine distances in components COMPS, and
1284 separates the references to CHAINS. LOOP is the current loop. */
1286 static void
1287 determine_roots (struct loop *loop,
1288 struct component *comps, vec<chain_p> *chains)
1290 struct component *comp;
1292 for (comp = comps; comp; comp = comp->next)
1293 determine_roots_comp (loop, comp, chains);
1296 /* Replace the reference in statement STMT with temporary variable
1297 NEW_TREE. If SET is true, NEW_TREE is instead initialized to the value of
1298 the reference in the statement. IN_LHS is true if the reference
1299 is in the lhs of STMT, false if it is in rhs. */
1301 static void
1302 replace_ref_with (gimple stmt, tree new_tree, bool set, bool in_lhs)
1304 tree val;
1305 gimple new_stmt;
1306 gimple_stmt_iterator bsi, psi;
1308 if (gimple_code (stmt) == GIMPLE_PHI)
1310 gcc_assert (!in_lhs && !set);
1312 val = PHI_RESULT (stmt);
1313 bsi = gsi_after_labels (gimple_bb (stmt));
1314 psi = gsi_for_stmt (stmt);
1315 remove_phi_node (&psi, false);
1317 /* Turn the phi node into GIMPLE_ASSIGN. */
1318 new_stmt = gimple_build_assign (val, new_tree);
1319 gsi_insert_before (&bsi, new_stmt, GSI_NEW_STMT);
1320 return;
1323 /* Since the reference is of gimple_reg type, it should only
1324 appear as lhs or rhs of modify statement. */
1325 gcc_assert (is_gimple_assign (stmt));
1327 bsi = gsi_for_stmt (stmt);
1329 /* If we do not need to initialize NEW_TREE, just replace the use of OLD. */
1330 if (!set)
1332 gcc_assert (!in_lhs);
1333 gimple_assign_set_rhs_from_tree (&bsi, new_tree);
1334 stmt = gsi_stmt (bsi);
1335 update_stmt (stmt);
1336 return;
1339 if (in_lhs)
1341 /* We have statement
1343 OLD = VAL
1345 If OLD is a memory reference, then VAL is gimple_val, and we transform
1346 this to
1348 OLD = VAL
1349 NEW = VAL
1351 Otherwise, we are replacing a combination chain,
1352 VAL is the expression that performs the combination, and OLD is an
1353 SSA name. In this case, we transform the assignment to
1355 OLD = VAL
1356 NEW = OLD
1360 val = gimple_assign_lhs (stmt);
1361 if (TREE_CODE (val) != SSA_NAME)
1363 val = gimple_assign_rhs1 (stmt);
1364 gcc_assert (gimple_assign_single_p (stmt));
1365 if (TREE_CLOBBER_P (val))
1366 val = get_or_create_ssa_default_def (cfun, SSA_NAME_VAR (new_tree));
1367 else
1368 gcc_assert (gimple_assign_copy_p (stmt));
1371 else
1373 /* VAL = OLD
1375 is transformed to
1377 VAL = OLD
1378 NEW = VAL */
1380 val = gimple_assign_lhs (stmt);
1383 new_stmt = gimple_build_assign (new_tree, unshare_expr (val));
1384 gsi_insert_after (&bsi, new_stmt, GSI_NEW_STMT);
1387 /* Returns a memory reference to DR in the ITER-th iteration of
1388 the loop it was analyzed in. Append init stmts to STMTS. */
1390 static tree
1391 ref_at_iteration (data_reference_p dr, int iter, gimple_seq *stmts)
1393 tree off = DR_OFFSET (dr);
1394 tree coff = DR_INIT (dr);
1395 if (iter == 0)
1397 else if (TREE_CODE (DR_STEP (dr)) == INTEGER_CST)
1398 coff = size_binop (PLUS_EXPR, coff,
1399 size_binop (MULT_EXPR, DR_STEP (dr), ssize_int (iter)));
1400 else
1401 off = size_binop (PLUS_EXPR, off,
1402 size_binop (MULT_EXPR, DR_STEP (dr), ssize_int (iter)));
1403 tree addr = fold_build_pointer_plus (DR_BASE_ADDRESS (dr), off);
1404 addr = force_gimple_operand_1 (addr, stmts, is_gimple_mem_ref_addr,
1405 NULL_TREE);
1406 tree alias_ptr = fold_convert (reference_alias_ptr_type (DR_REF (dr)), coff);
1407 /* While data-ref analysis punts on bit offsets it still handles
1408 bitfield accesses at byte boundaries. Cope with that. Note that
1409 we cannot simply re-apply the outer COMPONENT_REF because the
1410 byte-granular portion of it is already applied via DR_INIT and
1411 DR_OFFSET, so simply build a BIT_FIELD_REF knowing that the bits
1412 start at offset zero. */
1413 if (TREE_CODE (DR_REF (dr)) == COMPONENT_REF
1414 && DECL_BIT_FIELD (TREE_OPERAND (DR_REF (dr), 1)))
1416 tree field = TREE_OPERAND (DR_REF (dr), 1);
1417 return build3 (BIT_FIELD_REF, TREE_TYPE (DR_REF (dr)),
1418 build2 (MEM_REF, DECL_BIT_FIELD_TYPE (field),
1419 addr, alias_ptr),
1420 DECL_SIZE (field), bitsize_zero_node);
1422 else
1423 return fold_build2 (MEM_REF, TREE_TYPE (DR_REF (dr)), addr, alias_ptr);
1426 /* Get the initialization expression for the INDEX-th temporary variable
1427 of CHAIN. */
1429 static tree
1430 get_init_expr (chain_p chain, unsigned index)
1432 if (chain->type == CT_COMBINATION)
1434 tree e1 = get_init_expr (chain->ch1, index);
1435 tree e2 = get_init_expr (chain->ch2, index);
1437 return fold_build2 (chain->op, chain->rslt_type, e1, e2);
1439 else
1440 return chain->inits[index];
1443 /* Returns a new temporary variable used for the I-th variable carrying
1444 value of REF. The variable's uid is marked in TMP_VARS. */
1446 static tree
1447 predcom_tmp_var (tree ref, unsigned i, bitmap tmp_vars)
1449 tree type = TREE_TYPE (ref);
1450 /* We never access the components of the temporary variable in predictive
1451 commoning. */
1452 tree var = create_tmp_reg (type, get_lsm_tmp_name (ref, i));
1453 bitmap_set_bit (tmp_vars, DECL_UID (var));
1454 return var;
1457 /* Creates the variables for CHAIN, as well as phi nodes for them and
1458 initialization on entry to LOOP. Uids of the newly created
1459 temporary variables are marked in TMP_VARS. */
1461 static void
1462 initialize_root_vars (struct loop *loop, chain_p chain, bitmap tmp_vars)
1464 unsigned i;
1465 unsigned n = chain->length;
1466 dref root = get_chain_root (chain);
1467 bool reuse_first = !chain->has_max_use_after;
1468 tree ref, init, var, next;
1469 gimple phi;
1470 gimple_seq stmts;
1471 edge entry = loop_preheader_edge (loop), latch = loop_latch_edge (loop);
1473 /* If N == 0, then all the references are within the single iteration. And
1474 since this is an nonempty chain, reuse_first cannot be true. */
1475 gcc_assert (n > 0 || !reuse_first);
1477 chain->vars.create (n + 1);
1479 if (chain->type == CT_COMBINATION)
1480 ref = gimple_assign_lhs (root->stmt);
1481 else
1482 ref = DR_REF (root->ref);
1484 for (i = 0; i < n + (reuse_first ? 0 : 1); i++)
1486 var = predcom_tmp_var (ref, i, tmp_vars);
1487 chain->vars.quick_push (var);
1489 if (reuse_first)
1490 chain->vars.quick_push (chain->vars[0]);
1492 FOR_EACH_VEC_ELT (chain->vars, i, var)
1493 chain->vars[i] = make_ssa_name (var, NULL);
1495 for (i = 0; i < n; i++)
1497 var = chain->vars[i];
1498 next = chain->vars[i + 1];
1499 init = get_init_expr (chain, i);
1501 init = force_gimple_operand (init, &stmts, true, NULL_TREE);
1502 if (stmts)
1503 gsi_insert_seq_on_edge_immediate (entry, stmts);
1505 phi = create_phi_node (var, loop->header);
1506 add_phi_arg (phi, init, entry, UNKNOWN_LOCATION);
1507 add_phi_arg (phi, next, latch, UNKNOWN_LOCATION);
1511 /* Create the variables and initialization statement for root of chain
1512 CHAIN. Uids of the newly created temporary variables are marked
1513 in TMP_VARS. */
1515 static void
1516 initialize_root (struct loop *loop, chain_p chain, bitmap tmp_vars)
1518 dref root = get_chain_root (chain);
1519 bool in_lhs = (chain->type == CT_STORE_LOAD
1520 || chain->type == CT_COMBINATION);
1522 initialize_root_vars (loop, chain, tmp_vars);
1523 replace_ref_with (root->stmt,
1524 chain->vars[chain->length],
1525 true, in_lhs);
1528 /* Initializes a variable for load motion for ROOT and prepares phi nodes and
1529 initialization on entry to LOOP if necessary. The ssa name for the variable
1530 is stored in VARS. If WRITTEN is true, also a phi node to copy its value
1531 around the loop is created. Uid of the newly created temporary variable
1532 is marked in TMP_VARS. INITS is the list containing the (single)
1533 initializer. */
1535 static void
1536 initialize_root_vars_lm (struct loop *loop, dref root, bool written,
1537 vec<tree> *vars, vec<tree> inits,
1538 bitmap tmp_vars)
1540 unsigned i;
1541 tree ref = DR_REF (root->ref), init, var, next;
1542 gimple_seq stmts;
1543 gimple phi;
1544 edge entry = loop_preheader_edge (loop), latch = loop_latch_edge (loop);
1546 /* Find the initializer for the variable, and check that it cannot
1547 trap. */
1548 init = inits[0];
1550 vars->create (written ? 2 : 1);
1551 var = predcom_tmp_var (ref, 0, tmp_vars);
1552 vars->quick_push (var);
1553 if (written)
1554 vars->quick_push ((*vars)[0]);
1556 FOR_EACH_VEC_ELT (*vars, i, var)
1557 (*vars)[i] = make_ssa_name (var, NULL);
1559 var = (*vars)[0];
1561 init = force_gimple_operand (init, &stmts, written, NULL_TREE);
1562 if (stmts)
1563 gsi_insert_seq_on_edge_immediate (entry, stmts);
1565 if (written)
1567 next = (*vars)[1];
1568 phi = create_phi_node (var, loop->header);
1569 add_phi_arg (phi, init, entry, UNKNOWN_LOCATION);
1570 add_phi_arg (phi, next, latch, UNKNOWN_LOCATION);
1572 else
1574 gimple init_stmt = gimple_build_assign (var, init);
1575 gsi_insert_on_edge_immediate (entry, init_stmt);
1580 /* Execute load motion for references in chain CHAIN. Uids of the newly
1581 created temporary variables are marked in TMP_VARS. */
1583 static void
1584 execute_load_motion (struct loop *loop, chain_p chain, bitmap tmp_vars)
1586 auto_vec<tree> vars;
1587 dref a;
1588 unsigned n_writes = 0, ridx, i;
1589 tree var;
1591 gcc_assert (chain->type == CT_INVARIANT);
1592 gcc_assert (!chain->combined);
1593 FOR_EACH_VEC_ELT (chain->refs, i, a)
1594 if (DR_IS_WRITE (a->ref))
1595 n_writes++;
1597 /* If there are no reads in the loop, there is nothing to do. */
1598 if (n_writes == chain->refs.length ())
1599 return;
1601 initialize_root_vars_lm (loop, get_chain_root (chain), n_writes > 0,
1602 &vars, chain->inits, tmp_vars);
1604 ridx = 0;
1605 FOR_EACH_VEC_ELT (chain->refs, i, a)
1607 bool is_read = DR_IS_READ (a->ref);
1609 if (DR_IS_WRITE (a->ref))
1611 n_writes--;
1612 if (n_writes)
1614 var = vars[0];
1615 var = make_ssa_name (SSA_NAME_VAR (var), NULL);
1616 vars[0] = var;
1618 else
1619 ridx = 1;
1622 replace_ref_with (a->stmt, vars[ridx],
1623 !is_read, !is_read);
1627 /* Returns the single statement in that NAME is used, excepting
1628 the looparound phi nodes contained in one of the chains. If there is no
1629 such statement, or more statements, NULL is returned. */
1631 static gimple
1632 single_nonlooparound_use (tree name)
1634 use_operand_p use;
1635 imm_use_iterator it;
1636 gimple stmt, ret = NULL;
1638 FOR_EACH_IMM_USE_FAST (use, it, name)
1640 stmt = USE_STMT (use);
1642 if (gimple_code (stmt) == GIMPLE_PHI)
1644 /* Ignore uses in looparound phi nodes. Uses in other phi nodes
1645 could not be processed anyway, so just fail for them. */
1646 if (bitmap_bit_p (looparound_phis,
1647 SSA_NAME_VERSION (PHI_RESULT (stmt))))
1648 continue;
1650 return NULL;
1652 else if (is_gimple_debug (stmt))
1653 continue;
1654 else if (ret != NULL)
1655 return NULL;
1656 else
1657 ret = stmt;
1660 return ret;
1663 /* Remove statement STMT, as well as the chain of assignments in that it is
1664 used. */
1666 static void
1667 remove_stmt (gimple stmt)
1669 tree name;
1670 gimple next;
1671 gimple_stmt_iterator psi;
1673 if (gimple_code (stmt) == GIMPLE_PHI)
1675 name = PHI_RESULT (stmt);
1676 next = single_nonlooparound_use (name);
1677 reset_debug_uses (stmt);
1678 psi = gsi_for_stmt (stmt);
1679 remove_phi_node (&psi, true);
1681 if (!next
1682 || !gimple_assign_ssa_name_copy_p (next)
1683 || gimple_assign_rhs1 (next) != name)
1684 return;
1686 stmt = next;
1689 while (1)
1691 gimple_stmt_iterator bsi;
1693 bsi = gsi_for_stmt (stmt);
1695 name = gimple_assign_lhs (stmt);
1696 gcc_assert (TREE_CODE (name) == SSA_NAME);
1698 next = single_nonlooparound_use (name);
1699 reset_debug_uses (stmt);
1701 unlink_stmt_vdef (stmt);
1702 gsi_remove (&bsi, true);
1703 release_defs (stmt);
1705 if (!next
1706 || !gimple_assign_ssa_name_copy_p (next)
1707 || gimple_assign_rhs1 (next) != name)
1708 return;
1710 stmt = next;
1714 /* Perform the predictive commoning optimization for a chain CHAIN.
1715 Uids of the newly created temporary variables are marked in TMP_VARS.*/
1717 static void
1718 execute_pred_commoning_chain (struct loop *loop, chain_p chain,
1719 bitmap tmp_vars)
1721 unsigned i;
1722 dref a;
1723 tree var;
1725 if (chain->combined)
1727 /* For combined chains, just remove the statements that are used to
1728 compute the values of the expression (except for the root one). */
1729 for (i = 1; chain->refs.iterate (i, &a); i++)
1730 remove_stmt (a->stmt);
1732 else
1734 /* For non-combined chains, set up the variables that hold its value,
1735 and replace the uses of the original references by these
1736 variables. */
1737 initialize_root (loop, chain, tmp_vars);
1738 for (i = 1; chain->refs.iterate (i, &a); i++)
1740 var = chain->vars[chain->length - a->distance];
1741 replace_ref_with (a->stmt, var, false, false);
1746 /* Determines the unroll factor necessary to remove as many temporary variable
1747 copies as possible. CHAINS is the list of chains that will be
1748 optimized. */
1750 static unsigned
1751 determine_unroll_factor (vec<chain_p> chains)
1753 chain_p chain;
1754 unsigned factor = 1, af, nfactor, i;
1755 unsigned max = PARAM_VALUE (PARAM_MAX_UNROLL_TIMES);
1757 FOR_EACH_VEC_ELT (chains, i, chain)
1759 if (chain->type == CT_INVARIANT || chain->combined)
1760 continue;
1762 /* The best unroll factor for this chain is equal to the number of
1763 temporary variables that we create for it. */
1764 af = chain->length;
1765 if (chain->has_max_use_after)
1766 af++;
1768 nfactor = factor * af / gcd (factor, af);
1769 if (nfactor <= max)
1770 factor = nfactor;
1773 return factor;
1776 /* Perform the predictive commoning optimization for CHAINS.
1777 Uids of the newly created temporary variables are marked in TMP_VARS. */
1779 static void
1780 execute_pred_commoning (struct loop *loop, vec<chain_p> chains,
1781 bitmap tmp_vars)
1783 chain_p chain;
1784 unsigned i;
1786 FOR_EACH_VEC_ELT (chains, i, chain)
1788 if (chain->type == CT_INVARIANT)
1789 execute_load_motion (loop, chain, tmp_vars);
1790 else
1791 execute_pred_commoning_chain (loop, chain, tmp_vars);
1794 update_ssa (TODO_update_ssa_only_virtuals);
1797 /* For each reference in CHAINS, if its defining statement is
1798 phi node, record the ssa name that is defined by it. */
1800 static void
1801 replace_phis_by_defined_names (vec<chain_p> chains)
1803 chain_p chain;
1804 dref a;
1805 unsigned i, j;
1807 FOR_EACH_VEC_ELT (chains, i, chain)
1808 FOR_EACH_VEC_ELT (chain->refs, j, a)
1810 if (gimple_code (a->stmt) == GIMPLE_PHI)
1812 a->name_defined_by_phi = PHI_RESULT (a->stmt);
1813 a->stmt = NULL;
1818 /* For each reference in CHAINS, if name_defined_by_phi is not
1819 NULL, use it to set the stmt field. */
1821 static void
1822 replace_names_by_phis (vec<chain_p> chains)
1824 chain_p chain;
1825 dref a;
1826 unsigned i, j;
1828 FOR_EACH_VEC_ELT (chains, i, chain)
1829 FOR_EACH_VEC_ELT (chain->refs, j, a)
1830 if (a->stmt == NULL)
1832 a->stmt = SSA_NAME_DEF_STMT (a->name_defined_by_phi);
1833 gcc_assert (gimple_code (a->stmt) == GIMPLE_PHI);
1834 a->name_defined_by_phi = NULL_TREE;
1838 /* Wrapper over execute_pred_commoning, to pass it as a callback
1839 to tree_transform_and_unroll_loop. */
1841 struct epcc_data
1843 vec<chain_p> chains;
1844 bitmap tmp_vars;
1847 static void
1848 execute_pred_commoning_cbck (struct loop *loop, void *data)
1850 struct epcc_data *const dta = (struct epcc_data *) data;
1852 /* Restore phi nodes that were replaced by ssa names before
1853 tree_transform_and_unroll_loop (see detailed description in
1854 tree_predictive_commoning_loop). */
1855 replace_names_by_phis (dta->chains);
1856 execute_pred_commoning (loop, dta->chains, dta->tmp_vars);
1859 /* Base NAME and all the names in the chain of phi nodes that use it
1860 on variable VAR. The phi nodes are recognized by being in the copies of
1861 the header of the LOOP. */
1863 static void
1864 base_names_in_chain_on (struct loop *loop, tree name, tree var)
1866 gimple stmt, phi;
1867 imm_use_iterator iter;
1869 replace_ssa_name_symbol (name, var);
1871 while (1)
1873 phi = NULL;
1874 FOR_EACH_IMM_USE_STMT (stmt, iter, name)
1876 if (gimple_code (stmt) == GIMPLE_PHI
1877 && flow_bb_inside_loop_p (loop, gimple_bb (stmt)))
1879 phi = stmt;
1880 BREAK_FROM_IMM_USE_STMT (iter);
1883 if (!phi)
1884 return;
1886 name = PHI_RESULT (phi);
1887 replace_ssa_name_symbol (name, var);
1891 /* Given an unrolled LOOP after predictive commoning, remove the
1892 register copies arising from phi nodes by changing the base
1893 variables of SSA names. TMP_VARS is the set of the temporary variables
1894 for those we want to perform this. */
1896 static void
1897 eliminate_temp_copies (struct loop *loop, bitmap tmp_vars)
1899 edge e;
1900 gimple phi, stmt;
1901 tree name, use, var;
1902 gimple_stmt_iterator psi;
1904 e = loop_latch_edge (loop);
1905 for (psi = gsi_start_phis (loop->header); !gsi_end_p (psi); gsi_next (&psi))
1907 phi = gsi_stmt (psi);
1908 name = PHI_RESULT (phi);
1909 var = SSA_NAME_VAR (name);
1910 if (!var || !bitmap_bit_p (tmp_vars, DECL_UID (var)))
1911 continue;
1912 use = PHI_ARG_DEF_FROM_EDGE (phi, e);
1913 gcc_assert (TREE_CODE (use) == SSA_NAME);
1915 /* Base all the ssa names in the ud and du chain of NAME on VAR. */
1916 stmt = SSA_NAME_DEF_STMT (use);
1917 while (gimple_code (stmt) == GIMPLE_PHI
1918 /* In case we could not unroll the loop enough to eliminate
1919 all copies, we may reach the loop header before the defining
1920 statement (in that case, some register copies will be present
1921 in loop latch in the final code, corresponding to the newly
1922 created looparound phi nodes). */
1923 && gimple_bb (stmt) != loop->header)
1925 gcc_assert (single_pred_p (gimple_bb (stmt)));
1926 use = PHI_ARG_DEF (stmt, 0);
1927 stmt = SSA_NAME_DEF_STMT (use);
1930 base_names_in_chain_on (loop, use, var);
1934 /* Returns true if CHAIN is suitable to be combined. */
1936 static bool
1937 chain_can_be_combined_p (chain_p chain)
1939 return (!chain->combined
1940 && (chain->type == CT_LOAD || chain->type == CT_COMBINATION));
1943 /* Returns the modify statement that uses NAME. Skips over assignment
1944 statements, NAME is replaced with the actual name used in the returned
1945 statement. */
1947 static gimple
1948 find_use_stmt (tree *name)
1950 gimple stmt;
1951 tree rhs, lhs;
1953 /* Skip over assignments. */
1954 while (1)
1956 stmt = single_nonlooparound_use (*name);
1957 if (!stmt)
1958 return NULL;
1960 if (gimple_code (stmt) != GIMPLE_ASSIGN)
1961 return NULL;
1963 lhs = gimple_assign_lhs (stmt);
1964 if (TREE_CODE (lhs) != SSA_NAME)
1965 return NULL;
1967 if (gimple_assign_copy_p (stmt))
1969 rhs = gimple_assign_rhs1 (stmt);
1970 if (rhs != *name)
1971 return NULL;
1973 *name = lhs;
1975 else if (get_gimple_rhs_class (gimple_assign_rhs_code (stmt))
1976 == GIMPLE_BINARY_RHS)
1977 return stmt;
1978 else
1979 return NULL;
1983 /* Returns true if we may perform reassociation for operation CODE in TYPE. */
1985 static bool
1986 may_reassociate_p (tree type, enum tree_code code)
1988 if (FLOAT_TYPE_P (type)
1989 && !flag_unsafe_math_optimizations)
1990 return false;
1992 return (commutative_tree_code (code)
1993 && associative_tree_code (code));
1996 /* If the operation used in STMT is associative and commutative, go through the
1997 tree of the same operations and returns its root. Distance to the root
1998 is stored in DISTANCE. */
2000 static gimple
2001 find_associative_operation_root (gimple stmt, unsigned *distance)
2003 tree lhs;
2004 gimple next;
2005 enum tree_code code = gimple_assign_rhs_code (stmt);
2006 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
2007 unsigned dist = 0;
2009 if (!may_reassociate_p (type, code))
2010 return NULL;
2012 while (1)
2014 lhs = gimple_assign_lhs (stmt);
2015 gcc_assert (TREE_CODE (lhs) == SSA_NAME);
2017 next = find_use_stmt (&lhs);
2018 if (!next
2019 || gimple_assign_rhs_code (next) != code)
2020 break;
2022 stmt = next;
2023 dist++;
2026 if (distance)
2027 *distance = dist;
2028 return stmt;
2031 /* Returns the common statement in that NAME1 and NAME2 have a use. If there
2032 is no such statement, returns NULL_TREE. In case the operation used on
2033 NAME1 and NAME2 is associative and commutative, returns the root of the
2034 tree formed by this operation instead of the statement that uses NAME1 or
2035 NAME2. */
2037 static gimple
2038 find_common_use_stmt (tree *name1, tree *name2)
2040 gimple stmt1, stmt2;
2042 stmt1 = find_use_stmt (name1);
2043 if (!stmt1)
2044 return NULL;
2046 stmt2 = find_use_stmt (name2);
2047 if (!stmt2)
2048 return NULL;
2050 if (stmt1 == stmt2)
2051 return stmt1;
2053 stmt1 = find_associative_operation_root (stmt1, NULL);
2054 if (!stmt1)
2055 return NULL;
2056 stmt2 = find_associative_operation_root (stmt2, NULL);
2057 if (!stmt2)
2058 return NULL;
2060 return (stmt1 == stmt2 ? stmt1 : NULL);
2063 /* Checks whether R1 and R2 are combined together using CODE, with the result
2064 in RSLT_TYPE, in order R1 CODE R2 if SWAP is false and in order R2 CODE R1
2065 if it is true. If CODE is ERROR_MARK, set these values instead. */
2067 static bool
2068 combinable_refs_p (dref r1, dref r2,
2069 enum tree_code *code, bool *swap, tree *rslt_type)
2071 enum tree_code acode;
2072 bool aswap;
2073 tree atype;
2074 tree name1, name2;
2075 gimple stmt;
2077 name1 = name_for_ref (r1);
2078 name2 = name_for_ref (r2);
2079 gcc_assert (name1 != NULL_TREE && name2 != NULL_TREE);
2081 stmt = find_common_use_stmt (&name1, &name2);
2083 if (!stmt
2084 /* A simple post-dominance check - make sure the combination
2085 is executed under the same condition as the references. */
2086 || (gimple_bb (stmt) != gimple_bb (r1->stmt)
2087 && gimple_bb (stmt) != gimple_bb (r2->stmt)))
2088 return false;
2090 acode = gimple_assign_rhs_code (stmt);
2091 aswap = (!commutative_tree_code (acode)
2092 && gimple_assign_rhs1 (stmt) != name1);
2093 atype = TREE_TYPE (gimple_assign_lhs (stmt));
2095 if (*code == ERROR_MARK)
2097 *code = acode;
2098 *swap = aswap;
2099 *rslt_type = atype;
2100 return true;
2103 return (*code == acode
2104 && *swap == aswap
2105 && *rslt_type == atype);
2108 /* Remove OP from the operation on rhs of STMT, and replace STMT with
2109 an assignment of the remaining operand. */
2111 static void
2112 remove_name_from_operation (gimple stmt, tree op)
2114 tree other_op;
2115 gimple_stmt_iterator si;
2117 gcc_assert (is_gimple_assign (stmt));
2119 if (gimple_assign_rhs1 (stmt) == op)
2120 other_op = gimple_assign_rhs2 (stmt);
2121 else
2122 other_op = gimple_assign_rhs1 (stmt);
2124 si = gsi_for_stmt (stmt);
2125 gimple_assign_set_rhs_from_tree (&si, other_op);
2127 /* We should not have reallocated STMT. */
2128 gcc_assert (gsi_stmt (si) == stmt);
2130 update_stmt (stmt);
2133 /* Reassociates the expression in that NAME1 and NAME2 are used so that they
2134 are combined in a single statement, and returns this statement. */
2136 static gimple
2137 reassociate_to_the_same_stmt (tree name1, tree name2)
2139 gimple stmt1, stmt2, root1, root2, s1, s2;
2140 gimple new_stmt, tmp_stmt;
2141 tree new_name, tmp_name, var, r1, r2;
2142 unsigned dist1, dist2;
2143 enum tree_code code;
2144 tree type = TREE_TYPE (name1);
2145 gimple_stmt_iterator bsi;
2147 stmt1 = find_use_stmt (&name1);
2148 stmt2 = find_use_stmt (&name2);
2149 root1 = find_associative_operation_root (stmt1, &dist1);
2150 root2 = find_associative_operation_root (stmt2, &dist2);
2151 code = gimple_assign_rhs_code (stmt1);
2153 gcc_assert (root1 && root2 && root1 == root2
2154 && code == gimple_assign_rhs_code (stmt2));
2156 /* Find the root of the nearest expression in that both NAME1 and NAME2
2157 are used. */
2158 r1 = name1;
2159 s1 = stmt1;
2160 r2 = name2;
2161 s2 = stmt2;
2163 while (dist1 > dist2)
2165 s1 = find_use_stmt (&r1);
2166 r1 = gimple_assign_lhs (s1);
2167 dist1--;
2169 while (dist2 > dist1)
2171 s2 = find_use_stmt (&r2);
2172 r2 = gimple_assign_lhs (s2);
2173 dist2--;
2176 while (s1 != s2)
2178 s1 = find_use_stmt (&r1);
2179 r1 = gimple_assign_lhs (s1);
2180 s2 = find_use_stmt (&r2);
2181 r2 = gimple_assign_lhs (s2);
2184 /* Remove NAME1 and NAME2 from the statements in that they are used
2185 currently. */
2186 remove_name_from_operation (stmt1, name1);
2187 remove_name_from_operation (stmt2, name2);
2189 /* Insert the new statement combining NAME1 and NAME2 before S1, and
2190 combine it with the rhs of S1. */
2191 var = create_tmp_reg (type, "predreastmp");
2192 new_name = make_ssa_name (var, NULL);
2193 new_stmt = gimple_build_assign_with_ops (code, new_name, name1, name2);
2195 var = create_tmp_reg (type, "predreastmp");
2196 tmp_name = make_ssa_name (var, NULL);
2198 /* Rhs of S1 may now be either a binary expression with operation
2199 CODE, or gimple_val (in case that stmt1 == s1 or stmt2 == s1,
2200 so that name1 or name2 was removed from it). */
2201 tmp_stmt = gimple_build_assign_with_ops (gimple_assign_rhs_code (s1),
2202 tmp_name,
2203 gimple_assign_rhs1 (s1),
2204 gimple_assign_rhs2 (s1));
2206 bsi = gsi_for_stmt (s1);
2207 gimple_assign_set_rhs_with_ops (&bsi, code, new_name, tmp_name);
2208 s1 = gsi_stmt (bsi);
2209 update_stmt (s1);
2211 gsi_insert_before (&bsi, new_stmt, GSI_SAME_STMT);
2212 gsi_insert_before (&bsi, tmp_stmt, GSI_SAME_STMT);
2214 return new_stmt;
2217 /* Returns the statement that combines references R1 and R2. In case R1
2218 and R2 are not used in the same statement, but they are used with an
2219 associative and commutative operation in the same expression, reassociate
2220 the expression so that they are used in the same statement. */
2222 static gimple
2223 stmt_combining_refs (dref r1, dref r2)
2225 gimple stmt1, stmt2;
2226 tree name1 = name_for_ref (r1);
2227 tree name2 = name_for_ref (r2);
2229 stmt1 = find_use_stmt (&name1);
2230 stmt2 = find_use_stmt (&name2);
2231 if (stmt1 == stmt2)
2232 return stmt1;
2234 return reassociate_to_the_same_stmt (name1, name2);
2237 /* Tries to combine chains CH1 and CH2 together. If this succeeds, the
2238 description of the new chain is returned, otherwise we return NULL. */
2240 static chain_p
2241 combine_chains (chain_p ch1, chain_p ch2)
2243 dref r1, r2, nw;
2244 enum tree_code op = ERROR_MARK;
2245 bool swap = false;
2246 chain_p new_chain;
2247 unsigned i;
2248 gimple root_stmt;
2249 tree rslt_type = NULL_TREE;
2251 if (ch1 == ch2)
2252 return NULL;
2253 if (ch1->length != ch2->length)
2254 return NULL;
2256 if (ch1->refs.length () != ch2->refs.length ())
2257 return NULL;
2259 for (i = 0; (ch1->refs.iterate (i, &r1)
2260 && ch2->refs.iterate (i, &r2)); i++)
2262 if (r1->distance != r2->distance)
2263 return NULL;
2265 if (!combinable_refs_p (r1, r2, &op, &swap, &rslt_type))
2266 return NULL;
2269 if (swap)
2271 chain_p tmp = ch1;
2272 ch1 = ch2;
2273 ch2 = tmp;
2276 new_chain = XCNEW (struct chain);
2277 new_chain->type = CT_COMBINATION;
2278 new_chain->op = op;
2279 new_chain->ch1 = ch1;
2280 new_chain->ch2 = ch2;
2281 new_chain->rslt_type = rslt_type;
2282 new_chain->length = ch1->length;
2284 for (i = 0; (ch1->refs.iterate (i, &r1)
2285 && ch2->refs.iterate (i, &r2)); i++)
2287 nw = XCNEW (struct dref_d);
2288 nw->stmt = stmt_combining_refs (r1, r2);
2289 nw->distance = r1->distance;
2291 new_chain->refs.safe_push (nw);
2294 new_chain->has_max_use_after = false;
2295 root_stmt = get_chain_root (new_chain)->stmt;
2296 for (i = 1; new_chain->refs.iterate (i, &nw); i++)
2298 if (nw->distance == new_chain->length
2299 && !stmt_dominates_stmt_p (nw->stmt, root_stmt))
2301 new_chain->has_max_use_after = true;
2302 break;
2306 ch1->combined = true;
2307 ch2->combined = true;
2308 return new_chain;
2311 /* Try to combine the CHAINS. */
2313 static void
2314 try_combine_chains (vec<chain_p> *chains)
2316 unsigned i, j;
2317 chain_p ch1, ch2, cch;
2318 auto_vec<chain_p> worklist;
2320 FOR_EACH_VEC_ELT (*chains, i, ch1)
2321 if (chain_can_be_combined_p (ch1))
2322 worklist.safe_push (ch1);
2324 while (!worklist.is_empty ())
2326 ch1 = worklist.pop ();
2327 if (!chain_can_be_combined_p (ch1))
2328 continue;
2330 FOR_EACH_VEC_ELT (*chains, j, ch2)
2332 if (!chain_can_be_combined_p (ch2))
2333 continue;
2335 cch = combine_chains (ch1, ch2);
2336 if (cch)
2338 worklist.safe_push (cch);
2339 chains->safe_push (cch);
2340 break;
2346 /* Prepare initializers for CHAIN in LOOP. Returns false if this is
2347 impossible because one of these initializers may trap, true otherwise. */
2349 static bool
2350 prepare_initializers_chain (struct loop *loop, chain_p chain)
2352 unsigned i, n = (chain->type == CT_INVARIANT) ? 1 : chain->length;
2353 struct data_reference *dr = get_chain_root (chain)->ref;
2354 tree init;
2355 gimple_seq stmts;
2356 dref laref;
2357 edge entry = loop_preheader_edge (loop);
2359 /* Find the initializers for the variables, and check that they cannot
2360 trap. */
2361 chain->inits.create (n);
2362 for (i = 0; i < n; i++)
2363 chain->inits.quick_push (NULL_TREE);
2365 /* If we have replaced some looparound phi nodes, use their initializers
2366 instead of creating our own. */
2367 FOR_EACH_VEC_ELT (chain->refs, i, laref)
2369 if (gimple_code (laref->stmt) != GIMPLE_PHI)
2370 continue;
2372 gcc_assert (laref->distance > 0);
2373 chain->inits[n - laref->distance]
2374 = PHI_ARG_DEF_FROM_EDGE (laref->stmt, entry);
2377 for (i = 0; i < n; i++)
2379 if (chain->inits[i] != NULL_TREE)
2380 continue;
2382 init = ref_at_iteration (dr, (int) i - n, &stmts);
2383 if (!chain->all_always_accessed && tree_could_trap_p (init))
2384 return false;
2386 if (stmts)
2387 gsi_insert_seq_on_edge_immediate (entry, stmts);
2389 chain->inits[i] = init;
2392 return true;
2395 /* Prepare initializers for CHAINS in LOOP, and free chains that cannot
2396 be used because the initializers might trap. */
2398 static void
2399 prepare_initializers (struct loop *loop, vec<chain_p> chains)
2401 chain_p chain;
2402 unsigned i;
2404 for (i = 0; i < chains.length (); )
2406 chain = chains[i];
2407 if (prepare_initializers_chain (loop, chain))
2408 i++;
2409 else
2411 release_chain (chain);
2412 chains.unordered_remove (i);
2417 /* Performs predictive commoning for LOOP. Returns true if LOOP was
2418 unrolled. */
2420 static bool
2421 tree_predictive_commoning_loop (struct loop *loop)
2423 vec<data_reference_p> datarefs;
2424 vec<ddr_p> dependences;
2425 struct component *components;
2426 vec<chain_p> chains = vNULL;
2427 unsigned unroll_factor;
2428 struct tree_niter_desc desc;
2429 bool unroll = false;
2430 edge exit;
2431 bitmap tmp_vars;
2433 if (dump_file && (dump_flags & TDF_DETAILS))
2434 fprintf (dump_file, "Processing loop %d\n", loop->num);
2436 /* Find the data references and split them into components according to their
2437 dependence relations. */
2438 auto_vec<loop_p, 3> loop_nest;
2439 dependences.create (10);
2440 datarefs.create (10);
2441 if (! compute_data_dependences_for_loop (loop, true, &loop_nest, &datarefs,
2442 &dependences))
2444 if (dump_file && (dump_flags & TDF_DETAILS))
2445 fprintf (dump_file, "Cannot analyze data dependencies\n");
2446 free_data_refs (datarefs);
2447 free_dependence_relations (dependences);
2448 return false;
2451 if (dump_file && (dump_flags & TDF_DETAILS))
2452 dump_data_dependence_relations (dump_file, dependences);
2454 components = split_data_refs_to_components (loop, datarefs, dependences);
2455 loop_nest.release ();
2456 free_dependence_relations (dependences);
2457 if (!components)
2459 free_data_refs (datarefs);
2460 free_affine_expand_cache (&name_expansions);
2461 return false;
2464 if (dump_file && (dump_flags & TDF_DETAILS))
2466 fprintf (dump_file, "Initial state:\n\n");
2467 dump_components (dump_file, components);
2470 /* Find the suitable components and split them into chains. */
2471 components = filter_suitable_components (loop, components);
2473 tmp_vars = BITMAP_ALLOC (NULL);
2474 looparound_phis = BITMAP_ALLOC (NULL);
2475 determine_roots (loop, components, &chains);
2476 release_components (components);
2478 if (!chains.exists ())
2480 if (dump_file && (dump_flags & TDF_DETAILS))
2481 fprintf (dump_file,
2482 "Predictive commoning failed: no suitable chains\n");
2483 goto end;
2485 prepare_initializers (loop, chains);
2487 /* Try to combine the chains that are always worked with together. */
2488 try_combine_chains (&chains);
2490 if (dump_file && (dump_flags & TDF_DETAILS))
2492 fprintf (dump_file, "Before commoning:\n\n");
2493 dump_chains (dump_file, chains);
2496 /* Determine the unroll factor, and if the loop should be unrolled, ensure
2497 that its number of iterations is divisible by the factor. */
2498 unroll_factor = determine_unroll_factor (chains);
2499 scev_reset ();
2500 unroll = (unroll_factor > 1
2501 && can_unroll_loop_p (loop, unroll_factor, &desc));
2502 exit = single_dom_exit (loop);
2504 /* Execute the predictive commoning transformations, and possibly unroll the
2505 loop. */
2506 if (unroll)
2508 struct epcc_data dta;
2510 if (dump_file && (dump_flags & TDF_DETAILS))
2511 fprintf (dump_file, "Unrolling %u times.\n", unroll_factor);
2513 dta.chains = chains;
2514 dta.tmp_vars = tmp_vars;
2516 update_ssa (TODO_update_ssa_only_virtuals);
2518 /* Cfg manipulations performed in tree_transform_and_unroll_loop before
2519 execute_pred_commoning_cbck is called may cause phi nodes to be
2520 reallocated, which is a problem since CHAINS may point to these
2521 statements. To fix this, we store the ssa names defined by the
2522 phi nodes here instead of the phi nodes themselves, and restore
2523 the phi nodes in execute_pred_commoning_cbck. A bit hacky. */
2524 replace_phis_by_defined_names (chains);
2526 tree_transform_and_unroll_loop (loop, unroll_factor, exit, &desc,
2527 execute_pred_commoning_cbck, &dta);
2528 eliminate_temp_copies (loop, tmp_vars);
2530 else
2532 if (dump_file && (dump_flags & TDF_DETAILS))
2533 fprintf (dump_file,
2534 "Executing predictive commoning without unrolling.\n");
2535 execute_pred_commoning (loop, chains, tmp_vars);
2538 end: ;
2539 release_chains (chains);
2540 free_data_refs (datarefs);
2541 BITMAP_FREE (tmp_vars);
2542 BITMAP_FREE (looparound_phis);
2544 free_affine_expand_cache (&name_expansions);
2546 return unroll;
2549 /* Runs predictive commoning. */
2551 unsigned
2552 tree_predictive_commoning (void)
2554 bool unrolled = false;
2555 struct loop *loop;
2556 unsigned ret = 0;
2558 initialize_original_copy_tables ();
2559 FOR_EACH_LOOP (loop, LI_ONLY_INNERMOST)
2560 if (optimize_loop_for_speed_p (loop))
2562 unrolled |= tree_predictive_commoning_loop (loop);
2565 if (unrolled)
2567 scev_reset ();
2568 ret = TODO_cleanup_cfg;
2570 free_original_copy_tables ();
2572 return ret;
2575 /* Predictive commoning Pass. */
2577 static unsigned
2578 run_tree_predictive_commoning (struct function *fun)
2580 if (number_of_loops (fun) <= 1)
2581 return 0;
2583 return tree_predictive_commoning ();
2586 namespace {
2588 const pass_data pass_data_predcom =
2590 GIMPLE_PASS, /* type */
2591 "pcom", /* name */
2592 OPTGROUP_LOOP, /* optinfo_flags */
2593 TV_PREDCOM, /* tv_id */
2594 PROP_cfg, /* properties_required */
2595 0, /* properties_provided */
2596 0, /* properties_destroyed */
2597 0, /* todo_flags_start */
2598 TODO_update_ssa_only_virtuals, /* todo_flags_finish */
2601 class pass_predcom : public gimple_opt_pass
2603 public:
2604 pass_predcom (gcc::context *ctxt)
2605 : gimple_opt_pass (pass_data_predcom, ctxt)
2608 /* opt_pass methods: */
2609 virtual bool gate (function *) { return flag_predictive_commoning != 0; }
2610 virtual unsigned int execute (function *fun)
2612 return run_tree_predictive_commoning (fun);
2615 }; // class pass_predcom
2617 } // anon namespace
2619 gimple_opt_pass *
2620 make_pass_predcom (gcc::context *ctxt)
2622 return new pass_predcom (ctxt);