]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/tree-predcom.c
2013-11-08 Richard Biener <rguenther@suse.de>
[thirdparty/gcc.git] / gcc / tree-predcom.c
1 /* Predictive commoning.
2 Copyright (C) 2005-2013 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 3, or (at your option) any
9 later version.
10
11 GCC is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
19
20 /* 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.
30
31 Let us demonstrate what is done on an example:
32
33 for (i = 0; i < 100; i++)
34 {
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];
39 }
40
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:
46
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}
51
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.
66
67 In our example, we get the following chains (the chain for c is invalid).
68
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}
72
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),
83
84 a[i] --> (*) 2, a[i+1] --> (*) 1, a[i+2] (*)
85 b[10] --> (*) 1, b[10] (*)
86
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
92
93 e[i] + f[i+1] + e[i+1] + f[i]
94
95 can be reassociated as
96
97 (e[i] + f[i]) + (e[i+1] + f[i+1])
98
99 and we can combine the chains for e and f into one chain.
100
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.
111
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.
115
116 In our example, we get (only the parts concerning a and b are shown):
117 for (i = 0; i < 100; i++)
118 {
119 f = phi (a[0], s);
120 s = phi (a[1], f);
121 x = phi (b[10], x);
122
123 f = f + s;
124 a[i+2] = f;
125 x = x + i;
126 b[10] = x;
127 }
128
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.
135
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.
139
140 In our case, F = 2 and the (main loop of the) result is
141
142 for (i = 0; i < ...; i += 2)
143 {
144 f = phi (a[0], f);
145 s = phi (a[1], s);
146 x = phi (b[10], x);
147
148 f = f + s;
149 a[i+2] = f;
150 x = x + i;
151 b[10] = x;
152
153 s = s + f;
154 a[i+3] = s;
155 x = x + i;
156 b[10] = x;
157 }
158
159 TODO -- stores killing other stores can be taken into account, e.g.,
160 for (i = 0; i < n; i++)
161 {
162 a[i] = 1;
163 a[i+2] = 2;
164 }
165
166 can be replaced with
167
168 t0 = a[0];
169 t1 = a[1];
170 for (i = 0; i < n; i++)
171 {
172 a[i] = 1;
173 t2 = 2;
174 t0 = t1;
175 t1 = t2;
176 }
177 a[n] = t0;
178 a[n+1] = t1;
179
180 The interesting part is that this would generalize store motion; still, since
181 sm is performed elsewhere, it does not seem that important.
182
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. */
186
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 "gimple-ssa.h"
196 #include "tree-phinodes.h"
197 #include "ssa-iterators.h"
198 #include "tree-ssanames.h"
199 #include "tree-ssa-loop-ivopts.h"
200 #include "tree-ssa-loop-manip.h"
201 #include "tree-ssa-loop-niter.h"
202 #include "tree-ssa-loop.h"
203 #include "tree-into-ssa.h"
204 #include "tree-dfa.h"
205 #include "tree-ssa.h"
206 #include "ggc.h"
207 #include "tree-data-ref.h"
208 #include "tree-scalar-evolution.h"
209 #include "tree-chrec.h"
210 #include "params.h"
211 #include "gimple-pretty-print.h"
212 #include "tree-pass.h"
213 #include "tree-affine.h"
214 #include "tree-inline.h"
215
216 /* The maximum number of iterations between the considered memory
217 references. */
218
219 #define MAX_DISTANCE (target_avail_regs < 16 ? 4 : 8)
220
221 /* Data references (or phi nodes that carry data reference values across
222 loop iterations). */
223
224 typedef struct dref_d
225 {
226 /* The reference itself. */
227 struct data_reference *ref;
228
229 /* The statement in that the reference appears. */
230 gimple stmt;
231
232 /* In case that STMT is a phi node, this field is set to the SSA name
233 defined by it in replace_phis_by_defined_names (in order to avoid
234 pointing to phi node that got reallocated in the meantime). */
235 tree name_defined_by_phi;
236
237 /* Distance of the reference from the root of the chain (in number of
238 iterations of the loop). */
239 unsigned distance;
240
241 /* Number of iterations offset from the first reference in the component. */
242 double_int offset;
243
244 /* Number of the reference in a component, in dominance ordering. */
245 unsigned pos;
246
247 /* True if the memory reference is always accessed when the loop is
248 entered. */
249 unsigned always_accessed : 1;
250 } *dref;
251
252
253 /* Type of the chain of the references. */
254
255 enum chain_type
256 {
257 /* The addresses of the references in the chain are constant. */
258 CT_INVARIANT,
259
260 /* There are only loads in the chain. */
261 CT_LOAD,
262
263 /* Root of the chain is store, the rest are loads. */
264 CT_STORE_LOAD,
265
266 /* A combination of two chains. */
267 CT_COMBINATION
268 };
269
270 /* Chains of data references. */
271
272 typedef struct chain
273 {
274 /* Type of the chain. */
275 enum chain_type type;
276
277 /* For combination chains, the operator and the two chains that are
278 combined, and the type of the result. */
279 enum tree_code op;
280 tree rslt_type;
281 struct chain *ch1, *ch2;
282
283 /* The references in the chain. */
284 vec<dref> refs;
285
286 /* The maximum distance of the reference in the chain from the root. */
287 unsigned length;
288
289 /* The variables used to copy the value throughout iterations. */
290 vec<tree> vars;
291
292 /* Initializers for the variables. */
293 vec<tree> inits;
294
295 /* True if there is a use of a variable with the maximal distance
296 that comes after the root in the loop. */
297 unsigned has_max_use_after : 1;
298
299 /* True if all the memory references in the chain are always accessed. */
300 unsigned all_always_accessed : 1;
301
302 /* True if this chain was combined together with some other chain. */
303 unsigned combined : 1;
304 } *chain_p;
305
306
307 /* Describes the knowledge about the step of the memory references in
308 the component. */
309
310 enum ref_step_type
311 {
312 /* The step is zero. */
313 RS_INVARIANT,
314
315 /* The step is nonzero. */
316 RS_NONZERO,
317
318 /* The step may or may not be nonzero. */
319 RS_ANY
320 };
321
322 /* Components of the data dependence graph. */
323
324 struct component
325 {
326 /* The references in the component. */
327 vec<dref> refs;
328
329 /* What we know about the step of the references in the component. */
330 enum ref_step_type comp_step;
331
332 /* Next component in the list. */
333 struct component *next;
334 };
335
336 /* Bitmap of ssa names defined by looparound phi nodes covered by chains. */
337
338 static bitmap looparound_phis;
339
340 /* Cache used by tree_to_aff_combination_expand. */
341
342 static struct pointer_map_t *name_expansions;
343
344 /* Dumps data reference REF to FILE. */
345
346 extern void dump_dref (FILE *, dref);
347 void
348 dump_dref (FILE *file, dref ref)
349 {
350 if (ref->ref)
351 {
352 fprintf (file, " ");
353 print_generic_expr (file, DR_REF (ref->ref), TDF_SLIM);
354 fprintf (file, " (id %u%s)\n", ref->pos,
355 DR_IS_READ (ref->ref) ? "" : ", write");
356
357 fprintf (file, " offset ");
358 dump_double_int (file, ref->offset, false);
359 fprintf (file, "\n");
360
361 fprintf (file, " distance %u\n", ref->distance);
362 }
363 else
364 {
365 if (gimple_code (ref->stmt) == GIMPLE_PHI)
366 fprintf (file, " looparound ref\n");
367 else
368 fprintf (file, " combination ref\n");
369 fprintf (file, " in statement ");
370 print_gimple_stmt (file, ref->stmt, 0, TDF_SLIM);
371 fprintf (file, "\n");
372 fprintf (file, " distance %u\n", ref->distance);
373 }
374
375 }
376
377 /* Dumps CHAIN to FILE. */
378
379 extern void dump_chain (FILE *, chain_p);
380 void
381 dump_chain (FILE *file, chain_p chain)
382 {
383 dref a;
384 const char *chain_type;
385 unsigned i;
386 tree var;
387
388 switch (chain->type)
389 {
390 case CT_INVARIANT:
391 chain_type = "Load motion";
392 break;
393
394 case CT_LOAD:
395 chain_type = "Loads-only";
396 break;
397
398 case CT_STORE_LOAD:
399 chain_type = "Store-loads";
400 break;
401
402 case CT_COMBINATION:
403 chain_type = "Combination";
404 break;
405
406 default:
407 gcc_unreachable ();
408 }
409
410 fprintf (file, "%s chain %p%s\n", chain_type, (void *) chain,
411 chain->combined ? " (combined)" : "");
412 if (chain->type != CT_INVARIANT)
413 fprintf (file, " max distance %u%s\n", chain->length,
414 chain->has_max_use_after ? "" : ", may reuse first");
415
416 if (chain->type == CT_COMBINATION)
417 {
418 fprintf (file, " equal to %p %s %p in type ",
419 (void *) chain->ch1, op_symbol_code (chain->op),
420 (void *) chain->ch2);
421 print_generic_expr (file, chain->rslt_type, TDF_SLIM);
422 fprintf (file, "\n");
423 }
424
425 if (chain->vars.exists ())
426 {
427 fprintf (file, " vars");
428 FOR_EACH_VEC_ELT (chain->vars, i, var)
429 {
430 fprintf (file, " ");
431 print_generic_expr (file, var, TDF_SLIM);
432 }
433 fprintf (file, "\n");
434 }
435
436 if (chain->inits.exists ())
437 {
438 fprintf (file, " inits");
439 FOR_EACH_VEC_ELT (chain->inits, i, var)
440 {
441 fprintf (file, " ");
442 print_generic_expr (file, var, TDF_SLIM);
443 }
444 fprintf (file, "\n");
445 }
446
447 fprintf (file, " references:\n");
448 FOR_EACH_VEC_ELT (chain->refs, i, a)
449 dump_dref (file, a);
450
451 fprintf (file, "\n");
452 }
453
454 /* Dumps CHAINS to FILE. */
455
456 extern void dump_chains (FILE *, vec<chain_p> );
457 void
458 dump_chains (FILE *file, vec<chain_p> chains)
459 {
460 chain_p chain;
461 unsigned i;
462
463 FOR_EACH_VEC_ELT (chains, i, chain)
464 dump_chain (file, chain);
465 }
466
467 /* Dumps COMP to FILE. */
468
469 extern void dump_component (FILE *, struct component *);
470 void
471 dump_component (FILE *file, struct component *comp)
472 {
473 dref a;
474 unsigned i;
475
476 fprintf (file, "Component%s:\n",
477 comp->comp_step == RS_INVARIANT ? " (invariant)" : "");
478 FOR_EACH_VEC_ELT (comp->refs, i, a)
479 dump_dref (file, a);
480 fprintf (file, "\n");
481 }
482
483 /* Dumps COMPS to FILE. */
484
485 extern void dump_components (FILE *, struct component *);
486 void
487 dump_components (FILE *file, struct component *comps)
488 {
489 struct component *comp;
490
491 for (comp = comps; comp; comp = comp->next)
492 dump_component (file, comp);
493 }
494
495 /* Frees a chain CHAIN. */
496
497 static void
498 release_chain (chain_p chain)
499 {
500 dref ref;
501 unsigned i;
502
503 if (chain == NULL)
504 return;
505
506 FOR_EACH_VEC_ELT (chain->refs, i, ref)
507 free (ref);
508
509 chain->refs.release ();
510 chain->vars.release ();
511 chain->inits.release ();
512
513 free (chain);
514 }
515
516 /* Frees CHAINS. */
517
518 static void
519 release_chains (vec<chain_p> chains)
520 {
521 unsigned i;
522 chain_p chain;
523
524 FOR_EACH_VEC_ELT (chains, i, chain)
525 release_chain (chain);
526 chains.release ();
527 }
528
529 /* Frees a component COMP. */
530
531 static void
532 release_component (struct component *comp)
533 {
534 comp->refs.release ();
535 free (comp);
536 }
537
538 /* Frees list of components COMPS. */
539
540 static void
541 release_components (struct component *comps)
542 {
543 struct component *act, *next;
544
545 for (act = comps; act; act = next)
546 {
547 next = act->next;
548 release_component (act);
549 }
550 }
551
552 /* Finds a root of tree given by FATHERS containing A, and performs path
553 shortening. */
554
555 static unsigned
556 component_of (unsigned fathers[], unsigned a)
557 {
558 unsigned root, n;
559
560 for (root = a; root != fathers[root]; root = fathers[root])
561 continue;
562
563 for (; a != root; a = n)
564 {
565 n = fathers[a];
566 fathers[a] = root;
567 }
568
569 return root;
570 }
571
572 /* Join operation for DFU. FATHERS gives the tree, SIZES are sizes of the
573 components, A and B are components to merge. */
574
575 static void
576 merge_comps (unsigned fathers[], unsigned sizes[], unsigned a, unsigned b)
577 {
578 unsigned ca = component_of (fathers, a);
579 unsigned cb = component_of (fathers, b);
580
581 if (ca == cb)
582 return;
583
584 if (sizes[ca] < sizes[cb])
585 {
586 sizes[cb] += sizes[ca];
587 fathers[ca] = cb;
588 }
589 else
590 {
591 sizes[ca] += sizes[cb];
592 fathers[cb] = ca;
593 }
594 }
595
596 /* Returns true if A is a reference that is suitable for predictive commoning
597 in the innermost loop that contains it. REF_STEP is set according to the
598 step of the reference A. */
599
600 static bool
601 suitable_reference_p (struct data_reference *a, enum ref_step_type *ref_step)
602 {
603 tree ref = DR_REF (a), step = DR_STEP (a);
604
605 if (!step
606 || TREE_THIS_VOLATILE (ref)
607 || !is_gimple_reg_type (TREE_TYPE (ref))
608 || tree_could_throw_p (ref))
609 return false;
610
611 if (integer_zerop (step))
612 *ref_step = RS_INVARIANT;
613 else if (integer_nonzerop (step))
614 *ref_step = RS_NONZERO;
615 else
616 *ref_step = RS_ANY;
617
618 return true;
619 }
620
621 /* Stores DR_OFFSET (DR) + DR_INIT (DR) to OFFSET. */
622
623 static void
624 aff_combination_dr_offset (struct data_reference *dr, aff_tree *offset)
625 {
626 tree type = TREE_TYPE (DR_OFFSET (dr));
627 aff_tree delta;
628
629 tree_to_aff_combination_expand (DR_OFFSET (dr), type, offset,
630 &name_expansions);
631 aff_combination_const (&delta, type, tree_to_double_int (DR_INIT (dr)));
632 aff_combination_add (offset, &delta);
633 }
634
635 /* Determines number of iterations of the innermost enclosing loop before B
636 refers to exactly the same location as A and stores it to OFF. If A and
637 B do not have the same step, they never meet, or anything else fails,
638 returns false, otherwise returns true. Both A and B are assumed to
639 satisfy suitable_reference_p. */
640
641 static bool
642 determine_offset (struct data_reference *a, struct data_reference *b,
643 double_int *off)
644 {
645 aff_tree diff, baseb, step;
646 tree typea, typeb;
647
648 /* Check that both the references access the location in the same type. */
649 typea = TREE_TYPE (DR_REF (a));
650 typeb = TREE_TYPE (DR_REF (b));
651 if (!useless_type_conversion_p (typeb, typea))
652 return false;
653
654 /* Check whether the base address and the step of both references is the
655 same. */
656 if (!operand_equal_p (DR_STEP (a), DR_STEP (b), 0)
657 || !operand_equal_p (DR_BASE_ADDRESS (a), DR_BASE_ADDRESS (b), 0))
658 return false;
659
660 if (integer_zerop (DR_STEP (a)))
661 {
662 /* If the references have loop invariant address, check that they access
663 exactly the same location. */
664 *off = double_int_zero;
665 return (operand_equal_p (DR_OFFSET (a), DR_OFFSET (b), 0)
666 && operand_equal_p (DR_INIT (a), DR_INIT (b), 0));
667 }
668
669 /* Compare the offsets of the addresses, and check whether the difference
670 is a multiple of step. */
671 aff_combination_dr_offset (a, &diff);
672 aff_combination_dr_offset (b, &baseb);
673 aff_combination_scale (&baseb, double_int_minus_one);
674 aff_combination_add (&diff, &baseb);
675
676 tree_to_aff_combination_expand (DR_STEP (a), TREE_TYPE (DR_STEP (a)),
677 &step, &name_expansions);
678 return aff_combination_constant_multiple_p (&diff, &step, off);
679 }
680
681 /* Returns the last basic block in LOOP for that we are sure that
682 it is executed whenever the loop is entered. */
683
684 static basic_block
685 last_always_executed_block (struct loop *loop)
686 {
687 unsigned i;
688 vec<edge> exits = get_loop_exit_edges (loop);
689 edge ex;
690 basic_block last = loop->latch;
691
692 FOR_EACH_VEC_ELT (exits, i, ex)
693 last = nearest_common_dominator (CDI_DOMINATORS, last, ex->src);
694 exits.release ();
695
696 return last;
697 }
698
699 /* Splits dependence graph on DATAREFS described by DEPENDS to components. */
700
701 static struct component *
702 split_data_refs_to_components (struct loop *loop,
703 vec<data_reference_p> datarefs,
704 vec<ddr_p> depends)
705 {
706 unsigned i, n = datarefs.length ();
707 unsigned ca, ia, ib, bad;
708 unsigned *comp_father = XNEWVEC (unsigned, n + 1);
709 unsigned *comp_size = XNEWVEC (unsigned, n + 1);
710 struct component **comps;
711 struct data_reference *dr, *dra, *drb;
712 struct data_dependence_relation *ddr;
713 struct component *comp_list = NULL, *comp;
714 dref dataref;
715 basic_block last_always_executed = last_always_executed_block (loop);
716
717 FOR_EACH_VEC_ELT (datarefs, i, dr)
718 {
719 if (!DR_REF (dr))
720 {
721 /* A fake reference for call or asm_expr that may clobber memory;
722 just fail. */
723 goto end;
724 }
725 dr->aux = (void *) (size_t) i;
726 comp_father[i] = i;
727 comp_size[i] = 1;
728 }
729
730 /* A component reserved for the "bad" data references. */
731 comp_father[n] = n;
732 comp_size[n] = 1;
733
734 FOR_EACH_VEC_ELT (datarefs, i, dr)
735 {
736 enum ref_step_type dummy;
737
738 if (!suitable_reference_p (dr, &dummy))
739 {
740 ia = (unsigned) (size_t) dr->aux;
741 merge_comps (comp_father, comp_size, n, ia);
742 }
743 }
744
745 FOR_EACH_VEC_ELT (depends, i, ddr)
746 {
747 double_int dummy_off;
748
749 if (DDR_ARE_DEPENDENT (ddr) == chrec_known)
750 continue;
751
752 dra = DDR_A (ddr);
753 drb = DDR_B (ddr);
754 ia = component_of (comp_father, (unsigned) (size_t) dra->aux);
755 ib = component_of (comp_father, (unsigned) (size_t) drb->aux);
756 if (ia == ib)
757 continue;
758
759 bad = component_of (comp_father, n);
760
761 /* If both A and B are reads, we may ignore unsuitable dependences. */
762 if (DR_IS_READ (dra) && DR_IS_READ (drb)
763 && (ia == bad || ib == bad
764 || !determine_offset (dra, drb, &dummy_off)))
765 continue;
766
767 merge_comps (comp_father, comp_size, ia, ib);
768 }
769
770 comps = XCNEWVEC (struct component *, n);
771 bad = component_of (comp_father, n);
772 FOR_EACH_VEC_ELT (datarefs, i, dr)
773 {
774 ia = (unsigned) (size_t) dr->aux;
775 ca = component_of (comp_father, ia);
776 if (ca == bad)
777 continue;
778
779 comp = comps[ca];
780 if (!comp)
781 {
782 comp = XCNEW (struct component);
783 comp->refs.create (comp_size[ca]);
784 comps[ca] = comp;
785 }
786
787 dataref = XCNEW (struct dref_d);
788 dataref->ref = dr;
789 dataref->stmt = DR_STMT (dr);
790 dataref->offset = double_int_zero;
791 dataref->distance = 0;
792
793 dataref->always_accessed
794 = dominated_by_p (CDI_DOMINATORS, last_always_executed,
795 gimple_bb (dataref->stmt));
796 dataref->pos = comp->refs.length ();
797 comp->refs.quick_push (dataref);
798 }
799
800 for (i = 0; i < n; i++)
801 {
802 comp = comps[i];
803 if (comp)
804 {
805 comp->next = comp_list;
806 comp_list = comp;
807 }
808 }
809 free (comps);
810
811 end:
812 free (comp_father);
813 free (comp_size);
814 return comp_list;
815 }
816
817 /* Returns true if the component COMP satisfies the conditions
818 described in 2) at the beginning of this file. LOOP is the current
819 loop. */
820
821 static bool
822 suitable_component_p (struct loop *loop, struct component *comp)
823 {
824 unsigned i;
825 dref a, first;
826 basic_block ba, bp = loop->header;
827 bool ok, has_write = false;
828
829 FOR_EACH_VEC_ELT (comp->refs, i, a)
830 {
831 ba = gimple_bb (a->stmt);
832
833 if (!just_once_each_iteration_p (loop, ba))
834 return false;
835
836 gcc_assert (dominated_by_p (CDI_DOMINATORS, ba, bp));
837 bp = ba;
838
839 if (DR_IS_WRITE (a->ref))
840 has_write = true;
841 }
842
843 first = comp->refs[0];
844 ok = suitable_reference_p (first->ref, &comp->comp_step);
845 gcc_assert (ok);
846 first->offset = double_int_zero;
847
848 for (i = 1; comp->refs.iterate (i, &a); i++)
849 {
850 if (!determine_offset (first->ref, a->ref, &a->offset))
851 return false;
852
853 #ifdef ENABLE_CHECKING
854 {
855 enum ref_step_type a_step;
856 ok = suitable_reference_p (a->ref, &a_step);
857 gcc_assert (ok && a_step == comp->comp_step);
858 }
859 #endif
860 }
861
862 /* If there is a write inside the component, we must know whether the
863 step is nonzero or not -- we would not otherwise be able to recognize
864 whether the value accessed by reads comes from the OFFSET-th iteration
865 or the previous one. */
866 if (has_write && comp->comp_step == RS_ANY)
867 return false;
868
869 return true;
870 }
871
872 /* Check the conditions on references inside each of components COMPS,
873 and remove the unsuitable components from the list. The new list
874 of components is returned. The conditions are described in 2) at
875 the beginning of this file. LOOP is the current loop. */
876
877 static struct component *
878 filter_suitable_components (struct loop *loop, struct component *comps)
879 {
880 struct component **comp, *act;
881
882 for (comp = &comps; *comp; )
883 {
884 act = *comp;
885 if (suitable_component_p (loop, act))
886 comp = &act->next;
887 else
888 {
889 dref ref;
890 unsigned i;
891
892 *comp = act->next;
893 FOR_EACH_VEC_ELT (act->refs, i, ref)
894 free (ref);
895 release_component (act);
896 }
897 }
898
899 return comps;
900 }
901
902 /* Compares two drefs A and B by their offset and position. Callback for
903 qsort. */
904
905 static int
906 order_drefs (const void *a, const void *b)
907 {
908 const dref *const da = (const dref *) a;
909 const dref *const db = (const dref *) b;
910 int offcmp = (*da)->offset.scmp ((*db)->offset);
911
912 if (offcmp != 0)
913 return offcmp;
914
915 return (*da)->pos - (*db)->pos;
916 }
917
918 /* Returns root of the CHAIN. */
919
920 static inline dref
921 get_chain_root (chain_p chain)
922 {
923 return chain->refs[0];
924 }
925
926 /* Adds REF to the chain CHAIN. */
927
928 static void
929 add_ref_to_chain (chain_p chain, dref ref)
930 {
931 dref root = get_chain_root (chain);
932 double_int dist;
933
934 gcc_assert (root->offset.sle (ref->offset));
935 dist = ref->offset - root->offset;
936 if (double_int::from_uhwi (MAX_DISTANCE).ule (dist))
937 {
938 free (ref);
939 return;
940 }
941 gcc_assert (dist.fits_uhwi ());
942
943 chain->refs.safe_push (ref);
944
945 ref->distance = dist.to_uhwi ();
946
947 if (ref->distance >= chain->length)
948 {
949 chain->length = ref->distance;
950 chain->has_max_use_after = false;
951 }
952
953 if (ref->distance == chain->length
954 && ref->pos > root->pos)
955 chain->has_max_use_after = true;
956
957 chain->all_always_accessed &= ref->always_accessed;
958 }
959
960 /* Returns the chain for invariant component COMP. */
961
962 static chain_p
963 make_invariant_chain (struct component *comp)
964 {
965 chain_p chain = XCNEW (struct chain);
966 unsigned i;
967 dref ref;
968
969 chain->type = CT_INVARIANT;
970
971 chain->all_always_accessed = true;
972
973 FOR_EACH_VEC_ELT (comp->refs, i, ref)
974 {
975 chain->refs.safe_push (ref);
976 chain->all_always_accessed &= ref->always_accessed;
977 }
978
979 return chain;
980 }
981
982 /* Make a new chain rooted at REF. */
983
984 static chain_p
985 make_rooted_chain (dref ref)
986 {
987 chain_p chain = XCNEW (struct chain);
988
989 chain->type = DR_IS_READ (ref->ref) ? CT_LOAD : CT_STORE_LOAD;
990
991 chain->refs.safe_push (ref);
992 chain->all_always_accessed = ref->always_accessed;
993
994 ref->distance = 0;
995
996 return chain;
997 }
998
999 /* Returns true if CHAIN is not trivial. */
1000
1001 static bool
1002 nontrivial_chain_p (chain_p chain)
1003 {
1004 return chain != NULL && chain->refs.length () > 1;
1005 }
1006
1007 /* Returns the ssa name that contains the value of REF, or NULL_TREE if there
1008 is no such name. */
1009
1010 static tree
1011 name_for_ref (dref ref)
1012 {
1013 tree name;
1014
1015 if (is_gimple_assign (ref->stmt))
1016 {
1017 if (!ref->ref || DR_IS_READ (ref->ref))
1018 name = gimple_assign_lhs (ref->stmt);
1019 else
1020 name = gimple_assign_rhs1 (ref->stmt);
1021 }
1022 else
1023 name = PHI_RESULT (ref->stmt);
1024
1025 return (TREE_CODE (name) == SSA_NAME ? name : NULL_TREE);
1026 }
1027
1028 /* Returns true if REF is a valid initializer for ROOT with given DISTANCE (in
1029 iterations of the innermost enclosing loop). */
1030
1031 static bool
1032 valid_initializer_p (struct data_reference *ref,
1033 unsigned distance, struct data_reference *root)
1034 {
1035 aff_tree diff, base, step;
1036 double_int off;
1037
1038 /* Both REF and ROOT must be accessing the same object. */
1039 if (!operand_equal_p (DR_BASE_ADDRESS (ref), DR_BASE_ADDRESS (root), 0))
1040 return false;
1041
1042 /* The initializer is defined outside of loop, hence its address must be
1043 invariant inside the loop. */
1044 gcc_assert (integer_zerop (DR_STEP (ref)));
1045
1046 /* If the address of the reference is invariant, initializer must access
1047 exactly the same location. */
1048 if (integer_zerop (DR_STEP (root)))
1049 return (operand_equal_p (DR_OFFSET (ref), DR_OFFSET (root), 0)
1050 && operand_equal_p (DR_INIT (ref), DR_INIT (root), 0));
1051
1052 /* Verify that this index of REF is equal to the root's index at
1053 -DISTANCE-th iteration. */
1054 aff_combination_dr_offset (root, &diff);
1055 aff_combination_dr_offset (ref, &base);
1056 aff_combination_scale (&base, double_int_minus_one);
1057 aff_combination_add (&diff, &base);
1058
1059 tree_to_aff_combination_expand (DR_STEP (root), TREE_TYPE (DR_STEP (root)),
1060 &step, &name_expansions);
1061 if (!aff_combination_constant_multiple_p (&diff, &step, &off))
1062 return false;
1063
1064 if (off != double_int::from_uhwi (distance))
1065 return false;
1066
1067 return true;
1068 }
1069
1070 /* Finds looparound phi node of LOOP that copies the value of REF, and if its
1071 initial value is correct (equal to initial value of REF shifted by one
1072 iteration), returns the phi node. Otherwise, NULL_TREE is returned. ROOT
1073 is the root of the current chain. */
1074
1075 static gimple
1076 find_looparound_phi (struct loop *loop, dref ref, dref root)
1077 {
1078 tree name, init, init_ref;
1079 gimple phi = NULL, init_stmt;
1080 edge latch = loop_latch_edge (loop);
1081 struct data_reference init_dr;
1082 gimple_stmt_iterator psi;
1083
1084 if (is_gimple_assign (ref->stmt))
1085 {
1086 if (DR_IS_READ (ref->ref))
1087 name = gimple_assign_lhs (ref->stmt);
1088 else
1089 name = gimple_assign_rhs1 (ref->stmt);
1090 }
1091 else
1092 name = PHI_RESULT (ref->stmt);
1093 if (!name)
1094 return NULL;
1095
1096 for (psi = gsi_start_phis (loop->header); !gsi_end_p (psi); gsi_next (&psi))
1097 {
1098 phi = gsi_stmt (psi);
1099 if (PHI_ARG_DEF_FROM_EDGE (phi, latch) == name)
1100 break;
1101 }
1102
1103 if (gsi_end_p (psi))
1104 return NULL;
1105
1106 init = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
1107 if (TREE_CODE (init) != SSA_NAME)
1108 return NULL;
1109 init_stmt = SSA_NAME_DEF_STMT (init);
1110 if (gimple_code (init_stmt) != GIMPLE_ASSIGN)
1111 return NULL;
1112 gcc_assert (gimple_assign_lhs (init_stmt) == init);
1113
1114 init_ref = gimple_assign_rhs1 (init_stmt);
1115 if (!REFERENCE_CLASS_P (init_ref)
1116 && !DECL_P (init_ref))
1117 return NULL;
1118
1119 /* Analyze the behavior of INIT_REF with respect to LOOP (innermost
1120 loop enclosing PHI). */
1121 memset (&init_dr, 0, sizeof (struct data_reference));
1122 DR_REF (&init_dr) = init_ref;
1123 DR_STMT (&init_dr) = phi;
1124 if (!dr_analyze_innermost (&init_dr, loop))
1125 return NULL;
1126
1127 if (!valid_initializer_p (&init_dr, ref->distance + 1, root->ref))
1128 return NULL;
1129
1130 return phi;
1131 }
1132
1133 /* Adds a reference for the looparound copy of REF in PHI to CHAIN. */
1134
1135 static void
1136 insert_looparound_copy (chain_p chain, dref ref, gimple phi)
1137 {
1138 dref nw = XCNEW (struct dref_d), aref;
1139 unsigned i;
1140
1141 nw->stmt = phi;
1142 nw->distance = ref->distance + 1;
1143 nw->always_accessed = 1;
1144
1145 FOR_EACH_VEC_ELT (chain->refs, i, aref)
1146 if (aref->distance >= nw->distance)
1147 break;
1148 chain->refs.safe_insert (i, nw);
1149
1150 if (nw->distance > chain->length)
1151 {
1152 chain->length = nw->distance;
1153 chain->has_max_use_after = false;
1154 }
1155 }
1156
1157 /* For references in CHAIN that are copied around the LOOP (created previously
1158 by PRE, or by user), add the results of such copies to the chain. This
1159 enables us to remove the copies by unrolling, and may need less registers
1160 (also, it may allow us to combine chains together). */
1161
1162 static void
1163 add_looparound_copies (struct loop *loop, chain_p chain)
1164 {
1165 unsigned i;
1166 dref ref, root = get_chain_root (chain);
1167 gimple phi;
1168
1169 FOR_EACH_VEC_ELT (chain->refs, i, ref)
1170 {
1171 phi = find_looparound_phi (loop, ref, root);
1172 if (!phi)
1173 continue;
1174
1175 bitmap_set_bit (looparound_phis, SSA_NAME_VERSION (PHI_RESULT (phi)));
1176 insert_looparound_copy (chain, ref, phi);
1177 }
1178 }
1179
1180 /* Find roots of the values and determine distances in the component COMP.
1181 The references are redistributed into CHAINS. LOOP is the current
1182 loop. */
1183
1184 static void
1185 determine_roots_comp (struct loop *loop,
1186 struct component *comp,
1187 vec<chain_p> *chains)
1188 {
1189 unsigned i;
1190 dref a;
1191 chain_p chain = NULL;
1192 double_int last_ofs = double_int_zero;
1193
1194 /* Invariants are handled specially. */
1195 if (comp->comp_step == RS_INVARIANT)
1196 {
1197 chain = make_invariant_chain (comp);
1198 chains->safe_push (chain);
1199 return;
1200 }
1201
1202 comp->refs.qsort (order_drefs);
1203
1204 FOR_EACH_VEC_ELT (comp->refs, i, a)
1205 {
1206 if (!chain || DR_IS_WRITE (a->ref)
1207 || double_int::from_uhwi (MAX_DISTANCE).ule (a->offset - last_ofs))
1208 {
1209 if (nontrivial_chain_p (chain))
1210 {
1211 add_looparound_copies (loop, chain);
1212 chains->safe_push (chain);
1213 }
1214 else
1215 release_chain (chain);
1216 chain = make_rooted_chain (a);
1217 last_ofs = a->offset;
1218 continue;
1219 }
1220
1221 add_ref_to_chain (chain, a);
1222 }
1223
1224 if (nontrivial_chain_p (chain))
1225 {
1226 add_looparound_copies (loop, chain);
1227 chains->safe_push (chain);
1228 }
1229 else
1230 release_chain (chain);
1231 }
1232
1233 /* Find roots of the values and determine distances in components COMPS, and
1234 separates the references to CHAINS. LOOP is the current loop. */
1235
1236 static void
1237 determine_roots (struct loop *loop,
1238 struct component *comps, vec<chain_p> *chains)
1239 {
1240 struct component *comp;
1241
1242 for (comp = comps; comp; comp = comp->next)
1243 determine_roots_comp (loop, comp, chains);
1244 }
1245
1246 /* Replace the reference in statement STMT with temporary variable
1247 NEW_TREE. If SET is true, NEW_TREE is instead initialized to the value of
1248 the reference in the statement. IN_LHS is true if the reference
1249 is in the lhs of STMT, false if it is in rhs. */
1250
1251 static void
1252 replace_ref_with (gimple stmt, tree new_tree, bool set, bool in_lhs)
1253 {
1254 tree val;
1255 gimple new_stmt;
1256 gimple_stmt_iterator bsi, psi;
1257
1258 if (gimple_code (stmt) == GIMPLE_PHI)
1259 {
1260 gcc_assert (!in_lhs && !set);
1261
1262 val = PHI_RESULT (stmt);
1263 bsi = gsi_after_labels (gimple_bb (stmt));
1264 psi = gsi_for_stmt (stmt);
1265 remove_phi_node (&psi, false);
1266
1267 /* Turn the phi node into GIMPLE_ASSIGN. */
1268 new_stmt = gimple_build_assign (val, new_tree);
1269 gsi_insert_before (&bsi, new_stmt, GSI_NEW_STMT);
1270 return;
1271 }
1272
1273 /* Since the reference is of gimple_reg type, it should only
1274 appear as lhs or rhs of modify statement. */
1275 gcc_assert (is_gimple_assign (stmt));
1276
1277 bsi = gsi_for_stmt (stmt);
1278
1279 /* If we do not need to initialize NEW_TREE, just replace the use of OLD. */
1280 if (!set)
1281 {
1282 gcc_assert (!in_lhs);
1283 gimple_assign_set_rhs_from_tree (&bsi, new_tree);
1284 stmt = gsi_stmt (bsi);
1285 update_stmt (stmt);
1286 return;
1287 }
1288
1289 if (in_lhs)
1290 {
1291 /* We have statement
1292
1293 OLD = VAL
1294
1295 If OLD is a memory reference, then VAL is gimple_val, and we transform
1296 this to
1297
1298 OLD = VAL
1299 NEW = VAL
1300
1301 Otherwise, we are replacing a combination chain,
1302 VAL is the expression that performs the combination, and OLD is an
1303 SSA name. In this case, we transform the assignment to
1304
1305 OLD = VAL
1306 NEW = OLD
1307
1308 */
1309
1310 val = gimple_assign_lhs (stmt);
1311 if (TREE_CODE (val) != SSA_NAME)
1312 {
1313 val = gimple_assign_rhs1 (stmt);
1314 gcc_assert (gimple_assign_single_p (stmt));
1315 if (TREE_CLOBBER_P (val))
1316 val = get_or_create_ssa_default_def (cfun, SSA_NAME_VAR (new_tree));
1317 else
1318 gcc_assert (gimple_assign_copy_p (stmt));
1319 }
1320 }
1321 else
1322 {
1323 /* VAL = OLD
1324
1325 is transformed to
1326
1327 VAL = OLD
1328 NEW = VAL */
1329
1330 val = gimple_assign_lhs (stmt);
1331 }
1332
1333 new_stmt = gimple_build_assign (new_tree, unshare_expr (val));
1334 gsi_insert_after (&bsi, new_stmt, GSI_NEW_STMT);
1335 }
1336
1337 /* Returns a memory reference to DR in the ITER-th iteration of
1338 the loop it was analyzed in. Append init stmts to STMTS. */
1339
1340 static tree
1341 ref_at_iteration (data_reference_p dr, int iter, gimple_seq *stmts)
1342 {
1343 tree off = DR_OFFSET (dr);
1344 tree coff = DR_INIT (dr);
1345 if (iter == 0)
1346 ;
1347 else if (TREE_CODE (DR_STEP (dr)) == INTEGER_CST)
1348 coff = size_binop (PLUS_EXPR, coff,
1349 size_binop (MULT_EXPR, DR_STEP (dr), ssize_int (iter)));
1350 else
1351 off = size_binop (PLUS_EXPR, off,
1352 size_binop (MULT_EXPR, DR_STEP (dr), ssize_int (iter)));
1353 tree addr = fold_build_pointer_plus (DR_BASE_ADDRESS (dr), off);
1354 addr = force_gimple_operand_1 (addr, stmts, is_gimple_mem_ref_addr,
1355 NULL_TREE);
1356 tree alias_ptr = fold_convert (reference_alias_ptr_type (DR_REF (dr)), coff);
1357 /* While data-ref analysis punts on bit offsets it still handles
1358 bitfield accesses at byte boundaries. Cope with that. Note that
1359 we cannot simply re-apply the outer COMPONENT_REF because the
1360 byte-granular portion of it is already applied via DR_INIT and
1361 DR_OFFSET, so simply build a BIT_FIELD_REF knowing that the bits
1362 start at offset zero. */
1363 if (TREE_CODE (DR_REF (dr)) == COMPONENT_REF
1364 && DECL_BIT_FIELD (TREE_OPERAND (DR_REF (dr), 1)))
1365 {
1366 tree field = TREE_OPERAND (DR_REF (dr), 1);
1367 return build3 (BIT_FIELD_REF, TREE_TYPE (DR_REF (dr)),
1368 build2 (MEM_REF, DECL_BIT_FIELD_TYPE (field),
1369 addr, alias_ptr),
1370 DECL_SIZE (field), bitsize_zero_node);
1371 }
1372 else
1373 return fold_build2 (MEM_REF, TREE_TYPE (DR_REF (dr)), addr, alias_ptr);
1374 }
1375
1376 /* Get the initialization expression for the INDEX-th temporary variable
1377 of CHAIN. */
1378
1379 static tree
1380 get_init_expr (chain_p chain, unsigned index)
1381 {
1382 if (chain->type == CT_COMBINATION)
1383 {
1384 tree e1 = get_init_expr (chain->ch1, index);
1385 tree e2 = get_init_expr (chain->ch2, index);
1386
1387 return fold_build2 (chain->op, chain->rslt_type, e1, e2);
1388 }
1389 else
1390 return chain->inits[index];
1391 }
1392
1393 /* Returns a new temporary variable used for the I-th variable carrying
1394 value of REF. The variable's uid is marked in TMP_VARS. */
1395
1396 static tree
1397 predcom_tmp_var (tree ref, unsigned i, bitmap tmp_vars)
1398 {
1399 tree type = TREE_TYPE (ref);
1400 /* We never access the components of the temporary variable in predictive
1401 commoning. */
1402 tree var = create_tmp_reg (type, get_lsm_tmp_name (ref, i));
1403 bitmap_set_bit (tmp_vars, DECL_UID (var));
1404 return var;
1405 }
1406
1407 /* Creates the variables for CHAIN, as well as phi nodes for them and
1408 initialization on entry to LOOP. Uids of the newly created
1409 temporary variables are marked in TMP_VARS. */
1410
1411 static void
1412 initialize_root_vars (struct loop *loop, chain_p chain, bitmap tmp_vars)
1413 {
1414 unsigned i;
1415 unsigned n = chain->length;
1416 dref root = get_chain_root (chain);
1417 bool reuse_first = !chain->has_max_use_after;
1418 tree ref, init, var, next;
1419 gimple phi;
1420 gimple_seq stmts;
1421 edge entry = loop_preheader_edge (loop), latch = loop_latch_edge (loop);
1422
1423 /* If N == 0, then all the references are within the single iteration. And
1424 since this is an nonempty chain, reuse_first cannot be true. */
1425 gcc_assert (n > 0 || !reuse_first);
1426
1427 chain->vars.create (n + 1);
1428
1429 if (chain->type == CT_COMBINATION)
1430 ref = gimple_assign_lhs (root->stmt);
1431 else
1432 ref = DR_REF (root->ref);
1433
1434 for (i = 0; i < n + (reuse_first ? 0 : 1); i++)
1435 {
1436 var = predcom_tmp_var (ref, i, tmp_vars);
1437 chain->vars.quick_push (var);
1438 }
1439 if (reuse_first)
1440 chain->vars.quick_push (chain->vars[0]);
1441
1442 FOR_EACH_VEC_ELT (chain->vars, i, var)
1443 chain->vars[i] = make_ssa_name (var, NULL);
1444
1445 for (i = 0; i < n; i++)
1446 {
1447 var = chain->vars[i];
1448 next = chain->vars[i + 1];
1449 init = get_init_expr (chain, i);
1450
1451 init = force_gimple_operand (init, &stmts, true, NULL_TREE);
1452 if (stmts)
1453 gsi_insert_seq_on_edge_immediate (entry, stmts);
1454
1455 phi = create_phi_node (var, loop->header);
1456 add_phi_arg (phi, init, entry, UNKNOWN_LOCATION);
1457 add_phi_arg (phi, next, latch, UNKNOWN_LOCATION);
1458 }
1459 }
1460
1461 /* Create the variables and initialization statement for root of chain
1462 CHAIN. Uids of the newly created temporary variables are marked
1463 in TMP_VARS. */
1464
1465 static void
1466 initialize_root (struct loop *loop, chain_p chain, bitmap tmp_vars)
1467 {
1468 dref root = get_chain_root (chain);
1469 bool in_lhs = (chain->type == CT_STORE_LOAD
1470 || chain->type == CT_COMBINATION);
1471
1472 initialize_root_vars (loop, chain, tmp_vars);
1473 replace_ref_with (root->stmt,
1474 chain->vars[chain->length],
1475 true, in_lhs);
1476 }
1477
1478 /* Initializes a variable for load motion for ROOT and prepares phi nodes and
1479 initialization on entry to LOOP if necessary. The ssa name for the variable
1480 is stored in VARS. If WRITTEN is true, also a phi node to copy its value
1481 around the loop is created. Uid of the newly created temporary variable
1482 is marked in TMP_VARS. INITS is the list containing the (single)
1483 initializer. */
1484
1485 static void
1486 initialize_root_vars_lm (struct loop *loop, dref root, bool written,
1487 vec<tree> *vars, vec<tree> inits,
1488 bitmap tmp_vars)
1489 {
1490 unsigned i;
1491 tree ref = DR_REF (root->ref), init, var, next;
1492 gimple_seq stmts;
1493 gimple phi;
1494 edge entry = loop_preheader_edge (loop), latch = loop_latch_edge (loop);
1495
1496 /* Find the initializer for the variable, and check that it cannot
1497 trap. */
1498 init = inits[0];
1499
1500 vars->create (written ? 2 : 1);
1501 var = predcom_tmp_var (ref, 0, tmp_vars);
1502 vars->quick_push (var);
1503 if (written)
1504 vars->quick_push ((*vars)[0]);
1505
1506 FOR_EACH_VEC_ELT (*vars, i, var)
1507 (*vars)[i] = make_ssa_name (var, NULL);
1508
1509 var = (*vars)[0];
1510
1511 init = force_gimple_operand (init, &stmts, written, NULL_TREE);
1512 if (stmts)
1513 gsi_insert_seq_on_edge_immediate (entry, stmts);
1514
1515 if (written)
1516 {
1517 next = (*vars)[1];
1518 phi = create_phi_node (var, loop->header);
1519 add_phi_arg (phi, init, entry, UNKNOWN_LOCATION);
1520 add_phi_arg (phi, next, latch, UNKNOWN_LOCATION);
1521 }
1522 else
1523 {
1524 gimple init_stmt = gimple_build_assign (var, init);
1525 gsi_insert_on_edge_immediate (entry, init_stmt);
1526 }
1527 }
1528
1529
1530 /* Execute load motion for references in chain CHAIN. Uids of the newly
1531 created temporary variables are marked in TMP_VARS. */
1532
1533 static void
1534 execute_load_motion (struct loop *loop, chain_p chain, bitmap tmp_vars)
1535 {
1536 vec<tree> vars;
1537 dref a;
1538 unsigned n_writes = 0, ridx, i;
1539 tree var;
1540
1541 gcc_assert (chain->type == CT_INVARIANT);
1542 gcc_assert (!chain->combined);
1543 FOR_EACH_VEC_ELT (chain->refs, i, a)
1544 if (DR_IS_WRITE (a->ref))
1545 n_writes++;
1546
1547 /* If there are no reads in the loop, there is nothing to do. */
1548 if (n_writes == chain->refs.length ())
1549 return;
1550
1551 initialize_root_vars_lm (loop, get_chain_root (chain), n_writes > 0,
1552 &vars, chain->inits, tmp_vars);
1553
1554 ridx = 0;
1555 FOR_EACH_VEC_ELT (chain->refs, i, a)
1556 {
1557 bool is_read = DR_IS_READ (a->ref);
1558
1559 if (DR_IS_WRITE (a->ref))
1560 {
1561 n_writes--;
1562 if (n_writes)
1563 {
1564 var = vars[0];
1565 var = make_ssa_name (SSA_NAME_VAR (var), NULL);
1566 vars[0] = var;
1567 }
1568 else
1569 ridx = 1;
1570 }
1571
1572 replace_ref_with (a->stmt, vars[ridx],
1573 !is_read, !is_read);
1574 }
1575
1576 vars.release ();
1577 }
1578
1579 /* Returns the single statement in that NAME is used, excepting
1580 the looparound phi nodes contained in one of the chains. If there is no
1581 such statement, or more statements, NULL is returned. */
1582
1583 static gimple
1584 single_nonlooparound_use (tree name)
1585 {
1586 use_operand_p use;
1587 imm_use_iterator it;
1588 gimple stmt, ret = NULL;
1589
1590 FOR_EACH_IMM_USE_FAST (use, it, name)
1591 {
1592 stmt = USE_STMT (use);
1593
1594 if (gimple_code (stmt) == GIMPLE_PHI)
1595 {
1596 /* Ignore uses in looparound phi nodes. Uses in other phi nodes
1597 could not be processed anyway, so just fail for them. */
1598 if (bitmap_bit_p (looparound_phis,
1599 SSA_NAME_VERSION (PHI_RESULT (stmt))))
1600 continue;
1601
1602 return NULL;
1603 }
1604 else if (is_gimple_debug (stmt))
1605 continue;
1606 else if (ret != NULL)
1607 return NULL;
1608 else
1609 ret = stmt;
1610 }
1611
1612 return ret;
1613 }
1614
1615 /* Remove statement STMT, as well as the chain of assignments in that it is
1616 used. */
1617
1618 static void
1619 remove_stmt (gimple stmt)
1620 {
1621 tree name;
1622 gimple next;
1623 gimple_stmt_iterator psi;
1624
1625 if (gimple_code (stmt) == GIMPLE_PHI)
1626 {
1627 name = PHI_RESULT (stmt);
1628 next = single_nonlooparound_use (name);
1629 reset_debug_uses (stmt);
1630 psi = gsi_for_stmt (stmt);
1631 remove_phi_node (&psi, true);
1632
1633 if (!next
1634 || !gimple_assign_ssa_name_copy_p (next)
1635 || gimple_assign_rhs1 (next) != name)
1636 return;
1637
1638 stmt = next;
1639 }
1640
1641 while (1)
1642 {
1643 gimple_stmt_iterator bsi;
1644
1645 bsi = gsi_for_stmt (stmt);
1646
1647 name = gimple_assign_lhs (stmt);
1648 gcc_assert (TREE_CODE (name) == SSA_NAME);
1649
1650 next = single_nonlooparound_use (name);
1651 reset_debug_uses (stmt);
1652
1653 unlink_stmt_vdef (stmt);
1654 gsi_remove (&bsi, true);
1655 release_defs (stmt);
1656
1657 if (!next
1658 || !gimple_assign_ssa_name_copy_p (next)
1659 || gimple_assign_rhs1 (next) != name)
1660 return;
1661
1662 stmt = next;
1663 }
1664 }
1665
1666 /* Perform the predictive commoning optimization for a chain CHAIN.
1667 Uids of the newly created temporary variables are marked in TMP_VARS.*/
1668
1669 static void
1670 execute_pred_commoning_chain (struct loop *loop, chain_p chain,
1671 bitmap tmp_vars)
1672 {
1673 unsigned i;
1674 dref a;
1675 tree var;
1676
1677 if (chain->combined)
1678 {
1679 /* For combined chains, just remove the statements that are used to
1680 compute the values of the expression (except for the root one). */
1681 for (i = 1; chain->refs.iterate (i, &a); i++)
1682 remove_stmt (a->stmt);
1683 }
1684 else
1685 {
1686 /* For non-combined chains, set up the variables that hold its value,
1687 and replace the uses of the original references by these
1688 variables. */
1689 initialize_root (loop, chain, tmp_vars);
1690 for (i = 1; chain->refs.iterate (i, &a); i++)
1691 {
1692 var = chain->vars[chain->length - a->distance];
1693 replace_ref_with (a->stmt, var, false, false);
1694 }
1695 }
1696 }
1697
1698 /* Determines the unroll factor necessary to remove as many temporary variable
1699 copies as possible. CHAINS is the list of chains that will be
1700 optimized. */
1701
1702 static unsigned
1703 determine_unroll_factor (vec<chain_p> chains)
1704 {
1705 chain_p chain;
1706 unsigned factor = 1, af, nfactor, i;
1707 unsigned max = PARAM_VALUE (PARAM_MAX_UNROLL_TIMES);
1708
1709 FOR_EACH_VEC_ELT (chains, i, chain)
1710 {
1711 if (chain->type == CT_INVARIANT || chain->combined)
1712 continue;
1713
1714 /* The best unroll factor for this chain is equal to the number of
1715 temporary variables that we create for it. */
1716 af = chain->length;
1717 if (chain->has_max_use_after)
1718 af++;
1719
1720 nfactor = factor * af / gcd (factor, af);
1721 if (nfactor <= max)
1722 factor = nfactor;
1723 }
1724
1725 return factor;
1726 }
1727
1728 /* Perform the predictive commoning optimization for CHAINS.
1729 Uids of the newly created temporary variables are marked in TMP_VARS. */
1730
1731 static void
1732 execute_pred_commoning (struct loop *loop, vec<chain_p> chains,
1733 bitmap tmp_vars)
1734 {
1735 chain_p chain;
1736 unsigned i;
1737
1738 FOR_EACH_VEC_ELT (chains, i, chain)
1739 {
1740 if (chain->type == CT_INVARIANT)
1741 execute_load_motion (loop, chain, tmp_vars);
1742 else
1743 execute_pred_commoning_chain (loop, chain, tmp_vars);
1744 }
1745
1746 update_ssa (TODO_update_ssa_only_virtuals);
1747 }
1748
1749 /* For each reference in CHAINS, if its defining statement is
1750 phi node, record the ssa name that is defined by it. */
1751
1752 static void
1753 replace_phis_by_defined_names (vec<chain_p> chains)
1754 {
1755 chain_p chain;
1756 dref a;
1757 unsigned i, j;
1758
1759 FOR_EACH_VEC_ELT (chains, i, chain)
1760 FOR_EACH_VEC_ELT (chain->refs, j, a)
1761 {
1762 if (gimple_code (a->stmt) == GIMPLE_PHI)
1763 {
1764 a->name_defined_by_phi = PHI_RESULT (a->stmt);
1765 a->stmt = NULL;
1766 }
1767 }
1768 }
1769
1770 /* For each reference in CHAINS, if name_defined_by_phi is not
1771 NULL, use it to set the stmt field. */
1772
1773 static void
1774 replace_names_by_phis (vec<chain_p> chains)
1775 {
1776 chain_p chain;
1777 dref a;
1778 unsigned i, j;
1779
1780 FOR_EACH_VEC_ELT (chains, i, chain)
1781 FOR_EACH_VEC_ELT (chain->refs, j, a)
1782 if (a->stmt == NULL)
1783 {
1784 a->stmt = SSA_NAME_DEF_STMT (a->name_defined_by_phi);
1785 gcc_assert (gimple_code (a->stmt) == GIMPLE_PHI);
1786 a->name_defined_by_phi = NULL_TREE;
1787 }
1788 }
1789
1790 /* Wrapper over execute_pred_commoning, to pass it as a callback
1791 to tree_transform_and_unroll_loop. */
1792
1793 struct epcc_data
1794 {
1795 vec<chain_p> chains;
1796 bitmap tmp_vars;
1797 };
1798
1799 static void
1800 execute_pred_commoning_cbck (struct loop *loop, void *data)
1801 {
1802 struct epcc_data *const dta = (struct epcc_data *) data;
1803
1804 /* Restore phi nodes that were replaced by ssa names before
1805 tree_transform_and_unroll_loop (see detailed description in
1806 tree_predictive_commoning_loop). */
1807 replace_names_by_phis (dta->chains);
1808 execute_pred_commoning (loop, dta->chains, dta->tmp_vars);
1809 }
1810
1811 /* Base NAME and all the names in the chain of phi nodes that use it
1812 on variable VAR. The phi nodes are recognized by being in the copies of
1813 the header of the LOOP. */
1814
1815 static void
1816 base_names_in_chain_on (struct loop *loop, tree name, tree var)
1817 {
1818 gimple stmt, phi;
1819 imm_use_iterator iter;
1820
1821 replace_ssa_name_symbol (name, var);
1822
1823 while (1)
1824 {
1825 phi = NULL;
1826 FOR_EACH_IMM_USE_STMT (stmt, iter, name)
1827 {
1828 if (gimple_code (stmt) == GIMPLE_PHI
1829 && flow_bb_inside_loop_p (loop, gimple_bb (stmt)))
1830 {
1831 phi = stmt;
1832 BREAK_FROM_IMM_USE_STMT (iter);
1833 }
1834 }
1835 if (!phi)
1836 return;
1837
1838 name = PHI_RESULT (phi);
1839 replace_ssa_name_symbol (name, var);
1840 }
1841 }
1842
1843 /* Given an unrolled LOOP after predictive commoning, remove the
1844 register copies arising from phi nodes by changing the base
1845 variables of SSA names. TMP_VARS is the set of the temporary variables
1846 for those we want to perform this. */
1847
1848 static void
1849 eliminate_temp_copies (struct loop *loop, bitmap tmp_vars)
1850 {
1851 edge e;
1852 gimple phi, stmt;
1853 tree name, use, var;
1854 gimple_stmt_iterator psi;
1855
1856 e = loop_latch_edge (loop);
1857 for (psi = gsi_start_phis (loop->header); !gsi_end_p (psi); gsi_next (&psi))
1858 {
1859 phi = gsi_stmt (psi);
1860 name = PHI_RESULT (phi);
1861 var = SSA_NAME_VAR (name);
1862 if (!var || !bitmap_bit_p (tmp_vars, DECL_UID (var)))
1863 continue;
1864 use = PHI_ARG_DEF_FROM_EDGE (phi, e);
1865 gcc_assert (TREE_CODE (use) == SSA_NAME);
1866
1867 /* Base all the ssa names in the ud and du chain of NAME on VAR. */
1868 stmt = SSA_NAME_DEF_STMT (use);
1869 while (gimple_code (stmt) == GIMPLE_PHI
1870 /* In case we could not unroll the loop enough to eliminate
1871 all copies, we may reach the loop header before the defining
1872 statement (in that case, some register copies will be present
1873 in loop latch in the final code, corresponding to the newly
1874 created looparound phi nodes). */
1875 && gimple_bb (stmt) != loop->header)
1876 {
1877 gcc_assert (single_pred_p (gimple_bb (stmt)));
1878 use = PHI_ARG_DEF (stmt, 0);
1879 stmt = SSA_NAME_DEF_STMT (use);
1880 }
1881
1882 base_names_in_chain_on (loop, use, var);
1883 }
1884 }
1885
1886 /* Returns true if CHAIN is suitable to be combined. */
1887
1888 static bool
1889 chain_can_be_combined_p (chain_p chain)
1890 {
1891 return (!chain->combined
1892 && (chain->type == CT_LOAD || chain->type == CT_COMBINATION));
1893 }
1894
1895 /* Returns the modify statement that uses NAME. Skips over assignment
1896 statements, NAME is replaced with the actual name used in the returned
1897 statement. */
1898
1899 static gimple
1900 find_use_stmt (tree *name)
1901 {
1902 gimple stmt;
1903 tree rhs, lhs;
1904
1905 /* Skip over assignments. */
1906 while (1)
1907 {
1908 stmt = single_nonlooparound_use (*name);
1909 if (!stmt)
1910 return NULL;
1911
1912 if (gimple_code (stmt) != GIMPLE_ASSIGN)
1913 return NULL;
1914
1915 lhs = gimple_assign_lhs (stmt);
1916 if (TREE_CODE (lhs) != SSA_NAME)
1917 return NULL;
1918
1919 if (gimple_assign_copy_p (stmt))
1920 {
1921 rhs = gimple_assign_rhs1 (stmt);
1922 if (rhs != *name)
1923 return NULL;
1924
1925 *name = lhs;
1926 }
1927 else if (get_gimple_rhs_class (gimple_assign_rhs_code (stmt))
1928 == GIMPLE_BINARY_RHS)
1929 return stmt;
1930 else
1931 return NULL;
1932 }
1933 }
1934
1935 /* Returns true if we may perform reassociation for operation CODE in TYPE. */
1936
1937 static bool
1938 may_reassociate_p (tree type, enum tree_code code)
1939 {
1940 if (FLOAT_TYPE_P (type)
1941 && !flag_unsafe_math_optimizations)
1942 return false;
1943
1944 return (commutative_tree_code (code)
1945 && associative_tree_code (code));
1946 }
1947
1948 /* If the operation used in STMT is associative and commutative, go through the
1949 tree of the same operations and returns its root. Distance to the root
1950 is stored in DISTANCE. */
1951
1952 static gimple
1953 find_associative_operation_root (gimple stmt, unsigned *distance)
1954 {
1955 tree lhs;
1956 gimple next;
1957 enum tree_code code = gimple_assign_rhs_code (stmt);
1958 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
1959 unsigned dist = 0;
1960
1961 if (!may_reassociate_p (type, code))
1962 return NULL;
1963
1964 while (1)
1965 {
1966 lhs = gimple_assign_lhs (stmt);
1967 gcc_assert (TREE_CODE (lhs) == SSA_NAME);
1968
1969 next = find_use_stmt (&lhs);
1970 if (!next
1971 || gimple_assign_rhs_code (next) != code)
1972 break;
1973
1974 stmt = next;
1975 dist++;
1976 }
1977
1978 if (distance)
1979 *distance = dist;
1980 return stmt;
1981 }
1982
1983 /* Returns the common statement in that NAME1 and NAME2 have a use. If there
1984 is no such statement, returns NULL_TREE. In case the operation used on
1985 NAME1 and NAME2 is associative and commutative, returns the root of the
1986 tree formed by this operation instead of the statement that uses NAME1 or
1987 NAME2. */
1988
1989 static gimple
1990 find_common_use_stmt (tree *name1, tree *name2)
1991 {
1992 gimple stmt1, stmt2;
1993
1994 stmt1 = find_use_stmt (name1);
1995 if (!stmt1)
1996 return NULL;
1997
1998 stmt2 = find_use_stmt (name2);
1999 if (!stmt2)
2000 return NULL;
2001
2002 if (stmt1 == stmt2)
2003 return stmt1;
2004
2005 stmt1 = find_associative_operation_root (stmt1, NULL);
2006 if (!stmt1)
2007 return NULL;
2008 stmt2 = find_associative_operation_root (stmt2, NULL);
2009 if (!stmt2)
2010 return NULL;
2011
2012 return (stmt1 == stmt2 ? stmt1 : NULL);
2013 }
2014
2015 /* Checks whether R1 and R2 are combined together using CODE, with the result
2016 in RSLT_TYPE, in order R1 CODE R2 if SWAP is false and in order R2 CODE R1
2017 if it is true. If CODE is ERROR_MARK, set these values instead. */
2018
2019 static bool
2020 combinable_refs_p (dref r1, dref r2,
2021 enum tree_code *code, bool *swap, tree *rslt_type)
2022 {
2023 enum tree_code acode;
2024 bool aswap;
2025 tree atype;
2026 tree name1, name2;
2027 gimple stmt;
2028
2029 name1 = name_for_ref (r1);
2030 name2 = name_for_ref (r2);
2031 gcc_assert (name1 != NULL_TREE && name2 != NULL_TREE);
2032
2033 stmt = find_common_use_stmt (&name1, &name2);
2034
2035 if (!stmt)
2036 return false;
2037
2038 acode = gimple_assign_rhs_code (stmt);
2039 aswap = (!commutative_tree_code (acode)
2040 && gimple_assign_rhs1 (stmt) != name1);
2041 atype = TREE_TYPE (gimple_assign_lhs (stmt));
2042
2043 if (*code == ERROR_MARK)
2044 {
2045 *code = acode;
2046 *swap = aswap;
2047 *rslt_type = atype;
2048 return true;
2049 }
2050
2051 return (*code == acode
2052 && *swap == aswap
2053 && *rslt_type == atype);
2054 }
2055
2056 /* Remove OP from the operation on rhs of STMT, and replace STMT with
2057 an assignment of the remaining operand. */
2058
2059 static void
2060 remove_name_from_operation (gimple stmt, tree op)
2061 {
2062 tree other_op;
2063 gimple_stmt_iterator si;
2064
2065 gcc_assert (is_gimple_assign (stmt));
2066
2067 if (gimple_assign_rhs1 (stmt) == op)
2068 other_op = gimple_assign_rhs2 (stmt);
2069 else
2070 other_op = gimple_assign_rhs1 (stmt);
2071
2072 si = gsi_for_stmt (stmt);
2073 gimple_assign_set_rhs_from_tree (&si, other_op);
2074
2075 /* We should not have reallocated STMT. */
2076 gcc_assert (gsi_stmt (si) == stmt);
2077
2078 update_stmt (stmt);
2079 }
2080
2081 /* Reassociates the expression in that NAME1 and NAME2 are used so that they
2082 are combined in a single statement, and returns this statement. */
2083
2084 static gimple
2085 reassociate_to_the_same_stmt (tree name1, tree name2)
2086 {
2087 gimple stmt1, stmt2, root1, root2, s1, s2;
2088 gimple new_stmt, tmp_stmt;
2089 tree new_name, tmp_name, var, r1, r2;
2090 unsigned dist1, dist2;
2091 enum tree_code code;
2092 tree type = TREE_TYPE (name1);
2093 gimple_stmt_iterator bsi;
2094
2095 stmt1 = find_use_stmt (&name1);
2096 stmt2 = find_use_stmt (&name2);
2097 root1 = find_associative_operation_root (stmt1, &dist1);
2098 root2 = find_associative_operation_root (stmt2, &dist2);
2099 code = gimple_assign_rhs_code (stmt1);
2100
2101 gcc_assert (root1 && root2 && root1 == root2
2102 && code == gimple_assign_rhs_code (stmt2));
2103
2104 /* Find the root of the nearest expression in that both NAME1 and NAME2
2105 are used. */
2106 r1 = name1;
2107 s1 = stmt1;
2108 r2 = name2;
2109 s2 = stmt2;
2110
2111 while (dist1 > dist2)
2112 {
2113 s1 = find_use_stmt (&r1);
2114 r1 = gimple_assign_lhs (s1);
2115 dist1--;
2116 }
2117 while (dist2 > dist1)
2118 {
2119 s2 = find_use_stmt (&r2);
2120 r2 = gimple_assign_lhs (s2);
2121 dist2--;
2122 }
2123
2124 while (s1 != s2)
2125 {
2126 s1 = find_use_stmt (&r1);
2127 r1 = gimple_assign_lhs (s1);
2128 s2 = find_use_stmt (&r2);
2129 r2 = gimple_assign_lhs (s2);
2130 }
2131
2132 /* Remove NAME1 and NAME2 from the statements in that they are used
2133 currently. */
2134 remove_name_from_operation (stmt1, name1);
2135 remove_name_from_operation (stmt2, name2);
2136
2137 /* Insert the new statement combining NAME1 and NAME2 before S1, and
2138 combine it with the rhs of S1. */
2139 var = create_tmp_reg (type, "predreastmp");
2140 new_name = make_ssa_name (var, NULL);
2141 new_stmt = gimple_build_assign_with_ops (code, new_name, name1, name2);
2142
2143 var = create_tmp_reg (type, "predreastmp");
2144 tmp_name = make_ssa_name (var, NULL);
2145
2146 /* Rhs of S1 may now be either a binary expression with operation
2147 CODE, or gimple_val (in case that stmt1 == s1 or stmt2 == s1,
2148 so that name1 or name2 was removed from it). */
2149 tmp_stmt = gimple_build_assign_with_ops (gimple_assign_rhs_code (s1),
2150 tmp_name,
2151 gimple_assign_rhs1 (s1),
2152 gimple_assign_rhs2 (s1));
2153
2154 bsi = gsi_for_stmt (s1);
2155 gimple_assign_set_rhs_with_ops (&bsi, code, new_name, tmp_name);
2156 s1 = gsi_stmt (bsi);
2157 update_stmt (s1);
2158
2159 gsi_insert_before (&bsi, new_stmt, GSI_SAME_STMT);
2160 gsi_insert_before (&bsi, tmp_stmt, GSI_SAME_STMT);
2161
2162 return new_stmt;
2163 }
2164
2165 /* Returns the statement that combines references R1 and R2. In case R1
2166 and R2 are not used in the same statement, but they are used with an
2167 associative and commutative operation in the same expression, reassociate
2168 the expression so that they are used in the same statement. */
2169
2170 static gimple
2171 stmt_combining_refs (dref r1, dref r2)
2172 {
2173 gimple stmt1, stmt2;
2174 tree name1 = name_for_ref (r1);
2175 tree name2 = name_for_ref (r2);
2176
2177 stmt1 = find_use_stmt (&name1);
2178 stmt2 = find_use_stmt (&name2);
2179 if (stmt1 == stmt2)
2180 return stmt1;
2181
2182 return reassociate_to_the_same_stmt (name1, name2);
2183 }
2184
2185 /* Tries to combine chains CH1 and CH2 together. If this succeeds, the
2186 description of the new chain is returned, otherwise we return NULL. */
2187
2188 static chain_p
2189 combine_chains (chain_p ch1, chain_p ch2)
2190 {
2191 dref r1, r2, nw;
2192 enum tree_code op = ERROR_MARK;
2193 bool swap = false;
2194 chain_p new_chain;
2195 unsigned i;
2196 gimple root_stmt;
2197 tree rslt_type = NULL_TREE;
2198
2199 if (ch1 == ch2)
2200 return NULL;
2201 if (ch1->length != ch2->length)
2202 return NULL;
2203
2204 if (ch1->refs.length () != ch2->refs.length ())
2205 return NULL;
2206
2207 for (i = 0; (ch1->refs.iterate (i, &r1)
2208 && ch2->refs.iterate (i, &r2)); i++)
2209 {
2210 if (r1->distance != r2->distance)
2211 return NULL;
2212
2213 if (!combinable_refs_p (r1, r2, &op, &swap, &rslt_type))
2214 return NULL;
2215 }
2216
2217 if (swap)
2218 {
2219 chain_p tmp = ch1;
2220 ch1 = ch2;
2221 ch2 = tmp;
2222 }
2223
2224 new_chain = XCNEW (struct chain);
2225 new_chain->type = CT_COMBINATION;
2226 new_chain->op = op;
2227 new_chain->ch1 = ch1;
2228 new_chain->ch2 = ch2;
2229 new_chain->rslt_type = rslt_type;
2230 new_chain->length = ch1->length;
2231
2232 for (i = 0; (ch1->refs.iterate (i, &r1)
2233 && ch2->refs.iterate (i, &r2)); i++)
2234 {
2235 nw = XCNEW (struct dref_d);
2236 nw->stmt = stmt_combining_refs (r1, r2);
2237 nw->distance = r1->distance;
2238
2239 new_chain->refs.safe_push (nw);
2240 }
2241
2242 new_chain->has_max_use_after = false;
2243 root_stmt = get_chain_root (new_chain)->stmt;
2244 for (i = 1; new_chain->refs.iterate (i, &nw); i++)
2245 {
2246 if (nw->distance == new_chain->length
2247 && !stmt_dominates_stmt_p (nw->stmt, root_stmt))
2248 {
2249 new_chain->has_max_use_after = true;
2250 break;
2251 }
2252 }
2253
2254 ch1->combined = true;
2255 ch2->combined = true;
2256 return new_chain;
2257 }
2258
2259 /* Try to combine the CHAINS. */
2260
2261 static void
2262 try_combine_chains (vec<chain_p> *chains)
2263 {
2264 unsigned i, j;
2265 chain_p ch1, ch2, cch;
2266 vec<chain_p> worklist = vNULL;
2267
2268 FOR_EACH_VEC_ELT (*chains, i, ch1)
2269 if (chain_can_be_combined_p (ch1))
2270 worklist.safe_push (ch1);
2271
2272 while (!worklist.is_empty ())
2273 {
2274 ch1 = worklist.pop ();
2275 if (!chain_can_be_combined_p (ch1))
2276 continue;
2277
2278 FOR_EACH_VEC_ELT (*chains, j, ch2)
2279 {
2280 if (!chain_can_be_combined_p (ch2))
2281 continue;
2282
2283 cch = combine_chains (ch1, ch2);
2284 if (cch)
2285 {
2286 worklist.safe_push (cch);
2287 chains->safe_push (cch);
2288 break;
2289 }
2290 }
2291 }
2292
2293 worklist.release ();
2294 }
2295
2296 /* Prepare initializers for CHAIN in LOOP. Returns false if this is
2297 impossible because one of these initializers may trap, true otherwise. */
2298
2299 static bool
2300 prepare_initializers_chain (struct loop *loop, chain_p chain)
2301 {
2302 unsigned i, n = (chain->type == CT_INVARIANT) ? 1 : chain->length;
2303 struct data_reference *dr = get_chain_root (chain)->ref;
2304 tree init;
2305 gimple_seq stmts;
2306 dref laref;
2307 edge entry = loop_preheader_edge (loop);
2308
2309 /* Find the initializers for the variables, and check that they cannot
2310 trap. */
2311 chain->inits.create (n);
2312 for (i = 0; i < n; i++)
2313 chain->inits.quick_push (NULL_TREE);
2314
2315 /* If we have replaced some looparound phi nodes, use their initializers
2316 instead of creating our own. */
2317 FOR_EACH_VEC_ELT (chain->refs, i, laref)
2318 {
2319 if (gimple_code (laref->stmt) != GIMPLE_PHI)
2320 continue;
2321
2322 gcc_assert (laref->distance > 0);
2323 chain->inits[n - laref->distance]
2324 = PHI_ARG_DEF_FROM_EDGE (laref->stmt, entry);
2325 }
2326
2327 for (i = 0; i < n; i++)
2328 {
2329 if (chain->inits[i] != NULL_TREE)
2330 continue;
2331
2332 init = ref_at_iteration (dr, (int) i - n, &stmts);
2333 if (!chain->all_always_accessed && tree_could_trap_p (init))
2334 return false;
2335
2336 if (stmts)
2337 gsi_insert_seq_on_edge_immediate (entry, stmts);
2338
2339 chain->inits[i] = init;
2340 }
2341
2342 return true;
2343 }
2344
2345 /* Prepare initializers for CHAINS in LOOP, and free chains that cannot
2346 be used because the initializers might trap. */
2347
2348 static void
2349 prepare_initializers (struct loop *loop, vec<chain_p> chains)
2350 {
2351 chain_p chain;
2352 unsigned i;
2353
2354 for (i = 0; i < chains.length (); )
2355 {
2356 chain = chains[i];
2357 if (prepare_initializers_chain (loop, chain))
2358 i++;
2359 else
2360 {
2361 release_chain (chain);
2362 chains.unordered_remove (i);
2363 }
2364 }
2365 }
2366
2367 /* Performs predictive commoning for LOOP. Returns true if LOOP was
2368 unrolled. */
2369
2370 static bool
2371 tree_predictive_commoning_loop (struct loop *loop)
2372 {
2373 vec<data_reference_p> datarefs;
2374 vec<ddr_p> dependences;
2375 struct component *components;
2376 vec<chain_p> chains = vNULL;
2377 unsigned unroll_factor;
2378 struct tree_niter_desc desc;
2379 bool unroll = false;
2380 edge exit;
2381 bitmap tmp_vars;
2382
2383 if (dump_file && (dump_flags & TDF_DETAILS))
2384 fprintf (dump_file, "Processing loop %d\n", loop->num);
2385
2386 /* Find the data references and split them into components according to their
2387 dependence relations. */
2388 stack_vec<loop_p, 3> loop_nest;
2389 dependences.create (10);
2390 datarefs.create (10);
2391 if (! compute_data_dependences_for_loop (loop, true, &loop_nest, &datarefs,
2392 &dependences))
2393 {
2394 if (dump_file && (dump_flags & TDF_DETAILS))
2395 fprintf (dump_file, "Cannot analyze data dependencies\n");
2396 free_data_refs (datarefs);
2397 free_dependence_relations (dependences);
2398 return false;
2399 }
2400
2401 if (dump_file && (dump_flags & TDF_DETAILS))
2402 dump_data_dependence_relations (dump_file, dependences);
2403
2404 components = split_data_refs_to_components (loop, datarefs, dependences);
2405 loop_nest.release ();
2406 free_dependence_relations (dependences);
2407 if (!components)
2408 {
2409 free_data_refs (datarefs);
2410 return false;
2411 }
2412
2413 if (dump_file && (dump_flags & TDF_DETAILS))
2414 {
2415 fprintf (dump_file, "Initial state:\n\n");
2416 dump_components (dump_file, components);
2417 }
2418
2419 /* Find the suitable components and split them into chains. */
2420 components = filter_suitable_components (loop, components);
2421
2422 tmp_vars = BITMAP_ALLOC (NULL);
2423 looparound_phis = BITMAP_ALLOC (NULL);
2424 determine_roots (loop, components, &chains);
2425 release_components (components);
2426
2427 if (!chains.exists ())
2428 {
2429 if (dump_file && (dump_flags & TDF_DETAILS))
2430 fprintf (dump_file,
2431 "Predictive commoning failed: no suitable chains\n");
2432 goto end;
2433 }
2434 prepare_initializers (loop, chains);
2435
2436 /* Try to combine the chains that are always worked with together. */
2437 try_combine_chains (&chains);
2438
2439 if (dump_file && (dump_flags & TDF_DETAILS))
2440 {
2441 fprintf (dump_file, "Before commoning:\n\n");
2442 dump_chains (dump_file, chains);
2443 }
2444
2445 /* Determine the unroll factor, and if the loop should be unrolled, ensure
2446 that its number of iterations is divisible by the factor. */
2447 unroll_factor = determine_unroll_factor (chains);
2448 scev_reset ();
2449 unroll = (unroll_factor > 1
2450 && can_unroll_loop_p (loop, unroll_factor, &desc));
2451 exit = single_dom_exit (loop);
2452
2453 /* Execute the predictive commoning transformations, and possibly unroll the
2454 loop. */
2455 if (unroll)
2456 {
2457 struct epcc_data dta;
2458
2459 if (dump_file && (dump_flags & TDF_DETAILS))
2460 fprintf (dump_file, "Unrolling %u times.\n", unroll_factor);
2461
2462 dta.chains = chains;
2463 dta.tmp_vars = tmp_vars;
2464
2465 update_ssa (TODO_update_ssa_only_virtuals);
2466
2467 /* Cfg manipulations performed in tree_transform_and_unroll_loop before
2468 execute_pred_commoning_cbck is called may cause phi nodes to be
2469 reallocated, which is a problem since CHAINS may point to these
2470 statements. To fix this, we store the ssa names defined by the
2471 phi nodes here instead of the phi nodes themselves, and restore
2472 the phi nodes in execute_pred_commoning_cbck. A bit hacky. */
2473 replace_phis_by_defined_names (chains);
2474
2475 tree_transform_and_unroll_loop (loop, unroll_factor, exit, &desc,
2476 execute_pred_commoning_cbck, &dta);
2477 eliminate_temp_copies (loop, tmp_vars);
2478 }
2479 else
2480 {
2481 if (dump_file && (dump_flags & TDF_DETAILS))
2482 fprintf (dump_file,
2483 "Executing predictive commoning without unrolling.\n");
2484 execute_pred_commoning (loop, chains, tmp_vars);
2485 }
2486
2487 end: ;
2488 release_chains (chains);
2489 free_data_refs (datarefs);
2490 BITMAP_FREE (tmp_vars);
2491 BITMAP_FREE (looparound_phis);
2492
2493 free_affine_expand_cache (&name_expansions);
2494
2495 return unroll;
2496 }
2497
2498 /* Runs predictive commoning. */
2499
2500 unsigned
2501 tree_predictive_commoning (void)
2502 {
2503 bool unrolled = false;
2504 struct loop *loop;
2505 loop_iterator li;
2506 unsigned ret = 0;
2507
2508 initialize_original_copy_tables ();
2509 FOR_EACH_LOOP (li, loop, LI_ONLY_INNERMOST)
2510 if (optimize_loop_for_speed_p (loop))
2511 {
2512 unrolled |= tree_predictive_commoning_loop (loop);
2513 }
2514
2515 if (unrolled)
2516 {
2517 scev_reset ();
2518 ret = TODO_cleanup_cfg;
2519 }
2520 free_original_copy_tables ();
2521
2522 return ret;
2523 }
2524
2525 /* Predictive commoning Pass. */
2526
2527 static unsigned
2528 run_tree_predictive_commoning (void)
2529 {
2530 if (!current_loops)
2531 return 0;
2532
2533 return tree_predictive_commoning ();
2534 }
2535
2536 static bool
2537 gate_tree_predictive_commoning (void)
2538 {
2539 return flag_predictive_commoning != 0;
2540 }
2541
2542 namespace {
2543
2544 const pass_data pass_data_predcom =
2545 {
2546 GIMPLE_PASS, /* type */
2547 "pcom", /* name */
2548 OPTGROUP_LOOP, /* optinfo_flags */
2549 true, /* has_gate */
2550 true, /* has_execute */
2551 TV_PREDCOM, /* tv_id */
2552 PROP_cfg, /* properties_required */
2553 0, /* properties_provided */
2554 0, /* properties_destroyed */
2555 0, /* todo_flags_start */
2556 TODO_update_ssa_only_virtuals, /* todo_flags_finish */
2557 };
2558
2559 class pass_predcom : public gimple_opt_pass
2560 {
2561 public:
2562 pass_predcom (gcc::context *ctxt)
2563 : gimple_opt_pass (pass_data_predcom, ctxt)
2564 {}
2565
2566 /* opt_pass methods: */
2567 bool gate () { return gate_tree_predictive_commoning (); }
2568 unsigned int execute () { return run_tree_predictive_commoning (); }
2569
2570 }; // class pass_predcom
2571
2572 } // anon namespace
2573
2574 gimple_opt_pass *
2575 make_pass_predcom (gcc::context *ctxt)
2576 {
2577 return new pass_predcom (ctxt);
2578 }
2579
2580