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