PR rtl-optimization/82913
[official-gcc.git] / gcc / tree-loop-distribution.c
blob52db3c94bd9563d89a1ea65e5e621d59065b8f8c
1 /* Loop distribution.
2 Copyright (C) 2006-2017 Free Software Foundation, Inc.
3 Contributed by Georges-Andre Silber <Georges-Andre.Silber@ensmp.fr>
4 and Sebastian Pop <sebastian.pop@amd.com>.
6 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation; either version 3, or (at your option) any
11 later version.
13 GCC is distributed in the hope that it will be useful, but WITHOUT
14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 for more details.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
22 /* This pass performs loop distribution: for example, the loop
24 |DO I = 2, N
25 | A(I) = B(I) + C
26 | D(I) = A(I-1)*E
27 |ENDDO
29 is transformed to
31 |DOALL I = 2, N
32 | A(I) = B(I) + C
33 |ENDDO
35 |DOALL I = 2, N
36 | D(I) = A(I-1)*E
37 |ENDDO
39 Loop distribution is the dual of loop fusion. It separates statements
40 of a loop (or loop nest) into multiple loops (or loop nests) with the
41 same loop header. The major goal is to separate statements which may
42 be vectorized from those that can't. This pass implements distribution
43 in the following steps:
45 1) Seed partitions with specific type statements. For now we support
46 two types seed statements: statement defining variable used outside
47 of loop; statement storing to memory.
48 2) Build reduced dependence graph (RDG) for loop to be distributed.
49 The vertices (RDG:V) model all statements in the loop and the edges
50 (RDG:E) model flow and control dependencies between statements.
51 3) Apart from RDG, compute data dependencies between memory references.
52 4) Starting from seed statement, build up partition by adding depended
53 statements according to RDG's dependence information. Partition is
54 classified as parallel type if it can be executed paralleled; or as
55 sequential type if it can't. Parallel type partition is further
56 classified as different builtin kinds if it can be implemented as
57 builtin function calls.
58 5) Build partition dependence graph (PG) based on data dependencies.
59 The vertices (PG:V) model all partitions and the edges (PG:E) model
60 all data dependencies between every partitions pair. In general,
61 data dependence is either compilation time known or unknown. In C
62 family languages, there exists quite amount compilation time unknown
63 dependencies because of possible alias relation of data references.
64 We categorize PG's edge to two types: "true" edge that represents
65 compilation time known data dependencies; "alias" edge for all other
66 data dependencies.
67 6) Traverse subgraph of PG as if all "alias" edges don't exist. Merge
68 partitions in each strong connected component (SCC) correspondingly.
69 Build new PG for merged partitions.
70 7) Traverse PG again and this time with both "true" and "alias" edges
71 included. We try to break SCCs by removing some edges. Because
72 SCCs by "true" edges are all fused in step 6), we can break SCCs
73 by removing some "alias" edges. It's NP-hard to choose optimal
74 edge set, fortunately simple approximation is good enough for us
75 given the small problem scale.
76 8) Collect all data dependencies of the removed "alias" edges. Create
77 runtime alias checks for collected data dependencies.
78 9) Version loop under the condition of runtime alias checks. Given
79 loop distribution generally introduces additional overhead, it is
80 only useful if vectorization is achieved in distributed loop. We
81 version loop with internal function call IFN_LOOP_DIST_ALIAS. If
82 no distributed loop can be vectorized, we simply remove distributed
83 loops and recover to the original one.
85 TODO:
86 1) We only distribute innermost two-level loop nest now. We should
87 extend it for arbitrary loop nests in the future.
88 2) We only fuse partitions in SCC now. A better fusion algorithm is
89 desired to minimize loop overhead, maximize parallelism and maximize
90 data reuse. */
92 #include "config.h"
93 #define INCLUDE_ALGORITHM /* stable_sort */
94 #include "system.h"
95 #include "coretypes.h"
96 #include "backend.h"
97 #include "tree.h"
98 #include "gimple.h"
99 #include "cfghooks.h"
100 #include "tree-pass.h"
101 #include "ssa.h"
102 #include "gimple-pretty-print.h"
103 #include "fold-const.h"
104 #include "cfganal.h"
105 #include "gimple-iterator.h"
106 #include "gimplify-me.h"
107 #include "stor-layout.h"
108 #include "tree-cfg.h"
109 #include "tree-ssa-loop-manip.h"
110 #include "tree-ssa-loop-ivopts.h"
111 #include "tree-ssa-loop.h"
112 #include "tree-into-ssa.h"
113 #include "tree-ssa.h"
114 #include "cfgloop.h"
115 #include "tree-scalar-evolution.h"
116 #include "params.h"
117 #include "tree-vectorizer.h"
120 #define MAX_DATAREFS_NUM \
121 ((unsigned) PARAM_VALUE (PARAM_LOOP_MAX_DATAREFS_FOR_DATADEPS))
123 /* Threshold controlling number of distributed partitions. Given it may
124 be unnecessary if a memory stream cost model is invented in the future,
125 we define it as a temporary macro, rather than a parameter. */
126 #define NUM_PARTITION_THRESHOLD (4)
128 /* Hashtable helpers. */
130 struct ddr_hasher : nofree_ptr_hash <struct data_dependence_relation>
132 static inline hashval_t hash (const data_dependence_relation *);
133 static inline bool equal (const data_dependence_relation *,
134 const data_dependence_relation *);
137 /* Hash function for data dependence. */
139 inline hashval_t
140 ddr_hasher::hash (const data_dependence_relation *ddr)
142 inchash::hash h;
143 h.add_ptr (DDR_A (ddr));
144 h.add_ptr (DDR_B (ddr));
145 return h.end ();
148 /* Hash table equality function for data dependence. */
150 inline bool
151 ddr_hasher::equal (const data_dependence_relation *ddr1,
152 const data_dependence_relation *ddr2)
154 return (DDR_A (ddr1) == DDR_A (ddr2) && DDR_B (ddr1) == DDR_B (ddr2));
157 /* The loop (nest) to be distributed. */
158 static vec<loop_p> loop_nest;
160 /* Vector of data references in the loop to be distributed. */
161 static vec<data_reference_p> datarefs_vec;
163 /* Store index of data reference in aux field. */
164 #define DR_INDEX(dr) ((uintptr_t) (dr)->aux)
166 /* Hash table for data dependence relation in the loop to be distributed. */
167 static hash_table<ddr_hasher> *ddrs_table;
169 /* A Reduced Dependence Graph (RDG) vertex representing a statement. */
170 struct rdg_vertex
172 /* The statement represented by this vertex. */
173 gimple *stmt;
175 /* Vector of data-references in this statement. */
176 vec<data_reference_p> datarefs;
178 /* True when the statement contains a write to memory. */
179 bool has_mem_write;
181 /* True when the statement contains a read from memory. */
182 bool has_mem_reads;
185 #define RDGV_STMT(V) ((struct rdg_vertex *) ((V)->data))->stmt
186 #define RDGV_DATAREFS(V) ((struct rdg_vertex *) ((V)->data))->datarefs
187 #define RDGV_HAS_MEM_WRITE(V) ((struct rdg_vertex *) ((V)->data))->has_mem_write
188 #define RDGV_HAS_MEM_READS(V) ((struct rdg_vertex *) ((V)->data))->has_mem_reads
189 #define RDG_STMT(RDG, I) RDGV_STMT (&(RDG->vertices[I]))
190 #define RDG_DATAREFS(RDG, I) RDGV_DATAREFS (&(RDG->vertices[I]))
191 #define RDG_MEM_WRITE_STMT(RDG, I) RDGV_HAS_MEM_WRITE (&(RDG->vertices[I]))
192 #define RDG_MEM_READS_STMT(RDG, I) RDGV_HAS_MEM_READS (&(RDG->vertices[I]))
194 /* Data dependence type. */
196 enum rdg_dep_type
198 /* Read After Write (RAW). */
199 flow_dd = 'f',
201 /* Control dependence (execute conditional on). */
202 control_dd = 'c'
205 /* Dependence information attached to an edge of the RDG. */
207 struct rdg_edge
209 /* Type of the dependence. */
210 enum rdg_dep_type type;
213 #define RDGE_TYPE(E) ((struct rdg_edge *) ((E)->data))->type
215 /* Dump vertex I in RDG to FILE. */
217 static void
218 dump_rdg_vertex (FILE *file, struct graph *rdg, int i)
220 struct vertex *v = &(rdg->vertices[i]);
221 struct graph_edge *e;
223 fprintf (file, "(vertex %d: (%s%s) (in:", i,
224 RDG_MEM_WRITE_STMT (rdg, i) ? "w" : "",
225 RDG_MEM_READS_STMT (rdg, i) ? "r" : "");
227 if (v->pred)
228 for (e = v->pred; e; e = e->pred_next)
229 fprintf (file, " %d", e->src);
231 fprintf (file, ") (out:");
233 if (v->succ)
234 for (e = v->succ; e; e = e->succ_next)
235 fprintf (file, " %d", e->dest);
237 fprintf (file, ")\n");
238 print_gimple_stmt (file, RDGV_STMT (v), 0, TDF_VOPS|TDF_MEMSYMS);
239 fprintf (file, ")\n");
242 /* Call dump_rdg_vertex on stderr. */
244 DEBUG_FUNCTION void
245 debug_rdg_vertex (struct graph *rdg, int i)
247 dump_rdg_vertex (stderr, rdg, i);
250 /* Dump the reduced dependence graph RDG to FILE. */
252 static void
253 dump_rdg (FILE *file, struct graph *rdg)
255 fprintf (file, "(rdg\n");
256 for (int i = 0; i < rdg->n_vertices; i++)
257 dump_rdg_vertex (file, rdg, i);
258 fprintf (file, ")\n");
261 /* Call dump_rdg on stderr. */
263 DEBUG_FUNCTION void
264 debug_rdg (struct graph *rdg)
266 dump_rdg (stderr, rdg);
269 static void
270 dot_rdg_1 (FILE *file, struct graph *rdg)
272 int i;
273 pretty_printer buffer;
274 pp_needs_newline (&buffer) = false;
275 buffer.buffer->stream = file;
277 fprintf (file, "digraph RDG {\n");
279 for (i = 0; i < rdg->n_vertices; i++)
281 struct vertex *v = &(rdg->vertices[i]);
282 struct graph_edge *e;
284 fprintf (file, "%d [label=\"[%d] ", i, i);
285 pp_gimple_stmt_1 (&buffer, RDGV_STMT (v), 0, TDF_SLIM);
286 pp_flush (&buffer);
287 fprintf (file, "\"]\n");
289 /* Highlight reads from memory. */
290 if (RDG_MEM_READS_STMT (rdg, i))
291 fprintf (file, "%d [style=filled, fillcolor=green]\n", i);
293 /* Highlight stores to memory. */
294 if (RDG_MEM_WRITE_STMT (rdg, i))
295 fprintf (file, "%d [style=filled, fillcolor=red]\n", i);
297 if (v->succ)
298 for (e = v->succ; e; e = e->succ_next)
299 switch (RDGE_TYPE (e))
301 case flow_dd:
302 /* These are the most common dependences: don't print these. */
303 fprintf (file, "%d -> %d \n", i, e->dest);
304 break;
306 case control_dd:
307 fprintf (file, "%d -> %d [label=control] \n", i, e->dest);
308 break;
310 default:
311 gcc_unreachable ();
315 fprintf (file, "}\n\n");
318 /* Display the Reduced Dependence Graph using dotty. */
320 DEBUG_FUNCTION void
321 dot_rdg (struct graph *rdg)
323 /* When debugging, you may want to enable the following code. */
324 #ifdef HAVE_POPEN
325 FILE *file = popen ("dot -Tx11", "w");
326 if (!file)
327 return;
328 dot_rdg_1 (file, rdg);
329 fflush (file);
330 close (fileno (file));
331 pclose (file);
332 #else
333 dot_rdg_1 (stderr, rdg);
334 #endif
337 /* Returns the index of STMT in RDG. */
339 static int
340 rdg_vertex_for_stmt (struct graph *rdg ATTRIBUTE_UNUSED, gimple *stmt)
342 int index = gimple_uid (stmt);
343 gcc_checking_assert (index == -1 || RDG_STMT (rdg, index) == stmt);
344 return index;
347 /* Creates dependence edges in RDG for all the uses of DEF. IDEF is
348 the index of DEF in RDG. */
350 static void
351 create_rdg_edges_for_scalar (struct graph *rdg, tree def, int idef)
353 use_operand_p imm_use_p;
354 imm_use_iterator iterator;
356 FOR_EACH_IMM_USE_FAST (imm_use_p, iterator, def)
358 struct graph_edge *e;
359 int use = rdg_vertex_for_stmt (rdg, USE_STMT (imm_use_p));
361 if (use < 0)
362 continue;
364 e = add_edge (rdg, idef, use);
365 e->data = XNEW (struct rdg_edge);
366 RDGE_TYPE (e) = flow_dd;
370 /* Creates an edge for the control dependences of BB to the vertex V. */
372 static void
373 create_edge_for_control_dependence (struct graph *rdg, basic_block bb,
374 int v, control_dependences *cd)
376 bitmap_iterator bi;
377 unsigned edge_n;
378 EXECUTE_IF_SET_IN_BITMAP (cd->get_edges_dependent_on (bb->index),
379 0, edge_n, bi)
381 basic_block cond_bb = cd->get_edge_src (edge_n);
382 gimple *stmt = last_stmt (cond_bb);
383 if (stmt && is_ctrl_stmt (stmt))
385 struct graph_edge *e;
386 int c = rdg_vertex_for_stmt (rdg, stmt);
387 if (c < 0)
388 continue;
390 e = add_edge (rdg, c, v);
391 e->data = XNEW (struct rdg_edge);
392 RDGE_TYPE (e) = control_dd;
397 /* Creates the edges of the reduced dependence graph RDG. */
399 static void
400 create_rdg_flow_edges (struct graph *rdg)
402 int i;
403 def_operand_p def_p;
404 ssa_op_iter iter;
406 for (i = 0; i < rdg->n_vertices; i++)
407 FOR_EACH_PHI_OR_STMT_DEF (def_p, RDG_STMT (rdg, i),
408 iter, SSA_OP_DEF)
409 create_rdg_edges_for_scalar (rdg, DEF_FROM_PTR (def_p), i);
412 /* Creates the edges of the reduced dependence graph RDG. */
414 static void
415 create_rdg_cd_edges (struct graph *rdg, control_dependences *cd, loop_p loop)
417 int i;
419 for (i = 0; i < rdg->n_vertices; i++)
421 gimple *stmt = RDG_STMT (rdg, i);
422 if (gimple_code (stmt) == GIMPLE_PHI)
424 edge_iterator ei;
425 edge e;
426 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->preds)
427 if (flow_bb_inside_loop_p (loop, e->src))
428 create_edge_for_control_dependence (rdg, e->src, i, cd);
430 else
431 create_edge_for_control_dependence (rdg, gimple_bb (stmt), i, cd);
435 /* Build the vertices of the reduced dependence graph RDG. Return false
436 if that failed. */
438 static bool
439 create_rdg_vertices (struct graph *rdg, vec<gimple *> stmts, loop_p loop)
441 int i;
442 gimple *stmt;
444 FOR_EACH_VEC_ELT (stmts, i, stmt)
446 struct vertex *v = &(rdg->vertices[i]);
448 /* Record statement to vertex mapping. */
449 gimple_set_uid (stmt, i);
451 v->data = XNEW (struct rdg_vertex);
452 RDGV_STMT (v) = stmt;
453 RDGV_DATAREFS (v).create (0);
454 RDGV_HAS_MEM_WRITE (v) = false;
455 RDGV_HAS_MEM_READS (v) = false;
456 if (gimple_code (stmt) == GIMPLE_PHI)
457 continue;
459 unsigned drp = datarefs_vec.length ();
460 if (!find_data_references_in_stmt (loop, stmt, &datarefs_vec))
461 return false;
462 for (unsigned j = drp; j < datarefs_vec.length (); ++j)
464 data_reference_p dr = datarefs_vec[j];
465 if (DR_IS_READ (dr))
466 RDGV_HAS_MEM_READS (v) = true;
467 else
468 RDGV_HAS_MEM_WRITE (v) = true;
469 RDGV_DATAREFS (v).safe_push (dr);
472 return true;
475 /* Array mapping basic block's index to its topological order. */
476 static int *bb_top_order_index;
477 /* And size of the array. */
478 static int bb_top_order_index_size;
480 /* If X has a smaller topological sort number than Y, returns -1;
481 if greater, returns 1. */
483 static int
484 bb_top_order_cmp (const void *x, const void *y)
486 basic_block bb1 = *(const basic_block *) x;
487 basic_block bb2 = *(const basic_block *) y;
489 gcc_assert (bb1->index < bb_top_order_index_size
490 && bb2->index < bb_top_order_index_size);
491 gcc_assert (bb1 == bb2
492 || bb_top_order_index[bb1->index]
493 != bb_top_order_index[bb2->index]);
495 return (bb_top_order_index[bb1->index] - bb_top_order_index[bb2->index]);
498 /* Initialize STMTS with all the statements of LOOP. We use topological
499 order to discover all statements. The order is important because
500 generate_loops_for_partition is using the same traversal for identifying
501 statements in loop copies. */
503 static void
504 stmts_from_loop (struct loop *loop, vec<gimple *> *stmts)
506 unsigned int i;
507 basic_block *bbs = get_loop_body_in_custom_order (loop, bb_top_order_cmp);
509 for (i = 0; i < loop->num_nodes; i++)
511 basic_block bb = bbs[i];
513 for (gphi_iterator bsi = gsi_start_phis (bb); !gsi_end_p (bsi);
514 gsi_next (&bsi))
515 if (!virtual_operand_p (gimple_phi_result (bsi.phi ())))
516 stmts->safe_push (bsi.phi ());
518 for (gimple_stmt_iterator bsi = gsi_start_bb (bb); !gsi_end_p (bsi);
519 gsi_next (&bsi))
521 gimple *stmt = gsi_stmt (bsi);
522 if (gimple_code (stmt) != GIMPLE_LABEL && !is_gimple_debug (stmt))
523 stmts->safe_push (stmt);
527 free (bbs);
530 /* Free the reduced dependence graph RDG. */
532 static void
533 free_rdg (struct graph *rdg)
535 int i;
537 for (i = 0; i < rdg->n_vertices; i++)
539 struct vertex *v = &(rdg->vertices[i]);
540 struct graph_edge *e;
542 for (e = v->succ; e; e = e->succ_next)
543 free (e->data);
545 if (v->data)
547 gimple_set_uid (RDGV_STMT (v), -1);
548 (RDGV_DATAREFS (v)).release ();
549 free (v->data);
553 free_graph (rdg);
556 /* Build the Reduced Dependence Graph (RDG) with one vertex per statement of
557 LOOP, and one edge per flow dependence or control dependence from control
558 dependence CD. During visiting each statement, data references are also
559 collected and recorded in global data DATAREFS_VEC. */
561 static struct graph *
562 build_rdg (struct loop *loop, control_dependences *cd)
564 struct graph *rdg;
566 /* Create the RDG vertices from the stmts of the loop nest. */
567 auto_vec<gimple *, 10> stmts;
568 stmts_from_loop (loop, &stmts);
569 rdg = new_graph (stmts.length ());
570 if (!create_rdg_vertices (rdg, stmts, loop))
572 free_rdg (rdg);
573 return NULL;
575 stmts.release ();
577 create_rdg_flow_edges (rdg);
578 if (cd)
579 create_rdg_cd_edges (rdg, cd, loop);
581 return rdg;
585 /* Kind of distributed loop. */
586 enum partition_kind {
587 PKIND_NORMAL, PKIND_MEMSET, PKIND_MEMCPY, PKIND_MEMMOVE
590 /* Type of distributed loop. */
591 enum partition_type {
592 /* The distributed loop can be executed parallelly. */
593 PTYPE_PARALLEL = 0,
594 /* The distributed loop has to be executed sequentially. */
595 PTYPE_SEQUENTIAL
598 /* Builtin info for loop distribution. */
599 struct builtin_info
601 /* data-references a kind != PKIND_NORMAL partition is about. */
602 data_reference_p dst_dr;
603 data_reference_p src_dr;
604 /* Base address and size of memory objects operated by the builtin. Note
605 both dest and source memory objects must have the same size. */
606 tree dst_base;
607 tree src_base;
608 tree size;
609 /* Base and offset part of dst_base after stripping constant offset. This
610 is only used in memset builtin distribution for now. */
611 tree dst_base_base;
612 unsigned HOST_WIDE_INT dst_base_offset;
615 /* Partition for loop distribution. */
616 struct partition
618 /* Statements of the partition. */
619 bitmap stmts;
620 /* True if the partition defines variable which is used outside of loop. */
621 bool reduction_p;
622 enum partition_kind kind;
623 enum partition_type type;
624 /* Data references in the partition. */
625 bitmap datarefs;
626 /* Information of builtin parition. */
627 struct builtin_info *builtin;
631 /* Allocate and initialize a partition from BITMAP. */
633 static partition *
634 partition_alloc (void)
636 partition *partition = XCNEW (struct partition);
637 partition->stmts = BITMAP_ALLOC (NULL);
638 partition->reduction_p = false;
639 partition->kind = PKIND_NORMAL;
640 partition->datarefs = BITMAP_ALLOC (NULL);
641 return partition;
644 /* Free PARTITION. */
646 static void
647 partition_free (partition *partition)
649 BITMAP_FREE (partition->stmts);
650 BITMAP_FREE (partition->datarefs);
651 if (partition->builtin)
652 free (partition->builtin);
654 free (partition);
657 /* Returns true if the partition can be generated as a builtin. */
659 static bool
660 partition_builtin_p (partition *partition)
662 return partition->kind != PKIND_NORMAL;
665 /* Returns true if the partition contains a reduction. */
667 static bool
668 partition_reduction_p (partition *partition)
670 return partition->reduction_p;
673 /* Partitions are fused because of different reasons. */
674 enum fuse_type
676 FUSE_NON_BUILTIN = 0,
677 FUSE_REDUCTION = 1,
678 FUSE_SHARE_REF = 2,
679 FUSE_SAME_SCC = 3,
680 FUSE_FINALIZE = 4
683 /* Description on different fusing reason. */
684 static const char *fuse_message[] = {
685 "they are non-builtins",
686 "they have reductions",
687 "they have shared memory refs",
688 "they are in the same dependence scc",
689 "there is no point to distribute loop"};
691 static void
692 update_type_for_merge (struct graph *, partition *, partition *);
694 /* Merge PARTITION into the partition DEST. RDG is the reduced dependence
695 graph and we update type for result partition if it is non-NULL. */
697 static void
698 partition_merge_into (struct graph *rdg, partition *dest,
699 partition *partition, enum fuse_type ft)
701 if (dump_file && (dump_flags & TDF_DETAILS))
703 fprintf (dump_file, "Fuse partitions because %s:\n", fuse_message[ft]);
704 fprintf (dump_file, " Part 1: ");
705 dump_bitmap (dump_file, dest->stmts);
706 fprintf (dump_file, " Part 2: ");
707 dump_bitmap (dump_file, partition->stmts);
710 dest->kind = PKIND_NORMAL;
711 if (dest->type == PTYPE_PARALLEL)
712 dest->type = partition->type;
714 bitmap_ior_into (dest->stmts, partition->stmts);
715 if (partition_reduction_p (partition))
716 dest->reduction_p = true;
718 /* Further check if any data dependence prevents us from executing the
719 new partition parallelly. */
720 if (dest->type == PTYPE_PARALLEL && rdg != NULL)
721 update_type_for_merge (rdg, dest, partition);
723 bitmap_ior_into (dest->datarefs, partition->datarefs);
727 /* Returns true when DEF is an SSA_NAME defined in LOOP and used after
728 the LOOP. */
730 static bool
731 ssa_name_has_uses_outside_loop_p (tree def, loop_p loop)
733 imm_use_iterator imm_iter;
734 use_operand_p use_p;
736 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, def)
738 if (is_gimple_debug (USE_STMT (use_p)))
739 continue;
741 basic_block use_bb = gimple_bb (USE_STMT (use_p));
742 if (!flow_bb_inside_loop_p (loop, use_bb))
743 return true;
746 return false;
749 /* Returns true when STMT defines a scalar variable used after the
750 loop LOOP. */
752 static bool
753 stmt_has_scalar_dependences_outside_loop (loop_p loop, gimple *stmt)
755 def_operand_p def_p;
756 ssa_op_iter op_iter;
758 if (gimple_code (stmt) == GIMPLE_PHI)
759 return ssa_name_has_uses_outside_loop_p (gimple_phi_result (stmt), loop);
761 FOR_EACH_SSA_DEF_OPERAND (def_p, stmt, op_iter, SSA_OP_DEF)
762 if (ssa_name_has_uses_outside_loop_p (DEF_FROM_PTR (def_p), loop))
763 return true;
765 return false;
768 /* Return a copy of LOOP placed before LOOP. */
770 static struct loop *
771 copy_loop_before (struct loop *loop)
773 struct loop *res;
774 edge preheader = loop_preheader_edge (loop);
776 initialize_original_copy_tables ();
777 res = slpeel_tree_duplicate_loop_to_edge_cfg (loop, NULL, preheader);
778 gcc_assert (res != NULL);
779 free_original_copy_tables ();
780 delete_update_ssa ();
782 return res;
785 /* Creates an empty basic block after LOOP. */
787 static void
788 create_bb_after_loop (struct loop *loop)
790 edge exit = single_exit (loop);
792 if (!exit)
793 return;
795 split_edge (exit);
798 /* Generate code for PARTITION from the code in LOOP. The loop is
799 copied when COPY_P is true. All the statements not flagged in the
800 PARTITION bitmap are removed from the loop or from its copy. The
801 statements are indexed in sequence inside a basic block, and the
802 basic blocks of a loop are taken in dom order. */
804 static void
805 generate_loops_for_partition (struct loop *loop, partition *partition,
806 bool copy_p)
808 unsigned i;
809 basic_block *bbs;
811 if (copy_p)
813 int orig_loop_num = loop->orig_loop_num;
814 loop = copy_loop_before (loop);
815 gcc_assert (loop != NULL);
816 loop->orig_loop_num = orig_loop_num;
817 create_preheader (loop, CP_SIMPLE_PREHEADERS);
818 create_bb_after_loop (loop);
820 else
822 /* Origin number is set to the new versioned loop's num. */
823 gcc_assert (loop->orig_loop_num != loop->num);
826 /* Remove stmts not in the PARTITION bitmap. */
827 bbs = get_loop_body_in_dom_order (loop);
829 if (MAY_HAVE_DEBUG_STMTS)
830 for (i = 0; i < loop->num_nodes; i++)
832 basic_block bb = bbs[i];
834 for (gphi_iterator bsi = gsi_start_phis (bb); !gsi_end_p (bsi);
835 gsi_next (&bsi))
837 gphi *phi = bsi.phi ();
838 if (!virtual_operand_p (gimple_phi_result (phi))
839 && !bitmap_bit_p (partition->stmts, gimple_uid (phi)))
840 reset_debug_uses (phi);
843 for (gimple_stmt_iterator bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
845 gimple *stmt = gsi_stmt (bsi);
846 if (gimple_code (stmt) != GIMPLE_LABEL
847 && !is_gimple_debug (stmt)
848 && !bitmap_bit_p (partition->stmts, gimple_uid (stmt)))
849 reset_debug_uses (stmt);
853 for (i = 0; i < loop->num_nodes; i++)
855 basic_block bb = bbs[i];
856 edge inner_exit = NULL;
858 if (loop != bb->loop_father)
859 inner_exit = single_exit (bb->loop_father);
861 for (gphi_iterator bsi = gsi_start_phis (bb); !gsi_end_p (bsi);)
863 gphi *phi = bsi.phi ();
864 if (!virtual_operand_p (gimple_phi_result (phi))
865 && !bitmap_bit_p (partition->stmts, gimple_uid (phi)))
866 remove_phi_node (&bsi, true);
867 else
868 gsi_next (&bsi);
871 for (gimple_stmt_iterator bsi = gsi_start_bb (bb); !gsi_end_p (bsi);)
873 gimple *stmt = gsi_stmt (bsi);
874 if (gimple_code (stmt) != GIMPLE_LABEL
875 && !is_gimple_debug (stmt)
876 && !bitmap_bit_p (partition->stmts, gimple_uid (stmt)))
878 /* In distribution of loop nest, if bb is inner loop's exit_bb,
879 we choose its exit edge/path in order to avoid generating
880 infinite loop. For all other cases, we choose an arbitrary
881 path through the empty CFG part that this unnecessary
882 control stmt controls. */
883 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
885 if (inner_exit && inner_exit->flags & EDGE_TRUE_VALUE)
886 gimple_cond_make_true (cond_stmt);
887 else
888 gimple_cond_make_false (cond_stmt);
889 update_stmt (stmt);
891 else if (gimple_code (stmt) == GIMPLE_SWITCH)
893 gswitch *switch_stmt = as_a <gswitch *> (stmt);
894 gimple_switch_set_index
895 (switch_stmt, CASE_LOW (gimple_switch_label (switch_stmt, 1)));
896 update_stmt (stmt);
898 else
900 unlink_stmt_vdef (stmt);
901 gsi_remove (&bsi, true);
902 release_defs (stmt);
903 continue;
906 gsi_next (&bsi);
910 free (bbs);
913 /* If VAL memory representation contains the same value in all bytes,
914 return that value, otherwise return -1.
915 E.g. for 0x24242424 return 0x24, for IEEE double
916 747708026454360457216.0 return 0x44, etc. */
918 static int
919 const_with_all_bytes_same (tree val)
921 unsigned char buf[64];
922 int i, len;
924 if (integer_zerop (val)
925 || (TREE_CODE (val) == CONSTRUCTOR
926 && !TREE_CLOBBER_P (val)
927 && CONSTRUCTOR_NELTS (val) == 0))
928 return 0;
930 if (real_zerop (val))
932 /* Only return 0 for +0.0, not for -0.0, which doesn't have
933 an all bytes same memory representation. Don't transform
934 -0.0 stores into +0.0 even for !HONOR_SIGNED_ZEROS. */
935 switch (TREE_CODE (val))
937 case REAL_CST:
938 if (!real_isneg (TREE_REAL_CST_PTR (val)))
939 return 0;
940 break;
941 case COMPLEX_CST:
942 if (!const_with_all_bytes_same (TREE_REALPART (val))
943 && !const_with_all_bytes_same (TREE_IMAGPART (val)))
944 return 0;
945 break;
946 case VECTOR_CST:
947 unsigned int j;
948 for (j = 0; j < VECTOR_CST_NELTS (val); ++j)
949 if (const_with_all_bytes_same (VECTOR_CST_ELT (val, j)))
950 break;
951 if (j == VECTOR_CST_NELTS (val))
952 return 0;
953 break;
954 default:
955 break;
959 if (CHAR_BIT != 8 || BITS_PER_UNIT != 8)
960 return -1;
962 len = native_encode_expr (val, buf, sizeof (buf));
963 if (len == 0)
964 return -1;
965 for (i = 1; i < len; i++)
966 if (buf[i] != buf[0])
967 return -1;
968 return buf[0];
971 /* Generate a call to memset for PARTITION in LOOP. */
973 static void
974 generate_memset_builtin (struct loop *loop, partition *partition)
976 gimple_stmt_iterator gsi;
977 tree mem, fn, nb_bytes;
978 tree val;
979 struct builtin_info *builtin = partition->builtin;
980 gimple *fn_call;
982 /* The new statements will be placed before LOOP. */
983 gsi = gsi_last_bb (loop_preheader_edge (loop)->src);
985 nb_bytes = builtin->size;
986 nb_bytes = force_gimple_operand_gsi (&gsi, nb_bytes, true, NULL_TREE,
987 false, GSI_CONTINUE_LINKING);
988 mem = builtin->dst_base;
989 mem = force_gimple_operand_gsi (&gsi, mem, true, NULL_TREE,
990 false, GSI_CONTINUE_LINKING);
992 /* This exactly matches the pattern recognition in classify_partition. */
993 val = gimple_assign_rhs1 (DR_STMT (builtin->dst_dr));
994 /* Handle constants like 0x15151515 and similarly
995 floating point constants etc. where all bytes are the same. */
996 int bytev = const_with_all_bytes_same (val);
997 if (bytev != -1)
998 val = build_int_cst (integer_type_node, bytev);
999 else if (TREE_CODE (val) == INTEGER_CST)
1000 val = fold_convert (integer_type_node, val);
1001 else if (!useless_type_conversion_p (integer_type_node, TREE_TYPE (val)))
1003 tree tem = make_ssa_name (integer_type_node);
1004 gimple *cstmt = gimple_build_assign (tem, NOP_EXPR, val);
1005 gsi_insert_after (&gsi, cstmt, GSI_CONTINUE_LINKING);
1006 val = tem;
1009 fn = build_fold_addr_expr (builtin_decl_implicit (BUILT_IN_MEMSET));
1010 fn_call = gimple_build_call (fn, 3, mem, val, nb_bytes);
1011 gsi_insert_after (&gsi, fn_call, GSI_CONTINUE_LINKING);
1013 if (dump_file && (dump_flags & TDF_DETAILS))
1015 fprintf (dump_file, "generated memset");
1016 if (bytev == 0)
1017 fprintf (dump_file, " zero\n");
1018 else
1019 fprintf (dump_file, "\n");
1023 /* Generate a call to memcpy for PARTITION in LOOP. */
1025 static void
1026 generate_memcpy_builtin (struct loop *loop, partition *partition)
1028 gimple_stmt_iterator gsi;
1029 gimple *fn_call;
1030 tree dest, src, fn, nb_bytes;
1031 enum built_in_function kind;
1032 struct builtin_info *builtin = partition->builtin;
1034 /* The new statements will be placed before LOOP. */
1035 gsi = gsi_last_bb (loop_preheader_edge (loop)->src);
1037 nb_bytes = builtin->size;
1038 nb_bytes = force_gimple_operand_gsi (&gsi, nb_bytes, true, NULL_TREE,
1039 false, GSI_CONTINUE_LINKING);
1040 dest = builtin->dst_base;
1041 src = builtin->src_base;
1042 if (partition->kind == PKIND_MEMCPY
1043 || ! ptr_derefs_may_alias_p (dest, src))
1044 kind = BUILT_IN_MEMCPY;
1045 else
1046 kind = BUILT_IN_MEMMOVE;
1048 dest = force_gimple_operand_gsi (&gsi, dest, true, NULL_TREE,
1049 false, GSI_CONTINUE_LINKING);
1050 src = force_gimple_operand_gsi (&gsi, src, true, NULL_TREE,
1051 false, GSI_CONTINUE_LINKING);
1052 fn = build_fold_addr_expr (builtin_decl_implicit (kind));
1053 fn_call = gimple_build_call (fn, 3, dest, src, nb_bytes);
1054 gsi_insert_after (&gsi, fn_call, GSI_CONTINUE_LINKING);
1056 if (dump_file && (dump_flags & TDF_DETAILS))
1058 if (kind == BUILT_IN_MEMCPY)
1059 fprintf (dump_file, "generated memcpy\n");
1060 else
1061 fprintf (dump_file, "generated memmove\n");
1065 /* Remove and destroy the loop LOOP. */
1067 static void
1068 destroy_loop (struct loop *loop)
1070 unsigned nbbs = loop->num_nodes;
1071 edge exit = single_exit (loop);
1072 basic_block src = loop_preheader_edge (loop)->src, dest = exit->dest;
1073 basic_block *bbs;
1074 unsigned i;
1076 bbs = get_loop_body_in_dom_order (loop);
1078 redirect_edge_pred (exit, src);
1079 exit->flags &= ~(EDGE_TRUE_VALUE|EDGE_FALSE_VALUE);
1080 exit->flags |= EDGE_FALLTHRU;
1081 cancel_loop_tree (loop);
1082 rescan_loop_exit (exit, false, true);
1084 i = nbbs;
1087 /* We have made sure to not leave any dangling uses of SSA
1088 names defined in the loop. With the exception of virtuals.
1089 Make sure we replace all uses of virtual defs that will remain
1090 outside of the loop with the bare symbol as delete_basic_block
1091 will release them. */
1092 --i;
1093 for (gphi_iterator gsi = gsi_start_phis (bbs[i]); !gsi_end_p (gsi);
1094 gsi_next (&gsi))
1096 gphi *phi = gsi.phi ();
1097 if (virtual_operand_p (gimple_phi_result (phi)))
1098 mark_virtual_phi_result_for_renaming (phi);
1100 for (gimple_stmt_iterator gsi = gsi_start_bb (bbs[i]); !gsi_end_p (gsi);
1101 gsi_next (&gsi))
1103 gimple *stmt = gsi_stmt (gsi);
1104 tree vdef = gimple_vdef (stmt);
1105 if (vdef && TREE_CODE (vdef) == SSA_NAME)
1106 mark_virtual_operand_for_renaming (vdef);
1108 delete_basic_block (bbs[i]);
1110 while (i != 0);
1112 free (bbs);
1114 set_immediate_dominator (CDI_DOMINATORS, dest,
1115 recompute_dominator (CDI_DOMINATORS, dest));
1118 /* Generates code for PARTITION. Return whether LOOP needs to be destroyed. */
1120 static bool
1121 generate_code_for_partition (struct loop *loop,
1122 partition *partition, bool copy_p)
1124 switch (partition->kind)
1126 case PKIND_NORMAL:
1127 /* Reductions all have to be in the last partition. */
1128 gcc_assert (!partition_reduction_p (partition)
1129 || !copy_p);
1130 generate_loops_for_partition (loop, partition, copy_p);
1131 return false;
1133 case PKIND_MEMSET:
1134 generate_memset_builtin (loop, partition);
1135 break;
1137 case PKIND_MEMCPY:
1138 case PKIND_MEMMOVE:
1139 generate_memcpy_builtin (loop, partition);
1140 break;
1142 default:
1143 gcc_unreachable ();
1146 /* Common tail for partitions we turn into a call. If this was the last
1147 partition for which we generate code, we have to destroy the loop. */
1148 if (!copy_p)
1149 return true;
1150 return false;
1153 /* Return data dependence relation for data references A and B. The two
1154 data references must be in lexicographic order wrto reduced dependence
1155 graph RDG. We firstly try to find ddr from global ddr hash table. If
1156 it doesn't exist, compute the ddr and cache it. */
1158 static data_dependence_relation *
1159 get_data_dependence (struct graph *rdg, data_reference_p a, data_reference_p b)
1161 struct data_dependence_relation ent, **slot;
1162 struct data_dependence_relation *ddr;
1164 gcc_assert (DR_IS_WRITE (a) || DR_IS_WRITE (b));
1165 gcc_assert (rdg_vertex_for_stmt (rdg, DR_STMT (a))
1166 <= rdg_vertex_for_stmt (rdg, DR_STMT (b)));
1167 ent.a = a;
1168 ent.b = b;
1169 slot = ddrs_table->find_slot (&ent, INSERT);
1170 if (*slot == NULL)
1172 ddr = initialize_data_dependence_relation (a, b, loop_nest);
1173 compute_affine_dependence (ddr, loop_nest[0]);
1174 *slot = ddr;
1177 return *slot;
1180 /* In reduced dependence graph RDG for loop distribution, return true if
1181 dependence between references DR1 and DR2 leads to a dependence cycle
1182 and such dependence cycle can't be resolved by runtime alias check. */
1184 static bool
1185 data_dep_in_cycle_p (struct graph *rdg,
1186 data_reference_p dr1, data_reference_p dr2)
1188 struct data_dependence_relation *ddr;
1190 /* Re-shuffle data-refs to be in topological order. */
1191 if (rdg_vertex_for_stmt (rdg, DR_STMT (dr1))
1192 > rdg_vertex_for_stmt (rdg, DR_STMT (dr2)))
1193 std::swap (dr1, dr2);
1195 ddr = get_data_dependence (rdg, dr1, dr2);
1197 /* In case of no data dependence. */
1198 if (DDR_ARE_DEPENDENT (ddr) == chrec_known)
1199 return false;
1200 /* For unknown data dependence or known data dependence which can't be
1201 expressed in classic distance vector, we check if it can be resolved
1202 by runtime alias check. If yes, we still consider data dependence
1203 as won't introduce data dependence cycle. */
1204 else if (DDR_ARE_DEPENDENT (ddr) == chrec_dont_know
1205 || DDR_NUM_DIST_VECTS (ddr) == 0)
1206 return !runtime_alias_check_p (ddr, NULL, true);
1207 else if (DDR_NUM_DIST_VECTS (ddr) > 1)
1208 return true;
1209 else if (DDR_REVERSED_P (ddr)
1210 || lambda_vector_zerop (DDR_DIST_VECT (ddr, 0), 1))
1211 return false;
1213 return true;
1216 /* Given reduced dependence graph RDG, PARTITION1 and PARTITION2, update
1217 PARTITION1's type after merging PARTITION2 into PARTITION1. */
1219 static void
1220 update_type_for_merge (struct graph *rdg,
1221 partition *partition1, partition *partition2)
1223 unsigned i, j;
1224 bitmap_iterator bi, bj;
1225 data_reference_p dr1, dr2;
1227 EXECUTE_IF_SET_IN_BITMAP (partition1->datarefs, 0, i, bi)
1229 unsigned start = (partition1 == partition2) ? i + 1 : 0;
1231 dr1 = datarefs_vec[i];
1232 EXECUTE_IF_SET_IN_BITMAP (partition2->datarefs, start, j, bj)
1234 dr2 = datarefs_vec[j];
1235 if (DR_IS_READ (dr1) && DR_IS_READ (dr2))
1236 continue;
1238 /* Partition can only be executed sequentially if there is any
1239 data dependence cycle. */
1240 if (data_dep_in_cycle_p (rdg, dr1, dr2))
1242 partition1->type = PTYPE_SEQUENTIAL;
1243 return;
1249 /* Returns a partition with all the statements needed for computing
1250 the vertex V of the RDG, also including the loop exit conditions. */
1252 static partition *
1253 build_rdg_partition_for_vertex (struct graph *rdg, int v)
1255 partition *partition = partition_alloc ();
1256 auto_vec<int, 3> nodes;
1257 unsigned i, j;
1258 int x;
1259 data_reference_p dr;
1261 graphds_dfs (rdg, &v, 1, &nodes, false, NULL);
1263 FOR_EACH_VEC_ELT (nodes, i, x)
1265 bitmap_set_bit (partition->stmts, x);
1267 for (j = 0; RDG_DATAREFS (rdg, x).iterate (j, &dr); ++j)
1269 unsigned idx = (unsigned) DR_INDEX (dr);
1270 gcc_assert (idx < datarefs_vec.length ());
1272 /* Partition can only be executed sequentially if there is any
1273 unknown data reference. */
1274 if (!DR_BASE_ADDRESS (dr) || !DR_OFFSET (dr)
1275 || !DR_INIT (dr) || !DR_STEP (dr))
1276 partition->type = PTYPE_SEQUENTIAL;
1278 bitmap_set_bit (partition->datarefs, idx);
1282 if (partition->type == PTYPE_SEQUENTIAL)
1283 return partition;
1285 /* Further check if any data dependence prevents us from executing the
1286 partition parallelly. */
1287 update_type_for_merge (rdg, partition, partition);
1289 return partition;
1292 /* Given PARTITION of LOOP and RDG, record single load/store data references
1293 for builtin partition in SRC_DR/DST_DR, return false if there is no such
1294 data references. */
1296 static bool
1297 find_single_drs (struct loop *loop, struct graph *rdg, partition *partition,
1298 data_reference_p *dst_dr, data_reference_p *src_dr)
1300 unsigned i;
1301 data_reference_p single_ld = NULL, single_st = NULL;
1302 bitmap_iterator bi;
1304 EXECUTE_IF_SET_IN_BITMAP (partition->stmts, 0, i, bi)
1306 gimple *stmt = RDG_STMT (rdg, i);
1307 data_reference_p dr;
1309 if (gimple_code (stmt) == GIMPLE_PHI)
1310 continue;
1312 /* Any scalar stmts are ok. */
1313 if (!gimple_vuse (stmt))
1314 continue;
1316 /* Otherwise just regular loads/stores. */
1317 if (!gimple_assign_single_p (stmt))
1318 return false;
1320 /* But exactly one store and/or load. */
1321 for (unsigned j = 0; RDG_DATAREFS (rdg, i).iterate (j, &dr); ++j)
1323 tree type = TREE_TYPE (DR_REF (dr));
1325 /* The memset, memcpy and memmove library calls are only
1326 able to deal with generic address space. */
1327 if (!ADDR_SPACE_GENERIC_P (TYPE_ADDR_SPACE (type)))
1328 return false;
1330 if (DR_IS_READ (dr))
1332 if (single_ld != NULL)
1333 return false;
1334 single_ld = dr;
1336 else
1338 if (single_st != NULL)
1339 return false;
1340 single_st = dr;
1345 if (!single_st)
1346 return false;
1348 /* Bail out if this is a bitfield memory reference. */
1349 if (TREE_CODE (DR_REF (single_st)) == COMPONENT_REF
1350 && DECL_BIT_FIELD (TREE_OPERAND (DR_REF (single_st), 1)))
1351 return false;
1353 /* Data reference must be executed exactly once per iteration of each
1354 loop in the loop nest. We only need to check dominance information
1355 against the outermost one in a perfect loop nest because a bb can't
1356 dominate outermost loop's latch without dominating inner loop's. */
1357 basic_block bb_st = gimple_bb (DR_STMT (single_st));
1358 if (!dominated_by_p (CDI_DOMINATORS, loop->latch, bb_st))
1359 return false;
1361 if (single_ld)
1363 gimple *store = DR_STMT (single_st), *load = DR_STMT (single_ld);
1364 /* Direct aggregate copy or via an SSA name temporary. */
1365 if (load != store
1366 && gimple_assign_lhs (load) != gimple_assign_rhs1 (store))
1367 return false;
1369 /* Bail out if this is a bitfield memory reference. */
1370 if (TREE_CODE (DR_REF (single_ld)) == COMPONENT_REF
1371 && DECL_BIT_FIELD (TREE_OPERAND (DR_REF (single_ld), 1)))
1372 return false;
1374 /* Load and store must be in the same loop nest. */
1375 basic_block bb_ld = gimple_bb (DR_STMT (single_ld));
1376 if (bb_st->loop_father != bb_ld->loop_father)
1377 return false;
1379 /* Data reference must be executed exactly once per iteration.
1380 Same as single_st, we only need to check against the outermost
1381 loop. */
1382 if (!dominated_by_p (CDI_DOMINATORS, loop->latch, bb_ld))
1383 return false;
1385 edge e = single_exit (bb_st->loop_father);
1386 bool dom_ld = dominated_by_p (CDI_DOMINATORS, e->src, bb_ld);
1387 bool dom_st = dominated_by_p (CDI_DOMINATORS, e->src, bb_st);
1388 if (dom_ld != dom_st)
1389 return false;
1392 *src_dr = single_ld;
1393 *dst_dr = single_st;
1394 return true;
1397 /* Given data reference DR in LOOP_NEST, this function checks the enclosing
1398 loops from inner to outer to see if loop's step equals to access size at
1399 each level of loop. Return true if yes; record access base and size in
1400 BASE and SIZE; save loop's step at each level of loop in STEPS if it is
1401 not null. For example:
1403 int arr[100][100][100];
1404 for (i = 0; i < 100; i++) ;steps[2] = 40000
1405 for (j = 100; j > 0; j--) ;steps[1] = -400
1406 for (k = 0; k < 100; k++) ;steps[0] = 4
1407 arr[i][j - 1][k] = 0; ;base = &arr, size = 4000000. */
1409 static bool
1410 compute_access_range (loop_p loop_nest, data_reference_p dr, tree *base,
1411 tree *size, vec<tree> *steps = NULL)
1413 location_t loc = gimple_location (DR_STMT (dr));
1414 basic_block bb = gimple_bb (DR_STMT (dr));
1415 struct loop *loop = bb->loop_father;
1416 tree ref = DR_REF (dr);
1417 tree access_base = build_fold_addr_expr (ref);
1418 tree access_size = TYPE_SIZE_UNIT (TREE_TYPE (ref));
1420 do {
1421 tree scev_fn = analyze_scalar_evolution (loop, access_base);
1422 if (TREE_CODE (scev_fn) != POLYNOMIAL_CHREC)
1423 return false;
1425 access_base = CHREC_LEFT (scev_fn);
1426 if (tree_contains_chrecs (access_base, NULL))
1427 return false;
1429 tree scev_step = CHREC_RIGHT (scev_fn);
1430 /* Only support constant steps. */
1431 if (TREE_CODE (scev_step) != INTEGER_CST)
1432 return false;
1434 enum ev_direction access_dir = scev_direction (scev_fn);
1435 if (access_dir == EV_DIR_UNKNOWN)
1436 return false;
1438 if (steps != NULL)
1439 steps->safe_push (scev_step);
1441 scev_step = fold_convert_loc (loc, sizetype, scev_step);
1442 /* Compute absolute value of scev step. */
1443 if (access_dir == EV_DIR_DECREASES)
1444 scev_step = fold_build1_loc (loc, NEGATE_EXPR, sizetype, scev_step);
1446 /* At each level of loop, scev step must equal to access size. In other
1447 words, DR must access consecutive memory between loop iterations. */
1448 if (!operand_equal_p (scev_step, access_size, 0))
1449 return false;
1451 /* Compute DR's execution times in loop. */
1452 tree niters = number_of_latch_executions (loop);
1453 niters = fold_convert_loc (loc, sizetype, niters);
1454 if (dominated_by_p (CDI_DOMINATORS, single_exit (loop)->src, bb))
1455 niters = size_binop_loc (loc, PLUS_EXPR, niters, size_one_node);
1457 /* Compute DR's overall access size in loop. */
1458 access_size = fold_build2_loc (loc, MULT_EXPR, sizetype,
1459 niters, scev_step);
1460 /* Adjust base address in case of negative step. */
1461 if (access_dir == EV_DIR_DECREASES)
1463 tree adj = fold_build2_loc (loc, MINUS_EXPR, sizetype,
1464 scev_step, access_size);
1465 access_base = fold_build_pointer_plus_loc (loc, access_base, adj);
1467 } while (loop != loop_nest && (loop = loop_outer (loop)) != NULL);
1469 *base = access_base;
1470 *size = access_size;
1471 return true;
1474 /* Allocate and return builtin struct. Record information like DST_DR,
1475 SRC_DR, DST_BASE, SRC_BASE and SIZE in the allocated struct. */
1477 static struct builtin_info *
1478 alloc_builtin (data_reference_p dst_dr, data_reference_p src_dr,
1479 tree dst_base, tree src_base, tree size)
1481 struct builtin_info *builtin = XNEW (struct builtin_info);
1482 builtin->dst_dr = dst_dr;
1483 builtin->src_dr = src_dr;
1484 builtin->dst_base = dst_base;
1485 builtin->src_base = src_base;
1486 builtin->size = size;
1487 return builtin;
1490 /* Given data reference DR in loop nest LOOP, classify if it forms builtin
1491 memset call. */
1493 static void
1494 classify_builtin_st (loop_p loop, partition *partition, data_reference_p dr)
1496 gimple *stmt = DR_STMT (dr);
1497 tree base, size, rhs = gimple_assign_rhs1 (stmt);
1499 if (const_with_all_bytes_same (rhs) == -1
1500 && (!INTEGRAL_TYPE_P (TREE_TYPE (rhs))
1501 || (TYPE_MODE (TREE_TYPE (rhs))
1502 != TYPE_MODE (unsigned_char_type_node))))
1503 return;
1505 if (TREE_CODE (rhs) == SSA_NAME
1506 && !SSA_NAME_IS_DEFAULT_DEF (rhs)
1507 && flow_bb_inside_loop_p (loop, gimple_bb (SSA_NAME_DEF_STMT (rhs))))
1508 return;
1510 if (!compute_access_range (loop, dr, &base, &size))
1511 return;
1513 struct builtin_info *builtin;
1514 builtin = alloc_builtin (dr, NULL, base, NULL_TREE, size);
1515 builtin->dst_base_base = strip_offset (builtin->dst_base,
1516 &builtin->dst_base_offset);
1517 partition->builtin = builtin;
1518 partition->kind = PKIND_MEMSET;
1521 /* Given data references DST_DR and SRC_DR in loop nest LOOP and RDG, classify
1522 if it forms builtin memcpy or memmove call. */
1524 static void
1525 classify_builtin_ldst (loop_p loop, struct graph *rdg, partition *partition,
1526 data_reference_p dst_dr, data_reference_p src_dr)
1528 tree base, size, src_base, src_size;
1529 auto_vec<tree> dst_steps, src_steps;
1531 /* Compute access range of both load and store. They much have the same
1532 access size. */
1533 if (!compute_access_range (loop, dst_dr, &base, &size, &dst_steps)
1534 || !compute_access_range (loop, src_dr, &src_base, &src_size, &src_steps)
1535 || !operand_equal_p (size, src_size, 0))
1536 return;
1538 /* Load and store in loop nest must access memory in the same way, i.e,
1539 their must have the same steps in each loop of the nest. */
1540 if (dst_steps.length () != src_steps.length ())
1541 return;
1542 for (unsigned i = 0; i < dst_steps.length (); ++i)
1543 if (!operand_equal_p (dst_steps[i], src_steps[i], 0))
1544 return;
1546 /* Now check that if there is a dependence. */
1547 ddr_p ddr = get_data_dependence (rdg, src_dr, dst_dr);
1549 /* Classify as memcpy if no dependence between load and store. */
1550 if (DDR_ARE_DEPENDENT (ddr) == chrec_known)
1552 partition->builtin = alloc_builtin (dst_dr, src_dr, base, src_base, size);
1553 partition->kind = PKIND_MEMCPY;
1554 return;
1557 /* Can't do memmove in case of unknown dependence or dependence without
1558 classical distance vector. */
1559 if (DDR_ARE_DEPENDENT (ddr) == chrec_dont_know
1560 || DDR_NUM_DIST_VECTS (ddr) == 0)
1561 return;
1563 unsigned i;
1564 lambda_vector dist_v;
1565 int num_lev = (DDR_LOOP_NEST (ddr)).length ();
1566 FOR_EACH_VEC_ELT (DDR_DIST_VECTS (ddr), i, dist_v)
1568 unsigned dep_lev = dependence_level (dist_v, num_lev);
1569 /* Can't do memmove if load depends on store. */
1570 if (dep_lev > 0 && dist_v[dep_lev - 1] > 0 && !DDR_REVERSED_P (ddr))
1571 return;
1574 partition->builtin = alloc_builtin (dst_dr, src_dr, base, src_base, size);
1575 partition->kind = PKIND_MEMMOVE;
1576 return;
1579 /* Classifies the builtin kind we can generate for PARTITION of RDG and LOOP.
1580 For the moment we detect memset, memcpy and memmove patterns. Bitmap
1581 STMT_IN_ALL_PARTITIONS contains statements belonging to all partitions. */
1583 static void
1584 classify_partition (loop_p loop, struct graph *rdg, partition *partition,
1585 bitmap stmt_in_all_partitions)
1587 bitmap_iterator bi;
1588 unsigned i;
1589 data_reference_p single_ld = NULL, single_st = NULL;
1590 bool volatiles_p = false, has_reduction = false;
1592 EXECUTE_IF_SET_IN_BITMAP (partition->stmts, 0, i, bi)
1594 gimple *stmt = RDG_STMT (rdg, i);
1596 if (gimple_has_volatile_ops (stmt))
1597 volatiles_p = true;
1599 /* If the stmt is not included by all partitions and there is uses
1600 outside of the loop, then mark the partition as reduction. */
1601 if (stmt_has_scalar_dependences_outside_loop (loop, stmt))
1603 /* Due to limitation in the transform phase we have to fuse all
1604 reduction partitions. As a result, this could cancel valid
1605 loop distribution especially for loop that induction variable
1606 is used outside of loop. To workaround this issue, we skip
1607 marking partition as reudction if the reduction stmt belongs
1608 to all partitions. In such case, reduction will be computed
1609 correctly no matter how partitions are fused/distributed. */
1610 if (!bitmap_bit_p (stmt_in_all_partitions, i))
1612 partition->reduction_p = true;
1613 return;
1615 has_reduction = true;
1619 /* Perform general partition disqualification for builtins. */
1620 if (volatiles_p
1621 /* Simple workaround to prevent classifying the partition as builtin
1622 if it contains any use outside of loop. */
1623 || has_reduction
1624 || !flag_tree_loop_distribute_patterns)
1625 return;
1627 /* Find single load/store data references for builtin partition. */
1628 if (!find_single_drs (loop, rdg, partition, &single_st, &single_ld))
1629 return;
1631 /* Classify the builtin kind. */
1632 if (single_ld == NULL)
1633 classify_builtin_st (loop, partition, single_st);
1634 else
1635 classify_builtin_ldst (loop, rdg, partition, single_st, single_ld);
1638 /* Returns true when PARTITION1 and PARTITION2 access the same memory
1639 object in RDG. */
1641 static bool
1642 share_memory_accesses (struct graph *rdg,
1643 partition *partition1, partition *partition2)
1645 unsigned i, j;
1646 bitmap_iterator bi, bj;
1647 data_reference_p dr1, dr2;
1649 /* First check whether in the intersection of the two partitions are
1650 any loads or stores. Common loads are the situation that happens
1651 most often. */
1652 EXECUTE_IF_AND_IN_BITMAP (partition1->stmts, partition2->stmts, 0, i, bi)
1653 if (RDG_MEM_WRITE_STMT (rdg, i)
1654 || RDG_MEM_READS_STMT (rdg, i))
1655 return true;
1657 /* Then check whether the two partitions access the same memory object. */
1658 EXECUTE_IF_SET_IN_BITMAP (partition1->datarefs, 0, i, bi)
1660 dr1 = datarefs_vec[i];
1662 if (!DR_BASE_ADDRESS (dr1)
1663 || !DR_OFFSET (dr1) || !DR_INIT (dr1) || !DR_STEP (dr1))
1664 continue;
1666 EXECUTE_IF_SET_IN_BITMAP (partition2->datarefs, 0, j, bj)
1668 dr2 = datarefs_vec[j];
1670 if (!DR_BASE_ADDRESS (dr2)
1671 || !DR_OFFSET (dr2) || !DR_INIT (dr2) || !DR_STEP (dr2))
1672 continue;
1674 if (operand_equal_p (DR_BASE_ADDRESS (dr1), DR_BASE_ADDRESS (dr2), 0)
1675 && operand_equal_p (DR_OFFSET (dr1), DR_OFFSET (dr2), 0)
1676 && operand_equal_p (DR_INIT (dr1), DR_INIT (dr2), 0)
1677 && operand_equal_p (DR_STEP (dr1), DR_STEP (dr2), 0))
1678 return true;
1682 return false;
1685 /* For each seed statement in STARTING_STMTS, this function builds
1686 partition for it by adding depended statements according to RDG.
1687 All partitions are recorded in PARTITIONS. */
1689 static void
1690 rdg_build_partitions (struct graph *rdg,
1691 vec<gimple *> starting_stmts,
1692 vec<partition *> *partitions)
1694 auto_bitmap processed;
1695 int i;
1696 gimple *stmt;
1698 FOR_EACH_VEC_ELT (starting_stmts, i, stmt)
1700 int v = rdg_vertex_for_stmt (rdg, stmt);
1702 if (dump_file && (dump_flags & TDF_DETAILS))
1703 fprintf (dump_file,
1704 "ldist asked to generate code for vertex %d\n", v);
1706 /* If the vertex is already contained in another partition so
1707 is the partition rooted at it. */
1708 if (bitmap_bit_p (processed, v))
1709 continue;
1711 partition *partition = build_rdg_partition_for_vertex (rdg, v);
1712 bitmap_ior_into (processed, partition->stmts);
1714 if (dump_file && (dump_flags & TDF_DETAILS))
1716 fprintf (dump_file, "ldist creates useful %s partition:\n",
1717 partition->type == PTYPE_PARALLEL ? "parallel" : "sequent");
1718 bitmap_print (dump_file, partition->stmts, " ", "\n");
1721 partitions->safe_push (partition);
1724 /* All vertices should have been assigned to at least one partition now,
1725 other than vertices belonging to dead code. */
1728 /* Dump to FILE the PARTITIONS. */
1730 static void
1731 dump_rdg_partitions (FILE *file, vec<partition *> partitions)
1733 int i;
1734 partition *partition;
1736 FOR_EACH_VEC_ELT (partitions, i, partition)
1737 debug_bitmap_file (file, partition->stmts);
1740 /* Debug PARTITIONS. */
1741 extern void debug_rdg_partitions (vec<partition *> );
1743 DEBUG_FUNCTION void
1744 debug_rdg_partitions (vec<partition *> partitions)
1746 dump_rdg_partitions (stderr, partitions);
1749 /* Returns the number of read and write operations in the RDG. */
1751 static int
1752 number_of_rw_in_rdg (struct graph *rdg)
1754 int i, res = 0;
1756 for (i = 0; i < rdg->n_vertices; i++)
1758 if (RDG_MEM_WRITE_STMT (rdg, i))
1759 ++res;
1761 if (RDG_MEM_READS_STMT (rdg, i))
1762 ++res;
1765 return res;
1768 /* Returns the number of read and write operations in a PARTITION of
1769 the RDG. */
1771 static int
1772 number_of_rw_in_partition (struct graph *rdg, partition *partition)
1774 int res = 0;
1775 unsigned i;
1776 bitmap_iterator ii;
1778 EXECUTE_IF_SET_IN_BITMAP (partition->stmts, 0, i, ii)
1780 if (RDG_MEM_WRITE_STMT (rdg, i))
1781 ++res;
1783 if (RDG_MEM_READS_STMT (rdg, i))
1784 ++res;
1787 return res;
1790 /* Returns true when one of the PARTITIONS contains all the read or
1791 write operations of RDG. */
1793 static bool
1794 partition_contains_all_rw (struct graph *rdg,
1795 vec<partition *> partitions)
1797 int i;
1798 partition *partition;
1799 int nrw = number_of_rw_in_rdg (rdg);
1801 FOR_EACH_VEC_ELT (partitions, i, partition)
1802 if (nrw == number_of_rw_in_partition (rdg, partition))
1803 return true;
1805 return false;
1808 /* Compute partition dependence created by the data references in DRS1
1809 and DRS2, modify and return DIR according to that. IF ALIAS_DDR is
1810 not NULL, we record dependence introduced by possible alias between
1811 two data references in ALIAS_DDRS; otherwise, we simply ignore such
1812 dependence as if it doesn't exist at all. */
1814 static int
1815 pg_add_dependence_edges (struct graph *rdg, int dir,
1816 bitmap drs1, bitmap drs2, vec<ddr_p> *alias_ddrs)
1818 unsigned i, j;
1819 bitmap_iterator bi, bj;
1820 data_reference_p dr1, dr2, saved_dr1;
1822 /* dependence direction - 0 is no dependence, -1 is back,
1823 1 is forth, 2 is both (we can stop then, merging will occur). */
1824 EXECUTE_IF_SET_IN_BITMAP (drs1, 0, i, bi)
1826 dr1 = datarefs_vec[i];
1828 EXECUTE_IF_SET_IN_BITMAP (drs2, 0, j, bj)
1830 int res, this_dir = 1;
1831 ddr_p ddr;
1833 dr2 = datarefs_vec[j];
1835 /* Skip all <read, read> data dependence. */
1836 if (DR_IS_READ (dr1) && DR_IS_READ (dr2))
1837 continue;
1839 saved_dr1 = dr1;
1840 /* Re-shuffle data-refs to be in topological order. */
1841 if (rdg_vertex_for_stmt (rdg, DR_STMT (dr1))
1842 > rdg_vertex_for_stmt (rdg, DR_STMT (dr2)))
1844 std::swap (dr1, dr2);
1845 this_dir = -this_dir;
1847 ddr = get_data_dependence (rdg, dr1, dr2);
1848 if (DDR_ARE_DEPENDENT (ddr) == chrec_dont_know)
1850 this_dir = 0;
1851 res = data_ref_compare_tree (DR_BASE_ADDRESS (dr1),
1852 DR_BASE_ADDRESS (dr2));
1853 /* Be conservative. If data references are not well analyzed,
1854 or the two data references have the same base address and
1855 offset, add dependence and consider it alias to each other.
1856 In other words, the dependence can not be resolved by
1857 runtime alias check. */
1858 if (!DR_BASE_ADDRESS (dr1) || !DR_BASE_ADDRESS (dr2)
1859 || !DR_OFFSET (dr1) || !DR_OFFSET (dr2)
1860 || !DR_INIT (dr1) || !DR_INIT (dr2)
1861 || !DR_STEP (dr1) || !tree_fits_uhwi_p (DR_STEP (dr1))
1862 || !DR_STEP (dr2) || !tree_fits_uhwi_p (DR_STEP (dr2))
1863 || res == 0)
1864 this_dir = 2;
1865 /* Data dependence could be resolved by runtime alias check,
1866 record it in ALIAS_DDRS. */
1867 else if (alias_ddrs != NULL)
1868 alias_ddrs->safe_push (ddr);
1869 /* Or simply ignore it. */
1871 else if (DDR_ARE_DEPENDENT (ddr) == NULL_TREE)
1873 if (DDR_REVERSED_P (ddr))
1874 this_dir = -this_dir;
1876 /* Known dependences can still be unordered througout the
1877 iteration space, see gcc.dg/tree-ssa/ldist-16.c. */
1878 if (DDR_NUM_DIST_VECTS (ddr) != 1)
1879 this_dir = 2;
1880 /* If the overlap is exact preserve stmt order. */
1881 else if (lambda_vector_zerop (DDR_DIST_VECT (ddr, 0), 1))
1883 /* Else as the distance vector is lexicographic positive swap
1884 the dependence direction. */
1885 else
1886 this_dir = -this_dir;
1888 else
1889 this_dir = 0;
1890 if (this_dir == 2)
1891 return 2;
1892 else if (dir == 0)
1893 dir = this_dir;
1894 else if (this_dir != 0 && dir != this_dir)
1895 return 2;
1896 /* Shuffle "back" dr1. */
1897 dr1 = saved_dr1;
1900 return dir;
1903 /* Compare postorder number of the partition graph vertices V1 and V2. */
1905 static int
1906 pgcmp (const void *v1_, const void *v2_)
1908 const vertex *v1 = (const vertex *)v1_;
1909 const vertex *v2 = (const vertex *)v2_;
1910 return v2->post - v1->post;
1913 /* Data attached to vertices of partition dependence graph. */
1914 struct pg_vdata
1916 /* ID of the corresponding partition. */
1917 int id;
1918 /* The partition. */
1919 struct partition *partition;
1922 /* Data attached to edges of partition dependence graph. */
1923 struct pg_edata
1925 /* If the dependence edge can be resolved by runtime alias check,
1926 this vector contains data dependence relations for runtime alias
1927 check. On the other hand, if the dependence edge is introduced
1928 because of compilation time known data dependence, this vector
1929 contains nothing. */
1930 vec<ddr_p> alias_ddrs;
1933 /* Callback data for traversing edges in graph. */
1934 struct pg_edge_callback_data
1936 /* Bitmap contains strong connected components should be merged. */
1937 bitmap sccs_to_merge;
1938 /* Array constains component information for all vertices. */
1939 int *vertices_component;
1940 /* Vector to record all data dependence relations which are needed
1941 to break strong connected components by runtime alias checks. */
1942 vec<ddr_p> *alias_ddrs;
1945 /* Initialize vertice's data for partition dependence graph PG with
1946 PARTITIONS. */
1948 static void
1949 init_partition_graph_vertices (struct graph *pg,
1950 vec<struct partition *> *partitions)
1952 int i;
1953 partition *partition;
1954 struct pg_vdata *data;
1956 for (i = 0; partitions->iterate (i, &partition); ++i)
1958 data = new pg_vdata;
1959 pg->vertices[i].data = data;
1960 data->id = i;
1961 data->partition = partition;
1965 /* Add edge <I, J> to partition dependence graph PG. Attach vector of data
1966 dependence relations to the EDGE if DDRS isn't NULL. */
1968 static void
1969 add_partition_graph_edge (struct graph *pg, int i, int j, vec<ddr_p> *ddrs)
1971 struct graph_edge *e = add_edge (pg, i, j);
1973 /* If the edge is attached with data dependence relations, it means this
1974 dependence edge can be resolved by runtime alias checks. */
1975 if (ddrs != NULL)
1977 struct pg_edata *data = new pg_edata;
1979 gcc_assert (ddrs->length () > 0);
1980 e->data = data;
1981 data->alias_ddrs = vNULL;
1982 data->alias_ddrs.safe_splice (*ddrs);
1986 /* Callback function for graph travesal algorithm. It returns true
1987 if edge E should skipped when traversing the graph. */
1989 static bool
1990 pg_skip_alias_edge (struct graph_edge *e)
1992 struct pg_edata *data = (struct pg_edata *)e->data;
1993 return (data != NULL && data->alias_ddrs.length () > 0);
1996 /* Callback function freeing data attached to edge E of graph. */
1998 static void
1999 free_partition_graph_edata_cb (struct graph *, struct graph_edge *e, void *)
2001 if (e->data != NULL)
2003 struct pg_edata *data = (struct pg_edata *)e->data;
2004 data->alias_ddrs.release ();
2005 delete data;
2009 /* Free data attached to vertice of partition dependence graph PG. */
2011 static void
2012 free_partition_graph_vdata (struct graph *pg)
2014 int i;
2015 struct pg_vdata *data;
2017 for (i = 0; i < pg->n_vertices; ++i)
2019 data = (struct pg_vdata *)pg->vertices[i].data;
2020 delete data;
2024 /* Build and return partition dependence graph for PARTITIONS. RDG is
2025 reduced dependence graph for the loop to be distributed. If IGNORE_ALIAS_P
2026 is true, data dependence caused by possible alias between references
2027 is ignored, as if it doesn't exist at all; otherwise all depdendences
2028 are considered. */
2030 static struct graph *
2031 build_partition_graph (struct graph *rdg,
2032 vec<struct partition *> *partitions,
2033 bool ignore_alias_p)
2035 int i, j;
2036 struct partition *partition1, *partition2;
2037 graph *pg = new_graph (partitions->length ());
2038 auto_vec<ddr_p> alias_ddrs, *alias_ddrs_p;
2040 alias_ddrs_p = ignore_alias_p ? NULL : &alias_ddrs;
2042 init_partition_graph_vertices (pg, partitions);
2044 for (i = 0; partitions->iterate (i, &partition1); ++i)
2046 for (j = i + 1; partitions->iterate (j, &partition2); ++j)
2048 /* dependence direction - 0 is no dependence, -1 is back,
2049 1 is forth, 2 is both (we can stop then, merging will occur). */
2050 int dir = 0;
2052 /* If the first partition has reduction, add back edge; if the
2053 second partition has reduction, add forth edge. This makes
2054 sure that reduction partition will be sorted as the last one. */
2055 if (partition_reduction_p (partition1))
2056 dir = -1;
2057 else if (partition_reduction_p (partition2))
2058 dir = 1;
2060 /* Cleanup the temporary vector. */
2061 alias_ddrs.truncate (0);
2063 dir = pg_add_dependence_edges (rdg, dir, partition1->datarefs,
2064 partition2->datarefs, alias_ddrs_p);
2066 /* Add edge to partition graph if there exists dependence. There
2067 are two types of edges. One type edge is caused by compilation
2068 time known dependence, this type can not be resolved by runtime
2069 alias check. The other type can be resolved by runtime alias
2070 check. */
2071 if (dir == 1 || dir == 2
2072 || alias_ddrs.length () > 0)
2074 /* Attach data dependence relations to edge that can be resolved
2075 by runtime alias check. */
2076 bool alias_edge_p = (dir != 1 && dir != 2);
2077 add_partition_graph_edge (pg, i, j,
2078 (alias_edge_p) ? &alias_ddrs : NULL);
2080 if (dir == -1 || dir == 2
2081 || alias_ddrs.length () > 0)
2083 /* Attach data dependence relations to edge that can be resolved
2084 by runtime alias check. */
2085 bool alias_edge_p = (dir != -1 && dir != 2);
2086 add_partition_graph_edge (pg, j, i,
2087 (alias_edge_p) ? &alias_ddrs : NULL);
2091 return pg;
2094 /* Sort partitions in PG in descending post order and store them in
2095 PARTITIONS. */
2097 static void
2098 sort_partitions_by_post_order (struct graph *pg,
2099 vec<struct partition *> *partitions)
2101 int i;
2102 struct pg_vdata *data;
2104 /* Now order the remaining nodes in descending postorder. */
2105 qsort (pg->vertices, pg->n_vertices, sizeof (vertex), pgcmp);
2106 partitions->truncate (0);
2107 for (i = 0; i < pg->n_vertices; ++i)
2109 data = (struct pg_vdata *)pg->vertices[i].data;
2110 if (data->partition)
2111 partitions->safe_push (data->partition);
2115 /* Given reduced dependence graph RDG merge strong connected components
2116 of PARTITIONS. If IGNORE_ALIAS_P is true, data dependence caused by
2117 possible alias between references is ignored, as if it doesn't exist
2118 at all; otherwise all depdendences are considered. */
2120 static void
2121 merge_dep_scc_partitions (struct graph *rdg,
2122 vec<struct partition *> *partitions,
2123 bool ignore_alias_p)
2125 struct partition *partition1, *partition2;
2126 struct pg_vdata *data;
2127 graph *pg = build_partition_graph (rdg, partitions, ignore_alias_p);
2128 int i, j, num_sccs = graphds_scc (pg, NULL);
2130 /* Strong connected compoenent means dependence cycle, we cannot distribute
2131 them. So fuse them together. */
2132 if ((unsigned) num_sccs < partitions->length ())
2134 for (i = 0; i < num_sccs; ++i)
2136 for (j = 0; partitions->iterate (j, &partition1); ++j)
2137 if (pg->vertices[j].component == i)
2138 break;
2139 for (j = j + 1; partitions->iterate (j, &partition2); ++j)
2140 if (pg->vertices[j].component == i)
2142 partition_merge_into (NULL, partition1,
2143 partition2, FUSE_SAME_SCC);
2144 partition1->type = PTYPE_SEQUENTIAL;
2145 (*partitions)[j] = NULL;
2146 partition_free (partition2);
2147 data = (struct pg_vdata *)pg->vertices[j].data;
2148 data->partition = NULL;
2153 sort_partitions_by_post_order (pg, partitions);
2154 gcc_assert (partitions->length () == (unsigned)num_sccs);
2155 free_partition_graph_vdata (pg);
2156 free_graph (pg);
2159 /* Callback function for traversing edge E in graph G. DATA is private
2160 callback data. */
2162 static void
2163 pg_collect_alias_ddrs (struct graph *g, struct graph_edge *e, void *data)
2165 int i, j, component;
2166 struct pg_edge_callback_data *cbdata;
2167 struct pg_edata *edata = (struct pg_edata *) e->data;
2169 /* If the edge doesn't have attached data dependence, it represents
2170 compilation time known dependences. This type dependence cannot
2171 be resolved by runtime alias check. */
2172 if (edata == NULL || edata->alias_ddrs.length () == 0)
2173 return;
2175 cbdata = (struct pg_edge_callback_data *) data;
2176 i = e->src;
2177 j = e->dest;
2178 component = cbdata->vertices_component[i];
2179 /* Vertices are topologically sorted according to compilation time
2180 known dependences, so we can break strong connected components
2181 by removing edges of the opposite direction, i.e, edges pointing
2182 from vertice with smaller post number to vertice with bigger post
2183 number. */
2184 if (g->vertices[i].post < g->vertices[j].post
2185 /* We only need to remove edges connecting vertices in the same
2186 strong connected component to break it. */
2187 && component == cbdata->vertices_component[j]
2188 /* Check if we want to break the strong connected component or not. */
2189 && !bitmap_bit_p (cbdata->sccs_to_merge, component))
2190 cbdata->alias_ddrs->safe_splice (edata->alias_ddrs);
2193 /* This is the main function breaking strong conected components in
2194 PARTITIONS giving reduced depdendence graph RDG. Store data dependence
2195 relations for runtime alias check in ALIAS_DDRS. */
2197 static void
2198 break_alias_scc_partitions (struct graph *rdg,
2199 vec<struct partition *> *partitions,
2200 vec<ddr_p> *alias_ddrs)
2202 int i, j, k, num_sccs, num_sccs_no_alias;
2203 /* Build partition dependence graph. */
2204 graph *pg = build_partition_graph (rdg, partitions, false);
2206 alias_ddrs->truncate (0);
2207 /* Find strong connected components in the graph, with all dependence edges
2208 considered. */
2209 num_sccs = graphds_scc (pg, NULL);
2210 /* All SCCs now can be broken by runtime alias checks because SCCs caused by
2211 compilation time known dependences are merged before this function. */
2212 if ((unsigned) num_sccs < partitions->length ())
2214 struct pg_edge_callback_data cbdata;
2215 auto_bitmap sccs_to_merge;
2216 auto_vec<enum partition_type> scc_types;
2217 struct partition *partition, *first;
2219 /* If all partitions in a SCC have the same type, we can simply merge the
2220 SCC. This loop finds out such SCCS and record them in bitmap. */
2221 bitmap_set_range (sccs_to_merge, 0, (unsigned) num_sccs);
2222 for (i = 0; i < num_sccs; ++i)
2224 for (j = 0; partitions->iterate (j, &first); ++j)
2225 if (pg->vertices[j].component == i)
2226 break;
2227 for (++j; partitions->iterate (j, &partition); ++j)
2229 if (pg->vertices[j].component != i)
2230 continue;
2232 /* Note we Merge partitions of parallel type on purpose, though
2233 the result partition is sequential. The reason is vectorizer
2234 can do more accurate runtime alias check in this case. Also
2235 it results in more conservative distribution. */
2236 if (first->type != partition->type)
2238 bitmap_clear_bit (sccs_to_merge, i);
2239 break;
2244 /* Initialize callback data for traversing. */
2245 cbdata.sccs_to_merge = sccs_to_merge;
2246 cbdata.alias_ddrs = alias_ddrs;
2247 cbdata.vertices_component = XNEWVEC (int, pg->n_vertices);
2248 /* Record the component information which will be corrupted by next
2249 graph scc finding call. */
2250 for (i = 0; i < pg->n_vertices; ++i)
2251 cbdata.vertices_component[i] = pg->vertices[i].component;
2253 /* Collect data dependences for runtime alias checks to break SCCs. */
2254 if (bitmap_count_bits (sccs_to_merge) != (unsigned) num_sccs)
2256 /* Run SCC finding algorithm again, with alias dependence edges
2257 skipped. This is to topologically sort partitions according to
2258 compilation time known dependence. Note the topological order
2259 is stored in the form of pg's post order number. */
2260 num_sccs_no_alias = graphds_scc (pg, NULL, pg_skip_alias_edge);
2261 gcc_assert (partitions->length () == (unsigned) num_sccs_no_alias);
2262 /* With topological order, we can construct two subgraphs L and R.
2263 L contains edge <x, y> where x < y in terms of post order, while
2264 R contains edge <x, y> where x > y. Edges for compilation time
2265 known dependence all fall in R, so we break SCCs by removing all
2266 (alias) edges of in subgraph L. */
2267 for_each_edge (pg, pg_collect_alias_ddrs, &cbdata);
2270 /* For SCC that doesn't need to be broken, merge it. */
2271 for (i = 0; i < num_sccs; ++i)
2273 if (!bitmap_bit_p (sccs_to_merge, i))
2274 continue;
2276 for (j = 0; partitions->iterate (j, &first); ++j)
2277 if (cbdata.vertices_component[j] == i)
2278 break;
2279 for (k = j + 1; partitions->iterate (k, &partition); ++k)
2281 struct pg_vdata *data;
2283 if (cbdata.vertices_component[k] != i)
2284 continue;
2286 /* Update postorder number so that merged reduction partition is
2287 sorted after other partitions. */
2288 if (!partition_reduction_p (first)
2289 && partition_reduction_p (partition))
2291 gcc_assert (pg->vertices[k].post < pg->vertices[j].post);
2292 pg->vertices[j].post = pg->vertices[k].post;
2294 partition_merge_into (NULL, first, partition, FUSE_SAME_SCC);
2295 (*partitions)[k] = NULL;
2296 partition_free (partition);
2297 data = (struct pg_vdata *)pg->vertices[k].data;
2298 gcc_assert (data->id == k);
2299 data->partition = NULL;
2300 /* The result partition of merged SCC must be sequential. */
2301 first->type = PTYPE_SEQUENTIAL;
2306 sort_partitions_by_post_order (pg, partitions);
2307 free_partition_graph_vdata (pg);
2308 for_each_edge (pg, free_partition_graph_edata_cb, NULL);
2309 free_graph (pg);
2311 if (dump_file && (dump_flags & TDF_DETAILS))
2313 fprintf (dump_file, "Possible alias data dependence to break:\n");
2314 dump_data_dependence_relations (dump_file, *alias_ddrs);
2318 /* Compute and return an expression whose value is the segment length which
2319 will be accessed by DR in NITERS iterations. */
2321 static tree
2322 data_ref_segment_size (struct data_reference *dr, tree niters)
2324 tree segment_length;
2326 if (integer_zerop (DR_STEP (dr)))
2327 segment_length = TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (dr)));
2328 else
2329 segment_length = size_binop (MULT_EXPR,
2330 fold_convert (sizetype, DR_STEP (dr)),
2331 fold_convert (sizetype, niters));
2333 return segment_length;
2336 /* Return true if LOOP's latch is dominated by statement for data reference
2337 DR. */
2339 static inline bool
2340 latch_dominated_by_data_ref (struct loop *loop, data_reference *dr)
2342 return dominated_by_p (CDI_DOMINATORS, single_exit (loop)->src,
2343 gimple_bb (DR_STMT (dr)));
2346 /* Compute alias check pairs and store them in COMP_ALIAS_PAIRS for LOOP's
2347 data dependence relations ALIAS_DDRS. */
2349 static void
2350 compute_alias_check_pairs (struct loop *loop, vec<ddr_p> *alias_ddrs,
2351 vec<dr_with_seg_len_pair_t> *comp_alias_pairs)
2353 unsigned int i;
2354 unsigned HOST_WIDE_INT factor = 1;
2355 tree niters_plus_one, niters = number_of_latch_executions (loop);
2357 gcc_assert (niters != NULL_TREE && niters != chrec_dont_know);
2358 niters = fold_convert (sizetype, niters);
2359 niters_plus_one = size_binop (PLUS_EXPR, niters, size_one_node);
2361 if (dump_file && (dump_flags & TDF_DETAILS))
2362 fprintf (dump_file, "Creating alias check pairs:\n");
2364 /* Iterate all data dependence relations and compute alias check pairs. */
2365 for (i = 0; i < alias_ddrs->length (); i++)
2367 ddr_p ddr = (*alias_ddrs)[i];
2368 struct data_reference *dr_a = DDR_A (ddr);
2369 struct data_reference *dr_b = DDR_B (ddr);
2370 tree seg_length_a, seg_length_b;
2371 int comp_res = data_ref_compare_tree (DR_BASE_ADDRESS (dr_a),
2372 DR_BASE_ADDRESS (dr_b));
2374 if (comp_res == 0)
2375 comp_res = data_ref_compare_tree (DR_OFFSET (dr_a), DR_OFFSET (dr_b));
2376 gcc_assert (comp_res != 0);
2378 if (latch_dominated_by_data_ref (loop, dr_a))
2379 seg_length_a = data_ref_segment_size (dr_a, niters_plus_one);
2380 else
2381 seg_length_a = data_ref_segment_size (dr_a, niters);
2383 if (latch_dominated_by_data_ref (loop, dr_b))
2384 seg_length_b = data_ref_segment_size (dr_b, niters_plus_one);
2385 else
2386 seg_length_b = data_ref_segment_size (dr_b, niters);
2388 dr_with_seg_len_pair_t dr_with_seg_len_pair
2389 (dr_with_seg_len (dr_a, seg_length_a),
2390 dr_with_seg_len (dr_b, seg_length_b));
2392 /* Canonicalize pairs by sorting the two DR members. */
2393 if (comp_res > 0)
2394 std::swap (dr_with_seg_len_pair.first, dr_with_seg_len_pair.second);
2396 comp_alias_pairs->safe_push (dr_with_seg_len_pair);
2399 if (tree_fits_uhwi_p (niters))
2400 factor = tree_to_uhwi (niters);
2402 /* Prune alias check pairs. */
2403 prune_runtime_alias_test_list (comp_alias_pairs, factor);
2404 if (dump_file && (dump_flags & TDF_DETAILS))
2405 fprintf (dump_file,
2406 "Improved number of alias checks from %d to %d\n",
2407 alias_ddrs->length (), comp_alias_pairs->length ());
2410 /* Given data dependence relations in ALIAS_DDRS, generate runtime alias
2411 checks and version LOOP under condition of these runtime alias checks. */
2413 static void
2414 version_loop_by_alias_check (struct loop *loop, vec<ddr_p> *alias_ddrs)
2416 profile_probability prob;
2417 basic_block cond_bb;
2418 struct loop *nloop;
2419 tree lhs, arg0, cond_expr = NULL_TREE;
2420 gimple_seq cond_stmts = NULL;
2421 gimple *call_stmt = NULL;
2422 auto_vec<dr_with_seg_len_pair_t> comp_alias_pairs;
2424 /* Generate code for runtime alias checks if necessary. */
2425 gcc_assert (alias_ddrs->length () > 0);
2427 if (dump_file && (dump_flags & TDF_DETAILS))
2428 fprintf (dump_file,
2429 "Version loop <%d> with runtime alias check\n", loop->num);
2431 compute_alias_check_pairs (loop, alias_ddrs, &comp_alias_pairs);
2432 create_runtime_alias_checks (loop, &comp_alias_pairs, &cond_expr);
2433 cond_expr = force_gimple_operand_1 (cond_expr, &cond_stmts,
2434 is_gimple_val, NULL_TREE);
2436 /* Depend on vectorizer to fold IFN_LOOP_DIST_ALIAS. */
2437 if (flag_tree_loop_vectorize)
2439 /* Generate internal function call for loop distribution alias check. */
2440 call_stmt = gimple_build_call_internal (IFN_LOOP_DIST_ALIAS,
2441 2, NULL_TREE, cond_expr);
2442 lhs = make_ssa_name (boolean_type_node);
2443 gimple_call_set_lhs (call_stmt, lhs);
2445 else
2446 lhs = cond_expr;
2448 prob = profile_probability::guessed_always ().apply_scale (9, 10);
2449 initialize_original_copy_tables ();
2450 nloop = loop_version (loop, lhs, &cond_bb, prob, prob.invert (),
2451 prob, prob.invert (), true);
2452 free_original_copy_tables ();
2453 /* Record the original loop number in newly generated loops. In case of
2454 distribution, the original loop will be distributed and the new loop
2455 is kept. */
2456 loop->orig_loop_num = nloop->num;
2457 nloop->orig_loop_num = nloop->num;
2458 nloop->dont_vectorize = true;
2459 nloop->force_vectorize = false;
2461 if (call_stmt)
2463 /* Record new loop's num in IFN_LOOP_DIST_ALIAS because the original
2464 loop could be destroyed. */
2465 arg0 = build_int_cst (integer_type_node, loop->orig_loop_num);
2466 gimple_call_set_arg (call_stmt, 0, arg0);
2467 gimple_seq_add_stmt_without_update (&cond_stmts, call_stmt);
2470 if (cond_stmts)
2472 gimple_stmt_iterator cond_gsi = gsi_last_bb (cond_bb);
2473 gsi_insert_seq_before (&cond_gsi, cond_stmts, GSI_SAME_STMT);
2475 update_ssa (TODO_update_ssa);
2478 /* Return true if loop versioning is needed to distrubute PARTITIONS.
2479 ALIAS_DDRS are data dependence relations for runtime alias check. */
2481 static inline bool
2482 version_for_distribution_p (vec<struct partition *> *partitions,
2483 vec<ddr_p> *alias_ddrs)
2485 /* No need to version loop if we have only one partition. */
2486 if (partitions->length () == 1)
2487 return false;
2489 /* Need to version loop if runtime alias check is necessary. */
2490 return (alias_ddrs->length () > 0);
2493 /* Compare base offset of builtin mem* partitions P1 and P2. */
2495 static bool
2496 offset_cmp (struct partition *p1, struct partition *p2)
2498 gcc_assert (p1 != NULL && p1->builtin != NULL);
2499 gcc_assert (p2 != NULL && p2->builtin != NULL);
2500 return p1->builtin->dst_base_offset < p2->builtin->dst_base_offset;
2503 /* Fuse adjacent memset builtin PARTITIONS if possible. This is a special
2504 case optimization transforming below code:
2506 __builtin_memset (&obj, 0, 100);
2507 _1 = &obj + 100;
2508 __builtin_memset (_1, 0, 200);
2509 _2 = &obj + 300;
2510 __builtin_memset (_2, 0, 100);
2512 into:
2514 __builtin_memset (&obj, 0, 400);
2516 Note we don't have dependence information between different partitions
2517 at this point, as a result, we can't handle nonadjacent memset builtin
2518 partitions since dependence might be broken. */
2520 static void
2521 fuse_memset_builtins (vec<struct partition *> *partitions)
2523 unsigned i, j;
2524 struct partition *part1, *part2;
2526 for (i = 0; partitions->iterate (i, &part1);)
2528 if (part1->kind != PKIND_MEMSET)
2530 i++;
2531 continue;
2534 /* Find sub-array of memset builtins of the same base. Index range
2535 of the sub-array is [i, j) with "j > i". */
2536 for (j = i + 1; partitions->iterate (j, &part2); ++j)
2538 if (part2->kind != PKIND_MEMSET
2539 || !operand_equal_p (part1->builtin->dst_base_base,
2540 part2->builtin->dst_base_base, 0))
2541 break;
2544 /* Stable sort is required in order to avoid breaking dependence. */
2545 std::stable_sort (&(*partitions)[i],
2546 &(*partitions)[i] + j - i, offset_cmp);
2547 /* Continue with next partition. */
2548 i = j;
2551 /* Merge all consecutive memset builtin partitions. */
2552 for (i = 0; i < partitions->length () - 1;)
2554 part1 = (*partitions)[i];
2555 if (part1->kind != PKIND_MEMSET)
2557 i++;
2558 continue;
2561 part2 = (*partitions)[i + 1];
2562 /* Only merge memset partitions of the same base and with constant
2563 access sizes. */
2564 if (part2->kind != PKIND_MEMSET
2565 || TREE_CODE (part1->builtin->size) != INTEGER_CST
2566 || TREE_CODE (part2->builtin->size) != INTEGER_CST
2567 || !operand_equal_p (part1->builtin->dst_base_base,
2568 part2->builtin->dst_base_base, 0))
2570 i++;
2571 continue;
2573 tree rhs1 = gimple_assign_rhs1 (DR_STMT (part1->builtin->dst_dr));
2574 tree rhs2 = gimple_assign_rhs1 (DR_STMT (part2->builtin->dst_dr));
2575 int bytev1 = const_with_all_bytes_same (rhs1);
2576 int bytev2 = const_with_all_bytes_same (rhs2);
2577 /* Only merge memset partitions of the same value. */
2578 if (bytev1 != bytev2 || bytev1 == -1)
2580 i++;
2581 continue;
2583 wide_int end1 = wi::add (part1->builtin->dst_base_offset,
2584 wi::to_wide (part1->builtin->size));
2585 /* Only merge adjacent memset partitions. */
2586 if (wi::ne_p (end1, part2->builtin->dst_base_offset))
2588 i++;
2589 continue;
2591 /* Merge partitions[i] and partitions[i+1]. */
2592 part1->builtin->size = fold_build2 (PLUS_EXPR, sizetype,
2593 part1->builtin->size,
2594 part2->builtin->size);
2595 partition_free (part2);
2596 partitions->ordered_remove (i + 1);
2600 /* Fuse PARTITIONS of LOOP if necessary before finalizing distribution.
2601 ALIAS_DDRS contains ddrs which need runtime alias check. */
2603 static void
2604 finalize_partitions (struct loop *loop, vec<struct partition *> *partitions,
2605 vec<ddr_p> *alias_ddrs)
2607 unsigned i;
2608 struct partition *partition, *a;
2610 if (partitions->length () == 1
2611 || alias_ddrs->length () > 0)
2612 return;
2614 unsigned num_builtin = 0, num_normal = 0;
2615 bool same_type_p = true;
2616 enum partition_type type = ((*partitions)[0])->type;
2617 for (i = 0; partitions->iterate (i, &partition); ++i)
2619 same_type_p &= (type == partition->type);
2620 if (partition->kind != PKIND_NORMAL)
2621 num_builtin++;
2622 else
2623 num_normal++;
2626 /* Don't distribute current loop into too many loops given we don't have
2627 memory stream cost model. Be even more conservative in case of loop
2628 nest distribution. */
2629 if ((same_type_p && num_builtin == 0)
2630 || (loop->inner != NULL
2631 && i >= NUM_PARTITION_THRESHOLD && num_normal > 1)
2632 || (loop->inner == NULL
2633 && i >= NUM_PARTITION_THRESHOLD && num_normal > num_builtin))
2635 a = (*partitions)[0];
2636 for (i = 1; partitions->iterate (i, &partition); ++i)
2638 partition_merge_into (NULL, a, partition, FUSE_FINALIZE);
2639 partition_free (partition);
2641 partitions->truncate (1);
2644 /* Fuse memset builtins if possible. */
2645 if (partitions->length () > 1)
2646 fuse_memset_builtins (partitions);
2649 /* Distributes the code from LOOP in such a way that producer statements
2650 are placed before consumer statements. Tries to separate only the
2651 statements from STMTS into separate loops. Returns the number of
2652 distributed loops. Set NB_CALLS to number of generated builtin calls.
2653 Set *DESTROY_P to whether LOOP needs to be destroyed. */
2655 static int
2656 distribute_loop (struct loop *loop, vec<gimple *> stmts,
2657 control_dependences *cd, int *nb_calls, bool *destroy_p)
2659 ddrs_table = new hash_table<ddr_hasher> (389);
2660 struct graph *rdg;
2661 partition *partition;
2662 bool any_builtin;
2663 int i, nbp;
2665 *destroy_p = false;
2666 *nb_calls = 0;
2667 loop_nest.create (0);
2668 if (!find_loop_nest (loop, &loop_nest))
2670 loop_nest.release ();
2671 delete ddrs_table;
2672 return 0;
2675 datarefs_vec.create (20);
2676 rdg = build_rdg (loop, cd);
2677 if (!rdg)
2679 if (dump_file && (dump_flags & TDF_DETAILS))
2680 fprintf (dump_file,
2681 "Loop %d not distributed: failed to build the RDG.\n",
2682 loop->num);
2684 loop_nest.release ();
2685 free_data_refs (datarefs_vec);
2686 delete ddrs_table;
2687 return 0;
2690 if (datarefs_vec.length () > MAX_DATAREFS_NUM)
2692 if (dump_file && (dump_flags & TDF_DETAILS))
2693 fprintf (dump_file,
2694 "Loop %d not distributed: too many memory references.\n",
2695 loop->num);
2697 free_rdg (rdg);
2698 loop_nest.release ();
2699 free_data_refs (datarefs_vec);
2700 delete ddrs_table;
2701 return 0;
2704 data_reference_p dref;
2705 for (i = 0; datarefs_vec.iterate (i, &dref); ++i)
2706 dref->aux = (void *) (uintptr_t) i;
2708 if (dump_file && (dump_flags & TDF_DETAILS))
2709 dump_rdg (dump_file, rdg);
2711 auto_vec<struct partition *, 3> partitions;
2712 rdg_build_partitions (rdg, stmts, &partitions);
2714 auto_vec<ddr_p> alias_ddrs;
2716 auto_bitmap stmt_in_all_partitions;
2717 bitmap_copy (stmt_in_all_partitions, partitions[0]->stmts);
2718 for (i = 1; partitions.iterate (i, &partition); ++i)
2719 bitmap_and_into (stmt_in_all_partitions, partitions[i]->stmts);
2721 any_builtin = false;
2722 FOR_EACH_VEC_ELT (partitions, i, partition)
2724 classify_partition (loop, rdg, partition, stmt_in_all_partitions);
2725 any_builtin |= partition_builtin_p (partition);
2728 /* If we are only distributing patterns but did not detect any,
2729 simply bail out. */
2730 if (!flag_tree_loop_distribution
2731 && !any_builtin)
2733 nbp = 0;
2734 goto ldist_done;
2737 /* If we are only distributing patterns fuse all partitions that
2738 were not classified as builtins. This also avoids chopping
2739 a loop into pieces, separated by builtin calls. That is, we
2740 only want no or a single loop body remaining. */
2741 struct partition *into;
2742 if (!flag_tree_loop_distribution)
2744 for (i = 0; partitions.iterate (i, &into); ++i)
2745 if (!partition_builtin_p (into))
2746 break;
2747 for (++i; partitions.iterate (i, &partition); ++i)
2748 if (!partition_builtin_p (partition))
2750 partition_merge_into (NULL, into, partition, FUSE_NON_BUILTIN);
2751 partitions.unordered_remove (i);
2752 partition_free (partition);
2753 i--;
2757 /* Due to limitations in the transform phase we have to fuse all
2758 reduction partitions into the last partition so the existing
2759 loop will contain all loop-closed PHI nodes. */
2760 for (i = 0; partitions.iterate (i, &into); ++i)
2761 if (partition_reduction_p (into))
2762 break;
2763 for (i = i + 1; partitions.iterate (i, &partition); ++i)
2764 if (partition_reduction_p (partition))
2766 partition_merge_into (rdg, into, partition, FUSE_REDUCTION);
2767 partitions.unordered_remove (i);
2768 partition_free (partition);
2769 i--;
2772 /* Apply our simple cost model - fuse partitions with similar
2773 memory accesses. */
2774 for (i = 0; partitions.iterate (i, &into); ++i)
2776 bool changed = false;
2777 if (partition_builtin_p (into))
2778 continue;
2779 for (int j = i + 1;
2780 partitions.iterate (j, &partition); ++j)
2782 if (share_memory_accesses (rdg, into, partition))
2784 partition_merge_into (rdg, into, partition, FUSE_SHARE_REF);
2785 partitions.unordered_remove (j);
2786 partition_free (partition);
2787 j--;
2788 changed = true;
2791 /* If we fused 0 1 2 in step 1 to 0,2 1 as 0 and 2 have similar
2792 accesses when 1 and 2 have similar accesses but not 0 and 1
2793 then in the next iteration we will fail to consider merging
2794 1 into 0,2. So try again if we did any merging into 0. */
2795 if (changed)
2796 i--;
2799 /* Build the partition dependency graph and fuse partitions in strong
2800 connected component. */
2801 if (partitions.length () > 1)
2803 /* Don't support loop nest distribution under runtime alias check
2804 since it's not likely to enable many vectorization opportunities. */
2805 if (loop->inner)
2806 merge_dep_scc_partitions (rdg, &partitions, false);
2807 else
2809 merge_dep_scc_partitions (rdg, &partitions, true);
2810 if (partitions.length () > 1)
2811 break_alias_scc_partitions (rdg, &partitions, &alias_ddrs);
2815 finalize_partitions (loop, &partitions, &alias_ddrs);
2817 nbp = partitions.length ();
2818 if (nbp == 0
2819 || (nbp == 1 && !partition_builtin_p (partitions[0]))
2820 || (nbp > 1 && partition_contains_all_rw (rdg, partitions)))
2822 nbp = 0;
2823 goto ldist_done;
2826 if (version_for_distribution_p (&partitions, &alias_ddrs))
2827 version_loop_by_alias_check (loop, &alias_ddrs);
2829 if (dump_file && (dump_flags & TDF_DETAILS))
2831 fprintf (dump_file,
2832 "distribute loop <%d> into partitions:\n", loop->num);
2833 dump_rdg_partitions (dump_file, partitions);
2836 FOR_EACH_VEC_ELT (partitions, i, partition)
2838 if (partition_builtin_p (partition))
2839 (*nb_calls)++;
2840 *destroy_p |= generate_code_for_partition (loop, partition, i < nbp - 1);
2843 ldist_done:
2844 loop_nest.release ();
2845 free_data_refs (datarefs_vec);
2846 for (hash_table<ddr_hasher>::iterator iter = ddrs_table->begin ();
2847 iter != ddrs_table->end (); ++iter)
2849 free_dependence_relation (*iter);
2850 *iter = NULL;
2852 delete ddrs_table;
2854 FOR_EACH_VEC_ELT (partitions, i, partition)
2855 partition_free (partition);
2857 free_rdg (rdg);
2858 return nbp - *nb_calls;
2861 /* Distribute all loops in the current function. */
2863 namespace {
2865 const pass_data pass_data_loop_distribution =
2867 GIMPLE_PASS, /* type */
2868 "ldist", /* name */
2869 OPTGROUP_LOOP, /* optinfo_flags */
2870 TV_TREE_LOOP_DISTRIBUTION, /* tv_id */
2871 ( PROP_cfg | PROP_ssa ), /* properties_required */
2872 0, /* properties_provided */
2873 0, /* properties_destroyed */
2874 0, /* todo_flags_start */
2875 0, /* todo_flags_finish */
2878 class pass_loop_distribution : public gimple_opt_pass
2880 public:
2881 pass_loop_distribution (gcc::context *ctxt)
2882 : gimple_opt_pass (pass_data_loop_distribution, ctxt)
2885 /* opt_pass methods: */
2886 virtual bool gate (function *)
2888 return flag_tree_loop_distribution
2889 || flag_tree_loop_distribute_patterns;
2892 virtual unsigned int execute (function *);
2894 }; // class pass_loop_distribution
2897 /* Given LOOP, this function records seed statements for distribution in
2898 WORK_LIST. Return false if there is nothing for distribution. */
2900 static bool
2901 find_seed_stmts_for_distribution (struct loop *loop, vec<gimple *> *work_list)
2903 basic_block *bbs = get_loop_body_in_dom_order (loop);
2905 /* Initialize the worklist with stmts we seed the partitions with. */
2906 for (unsigned i = 0; i < loop->num_nodes; ++i)
2908 for (gphi_iterator gsi = gsi_start_phis (bbs[i]);
2909 !gsi_end_p (gsi); gsi_next (&gsi))
2911 gphi *phi = gsi.phi ();
2912 if (virtual_operand_p (gimple_phi_result (phi)))
2913 continue;
2914 /* Distribute stmts which have defs that are used outside of
2915 the loop. */
2916 if (!stmt_has_scalar_dependences_outside_loop (loop, phi))
2917 continue;
2918 work_list->safe_push (phi);
2920 for (gimple_stmt_iterator gsi = gsi_start_bb (bbs[i]);
2921 !gsi_end_p (gsi); gsi_next (&gsi))
2923 gimple *stmt = gsi_stmt (gsi);
2925 /* If there is a stmt with side-effects bail out - we
2926 cannot and should not distribute this loop. */
2927 if (gimple_has_side_effects (stmt))
2929 free (bbs);
2930 return false;
2933 /* Distribute stmts which have defs that are used outside of
2934 the loop. */
2935 if (stmt_has_scalar_dependences_outside_loop (loop, stmt))
2937 /* Otherwise only distribute stores for now. */
2938 else if (!gimple_vdef (stmt))
2939 continue;
2941 work_list->safe_push (stmt);
2944 free (bbs);
2945 return work_list->length () > 0;
2948 /* Given innermost LOOP, return the outermost enclosing loop that forms a
2949 perfect loop nest. */
2951 static struct loop *
2952 prepare_perfect_loop_nest (struct loop *loop)
2954 struct loop *outer = loop_outer (loop);
2955 tree niters = number_of_latch_executions (loop);
2957 /* TODO: We only support the innermost 2-level loop nest distribution
2958 because of compilation time issue for now. This should be relaxed
2959 in the future. */
2960 while (loop->inner == NULL
2961 && loop_outer (outer)
2962 && outer->inner == loop && loop->next == NULL
2963 && single_exit (outer)
2964 && optimize_loop_for_speed_p (outer)
2965 && !chrec_contains_symbols_defined_in_loop (niters, outer->num)
2966 && (niters = number_of_latch_executions (outer)) != NULL_TREE
2967 && niters != chrec_dont_know)
2969 loop = outer;
2970 outer = loop_outer (loop);
2973 return loop;
2976 unsigned int
2977 pass_loop_distribution::execute (function *fun)
2979 struct loop *loop;
2980 bool changed = false;
2981 basic_block bb;
2982 control_dependences *cd = NULL;
2983 auto_vec<loop_p> loops_to_be_destroyed;
2985 if (number_of_loops (fun) <= 1)
2986 return 0;
2988 /* Compute topological order for basic blocks. Topological order is
2989 needed because data dependence is computed for data references in
2990 lexicographical order. */
2991 if (bb_top_order_index == NULL)
2993 int rpo_num;
2994 int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
2996 bb_top_order_index = XNEWVEC (int, last_basic_block_for_fn (cfun));
2997 bb_top_order_index_size = last_basic_block_for_fn (cfun);
2998 rpo_num = pre_and_rev_post_order_compute_fn (cfun, NULL, rpo, true);
2999 for (int i = 0; i < rpo_num; i++)
3000 bb_top_order_index[rpo[i]] = i;
3002 free (rpo);
3005 FOR_ALL_BB_FN (bb, fun)
3007 gimple_stmt_iterator gsi;
3008 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3009 gimple_set_uid (gsi_stmt (gsi), -1);
3010 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3011 gimple_set_uid (gsi_stmt (gsi), -1);
3014 /* We can at the moment only distribute non-nested loops, thus restrict
3015 walking to innermost loops. */
3016 FOR_EACH_LOOP (loop, LI_ONLY_INNERMOST)
3018 /* Don't distribute multiple exit edges loop, or cold loop. */
3019 if (!single_exit (loop)
3020 || !optimize_loop_for_speed_p (loop))
3021 continue;
3023 /* Don't distribute loop if niters is unknown. */
3024 tree niters = number_of_latch_executions (loop);
3025 if (niters == NULL_TREE || niters == chrec_dont_know)
3026 continue;
3028 /* Get the perfect loop nest for distribution. */
3029 loop = prepare_perfect_loop_nest (loop);
3030 for (; loop; loop = loop->inner)
3032 auto_vec<gimple *> work_list;
3033 if (!find_seed_stmts_for_distribution (loop, &work_list))
3034 break;
3036 const char *str = loop->inner ? " nest" : "";
3037 location_t loc = find_loop_location (loop);
3038 if (!cd)
3040 calculate_dominance_info (CDI_DOMINATORS);
3041 calculate_dominance_info (CDI_POST_DOMINATORS);
3042 cd = new control_dependences ();
3043 free_dominance_info (CDI_POST_DOMINATORS);
3046 bool destroy_p;
3047 int nb_generated_loops, nb_generated_calls;
3048 nb_generated_loops = distribute_loop (loop, work_list, cd,
3049 &nb_generated_calls,
3050 &destroy_p);
3051 if (destroy_p)
3052 loops_to_be_destroyed.safe_push (loop);
3054 if (nb_generated_loops + nb_generated_calls > 0)
3056 changed = true;
3057 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS,
3058 loc, "Loop%s %d distributed: split to %d loops "
3059 "and %d library calls.\n", str, loop->num,
3060 nb_generated_loops, nb_generated_calls);
3062 break;
3065 if (dump_file && (dump_flags & TDF_DETAILS))
3066 fprintf (dump_file, "Loop%s %d not distributed.\n", str, loop->num);
3070 if (cd)
3071 delete cd;
3073 if (bb_top_order_index != NULL)
3075 free (bb_top_order_index);
3076 bb_top_order_index = NULL;
3077 bb_top_order_index_size = 0;
3080 if (changed)
3082 /* Destroy loop bodies that could not be reused. Do this late as we
3083 otherwise can end up refering to stale data in control dependences. */
3084 unsigned i;
3085 FOR_EACH_VEC_ELT (loops_to_be_destroyed, i, loop)
3086 destroy_loop (loop);
3088 /* Cached scalar evolutions now may refer to wrong or non-existing
3089 loops. */
3090 scev_reset_htab ();
3091 mark_virtual_operands_for_renaming (fun);
3092 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
3095 checking_verify_loop_structure ();
3097 return 0;
3100 } // anon namespace
3102 gimple_opt_pass *
3103 make_pass_loop_distribution (gcc::context *ctxt)
3105 return new pass_loop_distribution (ctxt);